hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 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 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a33b2f7baf6db29172228a072f537c2710690147 | 22,162 | cc | C++ | mace/ops/deconv_2d_test.cc | kweisamx/mace | 487ad9dceb49e90aedaa8dc2792b4827ef24d42a | [
"Apache-2.0"
] | null | null | null | mace/ops/deconv_2d_test.cc | kweisamx/mace | 487ad9dceb49e90aedaa8dc2792b4827ef24d42a | [
"Apache-2.0"
] | null | null | null | mace/ops/deconv_2d_test.cc | kweisamx/mace | 487ad9dceb49e90aedaa8dc2792b4827ef24d42a | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Xiaomi, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <fstream>
#include <vector>
#include "mace/ops/deconv_2d.h"
#include "mace/ops/conv_pool_2d_util.h"
#include "mace/ops/ops_test_util.h"
namespace mace {
namespace ops {
namespace test {
class Deconv2dOpTest : public OpsTestBase {};
namespace {
template <DeviceType D>
void RunTestSimple(const std::vector<index_t> &input_shape,
const std::vector<float> &input_data,
const std::vector<float> &bias_data,
const int stride,
Padding padding,
const std::vector<int> &padding_size,
const std::vector<int32_t> &output_shape,
const std::vector<index_t> &filter_shape,
const std::vector<float> &filter_data,
const std::vector<index_t> &expected_shape,
const std::vector<float> &expected_data,
ops::FrameworkType model_type) {
OpsTestNet net;
// Add input data
const index_t batch = input_shape[0];
const index_t out_channels = filter_shape[2];
net.AddInputFromArray<D, float>("Input", input_shape, input_data);
net.AddInputFromArray<D, float>("Filter", filter_shape, filter_data);
net.AddInputFromArray<D, float>("Bias", {out_channels}, bias_data);
net.TransformDataFormat<D, float>("Filter", HWOI, "FilterOIHW", OIHW);
if (D == DeviceType::GPU) {
BufferToImage<D, float>(&net, "Input", "InputImage",
ops::BufferType::IN_OUT_CHANNEL);
BufferToImage<D, float>(&net, "Bias", "BiasImage",
ops::BufferType::ARGUMENT);
BufferToImage<D, float>(&net, "FilterOIHW", "FilterImage",
ops::BufferType::CONV2D_FILTER);
if (model_type == ops::FrameworkType::CAFFE) {
OpDefBuilder("Deconv2D", "Deconv2dTest")
.Input("InputImage")
.Input("FilterImage")
.Input("BiasImage")
.Output("OutputImage")
.AddIntsArg("strides", {stride, stride})
.AddIntArg("padding", padding)
.AddIntsArg("padding_values", padding_size)
.AddIntArg("framework_type", model_type)
.Finalize(net.NewOperatorDef());
} else {
net.AddInputFromArray<D, int32_t>("OutputShape", {4}, output_shape);
OpDefBuilder("Deconv2D", "Deconv2dTest")
.Input("InputImage")
.Input("FilterImage")
.Input("OutputShape")
.Input("BiasImage")
.Output("OutputImage")
.AddIntsArg("strides", {stride, stride})
.AddIntArg("padding", padding)
.AddIntsArg("padding_values", padding_size)
.AddIntArg("framework_type", model_type)
.Finalize(net.NewOperatorDef());
}
net.RunOp(D);
// Transfer output
ImageToBuffer<D, float>(&net, "OutputImage", "Output",
ops::BufferType::IN_OUT_CHANNEL);
} else {
net.TransformDataFormat<DeviceType::CPU, float>("Input", NHWC, "InputNCHW",
NCHW);
if (model_type == ops::FrameworkType::CAFFE) {
OpDefBuilder("Deconv2D", "Deconv2dTest")
.Input("InputNCHW")
.Input("FilterOIHW")
.Input("Bias")
.Output("OutputNCHW")
.AddIntsArg("strides", {stride, stride})
.AddIntArg("padding", padding)
.AddIntsArg("padding_values", padding_size)
.AddIntArg("framework_type", model_type)
.Finalize(net.NewOperatorDef());
} else {
net.AddInputFromArray<D, int32_t>("OutputShape", {4}, output_shape);
OpDefBuilder("Deconv2D", "Deconv2dTest")
.Input("InputNCHW")
.Input("FilterOIHW")
.Input("OutputShape")
.Input("Bias")
.Output("OutputNCHW")
.AddIntsArg("strides", {stride, stride})
.AddIntArg("padding", padding)
.AddIntsArg("padding_values", padding_size)
.AddIntArg("framework_type", model_type)
.Finalize(net.NewOperatorDef());
}
// Run
net.RunOp(D);
net.TransformDataFormat<DeviceType::CPU, float>("OutputNCHW", NCHW,
"Output", NHWC);
}
auto expected = net.CreateTensor<float>(expected_shape, expected_data);
ExpectTensorNear<float>(*expected, *net.GetOutput("Output"), 0.0001);
}
template <DeviceType D>
void TestNHWCSimple3x3SAME_S1() {
RunTestSimple<D>({1, 3, 3, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}, {0.5, 0.6, 0.7},
1, Padding::SAME, {},
{1, 3, 3, 3}, {3, 3, 3, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 3, 3, 3},
{4.5, 4.6, 4.7, 6.5, 6.6, 6.7, 4.5, 4.6, 4.7,
6.5, 6.6, 6.7, 9.5, 9.6, 9.7, 6.5, 6.6, 6.7,
4.5, 4.6, 4.7, 6.5, 6.6, 6.7, 4.5, 4.6, 4.7},
ops::FrameworkType::TENSORFLOW);
RunTestSimple<D>({1, 3, 3, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0},
1, Padding::VALID, {2, 2},
{0}, {3, 3, 3, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 3, 3, 3},
{4, 4, 4, 6, 6, 6, 4, 4, 4, 6, 6, 6, 9, 9,
9, 6, 6, 6, 4, 4, 4, 6, 6, 6, 4, 4, 4},
ops::FrameworkType::CAFFE);
RunTestSimple<D>({1, 3, 3, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0},
1, Padding::SAME, {},
{1, 3, 3, 3}, {3, 3, 3, 1},
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27},
{1, 3, 3, 3},
{54, 66, 78, 126, 147, 168, 130, 146, 162,
198, 225, 252, 405, 450, 495, 366, 399, 432,
354, 378, 402, 630, 669, 708, 502, 530, 558},
ops::FrameworkType::TENSORFLOW);
RunTestSimple<D>({1, 3, 3, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0},
1, Padding::SAME, {2, 2},
{0}, {3, 3, 3, 1},
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27},
{1, 3, 3, 3},
{54, 66, 78, 126, 147, 168, 130, 146, 162,
198, 225, 252, 405, 450, 495, 366, 399, 432,
354, 378, 402, 630, 669, 708, 502, 530, 558},
ops::FrameworkType::CAFFE);
}
template <DeviceType D>
void TestNHWCSimple3x3SAME_S2() {
RunTestSimple<D>({1, 3, 3, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0},
2, Padding::SAME, {},
{1, 6, 6, 3},
{3, 3, 3, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 6, 6, 3},
{1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
2, 2, 2, 2, 2, 2, 4, 4, 4, 2, 2, 2, 4, 4, 4, 2, 2, 2,
1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
2, 2, 2, 2, 2, 2, 4, 4, 4, 2, 2, 2, 4, 4, 4, 2, 2, 2,
1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1},
ops::FrameworkType::TENSORFLOW);
RunTestSimple<D>({1, 3, 3, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0},
2, Padding::SAME, {2, 2},
{0}, {3, 3, 3, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 5, 5, 3},
{1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
2, 2, 2, 4, 4, 4, 2, 2, 2, 4, 4, 4, 2, 2, 2,
1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
2, 2, 2, 4, 4, 4, 2, 2, 2, 4, 4, 4, 2, 2, 2,
1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1},
ops::FrameworkType::CAFFE);
RunTestSimple<D>({1, 3, 3, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0},
2, Padding::SAME, {},
{1, 6, 6, 3}, {3, 3, 3, 1},
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27},
{1, 6, 6, 3},
{1, 2, 3, 4, 5, 6, 9, 12, 15, 8, 10, 12, 17, 22, 27, 12, 15,
18,
10, 11, 12, 13, 14, 15, 36, 39, 42, 26, 28, 30, 62, 67, 72,
39, 42, 45,
23, 28, 33, 38, 43, 48, 96, 108, 120, 64, 71, 78, 148, 164,
180, 90, 99, 108,
40, 44, 48, 52, 56, 60, 114, 123, 132, 65, 70, 75, 140,
151, 162, 78, 84, 90,
83, 94, 105, 116, 127, 138, 252, 276, 300, 142, 155, 168,
304, 332, 360, 168, 183, 198, 70, 77, 84, 91, 98, 105, 192,
207, 222, 104, 112, 120, 218, 235, 252, 117, 126, 135},
ops::FrameworkType::TENSORFLOW);
RunTestSimple<D>({1, 3, 3, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0},
2, Padding::SAME, {2, 2},
{0}, {3, 3, 3, 1},
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27},
{1, 5, 5, 3},
{13, 14, 15, 36, 39, 42, 26, 28, 30, 62, 67, 72, 39, 42, 45,
38, 43, 48, 96, 108, 120, 64, 71, 78, 148, 164, 180,
90, 99, 108, 52, 56, 60, 114, 123, 132, 65, 70, 75,
140, 151, 162, 78, 84, 90, 116, 127, 138, 252, 276, 300,
142, 155, 168, 304, 332, 360, 168, 183, 198, 91, 98, 105,
192, 207, 222, 104, 112, 120, 218, 235, 252, 117, 126, 135},
ops::FrameworkType::CAFFE);
}
template <DeviceType D>
void TestNHWCSimple3x3SAME_S2_1() {
RunTestSimple<D>({1, 3, 3, 1}, {12, 18, 12, 18, 27, 18, 12, 18, 12},
{0, 0, 0},
2, Padding::SAME, {},
{1, 5, 5, 3}, {3, 3, 3, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 5, 5, 3},
{12, 12, 12, 30, 30, 30, 18, 18, 18, 30, 30, 30, 12, 12, 12,
30, 30, 30, 75, 75, 75, 45, 45, 45, 75, 75, 75, 30, 30, 30,
18, 18, 18, 45, 45, 45, 27, 27, 27, 45, 45, 45, 18, 18, 18,
30, 30, 30, 75, 75, 75, 45, 45, 45, 75, 75, 75, 30, 30, 30,
12, 12, 12, 30, 30, 30, 18, 18, 18, 30, 30, 30, 12, 12, 12},
ops::FrameworkType::TENSORFLOW);
}
template <DeviceType D>
void TestNHWCSimple3x3VALID_S2() {
RunTestSimple<D>({1, 3, 3, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}, {0, 0, 0},
2, Padding::VALID, {},
{1, 7, 7, 3}, {3, 3, 3, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 7, 7, 3},
{1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
1, 1, 1,
1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
1, 1, 1,
2, 2, 2, 2, 2, 2, 4, 4, 4, 2, 2, 2, 4, 4, 4, 2, 2, 2,
2, 2, 2,
1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
1, 1, 1,
2, 2, 2, 2, 2, 2, 4, 4, 4, 2, 2, 2, 4, 4, 4, 2, 2, 2,
2, 2, 2,
1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
1, 1, 1,
1, 1, 1, 1, 1, 1, 2, 2, 2, 1, 1, 1, 2, 2, 2, 1, 1, 1,
1, 1, 1},
ops::FrameworkType::TENSORFLOW);
}
template <DeviceType D>
void TestNHWCSimple3x3VALID_S1() {
RunTestSimple<D>({1, 3, 3, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 0, 0},
1, Padding::VALID, {},
{1, 5, 5, 3}, {3, 3, 3, 1},
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27},
{1, 5, 5, 3},
{1, 2, 3, 6, 9, 12, 18, 24, 30, 26, 31, 36, 21,
24, 27, 14, 19, 24, 54, 66, 78, 126, 147, 168, 130, 146,
162, 90, 99, 108, 66, 78, 90, 198, 225, 252, 405, 450, 495,
366, 399, 432, 234, 252, 270, 146, 157, 168, 354, 378, 402,
630, 669, 708, 502, 530, 558, 294, 309, 324, 133, 140, 147,
306, 321, 336, 522, 546, 570, 398, 415, 432, 225, 234, 243},
ops::FrameworkType::TENSORFLOW);
}
template <DeviceType D>
void TestNHWCSimple2x2SAME() {
RunTestSimple<D>({1, 2, 2, 1}, {1, 1, 1, 1}, {0}, 1, Padding::SAME, {},
{1, 2, 2, 1}, {3, 3, 1, 1},
{1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f},
{1, 2, 2, 1}, {4.f, 4.f, 4.f, 4.f},
ops::FrameworkType::TENSORFLOW);
}
template <DeviceType D>
void TestNHWCSimple2x2VALID() {
RunTestSimple<D>(
{1, 2, 2, 1}, {1, 1, 1, 1}, {0}, 2, Padding::VALID, {}, {1, 5, 5, 1},
{3, 3, 1, 1}, {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f},
{1, 5, 5, 1},
{1.f, 1.f, 2.f, 1.f, 1.f, 1.f, 1.f, 2.f, 1.f, 1.f, 2.f, 2.f, 4.f,
2.f, 2.f, 1.f, 1.f, 2.f, 1.f, 1.f, 1.f, 1.f, 2.f, 1.f, 1.f},
ops::FrameworkType::TENSORFLOW);
}
} // namespace
TEST_F(Deconv2dOpTest, CPUSimple3X3PaddingSame_S1) {
TestNHWCSimple3x3SAME_S1<DeviceType::CPU>();
}
TEST_F(Deconv2dOpTest, CPUSimple3X3PaddingSame_S2) {
TestNHWCSimple3x3SAME_S2<DeviceType::CPU>();
}
TEST_F(Deconv2dOpTest, CPUSimple3X3PaddingSame_S2_1) {
TestNHWCSimple3x3SAME_S2_1<DeviceType::CPU>();
}
TEST_F(Deconv2dOpTest, CPUSimple2X2PaddingSame) {
TestNHWCSimple2x2SAME<DeviceType::CPU>();
}
TEST_F(Deconv2dOpTest, CPUSimple2X2PaddingValid) {
TestNHWCSimple2x2VALID<DeviceType::CPU>();
}
TEST_F(Deconv2dOpTest, CPUSimple3X3PaddingValid_S1) {
TestNHWCSimple3x3VALID_S1<DeviceType::CPU>();
}
TEST_F(Deconv2dOpTest, CPUSimple3X3PaddingValid_S2) {
TestNHWCSimple3x3VALID_S2<DeviceType::CPU>();
}
TEST_F(Deconv2dOpTest, OPENCLSimple2X2PaddingSame) {
TestNHWCSimple2x2SAME<DeviceType::GPU>();
}
TEST_F(Deconv2dOpTest, OPENCLSimple3X3PaddingSame_S1) {
TestNHWCSimple3x3SAME_S1<DeviceType::GPU>();
}
TEST_F(Deconv2dOpTest, OPENCLSimple3X3PaddingSame_S2) {
TestNHWCSimple3x3SAME_S2<DeviceType::GPU>();
}
TEST_F(Deconv2dOpTest, OPENCLSimple3X3PaddingSame_S2_1) {
TestNHWCSimple3x3SAME_S2_1<DeviceType::GPU>();
}
TEST_F(Deconv2dOpTest, OPENCLSimple2X2PaddingValid) {
TestNHWCSimple2x2VALID<DeviceType::GPU>();
}
TEST_F(Deconv2dOpTest, OPENCLSimple3X3PaddingValid_S1) {
TestNHWCSimple3x3VALID_S1<DeviceType::GPU>();
}
TEST_F(Deconv2dOpTest, OPENCLSimple3X3PaddingValid_S2) {
TestNHWCSimple3x3VALID_S2<DeviceType::GPU>();
}
namespace {
template <DeviceType D, typename T>
void TestComplexDeconvNxNS12(const int batch,
const std::vector<int> &shape,
const int stride) {
testing::internal::LogToStderr();
auto func = [&](int kernel_h, int kernel_w, int stride_h, int stride_w,
Padding type, int padding) {
// generate random input
int height = shape[0];
int width = shape[1];
int input_channels = shape[2];
int output_channels = shape[3];
OpsTestNet net;
// Add input data
net.AddRandomInput<D, T>("Input", {batch, height, width, input_channels});
net.AddRandomInput<D, T>(
"Filter", {output_channels, input_channels, kernel_h, kernel_w});
net.AddRandomInput<D, T>("Bias", {output_channels});
net.TransformDataFormat<DeviceType::CPU, float>("Input", NHWC, "InputNCHW",
NCHW);
int out_h = 0;
int out_w = 0;
std::vector<int> paddings;
std::vector<int> output_shape;
ops::FrameworkType model_type =
padding < 0 ?
ops::FrameworkType::TENSORFLOW : ops::FrameworkType::CAFFE;
if (model_type == ops::FrameworkType::TENSORFLOW) {
if (type == Padding::SAME) {
out_h = (height - 1) * stride_h + 1;
out_w = (width - 1) * stride_w + 1;
} else {
out_h = (height - 1) * stride_h + kernel_h;
out_w = (width - 1) * stride_w + kernel_w;
}
output_shape.push_back(batch);
output_shape.push_back(out_h);
output_shape.push_back(out_w);
output_shape.push_back(output_channels);
net.AddInputFromArray<D, int32_t>("OutputShape", {4}, output_shape);
} else {
// out_h = (height - 1) * stride + 1 + padding - kernel_h + 1;
// out_w = (width -1) * stride + 1 + padding - kernel_w + 1;
paddings.push_back(padding);
paddings.push_back(padding);
}
if (model_type == ops::FrameworkType::CAFFE) {
OpDefBuilder("Deconv2D", "Deconv2dTest")
.Input("InputNCHW")
.Input("Filter")
.Input("Bias")
.Output("OutputNCHW")
.AddIntsArg("strides", {stride_h, stride_w})
.AddIntsArg("padding_values", paddings)
.AddIntArg("framework_type", model_type)
.AddIntArg("T", static_cast<int>(DataTypeToEnum<T>::value))
.Finalize(net.NewOperatorDef());
} else {
OpDefBuilder("Deconv2D", "Deconv2dTest")
.Input("InputNCHW")
.Input("Filter")
.Input("OutputShape")
.Input("Bias")
.Output("OutputNCHW")
.AddIntsArg("strides", {stride_h, stride_w})
.AddIntArg("padding", type)
.AddIntArg("framework_type", model_type)
.AddIntArg("T", static_cast<int>(DataTypeToEnum<T>::value))
.Finalize(net.NewOperatorDef());
}
// run on cpu
net.RunOp();
net.TransformDataFormat<DeviceType::CPU, float>("OutputNCHW", NCHW,
"Output", NHWC);
// Check
auto expected = net.CreateTensor<float>();
expected->Copy(*net.GetOutput("Output"));
// run on gpu
BufferToImage<D, T>(&net, "Input", "InputImage",
ops::BufferType::IN_OUT_CHANNEL);
BufferToImage<D, T>(&net, "Filter", "FilterImage",
ops::BufferType::CONV2D_FILTER);
BufferToImage<D, T>(&net, "Bias", "BiasImage",
ops::BufferType::ARGUMENT);
if (model_type == ops::FrameworkType::CAFFE) {
OpDefBuilder("Deconv2D", "Deconv2dTest")
.Input("InputImage")
.Input("FilterImage")
.Input("BiasImage")
.Output("OutputImage")
.AddIntsArg("strides", {stride_h, stride_w})
.AddIntsArg("padding_values", paddings)
.AddIntArg("framework_type", model_type)
.AddIntArg("T", static_cast<int>(DataTypeToEnum<T>::value))
.Finalize(net.NewOperatorDef());
} else {
OpDefBuilder("Deconv2D", "Deconv2dTest")
.Input("InputImage")
.Input("FilterImage")
.Input("OutputShape")
.Input("BiasImage")
.Output("OutputImage")
.AddIntsArg("strides", {stride_h, stride_w})
.AddIntArg("padding", type)
.AddIntArg("framework_type", model_type)
.AddIntArg("T", static_cast<int>(DataTypeToEnum<T>::value))
.Finalize(net.NewOperatorDef());
}
// Run on device
net.RunOp(D);
ImageToBuffer<D, T>(&net, "OutputImage", "OPENCLOutput",
ops::BufferType::IN_OUT_CHANNEL);
ExpectTensorNear<float>(*expected, *net.GetOutput("OPENCLOutput"), 1e-4,
1e-4);
};
for (int kernel_size : {3, 4, 5, 7}) {
func(kernel_size, kernel_size, stride, stride, VALID, -1);
func(kernel_size, kernel_size, stride, stride, SAME, -1);
func(kernel_size, kernel_size, stride, stride, VALID, 2);
func(kernel_size, kernel_size, stride, stride, VALID, 3);
}
}
} // namespace
TEST_F(Deconv2dOpTest, OPENCLAlignedDeconvNxNS12) {
TestComplexDeconvNxNS12<DeviceType::GPU, float>(1, {32, 16, 16, 32}, 1);
TestComplexDeconvNxNS12<DeviceType::GPU, float>(1, {32, 16, 16, 32}, 2);
}
TEST_F(Deconv2dOpTest, OPENCLAlignedDeconvNxNS34) {
TestComplexDeconvNxNS12<DeviceType::GPU, float>(1, {32, 16, 16, 32}, 3);
TestComplexDeconvNxNS12<DeviceType::GPU, float>(1, {32, 16, 16, 32}, 4);
}
TEST_F(Deconv2dOpTest, OPENCLUnalignedDeconvNxNS12) {
TestComplexDeconvNxNS12<DeviceType::GPU, float>(1, {17, 113, 5, 7}, 1);
TestComplexDeconvNxNS12<DeviceType::GPU, float>(1, {17, 113, 5, 7}, 2);
}
TEST_F(Deconv2dOpTest, OPENCLUnalignedDeconvNxNS34) {
TestComplexDeconvNxNS12<DeviceType::GPU, float>(1, {17, 113, 5, 7}, 3);
TestComplexDeconvNxNS12<DeviceType::GPU, float>(1, {17, 113, 5, 7}, 4);
}
TEST_F(Deconv2dOpTest, OPENCLUnalignedDeconvNxNMultiBatch) {
TestComplexDeconvNxNS12<DeviceType::GPU, float>(3, {17, 113, 5, 7}, 1);
TestComplexDeconvNxNS12<DeviceType::GPU, float>(5, {17, 113, 5, 7}, 2);
}
} // namespace test
} // namespace ops
} // namespace mace
| 41.270019 | 80 | 0.501218 | [
"shape",
"vector"
] |
a33b78630125c06a611a701cd055328080b8c3da | 46,704 | cc | C++ | src/libxtp/aomatrices/aodipole_potential.cc | mbarbry/xtp | e79828209d11ec25bf1750ab75499ecf50f584ef | [
"Apache-2.0"
] | null | null | null | src/libxtp/aomatrices/aodipole_potential.cc | mbarbry/xtp | e79828209d11ec25bf1750ab75499ecf50f584ef | [
"Apache-2.0"
] | null | null | null | src/libxtp/aomatrices/aodipole_potential.cc | mbarbry/xtp | e79828209d11ec25bf1750ab75499ecf50f584ef | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2009-2018 The VOTCA Development Team
* (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License")
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "A_ol I_ol" BA_olI_ol,
* WITHOUT WARRANTIE_ol OR CONDITION_ol OF ANY KIND, either express or implied.
* _olee the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <votca/xtp/aomatrix.h>
#include <votca/xtp/aobasis.h>
#include <votca/tools/elements.h>
#include <votca/tools/constants.h>
namespace votca { namespace xtp {
void AODipole_Potential::FillBlock( Eigen::Block<Eigen::MatrixXd>& matrix,const AOShell* shell_row,const AOShell* shell_col) {
const double pi = boost::math::constants::pi<double>();
// Get components of dipole vector somehow
tools::vec dipole=-(apolarsite->getU1()+apolarsite->getQ1())*tools::conv::nm2bohr;
tools::vec position=apolarsite->getPos()*tools::conv::nm2bohr;
// shell info, only lmax tells how far to go
int lmax_row = shell_row->getLmax();
int lmax_col = shell_col->getLmax();
int lsum = lmax_row + lmax_col;
// set size of internal block for recursion
int nrows = this->getBlockSize( lmax_row );
int ncols = this->getBlockSize( lmax_col );
// initialize local matrix block for unnormalized cartesians
Eigen::MatrixXd dip = Eigen::MatrixXd::Zero(nrows,ncols);
int n_orbitals[] = { 1, 4, 10, 20, 35, 56, 84 };
int nx[] = { 0,
1, 0, 0,
2, 1, 1, 0, 0, 0,
3, 2, 2, 1, 1, 1, 0, 0, 0, 0,
4, 3, 3, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
int ny[] = { 0,
0, 1, 0,
0, 1, 0, 2, 1, 0,
0, 1, 0, 2, 1, 0, 3, 2, 1, 0,
0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0 };
int nz[] = { 0,
0, 0, 1,
0, 0, 1, 0, 1, 2,
0, 0, 1, 0, 1, 2, 0, 1, 2, 3,
0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4 };
int i_less_x[] = { 0,
0, 0, 0,
1, 2, 3, 0, 0, 0,
4, 5, 6, 7, 8, 9, 0, 0, 0, 0,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 0, 0, 0, 0, 0 };
int i_less_y[] = { 0,
0, 0, 0,
0, 1, 0, 2, 3, 0,
0, 4, 0, 5, 6, 0, 7, 8, 9, 0,
0, 10, 0, 11, 12, 0, 13, 14, 15, 0, 16, 17, 18, 19, 0 };
int i_less_z[] = { 0,
0, 0, 0,
0, 0, 1, 0, 2, 3,
0, 0, 4, 0, 5, 6, 0, 7, 8, 9,
0, 0, 10, 0, 11, 12, 0, 13, 14, 15, 0, 16, 17, 18, 19 };
// get shell positions
const tools::vec& pos_row = shell_row->getPos();
const tools::vec& _pos_col = shell_col->getPos();
const tools::vec diff = pos_row - _pos_col;
// initialize some helper
double distsq = diff*diff;
// iterate over Gaussians in this shell_row
for (AOShell::GaussianIterator itr = shell_row->begin(); itr != shell_row->end(); ++itr) {
// iterate over Gaussians in this shell_col
// get decay constant
const double decay_row = itr->getDecay();
for ( AOShell::GaussianIterator itc = shell_col->begin(); itc != shell_col->end(); ++itc) {
//get decay constant
const double decay_col = itc->getDecay();
const double zeta = decay_row + decay_col;
const double fak = 0.5/zeta;
const double fak2 = 2.0 * fak;
const double xi = decay_row * decay_col * fak2;
double exparg = xi *distsq;
// check if distance between postions is big, then skip step
if ( exparg > 30.0 ) { continue; }
// some helpers
double PmA0 = fak2*( decay_row * pos_row.getX() + decay_col * _pos_col.getX() ) - pos_row.getX();
double PmA1 = fak2*( decay_row * pos_row.getY() + decay_col * _pos_col.getY() ) - pos_row.getY();
double PmA2 = fak2*( decay_row * pos_row.getZ() + decay_col * _pos_col.getZ() ) - pos_row.getZ();
double PmB0 = fak2*( decay_row * pos_row.getX() + decay_col * _pos_col.getX() ) - _pos_col.getX();
double PmB1 = fak2*( decay_row * pos_row.getY() + decay_col * _pos_col.getY() ) - _pos_col.getY();
double PmB2 = fak2*( decay_row * pos_row.getZ() + decay_col * _pos_col.getZ() ) - _pos_col.getZ();
double PmC0 = fak2*( decay_row * pos_row.getX() + decay_col * _pos_col.getX() ) - position.getX();
double PmC1 = fak2*( decay_row * pos_row.getY() + decay_col * _pos_col.getY() ) - position.getY();
double PmC2 = fak2*( decay_row * pos_row.getZ() + decay_col * _pos_col.getZ() ) - position.getZ();
const double U = zeta*(PmC0*PmC0+PmC1*PmC1+PmC2*PmC2);
const std::vector<double> FmU=XIntegrate(lsum+2, U );
typedef boost::multi_array<double, 3> ma_type;
typedef boost::multi_array<double, 4> ma4_type; //////////////////
ma_type nuc3(boost::extents[nrows][ncols][lsum+1]);
ma4_type dip4(boost::extents[nrows][ncols][3][lsum+1]);
typedef ma_type::index index;
for (index i = 0; i < nrows; ++i) {
for (index j = 0; j < ncols; ++j) {
for (index m = 0; m < lsum+1; ++m) {
nuc3[i][j][m] = 0.;
}
}
}
for (index i = 0; i < nrows; ++i) {
for (index j = 0; j < ncols; ++j) {
for (index k = 0; k < 3 ; ++k) { ///////////////////////////////// error corrected
for (index m = 0; m < lsum+1; ++m) {
dip4[i][j][k][m] = 0.;
}
}
}
}
// (s-s element normiert )
double _prefactor = 4. * sqrt(2./pi) * pow(decay_row*decay_col,.75) * fak2 * exp(-exparg);
for (int m = 0; m < lsum+1; m++) {
nuc3[0][0][m] = _prefactor*FmU[m];
}
//------------------------------------------------------
//Integrals p - s
if (lmax_row > 0) {
for (int m = 0; m < lsum; m++) {
nuc3[Cart::x][0][m] = PmA0*nuc3[0][0][m] - PmC0*nuc3[0][0][m+1];
nuc3[Cart::y][0][m] = PmA1*nuc3[0][0][m] - PmC1*nuc3[0][0][m+1];
nuc3[Cart::z][0][m] = PmA2*nuc3[0][0][m] - PmC2*nuc3[0][0][m+1];
}
}
//------------------------------------------------------
//Integrals d - s
if (lmax_row > 1) {
for (int m = 0; m < lsum-1; m++) {
double term = fak*(nuc3[0][0][m]-nuc3[0][0][m+1]);
nuc3[Cart::xx][0][m] = PmA0*nuc3[Cart::x][0][m] - PmC0*nuc3[Cart::x][0][m+1] + term;
nuc3[Cart::xy][0][m] = PmA0*nuc3[Cart::y][0][m] - PmC0*nuc3[Cart::y][0][m+1];
nuc3[Cart::xz][0][m] = PmA0*nuc3[Cart::z][0][m] - PmC0*nuc3[Cart::z][0][m+1];
nuc3[Cart::yy][0][m] = PmA1*nuc3[Cart::y][0][m] - PmC1*nuc3[Cart::y][0][m+1] + term;
nuc3[Cart::yz][0][m] = PmA1*nuc3[Cart::z][0][m] - PmC1*nuc3[Cart::z][0][m+1];
nuc3[Cart::zz][0][m] = PmA2*nuc3[Cart::z][0][m] - PmC2*nuc3[Cart::z][0][m+1] + term;
}
}
//------------------------------------------------------
//Integrals f - s
if (lmax_row > 2) {
for (int m = 0; m < lsum-2; m++) {
nuc3[Cart::xxx][0][m] = PmA0*nuc3[Cart::xx][0][m] - PmC0*nuc3[Cart::xx][0][m+1] + 2*fak*(nuc3[Cart::x][0][m]-nuc3[Cart::x][0][m+1]);
nuc3[Cart::xxy][0][m] = PmA1*nuc3[Cart::xx][0][m] - PmC1*nuc3[Cart::xx][0][m+1];
nuc3[Cart::xxz][0][m] = PmA2*nuc3[Cart::xx][0][m] - PmC2*nuc3[Cart::xx][0][m+1];
nuc3[Cart::xyy][0][m] = PmA0*nuc3[Cart::yy][0][m] - PmC0*nuc3[Cart::yy][0][m+1];
nuc3[Cart::xyz][0][m] = PmA0*nuc3[Cart::yz][0][m] - PmC0*nuc3[Cart::yz][0][m+1];
nuc3[Cart::xzz][0][m] = PmA0*nuc3[Cart::zz][0][m] - PmC0*nuc3[Cart::zz][0][m+1];
nuc3[Cart::yyy][0][m] = PmA1*nuc3[Cart::yy][0][m] - PmC1*nuc3[Cart::yy][0][m+1] + 2*fak*(nuc3[Cart::y][0][m]-nuc3[Cart::y][0][m+1]);
nuc3[Cart::yyz][0][m] = PmA2*nuc3[Cart::yy][0][m] - PmC2*nuc3[Cart::yy][0][m+1];
nuc3[Cart::yzz][0][m] = PmA1*nuc3[Cart::zz][0][m] - PmC1*nuc3[Cart::zz][0][m+1];
nuc3[Cart::zzz][0][m] = PmA2*nuc3[Cart::zz][0][m] - PmC2*nuc3[Cart::zz][0][m+1] + 2*fak*(nuc3[Cart::z][0][m]-nuc3[Cart::z][0][m+1]);
}
}
//------------------------------------------------------
//Integrals g - s
if (lmax_row > 3) {
for (int m = 0; m < lsum-3; m++) {
double term_xx = fak*(nuc3[Cart::xx][0][m]-nuc3[Cart::xx][0][m+1]);
double term_yy = fak*(nuc3[Cart::yy][0][m]-nuc3[Cart::yy][0][m+1]);
double term_zz = fak*(nuc3[Cart::zz][0][m]-nuc3[Cart::zz][0][m+1]);
nuc3[Cart::xxxx][0][m] = PmA0*nuc3[Cart::xxx][0][m] - PmC0*nuc3[Cart::xxx][0][m+1] + 3*term_xx;
nuc3[Cart::xxxy][0][m] = PmA1*nuc3[Cart::xxx][0][m] - PmC1*nuc3[Cart::xxx][0][m+1];
nuc3[Cart::xxxz][0][m] = PmA2*nuc3[Cart::xxx][0][m] - PmC2*nuc3[Cart::xxx][0][m+1];
nuc3[Cart::xxyy][0][m] = PmA0*nuc3[Cart::xyy][0][m] - PmC0*nuc3[Cart::xyy][0][m+1] + term_yy;
nuc3[Cart::xxyz][0][m] = PmA1*nuc3[Cart::xxz][0][m] - PmC1*nuc3[Cart::xxz][0][m+1];
nuc3[Cart::xxzz][0][m] = PmA0*nuc3[Cart::xzz][0][m] - PmC0*nuc3[Cart::xzz][0][m+1] + term_zz;
nuc3[Cart::xyyy][0][m] = PmA0*nuc3[Cart::yyy][0][m] - PmC0*nuc3[Cart::yyy][0][m+1];
nuc3[Cart::xyyz][0][m] = PmA0*nuc3[Cart::yyz][0][m] - PmC0*nuc3[Cart::yyz][0][m+1];
nuc3[Cart::xyzz][0][m] = PmA0*nuc3[Cart::yzz][0][m] - PmC0*nuc3[Cart::yzz][0][m+1];
nuc3[Cart::xzzz][0][m] = PmA0*nuc3[Cart::zzz][0][m] - PmC0*nuc3[Cart::zzz][0][m+1];
nuc3[Cart::yyyy][0][m] = PmA1*nuc3[Cart::yyy][0][m] - PmC1*nuc3[Cart::yyy][0][m+1] + 3*term_yy;
nuc3[Cart::yyyz][0][m] = PmA2*nuc3[Cart::yyy][0][m] - PmC2*nuc3[Cart::yyy][0][m+1];
nuc3[Cart::yyzz][0][m] = PmA1*nuc3[Cart::yzz][0][m] - PmC1*nuc3[Cart::yzz][0][m+1] + term_zz;
nuc3[Cart::yzzz][0][m] = PmA1*nuc3[Cart::zzz][0][m] - PmC1*nuc3[Cart::zzz][0][m+1];
nuc3[Cart::zzzz][0][m] = PmA2*nuc3[Cart::zzz][0][m] - PmC2*nuc3[Cart::zzz][0][m+1] + 3*term_zz;
}
}
//------------------------------------------------------
if (lmax_col > 0) {
//Integrals s - p
for (int m = 0; m < lmax_col; m++) {
nuc3[0][Cart::x][m] = PmB0*nuc3[0][0][m] - PmC0*nuc3[0][0][m+1];
nuc3[0][Cart::y][m] = PmB1*nuc3[0][0][m] - PmC1*nuc3[0][0][m+1];
nuc3[0][Cart::z][m] = PmB2*nuc3[0][0][m] - PmC2*nuc3[0][0][m+1];
}
//------------------------------------------------------
//Integrals p - p
if (lmax_row > 0) {
for (int m = 0; m < lmax_col; m++) {
double term = fak*(nuc3[0][0][m]-nuc3[0][0][m+1]);
for (int i = 1; i < 4; i++) {
nuc3[i][Cart::x][m] = PmB0*nuc3[i][0][m] - PmC0*nuc3[i][0][m+1] + nx[i]*term;
nuc3[i][Cart::y][m] = PmB1*nuc3[i][0][m] - PmC1*nuc3[i][0][m+1] + ny[i]*term;
nuc3[i][Cart::z][m] = PmB2*nuc3[i][0][m] - PmC2*nuc3[i][0][m+1] + nz[i]*term;
}
}
}
//------------------------------------------------------
//Integrals d - p f - p g - p
for (int m = 0; m < lmax_col; m++) {
for (int i = 4; i < n_orbitals[lmax_row]; i++) {
int nx_i = nx[i];
int ny_i = ny[i];
int nz_i = nz[i];
int ilx_i = i_less_x[i];
int ily_i = i_less_y[i];
int ilz_i = i_less_z[i];
nuc3[i][Cart::x][m] = PmB0*nuc3[i][0][m] - PmC0*nuc3[i][0][m+1] + nx_i*fak*(nuc3[ilx_i][0][m] - nuc3[ilx_i][0][m+1]);
nuc3[i][Cart::y][m] = PmB1*nuc3[i][0][m] - PmC1*nuc3[i][0][m+1] + ny_i*fak*(nuc3[ily_i][0][m] - nuc3[ily_i][0][m+1]);
nuc3[i][Cart::z][m] = PmB2*nuc3[i][0][m] - PmC2*nuc3[i][0][m+1] + nz_i*fak*(nuc3[ilz_i][0][m] - nuc3[ilz_i][0][m+1]);
}
}
//------------------------------------------------------
} // end if (lmax_col > 0)
if (lmax_col > 1) {
//Integrals s - d
for (int m = 0; m < lmax_col-1; m++) {
double term = fak*(nuc3[0][0][m]-nuc3[0][0][m+1]);
nuc3[0][Cart::xx][m] = PmB0*nuc3[0][Cart::x][m] - PmC0*nuc3[0][Cart::x][m+1] + term;
nuc3[0][Cart::xy][m] = PmB0*nuc3[0][Cart::y][m] - PmC0*nuc3[0][Cart::y][m+1];
nuc3[0][Cart::xz][m] = PmB0*nuc3[0][Cart::z][m] - PmC0*nuc3[0][Cart::z][m+1];
nuc3[0][Cart::yy][m] = PmB1*nuc3[0][Cart::y][m] - PmC1*nuc3[0][Cart::y][m+1] + term;
nuc3[0][Cart::yz][m] = PmB1*nuc3[0][Cart::z][m] - PmC1*nuc3[0][Cart::z][m+1];
nuc3[0][Cart::zz][m] = PmB2*nuc3[0][Cart::z][m] - PmC2*nuc3[0][Cart::z][m+1] + term;
}
//------------------------------------------------------
//Integrals p - d d - d f - d g - d
for (int m = 0; m < lmax_col-1; m++) {
for (int i = 1; i < n_orbitals[lmax_row]; i++) {
int nx_i = nx[i];
int ny_i = ny[i];
int nz_i = nz[i];
int ilx_i = i_less_x[i];
int ily_i = i_less_y[i];
int ilz_i = i_less_z[i];
double term = fak*(nuc3[i][0][m]-nuc3[i][0][m+1]);
nuc3[i][Cart::xx][m] = PmB0*nuc3[i][Cart::x][m] - PmC0*nuc3[i][Cart::x][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::x][m] - nuc3[ilx_i][Cart::x][m+1]) + term;
nuc3[i][Cart::xy][m] = PmB0*nuc3[i][Cart::y][m] - PmC0*nuc3[i][Cart::y][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::y][m] - nuc3[ilx_i][Cart::y][m+1]);
nuc3[i][Cart::xz][m] = PmB0*nuc3[i][Cart::z][m] - PmC0*nuc3[i][Cart::z][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::z][m] - nuc3[ilx_i][Cart::z][m+1]);
nuc3[i][Cart::yy][m] = PmB1*nuc3[i][Cart::y][m] - PmC1*nuc3[i][Cart::y][m+1] + ny_i*fak*(nuc3[ily_i][Cart::y][m] - nuc3[ily_i][Cart::y][m+1]) + term;
nuc3[i][Cart::yz][m] = PmB1*nuc3[i][Cart::z][m] - PmC1*nuc3[i][Cart::z][m+1] + ny_i*fak*(nuc3[ily_i][Cart::z][m] - nuc3[ily_i][Cart::z][m+1]);
nuc3[i][Cart::zz][m] = PmB2*nuc3[i][Cart::z][m] - PmC2*nuc3[i][Cart::z][m+1] + nz_i*fak*(nuc3[ilz_i][Cart::z][m] - nuc3[ilz_i][Cart::z][m+1]) + term;
}
}
//------------------------------------------------------
} // end if (lmax_col > 1)
if (lmax_col > 2) {
//Integrals s - f
for (int m = 0; m < lmax_col-2; m++) {
nuc3[0][Cart::xxx][m] = PmB0*nuc3[0][Cart::xx][m] - PmC0*nuc3[0][Cart::xx][m+1] + 2*fak*(nuc3[0][Cart::x][m]-nuc3[0][Cart::x][m+1]);
nuc3[0][Cart::xxy][m] = PmB1*nuc3[0][Cart::xx][m] - PmC1*nuc3[0][Cart::xx][m+1];
nuc3[0][Cart::xxz][m] = PmB2*nuc3[0][Cart::xx][m] - PmC2*nuc3[0][Cart::xx][m+1];
nuc3[0][Cart::xyy][m] = PmB0*nuc3[0][Cart::yy][m] - PmC0*nuc3[0][Cart::yy][m+1];
nuc3[0][Cart::xyz][m] = PmB0*nuc3[0][Cart::yz][m] - PmC0*nuc3[0][Cart::yz][m+1];
nuc3[0][Cart::xzz][m] = PmB0*nuc3[0][Cart::zz][m] - PmC0*nuc3[0][Cart::zz][m+1];
nuc3[0][Cart::yyy][m] = PmB1*nuc3[0][Cart::yy][m] - PmC1*nuc3[0][Cart::yy][m+1] + 2*fak*(nuc3[0][Cart::y][m]-nuc3[0][Cart::y][m+1]);
nuc3[0][Cart::yyz][m] = PmB2*nuc3[0][Cart::yy][m] - PmC2*nuc3[0][Cart::yy][m+1];
nuc3[0][Cart::yzz][m] = PmB1*nuc3[0][Cart::zz][m] - PmC1*nuc3[0][Cart::zz][m+1];
nuc3[0][Cart::zzz][m] = PmB2*nuc3[0][Cart::zz][m] - PmC2*nuc3[0][Cart::zz][m+1] + 2*fak*(nuc3[0][Cart::z][m]-nuc3[0][Cart::z][m+1]);
}
//------------------------------------------------------
//Integrals p - f d - f f - f g - f
for (int m = 0; m < lmax_col-2; m++) {
for (int i = 1; i < n_orbitals[lmax_row]; i++) {
int nx_i = nx[i];
int ny_i = ny[i];
int nz_i = nz[i];
int ilx_i = i_less_x[i];
int ily_i = i_less_y[i];
int ilz_i = i_less_z[i];
double term_x = 2*fak*(nuc3[i][Cart::x][m]-nuc3[i][Cart::x][m+1]);
double term_y = 2*fak*(nuc3[i][Cart::y][m]-nuc3[i][Cart::y][m+1]);
double term_z = 2*fak*(nuc3[i][Cart::z][m]-nuc3[i][Cart::z][m+1]);
nuc3[i][Cart::xxx][m] = PmB0*nuc3[i][Cart::xx][m] - PmC0*nuc3[i][Cart::xx][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::xx][m] - nuc3[ilx_i][Cart::xx][m+1]) + term_x;
nuc3[i][Cart::xxy][m] = PmB1*nuc3[i][Cart::xx][m] - PmC1*nuc3[i][Cart::xx][m+1] + ny_i*fak*(nuc3[ily_i][Cart::xx][m] - nuc3[ily_i][Cart::xx][m+1]);
nuc3[i][Cart::xxz][m] = PmB2*nuc3[i][Cart::xx][m] - PmC2*nuc3[i][Cart::xx][m+1] + nz_i*fak*(nuc3[ilz_i][Cart::xx][m] - nuc3[ilz_i][Cart::xx][m+1]);
nuc3[i][Cart::xyy][m] = PmB0*nuc3[i][Cart::yy][m] - PmC0*nuc3[i][Cart::yy][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::yy][m] - nuc3[ilx_i][Cart::yy][m+1]);
nuc3[i][Cart::xyz][m] = PmB0*nuc3[i][Cart::yz][m] - PmC0*nuc3[i][Cart::yz][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::yz][m] - nuc3[ilx_i][Cart::yz][m+1]);
nuc3[i][Cart::xzz][m] = PmB0*nuc3[i][Cart::zz][m] - PmC0*nuc3[i][Cart::zz][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::zz][m] - nuc3[ilx_i][Cart::zz][m+1]);
nuc3[i][Cart::yyy][m] = PmB1*nuc3[i][Cart::yy][m] - PmC1*nuc3[i][Cart::yy][m+1] + ny_i*fak*(nuc3[ily_i][Cart::yy][m] - nuc3[ily_i][Cart::yy][m+1]) + term_y;
nuc3[i][Cart::yyz][m] = PmB2*nuc3[i][Cart::yy][m] - PmC2*nuc3[i][Cart::yy][m+1] + nz_i*fak*(nuc3[ilz_i][Cart::yy][m] - nuc3[ilz_i][Cart::yy][m+1]);
nuc3[i][Cart::yzz][m] = PmB1*nuc3[i][Cart::zz][m] - PmC1*nuc3[i][Cart::zz][m+1] + ny_i*fak*(nuc3[ily_i][Cart::zz][m] - nuc3[ily_i][Cart::zz][m+1]);
nuc3[i][Cart::zzz][m] = PmB2*nuc3[i][Cart::zz][m] - PmC2*nuc3[i][Cart::zz][m+1] + nz_i*fak*(nuc3[ilz_i][Cart::zz][m] - nuc3[ilz_i][Cart::zz][m+1]) + term_z;
}
}
//------------------------------------------------------
} // end if (lmax_col > 2)
if (lmax_col > 3) {
//Integrals s - g
for (int m = 0; m < lmax_col-3; m++) {
double term_xx = fak*(nuc3[0][Cart::xx][m]-nuc3[0][Cart::xx][m+1]);
double term_yy = fak*(nuc3[0][Cart::yy][m]-nuc3[0][Cart::yy][m+1]);
double term_zz = fak*(nuc3[0][Cart::zz][m]-nuc3[0][Cart::zz][m+1]);
nuc3[0][Cart::xxxx][m] = PmB0*nuc3[0][Cart::xxx][m] - PmC0*nuc3[0][Cart::xxx][m+1] + 3*term_xx;
nuc3[0][Cart::xxxy][m] = PmB1*nuc3[0][Cart::xxx][m] - PmC1*nuc3[0][Cart::xxx][m+1];
nuc3[0][Cart::xxxz][m] = PmB2*nuc3[0][Cart::xxx][m] - PmC2*nuc3[0][Cart::xxx][m+1];
nuc3[0][Cart::xxyy][m] = PmB0*nuc3[0][Cart::xyy][m] - PmC0*nuc3[0][Cart::xyy][m+1] + term_yy;
nuc3[0][Cart::xxyz][m] = PmB1*nuc3[0][Cart::xxz][m] - PmC1*nuc3[0][Cart::xxz][m+1];
nuc3[0][Cart::xxzz][m] = PmB0*nuc3[0][Cart::xzz][m] - PmC0*nuc3[0][Cart::xzz][m+1] + term_zz;
nuc3[0][Cart::xyyy][m] = PmB0*nuc3[0][Cart::yyy][m] - PmC0*nuc3[0][Cart::yyy][m+1];
nuc3[0][Cart::xyyz][m] = PmB0*nuc3[0][Cart::yyz][m] - PmC0*nuc3[0][Cart::yyz][m+1];
nuc3[0][Cart::xyzz][m] = PmB0*nuc3[0][Cart::yzz][m] - PmC0*nuc3[0][Cart::yzz][m+1];
nuc3[0][Cart::xzzz][m] = PmB0*nuc3[0][Cart::zzz][m] - PmC0*nuc3[0][Cart::zzz][m+1];
nuc3[0][Cart::yyyy][m] = PmB1*nuc3[0][Cart::yyy][m] - PmC1*nuc3[0][Cart::yyy][m+1] + 3*term_yy;
nuc3[0][Cart::yyyz][m] = PmB2*nuc3[0][Cart::yyy][m] - PmC2*nuc3[0][Cart::yyy][m+1];
nuc3[0][Cart::yyzz][m] = PmB1*nuc3[0][Cart::yzz][m] - PmC1*nuc3[0][Cart::yzz][m+1] + term_zz;
nuc3[0][Cart::yzzz][m] = PmB1*nuc3[0][Cart::zzz][m] - PmC1*nuc3[0][Cart::zzz][m+1];
nuc3[0][Cart::zzzz][m] = PmB2*nuc3[0][Cart::zzz][m] - PmC2*nuc3[0][Cart::zzz][m+1] + 3*term_zz;
}
//------------------------------------------------------
//Integrals p - g d - g f - g g - g
for (int m = 0; m < lmax_col-3; m++) {
for (int i = 1; i < n_orbitals[lmax_row]; i++) {
int nx_i = nx[i];
int ny_i = ny[i];
int nz_i = nz[i];
int ilx_i = i_less_x[i];
int ily_i = i_less_y[i];
int ilz_i = i_less_z[i];
double term_xx = fak*(nuc3[i][Cart::xx][m]-nuc3[i][Cart::xx][m+1]);
double term_yy = fak*(nuc3[i][Cart::yy][m]-nuc3[i][Cart::yy][m+1]);
double term_zz = fak*(nuc3[i][Cart::zz][m]-nuc3[i][Cart::zz][m+1]);
nuc3[i][Cart::xxxx][m] = PmB0*nuc3[i][Cart::xxx][m] - PmC0*nuc3[i][Cart::xxx][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::xxx][m] - nuc3[ilx_i][Cart::xxx][m+1]) + 3*term_xx;
nuc3[i][Cart::xxxy][m] = PmB1*nuc3[i][Cart::xxx][m] - PmC1*nuc3[i][Cart::xxx][m+1] + ny_i*fak*(nuc3[ily_i][Cart::xxx][m] - nuc3[ily_i][Cart::xxx][m+1]);
nuc3[i][Cart::xxxz][m] = PmB2*nuc3[i][Cart::xxx][m] - PmC2*nuc3[i][Cart::xxx][m+1] + nz_i*fak*(nuc3[ilz_i][Cart::xxx][m] - nuc3[ilz_i][Cart::xxx][m+1]);
nuc3[i][Cart::xxyy][m] = PmB0*nuc3[i][Cart::xyy][m] - PmC0*nuc3[i][Cart::xyy][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::xyy][m] - nuc3[ilx_i][Cart::xyy][m+1]) + term_yy;
nuc3[i][Cart::xxyz][m] = PmB1*nuc3[i][Cart::xxz][m] - PmC1*nuc3[i][Cart::xxz][m+1] + ny_i*fak*(nuc3[ily_i][Cart::xxz][m] - nuc3[ily_i][Cart::xxz][m+1]);
nuc3[i][Cart::xxzz][m] = PmB0*nuc3[i][Cart::xzz][m] - PmC0*nuc3[i][Cart::xzz][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::xzz][m] - nuc3[ilx_i][Cart::xzz][m+1]) + term_zz;
nuc3[i][Cart::xyyy][m] = PmB0*nuc3[i][Cart::yyy][m] - PmC0*nuc3[i][Cart::yyy][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::yyy][m] - nuc3[ilx_i][Cart::yyy][m+1]);
nuc3[i][Cart::xyyz][m] = PmB0*nuc3[i][Cart::yyz][m] - PmC0*nuc3[i][Cart::yyz][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::yyz][m] - nuc3[ilx_i][Cart::yyz][m+1]);
nuc3[i][Cart::xyzz][m] = PmB0*nuc3[i][Cart::yzz][m] - PmC0*nuc3[i][Cart::yzz][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::yzz][m] - nuc3[ilx_i][Cart::yzz][m+1]);
nuc3[i][Cart::xzzz][m] = PmB0*nuc3[i][Cart::zzz][m] - PmC0*nuc3[i][Cart::zzz][m+1] + nx_i*fak*(nuc3[ilx_i][Cart::zzz][m] - nuc3[ilx_i][Cart::zzz][m+1]);
nuc3[i][Cart::yyyy][m] = PmB1*nuc3[i][Cart::yyy][m] - PmC1*nuc3[i][Cart::yyy][m+1] + ny_i*fak*(nuc3[ily_i][Cart::yyy][m] - nuc3[ily_i][Cart::yyy][m+1]) + 3*term_yy;
nuc3[i][Cart::yyyz][m] = PmB2*nuc3[i][Cart::yyy][m] - PmC2*nuc3[i][Cart::yyy][m+1] + nz_i*fak*(nuc3[ilz_i][Cart::yyy][m] - nuc3[ilz_i][Cart::yyy][m+1]);
nuc3[i][Cart::yyzz][m] = PmB1*nuc3[i][Cart::yzz][m] - PmC1*nuc3[i][Cart::yzz][m+1] + ny_i*fak*(nuc3[ily_i][Cart::yzz][m] - nuc3[ily_i][Cart::yzz][m+1]) + term_zz;
nuc3[i][Cart::yzzz][m] = PmB1*nuc3[i][Cart::zzz][m] - PmC1*nuc3[i][Cart::zzz][m+1] + ny_i*fak*(nuc3[ily_i][Cart::zzz][m] - nuc3[ily_i][Cart::zzz][m+1]);
nuc3[i][Cart::zzzz][m] = PmB2*nuc3[i][Cart::zzz][m] - PmC2*nuc3[i][Cart::zzz][m+1] + nz_i*fak*(nuc3[ilz_i][Cart::zzz][m] - nuc3[ilz_i][Cart::zzz][m+1]) + 3*term_zz;
}
}
//------------------------------------------------------
} // end if (lmax_col > 3)
// (s-s element normiert )
double _prefactor_dip = 2. * zeta * _prefactor;
for (int m = 0; m < lsum+1; m++) {
dip4[0][0][0][m] = PmC0*_prefactor_dip*FmU[m+1];
dip4[0][0][1][m] = PmC1*_prefactor_dip*FmU[m+1];
dip4[0][0][2][m] = PmC2*_prefactor_dip*FmU[m+1];
}
//------------------------------------------------------
//Integrals p - s
if (lmax_row > 0) {
for (int m = 0; m < lsum; m++) {
for (int k = 0; k < 3; k++) {
dip4[Cart::x][0][k][m] = PmA0*dip4[0][0][k][m] - PmC0*dip4[0][0][k][m+1] + (k==0)*nuc3[0][0][m+1];
dip4[Cart::y][0][k][m] = PmA1*dip4[0][0][k][m] - PmC1*dip4[0][0][k][m+1] + (k==1)*nuc3[0][0][m+1];
dip4[Cart::z][0][k][m] = PmA2*dip4[0][0][k][m] - PmC2*dip4[0][0][k][m+1] + (k==2)*nuc3[0][0][m+1];
}
}
}
//------------------------------------------------------
//Integrals d - s
if (lmax_row > 1) {
for (int m = 0; m < lsum-1; m++) {
for (int k = 0; k < 3; k++) {
double term = fak*(dip4[0][0][k][m]-dip4[0][0][k][m+1]);
dip4[Cart::xx][0][k][m] = PmA0*dip4[Cart::x][0][k][m] - PmC0*dip4[Cart::x][0][k][m+1] + (k==0)*nuc3[Cart::x][0][m+1] + term;
dip4[Cart::xy][0][k][m] = PmA0*dip4[Cart::y][0][k][m] - PmC0*dip4[Cart::y][0][k][m+1] + (k==0)*nuc3[Cart::y][0][m+1];
dip4[Cart::xz][0][k][m] = PmA0*dip4[Cart::z][0][k][m] - PmC0*dip4[Cart::z][0][k][m+1] + (k==0)*nuc3[Cart::z][0][m+1];
dip4[Cart::yy][0][k][m] = PmA1*dip4[Cart::y][0][k][m] - PmC1*dip4[Cart::y][0][k][m+1] + (k==1)*nuc3[Cart::y][0][m+1] + term;
dip4[Cart::yz][0][k][m] = PmA1*dip4[Cart::z][0][k][m] - PmC1*dip4[Cart::z][0][k][m+1] + (k==1)*nuc3[Cart::z][0][m+1];
dip4[Cart::zz][0][k][m] = PmA2*dip4[Cart::z][0][k][m] - PmC2*dip4[Cart::z][0][k][m+1] + (k==2)*nuc3[Cart::z][0][m+1] + term;
}
}
}
//------------------------------------------------------
//Integrals f - s
if (lmax_row > 2) {
for (int m = 0; m < lsum-2; m++) {
for (int k = 0; k < 3; k++) {
dip4[Cart::xxx][0][k][m] = PmA0*dip4[Cart::xx][0][k][m] - PmC0*dip4[Cart::xx][0][k][m+1] + (k==0)*nuc3[Cart::xx][0][m+1] + 2*fak*(dip4[Cart::x][0][k][m]-dip4[Cart::x][0][k][m+1]);
dip4[Cart::xxy][0][k][m] = PmA1*dip4[Cart::xx][0][k][m] - PmC1*dip4[Cart::xx][0][k][m+1] + (k==1)*nuc3[Cart::xx][0][m+1];
dip4[Cart::xxz][0][k][m] = PmA2*dip4[Cart::xx][0][k][m] - PmC2*dip4[Cart::xx][0][k][m+1] + (k==2)*nuc3[Cart::xx][0][m+1];
dip4[Cart::xyy][0][k][m] = PmA0*dip4[Cart::yy][0][k][m] - PmC0*dip4[Cart::yy][0][k][m+1] + (k==0)*nuc3[Cart::yy][0][m+1];
dip4[Cart::xyz][0][k][m] = PmA0*dip4[Cart::yz][0][k][m] - PmC0*dip4[Cart::yz][0][k][m+1] + (k==0)*nuc3[Cart::yz][0][m+1];
dip4[Cart::xzz][0][k][m] = PmA0*dip4[Cart::zz][0][k][m] - PmC0*dip4[Cart::zz][0][k][m+1] + (k==0)*nuc3[Cart::zz][0][m+1];
dip4[Cart::yyy][0][k][m] = PmA1*dip4[Cart::yy][0][k][m] - PmC1*dip4[Cart::yy][0][k][m+1] + (k==1)*nuc3[Cart::yy][0][m+1] + 2*fak*(dip4[Cart::y][0][k][m]-dip4[Cart::y][0][k][m+1]);
dip4[Cart::yyz][0][k][m] = PmA2*dip4[Cart::yy][0][k][m] - PmC2*dip4[Cart::yy][0][k][m+1] + (k==2)*nuc3[Cart::yy][0][m+1];
dip4[Cart::yzz][0][k][m] = PmA1*dip4[Cart::zz][0][k][m] - PmC1*dip4[Cart::zz][0][k][m+1] + (k==1)*nuc3[Cart::zz][0][m+1];
dip4[Cart::zzz][0][k][m] = PmA2*dip4[Cart::zz][0][k][m] - PmC2*dip4[Cart::zz][0][k][m+1] + (k==2)*nuc3[Cart::zz][0][m+1] + 2*fak*(dip4[Cart::z][0][k][m]-dip4[Cart::z][0][k][m+1]);
}
}
}
//------------------------------------------------------
//Integrals g - s
if (lmax_row > 3) {
for (int m = 0; m < lsum-3; m++) {
for (int k = 0; k < 3; k++) {
double term_xx = fak*(dip4[Cart::xx][0][k][m]-dip4[Cart::xx][0][k][m+1]);
double term_yy = fak*(dip4[Cart::yy][0][k][m]-dip4[Cart::yy][0][k][m+1]);
double term_zz = fak*(dip4[Cart::zz][0][k][m]-dip4[Cart::zz][0][k][m+1]);
dip4[Cart::xxxx][0][k][m] = PmA0*dip4[Cart::xxx][0][k][m] - PmC0*dip4[Cart::xxx][0][k][m+1] + (k==0)*nuc3[Cart::xxx][0][m+1] + 3*term_xx;
dip4[Cart::xxxy][0][k][m] = PmA1*dip4[Cart::xxx][0][k][m] - PmC1*dip4[Cart::xxx][0][k][m+1] + (k==1)*nuc3[Cart::xxx][0][m+1];
dip4[Cart::xxxz][0][k][m] = PmA2*dip4[Cart::xxx][0][k][m] - PmC2*dip4[Cart::xxx][0][k][m+1] + (k==2)*nuc3[Cart::xxx][0][m+1];
dip4[Cart::xxyy][0][k][m] = PmA0*dip4[Cart::xyy][0][k][m] - PmC0*dip4[Cart::xyy][0][k][m+1] + (k==0)*nuc3[Cart::xyy][0][m+1] + term_yy;
dip4[Cart::xxyz][0][k][m] = PmA1*dip4[Cart::xxz][0][k][m] - PmC1*dip4[Cart::xxz][0][k][m+1] + (k==1)*nuc3[Cart::xxz][0][m+1];
dip4[Cart::xxzz][0][k][m] = PmA0*dip4[Cart::xzz][0][k][m] - PmC0*dip4[Cart::xzz][0][k][m+1] + (k==0)*nuc3[Cart::xzz][0][m+1] + term_zz;
dip4[Cart::xyyy][0][k][m] = PmA0*dip4[Cart::yyy][0][k][m] - PmC0*dip4[Cart::yyy][0][k][m+1] + (k==0)*nuc3[Cart::yyy][0][m+1];
dip4[Cart::xyyz][0][k][m] = PmA0*dip4[Cart::yyz][0][k][m] - PmC0*dip4[Cart::yyz][0][k][m+1] + (k==0)*nuc3[Cart::yyz][0][m+1];
dip4[Cart::xyzz][0][k][m] = PmA0*dip4[Cart::yzz][0][k][m] - PmC0*dip4[Cart::yzz][0][k][m+1] + (k==0)*nuc3[Cart::yzz][0][m+1];
dip4[Cart::xzzz][0][k][m] = PmA0*dip4[Cart::zzz][0][k][m] - PmC0*dip4[Cart::zzz][0][k][m+1] + (k==0)*nuc3[Cart::zzz][0][m+1];
dip4[Cart::yyyy][0][k][m] = PmA1*dip4[Cart::yyy][0][k][m] - PmC1*dip4[Cart::yyy][0][k][m+1] + (k==1)*nuc3[Cart::yyy][0][m+1] + 3*term_yy;
dip4[Cart::yyyz][0][k][m] = PmA2*dip4[Cart::yyy][0][k][m] - PmC2*dip4[Cart::yyy][0][k][m+1] + (k==2)*nuc3[Cart::yyy][0][m+1];
dip4[Cart::yyzz][0][k][m] = PmA1*dip4[Cart::yzz][0][k][m] - PmC1*dip4[Cart::yzz][0][k][m+1] + (k==1)*nuc3[Cart::yzz][0][m+1] + term_zz;
dip4[Cart::yzzz][0][k][m] = PmA1*dip4[Cart::zzz][0][k][m] - PmC1*dip4[Cart::zzz][0][k][m+1] + (k==1)*nuc3[Cart::zzz][0][m+1];
dip4[Cart::zzzz][0][k][m] = PmA2*dip4[Cart::zzz][0][k][m] - PmC2*dip4[Cart::zzz][0][k][m+1] + (k==2)*nuc3[Cart::zzz][0][m+1] + 3*term_zz;
}
}
}
//------------------------------------------------------
if (lmax_col > 0) {
//Integrals s - p
for (int m = 0; m < lmax_col; m++) {
for (int k = 0; k < 3; k++) {
dip4[0][Cart::x][k][m] = PmB0*dip4[0][0][k][m] - PmC0*dip4[0][0][k][m+1] + (k==0)*nuc3[0][0][m+1];
dip4[0][Cart::y][k][m] = PmB1*dip4[0][0][k][m] - PmC1*dip4[0][0][k][m+1] + (k==1)*nuc3[0][0][m+1];
dip4[0][Cart::z][k][m] = PmB2*dip4[0][0][k][m] - PmC2*dip4[0][0][k][m+1] + (k==2)*nuc3[0][0][m+1];
}
}
//------------------------------------------------------
//Integrals p - p
if (lmax_row > 0) {
for (int m = 0; m < lmax_col; m++) {
for (int i = 1; i < 4; i++) {
for (int k = 0; k < 3; k++) {
double term = fak*(dip4[0][0][k][m]-dip4[0][0][k][m+1]);
dip4[i][Cart::x][k][m] = PmB0*dip4[i][0][k][m] - PmC0*dip4[i][0][k][m+1] + (k==0)*nuc3[i][0][m+1] + nx[i]*term;
dip4[i][Cart::y][k][m] = PmB1*dip4[i][0][k][m] - PmC1*dip4[i][0][k][m+1] + (k==1)*nuc3[i][0][m+1] + ny[i]*term;
dip4[i][Cart::z][k][m] = PmB2*dip4[i][0][k][m] - PmC2*dip4[i][0][k][m+1] + (k==2)*nuc3[i][0][m+1] + nz[i]*term;
}
}
}
}
//------------------------------------------------------
//Integrals d - p f - p g - p
for (int m = 0; m < lmax_col; m++) {
for (int i = 4; i < n_orbitals[lmax_row]; i++) {
int nx_i = nx[i];
int ny_i = ny[i];
int nz_i = nz[i];
int ilx_i = i_less_x[i];
int ily_i = i_less_y[i];
int ilz_i = i_less_z[i];
for (int k = 0; k < 3; k++) {
dip4[i][Cart::x][k][m] = PmB0*dip4[i][0][k][m] - PmC0*dip4[i][0][k][m+1] + (k==0)*nuc3[i][0][m+1] + nx_i*fak*(dip4[ilx_i][0][k][m] - dip4[ilx_i][0][k][m+1]);
dip4[i][Cart::y][k][m] = PmB1*dip4[i][0][k][m] - PmC1*dip4[i][0][k][m+1] + (k==1)*nuc3[i][0][m+1] + ny_i*fak*(dip4[ily_i][0][k][m] - dip4[ily_i][0][k][m+1]);
dip4[i][Cart::z][k][m] = PmB2*dip4[i][0][k][m] - PmC2*dip4[i][0][k][m+1] + (k==2)*nuc3[i][0][m+1] + nz_i*fak*(dip4[ilz_i][0][k][m] - dip4[ilz_i][0][k][m+1]);
}
}
}
//------------------------------------------------------
} // end if (lmax_col > 0)
if (lmax_col > 1) {
//Integrals s - d
for (int m = 0; m < lmax_col-1; m++) {
for (int k = 0; k < 3; k++) {
double term = fak*(dip4[0][0][k][m]-dip4[0][0][k][m+1]);
dip4[0][Cart::xx][k][m] = PmB0*dip4[0][Cart::x][k][m] - PmC0*dip4[0][Cart::x][k][m+1] + (k==0)*nuc3[0][Cart::x][m+1] + term;
dip4[0][Cart::xy][k][m] = PmB0*dip4[0][Cart::y][k][m] - PmC0*dip4[0][Cart::y][k][m+1] + (k==0)*nuc3[0][Cart::y][m+1];
dip4[0][Cart::xz][k][m] = PmB0*dip4[0][Cart::z][k][m] - PmC0*dip4[0][Cart::z][k][m+1] + (k==0)*nuc3[0][Cart::z][m+1];
dip4[0][Cart::yy][k][m] = PmB1*dip4[0][Cart::y][k][m] - PmC1*dip4[0][Cart::y][k][m+1] + (k==1)*nuc3[0][Cart::y][m+1] + term;
dip4[0][Cart::yz][k][m] = PmB1*dip4[0][Cart::z][k][m] - PmC1*dip4[0][Cart::z][k][m+1] + (k==1)*nuc3[0][Cart::z][m+1];
dip4[0][Cart::zz][k][m] = PmB2*dip4[0][Cart::z][k][m] - PmC2*dip4[0][Cart::z][k][m+1] + (k==2)*nuc3[0][Cart::z][m+1] + term;
}
}
//------------------------------------------------------
//Integrals p - d d - d f - d g - d
for (int m = 0; m < lmax_col-1; m++) {
for (int i = 1; i < n_orbitals[lmax_row]; i++) {
int nx_i = nx[i];
int ny_i = ny[i];
int nz_i = nz[i];
int ilx_i = i_less_x[i];
int ily_i = i_less_y[i];
int ilz_i = i_less_z[i];
for (int k = 0; k < 3; k++) {
double term = fak*(dip4[i][0][k][m]-dip4[i][0][k][m+1]);
dip4[i][Cart::xx][k][m] = PmB0*dip4[i][Cart::x][k][m] - PmC0*dip4[i][Cart::x][k][m+1] + (k==0)*nuc3[i][Cart::x][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::x][k][m] - dip4[ilx_i][Cart::x][k][m+1]) + term;
dip4[i][Cart::xy][k][m] = PmB0*dip4[i][Cart::y][k][m] - PmC0*dip4[i][Cart::y][k][m+1] + (k==0)*nuc3[i][Cart::y][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::y][k][m] - dip4[ilx_i][Cart::y][k][m+1]);
dip4[i][Cart::xz][k][m] = PmB0*dip4[i][Cart::z][k][m] - PmC0*dip4[i][Cart::z][k][m+1] + (k==0)*nuc3[i][Cart::z][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::z][k][m] - dip4[ilx_i][Cart::z][k][m+1]);
dip4[i][Cart::yy][k][m] = PmB1*dip4[i][Cart::y][k][m] - PmC1*dip4[i][Cart::y][k][m+1] + (k==1)*nuc3[i][Cart::y][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::y][k][m] - dip4[ily_i][Cart::y][k][m+1]) + term;
dip4[i][Cart::yz][k][m] = PmB1*dip4[i][Cart::z][k][m] - PmC1*dip4[i][Cart::z][k][m+1] + (k==1)*nuc3[i][Cart::z][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::z][k][m] - dip4[ily_i][Cart::z][k][m+1]);
dip4[i][Cart::zz][k][m] = PmB2*dip4[i][Cart::z][k][m] - PmC2*dip4[i][Cart::z][k][m+1] + (k==2)*nuc3[i][Cart::z][m+1]
+ nz_i*fak*(dip4[ilz_i][Cart::z][k][m] - dip4[ilz_i][Cart::z][k][m+1]) + term;
}
}
}
//------------------------------------------------------
} // end if (lmax_col > 1)
if (lmax_col > 2) {
//Integrals s - f
for (int m = 0; m < lmax_col-2; m++) {
for (int k = 0; k < 3; k++) {
dip4[0][Cart::xxx][k][m] = PmB0*dip4[0][Cart::xx][k][m] - PmC0*dip4[0][Cart::xx][k][m+1] + (k==0)*nuc3[0][Cart::xx][m+1] + 2*fak*(dip4[0][Cart::x][k][m]-dip4[0][Cart::x][k][m+1]);
dip4[0][Cart::xxy][k][m] = PmB1*dip4[0][Cart::xx][k][m] - PmC1*dip4[0][Cart::xx][k][m+1] + (k==1)*nuc3[0][Cart::xx][m+1];
dip4[0][Cart::xxz][k][m] = PmB2*dip4[0][Cart::xx][k][m] - PmC2*dip4[0][Cart::xx][k][m+1] + (k==2)*nuc3[0][Cart::xx][m+1];
dip4[0][Cart::xyy][k][m] = PmB0*dip4[0][Cart::yy][k][m] - PmC0*dip4[0][Cart::yy][k][m+1] + (k==0)*nuc3[0][Cart::yy][m+1];
dip4[0][Cart::xyz][k][m] = PmB0*dip4[0][Cart::yz][k][m] - PmC0*dip4[0][Cart::yz][k][m+1] + (k==0)*nuc3[0][Cart::yz][m+1];
dip4[0][Cart::xzz][k][m] = PmB0*dip4[0][Cart::zz][k][m] - PmC0*dip4[0][Cart::zz][k][m+1] + (k==0)*nuc3[0][Cart::zz][m+1];
dip4[0][Cart::yyy][k][m] = PmB1*dip4[0][Cart::yy][k][m] - PmC1*dip4[0][Cart::yy][k][m+1] + (k==1)*nuc3[0][Cart::yy][m+1] + 2*fak*(dip4[0][Cart::y][k][m]-dip4[0][Cart::y][k][m+1]);
dip4[0][Cart::yyz][k][m] = PmB2*dip4[0][Cart::yy][k][m] - PmC2*dip4[0][Cart::yy][k][m+1] + (k==2)*nuc3[0][Cart::yy][m+1];
dip4[0][Cart::yzz][k][m] = PmB1*dip4[0][Cart::zz][k][m] - PmC1*dip4[0][Cart::zz][k][m+1] + (k==1)*nuc3[0][Cart::zz][m+1];
dip4[0][Cart::zzz][k][m] = PmB2*dip4[0][Cart::zz][k][m] - PmC2*dip4[0][Cart::zz][k][m+1] + (k==2)*nuc3[0][Cart::zz][m+1] + 2*fak*(dip4[0][Cart::z][k][m]-dip4[0][Cart::z][k][m+1]);
}
}
//------------------------------------------------------
//Integrals p - f d - f f - f g - f
for (int m = 0; m < lmax_col-2; m++) {
for (int i = 1; i < n_orbitals[lmax_row]; i++) {
int nx_i = nx[i];
int ny_i = ny[i];
int nz_i = nz[i];
int ilx_i = i_less_x[i];
int ily_i = i_less_y[i];
int ilz_i = i_less_z[i];
for (int k = 0; k < 3; k++) {
double term_x = 2*fak*(dip4[i][Cart::x][k][m]-dip4[i][Cart::x][k][m+1]);
double term_y = 2*fak*(dip4[i][Cart::y][k][m]-dip4[i][Cart::y][k][m+1]);
double term_z = 2*fak*(dip4[i][Cart::z][k][m]-dip4[i][Cart::z][k][m+1]);
dip4[i][Cart::xxx][k][m] = PmB0*dip4[i][Cart::xx][k][m] - PmC0*dip4[i][Cart::xx][k][m+1] + (k==0)*nuc3[i][Cart::xx][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::xx][k][m] - dip4[ilx_i][Cart::xx][k][m+1]) + term_x;
dip4[i][Cart::xxy][k][m] = PmB1*dip4[i][Cart::xx][k][m] - PmC1*dip4[i][Cart::xx][k][m+1] + (k==1)*nuc3[i][Cart::xx][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::xx][k][m] - dip4[ily_i][Cart::xx][k][m+1]);
dip4[i][Cart::xxz][k][m] = PmB2*dip4[i][Cart::xx][k][m] - PmC2*dip4[i][Cart::xx][k][m+1] + (k==2)*nuc3[i][Cart::xx][m+1]
+ nz_i*fak*(dip4[ilz_i][Cart::xx][k][m] - dip4[ilz_i][Cart::xx][k][m+1]);
dip4[i][Cart::xyy][k][m] = PmB0*dip4[i][Cart::yy][k][m] - PmC0*dip4[i][Cart::yy][k][m+1] + (k==0)*nuc3[i][Cart::yy][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::yy][k][m] - dip4[ilx_i][Cart::yy][k][m+1]);
dip4[i][Cart::xyz][k][m] = PmB0*dip4[i][Cart::yz][k][m] - PmC0*dip4[i][Cart::yz][k][m+1] + (k==0)*nuc3[i][Cart::yz][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::yz][k][m] - dip4[ilx_i][Cart::yz][k][m+1]);
dip4[i][Cart::xzz][k][m] = PmB0*dip4[i][Cart::zz][k][m] - PmC0*dip4[i][Cart::zz][k][m+1] + (k==0)*nuc3[i][Cart::zz][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::zz][k][m] - dip4[ilx_i][Cart::zz][k][m+1]);
dip4[i][Cart::yyy][k][m] = PmB1*dip4[i][Cart::yy][k][m] - PmC1*dip4[i][Cart::yy][k][m+1] + (k==1)*nuc3[i][Cart::yy][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::yy][k][m] - dip4[ily_i][Cart::yy][k][m+1]) + term_y;
dip4[i][Cart::yyz][k][m] = PmB2*dip4[i][Cart::yy][k][m] - PmC2*dip4[i][Cart::yy][k][m+1] + (k==2)*nuc3[i][Cart::yy][m+1]
+ nz_i*fak*(dip4[ilz_i][Cart::yy][k][m] - dip4[ilz_i][Cart::yy][k][m+1]);
dip4[i][Cart::yzz][k][m] = PmB1*dip4[i][Cart::zz][k][m] - PmC1*dip4[i][Cart::zz][k][m+1] + (k==1)*nuc3[i][Cart::zz][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::zz][k][m] - dip4[ily_i][Cart::zz][k][m+1]);
dip4[i][Cart::zzz][k][m] = PmB2*dip4[i][Cart::zz][k][m] - PmC2*dip4[i][Cart::zz][k][m+1] + (k==2)*nuc3[i][Cart::zz][m+1]
+ nz_i*fak*(dip4[ilz_i][Cart::zz][k][m] - dip4[ilz_i][Cart::zz][k][m+1]) + term_z;
}
}
}
//------------------------------------------------------
} // end if (lmax_col > 2)
if (lmax_col > 3) {
//Integrals s - g
for (int m = 0; m < lmax_col-3; m++) {
for (int k = 0; k < 3; k++) {
double term_xx = fak*(dip4[0][Cart::xx][k][m]-dip4[0][Cart::xx][k][m+1]);
double term_yy = fak*(dip4[0][Cart::yy][k][m]-dip4[0][Cart::yy][k][m+1]);
double term_zz = fak*(dip4[0][Cart::zz][k][m]-dip4[0][Cart::zz][k][m+1]);
dip4[0][Cart::xxxx][k][m] = PmB0*dip4[0][Cart::xxx][k][m] - PmC0*dip4[0][Cart::xxx][k][m+1] + (k==0)*nuc3[0][Cart::xxx][m+1] + 3*term_xx;
dip4[0][Cart::xxxy][k][m] = PmB1*dip4[0][Cart::xxx][k][m] - PmC1*dip4[0][Cart::xxx][k][m+1] + (k==1)*nuc3[0][Cart::xxx][m+1];
dip4[0][Cart::xxxz][k][m] = PmB2*dip4[0][Cart::xxx][k][m] - PmC2*dip4[0][Cart::xxx][k][m+1] + (k==2)*nuc3[0][Cart::xxx][m+1];
dip4[0][Cart::xxyy][k][m] = PmB0*dip4[0][Cart::xyy][k][m] - PmC0*dip4[0][Cart::xyy][k][m+1] + (k==0)*nuc3[0][Cart::xyy][m+1] + term_yy;
dip4[0][Cart::xxyz][k][m] = PmB1*dip4[0][Cart::xxz][k][m] - PmC1*dip4[0][Cart::xxz][k][m+1] + (k==1)*nuc3[0][Cart::xxz][m+1];
dip4[0][Cart::xxzz][k][m] = PmB0*dip4[0][Cart::xzz][k][m] - PmC0*dip4[0][Cart::xzz][k][m+1] + (k==0)*nuc3[0][Cart::xzz][m+1] + term_zz;
dip4[0][Cart::xyyy][k][m] = PmB0*dip4[0][Cart::yyy][k][m] - PmC0*dip4[0][Cart::yyy][k][m+1] + (k==0)*nuc3[0][Cart::yyy][m+1];
dip4[0][Cart::xyyz][k][m] = PmB0*dip4[0][Cart::yyz][k][m] - PmC0*dip4[0][Cart::yyz][k][m+1] + (k==0)*nuc3[0][Cart::yyz][m+1];
dip4[0][Cart::xyzz][k][m] = PmB0*dip4[0][Cart::yzz][k][m] - PmC0*dip4[0][Cart::yzz][k][m+1] + (k==0)*nuc3[0][Cart::yzz][m+1];
dip4[0][Cart::xzzz][k][m] = PmB0*dip4[0][Cart::zzz][k][m] - PmC0*dip4[0][Cart::zzz][k][m+1] + (k==0)*nuc3[0][Cart::zzz][m+1];
dip4[0][Cart::yyyy][k][m] = PmB1*dip4[0][Cart::yyy][k][m] - PmC1*dip4[0][Cart::yyy][k][m+1] + (k==1)*nuc3[0][Cart::yyy][m+1] + 3*term_yy;
dip4[0][Cart::yyyz][k][m] = PmB2*dip4[0][Cart::yyy][k][m] - PmC2*dip4[0][Cart::yyy][k][m+1] + (k==2)*nuc3[0][Cart::yyy][m+1];
dip4[0][Cart::yyzz][k][m] = PmB1*dip4[0][Cart::yzz][k][m] - PmC1*dip4[0][Cart::yzz][k][m+1] + (k==1)*nuc3[0][Cart::yzz][m+1] + term_zz;
dip4[0][Cart::yzzz][k][m] = PmB1*dip4[0][Cart::zzz][k][m] - PmC1*dip4[0][Cart::zzz][k][m+1] + (k==1)*nuc3[0][Cart::zzz][m+1];
dip4[0][Cart::zzzz][k][m] = PmB2*dip4[0][Cart::zzz][k][m] - PmC2*dip4[0][Cart::zzz][k][m+1] + (k==2)*nuc3[0][Cart::zzz][m+1] + 3*term_zz;
}
}
//------------------------------------------------------
//Integrals p - g d - g f - g g - g
for (int m = 0; m < lmax_col-3; m++) {
for (int i = 1; i < n_orbitals[lmax_row]; i++) {
int nx_i = nx[i];
int ny_i = ny[i];
int nz_i = nz[i];
int ilx_i = i_less_x[i];
int ily_i = i_less_y[i];
int ilz_i = i_less_z[i];
for (int k = 0; k < 3; k++) {
double term_xx = fak*(dip4[i][Cart::xx][k][m]-dip4[i][Cart::xx][k][m+1]);
double term_yy = fak*(dip4[i][Cart::yy][k][m]-dip4[i][Cart::yy][k][m+1]);
double term_zz = fak*(dip4[i][Cart::zz][k][m]-dip4[i][Cart::zz][k][m+1]);
dip4[i][Cart::xxxx][k][m] = PmB0*dip4[i][Cart::xxx][k][m] - PmC0*dip4[i][Cart::xxx][k][m+1] + (k==0)*nuc3[i][Cart::xxx][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::xxx][k][m] - dip4[ilx_i][Cart::xxx][k][m+1]) + 3*term_xx;
dip4[i][Cart::xxxy][k][m] = PmB1*dip4[i][Cart::xxx][k][m] - PmC1*dip4[i][Cart::xxx][k][m+1] + (k==1)*nuc3[i][Cart::xxx][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::xxx][k][m] - dip4[ily_i][Cart::xxx][k][m+1]);
dip4[i][Cart::xxxz][k][m] = PmB2*dip4[i][Cart::xxx][k][m] - PmC2*dip4[i][Cart::xxx][k][m+1] + (k==2)*nuc3[i][Cart::xxx][m+1]
+ nz_i*fak*(dip4[ilz_i][Cart::xxx][k][m] - dip4[ilz_i][Cart::xxx][k][m+1]);
dip4[i][Cart::xxyy][k][m] = PmB0*dip4[i][Cart::xyy][k][m] - PmC0*dip4[i][Cart::xyy][k][m+1] + (k==0)*nuc3[i][Cart::xyy][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::xyy][k][m] - dip4[ilx_i][Cart::xyy][k][m+1]) + term_yy;
dip4[i][Cart::xxyz][k][m] = PmB1*dip4[i][Cart::xxz][k][m] - PmC1*dip4[i][Cart::xxz][k][m+1] + (k==1)*nuc3[i][Cart::xxz][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::xxz][k][m] - dip4[ily_i][Cart::xxz][k][m+1]);
dip4[i][Cart::xxzz][k][m] = PmB0*dip4[i][Cart::xzz][k][m] - PmC0*dip4[i][Cart::xzz][k][m+1] + (k==0)*nuc3[i][Cart::xzz][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::xzz][k][m] - dip4[ilx_i][Cart::xzz][k][m+1]) + term_zz;
dip4[i][Cart::xyyy][k][m] = PmB0*dip4[i][Cart::yyy][k][m] - PmC0*dip4[i][Cart::yyy][k][m+1] + (k==0)*nuc3[i][Cart::yyy][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::yyy][k][m] - dip4[ilx_i][Cart::yyy][k][m+1]);
dip4[i][Cart::xyyz][k][m] = PmB0*dip4[i][Cart::yyz][k][m] - PmC0*dip4[i][Cart::yyz][k][m+1] + (k==0)*nuc3[i][Cart::yyz][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::yyz][k][m] - dip4[ilx_i][Cart::yyz][k][m+1]);
dip4[i][Cart::xyzz][k][m] = PmB0*dip4[i][Cart::yzz][k][m] - PmC0*dip4[i][Cart::yzz][k][m+1] + (k==0)*nuc3[i][Cart::yzz][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::yzz][k][m] - dip4[ilx_i][Cart::yzz][k][m+1]);
dip4[i][Cart::xzzz][k][m] = PmB0*dip4[i][Cart::zzz][k][m] - PmC0*dip4[i][Cart::zzz][k][m+1] + (k==0)*nuc3[i][Cart::zzz][m+1]
+ nx_i*fak*(dip4[ilx_i][Cart::zzz][k][m] - dip4[ilx_i][Cart::zzz][k][m+1]);
dip4[i][Cart::yyyy][k][m] = PmB1*dip4[i][Cart::yyy][k][m] - PmC1*dip4[i][Cart::yyy][k][m+1] + (k==1)*nuc3[i][Cart::yyy][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::yyy][k][m] - dip4[ily_i][Cart::yyy][k][m+1]) + 3*term_yy;
dip4[i][Cart::yyyz][k][m] = PmB2*dip4[i][Cart::yyy][k][m] - PmC2*dip4[i][Cart::yyy][k][m+1] + (k==2)*nuc3[i][Cart::yyy][m+1]
+ nz_i*fak*(dip4[ilz_i][Cart::yyy][k][m] - dip4[ilz_i][Cart::yyy][k][m+1]);
dip4[i][Cart::yyzz][k][m] = PmB1*dip4[i][Cart::yzz][k][m] - PmC1*dip4[i][Cart::yzz][k][m+1] + (k==1)*nuc3[i][Cart::yzz][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::yzz][k][m] - dip4[ily_i][Cart::yzz][k][m+1]) + term_zz;
dip4[i][Cart::yzzz][k][m] = PmB1*dip4[i][Cart::zzz][k][m] - PmC1*dip4[i][Cart::zzz][k][m+1] + (k==1)*nuc3[i][Cart::zzz][m+1]
+ ny_i*fak*(dip4[ily_i][Cart::zzz][k][m] - dip4[ily_i][Cart::zzz][k][m+1]);
dip4[i][Cart::zzzz][k][m] = PmB2*dip4[i][Cart::zzz][k][m] - PmC2*dip4[i][Cart::zzz][k][m+1] + (k==2)*nuc3[i][Cart::zzz][m+1]
+ nz_i*fak*(dip4[ilz_i][Cart::zzz][k][m] - dip4[ilz_i][Cart::zzz][k][m+1]) + 3*term_zz;
}
}
}
//------------------------------------------------------
} // end if (lmax_col > 3)
//votca dipoles are spherical in ordering z,y,x
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
dip(i,j) = dipole.getX() * dip4[i][j][0][0] +dipole.getY() * dip4[i][j][1][0] + dipole.getZ() * dip4[i][j][2][0];
}
}
Eigen::MatrixXd dip_sph = getTrafo(*itr).transpose()*dip*getTrafo(*itc);
// save to matrix
for ( unsigned i = 0; i< matrix.rows(); i++ ) {
for (unsigned j = 0; j < matrix.cols(); j++) {
matrix(i,j) += dip_sph(i+shell_row->getOffset(),j+shell_col->getOffset());
}
}
}// shell_col Gaussians
}// shell_row Gaussians
}
void AODipole_Potential::Fillextpotential(const AOBasis& aobasis, const std::vector<std::shared_ptr<ctp::PolarSeg> > & sites) {
_externalpotential = Eigen::MatrixXd::Zero(aobasis.AOBasisSize(), aobasis.AOBasisSize());
for (unsigned int i = 0; i < sites.size(); i++) {
for (ctp::APolarSite* site:*(sites[i])) {
if (site->getRank() > 0 || site->IsPolarizable()) {
if(tools::abs(site->getU1()+site->getQ1())<1e-12){continue;}
_aomatrix = Eigen::MatrixXd::Zero(aobasis.AOBasisSize(), aobasis.AOBasisSize());
setAPolarSite(site);
Fill(aobasis);
_externalpotential += _aomatrix;
}
}
}
return;
}
}}
| 59.193916 | 185 | 0.480751 | [
"vector"
] |
a344bca11f5106cfb778ce7c8119b8a5a9f240ff | 6,079 | cpp | C++ | FaceX-Train/regressor_train.cpp | rivid/FaceX | ccbb2693091dbe515666a8d0373d7b9650d25f5e | [
"MIT"
] | 166 | 2015-02-21T17:57:13.000Z | 2022-03-21T09:33:36.000Z | FaceX-Train/regressor_train.cpp | rivid/FaceX | ccbb2693091dbe515666a8d0373d7b9650d25f5e | [
"MIT"
] | 12 | 2015-01-15T21:52:25.000Z | 2018-04-17T12:43:49.000Z | FaceX-Train/regressor_train.cpp | rivid/FaceX | ccbb2693091dbe515666a8d0373d7b9650d25f5e | [
"MIT"
] | 98 | 2015-03-01T12:19:29.000Z | 2021-06-27T10:54:44.000Z | /*
FaceX-Train is a tool to train model file for FaceX, which is an open
source face alignment library.
Copyright(C) 2015 Yang Cao
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 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program.If not, see <http://www.gnu.org/licenses/>.
*/
#include "regressor_train.h"
#include <utility>
#include <iostream>
#include <memory>
#include <algorithm>
#include "utils_train.h"
using namespace std;
RegressorTrain::RegressorTrain(const TrainingParameters &tp)
: training_parameters_(tp)
{
ferns_ = vector<FernTrain>(training_parameters_.K, FernTrain(tp));
pixels_ = std::vector<std::pair<int, cv::Point2d>>(training_parameters_.P);
}
void RegressorTrain::Regress(const vector<cv::Point2d> &mean_shape,
vector<vector<cv::Point2d>> *targets,
const vector<DataPoint> & training_data)
{
for (int i = 0; i < training_parameters_.P; ++i)
{
pixels_[i].first = cv::theRNG().uniform(0,
training_data[0].landmarks.size());
pixels_[i].second.x = cv::theRNG().uniform(-training_parameters_.Kappa,
training_parameters_.Kappa);
pixels_[i].second.y = cv::theRNG().uniform(-training_parameters_.Kappa,
training_parameters_.Kappa);
}
// If you want to use AVX2, you must pay attention to memory alignment.
// AVX2 is not used by default. You can change Covariance in fern_train.cpp
// to AVXCovariance to enable it.
unique_ptr<double[]> pixels_val_data(new double[
training_parameters_.P * training_data.size() + 3]);
cv::Mat pixels_val(training_parameters_.P, training_data.size(), CV_64FC1,
cv::alignPtr(pixels_val_data.get(), 32));
for (int i = 0; i < pixels_val.cols; ++i)
{
Transform t = Procrustes(training_data[i].init_shape, mean_shape);
vector<cv::Point2d> offsets(training_parameters_.P);
for (int j = 0; j < training_parameters_.P; ++j)
offsets[j] = pixels_[j].second;
t.Apply(&offsets, false);
for (int j = 0; j < training_parameters_.P; ++j)
{
cv::Point pixel_pos = training_data[i].init_shape[pixels_[j].first]
+ offsets[j];
if (pixel_pos.inside(cv::Rect(0, 0,
training_data[i].image.cols, training_data[i].image.rows)))
{
pixels_val.at<double>(j, i) =
training_data[i].image.at<uchar>(pixel_pos);
}
else
pixels_val.at<double>(j, i) = 0;
}
}
cv::Mat pixels_cov, means;
cv::calcCovarMatrix(pixels_val, pixels_cov, means,
cv::COVAR_NORMAL | cv::COVAR_SCALE | cv::COVAR_COLS);
for (int i = 0; i < training_parameters_.K; ++i)
{
ferns_[i].Regress(targets, pixels_val, pixels_cov);
for (int j = 0; j < targets->size(); ++j)
{
(*targets)[j] = ShapeDifference((*targets)[j], ferns_[i].Apply(
pixels_val(cv::Range::all(), cv::Range(j, j + 1))));
}
}
CompressFerns();
}
void RegressorTrain::CompressFerns()
{
base_.create(ferns_[0].outputs[0].size() * 2, training_parameters_.Base, CV_64FC1);
vector<int> rand_index;
for (int i = 0; i < training_parameters_.K * (1 << training_parameters_.F); ++i)
rand_index.push_back(i);
random_shuffle(rand_index.begin(), rand_index.end());
for (int i = 0; i < training_parameters_.Base; ++i)
{
const vector<cv::Point2d> &output = ferns_[rand_index[i] >> training_parameters_.F]
.outputs[rand_index[i] & ((1 << training_parameters_.F) - 1)];
for (int j = 0; j < output.size(); ++j)
{
base_.at<double>(j * 2, i) = output[j].x;
base_.at<double>(j * 2 + 1, i) = output[j].y;
}
cv::normalize(base_.col(i), base_.col(i));
}
for (int i = 0; i < training_parameters_.K; ++i)
{
for (int j = 0; j < (1 << training_parameters_.F); ++j)
{
const vector<cv::Point2d> &output = ferns_[i].outputs[j];
cv::Mat output_mat(base_.rows, 1, CV_64FC1);
for (int k = 0; k < output.size(); ++k)
{
output_mat.at<double>(k * 2) = output[k].x;
output_mat.at<double>(k * 2 + 1) = output[k].y;
}
ferns_[i].outputs_mini.push_back(OMP(output_mat, base_, training_parameters_.Q));
}
}
}
vector<cv::Point2d> RegressorTrain::Apply(const vector<cv::Point2d> &mean_shape,
const DataPoint &data) const
{
cv::Mat pixels_val(1, training_parameters_.P, CV_64FC1);
Transform t = Procrustes(data.init_shape, mean_shape);
vector<cv::Point2d> offsets(training_parameters_.P);
for (int j = 0; j < training_parameters_.P; ++j)
offsets[j] = pixels_[j].second;
t.Apply(&offsets, false);
double *p = pixels_val.ptr<double>(0);
for (int j = 0; j < training_parameters_.P; ++j)
{
cv::Point pixel_pos = data.init_shape[pixels_[j].first] + offsets[j];
if (pixel_pos.inside(cv::Rect(0, 0, data.image.cols, data.image.rows)))
p[j] = data.image.at<uchar>(pixel_pos);
else
p[j] = 0;
}
vector<double> coeffs(training_parameters_.Base);
for (int i = 0; i < training_parameters_.K; ++i)
ferns_[i].ApplyMini(pixels_val, coeffs);
cv::Mat result_mat = cv::Mat::zeros(mean_shape.size() * 2, 1, CV_64FC1);
for (int i = 0; i < training_parameters_.Base; ++i)
result_mat += coeffs[i] * base_.col(i);
vector<cv::Point2d> result(mean_shape.size());
for (int i = 0; i < result.size(); ++i)
{
result[i].x = result_mat.at<double>(i * 2);
result[i].y = result_mat.at<double>(i * 2 + 1);
}
return result;
}
void RegressorTrain::write(cv::FileStorage &fs)const
{
fs << "{";
fs << "pixels";
fs << "[";
for (auto it = pixels_.begin(); it != pixels_.end(); ++it)
fs << "{" << "first" << it->first << "second" << it->second << "}";
fs << "]";
fs << "ferns" << "[";
for (auto it = ferns_.begin(); it != ferns_.end(); ++it)
fs << *it;
fs << "]";
fs << "base" << base_;
fs << "}";
}
void write(cv::FileStorage& fs, const string&, const RegressorTrain& r)
{
r.write(fs);
}
| 31.015306 | 85 | 0.671821 | [
"vector",
"model",
"transform"
] |
a34902f6f302bf341b644def4144a4c2aa76e666 | 24,399 | cpp | C++ | ssc/cmod_wind_landbosse.cpp | NREL/ssc | bf6e73a89dbe81ac7c896d192929c28011bc6d24 | [
"BSD-3-Clause"
] | 61 | 2017-08-09T15:10:59.000Z | 2022-02-15T21:45:31.000Z | ssc/cmod_wind_landbosse.cpp | NREL/ssc | bf6e73a89dbe81ac7c896d192929c28011bc6d24 | [
"BSD-3-Clause"
] | 462 | 2017-07-31T21:26:46.000Z | 2022-03-30T22:53:50.000Z | ssc/cmod_wind_landbosse.cpp | NREL/ssc | bf6e73a89dbe81ac7c896d192929c28011bc6d24 | [
"BSD-3-Clause"
] | 73 | 2017-08-24T17:39:31.000Z | 2022-03-28T08:37:47.000Z | /**
BSD-3-Clause
Copyright 2019 Alliance for Sustainable Energy, LLC
Redistribution and use in source and binary forms, with or without modification, are permitted provided
that the following conditions are met :
1. Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT HOLDER, CONTRIBUTORS, UNITED STATES GOVERNMENT OR UNITED STATES
DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, 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 <fstream>
#include <future>
#include <sstream>
#ifdef __WINDOWS__
#include <Windows.h>
#include <stdio.h>
#include <tchar.h>
#pragma warning(disable: 4191)
#include "AtlBase.h"
#include "AtlConv.h"
#endif
#include "../rapidjson/document.h"
#include "../rapidjson/istreamwrapper.h"
#include "sscapi.h"
#include "core.h"
#include "cmod_wind_landbosse.h"
static var_info _cm_vtab_wind_landbosse[] = {
/* VARTYPE DATATYPE NAME LABEL UNITS META GROUP REQUIRED_IF CONSTRAINTS UI_HINTS*/
// Inputs
{ SSC_INPUT, SSC_NUMBER, "en_landbosse", "Enable landbosse (1 for enabled)", "", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_STRING, "wind_resource_filename", "Local hourly wind data file path", "", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "distance_to_interconnect_mi", "Distance to Interconnect", "miles", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "interconnect_voltage_kV", "Interconnect Voltage", "kV", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "depth", "Foundation Depth", "m", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "rated_thrust_N", "Rated Thrust", "N", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "labor_cost_multiplier", "Labor Cost Multiplier", "", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "gust_velocity_m_per_s", "50 year Gust Velocity", "m/s", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "wind_resource_shear", "Wind Shear Exponent", "", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "num_turbines", "Number of Turbines", "", "", "LandBOSSE", "*", "INTEGER,", "" },
{ SSC_INPUT, SSC_NUMBER, "turbine_spacing_rotor_diameters", "Turbine Spacing", "diameters","", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "row_spacing_rotor_diameters", "Row Spacing", "diameters","", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "turbine_rating_MW", "Turbine Rating", "kW", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "wind_turbine_hub_ht", "Hub Height", "m", "", "LandBOSSE", "*", "", "" },
{ SSC_INPUT, SSC_NUMBER, "wind_turbine_rotor_diameter", "Rotor Diameter", "m", "", "LandBOSSE", "*", "", "" },
{ SSC_OUTPUT, SSC_STRING, "errors", "BOS - Error message", "", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "bonding_usd", "BOS - Management - Bonding Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "collection_equipment_rental_usd", "BOS - Collection - Equipment Rental Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "collection_labor_usd", "BOS - Collection - Labor Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "collection_material_usd", "BOS - Collection - Materials Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "collection_mobilization_usd", "BOS - Collection - Mobilization Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "construction_permitting_usd", "BOS - Management - Construction Permitting Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "development_labor_usd", "BOS - Development - Labor Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "development_material_usd", "BOS - Development - Material Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "development_mobilization_usd", "BOS - Development - Mobilization Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "engineering_usd", "BOS - Management - Engineering Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "erection_equipment_rental_usd", "BOS - Erection - Equipment Rental Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "erection_fuel_usd", "BOS - Erection - Fuel Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "erection_labor_usd", "BOS - Erection - Labor Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "erection_material_usd", "BOS - Erection - Material Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "erection_mobilization_usd", "BOS - Erection - Mobilization Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "erection_other_usd", "BOS - Erection - Other Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "foundation_equipment_rental_usd", "BOS - Foundation - Equipment Rental Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "foundation_labor_usd", "BOS - Foundation - Labor Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "foundation_material_usd", "BOS - Foundation - Material Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "foundation_mobilization_usd", "BOS - Foundation - Mobilization Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "insurance_usd", "BOS - Management - Insurance Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "markup_contingency_usd", "BOS - Management - Markup Contingency", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "project_management_usd", "BOS - Management - Project Management Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "site_facility_usd", "BOS - Management - Site Facility Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "sitepreparation_equipment_rental_usd", "BOS - Site Preparation - Equipment Rental Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "sitepreparation_labor_usd", "BOS - Site Preparation - Labor Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "sitepreparation_material_usd", "BOS - Site Preparation - Material Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "sitepreparation_mobilization_usd", "BOS - Site Preparation - Mobilization Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_collection_cost", "BOS - Total Collection Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_development_cost", "BOS - Total Development Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_erection_cost", "BOS - Total Erection Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_foundation_cost", "BOS - Total Foundation Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_gridconnection_cost", "BOS - Total Grid Connection Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_management_cost", "BOS - Total Management Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_sitepreparation_cost", "BOS - Total Site Preparation Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_substation_cost", "BOS - Total Substation Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
{ SSC_OUTPUT, SSC_NUMBER, "total_bos_cost", "BOS - Total BOS Cost", "$", "", "LandBOSSE", "en_landbosse=1", "", "", } ,
var_info_invalid
};
cm_wind_landbosse::cm_wind_landbosse() {
add_var_info(_cm_vtab_wind_landbosse);
}
void cm_wind_landbosse::load_config(){
std::string python_config_path = get_python_path();
if (python_config_path.empty())
throw exec_error("wind_landbosse", "Path to SAM python configuration directory not set. "
"Use 'set_python_path' function in sscapi.h to point to the correct folder.");
// load python configuration
rapidjson::Document python_config_root;
std::ifstream python_config_doc(python_config_path + "/python_config.json");
if (python_config_doc.fail())
throw exec_error("wind_landbosse", "Could not open 'python_config.json'. "
"Use 'set_python_path' function in sscapi.h to point to the folder containing the file.");
#ifdef __WINDOWS__
// check for byte-order mark indicating UTF-8 and skip if it exists since it's not JSON-compatible
char a,b,c;
a = (char)python_config_doc.get();
b = (char)python_config_doc.get();
c = (char)python_config_doc.get();
if (a != (char)0xEF || b != (char)0xBB || c != (char)0xBF) {
python_config_doc.seekg(0);
}
#endif
std::ostringstream tmp;
tmp << python_config_doc.rdbuf();
python_config_root.Parse(tmp.str().c_str());
if (!python_config_root.HasMember("exec_path"))
throw exec_error("wind_landbosse", "Missing key 'exec_path' in 'python_config.json'.");
if (!python_config_root.HasMember("python_version"))
throw exec_error("wind_landbosse", "Missing key 'python_version' in 'python_config.json'.");
python_exec_path = python_config_root["exec_path"].GetString();
auto str_python = std::string(get_python_path()) + "/" + python_exec_path;
if (!util::file_exists( str_python.c_str()))
throw exec_error("wind_landbosse", "Missing python executable 'exe_path' in 'python_config.json'.");
auto python_version = python_config_root["python_version"].GetString();
// load landbosse configuration
rapidjson::Document landbosse_config_root;
std::ifstream landbosse_config_doc(python_config_path + "/landbosse.json");
if (landbosse_config_doc.fail())
throw exec_error("wind_landbosse", "Could not open 'landbosse.json'. "
"Use 'set_python_path' function in sscapi.h to point to the folder containing the file.");
std::ostringstream tmplb;
tmplb << landbosse_config_doc.rdbuf();
landbosse_config_root.Parse(tmplb.str().c_str());
if (!landbosse_config_root.HasMember("run_cmd"))
throw exec_error("wind_landbosse", "Missing key 'run_cmd' in 'landbosse.json'.");
if (!landbosse_config_root.HasMember("min_python_version"))
throw exec_error("wind_landbosse", "Missing key 'min_python_version' in 'landbosse.json'.");
python_run_cmd = landbosse_config_root["run_cmd"].GetString();
auto min_python_version = landbosse_config_root["min_python_version"].GetString();
// check version works out
std::stringstream min_ver(min_python_version);
std::stringstream py_ver(python_version);
std::string min_ver_token, py_ver_token;
while (std::getline(min_ver, min_ver_token, '.')) {
if (!std::getline(py_ver, py_ver_token, '.'))
return;
if (std::stoi(min_ver_token) > std::stoi(py_ver_token))
throw exec_error("wind_landbosse", "'min_python_version' requirement not met.");
}
}
const size_t BUFSIZE = 4096;
std::string cm_wind_landbosse::call_python_module(const std::string& input_dict_as_text){
std::promise<std::string> python_result;
std::future<std::string> f_completes = python_result.get_future();
std::thread([&]
{
std::string cmd = std::string(get_python_path()) + "/" + python_exec_path + " -c \"" + python_run_cmd + "\"";
size_t pos = cmd.find("<input>");
cmd.replace(pos, 7, input_dict_as_text);
FILE *file_pipe = popen(cmd.c_str(), "r");
if (!file_pipe){
python_result.set_value("wind_landbosse error. Could not call python with cmd:\n" + cmd);
return;
}
std::string mod_response;
char buffer[BUFSIZE];
while (fgets(buffer, sizeof(buffer), file_pipe)){
mod_response += buffer;
}
pclose(file_pipe);
if (mod_response.empty())
python_result.set_value("LandBOSSE error. Function did not return a response.");
else
python_result.set_value(mod_response);
}
).detach();
std::chrono::system_clock::time_point time_passed
= std::chrono::system_clock::now() + std::chrono::seconds(60 * 5);
if(std::future_status::ready == f_completes.wait_until(time_passed))
return f_completes.get();
else
throw exec_error("wind_landbosse", "python handler error. Python process timed out.");
}
#ifdef __WINDOWS__
std::string cm_wind_landbosse::call_python_module_windows(const std::string& input_dict_as_text) {
STARTUPINFO si;
SECURITY_ATTRIBUTES sa;
PROCESS_INFORMATION pi;
HANDLE stdin_rd = NULL;
HANDLE stdout_wr = NULL;
HANDLE stdout_rd = NULL;
HANDLE stdin_wr = NULL;
HANDLE stderr_rd = NULL;
HANDLE stderr_wr = NULL; //pipe handles
char buf[BUFSIZE]; //i/o buffer
memset(buf, 0, sizeof(buf));
std::string pythonpath = std::string(get_python_path()) + "\\" + python_exec_path;
CA2T programpath( pythonpath.c_str());
std::string pythonarg = " -c \"" + python_run_cmd + "\"";
size_t pos = pythonarg.find("<input>");
pythonarg.replace(pos, 7, input_dict_as_text);
CA2T programargs(pythonarg.c_str());
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
if (!CreatePipe(&stdin_rd, &stdin_wr, &sa, 0)) {
goto done;
}
if (!SetHandleInformation(stdin_wr, HANDLE_FLAG_INHERIT, 0)) {
goto done;
}
if (!CreatePipe(&stdout_rd, &stdout_wr, &sa, 0)) {
goto done;
}
if (!SetHandleInformation(stdout_rd, HANDLE_FLAG_INHERIT, 0)) {
goto done;
}
if (!CreatePipe(&stderr_rd, &stderr_wr, &sa, 0)) {
goto done;
}
if (!SetHandleInformation(stderr_rd, HANDLE_FLAG_INHERIT, 0)) {
goto done;
}
//set startupinfo for the spawned process
/*The dwFlags member tells CreateProcess how to make the process.
STARTF_USESTDHANDLES: validates the hStd* members.
STARTF_USESHOWWINDOW: validates the wShowWindow member*/
GetStartupInfo(&si);
si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
si.wShowWindow = SW_HIDE;
//set the new handles for the child process
si.hStdOutput = stdout_wr;
si.hStdError = stderr_wr;
si.hStdInput = stdin_rd;
//spawn the child process
if (CreateProcess(programpath, programargs, NULL, NULL, TRUE, CREATE_NO_WINDOW,
NULL, NULL, &si, &pi)) {
unsigned long bread; //bytes read
unsigned long bread_last = 0;
unsigned long avail; //bytes available
size_t i = 0;
size_t n_timeout_max = 100000000; // timeout
for (i=0;i<n_timeout_max;i++) {
PeekNamedPipe(stdout_rd, buf, BUFSIZE - 1, &bread, &avail, NULL);
//check to see if there is any data to read from stdout
if (bread != 0) {
if (ReadFile(stdout_rd, buf, BUFSIZE - 1, &bread, NULL)) {
bread_last = bread;
}
}
else if (bread_last > 0)
{
break;
}
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
if (i>=n_timeout_max)
throw exec_error("wind_landbosse", "LandBOSSE error. Timeout while running.");
}
done:
std::vector<HANDLE> handles = {stdin_rd, stdin_wr, stdout_rd, stdout_wr, stderr_rd, stderr_wr};
for (HANDLE handle : handles) {
if (handle && handle != INVALID_HANDLE_VALUE) {
CloseHandle(handle);
}
}
if (buf[0] == '\0')
throw exec_error("wind_landbosse", "LandBOSSE error. Function did not return a response.");
return buf;
}
#endif
void cm_wind_landbosse::cleanOutputString(std::string& output_json) {
size_t pos = output_json.find("{");
if (pos != std::string::npos)
output_json = output_json.substr(pos);
std::replace(output_json.begin(), output_json.end(), '\'', '\"');
}
void cm_wind_landbosse::exec() {
if (!m_vartab->lookup("en_landbosse")->num[0])
return;
// limit the input json through the process pip to only landbosse-required inputs
var_table input_data;
input_data.assign_match_case("weather_file_path", *m_vartab->lookup("wind_resource_filename"));
input_data.assign_match_case("distance_to_interconnect_mi", *m_vartab->lookup("distance_to_interconnect_mi"));
input_data.assign_match_case("interconnect_voltage_kV", *m_vartab->lookup("interconnect_voltage_kv"));
input_data.assign_match_case("depth", *m_vartab->lookup("depth"));
input_data.assign_match_case("rated_thrust_N", *m_vartab->lookup("rated_thrust_n"));
input_data.assign_match_case("labor_cost_multiplier", *m_vartab->lookup("labor_cost_multiplier"));
input_data.assign_match_case("gust_velocity_m_per_s", *m_vartab->lookup("gust_velocity_m_per_s"));
input_data.assign_match_case("wind_shear_exponent", *m_vartab->lookup("wind_resource_shear"));
input_data.assign_match_case("num_turbines", *m_vartab->lookup("num_turbines"));
input_data.assign_match_case("turbine_spacing_rotor_diameters", *m_vartab->lookup("turbine_spacing_rotor_diameters"));
input_data.assign_match_case("row_spacing_rotor_diameters", *m_vartab->lookup("row_spacing_rotor_diameters"));
input_data.assign_match_case("turbine_rating_MW", *m_vartab->lookup("turbine_rating_mw"));
input_data.assign_match_case("hub_height_meters", *m_vartab->lookup("wind_turbine_hub_ht"));
input_data.assign_match_case("rotor_diameter_m", *m_vartab->lookup("wind_turbine_rotor_diameter"));
std::string input_json = ssc_data_to_json(&input_data);
std::string input_dict_as_text = input_json;
std::replace(input_dict_as_text.begin(), input_dict_as_text.end(), '\"', '\'');
load_config();
#ifdef __WINDOWS__
std::string output_json = call_python_module_windows(input_dict_as_text);
#else
std::string output_json = call_python_module(input_dict_as_text);
#endif
cleanOutputString(output_json);
auto output_data = static_cast<var_table*>(json_to_ssc_data(output_json.c_str()));
if (output_data->is_assigned("error")){
m_vartab->assign("errors", output_json);
return;
}
m_vartab->merge(*output_data, false);
auto error_vd = m_vartab->lookup("errors");
if (error_vd && error_vd->type == SSC_ARRAY)
m_vartab->assign("errors", std::to_string(int(0)));
if (error_vd && error_vd->type == SSC_DATARR)
m_vartab->assign("errors", error_vd->vec[0].str);
}
DEFINE_MODULE_ENTRY( wind_landbosse, "Land-based Balance-of-System Systems Engineering (LandBOSSE) cost model", 1 )
| 64.547619 | 260 | 0.559244 | [
"vector",
"model"
] |
a34a3fc0c3efad60edeab1ee3f94502bf74c8d58 | 51,477 | cpp | C++ | goalc/compiler/compilation/Asm.cpp | 0x715C/jak-project | 490633d434fbb09b938d4a064a32b4bea14e7d80 | [
"0BSD"
] | null | null | null | goalc/compiler/compilation/Asm.cpp | 0x715C/jak-project | 490633d434fbb09b938d4a064a32b4bea14e7d80 | [
"0BSD"
] | null | null | null | goalc/compiler/compilation/Asm.cpp | 0x715C/jak-project | 490633d434fbb09b938d4a064a32b4bea14e7d80 | [
"0BSD"
] | null | null | null | #include "goalc/compiler/Compiler.h"
namespace {
const char* reg_names[] = {
"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10",
"r11", "r12", "r13", "r14", "r15", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5",
"xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15",
};
}
emitter::Register Compiler::parse_register(const goos::Object& code) {
if (!code.is_symbol()) {
throw_compiler_error(code, "Could not parse {} as a register name", code.print());
}
auto nas = code.as_symbol();
for (int i = 0; i < 32; i++) {
if (nas->name == reg_names[i]) {
return emitter::Register(i);
}
}
throw_compiler_error(code, "Could not parse {} as a register name", code.print());
return {};
}
Val* Compiler::compile_rlet(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
if (args.unnamed.size() < 1 || !args.named.empty()) {
throw_compiler_error(form, "Must have an rlet body.");
}
auto defs = args.unnamed.front();
auto fenv = get_parent_env_of_type<FunctionEnv>(env);
auto lenv = fenv->alloc_env<LexicalEnv>(env);
std::vector<IRegConstraint> constraints;
std::vector<RegVal*> reset_regs;
for_each_in_list(defs, [&](const goos::Object& o) {
// (new-place [:reg old-place] [:type type-spec] [:class reg-type] [:bind #f|lexical|lambda])
auto def_args = get_va(o, o);
va_check(o, def_args, {goos::ObjectType::SYMBOL},
{{"reg", {false, goos::ObjectType::SYMBOL}},
{"type", {false, {}}},
{"reset-here", {false, {}}},
{"class", {false, goos::ObjectType::SYMBOL}}});
// get the name of the new place
auto new_place_name = def_args.unnamed.at(0);
// get the type of the new place
TypeSpec ts = m_ts.make_typespec("object");
if (def_args.has_named("type")) {
ts = parse_typespec(def_args.named.at("type"));
}
// figure out the class
RegClass register_class = RegClass::GPR_64;
if (def_args.has_named("class")) {
auto& class_name = def_args.named.at("class").as_symbol()->name;
if (class_name == "gpr") {
register_class = RegClass::GPR_64;
} else if (class_name == "fpr") {
register_class = RegClass::FLOAT;
} else if (class_name == "vf") {
register_class = RegClass::VECTOR_FLOAT;
} else if (class_name == "i128") {
register_class = RegClass::INT_128;
} else {
throw_compiler_error(o, "Register class {} is unknown.", class_name);
}
}
// alloc a register:
auto new_place_reg = env->make_ireg(ts, register_class);
new_place_reg->mark_as_settable();
if (def_args.has_named("reg")) {
IRegConstraint constraint;
constraint.ireg = new_place_reg->ireg();
constraint.contrain_everywhere = true;
constraint.desired_register = parse_register(def_args.named.at("reg"));
if (def_args.has_named("reset-here") &&
get_true_or_false(form, def_args.get_named("reset-here"))) {
reset_regs.push_back(new_place_reg);
}
new_place_reg->set_rlet_constraint(constraint.desired_register);
constraints.push_back(constraint);
}
lenv->vars[new_place_name.as_symbol()->name] = new_place_reg;
});
if (!reset_regs.empty()) {
lenv->emit_ir<IR_ValueReset>(reset_regs);
}
Val* result = get_none();
for (u64 i = 1; i < args.unnamed.size(); i++) {
auto& o = args.unnamed.at(i);
result = compile_error_guard(o, lenv);
if (!dynamic_cast<None*>(result)) {
result = result->to_reg(lenv);
}
}
for (auto c : constraints) {
fenv->constrain(c);
}
return result;
}
Val* Compiler::compile_asm_ret(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
env->emit_ir<IR_AsmRet>(color);
return get_none();
}
Val* Compiler::compile_asm_pop(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto pop_dest = compile_error_guard(args.unnamed.at(0), env)->to_gpr(env);
if (!pop_dest->settable()) {
throw_compiler_error(form, "Cannot pop into this destination. Got a {}.", pop_dest->print());
}
env->emit_ir<IR_AsmPop>(color, pop_dest);
return get_none();
}
Val* Compiler::compile_asm_push(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
env->emit_ir<IR_AsmPush>(color, compile_error_guard(args.unnamed.at(0), env)->to_gpr(env));
return get_none();
}
Val* Compiler::compile_asm_sub(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_gpr(env);
if (!dest->settable()) {
throw_compiler_error(form, "Cannot .sub this. Got a {}.", dest->print());
}
auto src = compile_error_guard(args.unnamed.at(1), env)->to_gpr(env);
env->emit_ir<IR_AsmSub>(color, dest, src);
return get_none();
}
Val* Compiler::compile_asm_add(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_gpr(env);
if (!dest->settable()) {
throw_compiler_error(form, "Cannot .add this. Got a {}.", dest->print());
}
auto src = compile_error_guard(args.unnamed.at(1), env)->to_gpr(env);
env->emit_ir<IR_AsmAdd>(color, dest, src);
return get_none();
}
Val* Compiler::compile_asm_load_sym(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {goos::ObjectType::SYMBOL}},
{{"sext", {false, goos::ObjectType::SYMBOL}}, {"color", {false, goos::ObjectType::SYMBOL}}});
auto& sym_name = args.unnamed.at(1).as_symbol()->name;
auto sym_kv = m_symbol_types.find(sym_name);
if (sym_kv == m_symbol_types.end()) {
throw_compiler_error(form, "Cannot find a symbol named {}.", sym_name);
}
auto ts = sym_kv->second;
bool sext = m_ts.lookup_type(ts)->get_load_signed();
if (args.has_named("sext")) {
sext = get_true_or_false(form, args.named.at("sext"));
}
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_gpr(env);
if (!dest->settable()) {
throw_compiler_error(form, "Cannot .load-sym this. Got a {}.", dest->print());
}
env->emit_ir<IR_GetSymbolValueAsm>(color, dest, sym_name, sext);
return get_none();
}
Val* Compiler::compile_asm_jr(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto src = compile_error_guard(args.unnamed.at(0), env)->to_gpr(env);
env->emit_ir<IR_JumpReg>(color, src);
return get_none();
}
Val* Compiler::compile_asm_mov(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
if (!dest->settable()) {
throw_compiler_error(form, "Cannot .mov this. Got a {}.", dest->print());
}
auto src = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
env->emit_ir<IR_RegSetAsm>(color, dest, src);
return get_none();
}
Val* Compiler::compile_asm_nop_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {}, {});
env->emit_ir<IR_AsmFNop>();
return get_none();
}
Val* Compiler::compile_asm_wait_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {}, {});
env->emit_ir<IR_AsmFWait>();
return get_none();
}
/*!
* Load a vector float from memory. Does an aligned load.
*/
Val* Compiler::compile_asm_lvf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}},
{"offset", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
if (!dest->settable() || dest->ireg().reg_class != RegClass::VECTOR_FLOAT) {
throw_compiler_error(form, "Cannot .lvf into this. Got a {}.", dest->print());
}
auto src = compile_error_guard(args.unnamed.at(1), env);
auto as_sv = dynamic_cast<StaticVal*>(src);
// Loading directly from a static value is not supported!
if (as_sv && args.has_named("offset")) {
throw_compiler_error(form, "Cannot .lvf from a static value");
} else if (as_sv && !args.has_named("offset")) {
env->emit_ir<IR_StaticVarLoad>(dest, as_sv->obj);
return get_none();
}
auto as_co = dynamic_cast<MemoryOffsetConstantVal*>(src);
RegVal* baseReg = as_co ? as_co->base->to_gpr(env) : src->to_gpr(env);
int offset = 0;
if (as_co) {
if (!args.has_named("offset")) {
offset = as_co->offset;
} else {
offset = as_co->offset + args.named.at("offset").as_int();
}
} else if (args.has_named("offset")) {
offset = args.named.at("offset").as_int();
}
MemLoadInfo info;
info.sign_extend = false;
info.size = 16;
info.reg = RegClass::VECTOR_FLOAT;
env->emit_ir<IR_LoadConstOffset>(dest, offset, baseReg, info, color);
return get_none();
}
/*!
* Store a vector float into memory. Does an aligned load.
*/
Val* Compiler::compile_asm_svf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}},
{"offset", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env);
auto src = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
if (!src->settable() || src->ireg().reg_class != RegClass::VECTOR_FLOAT) {
throw_compiler_error(form, "Cannot .svf from this. Got a {}.", dest->print());
}
auto as_co = dynamic_cast<MemoryOffsetConstantVal*>(dest);
RegVal* baseReg = as_co ? as_co->base->to_gpr(env) : dest->to_gpr(env);
int offset = 0;
if (as_co) {
if (!args.has_named("offset")) {
offset = as_co->offset;
} else {
offset = as_co->offset + args.named.at("offset").as_int();
}
} else if (args.has_named("offset")) {
offset = args.named.at("offset").as_int();
}
MemLoadInfo info;
info.sign_extend = false;
info.size = 16;
info.reg = RegClass::VECTOR_FLOAT;
env->emit_ir<IR_StoreConstOffset>(src, offset, baseReg, info.size, color);
return get_none();
}
void Compiler::check_vector_float_regs(const goos::Object& form,
Env*,
std::vector<std::pair<std::string, RegVal*>> args) {
for (std::pair<std::string, RegVal*> arg : args) {
if (!arg.second->settable() || arg.second->ireg().reg_class != RegClass::VECTOR_FLOAT) {
throw_compiler_error(form, "Invalid {} register for a vector float operation form. Got a {}.",
arg.first, arg.second->print());
}
}
}
Val* Compiler::compile_asm_mov_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}}, {"mask", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
check_vector_float_regs(form, env, {{"destination", dest}, {"source", src}});
u8 mask = 0b1111;
if (args.has_named("mask")) {
mask = args.named.at("mask").as_int();
if (mask > 15) {
throw_compiler_error(form, "The value {} is out of range for a blend mask (0-15 inclusive).",
mask);
}
}
env->emit_ir<IR_BlendVF>(color, dest, dest, src, mask);
return get_none();
}
Val* Compiler::compile_asm_blend_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}}, {"mask", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env);
check_vector_float_regs(form, env,
{{"destination", dest}, {"first source", src1}, {"second source", src2}});
u8 mask = 0b1111;
if (args.has_named("mask")) {
mask = args.named.at("mask").as_int();
if (mask > 15) {
throw_compiler_error(form, "The value {} is out of range for a blend mask (0-15 inclusive).",
mask);
}
}
env->emit_ir<IR_BlendVF>(color, dest, src1, src2, mask);
return get_none();
}
Val* Compiler::compile_asm_vf_math3(const goos::Object& form,
const goos::Object& rest,
IR_VFMath3Asm::Kind kind,
emitter::Register::VF_ELEMENT broadcastElement,
Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}}, {"mask", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env);
check_vector_float_regs(form, env,
{{"destination", dest}, {"first source", src1}, {"second source", src2}});
u8 mask = 0b1111;
if (args.has_named("mask")) {
mask = args.named.at("mask").as_int();
if (mask > 15) {
throw_compiler_error(form, "The value {} is out of range for a blend mask (0-15 inclusive).",
mask);
}
}
// If there is a broadcast register, splat that float across the entire src2 register before
// performing the operation For example vaddx.xyzw vf10, vf20, vf30
// vf10[x] = vf20[x] + vf30[x]
// vf10[y] = vf20[y] + vf30[x]
// vf10[z] = vf20[z] + vf30[x]
// vf10[w] = vf20[w] + vf30[x]
if (broadcastElement != emitter::Register::VF_ELEMENT::NONE) {
auto temp_reg = env->make_vfr(dest->type());
env->emit_ir<IR_SplatVF>(color, temp_reg, src2, broadcastElement);
// If the entire destination is to be copied, we can optimize out the blend
if (mask == 0b1111) {
env->emit_ir<IR_VFMath3Asm>(color, dest, src1, temp_reg, kind);
} else {
// Perform the arithmetic operation on the two vectors into a temporary register
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, src1, temp_reg, kind);
// Blend the result back into the destination register using the mask
env->emit_ir<IR_BlendVF>(color, dest, dest, temp_reg, mask);
}
} else {
// If the entire destination is to be copied, we can optimize out the blend
if (mask == 0b1111) {
env->emit_ir<IR_VFMath3Asm>(color, dest, src1, src2, kind);
} else {
auto temp_reg = env->make_vfr(dest->type());
// Perform the arithmetic operation on the two vectors into a temporary register
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, src1, src2, kind);
// Blend the result back into the destination register using the mask
env->emit_ir<IR_BlendVF>(color, dest, dest, temp_reg, mask);
}
}
return get_none();
}
Val* Compiler::compile_asm_int128_math3(const goos::Object& form,
const goos::Object& rest,
IR_Int128Math3Asm::Kind kind,
Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}, {}}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env);
if (!dest->settable()) {
throw_compiler_error(form, "Cannot set destination");
}
env->emit_ir<IR_Int128Math3Asm>(color, dest, src1, src2, kind);
return get_none();
}
Val* Compiler::compile_asm_vf_math2(const goos::Object& form,
const goos::Object& rest,
IR_VFMath2Asm::Kind kind,
Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}}, {"mask", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
check_vector_float_regs(form, env, {{"destination", dest}, {"source", src}});
u8 mask = 0b1111;
if (args.has_named("mask")) {
mask = args.named.at("mask").as_int();
if (mask > 15) {
throw_compiler_error(form, "The value {} is out of range for a blend mask (0-15 inclusive).",
mask);
}
}
// If the entire destination is to be copied, we can optimize out the blend
if (mask == 0b1111) {
env->emit_ir<IR_VFMath2Asm>(color, dest, src, kind);
} else {
auto temp_reg = env->make_vfr(dest->type());
// Perform the arithmetic operation on the two vectors into a temporary register
env->emit_ir<IR_VFMath2Asm>(color, temp_reg, src, kind);
// Blend the result back into the destination register using the mask
env->emit_ir<IR_BlendVF>(color, dest, dest, temp_reg, mask);
}
return get_none();
}
Val* Compiler::compile_asm_int128_math2_imm_u8(const goos::Object& form,
const goos::Object& rest,
IR_Int128Math2Asm::Kind kind,
Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}}, {"mask", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
s64 imm;
if (!try_getting_constant_integer(args.unnamed.at(2), &imm, env)) {
throw_compiler_error(form, "Could not evaluate {} as a compile-time integer.",
args.unnamed.at(2).print());
}
if (imm < 0 || imm > 255) {
throw_compiler_error(form, "Immediate {} is invalid. The value {} is out of range for a uint8.",
args.unnamed.at(2).print(), imm);
}
u8 mask = 0b1111;
if (args.has_named("mask")) {
mask = args.named.at("mask").as_int();
if (mask > 15) {
throw_compiler_error(form, "The value {} is out of range for a blend mask (0-15 inclusive).",
mask);
}
}
// If the entire destination is to be copied, we can optimize out the blend
if (mask == 0b1111) {
env->emit_ir<IR_Int128Math2Asm>(color, dest, src, kind, imm);
} else {
auto temp_reg = env->make_vfr(dest->type());
// Perform the arithmetic operation on the two vectors into a temporary register
env->emit_ir<IR_Int128Math2Asm>(color, temp_reg, src, kind, imm);
// Blend the result back into the destination register using the mask
env->emit_ir<IR_BlendVF>(color, dest, dest, temp_reg, mask);
}
return get_none();
}
Val* Compiler::compile_asm_pw_sll(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math2_imm_u8(form, rest, IR_Int128Math2Asm::Kind::PW_SLL, env);
}
Val* Compiler::compile_asm_pw_srl(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math2_imm_u8(form, rest, IR_Int128Math2Asm::Kind::PW_SRL, env);
}
Val* Compiler::compile_asm_pw_sra(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math2_imm_u8(form, rest, IR_Int128Math2Asm::Kind::PW_SRA, env);
}
Val* Compiler::compile_asm_pextlw(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math3(form, rest, IR_Int128Math3Asm::Kind::PEXTLW, env);
}
Val* Compiler::compile_asm_pextuw(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math3(form, rest, IR_Int128Math3Asm::Kind::PEXTUW, env);
}
Val* Compiler::compile_asm_pcpyud(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math3(form, rest, IR_Int128Math3Asm::Kind::PCPYUD, env);
}
Val* Compiler::compile_asm_pcpyld(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math3(form, rest, IR_Int128Math3Asm::Kind::PCPYLD, env);
}
Val* Compiler::compile_asm_pceqw(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math3(form, rest, IR_Int128Math3Asm::Kind::PCEQW, env);
}
Val* Compiler::compile_asm_psubw(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_int128_math3(form, rest, IR_Int128Math3Asm::Kind::PSUBW, env);
}
Val* Compiler::compile_asm_ppach(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}, {}}, {});
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env); // rs
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env); // rt
auto temp = env->make_ireg(TypeSpec("uint128"), RegClass::INT_128);
if (!dest->settable()) {
throw_compiler_error(form, "Cannot set destination");
}
env->emit_ir<IR_Int128Math2Asm>(true, temp, src1, IR_Int128Math2Asm::Kind::VPSHUFLW, 0x88);
env->emit_ir<IR_Int128Math2Asm>(true, dest, src2, IR_Int128Math2Asm::Kind::VPSHUFLW, 0x88);
env->emit_ir<IR_Int128Math2Asm>(true, temp, temp, IR_Int128Math2Asm::Kind::VPSHUFHW, 0x88);
env->emit_ir<IR_Int128Math2Asm>(true, dest, dest, IR_Int128Math2Asm::Kind::VPSHUFHW, 0x88);
env->emit_ir<IR_Int128Math2Asm>(true, temp, temp, IR_Int128Math2Asm::Kind::VPSRLDQ, 4);
env->emit_ir<IR_Int128Math2Asm>(true, dest, dest, IR_Int128Math2Asm::Kind::VPSRLDQ, 4);
// is actually a VPUNPCKLQDQ with srcs swapped.
env->emit_ir<IR_Int128Math3Asm>(true, dest, temp, dest, IR_Int128Math3Asm::Kind::PCPYLD);
return get_none();
}
Val* Compiler::compile_asm_xorp(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}, {}}, {});
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env); // rs
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env); // rt
if (!dest->settable()) {
throw_compiler_error(form, "Cannot set destination");
}
env->emit_ir<IR_VFMath3Asm>(true, dest, src1, src2, IR_VFMath3Asm::Kind::XOR);
return get_none();
}
Val* Compiler::compile_asm_itof_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math2(form, rest, IR_VFMath2Asm::Kind::ITOF, env);
}
Val* Compiler::compile_asm_ftoi_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math2(form, rest, IR_VFMath2Asm::Kind::FTOI, env);
}
Val* Compiler::compile_asm_xor_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::XOR,
emitter::Register::VF_ELEMENT::NONE, env);
}
Val* Compiler::compile_asm_max_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MAX,
emitter::Register::VF_ELEMENT::NONE, env);
}
Val* Compiler::compile_asm_max_x_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MAX,
emitter::Register::VF_ELEMENT::X, env);
}
Val* Compiler::compile_asm_max_y_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MAX,
emitter::Register::VF_ELEMENT::Y, env);
}
Val* Compiler::compile_asm_max_z_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MAX,
emitter::Register::VF_ELEMENT::Z, env);
}
Val* Compiler::compile_asm_max_w_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MAX,
emitter::Register::VF_ELEMENT::W, env);
}
Val* Compiler::compile_asm_min_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MIN,
emitter::Register::VF_ELEMENT::NONE, env);
}
Val* Compiler::compile_asm_min_x_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MIN,
emitter::Register::VF_ELEMENT::X, env);
}
Val* Compiler::compile_asm_min_y_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MIN,
emitter::Register::VF_ELEMENT::Y, env);
}
Val* Compiler::compile_asm_min_z_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MIN,
emitter::Register::VF_ELEMENT::Z, env);
}
Val* Compiler::compile_asm_min_w_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MIN,
emitter::Register::VF_ELEMENT::W, env);
}
Val* Compiler::compile_asm_sub_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::NONE, env);
}
Val* Compiler::compile_asm_sub_x_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::X, env);
}
Val* Compiler::compile_asm_sub_y_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::Y, env);
}
Val* Compiler::compile_asm_sub_z_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::Z, env);
}
Val* Compiler::compile_asm_sub_w_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::W, env);
}
Val* Compiler::compile_asm_add_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::NONE, env);
}
Val* Compiler::compile_asm_add_x_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::X, env);
}
Val* Compiler::compile_asm_add_y_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::Y, env);
}
Val* Compiler::compile_asm_add_z_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::Z, env);
}
Val* Compiler::compile_asm_add_w_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::W, env);
}
Val* Compiler::compile_asm_mul_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MUL,
emitter::Register::VF_ELEMENT::NONE, env);
}
Val* Compiler::compile_asm_mul_x_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MUL,
emitter::Register::VF_ELEMENT::X, env);
}
Val* Compiler::compile_asm_mul_y_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MUL,
emitter::Register::VF_ELEMENT::Y, env);
}
Val* Compiler::compile_asm_mul_z_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MUL,
emitter::Register::VF_ELEMENT::Z, env);
}
Val* Compiler::compile_asm_mul_w_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
return compile_asm_vf_math3(form, rest, IR_VFMath3Asm::Kind::MUL,
emitter::Register::VF_ELEMENT::W, env);
}
Val* Compiler::compile_asm_vf_math4_two_operation(const goos::Object& form,
const goos::Object& rest,
IR_VFMath3Asm::Kind first_op_kind,
IR_VFMath3Asm::Kind second_op_kind,
emitter::Register::VF_ELEMENT broadcastElement,
Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {}, {}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}}, {"mask", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env);
// This third register is intended for the ACC/Q/ETC, and is used to temporarily store the value
// that eventually goes into the destination
//
// For example VMADDA:
// > ACC += src1 * src2
// > DEST = ACC
auto src3 = compile_error_guard(args.unnamed.at(3), env)->to_reg(env);
check_vector_float_regs(form, env,
{{"destination", dest},
{"first source", src1},
{"second source", src2},
{"third source", src3}});
u8 mask = 0b1111;
if (args.has_named("mask")) {
mask = args.named.at("mask").as_int();
if (mask > 15) {
throw_compiler_error(form, "The value {} is out of range for a blend mask (0-15 inclusive).",
mask);
}
}
// First we clear a temporary register
auto temp_reg = env->make_vfr(dest->type());
// If there is a broadcast register, splat that float across the entire src2 register before
// performing the operation For example vaddx.xyzw vf10, vf20, vf30
// vf10[x] = vf20[x] + vf30[x]
// vf10[y] = vf20[y] + vf30[x]
// vf10[z] = vf20[z] + vf30[x]
// vf10[w] = vf20[w] + vf30[x]
if (broadcastElement != emitter::Register::VF_ELEMENT::NONE) {
env->emit_ir<IR_SplatVF>(color, temp_reg, src2, broadcastElement);
// Perform the first operation
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, src1, temp_reg, first_op_kind);
// If the entire destination is to be copied, we can optimize out the blend
if (mask == 0b1111) {
env->emit_ir<IR_VFMath3Asm>(color, dest, src3, temp_reg, second_op_kind);
} else {
// Perform the second operation on the two vectors into the temporary register
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, src3, temp_reg, second_op_kind);
// Blend the result back into the destination register using the mask
env->emit_ir<IR_BlendVF>(color, dest, dest, temp_reg, mask);
}
} else {
// Perform the first operation
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, src1, src2, first_op_kind);
// If the entire destination is to be copied, we can optimize out the blend
if (mask == 0b1111) {
env->emit_ir<IR_VFMath3Asm>(color, dest, src3, temp_reg, second_op_kind);
} else {
// Perform the second operation on the two vectors into the temporary register
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, src3, temp_reg, second_op_kind);
// Blend the result back into the destination register using the mask
env->emit_ir<IR_BlendVF>(color, dest, dest, temp_reg, mask);
}
}
return get_none();
}
Val* Compiler::compile_asm_mul_add_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::NONE, env);
}
Val* Compiler::compile_asm_mul_add_x_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::X, env);
}
Val* Compiler::compile_asm_mul_add_y_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::Y, env);
}
Val* Compiler::compile_asm_mul_add_z_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::Z, env);
}
Val* Compiler::compile_asm_mul_add_w_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::ADD,
emitter::Register::VF_ELEMENT::W, env);
}
Val* Compiler::compile_asm_mul_sub_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::NONE, env);
}
Val* Compiler::compile_asm_mul_sub_x_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::X, env);
}
Val* Compiler::compile_asm_mul_sub_y_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::Y, env);
}
Val* Compiler::compile_asm_mul_sub_z_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::Z, env);
}
Val* Compiler::compile_asm_mul_sub_w_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
return compile_asm_vf_math4_two_operation(form, rest, IR_VFMath3Asm::Kind::MUL,
IR_VFMath3Asm::Kind::SUB,
emitter::Register::VF_ELEMENT::W, env);
}
Val* Compiler::compile_asm_abs_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}}, {"mask", {false, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
check_vector_float_regs(form, env, {{"destination", dest}, {"source", src}});
u8 mask = 0b1111;
if (args.has_named("mask")) {
mask = args.named.at("mask").as_int();
if (mask > 15) {
throw_compiler_error(
form, "The value {} is out of range for a destination mask (0-15 inclusive).", mask);
}
}
// There is no single instruction ABS on AVX, so there are a number of ways to do it manually,
// this is one of them. For example, assume the original vec = <1, -2, -3, 4>
// First we clear a temporary register, XOR'ing itself
auto temp_reg = env->make_vfr(dest->type());
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, temp_reg, temp_reg, IR_VFMath3Asm::Kind::XOR);
// Next, find the difference between our source operand and 0, use the same temp register, no need
// to use another <0, 0, 0, 0> - <1, -2, -3, 4> = <-1, 2, 3, 4>
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, temp_reg, src, IR_VFMath3Asm::Kind::SUB);
// Finally, find the maximum between our difference, and the original value
// MAX_OF(<-1, 2, 3, 4>, <1, -2, -3, 4>) = <1, 2, 3, 4>
if (mask == 0b1111) { // If the entire destination is to be copied, we can optimize out the blend
env->emit_ir<IR_VFMath3Asm>(color, dest, src, temp_reg, IR_VFMath3Asm::Kind::MAX);
} else {
env->emit_ir<IR_VFMath3Asm>(color, temp_reg, src, temp_reg, IR_VFMath3Asm::Kind::MAX);
// Blend the result back into the destination register using the mask
env->emit_ir<IR_BlendVF>(color, dest, dest, temp_reg, mask);
}
return get_none();
}
u8 Compiler::ftf_fsf_to_blend_mask(u8 val) {
// 00 -> x
// ...
// 11 -> w
return 0b0001 << val;
}
emitter::Register::VF_ELEMENT Compiler::ftf_fsf_to_vector_element(u8 val) {
// 00 -> x
// ...
// 11 -> w
switch (val) {
case 0b00:
return emitter::Register::VF_ELEMENT::X;
case 0b01:
return emitter::Register::VF_ELEMENT::Y;
case 0b10:
return emitter::Register::VF_ELEMENT::Z;
case 0b11:
return emitter::Register::VF_ELEMENT::W;
default:
throw_compiler_error_no_code("Invalid vector element {}", (int)val);
return emitter::Register::VF_ELEMENT::NONE;
}
}
Val* Compiler::compile_asm_div_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}, {}},
{
{"color", {false, goos::ObjectType::SYMBOL}},
{"fsf", {true, goos::ObjectType::INTEGER}},
{"ftf", {true, goos::ObjectType::INTEGER}},
});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env);
check_vector_float_regs(form, env,
{{"destination", dest}, {"first source", src1}, {"second source", src2}});
u8 fsf = args.named.at("fsf").as_int();
if (fsf > 3) {
throw_compiler_error(form, "The value {} is out of range for fsf (0-3 inclusive).", fsf);
}
u8 ftf = args.named.at("ftf").as_int();
if (ftf > 3) {
throw_compiler_error(form, "The value {} is out of range for ftf (0-3 inclusive).", ftf);
}
// VDIV in the VU stores its result in a single 32bit `Q` Register, it does not compute the packed
// division result
//
// Further more, you can mix and match the vector elements (ex. src1's X component divided by
// src2's Y) Because of this, we need to blend the two components into corresponding locations,
// perform the divide then place into the cleared dest. register.
//
// Why do we even bother using VDIVPS instead of FDIV? Because otherwise in x86, you have to use
// the FPU stack Registers are nicer.
// Save one temp reg, use the destination as one
auto temp_reg = env->make_vfr(dest->type());
// Splat src1's value into the dest reg, keep it simple, this way no matter which vector component
// is accessed from the final result will be the correct answer
env->emit_ir<IR_SplatVF>(color, dest, src1, ftf_fsf_to_vector_element(fsf));
// Splat src1's value into the the temp reg
env->emit_ir<IR_SplatVF>(color, temp_reg, src2, ftf_fsf_to_vector_element(ftf));
// Perform the Division
env->emit_ir<IR_VFMath3Asm>(color, dest, dest, temp_reg, IR_VFMath3Asm::Kind::DIV);
return get_none();
}
Val* Compiler::compile_asm_sqrt_vf(const goos::Object& form, const goos::Object& rest, Env* env) {
auto args = get_va(form, rest);
va_check(
form, args, {{}, {}},
{{"color", {false, goos::ObjectType::SYMBOL}}, {"ftf", {true, goos::ObjectType::INTEGER}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
check_vector_float_regs(form, env, {{"destination", dest}, {"source", src}});
u8 ftf = args.named.at("ftf").as_int();
if (ftf > 3) {
throw_compiler_error(form, "The value {} is out of range for ftf (0-3 inclusive).", ftf);
}
// VSQRT in the VU stores its result in a single 32bit `Q` Register, it does not compute the
// packed division result
//
// Because of this, we need to blend the relevent component into a cleared register and then
// perform the SQRT
//
// Why do we even bother using VSQRTPS instead of FSQRT? Because otherwise in x86, you have to use
// the FPU stack Registers are nicer.
// Splat src's value into the dest reg, keep it simple, this way no matter which vector component
// is accessed from the final result will be the correct answer
env->emit_ir<IR_SplatVF>(color, dest, src, ftf_fsf_to_vector_element(ftf));
env->emit_ir<IR_SqrtVF>(color, dest, dest);
return get_none();
}
Val* Compiler::compile_asm_inv_sqrt_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}, {}},
{
{"color", {false, goos::ObjectType::SYMBOL}},
{"fsf", {true, goos::ObjectType::INTEGER}},
{"ftf", {true, goos::ObjectType::INTEGER}},
});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env);
check_vector_float_regs(form, env,
{{"destination", dest}, {"first source", src1}, {"second source", src2}});
u8 fsf = args.named.at("fsf").as_int();
if (fsf > 3) {
throw_compiler_error(form, "The value {} is out of range for fsf (0-3 inclusive).", fsf);
}
u8 ftf = args.named.at("ftf").as_int();
if (ftf > 3) {
throw_compiler_error(form, "The value {} is out of range for ftf (0-3 inclusive).", ftf);
}
// Save one temp reg, use the destination as one
auto temp_reg = env->make_vfr(dest->type());
// Splat src1's value into the dest reg, keep it simple, this way no matter which vector component
// is accessed from the final result will be the correct answer
env->emit_ir<IR_SplatVF>(color, dest, src1, ftf_fsf_to_vector_element(fsf));
// Splat src1's value into the the temp reg
env->emit_ir<IR_SplatVF>(color, temp_reg, src2, ftf_fsf_to_vector_element(ftf));
// Square Root the temp reg
env->emit_ir<IR_SqrtVF>(color, temp_reg, temp_reg);
// Perform the Division
env->emit_ir<IR_VFMath3Asm>(color, dest, dest, temp_reg, IR_VFMath3Asm::Kind::DIV);
return get_none();
}
Val* Compiler::compile_asm_outer_product_vf(const goos::Object& form,
const goos::Object& rest,
Env* env) {
auto args = get_va(form, rest);
va_check(form, args, {{}, {}, {}}, {{"color", {false, goos::ObjectType::SYMBOL}}});
bool color = true;
if (args.has_named("color")) {
color = get_true_or_false(form, args.named.at("color"));
}
auto dest = compile_error_guard(args.unnamed.at(0), env)->to_reg(env);
auto src1 = compile_error_guard(args.unnamed.at(1), env)->to_reg(env);
auto src2 = compile_error_guard(args.unnamed.at(2), env)->to_reg(env);
check_vector_float_regs(form, env,
{{"destination", dest}, {"first source", src1}, {"second source", src2}});
// Given 2 vectors V1 = <1,2,3,4> and V2 = <5,6,7,8> and assume VDEST = <0, 0, 0, 999>
// The outer product is computed like so (only x,y,z components are operated on):
// x = (V1y * V2z) - (V2y * V1z) => (2 * 7) - (6 * 3) => -4
// y = (V1z * V2x) - (V2z * V1x) => (3 * 5) - (7 * 1) => 8
// z = (V1x * V2y) - (V2x * V1y) => (1 * 6) - (5 * 2) => -4
// w = N/A, left alone => 999
//
// There is probably a more optimized alg for this, but we can just do this in two stages
// First swizzle the first two vectors accordingly, and store in `dest`
// Then follow up with the second half.
//
// Some temporary regs are required AND its important to not modify dest's `w` or the source
// registers at all
// Init two temp registers
auto temp1 = env->make_vfr(dest->type());
auto temp2 = env->make_vfr(dest->type());
auto temp_dst = env->make_vfr(dest->type());
// First Portion
// - Swizzle src1 appropriately
env->emit_ir<IR_SwizzleVF>(color, temp1, src1, 0b00001001);
// - Move it into 'dest' safely (avoid mutating `w`)
env->emit_ir<IR_BlendVF>(color, temp_dst, temp_dst, temp1, 0b0111);
// - Swizzle src2 appropriately
env->emit_ir<IR_SwizzleVF>(color, temp1, src2, 0b00010010);
// - Multiply - Result in `dest`
env->emit_ir<IR_VFMath3Asm>(color, temp1, temp_dst, temp1, IR_VFMath3Asm::Kind::MUL);
// - Move it into 'dest' safely (avoid mutating `w`)
env->emit_ir<IR_BlendVF>(color, temp_dst, temp_dst, temp1, 0b0111);
// Second Portion
// - Swizzle src2 appropriately
env->emit_ir<IR_SwizzleVF>(color, temp1, src2, 0b00001001);
// - Swizzle src1 appropriately
env->emit_ir<IR_SwizzleVF>(color, temp2, src1, 0b00010010);
// - Multiply - Result in `temp1`
env->emit_ir<IR_VFMath3Asm>(color, temp1, temp1, temp2, IR_VFMath3Asm::Kind::MUL);
// Finalize
// - Subtract
env->emit_ir<IR_VFMath3Asm>(color, temp2, temp_dst, temp1, IR_VFMath3Asm::Kind::SUB);
// - Blend result, as to avoid not modifying dest's `w` component
env->emit_ir<IR_BlendVF>(color, dest, dest, temp2, 0b0111);
return get_none();
}
| 41.346988 | 100 | 0.625503 | [
"object",
"vector"
] |
a34a8fe112489536cb2146c7f0af7d8eac7da402 | 376 | cpp | C++ | examples/surfaces/surf/surf_3.cpp | lpea/matplotplusplus | 642f04b5bc2f7c7ec0f4b81c683bbd30bcbc4ed8 | [
"MIT"
] | 1 | 2022-03-22T11:09:19.000Z | 2022-03-22T11:09:19.000Z | examples/surfaces/surf/surf_3.cpp | lpea/matplotplusplus | 642f04b5bc2f7c7ec0f4b81c683bbd30bcbc4ed8 | [
"MIT"
] | null | null | null | examples/surfaces/surf/surf_3.cpp | lpea/matplotplusplus | 642f04b5bc2f7c7ec0f4b81c683bbd30bcbc4ed8 | [
"MIT"
] | 1 | 2022-03-22T11:46:39.000Z | 2022-03-22T11:46:39.000Z | #include <cmath>
#include <matplot/matplot.h>
int main() {
using namespace matplot;
auto [X, Y] = meshgrid(iota(1, 0.5, 10), iota(1, 20));
auto Z =
transform(X, Y, [](double x, double y) { return sin(x) + cos(y); });
auto C = transform(X, Y, [](double x, double y) { return x * y; });
surf(X, Y, Z, C);
colorbar();
wait();
return 0;
} | 25.066667 | 76 | 0.534574 | [
"transform"
] |
a3524475d29e24800cacf091bfe889519e91286c | 28,540 | cc | C++ | libcef/browser/extensions/extension_system.cc | VodBox/cef | c16d8fcbc7d5407fa4fb5f778b5c3c94ed54288f | [
"BSD-3-Clause"
] | 3 | 2021-12-24T16:51:23.000Z | 2022-03-28T21:16:45.000Z | libcef/browser/extensions/extension_system.cc | VodBox/cef | c16d8fcbc7d5407fa4fb5f778b5c3c94ed54288f | [
"BSD-3-Clause"
] | null | null | null | libcef/browser/extensions/extension_system.cc | VodBox/cef | c16d8fcbc7d5407fa4fb5f778b5c3c94ed54288f | [
"BSD-3-Clause"
] | 3 | 2021-11-11T14:11:35.000Z | 2022-03-28T07:00:47.000Z | // Copyright 2015 The Chromium Embedded Framework Authors.
// Portions 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.
#include "libcef/browser/extensions/extension_system.h"
#include <string>
#include "libcef/browser/extension_impl.h"
#include "libcef/browser/extensions/pdf_extension_util.h"
#include "libcef/browser/extensions/value_store/cef_value_store_factory.h"
#include "libcef/browser/thread_util.h"
#include "libcef/common/extensions/extensions_util.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/json/json_string_value_serializer.h"
#include "base/path_service.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "components/crx_file/id_util.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_details.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/render_process_host.h"
#include "extensions/browser/api/app_runtime/app_runtime_api.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/info_map.h"
#include "extensions/browser/notification_types.h"
#include "extensions/browser/null_app_sorting.h"
#include "extensions/browser/quota_service.h"
#include "extensions/browser/renderer_startup_helper.h"
#include "extensions/browser/runtime_data.h"
#include "extensions/browser/service_worker_manager.h"
#include "extensions/browser/state_store.h"
#include "extensions/browser/unloaded_extension_reason.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension_messages.h"
#include "extensions/common/file_util.h"
#include "extensions/common/manifest_constants.h"
#include "extensions/common/manifest_handlers/mime_types_handler.h"
#include "extensions/common/switches.h"
#include "net/base/mime_util.h"
using content::BrowserContext;
namespace extensions {
namespace {
// Implementation based on ComponentLoader::ParseManifest.
std::unique_ptr<base::DictionaryValue> ParseManifest(
const std::string& manifest_contents) {
JSONStringValueDeserializer deserializer(manifest_contents);
std::unique_ptr<base::Value> manifest(
deserializer.Deserialize(nullptr, nullptr));
if (!manifest.get() || !manifest->is_dict()) {
LOG(ERROR) << "Failed to parse extension manifest.";
return nullptr;
}
// Transfer ownership to the caller.
return base::WrapUnique(
static_cast<base::DictionaryValue*>(manifest.release()));
}
void ExecuteLoadFailure(CefRefPtr<CefExtensionHandler> handler,
cef_errorcode_t result) {
if (!handler)
return;
if (!CEF_CURRENTLY_ON_UIT()) {
CEF_POST_TASK(CEF_UIT, base::BindOnce(ExecuteLoadFailure, handler, result));
return;
}
handler->OnExtensionLoadFailed(result);
}
void LoadExtensionOnUIThread(base::WeakPtr<CefExtensionSystem> context,
std::unique_ptr<base::DictionaryValue> manifest,
const base::FilePath& root_directory,
bool internal,
CefRefPtr<CefRequestContext> loader_context,
CefRefPtr<CefExtensionHandler> handler) {
if (!CEF_CURRENTLY_ON_UIT()) {
CEF_POST_TASK(CEF_UIT, base::BindOnce(LoadExtensionOnUIThread, context,
std::move(manifest), root_directory,
internal, loader_context, handler));
return;
}
if (context) {
context->LoadExtension(std::move(manifest), root_directory, internal,
loader_context, handler);
}
}
void LoadExtensionWithManifest(base::WeakPtr<CefExtensionSystem> context,
const std::string& manifest_contents,
const base::FilePath& root_directory,
bool internal,
CefRefPtr<CefRequestContext> loader_context,
CefRefPtr<CefExtensionHandler> handler) {
CEF_REQUIRE_BLOCKING();
std::unique_ptr<base::DictionaryValue> manifest =
ParseManifest(manifest_contents);
if (!manifest) {
LOG(WARNING) << "Failed to parse extension manifest";
ExecuteLoadFailure(handler, ERR_INVALID_ARGUMENT);
return;
}
LoadExtensionOnUIThread(context, std::move(manifest), root_directory,
internal, loader_context, handler);
}
void LoadExtensionFromDisk(base::WeakPtr<CefExtensionSystem> context,
const base::FilePath& root_directory,
bool internal,
CefRefPtr<CefRequestContext> loader_context,
CefRefPtr<CefExtensionHandler> handler) {
CEF_REQUIRE_BLOCKING();
base::FilePath manifest_path = root_directory.AppendASCII("manifest.json");
std::string manifest_contents;
if (!base::ReadFileToString(manifest_path, &manifest_contents)) {
LOG(WARNING) << "Failed to read extension manifest from "
<< manifest_path.MaybeAsASCII();
ExecuteLoadFailure(handler, ERR_FILE_NOT_FOUND);
return;
}
LoadExtensionWithManifest(context, manifest_contents, root_directory,
internal, loader_context, handler);
}
} // namespace
CefExtensionSystem::CefExtensionSystem(BrowserContext* browser_context)
: browser_context_(browser_context),
initialized_(false),
registry_(ExtensionRegistry::Get(browser_context)),
renderer_helper_(
extensions::RendererStartupHelperFactory::GetForBrowserContext(
browser_context)),
weak_ptr_factory_(this) {
InitPrefs();
}
CefExtensionSystem::~CefExtensionSystem() {}
void CefExtensionSystem::Init() {
DCHECK(!initialized_);
// There's complexity here related to the ordering of message delivery. For
// an extension to load correctly both the ExtensionMsg_Loaded and
// ExtensionMsg_ActivateExtension messages must be sent. These messages are
// currently sent by RendererStartupHelper, ExtensionWebContentsObserver, and
// this class. ExtensionMsg_Loaded is handled by Dispatcher::OnLoaded and adds
// the extension to |extensions_|. ExtensionMsg_ActivateExtension is handled
// by Dispatcher::OnActivateExtension and adds the extension to
// |active_extension_ids_|. If these messages are not sent correctly then
// ScriptContextSet::Register called from Dispatcher::DidCreateScriptContext
// will classify the extension incorrectly and API bindings will not be added.
// Inform the rest of the extensions system to start.
ready_.Signal();
// Add the internal PDF extension. PDF loading works as follows:
// 1. The PDF PPAPI plugin is registered in libcef/common/content_client.cc
// ComputeBuiltInPlugins to handle the kPDFPluginOutOfProcessMimeType.
// 2. The PDF extension is registered by the below call to AddExtension and
// associated with the "application/pdf" mime type.
// 3. Web content running in the owner CefBrowser requests to load a PDF file
// resource with the "application/pdf" mime type. This can be via a frame
// (main frame/iframe) or object/embed tag.
// 4. PluginResponseInterceptorURLLoaderThrottle intercepts the PDF resource
// load in the browser process and registers the PDF resource as a stream
// via MimeHandlerStreamManager::AddStream.
// 5. PluginResponseInterceptorURLLoaderThrottle::WillProcessResponse triggers
// creation of a MimeHandlerViewEmbedder in the browser process via
// MimeHandlerViewAttachHelper::OverrideBodyForInterceptedResponse.
// 6. MimeHandlerViewEmbedder::ReadyToCommitNavigation is called and sends a
// Mojo message to MimeHandlerViewContainerManager::SetInternalId in the
// owner renderer process.
// 7. The MimeHandlerViewContainerManager is created in the owner renderer
// process via MimeHandlerViewContainerManager::BindReceiver and the
// SetInternalId call arrives.
// 8. HTMLPlugInElement::RequestObject is called in the owner renderer process
// to handle the PDF file frame/object/embed tag. This results in calls to
// ContentBrowserClient::GetPluginMimeTypesWithExternalHandlers (browser
// process) and ContentRendererClient::IsPluginHandledExternally (owner
// renderer process), and determines that the plugin should be handled
// externally (handled_externally=true).
// 9. MimeHandlerViewContainerManager::IsManagedByContainerManager sends a
// Mojo message to MimeHandlerViewEmbedder::ReadyToCreateMimeHandlerView
// in the browser process.
// 10.MimeHandlerViewEmbedder::RenderFrameCreated triggers creation of a
// MimeHandlerViewGuest and CefMimeHandlerViewGuestDelegate in the browser
// process.
// 11.MimeHandlerViewGuest::CreateWebContents creates a new guest WebContents
// (is_guest_view=true) to host the PDF extension and the PDF resource
// stream is retrieved via MimeHandlerStreamManager::ReleaseStream.
// 12.MimeHandlerViewGuest::DidAttachToEmbedder calls
// CefMimeHandlerViewGuestDelegate::OnGuestAttached to associate the guest
// WebContents routing IDs with the owner CefBrowser. MimeHandlerViewGuest
// then loads the extension URL (index.html) in the guest WebContents.
// 13.Creation of the RenderFrame in the guest renderer process triggers a
// sync IPC call from AlloyContentRendererClient::MaybeCreateBrowser to
// CefBrowserInfoManager::GetBrowserInfo in the browser process to retrieve
// the CefBrowser information, which will be immediately available due to
// step 12.
// 14.The PDF extension begins to load. Extension resource requests are
// handled via ExtensionURLLoaderFactory::CreateLoaderAndStart in the
// browser process. Access to PDF extension resources is checked by
// CefExtensionsBrowserClient::AllowCrossRendererResourceLoad and
// PDF extension resources are provided from bundle via
// CefExtensionsBrowserClient::LoadResourceFromResourceBundle
// and CefComponentExtensionResourceManager. Access to chrome://resources
// is granted via CefExtensionWebContentsObserver::RenderViewCreated.
// 15.The PDF extension calls chrome.mimeHandlerPrivate.getStreamInfo
// (chrome/browser/resources/pdf/browser_api.js) to retrieve the PDF
// resource stream. This API is implemented using Mojo as described in
// libcef/common/extensions/api/README.txt.
// 16.The PDF extension requests the PDF PPAPI plugin to handle
// kPDFPluginOutOfProcessMimeType. Approval arrives in the guest renderer
// process via ExtensionFrameHelper::OnExtensionResponse which calls
// NativeExtensionBindingsSystem::HandleResponse. This triggers creation of
// an HTMLPlugInElement via native V8 bindings to host the PDF plugin.
// 17.HTMLPlugInElement::RequestObject is called in the guest renderer process
// and determines that the PDF PPAPI plugin should be handled internally
// (handled_externally=false). A PluginDocument is created and
// AlloyContentRendererClient::OverrideCreatePlugin is called to create a
// WebPlugin.
// 18.The PDF extension and PDF plugin are now loaded. Print commands, if
// any, are handled in the guest renderer process by ChromePDFPrintClient
// and CefPrintRenderFrameHelperDelegate.
// 19.When navigating away from the PDF file or closing the owner CefBrowser
// the guest WebContents will be destroyed. This triggers a call to
// CefMimeHandlerViewGuestDelegate::OnGuestDetached which removes the
// routing ID association with the owner CefBrowser.
if (PdfExtensionEnabled()) {
LoadExtension(ParseManifest(pdf_extension_util::GetManifest()),
base::FilePath(FILE_PATH_LITERAL("pdf")), true /* internal */,
nullptr, nullptr);
}
initialized_ = true;
}
void CefExtensionSystem::LoadExtension(
const base::FilePath& root_directory,
bool internal,
CefRefPtr<CefRequestContext> loader_context,
CefRefPtr<CefExtensionHandler> handler) {
CEF_REQUIRE_UIT();
CEF_POST_USER_VISIBLE_TASK(
base::BindOnce(LoadExtensionFromDisk, weak_ptr_factory_.GetWeakPtr(),
root_directory, internal, loader_context, handler));
}
void CefExtensionSystem::LoadExtension(
const std::string& manifest_contents,
const base::FilePath& root_directory,
bool internal,
CefRefPtr<CefRequestContext> loader_context,
CefRefPtr<CefExtensionHandler> handler) {
CEF_REQUIRE_UIT();
CEF_POST_USER_VISIBLE_TASK(base::BindOnce(
LoadExtensionWithManifest, weak_ptr_factory_.GetWeakPtr(),
manifest_contents, root_directory, internal, loader_context, handler));
}
// Implementation based on ComponentLoader::Add.
void CefExtensionSystem::LoadExtension(
std::unique_ptr<base::DictionaryValue> manifest,
const base::FilePath& root_directory,
bool internal,
CefRefPtr<CefRequestContext> loader_context,
CefRefPtr<CefExtensionHandler> handler) {
CEF_REQUIRE_UIT();
// Internal extensions don't have a loader context. External extensions should.
#if DCHECK_IS_ON()
if (internal) {
DCHECK(!loader_context);
} else {
DCHECK(loader_context);
}
#endif
ComponentExtensionInfo info(manifest.get(), root_directory, internal);
const Extension* extension = LoadExtension(info, loader_context, handler);
if (!extension)
ExecuteLoadFailure(handler, ERR_FAILED);
}
// Implementation based on ExtensionService::RemoveComponentExtension.
bool CefExtensionSystem::UnloadExtension(const std::string& extension_id) {
CEF_REQUIRE_UIT();
ExtensionMap::iterator it = extension_map_.find(extension_id);
if (it == extension_map_.end()) {
// No CEF representation so we've already unloaded it.
return false;
}
CefRefPtr<CefExtensionImpl> cef_extension =
static_cast<CefExtensionImpl*>(it->second.get());
// Erase first so that callbacks can't retrieve the unloaded extension.
extension_map_.erase(it);
cef_extension->OnExtensionUnloaded();
scoped_refptr<const Extension> extension(
registry_->GetInstalledExtension(extension_id));
UnloadExtension(extension_id, UnloadedExtensionReason::UNINSTALL);
if (extension.get()) {
registry_->TriggerOnUninstalled(
extension.get(), extensions::UNINSTALL_REASON_COMPONENT_REMOVED);
}
return true;
}
bool CefExtensionSystem::HasExtension(const std::string& extension_id) const {
return !!GetExtension(extension_id);
}
CefRefPtr<CefExtension> CefExtensionSystem::GetExtension(
const std::string& extension_id) const {
CEF_REQUIRE_UIT();
ExtensionMap::const_iterator it = extension_map_.find(extension_id);
if (it != extension_map_.end())
return it->second;
return nullptr;
}
CefExtensionSystem::ExtensionMap CefExtensionSystem::GetExtensions() const {
CEF_REQUIRE_UIT();
return extension_map_;
}
void CefExtensionSystem::OnRequestContextDeleted(CefRequestContext* context) {
CEF_REQUIRE_UIT();
DCHECK(context);
// Make a copy of the map because UnloadExtension will modify it.
// Don't add any references to |context|.
ExtensionMap map = extension_map_;
ExtensionMap::const_iterator it = map.begin();
for (; it != map.end(); ++it) {
CefRefPtr<CefExtensionImpl> cef_extension =
static_cast<CefExtensionImpl*>(it->second.get());
if (cef_extension->loader_context() == context)
UnloadExtension(it->first);
}
}
void CefExtensionSystem::Shutdown() {
CEF_REQUIRE_UIT();
// Only internal extensions should exist at this point.
#if DCHECK_IS_ON()
ExtensionMap::iterator it = extension_map_.begin();
for (; it != extension_map_.end(); ++it) {
CefRefPtr<CefExtensionImpl> cef_extension =
static_cast<CefExtensionImpl*>(it->second.get());
DCHECK(!cef_extension->loader_context());
}
#endif
extension_map_.clear();
}
void CefExtensionSystem::InitForRegularProfile(bool extensions_enabled) {
DCHECK(!initialized_);
service_worker_manager_.reset(new ServiceWorkerManager(browser_context_));
runtime_data_.reset(new RuntimeData(registry_));
quota_service_.reset(new QuotaService);
app_sorting_.reset(new NullAppSorting);
}
ExtensionService* CefExtensionSystem::extension_service() {
return nullptr;
}
RuntimeData* CefExtensionSystem::runtime_data() {
return runtime_data_.get();
}
ManagementPolicy* CefExtensionSystem::management_policy() {
return nullptr;
}
ServiceWorkerManager* CefExtensionSystem::service_worker_manager() {
return service_worker_manager_.get();
}
UserScriptManager* CefExtensionSystem::user_script_manager() {
return nullptr;
}
StateStore* CefExtensionSystem::state_store() {
return state_store_.get();
}
StateStore* CefExtensionSystem::rules_store() {
return rules_store_.get();
}
scoped_refptr<value_store::ValueStoreFactory>
CefExtensionSystem::store_factory() {
return store_factory_;
}
InfoMap* CefExtensionSystem::info_map() {
if (!info_map_.get())
info_map_ = new InfoMap;
return info_map_.get();
}
QuotaService* CefExtensionSystem::quota_service() {
return quota_service_.get();
}
AppSorting* CefExtensionSystem::app_sorting() {
return app_sorting_.get();
}
// Implementation based on
// ExtensionSystemImpl::RegisterExtensionWithRequestContexts.
void CefExtensionSystem::RegisterExtensionWithRequestContexts(
const Extension* extension,
base::OnceClosure callback) {
// TODO(extensions): The |incognito_enabled| value should be set based on
// manifest settings.
content::GetIOThreadTaskRunner({})->PostTaskAndReply(
FROM_HERE,
base::BindOnce(&InfoMap::AddExtension, info_map(),
base::RetainedRef(extension), base::Time::Now(),
true, // incognito_enabled
false), // notifications_disabled
std::move(callback));
}
// Implementation based on
// ExtensionSystemImpl::UnregisterExtensionWithRequestContexts.
void CefExtensionSystem::UnregisterExtensionWithRequestContexts(
const std::string& extension_id,
const UnloadedExtensionReason reason) {
content::GetIOThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(&InfoMap::RemoveExtension, info_map(),
extension_id, reason));
}
const base::OneShotEvent& CefExtensionSystem::ready() const {
return ready_;
}
bool CefExtensionSystem::is_ready() const {
return ready_.is_signaled();
}
ContentVerifier* CefExtensionSystem::content_verifier() {
return nullptr;
}
std::unique_ptr<ExtensionSet> CefExtensionSystem::GetDependentExtensions(
const Extension* extension) {
return std::make_unique<ExtensionSet>();
}
void CefExtensionSystem::InstallUpdate(
const std::string& extension_id,
const std::string& public_key,
const base::FilePath& temp_dir,
bool install_immediately,
InstallUpdateCallback install_update_callback) {
NOTREACHED();
base::DeletePathRecursively(temp_dir);
}
void CefExtensionSystem::PerformActionBasedOnOmahaAttributes(
const std::string& extension_id,
const base::Value& attributes) {
NOTREACHED();
}
bool CefExtensionSystem::FinishDelayedInstallationIfReady(
const std::string& extension_id,
bool install_immediately) {
NOTREACHED();
return false;
}
CefExtensionSystem::ComponentExtensionInfo::ComponentExtensionInfo(
const base::DictionaryValue* manifest,
const base::FilePath& directory,
bool internal)
: manifest(manifest), root_directory(directory), internal(internal) {
if (!root_directory.IsAbsolute()) {
// This path structure is required by
// url_request_util::MaybeCreateURLRequestResourceBundleJob.
CHECK(base::PathService::Get(chrome::DIR_RESOURCES, &root_directory));
root_directory = root_directory.Append(directory);
}
}
void CefExtensionSystem::InitPrefs() {
store_factory_ =
new value_store::CefValueStoreFactory(browser_context_->GetPath());
Profile* profile = Profile::FromBrowserContext(browser_context_);
// Two state stores. The latter, which contains declarative rules, must be
// loaded immediately so that the rules are ready before we issue network
// requests.
state_store_ = std::make_unique<StateStore>(
profile, store_factory_, StateStore::BackendType::STATE, true);
rules_store_ = std::make_unique<StateStore>(
profile, store_factory_, StateStore::BackendType::RULES, false);
}
// Implementation based on ComponentLoader::CreateExtension.
scoped_refptr<const Extension> CefExtensionSystem::CreateExtension(
const ComponentExtensionInfo& info,
std::string* utf8_error) {
// TODO(abarth): We should REQUIRE_MODERN_MANIFEST_VERSION once we've updated
// our component extensions to the new manifest version.
int flags = 0;
if (info.internal) {
// Internal extensions must have kPublicKey in the manifest.
flags |= Extension::REQUIRE_KEY;
}
return Extension::Create(
info.root_directory,
// Tests should continue to use the Manifest::COMMAND_LINE value here
// Some Chrome APIs will cause undesired effects if this is incorrect
// e.g.: alarms API has 1 minute minimum applied to Packed Extensions
info.internal ? mojom::ManifestLocation::kComponent
: mojom::ManifestLocation::kCommandLine,
*info.manifest, flags, utf8_error);
}
// Implementation based on ComponentLoader::Load and
// ExtensionService::AddExtension.
const Extension* CefExtensionSystem::LoadExtension(
const ComponentExtensionInfo& info,
CefRefPtr<CefRequestContext> loader_context,
CefRefPtr<CefExtensionHandler> handler) {
std::string error;
scoped_refptr<const Extension> extension(CreateExtension(info, &error));
if (!extension.get()) {
LOG(ERROR) << error;
return nullptr;
}
if (registry_->GetInstalledExtension(extension->id())) {
LOG(ERROR) << "Extension with id " << extension->id()
<< "is already installed";
return nullptr;
}
CefRefPtr<CefExtensionImpl> cef_extension =
new CefExtensionImpl(extension.get(), loader_context.get(), handler);
// Insert first so that callbacks can retrieve the loaded extension.
extension_map_.insert(std::make_pair(extension->id(), cef_extension));
// This may trigger additional callbacks.
registry_->AddEnabled(extension.get());
NotifyExtensionLoaded(extension.get());
cef_extension->OnExtensionLoaded();
return extension.get();
}
// Implementation based on ExtensionService::UnloadExtension.
void CefExtensionSystem::UnloadExtension(const std::string& extension_id,
UnloadedExtensionReason reason) {
// Make sure the extension gets deleted after we return from this function.
int include_mask =
ExtensionRegistry::EVERYTHING & ~ExtensionRegistry::TERMINATED;
scoped_refptr<const Extension> extension(
registry_->GetExtensionById(extension_id, include_mask));
// This method can be called via PostTask, so the extension may have been
// unloaded by the time this runs.
if (!extension.get()) {
// In case the extension may have crashed/uninstalled. Allow the profile to
// clean up its RequestContexts.
UnregisterExtensionWithRequestContexts(extension_id, reason);
return;
}
if (registry_->disabled_extensions().Contains(extension->id())) {
registry_->RemoveDisabled(extension->id());
// Make sure the profile cleans up its RequestContexts when an already
// disabled extension is unloaded (since they are also tracking the disabled
// extensions).
UnregisterExtensionWithRequestContexts(extension_id, reason);
// Don't send the unloaded notification. It was sent when the extension
// was disabled.
} else {
// Remove the extension from the enabled list.
registry_->RemoveEnabled(extension->id());
NotifyExtensionUnloaded(extension.get(), reason);
}
content::NotificationService::current()->Notify(
extensions::NOTIFICATION_EXTENSION_REMOVED,
content::Source<content::BrowserContext>(browser_context_),
content::Details<const Extension>(extension.get()));
}
// Implementation based on ExtensionService::NotifyExtensionLoaded.
void CefExtensionSystem::NotifyExtensionLoaded(const Extension* extension) {
// The URLRequestContexts need to be first to know that the extension
// was loaded, otherwise a race can arise where a renderer that is created
// for the extension may try to load an extension URL with an extension id
// that the request context doesn't yet know about. The profile is responsible
// for ensuring its URLRequestContexts appropriately discover the loaded
// extension.
RegisterExtensionWithRequestContexts(
extension,
base::BindOnce(
&CefExtensionSystem::OnExtensionRegisteredWithRequestContexts,
weak_ptr_factory_.GetWeakPtr(), base::WrapRefCounted(extension)));
// Tell renderers about the loaded extension.
renderer_helper_->OnExtensionLoaded(*extension);
// Tell subsystems that use the ExtensionRegistryObserver::OnExtensionLoaded
// about the new extension.
//
// NOTE: It is important that this happen after notifying the renderers about
// the new extensions so that if we navigate to an extension URL in
// ExtensionRegistryObserver::OnExtensionLoaded the renderer is guaranteed to
// know about it.
registry_->TriggerOnLoaded(extension);
// Register plugins included with the extension.
// Implementation based on PluginManager::OnExtensionLoaded.
const MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension);
if (handler && !handler->handler_url().empty()) {
content::WebPluginInfo info;
info.type = content::WebPluginInfo::PLUGIN_TYPE_BROWSER_PLUGIN;
info.name = base::UTF8ToUTF16(extension->name());
info.path = base::FilePath::FromUTF8Unsafe(extension->url().spec());
for (std::set<std::string>::const_iterator mime_type =
handler->mime_type_set().begin();
mime_type != handler->mime_type_set().end(); ++mime_type) {
content::WebPluginMimeType mime_type_info;
mime_type_info.mime_type = *mime_type;
base::FilePath::StringType file_extension;
if (net::GetPreferredExtensionForMimeType(*mime_type, &file_extension)) {
mime_type_info.file_extensions.push_back(
base::FilePath(file_extension).AsUTF8Unsafe());
}
info.mime_types.push_back(mime_type_info);
}
content::PluginService* plugin_service =
content::PluginService::GetInstance();
plugin_service->RefreshPlugins();
plugin_service->RegisterInternalPlugin(info, true);
}
}
void CefExtensionSystem::OnExtensionRegisteredWithRequestContexts(
scoped_refptr<const extensions::Extension> extension) {
registry_->AddReady(extension);
if (registry_->enabled_extensions().Contains(extension->id()))
registry_->TriggerOnReady(extension.get());
}
// Implementation based on ExtensionService::NotifyExtensionUnloaded.
void CefExtensionSystem::NotifyExtensionUnloaded(
const Extension* extension,
UnloadedExtensionReason reason) {
// Unregister plugins included with the extension.
// Implementation based on PluginManager::OnExtensionUnloaded.
const MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension);
if (handler && !handler->handler_url().empty()) {
base::FilePath path =
base::FilePath::FromUTF8Unsafe(extension->url().spec());
content::PluginService* plugin_service =
content::PluginService::GetInstance();
plugin_service->UnregisterInternalPlugin(path);
plugin_service->RefreshPlugins();
}
registry_->TriggerOnUnloaded(extension, reason);
// Tell renderers about the unloaded extension.
renderer_helper_->OnExtensionUnloaded(*extension);
UnregisterExtensionWithRequestContexts(extension->id(), reason);
}
} // namespace extensions
| 39.860335 | 80 | 0.739979 | [
"object"
] |
a352e88f6488b5d2b6ed3d140e821e362fb21ce5 | 426 | cc | C++ | leetcode/cpp/rotate_image.cc | haonancool/OnlineJudge | 43e9e7fb30ed1ed80c08ef54d32aaa6ae5652064 | [
"Apache-2.0"
] | null | null | null | leetcode/cpp/rotate_image.cc | haonancool/OnlineJudge | 43e9e7fb30ed1ed80c08ef54d32aaa6ae5652064 | [
"Apache-2.0"
] | null | null | null | leetcode/cpp/rotate_image.cc | haonancool/OnlineJudge | 43e9e7fb30ed1ed80c08ef54d32aaa6ae5652064 | [
"Apache-2.0"
] | null | null | null | class Solution {
public:
void rotate(vector<vector<int>> &matrix) {
int n = matrix.size();
if (n <= 1)
return;
for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int tmp = matrix[i][j];
matrix[i][j] = matrix[n - 1 - j][i];
matrix[n - 1 - j][i] = matrix[n - 1 - i][n - 1 - j];
matrix[n - 1 - i][n - 1 - j] = matrix[j][n - 1 - i];
matrix[j][n - 1 - i] = tmp;
}
}
}
};
| 23.666667 | 56 | 0.441315 | [
"vector"
] |
a353dcddd65f70e3eb9011fe09d830216487ebb1 | 3,773 | cpp | C++ | src/lib/impl_/find.cpp | jw3/omega-edit | d0d64088a028a9f0e938313d31e693c8a45f135c | [
"Apache-2.0"
] | null | null | null | src/lib/impl_/find.cpp | jw3/omega-edit | d0d64088a028a9f0e938313d31e693c8a45f135c | [
"Apache-2.0"
] | null | null | null | src/lib/impl_/find.cpp | jw3/omega-edit | d0d64088a028a9f0e938313d31e693c8a45f135c | [
"Apache-2.0"
] | null | null | null | /**********************************************************************************************************************
* Copyright (c) 2021-2022 Concurrent Technologies Corporation. *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance *
* with the License. You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software is 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 "find.h"
#include <cassert>
#include <climits>
#include <cstring>
#include <vector>
struct omega_find_skip_table_t : public std::vector<size_t> {
omega_find_skip_table_t(size_t vec_size, size_t fill) : std::vector<size_t>(vec_size, fill) {}
};
const omega_find_skip_table_t *omega_find_create_skip_table(const unsigned char *needle, size_t needle_length) {
assert(needle);
assert(needle_length > 0);
auto skip_table_ptr = new omega_find_skip_table_t(UCHAR_MAX + 1, needle_length);
assert(skip_table_ptr);
if (needle_length >= 1) {
const auto needle_length_minus_1 = needle_length - 1;
for (size_t i = 0; i < needle_length_minus_1; ++i) { (*skip_table_ptr)[needle[i]] = needle_length_minus_1 - i; }
}
return skip_table_ptr;
}
/*
* Boyer-Moore-Horspool with additional tuning (https://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.14.7176)
*/
const unsigned char *omega_find(const unsigned char *haystack, size_t haystack_length,
const omega_find_skip_table_t *skip_table_ptr, const unsigned char *needle,
size_t needle_length) {
assert(haystack);
assert(skip_table_ptr);
assert(needle);
assert(needle_length > 0);
if (needle_length > haystack_length) { return nullptr; }
if (needle_length == 1) {
auto *result = (const unsigned char *) std::memchr(haystack, *needle, haystack_length);
return (result) ? result : nullptr;
}
const auto needle_length_minus_1 = needle_length - 1;
const unsigned char last_needle_char = needle[needle_length_minus_1];
size_t haystack_position = 0;
while (haystack_position <= haystack_length - needle_length) {
const auto skip = haystack[haystack_position + needle_length_minus_1];
if (last_needle_char == skip && std::memcmp(needle, haystack + haystack_position, needle_length_minus_1) == 0) {
return haystack + haystack_position;
}
haystack_position += (*skip_table_ptr)[skip];
}
return nullptr;
}
void omega_find_destroy_skip_table(const omega_find_skip_table_t *skip_table_ptr) {
assert(skip_table_ptr);
delete skip_table_ptr;
}
| 54.681159 | 120 | 0.532468 | [
"vector"
] |
a35763bd48c1bd339cb03c9517e66fc4bf7aa79f | 845 | hpp | C++ | map/benchmark_tool/api.hpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | 4,879 | 2015-09-30T10:56:36.000Z | 2022-03-31T18:43:03.000Z | map/benchmark_tool/api.hpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | 7,549 | 2015-09-30T10:52:53.000Z | 2022-03-31T22:04:22.000Z | map/benchmark_tool/api.hpp | smartyw/organicmaps | 9b10eb9d3ed6833861cef294c2416cc98b15e10d | [
"Apache-2.0"
] | 1,493 | 2015-09-30T10:43:06.000Z | 2022-03-21T09:16:49.000Z | #pragma once
#include <string>
#include <utility>
#include <vector>
namespace bench
{
class Result
{
public:
void Add(double t)
{
m_time.push_back(t);
}
void Add(Result const & r)
{
m_time.insert(m_time.end(), r.m_time.begin(), r.m_time.end());
}
void PrintAllTimes();
void CalcMetrics();
double m_all = 0.0;
double m_max = 0.0;
double m_avg = 0.0;
double m_med = 0.0;
private:
std::vector<double> m_time;
};
class AllResult
{
public:
AllResult() = default;
void Add(double t) { m_all += t; }
void Print();
Result m_reading;
double m_all = 0.0;
};
/// @param[in] count number of times to run benchmark
void RunFeaturesLoadingBenchmark(std::string const & file, std::pair<int, int> scaleR, AllResult & res);
} // namespace bench
| 17.244898 | 106 | 0.604734 | [
"vector"
] |
a35a1df5ed62bc2adc5576401dad20eb3ce53e65 | 1,828 | cpp | C++ | src/Tools/Math/MatrixOperation.cpp | NaokiTakahashi12/OpenHumanoidController | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | 1 | 2019-09-23T06:21:47.000Z | 2019-09-23T06:21:47.000Z | src/Tools/Math/MatrixOperation.cpp | NaokiTakahashi12/hc-early | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | 12 | 2019-07-30T00:17:09.000Z | 2019-12-09T23:00:43.000Z | src/Tools/Math/MatrixOperation.cpp | NaokiTakahashi12/OpenHumanoidController | ce8da0cabc8bbeec86f16a36b9ba5e6a16c4a67d | [
"MIT"
] | null | null | null |
/**
*
* @file MatrixOperation.cpp
* @author Naoki Takahashi
*
**/
#include "MatrixOperation.hpp"
namespace Tools {
namespace Math {
template <>
int norm(const Eigen::MatrixXi &matrix) {
return matrix.lpNorm<Eigen::Infinity>();
}
template <>
float norm(const Eigen::MatrixXf &matrix) {
return matrix.lpNorm<Eigen::Infinity>();
}
template <>
double norm(const Eigen::MatrixXd &matrix) {
return matrix.lpNorm<Eigen::Infinity>();
}
template <>
Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic> diagonal(const Eigen::VectorXi &vector) {
return vector.asDiagonal();
}
template <>
Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic> diagonal(const Eigen::VectorXf &vector) {
return vector.asDiagonal();
}
template <>
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> diagonal(const Eigen::VectorXd &vector) {
return vector.asDiagonal();
}
template <>
int dot(const Eigen::VectorXi &vector1, const Eigen::VectorXi &vector2) {
return vector1.dot(vector2);
}
template <>
float dot(const Eigen::VectorXf &vector1, const Eigen::VectorXf &vector2) {
return vector1.dot(vector2);
}
template <>
double dot(const Eigen::VectorXd &vector1, const Eigen::VectorXd &vector2) {
return vector1.dot(vector2);
}
template <>
Eigen::Matrix<int, 3, 1> cross(const Eigen::Matrix<int, 3, 1> &vector1, const Eigen::Matrix<int, 3, 1> &vector2) {
return vector1.cross(vector2);
}
template <>
Eigen::Matrix<float, 3, 1> cross(const Eigen::Matrix<float, 3, 1> &vector1, const Eigen::Matrix<float, 3, 1> &vector2) {
return vector1.cross(vector2);
}
template <>
Eigen::Matrix<double, 3, 1> cross(const Eigen::Matrix<double, 3, 1> &vector1, const Eigen::Matrix<double, 3, 1> &vector2) {
return vector1.cross(vector2);
}
}
}
| 24.373333 | 125 | 0.670131 | [
"vector"
] |
a35c1720f7b9180af72eab67a0134deb06519e0e | 10,451 | hpp | C++ | sparta/sparta/memory/SimpleMemoryMapNode.hpp | bdutro-sv/map | 90812bf631915958c42a1ba8e1c606973b8e1030 | [
"MIT"
] | null | null | null | sparta/sparta/memory/SimpleMemoryMapNode.hpp | bdutro-sv/map | 90812bf631915958c42a1ba8e1c606973b8e1030 | [
"MIT"
] | null | null | null | sparta/sparta/memory/SimpleMemoryMapNode.hpp | bdutro-sv/map | 90812bf631915958c42a1ba8e1c606973b8e1030 | [
"MIT"
] | null | null | null |
/**
* \file SimpleMemoryMapNode.hpp
* \brief File that contains SimpleMemoryMapNode
*/
#ifndef __SIMPLE_MEMORY_MAP_NODE_H__
#define __SIMPLE_MEMORY_MAP_NODE_H__
#include "sparta/memory/BlockingMemoryIFNode.hpp"
#include "sparta/memory/SimpleMemoryMap.hpp"
namespace sparta
{
namespace memory
{
/*!
* \brief Memory mapping object which implements BlockingMemoryIFNode.
* Supports a simple mapping of incoming addresses to addresses within
* a set of destination BlockingMemoryIFs.
*
* Note that this map supports notifications and instrumentation on the
* Map itself as well as on the destination memory interfaces.
*
* Destinations must start and end on block boundaries and accesses
* cannot span destinations.
*
* \see BlockingMemoryIFNode
* \see SimpleMemoryMap
*/
class SimpleMemoryMapNode : public BlockingMemoryIFNode, public SimpleMemoryMap
{
public:
using BlockingMemoryIFNode::getBlockSize;
//! \name Construction
//! @{
////////////////////////////////////////////////////////////////////////
SimpleMemoryMapNode() = delete;
/*!
* \brief Construct a SimpleMemoryMap that is also a
* BlockingMemoryIFNode subclass
* \param parent Parent TreeNode. Must not be null
* \param group Group name. Must not be empty. See
* sparta::TreeNode for rules
* \param group_idx Group index. See sparta::TreeNode
* \param desc Description of this interface. Must not be empty. See
* sparta::TreeNode
* \param block_size Size for all blocks that are accessible through
* this interfaces
* \param total_size Total size of the mapping space. This does not
* need to be entirely packed with mappings. This is required for
* BlockingMemoryIF
* \param transif See BlockingMemoryIF::BlockingMemoryIF
*/
SimpleMemoryMapNode(sparta::TreeNode* parent,
const std::string& name,
const std::string& group,
group_idx_type group_idx,
const std::string& desc,
addr_t block_size,
addr_t total_size,
TranslationIF* transif=nullptr) :
BlockingMemoryIFNode(parent, name, group, group_idx, desc,
block_size,
DebugMemoryIF::AccessWindow(0, total_size),
transif),
SimpleMemoryMap(block_size)
{ }
/*!
* \brief Constructor for SimpleMemoryMapNode without TreeNode group
* information
*
* This is the simplest constructor available for this class
*/
SimpleMemoryMapNode(sparta::TreeNode* parent,
const std::string& name,
const std::string& desc,
addr_t block_size,
addr_t total_size,
TranslationIF* transif=nullptr) :
SimpleMemoryMapNode(parent,
name,
sparta::TreeNode::GROUP_NAME_NONE,
sparta::TreeNode::GROUP_IDX_NONE,
desc,
block_size,
total_size,
transif)
{ }
virtual ~SimpleMemoryMapNode() {}
////////////////////////////////////////////////////////////////////////
//! @}
//! \name Memory Access
//! @{
////////////////////////////////////////////////////////////////////////
void read(addr_t addr,
addr_t size,
uint8_t *buf,
const void *in_supplement=nullptr,
void *out_supplement=nullptr) {
if(!tryRead(addr, size, buf, in_supplement, out_supplement)){
verifyHasMapping(addr, size);
verifyNoBlockSpan(addr, size);
verifyInAccessWindows(addr, size);
throw MemoryReadError(addr, size, "Unknown reason");
}
}
void write(addr_t addr,
addr_t size,
const uint8_t *buf,
const void *in_supplement=nullptr,
void *out_supplement=nullptr) {
if(!tryWrite(addr, size, buf, in_supplement, out_supplement)){
verifyHasMapping(addr, size);
verifyNoBlockSpan(addr, size);
verifyInAccessWindows(addr, size);
throw MemoryReadError(addr, size, "Unkonwn reason");
}
}
/*!
* \brief implement getDMI by passing the call down to the underlaying
* appropriate mapped blocking memory if.
* \param addr the address for the dmi
* \param size the required size of the dmi in bytes.
* \param dmi reference to populate.
* \param supplement caller-defined object identifying this memory access
* for notifications & debug purposes. This pointer is passed to any
* subsequent memory interfaces. Can be any pointer, and nullptr
* indicates no info.
*/
virtual bool getDMI_DEPRECATED(const addr_t addr,
const addr_t size,
DMI_DEPRECATED &dmi,
const void *supplement = nullptr) override
{
const Mapping* mapping = findMapping(addr);
if(!mapping)
{
return false;
}
return mapping->memif->getDMI_DEPRECATED(
mapping->mapAddress(addr), size, dmi, supplement);
}
////////////////////////////////////////////////////////////////////////
//! @}
protected:
//! \name Access and Query Implementations
//! @{
////////////////////////////////////////////////////////////////////////
/*!
* \brief Implements tryRead_
* \param addr Address to read from where 0 is start of this memory
* object.
* \warning Does not immediately prohibit accesses spanning blocks or
* mappings. This is the responsibility of the caller
*/
virtual bool tryRead_(addr_t addr,
addr_t size,
uint8_t *buf,
const void *in_supplement=nullptr,
void *out_supplement=nullptr) override {
const Mapping* m = findMapping(addr);
if(!m){
return false;
//throw MemoryReadError(addr, size, "Could not find mapping at this address");
}
return m->memif->tryRead(m->mapAddress(addr), size, buf, in_supplement, out_supplement);
}
/*!
* \brief Implements tryWrite_
* \param addr Address to write to where 0 is start of this memory
* object.
* \warning Does not immediately prohibit accesses spanning blocks or
* mappings. This is the responsibility of the caller
*/
virtual bool tryWrite_(addr_t addr,
addr_t size,
const uint8_t *buf,
const void *in_supplement=nullptr,
void *out_supplement=nullptr) override {
Mapping* m = findMapping(addr);
if(!m){
return false;
//throw MemoryWriteError(addr, size, "Could not find mapping at this address");
}
return m->memif->tryWrite(m->mapAddress(addr), size, buf, in_supplement, out_supplement);
}
/*!
* \brief Implements tryPeek_
*
* These accesses can span mappings and are automatically split
*/
virtual bool tryPeek_(addr_t addr,
addr_t size,
uint8_t *buf) const override {
// Note that input peeks are already split into blocks, so each
// may be translated once. Easy. Recall that peek has no
// performance requirement either.
const Mapping* m = findMapping(addr);
if(!m){
return false;
}
return m->memif->tryPeek(m->mapAddress(addr), size, buf);
}
/*!
* \brief Implements tryPoke_
*
* These accesses can span mappings and are automatically split
*/
virtual bool tryPoke_(addr_t addr,
addr_t size,
const uint8_t *buf) override {
// Note that input peeks are already split into blocks, so each
// may be translated once. Easy. Recall that peek has no
// performance requirement either.
Mapping* m = findMapping(addr);
if(!m){
return false;
}
return m->memif->tryPoke(m->mapAddress(addr), size, buf);
}
////////////////////////////////////////////////////////////////////////
//! @}
}; // class SimpleMemoryMapNode
}; // namespace memory
}; // namespace sparta
#endif // __SIMPLE_MEMORY_MAP_NODE_H__
| 41.472222 | 105 | 0.463305 | [
"object"
] |
a35da7f3f621e6653e3eb451a46caf4d686b4826 | 252 | cpp | C++ | src/core/ReconstructionFilter.cpp | BlauHimmel/Hikari | 38746e5d03a8e106a346a6f792f3093034a576bb | [
"MIT"
] | 11 | 2018-11-22T03:07:10.000Z | 2022-03-31T15:51:29.000Z | src/core/ReconstructionFilter.cpp | BlauHimmel/Hikari | 38746e5d03a8e106a346a6f792f3093034a576bb | [
"MIT"
] | 2 | 2019-02-14T15:05:42.000Z | 2019-07-26T06:07:13.000Z | src/core/ReconstructionFilter.cpp | BlauHimmel/Hikari | 38746e5d03a8e106a346a6f792f3093034a576bb | [
"MIT"
] | 4 | 2018-12-18T12:40:07.000Z | 2022-03-31T15:51:31.000Z | #include <core\ReconstructionFilter.hpp>
NAMESPACE_BEGIN
float ReconstructionFilter::GetRadius() const
{
return m_Radius;
}
Object::EClassType ReconstructionFilter::GetClassType() const
{
return EClassType::EReconstructionFilter;
}
NAMESPACE_END
| 15.75 | 61 | 0.813492 | [
"object"
] |
a35dc50461cc963bab4902169aeab0fb27c57ef5 | 2,832 | cpp | C++ | examples/q13_timer/src/simple/timer.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | examples/q13_timer/src/simple/timer.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | examples/q13_timer/src/simple/timer.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | #include <fstream>
#include <vector>
#include <iostream>
#include <thread>
#include <string>
#include <cpen333/util.h>
#include <cpen333/thread/timer.h>
//
// Most operating systems have timers that you can leverage to perform certain tasks. These timers are generally
// limited to a single process. On Windows, you can use a timer to send a message to each thread's message queue.
// On POSIX, you can use timers to send signal events. In both cases, you can also specify a callback function
// to be called when the timer "ticks".
//
// For inter-process communication, you would have to configure the timer's callback to notify all processes of the
// event using either datapools or message queues. We can also use synchronization mechanisms to inform processes
// of a timer event (such as conditions/events)
//
// Here we simply demonstrate the use of a timer to ping a callback function at a regular interval. The timer
// definition is in
// cpen333/thread/timer.h
//
// will be used as a callback for our timer
class TimedPrinter {
public:
TimedPrinter(const std::vector<std::string>& lines) :
lidx_(0), lines_(lines) {}
// override () operator
void operator()() {
if (lidx_ < lines_.size()) {
std::cout << lines_[lidx_];
std::cout.flush();
++lidx_;
if (lidx_ == lines_.size()) {
lidx_ = 0;
}
}
}
private:
size_t lidx_; // line index
std::vector<std::string> lines_; // list of lines to sing
};
int main() {
std::vector<std::string> lines;
// load data from file
std::ifstream fin("./timer.dat");
if (!fin.is_open()) {
fin.open("../timer.dat"); // search up one directory with Visual Studio
}
while (fin.is_open() && !fin.eof()) {
std::string line;
std::getline(fin, line);
// substitute "\n" for end-of-line characters
// and strip away \r characters
std::string add;
size_t i;
for (i=0; i+1<line.size(); ++i) {
if (line[i]== '\\' && line[i+1] == 'n') {
add.push_back('\n');
++i; // advance another character
} else if (line[i] != '\r') {
add.push_back(line[i]);
}
}
if (i < line.size() && line[i] != '\r') {
add.push_back(line[i]);
}
lines.push_back(add);
}
fin.close(); // make sure to close file
// timer set for every half-second, call singer as a callback
TimedPrinter printer(lines);
cpen333::thread::timer<std::chrono::milliseconds> timer(std::chrono::milliseconds(500), printer);
// run for about half a minute, then stop
timer.start();
std::this_thread::sleep_for(std::chrono::seconds(34));
timer.stop();
std::cout << std::endl << "Done." << std::endl;
cpen333::pause();
return 0;
} | 29.5 | 117 | 0.613701 | [
"vector"
] |
a35e1822110b8874539578f079b5edd46414f13a | 38,527 | cc | C++ | native_client_sdk/src/libraries/nacl_io/kernel_proxy.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | native_client_sdk/src/libraries/nacl_io/kernel_proxy.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | native_client_sdk/src/libraries/nacl_io/kernel_proxy.cc | tmpsantos/chromium | 802d4aeeb33af25c01ee5994037bbf14086d4ac0 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 "nacl_io/kernel_proxy.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <poll.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <iterator>
#include <string>
#include "nacl_io/devfs/dev_fs.h"
#include "nacl_io/filesystem.h"
#include "nacl_io/fusefs/fuse_fs_factory.h"
#include "nacl_io/host_resolver.h"
#include "nacl_io/html5fs/html5_fs.h"
#include "nacl_io/httpfs/http_fs.h"
#include "nacl_io/kernel_handle.h"
#include "nacl_io/kernel_wrap_real.h"
#include "nacl_io/log.h"
#include "nacl_io/memfs/mem_fs.h"
#include "nacl_io/node.h"
#include "nacl_io/osmman.h"
#include "nacl_io/ossocket.h"
#include "nacl_io/osstat.h"
#include "nacl_io/passthroughfs/passthrough_fs.h"
#include "nacl_io/path.h"
#include "nacl_io/pepper_interface.h"
#include "nacl_io/pipe/pipe_node.h"
#include "nacl_io/socket/tcp_node.h"
#include "nacl_io/socket/udp_node.h"
#include "nacl_io/stream/stream_fs.h"
#include "nacl_io/typed_fs_factory.h"
#include "sdk_util/auto_lock.h"
#include "sdk_util/ref_object.h"
#include "sdk_util/string_util.h"
#ifndef MAXPATHLEN
#define MAXPATHLEN 256
#endif
namespace nacl_io {
KernelProxy::KernelProxy()
: dev_(0),
ppapi_(NULL),
exit_callback_(NULL),
exit_callback_user_data_(NULL),
mount_callback_(NULL),
mount_callback_user_data_(NULL),
signal_emitter_(new EventEmitter) {
memset(&sigwinch_handler_, 0, sizeof(sigwinch_handler_));
sigwinch_handler_.sa_handler = SIG_DFL;
}
KernelProxy::~KernelProxy() {
// Clean up the FsFactories.
for (FsFactoryMap_t::iterator i = factories_.begin(); i != factories_.end();
++i) {
delete i->second;
}
}
Error KernelProxy::Init(PepperInterface* ppapi) {
Error rtn = 0;
ppapi_ = ppapi;
dev_ = 1;
factories_["memfs"] = new TypedFsFactory<MemFs>;
factories_["dev"] = new TypedFsFactory<DevFs>;
factories_["html5fs"] = new TypedFsFactory<Html5Fs>;
factories_["httpfs"] = new TypedFsFactory<HttpFs>;
factories_["passthroughfs"] = new TypedFsFactory<PassthroughFs>;
ScopedFilesystem root_fs;
rtn = MountInternal("", "/", "passthroughfs", 0, NULL, false, &root_fs);
if (rtn != 0)
assert(false);
ScopedFilesystem fs;
rtn = MountInternal("", "/dev", "dev", 0, NULL, false, &fs);
if (rtn != 0)
assert(false);
dev_fs_ = sdk_util::static_scoped_ref_cast<DevFs>(fs);
// Create the filesystem nodes for / and /dev afterward. They can't be
// created the normal way because the dev filesystem didn't exist yet.
rtn = CreateFsNode(root_fs);
if (rtn != 0)
assert(false);
rtn = CreateFsNode(dev_fs_);
if (rtn != 0)
assert(false);
// Open the first three in order to get STDIN, STDOUT, STDERR
int fd;
fd = open("/dev/stdin", O_RDONLY);
assert(fd == 0);
if (fd < 0)
rtn = errno;
fd = open("/dev/stdout", O_WRONLY);
assert(fd == 1);
if (fd < 0)
rtn = errno;
fd = open("/dev/stderr", O_WRONLY);
assert(fd == 2);
if (fd < 0)
rtn = errno;
#ifdef PROVIDES_SOCKET_API
host_resolver_.Init(ppapi_);
#endif
FsInitArgs args;
args.dev = dev_++;
args.ppapi = ppapi_;
stream_fs_.reset(new StreamFs());
int result = stream_fs_->Init(args);
if (result != 0) {
assert(false);
rtn = result;
}
return rtn;
}
bool KernelProxy::RegisterFsType(const char* fs_type,
fuse_operations* fuse_ops) {
FsFactoryMap_t::iterator iter = factories_.find(fs_type);
if (iter != factories_.end())
return false;
factories_[fs_type] = new FuseFsFactory(fuse_ops);
return true;
}
bool KernelProxy::UnregisterFsType(const char* fs_type) {
FsFactoryMap_t::iterator iter = factories_.find(fs_type);
if (iter == factories_.end())
return false;
delete iter->second;
factories_.erase(iter);
return true;
}
void KernelProxy::SetExitCallback(nacl_io_exit_callback_t exit_callback,
void* user_data) {
exit_callback_ = exit_callback;
exit_callback_user_data_ = user_data;
}
void KernelProxy::SetMountCallback(nacl_io_mount_callback_t mount_callback,
void* user_data) {
mount_callback_ = mount_callback;
mount_callback_user_data_ = user_data;
}
int KernelProxy::open_resource(const char* path) {
ScopedFilesystem fs;
Path rel;
Error error = AcquireFsAndRelPath(path, &fs, &rel);
if (error) {
errno = error;
return -1;
}
ScopedNode node;
error = fs->OpenResource(rel, &node);
if (error) {
// OpenResource failed, try Open().
error = fs->Open(rel, O_RDONLY, &node);
if (error) {
errno = error;
return -1;
}
}
ScopedKernelHandle handle(new KernelHandle(fs, node));
error = handle->Init(O_RDONLY);
if (error) {
errno = error;
return -1;
}
return AllocateFD(handle, path);
}
int KernelProxy::open(const char* path, int open_flags) {
ScopedFilesystem fs;
ScopedNode node;
Error error = AcquireFsAndNode(path, open_flags, &fs, &node);
if (error) {
errno = error;
return -1;
}
ScopedKernelHandle handle(new KernelHandle(fs, node));
error = handle->Init(open_flags);
if (error) {
errno = error;
return -1;
}
return AllocateFD(handle, path);
}
int KernelProxy::pipe(int pipefds[2]) {
PipeNode* pipe = new PipeNode(stream_fs_.get());
ScopedNode node(pipe);
if (pipe->Init(O_RDWR) == 0) {
ScopedKernelHandle handle0(new KernelHandle(stream_fs_, node));
ScopedKernelHandle handle1(new KernelHandle(stream_fs_, node));
// Should never fail, but...
if (handle0->Init(O_RDONLY) || handle1->Init(O_WRONLY)) {
errno = EACCES;
return -1;
}
pipefds[0] = AllocateFD(handle0);
pipefds[1] = AllocateFD(handle1);
return 0;
}
errno = ENOSYS;
return -1;
}
int KernelProxy::close(int fd) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
// Remove the FD from the process open file descriptor map
FreeFD(fd);
return 0;
}
int KernelProxy::dup(int oldfd) {
ScopedKernelHandle handle;
std::string path;
Error error = AcquireHandleAndPath(oldfd, &handle, &path);
if (error) {
errno = error;
return -1;
}
return AllocateFD(handle, path);
}
int KernelProxy::dup2(int oldfd, int newfd) {
// If it's the same file handle, just return
if (oldfd == newfd)
return newfd;
ScopedKernelHandle old_handle;
std::string old_path;
Error error = AcquireHandleAndPath(oldfd, &old_handle, &old_path);
if (error) {
errno = error;
return -1;
}
FreeAndReassignFD(newfd, old_handle, old_path);
return newfd;
}
int KernelProxy::chdir(const char* path) {
Error error = SetCWD(path);
if (error) {
errno = error;
return -1;
}
return 0;
}
void KernelProxy::exit(int status) {
if (exit_callback_)
exit_callback_(status, exit_callback_user_data_);
}
char* KernelProxy::getcwd(char* buf, size_t size) {
if (NULL == buf) {
errno = EFAULT;
return NULL;
}
std::string cwd = GetCWD();
// Verify the buffer is large enough
if (size <= cwd.size()) {
errno = ERANGE;
return NULL;
}
strcpy(buf, cwd.c_str());
return buf;
}
char* KernelProxy::getwd(char* buf) {
if (NULL == buf) {
errno = EFAULT;
return NULL;
}
return getcwd(buf, MAXPATHLEN);
}
int KernelProxy::chmod(const char* path, mode_t mode) {
int fd = KernelProxy::open(path, O_RDONLY);
if (-1 == fd)
return -1;
int result = fchmod(fd, mode);
close(fd);
return result;
}
int KernelProxy::chown(const char* path, uid_t owner, gid_t group) {
return 0;
}
int KernelProxy::fchown(int fd, uid_t owner, gid_t group) {
return 0;
}
int KernelProxy::lchown(const char* path, uid_t owner, gid_t group) {
return 0;
}
int KernelProxy::utime(const char* filename, const struct utimbuf* times) {
return 0;
}
int KernelProxy::mkdir(const char* path, mode_t mode) {
ScopedFilesystem fs;
Path rel;
Error error = AcquireFsAndRelPath(path, &fs, &rel);
if (error) {
errno = error;
return -1;
}
error = fs->Mkdir(rel, mode);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::rmdir(const char* path) {
ScopedFilesystem fs;
Path rel;
Error error = AcquireFsAndRelPath(path, &fs, &rel);
if (error) {
errno = error;
return -1;
}
error = fs->Rmdir(rel);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::stat(const char* path, struct stat* buf) {
int fd = open(path, O_RDONLY);
if (-1 == fd)
return -1;
int result = fstat(fd, buf);
close(fd);
return result;
}
int KernelProxy::mount(const char* source,
const char* target,
const char* filesystemtype,
unsigned long mountflags,
const void* data) {
ScopedFilesystem fs;
Error error = MountInternal(
source, target, filesystemtype, mountflags, data, true, &fs);
if (error) {
errno = error;
return -1;
}
return 0;
}
Error KernelProxy::MountInternal(const char* source,
const char* target,
const char* filesystemtype,
unsigned long mountflags,
const void* data,
bool create_fs_node,
ScopedFilesystem* out_filesystem) {
std::string abs_path = GetAbsParts(target).Join();
// Find a factory of that type
FsFactoryMap_t::iterator factory = factories_.find(filesystemtype);
if (factory == factories_.end()) {
LOG_ERROR("Unknown filesystem type: %s", filesystemtype);
return ENODEV;
}
// Create a map of settings
StringMap_t smap;
smap["SOURCE"] = source;
if (data) {
std::vector<std::string> elements;
sdk_util::SplitString(static_cast<const char*>(data), ',', &elements);
for (std::vector<std::string>::const_iterator it = elements.begin();
it != elements.end();
++it) {
size_t location = it->find('=');
if (location != std::string::npos) {
std::string key = it->substr(0, location);
std::string val = it->substr(location + 1);
smap[key] = val;
} else {
smap[*it] = "TRUE";
}
}
}
FsInitArgs args;
args.dev = dev_++;
args.string_map = smap;
args.ppapi = ppapi_;
ScopedFilesystem fs;
Error error = factory->second->CreateFilesystem(args, &fs);
if (error)
return error;
error = AttachFsAtPath(fs, abs_path);
if (error)
return error;
if (create_fs_node) {
error = CreateFsNode(fs);
if (error) {
DetachFsAtPath(abs_path, &fs);
return error;
}
}
*out_filesystem = fs;
if (mount_callback_) {
mount_callback_(source,
target,
filesystemtype,
mountflags,
data,
fs->dev(),
mount_callback_user_data_);
}
return 0;
}
Error KernelProxy::CreateFsNode(const ScopedFilesystem& fs) {
assert(dev_fs_);
return dev_fs_->CreateFsNode(fs.get());
}
int KernelProxy::umount(const char* path) {
ScopedFilesystem fs;
Error error = DetachFsAtPath(path, &fs);
if (error) {
errno = error;
return -1;
}
error = dev_fs_->DestroyFsNode(fs.get());
if (error) {
// Ignore any errors here, just log.
LOG_ERROR("Unable to destroy FsNode: %s", strerror(error));
}
return 0;
}
ssize_t KernelProxy::read(int fd, void* buf, size_t nbytes) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
int cnt = 0;
error = handle->Read(buf, nbytes, &cnt);
if (error) {
errno = error;
return -1;
}
return cnt;
}
ssize_t KernelProxy::write(int fd, const void* buf, size_t nbytes) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
int cnt = 0;
error = handle->Write(buf, nbytes, &cnt);
if (error) {
errno = error;
return -1;
}
return cnt;
}
int KernelProxy::fstat(int fd, struct stat* buf) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
error = handle->node()->GetStat(buf);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::getdents(int fd, void* buf, unsigned int count) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
int cnt = 0;
error = handle->GetDents(static_cast<dirent*>(buf), count, &cnt);
if (error)
errno = error;
return cnt;
}
int KernelProxy::fchdir(int fd) {
ScopedKernelHandle handle;
std::string path;
Error error = AcquireHandleAndPath(fd, &handle, &path);
if (error) {
errno = error;
return -1;
}
if (!handle->node()->IsaDir()) {
errno = ENOTDIR;
return -1;
}
if (path.empty()) {
errno = EBADF;
return -1;
}
error = SetCWD(path);
if (error) {
// errno is return value from SetCWD
errno = error;
return -1;
}
return 0;
}
int KernelProxy::ftruncate(int fd, off_t length) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
error = handle->node()->FTruncate(length);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::fsync(int fd) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
error = handle->node()->FSync();
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::fdatasync(int fd) {
errno = ENOSYS;
return -1;
}
int KernelProxy::isatty(int fd) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return 0;
}
error = handle->node()->Isatty();
if (error) {
errno = error;
return 0;
}
return 1;
}
int KernelProxy::ioctl(int fd, int request, va_list args) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
error = handle->node()->VIoctl(request, args);
if (error) {
errno = error;
return -1;
}
return 0;
}
off_t KernelProxy::lseek(int fd, off_t offset, int whence) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
off_t new_offset;
error = handle->Seek(offset, whence, &new_offset);
if (error) {
errno = error;
return -1;
}
return new_offset;
}
int KernelProxy::unlink(const char* path) {
ScopedFilesystem fs;
Path rel;
Error error = AcquireFsAndRelPath(path, &fs, &rel);
if (error) {
errno = error;
return -1;
}
error = fs->Unlink(rel);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::truncate(const char* path, off_t len) {
int fd = KernelProxy::open(path, O_WRONLY);
if (-1 == fd)
return -1;
int result = ftruncate(fd, len);
close(fd);
return result;
}
int KernelProxy::lstat(const char* path, struct stat* buf) {
return stat(path, buf);
}
int KernelProxy::rename(const char* path, const char* newpath) {
ScopedFilesystem fs;
Path rel;
Error error = AcquireFsAndRelPath(path, &fs, &rel);
if (error) {
errno = error;
return -1;
}
ScopedFilesystem newfs;
Path newrel;
error = AcquireFsAndRelPath(newpath, &newfs, &newrel);
if (error) {
errno = error;
return -1;
}
if (newfs.get() != fs.get()) {
// Renaming accross mountpoints is not allowed
errno = EXDEV;
return -1;
}
// They already point to the same path
if (rel == newrel)
return 0;
error = fs->Rename(rel, newrel);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::remove(const char* path) {
ScopedFilesystem fs;
Path rel;
Error error = AcquireFsAndRelPath(path, &fs, &rel);
if (error) {
errno = error;
return -1;
}
error = fs->Remove(rel);
if (error) {
errno = error;
return -1;
}
return 0;
}
// TODO(noelallen): Needs implementation.
int KernelProxy::fchmod(int fd, int mode) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::fcntl(int fd, int request, va_list args) {
Error error = 0;
// F_GETFD and F_SETFD are descriptor specific flags that
// are stored in the KernelObject's decriptor map unlike
// F_GETFL and F_SETFL which are handle specific.
switch (request) {
case F_GETFD: {
int rtn = -1;
error = GetFDFlags(fd, &rtn);
if (error) {
errno = error;
return -1;
}
return rtn;
}
case F_SETFD: {
int flags = va_arg(args, int);
error = SetFDFlags(fd, flags);
if (error) {
errno = error;
return -1;
}
return 0;
}
}
ScopedKernelHandle handle;
error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
int rtn = 0;
error = handle->VFcntl(request, &rtn, args);
if (error) {
errno = error;
return -1;
}
return rtn;
}
int KernelProxy::access(const char* path, int amode) {
ScopedFilesystem fs;
Path rel;
Error error = AcquireFsAndRelPath(path, &fs, &rel);
if (error) {
errno = error;
return -1;
}
error = fs->Access(rel, amode);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::readlink(const char* path, char* buf, size_t count) {
LOG_TRACE("readlink is not implemented.");
errno = EINVAL;
return -1;
}
int KernelProxy::utimes(const char* filename, const struct timeval times[2]) {
LOG_TRACE("utimes is not implemented.");
errno = EINVAL;
return -1;
}
// TODO(noelallen): Needs implementation.
int KernelProxy::link(const char* oldpath, const char* newpath) {
LOG_TRACE("link is not implemented.");
errno = EINVAL;
return -1;
}
int KernelProxy::symlink(const char* oldpath, const char* newpath) {
LOG_TRACE("symlink is not implemented.");
errno = EINVAL;
return -1;
}
void* KernelProxy::mmap(void* addr,
size_t length,
int prot,
int flags,
int fd,
size_t offset) {
// We shouldn't be getting anonymous mmaps here.
assert((flags & MAP_ANONYMOUS) == 0);
assert(fd != -1);
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return MAP_FAILED;
}
void* new_addr;
error = handle->node()->MMap(addr, length, prot, flags, offset, &new_addr);
if (error) {
errno = error;
return MAP_FAILED;
}
return new_addr;
}
int KernelProxy::munmap(void* addr, size_t length) {
// NOTE: The comment below is from a previous discarded implementation that
// tracks mmap'd regions. For simplicity, we no longer do this; because we
// "snapshot" the contents of the file in mmap(), and don't support
// write-back or updating the mapped region when the file is written, holding
// on to the KernelHandle is pointless.
//
// If we ever do, these threading issues should be considered.
//
// WARNING: this function may be called by free().
//
// There is a potential deadlock scenario:
// Thread 1: open() -> takes lock1 -> free() -> takes lock2
// Thread 2: free() -> takes lock2 -> munmap() -> takes lock1
//
// Note that open() above could be any function that takes a lock that is
// shared with munmap (this includes munmap!)
//
// To prevent this, we avoid taking locks in munmap() that are used by other
// nacl_io functions that may call free. Specifically, we only take the
// mmap_lock, which is only shared with mmap() above. There is still a
// possibility of deadlock if mmap() or munmap() calls free(), so this is not
// allowed.
//
// Unfortunately, munmap still needs to acquire other locks; see the call to
// ReleaseHandle below which takes the process lock. This is safe as long as
// this is never executed from free() -- we can be reasonably sure this is
// true, because malloc only makes anonymous mmap() requests, and should only
// be munmapping those allocations. We never add to mmap_info_list_ for
// anonymous maps, so the unmap_list should always be empty when called from
// free().
return 0;
}
int KernelProxy::tcflush(int fd, int queue_selector) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
error = handle->node()->Tcflush(queue_selector);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::tcgetattr(int fd, struct termios* termios_p) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
error = handle->node()->Tcgetattr(termios_p);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::tcsetattr(int fd,
int optional_actions,
const struct termios* termios_p) {
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
error = handle->node()->Tcsetattr(optional_actions, termios_p);
if (error) {
errno = error;
return -1;
}
return 0;
}
int KernelProxy::kill(pid_t pid, int sig) {
// Currently we don't even pretend that other processes exist
// so we can only send a signal to outselves. For kill(2)
// pid 0 means the current process group and -1 means all the
// processes we have permission to send signals to.
if (pid != getpid() && pid != -1 && pid != 0) {
errno = ESRCH;
return -1;
}
// Raise an event so that select/poll get interrupted.
AUTO_LOCK(signal_emitter_->GetLock())
signal_emitter_->RaiseEvents_Locked(POLLERR);
switch (sig) {
case SIGWINCH:
if (sigwinch_handler_.sa_handler != SIG_IGN &&
sigwinch_handler_.sa_handler != SIG_DFL) {
sigwinch_handler_.sa_handler(SIGWINCH);
}
break;
case SIGUSR1:
case SIGUSR2:
break;
default:
LOG_TRACE("Unsupported signal: %d", sig);
errno = EINVAL;
return -1;
}
return 0;
}
int KernelProxy::sigaction(int signum,
const struct sigaction* action,
struct sigaction* oaction) {
if (action && action->sa_flags & SA_SIGINFO) {
// We don't support SA_SIGINFO (sa_sigaction field) yet
errno = EINVAL;
return -1;
}
switch (signum) {
// Handled signals.
case SIGWINCH: {
if (oaction)
*oaction = sigwinch_handler_;
if (action) {
sigwinch_handler_ = *action;
}
return 0;
}
// Known signals
case SIGHUP:
case SIGINT:
case SIGPIPE:
case SIGPOLL:
case SIGPROF:
case SIGTERM:
case SIGCHLD:
case SIGURG:
case SIGFPE:
case SIGILL:
case SIGQUIT:
case SIGSEGV:
case SIGTRAP:
if (action && action->sa_handler != SIG_DFL) {
// Trying to set this action to anything other than SIG_DFL
// is not yet supported.
LOG_TRACE("sigaction on signal %d != SIG_DFL not supported.", sig);
errno = EINVAL;
return -1;
}
if (oaction) {
memset(oaction, 0, sizeof(*oaction));
oaction->sa_handler = SIG_DFL;
}
return 0;
// KILL and STOP cannot be handled
case SIGKILL:
case SIGSTOP:
LOG_TRACE("sigaction on SIGKILL/SIGSTOP not supported.");
errno = EINVAL;
return -1;
}
// Unknown signum
errno = EINVAL;
return -1;
}
#ifdef PROVIDES_SOCKET_API
int KernelProxy::select(int nfds,
fd_set* readfds,
fd_set* writefds,
fd_set* exceptfds,
struct timeval* timeout) {
std::vector<pollfd> pollfds;
for (int fd = 0; fd < nfds; fd++) {
int events = 0;
if (readfds && FD_ISSET(fd, readfds)) {
events |= POLLIN;
FD_CLR(fd, readfds);
}
if (writefds && FD_ISSET(fd, writefds)) {
events |= POLLOUT;
FD_CLR(fd, writefds);
}
if (exceptfds && FD_ISSET(fd, exceptfds)) {
events |= POLLERR | POLLHUP;
FD_CLR(fd, exceptfds);
}
if (events) {
pollfd info;
info.fd = fd;
info.events = events;
pollfds.push_back(info);
}
}
// NULL timeout signals wait forever.
int ms_timeout = -1;
if (timeout != NULL) {
int64_t ms = timeout->tv_sec * 1000 + ((timeout->tv_usec + 500) / 1000);
// If the timeout is invalid or too long (larger than signed 32 bit).
if ((timeout->tv_sec < 0) || (timeout->tv_sec >= (INT_MAX / 1000)) ||
(timeout->tv_usec < 0) || (timeout->tv_usec >= 1000000) || (ms < 0) ||
(ms >= INT_MAX)) {
LOG_TRACE("Invalid timeout: tv_sec=%d tv_usec=%d.",
timeout->tv_sec,
timeout->tv_usec);
errno = EINVAL;
return -1;
}
ms_timeout = static_cast<int>(ms);
}
int result = poll(&pollfds[0], pollfds.size(), ms_timeout);
if (result == -1)
return -1;
int event_cnt = 0;
for (size_t index = 0; index < pollfds.size(); index++) {
pollfd* info = &pollfds[index];
if (info->revents & POLLIN) {
FD_SET(info->fd, readfds);
event_cnt++;
}
if (info->revents & POLLOUT) {
FD_SET(info->fd, writefds);
event_cnt++;
}
if (info->revents & (POLLHUP | POLLERR)) {
FD_SET(info->fd, exceptfds);
event_cnt++;
}
}
return event_cnt;
}
struct PollInfo {
PollInfo() : index(-1) {};
std::vector<struct pollfd*> fds;
int index;
};
typedef std::map<EventEmitter*, PollInfo> EventPollMap_t;
int KernelProxy::poll(struct pollfd* fds, nfds_t nfds, int timeout) {
EventPollMap_t event_map;
std::vector<EventRequest> requests;
size_t event_cnt = 0;
for (int index = 0; static_cast<nfds_t>(index) < nfds; index++) {
ScopedKernelHandle handle;
struct pollfd* fd_info = &fds[index];
Error err = AcquireHandle(fd_info->fd, &handle);
fd_info->revents = 0;
// If the node isn't open, or somehow invalid, mark it so.
if (err != 0) {
fd_info->revents = POLLNVAL;
event_cnt++;
continue;
}
// If it's already signaled, then just capture the event
ScopedEventEmitter emitter(handle->node()->GetEventEmitter());
int events = POLLIN | POLLOUT;
if (emitter)
events = emitter->GetEventStatus();
if (events & fd_info->events) {
fd_info->revents = events & fd_info->events;
event_cnt++;
continue;
}
if (NULL == emitter) {
fd_info->revents = POLLNVAL;
event_cnt++;
continue;
}
// Otherwise try to track it.
PollInfo* info = &event_map[emitter.get()];
if (info->index == -1) {
EventRequest request;
request.emitter = emitter;
request.filter = fd_info->events;
request.events = 0;
info->index = requests.size();
requests.push_back(request);
}
info->fds.push_back(fd_info);
requests[info->index].filter |= fd_info->events;
}
// If nothing is signaled, then we must wait on the event map
if (0 == event_cnt) {
EventListenerPoll wait;
Error err = wait.WaitOnAny(&requests[0], requests.size(), timeout);
if ((err != 0) && (err != ETIMEDOUT)) {
errno = err;
return -1;
}
for (size_t rindex = 0; rindex < requests.size(); rindex++) {
EventRequest* request = &requests[rindex];
if (request->events) {
PollInfo* poll_info = &event_map[request->emitter.get()];
for (size_t findex = 0; findex < poll_info->fds.size(); findex++) {
struct pollfd* fd_info = poll_info->fds[findex];
uint32_t events = fd_info->events & request->events;
if (events) {
fd_info->revents = events;
event_cnt++;
}
}
}
}
}
return event_cnt;
}
// Socket Functions
int KernelProxy::accept(int fd, struct sockaddr* addr, socklen_t* len) {
if (NULL == addr || NULL == len) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
PP_Resource new_sock = 0;
error = handle->Accept(&new_sock, addr, len);
if (error != 0) {
errno = error;
return -1;
}
SocketNode* sock = new TcpNode(stream_fs_.get(), new_sock);
// The SocketNode now holds a reference to the new socket
// so we release ours.
ppapi_->ReleaseResource(new_sock);
error = sock->Init(O_RDWR);
if (error != 0) {
errno = error;
return -1;
}
ScopedNode node(sock);
ScopedKernelHandle new_handle(new KernelHandle(stream_fs_, node));
error = new_handle->Init(O_RDWR);
if (error != 0) {
errno = error;
return -1;
}
return AllocateFD(new_handle);
}
int KernelProxy::bind(int fd, const struct sockaddr* addr, socklen_t len) {
if (NULL == addr) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
Error err = handle->socket_node()->Bind(addr, len);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
int KernelProxy::connect(int fd, const struct sockaddr* addr, socklen_t len) {
if (NULL == addr) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
error = handle->Connect(addr, len);
if (error != 0) {
errno = error;
return -1;
}
return 0;
}
void KernelProxy::freeaddrinfo(struct addrinfo* res) {
return host_resolver_.freeaddrinfo(res);
}
int KernelProxy::getaddrinfo(const char* node,
const char* service,
const struct addrinfo* hints,
struct addrinfo** res) {
return host_resolver_.getaddrinfo(node, service, hints, res);
}
int KernelProxy::getnameinfo(const struct sockaddr *sa,
socklen_t salen,
char *host,
size_t hostlen,
char *serv,
size_t servlen,
int flags) {
return host_resolver_.getnameinfo(sa, salen, host, hostlen, serv, servlen,
flags);
}
struct hostent* KernelProxy::gethostbyname(const char* name) {
return host_resolver_.gethostbyname(name);
}
int KernelProxy::getpeername(int fd, struct sockaddr* addr, socklen_t* len) {
if (NULL == addr || NULL == len) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
Error err = handle->socket_node()->GetPeerName(addr, len);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
int KernelProxy::getsockname(int fd, struct sockaddr* addr, socklen_t* len) {
if (NULL == addr || NULL == len) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
Error err = handle->socket_node()->GetSockName(addr, len);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
int KernelProxy::getsockopt(int fd,
int lvl,
int optname,
void* optval,
socklen_t* len) {
if (NULL == optval || NULL == len) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
Error err = handle->socket_node()->GetSockOpt(lvl, optname, optval, len);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
int KernelProxy::listen(int fd, int backlog) {
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
Error err = handle->socket_node()->Listen(backlog);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
ssize_t KernelProxy::recv(int fd, void* buf, size_t len, int flags) {
if (NULL == buf) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
int out_len = 0;
error = handle->Recv(buf, len, flags, &out_len);
if (error != 0) {
errno = error;
return -1;
}
return static_cast<ssize_t>(out_len);
}
ssize_t KernelProxy::recvfrom(int fd,
void* buf,
size_t len,
int flags,
struct sockaddr* addr,
socklen_t* addrlen) {
// According to the manpage, recvfrom with a null addr is identical to recv.
if (NULL == addr) {
return recv(fd, buf, len, flags);
}
if (NULL == buf || NULL == addrlen) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
int out_len = 0;
error = handle->RecvFrom(buf, len, flags, addr, addrlen, &out_len);
if (error != 0) {
errno = error;
return -1;
}
return static_cast<ssize_t>(out_len);
}
ssize_t KernelProxy::recvmsg(int fd, struct msghdr* msg, int flags) {
if (NULL == msg) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
errno = EOPNOTSUPP;
return -1;
}
ssize_t KernelProxy::send(int fd, const void* buf, size_t len, int flags) {
if (NULL == buf) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
int out_len = 0;
error = handle->Send(buf, len, flags, &out_len);
if (error != 0) {
errno = error;
return -1;
}
return static_cast<ssize_t>(out_len);
}
ssize_t KernelProxy::sendto(int fd,
const void* buf,
size_t len,
int flags,
const struct sockaddr* addr,
socklen_t addrlen) {
// According to the manpage, sendto with a null addr is identical to send.
if (NULL == addr) {
return send(fd, buf, len, flags);
}
if (NULL == buf) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
Error error = AcquireHandle(fd, &handle);
if (error) {
errno = error;
return -1;
}
int out_len = 0;
error = handle->SendTo(buf, len, flags, addr, addrlen, &out_len);
if (error != 0) {
errno = error;
return -1;
}
return static_cast<ssize_t>(out_len);
}
ssize_t KernelProxy::sendmsg(int fd, const struct msghdr* msg, int flags) {
if (NULL == msg) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
errno = EOPNOTSUPP;
return -1;
}
int KernelProxy::setsockopt(int fd,
int lvl,
int optname,
const void* optval,
socklen_t len) {
if (NULL == optval) {
errno = EFAULT;
return -1;
}
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
Error err = handle->socket_node()->SetSockOpt(lvl, optname, optval, len);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
int KernelProxy::shutdown(int fd, int how) {
ScopedKernelHandle handle;
if (AcquireSocketHandle(fd, &handle) == -1)
return -1;
Error err = handle->socket_node()->Shutdown(how);
if (err != 0) {
errno = err;
return -1;
}
return 0;
}
int KernelProxy::socket(int domain, int type, int protocol) {
if (AF_INET != domain && AF_INET6 != domain) {
errno = EAFNOSUPPORT;
return -1;
}
int open_flags = O_RDWR;
if (type & SOCK_CLOEXEC) {
#ifdef O_CLOEXEC
// The NaCl newlib version of fcntl.h doesn't currently define
// O_CLOEXEC.
// TODO(sbc): remove this guard once it gets added.
open_flags |= O_CLOEXEC;
#endif
type &= ~SOCK_CLOEXEC;
}
if (type & SOCK_NONBLOCK) {
open_flags |= O_NONBLOCK;
type &= ~SOCK_NONBLOCK;
}
SocketNode* sock = NULL;
switch (type) {
case SOCK_DGRAM:
sock = new UdpNode(stream_fs_.get());
break;
case SOCK_STREAM:
sock = new TcpNode(stream_fs_.get());
break;
case SOCK_SEQPACKET:
case SOCK_RDM:
case SOCK_RAW:
errno = EPROTONOSUPPORT;
return -1;
default:
errno = EINVAL;
return -1;
}
ScopedNode node(sock);
Error rtn = sock->Init(O_RDWR);
if (rtn != 0) {
errno = rtn;
return -1;
}
ScopedKernelHandle handle(new KernelHandle(stream_fs_, node));
rtn = handle->Init(open_flags);
if (rtn != 0) {
errno = rtn;
return -1;
}
return AllocateFD(handle);
}
int KernelProxy::socketpair(int domain, int type, int protocol, int* sv) {
if (NULL == sv) {
errno = EFAULT;
return -1;
}
// Catch-22: We don't support AF_UNIX, but any other AF doesn't support
// socket pairs. Thus, this function always fails.
if (AF_UNIX != domain) {
errno = EPROTONOSUPPORT;
return -1;
}
if (AF_INET != domain && AF_INET6 != domain) {
errno = EAFNOSUPPORT;
return -1;
}
// We cannot reach this point.
errno = ENOSYS;
return -1;
}
int KernelProxy::AcquireSocketHandle(int fd, ScopedKernelHandle* handle) {
Error error = AcquireHandle(fd, handle);
if (error) {
errno = error;
return -1;
}
if ((handle->get()->node_->GetType() & S_IFSOCK) == 0) {
errno = ENOTSOCK;
return -1;
}
return 0;
}
#endif // PROVIDES_SOCKET_API
} // namespace_nacl_io
| 22.282822 | 79 | 0.607392 | [
"vector"
] |
a35e8c6f21b420685057f0bc161a0a326d3eda85 | 443 | cpp | C++ | webassembly/day3/cpp/fibo.cpp | byteshiva/es6-tuts | d8e611669bae1eb2283438832d9c4ad27b1874b9 | [
"Apache-2.0"
] | 5 | 2019-04-16T07:28:02.000Z | 2022-02-17T18:15:13.000Z | webassembly/day3/cpp/fibo.cpp | byteshiva/es6-tuts | d8e611669bae1eb2283438832d9c4ad27b1874b9 | [
"Apache-2.0"
] | 10 | 2018-06-27T20:28:45.000Z | 2021-08-04T00:53:49.000Z | webassembly/day3/cpp/fibo.cpp | byteshiva/es6-tuts | d8e611669bae1eb2283438832d9c4ad27b1874b9 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include <math.h>
#include <vector>
using namespace std;
int fib(int n) {
static std::vector<int> table; // our cache
if (n <= 1) {
return n;
}
else if (n >= table.size()) {
table.resize(n+1);
}
if (table[n] == 0) {
// only recalc if we don't have a value
table[n] = fib(n-1) + fib(n-2);
}
return table[n];
}
int main(void) {
printf("%d \n",fib(450));
} | 18.458333 | 47 | 0.510158 | [
"vector"
] |
a361b1423b8efd230fee2407f5a1f70c9c0f83b5 | 10,865 | cpp | C++ | src/tests/tests.cpp | biogeochemistry/reaction_network | 7941b11e0bb228fa47107a9d48947b18ed5c75e6 | [
"MIT",
"Unlicense"
] | null | null | null | src/tests/tests.cpp | biogeochemistry/reaction_network | 7941b11e0bb228fa47107a9d48947b18ed5c75e6 | [
"MIT",
"Unlicense"
] | null | null | null | src/tests/tests.cpp | biogeochemistry/reaction_network | 7941b11e0bb228fa47107a9d48947b18ed5c75e6 | [
"MIT",
"Unlicense"
] | null | null | null | #include "gtest/gtest.h"
#include "BvpPde.hpp"
#include "iostream"
#include "gnuplot_i.hpp"
#include "math.h"
double model_prob_1_rhs(double x){return 1.0;}
double model_prob_2_rhs(double x){return 34.0*sin(x);}
double model_prob_1_solution(double x){return 0.5*x*(1-x);}
double model_prob_2_solution(double x){return (4*exp(x) + exp(-4*x) ) / (4*exp(M_PI)+exp(-4*M_PI))-5*sin(x)-3*cos(x);};
double bc_x0(double y){return -pow(y,2);}
double bc_xN(double y){return pow(y,2);}
double bc_y0(double x){return -pow(x,4);}
double bc_yN(double x){return pow(x,4);}
TEST(boundary_conditions, assigning_var){
BoundaryConditions bc_dir, bc_neu;
// Const
bc_dir.SetX0DirichletBc2D(bc_x0);
bc_dir.SetXNDirichletBc2D(bc_xN);
bc_dir.SetY0DirichletBc2D(bc_y0);
bc_dir.SetYNDirichletBc2D(bc_yN);
// Neumann
bc_neu.SetX0NeumannBc2D(bc_x0);
bc_neu.SetXNNeumannBc2D(bc_xN);
bc_neu.SetY0NeumannBc2D(bc_y0);
bc_neu.SetYNNeumannBc2D(bc_yN);
Vector3d bc_v(1,2,3);
for (int i = 0; i < bc_v.size(); ++i) {
/*
Testing of the assigning of the value of given function to the BC
*/
// Const
EXPECT_EQ( bc_dir.mpX0BcFunc2D(bc_v[i]), bc_x0(bc_v[i]) );
EXPECT_EQ( bc_dir.mpXNBcFunc2D(bc_v[i]), bc_xN(bc_v[i]) );
EXPECT_EQ( bc_dir.mpY0BcFunc2D(bc_v[i]), bc_y0(bc_v[i]) );
EXPECT_EQ( bc_dir.mpYNBcFunc2D(bc_v[i]), bc_yN(bc_v[i]) );
EXPECT_EQ( bc_dir.mX0BcisDirichlet, true);
EXPECT_EQ( bc_dir.mXNBcisDirichlet, true);
EXPECT_EQ( bc_dir.mYNBcisDirichlet, true);
EXPECT_EQ( bc_dir.mY0BcisDirichlet, true);
EXPECT_EQ( bc_dir.mX0BcIsNeumann, false);
EXPECT_EQ( bc_dir.mXNBcIsNeumann, false);
EXPECT_EQ( bc_dir.mYNBcIsNeumann, false);
EXPECT_EQ( bc_dir.mY0BcIsNeumann, false);
// Neumann
EXPECT_EQ( bc_neu.mpX0BcFunc2D(bc_v[i]), bc_x0(bc_v[i]) );
EXPECT_EQ( bc_neu.mpXNBcFunc2D(bc_v[i]), bc_xN(bc_v[i]) );
EXPECT_EQ( bc_neu.mpY0BcFunc2D(bc_v[i]), bc_y0(bc_v[i]) );
EXPECT_EQ( bc_neu.mpYNBcFunc2D(bc_v[i]), bc_yN(bc_v[i]) );
EXPECT_EQ( bc_neu.mX0BcisDirichlet, false);
EXPECT_EQ( bc_neu.mXNBcisDirichlet, false);
EXPECT_EQ( bc_neu.mYNBcisDirichlet, false);
EXPECT_EQ( bc_neu.mY0BcisDirichlet, false);
EXPECT_EQ( bc_neu.mX0BcIsNeumann, true);
EXPECT_EQ( bc_neu.mXNBcIsNeumann, true);
EXPECT_EQ( bc_neu.mYNBcIsNeumann, true);
EXPECT_EQ( bc_neu.mY0BcIsNeumann, true);
}
}
TEST(FiniteDifferenceGrid, mesh_formation) {
FiniteDifferenceGrid grid = FiniteDifferenceGrid(3,1,2);
Vector3d v(1,1.5,2);
for (int i = 0; i < v.size(); ++i) {
EXPECT_EQ(v[i], grid.mNodes[i].C.x) << "Vectors x and y differ at index ";
}
}
TEST(boundary_conditions, constructor) {
BoundaryConditions bc;
ASSERT_EQ(bc.mX0BcisDirichlet, false);
ASSERT_EQ(bc.mXNBcisDirichlet, false);
ASSERT_EQ(bc.mX0BcIsNeumann, false);
ASSERT_EQ(bc.mXNBcIsNeumann, false);
ASSERT_EQ(bc.mX0BcIsRobin, false);
ASSERT_EQ(bc.mXNBcIsRobin, false);
}
TEST(second_order_ode, assigning_var){
SecondOrderOde ode_mp1(-1.0, 0.0, 0.0, model_prob_1_rhs, 0.0, 1.0);
ASSERT_EQ(ode_mp1.mCoeffOfUxx, -1);
ASSERT_EQ(ode_mp1.mCoeffOfUx, 0);
ASSERT_EQ(ode_mp1.mCoeffOfU, 0);
ASSERT_EQ(ode_mp1.mXmin, 0);
ASSERT_EQ(ode_mp1.mXmax, 1);
}
TEST(bvpode, error_of_the_solution){
// Checking error of the solution with 2nd order error term
int n = 128;
SecondOrderOde ode_mp1(-1.0, 0.0, 0.0, model_prob_1_rhs, 0.0, 1);
BoundaryConditions bc_mp1;
bc_mp1.SetX0DirichletBc1D(0);
bc_mp1.SetXNDirichletBc1D(0);
BvpOde bvpode_mp1(&ode_mp1, &bc_mp1, n);
bvpode_mp1.SetFilename("model_problem_results1.dat");
bvpode_mp1.Solve();
double sum = 0;
for (int i = 0; i < bvpode_mp1.mpGrid->xGrid.size(); ++i) {
double x = bvpode_mp1.mpGrid->xGrid[i];
double Uexact = model_prob_1_solution(x);
sum += pow((bvpode_mp1.solution[i] - Uexact),2);
}
sum /=n-1;
cout << "Standard deviation: " << sqrt(sum) <<'\n';
ASSERT_EQ(sqrt(sum) < 1e-2, true);
SecondOrderOde ode_mp2(1.0, 3.0, -4.0, model_prob_2_rhs, 0.0, M_PI);
BoundaryConditions bc_mp2;
bc_mp2.SetX0NeumannBc1D(-5.0);
bc_mp2.SetXNDirichletBc1D(4.0);
BvpOde bvpode_mp2(&ode_mp2, &bc_mp2, n);
bvpode_mp2.SetFilename("model_problem_results2.dat");
bvpode_mp2.Solve();
sum = 0;
for (int i = 0; i < bvpode_mp2.mpGrid->xGrid.size(); ++i) {
double x = bvpode_mp2.mpGrid->xGrid[i];
double Uexact = model_prob_2_solution(x);
sum += pow((bvpode_mp2.solution[i] - Uexact),2);
}
sum /=n-1;
cout << "Standard deviation: " << sqrt(sum) <<'\n';
// ASSERT_EQ(sqrt(sum) < 1e-2, true);
// Gnuplot g1, g2;
// g1.set_style("points").plot_xy(bvpode_mp1.mpGrid->xGrid,bvpode_mp1.solution,"differentiation");
// g1.set_style("lines").plot_equation("0.5*x*(1-x)","exact solution");
// g2.set_style("points").plot_xy(bvpode_mp2.mpGrid->xGrid,bvpode_mp2.solution);
// g2.set_style("lines").plot_equation("(4*exp(x) + exp(-4*x) ) / (4*exp(pi)+exp(-4*pi))-5*sin(x)-3*cos(x)","exact solution");
}
TEST(FiniteDifferenceGrid2d, mesh_formation) {
FiniteDifferenceGrid grid = FiniteDifferenceGrid(3, 1, 2, 3, 1, 2);
Vector3d v(1,1.5,2);
for (int i = 0; i < v.size(); ++i) {
ASSERT_EQ(v[i], grid.xGrid[i]) << "xGrid formation";
ASSERT_EQ(v[i], grid.yGrid[i]) << "yGrid formation";
}
// testing mesh
// format: Node#[x,y]
//
// y^
// | 6[1,2]-----7[1.5,2]------8[2,2]
// | | | |
// | | | |
// | 3[1,1.5]--4[1.5,1.5]----5[2,1.5]
// | | | |
// | | | |
// | 0[1,1] ---1[1.5,1]------2[2,1]
// |
// 0----------------------------------->
// x
// Node # 0
ASSERT_EQ(grid.mNodes[0].num, 0);
ASSERT_EQ(grid.mNodes[0].C.x, 1.0);
ASSERT_EQ(grid.mNodes[0].C.y, 1.0);
ASSERT_EQ(grid.mNodes[0].N.x, 1.0);
ASSERT_EQ(grid.mNodes[0].N.y, 1.5);
ASSERT_EQ(grid.mNodes[0].E.x, 1.5);
ASSERT_EQ(grid.mNodes[0].E.y, 1);
ASSERT_EQ(grid.mNodes[0].S.x, NULL);
ASSERT_EQ(grid.mNodes[0].S.y, NULL);
ASSERT_EQ(grid.mNodes[0].W.x, NULL);
ASSERT_EQ(grid.mNodes[0].W.y, NULL);
// Node # 1
ASSERT_EQ(grid.mNodes[1].num, 1);
ASSERT_EQ(grid.mNodes[1].C.x, 1.5);
ASSERT_EQ(grid.mNodes[1].C.y, 1.0);
ASSERT_EQ(grid.mNodes[1].N.x, 1.5);
ASSERT_EQ(grid.mNodes[1].N.y, 1.5);
ASSERT_EQ(grid.mNodes[1].E.x, 2);
ASSERT_EQ(grid.mNodes[1].E.y, 1);
ASSERT_EQ(grid.mNodes[1].S.x, NULL);
ASSERT_EQ(grid.mNodes[1].S.y, NULL);
ASSERT_EQ(grid.mNodes[1].W.x, 1);
ASSERT_EQ(grid.mNodes[1].W.y, 1);
// Node # 2
ASSERT_EQ(grid.mNodes[2].num, 2);
ASSERT_EQ(grid.mNodes[2].C.x, 2);
ASSERT_EQ(grid.mNodes[2].C.y, 1);
ASSERT_EQ(grid.mNodes[2].N.x, 2);
ASSERT_EQ(grid.mNodes[2].N.y, 1.5);
ASSERT_EQ(grid.mNodes[2].E.x, NULL);
ASSERT_EQ(grid.mNodes[2].E.y, NULL);
ASSERT_EQ(grid.mNodes[2].S.x, NULL);
ASSERT_EQ(grid.mNodes[2].S.y, NULL);
ASSERT_EQ(grid.mNodes[2].W.x, 1.5);
ASSERT_EQ(grid.mNodes[2].W.y, 1);
// Node # 3
ASSERT_EQ(grid.mNodes[3].num, 3);
ASSERT_EQ(grid.mNodes[3].C.x, 1);
ASSERT_EQ(grid.mNodes[3].C.y, 1.5);
ASSERT_EQ(grid.mNodes[3].N.x, 1);
ASSERT_EQ(grid.mNodes[3].N.y, 2);
ASSERT_EQ(grid.mNodes[3].E.x, 1.5);
ASSERT_EQ(grid.mNodes[3].E.y, 1.5);
ASSERT_EQ(grid.mNodes[3].S.x, 1);
ASSERT_EQ(grid.mNodes[3].S.y, 1);
ASSERT_EQ(grid.mNodes[3].W.x, NULL);
ASSERT_EQ(grid.mNodes[3].W.y, NULL);
// Node # 4
ASSERT_EQ(grid.mNodes[4].num, 4);
ASSERT_EQ(grid.mNodes[4].C.x, 1.5);
ASSERT_EQ(grid.mNodes[4].C.y, 1.5);
ASSERT_EQ(grid.mNodes[4].N.x, 1.5);
ASSERT_EQ(grid.mNodes[4].N.y, 2);
ASSERT_EQ(grid.mNodes[4].E.x, 2);
ASSERT_EQ(grid.mNodes[4].E.y, 1.5);
ASSERT_EQ(grid.mNodes[4].S.x, 1.5);
ASSERT_EQ(grid.mNodes[4].S.y, 1);
ASSERT_EQ(grid.mNodes[4].W.x, 1);
ASSERT_EQ(grid.mNodes[4].W.y, 1.5);
// Node # 5
ASSERT_EQ(grid.mNodes[5].num, 5);
ASSERT_EQ(grid.mNodes[5].C.x, 2);
ASSERT_EQ(grid.mNodes[5].C.y, 1.5);
ASSERT_EQ(grid.mNodes[5].N.x, 2);
ASSERT_EQ(grid.mNodes[5].N.y, 2);
ASSERT_EQ(grid.mNodes[5].E.x, NULL);
ASSERT_EQ(grid.mNodes[5].E.y, NULL);
ASSERT_EQ(grid.mNodes[5].S.x, 2);
ASSERT_EQ(grid.mNodes[5].S.y, 1);
ASSERT_EQ(grid.mNodes[5].W.x, 1.5);
ASSERT_EQ(grid.mNodes[5].W.y, 1.5);
// Node # 6
ASSERT_EQ(grid.mNodes[6].num, 6);
ASSERT_EQ(grid.mNodes[6].C.x, 1);
ASSERT_EQ(grid.mNodes[6].C.y, 2);
ASSERT_EQ(grid.mNodes[6].N.x, NULL);
ASSERT_EQ(grid.mNodes[6].N.y, NULL);
ASSERT_EQ(grid.mNodes[6].E.x, 1.5);
ASSERT_EQ(grid.mNodes[6].E.y, 2);
ASSERT_EQ(grid.mNodes[6].S.x, 1);
ASSERT_EQ(grid.mNodes[6].S.y, 1.5);
ASSERT_EQ(grid.mNodes[6].W.x, NULL);
ASSERT_EQ(grid.mNodes[6].W.y, NULL);
// Node # 7
ASSERT_EQ(grid.mNodes[7].num, 7);
ASSERT_EQ(grid.mNodes[7].C.x, 1.5);
ASSERT_EQ(grid.mNodes[7].C.y, 2);
ASSERT_EQ(grid.mNodes[7].N.x, NULL);
ASSERT_EQ(grid.mNodes[7].N.y, NULL);
ASSERT_EQ(grid.mNodes[7].E.x, 2);
ASSERT_EQ(grid.mNodes[7].E.y, 2);
ASSERT_EQ(grid.mNodes[7].S.x, 1.5);
ASSERT_EQ(grid.mNodes[7].S.y, 1.5);
ASSERT_EQ(grid.mNodes[7].W.x, 1);
ASSERT_EQ(grid.mNodes[7].W.y, 2);
// Node # 8
ASSERT_EQ(grid.mNodes[8].num, 8);
ASSERT_EQ(grid.mNodes[8].C.x, 2);
ASSERT_EQ(grid.mNodes[8].C.y, 2);
ASSERT_EQ(grid.mNodes[8].N.x, NULL);
ASSERT_EQ(grid.mNodes[8].N.y, NULL);
ASSERT_EQ(grid.mNodes[8].E.x, NULL);
ASSERT_EQ(grid.mNodes[8].E.y, NULL);
ASSERT_EQ(grid.mNodes[8].S.x, 2);
ASSERT_EQ(grid.mNodes[8].S.y, 1.5);
ASSERT_EQ(grid.mNodes[8].W.x, 1.5);
ASSERT_EQ(grid.mNodes[8].W.y, 2);
}
TEST(boundary_conditions2d, constructor) {
BoundaryConditions bc;
ASSERT_EQ(bc.mX0BcisDirichlet, false);
ASSERT_EQ(bc.mXNBcisDirichlet, false);
ASSERT_EQ(bc.mX0BcIsNeumann, false);
ASSERT_EQ(bc.mXNBcIsNeumann, false);
ASSERT_EQ(bc.mYNBcisDirichlet, false);
ASSERT_EQ(bc.mYNBcisDirichlet, false);
ASSERT_EQ(bc.mYNBcIsNeumann, false);
ASSERT_EQ(bc.mY0BcIsNeumann, false);
}
TEST(PDE_init, constractor) {
SecondOrderOde ode_mp2(1.0, 3.0, -4.0, model_prob_2_rhs, 0.0, M_PI);
BoundaryConditions bc_mp2;
bc_mp2.SetX0NeumannBc1D(-5.0);
bc_mp2.SetXNDirichletBc1D(4.0);
BvpPde bvppde_mp2(&ode_mp2, &bc_mp2,0.1, 1.0, 1, 128);
ASSERT_EQ(bvppde_mp2.mtau, 1.0);
ASSERT_EQ(bvppde_mp2.mdt, 0.1);
}
| 36.096346 | 130 | 0.614082 | [
"mesh"
] |
a361c6b1e6874b06e893372175fc1d72cf3b114b | 3,955 | cpp | C++ | bench/ClearBench.cpp | travisleithead/skia | 2092340a0edc25e9082ce9717643d12d901c3971 | [
"BSD-3-Clause"
] | 10 | 2017-12-04T10:41:55.000Z | 2021-12-03T07:36:59.000Z | bench/ClearBench.cpp | travisleithead/skia | 2092340a0edc25e9082ce9717643d12d901c3971 | [
"BSD-3-Clause"
] | 5 | 2022-01-03T13:41:38.000Z | 2022-03-02T13:01:38.000Z | bench/ClearBench.cpp | travisleithead/skia | 2092340a0edc25e9082ce9717643d12d901c3971 | [
"BSD-3-Clause"
] | 17 | 2017-11-05T21:36:53.000Z | 2021-05-22T20:33:51.000Z | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This benchmark attempts to measure the time to do a fullscreen clear, an axis-aligned partial
// clear, and a clear restricted to an axis-aligned rounded rect. The fullscreen and axis-aligned
// partial clears on the GPU should follow a fast path that maps to backend-specialized clear
// operations, whereas the rounded-rect clear cannot be.
#include "bench/Benchmark.h"
#include "include/core/SkCanvas.h"
#include "include/core/SkPaint.h"
#include "include/core/SkRRect.h"
#include "include/core/SkRect.h"
#include "include/effects/SkGradientShader.h"
#include "src/core/SkCanvasPriv.h"
#include "src/gpu/GrSurfaceDrawContext.h"
static sk_sp<SkShader> make_shader() {
static const SkPoint kPts[] = {{0, 0}, {10, 10}};
static const SkColor kColors[] = {SK_ColorBLUE, SK_ColorWHITE};
return SkGradientShader::MakeLinear(kPts, kColors, nullptr, 2, SkTileMode::kClamp);
}
class ClearBench : public Benchmark {
public:
enum ClearType {
kFull_ClearType,
kPartial_ClearType,
kComplex_ClearType
};
ClearBench(ClearType type) : fType(type) {}
protected:
const char* onGetName() override {
switch(fType) {
case kFull_ClearType:
return "Clear-Full";
case kPartial_ClearType:
return "Clear-Partial";
case kComplex_ClearType:
return "Clear-Complex";
}
SkASSERT(false);
return "Unreachable";
}
void onDraw(int loops, SkCanvas* canvas) override {
static const SkRect kPartialClip = SkRect::MakeLTRB(50, 50, 400, 400);
static const SkRRect kComplexClip = SkRRect::MakeRectXY(kPartialClip, 15, 15);
// Small to limit fill cost, but intersects the clips to confound batching
static const SkRect kInterruptRect = SkRect::MakeXYWH(200, 200, 3, 3);
// For the draw that sits between consecutive clears, use a shader that is simple but
// requires local coordinates so that Ganesh does not convert it into a solid color rect,
// which could then turn into a scissored-clear behind the scenes.
SkPaint interruptPaint;
interruptPaint.setShader(make_shader());
GrSurfaceDrawContext* sdc = SkCanvasPriv::TopDeviceSurfaceDrawContext(canvas);
if (sdc) {
// Tell the GrSurfaceDrawContext to not reset its draw op list on a fullscreen clear.
// If we don't do this, fullscreen clear ops would be created and constantly discard the
// previous iteration's op so execution would only invoke one actual clear on the GPU
// (not what we want to measure).
sdc->testingOnly_SetPreserveOpsOnFullClear();
}
for (int i = 0; i < loops; i++) {
canvas->save();
switch(fType) {
case kPartial_ClearType:
canvas->clipRect(kPartialClip);
break;
case kComplex_ClearType:
canvas->clipRRect(kComplexClip);
break;
case kFull_ClearType:
// Don't add any extra clipping, since it defaults to the entire "device"
break;
}
// The clear we care about measuring
canvas->clear(SK_ColorBLUE);
canvas->restore();
// Perform as minimal a draw as possible that intersects with the clear region in
// order to prevent the clear ops from being batched together.
canvas->drawRect(kInterruptRect, interruptPaint);
}
}
private:
ClearType fType;
};
DEF_BENCH( return new ClearBench(ClearBench::kFull_ClearType); )
DEF_BENCH( return new ClearBench(ClearBench::kPartial_ClearType); )
DEF_BENCH( return new ClearBench(ClearBench::kComplex_ClearType); )
| 37.666667 | 100 | 0.651075 | [
"solid"
] |
a362142cc47350284b8729aea0a2aeb8b2ff6815 | 15,377 | cc | C++ | chromium/chrome/browser/media/webrtc_rtp_dump_writer.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/media/webrtc_rtp_dump_writer.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | chromium/chrome/browser/media/webrtc_rtp_dump_writer.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | null | null | null | // 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.
#include "chrome/browser/media/webrtc_rtp_dump_writer.h"
#include <string.h>
#include "base/big_endian.h"
#include "base/files/file_util.h"
#include "base/logging.h"
#include "base/macros.h"
#include "content/public/browser/browser_thread.h"
#include "third_party/zlib/zlib.h"
using content::BrowserThread;
namespace {
static const size_t kMinimumGzipOutputBufferSize = 256; // In bytes.
const unsigned char kRtpDumpFileHeaderFirstLine[] = "#!rtpplay1.0 0.0.0.0/0\n";
static const size_t kRtpDumpFileHeaderSize = 16; // In bytes.
// A helper for writing the header of the dump file.
void WriteRtpDumpFileHeaderBigEndian(base::TimeTicks start,
std::vector<uint8_t>* output) {
size_t buffer_start_pos = output->size();
output->resize(output->size() + kRtpDumpFileHeaderSize);
char* buffer = reinterpret_cast<char*>(&(*output)[buffer_start_pos]);
base::TimeDelta delta = start - base::TimeTicks();
uint32_t start_sec = delta.InSeconds();
base::WriteBigEndian(buffer, start_sec);
buffer += sizeof(start_sec);
uint32_t start_usec =
delta.InMilliseconds() * base::Time::kMicrosecondsPerMillisecond;
base::WriteBigEndian(buffer, start_usec);
buffer += sizeof(start_usec);
// Network source, always 0.
base::WriteBigEndian(buffer, uint32_t(0));
buffer += sizeof(uint32_t);
// UDP port, always 0.
base::WriteBigEndian(buffer, uint16_t(0));
buffer += sizeof(uint16_t);
// 2 bytes padding.
base::WriteBigEndian(buffer, uint16_t(0));
}
// The header size for each packet dump.
static const size_t kPacketDumpHeaderSize = 8; // In bytes.
// A helper for writing the header for each packet dump.
// |start| is the time when the recording is started.
// |dump_length| is the length of the packet dump including this header.
// |packet_length| is the length of the RTP packet header.
void WritePacketDumpHeaderBigEndian(const base::TimeTicks& start,
uint16_t dump_length,
uint16_t packet_length,
std::vector<uint8_t>* output) {
size_t buffer_start_pos = output->size();
output->resize(output->size() + kPacketDumpHeaderSize);
char* buffer = reinterpret_cast<char*>(&(*output)[buffer_start_pos]);
base::WriteBigEndian(buffer, dump_length);
buffer += sizeof(dump_length);
base::WriteBigEndian(buffer, packet_length);
buffer += sizeof(packet_length);
uint32_t elapsed =
static_cast<uint32_t>((base::TimeTicks::Now() - start).InMilliseconds());
base::WriteBigEndian(buffer, elapsed);
}
// Append |src_len| bytes from |src| to |dest|.
void AppendToBuffer(const uint8_t* src,
size_t src_len,
std::vector<uint8_t>* dest) {
size_t old_dest_size = dest->size();
dest->resize(old_dest_size + src_len);
memcpy(&(*dest)[old_dest_size], src, src_len);
}
} // namespace
// This class is running on the FILE thread for compressing and writing the
// dump buffer to disk.
class WebRtcRtpDumpWriter::FileThreadWorker {
public:
explicit FileThreadWorker(const base::FilePath& dump_path)
: dump_path_(dump_path) {
thread_checker_.DetachFromThread();
memset(&stream_, 0, sizeof(stream_));
int result = deflateInit2(&stream_,
Z_DEFAULT_COMPRESSION,
Z_DEFLATED,
// windowBits = 15 is default, 16 is added to
// produce a gzip header + trailer.
15 + 16,
8, // memLevel = 8 is default.
Z_DEFAULT_STRATEGY);
DCHECK_EQ(Z_OK, result);
}
~FileThreadWorker() {
DCHECK(thread_checker_.CalledOnValidThread());
// Makes sure all allocations are freed.
deflateEnd(&stream_);
}
// Compresses the data in |buffer| and write to the dump file. If |end_stream|
// is true, the compression stream will be ended and the dump file cannot be
// written to any more.
void CompressAndWriteToFileOnFileThread(
scoped_ptr<std::vector<uint8_t>> buffer,
bool end_stream,
FlushResult* result,
size_t* bytes_written) {
DCHECK(thread_checker_.CalledOnValidThread());
// This is called either when the in-memory buffer is full or the dump
// should be ended.
DCHECK(!buffer->empty() || end_stream);
*result = FLUSH_RESULT_SUCCESS;
*bytes_written = 0;
// There may be nothing to compress/write if there is no RTP packet since
// the last flush.
if (!buffer->empty()) {
*bytes_written = CompressAndWriteBufferToFile(buffer.get(), result);
} else if (!base::PathExists(dump_path_)) {
// If the dump does not exist, it means there is no RTP packet recorded.
// Return FLUSH_RESULT_NO_DATA to indicate no dump file created.
*result = FLUSH_RESULT_NO_DATA;
}
if (end_stream && !EndDumpFile())
*result = FLUSH_RESULT_FAILURE;
}
private:
// Helper for CompressAndWriteToFileOnFileThread to compress and write one
// dump.
size_t CompressAndWriteBufferToFile(std::vector<uint8_t>* buffer,
FlushResult* result) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(buffer->size());
*result = FLUSH_RESULT_SUCCESS;
std::vector<uint8_t> compressed_buffer;
if (!Compress(buffer, &compressed_buffer)) {
DVLOG(2) << "Compressing buffer failed.";
*result = FLUSH_RESULT_FAILURE;
return 0;
}
int bytes_written = -1;
if (base::PathExists(dump_path_)) {
bytes_written =
base::AppendToFile(dump_path_, reinterpret_cast<const char*>(
compressed_buffer.data()),
compressed_buffer.size())
? compressed_buffer.size()
: -1;
} else {
bytes_written = base::WriteFile(
dump_path_,
reinterpret_cast<const char*>(&compressed_buffer[0]),
compressed_buffer.size());
}
if (bytes_written == -1) {
DVLOG(2) << "Writing file failed: " << dump_path_.value();
*result = FLUSH_RESULT_FAILURE;
return 0;
}
DCHECK_EQ(static_cast<size_t>(bytes_written), compressed_buffer.size());
return bytes_written;
}
// Compresses |input| into |output|.
bool Compress(std::vector<uint8_t>* input, std::vector<uint8_t>* output) {
DCHECK(thread_checker_.CalledOnValidThread());
int result = Z_OK;
output->resize(std::max(kMinimumGzipOutputBufferSize, input->size()));
stream_.next_in = &(*input)[0];
stream_.avail_in = input->size();
stream_.next_out = &(*output)[0];
stream_.avail_out = output->size();
result = deflate(&stream_, Z_SYNC_FLUSH);
DCHECK_EQ(Z_OK, result);
DCHECK_EQ(0U, stream_.avail_in);
output->resize(output->size() - stream_.avail_out);
stream_.next_in = NULL;
stream_.next_out = NULL;
stream_.avail_out = 0;
return true;
}
// Ends the compression stream and completes the dump file.
bool EndDumpFile() {
DCHECK(thread_checker_.CalledOnValidThread());
std::vector<uint8_t> output_buffer;
output_buffer.resize(kMinimumGzipOutputBufferSize);
stream_.next_in = NULL;
stream_.avail_in = 0;
stream_.next_out = &output_buffer[0];
stream_.avail_out = output_buffer.size();
int result = deflate(&stream_, Z_FINISH);
DCHECK_EQ(Z_STREAM_END, result);
result = deflateEnd(&stream_);
DCHECK_EQ(Z_OK, result);
output_buffer.resize(output_buffer.size() - stream_.avail_out);
memset(&stream_, 0, sizeof(z_stream));
DCHECK(!output_buffer.empty());
return base::AppendToFile(
dump_path_, reinterpret_cast<const char*>(output_buffer.data()),
output_buffer.size());
}
const base::FilePath dump_path_;
z_stream stream_;
base::ThreadChecker thread_checker_;
DISALLOW_COPY_AND_ASSIGN(FileThreadWorker);
};
WebRtcRtpDumpWriter::WebRtcRtpDumpWriter(
const base::FilePath& incoming_dump_path,
const base::FilePath& outgoing_dump_path,
size_t max_dump_size,
const base::Closure& max_dump_size_reached_callback)
: max_dump_size_(max_dump_size),
max_dump_size_reached_callback_(max_dump_size_reached_callback),
total_dump_size_on_disk_(0),
incoming_file_thread_worker_(new FileThreadWorker(incoming_dump_path)),
outgoing_file_thread_worker_(new FileThreadWorker(outgoing_dump_path)),
weak_ptr_factory_(this) {
}
WebRtcRtpDumpWriter::~WebRtcRtpDumpWriter() {
DCHECK(thread_checker_.CalledOnValidThread());
bool success = BrowserThread::DeleteSoon(
BrowserThread::FILE, FROM_HERE, incoming_file_thread_worker_.release());
DCHECK(success);
success = BrowserThread::DeleteSoon(
BrowserThread::FILE, FROM_HERE, outgoing_file_thread_worker_.release());
DCHECK(success);
}
void WebRtcRtpDumpWriter::WriteRtpPacket(const uint8_t* packet_header,
size_t header_length,
size_t packet_length,
bool incoming) {
DCHECK(thread_checker_.CalledOnValidThread());
static const size_t kMaxInMemoryBufferSize = 65536;
std::vector<uint8_t>* dest_buffer =
incoming ? &incoming_buffer_ : &outgoing_buffer_;
// We use the capacity of the buffer to indicate if the buffer has been
// initialized and if the dump file header has been created.
if (!dest_buffer->capacity()) {
dest_buffer->reserve(std::min(kMaxInMemoryBufferSize, max_dump_size_));
start_time_ = base::TimeTicks::Now();
// Writes the dump file header.
AppendToBuffer(kRtpDumpFileHeaderFirstLine,
arraysize(kRtpDumpFileHeaderFirstLine) - 1,
dest_buffer);
WriteRtpDumpFileHeaderBigEndian(start_time_, dest_buffer);
}
size_t packet_dump_length = kPacketDumpHeaderSize + header_length;
// Flushes the buffer to disk if the buffer is full.
if (dest_buffer->size() + packet_dump_length > dest_buffer->capacity())
FlushBuffer(incoming, false, FlushDoneCallback());
WritePacketDumpHeaderBigEndian(
start_time_, packet_dump_length, packet_length, dest_buffer);
// Writes the actual RTP packet header.
AppendToBuffer(packet_header, header_length, dest_buffer);
}
void WebRtcRtpDumpWriter::EndDump(RtpDumpType type,
const EndDumpCallback& finished_callback) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(type == RTP_DUMP_OUTGOING || incoming_file_thread_worker_ != NULL);
DCHECK(type == RTP_DUMP_INCOMING || outgoing_file_thread_worker_ != NULL);
bool incoming = (type == RTP_DUMP_BOTH || type == RTP_DUMP_INCOMING);
EndDumpContext context(type, finished_callback);
// End the incoming dump first if required. OnDumpEnded will continue to end
// the outgoing dump if necessary.
FlushBuffer(incoming,
true,
base::Bind(&WebRtcRtpDumpWriter::OnDumpEnded,
weak_ptr_factory_.GetWeakPtr(),
context,
incoming));
}
size_t WebRtcRtpDumpWriter::max_dump_size() const {
DCHECK(thread_checker_.CalledOnValidThread());
return max_dump_size_;
}
WebRtcRtpDumpWriter::EndDumpContext::EndDumpContext(
RtpDumpType type,
const EndDumpCallback& callback)
: type(type),
incoming_succeeded(false),
outgoing_succeeded(false),
callback(callback) {
}
WebRtcRtpDumpWriter::EndDumpContext::~EndDumpContext() {
}
void WebRtcRtpDumpWriter::FlushBuffer(bool incoming,
bool end_stream,
const FlushDoneCallback& callback) {
DCHECK(thread_checker_.CalledOnValidThread());
scoped_ptr<std::vector<uint8_t>> new_buffer(new std::vector<uint8_t>());
if (incoming) {
new_buffer->reserve(incoming_buffer_.capacity());
new_buffer->swap(incoming_buffer_);
} else {
new_buffer->reserve(outgoing_buffer_.capacity());
new_buffer->swap(outgoing_buffer_);
}
scoped_ptr<FlushResult> result(new FlushResult(FLUSH_RESULT_FAILURE));
scoped_ptr<size_t> bytes_written(new size_t(0));
FileThreadWorker* worker = incoming ? incoming_file_thread_worker_.get()
: outgoing_file_thread_worker_.get();
// Using "Unretained(worker)" because |worker| is owner by this object and it
// guaranteed to be deleted on the FILE thread before this object goes away.
base::Closure task =
base::Bind(&FileThreadWorker::CompressAndWriteToFileOnFileThread,
base::Unretained(worker), base::Passed(&new_buffer),
end_stream, result.get(), bytes_written.get());
// OnFlushDone is necessary to avoid running the callback after this
// object is gone.
base::Closure reply = base::Bind(
&WebRtcRtpDumpWriter::OnFlushDone, weak_ptr_factory_.GetWeakPtr(),
callback, base::Passed(&result), base::Passed(&bytes_written));
// Define the task and reply outside the method call so that getting and
// passing the scoped_ptr does not depend on the argument evaluation order.
BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE, task, reply);
if (end_stream) {
bool success = BrowserThread::DeleteSoon(
BrowserThread::FILE,
FROM_HERE,
incoming ? incoming_file_thread_worker_.release()
: outgoing_file_thread_worker_.release());
DCHECK(success);
}
}
void WebRtcRtpDumpWriter::OnFlushDone(const FlushDoneCallback& callback,
const scoped_ptr<FlushResult>& result,
const scoped_ptr<size_t>& bytes_written) {
DCHECK(thread_checker_.CalledOnValidThread());
total_dump_size_on_disk_ += *bytes_written;
if (total_dump_size_on_disk_ >= max_dump_size_ &&
!max_dump_size_reached_callback_.is_null()) {
max_dump_size_reached_callback_.Run();
}
// Returns success for FLUSH_RESULT_MAX_SIZE_REACHED since the dump is still
// valid.
if (!callback.is_null()) {
callback.Run(*result != FLUSH_RESULT_FAILURE &&
*result != FLUSH_RESULT_NO_DATA);
}
}
void WebRtcRtpDumpWriter::OnDumpEnded(EndDumpContext context,
bool incoming,
bool success) {
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(2) << "Dump ended, incoming = " << incoming
<< ", succeeded = " << success;
if (incoming)
context.incoming_succeeded = success;
else
context.outgoing_succeeded = success;
// End the outgoing dump if needed.
if (incoming && context.type == RTP_DUMP_BOTH) {
FlushBuffer(false,
true,
base::Bind(&WebRtcRtpDumpWriter::OnDumpEnded,
weak_ptr_factory_.GetWeakPtr(),
context,
false));
return;
}
// This object might be deleted after running the callback.
context.callback.Run(context.incoming_succeeded, context.outgoing_succeeded);
}
| 34.171111 | 80 | 0.66749 | [
"object",
"vector"
] |
a3629fa4c689533092deb0732744bb7d398606d1 | 4,381 | cpp | C++ | examples/1d_stencil/1d_stencil_1.cpp | biddisco/pika | 6900b19b5bd0feea491c21f7557a863c0cf2b904 | [
"BSL-1.0"
] | null | null | null | examples/1d_stencil/1d_stencil_1.cpp | biddisco/pika | 6900b19b5bd0feea491c21f7557a863c0cf2b904 | [
"BSL-1.0"
] | null | null | null | examples/1d_stencil/1d_stencil_1.cpp | biddisco/pika | 6900b19b5bd0feea491c21f7557a863c0cf2b904 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2014 Hartmut Kaiser
// Copyright (c) 2014 Patricia Grubel
//
// SPDX-License-Identifier: BSL-1.0
// 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)
// This is the first in a series of examples demonstrating the development of a
// fully distributed solver for a simple 1D heat distribution problem.
//
// This example provides a serial base line implementation. No parallelization
// is performed.
#include <pika/chrono.hpp>
#include <pika/init.hpp>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <vector>
#include "print_time_results.hpp"
///////////////////////////////////////////////////////////////////////////////
// Command-line variables
bool header = true; // print csv heading
double k = 0.5; // heat transfer coefficient
double dt = 1.; // time step
double dx = 1.; // grid spacing
///////////////////////////////////////////////////////////////////////////////
//[stepper_1
struct stepper
{
// Our partition type
typedef double partition;
// Our data for one time step
typedef std::vector<partition> space;
// Our operator
static double heat(double left, double middle, double right)
{
return middle + (k * dt / (dx * dx)) * (left - 2 * middle + right);
}
// do all the work on 'nx' data points for 'nt' time steps
space do_work(std::size_t nx, std::size_t nt)
{
// U[t][i] is the state of position i at time t.
std::vector<space> U(2);
for (space& s : U)
s.resize(nx);
// Initial conditions: f(0, i) = i
for (std::size_t i = 0; i != nx; ++i)
U[0][i] = double(i);
// Actual time step loop
for (std::size_t t = 0; t != nt; ++t)
{
space const& current = U[t % 2];
space& next = U[(t + 1) % 2];
next[0] = heat(current[nx - 1], current[0], current[1]);
for (std::size_t i = 1; i != nx - 1; ++i)
next[i] = heat(current[i - 1], current[i], current[i + 1]);
next[nx - 1] = heat(current[nx - 2], current[nx - 1], current[0]);
}
// Return the solution at time-step 'nt'.
return U[nt % 2];
}
};
//]
///////////////////////////////////////////////////////////////////////////////
int pika_main(pika::program_options::variables_map& vm)
{
std::uint64_t nx =
vm["nx"].as<std::uint64_t>(); // Number of grid points.
std::uint64_t nt = vm["nt"].as<std::uint64_t>(); // Number of steps.
if (vm.count("no-header"))
header = false;
// Create the stepper object
stepper step;
// Measure execution time.
std::uint64_t t = pika::chrono::high_resolution_clock::now();
// Execute nt time steps on nx grid points.
stepper::space solution = step.do_work(nx, nt);
// Print the final solution
if (vm.count("results"))
{
for (std::size_t i = 0; i != nx; ++i)
std::cout << "U[" << i << "] = " << solution[i] << std::endl;
}
std::uint64_t elapsed = pika::chrono::high_resolution_clock::now() - t;
std::uint64_t const os_thread_count = pika::get_os_thread_count();
print_time_results(os_thread_count, elapsed, nx, nt, header);
return pika::finalize();
}
int main(int argc, char* argv[])
{
namespace po = pika::program_options;
// clang-format off
po::options_description desc_commandline;
desc_commandline.add_options()
("results", "print generated results (default: false)")
("nx", po::value<std::uint64_t>()->default_value(100),
"Local x dimension")
("nt", po::value<std::uint64_t>()->default_value(45),
"Number of time steps")
("k", po::value<double>(&k)->default_value(0.5),
"Heat transfer coefficient (default: 0.5)")
("dt", po::value<double>(&dt)->default_value(1.0),
"Timestep unit (default: 1.0[s])")
("dx", po::value<double>(&dx)->default_value(1.0),
"Local x dimension")
( "no-header", "do not print out the csv header row")
;
// clang-format on
// Initialize and run pika
pika::init_params init_args;
init_args.desc_cmdline = desc_commandline;
return pika::init(pika_main, argc, argv, init_args);
}
| 31.292857 | 80 | 0.561059 | [
"object",
"vector"
] |
a363f70f22cd84dafc66431ad492928f620dd3ad | 2,691 | cc | C++ | lubancloud/src/model/GetStylesResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | lubancloud/src/model/GetStylesResult.cc | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | lubancloud/src/model/GetStylesResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/lubancloud/model/GetStylesResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Lubancloud;
using namespace AlibabaCloud::Lubancloud::Model;
GetStylesResult::GetStylesResult() :
ServiceResult()
{}
GetStylesResult::GetStylesResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
GetStylesResult::~GetStylesResult()
{}
void GetStylesResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto allStylesNode = value["Styles"]["Style"];
for (auto valueStylesStyle : allStylesNode)
{
Style stylesObject;
if(!valueStylesStyle["Id"].isNull())
stylesObject.id = std::stol(valueStylesStyle["Id"].asString());
if(!valueStylesStyle["Name"].isNull())
stylesObject.name = valueStylesStyle["Name"].asString();
if(!valueStylesStyle["ParentId"].isNull())
stylesObject.parentId = std::stol(valueStylesStyle["ParentId"].asString());
if(!valueStylesStyle["PreviewUrl"].isNull())
stylesObject.previewUrl = valueStylesStyle["PreviewUrl"].asString();
auto allSubStylesNode = allStylesNode["SubStyles"]["SubStyle"];
for (auto allStylesNodeSubStylesSubStyle : allSubStylesNode)
{
Style::SubStyle subStylesObject;
if(!allStylesNodeSubStylesSubStyle["Id"].isNull())
subStylesObject.id = std::stol(allStylesNodeSubStylesSubStyle["Id"].asString());
if(!allStylesNodeSubStylesSubStyle["Name"].isNull())
subStylesObject.name = allStylesNodeSubStylesSubStyle["Name"].asString();
if(!allStylesNodeSubStylesSubStyle["ParentId"].isNull())
subStylesObject.parentId = std::stol(allStylesNodeSubStylesSubStyle["ParentId"].asString());
if(!allStylesNodeSubStylesSubStyle["PreviewUrl"].isNull())
subStylesObject.previewUrl = allStylesNodeSubStylesSubStyle["PreviewUrl"].asString();
stylesObject.subStyles.push_back(subStylesObject);
}
styles_.push_back(stylesObject);
}
}
std::vector<GetStylesResult::Style> GetStylesResult::getStyles()const
{
return styles_;
}
| 34.5 | 96 | 0.751765 | [
"vector",
"model"
] |
a364d8d7ecbd4c563cbc097c4a61348263b14c39 | 3,198 | cc | C++ | CondFormats/CSCObjects/test/stubs/CSCReadDDUMapValuesAnalyzer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | CondFormats/CSCObjects/test/stubs/CSCReadDDUMapValuesAnalyzer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | CondFormats/CSCObjects/test/stubs/CSCReadDDUMapValuesAnalyzer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | /*----------------------------------------------------------------------
Toy EDProducers and EDProducts for testing purposes only.
----------------------------------------------------------------------*/
#include <stdexcept>
#include <string>
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include "FWCore/Framework/interface/EDAnalyzer.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "CondFormats/CSCObjects/interface/CSCDDUMap.h"
#include "CondFormats/DataRecord/interface/CSCDDUMapRcd.h"
#include "CondFormats/CSCObjects/interface/CSCMapItem.h"
using namespace std;
namespace edmtest
{
class CSCReadDDUMapValuesAnalyzer : public edm::EDAnalyzer
{
public:
explicit CSCReadDDUMapValuesAnalyzer(edm::ParameterSet const& p)
{ }
explicit CSCReadDDUMapValuesAnalyzer(int i)
{ }
virtual ~ CSCReadDDUMapValuesAnalyzer() { }
virtual void analyze(const edm::Event& e, const edm::EventSetup& c);
private:
};
void
CSCReadDDUMapValuesAnalyzer::analyze(const edm::Event& e, const edm::EventSetup& context)
{
using namespace edm::eventsetup;
// Context is not used.
std::cout <<" I AM IN RUN NUMBER "<<e.id().run() <<std::endl;
std::cout <<" ---EVENT NUMBER "<<e.id().event() <<std::endl;
edm::ESHandle<CSCDDUMap> pDDUMap;
context.get<CSCDDUMapRcd>().get(pDDUMap);
const CSCDDUMap* myDDUMap=pDDUMap.product();
std::map<int,CSCMapItem::MapItem>::const_iterator it;
int count=0;
for( it=myDDUMap->ddu_map.begin();it!=myDDUMap->ddu_map.end(); ++it ){
count=count+1;
std::cout<<"Key: ddu_crate*10+ddu_input "<<it->first<<std::endl;
std::cout<<count<<") ";
std::cout<<it->second.chamberLabel<<" ";
std::cout<<it->second.chamberId<<" ";
std::cout<<it->second.endcap<<" ";
std::cout<<it->second.station<<" ";
std::cout<<it->second.ring<<" ";
std::cout<<it->second.chamber<<" ";
std::cout<<it->second.cscIndex<<" ";
std::cout<<it->second.layerIndex<<" ";
std::cout<<it->second.stripIndex<<" ";
std::cout<<it->second.anodeIndex<<" ";
std::cout<<it->second.strips<<" ";
std::cout<<it->second.anodes<<" ";
std::cout<<it->second.crateLabel<<" ";
std::cout<<it->second.crateid<<" ";
std::cout<<it->second.sector<<" ";
std::cout<<it->second.trig_sector<<" ";
std::cout<<it->second.dmb<<" ";
std::cout<<it->second.cscid<<" ";
std::cout<<it->second.ddu<<" ";
std::cout<<it->second.ddu_input<<" ";
std::cout<<it->second.slink<<" ";
std::cout<<it->second.fed_crate<<" "<<" ";
std::cout<<it->second.ddu_slot<<" "<<" ";
std::cout<<it->second.dcc_fifo<<" "<<" ";
std::cout<<it->second.fiber_crate<<" "<<" ";
std::cout<<it->second.fiber_pos<<" "<<" ";
std::cout<<it->second.fiber_socket<<" "<<std::endl;
}
}
DEFINE_FWK_MODULE(CSCReadDDUMapValuesAnalyzer);
}
| 34.387097 | 92 | 0.599437 | [
"vector"
] |
a3667c968d802029a50ae98641eadf452aac234b | 10,644 | hpp | C++ | test-suite/linearleastsquaresregression.hpp | markxio/Quantuccia | ebe71a1b9c2a9ee7fc4ea918a9602f100316869d | [
"BSD-3-Clause"
] | 29 | 2017-03-20T14:17:39.000Z | 2021-12-22T08:00:52.000Z | test-suite/linearleastsquaresregression.hpp | markxio/Quantuccia | ebe71a1b9c2a9ee7fc4ea918a9602f100316869d | [
"BSD-3-Clause"
] | 10 | 2017-04-02T14:34:07.000Z | 2021-01-13T05:31:12.000Z | test-suite/linearleastsquaresregression.hpp | markxio/Quantuccia | ebe71a1b9c2a9ee7fc4ea918a9602f100316869d | [
"BSD-3-Clause"
] | 22 | 2017-03-19T05:56:19.000Z | 2022-03-16T13:30:20.000Z | /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006 Klaus Spanderen
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#ifndef quantlib_test_linear_least_squares_regression_hpp
#define quantlib_test_linear_least_squares_regression_hpp
#include <boost/test/unit_test.hpp>
/* remember to document new and/or updated tests in the Doxygen
comment block of the corresponding class */
class LinearLeastSquaresRegressionTest {
public:
static void testRegression();
static void testMultiDimRegression();
static void test1dLinearRegression();
static boost::unit_test_framework::test_suite* suite();
};
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006 Klaus Spanderen
Copyright (C) 2010 Slava Mazur
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include "utilities.hpp"
#include <ql/math/functional.hpp>
#include <ql/math/randomnumbers/rngtraits.hpp>
#include <ql/math/linearleastsquaresregression.hpp>
#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-local-typedefs"
#endif
#include <boost/bind.hpp>
#include <boost/circular_buffer.hpp>
#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ > 4))
#pragma GCC diagnostic pop
#endif
using namespace QuantLib;
using namespace boost::unit_test_framework;
void LinearLeastSquaresRegressionTest::testRegression() {
BOOST_TEST_MESSAGE("Testing linear least-squares regression...");
SavedSettings backup;
const Real tolerance = 0.05;
const Size nr=100000;
PseudoRandom::rng_type rng(PseudoRandom::urng_type(1234u));
std::vector<boost::function1<Real, Real> > v;
v.push_back(constant<Real, Real>(1.0));
v.push_back(QuantLib::identity<Real>());
v.push_back(square<Real>());
v.push_back(std::ptr_fun<Real, Real>(std::sin));
std::vector<boost::function1<Real, Real> > w(v);
w.push_back(square<Real>());
for (Size k=0; k<3; ++k) {
Size i;
const Real a[] = {rng.next().value,
rng.next().value,
rng.next().value,
rng.next().value};
std::vector<Real> x(nr), y(nr);
for (i=0; i<nr; ++i) {
x[i] = rng.next().value;
// regression in y = a_1 + a_2*x + a_3*x^2 + a_4*sin(x) + eps
y[i] = a[0]*v[0](x[i]) + a[1]*v[1](x[i]) + a[2]*v[2](x[i])
+ a[3]*v[3](x[i]) + rng.next().value;
}
LinearRegression m(x, y, v);
for (i=0; i<v.size(); ++i) {
if (m.standardErrors()[i] > tolerance) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n error: " << m.standardErrors()[i]
<< "\n tolerance: " << tolerance);
}
if (std::fabs(m.coefficients()[i]-a[i]) > 3*m.standardErrors()[i]) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n calculated: " << m.coefficients()[i]
<< "\n error: " << m.standardErrors()[i]
<< "\n expected: " << a[i]);
}
}
m = LinearRegression(x, y, w);
const Real ma[] = {m.coefficients()[0], m.coefficients()[1],
m.coefficients()[2]+m.coefficients()[4],
m.coefficients()[3]};
const Real err[] = {m.standardErrors()[0], m.standardErrors()[1],
std::sqrt( m.standardErrors()[2]*m.standardErrors()[2]
+m.standardErrors()[4]*m.standardErrors()[4]),
m.standardErrors()[3]};
for (i=0; i<v.size(); ++i) {
if (std::fabs(ma[i] - a[i]) > 3*err[i]) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n calculated: " << ma[i]
<< "\n error: " << err[i]
<< "\n expected: " << a[i]);
}
}
}
}
namespace {
Real f(const Array& a, Size i) {
return a[i];
}
}
void LinearLeastSquaresRegressionTest::testMultiDimRegression() {
BOOST_TEST_MESSAGE(
"Testing multi-dimensional linear least-squares regression...");
SavedSettings backup;
const Size nr=100000;
const Size dims = 4;
const Real tolerance = 0.01;
PseudoRandom::rng_type rng(PseudoRandom::urng_type(1234u));
std::vector<boost::function1<Real, Array> > v;
v.push_back(constant<Array, Real>(1.0));
for (Size i=0; i < dims; ++i) {
v.push_back(boost::bind(f, _1, i));
}
Array coeff(v.size());
for (Size i=0; i < v.size(); ++i) {
coeff[i] = rng.next().value;
}
std::vector<Real> y(nr, 0.0);
std::vector<Array> x(nr, Array(dims));
for (Size i=0; i < nr; ++i) {
for (Size j=0; j < dims; ++j) {
x[i][j] = rng.next().value;
}
for (Size j=0; j < v.size(); ++j) {
y[i] += coeff[j]*v[j](x[i]);
}
y[i] += rng.next().value;
}
LinearRegression m(x, y, v);
for (Size i=0; i < v.size(); ++i) {
if (m.standardErrors()[i] > tolerance) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n error: " << m.standardErrors()[i]
<< "\n tolerance: " << tolerance);
}
if (std::fabs(m.coefficients()[i]-coeff[i]) > 3*tolerance) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n calculated: " << m.coefficients()[i]
<< "\n error: " << m.standardErrors()[i]
<< "\n expected: " << coeff[i]);
}
}
// much simpler
LinearRegression m1(x, y, Real(1.0));
for (Size i=0; i < m1.dim(); ++i) {
if (m1.standardErrors()[i] > tolerance) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n error: " << m1.standardErrors()[i]
<< "\n tolerance: " << tolerance);
}
if (std::fabs(m1.coefficients()[i]-coeff[i]) > 3*tolerance) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n calculated: " << m1.coefficients()[i]
<< "\n error: " << m1.standardErrors()[i]
<< "\n expected: " << coeff[i]);
}
}
}
void LinearLeastSquaresRegressionTest::test1dLinearRegression() {
BOOST_TEST_MESSAGE("Testing 1D simple linear least-squares regression...");
/* Example taken from the QuantLib-User list, see posting
* Multiple linear regression/weighted regression, Boris Skorodumov */
SavedSettings backup;
std::vector<Real> x(9),y(9);
x[0]=2.4; x[1]=1.8; x[2]=2.5; x[3]=3.0;
x[4]=2.1; x[5]=1.2; x[6]=2.0; x[7]=2.7; x[8]=3.6;
y[0]=7.8; y[1]=5.5; y[2]=8.0; y[3]=9.0;
y[4]=6.5; y[5]=4.0; y[6]=6.3; y[7]=8.4; y[8]=10.2;
std::vector<boost::function1<Real, Real> > v;
v.push_back(constant<Real, Real>(1.0));
v.push_back(QuantLib::identity<Real>());
LinearRegression m(x, y);
const Real tol = 0.0002;
const Real coeffExpected[] = { 0.9448, 2.6853 };
const Real errorsExpected[] = { 0.3654, 0.1487 };
for (Size i=0; i < 2; ++i) {
if (std::fabs(m.standardErrors()[i]-errorsExpected[i]) > tol) {
BOOST_ERROR("Failed to reproduce linear regression standard errors"
<< "\n calculated: " << m.standardErrors()[i]
<< "\n expected: " << errorsExpected[i]
<< "\n tolerance: " << tol);
}
if (std::fabs(m.coefficients()[i]-coeffExpected[i]) > tol) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n calculated: " << m.coefficients()[i]
<< "\n expected: " << coeffExpected[i]
<< "\n tolerance: " << tol);
}
}
// an alternative container type
boost::circular_buffer<Real> cx(x.begin(), x.end()), cy(y.begin(), y.end());
LinearRegression m1(cx, cy);
for (Size i=0; i < 2; ++i) {
if (std::fabs(m1.standardErrors()[i]-errorsExpected[i]) > tol) {
BOOST_ERROR("Failed to reproduce linear regression standard errors"
<< "\n calculated: " << m1.standardErrors()[i]
<< "\n expected: " << errorsExpected[i]
<< "\n tolerance: " << tol);
}
if (std::fabs(m1.coefficients()[i]-coeffExpected[i]) > tol) {
BOOST_ERROR("Failed to reproduce linear regression coef."
<< "\n calculated: " << m1.coefficients()[i]
<< "\n expected: " << coeffExpected[i]
<< "\n tolerance: " << tol);
}
}
}
test_suite* LinearLeastSquaresRegressionTest::suite() {
test_suite* suite =
BOOST_TEST_SUITE("linear least squares regression tests");
suite->add(QUANTLIB_TEST_CASE(
&LinearLeastSquaresRegressionTest::testRegression));
suite->add(QUANTLIB_TEST_CASE(
&LinearLeastSquaresRegressionTest::testMultiDimRegression));
suite->add(QUANTLIB_TEST_CASE(
&LinearLeastSquaresRegressionTest::test1dLinearRegression));
return suite;
}
#endif | 35.362126 | 98 | 0.575442 | [
"vector"
] |
a36a1433f123c7cfa31344814ff3c7d9b5c41e64 | 3,633 | hpp | C++ | tools/converter/source/optimizer/passes/Pass.hpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | 6,958 | 2019-05-06T02:38:02.000Z | 2022-03-31T18:08:48.000Z | tools/converter/source/optimizer/passes/Pass.hpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | 1,775 | 2019-05-06T04:40:19.000Z | 2022-03-30T15:39:24.000Z | tools/converter/source/optimizer/passes/Pass.hpp | foreverlms/MNN | 8f9d3e3331fb54382bb61ac3a2087637a161fec5 | [
"Apache-2.0"
] | 1,511 | 2019-05-06T02:38:05.000Z | 2022-03-31T16:59:39.000Z | //
// Pass.hpp
// MNNConverter
//
// Created by MNN on b'2020/12/07'.
// Copyright © 2018, Alibaba Group Holding Limited
//
#ifndef MNN_CONVERTER_PASSES_PASS_HPP_
#define MNN_CONVERTER_PASSES_PASS_HPP_
#include "MNN/expr/Expr.hpp"
#include "MNN_generated.h"
#include <string>
#include <vector>
#include <unordered_map>
#include <functional>
#include <memory>
namespace MNN {
namespace passes {
typedef struct PassContext {
bool is_training = false;
bool verbose = true;
NetSource source = NetSource_TENSORFLOW;
//
Express::EXPRP node;
} PassContext;
class Pass;
class NestedPass;
class PassManager;
// The abstract base pass class.
class MNN_PUBLIC Pass {
public:
Pass() = default;
Pass(const std::string& pass_name) : pass_name_(pass_name) {}
virtual ~Pass() = default;
const std::string& name() const { return pass_name_; }
enum class PassType : int {
kInvalid = 0,
kNested = 1,
kRewrite = 2,
};
virtual PassType type() const = 0;
virtual std::unique_ptr<Pass> Clone() const = 0;
virtual bool Run(PassContext *context) = 0;
private:
std::string pass_name_;
};
class MNN_PUBLIC PassManager {
public:
PassManager() = delete;
PassManager(PassContext *context) : context_(context) {}
PassManager(const PassManager& other);
virtual ~PassManager() = default;
void AddPass(std::unique_ptr<Pass>&& pass);
void AddPass(const std::string& pass_name);
void AddNestedPass(std::unique_ptr<Pass>&& pass);
void AddNestedPass(const std::string& pass_name);
PassManager& AddNest();
std::unique_ptr<NetT> Run(std::unique_ptr<NetT>& net);
private:
friend class NestedPass;
bool RunOnOperation(PassContext *context);
std::unique_ptr<NetT> RunAllPasses(
std::unique_ptr<MNN::NetT>& originNet, // NOLINT
const std::unordered_map<std::string, Express::VARP>& inputs);
PassContext *context_;
std::vector<std::unique_ptr<Pass>> passes_;
};
class MNN_PUBLIC NestedPass : public Pass {
public:
NestedPass() = default;
NestedPass(const std::string& pass_name, PassContext *context);
PassType type() const override { return PassType::kNested; }
PassManager& OwningPassManager() const;
std::unique_ptr<Pass> Clone() const override {
// TODO
return nullptr;
}
bool Run(PassContext *context) override;
private:
std::unique_ptr<PassManager> pass_manager_;
};
class MNN_PUBLIC RewritePass : public Pass {
public:
using FuncType = std::function<bool(PassContext* context)>;
RewritePass() = delete;
virtual ~RewritePass() = default;
RewritePass(const std::string& pass_name) : Pass(pass_name) {}
RewritePass(const std::string& pass_name, FuncType verify_fn,
FuncType rewrite_fn)
: Pass(pass_name), verify_fn_(verify_fn), rewrite_fn_(rewrite_fn) {}
void SetVerify(FuncType verify_fn) {
verify_fn_ = verify_fn;
}
void SetRewrite(FuncType rewrite_fn) {
rewrite_fn_ = rewrite_fn;
}
PassType type() const override { return PassType::kRewrite; }
std::unique_ptr<Pass> Clone() const override {
return std::unique_ptr<RewritePass>(
new RewritePass(this->name(), verify_fn_, rewrite_fn_));
}
bool Run(PassContext *context) override;
private:
bool VerifyAndRewrite(PassContext* context);
std::function<bool(PassContext* context)> verify_fn_;
std::function<bool(PassContext* context)> rewrite_fn_;
};
} // namespace passes
} // namespace MNN
#endif // MNN_CONVERTER_PASSES_PASS_HPP_
| 24.714286 | 76 | 0.678778 | [
"vector"
] |
a36b3c8ad223f29a47b4bfae77413d24ada884db | 13,971 | cpp | C++ | inference-engine/thirdparty/clDNN/tests/module_tests/test_module_fusing_reorder.cpp | rayonnant14/openvino | 00361b761750b96e0fd94abf65faaf083b621a5a | [
"Apache-2.0"
] | 1 | 2022-01-10T07:31:37.000Z | 2022-01-10T07:31:37.000Z | inference-engine/thirdparty/clDNN/tests/module_tests/test_module_fusing_reorder.cpp | rayonnant14/openvino | 00361b761750b96e0fd94abf65faaf083b621a5a | [
"Apache-2.0"
] | 1 | 2021-05-21T08:53:26.000Z | 2021-05-21T08:57:41.000Z | inference-engine/thirdparty/clDNN/tests/module_tests/test_module_fusing_reorder.cpp | rayonnant14/openvino | 00361b761750b96e0fd94abf65faaf083b621a5a | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
///////////////////////////////////////////////////////////////////////////////////////////////////
#include "test_utils.h"
#include "program_helpers.h"
#include "layout_optimizer.h"
#include <intel_gpu/primitives/input_layout.hpp>
#include <intel_gpu/primitives/reshape.hpp>
#include "intel_gpu/primitives/reorder.hpp"
#include <intel_gpu/primitives/data.hpp>
#include <cmath>
#include <limits>
using namespace cldnn;
using namespace ::tests;
using namespace testing;
static void setting_node(program::ptr prog, const primitive_id& id, layout new_layout) {
auto itr = prog->get_processing_order().begin();
while (itr != prog->get_processing_order().end()) {
auto node_ptr = *itr++;
if (node_ptr->id() == id)
node_ptr->set_output_layout(new_layout);
}
}
// To test removal of reorder for mixed precision of Onednn conv kernel (conv: u8->fp32)
TEST(test_can_fuse_reorder, reorder_for_mixed_type_convolution_fsv32_onednn)
{
build_options build_opt;
topology topology;
#ifdef ENABLE_ONEDNN_FOR_GPU
auto& engine = get_onednn_test_engine();
#else
auto& engine = get_test_engine();
#endif
layout reorder_layout(data_types::u8, format::b_fs_yx_fsv32, {1, 32, 2, 2}, padding({0, }, 0));
auto input = engine.allocate_memory({ data_types::u8, format::bfyx, {1, 3, 2, 2} });
auto weights = engine.allocate_memory({ data_types::u8, format::bfyx, {1, 3, 2, 2} });
auto bias = engine.allocate_memory({ data_types::u8, format::bfyx, {1, 3, 1, 1} });
topology.add(input_layout("input", input->get_layout()));
topology.add(data("weights", weights));
topology.add(data("bias", bias));
topology.add(reorder("reorder_input", "input", format::b_fs_yx_fsv32, data_types::u8));
topology.add(cldnn::convolution("conv", { "reorder_input" }, { "weights" }, { "bias"}, 1, tensor{1}, tensor{0}, tensor{1}, {1, 32, 2, 2}, data_types::f32, false));
topology.add(reorder("reorder_conv", "conv", reorder_layout));
program::ptr prog = program::build_program(engine, topology, build_opt, false, true);
layout_optimizer lo = layout_optimizer();
lo.set_optimization_attribute(layout_optimizer::optimization_attributes_type::use_onednn_impls, true);
auto itr = prog->get_processing_order().begin();
while (itr != prog->get_processing_order().end()) {
auto node_ptr = *itr++;
if (!node_ptr->is_type<reorder>() || node_ptr->id() != "reorder_input") // target reorder
continue;
auto& node = node_ptr->as<reorder>();
auto& input = node.input();
for (auto usr : node_ptr->get_users()) {
auto temp = usr->get_output_layout();
EXPECT_EQ(false, lo.can_fuse_reorder(input, *usr, node.input().get_output_layout().format, usr->get_output_layout().format));
}
}
}
// To test mixed precision of Cldnn conv kernel (conv: u8->fp32)
TEST(test_can_fuse_reorder, reorder_for_mixed_type_convolution_fsv32_cldnn)
{
build_options build_opt;
topology topology;
#ifdef ENABLE_ONEDNN_FOR_GPU
auto& engine = get_onednn_test_engine();
#else
auto& engine = get_test_engine();
#endif
layout reorder_layout(data_types::u8, format::b_fs_yx_fsv32, {1, 32, 2, 2}, padding({0, }, 0));
auto input = engine.allocate_memory({ data_types::u8, format::bfyx, {1, 3, 2, 2} });
auto weights = engine.allocate_memory({ data_types::u8, format::bfyx, {1, 3, 2, 2} });
auto bias = engine.allocate_memory({ data_types::u8, format::bfyx, {1, 3, 1, 1} });
topology.add(input_layout("input", input->get_layout()));
topology.add(data("weights", weights));
topology.add(data("bias", bias));
topology.add(reorder("reorder_input", "input", format::b_fs_yx_fsv32, data_types::u8));
topology.add(cldnn::convolution("conv", { "reorder_input" }, { "weights" }, { "bias"}, 1, tensor{1}, tensor{0}, tensor{1}, {1, 32, 2, 2}, data_types::f32, false));
topology.add(reorder("reorder_conv", "conv", reorder_layout));
program::ptr prog = program::build_program(engine, topology, build_opt, false, true);
layout_optimizer lo = layout_optimizer();
lo.set_optimization_attribute(layout_optimizer::optimization_attributes_type::use_onednn_impls, false);
auto itr = prog->get_processing_order().begin();
while (itr != prog->get_processing_order().end()) {
auto node_ptr = *itr++;
if (!node_ptr->is_type<reorder>() || node_ptr->id() != "reorder_input") // target reorder
continue;
auto& node = node_ptr->as<reorder>();
auto& input = node.input();
for (auto usr : node_ptr->get_users()) {
auto temp = usr->get_output_layout();
EXPECT_EQ(true, lo.can_fuse_reorder(input, *usr, node.input().get_output_layout().format, usr->get_output_layout().format));
}
}
}
struct reorder_test_param {
format input_format;
format output_format;
data_types input_data_type;
data_types output_data_type;
tensor in_shape;
tensor out_shape;
tensor weight_shape;
tensor stride;
tensor pad;
data_types weights_type;
format weights_format;
bool expected_result;
};
template<typename T>
class ReorderTest : public ::testing::TestWithParam<T> {
public:
#ifdef ENABLE_ONEDNN_FOR_GPU
cldnn::engine& engine = get_onednn_test_engine();
#else
cldnn::engine& engine = get_test_engine();
#endif
layout get_input_layout(T& p) {
auto pad = p.pad;
std::vector<int> pad_ = { 0, 0, pad.spatial[0], pad.spatial[1] };
return layout{ p.data_type, p.input_format, p.in_shape, padding{pad_} };
}
bool check_supports_immad() {
return this->engine.get_device_info().supports_immad;
}
};
// Not to fuse a reorder if the next conv has deep depth input
class test_fused_reorder_deep_depth : public ReorderTest<reorder_test_param> {};
TEST_P(test_fused_reorder_deep_depth, no_removal_for_deep_depth_conv)
{
build_options build_opt;
topology topology;
auto p = GetParam();
layout conv_layout(p.input_data_type, p.output_format, p.out_shape, padding({0, }, 0));
layout reorder_layout(p.output_data_type, p.output_format, p.out_shape, padding({0, }, 0));
auto input = engine.allocate_memory({ p.input_data_type, p.input_format, p.in_shape });
auto weights = engine.allocate_memory({ p.input_data_type, p.input_format, p.weight_shape });
auto bias = engine.allocate_memory({ p.input_data_type, p.input_format, p.weight_shape });
topology.add(input_layout("input", input->get_layout()));
topology.add(data("weights", weights));
topology.add(reorder("reorder_input", "input", p.output_format, p.input_data_type));
topology.add(cldnn::convolution("conv", { "reorder_input" }, { "weights" }));
topology.add(reorder("reorder_conv", "conv", reorder_layout));
program::ptr prog = program::build_program(engine, topology, build_opt, false, true);
layout_optimizer lo = layout_optimizer();
lo.set_optimization_attribute(layout_optimizer::optimization_attributes_type::use_onednn_impls, true);
setting_node(prog, "conv", conv_layout);
auto itr = prog->get_processing_order().begin();
while (itr != prog->get_processing_order().end()) {
auto node_ptr = *itr++;
if (!node_ptr->is_type<reorder>() || node_ptr->id() != "reorder_input") // target reorder
continue;
auto& node = node_ptr->as<reorder>();
auto& input = node.input();
for (auto usr : node_ptr->get_users()) {
auto temp = usr->get_output_layout();
EXPECT_EQ(p.expected_result, lo.can_fuse_reorder(input, *usr, node.input().get_output_layout().format, usr->get_output_layout().format));
}
}
}
INSTANTIATE_TEST_SUITE_P(testing_deep_depth_conv, test_fused_reorder_deep_depth,
::testing::ValuesIn(std::vector<reorder_test_param>{
reorder_test_param{format::bfyx, format::b_fs_yx_fsv32, data_types::u8, data_types::u8, {1, 32, 8, 8}, {1, 32, 8, 8}, {1, 32, 1, 1},
tensor{1}, tensor{0}, data_types::u8, format::goiyx, false},
reorder_test_param{format::bfyx, format::b_fs_yx_fsv16, data_types::f16, data_types::f16, {1, 32, 8, 8}, {1, 32, 8, 8}, {1, 32, 1, 1},
tensor{1}, tensor{0}, data_types::f16, format::goiyx, false},
reorder_test_param{format::bfyx, format::bs_fs_yx_bsv32_fsv32, data_types::u8, data_types::u8, {32, 32, 8, 8}, {32, 32, 8, 8}, {1, 32, 1, 1},
tensor{1}, tensor{0}, data_types::u8, format::goiyx, false},
reorder_test_param{format::bfyx, format::bs_fs_yx_bsv32_fsv16, data_types::f16, data_types::f16, {32, 32, 8, 8}, {32, 32, 8, 8}, {1, 32, 1, 1},
tensor{1}, tensor{0}, data_types::f16, format::goiyx, false},
}));
// To test removal of reorder for first convolution optimizing in cldnn kernel (shallow input depth to deep output depth)
class test_can_fuse_reorder_first_conv : public ReorderTest<reorder_test_param> {};
TEST_P(test_can_fuse_reorder_first_conv, reorder_for_firstconv_cldnn)
{
build_options build_opt;
topology topology;
auto p = GetParam();
layout reorder_layout(p.output_data_type, p.output_format, p.out_shape, padding({0, }, 0));
auto input = engine.allocate_memory({ p.input_data_type, p.input_format, p.in_shape });
auto weights = engine.allocate_memory({ p.input_data_type, p.input_format, p.weight_shape });
auto bias = engine.allocate_memory({ p.input_data_type, p.input_format, p.weight_shape });
topology.add(input_layout("input", input->get_layout()));
topology.add(data("weights", weights));
topology.add(data("bias", bias));
topology.add(reorder("reorder_input", "input", p.output_format, p.input_data_type));
topology.add(cldnn::convolution("conv2", { "reorder_input" }, { "weights" }, { "bias"}, 1, tensor{1}, tensor{0}, tensor{1}, p.out_shape, p.input_data_type, false));
topology.add(reorder("reorder_conv", "conv2", reorder_layout));
program::ptr prog = program::build_program(engine, topology, build_opt, false, true);
layout_optimizer lo = layout_optimizer();
lo.set_optimization_attribute(layout_optimizer::optimization_attributes_type::use_onednn_impls, false);
auto itr = prog->get_processing_order().begin();
while (itr != prog->get_processing_order().end()) {
auto node_ptr = *itr++;
if (!node_ptr->is_type<reorder>() || node_ptr->id() != "reorder_input") // target reorder
continue;
auto& node = node_ptr->as<reorder>();
auto& input = node.input();
for (auto usr : node_ptr->get_users()) {
auto temp = usr->get_output_layout();
EXPECT_EQ(p.expected_result, lo.can_fuse_reorder(input, *usr, node.input().get_output_layout().format, usr->get_output_layout().format));
}
}
}
// To test removal of reorder for first convolution optimizing in onednn kernel (shallow input depth to deep output depth)
TEST_P(test_can_fuse_reorder_first_conv, reorder_for_firstconv_onednn)
{
build_options build_opt;
topology topology;
auto p = GetParam();
layout conv_layout(p.input_data_type, p.output_format, p.out_shape, padding({0, }, 0));
layout reorder_layout(p.output_data_type, p.output_format, p.out_shape, padding({0, }, 0));
auto input = engine.allocate_memory({ p.input_data_type, p.input_format, p.in_shape });
auto weights = engine.allocate_memory({ p.input_data_type, p.input_format, p.weight_shape });
topology.add(input_layout("input", input->get_layout()));
topology.add(data("weights", weights));
topology.add(reorder("reorder_input", "input", p.output_format, p.input_data_type));
topology.add(cldnn::convolution("conv", { "reorder_input" }, { "weights" }));
topology.add(reorder("reorder_conv", "conv", reorder_layout));
program::ptr prog = program::build_program(engine, topology, build_opt, false, true);
layout_optimizer lo = layout_optimizer();
lo.set_optimization_attribute(layout_optimizer::optimization_attributes_type::use_onednn_impls, true);
setting_node(prog, "conv", conv_layout);
auto itr = prog->get_processing_order().begin();
while (itr != prog->get_processing_order().end()) {
auto node_ptr = *itr++;
if (!node_ptr->is_type<reorder>() || node_ptr->id() != "reorder_input") // target reorder
continue;
auto& node = node_ptr->as<reorder>();
auto& input = node.input();
for (auto usr : node_ptr->get_users()) {
auto temp = usr->get_output_layout();
EXPECT_EQ(p.expected_result, lo.can_fuse_reorder(input, *usr, node.input().get_output_layout().format, usr->get_output_layout().format));
}
}
}
INSTANTIATE_TEST_SUITE_P(testing_can_fuse_reorder_first_conv, test_can_fuse_reorder_first_conv,
::testing::ValuesIn(std::vector<reorder_test_param>{
reorder_test_param{format::bfyx, format::b_fs_yx_fsv32, data_types::u8, data_types::u8, {1, 3, 8, 8}, {1, 32, 8, 8}, {1, 3, 1, 1},
tensor{1}, tensor{0}, data_types::u8, format::goiyx, true},
reorder_test_param{format::bfyx, format::b_fs_yx_fsv16, data_types::f16, data_types::f16, {1, 3, 8, 8}, {1, 32, 8, 8}, {1, 3, 1, 1},
tensor{1}, tensor{0}, data_types::f16, format::goiyx, true},
}));
| 48.342561 | 187 | 0.648772 | [
"vector"
] |
a36b574330a6ed45aa6d68368409a83610707b30 | 765 | cc | C++ | src/nix.cc | felixge/node-nix | 681c6490099a76daef5cbb52d1fed7b11775772c | [
"MIT"
] | 2 | 2015-05-13T10:56:42.000Z | 2019-04-27T20:27:05.000Z | src/nix.cc | felixge/node-nix | 681c6490099a76daef5cbb52d1fed7b11775772c | [
"MIT"
] | null | null | null | src/nix.cc | felixge/node-nix | 681c6490099a76daef5cbb52d1fed7b11775772c | [
"MIT"
] | null | null | null | #include <v8.h>
#include <node.h>
// this is where fork() comes from
#include <unistd.h>
using namespace v8;
static Handle<Value> Fork(const Arguments& args) {
HandleScope scope;
pid_t pid = fork();
if (pid < 0)
{
return ThrowException(Exception::Error(String::New("fork: could not fork, pid < 0. see man fork")));
}
if (pid == 0) {
// Child process: We need to tell libev that we are forking because
// kqueue can't deal with this gracefully.
//
// See: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_fork_code_the_audacity_to_re
ev_default_fork();
}
return scope.Close(Number::New(pid));
}
extern "C" void init (Handle<Object> target)
{
HandleScope scope;
NODE_SET_METHOD(target, "fork", Fork);
}
| 21.857143 | 104 | 0.666667 | [
"object"
] |
a36c2305cf6b4ff7fc319306c0c45c7829833476 | 337 | cpp | C++ | Questions Level-Wise/Medium/find-all-duplicates-in-an-array.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | 2 | 2021-03-05T22:32:23.000Z | 2021-03-05T22:32:29.000Z | Questions Level-Wise/Medium/find-all-duplicates-in-an-array.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | Questions Level-Wise/Medium/find-all-duplicates-in-an-array.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> findDuplicates(vector<int>& nums)
{
vector<int> a(nums.size());
for(auto e: nums)
a[e-1]++;
nums.resize(0);
for(int i=0;i<a.size();i++)
if(a[i]>1)
nums.push_back(i+1);
a.resize(0);
return nums;
}
};
| 21.0625 | 50 | 0.451039 | [
"vector"
] |
a36da2fd9b7400b67567f14ed495fab7167be5a0 | 3,198 | cpp | C++ | modules/task_2/barysheva_m_tape_hor_chart/main.cpp | NickitaKraev/pp_2021_autumn | dac9c0aa556ef15823af16bfae0044e282c5f7cb | [
"BSD-3-Clause"
] | 1 | 2021-12-09T17:20:25.000Z | 2021-12-09T17:20:25.000Z | modules/task_2/barysheva_m_tape_hor_chart/main.cpp | NickitaKraev/pp_2021_autumn | dac9c0aa556ef15823af16bfae0044e282c5f7cb | [
"BSD-3-Clause"
] | null | null | null | modules/task_2/barysheva_m_tape_hor_chart/main.cpp | NickitaKraev/pp_2021_autumn | dac9c0aa556ef15823af16bfae0044e282c5f7cb | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 Barysheva Maria
#include <gtest/gtest.h>
#include <gtest-mpi-listener.hpp>
#include "./tape_hor_chart.h"
TEST(MATRIX_MULTIPLICATION_A_B, TEST_SQUARE_1) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 33, m = 33;
vector<int> A(n * m), B(n * m);
if (rank == 0) {
A = getRandomMatrix(n, m);
B = getRandomMatrix(m, n);
}
ASSERT_NO_THROW(ParallelMatrixMultiplication(A, B, n, m));
}
TEST(MATRIX_MULTIPLICATION_A_B, TEST_2) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 15, m = 30;
vector<int> A(n * m), B(n * m);
if (rank == 0) {
A = getRandomMatrix(n, m);
B = getRandomMatrix(m, n);
}
ASSERT_NO_THROW(ParallelMatrixMultiplication(A, B, n, m));
}
TEST(MATRIX_MULTIPLICATION_A_B, TEST_SQUARE_3) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 50, m = 50;
vector<int> A(n * m), B(n * m);
if (rank == 0) {
A = getRandomMatrix(n, m);
B = getRandomMatrix(m, n);
}
vector<int> res = ParallelMatrixMultiplication(A, B, n, m);
if (rank == 0) {
vector<int> expected_res = SequentialMatrixMultiplication(A, B, n, m, n);
ASSERT_EQ(res, expected_res);
}
}
TEST(MATRIX_MULTIPLICATION_A_B, TEST_COLS_4) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 50, m = 75;
vector<int> A(n * m), B(n * m);
if (rank == 0) {
A = getRandomMatrix(n, m);
B = getRandomMatrix(m, n);
}
vector<int> res = ParallelMatrixMultiplication(A, B, n, m);
if (rank == 0) {
vector<int> expected_res = SequentialMatrixMultiplication(A, B, n, m, n);
ASSERT_EQ(res, expected_res);
}
}
TEST(MATRIX_MULTIPLICATION_A_B, TEST_ROWS_5) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 75, m = 50;
vector<int> A(n * m), B(n * m);
if (rank == 0) {
A = getRandomMatrix(n, m);
B = getRandomMatrix(m, n);
}
vector<int> res = ParallelMatrixMultiplication(A, B, n, m);
if (rank == 0) {
vector<int> expected_res = SequentialMatrixMultiplication(A, B, n, m, n);
ASSERT_EQ(res, expected_res);
}
}
TEST(MATRIX_MULTIPLICATION_A_B, TEST_BIG_6) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int n = 567, m = 183;
vector<int> A(n * m), B(n * m);
if (rank == 0) {
A = getRandomMatrix(n, m);
B = getRandomMatrix(m, n);
}
double start = MPI_Wtime();
vector<int> res = ParallelMatrixMultiplication(A, B, n, m);
double end = MPI_Wtime();
if (rank == 0) {
double time1 = end - start;
start = MPI_Wtime();
vector<int> expected_res = SequentialMatrixMultiplication(A, B, n, m, n);
end = MPI_Wtime();
double time2 = end - start;
std::cout << "Speedup: " << time2 / time1 << std::endl;
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 23.343066 | 77 | 0.642902 | [
"vector"
] |
a36e3605270dae7dfb7039891d5bbc410edefd2a | 28,077 | cc | C++ | paddle/fluid/framework/op_desc.cc | frankwhzhang/Paddle | 131b1dc3240e53ea295cc49323bb2a7e7dcc717f | [
"Apache-2.0"
] | 3 | 2019-07-17T09:30:31.000Z | 2021-12-27T03:16:55.000Z | paddle/fluid/framework/op_desc.cc | frankwhzhang/Paddle | 131b1dc3240e53ea295cc49323bb2a7e7dcc717f | [
"Apache-2.0"
] | null | null | null | paddle/fluid/framework/op_desc.cc | frankwhzhang/Paddle | 131b1dc3240e53ea295cc49323bb2a7e7dcc717f | [
"Apache-2.0"
] | 4 | 2019-09-30T02:15:34.000Z | 2019-09-30T02:41:30.000Z | /* Copyright (c) 2016 PaddlePaddle 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 "paddle/fluid/framework/op_desc.h"
#include <algorithm>
#include <functional>
#include <mutex> // NOLINT
#include <string>
#include <unordered_map>
#include <utility>
#include "glog/logging.h"
#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/framework/op_call_stack.h"
#include "paddle/fluid/framework/op_proto_maker.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/shape_inference.h"
#include "paddle/fluid/framework/var_type_inference.h"
namespace paddle {
namespace framework {
class OpDesc;
class BlockDesc;
class CompileTimeInferShapeContext : public InferShapeContext {
public:
CompileTimeInferShapeContext(const OpDesc &op, const BlockDesc &block);
bool HasInput(const std::string &name) const override;
bool HasOutput(const std::string &name) const override;
bool HasInputs(const std::string &name) const override;
bool HasOutputs(const std::string &name) const override;
AttrReader Attrs() const override;
const std::vector<std::string> &Inputs(
const std::string &name) const override;
const std::vector<std::string> &Outputs(
const std::string &name) const override;
void ShareDim(const std::string &in, const std::string &out, size_t i = 0,
size_t j = 0) override {
PADDLE_ENFORCE_LT(i, Inputs(in).size());
PADDLE_ENFORCE_LT(j, Outputs(out).size());
const std::string &input_n = Inputs(in)[i];
const std::string &output_n = Outputs(out)[j];
PADDLE_ENFORCE(input_n != framework::kEmptyVarName, "The %s[%d] is @EMPTY@",
in, i);
PADDLE_ENFORCE(output_n != framework::kEmptyVarName,
"The %s[%d] is @EMPTY@", out, j);
auto *in_var = block_.FindVarRecursive(input_n);
auto *out_var = block_.FindVarRecursive(output_n);
PADDLE_ENFORCE(in_var->GetType() == out_var->GetType(),
"The type of %s and %s is not the same.", input_n, output_n);
SetDim(output_n, GetDim(input_n));
}
void ShareLoD(const std::string &in, const std::string &out, size_t i = 0,
size_t j = 0) const override {
PADDLE_ENFORCE_LT(i, Inputs(in).size());
PADDLE_ENFORCE_LT(j, Outputs(out).size());
PADDLE_ENFORCE(Inputs(in)[i] != framework::kEmptyVarName,
"The %s[%d] is @EMPTY@", in, i);
PADDLE_ENFORCE(Outputs(out)[j] != framework::kEmptyVarName,
"The %s[%d] is @EMPTY@", out, j);
auto *in_var = block_.FindVarRecursive(Inputs(in)[i]);
auto *out_var = block_.FindVarRecursive(Outputs(out)[j]);
if (in_var->GetType() != proto::VarType::LOD_TENSOR &&
in_var->GetType() != proto::VarType::LOD_TENSOR_ARRAY) {
VLOG(3) << "input " << in << " is not LodTensor or LodTensorArray.";
return;
}
out_var->SetLoDLevel(in_var->GetLoDLevel());
}
void DecreaseLoDLevel(const std::string &in, const std::string &out,
size_t i = 0, size_t j = 0) const override {
PADDLE_ENFORCE_LT(i, Inputs(in).size());
PADDLE_ENFORCE_LT(j, Outputs(out).size());
PADDLE_ENFORCE(Inputs(in)[i] != framework::kEmptyVarName,
"The %s[%d] is @EMPTY@", in, i);
PADDLE_ENFORCE(Outputs(out)[j] != framework::kEmptyVarName,
"The %s[%d] is @EMPTY@", out, j);
auto *in_var = block_.FindVarRecursive(Inputs(in)[i]);
auto *out_var = block_.FindVarRecursive(Outputs(out)[j]);
PADDLE_ENFORCE(out_var->GetType() == proto::VarType::LOD_TENSOR_ARRAY ||
out_var->GetType() == proto::VarType::LOD_TENSOR,
"The input %s should be LodTensorArray or LodTensor.",
out_var->Name());
PADDLE_ENFORCE(in_var->GetType() == proto::VarType::LOD_TENSOR,
"The input %s should be LodTensor.", in_var->Name());
if (in_var->GetLoDLevel() > 0) {
out_var->SetLoDLevel(in_var->GetLoDLevel() - 1);
}
}
std::vector<InferShapeVarPtr> GetInputVarPtrs(
const std::string &name) override {
const std::vector<std::string> arg_names = Inputs(name);
std::vector<InferShapeVarPtr> res;
res.reserve(arg_names.size());
std::transform(arg_names.begin(), arg_names.end(), std::back_inserter(res),
[this](const std::string &name) {
return block_.FindVarRecursive(name);
});
return res;
}
std::vector<InferShapeVarPtr> GetOutputVarPtrs(
const std::string &name) override {
const std::vector<std::string> arg_names = Outputs(name);
std::vector<InferShapeVarPtr> res;
res.reserve(arg_names.size());
std::transform(arg_names.begin(), arg_names.end(), std::back_inserter(res),
[this](const std::string &name) {
return block_.FindVarRecursive(name);
});
return res;
}
DDim GetInputDim(const std::string &name) const override {
const std::vector<std::string> &arg_names = Inputs(name);
PADDLE_ENFORCE_EQ(arg_names.size(), 1UL,
"Input(%s) should hold one element, but now it holds %d",
name, arg_names.size());
return this->GetDim(arg_names[0]);
}
std::vector<DDim> GetInputsDim(const std::string &name) const override {
const std::vector<std::string> &arg_names = Inputs(name);
return GetDims(arg_names);
}
bool IsRuntime() const override;
std::vector<proto::VarType::Type> GetInputsVarType(
const std::string &name) const override {
return GetVarTypes(Inputs(name));
}
std::vector<proto::VarType::Type> GetOutputsVarType(
const std::string &name) const override {
return GetVarTypes(Outputs(name));
}
void SetOutputDim(const std::string &name, const DDim &dim) override {
auto &arg_names = Outputs(name);
PADDLE_ENFORCE_EQ(arg_names.size(), 1UL,
"Output(%s) should hold one element, but now it holds %d",
name, arg_names.size());
SetDim(arg_names[0], dim);
}
void SetOutputsDim(const std::string &name,
const std::vector<DDim> &dims) override {
auto &names = Outputs(name);
SetDims(names, dims);
}
protected:
std::vector<proto::VarType::Type> GetVarTypes(
const std::vector<std::string> &names) const {
std::vector<proto::VarType::Type> retv;
retv.resize(names.size());
std::transform(
names.begin(), names.end(), retv.begin(),
std::bind(std::mem_fn(&CompileTimeInferShapeContext::GetVarType), this,
std::placeholders::_1));
return retv;
}
proto::VarType::Type GetVarType(const std::string &name) const;
DDim GetDim(const std::string &name) const {
auto var = block_.FindVarRecursive(name);
PADDLE_ENFORCE(var != nullptr, "Cannot find variable %s", name);
DDim res;
try {
auto shape = var->GetShape();
res = shape.empty() ? make_ddim({0UL}) : make_ddim(shape);
} catch (...) {
VLOG(5) << "GetDim of variable " << name << " error";
std::rethrow_exception(std::current_exception());
}
return res;
}
std::vector<DDim> GetDims(const std::vector<std::string> &names) const {
std::vector<DDim> ret;
ret.reserve(names.size());
std::transform(
names.begin(), names.end(), std::back_inserter(ret),
[this](const std::string &name) { return this->GetDim(name); });
return ret;
}
void SetDim(const std::string &name, const DDim &dim);
void SetDims(const std::vector<std::string> &names,
const std::vector<DDim> &dims) {
size_t length = names.size();
PADDLE_ENFORCE_EQ(length, dims.size());
for (size_t i = 0; i < length; ++i) {
if (names[i] == framework::kEmptyVarName) {
continue;
}
SetDim(names[i], dims[i]);
}
}
std::vector<DDim> GetRepeatedDims(const std::string &name) const override;
void SetRepeatedDims(const std::string &name,
const std::vector<DDim> &dims) override;
const OpDesc &op_;
const BlockDesc &block_;
};
OpDesc::OpDesc(const std::string &type, const VariableNameMap &inputs,
const VariableNameMap &outputs, const AttributeMap &attrs) {
desc_.set_type(type);
inputs_ = inputs;
outputs_ = outputs;
attrs_ = attrs;
need_update_ = true;
block_ = nullptr;
}
OpDesc::OpDesc(const OpDesc &other, BlockDesc *block) {
CopyFrom(other);
block_ = block;
need_update_ = true;
}
void OpDesc::CopyFrom(const OpDesc &op_desc) {
desc_.set_type(op_desc.Type());
inputs_ = op_desc.inputs_;
outputs_ = op_desc.outputs_;
attrs_ = op_desc.attrs_;
need_update_ = true;
}
OpDesc::OpDesc(const proto::OpDesc &desc, BlockDesc *block)
: desc_(desc), need_update_(false) {
// restore inputs_
int input_size = desc_.inputs_size();
for (int i = 0; i < input_size; ++i) {
const proto::OpDesc::Var &var = desc_.inputs(i);
std::vector<std::string> &args = inputs_[var.parameter()];
int argu_size = var.arguments_size();
args.reserve(argu_size);
for (int j = 0; j < argu_size; ++j) {
args.push_back(var.arguments(j));
}
}
// restore outputs_
int output_size = desc_.outputs_size();
for (int i = 0; i < output_size; ++i) {
const proto::OpDesc::Var &var = desc_.outputs(i);
std::vector<std::string> &args = outputs_[var.parameter()];
int argu_size = var.arguments_size();
args.reserve(argu_size);
for (int j = 0; j < argu_size; ++j) {
args.push_back(var.arguments(j));
}
}
// restore attrs_
for (const proto::OpDesc::Attr &attr : desc_.attrs()) {
std::string attr_name = attr.name();
// The sub_block referred to by the BLOCK attr hasn't been added
// to ProgramDesc class yet, we skip setting BLOCK/BLOCKS attr here.
if (attr.type() != proto::AttrType::BLOCK &&
attr.type() != proto::AttrType::BLOCKS) {
attrs_[attr_name] = GetAttrValue(attr);
}
}
this->block_ = block;
}
proto::OpDesc *OpDesc::Proto() {
Flush();
return &desc_;
}
const std::vector<std::string> &OpDesc::Input(const std::string &name) const {
auto it = inputs_.find(name);
PADDLE_ENFORCE(it != inputs_.end(), "Input %s cannot be found in Op %s", name,
Type());
return it->second;
}
std::vector<std::string> OpDesc::InputArgumentNames() const {
std::vector<std::string> retv;
for (auto &ipt : this->inputs_) {
retv.insert(retv.end(), ipt.second.begin(), ipt.second.end());
}
return retv;
}
void OpDesc::SetInput(const std::string ¶m_name,
const std::vector<std::string> &args) {
need_update_ = true;
inputs_[param_name] = args;
}
const std::vector<std::string> &OpDesc::Output(const std::string &name) const {
auto it = outputs_.find(name);
PADDLE_ENFORCE(it != outputs_.end(), "Output %s cannot be found in Op %s",
name, Type());
return it->second;
}
std::vector<std::string> OpDesc::OutputArgumentNames() const {
std::vector<std::string> retv;
for (auto &ipt : this->outputs_) {
retv.insert(retv.end(), ipt.second.begin(), ipt.second.end());
}
return retv;
}
void OpDesc::SetOutput(const std::string ¶m_name,
const std::vector<std::string> &args) {
need_update_ = true;
this->outputs_[param_name] = args;
}
bool OpDesc::HasProtoAttr(const std::string &name) const {
auto &op_info = OpInfoMap::Instance();
if (op_info.Has(desc_.type())) {
auto op_info_ptr = op_info.Get(desc_.type());
if (op_info_ptr.HasOpProtoAndChecker()) {
const proto::OpProto &proto = op_info_ptr.Proto();
for (int i = 0; i != proto.attrs_size(); ++i) {
const proto::OpProto::Attr &attr = proto.attrs(i);
if (attr.name() == name) {
return true;
}
}
}
}
return false;
}
proto::AttrType OpDesc::GetAttrType(const std::string &name) const {
auto it = attrs_.find(name);
PADDLE_ENFORCE(it != attrs_.end(), "Attribute %s is not found", name);
return static_cast<proto::AttrType>(it->second.which() - 1);
}
std::vector<std::string> OpDesc::AttrNames() const {
std::vector<std::string> retv;
retv.reserve(attrs_.size());
for (auto &attr : attrs_) {
retv.push_back(attr.first);
}
return retv;
}
void OpDesc::RemoveAttr(const std::string &name) {
attrs_.erase(name);
need_update_ = true;
}
void OpDesc::SetAttr(const std::string &name, const Attribute &v) {
// NOTICE(minqiyang): pybind11 will take the empty list in python as
// the std::vector<int> type in C++; so we have to change the attr's type
// here if we meet this issue
proto::AttrType attr_type = static_cast<proto::AttrType>(v.which() - 1);
if (attr_type == proto::AttrType::INTS &&
boost::get<std::vector<int>>(v).size() == 0u) {
// Find current attr via attr name and set the correct attribute value
const proto::OpProto::Attr &attr = GetProtoAttr(name);
switch (attr.type()) {
case proto::AttrType::BOOLEANS: {
VLOG(11) << "SetAttr: " << Type() << ", " << name
<< " from INTS to BOOLEANS";
this->attrs_[name] = std::vector<bool>();
break;
}
case proto::AttrType::INTS: {
VLOG(11) << "SetAttr: " << Type() << ", " << name
<< " from INTS to INTS";
this->attrs_[name] = std::vector<int>();
break;
}
case proto::AttrType::LONGS: {
VLOG(11) << "SetAttr: " << Type() << ", " << name
<< " from LONGS to LONGS";
this->attrs_[name] = std::vector<int64_t>();
break;
}
case proto::AttrType::FLOATS: {
VLOG(11) << "SetAttr: " << Type() << ", " << name
<< " from INTS to FLOATS";
this->attrs_[name] = std::vector<float>();
break;
}
case proto::AttrType::STRINGS: {
VLOG(11) << "SetAttr: " << Type() << ", " << name
<< " from INTS to STRINGS";
this->attrs_[name] = std::vector<std::string>();
break;
}
case proto::AttrType::BLOCKS: {
VLOG(11) << "SetAttr: " << Type() << ", " << name
<< " from INTS to BLOCKS";
this->SetBlocksAttr(name, std::vector<BlockDesc *>());
return;
}
default:
PADDLE_THROW("Wrong attr type %d", attr.type());
}
need_update_ = true;
return;
}
this->attrs_[name] = v;
need_update_ = true;
}
void OpDesc::SetBlockAttr(const std::string &name, BlockDesc *block) {
this->attrs_[name] = block;
need_update_ = true;
}
void OpDesc::SetBlocksAttr(const std::string &name,
std::vector<BlockDesc *> blocks) {
this->attrs_[name] = blocks;
need_update_ = true;
}
void OpDesc::SetAttrMap(
const std::unordered_map<std::string, Attribute> &attr_map) {
attrs_ = attr_map;
need_update_ = true;
}
Attribute OpDesc::GetAttr(const std::string &name) const {
auto it = attrs_.find(name);
PADDLE_ENFORCE(it != attrs_.end(), "Attribute %s is not found", name);
return it->second;
}
const proto::OpProto::Attr &OpDesc::GetProtoAttr(
const std::string &name) const {
const proto::OpProto &proto = OpInfoMap::Instance().Get(Type()).Proto();
for (int i = 0; i != proto.attrs_size(); ++i) {
const proto::OpProto::Attr &attr = proto.attrs(i);
if (attr.name() == name) {
return attr;
}
}
PADDLE_THROW("Attribute %s is not found in proto %s", name, proto.type());
}
Attribute OpDesc::GetNullableAttr(const std::string &name) const {
auto it = attrs_.find(name);
if (it != attrs_.end()) {
return it->second;
} else {
return Attribute();
}
}
std::vector<int> OpDesc::GetBlocksAttrIds(const std::string &name) const {
auto it = attrs_.find(name);
PADDLE_ENFORCE(it != attrs_.end(), "Attribute %s is not found", name);
auto blocks = boost::get<std::vector<BlockDesc *>>(it->second);
std::vector<int> ids;
for (auto n : blocks) {
ids.push_back(n->ID());
}
return ids;
}
int OpDesc::GetBlockAttrId(const std::string &name) const {
auto it = attrs_.find(name);
PADDLE_ENFORCE(it != attrs_.end(), "Attribute %s is not found", name);
return boost::get<BlockDesc *>(it->second)->ID();
}
const std::unordered_map<std::string, Attribute> &OpDesc::GetAttrMap() const {
return attrs_;
}
void OpDesc::Rename(const std::string &old_name, const std::string &new_name) {
RenameInput(old_name, new_name);
RenameOutput(old_name, new_name);
need_update_ = true;
}
void OpDesc::RenameOutput(const std::string &old_name,
const std::string &new_name) {
for (auto &output : outputs_) {
std::replace(output.second.begin(), output.second.end(), old_name,
new_name);
}
auto it = attrs_.find(framework::OpProtoAndCheckerMaker::OpRoleVarAttrName());
if (it != attrs_.end()) {
auto &op_vars = boost::get<std::vector<std::string>>(it->second);
std::replace(op_vars.begin(), op_vars.end(), old_name, new_name);
}
need_update_ = true;
}
void OpDesc::RenameInput(const std::string &old_name,
const std::string &new_name) {
for (auto &input : inputs_) {
std::replace(input.second.begin(), input.second.end(), old_name, new_name);
}
auto it = attrs_.find(framework::OpProtoAndCheckerMaker::OpRoleVarAttrName());
if (it != attrs_.end()) {
auto &op_vars = boost::get<std::vector<std::string>>(it->second);
std::replace(op_vars.begin(), op_vars.end(), old_name, new_name);
}
need_update_ = true;
}
struct SetAttrDescVisitor : public boost::static_visitor<void> {
explicit SetAttrDescVisitor(proto::OpDesc::Attr *attr) : attr_(attr) {}
mutable proto::OpDesc::Attr *attr_;
void operator()(int v) const { attr_->set_i(v); }
void operator()(float v) const { attr_->set_f(v); }
void operator()(const std::string &v) const { attr_->set_s(v); }
// Please refer to https://github.com/PaddlePaddle/Paddle/issues/7162
template <class T,
class = typename std::enable_if<std::is_same<bool, T>::value>::type>
void operator()(T b) const {
attr_->set_b(b);
}
void operator()(const std::vector<int> &v) const {
VectorToRepeated(v, attr_->mutable_ints());
}
void operator()(const std::vector<float> &v) const {
VectorToRepeated(v, attr_->mutable_floats());
}
void operator()(const std::vector<std::string> &v) const {
VectorToRepeated(v, attr_->mutable_strings());
}
void operator()(const std::vector<bool> &v) const {
VectorToRepeated(v, attr_->mutable_bools());
}
void operator()(const std::vector<BlockDesc *> &v) const {
std::vector<int> blocks_idx;
for (auto blk : v) {
blocks_idx.push_back(blk->ID());
}
VectorToRepeated(blocks_idx, attr_->mutable_blocks_idx());
}
void operator()(BlockDesc *desc) const { attr_->set_block_idx(desc->ID()); }
void operator()(int64_t v) const { attr_->set_l(v); }
void operator()(const std::vector<int64_t> &v) const {
VectorToRepeated(v, attr_->mutable_longs());
}
void operator()(boost::blank) const { PADDLE_THROW("Unexpected branch"); }
};
void OpDesc::Flush() {
if (need_update_) {
this->desc_.mutable_inputs()->Clear();
for (auto &ipt : inputs_) {
auto *input = desc_.add_inputs();
input->set_parameter(ipt.first);
VectorToRepeated(ipt.second, input->mutable_arguments());
}
this->desc_.mutable_outputs()->Clear();
for (auto &opt : outputs_) {
auto *output = desc_.add_outputs();
output->set_parameter(opt.first);
VectorToRepeated(opt.second, output->mutable_arguments());
}
this->desc_.mutable_attrs()->Clear();
for (auto &attr : attrs_) {
auto *attr_desc = desc_.add_attrs();
attr_desc->set_name(attr.first);
attr_desc->set_type(
static_cast<proto::AttrType>(attr.second.which() - 1));
SetAttrDescVisitor visitor(attr_desc);
boost::apply_visitor(visitor, attr.second);
}
need_update_ = false;
}
}
static std::once_flag init_infer_shape_funcs;
/**
* NOTE(paddle-dev): Very tricky code here. Maybe we should find a
* better way to register compile-time infershape method gentlely.
*
* Normally, we can register a class derived from InferShapeBase, so that
* we can set the field of `infer_shape_` inside OpInfo when registering op.
*
* However, there is another way we can set the field of `infer_shape_` inside
* OpInfo. Usually, we overload InferShape method of OperatorWithKernel. After
* running the following method InitInferShapeFuncs, `infer_shape_` would be set
* to be the InferShape method of OperatorWithKernel. That is to say, we borrow
* the run-time InferShape method of OperatorWithKernel to be the compile-time
* InferShape method.
*
* However, during compiling time, we may not know inputs, outputs and attrs of
* run-time OperatorWithKernel. So the following code creates a fake
* OperatorWithKernel object. That is why the field info_ of OperatorBase
* would be null.
*/
static void InitInferShapeFuncs() {
std::call_once(init_infer_shape_funcs, [] {
auto &map = OpInfoMap::Instance();
auto &info_map = *map.mutable_map();
for (auto &kern_pair : OperatorWithKernel::AllOpKernels()) {
auto op_type = kern_pair.first;
auto it = info_map.find(op_type);
PADDLE_ENFORCE(it != info_map.end(), "%s has not been registered",
op_type);
auto &op_info = it->second;
if (op_info.infer_shape_) { // infer_shape has been registered.
continue;
}
auto op = dynamic_cast<OperatorWithKernel *>(op_info.Creator()(
"", VariableNameMap{}, VariableNameMap{}, AttributeMap{}));
PADDLE_ENFORCE_NOT_NULL(
op, "InferShapeBase is not registered to Operator %s", op_type);
op_info.infer_shape_ = [op](InferShapeContext *ctx) {
op->InferShape(ctx);
};
}
});
}
void OpDesc::CheckAttrs() {
PADDLE_ENFORCE(!Type().empty(),
"CheckAttr() can not be called before type is setted.");
auto *checker = OpInfoMap::Instance().Get(Type()).Checker();
if (checker == nullptr) {
// checker is not configured. That operator could be generated by Paddle,
// not by users.
return;
}
VLOG(10) << "begin to check attribute of " << Type();
checker->Check(&attrs_);
}
void OpDesc::InferShape(const BlockDesc &block) const {
try {
VLOG(3) << "CompileTime infer shape on " << Type();
InitInferShapeFuncs();
auto &infer_shape = OpInfoMap::Instance().Get(this->Type()).infer_shape_;
PADDLE_ENFORCE(static_cast<bool>(infer_shape),
"%s's infer_shape has not been registered", this->Type());
CompileTimeInferShapeContext ctx(*this, block);
if (VLOG_IS_ON(10)) {
std::ostringstream sout;
auto inames = this->InputArgumentNames();
sout << " From [";
std::copy(inames.begin(), inames.end(),
std::ostream_iterator<std::string>(sout, ", "));
sout << "] to [";
auto onames = this->OutputArgumentNames();
std::copy(onames.begin(), onames.end(),
std::ostream_iterator<std::string>(sout, ", "));
sout << "]";
VLOG(10) << sout.str();
}
infer_shape(&ctx);
} catch (platform::EnforceNotMet exception) {
framework::InsertCallStackInfo(Type(), attrs_, &exception);
throw std::move(exception);
} catch (...) {
std::rethrow_exception(std::current_exception());
}
}
void OpDesc::InferVarType(BlockDesc *block) const {
// There are a few places that var type can be set.
// When VarDesc is created, default set to LOD_TENSOR.
// When output variable is created, default is defaut set to LOD_TENSOR.
// We limit here to be the only place that operator defines its customized
// var type inference. Hence, we don't do any "default" setting here.
auto &info = OpInfoMap::Instance().Get(this->Type());
if (info.infer_var_type_) {
InferVarTypeContext context(this, block);
info.infer_var_type_(&context);
}
}
CompileTimeInferShapeContext::CompileTimeInferShapeContext(
const OpDesc &op, const BlockDesc &block)
: op_(op), block_(block) {}
bool CompileTimeInferShapeContext::HasInput(const std::string &name) const {
const std::vector<std::string> &input_names = op_.Input(name);
auto length = input_names.size();
if (length == 0) {
return false;
}
PADDLE_ENFORCE_EQ(length, 1UL,
"Input(%s) should have only one value, "
"but it have %d now",
name, length);
return block_.HasVarRecursive(input_names[0]);
}
bool CompileTimeInferShapeContext::HasOutput(const std::string &name) const {
const std::vector<std::string> &output_names = op_.Output(name);
auto length = output_names.size();
if (length == 0) {
return false;
}
PADDLE_ENFORCE_EQ(length, 1UL,
"Output(%s) should have only one value, "
"but it have %d now",
name, length);
return block_.HasVarRecursive(output_names[0]);
}
bool CompileTimeInferShapeContext::HasInputs(const std::string &name) const {
const std::vector<std::string> &input_names = op_.Input(name);
if (input_names.empty()) {
return false;
}
for (auto &input : input_names) {
if (!block_.HasVarRecursive(input)) return false;
}
return true;
}
bool CompileTimeInferShapeContext::HasOutputs(const std::string &name) const {
const std::vector<std::string> &output_names = op_.Output(name);
if (output_names.empty()) {
return false;
}
for (auto &output : output_names) {
if (!block_.HasVarRecursive(output)) return false;
}
return true;
}
AttrReader CompileTimeInferShapeContext::Attrs() const {
return AttrReader(op_.GetAttrMap());
}
const std::vector<std::string> &CompileTimeInferShapeContext::Inputs(
const std::string &name) const {
return op_.Input(name);
}
const std::vector<std::string> &CompileTimeInferShapeContext::Outputs(
const std::string &name) const {
return op_.Output(name);
}
std::vector<DDim> CompileTimeInferShapeContext::GetRepeatedDims(
const std::string &name) const {
auto var = block_.FindVarRecursive(name);
PADDLE_ENFORCE(var != nullptr, "Cannot find variable %s", name);
std::vector<DDim> res;
try {
auto shapes = var->GetShapes();
for (const auto &s : shapes) {
res.push_back(s.empty() ? make_ddim({0UL}) : make_ddim(s));
}
} catch (...) {
VLOG(5) << "GetRepeatedDim of variable " << name << " error.";
std::rethrow_exception(std::current_exception());
}
return res;
}
void CompileTimeInferShapeContext::SetDim(const std::string &name,
const DDim &dim) {
block_.FindVarRecursive(name)->SetShape(vectorize(dim));
}
void CompileTimeInferShapeContext::SetRepeatedDims(
const std::string &name, const std::vector<DDim> &dims) {
auto var = block_.FindVarRecursive(name);
PADDLE_ENFORCE(var != nullptr, "Cannot find variable %s", name);
std::vector<std::vector<int64_t>> dim_vec(dims.size());
std::transform(dims.begin(), dims.end(), dim_vec.begin(), vectorize<>);
var->SetShapes(dim_vec);
}
bool CompileTimeInferShapeContext::IsRuntime() const { return false; }
proto::VarType::Type CompileTimeInferShapeContext::GetVarType(
const std::string &name) const {
return block_.FindVarRecursive(name)->GetType();
}
} // namespace framework
} // namespace paddle
| 33.746394 | 80 | 0.641486 | [
"object",
"shape",
"vector",
"transform"
] |
a373f93fea379b33069d7b6f3d13678799d6fc03 | 9,705 | hh | C++ | gazebo/gui/building/RectItem.hh | thomas-moulard/gazebo-deb | 456da84cfb7b0bdac53241f6c4e86ffe1becfa7d | [
"ECL-2.0",
"Apache-2.0"
] | 8 | 2015-07-02T08:23:30.000Z | 2020-11-17T19:00:38.000Z | gazebo/gui/building/RectItem.hh | thomas-moulard/gazebo-deb | 456da84cfb7b0bdac53241f6c4e86ffe1becfa7d | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | gazebo/gui/building/RectItem.hh | thomas-moulard/gazebo-deb | 456da84cfb7b0bdac53241f6c4e86ffe1becfa7d | [
"ECL-2.0",
"Apache-2.0"
] | 10 | 2015-04-22T18:33:15.000Z | 2021-11-16T10:17:45.000Z | /*
* Copyright 2012 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.
*
*/
#ifndef _RECT_ITEM_HH_
#define _RECT_ITEM_HH_
#include <vector>
#include "gazebo/gui/qt.h"
#include "gazebo/gui/building/EditorItem.hh"
namespace gazebo
{
namespace gui
{
class GrabberHandle;
class RotateHandle;
class EditorItem;
/// \addtogroup gazebo_gui
/// \{
/// \class RectItem RectItem.hh
/// \brief 2D rectangle.
class RectItem : public EditorItem, public QGraphicsRectItem
{
Q_OBJECT
/// \brief Resize flags used to indicate which dimension can be resized.
public: enum ResizeFlags {NONE = 0x00,
ITEM_WIDTH = 0x01, ITEM_HEIGHT = 0x02};
/// \brief Constructor
public: RectItem();
/// \brief Destructor
public: virtual ~RectItem();
/// \brief Set the width of the rect item.
/// \param[in] _width Width of the rect item in pixels.
public: void SetWidth(int _width);
/// \brief Set the height of the rect item.
/// \param[in] _height Height of the rect item in pixels.
public: void SetHeight(int _height);
/// \brief Set the size of the rect item.
/// \param[in] _size Size of the rect item in pixels.
public: void SetSize(QSize _size);
/// \brief Get the width of the rect item.
/// \return Width of the rect item in pixels.
public: double GetWidth() const;
/// \brief Get the height of the rect item.
/// \return Height of the rect item in pixels.
public: double GetHeight() const;
/// \brief Show the grabber and rotate handles of the rect item.
/// \param[in] _show True to draw the handles, and false to hide them.
public: void ShowHandles(bool _show);
/// \brief Helper method for Updating the corner positions of the rect
/// item.
protected: void UpdateCornerPositions();
/// \brief Draw bounding box
/// \param[in] _painter Qt painter object.
protected: void DrawBoundingBox(QPainter *_painter);
/// \brief Set the position of the rect item
/// \param[in] _pos Position in pixel coordinates.
public: virtual void SetPosition(const QPointF &_pos);
/// \brief Set the position of the rect item
/// \param[in] _x X position in pixel coordinates.
/// \param[in] _y Y position in pixel coordinates.
public: virtual void SetPosition(double _x, double _y);
/// \brief Set the rotation of the rect item.
/// \param[in] _angle Rotation angle in degrees.
public: virtual void SetRotation(double _angle);
/// \brief Set the resize flag of the rect item.
/// \param[in] _flag Resize flag which controls how the item can be
/// resized.
public: virtual void SetResizeFlag(unsigned int _flag);
/// \brief Get the rotation of the rect item
/// \return Rotation in degrees.
public: virtual double GetRotation() const;
// Documentation inherited
public: virtual QVector3D GetSize() const;
// Documentation inherited
public: virtual QVector3D GetScenePosition() const;
// Documentation inherited
public: virtual double GetSceneRotation() const;
/// \brief Get the bounding box of the rect item.
/// \return The bounding box of the rect item.
protected: virtual QRectF boundingRect() const;
/// \brief Filter Qt events and redirect them to the rotate handle.
/// \param[in] _rotateHandle Rotate handle that will handle the event.
/// \param[in] _event Qt event
private: virtual bool RotateEventFilter(RotateHandle *_rotateHandle,
QEvent *_event);
/// \brief Filter Qt events and redirect them to the grabber handle.
/// \param[in] _rotateHandle Grabber handle that will handle the event.
/// \param[in] _event Qt event
private: virtual bool GrabberEventFilter(GrabberHandle *_grabber,
QEvent *_event);
/// \brief Qt paint function for drawing the rect item.
/// \param[in] _painter Qt painter object.
/// \param[in] _option Qt style options for the item.
/// \param[in] _widget Qt widget being painted on.
private: virtual void paint(QPainter *_painter,
const QStyleOptionGraphicsItem *_option, QWidget *_widget);
/// \brief Qt mouse hover enter event.
/// \param[in] _event Qt mouse hover event.
private: void hoverEnterEvent(QGraphicsSceneHoverEvent *_event);
/// \brief Qt mouse hover move event.
/// \param[in] _event Qt mouse hover event.
private: void hoverMoveEvent(QGraphicsSceneHoverEvent *_event);
/// \brief Qt mouse hover leave event.
/// \param[in] _event Qt mouse hover event.
private: void hoverLeaveEvent(QGraphicsSceneHoverEvent *_event);
/// \brief Qt mouse move event.
/// \param[in] _event Qt mouse event.
private: virtual void mouseMoveEvent(QGraphicsSceneMouseEvent *_event);
/// \brief Qt mouse press event.
/// \param[in] _event Qt mouse event.
private: virtual void mousePressEvent(QGraphicsSceneMouseEvent *_event);
/// \brief Qt mouse release event.
/// \param[in] _event Qt mouse event.
private: virtual void mouseReleaseEvent(
QGraphicsSceneMouseEvent *_event);
/// \brief Qt mouse press event during drag and drop.
/// \param[in] _event Qt mouse drag and drop event.
private: virtual void mousePressEvent(
QGraphicsSceneDragDropEvent *_event);
/// \brief Qt mouse move event during drag and drop.
/// \param[in] _event Qt mouse drag and drop event.
private: virtual void mouseMoveEvent(
QGraphicsSceneDragDropEvent *_event);
/// \brief Qt mouse double click event.
/// \param[in] _event Qt mouse event.
private: virtual void mouseDoubleClickEvent(
QGraphicsSceneMouseEvent *_event);
/// \brief Filter Qt events and redirect them to another item.
/// \param[in] _watched Item that handle that will handle the event.
/// \param[in] _event Qt event.
private: virtual bool sceneEventFilter(QGraphicsItem *_watched,
QEvent *_event);
/// \brief React to item changes notified by Qt.
/// \param[in] _change Qt change type, e.g. selected change, position
/// change.
/// \param[in] _value Value to changed to.
private: QVariant itemChange(GraphicsItemChange _change,
const QVariant &_value);
/// \brief Qt context menu event received on a mouse right click.
/// \param[in] Qt context menu event.
private: virtual void contextMenuEvent(
QGraphicsSceneContextMenuEvent *_event);
/// brief Emit size changed Qt signals.
private: virtual void SizeChanged();
/// brief Helper function for resizing the rect item.
/// \param[in] _x Change in x (width).
/// \param[in] _y Change in y (height).
private: void AdjustSize(double _x, double _y);
/// \brief Qt callback for opening the item inspector
private slots: virtual void OnOpenInspector();
/// \brief Qt callback when the item is being deleted.
private slots: virtual void OnDeleteItem();
/// \brief Width of rect item in pixels.
protected: double width;
/// \brief Height of rect item in pixels.
protected: double height;
/// \brief Actual width of rect item drawn in pixels.
protected: double drawingWidth;
/// \brief Actual height of rect item drawn in pixels.
protected: double drawingHeight;
/// \brief X origin of the rect item in pixels.
protected: double drawingOriginX;
/// \brief Y origin of the rect item in pixels.
protected: double drawingOriginY;
/// \brief Border color of the rect item.
protected: QColor borderColor;
/// \brief Rotation angle of the rect item in degrees.
protected: double rotationAngle;
/// \brief Z ordering of the rect item when idle (unselected.)
protected: int zValueIdle;
/// \brief Qt action for opening the inspector.
protected: QAction *openInspectorAct;
/// \brief Qt action for deleting the item.
protected: QAction *deleteItemAct;
/// \brief Mouse press position in pixel coordinates.
private: QPointF mousePressPos;
/// \brief Mouse press position in pixel coordinates.
private: int gridSpace;
/// \brief A list of grabber handles for this item. Four for corners and
/// four for edges, going clockwise with 0 being top left
private: std::vector<GrabberHandle *> grabbers;
/// \brief Rotate handle for rotating the rect item.
private: RotateHandle *rotateHandle;
/// \brief A list of resize cursors used when the mouse hovers over the
/// grabber handles.
private: std::vector<Qt::CursorShape> cursors;
/// \brieft Z ordering of the rect item when selected.
private: int zValueSelected;
/// \brieft Resize flag that controls how the rect item can be resized.
private: unsigned int resizeFlag;
};
/// \}
}
}
#endif
| 35.811808 | 78 | 0.661103 | [
"object",
"vector"
] |
a3756805f74aafd45ec0ea58812a8cb988481b31 | 7,218 | hpp | C++ | libs/pika/resource_partitioner/include/pika/resource_partitioner/partitioner.hpp | msimberg/pika | f86bc232bca88900dabd931de429f2d1cd3f4cc1 | [
"BSL-1.0"
] | null | null | null | libs/pika/resource_partitioner/include/pika/resource_partitioner/partitioner.hpp | msimberg/pika | f86bc232bca88900dabd931de429f2d1cd3f4cc1 | [
"BSL-1.0"
] | null | null | null | libs/pika/resource_partitioner/include/pika/resource_partitioner/partitioner.hpp | msimberg/pika | f86bc232bca88900dabd931de429f2d1cd3f4cc1 | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2017 Shoshana Jakobovits
//
// SPDX-License-Identifier: BSL-1.0
// 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)
#pragma once
#include <pika/local/config.hpp>
#include <pika/functional/function.hpp>
#include <pika/ini/ini.hpp>
#include <pika/resource_partitioner/detail/create_partitioner.hpp>
#include <pika/resource_partitioner/partitioner_fwd.hpp>
#include <pika/threading_base/scheduler_mode.hpp>
#include <cstddef>
#include <memory>
#include <string>
#include <utility>
#include <vector>
namespace pika { namespace resource {
///////////////////////////////////////////////////////////////////////////
class pu
{
static constexpr const std::size_t invalid_pu_id = std::size_t(-1);
public:
explicit pu(std::size_t id = invalid_pu_id, core* core = nullptr,
std::size_t thread_occupancy = 0)
: id_(id)
, core_(core)
, thread_occupancy_(thread_occupancy)
, thread_occupancy_count_(0)
{
}
std::size_t id() const
{
return id_;
}
private:
friend class core;
friend class numa_domain;
friend class resource::detail::partitioner;
std::vector<pu> pus_sharing_core();
std::vector<pu> pus_sharing_numa_domain();
std::size_t id_;
core* core_;
// indicates the number of threads that should run on this PU
// 0: this PU is not exposed by the affinity bindings
// 1: normal occupancy
// >1: oversubscription
std::size_t thread_occupancy_;
// counts number of threads bound to this PU
mutable std::size_t thread_occupancy_count_;
};
class core
{
static constexpr const std::size_t invalid_core_id = std::size_t(-1);
public:
explicit core(
std::size_t id = invalid_core_id, numa_domain* domain = nullptr)
: id_(id)
, domain_(domain)
{
}
std::vector<pu> const& pus() const
{
return pus_;
}
std::size_t id() const
{
return id_;
}
private:
std::vector<core> cores_sharing_numa_domain();
friend class pu;
friend class numa_domain;
friend class resource::detail::partitioner;
std::size_t id_;
numa_domain* domain_;
std::vector<pu> pus_;
};
class numa_domain
{
static constexpr const std::size_t invalid_numa_domain_id =
std::size_t(-1);
public:
explicit numa_domain(std::size_t id = invalid_numa_domain_id)
: id_(id)
{
}
std::vector<core> const& cores() const
{
return cores_;
}
std::size_t id() const
{
return id_;
}
private:
friend class pu;
friend class core;
friend class resource::detail::partitioner;
std::size_t id_;
std::vector<core> cores_;
};
///////////////////////////////////////////////////////////////////////////
namespace detail {
inline ::pika::resource::partitioner make_partitioner(
resource::partitioner_mode rpmode, pika::util::section rtcfg,
pika::threads::policies::detail::affinity_data affinity_data);
}
class partitioner
{
private:
friend ::pika::resource::partitioner detail::make_partitioner(
resource::partitioner_mode rpmode, pika::util::section rtcfg,
pika::threads::policies::detail::affinity_data affinity_data);
partitioner(resource::partitioner_mode rpmode,
pika::util::section rtcfg,
pika::threads::policies::detail::affinity_data affinity_data)
: partitioner_(
detail::create_partitioner(rpmode, rtcfg, affinity_data))
{
}
public:
///////////////////////////////////////////////////////////////////////
// Create one of the predefined thread pools
PIKA_EXPORT void create_thread_pool(std::string const& name,
scheduling_policy sched = scheduling_policy::unspecified,
pika::threads::policies::scheduler_mode =
pika::threads::policies::scheduler_mode::default_mode);
// Create a custom thread pool with a callback function
PIKA_EXPORT void create_thread_pool(
std::string const& name, scheduler_function scheduler_creation);
// allow the default pool to be renamed to something else
PIKA_EXPORT void set_default_pool_name(std::string const& name);
PIKA_EXPORT const std::string& get_default_pool_name() const;
///////////////////////////////////////////////////////////////////////
// Functions to add processing units to thread pools via
// the pu/core/numa_domain API
void add_resource(pika::resource::pu const& p,
std::string const& pool_name, std::size_t num_threads = 1)
{
add_resource(p, pool_name, true, num_threads);
}
PIKA_EXPORT void add_resource(pika::resource::pu const& p,
std::string const& pool_name, bool exclusive,
std::size_t num_threads = 1);
PIKA_EXPORT void add_resource(std::vector<pika::resource::pu> const& pv,
std::string const& pool_name, bool exclusive = true);
PIKA_EXPORT void add_resource(pika::resource::core const& c,
std::string const& pool_name, bool exclusive = true);
PIKA_EXPORT void add_resource(std::vector<pika::resource::core>& cv,
std::string const& pool_name, bool exclusive = true);
PIKA_EXPORT void add_resource(pika::resource::numa_domain const& nd,
std::string const& pool_name, bool exclusive = true);
PIKA_EXPORT void add_resource(
std::vector<pika::resource::numa_domain> const& ndv,
std::string const& pool_name, bool exclusive = true);
// Access all available NUMA domains
PIKA_EXPORT std::vector<numa_domain> const& numa_domains() const;
// Returns the threads requested at startup --pika:threads=cores
// for example will return the number actually created
PIKA_EXPORT std::size_t get_number_requested_threads();
// return the topology object managed by the internal partitioner
PIKA_EXPORT pika::threads::topology const& get_topology() const;
// Does initialization of all resources and internal data of the
// resource partitioner called in pika_init
PIKA_EXPORT void configure_pools();
private:
detail::partitioner& partitioner_;
};
namespace detail {
::pika::resource::partitioner make_partitioner(
resource::partitioner_mode rpmode, pika::util::section rtcfg,
pika::threads::policies::detail::affinity_data affinity_data)
{
return ::pika::resource::partitioner(rpmode, rtcfg, affinity_data);
}
} // namespace detail
}} // namespace pika::resource
| 33.572093 | 80 | 0.597672 | [
"object",
"vector"
] |
a376b23d269d0f64768d6b44342b8f22ba864158 | 583 | cpp | C++ | Codeforces/ITMO Academy/Z-function/Step 2/1.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | Codeforces/ITMO Academy/Z-function/Step 2/1.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | Codeforces/ITMO Academy/Z-function/Step 2/1.cpp | LeKSuS-04/Competitive-Programming | fbc86a8c6febeef72587a8f94135e92197e1f99e | [
"WTFPL"
] | null | null | null | /* A. Z-функция (простая версия) */
// https://codeforces.com/edu/course/2/lesson/3/2/practice/contest/272261/problem/A
// Date: 20.08.2021 07:31
// Run time: 31 ms
// Memory: 3700 KB
// Verdict: AC
#include <iostream>
#include <string>
#include <vector>
using namespace std;
vector<int> z;
void get_z(string s) {
z.assign(s.size(), 0);
for (int i = 1; i < s.size(); i++) {
while (z[i] + i < s.size() && s[z[i]] == s[z[i] + i]) ++z[i];
}
}
int main() {
string s;
cin >> s;
get_z(s);
for (int i = 0; i < z.size(); i++) cout << z[i] << " ";
} | 19.433333 | 83 | 0.538593 | [
"vector"
] |
a37860c2c4379708f85d44f21813fef2c2e31a30 | 1,844 | cpp | C++ | cds/partial_sums.cpp | echizentm/CompactDataStructures | f7a7ab95f7353440dc4b66caeb07448b35b743fe | [
"Apache-2.0"
] | 2 | 2017-01-29T16:06:48.000Z | 2017-04-11T07:58:08.000Z | cds/partial_sums.cpp | echizentm/CompactDataStructures | f7a7ab95f7353440dc4b66caeb07448b35b743fe | [
"Apache-2.0"
] | null | null | null | cds/partial_sums.cpp | echizentm/CompactDataStructures | f7a7ab95f7353440dc4b66caeb07448b35b743fe | [
"Apache-2.0"
] | null | null | null | #include <algorithm>
#include "partial_sums.h"
namespace cds {
using namespace std;
partial_sums::partial_sums(uint64_t length, uint64_t rate, uint64_t size, bool is_rapid)
: fixed_length_vector(length, size, is_rapid) {
this->rate = rate;
this->resize(size);
}
void partial_sums::resize(uint64_t size) {
fixed_length_vector::resize(size);
this->samples.resize(
(size + this->rate - 2) / this->rate + 1,
(this->samples.size() > 0) ? *(this->samples.rbegin()) : 0
);
}
uint64_t partial_sums::vector_size() const {
return fixed_length_vector::vector_size() + this->samples.size();
}
void partial_sums::write(uint64_t index, uint64_t value) {
uint64_t pos = (index + this->rate - 1) / this->rate;
while (pos < this->samples.size()) {
this->samples[pos] += (value - this->read(index));
pos++;
}
fixed_length_vector::write(index, value);
}
uint64_t partial_sums::sum(uint64_t index) const {
uint64_t pos = index / this->rate;
uint64_t sum = this->samples[pos];
pos = pos * this->rate + 1;
while (pos <= index) {
sum += this->read(pos);
pos++;
}
return sum;
}
uint64_t partial_sums::search(uint64_t value) const {
if (value <= *(this->samples.begin())) {
return 0;
}
vector<uint64_t>::const_iterator it = lower_bound(
this->samples.begin(), this->samples.end(), value
);
it--;
uint64_t sum = *it;
uint64_t pos = distance(this->samples.begin(), it) * this->rate;
while (sum < value && pos < this->size) {
pos++;
sum += this->read(pos);
}
return pos;
}
}
| 27.522388 | 92 | 0.542842 | [
"vector"
] |
a37a7d797fd6e6dcb40765ffd5a870a971e03341 | 28,886 | cc | C++ | hybridse/src/passes/physical/group_and_sort_optimized.cc | jingchen2222/OpenMLDB | 1e5c6aa1bc4123f3deb952bebf0514e694462dfc | [
"Apache-2.0"
] | 36 | 2021-01-20T06:15:11.000Z | 2021-05-28T05:15:36.000Z | hybridse/src/passes/physical/group_and_sort_optimized.cc | 4paradigm/fedb | ca8ce048423984347783580baf81a9a8188c8502 | [
"Apache-2.0"
] | 33 | 2021-04-15T05:55:37.000Z | 2021-05-27T06:47:48.000Z | hybridse/src/passes/physical/group_and_sort_optimized.cc | jingchen2222/OpenMLDB | 1e5c6aa1bc4123f3deb952bebf0514e694462dfc | [
"Apache-2.0"
] | 13 | 2021-02-02T06:43:47.000Z | 2021-05-17T09:51:06.000Z | /*
* Copyright 2021 4paradigm
*
* 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 "passes/physical/group_and_sort_optimized.h"
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "vm/physical_op.h"
namespace hybridse {
namespace passes {
using hybridse::vm::DataProviderType;
using hybridse::vm::INVALID_POS;
using hybridse::vm::PhysicalDataProviderNode;
using hybridse::vm::PhysicalFilterNode;
using hybridse::vm::PhysicalGroupNode;
using hybridse::vm::PhysicalJoinNode;
using hybridse::vm::PhysicalOpType;
using hybridse::vm::PhysicalPartitionProviderNode;
using hybridse::vm::PhysicalProjectNode;
using hybridse::vm::PhysicalRenameNode;
using hybridse::vm::PhysicalRequestJoinNode;
using hybridse::vm::PhysicalRequestUnionNode;
using hybridse::vm::PhysicalSimpleProjectNode;
using hybridse::vm::PhysicalWindowAggrerationNode;
using hybridse::vm::ProjectType;
static bool ResolveColumnToSourceColumnName(const node::ColumnRefNode* col,
const SchemasContext* schemas_ctx,
std::string* source_name);
bool GroupAndSortOptimized::Transform(PhysicalOpNode* in,
PhysicalOpNode** output) {
*output = in;
switch (in->GetOpType()) {
case PhysicalOpType::kPhysicalOpGroupBy: {
PhysicalGroupNode* group_op = dynamic_cast<PhysicalGroupNode*>(in);
PhysicalOpNode* new_producer;
if (!GroupOptimized(group_op->schemas_ctx(),
group_op->GetProducer(0), &group_op->group_,
&new_producer)) {
return false;
}
if (!ResetProducer(plan_ctx_, group_op, 0, new_producer)) {
return false;
}
if (!group_op->Valid()) {
*output = group_op->producers()[0];
}
return true;
}
case PhysicalOpType::kPhysicalOpProject: {
auto project_op = dynamic_cast<PhysicalProjectNode*>(in);
if (ProjectType::kWindowAggregation == project_op->project_type_) {
auto window_agg_op =
dynamic_cast<PhysicalWindowAggrerationNode*>(project_op);
PhysicalOpNode* input = window_agg_op->GetProducer(0);
PhysicalOpNode* new_producer;
if (!window_agg_op->instance_not_in_window()) {
if (KeyAndOrderOptimized(input->schemas_ctx(), input,
&window_agg_op->window_.partition_,
&window_agg_op->window_.sort_,
&new_producer)) {
input = new_producer;
if (!ResetProducer(plan_ctx_, window_agg_op, 0,
input)) {
return false;
}
}
}
// must prepare for window join column infer
auto& window_joins = window_agg_op->window_joins();
auto& window_unions = window_agg_op->window_unions();
window_agg_op->InitJoinList(plan_ctx_);
auto& joined_op_list_ = window_agg_op->joined_op_list_;
if (!window_joins.Empty()) {
size_t join_idx = 0;
for (auto& window_join : window_joins.window_joins()) {
PhysicalOpNode* cur_joined = joined_op_list_[join_idx];
PhysicalOpNode* new_join_right;
if (JoinKeysOptimized(
cur_joined->schemas_ctx(), window_join.first,
&window_join.second, &new_join_right)) {
window_join.first = new_join_right;
}
join_idx += 1;
}
}
if (!window_unions.Empty()) {
for (auto& window_union : window_unions.window_unions_) {
PhysicalOpNode* new_producer;
if (KeyAndOrderOptimized(
window_union.first->schemas_ctx(),
window_union.first,
&window_union.second.partition_,
&window_union.second.sort_, &new_producer)) {
window_union.first = new_producer;
}
}
}
return true;
}
break;
}
case PhysicalOpType::kPhysicalOpRequestUnion: {
PhysicalRequestUnionNode* union_op =
dynamic_cast<PhysicalRequestUnionNode*>(in);
PhysicalOpNode* new_producer;
if (!union_op->instance_not_in_window()) {
if (KeysAndOrderFilterOptimized(
union_op->schemas_ctx(), union_op->GetProducer(1),
&union_op->window_.partition_,
&union_op->window_.index_key_, &union_op->window_.sort_,
&new_producer)) {
if (!ResetProducer(plan_ctx_, union_op, 1, new_producer)) {
return false;
}
}
}
if (!union_op->window_unions().Empty()) {
for (auto& window_union :
union_op->window_unions_.window_unions_) {
PhysicalOpNode* new_producer;
auto& window = window_union.second;
if (KeysAndOrderFilterOptimized(
window_union.first->schemas_ctx(),
window_union.first, &window.partition_,
&window.index_key_, &window.sort_, &new_producer)) {
window_union.first = new_producer;
}
}
}
return true;
}
case PhysicalOpType::kPhysicalOpRequestJoin: {
PhysicalRequestJoinNode* join_op =
dynamic_cast<PhysicalRequestJoinNode*>(in);
PhysicalOpNode* new_producer;
// Optimized Right Table Partition
if (!JoinKeysOptimized(join_op->schemas_ctx(),
join_op->GetProducer(1), &join_op->join_,
&new_producer)) {
return false;
}
if (!ResetProducer(plan_ctx_, join_op, 1, new_producer)) {
return false;
}
return true;
}
case PhysicalOpType::kPhysicalOpJoin: {
PhysicalJoinNode* join_op = dynamic_cast<PhysicalJoinNode*>(in);
PhysicalOpNode* new_producer;
// Optimized Right Table Partition
if (!JoinKeysOptimized(join_op->schemas_ctx(),
join_op->GetProducer(1), &join_op->join_,
&new_producer)) {
return false;
}
if (!ResetProducer(plan_ctx_, join_op, 1, new_producer)) {
return false;
}
return true;
}
case PhysicalOpType::kPhysicalOpFilter: {
PhysicalFilterNode* filter_op =
dynamic_cast<PhysicalFilterNode*>(in);
PhysicalOpNode* new_producer;
if (FilterOptimized(filter_op->schemas_ctx(),
filter_op->GetProducer(0), &filter_op->filter_,
&new_producer)) {
if (!ResetProducer(plan_ctx_, filter_op, 0, new_producer)) {
return false;
}
}
}
default: {
return false;
}
}
return false;
}
/**
* optimize keys on condition. Remove keys from upper node if key match indexes
* defined in table schema `left_key` & `index_key` is required, `right_key` is
* optional
* if `right_key` is not nullptr:
* - `left_key`, `index_key`, `right_key` corresponding to
* `Filter::left_key_`, `Filter::index_key_`, `Filter::right_key_`
* otherwise:
* - `left_key`, `index_key` corresponding to Key group & Key hash
*/
bool GroupAndSortOptimized::KeysOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Key* left_key,
Key* index_key, Key* right_key, Sort* sort, PhysicalOpNode** new_in) {
if (nullptr == left_key || nullptr == index_key || !left_key->ValidKey()) {
return false;
}
if (right_key != nullptr && !right_key->ValidKey()) {
return false;
}
if (PhysicalOpType::kPhysicalOpDataProvider == in->GetOpType()) {
auto scan_op = dynamic_cast<PhysicalDataProviderNode*>(in);
// Do not optimize with Request DataProvider (no index has been provided)
if (DataProviderType::kProviderTypeRequest == scan_op->provider_type_) {
return false;
}
if (DataProviderType::kProviderTypeTable == scan_op->provider_type_ ||
DataProviderType::kProviderTypePartition == scan_op->provider_type_) {
const node::ExprListNode* right_partition =
right_key == nullptr ? left_key->keys() : right_key->keys();
size_t key_num = right_partition->GetChildNum();
std::vector<bool> bitmap(key_num, false);
node::ExprListNode order_values;
PhysicalPartitionProviderNode* partition_op = nullptr;
std::string index_name;
if (DataProviderType::kProviderTypeTable == scan_op->provider_type_) {
// Apply key columns and order column optimization with all indexes binding to scan_op->table_handler_
// Return false if fail to find an appropriate index
if (!TransformKeysAndOrderExpr(root_schemas_ctx, right_partition,
nullptr == sort ? nullptr : sort->orders_, scan_op->table_handler_,
&index_name, &bitmap)) {
return false;
}
Status status = plan_ctx_->CreateOp<PhysicalPartitionProviderNode>(&partition_op, scan_op, index_name);
if (!status.isOK()) {
LOG(WARNING) << "Fail to create partition op: " << status;
return false;
}
} else {
partition_op = dynamic_cast<PhysicalPartitionProviderNode*>(scan_op);
index_name = partition_op->index_name_;
// Apply key columns and order column optimization with given index name
// Return false if given index do not match the keys and order column
if (!TransformKeysAndOrderExpr(root_schemas_ctx, right_partition,
nullptr == sort ? nullptr : sort->orders_, scan_op->table_handler_,
&index_name, &bitmap)) {
return false;
}
}
auto new_left_keys = node_manager_->MakeExprList();
auto new_right_keys = node_manager_->MakeExprList();
auto new_index_keys = node_manager_->MakeExprList();
for (size_t i = 0; i < bitmap.size(); ++i) {
auto left = left_key->keys()->GetChild(i);
if (bitmap[i]) {
new_index_keys->AddChild(left);
} else {
new_left_keys->AddChild(left);
if (right_key != nullptr) {
new_right_keys->AddChild(
right_key->keys()->GetChild(i));
}
}
}
if (right_key != nullptr) {
right_key->set_keys(new_right_keys);
}
index_key->set_keys(new_index_keys);
left_key->set_keys(new_left_keys);
// Clear order expr list if we optimized orders
if (nullptr != sort && nullptr != sort->orders_ && nullptr != sort->orders_->GetOrderExpression(0)) {
auto first_order_expression = sort->orders_->GetOrderExpression(0);
sort->set_orders(dynamic_cast<node::OrderByNode*>(
node_manager_->MakeOrderByNode(
node_manager_->MakeExprList(
node_manager_->MakeOrderExpression(nullptr, first_order_expression->is_asc())))));
}
*new_in = partition_op;
return true;
}
} else if (PhysicalOpType::kPhysicalOpSimpleProject == in->GetOpType()) {
auto simple_project = dynamic_cast<PhysicalSimpleProjectNode*>(in);
PhysicalOpNode* new_depend;
if (!KeysOptimized(root_schemas_ctx, simple_project->producers()[0],
left_key, index_key, right_key, sort, &new_depend)) {
return false;
}
PhysicalSimpleProjectNode* new_simple_op = nullptr;
Status status = plan_ctx_->CreateOp<PhysicalSimpleProjectNode>(
&new_simple_op, new_depend, simple_project->project());
if (!status.isOK()) {
LOG(WARNING) << "Fail to create simple project op: " << status;
return false;
}
*new_in = new_simple_op;
return true;
} else if (PhysicalOpType::kPhysicalOpRename == in->GetOpType()) {
PhysicalOpNode* new_depend;
if (!KeysOptimized(root_schemas_ctx, in->producers()[0], left_key,
index_key, right_key, sort, &new_depend)) {
return false;
}
PhysicalRenameNode* new_op = nullptr;
Status status = plan_ctx_->CreateOp<PhysicalRenameNode>(
&new_op, new_depend, dynamic_cast<PhysicalRenameNode*>(in)->name_);
if (!status.isOK()) {
LOG(WARNING) << "Fail to create rename op: " << status;
return false;
}
*new_in = new_op;
return true;
}
return false;
}
bool GroupAndSortOptimized::KeysFilterOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Key* group,
Key* hash, PhysicalOpNode** new_in) {
return KeysAndOrderFilterOptimized(root_schemas_ctx, in, group, hash,
nullptr, new_in);
}
bool GroupAndSortOptimized::KeysAndOrderFilterOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Key* group,
Key* hash, Sort* sort, PhysicalOpNode** new_in) {
return KeysOptimized(root_schemas_ctx, in, group, hash, nullptr, sort,
new_in);
}
bool GroupAndSortOptimized::JoinKeysOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Join* join,
PhysicalOpNode** new_in) {
if (nullptr == join) {
return false;
}
return FilterAndOrderOptimized(root_schemas_ctx, in, join,
&join->right_sort_, new_in);
}
bool GroupAndSortOptimized::FilterOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Filter* filter,
PhysicalOpNode** new_in) {
return FilterAndOrderOptimized(root_schemas_ctx, in, filter, nullptr,
new_in);
}
bool GroupAndSortOptimized::FilterAndOrderOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Filter* filter,
Sort* sort, PhysicalOpNode** new_in) {
return KeysOptimized(root_schemas_ctx, in, &filter->left_key_,
&filter->index_key_, &filter->right_key_, sort,
new_in);
}
bool GroupAndSortOptimized::GroupOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Key* group,
PhysicalOpNode** new_in) {
return KeyAndOrderOptimized(root_schemas_ctx, in, group, nullptr, new_in);
}
bool GroupAndSortOptimized::KeyAndOrderOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Key* group,
Sort* sort, PhysicalOpNode** new_in) {
Key mock_key;
return KeysAndOrderFilterOptimized(root_schemas_ctx, in, group, &mock_key,
sort, new_in);
}
bool GroupAndSortOptimized::SortOptimized(
const SchemasContext* root_schemas_ctx, PhysicalOpNode* in, Sort* sort) {
if (nullptr == sort) {
return false;
}
if (PhysicalOpType::kPhysicalOpDataProvider == in->GetOpType()) {
auto scan_op = dynamic_cast<PhysicalDataProviderNode*>(in);
if (DataProviderType::kProviderTypePartition !=
scan_op->provider_type_) {
return false;
}
auto partition_provider =
dynamic_cast<PhysicalPartitionProviderNode*>(scan_op);
const node::OrderByNode* new_orders = nullptr;
auto& index_hint = partition_provider->table_handler_->GetIndex();
std::string index_name = partition_provider->index_name_;
auto index_st = index_hint.at(index_name);
TransformOrderExpr(root_schemas_ctx, sort->orders(),
*(scan_op->table_handler_->GetSchema()), index_st,
&new_orders);
sort->set_orders(new_orders);
return true;
} else if (PhysicalOpType::kPhysicalOpSimpleProject == in->GetOpType()) {
auto simple_project = dynamic_cast<PhysicalSimpleProjectNode*>(in);
return SortOptimized(root_schemas_ctx, simple_project->producers()[0],
sort);
} else if (PhysicalOpType::kPhysicalOpRename == in->GetOpType()) {
return SortOptimized(root_schemas_ctx, in->producers()[0], sort);
}
return false;
}
bool GroupAndSortOptimized::TransformGroupExpr(
const SchemasContext* root_schemas_ctx, const node::ExprListNode* groups,
std::shared_ptr<TableHandler> table_handler, std::string* index_name,
std::vector<bool>* output_bitmap) {
return TransformKeysAndOrderExpr(root_schemas_ctx, groups, nullptr,
table_handler, index_name, output_bitmap);
}
bool GroupAndSortOptimized::TransformKeysAndOrderExpr(
const SchemasContext* root_schemas_ctx, const node::ExprListNode* groups,
const node::OrderByNode* order, std::shared_ptr<TableHandler> table_handler,
std::string* index_name, std::vector<bool>* output_bitmap) {
if (nullptr == groups || nullptr == output_bitmap ||
nullptr == index_name) {
DLOG(WARNING) << "fail to transform keys expr : key expr or output "
"or index_name ptr is null";
return false;
}
if (nullptr == order) {
DLOG(INFO) << "keys optimized: " << node::ExprString(groups);
} else {
DLOG(INFO) << "keys and order optimized: keys="
<< node::ExprString(groups)
<< ", order=" << node::ExprString(order);
}
std::vector<std::string> columns;
std::vector<std::string> order_columns;
std::map<size_t, size_t> result_bitmap_mapping;
for (size_t i = 0; i < groups->children_.size(); ++i) {
auto group = groups->children_[i];
switch (group->expr_type_) {
case node::kExprColumnRef: {
auto column = dynamic_cast<node::ColumnRefNode*>(group);
std::string source_column_name;
if (!ResolveColumnToSourceColumnName(column, root_schemas_ctx,
&source_column_name)) {
return false;
}
result_bitmap_mapping[columns.size()] = i;
columns.push_back(source_column_name);
break;
}
default: {
break;
}
}
}
if (nullptr != order) {
for (size_t i = 0; i < order->order_expressions()->GetChildNum(); ++i) {
auto expr = order->GetOrderExpressionExpr(i);
if (nullptr != expr && expr->GetExprType() == node::kExprColumnRef) {
auto column = dynamic_cast<const node::ColumnRefNode*>(expr);
std::string source_column_name;
if (!ResolveColumnToSourceColumnName(column, root_schemas_ctx,
&source_column_name)) {
return false;
}
order_columns.push_back(source_column_name);
}
}
}
if (columns.empty()) {
return false;
}
std::vector<bool> match_bitmap;
std::vector<bool> state_bitmap(columns.size(), true);
if (!MatchBestIndex(columns, order_columns, table_handler, &state_bitmap,
index_name, &match_bitmap)) {
return false;
}
if (match_bitmap.size() != columns.size()) {
return false;
}
for (size_t i = 0; i < columns.size(); ++i) {
if (match_bitmap[i]) {
size_t origin_idx = result_bitmap_mapping[i];
(*output_bitmap)[origin_idx] = true;
}
}
return true;
}
// When *index_name is empty, return true if we can find the best index for key columns and order column
// When *index_name isn't empty, return true if the given index_name match key columns and order column
bool GroupAndSortOptimized::MatchBestIndex(
const std::vector<std::string>& columns,
const std::vector<std::string>& order_columns,
std::shared_ptr<TableHandler> table_handler, std::vector<bool>* bitmap_ptr,
std::string* index_name, std::vector<bool>* index_bitmap) {
if (nullptr == bitmap_ptr || nullptr == index_name) {
LOG(WARNING)
<< "fail to match best index: bitmap or index_name ptr is null";
return false;
}
if (!table_handler) {
LOG(WARNING) << "fail to match best index: table is null";
return false;
}
auto& index_hint = table_handler->GetIndex();
auto schema = table_handler->GetSchema();
if (nullptr == schema) {
LOG(WARNING) << "fail to match best index: table schema null";
return false;
}
std::set<std::string> column_set;
auto& bitmap = *bitmap_ptr;
for (size_t i = 0; i < columns.size(); ++i) {
if (bitmap[i]) {
column_set.insert(columns[i]);
}
}
if (order_columns.size() > 1) {
LOG(WARNING) << "fail to match best index: non-support multi ts index";
return false;
}
// Go through the all indexs to find out index meet the requirements.
// Notice: only deal with index specific by given index name when (*index_name) is non-emtpy
for (auto iter = index_hint.cbegin(); iter != index_hint.cend(); iter++) {
IndexSt index = iter->second;
if (!(*index_name).empty() && index.name != *index_name) {
// if (*index_name) isn't empty
// skip index whose index.name != given index_name
continue;
}
if (!order_columns.empty()) {
if (index.ts_pos == INVALID_POS) {
continue;
}
auto& ts_column = schema->Get(index.ts_pos);
if (ts_column.name() != order_columns[0]) {
continue;
}
}
std::set<std::string> keys;
for (auto key_iter = index.keys.cbegin(); key_iter != index.keys.cend();
key_iter++) {
keys.insert(key_iter->name);
}
if (column_set == keys) {
*index_name = index.name;
*index_bitmap = bitmap;
return true;
}
}
std::string best_index_name;
std::vector<bool> best_index_bitmap;
bool succ = false;
for (size_t i = 0; i < bitmap.size(); ++i) {
if (bitmap[i]) {
bitmap[i] = false;
std::string name;
std::vector<bool> sub_best_bitmap;
if (MatchBestIndex(columns, order_columns, table_handler,
bitmap_ptr, &name, &sub_best_bitmap)) {
succ = true;
if (best_index_name.empty()) {
best_index_name = name;
best_index_bitmap = sub_best_bitmap;
} else {
auto org_index = index_hint.at(best_index_name);
auto new_index = index_hint.at(name);
if (org_index.keys.size() < new_index.keys.size()) {
best_index_name = name;
best_index_bitmap = sub_best_bitmap;
}
}
}
bitmap[i] = true;
}
}
*index_name = best_index_name;
*index_bitmap = best_index_bitmap;
return succ;
}
bool GroupAndSortOptimized::TransformOrderExpr(
const SchemasContext* schemas_ctx, const node::OrderByNode* order,
const Schema& schema, const IndexSt& index_st,
const node::OrderByNode** output) {
*output = order;
if (nullptr == order || nullptr == output) {
DLOG(WARNING)
<< "fail to optimize order expr : order expr or output is null";
return false;
}
if (index_st.ts_pos == INVALID_POS) {
DLOG(WARNING) << "not set ts col";
return false;
}
auto& ts_column = schema.Get(index_st.ts_pos);
*output = order;
int succ_match = -1;
for (size_t i = 0; i < order->order_expressions()->GetChildNum(); ++i) {
auto expr = order->GetOrderExpressionExpr(i);
if (nullptr != expr && expr->GetExprType() == node::kExprColumnRef) {
auto column = dynamic_cast<const node::ColumnRefNode*>(expr);
std::string source_column_name;
if (ResolveColumnToSourceColumnName(column, schemas_ctx,
&source_column_name)) {
if (ts_column.name() == source_column_name) {
succ_match = i;
break;
}
}
}
}
if (succ_match >= 0) {
node::ExprListNode* expr_list = node_manager_->MakeExprList();
for (size_t i = 0; i < order->order_expressions()->GetChildNum(); ++i) {
if (static_cast<size_t>(succ_match) != i) {
expr_list->AddChild(order->order_expressions()->GetChild(i));
}
}
*output = dynamic_cast<node::OrderByNode*>(
node_manager_->MakeOrderByNode(expr_list));
return true;
} else {
return false;
}
}
/**
* Resolve column reference to possible source table's column name
*/
static bool ResolveColumnToSourceColumnName(const node::ColumnRefNode* col,
const SchemasContext* schemas_ctx,
std::string* source_name) {
// use detailed column resolve utility
size_t column_id;
int path_idx;
size_t child_column_id;
size_t source_column_id;
const PhysicalOpNode* source;
Status status = schemas_ctx->ResolveColumnID(col->GetDBName(),
col->GetRelationName(), col->GetColumnName(), &column_id, &path_idx,
&child_column_id, &source_column_id, &source);
// try loose the relation
if (!status.isOK() && !col->GetRelationName().empty()) {
status = schemas_ctx->ResolveColumnID(
col->GetDBName(), col->GetRelationName(), col->GetColumnName(),
&column_id, &path_idx, &child_column_id,
&source_column_id, &source);
}
if (!status.isOK()) {
LOG(WARNING) << "Illegal index column: " << col->GetExprString();
return false;
}
if (source == nullptr ||
source->GetOpType() != PhysicalOpType::kPhysicalOpDataProvider) {
LOG(WARNING) << "Index column is not from any source table: "
<< col->GetExprString();
return false;
}
status = source->schemas_ctx()->ResolveColumnNameByID(source_column_id,
source_name);
if (!status.isOK()) {
LOG(WARNING) << "Illegal source column id #" << source_column_id
<< " for index column " << col->GetExprString();
return false;
}
return true;
}
} // namespace passes
} // namespace hybridse
| 41.622478 | 119 | 0.566053 | [
"vector",
"transform"
] |
a37ba67a800c56eb8f30e510fca8e4915c293431 | 16,082 | cpp | C++ | lammps-master/src/USER-SMD/fix_smd_wall_surface.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/USER-SMD/fix_smd_wall_surface.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/USER-SMD/fix_smd_wall_surface.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"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 authors: Mike Parks (SNL), Ezwanur Rahman, J.T. Foster (UTSA)
------------------------------------------------------------------------- */
#include <cmath>
#include <cstring>
#include <cstdio>
#include <Eigen/Eigen>
#include "fix_smd_wall_surface.h"
#include "atom.h"
#include "domain.h"
#include "force.h"
#include "comm.h"
#include "update.h"
#include "neighbor.h"
#include "neigh_list.h"
#include "neigh_request.h"
#include "pair.h"
#include "lattice.h"
#include "memory.h"
#include "error.h"
#include "atom_vec.h"
using namespace LAMMPS_NS;
using namespace FixConst;
using namespace Eigen;
using namespace std;
#define DELTA 16384
#define EPSILON 1.0e-6
/* ---------------------------------------------------------------------- */
FixSMDWallSurface::FixSMDWallSurface(LAMMPS *lmp, int narg, char **arg) :
Fix(lmp, narg, arg) {
restart_global = 0;
restart_peratom = 0;
first = 1;
//atom->add_callback(0);
//atom->add_callback(1);
if (narg != 6)
error->all(FLERR, "Illegal number of arguments for fix smd/wall_surface");
filename = strdup(arg[3]);
wall_particle_type = force->inumeric(FLERR, arg[4]);
wall_molecule_id = force->inumeric(FLERR, arg[5]);
if (wall_molecule_id < 65535) {
error->one(FLERR, "wall molcule id must be >= 65535\n");
}
if (comm->me == 0) {
printf("\n>>========>>========>>========>>========>>========>>========>>========>>========\n");
printf("fix smd/wall_surface reads trianglulated surface from file: %s\n", filename);
printf("fix smd/wall_surface has particle type %d \n", wall_particle_type);
printf("fix smd/wall_surface has molecule id %d \n", wall_molecule_id);
printf(">>========>>========>>========>>========>>========>>========>>========>>========\n");
}
}
/* ---------------------------------------------------------------------- */
FixSMDWallSurface::~FixSMDWallSurface() {
free(filename);
filename = NULL;
// unregister this fix so atom class doesn't invoke it any more
//atom->delete_callback(id, 0);
//atom->delete_callback(id, 1);
}
/* ---------------------------------------------------------------------- */
int FixSMDWallSurface::setmask() {
int mask = 0;
return mask;
}
/* ---------------------------------------------------------------------- */
void FixSMDWallSurface::init() {
if (!first)
return;
}
/* ----------------------------------------------------------------------
For minimization: setup as with dynamics
------------------------------------------------------------------------- */
void FixSMDWallSurface::min_setup(int vflag) {
setup(vflag);
}
/* ----------------------------------------------------------------------
create initial list of neighbor partners via call to neighbor->build()
must be done in setup (not init) since fix init comes before neigh init
------------------------------------------------------------------------- */
void FixSMDWallSurface::setup(int /*vflag*/) {
if (!first)
return;
first = 0;
// set bounds for my proc
// if periodic and I am lo/hi proc, adjust bounds by EPSILON
// insures all data atoms will be owned even with round-off
int triclinic = domain->triclinic;
double epsilon[3];
if (triclinic)
epsilon[0] = epsilon[1] = epsilon[2] = EPSILON;
else {
epsilon[0] = domain->prd[0] * EPSILON;
epsilon[1] = domain->prd[1] * EPSILON;
epsilon[2] = domain->prd[2] * EPSILON;
}
if (triclinic == 0) {
sublo[0] = domain->sublo[0];
subhi[0] = domain->subhi[0];
sublo[1] = domain->sublo[1];
subhi[1] = domain->subhi[1];
sublo[2] = domain->sublo[2];
subhi[2] = domain->subhi[2];
} else {
sublo[0] = domain->sublo_lamda[0];
subhi[0] = domain->subhi_lamda[0];
sublo[1] = domain->sublo_lamda[1];
subhi[1] = domain->subhi_lamda[1];
sublo[2] = domain->sublo_lamda[2];
subhi[2] = domain->subhi_lamda[2];
}
if (comm->layout != Comm::LAYOUT_TILED) {
if (domain->xperiodic) {
if (comm->myloc[0] == 0)
sublo[0] -= epsilon[0];
if (comm->myloc[0] == comm->procgrid[0] - 1)
subhi[0] += epsilon[0];
}
if (domain->yperiodic) {
if (comm->myloc[1] == 0)
sublo[1] -= epsilon[1];
if (comm->myloc[1] == comm->procgrid[1] - 1)
subhi[1] += epsilon[1];
}
if (domain->zperiodic) {
if (comm->myloc[2] == 0)
sublo[2] -= epsilon[2];
if (comm->myloc[2] == comm->procgrid[2] - 1)
subhi[2] += epsilon[2];
}
} else {
if (domain->xperiodic) {
if (comm->mysplit[0][0] == 0.0)
sublo[0] -= epsilon[0];
if (comm->mysplit[0][1] == 1.0)
subhi[0] += epsilon[0];
}
if (domain->yperiodic) {
if (comm->mysplit[1][0] == 0.0)
sublo[1] -= epsilon[1];
if (comm->mysplit[1][1] == 1.0)
subhi[1] += epsilon[1];
}
if (domain->zperiodic) {
if (comm->mysplit[2][0] == 0.0)
sublo[2] -= epsilon[2];
if (comm->mysplit[2][1] == 1.0)
subhi[2] += epsilon[2];
}
}
read_triangles(0);
}
/* ----------------------------------------------------------------------
function to determine number of values in a text line
------------------------------------------------------------------------- */
int FixSMDWallSurface::count_words(const char *line) {
int n = strlen(line) + 1;
char *copy;
memory->create(copy, n, "atom:copy");
strcpy(copy, line);
char *ptr;
if ((ptr = strchr(copy, '#')))
*ptr = '\0';
if (strtok(copy, " \t\n\r\f") == NULL) {
memory->destroy(copy);
return 0;
}
n = 1;
while (strtok(NULL, " \t\n\r\f"))
n++;
memory->destroy(copy);
return n;
}
/* ----------------------------------------------------------------------
size of atom nlocal's restart data
------------------------------------------------------------------------- */
void FixSMDWallSurface::read_triangles(int pass) {
double coord[3];
int nlocal_previous = atom->nlocal;
int ilocal = nlocal_previous;
int m;
int me;
bigint natoms_previous = atom->natoms;
Vector3d *vert;
vert = new Vector3d[3];
Vector3d normal, center;
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
char str[128];
snprintf(str,128, "Cannot open file %s", filename);
error->one(FLERR, str);
}
MPI_Comm_rank(world, &me);
if (me == 0) {
if (screen) {
if (pass == 0) {
printf("\n>>========>>========>>========>>========>>========>>========>>========>>========\n");
fprintf(screen, " scanning triangle pairs ...\n");
} else {
fprintf(screen, " reading triangle pairs ...\n");
}
}
if (logfile) {
if (pass == 0) {
fprintf(logfile, " scanning triangle pairs ...\n");
} else {
fprintf(logfile, " reading triangle pairs ...\n");
}
}
}
char line[256];
char *retpointer;
char **values;
int nwords;
// read STL solid name
retpointer = fgets(line, sizeof(line), fp);
if (retpointer == NULL) {
error->one(FLERR,"error reading number of triangle pairs");
}
nwords = count_words(line);
if (nwords < 1) {
error->one(FLERR,"first line of file is incorrect");
}
// values = new char*[nwords];
// values[0] = strtok(line, " \t\n\r\f");
// if (values[0] == NULL)
// error->all(FLERR, "Incorrect atom format in data file");
// for (m = 1; m < nwords; m++) {
// values[m] = strtok(NULL, " \t\n\r\f");
// if (values[m] == NULL)
// error->all(FLERR, "Incorrect atom format in data file");
// }
// delete[] values;
//
// if (comm->me == 0) {
// cout << "STL file contains solid body with name: " << values[1] << endl;
// }
// iterate over STL facets util end of body is reached
while (fgets(line, sizeof(line), fp)) { // read a line, should be the facet line
// evaluate facet line
nwords = count_words(line);
if (nwords != 5) {
//sprintf(str, "found end solid line");
//error->message(FLERR, str);
break;
} else {
// should be facet line
}
values = new char*[nwords];
values[0] = strtok(line, " \t\n\r\f");
if (values[0] == NULL)
error->all(FLERR, "Incorrect atom format in data file");
for (m = 1; m < nwords; m++) {
values[m] = strtok(NULL, " \t\n\r\f");
if (values[m] == NULL)
error->all(FLERR, "Incorrect atom format in data file");
}
normal << force->numeric(FLERR, values[2]), force->numeric(FLERR, values[3]), force->numeric(FLERR, values[4]);
//cout << "normal is " << normal << endl;
delete[] values;
// read outer loop line
retpointer = fgets(line, sizeof(line), fp);
if (retpointer == NULL) {
error->one(FLERR, "error reading outer loop");
}
nwords = count_words(line);
if (nwords != 2) {
error->one(FLERR,"error reading outer loop");
}
// read vertex lines
for (int k = 0; k < 3; k++) {
retpointer = fgets(line, sizeof(line), fp);
if (retpointer == NULL) {
error->one(FLERR,"error reading vertex line");
}
nwords = count_words(line);
if (nwords != 4) {
error->one(FLERR,"error reading vertex line");
}
values = new char*[nwords];
values[0] = strtok(line, " \t\n\r\f");
if (values[0] == NULL)
error->all(FLERR,"Incorrect vertex line");
for (m = 1; m < nwords; m++) {
values[m] = strtok(NULL, " \t\n\r\f");
if (values[m] == NULL)
error->all(FLERR, "Incorrect vertex line");
}
vert[k] << force->numeric(FLERR, values[1]), force->numeric(FLERR, values[2]), force->numeric(FLERR, values[3]);
//cout << "vertex is " << vert[k] << endl;
//printf("%s %s %s\n", values[1], values[2], values[3]);
delete[] values;
//exit(1);
}
// read end loop line
retpointer = fgets(line, sizeof(line), fp);
if (retpointer == NULL) {
error->one(FLERR, "error reading endloop");
}
nwords = count_words(line);
if (nwords != 1) {
error->one(FLERR,"error reading endloop");
}
// read end facet line
retpointer = fgets(line, sizeof(line), fp);
if (retpointer == NULL) {
error->one(FLERR,"error reading endfacet");
}
nwords = count_words(line);
if (nwords != 1) {
error->one(FLERR,"error reading endfacet");
}
// now we have a normal and three vertices ... proceed with adding triangle
center = (vert[0] + vert[1] + vert[2]) / 3.0;
// cout << "center is " << center << endl;
double r1 = (center - vert[0]).norm();
double r2 = (center - vert[1]).norm();
double r3 = (center - vert[2]).norm();
double r = MAX(r1, r2);
r = MAX(r, r3);
/*
* if atom/molecule is in my subbox, create it
* ... use x0 to hold triangle normal.
* ... use smd_data_9 to hold the three vertices
* ... use x to hold triangle center
* ... radius is the mmaximal distance from triangle center to all vertices
*/
// printf("coord: %f %f %f\n", coord[0], coord[1], coord[2]);
// printf("sublo: %f %f %f\n", sublo[0], sublo[1], sublo[2]);
// printf("subhi: %f %f %f\n", subhi[0], subhi[1], subhi[2]);
//printf("ilocal = %d\n", ilocal);
if (center(0) >= sublo[0] && center(0) < subhi[0] && center(1) >= sublo[1] && center(1) < subhi[1] && center(2) >= sublo[2]
&& center(2) < subhi[2]) {
//printf("******* KERATIN nlocal=%d ***\n", nlocal);
coord[0] = center(0);
coord[1] = center(1);
coord[2] = center(2);
atom->avec->create_atom(wall_particle_type, coord);
/*
* need to initialize pointers to atom vec arrays here, because they could have changed
* due to calling grow() in create_atoms() above;
*/
tagint *mol = atom->molecule;
int *type = atom->type;
double *radius = atom->radius;
double *contact_radius = atom->contact_radius;
double **smd_data_9 = atom->smd_data_9;
double **x0 = atom->x0;
radius[ilocal] = r; //ilocal;
contact_radius[ilocal] = r; //ilocal;
mol[ilocal] = wall_molecule_id;
type[ilocal] = wall_particle_type;
x0[ilocal][0] = normal(0);
x0[ilocal][1] = normal(1);
x0[ilocal][2] = normal(2);
smd_data_9[ilocal][0] = vert[0](0);
smd_data_9[ilocal][1] = vert[0](1);
smd_data_9[ilocal][2] = vert[0](2);
smd_data_9[ilocal][3] = vert[1](0);
smd_data_9[ilocal][4] = vert[1](1);
smd_data_9[ilocal][5] = vert[1](2);
smd_data_9[ilocal][6] = vert[2](0);
smd_data_9[ilocal][7] = vert[2](1);
smd_data_9[ilocal][8] = vert[2](2);
ilocal++;
}
}
// set new total # of atoms and error check
bigint nblocal = atom->nlocal;
MPI_Allreduce(&nblocal, &atom->natoms, 1, MPI_LMP_BIGINT, MPI_SUM, world);
if (atom->natoms < 0 || atom->natoms >= MAXBIGINT)
error->all(FLERR, "Too many total atoms");
// add IDs for newly created atoms
// check that atom IDs are valid
if (atom->tag_enable)
atom->tag_extend();
atom->tag_check();
// create global mapping of atoms
// zero nghost in case are adding new atoms to existing atoms
if (atom->map_style) {
atom->nghost = 0;
atom->map_init();
atom->map_set();
}
// print status
if (comm->me == 0) {
if (screen) {
printf("... fix smd/wall_surface finished reading triangulated surface\n");
fprintf(screen, "fix smd/wall_surface created " BIGINT_FORMAT " atoms\n", atom->natoms - natoms_previous);
printf(">>========>>========>>========>>========>>========>>========>>========>>========\n");
}
if (logfile) {
fprintf(logfile, "... fix smd/wall_surface finished reading triangulated surface\n");
fprintf(logfile, "fix smd/wall_surface created " BIGINT_FORMAT " atoms\n", atom->natoms - natoms_previous);
fprintf(logfile, ">>========>>========>>========>>========>>========>>========>>========>>========\n");
}
}
delete[] vert;
fclose(fp);
}
| 32.488889 | 127 | 0.479605 | [
"solid"
] |
a37f911823b7006f71e1f6ce3f7adcf2836a2caf | 5,347 | cc | C++ | src/lrit/file.cc | DJRaov/goestools | 3e09e099b6ab27bd697a9f3cce3c523684a89e44 | [
"BSD-2-Clause"
] | 19 | 2019-06-19T08:59:13.000Z | 2022-03-15T16:09:31.000Z | src/lrit/file.cc | DJRaov/goestools | 3e09e099b6ab27bd697a9f3cce3c523684a89e44 | [
"BSD-2-Clause"
] | 6 | 2020-11-27T01:18:42.000Z | 2022-01-09T10:36:27.000Z | src/lrit/file.cc | DJRaov/goestools | 3e09e099b6ab27bd697a9f3cce3c523684a89e44 | [
"BSD-2-Clause"
] | 7 | 2019-06-19T08:59:16.000Z | 2021-07-07T16:40:59.000Z | #include "file.h"
#include <array>
#include <time.h>
#include <util/error.h>
namespace lrit {
namespace {
// http://tuttlem.github.io/2014/08/18/getting-istream-to-work-off-a-byte-array.html
class membuf : public std::basic_streambuf<char> {
public:
membuf(const uint8_t* p, size_t l) {
setg((char*)p, (char*)p, (char*)p + l);
}
pos_type seekpos(
pos_type sp,
std::ios_base::openmode which) override {
return seekoff(sp - pos_type(off_type(0)), std::ios_base::beg, which);
}
pos_type seekoff(
off_type off,
std::ios_base::seekdir dir,
std::ios_base::openmode which = std::ios_base::in) override {
if (dir == std::ios_base::cur) {
gbump(off);
} else if (dir == std::ios_base::end) {
setg(eback(), egptr() + off, egptr());
} else if (dir == std::ios_base::beg) {
setg(eback(), eback() + off, egptr());
}
return gptr() - eback();
}
};
class memstream : public std::istream {
public:
memstream(const uint8_t* p, size_t l)
: std::istream(&buf_),
buf_(p, l) {
rdbuf(&buf_);
}
private:
membuf buf_;
};
class offsetfilebuf : public std::filebuf {
public:
void mark() {
offset_ = seekoff(0, std::ios_base::cur);
}
pos_type seekpos(
pos_type sp,
std::ios_base::openmode which) override {
return seekoff(sp - pos_type(off_type(0)), std::ios_base::beg, which);
}
pos_type seekoff(
off_type off,
std::ios_base::seekdir dir,
std::ios_base::openmode which = std::ios_base::in) override {
pos_type pos = 0;
if (dir == std::ios_base::cur) {
pos = std::filebuf::seekoff(off, dir, which);
} else if (dir == std::ios_base::end) {
pos = std::filebuf::seekoff(off, dir, which);
} else if (dir == std::ios_base::beg) {
pos = std::filebuf::seekoff(off + offset_, dir, which);
}
return pos - offset_;
}
private:
off_type offset_ = 0;
};
class offsetifstream : public std::istream {
public:
offsetifstream(const std::string& path)
: std::istream(&buf_) {
buf_.open(path, std::ios::in);
}
void mark() {
buf_.mark();
}
private:
offsetfilebuf buf_;
};
} // namespace
File::File(const std::string& file)
: file_(file) {
std::ifstream ifs(file_.c_str());
ASSERT(ifs);
// First 16 bytes hold the primary header
header_.resize(16);
ifs.read(reinterpret_cast<char*>(&header_[0]), header_.size());
ASSERT(ifs);
// Parse primary header
ph_ = lrit::getHeader<lrit::PrimaryHeader>(header_, 0);
// Read remaining headers
header_.resize(ph_.totalHeaderLength);
ifs.read(reinterpret_cast<char*>(&header_[16]), ph_.totalHeaderLength - 16);
ASSERT(ifs);
// Build header map
m_ = lrit::getHeaderMap(header_);
}
File::File(const std::vector<uint8_t>& buf) : buf_(buf) {
// First 16 bytes hold the primary header
header_.insert(header_.end(), buf_.begin(), buf_.begin() + 16);
// Parse primary header
ph_ = lrit::getHeader<lrit::PrimaryHeader>(header_, 0);
// Read remaining headers
header_.insert(
header_.end(),
buf_.begin() + 16,
buf_.begin() + ph_.totalHeaderLength);
// Build header map
m_ = lrit::getHeaderMap(header_);
}
std::string File::getTime() const {
std::array<char, 128> tsbuf;
auto ts = getHeader<lrit::TimeStampHeader>().getUnix();
auto len = strftime(
tsbuf.data(),
tsbuf.size(),
"%Y%d%m-%H%M%S",
gmtime(&ts.tv_sec));
return std::string(tsbuf.data(), len);
}
std::unique_ptr<std::istream> File::getDataFromFile() const {
auto ifs = std::make_unique<offsetifstream>(file_);
ASSERT(*ifs);
ifs->seekg(ph_.totalHeaderLength);
ASSERT(*ifs);
// Because of a bug in goesdec, LRIT image files that used
// compression have an initial bogus line, followed by the real
// image. Detect if this is one of those files and ignore the bogus
// line if so. See 2bd11f16 for more info.
if (ph_.fileType == 0) {
// Number of bytes remaining in file
std::streampos fpos1 = ifs->tellg();
ifs->seekg(0, std::ios::end);
std::streampos fpos2 = ifs->tellg();
ifs->seekg(fpos1);
// Seek to first byte beyond bogus line
// Round up (hence the + 7) so that images with 1 bit per pixel
// and a number of pixels not equal to a power of 8 are not
// accidentally made 1 byte shorter than expected.
auto delta = (fpos2 - fpos1) - ((int) ((ph_.dataLength + 7) / 8));
if (delta > 0) {
ifs->seekg(delta, ifs->cur);
ASSERT(*ifs);
}
}
// Current position is the start of the data section,
// and the 0-offset for other code that uses it.
ifs->mark();
return std::unique_ptr<std::istream>(ifs.release());
}
std::unique_ptr<std::istream> File::getDataFromBuffer() const {
auto ms = std::make_unique<memstream>(
buf_.data() + ph_.totalHeaderLength,
buf_.size() - ph_.totalHeaderLength);
return std::unique_ptr<std::istream>(ms.release());
}
std::unique_ptr<std::istream> File::getData() const {
if (!file_.empty()) {
return getDataFromFile();
}
if (!buf_.empty()) {
return getDataFromBuffer();
}
ERROR("unreachable");
}
std::vector<char> File::read() const {
std::vector<char> out;
auto ifs = getData();
auto bytes = (int) ((ph_.dataLength + 7) / 8);
out.resize(bytes);
ifs->read(out.data(), out.size());
return out;
}
} // namespace lrit
| 25.103286 | 84 | 0.633626 | [
"vector"
] |
a38750a0ac14294658bc77fd3f3eb70349490290 | 3,568 | cpp | C++ | src/lib/src/models/url-downloader/url-downloader.cpp | Penguin-Guru/imgbrd-grabber | 69bdd5566dc2b2cb3a67456bf1a159d544699bc9 | [
"Apache-2.0"
] | 1 | 2022-02-08T14:24:06.000Z | 2022-02-08T14:24:06.000Z | src/lib/src/models/url-downloader/url-downloader.cpp | Penguin-Guru/imgbrd-grabber | 69bdd5566dc2b2cb3a67456bf1a159d544699bc9 | [
"Apache-2.0"
] | null | null | null | src/lib/src/models/url-downloader/url-downloader.cpp | Penguin-Guru/imgbrd-grabber | 69bdd5566dc2b2cb3a67456bf1a159d544699bc9 | [
"Apache-2.0"
] | null | null | null | #include "url-downloader.h"
#include <QJSValue>
#include <QJSValueIterator>
#include <QUrl>
#include "js-helpers.h"
#include "logger.h"
UrlDownloader::UrlDownloader(QJSValue downloader, int index, QObject *parent)
: QObject(parent), m_downloader(std::move(downloader)), m_index(index)
{
m_name = m_downloader.property("name").toString();
const QStringList regexes = jsToStringList(m_downloader.property("handlers").property(m_index).property("regexes"));
m_regexes.reserve(regexes.count());
for (const QString ®ex : regexes) {
m_regexes.append(QRegularExpression(regex));
}
}
const QString &UrlDownloader::name() const
{
return m_name;
}
bool UrlDownloader::canDownload(const QUrl &url) const
{
const QString str = url.toString();
return std::any_of(m_regexes.constBegin(), m_regexes.constEnd(), [&str](const QRegularExpression &rx) {
return rx.match(str).hasMatch();
});
}
UrlDownloaderUrl UrlDownloader::url(const QUrl &url) const
{
UrlDownloaderUrl ret;
QJSValue urlFunction = m_downloader.property("handlers").property(m_index).property("url");
if (urlFunction.isUndefined()) {
ret.url = url.toString();
return ret;
}
const QJSValue &result = urlFunction.call(QList<QJSValue> { url.toString() });
// Script errors and exceptions
if (result.isError()) {
const QString err = QStringLiteral("Uncaught exception at line %1: %2").arg(result.property("lineNumber").toInt()).arg(result.toString());
ret.error = err;
log(err, Logger::Error);
return ret;
}
// String return for basic URL
if (!result.isObject()) {
ret.url = result.toString();
return ret;
}
// Error objects
if (result.hasProperty("error")) {
ret.error = result.property("error").toString();
return ret;
}
// URL + headers object
ret.url = result.property("url").toString();
if (result.hasProperty("headers")) {
const QJSValue &headers = result.property("headers");
QJSValueIterator headersIt(headers);
while (headersIt.hasNext()) {
headersIt.next();
ret.headers[headersIt.name()] = headersIt.value().toString();
}
}
return ret;
}
UrlDownloaderResult UrlDownloader::parse(const QString &source, int statusCode) const
{
UrlDownloaderResult ret;
QJSValue parseFunction = m_downloader.property("handlers").property(m_index).property("parse");
const QJSValue &result = parseFunction.call(QList<QJSValue> { source, statusCode });
// Script errors and exceptions
if (result.isError()) {
const QString err = QStringLiteral("Uncaught exception at line %1: %2").arg(result.property("lineNumber").toInt()).arg(result.toString());
ret.error = err;
log(err, Logger::Error);
return ret;
}
// Error objects
if (result.hasProperty("error")) {
ret.error = result.property("error").toString();
return ret;
}
// Tokens
if (result.hasProperty("tokens")) {
const QJSValue &tokens = result.property("tokens");
QJSValueIterator tokensIt(tokens);
while (tokensIt.hasNext()) {
tokensIt.next();
ret.tokens[tokensIt.name()] = tokensIt.value().toVariant();
}
}
// Files
if (result.hasProperty("files")) {
const QJSValue &files = result.property("files");
const quint32 length = files.property("length").toUInt();
for (quint32 i = 0; i < length; ++i) {
const QJSValue &file = files.property(i);
UrlDownloaderFile rFile;
getProperty(file, "url", rFile.url);
getProperty(file, "width", rFile.width);
getProperty(file, "height", rFile.height);
getProperty(file, "filesize", rFile.filesize);
getProperty(file, "ext", rFile.ext);
ret.files.append(rFile);
}
}
return ret;
}
| 27.030303 | 140 | 0.703195 | [
"object"
] |
a3882e8fa1da92ed5f213f920fbe44be99b9f951 | 2,524 | cpp | C++ | codeforces/1017 D. The Wu bit manipulation cumulative .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | 1 | 2021-11-22T02:26:43.000Z | 2021-11-22T02:26:43.000Z | codeforces/1017 D. The Wu bit manipulation cumulative .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | codeforces/1017 D. The Wu bit manipulation cumulative .cpp | priojeetpriyom/competitive-programming | 0024328972d4e14c04c0fd5d6dd3cdf131d84f9d | [
"MIT"
] | null | null | null | /*
idea: if we pre calculate all possible outcomes all queries it will take
(1<<13)^2 complexity. then we can answer each query in O(1) time
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define for0(i, n) for(int i=0; i<n; i++)
#define for1(i, n) for(int i=1; i<=n; i++)
#define cin0(n, ara) for(int i=0; i<n; i++) {cin>>ara[i];}
#define cini0(i, n, ara) for(int i=0; i<n; i++) {cin>>ara[i];}
#define cin1(n, ara) for(int i=1; i<=n; i++) {cin>>ar[i];}
#define cini1(i, n, ara) for(int i=1; i<=n; i++) {cin>>ar[i];}
#define MX 500100
#define double long double
#define mod 1000000007
#define mod2 1000000009
vector<int> query[1<<13] [105];
ll cost[15], fre[1<<13];
int can[1<<13][105];
int ans[MX];
int get_decimal(char str[], int len);
void pre_process(int n);
int get_cost(int i, int j, int n);
int main()
{
// double time = clock();
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// std::ios_base::sync_with_stdio(false);
// cin.tie(0);
int n, m ,q;
// memset(dp, -1, sizeof dp);
scanf("%d %d %d", &n, &m, &q);
for(int i=0; i<n; i++)
scanf("%lld", &cost[i]);
char str[100];
for(int i=0; i<m; i++) {
scanf("\n%s", str);
int num = get_decimal(str, strlen(str));
fre[num]++;
// cout<<"num "<<num<<" fre "<<fre[num]<<endl;
}
int k;
for(int i=0; i<q; i++) {
scanf("\n%s %d", str, &k);
int num = get_decimal(str, strlen(str));
query[num] [k].push_back(i);
}
pre_process(n);
for(int i=0; i<q; i++) {
printf("%d\n", ans[i]);
}
// cout<<(clock()-time)/CLOCKS_PER_SEC;
return 0;
}
void pre_process(int n) {
for(int i=0; i<(1<<n); i++) {
int sum=0;
for(int j=0; j<(1<<n); j++) {
sum= get_cost(i, j, n);
if(sum>100)
continue;
can[i] [sum]+= fre[j];
}
sum=0;
for(int k=0; k<=100; k++) {
sum+= can[i][k];
for(int q : query[i][k])
ans[q] = sum;
}
}
}
int get_cost(int a, int b, int n) {
int sum=0;
for(int i=0; i<n; i++)
if((a&(1<<i))==(b&(1<<i)))
sum+= cost[i];
// cout<<"a "<<a<<" b "<<b<<" cost "<<sum<<endl;
return sum;
}
int get_decimal(char str[], int len) {
int num=0;
for(int i=0; i<len; i++)
if(str[i]=='1')
num = num | (1<<i);
return num;
}
| 20.688525 | 74 | 0.492472 | [
"vector"
] |
a392517a9f8f578239ec989f324ef5f18b793020 | 9,245 | cpp | C++ | test/test_xio.cpp | rajashekar007/xtensor | 574dbf5aa0588fe80f513a344dd9b0e3f7247359 | [
"BSD-3-Clause"
] | 7 | 2020-03-13T17:08:01.000Z | 2021-11-17T11:43:58.000Z | test/test_xio.cpp | rajashekar007/xtensor | 574dbf5aa0588fe80f513a344dd9b0e3f7247359 | [
"BSD-3-Clause"
] | 2 | 2021-03-16T12:05:50.000Z | 2021-03-16T13:06:47.000Z | test/test_xio.cpp | rajashekar007/xtensor | 574dbf5aa0588fe80f513a344dd9b0e3f7247359 | [
"BSD-3-Clause"
] | 8 | 2020-02-13T18:05:55.000Z | 2021-03-16T11:12:33.000Z | /***************************************************************************
* Copyright (c) 2016, Johan Mabille, Sylvain Corlay and Wolf Vollprecht *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "gtest/gtest.h"
#include <vector>
#include <algorithm>
#include <sstream>
#include <limits>
#include "xtensor/xarray.hpp"
#include "xtensor/xtensor.hpp"
#include "xtensor/xio.hpp"
#include "xtensor/xrandom.hpp"
#include "xtensor/xbuilder.hpp"
#include "xtensor/xdynamic_view.hpp"
#include "xtensor/xview.hpp"
#include "files/xio_expected_results.hpp"
namespace xt
{
TEST(xio, xtensor_one_d)
{
xtensor<double, 1> e = xt::arange<double>(1, 6);
std::stringstream out;
out << e;
EXPECT_EQ("{ 1., 2., 3., 4., 5.}", out.str());
}
TEST(xio, xarray_one_d)
{
xarray<double> e{1, 2, 3, 4, 5};
std::stringstream out;
out << e;
EXPECT_EQ("{ 1., 2., 3., 4., 5.}", out.str());
}
TEST(xio, xarray_two_d)
{
xarray<double> e{{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
std::stringstream out;
out << e;
EXPECT_EQ(twod_double, out.str());
}
TEST(xio, view)
{
xarray<double> e{{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
auto v_1 = view(e, 1, xt::all());
auto v_2 = view(e, xt::all(), 1);
auto v_new_axis = view(e, 1, xt::newaxis(), xt::all());
xarray<int> c = {1, 2, 3, 4};
auto v_just_new_axis = view(c, xt::newaxis());
std::stringstream out_1;
out_1 << v_1;
EXPECT_EQ("{ 5., 6., 7., 8.}", out_1.str());
std::stringstream out_2;
out_2 << v_2;
EXPECT_EQ("{ 2., 6., 10.}", out_2.str());
std::stringstream out_3;
out_3 << v_new_axis;
EXPECT_EQ("{{ 5., 6., 7., 8.}}", out_3.str());
std::stringstream out_4;
out_4 << v_just_new_axis;
EXPECT_EQ("{{1, 2, 3, 4}}", out_4.str());
}
TEST(xio, xdynamic_view)
{
xarray<int> e{{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}};
auto v = xt::dynamic_view(e, { 1, keep(0, 2, 3)});
std::stringstream out;
out << v;
EXPECT_EQ("{5, 7, 8}", out.str());
}
TEST(xio, random_nan_inf)
{
xt::random::seed(123);
xt::xarray<double, layout_type::row_major> rn = xt::random::rand<double>({20, 20}, -10, 10);
rn(1, 1) = -1;
rn(1, 2) = +1;
rn(1, 1) = -1;
rn(2, 2) = std::numeric_limits<double>::infinity(); // inf
rn(2, 3) = -std::numeric_limits<double>::infinity(); // -inf
rn(4, 4) = std::nan("xnan");
std::stringstream out;
out << rn;
EXPECT_EQ(random_nan_inf, out.str());
}
TEST(xio, big_exp)
{
xt::random::seed(123);
xt::xarray<double, layout_type::row_major> rn = xt::random::rand<double>({5, 4}, -10, 10);
rn(1, 1) = 1e220;
rn(1, 2) = 1e-124;
std::stringstream out;
out << rn;
EXPECT_EQ(big_exp, out.str());
}
TEST(xio, precision)
{
xt::random::seed(123);
xt::xarray<double, layout_type::row_major> rn = xt::random::rand<double>({5, 4}, -10, 10);
std::stringstream out;
out << std::setprecision(12) << rn;
EXPECT_EQ(precision, out.str());
}
TEST(xio, bool_fn)
{
xt::random::seed(123);
xt::xarray<double, layout_type::row_major> rn = xt::random::rand<double>({5, 5}, -10, 10);
std::stringstream out;
out << (rn > 0);
std::string res = bool_fn;
EXPECT_EQ(res, out.str());
}
TEST(xio, cutoff)
{
xt::xarray<int> rn = xt::ones<int>({1, 1001});
std::stringstream out;
out << rn;
EXPECT_EQ("{{1, 1, 1, ..., 1, 1, 1}}", out.str());
std::stringstream out2;
xt::xarray<int> rn2 = xt::ones<int>({1001, 1});
out2 << rn2;
EXPECT_EQ(cut_high, out2.str());
}
TEST(xio, cut_longwise)
{
xt::xarray<unsigned int> a = xt::ones<unsigned int>({5, 1000});
std::stringstream out;
out << a;
EXPECT_EQ(cut_long, out.str());
xt::xarray<int> b = xt::ones<int>({7, 1000});
std::stringstream outb;
outb << b;
EXPECT_EQ(cut_both, outb.str());
xt::xarray<int> c = xt::ones<int>({7, 7, 7, 1000});
std::stringstream outc;
outc << c;
EXPECT_EQ(cut_4d, outc.str());
}
TEST(xio, options)
{
xt::random::seed(123);
xt::xarray<double, layout_type::row_major> rn = xt::random::rand<double>({100, 100}, -10, 10);
xt::print_options::set_line_width(150);
xt::print_options::set_edge_items(10);
xt::print_options::set_precision(10);
xt::print_options::set_threshold(100);
std::stringstream out;
out << rn;
EXPECT_EQ(print_options_result, out.str());
// reset back to default
xt::print_options::set_line_width(75);
xt::print_options::set_edge_items(3);
xt::print_options::set_precision(-1);
xt::print_options::set_threshold(1000);
}
namespace po = xt::print_options;
TEST(xio, local_options)
{
xt::random::seed(123);
xt::xarray<double, layout_type::row_major> rn = xt::random::rand<double>({100, 100}, -10, 10);
std::stringstream out;
out << po::line_width(150)
<< po::edge_items(10)
<< po::precision(10)
<< po::threshold(100)
<< rn;
EXPECT_EQ(print_options_result, out.str());
EXPECT_EQ(out.iword(po::edge_items::id()), long(0));
EXPECT_EQ(out.iword(po::line_width::id()), long(0));
EXPECT_EQ(out.iword(po::threshold::id()), long(0));
EXPECT_EQ(out.iword(po::precision::id()), long(0));
}
TEST(xio, three_d)
{
xarray<double> e{{{1, 2},
{3, 4},
{5, 6},
{7, 8}},
{{9, 10},
{11, 12},
{7, 9},
{11, 14}},
{{5, 26},
{7, 8},
{10, 8},
{4, 3}}};
std::stringstream out;
out << e;
EXPECT_EQ(threed_double, out.str());
}
TEST(xio, strings)
{
xt::xarray<std::string> e = {{"some", "random", "boring"}, {"strings", "in", "xtensor xarray"}};
std::stringstream out;
out << e;
EXPECT_EQ(random_strings, out.str());
}
TEST(xio, long_strings)
{
xt::xarray<std::string> e = {{"some", "random very long and very very", "boring"}, {"strings", "in", "xtensor xarray"}};
std::stringstream out;
out << e;
EXPECT_EQ(long_strings, out.str());
}
TEST(xio, complex)
{
xt::random::seed(123);
xt::xarray<double, layout_type::row_major> real = xt::random::rand<double>({10, 10}, -10, 10);
xt::xarray<double, layout_type::row_major> imag = xt::random::rand<double>({10, 10}, -5, 5);
xt::xarray<std::complex<double>, layout_type::row_major> e = real + (imag * std::complex<double>(0, 1));
std::stringstream out;
out << e;
EXPECT_EQ(complex_numbers, out.str());
}
TEST(xio, complex_zero_erasing)
{
xt::random::seed(123);
xt::xarray<double, layout_type::row_major> real = xt::random::rand<double>({10, 10}) - 0.5;
xt::xarray<double, layout_type::row_major> imag = xt::random::rand<double>({10, 10}) - 0.5;
xt::xarray<std::complex<double>, layout_type::row_major> e = real + (imag * std::complex<double>(0, 1));
std::stringstream out;
out << e;
EXPECT_EQ(complex_zero_erasing, out.str());
}
TEST(xio, float_leading_zero)
{
xt::random::seed(123);
std::stringstream out;
out << xt::random::rand<double>({10, 10}) - 0.5;
EXPECT_EQ(float_leading_zero, out.str());
}
TEST(xio, custom_formatter)
{
xt::xarray<int> e = {{1, 2, 3, 4}, {100, 200, 1000, 10000000}};
std::stringstream out;
pretty_print(e, [](const int& val) {
std::stringstream buf;
buf << "0x" << std::hex << val;
return buf.str();
}, out);
EXPECT_EQ(custom_formatter_result, out.str());
}
TEST(xio, view_on_broadcast)
{
auto on = xt::ones<int>({5, 5});
auto von = xt::view(on, 1);
std::stringstream out;
out << von;
std::string exp = "{1, 1, 1, 1, 1}";
EXPECT_EQ(exp, out.str());
}
}
| 29.442675 | 128 | 0.485235 | [
"vector"
] |
a394c21f96b2ac0015e9c6468cd8ee44d0511d97 | 20,405 | cc | C++ | device/fido/device_response_converter.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | device/fido/device_response_converter.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | device/fido/device_response_converter.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/fido/device_response_converter.h"
#include <memory>
#include <string>
#include <utility>
#include "base/containers/span.h"
#include "base/i18n/streaming_utf8_validator.h"
#include "base/numerics/safe_conversions.h"
#include "base/optional.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "components/cbor/diagnostic_writer.h"
#include "components/cbor/reader.h"
#include "components/cbor/writer.h"
#include "components/device_event_log/device_event_log.h"
#include "device/fido/authenticator_data.h"
#include "device/fido/authenticator_supported_options.h"
#include "device/fido/client_data.h"
#include "device/fido/features.h"
#include "device/fido/fido_constants.h"
#include "device/fido/opaque_attestation_statement.h"
namespace device {
namespace {
constexpr size_t kResponseCodeLength = 1;
ProtocolVersion ConvertStringToProtocolVersion(base::StringPiece version) {
if (version == kCtap2Version)
return ProtocolVersion::kCtap2;
if (version == kU2fVersion)
return ProtocolVersion::kU2f;
return ProtocolVersion::kUnknown;
}
// Converts a CBOR unsigned integer value to a uint32_t. The conversion is
// clamped at uint32_max.
uint32_t CBORUnsignedToUint32Safe(const cbor::Value& value) {
DCHECK(value.is_unsigned());
constexpr uint32_t uint32_max = std::numeric_limits<uint32_t>::max();
const int64_t n = value.GetUnsigned();
return n > uint32_max ? uint32_max : n;
}
} // namespace
using CBOR = cbor::Value;
CtapDeviceResponseCode GetResponseCode(base::span<const uint8_t> buffer) {
if (buffer.empty())
return CtapDeviceResponseCode::kCtap2ErrInvalidCBOR;
auto code = static_cast<CtapDeviceResponseCode>(buffer[0]);
return base::Contains(GetCtapResponseCodeList(), code)
? code
: CtapDeviceResponseCode::kCtap2ErrInvalidCBOR;
}
// Decodes byte array response from authenticator to CBOR value object and
// checks for correct encoding format.
base::Optional<AuthenticatorMakeCredentialResponse>
ReadCTAPMakeCredentialResponse(FidoTransportProtocol transport_used,
const base::Optional<cbor::Value>& cbor) {
if (!cbor || !cbor->is_map())
return base::nullopt;
const auto& decoded_map = cbor->GetMap();
auto it = decoded_map.find(CBOR(1));
if (it == decoded_map.end() || !it->second.is_string())
return base::nullopt;
auto format = it->second.GetString();
it = decoded_map.find(CBOR(2));
if (it == decoded_map.end() || !it->second.is_bytestring())
return base::nullopt;
auto authenticator_data =
AuthenticatorData::DecodeAuthenticatorData(it->second.GetBytestring());
if (!authenticator_data)
return base::nullopt;
it = decoded_map.find(CBOR(3));
if (it == decoded_map.end() || !it->second.is_map())
return base::nullopt;
AuthenticatorMakeCredentialResponse response(
transport_used,
AttestationObject(std::move(*authenticator_data),
std::make_unique<OpaqueAttestationStatement>(
format, it->second.Clone())));
if (base::FeatureList::IsEnabled(kWebAuthPhoneSupport)) {
it = decoded_map.find(CBOR(kAndroidClientDataExtOutputKey));
if (it != decoded_map.end() && it->second.is_bytestring()) {
response.set_android_client_data_ext(it->second.GetBytestring());
}
}
return response;
}
base::Optional<AuthenticatorGetAssertionResponse> ReadCTAPGetAssertionResponse(
const base::Optional<cbor::Value>& cbor) {
if (!cbor || !cbor->is_map())
return base::nullopt;
auto& response_map = cbor->GetMap();
auto it = response_map.find(CBOR(2));
if (it == response_map.end() || !it->second.is_bytestring())
return base::nullopt;
auto auth_data =
AuthenticatorData::DecodeAuthenticatorData(it->second.GetBytestring());
if (!auth_data)
return base::nullopt;
it = response_map.find(CBOR(3));
if (it == response_map.end() || !it->second.is_bytestring())
return base::nullopt;
auto signature = it->second.GetBytestring();
AuthenticatorGetAssertionResponse response(std::move(*auth_data),
std::move(signature));
it = response_map.find(CBOR(1));
if (it != response_map.end()) {
auto credential =
PublicKeyCredentialDescriptor::CreateFromCBORValue(it->second);
if (!credential)
return base::nullopt;
response.SetCredential(std::move(*credential));
}
it = response_map.find(CBOR(4));
if (it != response_map.end()) {
auto user = PublicKeyCredentialUserEntity::CreateFromCBORValue(it->second);
if (!user)
return base::nullopt;
response.SetUserEntity(std::move(*user));
}
it = response_map.find(CBOR(5));
if (it != response_map.end()) {
if (!it->second.is_unsigned())
return base::nullopt;
response.SetNumCredentials(it->second.GetUnsigned());
}
if (base::FeatureList::IsEnabled(kWebAuthPhoneSupport)) {
it = response_map.find(CBOR(kAndroidClientDataExtOutputKey));
if (it != response_map.end() && it->second.is_bytestring()) {
response.set_android_client_data_ext(it->second.GetBytestring());
}
}
return response;
}
base::Optional<AuthenticatorGetInfoResponse> ReadCTAPGetInfoResponse(
base::span<const uint8_t> buffer) {
if (buffer.size() <= kResponseCodeLength ||
GetResponseCode(buffer) != CtapDeviceResponseCode::kSuccess)
return base::nullopt;
cbor::Reader::DecoderError error;
base::Optional<CBOR> decoded_response =
cbor::Reader::Read(buffer.subspan(1), &error);
if (!decoded_response) {
FIDO_LOG(ERROR) << "-> (CBOR parse error from GetInfo response '"
<< cbor::Reader::ErrorCodeToString(error)
<< "' from raw message "
<< base::HexEncode(buffer.data(), buffer.size()) << ")";
return base::nullopt;
}
if (!decoded_response->is_map())
return base::nullopt;
FIDO_LOG(DEBUG) << "-> " << cbor::DiagnosticWriter::Write(*decoded_response);
const auto& response_map = decoded_response->GetMap();
auto it = response_map.find(CBOR(1));
if (it == response_map.end() || !it->second.is_array()) {
return base::nullopt;
}
base::flat_set<ProtocolVersion> protocol_versions;
base::flat_set<base::StringPiece> advertised_protocols;
for (const auto& version : it->second.GetArray()) {
if (!version.is_string())
return base::nullopt;
const std::string& version_string = version.GetString();
if (!advertised_protocols.insert(version_string).second) {
// Duplicate versions are not allowed.
return base::nullopt;
}
auto protocol = ConvertStringToProtocolVersion(version_string);
if (protocol == ProtocolVersion::kUnknown) {
FIDO_LOG(DEBUG) << "Unexpected protocol version received.";
continue;
}
if (!protocol_versions.insert(protocol).second) {
// A duplicate value will have already caused an error therefore hitting
// this suggests that |ConvertStringToProtocolVersion| is non-injective.
NOTREACHED();
return base::nullopt;
}
}
if (protocol_versions.empty())
return base::nullopt;
it = response_map.find(CBOR(3));
if (it == response_map.end() || !it->second.is_bytestring() ||
it->second.GetBytestring().size() != kAaguidLength) {
return base::nullopt;
}
AuthenticatorGetInfoResponse response(
std::move(protocol_versions),
base::make_span<kAaguidLength>(it->second.GetBytestring()));
AuthenticatorSupportedOptions options;
it = response_map.find(CBOR(2));
if (it != response_map.end()) {
if (!it->second.is_array())
return base::nullopt;
std::vector<std::string> extensions;
for (const auto& extension : it->second.GetArray()) {
if (!extension.is_string())
return base::nullopt;
const std::string& extension_str = extension.GetString();
if (extension_str == kExtensionCredProtect) {
options.supports_cred_protect = true;
} else if (extension_str == kExtensionAndroidClientData) {
options.supports_android_client_data_ext = true;
}
extensions.push_back(extension_str);
}
response.extensions = std::move(extensions);
}
it = response_map.find(CBOR(4));
if (it != response_map.end()) {
if (!it->second.is_map())
return base::nullopt;
const auto& option_map = it->second.GetMap();
auto option_map_it = option_map.find(CBOR(kPlatformDeviceMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool())
return base::nullopt;
options.is_platform_device = option_map_it->second.GetBool();
}
option_map_it = option_map.find(CBOR(kResidentKeyMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool())
return base::nullopt;
options.supports_resident_key = option_map_it->second.GetBool();
}
option_map_it = option_map.find(CBOR(kUserPresenceMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool())
return base::nullopt;
options.supports_user_presence = option_map_it->second.GetBool();
}
option_map_it = option_map.find(CBOR(kUserVerificationMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool())
return base::nullopt;
if (option_map_it->second.GetBool()) {
options.user_verification_availability = AuthenticatorSupportedOptions::
UserVerificationAvailability::kSupportedAndConfigured;
} else {
options.user_verification_availability = AuthenticatorSupportedOptions::
UserVerificationAvailability::kSupportedButNotConfigured;
}
}
option_map_it = option_map.find(CBOR(kClientPinMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool())
return base::nullopt;
if (option_map_it->second.GetBool()) {
options.client_pin_availability = AuthenticatorSupportedOptions::
ClientPinAvailability::kSupportedAndPinSet;
} else {
options.client_pin_availability = AuthenticatorSupportedOptions::
ClientPinAvailability::kSupportedButPinNotSet;
}
}
option_map_it = option_map.find(CBOR(kCredentialManagementMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool()) {
return base::nullopt;
}
options.supports_credential_management = option_map_it->second.GetBool();
}
option_map_it = option_map.find(CBOR(kCredentialManagementPreviewMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool()) {
return base::nullopt;
}
options.supports_credential_management_preview =
option_map_it->second.GetBool();
}
option_map_it = option_map.find(CBOR(kBioEnrollmentMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool()) {
return base::nullopt;
}
using Availability =
AuthenticatorSupportedOptions::BioEnrollmentAvailability;
options.bio_enrollment_availability =
option_map_it->second.GetBool()
? Availability::kSupportedAndProvisioned
: Availability::kSupportedButUnprovisioned;
}
option_map_it = option_map.find(CBOR(kBioEnrollmentPreviewMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool()) {
return base::nullopt;
}
using Availability =
AuthenticatorSupportedOptions::BioEnrollmentAvailability;
options.bio_enrollment_availability_preview =
option_map_it->second.GetBool()
? Availability::kSupportedAndProvisioned
: Availability::kSupportedButUnprovisioned;
}
option_map_it = option_map.find(CBOR(kUvTokenMapKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_bool()) {
return base::nullopt;
}
options.supports_uv_token = option_map_it->second.GetBool();
}
option_map_it = option_map.find(CBOR(kDefaultCredProtectKey));
if (option_map_it != option_map.end()) {
if (!option_map_it->second.is_unsigned()) {
return base::nullopt;
}
const int64_t value = option_map_it->second.GetInteger();
if (value != static_cast<uint8_t>(CredProtect::kUVOrCredIDRequired) &&
value != static_cast<uint8_t>(CredProtect::kUVRequired)) {
return base::nullopt;
}
options.default_cred_protect = static_cast<CredProtect>(value);
}
response.options = std::move(options);
}
it = response_map.find(CBOR(5));
if (it != response_map.end()) {
if (!it->second.is_unsigned())
return base::nullopt;
response.max_msg_size = CBORUnsignedToUint32Safe(it->second);
}
it = response_map.find(CBOR(6));
if (it != response_map.end()) {
if (!it->second.is_array())
return base::nullopt;
std::vector<uint8_t> supported_pin_protocols;
for (const auto& protocol : it->second.GetArray()) {
if (!protocol.is_unsigned())
return base::nullopt;
supported_pin_protocols.push_back(protocol.GetUnsigned());
}
response.pin_protocols = std::move(supported_pin_protocols);
}
it = response_map.find(CBOR(7));
if (it != response_map.end()) {
if (!it->second.is_unsigned())
return base::nullopt;
response.max_credential_count_in_list =
CBORUnsignedToUint32Safe(it->second);
}
it = response_map.find(CBOR(8));
if (it != response_map.end()) {
if (!it->second.is_unsigned())
return base::nullopt;
response.max_credential_id_length = CBORUnsignedToUint32Safe(it->second);
}
return base::Optional<AuthenticatorGetInfoResponse>(std::move(response));
}
static base::Optional<std::string> FixInvalidUTF8String(
base::span<const uint8_t> utf8_bytes) {
// CTAP2 devices must store at least 64 bytes of any string.
if (utf8_bytes.size() < 64) {
FIDO_LOG(ERROR) << "Not accepting invalid UTF-8 string because it's only "
<< utf8_bytes.size() << " bytes long";
return base::nullopt;
}
base::StreamingUtf8Validator validator;
base::StreamingUtf8Validator::State state;
size_t longest_valid_prefix_len = 0;
for (size_t i = 0; i < utf8_bytes.size(); i++) {
state =
validator.AddBytes(reinterpret_cast<const char*>(&utf8_bytes[i]), 1);
switch (state) {
case base::StreamingUtf8Validator::VALID_ENDPOINT:
longest_valid_prefix_len = i + 1;
break;
case base::StreamingUtf8Validator::INVALID:
return base::nullopt;
case base::StreamingUtf8Validator::VALID_MIDPOINT:
break;
}
}
switch (state) {
case base::StreamingUtf8Validator::VALID_ENDPOINT:
// |base::IsStringUTF8|, which the CBOR code uses, is stricter than
// |StreamingUtf8Validator| in that the former rejects ranges of code
// points that should never appear. Therefore, if this case occurs, the
// string is structurally valid as UTF-8, but includes invalid code points
// and thus we reject it.
return base::nullopt;
case base::StreamingUtf8Validator::INVALID:
// This shouldn't happen because we should return immediately if
// |INVALID| occurs.
NOTREACHED();
return base::nullopt;
case base::StreamingUtf8Validator::VALID_MIDPOINT: {
// This string has been truncated. This is the case that we expect to
// have to handle since CTAP2 devices are permitted to truncate strings
// without reference to UTF-8.
const std::string candidate(
reinterpret_cast<const char*>(utf8_bytes.data()),
longest_valid_prefix_len);
// Check that the result is now acceptable to |IsStringUTF8|, which is
// stricter than |StreamingUtf8Validator|. Without this, a string could
// have both contained invalid code-points /and/ been truncated, and this
// function would only have corrected the latter issue.
if (base::IsStringUTF8(candidate)) {
return candidate;
}
return base::nullopt;
}
}
}
typedef bool (*PathPredicate)(const std::vector<const cbor::Value*>&);
static base::Optional<cbor::Value> FixInvalidUTF8Value(
const cbor::Value& v,
std::vector<const cbor::Value*>* path,
PathPredicate predicate) {
switch (v.type()) {
case cbor::Value::Type::INVALID_UTF8: {
if (!predicate(*path)) {
return base::nullopt;
}
base::Optional<std::string> maybe_fixed(
FixInvalidUTF8String(v.GetInvalidUTF8()));
if (!maybe_fixed) {
return base::nullopt;
}
return cbor::Value(*maybe_fixed);
}
case cbor::Value::Type::UNSIGNED:
case cbor::Value::Type::NEGATIVE:
case cbor::Value::Type::BYTE_STRING:
case cbor::Value::Type::STRING:
case cbor::Value::Type::TAG:
case cbor::Value::Type::SIMPLE_VALUE:
case cbor::Value::Type::NONE:
return v.Clone();
case cbor::Value::Type::ARRAY: {
const cbor::Value::ArrayValue& old_array = v.GetArray();
cbor::Value::ArrayValue new_array;
new_array.reserve(old_array.size());
for (const auto& child : old_array) {
base::Optional<cbor::Value> maybe_fixed =
FixInvalidUTF8Value(child, path, predicate);
if (!maybe_fixed) {
return base::nullopt;
}
new_array.emplace_back(std::move(*maybe_fixed));
}
return cbor::Value(new_array);
}
case cbor::Value::Type::MAP: {
const cbor::Value::MapValue& old_map = v.GetMap();
cbor::Value::MapValue new_map;
new_map.reserve(old_map.size());
for (const auto& it : old_map) {
switch (it.first.type()) {
case cbor::Value::Type::INVALID_UTF8:
// Invalid strings in map keys are not supported.
return base::nullopt;
case cbor::Value::Type::UNSIGNED:
case cbor::Value::Type::NEGATIVE:
case cbor::Value::Type::STRING:
break;
default:
// Other types are not permitted as map keys in CTAP2.
return base::nullopt;
}
path->push_back(&it.first);
base::Optional<cbor::Value> maybe_fixed =
FixInvalidUTF8Value(it.second, path, predicate);
path->pop_back();
if (!maybe_fixed) {
return base::nullopt;
}
new_map.emplace(it.first.Clone(), std::move(*maybe_fixed));
}
return cbor::Value(new_map);
}
}
}
// ContainsInvalidUTF8 returns true if any element of |v| (recursively) contains
// a string with invalid UTF-8. It bases this determination purely on the type
// of the nodes and doesn't actually check the contents of the strings
// themselves.
static bool ContainsInvalidUTF8(const cbor::Value& v) {
switch (v.type()) {
case cbor::Value::Type::INVALID_UTF8:
return true;
case cbor::Value::Type::UNSIGNED:
case cbor::Value::Type::NEGATIVE:
case cbor::Value::Type::BYTE_STRING:
case cbor::Value::Type::STRING:
case cbor::Value::Type::TAG:
case cbor::Value::Type::SIMPLE_VALUE:
case cbor::Value::Type::NONE:
return false;
case cbor::Value::Type::ARRAY: {
const cbor::Value::ArrayValue& array = v.GetArray();
for (const auto& child : array) {
if (ContainsInvalidUTF8(child)) {
return true;
}
}
return false;
}
case cbor::Value::Type::MAP: {
const cbor::Value::MapValue& map = v.GetMap();
for (const auto& it : map) {
if (ContainsInvalidUTF8(it.first) || ContainsInvalidUTF8(it.second)) {
return true;
}
}
return false;
}
}
}
base::Optional<cbor::Value> FixInvalidUTF8(cbor::Value in,
PathPredicate predicate) {
if (!ContainsInvalidUTF8(in)) {
// Common case that everything is fine.
return in;
}
std::vector<const cbor::Value*> path;
return FixInvalidUTF8Value(in, &path, predicate);
}
} // namespace device
| 32.54386 | 80 | 0.665474 | [
"object",
"vector"
] |
a396ea7f8662b4dedc4e12afcbe86dc9a26ee2b0 | 16,058 | cpp | C++ | main/trs_memory.cpp | shaeberling/mini-trs | 9496a764f51809d907bffdae202aa48c53b114d7 | [
"Apache-2.0"
] | null | null | null | main/trs_memory.cpp | shaeberling/mini-trs | 9496a764f51809d907bffdae202aa48c53b114d7 | [
"Apache-2.0"
] | null | null | null | main/trs_memory.cpp | shaeberling/mini-trs | 9496a764f51809d907bffdae202aa48c53b114d7 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 1992 Clarendon Hill Software.
*
* Permission is granted to any individual or institution to use, copy,
* or redistribute this software, provided this copyright notice is retained.
*
* This software is provided "as is" without any expressed or implied
* warranty. If this software brings on any sort of damage -- physical,
* monetary, emotional, or brain -- too bad. You've got no one to blame
* but yourself.
*
* The software may be modified for your own purposes, but modified versions
* must retain this notice.
*/
/*
* Copyright (c) 1996-2020, Timothy P. Mann
*
* 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.
*/
/*
* trs_memory.c -- memory emulation functions for the TRS-80 emulator
*
* Routines in this file perform operations such as mem_read and mem_write,
* and are the top level emulation points for memory-mapped devices such
* as the screen and keyboard.
*/
#include "trs.h"
#include "trs-keyboard.h"
#include "trs_screen.h"
#include "esp_attr.h"
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include "rom/model3-frehd.cpp-inc"
//#define SUPERMEM 1
typedef unsigned char Uchar;
#define MAX_ROM_SIZE (0x3800)
#define MAX_VIDEO_SIZE (0x0800)
/* 512K is the largest we support. There were it seems 1MByte
options at some point which is the full range of the mapping.
How the mapping register worked for > 1MB is not known */
#define MAX_SUPERMEM_SIZE (0x80000)
/* Locations for Model I, Model III, and Model 4 map 0 */
#define ROM_START (0x0000)
#define IO_START (0x3000)
#define KEYBOARD_START (0x3800)
#define MORE_IO_START (0x3c00)
#define VIDEO_START (0x3c00)
#define RAM_START (0x4000)
#define PRINTER_ADDRESS (0x37E8)
/* Interrupt latch register in EI (Model 1) */
#define TRS_INTLATCH(addr) (((addr)&~3) == 0x37e0)
/* We allow for 2MB of banked memory via port 0x94. That is the extreme limit
of the port mods rather than anything normal (512K might be more 'normal' */
Uchar memory[2 * 64 * 1024] EXT_RAM_ATTR;
Uchar video[MAX_VIDEO_SIZE + 1] EXT_RAM_ATTR;
const Uchar* rom = model3_frehd_rom;
int trs_rom_size = model3_frehd_rom_len;
int lowercase = 1;
int romin = 0; /* Model 4p */
int huffman_ram = 0;
int hypermem = 0;
#ifdef SUPERMEM
int supermem = 0;
#endif
int selector = 0;
/* private data */
//static Uchar video[MAX_VIDEO_SIZE + 1];
static int trs_video_size;
static int memory_map = 0;
static int bank_offset[2];
#define VIDEO_PAGE_0 0
#define VIDEO_PAGE_1 1024
static int video_offset = (-VIDEO_START + VIDEO_PAGE_0);
static unsigned int bank_base = 0x10000;
static unsigned char mem_command = 0;
#ifdef SUPERMEM
static Uchar *supermem_ram = NULL;
static int supermem_base;
static unsigned int supermem_hi;
#endif
static int selector_reg = 0;
void mem_video_page(int which)
{
video_offset = -VIDEO_START + (which ? VIDEO_PAGE_1 : VIDEO_PAGE_0);
}
void mem_bank(int command)
{
switch (command) {
case 0:
/* L64 Lower / Upper */
bank_offset[0] = 0 << 15;
bank_offset[1] = 0 << 15;
break;
case 2:
/* L64 Lower / H64 Lower */
bank_offset[0] = 0 << 15;
bank_offset[1] = bank_base - (1 << 15);
break;
case 3:
/* L64 Lower / H64 upper */
bank_offset[0] = 0 << 15;
bank_offset[1] = (0 << 15) + bank_base;
break;
case 6:
/* H64 Lower / L64 upper */
bank_offset[0] = (0 << 15) + bank_base;
bank_offset[1] = 0 << 15;
break;
case 7:
/* H64 Upper / L64 Upper */
bank_offset[0] = (1 << 15) + bank_base;
bank_offset[1] = 0 << 15;
break;
default:
assert(0);//error("unknown mem_bank command %d", command);
break;
}
mem_command = command;
}
/*
* Dave Huffman (and some other) memory expansions. These decode
* port 0x94 off U50 as follows
*
* 7: only used with Z180 board (not emulated - would need Z180 emulation!)
* 6: write protect - not emulated
* 5: sometimes used for > 4MHz turbo mod
* 4-0: Bits A20-A16 of the alt bank
*
* Set to 1 on a reset so that you get the 'classic' memory map
* This port is read-write and the drivers depend upon it
* (See RAMDV364.ASM)
*
* The Hypermem is very similar and also changes the upper
* 64K bank between multiple banks. However the values
* are on port 0x90 (sound) bits 4-1, which is a much poorer
* design IMHO as sound using apps can randomly change the
* upper bank. Fine for a ramdisc but means other software
* must take great care.
*
* The MegaMem mappings are not known and not emulated.
*/
void mem_bank_base(int bits)
{
if (huffman_ram) {
bits &= 0x1F;
bank_base = bits << 16;
mem_bank(mem_command);
}
if (hypermem) {
/* HyperMem replaces the upper 64K bank with multiple
banks according to port 0x90 bits 4-1 */
bits &= 0x1E;
/* 0 base is upper bank of 64K */
bits += 2;
bank_base = bits << 15;
mem_bank(mem_command);
}
#ifdef SUPERMEM
if (supermem) {
/* Emulate a 512Kb system. A standard model 1 SuperMEM is 256K
or 512K with double stacked chips */
bits &= 0x0F; /* 15 bits of address + 4bits logical */
supermem_base = bits << 15;
/* The supermem can flip the low or high 32K. Set
bit 5 to map low */
if (bits & 0x20)
supermem_hi = 0x0000;
else
supermem_hi = 0x8000;
}
#endif
}
int mem_read_bank_base(void)
{
if (huffman_ram)
return (bank_base >> 16) & 0x1F;
#ifdef SUPERMEM
if (supermem)
return (supermem_base >> 15) |
((supermem_hi == 0) ? 0x20 : 0);
#endif
/* And the HyperMem appears to be write-only */
return 0xFF;
}
void selector_out(unsigned char value)
{
/* Not all bits are necessarily really present but hey what
you can't read back you can't tell */
selector_reg = value;
/* Always Model 1 */
memory_map = (trs_model << 4) + (selector_reg & 7);
/* 0x10 is already the default tandy map we add 11-17 in the style
of the model 4 approach */
if (selector_reg & 0x8) {
/* External RAM enabled */
/* Effectively the selector bits << 15 */
/* Low 64K is the base memory */
bank_base = 32768 + ((selector_reg & 0x30) << 11);
/* Now are we mapping it high or low */
if (selector_reg & 1) /* Low */
bank_base += 32768;
} else
bank_base = 0;
}
#if 0
/* Handle reset button if poweron=0;
handle hard reset or initial poweron if poweron=1 */
void trs_reset(int poweron)
{
trs_emu_mouse = FALSE;
/* Close disks opened by Z80 programs */
do_emt_resetdisk();
/* Reset devices (Model I SYSRES, Model III/4 RESET) */
trs_cassette_reset();
trs_disk_init(poweron); /* also inits trs_hard and trs_stringy */
/* I'm told that the hard disk controller is enabled on powerup */
/* XXX should trs_hard_init do this, then? */
trs_hard_out(TRS_HARD_CONTROL,
TRS_HARD_SOFTWARE_RESET|TRS_HARD_DEVICE_ENABLE);
supermem_base = 0;
supermem_hi = 0x8000;
if (trs_model == 5) {
/* Switch in boot ROM */
z80_out(0x9C, 1);
}
if (trs_model >= 4) {
/* Turn off various memory map and video mode bits */
z80_out(0x84, 0);
if (huffman_ram)
z80_out(0x94, 0);
if (hypermem)
z80_out(0x90, 0);
}
if (trs_model >= 3) {
grafyx_write_mode(0);
trs_interrupt_mask_write(0);
trs_nmi_mask_write(0);
}
if (trs_model == 3) {
grafyx_m3_reset();
}
if (trs_model == 1) {
hrg_onoff(0); /* Switch off HRG1B hi-res graphics. */
bank_base = 0;
selector_reg = 0;
}
trs_kb_reset(); /* Part of keyboard stretch kludge */
clear_key_queue(); /* init the key queue */
trs_cancel_event();
trs_timer_interrupt(0);
if (poweron || trs_model >= 4) {
/* Reset processor */
z80_reset();
/* Initialize memory, ROM & timer */
mem_init();
trs_rom_init();
trs_timer_init();
if (trs_show_led) {
trs_disk_led(-1, -1);
trs_hard_led(-1, -1);
trs_turbo_led();
}
} else {
trs_timer_speed(0);
/* Signal a nonmaskable interrupt. */
trs_reset_button_interrupt(1);
trs_schedule_event(trs_reset_button_interrupt, 0, 2000);
}
/* Clear screen */
screen_init();
}
#endif
void mem_map(int which)
{
memory_map = which + (trs_model << 4) + (romin << 2);
}
void mem_romin(int state)
{
romin = (state & 1);
memory_map = (memory_map & ~4) + (romin << 2);
}
void mem_init()
{
/* Initialize RAM, ROM & Video memory */
memset(memory, 0, sizeof(memory));
memset(video, 0, sizeof(video));
if (trs_model < 4)
trs_video_size = 1024;
else
trs_video_size = MAX_VIDEO_SIZE;
#ifdef SUPERMEM
/* We map the SuperMem separately, otherwise it can get really
confusing when combining with other stuff */
if (supermem_ram == NULL)
supermem_ram = (Uchar *) calloc(MAX_SUPERMEM_SIZE + 1, 1);
else
memset(supermem_ram, 0, MAX_SUPERMEM_SIZE + 1);
#endif
mem_map(0);
mem_bank(0);
mem_video_page(0);
#if 0
if (trs_model == 5) {
z80_out(0x9C, 1);
}
#endif
}
int mem_read(unsigned int address)
{
address &= 0xffff; /* allow callers to be sloppy */
/* There are some adapters that sit above the system and
either intercept before the hardware proper, or adjust
the address. Deal with these first so that we take their
output and feed it into the memory map */
#ifdef SUPERMEM
/* The SuperMem sits between the system and the Z80 */
if (supermem) {
if (!((address ^ supermem_hi) & 0x8000))
return supermem_ram[supermem_base + (address & 0x7FFF)];
/* Otherwise the request comes from the system */
}
#endif
switch (memory_map) {
case 0x30: /* Model III */
if (address >= RAM_START) return memory[address];
//if (address == PRINTER_ADDRESS) return trs_printer_read();
if (address < trs_rom_size) return rom[address];
if (address >= VIDEO_START) {
byte character;
if (trs_screen.getChar(address - VIDEO_START, character)) {
return character;
}
return memory[address];
//return grafyx_m3_read_byte(address - VIDEO_START);
}
if (address >= KEYBOARD_START) return trs_kb_mem_read(address);
return 0xff;
case 0x40: /* Model 4 map 0 */
if (address >= RAM_START) {
assert(address + bank_offset[address >> 15] < sizeof(memory));
return memory[address + bank_offset[address >> 15]];
}
//if (address == PRINTER_ADDRESS) return trs_printer_read();
if (address < trs_rom_size) return rom[address];
if (address >= VIDEO_START) {
return video[address + video_offset];
}
if (address >= KEYBOARD_START) return trs_kb_mem_read(address);
return 0xff;
case 0x54: /* Model 4P map 0, boot ROM in */
case 0x55: /* Model 4P map 1, boot ROM in */
if (address < trs_rom_size) return rom[address];
/* else fall thru */
case 0x41: /* Model 4 map 1 */
case 0x50: /* Model 4P map 0, boot ROM out */
case 0x51: /* Model 4P map 1, boot ROM out */
if (address >= RAM_START || address < KEYBOARD_START) {
assert(address + bank_offset[address >> 15] < sizeof(memory));
return memory[address + bank_offset[address >> 15]];
}
if (address >= VIDEO_START) {
return video[address + video_offset];
}
if (address >= KEYBOARD_START) return trs_kb_mem_read(address);
return 0xff;
case 0x42: /* Model 4 map 2 */
case 0x52: /* Model 4P map 2, boot ROM out */
case 0x56: /* Model 4P map 2, boot ROM in */
if (address < 0xf400) {
assert(address + bank_offset[address >> 15] < sizeof(memory));
return memory[address + bank_offset[address >> 15]];
}
if (address >= 0xf800) {
return video[address - 0xf800];
}
return trs_kb_mem_read(address);
case 0x43: /* Model 4 map 3 */
case 0x53: /* Model 4P map 3, boot ROM out */
case 0x57: /* Model 4P map 3, boot ROM in */
assert(address + bank_offset[address >> 15] < sizeof(memory));
return memory[address + bank_offset[address >> 15]];
}
/* not reached */
assert(0);
return 0xff;
}
void mem_write(unsigned int address, int value)
{
address &= 0xffff;
#ifdef SUPERMEM
/* The SuperMem sits between the system and the Z80 */
if (supermem) {
if (!((address ^ supermem_hi) & 0x8000)) {
supermem_ram[supermem_base + (address & 0x7FFF)] = value;
return;
}
/* Otherwise the request comes from the system */
}
#endif
switch (memory_map) {
case 0x30: /* Model III */
if (address >= RAM_START) {
memory[address] = value;
} else if (address >= VIDEO_START) {
int vaddr = address + video_offset;
// if (grafyx_m3_write_byte(vaddr, value)) return;
if (video[vaddr] != value) {
video[vaddr] = value;
trs_screen.drawChar(vaddr, value);
}
} else if (address == PRINTER_ADDRESS) {
//trs_printer_write(value);
}
break;
case 0x40: /* Model 4 map 0 */
case 0x50: /* Model 4P map 0, boot ROM out */
case 0x54: /* Model 4P map 0, boot ROM in */
if (address >= RAM_START) {
assert(address + bank_offset[address >> 15] < sizeof(memory));
memory[address + bank_offset[address >> 15]] = value;
} else if (address >= VIDEO_START) {
int vaddr = address + video_offset;
if (video[vaddr] != value) {
video[vaddr] = value;
trs_screen.drawChar(vaddr, value);
}
} else if (address == PRINTER_ADDRESS) {
//trs_printer_write(value);
}
break;
case 0x41: /* Model 4 map 1 */
case 0x51: /* Model 4P map 1, boot ROM out */
case 0x55: /* Model 4P map 1, boot ROM in */
if (address >= RAM_START || address < KEYBOARD_START) {
assert(address + bank_offset[address >> 15] < sizeof(memory));
memory[address + bank_offset[address >> 15]] = value;
} else if (address >= VIDEO_START) {
int vaddr = address + video_offset;
if (video[vaddr] != value) {
video[vaddr] = value;
trs_screen.drawChar(vaddr, value);
}
}
break;
case 0x42: /* Model 4 map 2 */
case 0x52: /* Model 4P map 2, boot ROM out */
case 0x56: /* Model 4P map 2, boot ROM in */
if (address < 0xf400) {
assert(address + bank_offset[address >> 15] < sizeof(memory));
memory[address + bank_offset[address >> 15]] = value;
} else if (address >= 0xf800) {
int vaddr = address - 0xf800;
if (video[vaddr] != value) {
video[vaddr] = value;
trs_screen.drawChar(vaddr, value);
}
}
break;
case 0x43: /* Model 4 map 3 */
case 0x53: /* Model 4P map 3, boot ROM out */
case 0x57: /* Model 4P map 3, boot ROM in */
assert(address + bank_offset[address >> 15] < sizeof(memory));
memory[address + bank_offset[address >> 15]] = value;
break;
default:
assert(0);
}
}
/*
* Words are stored with the low-order byte in the lower address.
*/
int mem_read_word(int address)
{
int rval;
rval = mem_read(address++);
rval |= mem_read(address & 0xffff) << 8;
return rval;
}
void mem_write_word(int address, int value)
{
mem_write(address++, value & 0xff);
mem_write(address, value >> 8);
}
| 29.196364 | 79 | 0.651825 | [
"model"
] |
a39a37c9a4f190d8cc7f6dd1ebddefc6fa6ab10c | 93,324 | cc | C++ | binutils/gold/object.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | 1 | 2016-04-09T02:58:13.000Z | 2016-04-09T02:58:13.000Z | binutils/gold/object.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | binutils/gold/object.cc | vidkidz/crossbridge | ba0bf94aee0ce6cf7eb5be882382e52bc57ba396 | [
"MIT"
] | null | null | null | // object.cc -- support for an object file for linking in gold
// Copyright 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
// Written by Ian Lance Taylor <iant@google.com>.
// This file is part of gold.
// 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 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
// MA 02110-1301, USA.
#include "gold.h"
#include <cerrno>
#include <cstring>
#include <cstdarg>
#include "demangle.h"
#include "libiberty.h"
#include "gc.h"
#include "target-select.h"
#include "dwarf_reader.h"
#include "layout.h"
#include "output.h"
#include "symtab.h"
#include "cref.h"
#include "reloc.h"
#include "object.h"
#include "dynobj.h"
#include "plugin.h"
#include "compressed_output.h"
#include "incremental.h"
namespace gold
{
// Struct Read_symbols_data.
// Destroy any remaining File_view objects.
Read_symbols_data::~Read_symbols_data()
{
if (this->section_headers != NULL)
delete this->section_headers;
if (this->section_names != NULL)
delete this->section_names;
if (this->symbols != NULL)
delete this->symbols;
if (this->symbol_names != NULL)
delete this->symbol_names;
if (this->versym != NULL)
delete this->versym;
if (this->verdef != NULL)
delete this->verdef;
if (this->verneed != NULL)
delete this->verneed;
}
// Class Xindex.
// Initialize the symtab_xindex_ array. Find the SHT_SYMTAB_SHNDX
// section and read it in. SYMTAB_SHNDX is the index of the symbol
// table we care about.
template<int size, bool big_endian>
void
Xindex::initialize_symtab_xindex(Object* object, unsigned int symtab_shndx)
{
if (!this->symtab_xindex_.empty())
return;
gold_assert(symtab_shndx != 0);
// Look through the sections in reverse order, on the theory that it
// is more likely to be near the end than the beginning.
unsigned int i = object->shnum();
while (i > 0)
{
--i;
if (object->section_type(i) == elfcpp::SHT_SYMTAB_SHNDX
&& this->adjust_shndx(object->section_link(i)) == symtab_shndx)
{
this->read_symtab_xindex<size, big_endian>(object, i, NULL);
return;
}
}
object->error(_("missing SHT_SYMTAB_SHNDX section"));
}
// Read in the symtab_xindex_ array, given the section index of the
// SHT_SYMTAB_SHNDX section. If PSHDRS is not NULL, it points at the
// section headers.
template<int size, bool big_endian>
void
Xindex::read_symtab_xindex(Object* object, unsigned int xindex_shndx,
const unsigned char* pshdrs)
{
section_size_type bytecount;
const unsigned char* contents;
if (pshdrs == NULL)
contents = object->section_contents(xindex_shndx, &bytecount, false);
else
{
const unsigned char* p = (pshdrs
+ (xindex_shndx
* elfcpp::Elf_sizes<size>::shdr_size));
typename elfcpp::Shdr<size, big_endian> shdr(p);
bytecount = convert_to_section_size_type(shdr.get_sh_size());
contents = object->get_view(shdr.get_sh_offset(), bytecount, true, false);
}
gold_assert(this->symtab_xindex_.empty());
this->symtab_xindex_.reserve(bytecount / 4);
for (section_size_type i = 0; i < bytecount; i += 4)
{
unsigned int shndx = elfcpp::Swap<32, big_endian>::readval(contents + i);
// We preadjust the section indexes we save.
this->symtab_xindex_.push_back(this->adjust_shndx(shndx));
}
}
// Symbol symndx has a section of SHN_XINDEX; return the real section
// index.
unsigned int
Xindex::sym_xindex_to_shndx(Object* object, unsigned int symndx)
{
if (symndx >= this->symtab_xindex_.size())
{
object->error(_("symbol %u out of range for SHT_SYMTAB_SHNDX section"),
symndx);
return elfcpp::SHN_UNDEF;
}
unsigned int shndx = this->symtab_xindex_[symndx];
if (shndx < elfcpp::SHN_LORESERVE || shndx >= object->shnum())
{
object->error(_("extended index for symbol %u out of range: %u"),
symndx, shndx);
return elfcpp::SHN_UNDEF;
}
return shndx;
}
// Class Object.
// Report an error for this object file. This is used by the
// elfcpp::Elf_file interface, and also called by the Object code
// itself.
void
Object::error(const char* format, ...) const
{
va_list args;
va_start(args, format);
char* buf = NULL;
if (vasprintf(&buf, format, args) < 0)
gold_nomem();
va_end(args);
gold_error(_("%s: %s"), this->name().c_str(), buf);
free(buf);
}
// Return a view of the contents of a section.
const unsigned char*
Object::section_contents(unsigned int shndx, section_size_type* plen,
bool cache)
{
Location loc(this->do_section_contents(shndx));
*plen = convert_to_section_size_type(loc.data_size);
if (*plen == 0)
{
static const unsigned char empty[1] = { '\0' };
return empty;
}
return this->get_view(loc.file_offset, *plen, true, cache);
}
// Read the section data into SD. This is code common to Sized_relobj
// and Sized_dynobj, so we put it into Object.
template<int size, bool big_endian>
void
Object::read_section_data(elfcpp::Elf_file<size, big_endian, Object>* elf_file,
Read_symbols_data* sd)
{
const int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
// Read the section headers.
const off_t shoff = elf_file->shoff();
const unsigned int shnum = this->shnum();
sd->section_headers = this->get_lasting_view(shoff, shnum * shdr_size,
true, true);
// Read the section names.
const unsigned char* pshdrs = sd->section_headers->data();
const unsigned char* pshdrnames = pshdrs + elf_file->shstrndx() * shdr_size;
typename elfcpp::Shdr<size, big_endian> shdrnames(pshdrnames);
if (shdrnames.get_sh_type() != elfcpp::SHT_STRTAB)
this->error(_("section name section has wrong type: %u"),
static_cast<unsigned int>(shdrnames.get_sh_type()));
sd->section_names_size =
convert_to_section_size_type(shdrnames.get_sh_size());
sd->section_names = this->get_lasting_view(shdrnames.get_sh_offset(),
sd->section_names_size, false,
false);
}
// If NAME is the name of a special .gnu.warning section, arrange for
// the warning to be issued. SHNDX is the section index. Return
// whether it is a warning section.
bool
Object::handle_gnu_warning_section(const char* name, unsigned int shndx,
Symbol_table* symtab)
{
const char warn_prefix[] = ".gnu.warning.";
const int warn_prefix_len = sizeof warn_prefix - 1;
if (strncmp(name, warn_prefix, warn_prefix_len) == 0)
{
// Read the section contents to get the warning text. It would
// be nicer if we only did this if we have to actually issue a
// warning. Unfortunately, warnings are issued as we relocate
// sections. That means that we can not lock the object then,
// as we might try to issue the same warning multiple times
// simultaneously.
section_size_type len;
const unsigned char* contents = this->section_contents(shndx, &len,
false);
if (len == 0)
{
const char* warning = name + warn_prefix_len;
contents = reinterpret_cast<const unsigned char*>(warning);
len = strlen(warning);
}
std::string warning(reinterpret_cast<const char*>(contents), len);
symtab->add_warning(name + warn_prefix_len, this, warning);
return true;
}
return false;
}
// If NAME is the name of the special section which indicates that
// this object was compiled with -fsplit-stack, mark it accordingly.
bool
Object::handle_split_stack_section(const char* name)
{
if (strcmp(name, ".note.GNU-split-stack") == 0)
{
this->uses_split_stack_ = true;
return true;
}
if (strcmp(name, ".note.GNU-no-split-stack") == 0)
{
this->has_no_split_stack_ = true;
return true;
}
return false;
}
// Class Relobj
// To copy the symbols data read from the file to a local data structure.
// This function is called from do_layout only while doing garbage
// collection.
void
Relobj::copy_symbols_data(Symbols_data* gc_sd, Read_symbols_data* sd,
unsigned int section_header_size)
{
gc_sd->section_headers_data =
new unsigned char[(section_header_size)];
memcpy(gc_sd->section_headers_data, sd->section_headers->data(),
section_header_size);
gc_sd->section_names_data =
new unsigned char[sd->section_names_size];
memcpy(gc_sd->section_names_data, sd->section_names->data(),
sd->section_names_size);
gc_sd->section_names_size = sd->section_names_size;
if (sd->symbols != NULL)
{
gc_sd->symbols_data =
new unsigned char[sd->symbols_size];
memcpy(gc_sd->symbols_data, sd->symbols->data(),
sd->symbols_size);
}
else
{
gc_sd->symbols_data = NULL;
}
gc_sd->symbols_size = sd->symbols_size;
gc_sd->external_symbols_offset = sd->external_symbols_offset;
if (sd->symbol_names != NULL)
{
gc_sd->symbol_names_data =
new unsigned char[sd->symbol_names_size];
memcpy(gc_sd->symbol_names_data, sd->symbol_names->data(),
sd->symbol_names_size);
}
else
{
gc_sd->symbol_names_data = NULL;
}
gc_sd->symbol_names_size = sd->symbol_names_size;
}
// This function determines if a particular section name must be included
// in the link. This is used during garbage collection to determine the
// roots of the worklist.
bool
Relobj::is_section_name_included(const char* name)
{
if (is_prefix_of(".ctors", name)
|| is_prefix_of(".dtors", name)
|| is_prefix_of(".note", name)
|| is_prefix_of(".init", name)
|| is_prefix_of(".fini", name)
|| is_prefix_of(".gcc_except_table", name)
|| is_prefix_of(".jcr", name)
|| is_prefix_of(".preinit_array", name)
|| (is_prefix_of(".text", name)
&& strstr(name, "personality"))
|| (is_prefix_of(".data", name)
&& strstr(name, "personality"))
|| (is_prefix_of(".gnu.linkonce.d", name)
&& strstr(name, "personality")))
{
return true;
}
return false;
}
// Finalize the incremental relocation information. Allocates a block
// of relocation entries for each symbol, and sets the reloc_bases_
// array to point to the first entry in each block. If CLEAR_COUNTS
// is TRUE, also clear the per-symbol relocation counters.
void
Relobj::finalize_incremental_relocs(Layout* layout, bool clear_counts)
{
unsigned int nsyms = this->get_global_symbols()->size();
this->reloc_bases_ = new unsigned int[nsyms];
gold_assert(this->reloc_bases_ != NULL);
gold_assert(layout->incremental_inputs() != NULL);
unsigned int rindex = layout->incremental_inputs()->get_reloc_count();
for (unsigned int i = 0; i < nsyms; ++i)
{
this->reloc_bases_[i] = rindex;
rindex += this->reloc_counts_[i];
if (clear_counts)
this->reloc_counts_[i] = 0;
}
layout->incremental_inputs()->set_reloc_count(rindex);
}
// Class Sized_relobj.
template<int size, bool big_endian>
Sized_relobj<size, big_endian>::Sized_relobj(
const std::string& name,
Input_file* input_file,
off_t offset,
const elfcpp::Ehdr<size, big_endian>& ehdr)
: Sized_relobj_base<size, big_endian>(name, input_file, offset),
elf_file_(this, ehdr),
symtab_shndx_(-1U),
local_symbol_count_(0),
output_local_symbol_count_(0),
output_local_dynsym_count_(0),
symbols_(),
defined_count_(0),
local_symbol_offset_(0),
local_dynsym_offset_(0),
local_values_(),
local_got_offsets_(),
local_plt_offsets_(),
kept_comdat_sections_(),
has_eh_frame_(false),
discarded_eh_frame_shndx_(-1U),
deferred_layout_(),
deferred_layout_relocs_(),
compressed_sections_()
{
}
template<int size, bool big_endian>
Sized_relobj<size, big_endian>::~Sized_relobj()
{
}
// Set up an object file based on the file header. This sets up the
// section information.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_setup()
{
const unsigned int shnum = this->elf_file_.shnum();
this->set_shnum(shnum);
}
// Find the SHT_SYMTAB section, given the section headers. The ELF
// standard says that maybe in the future there can be more than one
// SHT_SYMTAB section. Until somebody figures out how that could
// work, we assume there is only one.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::find_symtab(const unsigned char* pshdrs)
{
const unsigned int shnum = this->shnum();
this->symtab_shndx_ = 0;
if (shnum > 0)
{
// Look through the sections in reverse order, since gas tends
// to put the symbol table at the end.
const unsigned char* p = pshdrs + shnum * This::shdr_size;
unsigned int i = shnum;
unsigned int xindex_shndx = 0;
unsigned int xindex_link = 0;
while (i > 0)
{
--i;
p -= This::shdr_size;
typename This::Shdr shdr(p);
if (shdr.get_sh_type() == elfcpp::SHT_SYMTAB)
{
this->symtab_shndx_ = i;
if (xindex_shndx > 0 && xindex_link == i)
{
Xindex* xindex =
new Xindex(this->elf_file_.large_shndx_offset());
xindex->read_symtab_xindex<size, big_endian>(this,
xindex_shndx,
pshdrs);
this->set_xindex(xindex);
}
break;
}
// Try to pick up the SHT_SYMTAB_SHNDX section, if there is
// one. This will work if it follows the SHT_SYMTAB
// section.
if (shdr.get_sh_type() == elfcpp::SHT_SYMTAB_SHNDX)
{
xindex_shndx = i;
xindex_link = this->adjust_shndx(shdr.get_sh_link());
}
}
}
}
// Return the Xindex structure to use for object with lots of
// sections.
template<int size, bool big_endian>
Xindex*
Sized_relobj<size, big_endian>::do_initialize_xindex()
{
gold_assert(this->symtab_shndx_ != -1U);
Xindex* xindex = new Xindex(this->elf_file_.large_shndx_offset());
xindex->initialize_symtab_xindex<size, big_endian>(this, this->symtab_shndx_);
return xindex;
}
// Return whether SHDR has the right type and flags to be a GNU
// .eh_frame section.
template<int size, bool big_endian>
bool
Sized_relobj<size, big_endian>::check_eh_frame_flags(
const elfcpp::Shdr<size, big_endian>* shdr) const
{
return (shdr->get_sh_type() == elfcpp::SHT_PROGBITS
&& (shdr->get_sh_flags() & elfcpp::SHF_ALLOC) != 0);
}
// Return whether there is a GNU .eh_frame section, given the section
// headers and the section names.
template<int size, bool big_endian>
bool
Sized_relobj<size, big_endian>::find_eh_frame(
const unsigned char* pshdrs,
const char* names,
section_size_type names_size) const
{
const unsigned int shnum = this->shnum();
const unsigned char* p = pshdrs + This::shdr_size;
for (unsigned int i = 1; i < shnum; ++i, p += This::shdr_size)
{
typename This::Shdr shdr(p);
if (this->check_eh_frame_flags(&shdr))
{
if (shdr.get_sh_name() >= names_size)
{
this->error(_("bad section name offset for section %u: %lu"),
i, static_cast<unsigned long>(shdr.get_sh_name()));
continue;
}
const char* name = names + shdr.get_sh_name();
if (strcmp(name, ".eh_frame") == 0)
return true;
}
}
return false;
}
// Build a table for any compressed debug sections, mapping each section index
// to the uncompressed size.
template<int size, bool big_endian>
Compressed_section_map*
build_compressed_section_map(
const unsigned char* pshdrs,
unsigned int shnum,
const char* names,
section_size_type names_size,
Sized_relobj<size, big_endian>* obj)
{
Compressed_section_map* uncompressed_sizes = new Compressed_section_map();
const unsigned int shdr_size = elfcpp::Elf_sizes<size>::shdr_size;
const unsigned char* p = pshdrs + shdr_size;
for (unsigned int i = 1; i < shnum; ++i, p += shdr_size)
{
typename elfcpp::Shdr<size, big_endian> shdr(p);
if (shdr.get_sh_type() == elfcpp::SHT_PROGBITS
&& (shdr.get_sh_flags() & elfcpp::SHF_ALLOC) == 0)
{
if (shdr.get_sh_name() >= names_size)
{
obj->error(_("bad section name offset for section %u: %lu"),
i, static_cast<unsigned long>(shdr.get_sh_name()));
continue;
}
const char* name = names + shdr.get_sh_name();
if (is_compressed_debug_section(name))
{
section_size_type len;
const unsigned char* contents =
obj->section_contents(i, &len, false);
uint64_t uncompressed_size = get_uncompressed_size(contents, len);
if (uncompressed_size != -1ULL)
(*uncompressed_sizes)[i] =
convert_to_section_size_type(uncompressed_size);
}
}
}
return uncompressed_sizes;
}
// Read the sections and symbols from an object file.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_read_symbols(Read_symbols_data* sd)
{
this->read_section_data(&this->elf_file_, sd);
const unsigned char* const pshdrs = sd->section_headers->data();
this->find_symtab(pshdrs);
const unsigned char* namesu = sd->section_names->data();
const char* names = reinterpret_cast<const char*>(namesu);
if (memmem(names, sd->section_names_size, ".eh_frame", 10) != NULL)
{
if (this->find_eh_frame(pshdrs, names, sd->section_names_size))
this->has_eh_frame_ = true;
}
if (memmem(names, sd->section_names_size, ".zdebug_", 8) != NULL)
this->compressed_sections_ =
build_compressed_section_map(pshdrs, this->shnum(), names,
sd->section_names_size, this);
sd->symbols = NULL;
sd->symbols_size = 0;
sd->external_symbols_offset = 0;
sd->symbol_names = NULL;
sd->symbol_names_size = 0;
if (this->symtab_shndx_ == 0)
{
// No symbol table. Weird but legal.
return;
}
// Get the symbol table section header.
typename This::Shdr symtabshdr(pshdrs
+ this->symtab_shndx_ * This::shdr_size);
gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
// If this object has a .eh_frame section, we need all the symbols.
// Otherwise we only need the external symbols. While it would be
// simpler to just always read all the symbols, I've seen object
// files with well over 2000 local symbols, which for a 64-bit
// object file format is over 5 pages that we don't need to read
// now.
const int sym_size = This::sym_size;
const unsigned int loccount = symtabshdr.get_sh_info();
this->local_symbol_count_ = loccount;
this->local_values_.resize(loccount);
section_offset_type locsize = loccount * sym_size;
off_t dataoff = symtabshdr.get_sh_offset();
section_size_type datasize =
convert_to_section_size_type(symtabshdr.get_sh_size());
off_t extoff = dataoff + locsize;
section_size_type extsize = datasize - locsize;
off_t readoff = this->has_eh_frame_ ? dataoff : extoff;
section_size_type readsize = this->has_eh_frame_ ? datasize : extsize;
if (readsize == 0)
{
// No external symbols. Also weird but also legal.
return;
}
File_view* fvsymtab = this->get_lasting_view(readoff, readsize, true, false);
// Read the section header for the symbol names.
unsigned int strtab_shndx = this->adjust_shndx(symtabshdr.get_sh_link());
if (strtab_shndx >= this->shnum())
{
this->error(_("invalid symbol table name index: %u"), strtab_shndx);
return;
}
typename This::Shdr strtabshdr(pshdrs + strtab_shndx * This::shdr_size);
if (strtabshdr.get_sh_type() != elfcpp::SHT_STRTAB)
{
this->error(_("symbol table name section has wrong type: %u"),
static_cast<unsigned int>(strtabshdr.get_sh_type()));
return;
}
// Read the symbol names.
File_view* fvstrtab = this->get_lasting_view(strtabshdr.get_sh_offset(),
strtabshdr.get_sh_size(),
false, true);
sd->symbols = fvsymtab;
sd->symbols_size = readsize;
sd->external_symbols_offset = this->has_eh_frame_ ? locsize : 0;
sd->symbol_names = fvstrtab;
sd->symbol_names_size =
convert_to_section_size_type(strtabshdr.get_sh_size());
}
// Return the section index of symbol SYM. Set *VALUE to its value in
// the object file. Set *IS_ORDINARY if this is an ordinary section
// index, not a special code between SHN_LORESERVE and SHN_HIRESERVE.
// Note that for a symbol which is not defined in this object file,
// this will set *VALUE to 0 and return SHN_UNDEF; it will not return
// the final value of the symbol in the link.
template<int size, bool big_endian>
unsigned int
Sized_relobj<size, big_endian>::symbol_section_and_value(unsigned int sym,
Address* value,
bool* is_ordinary)
{
section_size_type symbols_size;
const unsigned char* symbols = this->section_contents(this->symtab_shndx_,
&symbols_size,
false);
const size_t count = symbols_size / This::sym_size;
gold_assert(sym < count);
elfcpp::Sym<size, big_endian> elfsym(symbols + sym * This::sym_size);
*value = elfsym.get_st_value();
return this->adjust_sym_shndx(sym, elfsym.get_st_shndx(), is_ordinary);
}
// Return whether to include a section group in the link. LAYOUT is
// used to keep track of which section groups we have already seen.
// INDEX is the index of the section group and SHDR is the section
// header. If we do not want to include this group, we set bits in
// OMIT for each section which should be discarded.
template<int size, bool big_endian>
bool
Sized_relobj<size, big_endian>::include_section_group(
Symbol_table* symtab,
Layout* layout,
unsigned int index,
const char* name,
const unsigned char* shdrs,
const char* section_names,
section_size_type section_names_size,
std::vector<bool>* omit)
{
// Read the section contents.
typename This::Shdr shdr(shdrs + index * This::shdr_size);
const unsigned char* pcon = this->get_view(shdr.get_sh_offset(),
shdr.get_sh_size(), true, false);
const elfcpp::Elf_Word* pword =
reinterpret_cast<const elfcpp::Elf_Word*>(pcon);
// The first word contains flags. We only care about COMDAT section
// groups. Other section groups are always included in the link
// just like ordinary sections.
elfcpp::Elf_Word flags = elfcpp::Swap<32, big_endian>::readval(pword);
// Look up the group signature, which is the name of a symbol. This
// is a lot of effort to go to to read a string. Why didn't they
// just have the group signature point into the string table, rather
// than indirect through a symbol?
// Get the appropriate symbol table header (this will normally be
// the single SHT_SYMTAB section, but in principle it need not be).
const unsigned int link = this->adjust_shndx(shdr.get_sh_link());
typename This::Shdr symshdr(this, this->elf_file_.section_header(link));
// Read the symbol table entry.
unsigned int symndx = shdr.get_sh_info();
if (symndx >= symshdr.get_sh_size() / This::sym_size)
{
this->error(_("section group %u info %u out of range"),
index, symndx);
return false;
}
off_t symoff = symshdr.get_sh_offset() + symndx * This::sym_size;
const unsigned char* psym = this->get_view(symoff, This::sym_size, true,
false);
elfcpp::Sym<size, big_endian> sym(psym);
// Read the symbol table names.
section_size_type symnamelen;
const unsigned char* psymnamesu;
psymnamesu = this->section_contents(this->adjust_shndx(symshdr.get_sh_link()),
&symnamelen, true);
const char* psymnames = reinterpret_cast<const char*>(psymnamesu);
// Get the section group signature.
if (sym.get_st_name() >= symnamelen)
{
this->error(_("symbol %u name offset %u out of range"),
symndx, sym.get_st_name());
return false;
}
std::string signature(psymnames + sym.get_st_name());
// It seems that some versions of gas will create a section group
// associated with a section symbol, and then fail to give a name to
// the section symbol. In such a case, use the name of the section.
if (signature[0] == '\0' && sym.get_st_type() == elfcpp::STT_SECTION)
{
bool is_ordinary;
unsigned int sym_shndx = this->adjust_sym_shndx(symndx,
sym.get_st_shndx(),
&is_ordinary);
if (!is_ordinary || sym_shndx >= this->shnum())
{
this->error(_("symbol %u invalid section index %u"),
symndx, sym_shndx);
return false;
}
typename This::Shdr member_shdr(shdrs + sym_shndx * This::shdr_size);
if (member_shdr.get_sh_name() < section_names_size)
signature = section_names + member_shdr.get_sh_name();
}
// Record this section group in the layout, and see whether we've already
// seen one with the same signature.
bool include_group;
bool is_comdat;
Kept_section* kept_section = NULL;
if ((flags & elfcpp::GRP_COMDAT) == 0)
{
include_group = true;
is_comdat = false;
}
else
{
include_group = layout->find_or_add_kept_section(signature,
this, index, true,
true, &kept_section);
is_comdat = true;
}
size_t count = shdr.get_sh_size() / sizeof(elfcpp::Elf_Word);
std::vector<unsigned int> shndxes;
bool relocate_group = include_group && parameters->options().relocatable();
if (relocate_group)
shndxes.reserve(count - 1);
for (size_t i = 1; i < count; ++i)
{
elfcpp::Elf_Word shndx =
this->adjust_shndx(elfcpp::Swap<32, big_endian>::readval(pword + i));
if (relocate_group)
shndxes.push_back(shndx);
if (shndx >= this->shnum())
{
this->error(_("section %u in section group %u out of range"),
shndx, index);
continue;
}
// Check for an earlier section number, since we're going to get
// it wrong--we may have already decided to include the section.
if (shndx < index)
this->error(_("invalid section group %u refers to earlier section %u"),
index, shndx);
// Get the name of the member section.
typename This::Shdr member_shdr(shdrs + shndx * This::shdr_size);
if (member_shdr.get_sh_name() >= section_names_size)
{
// This is an error, but it will be diagnosed eventually
// in do_layout, so we don't need to do anything here but
// ignore it.
continue;
}
std::string mname(section_names + member_shdr.get_sh_name());
if (include_group)
{
if (is_comdat)
kept_section->add_comdat_section(mname, shndx,
member_shdr.get_sh_size());
}
else
{
(*omit)[shndx] = true;
if (is_comdat)
{
Relobj* kept_object = kept_section->object();
if (kept_section->is_comdat())
{
// Find the corresponding kept section, and store
// that info in the discarded section table.
unsigned int kept_shndx;
uint64_t kept_size;
if (kept_section->find_comdat_section(mname, &kept_shndx,
&kept_size))
{
// We don't keep a mapping for this section if
// it has a different size. The mapping is only
// used for relocation processing, and we don't
// want to treat the sections as similar if the
// sizes are different. Checking the section
// size is the approach used by the GNU linker.
if (kept_size == member_shdr.get_sh_size())
this->set_kept_comdat_section(shndx, kept_object,
kept_shndx);
}
}
else
{
// The existing section is a linkonce section. Add
// a mapping if there is exactly one section in the
// group (which is true when COUNT == 2) and if it
// is the same size.
if (count == 2
&& (kept_section->linkonce_size()
== member_shdr.get_sh_size()))
this->set_kept_comdat_section(shndx, kept_object,
kept_section->shndx());
}
}
}
}
if (relocate_group)
layout->layout_group(symtab, this, index, name, signature.c_str(),
shdr, flags, &shndxes);
return include_group;
}
// Whether to include a linkonce section in the link. NAME is the
// name of the section and SHDR is the section header.
// Linkonce sections are a GNU extension implemented in the original
// GNU linker before section groups were defined. The semantics are
// that we only include one linkonce section with a given name. The
// name of a linkonce section is normally .gnu.linkonce.T.SYMNAME,
// where T is the type of section and SYMNAME is the name of a symbol.
// In an attempt to make linkonce sections interact well with section
// groups, we try to identify SYMNAME and use it like a section group
// signature. We want to block section groups with that signature,
// but not other linkonce sections with that signature. We also use
// the full name of the linkonce section as a normal section group
// signature.
template<int size, bool big_endian>
bool
Sized_relobj<size, big_endian>::include_linkonce_section(
Layout* layout,
unsigned int index,
const char* name,
const elfcpp::Shdr<size, big_endian>& shdr)
{
typename elfcpp::Elf_types<size>::Elf_WXword sh_size = shdr.get_sh_size();
// In general the symbol name we want will be the string following
// the last '.'. However, we have to handle the case of
// .gnu.linkonce.t.__i686.get_pc_thunk.bx, which was generated by
// some versions of gcc. So we use a heuristic: if the name starts
// with ".gnu.linkonce.t.", we use everything after that. Otherwise
// we look for the last '.'. We can't always simply skip
// ".gnu.linkonce.X", because we have to deal with cases like
// ".gnu.linkonce.d.rel.ro.local".
const char* const linkonce_t = ".gnu.linkonce.t.";
const char* symname;
if (strncmp(name, linkonce_t, strlen(linkonce_t)) == 0)
symname = name + strlen(linkonce_t);
else
symname = strrchr(name, '.') + 1;
std::string sig1(symname);
std::string sig2(name);
Kept_section* kept1;
Kept_section* kept2;
bool include1 = layout->find_or_add_kept_section(sig1, this, index, false,
false, &kept1);
bool include2 = layout->find_or_add_kept_section(sig2, this, index, false,
true, &kept2);
if (!include2)
{
// We are not including this section because we already saw the
// name of the section as a signature. This normally implies
// that the kept section is another linkonce section. If it is
// the same size, record it as the section which corresponds to
// this one.
if (kept2->object() != NULL
&& !kept2->is_comdat()
&& kept2->linkonce_size() == sh_size)
this->set_kept_comdat_section(index, kept2->object(), kept2->shndx());
}
else if (!include1)
{
// The section is being discarded on the basis of its symbol
// name. This means that the corresponding kept section was
// part of a comdat group, and it will be difficult to identify
// the specific section within that group that corresponds to
// this linkonce section. We'll handle the simple case where
// the group has only one member section. Otherwise, it's not
// worth the effort.
unsigned int kept_shndx;
uint64_t kept_size;
if (kept1->object() != NULL
&& kept1->is_comdat()
&& kept1->find_single_comdat_section(&kept_shndx, &kept_size)
&& kept_size == sh_size)
this->set_kept_comdat_section(index, kept1->object(), kept_shndx);
}
else
{
kept1->set_linkonce_size(sh_size);
kept2->set_linkonce_size(sh_size);
}
return include1 && include2;
}
// Layout an input section.
template<int size, bool big_endian>
inline void
Sized_relobj<size, big_endian>::layout_section(Layout* layout,
unsigned int shndx,
const char* name,
typename This::Shdr& shdr,
unsigned int reloc_shndx,
unsigned int reloc_type)
{
off_t offset;
Output_section* os = layout->layout(this, shndx, name, shdr,
reloc_shndx, reloc_type, &offset);
this->output_sections()[shndx] = os;
if (offset == -1)
this->section_offsets_[shndx] = invalid_address;
else
this->section_offsets_[shndx] = convert_types<Address, off_t>(offset);
// If this section requires special handling, and if there are
// relocs that apply to it, then we must do the special handling
// before we apply the relocs.
if (offset == -1 && reloc_shndx != 0)
this->set_relocs_must_follow_section_writes();
}
// Lay out the input sections. We walk through the sections and check
// whether they should be included in the link. If they should, we
// pass them to the Layout object, which will return an output section
// and an offset.
// During garbage collection (--gc-sections) and identical code folding
// (--icf), this function is called twice. When it is called the first
// time, it is for setting up some sections as roots to a work-list for
// --gc-sections and to do comdat processing. Actual layout happens the
// second time around after all the relevant sections have been determined.
// The first time, is_worklist_ready or is_icf_ready is false. It is then
// set to true after the garbage collection worklist or identical code
// folding is processed and the relevant sections to be kept are
// determined. Then, this function is called again to layout the sections.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_layout(Symbol_table* symtab,
Layout* layout,
Read_symbols_data* sd)
{
const unsigned int shnum = this->shnum();
bool is_gc_pass_one = ((parameters->options().gc_sections()
&& !symtab->gc()->is_worklist_ready())
|| (parameters->options().icf_enabled()
&& !symtab->icf()->is_icf_ready()));
bool is_gc_pass_two = ((parameters->options().gc_sections()
&& symtab->gc()->is_worklist_ready())
|| (parameters->options().icf_enabled()
&& symtab->icf()->is_icf_ready()));
bool is_gc_or_icf = (parameters->options().gc_sections()
|| parameters->options().icf_enabled());
// Both is_gc_pass_one and is_gc_pass_two should not be true.
gold_assert(!(is_gc_pass_one && is_gc_pass_two));
if (shnum == 0)
return;
Symbols_data* gc_sd = NULL;
if (is_gc_pass_one)
{
// During garbage collection save the symbols data to use it when
// re-entering this function.
gc_sd = new Symbols_data;
this->copy_symbols_data(gc_sd, sd, This::shdr_size * shnum);
this->set_symbols_data(gc_sd);
}
else if (is_gc_pass_two)
{
gc_sd = this->get_symbols_data();
}
const unsigned char* section_headers_data = NULL;
section_size_type section_names_size;
const unsigned char* symbols_data = NULL;
section_size_type symbols_size;
section_offset_type external_symbols_offset;
const unsigned char* symbol_names_data = NULL;
section_size_type symbol_names_size;
if (is_gc_or_icf)
{
section_headers_data = gc_sd->section_headers_data;
section_names_size = gc_sd->section_names_size;
symbols_data = gc_sd->symbols_data;
symbols_size = gc_sd->symbols_size;
external_symbols_offset = gc_sd->external_symbols_offset;
symbol_names_data = gc_sd->symbol_names_data;
symbol_names_size = gc_sd->symbol_names_size;
}
else
{
section_headers_data = sd->section_headers->data();
section_names_size = sd->section_names_size;
if (sd->symbols != NULL)
symbols_data = sd->symbols->data();
symbols_size = sd->symbols_size;
external_symbols_offset = sd->external_symbols_offset;
if (sd->symbol_names != NULL)
symbol_names_data = sd->symbol_names->data();
symbol_names_size = sd->symbol_names_size;
}
// Get the section headers.
const unsigned char* shdrs = section_headers_data;
const unsigned char* pshdrs;
// Get the section names.
const unsigned char* pnamesu = (is_gc_or_icf)
? gc_sd->section_names_data
: sd->section_names->data();
const char* pnames = reinterpret_cast<const char*>(pnamesu);
// If any input files have been claimed by plugins, we need to defer
// actual layout until the replacement files have arrived.
const bool should_defer_layout =
(parameters->options().has_plugins()
&& parameters->options().plugins()->should_defer_layout());
unsigned int num_sections_to_defer = 0;
// For each section, record the index of the reloc section if any.
// Use 0 to mean that there is no reloc section, -1U to mean that
// there is more than one.
std::vector<unsigned int> reloc_shndx(shnum, 0);
std::vector<unsigned int> reloc_type(shnum, elfcpp::SHT_NULL);
// Skip the first, dummy, section.
pshdrs = shdrs + This::shdr_size;
for (unsigned int i = 1; i < shnum; ++i, pshdrs += This::shdr_size)
{
typename This::Shdr shdr(pshdrs);
// Count the number of sections whose layout will be deferred.
if (should_defer_layout && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC))
++num_sections_to_defer;
unsigned int sh_type = shdr.get_sh_type();
if (sh_type == elfcpp::SHT_REL || sh_type == elfcpp::SHT_RELA)
{
unsigned int target_shndx = this->adjust_shndx(shdr.get_sh_info());
if (target_shndx == 0 || target_shndx >= shnum)
{
this->error(_("relocation section %u has bad info %u"),
i, target_shndx);
continue;
}
if (reloc_shndx[target_shndx] != 0)
reloc_shndx[target_shndx] = -1U;
else
{
reloc_shndx[target_shndx] = i;
reloc_type[target_shndx] = sh_type;
}
}
}
Output_sections& out_sections(this->output_sections());
std::vector<Address>& out_section_offsets(this->section_offsets_);
if (!is_gc_pass_two)
{
out_sections.resize(shnum);
out_section_offsets.resize(shnum);
}
// If we are only linking for symbols, then there is nothing else to
// do here.
if (this->input_file()->just_symbols())
{
if (!is_gc_pass_two)
{
delete sd->section_headers;
sd->section_headers = NULL;
delete sd->section_names;
sd->section_names = NULL;
}
return;
}
if (num_sections_to_defer > 0)
{
parameters->options().plugins()->add_deferred_layout_object(this);
this->deferred_layout_.reserve(num_sections_to_defer);
}
// Whether we've seen a .note.GNU-stack section.
bool seen_gnu_stack = false;
// The flags of a .note.GNU-stack section.
uint64_t gnu_stack_flags = 0;
// Keep track of which sections to omit.
std::vector<bool> omit(shnum, false);
// Keep track of reloc sections when emitting relocations.
const bool relocatable = parameters->options().relocatable();
const bool emit_relocs = (relocatable
|| parameters->options().emit_relocs());
std::vector<unsigned int> reloc_sections;
// Keep track of .eh_frame sections.
std::vector<unsigned int> eh_frame_sections;
// Skip the first, dummy, section.
pshdrs = shdrs + This::shdr_size;
for (unsigned int i = 1; i < shnum; ++i, pshdrs += This::shdr_size)
{
typename This::Shdr shdr(pshdrs);
if (shdr.get_sh_name() >= section_names_size)
{
this->error(_("bad section name offset for section %u: %lu"),
i, static_cast<unsigned long>(shdr.get_sh_name()));
return;
}
const char* name = pnames + shdr.get_sh_name();
if (!is_gc_pass_two)
{
if (this->handle_gnu_warning_section(name, i, symtab))
{
if (!relocatable)
omit[i] = true;
}
// The .note.GNU-stack section is special. It gives the
// protection flags that this object file requires for the stack
// in memory.
if (strcmp(name, ".note.GNU-stack") == 0)
{
seen_gnu_stack = true;
gnu_stack_flags |= shdr.get_sh_flags();
omit[i] = true;
}
// The .note.GNU-split-stack section is also special. It
// indicates that the object was compiled with
// -fsplit-stack.
if (this->handle_split_stack_section(name))
{
if (!parameters->options().relocatable()
&& !parameters->options().shared())
omit[i] = true;
}
// Skip attributes section.
if (parameters->target().is_attributes_section(name))
{
omit[i] = true;
}
bool discard = omit[i];
if (!discard)
{
if (shdr.get_sh_type() == elfcpp::SHT_GROUP)
{
if (!this->include_section_group(symtab, layout, i, name,
shdrs, pnames,
section_names_size,
&omit))
discard = true;
}
else if ((shdr.get_sh_flags() & elfcpp::SHF_GROUP) == 0
&& Layout::is_linkonce(name))
{
if (!this->include_linkonce_section(layout, i, name, shdr))
discard = true;
}
}
// Add the section to the incremental inputs layout.
Incremental_inputs* incremental_inputs = layout->incremental_inputs();
if (incremental_inputs != NULL
&& !discard
&& (shdr.get_sh_type() == elfcpp::SHT_PROGBITS
|| shdr.get_sh_type() == elfcpp::SHT_NOBITS
|| shdr.get_sh_type() == elfcpp::SHT_NOTE))
incremental_inputs->report_input_section(this, i, name,
shdr.get_sh_size());
if (discard)
{
// Do not include this section in the link.
out_sections[i] = NULL;
out_section_offsets[i] = invalid_address;
continue;
}
}
if (is_gc_pass_one && parameters->options().gc_sections())
{
if (this->is_section_name_included(name)
|| shdr.get_sh_type() == elfcpp::SHT_INIT_ARRAY
|| shdr.get_sh_type() == elfcpp::SHT_FINI_ARRAY)
{
symtab->gc()->worklist().push(Section_id(this, i));
}
// If the section name XXX can be represented as a C identifier
// it cannot be discarded if there are references to
// __start_XXX and __stop_XXX symbols. These need to be
// specially handled.
if (is_cident(name))
{
symtab->gc()->add_cident_section(name, Section_id(this, i));
}
}
// When doing a relocatable link we are going to copy input
// reloc sections into the output. We only want to copy the
// ones associated with sections which are not being discarded.
// However, we don't know that yet for all sections. So save
// reloc sections and process them later. Garbage collection is
// not triggered when relocatable code is desired.
if (emit_relocs
&& (shdr.get_sh_type() == elfcpp::SHT_REL
|| shdr.get_sh_type() == elfcpp::SHT_RELA))
{
reloc_sections.push_back(i);
continue;
}
if (relocatable && shdr.get_sh_type() == elfcpp::SHT_GROUP)
continue;
// The .eh_frame section is special. It holds exception frame
// information that we need to read in order to generate the
// exception frame header. We process these after all the other
// sections so that the exception frame reader can reliably
// determine which sections are being discarded, and discard the
// corresponding information.
if (!relocatable
&& strcmp(name, ".eh_frame") == 0
&& this->check_eh_frame_flags(&shdr))
{
if (is_gc_pass_one)
{
out_sections[i] = reinterpret_cast<Output_section*>(1);
out_section_offsets[i] = invalid_address;
}
else
eh_frame_sections.push_back(i);
continue;
}
if (is_gc_pass_two && parameters->options().gc_sections())
{
// This is executed during the second pass of garbage
// collection. do_layout has been called before and some
// sections have been already discarded. Simply ignore
// such sections this time around.
if (out_sections[i] == NULL)
{
gold_assert(out_section_offsets[i] == invalid_address);
continue;
}
if (((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0)
&& symtab->gc()->is_section_garbage(this, i))
{
if (parameters->options().print_gc_sections())
gold_info(_("%s: removing unused section from '%s'"
" in file '%s'"),
program_name, this->section_name(i).c_str(),
this->name().c_str());
out_sections[i] = NULL;
out_section_offsets[i] = invalid_address;
continue;
}
}
if (is_gc_pass_two && parameters->options().icf_enabled())
{
if (out_sections[i] == NULL)
{
gold_assert(out_section_offsets[i] == invalid_address);
continue;
}
if (((shdr.get_sh_flags() & elfcpp::SHF_ALLOC) != 0)
&& symtab->icf()->is_section_folded(this, i))
{
if (parameters->options().print_icf_sections())
{
Section_id folded =
symtab->icf()->get_folded_section(this, i);
Relobj* folded_obj =
reinterpret_cast<Relobj*>(folded.first);
gold_info(_("%s: ICF folding section '%s' in file '%s'"
"into '%s' in file '%s'"),
program_name, this->section_name(i).c_str(),
this->name().c_str(),
folded_obj->section_name(folded.second).c_str(),
folded_obj->name().c_str());
}
out_sections[i] = NULL;
out_section_offsets[i] = invalid_address;
continue;
}
}
// Defer layout here if input files are claimed by plugins. When gc
// is turned on this function is called twice. For the second call
// should_defer_layout should be false.
if (should_defer_layout && (shdr.get_sh_flags() & elfcpp::SHF_ALLOC))
{
gold_assert(!is_gc_pass_two);
this->deferred_layout_.push_back(Deferred_layout(i, name,
pshdrs,
reloc_shndx[i],
reloc_type[i]));
// Put dummy values here; real values will be supplied by
// do_layout_deferred_sections.
out_sections[i] = reinterpret_cast<Output_section*>(2);
out_section_offsets[i] = invalid_address;
continue;
}
// During gc_pass_two if a section that was previously deferred is
// found, do not layout the section as layout_deferred_sections will
// do it later from gold.cc.
if (is_gc_pass_two
&& (out_sections[i] == reinterpret_cast<Output_section*>(2)))
continue;
if (is_gc_pass_one)
{
// This is during garbage collection. The out_sections are
// assigned in the second call to this function.
out_sections[i] = reinterpret_cast<Output_section*>(1);
out_section_offsets[i] = invalid_address;
}
else
{
// When garbage collection is switched on the actual layout
// only happens in the second call.
this->layout_section(layout, i, name, shdr, reloc_shndx[i],
reloc_type[i]);
}
}
if (!is_gc_pass_two)
layout->layout_gnu_stack(seen_gnu_stack, gnu_stack_flags, this);
// When doing a relocatable link handle the reloc sections at the
// end. Garbage collection and Identical Code Folding is not
// turned on for relocatable code.
if (emit_relocs)
this->size_relocatable_relocs();
gold_assert(!(is_gc_or_icf) || reloc_sections.empty());
for (std::vector<unsigned int>::const_iterator p = reloc_sections.begin();
p != reloc_sections.end();
++p)
{
unsigned int i = *p;
const unsigned char* pshdr;
pshdr = section_headers_data + i * This::shdr_size;
typename This::Shdr shdr(pshdr);
unsigned int data_shndx = this->adjust_shndx(shdr.get_sh_info());
if (data_shndx >= shnum)
{
// We already warned about this above.
continue;
}
Output_section* data_section = out_sections[data_shndx];
if (data_section == reinterpret_cast<Output_section*>(2))
{
// The layout for the data section was deferred, so we need
// to defer the relocation section, too.
const char* name = pnames + shdr.get_sh_name();
this->deferred_layout_relocs_.push_back(
Deferred_layout(i, name, pshdr, 0, elfcpp::SHT_NULL));
out_sections[i] = reinterpret_cast<Output_section*>(2);
out_section_offsets[i] = invalid_address;
continue;
}
if (data_section == NULL)
{
out_sections[i] = NULL;
out_section_offsets[i] = invalid_address;
continue;
}
Relocatable_relocs* rr = new Relocatable_relocs();
this->set_relocatable_relocs(i, rr);
Output_section* os = layout->layout_reloc(this, i, shdr, data_section,
rr);
out_sections[i] = os;
out_section_offsets[i] = invalid_address;
}
// Handle the .eh_frame sections at the end.
gold_assert(!is_gc_pass_one || eh_frame_sections.empty());
for (std::vector<unsigned int>::const_iterator p = eh_frame_sections.begin();
p != eh_frame_sections.end();
++p)
{
gold_assert(this->has_eh_frame_);
gold_assert(external_symbols_offset != 0);
unsigned int i = *p;
const unsigned char* pshdr;
pshdr = section_headers_data + i * This::shdr_size;
typename This::Shdr shdr(pshdr);
off_t offset;
Output_section* os = layout->layout_eh_frame(this,
symbols_data,
symbols_size,
symbol_names_data,
symbol_names_size,
i, shdr,
reloc_shndx[i],
reloc_type[i],
&offset);
out_sections[i] = os;
if (os == NULL || offset == -1)
{
// An object can contain at most one section holding exception
// frame information.
gold_assert(this->discarded_eh_frame_shndx_ == -1U);
this->discarded_eh_frame_shndx_ = i;
out_section_offsets[i] = invalid_address;
}
else
out_section_offsets[i] = convert_types<Address, off_t>(offset);
// If this section requires special handling, and if there are
// relocs that apply to it, then we must do the special handling
// before we apply the relocs.
if (os != NULL && offset == -1 && reloc_shndx[i] != 0)
this->set_relocs_must_follow_section_writes();
}
if (is_gc_pass_two)
{
delete[] gc_sd->section_headers_data;
delete[] gc_sd->section_names_data;
delete[] gc_sd->symbols_data;
delete[] gc_sd->symbol_names_data;
this->set_symbols_data(NULL);
}
else
{
delete sd->section_headers;
sd->section_headers = NULL;
delete sd->section_names;
sd->section_names = NULL;
}
}
// Layout sections whose layout was deferred while waiting for
// input files from a plugin.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_layout_deferred_sections(Layout* layout)
{
typename std::vector<Deferred_layout>::iterator deferred;
for (deferred = this->deferred_layout_.begin();
deferred != this->deferred_layout_.end();
++deferred)
{
typename This::Shdr shdr(deferred->shdr_data_);
// If the section is not included, it is because the garbage collector
// decided it is not needed. Avoid reverting that decision.
if (!this->is_section_included(deferred->shndx_))
continue;
this->layout_section(layout, deferred->shndx_, deferred->name_.c_str(),
shdr, deferred->reloc_shndx_, deferred->reloc_type_);
}
this->deferred_layout_.clear();
// Now handle the deferred relocation sections.
Output_sections& out_sections(this->output_sections());
std::vector<Address>& out_section_offsets(this->section_offsets_);
for (deferred = this->deferred_layout_relocs_.begin();
deferred != this->deferred_layout_relocs_.end();
++deferred)
{
unsigned int shndx = deferred->shndx_;
typename This::Shdr shdr(deferred->shdr_data_);
unsigned int data_shndx = this->adjust_shndx(shdr.get_sh_info());
Output_section* data_section = out_sections[data_shndx];
if (data_section == NULL)
{
out_sections[shndx] = NULL;
out_section_offsets[shndx] = invalid_address;
continue;
}
Relocatable_relocs* rr = new Relocatable_relocs();
this->set_relocatable_relocs(shndx, rr);
Output_section* os = layout->layout_reloc(this, shndx, shdr,
data_section, rr);
out_sections[shndx] = os;
out_section_offsets[shndx] = invalid_address;
}
}
// Add the symbols to the symbol table.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_add_symbols(Symbol_table* symtab,
Read_symbols_data* sd,
Layout*)
{
if (sd->symbols == NULL)
{
gold_assert(sd->symbol_names == NULL);
return;
}
const int sym_size = This::sym_size;
size_t symcount = ((sd->symbols_size - sd->external_symbols_offset)
/ sym_size);
if (symcount * sym_size != sd->symbols_size - sd->external_symbols_offset)
{
this->error(_("size of symbols is not multiple of symbol size"));
return;
}
this->symbols_.resize(symcount);
const char* sym_names =
reinterpret_cast<const char*>(sd->symbol_names->data());
symtab->add_from_relobj(this,
sd->symbols->data() + sd->external_symbols_offset,
symcount, this->local_symbol_count_,
sym_names, sd->symbol_names_size,
&this->symbols_,
&this->defined_count_);
delete sd->symbols;
sd->symbols = NULL;
delete sd->symbol_names;
sd->symbol_names = NULL;
}
// Find out if this object, that is a member of a lib group, should be included
// in the link. We check every symbol defined by this object. If the symbol
// table has a strong undefined reference to that symbol, we have to include
// the object.
template<int size, bool big_endian>
Archive::Should_include
Sized_relobj<size, big_endian>::do_should_include_member(Symbol_table* symtab,
Layout* layout,
Read_symbols_data* sd,
std::string* why)
{
char* tmpbuf = NULL;
size_t tmpbuflen = 0;
const char* sym_names =
reinterpret_cast<const char*>(sd->symbol_names->data());
const unsigned char* syms =
sd->symbols->data() + sd->external_symbols_offset;
const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
size_t symcount = ((sd->symbols_size - sd->external_symbols_offset)
/ sym_size);
const unsigned char* p = syms;
for (size_t i = 0; i < symcount; ++i, p += sym_size)
{
elfcpp::Sym<size, big_endian> sym(p);
unsigned int st_shndx = sym.get_st_shndx();
if (st_shndx == elfcpp::SHN_UNDEF)
continue;
unsigned int st_name = sym.get_st_name();
const char* name = sym_names + st_name;
Symbol* symbol;
Archive::Should_include t = Archive::should_include_member(symtab,
layout,
name,
&symbol, why,
&tmpbuf,
&tmpbuflen);
if (t == Archive::SHOULD_INCLUDE_YES)
{
if (tmpbuf != NULL)
free(tmpbuf);
return t;
}
}
if (tmpbuf != NULL)
free(tmpbuf);
return Archive::SHOULD_INCLUDE_UNKNOWN;
}
// Iterate over global defined symbols, calling a visitor class V for each.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_for_all_global_symbols(
Read_symbols_data* sd,
Library_base::Symbol_visitor_base* v)
{
const char* sym_names =
reinterpret_cast<const char*>(sd->symbol_names->data());
const unsigned char* syms =
sd->symbols->data() + sd->external_symbols_offset;
const int sym_size = elfcpp::Elf_sizes<size>::sym_size;
size_t symcount = ((sd->symbols_size - sd->external_symbols_offset)
/ sym_size);
const unsigned char* p = syms;
for (size_t i = 0; i < symcount; ++i, p += sym_size)
{
elfcpp::Sym<size, big_endian> sym(p);
if (sym.get_st_shndx() != elfcpp::SHN_UNDEF)
v->visit(sym_names + sym.get_st_name());
}
}
// Iterate over local symbols, calling a visitor class V for each GOT offset
// associated with a local symbol.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_for_all_local_got_entries(
Got_offset_list::Visitor* v) const
{
unsigned int nsyms = this->local_symbol_count();
for (unsigned int i = 0; i < nsyms; i++)
{
Local_got_offsets::const_iterator p = this->local_got_offsets_.find(i);
if (p != this->local_got_offsets_.end())
{
const Got_offset_list* got_offsets = p->second;
got_offsets->for_all_got_offsets(v);
}
}
}
// Return whether the local symbol SYMNDX has a PLT offset.
template<int size, bool big_endian>
bool
Sized_relobj<size, big_endian>::local_has_plt_offset(unsigned int symndx) const
{
typename Local_plt_offsets::const_iterator p =
this->local_plt_offsets_.find(symndx);
return p != this->local_plt_offsets_.end();
}
// Get the PLT offset of a local symbol.
template<int size, bool big_endian>
unsigned int
Sized_relobj<size, big_endian>::local_plt_offset(unsigned int symndx) const
{
typename Local_plt_offsets::const_iterator p =
this->local_plt_offsets_.find(symndx);
gold_assert(p != this->local_plt_offsets_.end());
return p->second;
}
// Set the PLT offset of a local symbol.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::set_local_plt_offset(unsigned int symndx,
unsigned int plt_offset)
{
std::pair<typename Local_plt_offsets::iterator, bool> ins =
this->local_plt_offsets_.insert(std::make_pair(symndx, plt_offset));
gold_assert(ins.second);
}
// First pass over the local symbols. Here we add their names to
// *POOL and *DYNPOOL, and we store the symbol value in
// THIS->LOCAL_VALUES_. This function is always called from a
// singleton thread. This is followed by a call to
// finalize_local_symbols.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_count_local_symbols(Stringpool* pool,
Stringpool* dynpool)
{
gold_assert(this->symtab_shndx_ != -1U);
if (this->symtab_shndx_ == 0)
{
// This object has no symbols. Weird but legal.
return;
}
// Read the symbol table section header.
const unsigned int symtab_shndx = this->symtab_shndx_;
typename This::Shdr symtabshdr(this,
this->elf_file_.section_header(symtab_shndx));
gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
// Read the local symbols.
const int sym_size = This::sym_size;
const unsigned int loccount = this->local_symbol_count_;
gold_assert(loccount == symtabshdr.get_sh_info());
off_t locsize = loccount * sym_size;
const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
locsize, true, true);
// Read the symbol names.
const unsigned int strtab_shndx =
this->adjust_shndx(symtabshdr.get_sh_link());
section_size_type strtab_size;
const unsigned char* pnamesu = this->section_contents(strtab_shndx,
&strtab_size,
true);
const char* pnames = reinterpret_cast<const char*>(pnamesu);
// Loop over the local symbols.
const Output_sections& out_sections(this->output_sections());
unsigned int shnum = this->shnum();
unsigned int count = 0;
unsigned int dyncount = 0;
// Skip the first, dummy, symbol.
psyms += sym_size;
bool strip_all = parameters->options().strip_all();
bool discard_all = parameters->options().discard_all();
bool discard_locals = parameters->options().discard_locals();
for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
{
elfcpp::Sym<size, big_endian> sym(psyms);
Symbol_value<size>& lv(this->local_values_[i]);
bool is_ordinary;
unsigned int shndx = this->adjust_sym_shndx(i, sym.get_st_shndx(),
&is_ordinary);
lv.set_input_shndx(shndx, is_ordinary);
if (sym.get_st_type() == elfcpp::STT_SECTION)
lv.set_is_section_symbol();
else if (sym.get_st_type() == elfcpp::STT_TLS)
lv.set_is_tls_symbol();
else if (sym.get_st_type() == elfcpp::STT_GNU_IFUNC)
lv.set_is_ifunc_symbol();
// Save the input symbol value for use in do_finalize_local_symbols().
lv.set_input_value(sym.get_st_value());
// Decide whether this symbol should go into the output file.
if ((shndx < shnum && out_sections[shndx] == NULL)
|| shndx == this->discarded_eh_frame_shndx_)
{
lv.set_no_output_symtab_entry();
gold_assert(!lv.needs_output_dynsym_entry());
continue;
}
if (sym.get_st_type() == elfcpp::STT_SECTION)
{
lv.set_no_output_symtab_entry();
gold_assert(!lv.needs_output_dynsym_entry());
continue;
}
if (sym.get_st_name() >= strtab_size)
{
this->error(_("local symbol %u section name out of range: %u >= %u"),
i, sym.get_st_name(),
static_cast<unsigned int>(strtab_size));
lv.set_no_output_symtab_entry();
continue;
}
const char* name = pnames + sym.get_st_name();
// If needed, add the symbol to the dynamic symbol table string pool.
if (lv.needs_output_dynsym_entry())
{
dynpool->add(name, true, NULL);
++dyncount;
}
if (strip_all
|| (discard_all && lv.may_be_discarded_from_output_symtab()))
{
lv.set_no_output_symtab_entry();
continue;
}
// If --discard-locals option is used, discard all temporary local
// symbols. These symbols start with system-specific local label
// prefixes, typically .L for ELF system. We want to be compatible
// with GNU ld so here we essentially use the same check in
// bfd_is_local_label(). The code is different because we already
// know that:
//
// - the symbol is local and thus cannot have global or weak binding.
// - the symbol is not a section symbol.
// - the symbol has a name.
//
// We do not discard a symbol if it needs a dynamic symbol entry.
if (discard_locals
&& sym.get_st_type() != elfcpp::STT_FILE
&& !lv.needs_output_dynsym_entry()
&& lv.may_be_discarded_from_output_symtab()
&& parameters->target().is_local_label_name(name))
{
lv.set_no_output_symtab_entry();
continue;
}
// Discard the local symbol if -retain_symbols_file is specified
// and the local symbol is not in that file.
if (!parameters->options().should_retain_symbol(name))
{
lv.set_no_output_symtab_entry();
continue;
}
// Add the symbol to the symbol table string pool.
pool->add(name, true, NULL);
++count;
}
this->output_local_symbol_count_ = count;
this->output_local_dynsym_count_ = dyncount;
}
// Compute the final value of a local symbol.
template<int size, bool big_endian>
typename Sized_relobj<size, big_endian>::Compute_final_local_value_status
Sized_relobj<size, big_endian>::compute_final_local_value_internal(
unsigned int r_sym,
const Symbol_value<size>* lv_in,
Symbol_value<size>* lv_out,
bool relocatable,
const Output_sections& out_sections,
const std::vector<Address>& out_offsets,
const Symbol_table* symtab)
{
// We are going to overwrite *LV_OUT, if it has a merged symbol value,
// we may have a memory leak.
gold_assert(lv_out->has_output_value());
bool is_ordinary;
unsigned int shndx = lv_in->input_shndx(&is_ordinary);
// Set the output symbol value.
if (!is_ordinary)
{
if (shndx == elfcpp::SHN_ABS || Symbol::is_common_shndx(shndx))
lv_out->set_output_value(lv_in->input_value());
else
{
this->error(_("unknown section index %u for local symbol %u"),
shndx, r_sym);
lv_out->set_output_value(0);
return This::CFLV_ERROR;
}
}
else
{
if (shndx >= this->shnum())
{
this->error(_("local symbol %u section index %u out of range"),
r_sym, shndx);
lv_out->set_output_value(0);
return This::CFLV_ERROR;
}
Output_section* os = out_sections[shndx];
Address secoffset = out_offsets[shndx];
if (symtab->is_section_folded(this, shndx))
{
gold_assert(os == NULL && secoffset == invalid_address);
// Get the os of the section it is folded onto.
Section_id folded = symtab->icf()->get_folded_section(this,
shndx);
gold_assert(folded.first != NULL);
Sized_relobj<size, big_endian>* folded_obj = reinterpret_cast
<Sized_relobj<size, big_endian>*>(folded.first);
os = folded_obj->output_section(folded.second);
gold_assert(os != NULL);
secoffset = folded_obj->get_output_section_offset(folded.second);
// This could be a relaxed input section.
if (secoffset == invalid_address)
{
const Output_relaxed_input_section* relaxed_section =
os->find_relaxed_input_section(folded_obj, folded.second);
gold_assert(relaxed_section != NULL);
secoffset = relaxed_section->address() - os->address();
}
}
if (os == NULL)
{
// This local symbol belongs to a section we are discarding.
// In some cases when applying relocations later, we will
// attempt to match it to the corresponding kept section,
// so we leave the input value unchanged here.
return This::CFLV_DISCARDED;
}
else if (secoffset == invalid_address)
{
uint64_t start;
// This is a SHF_MERGE section or one which otherwise
// requires special handling.
if (shndx == this->discarded_eh_frame_shndx_)
{
// This local symbol belongs to a discarded .eh_frame
// section. Just treat it like the case in which
// os == NULL above.
gold_assert(this->has_eh_frame_);
return This::CFLV_DISCARDED;
}
else if (!lv_in->is_section_symbol())
{
// This is not a section symbol. We can determine
// the final value now.
lv_out->set_output_value(
os->output_address(this, shndx, lv_in->input_value()));
}
else if (!os->find_starting_output_address(this, shndx, &start))
{
// This is a section symbol, but apparently not one in a
// merged section. First check to see if this is a relaxed
// input section. If so, use its address. Otherwise just
// use the start of the output section. This happens with
// relocatable links when the input object has section
// symbols for arbitrary non-merge sections.
const Output_section_data* posd =
os->find_relaxed_input_section(this, shndx);
if (posd != NULL)
{
Address relocatable_link_adjustment =
relocatable ? os->address() : 0;
lv_out->set_output_value(posd->address()
- relocatable_link_adjustment);
}
else
lv_out->set_output_value(os->address());
}
else
{
// We have to consider the addend to determine the
// value to use in a relocation. START is the start
// of this input section. If we are doing a relocatable
// link, use offset from start output section instead of
// address.
Address adjusted_start =
relocatable ? start - os->address() : start;
Merged_symbol_value<size>* msv =
new Merged_symbol_value<size>(lv_in->input_value(),
adjusted_start);
lv_out->set_merged_symbol_value(msv);
}
}
else if (lv_in->is_tls_symbol())
lv_out->set_output_value(os->tls_offset()
+ secoffset
+ lv_in->input_value());
else
lv_out->set_output_value((relocatable ? 0 : os->address())
+ secoffset
+ lv_in->input_value());
}
return This::CFLV_OK;
}
// Compute final local symbol value. R_SYM is the index of a local
// symbol in symbol table. LV points to a symbol value, which is
// expected to hold the input value and to be over-written by the
// final value. SYMTAB points to a symbol table. Some targets may want
// to know would-be-finalized local symbol values in relaxation.
// Hence we provide this method. Since this method updates *LV, a
// callee should make a copy of the original local symbol value and
// use the copy instead of modifying an object's local symbols before
// everything is finalized. The caller should also free up any allocated
// memory in the return value in *LV.
template<int size, bool big_endian>
typename Sized_relobj<size, big_endian>::Compute_final_local_value_status
Sized_relobj<size, big_endian>::compute_final_local_value(
unsigned int r_sym,
const Symbol_value<size>* lv_in,
Symbol_value<size>* lv_out,
const Symbol_table* symtab)
{
// This is just a wrapper of compute_final_local_value_internal.
const bool relocatable = parameters->options().relocatable();
const Output_sections& out_sections(this->output_sections());
const std::vector<Address>& out_offsets(this->section_offsets_);
return this->compute_final_local_value_internal(r_sym, lv_in, lv_out,
relocatable, out_sections,
out_offsets, symtab);
}
// Finalize the local symbols. Here we set the final value in
// THIS->LOCAL_VALUES_ and set their output symbol table indexes.
// This function is always called from a singleton thread. The actual
// output of the local symbols will occur in a separate task.
template<int size, bool big_endian>
unsigned int
Sized_relobj<size, big_endian>::do_finalize_local_symbols(unsigned int index,
off_t off,
Symbol_table* symtab)
{
gold_assert(off == static_cast<off_t>(align_address(off, size >> 3)));
const unsigned int loccount = this->local_symbol_count_;
this->local_symbol_offset_ = off;
const bool relocatable = parameters->options().relocatable();
const Output_sections& out_sections(this->output_sections());
const std::vector<Address>& out_offsets(this->section_offsets_);
for (unsigned int i = 1; i < loccount; ++i)
{
Symbol_value<size>* lv = &this->local_values_[i];
Compute_final_local_value_status cflv_status =
this->compute_final_local_value_internal(i, lv, lv, relocatable,
out_sections, out_offsets,
symtab);
switch (cflv_status)
{
case CFLV_OK:
if (!lv->is_output_symtab_index_set())
{
lv->set_output_symtab_index(index);
++index;
}
break;
case CFLV_DISCARDED:
case CFLV_ERROR:
// Do nothing.
break;
default:
gold_unreachable();
}
}
return index;
}
// Set the output dynamic symbol table indexes for the local variables.
template<int size, bool big_endian>
unsigned int
Sized_relobj<size, big_endian>::do_set_local_dynsym_indexes(unsigned int index)
{
const unsigned int loccount = this->local_symbol_count_;
for (unsigned int i = 1; i < loccount; ++i)
{
Symbol_value<size>& lv(this->local_values_[i]);
if (lv.needs_output_dynsym_entry())
{
lv.set_output_dynsym_index(index);
++index;
}
}
return index;
}
// Set the offset where local dynamic symbol information will be stored.
// Returns the count of local symbols contributed to the symbol table by
// this object.
template<int size, bool big_endian>
unsigned int
Sized_relobj<size, big_endian>::do_set_local_dynsym_offset(off_t off)
{
gold_assert(off == static_cast<off_t>(align_address(off, size >> 3)));
this->local_dynsym_offset_ = off;
return this->output_local_dynsym_count_;
}
// If Symbols_data is not NULL get the section flags from here otherwise
// get it from the file.
template<int size, bool big_endian>
uint64_t
Sized_relobj<size, big_endian>::do_section_flags(unsigned int shndx)
{
Symbols_data* sd = this->get_symbols_data();
if (sd != NULL)
{
const unsigned char* pshdrs = sd->section_headers_data
+ This::shdr_size * shndx;
typename This::Shdr shdr(pshdrs);
return shdr.get_sh_flags();
}
// If sd is NULL, read the section header from the file.
return this->elf_file_.section_flags(shndx);
}
// Get the section's ent size from Symbols_data. Called by get_section_contents
// in icf.cc
template<int size, bool big_endian>
uint64_t
Sized_relobj<size, big_endian>::do_section_entsize(unsigned int shndx)
{
Symbols_data* sd = this->get_symbols_data();
gold_assert(sd != NULL);
const unsigned char* pshdrs = sd->section_headers_data
+ This::shdr_size * shndx;
typename This::Shdr shdr(pshdrs);
return shdr.get_sh_entsize();
}
// Write out the local symbols.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::write_local_symbols(
Output_file* of,
const Stringpool* sympool,
const Stringpool* dynpool,
Output_symtab_xindex* symtab_xindex,
Output_symtab_xindex* dynsym_xindex,
off_t symtab_off)
{
const bool strip_all = parameters->options().strip_all();
if (strip_all)
{
if (this->output_local_dynsym_count_ == 0)
return;
this->output_local_symbol_count_ = 0;
}
gold_assert(this->symtab_shndx_ != -1U);
if (this->symtab_shndx_ == 0)
{
// This object has no symbols. Weird but legal.
return;
}
// Read the symbol table section header.
const unsigned int symtab_shndx = this->symtab_shndx_;
typename This::Shdr symtabshdr(this,
this->elf_file_.section_header(symtab_shndx));
gold_assert(symtabshdr.get_sh_type() == elfcpp::SHT_SYMTAB);
const unsigned int loccount = this->local_symbol_count_;
gold_assert(loccount == symtabshdr.get_sh_info());
// Read the local symbols.
const int sym_size = This::sym_size;
off_t locsize = loccount * sym_size;
const unsigned char* psyms = this->get_view(symtabshdr.get_sh_offset(),
locsize, true, false);
// Read the symbol names.
const unsigned int strtab_shndx =
this->adjust_shndx(symtabshdr.get_sh_link());
section_size_type strtab_size;
const unsigned char* pnamesu = this->section_contents(strtab_shndx,
&strtab_size,
false);
const char* pnames = reinterpret_cast<const char*>(pnamesu);
// Get views into the output file for the portions of the symbol table
// and the dynamic symbol table that we will be writing.
off_t output_size = this->output_local_symbol_count_ * sym_size;
unsigned char* oview = NULL;
if (output_size > 0)
oview = of->get_output_view(symtab_off + this->local_symbol_offset_,
output_size);
off_t dyn_output_size = this->output_local_dynsym_count_ * sym_size;
unsigned char* dyn_oview = NULL;
if (dyn_output_size > 0)
dyn_oview = of->get_output_view(this->local_dynsym_offset_,
dyn_output_size);
const Output_sections out_sections(this->output_sections());
gold_assert(this->local_values_.size() == loccount);
unsigned char* ov = oview;
unsigned char* dyn_ov = dyn_oview;
psyms += sym_size;
for (unsigned int i = 1; i < loccount; ++i, psyms += sym_size)
{
elfcpp::Sym<size, big_endian> isym(psyms);
Symbol_value<size>& lv(this->local_values_[i]);
bool is_ordinary;
unsigned int st_shndx = this->adjust_sym_shndx(i, isym.get_st_shndx(),
&is_ordinary);
if (is_ordinary)
{
gold_assert(st_shndx < out_sections.size());
if (out_sections[st_shndx] == NULL)
continue;
st_shndx = out_sections[st_shndx]->out_shndx();
if (st_shndx >= elfcpp::SHN_LORESERVE)
{
if (lv.has_output_symtab_entry())
symtab_xindex->add(lv.output_symtab_index(), st_shndx);
if (lv.has_output_dynsym_entry())
dynsym_xindex->add(lv.output_dynsym_index(), st_shndx);
st_shndx = elfcpp::SHN_XINDEX;
}
}
// Write the symbol to the output symbol table.
if (lv.has_output_symtab_entry())
{
elfcpp::Sym_write<size, big_endian> osym(ov);
gold_assert(isym.get_st_name() < strtab_size);
const char* name = pnames + isym.get_st_name();
osym.put_st_name(sympool->get_offset(name));
osym.put_st_value(this->local_values_[i].value(this, 0));
osym.put_st_size(isym.get_st_size());
osym.put_st_info(isym.get_st_info());
osym.put_st_other(isym.get_st_other());
osym.put_st_shndx(st_shndx);
ov += sym_size;
}
// Write the symbol to the output dynamic symbol table.
if (lv.has_output_dynsym_entry())
{
gold_assert(dyn_ov < dyn_oview + dyn_output_size);
elfcpp::Sym_write<size, big_endian> osym(dyn_ov);
gold_assert(isym.get_st_name() < strtab_size);
const char* name = pnames + isym.get_st_name();
osym.put_st_name(dynpool->get_offset(name));
osym.put_st_value(this->local_values_[i].value(this, 0));
osym.put_st_size(isym.get_st_size());
osym.put_st_info(isym.get_st_info());
osym.put_st_other(isym.get_st_other());
osym.put_st_shndx(st_shndx);
dyn_ov += sym_size;
}
}
if (output_size > 0)
{
gold_assert(ov - oview == output_size);
of->write_output_view(symtab_off + this->local_symbol_offset_,
output_size, oview);
}
if (dyn_output_size > 0)
{
gold_assert(dyn_ov - dyn_oview == dyn_output_size);
of->write_output_view(this->local_dynsym_offset_, dyn_output_size,
dyn_oview);
}
}
// Set *INFO to symbolic information about the offset OFFSET in the
// section SHNDX. Return true if we found something, false if we
// found nothing.
template<int size, bool big_endian>
bool
Sized_relobj<size, big_endian>::get_symbol_location_info(
unsigned int shndx,
off_t offset,
Symbol_location_info* info)
{
if (this->symtab_shndx_ == 0)
return false;
section_size_type symbols_size;
const unsigned char* symbols = this->section_contents(this->symtab_shndx_,
&symbols_size,
false);
unsigned int symbol_names_shndx =
this->adjust_shndx(this->section_link(this->symtab_shndx_));
section_size_type names_size;
const unsigned char* symbol_names_u =
this->section_contents(symbol_names_shndx, &names_size, false);
const char* symbol_names = reinterpret_cast<const char*>(symbol_names_u);
const int sym_size = This::sym_size;
const size_t count = symbols_size / sym_size;
const unsigned char* p = symbols;
for (size_t i = 0; i < count; ++i, p += sym_size)
{
elfcpp::Sym<size, big_endian> sym(p);
if (sym.get_st_type() == elfcpp::STT_FILE)
{
if (sym.get_st_name() >= names_size)
info->source_file = "(invalid)";
else
info->source_file = symbol_names + sym.get_st_name();
continue;
}
bool is_ordinary;
unsigned int st_shndx = this->adjust_sym_shndx(i, sym.get_st_shndx(),
&is_ordinary);
if (is_ordinary
&& st_shndx == shndx
&& static_cast<off_t>(sym.get_st_value()) <= offset
&& (static_cast<off_t>(sym.get_st_value() + sym.get_st_size())
> offset))
{
if (sym.get_st_name() > names_size)
info->enclosing_symbol_name = "(invalid)";
else
{
info->enclosing_symbol_name = symbol_names + sym.get_st_name();
if (parameters->options().do_demangle())
{
char* demangled_name = cplus_demangle(
info->enclosing_symbol_name.c_str(),
DMGL_ANSI | DMGL_PARAMS);
if (demangled_name != NULL)
{
info->enclosing_symbol_name.assign(demangled_name);
free(demangled_name);
}
}
}
return true;
}
}
return false;
}
// Look for a kept section corresponding to the given discarded section,
// and return its output address. This is used only for relocations in
// debugging sections. If we can't find the kept section, return 0.
template<int size, bool big_endian>
typename Sized_relobj<size, big_endian>::Address
Sized_relobj<size, big_endian>::map_to_kept_section(
unsigned int shndx,
bool* found) const
{
Relobj* kept_object;
unsigned int kept_shndx;
if (this->get_kept_comdat_section(shndx, &kept_object, &kept_shndx))
{
Sized_relobj<size, big_endian>* kept_relobj =
static_cast<Sized_relobj<size, big_endian>*>(kept_object);
Output_section* os = kept_relobj->output_section(kept_shndx);
Address offset = kept_relobj->get_output_section_offset(kept_shndx);
if (os != NULL && offset != invalid_address)
{
*found = true;
return os->address() + offset;
}
}
*found = false;
return 0;
}
// Get symbol counts.
template<int size, bool big_endian>
void
Sized_relobj<size, big_endian>::do_get_global_symbol_counts(
const Symbol_table*,
size_t* defined,
size_t* used) const
{
*defined = this->defined_count_;
size_t count = 0;
for (typename Symbols::const_iterator p = this->symbols_.begin();
p != this->symbols_.end();
++p)
if (*p != NULL
&& (*p)->source() == Symbol::FROM_OBJECT
&& (*p)->object() == this
&& (*p)->is_defined())
++count;
*used = count;
}
// Input_objects methods.
// Add a regular relocatable object to the list. Return false if this
// object should be ignored.
bool
Input_objects::add_object(Object* obj)
{
// Print the filename if the -t/--trace option is selected.
if (parameters->options().trace())
gold_info("%s", obj->name().c_str());
if (!obj->is_dynamic())
this->relobj_list_.push_back(static_cast<Relobj*>(obj));
else
{
// See if this is a duplicate SONAME.
Dynobj* dynobj = static_cast<Dynobj*>(obj);
const char* soname = dynobj->soname();
std::pair<Unordered_set<std::string>::iterator, bool> ins =
this->sonames_.insert(soname);
if (!ins.second)
{
// We have already seen a dynamic object with this soname.
return false;
}
this->dynobj_list_.push_back(dynobj);
}
// Add this object to the cross-referencer if requested.
if (parameters->options().user_set_print_symbol_counts()
|| parameters->options().cref())
{
if (this->cref_ == NULL)
this->cref_ = new Cref();
this->cref_->add_object(obj);
}
return true;
}
// For each dynamic object, record whether we've seen all of its
// explicit dependencies.
void
Input_objects::check_dynamic_dependencies() const
{
bool issued_copy_dt_needed_error = false;
for (Dynobj_list::const_iterator p = this->dynobj_list_.begin();
p != this->dynobj_list_.end();
++p)
{
const Dynobj::Needed& needed((*p)->needed());
bool found_all = true;
Dynobj::Needed::const_iterator pneeded;
for (pneeded = needed.begin(); pneeded != needed.end(); ++pneeded)
{
if (this->sonames_.find(*pneeded) == this->sonames_.end())
{
found_all = false;
break;
}
}
(*p)->set_has_unknown_needed_entries(!found_all);
// --copy-dt-needed-entries aka --add-needed is a GNU ld option
// that gold does not support. However, they cause no trouble
// unless there is a DT_NEEDED entry that we don't know about;
// warn only in that case.
if (!found_all
&& !issued_copy_dt_needed_error
&& (parameters->options().copy_dt_needed_entries()
|| parameters->options().add_needed()))
{
const char* optname;
if (parameters->options().copy_dt_needed_entries())
optname = "--copy-dt-needed-entries";
else
optname = "--add-needed";
gold_error(_("%s is not supported but is required for %s in %s"),
optname, (*pneeded).c_str(), (*p)->name().c_str());
issued_copy_dt_needed_error = true;
}
}
}
// Start processing an archive.
void
Input_objects::archive_start(Archive* archive)
{
if (parameters->options().user_set_print_symbol_counts()
|| parameters->options().cref())
{
if (this->cref_ == NULL)
this->cref_ = new Cref();
this->cref_->add_archive_start(archive);
}
}
// Stop processing an archive.
void
Input_objects::archive_stop(Archive* archive)
{
if (parameters->options().user_set_print_symbol_counts()
|| parameters->options().cref())
this->cref_->add_archive_stop(archive);
}
// Print symbol counts
void
Input_objects::print_symbol_counts(const Symbol_table* symtab) const
{
if (parameters->options().user_set_print_symbol_counts()
&& this->cref_ != NULL)
this->cref_->print_symbol_counts(symtab);
}
// Print a cross reference table.
void
Input_objects::print_cref(const Symbol_table* symtab, FILE* f) const
{
if (parameters->options().cref() && this->cref_ != NULL)
this->cref_->print_cref(symtab, f);
}
// Relocate_info methods.
// Return a string describing the location of a relocation when file
// and lineno information is not available. This is only used in
// error messages.
template<int size, bool big_endian>
std::string
Relocate_info<size, big_endian>::location(size_t, off_t offset) const
{
Sized_dwarf_line_info<size, big_endian> line_info(this->object);
std::string ret = line_info.addr2line(this->data_shndx, offset, NULL);
if (!ret.empty())
return ret;
ret = this->object->name();
Symbol_location_info info;
if (this->object->get_symbol_location_info(this->data_shndx, offset, &info))
{
if (!info.source_file.empty())
{
ret += ":";
ret += info.source_file;
}
size_t len = info.enclosing_symbol_name.length() + 100;
char* buf = new char[len];
snprintf(buf, len, _(":function %s"),
info.enclosing_symbol_name.c_str());
ret += buf;
delete[] buf;
return ret;
}
ret += "(";
ret += this->object->section_name(this->data_shndx);
char buf[100];
snprintf(buf, sizeof buf, "+0x%lx)", static_cast<long>(offset));
ret += buf;
return ret;
}
} // End namespace gold.
namespace
{
using namespace gold;
// Read an ELF file with the header and return the appropriate
// instance of Object.
template<int size, bool big_endian>
Object*
make_elf_sized_object(const std::string& name, Input_file* input_file,
off_t offset, const elfcpp::Ehdr<size, big_endian>& ehdr,
bool* punconfigured)
{
Target* target = select_target(ehdr.get_e_machine(), size, big_endian,
ehdr.get_e_ident()[elfcpp::EI_OSABI],
ehdr.get_e_ident()[elfcpp::EI_ABIVERSION]);
if (target == NULL)
gold_fatal(_("%s: unsupported ELF machine number %d"),
name.c_str(), ehdr.get_e_machine());
if (!parameters->target_valid())
set_parameters_target(target);
else if (target != ¶meters->target())
{
if (punconfigured != NULL)
*punconfigured = true;
else
gold_error(_("%s: incompatible target"), name.c_str());
return NULL;
}
return target->make_elf_object<size, big_endian>(name, input_file, offset,
ehdr);
}
} // End anonymous namespace.
namespace gold
{
// Return whether INPUT_FILE is an ELF object.
bool
is_elf_object(Input_file* input_file, off_t offset,
const unsigned char** start, int* read_size)
{
off_t filesize = input_file->file().filesize();
int want = elfcpp::Elf_recognizer::max_header_size;
if (filesize - offset < want)
want = filesize - offset;
const unsigned char* p = input_file->file().get_view(offset, 0, want,
true, false);
*start = p;
*read_size = want;
return elfcpp::Elf_recognizer::is_elf_file(p, want);
}
// Read an ELF file and return the appropriate instance of Object.
Object*
make_elf_object(const std::string& name, Input_file* input_file, off_t offset,
const unsigned char* p, section_offset_type bytes,
bool* punconfigured)
{
if (punconfigured != NULL)
*punconfigured = false;
std::string error;
bool big_endian = false;
int size = 0;
if (!elfcpp::Elf_recognizer::is_valid_header(p, bytes, &size,
&big_endian, &error))
{
gold_error(_("%s: %s"), name.c_str(), error.c_str());
return NULL;
}
if (size == 32)
{
if (big_endian)
{
#ifdef HAVE_TARGET_32_BIG
elfcpp::Ehdr<32, true> ehdr(p);
return make_elf_sized_object<32, true>(name, input_file,
offset, ehdr, punconfigured);
#else
if (punconfigured != NULL)
*punconfigured = true;
else
gold_error(_("%s: not configured to support "
"32-bit big-endian object"),
name.c_str());
return NULL;
#endif
}
else
{
#ifdef HAVE_TARGET_32_LITTLE
elfcpp::Ehdr<32, false> ehdr(p);
return make_elf_sized_object<32, false>(name, input_file,
offset, ehdr, punconfigured);
#else
if (punconfigured != NULL)
*punconfigured = true;
else
gold_error(_("%s: not configured to support "
"32-bit little-endian object"),
name.c_str());
return NULL;
#endif
}
}
else if (size == 64)
{
if (big_endian)
{
#ifdef HAVE_TARGET_64_BIG
elfcpp::Ehdr<64, true> ehdr(p);
return make_elf_sized_object<64, true>(name, input_file,
offset, ehdr, punconfigured);
#else
if (punconfigured != NULL)
*punconfigured = true;
else
gold_error(_("%s: not configured to support "
"64-bit big-endian object"),
name.c_str());
return NULL;
#endif
}
else
{
#ifdef HAVE_TARGET_64_LITTLE
elfcpp::Ehdr<64, false> ehdr(p);
return make_elf_sized_object<64, false>(name, input_file,
offset, ehdr, punconfigured);
#else
if (punconfigured != NULL)
*punconfigured = true;
else
gold_error(_("%s: not configured to support "
"64-bit little-endian object"),
name.c_str());
return NULL;
#endif
}
}
else
gold_unreachable();
}
// Instantiate the templates we need.
#ifdef HAVE_TARGET_32_LITTLE
template
void
Object::read_section_data<32, false>(elfcpp::Elf_file<32, false, Object>*,
Read_symbols_data*);
#endif
#ifdef HAVE_TARGET_32_BIG
template
void
Object::read_section_data<32, true>(elfcpp::Elf_file<32, true, Object>*,
Read_symbols_data*);
#endif
#ifdef HAVE_TARGET_64_LITTLE
template
void
Object::read_section_data<64, false>(elfcpp::Elf_file<64, false, Object>*,
Read_symbols_data*);
#endif
#ifdef HAVE_TARGET_64_BIG
template
void
Object::read_section_data<64, true>(elfcpp::Elf_file<64, true, Object>*,
Read_symbols_data*);
#endif
#ifdef HAVE_TARGET_32_LITTLE
template
class Sized_relobj<32, false>;
#endif
#ifdef HAVE_TARGET_32_BIG
template
class Sized_relobj<32, true>;
#endif
#ifdef HAVE_TARGET_64_LITTLE
template
class Sized_relobj<64, false>;
#endif
#ifdef HAVE_TARGET_64_BIG
template
class Sized_relobj<64, true>;
#endif
#ifdef HAVE_TARGET_32_LITTLE
template
struct Relocate_info<32, false>;
#endif
#ifdef HAVE_TARGET_32_BIG
template
struct Relocate_info<32, true>;
#endif
#ifdef HAVE_TARGET_64_LITTLE
template
struct Relocate_info<64, false>;
#endif
#ifdef HAVE_TARGET_64_BIG
template
struct Relocate_info<64, true>;
#endif
#ifdef HAVE_TARGET_32_LITTLE
template
void
Xindex::initialize_symtab_xindex<32, false>(Object*, unsigned int);
template
void
Xindex::read_symtab_xindex<32, false>(Object*, unsigned int,
const unsigned char*);
#endif
#ifdef HAVE_TARGET_32_BIG
template
void
Xindex::initialize_symtab_xindex<32, true>(Object*, unsigned int);
template
void
Xindex::read_symtab_xindex<32, true>(Object*, unsigned int,
const unsigned char*);
#endif
#ifdef HAVE_TARGET_64_LITTLE
template
void
Xindex::initialize_symtab_xindex<64, false>(Object*, unsigned int);
template
void
Xindex::read_symtab_xindex<64, false>(Object*, unsigned int,
const unsigned char*);
#endif
#ifdef HAVE_TARGET_64_BIG
template
void
Xindex::initialize_symtab_xindex<64, true>(Object*, unsigned int);
template
void
Xindex::read_symtab_xindex<64, true>(Object*, unsigned int,
const unsigned char*);
#endif
} // End namespace gold.
| 31.775281 | 80 | 0.659691 | [
"object",
"vector"
] |
a39bc7f1784246e09af4e91316649cdaeb561496 | 3,768 | hh | C++ | platform/eSDK_LogAPI_V2.1.10/log4cpp/log4cpp/PatternLayout.hh | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 22 | 2019-06-13T01:16:44.000Z | 2022-03-29T02:42:39.000Z | platform/eSDK_LogAPI_V2.1.10/log4cpp/log4cpp/PatternLayout.hh | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 26 | 2019-09-20T06:46:05.000Z | 2022-03-11T08:07:14.000Z | platform/eSDK_LogAPI_V2.1.10/log4cpp/log4cpp/PatternLayout.hh | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 14 | 2019-07-15T06:42:39.000Z | 2022-02-15T10:32:28.000Z | /*
* PatternLayout.hh
*
* Copyright 2002, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#ifndef _LOG4CPP_PATTERNLAYOUT_HH
#define _LOG4CPP_PATTERNLAYOUT_HH
#include "log4cpp/Portability.hh"
#include "log4cpp/Layout.hh"
#include "log4cpp/Configurator.hh"
#include <vector>
#ifdef LOG4CPP_HAVE_SSTREAM
#include <sstream>
#endif
namespace log4cpp {
/**
* PatternLayout is a simple fixed format Layout implementation.
**/
class LOG4CPP_EXPORT PatternLayout : public Layout {
public:
/**
The default conversion pattern
**/
static const char* DEFAULT_CONVERSION_PATTERN;
/**
A conversion pattern equivalent to the SimpleLayout.
**/
static const char* SIMPLE_CONVERSION_PATTERN;
/**
A conversion pattern equivalent to the BasicLayout.
**/
static const char* BASIC_CONVERSION_PATTERN;
/**
A conversion pattern equivalent to the TTCCLayout.
Note: TTCCLayout is in log4j but not log4cpp.
**/
static const char* TTCC_CONVERSION_PATTERN;
PatternLayout();
virtual ~PatternLayout();
// NOTE: All double percentage signs ('%%') followed by a character
// in the following comments should actually be a single char.
// The doubles are included so that doxygen will print them correctly.
/**
* Formats the LoggingEvent in the style set by
* the setConversionPattern call. By default, set
* to "%%m%%n"
**/
virtual std::string format(const LoggingEvent& event);
/**
* Sets the format of log lines handled by this
* PatternLayout. By default, set to "%%m%%n".<br>
* Format characters are as follows:<br>
* <li><b>%%</b> - a single percent sign</li>
* <li><b>%%c</b> - the category</li>
* <li><b>%%d</b> - the date\n
* Date format: The date format character may be followed by a date format
* specifier enclosed between braces. For example, %%d{%%H:%%M:%%S,%%l} or %%d{%%d %%m %%Y %%H:%%M:%%S,%%l}.
* If no date format specifier is given then the following format is used:
* "Wed Jan 02 02:03:55 1980". The date format specifier admits the same syntax
* as the ANSI C function strftime, with 1 addition. The addition is the specifier
* %%l for milliseconds, padded with zeros to make 3 digits.</li>
* <li><b>%%m</b> - the message</li>
* <li><b>%%n</b> - the platform specific line separator</li>
* <li><b>%%p</b> - the priority</li>
* <li><b>%%r</b> - milliseconds since this layout was created.</li>
* <li><b>%%R</b> - seconds since Jan 1, 1970</li>
* <li><b>%%u</b> - clock ticks since process start</li>
* <li><b>%%x</b> - the NDC</li>
* @param conversionPattern the conversion pattern
* @exception ConfigureFailure if the pattern is invalid
**/
virtual void setConversionPattern(const std::string& conversionPattern)
throw(ConfigureFailure);
virtual std::string getConversionPattern() const;
virtual void clearConversionPattern();
class LOG4CPP_EXPORT PatternComponent {
public:
inline virtual ~PatternComponent() {};
virtual void append(std::ostringstream& out, const LoggingEvent& event) = 0;
};
private:
typedef std::vector<PatternComponent*> ComponentVector;
ComponentVector _components;
std::string _conversionPattern;
};
}
#endif // _LOG4CPP_PATTERNLAYOUT_HH
| 35.54717 | 117 | 0.605626 | [
"vector"
] |
a39c412989a06aa642736d18b41a6f587f935e40 | 6,650 | cpp | C++ | src/ir_builder.cpp | huangjd/simit-staging | 6a1d7946e88c7bf383abe800ee835d3680e86559 | [
"MIT"
] | null | null | null | src/ir_builder.cpp | huangjd/simit-staging | 6a1d7946e88c7bf383abe800ee835d3680e86559 | [
"MIT"
] | null | null | null | src/ir_builder.cpp | huangjd/simit-staging | 6a1d7946e88c7bf383abe800ee835d3680e86559 | [
"MIT"
] | null | null | null | #include "ir_builder.h"
#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>
using namespace std;
namespace simit {
namespace ir {
// class IndexVarFactory
IndexVar IndexVarFactory::createIndexVar(const IndexDomain &domain) {
return IndexVar(makeName(), domain);
}
IndexVar IndexVarFactory::createIndexVar(const IndexDomain &domain,
ReductionOperator rop) {
return IndexVar(makeName(), domain, rop);
}
std::string IndexVarFactory::makeName() {
char name[2];
name[0] = 'i' + nameID;
name[1] = '\0';
nameID++;
if (nameID == 18) {
nameID = 0;
}
return std::string(name);
}
// class IRBuilder
Expr IRBuilder::unaryElwiseExpr(UnaryOperator op, Expr e) {
tassert(e.type().isTensor())
<< "Only tensors can be operands of index expressions "
<< "(not " << e.type() << " types)";
vector<IndexVar> indexVars;
const TensorType *tensorType = e.type().toTensor();
vector<IndexDomain> dimensions = tensorType->getDimensions();
for (unsigned int i=0; i < tensorType->order(); ++i) {
IndexDomain domain = dimensions[i];
indexVars.push_back(factory.createIndexVar(domain));
}
Expr a = IndexedTensor::make(e, indexVars);
Expr val;
switch (op) {
case Copy:
val = a;
break;
case Neg:
val = Neg::make(a);
break;
default:
unreachable;
break;
}
iassert(val.defined());
return IndexExpr::make(indexVars, val, e.type().toTensor()->isColumnVector);
}
Expr IRBuilder::binaryElwiseExpr(Expr l, BinaryOperator op, Expr r) {
const TensorType *ltype = l.type().toTensor();
const TensorType *rtype = r.type().toTensor();
Expr tensor = (ltype->order() > 0) ? l : r;
std::vector<IndexVar> indexVars;
const TensorType *tensorType = tensor.type().toTensor();
vector<IndexDomain> dimensions = tensorType->getDimensions();
for (unsigned int i=0; i < tensorType->order(); ++i) {
IndexDomain domain = dimensions[i];
indexVars.push_back(factory.createIndexVar(domain));
}
Expr a, b;
if (ltype->order() == 0 || rtype->order() == 0) {
std::vector<IndexVar> scalarIndexVars;
std::vector<IndexVar> *lIndexVars;
std::vector<IndexVar> *rIndexVars;
if (ltype->order() == 0) {
lIndexVars = &scalarIndexVars;
rIndexVars = &indexVars;
}
else {
lIndexVars = &indexVars;
rIndexVars = &scalarIndexVars;
}
a = IndexedTensor::make(l, *lIndexVars);
b = IndexedTensor::make(r, *rIndexVars);
}
else {
iassert(l.type() == r.type());
a = IndexedTensor::make(l, indexVars);
b = IndexedTensor::make(r, indexVars);
}
iassert(a.defined() && b.defined());
Expr val;
switch (op) {
case Add:
val = Add::make(a, b);
break;
case Sub:
val = Sub::make(a, b);
break;
case Mul:
val = Mul::make(a, b);
break;
case Div:
val = Div::make(a, b);
break;
default:
unreachable;
break;
}
iassert(val.defined());
const bool isColumnVector = tensor.type().toTensor()->isColumnVector;
return IndexExpr::make(indexVars, val, isColumnVector);
}
Expr IRBuilder::innerProduct(Expr l, Expr r) {
iassert(l.type() == r.type());
const TensorType *type = l.type().toTensor();
vector<IndexDomain> dimensions = type->getDimensions();
auto i = factory.createIndexVar(dimensions[0], ReductionOperator::Sum);
Expr a = IndexedTensor::make(l, {i});
Expr b = IndexedTensor::make(r, {i});
Expr val = Mul::make(a, b);
std::vector<IndexVar> none;
return IndexExpr::make(none, val);
}
Expr IRBuilder::outerProduct(Expr l, Expr r) {
iassert(l.type() == r.type());
const TensorType *type = l.type().toTensor();
vector<IndexDomain> dimensions = type->getDimensions();
auto i = factory.createIndexVar(dimensions[0]);
auto j = factory.createIndexVar(dimensions[0]);
Expr a = IndexedTensor::make(l, {i});
Expr b = IndexedTensor::make(r, {j});
Expr val = Mul::make(a, b);
return IndexExpr::make({i,j}, val);
}
Expr IRBuilder::gemv(Expr l, Expr r) {
const TensorType *ltype = l.type().toTensor();
const TensorType *rtype = r.type().toTensor();
vector<IndexDomain> ldimensions = ltype->getDimensions();
vector<IndexDomain> rdimensions = rtype->getDimensions();
iassert(ltype->order() == 2 && rtype->order() == 1);
iassert(ldimensions[1] == rdimensions[0]);
auto i = factory.createIndexVar(ldimensions[0]);
auto j = factory.createIndexVar(ldimensions[1], ReductionOperator::Sum);
Expr a = IndexedTensor::make(l, {i, j});
Expr b = IndexedTensor::make(r, {j});
Expr val = Mul::make(a, b);
return IndexExpr::make({i}, val, true);
}
Expr IRBuilder::gevm(Expr l, Expr r) {
const TensorType *ltype = l.type().toTensor();
const TensorType *rtype = r.type().toTensor();
vector<IndexDomain> ldimensions = ltype->getDimensions();
vector<IndexDomain> rdimensions = rtype->getDimensions();
iassert(ltype->order() == 1 && rtype->order() == 2);
iassert(ldimensions[0] == rdimensions[0]);
auto i = factory.createIndexVar(rdimensions[1]);
auto j = factory.createIndexVar(rdimensions[0], ReductionOperator::Sum);
Expr a = IndexedTensor::make(l, {j});
Expr b = IndexedTensor::make(r, {j,i});
Expr val = Mul::make(a, b);
return IndexExpr::make({i}, val);
}
Expr IRBuilder::gemm(Expr l, Expr r) {
const TensorType *ltype = l.type().toTensor();
const TensorType *rtype = r.type().toTensor();
vector<IndexDomain> ldimensions = ltype->getDimensions();
vector<IndexDomain> rdimensions = rtype->getDimensions();
iassert(ltype->order() == 2 && rtype->order() == 2);
iassert(ldimensions[1] == rdimensions[0]);
auto i = factory.createIndexVar(ldimensions[0]);
auto j = factory.createIndexVar(rdimensions[1]);
auto k = factory.createIndexVar(ldimensions[1], ReductionOperator::Sum);
Expr a = IndexedTensor::make(l, {i,k});
Expr b = IndexedTensor::make(r, {k,j});
Expr val = Mul::make(a, b);
return IndexExpr::make({i,j}, val);
}
Expr IRBuilder::transposedMatrix(Expr mat) {
const TensorType *mattype = mat.type().toTensor();
iassert(mattype->order() == 2);
const std::vector<IndexDomain> &dimensions = mattype->getDimensions();
std::vector<IndexVar> indexVars;
indexVars.push_back(factory.createIndexVar(dimensions[0]));
indexVars.push_back(factory.createIndexVar(dimensions[1]));
Expr val = IndexedTensor::make(mat, {indexVars[0], indexVars[1]});
return IndexExpr::make({indexVars[1], indexVars[0]}, val);
}
Var IRBuilder::temporary(Type type, std::string name) {
return Var(names.getName(name), type);
}
}} // namespace simit::internal
| 28.059072 | 78 | 0.653534 | [
"vector"
] |
a39c8f89d4dbbe21250013516c77392fa777fec7 | 25,600 | hpp | C++ | clm/src/main/clm/jni/boost/armv7a/include/boost/geometry/io/wkt/read.hpp | BruceNUAA/gaze-detection-android-app | 5daa2c8a0e51eb506fe435a6f8d03758162d0579 | [
"MIT"
] | 1,210 | 2020-08-18T07:57:36.000Z | 2022-03-31T15:06:05.000Z | libs/boost/include/boost/geometry/io/wkt/read.hpp | dnevera/ofxiOSBoost | aae717bf8c5229f644057a17ccc971abf1c68bc3 | [
"BSL-1.0"
] | 37 | 2015-01-05T02:24:13.000Z | 2022-02-24T09:18:43.000Z | libs/boost/include/boost/geometry/io/wkt/read.hpp | dnevera/ofxiOSBoost | aae717bf8c5229f644057a17ccc971abf1c68bc3 | [
"BSL-1.0"
] | 275 | 2020-08-18T08:35:16.000Z | 2022-03-31T15:06:07.000Z | // Boost.Geometry (aka GGL, Generic Geometry Library)
// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// This file was modified by Oracle on 2014, 2015.
// Modifications copyright (c) 2014-2015 Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_GEOMETRY_IO_WKT_READ_HPP
#define BOOST_GEOMETRY_IO_WKT_READ_HPP
#include <cstddef>
#include <string>
#include <boost/lexical_cast.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/mpl/if.hpp>
#include <boost/range.hpp>
#include <boost/type_traits.hpp>
#include <boost/geometry/algorithms/assign.hpp>
#include <boost/geometry/algorithms/append.hpp>
#include <boost/geometry/algorithms/clear.hpp>
#include <boost/geometry/algorithms/detail/equals/point_point.hpp>
#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/exception.hpp>
#include <boost/geometry/core/exterior_ring.hpp>
#include <boost/geometry/core/geometry_id.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/core/mutable_range.hpp>
#include <boost/geometry/core/point_type.hpp>
#include <boost/geometry/core/tag_cast.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>
#include <boost/geometry/util/coordinate_cast.hpp>
#include <boost/geometry/io/wkt/detail/prefix.hpp>
namespace boost { namespace geometry
{
/*!
\brief Exception showing things wrong with WKT parsing
\ingroup wkt
*/
struct read_wkt_exception : public geometry::exception
{
template <typename Iterator>
read_wkt_exception(std::string const& msg,
Iterator const& it,
Iterator const& end,
std::string const& wkt)
: message(msg)
, wkt(wkt)
{
if (it != end)
{
source = " at '";
source += it->c_str();
source += "'";
}
complete = message + source + " in '" + wkt.substr(0, 100) + "'";
}
read_wkt_exception(std::string const& msg, std::string const& wkt)
: message(msg)
, wkt(wkt)
{
complete = message + "' in (" + wkt.substr(0, 100) + ")";
}
virtual ~read_wkt_exception() throw() {}
virtual const char* what() const throw()
{
return complete.c_str();
}
private :
std::string source;
std::string message;
std::string wkt;
std::string complete;
};
#ifndef DOXYGEN_NO_DETAIL
// (wkt: Well Known Text, defined by OGC for all geometries and implemented by e.g. databases (MySQL, PostGIS))
namespace detail { namespace wkt
{
typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
template <typename Point,
std::size_t Dimension = 0,
std::size_t DimensionCount = geometry::dimension<Point>::value>
struct parsing_assigner
{
static inline void apply(tokenizer::iterator& it,
tokenizer::iterator const& end,
Point& point,
std::string const& wkt)
{
typedef typename coordinate_type<Point>::type coordinate_type;
// Stop at end of tokens, or at "," ot ")"
bool finished = (it == end || *it == "," || *it == ")");
try
{
// Initialize missing coordinates to default constructor (zero)
// OR
// Use lexical_cast for conversion to double/int
// Note that it is much slower than atof. However, it is more standard
// and in parsing the change in performance falls probably away against
// the tokenizing
set<Dimension>(point, finished
? coordinate_type()
: coordinate_cast<coordinate_type>::apply(*it));
}
catch(boost::bad_lexical_cast const& blc)
{
throw read_wkt_exception(blc.what(), it, end, wkt);
}
catch(std::exception const& e)
{
throw read_wkt_exception(e.what(), it, end, wkt);
}
catch(...)
{
throw read_wkt_exception("", it, end, wkt);
}
parsing_assigner<Point, Dimension + 1, DimensionCount>::apply(
(finished ? it : ++it), end, point, wkt);
}
};
template <typename Point, std::size_t DimensionCount>
struct parsing_assigner<Point, DimensionCount, DimensionCount>
{
static inline void apply(tokenizer::iterator&,
tokenizer::iterator const&,
Point&,
std::string const&)
{
}
};
template <typename Iterator>
inline void handle_open_parenthesis(Iterator& it,
Iterator const& end,
std::string const& wkt)
{
if (it == end || *it != "(")
{
throw read_wkt_exception("Expected '('", it, end, wkt);
}
++it;
}
template <typename Iterator>
inline void handle_close_parenthesis(Iterator& it,
Iterator const& end,
std::string const& wkt)
{
if (it != end && *it == ")")
{
++it;
}
else
{
throw read_wkt_exception("Expected ')'", it, end, wkt);
}
}
template <typename Iterator>
inline void check_end(Iterator& it,
Iterator const& end,
std::string const& wkt)
{
if (it != end)
{
throw read_wkt_exception("Too much tokens", it, end, wkt);
}
}
/*!
\brief Internal, parses coordinate sequences, strings are formated like "(1 2,3 4,...)"
\param it token-iterator, should be pre-positioned at "(", is post-positions after last ")"
\param end end-token-iterator
\param out Output itererator receiving coordinates
*/
template <typename Point>
struct container_inserter
{
// Version with output iterator
template <typename OutputIterator>
static inline void apply(tokenizer::iterator& it,
tokenizer::iterator const& end,
std::string const& wkt,
OutputIterator out)
{
handle_open_parenthesis(it, end, wkt);
Point point;
// Parse points until closing parenthesis
while (it != end && *it != ")")
{
parsing_assigner<Point>::apply(it, end, point, wkt);
out = point;
++out;
if (it != end && *it == ",")
{
++it;
}
}
handle_close_parenthesis(it, end, wkt);
}
};
template <typename Geometry,
closure_selector Closure = closure<Geometry>::value>
struct stateful_range_appender
{
typedef typename geometry::point_type<Geometry>::type point_type;
// NOTE: Geometry is a reference
inline void append(Geometry geom, point_type const& point, bool)
{
geometry::append(geom, point);
}
};
template <typename Geometry>
struct stateful_range_appender<Geometry, open>
{
typedef typename geometry::point_type<Geometry>::type point_type;
typedef typename boost::range_size
<
typename util::bare_type<Geometry>::type
>::type size_type;
BOOST_STATIC_ASSERT(( boost::is_same
<
typename tag<Geometry>::type,
ring_tag
>::value ));
inline stateful_range_appender()
: pt_index(0)
{}
// NOTE: Geometry is a reference
inline void append(Geometry geom, point_type const& point, bool is_next_expected)
{
bool should_append = true;
if (pt_index == 0)
{
first_point = point;
//should_append = true;
}
else
{
// NOTE: if there is not enough Points, they're always appended
should_append
= is_next_expected
|| pt_index < core_detail::closure::minimum_ring_size<open>::value
|| !detail::equals::equals_point_point(point, first_point);
}
++pt_index;
if (should_append)
{
geometry::append(geom, point);
}
}
private:
size_type pt_index;
point_type first_point;
};
// Geometry is a value-type or reference-type
template <typename Geometry>
struct container_appender
{
typedef typename geometry::point_type<Geometry>::type point_type;
static inline void apply(tokenizer::iterator& it,
tokenizer::iterator const& end,
std::string const& wkt,
Geometry out)
{
handle_open_parenthesis(it, end, wkt);
stateful_range_appender<Geometry> appender;
// Parse points until closing parenthesis
while (it != end && *it != ")")
{
point_type point;
parsing_assigner<point_type>::apply(it, end, point, wkt);
bool const is_next_expected = it != end && *it == ",";
appender.append(out, point, is_next_expected);
if (is_next_expected)
{
++it;
}
}
handle_close_parenthesis(it, end, wkt);
}
};
/*!
\brief Internal, parses a point from a string like this "(x y)"
\note used for parsing points and multi-points
*/
template <typename P>
struct point_parser
{
static inline void apply(tokenizer::iterator& it,
tokenizer::iterator const& end,
std::string const& wkt,
P& point)
{
handle_open_parenthesis(it, end, wkt);
parsing_assigner<P>::apply(it, end, point, wkt);
handle_close_parenthesis(it, end, wkt);
}
};
template <typename Geometry>
struct linestring_parser
{
static inline void apply(tokenizer::iterator& it,
tokenizer::iterator const& end,
std::string const& wkt,
Geometry& geometry)
{
container_appender<Geometry&>::apply(it, end, wkt, geometry);
}
};
template <typename Ring>
struct ring_parser
{
static inline void apply(tokenizer::iterator& it,
tokenizer::iterator const& end,
std::string const& wkt,
Ring& ring)
{
// A ring should look like polygon((x y,x y,x y...))
// So handle the extra opening/closing parentheses
// and in between parse using the container-inserter
handle_open_parenthesis(it, end, wkt);
container_appender<Ring&>::apply(it, end, wkt, ring);
handle_close_parenthesis(it, end, wkt);
}
};
/*!
\brief Internal, parses a polygon from a string like this "((x y,x y),(x y,x y))"
\note used for parsing polygons and multi-polygons
*/
template <typename Polygon>
struct polygon_parser
{
typedef typename ring_return_type<Polygon>::type ring_return_type;
typedef container_appender<ring_return_type> appender;
static inline void apply(tokenizer::iterator& it,
tokenizer::iterator const& end,
std::string const& wkt,
Polygon& poly)
{
handle_open_parenthesis(it, end, wkt);
int n = -1;
// Stop at ")"
while (it != end && *it != ")")
{
// Parse ring
if (++n == 0)
{
appender::apply(it, end, wkt, exterior_ring(poly));
}
else
{
typename ring_type<Polygon>::type ring;
appender::apply(it, end, wkt, ring);
traits::push_back
<
typename boost::remove_reference
<
typename traits::interior_mutable_type<Polygon>::type
>::type
>::apply(interior_rings(poly), ring);
}
if (it != end && *it == ",")
{
// Skip "," after ring is parsed
++it;
}
}
handle_close_parenthesis(it, end, wkt);
}
};
inline bool one_of(tokenizer::iterator const& it,
std::string const& value,
bool& is_present)
{
if (boost::iequals(*it, value))
{
is_present = true;
return true;
}
return false;
}
inline bool one_of(tokenizer::iterator const& it,
std::string const& value,
bool& present1,
bool& present2)
{
if (boost::iequals(*it, value))
{
present1 = true;
present2 = true;
return true;
}
return false;
}
inline void handle_empty_z_m(tokenizer::iterator& it,
tokenizer::iterator const& end,
bool& has_empty,
bool& has_z,
bool& has_m)
{
has_empty = false;
has_z = false;
has_m = false;
// WKT can optionally have Z and M (measured) values as in
// POINT ZM (1 1 5 60), POINT M (1 1 80), POINT Z (1 1 5)
// GGL supports any of them as coordinate values, but is not aware
// of any Measured value.
while (it != end
&& (one_of(it, "M", has_m)
|| one_of(it, "Z", has_z)
|| one_of(it, "EMPTY", has_empty)
|| one_of(it, "MZ", has_m, has_z)
|| one_of(it, "ZM", has_z, has_m)
)
)
{
++it;
}
}
/*!
\brief Internal, starts parsing
\param tokens boost tokens, parsed with separator " " and keeping separator "()"
\param geometry string to compare with first token
*/
template <typename Geometry>
inline bool initialize(tokenizer const& tokens,
std::string const& geometry_name,
std::string const& wkt,
tokenizer::iterator& it,
tokenizer::iterator& end)
{
it = tokens.begin();
end = tokens.end();
if (it != end && boost::iequals(*it++, geometry_name))
{
bool has_empty, has_z, has_m;
handle_empty_z_m(it, end, has_empty, has_z, has_m);
// Silence warning C4127: conditional expression is constant
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4127)
#endif
if (has_z && dimension<Geometry>::type::value < 3)
{
throw read_wkt_exception("Z only allowed for 3 or more dimensions", wkt);
}
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
if (has_empty)
{
check_end(it, end, wkt);
return false;
}
// M is ignored at all.
return true;
}
throw read_wkt_exception(std::string("Should start with '") + geometry_name + "'", wkt);
}
template <typename Geometry, template<typename> class Parser, typename PrefixPolicy>
struct geometry_parser
{
static inline void apply(std::string const& wkt, Geometry& geometry)
{
geometry::clear(geometry);
tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()"));
tokenizer::iterator it, end;
if (initialize<Geometry>(tokens, PrefixPolicy::apply(), wkt, it, end))
{
Parser<Geometry>::apply(it, end, wkt, geometry);
check_end(it, end, wkt);
}
}
};
template <typename MultiGeometry, template<typename> class Parser, typename PrefixPolicy>
struct multi_parser
{
static inline void apply(std::string const& wkt, MultiGeometry& geometry)
{
traits::clear<MultiGeometry>::apply(geometry);
tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()"));
tokenizer::iterator it, end;
if (initialize<MultiGeometry>(tokens, PrefixPolicy::apply(), wkt, it, end))
{
handle_open_parenthesis(it, end, wkt);
// Parse sub-geometries
while(it != end && *it != ")")
{
traits::resize<MultiGeometry>::apply(geometry, boost::size(geometry) + 1);
Parser
<
typename boost::range_value<MultiGeometry>::type
>::apply(it, end, wkt, *(boost::end(geometry) - 1));
if (it != end && *it == ",")
{
// Skip "," after multi-element is parsed
++it;
}
}
handle_close_parenthesis(it, end, wkt);
}
check_end(it, end, wkt);
}
};
template <typename P>
struct noparenthesis_point_parser
{
static inline void apply(tokenizer::iterator& it,
tokenizer::iterator const& end,
std::string const& wkt,
P& point)
{
parsing_assigner<P>::apply(it, end, point, wkt);
}
};
template <typename MultiGeometry, typename PrefixPolicy>
struct multi_point_parser
{
static inline void apply(std::string const& wkt, MultiGeometry& geometry)
{
traits::clear<MultiGeometry>::apply(geometry);
tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()"));
tokenizer::iterator it, end;
if (initialize<MultiGeometry>(tokens, PrefixPolicy::apply(), wkt, it, end))
{
handle_open_parenthesis(it, end, wkt);
// If first point definition starts with "(" then parse points as (x y)
// otherwise as "x y"
bool using_brackets = (it != end && *it == "(");
while(it != end && *it != ")")
{
traits::resize<MultiGeometry>::apply(geometry, boost::size(geometry) + 1);
if (using_brackets)
{
point_parser
<
typename boost::range_value<MultiGeometry>::type
>::apply(it, end, wkt, *(boost::end(geometry) - 1));
}
else
{
noparenthesis_point_parser
<
typename boost::range_value<MultiGeometry>::type
>::apply(it, end, wkt, *(boost::end(geometry) - 1));
}
if (it != end && *it == ",")
{
// Skip "," after point is parsed
++it;
}
}
handle_close_parenthesis(it, end, wkt);
}
check_end(it, end, wkt);
}
};
/*!
\brief Supports box parsing
\note OGC does not define the box geometry, and WKT does not support boxes.
However, to be generic GGL supports reading and writing from and to boxes.
Boxes are outputted as a standard POLYGON. GGL can read boxes from
a standard POLYGON, from a POLYGON with 2 points of from a BOX
\tparam Box the box
*/
template <typename Box>
struct box_parser
{
static inline void apply(std::string const& wkt, Box& box)
{
bool should_close = false;
tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()"));
tokenizer::iterator it = tokens.begin();
tokenizer::iterator end = tokens.end();
if (it != end && boost::iequals(*it, "POLYGON"))
{
++it;
bool has_empty, has_z, has_m;
handle_empty_z_m(it, end, has_empty, has_z, has_m);
if (has_empty)
{
assign_zero(box);
return;
}
handle_open_parenthesis(it, end, wkt);
should_close = true;
}
else if (it != end && boost::iequals(*it, "BOX"))
{
++it;
}
else
{
throw read_wkt_exception("Should start with 'POLYGON' or 'BOX'", wkt);
}
typedef typename point_type<Box>::type point_type;
std::vector<point_type> points;
container_inserter<point_type>::apply(it, end, wkt, std::back_inserter(points));
if (should_close)
{
handle_close_parenthesis(it, end, wkt);
}
check_end(it, end, wkt);
unsigned int index = 0;
std::size_t n = boost::size(points);
if (n == 2)
{
index = 1;
}
else if (n == 4 || n == 5)
{
// In case of 4 or 5 points, we do not check the other ones, just
// take the opposite corner which is always 2
index = 2;
}
else
{
throw read_wkt_exception("Box should have 2,4 or 5 points", wkt);
}
geometry::detail::assign_point_to_index<min_corner>(points.front(), box);
geometry::detail::assign_point_to_index<max_corner>(points[index], box);
}
};
/*!
\brief Supports segment parsing
\note OGC does not define the segment, and WKT does not support segmentes.
However, it is useful to implement it, also for testing purposes
\tparam Segment the segment
*/
template <typename Segment>
struct segment_parser
{
static inline void apply(std::string const& wkt, Segment& segment)
{
tokenizer tokens(wkt, boost::char_separator<char>(" ", ",()"));
tokenizer::iterator it = tokens.begin();
tokenizer::iterator end = tokens.end();
if (it != end &&
(boost::iequals(*it, "SEGMENT")
|| boost::iequals(*it, "LINESTRING") ))
{
++it;
}
else
{
throw read_wkt_exception("Should start with 'LINESTRING' or 'SEGMENT'", wkt);
}
typedef typename point_type<Segment>::type point_type;
std::vector<point_type> points;
container_inserter<point_type>::apply(it, end, wkt, std::back_inserter(points));
check_end(it, end, wkt);
if (boost::size(points) == 2)
{
geometry::detail::assign_point_to_index<0>(points.front(), segment);
geometry::detail::assign_point_to_index<1>(points.back(), segment);
}
else
{
throw read_wkt_exception("Segment should have 2 points", wkt);
}
}
};
}} // namespace detail::wkt
#endif // DOXYGEN_NO_DETAIL
#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{
template <typename Tag, typename Geometry>
struct read_wkt {};
template <typename Point>
struct read_wkt<point_tag, Point>
: detail::wkt::geometry_parser
<
Point,
detail::wkt::point_parser,
detail::wkt::prefix_point
>
{};
template <typename L>
struct read_wkt<linestring_tag, L>
: detail::wkt::geometry_parser
<
L,
detail::wkt::linestring_parser,
detail::wkt::prefix_linestring
>
{};
template <typename Ring>
struct read_wkt<ring_tag, Ring>
: detail::wkt::geometry_parser
<
Ring,
detail::wkt::ring_parser,
detail::wkt::prefix_polygon
>
{};
template <typename Geometry>
struct read_wkt<polygon_tag, Geometry>
: detail::wkt::geometry_parser
<
Geometry,
detail::wkt::polygon_parser,
detail::wkt::prefix_polygon
>
{};
template <typename MultiGeometry>
struct read_wkt<multi_point_tag, MultiGeometry>
: detail::wkt::multi_point_parser
<
MultiGeometry,
detail::wkt::prefix_multipoint
>
{};
template <typename MultiGeometry>
struct read_wkt<multi_linestring_tag, MultiGeometry>
: detail::wkt::multi_parser
<
MultiGeometry,
detail::wkt::linestring_parser,
detail::wkt::prefix_multilinestring
>
{};
template <typename MultiGeometry>
struct read_wkt<multi_polygon_tag, MultiGeometry>
: detail::wkt::multi_parser
<
MultiGeometry,
detail::wkt::polygon_parser,
detail::wkt::prefix_multipolygon
>
{};
// Box (Non-OGC)
template <typename Box>
struct read_wkt<box_tag, Box>
: detail::wkt::box_parser<Box>
{};
// Segment (Non-OGC)
template <typename Segment>
struct read_wkt<segment_tag, Segment>
: detail::wkt::segment_parser<Segment>
{};
} // namespace dispatch
#endif // DOXYGEN_NO_DISPATCH
/*!
\brief Parses OGC Well-Known Text (\ref WKT) into a geometry (any geometry)
\ingroup wkt
\tparam Geometry \tparam_geometry
\param wkt string containing \ref WKT
\param geometry \param_geometry output geometry
\ingroup wkt
\qbk{[include reference/io/read_wkt.qbk]}
*/
template <typename Geometry>
inline void read_wkt(std::string const& wkt, Geometry& geometry)
{
geometry::concept::check<Geometry>();
dispatch::read_wkt<typename tag<Geometry>::type, Geometry>::apply(wkt, geometry);
}
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_IO_WKT_READ_HPP
| 28.412875 | 111 | 0.561992 | [
"geometry",
"vector"
] |
a39f8d73a7f24dbd8b928c26aa66218485102a1b | 6,850 | hpp | C++ | include/ting/PoolStored.hpp | bobsomers/haste | eb33c3862d79cc90185044e0fdb44c6ce01a89c6 | [
"MIT"
] | 1 | 2016-10-24T03:52:23.000Z | 2016-10-24T03:52:23.000Z | include/ting/PoolStored.hpp | bobsomers/haste | eb33c3862d79cc90185044e0fdb44c6ce01a89c6 | [
"MIT"
] | null | null | null | include/ting/PoolStored.hpp | bobsomers/haste | eb33c3862d79cc90185044e0fdb44c6ce01a89c6 | [
"MIT"
] | null | null | null | /* The MIT License:
Copyright (c) 2009-2010 Ivan Gagis
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. */
// ting 0.4.2
// Homepage: http://code.google.com/p/ting
/**
* @file PoolStored.hpp
* @author Ivan Gagis <igagis@gmail.com>
* @brief Memory Pool.
* Alternative memory allocation functions for simple objects.
* The main purpose of this facilities is to prevent memory fragmentation.
*/
#pragma once
#include <new>
#include <vector>
#include "debug.hpp"
#include "types.hpp"
#include "utils.hpp"
#include "Thread.hpp"
#include "Exc.hpp"
#include "Array.hpp"
//#define M_ENABLE_POOL_TRACE
#ifdef M_ENABLE_POOL_TRACE
#define M_POOL_TRACE(x) TRACE(<<"[POOL] ") TRACE(x)
#else
#define M_POOL_TRACE(x)
#endif
namespace ting{
//make sure theat we align PoolElem by int size when using MSVC compiler.
STATIC_ASSERT(sizeof(int) == 4)
/**
* @brief Base class for pool-stored objects.
* If the class is derived from PoolStored it will override 'new' and 'delete'
* operators for that class so that the objects would be stored in the
* memory pool instead of using standard memory manager to allocate memory.
* Storing objects in memory pool allows to avoid memory fragmentation.
* PoolStored is only useful for systems with large ammount of small and
* simple objects which have to be allocated dynamically (i.e. using new/delete
* operators).
* For example, PoolStored is used in ting::Ref (reference counted objects)
* class to allocate reference counting objects which holds number of references and
* pointer to reference counted object.
* NOTE: class derived from PoolStored SHALL NOT be used as a base class further.
*/
template <class T> class PoolStored{
template <unsigned ElemSize, unsigned NumElemsInChunk> class MemPool{
struct BufHolder{
u8 buf[ElemSize];
};
M_DECLARE_ALIGNED_MSVC(4) struct PoolElem : public BufHolder{
bool isFree;
PoolElem() :
isFree(true)
{}
}
//Align by sizeof(int) boundary, just to be more safe.
//I once had a problem with pthread mutex when it was not aligned by 4 byte bounday,
//so I resolved this by declaring PoolElem struct as aligned by sizeof(int).
M_DECLARE_ALIGNED(sizeof(int));
struct Chunk : public ting::Array<PoolElem>{
unsigned numAllocated;
Chunk() :
ting::Array<PoolElem>(NumElemsInChunk),
numAllocated(0)
{}
Chunk(const Chunk& c) :
ting::Array<PoolElem>(c),
numAllocated(c.numAllocated)
{
const_cast<Chunk&>(c).numAllocated = 0;//to prevent assert in destructor
M_POOL_TRACE(<< "Chunk::Chunk(copy): invoked" << std::endl)
}
Chunk& operator=(const Chunk& c){
M_POOL_TRACE(<< "Chunk::operator=(): invoked" << std::endl)
ASSERT(false)
return *this;
}
~Chunk(){
ASSERT_INFO(this->numAllocated == 0, "this->numAllocated = " << this->numAllocated << " should be 0")
}
};
struct ChunksList{
typedef std::vector<Chunk> T_List;
typedef typename T_List::iterator T_Iter;
T_List chunks;
ting::Mutex mutex;
~ChunksList(){
// TRACE(<< "PoolStored::ChunksList::~ChunksList(): invoked" << std::endl)
ASSERT_INFO(this->chunks.size() == 0, "PoolStored: cannot destroy chunk list because it is not empty. Check for static PoolStored objects, they are not allowed, e.g. static Ref/WeakRef are not allowed!")
}
};
static ChunksList& Chunks(){
static ChunksList chunks;
return chunks;
}
public:
static void* Alloc(){
ChunksList &cl = Chunks();
ting::Mutex::Guard mutlock(cl.mutex);
//find chunk with free cell
Chunk *chunk = 0;
for(typename ChunksList::T_Iter i = cl.chunks.begin(); i != cl.chunks.end(); ++i){
if((*i).numAllocated < (*i).Size()){
chunk = &(*i);
}
}
//create new chunk if necessary
if(chunk == 0){
cl.chunks.push_back(Chunk());
chunk = &cl.chunks.back();
}
ASSERT(chunk)
M_POOL_TRACE(<< "Alloc(): Free chunk = " << chunk << std::endl)
//find free cell
for(PoolElem* i = chunk->Begin(); i != chunk->End(); ++i){
if(i->isFree){
ASSERT(chunk->numAllocated < chunk->Size())
i->isFree = false;
++chunk->numAllocated;
M_POOL_TRACE(<< "Alloc(): Free cell found = " << i << " sizeof(PoolElem) = " << sizeof(PoolElem) << std::endl)
M_POOL_TRACE(<< "Alloc(): returning " << static_cast<BufHolder*>(i) << std::endl)
return reinterpret_cast<void*>(static_cast<BufHolder*>(i));
}
}
ASSERT(false)
return 0;
}
static void Free(void* p){
M_POOL_TRACE(<< "Free(): p = " << p << std::endl)
if(!p)
return;
ChunksList &cl = Chunks();
ting::Mutex::Guard mutlock(cl.mutex);
//find chunk the p belongs to
for(typename ChunksList::T_Iter i = cl.chunks.begin(); i != cl.chunks.end(); ++i){
ASSERT((*i).numAllocated != 0)
if((*i).End() > p && p >= (*i).Begin()){
Chunk *chunk = &(*i);
M_POOL_TRACE(<< "Free(): chunk found = " << chunk << std::endl)
--(chunk->numAllocated);
if(chunk->numAllocated == 0){
cl.chunks.erase(i);
}else{
static_cast<PoolElem*>(
reinterpret_cast<BufHolder*>(p)
)->isFree = true;
}
return;
}
}
ASSERT(false)
}
};//~template class MemPool
protected:
//this should only be used as a base class
PoolStored(){}
public:
#define M_MEMPOOL_TYPEDEF \
typedef MemPool< \
sizeof(T), \
((8192 / sizeof(T)) < 32) ? 32 : (8192 / sizeof(T)) \
> T_MemoryPool;
static void* operator new (size_t size){
M_POOL_TRACE(<< "new(): size = " << size << std::endl)
if(size != sizeof(T))
throw ting::Exc("PoolStored::operator new(): attempt to allocate memory block of incorrect size");
M_MEMPOOL_TYPEDEF
return T_MemoryPool::Alloc();
}
static void operator delete (void *p){
M_MEMPOOL_TYPEDEF
T_MemoryPool::Free(p);
}
#undef M_MEMPOOL_TYPEDEF
private:
};
}//~namespace ting
| 28.781513 | 207 | 0.67708 | [
"object",
"vector"
] |
a3a02092c3154c7d05cf2ed8eca842ec2ffe017a | 2,806 | cpp | C++ | sources/meshSaving.cpp | malytomas/unnatural-planets | 57ad1a48629a37f95ff729b75f8aaf439e209093 | [
"MIT"
] | null | null | null | sources/meshSaving.cpp | malytomas/unnatural-planets | 57ad1a48629a37f95ff729b75f8aaf439e209093 | [
"MIT"
] | null | null | null | sources/meshSaving.cpp | malytomas/unnatural-planets | 57ad1a48629a37f95ff729b75f8aaf439e209093 | [
"MIT"
] | null | null | null | #include <cage-core/files.h>
#include <cage-core/mesh.h>
#include "terrain.h"
#include "mesh.h"
void meshSaveDebug(const String &path, const Holder<Mesh> &mesh)
{
CAGE_LOG(SeverityEnum::Info, "generator", Stringizer() + "saving debug mesh: " + path);
MeshExportObjConfig cfg;
cfg.objectName = pathExtractFilenameNoExtension(path);
mesh->exportObjFile(path, cfg);
}
void meshSaveRender(const String &path, const Holder<Mesh> &mesh, bool transparency)
{
CAGE_LOG(SeverityEnum::Info, "generator", Stringizer() + "saving render mesh: " + path);
CAGE_ASSERT(mesh->normals().size() == mesh->verticesCount());
CAGE_ASSERT(mesh->uvs().size() == mesh->verticesCount());
MeshExportObjConfig cfg;
cfg.objectName = pathExtractFilenameNoExtension(path);
cfg.materialLibraryName = cfg.objectName + ".mtl";
cfg.materialName = cfg.objectName;
mesh->exportObjFile(path, cfg);
const String directory = pathExtractDirectory(path);
const String cpmName = cfg.objectName + ".cpm";
{ // write mtl file with link to albedo texture
Holder<File> f = writeFile(pathJoin(directory, cfg.materialLibraryName));
f->writeLine(Stringizer() + "newmtl " + cfg.materialName);
f->writeLine(Stringizer() + "map_Kd " + cfg.objectName + "-albedo.png");
if (transparency)
f->writeLine(Stringizer() + "map_d " + cfg.objectName + "-albedo.png");
}
{ // write cpm material file
Holder<File> f = newFile(pathJoin(directory, cpmName), FileMode(false, true));
f->writeLine("[textures]");
f->writeLine(Stringizer() + "albedo = " + cfg.objectName + "-albedo.png");
f->writeLine(Stringizer() + "special = " + cfg.objectName + "-special.png");
f->writeLine(Stringizer() + "normal = " + cfg.objectName + "-height.png");
if (transparency)
{
f->writeLine("[flags]");
//f->writeLine("noShadowCast");
f->writeLine("translucent");
}
}
}
void meshSaveNavigation(const String &path, const Holder<Mesh> &mesh, const std::vector<Tile> &tiles)
{
CAGE_LOG(SeverityEnum::Info, "generator", Stringizer() + "saving navigation mesh: " + path);
CAGE_ASSERT(mesh->normals().size() == mesh->verticesCount());
CAGE_ASSERT(tiles.size() == mesh->verticesCount());
Holder<Mesh> m = mesh->copy();
std::vector<Vec2> uvs;
uvs.reserve(tiles.size());
for (const Tile &t : tiles)
{
static_assert((uint8)TerrainTypeEnum::_Total <= 32);
uvs.push_back(Vec2(((uint8)(t.type) + 0.5) / 32, 0));
}
m->uvs(uvs);
MeshExportObjConfig cfg;
cfg.objectName = "navigation";
m->exportObjFile(path, cfg);
}
void meshSaveCollider(const String &path, const Holder<Mesh> &mesh)
{
CAGE_LOG(SeverityEnum::Info, "generator", Stringizer() + "saving collider: " + path);
Holder<Mesh> m = mesh->copy();
m->normals({});
m->uvs({});
MeshExportObjConfig cfg;
cfg.objectName = "collider";
m->exportObjFile(path, cfg);
}
| 32.252874 | 101 | 0.68995 | [
"mesh",
"render",
"vector"
] |
a3a71023fba6ce27b755654230e9697169b75c5d | 2,649 | cpp | C++ | test_package/source/testreactor_tests.cpp | CynaraKrewe/Flow | b894658c8a7e811a9b8f4fef8a6aba67fb59fac4 | [
"MIT"
] | 6 | 2016-12-23T14:41:36.000Z | 2021-03-11T20:14:53.000Z | test_package/source/testreactor_tests.cpp | CynaraKrewe/Flow | b894658c8a7e811a9b8f4fef8a6aba67fb59fac4 | [
"MIT"
] | 4 | 2018-04-03T19:42:26.000Z | 2018-08-27T17:59:02.000Z | test_package/source/testreactor_tests.cpp | CynaraKrewe/Flow | b894658c8a7e811a9b8f4fef8a6aba67fb59fac4 | [
"MIT"
] | 1 | 2021-01-19T15:07:50.000Z | 2021-01-19T15:07:50.000Z | /* The MIT License (MIT)
*
* Copyright (c) 2020 Cynara Krewe
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software, hardware and associated documentation files (the "Solution"), to deal
* in the Solution without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Solution, and to permit persons to whom the Solution 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 Solution.
*
* THE SOLUTION 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 SOLUTION OR THE USE OR OTHER DEALINGS IN THE
* SOLUTION.
*/
#include <stdint.h>
#include <vector>
#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"
#include "flow/components.h"
#include "flow/reactor.h"
#include "flow/utility.h"
#include "data.h"
using Flow::Test::Reactor;
TEST_GROUP(TestReactor_TestBench)
{
Reactor* reactor;
SoftwareTimer* timer;
Counter<Tick>* counterA;
Counter<uint32_t>* counterB;
std::vector<Flow::Connection*> connections;
Flow::InPort<uint32_t> inCount{ nullptr };
void setup()
{
reactor = new Reactor;
timer = new SoftwareTimer{1};
counterA = new Counter<Tick>{UINT32_MAX};
counterB = new Counter<uint32_t>{UINT32_MAX};
connections =
{
Flow::connect(timer->outTick, counterA->in),
Flow::connect(counterA->out, counterB->in),
Flow::connect(counterB->out, inCount)
};
}
void teardown()
{
mock().clear();
for(Flow::Connection* connection : connections)
{
Flow::disconnect(connection);
}
connections.clear();
delete timer;
delete counterA;
delete counterB;
delete reactor;
}
};
TEST(TestReactor_TestBench, React)
{
reactor->start();
uint32_t finalCount = 0;
do
{
timer->isr();
mock().expectOneCall("Platform::waitForEvent()");
reactor->run();
inCount.receive(finalCount);
} while(finalCount < 100);
mock().expectOneCall("Platform::waitForEvent()");
reactor->run();
reactor->stop();
mock().checkExpectations();
}
| 24.990566 | 91 | 0.691959 | [
"vector"
] |
a3a8d03e2e9b8116621d1604155c5a3dc4ab189e | 2,912 | cpp | C++ | c++/main.cpp | ToruNiina/rigid_disk | 4c4fa95674feb17e273515e45b0707f914c29e5e | [
"MIT"
] | null | null | null | c++/main.cpp | ToruNiina/rigid_disk | 4c4fa95674feb17e273515e45b0707f914c29e5e | [
"MIT"
] | null | null | null | c++/main.cpp | ToruNiina/rigid_disk | 4c4fa95674feb17e273515e45b0707f914c29e5e | [
"MIT"
] | null | null | null | #include "position.hpp"
#include "boundary.hpp"
#include "disk.hpp"
#include <algorithm>
#include <numeric>
#include <vector>
#include <array>
#include <random>
#include <iostream>
namespace rigid_disk
{
struct system
{
boundary bc;
std::vector<disk> disks;
};
void print_system(const system& sys)
{
std::cout << sys.disks.size() << "\n\n";
for(const auto& dsk : sys.disks)
{
std::cout << "H " << dsk.p.x << ' ' << dsk.p.y << " 0.0\n";
}
return;
}
} // rigid_disk
int main(int argc, char **argv)
{
std::ios_base::sync_with_stdio(false);
std::mt19937 rng(123456789);
constexpr double radius = 1.0;
constexpr std::size_t num_disks = 100;
constexpr double delta = 0.3;
//------------------------ initialize system ------------------------
const rigid_disk::position lower = { 0.0, 0.0};
const rigid_disk::position upper = {30.0, 30.0};
rigid_disk::system sys{rigid_disk::boundary{lower, upper}, {}};
std::uniform_real_distribution<double> uni_x(lower.x, upper.x);
std::uniform_real_distribution<double> uni_y(lower.y, upper.y);
for(std::size_t n=0; n<num_disks; ++n)
{
while(true)
{
const rigid_disk::disk new_disk = {
radius, rigid_disk::position{uni_x(rng), uni_y(rng)}
};
const auto overlap_with = [&](const rigid_disk::disk& dsk){
return rigid_disk::overlaps(new_disk, dsk, sys.bc);
};
if(sys.disks.cend() == std::find_if(
sys.disks.cbegin(), sys.disks.cend(), overlap_with))
{
sys.disks.push_back(new_disk);
break;
}
}
}
//------------------------------ MCMC ------------------------------
std::uniform_real_distribution<double> displacement(-delta, delta);
std::array<std::size_t, num_disks> idx_list;
std::iota(idx_list.begin(), idx_list.end(), 0ul);
for(std::size_t t=0; t<10000; ++t)
{
rigid_disk::print_system(sys);
std::shuffle(idx_list.begin(), idx_list.end(), rng);
for(std::size_t idx : idx_list)
{
rigid_disk::disk target = sys.disks[idx];
const rigid_disk::position dv = {
displacement(rng), displacement(rng)
};
target.p = restrict_position(target.p + dv, sys.bc);
bool collides = false;
for(size_t j=0; j<num_disks; ++j)
{
if(j == idx){continue;}
if(rigid_disk::overlaps(target, sys.disks[j], sys.bc))
{
collides = true;
break;
}
}
if(!collides)
{
sys.disks[idx] = target;
}
}
}
rigid_disk::print_system(sys);
return 0;
}
| 26.962963 | 73 | 0.510646 | [
"vector"
] |
a3a91f1443e378fa9f8852cfff02ae7775dcbb40 | 5,443 | cpp | C++ | be/src/http/web_page_handler.cpp | mengqinghuan/Doris | c0cccb27c966821f630400ad8d19f49a59bc582c | [
"Apache-2.0"
] | 1 | 2017-08-10T13:14:50.000Z | 2017-08-10T13:14:50.000Z | be/src/http/web_page_handler.cpp | rinack/palo | fb64a1a8e8ed612cd95d1ea0c67bf70804a1d2da | [
"Apache-2.0"
] | null | null | null | be/src/http/web_page_handler.cpp | rinack/palo | fb64a1a8e8ed612cd95d1ea0c67bf70804a1d2da | [
"Apache-2.0"
] | 1 | 2021-07-21T03:05:40.000Z | 2021-07-21T03:05:40.000Z | // Copyright (c) 2017, Baidu.com, Inc. All Rights Reserved
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "http/web_page_handler.h"
#include <boost/bind.hpp>
#include <boost/mem_fn.hpp>
#include "http/http_status.h"
#include "http/http_request.h"
#include "http/http_response.h"
#include "http/http_channel.h"
#include "http/webserver.h"
#include "util/debug_util.h"
#include "util/cpu_info.h"
#include "util/disk_info.h"
#include "util/mem_info.h"
namespace palo {
static std::string s_html_content_type = "text/html";
WebPageHandler::WebPageHandler(Webserver* web) :
_web_server(web) {
PageHandlerCallback default_callback =
boost::bind<void>(boost::mem_fn(&WebPageHandler::root_handler), this, _1, _2);
register_page("/", default_callback);
}
void WebPageHandler::register_page(
const std::string& path,
const PageHandlerCallback& callback) {
// Put this handler to to s_handler_by_name
// because handler does't often new
// So we insert it to this set when everytime
boost::mutex::scoped_lock lock(_map_lock);
auto map_iter = _page_map.find(path);
if (map_iter == _page_map.end()) {
// first time, register this to web server
_web_server->register_handler(HttpMethod::GET, path, this);
}
_page_map[path].add_callback(callback);
}
void WebPageHandler::handle(HttpRequest *req, HttpChannel *channel) {
// Should we render with css styles?
bool use_style = true;
std::map<std::string, std::string>& params = *req->params();
if (params.find("raw") != params.end()) {
use_style = false;
}
std::stringstream output;
// Append header
if (use_style) {
bootstrap_page_header(&output);
}
// Append content
// push_content(&output);
LOG(INFO) << req->debug_string();
{
boost::mutex::scoped_lock lock(_map_lock);
auto iter = _page_map.find(req->raw_path());
if (iter != _page_map.end()) {
for (auto& callback : iter->second.callbacks()) {
callback(*req->params(), &output);
}
}
}
// Append footer
if (use_style) {
bootstrap_page_footer(&output);
}
std::string str = output.str();
HttpResponse response(HttpStatus::OK, s_html_content_type, &str);
channel->send_response(response);
}
static const std::string PAGE_HEADER =
"<!DOCTYPE html>"
" <html>"
" <head><title>Palo</title>"
" <link href='www/bootstrap/css/bootstrap.min.css' rel='stylesheet' media='screen'>"
" <style>"
" body {"
" padding-top: 60px; "
" }"
" </style>"
" </head>"
" <body>";
static const std::string PAGE_FOOTER = "</div></body></html>";
static const std::string NAVIGATION_BAR_PREFIX =
"<div class='navbar navbar-inverse navbar-fixed-top'>"
" <div class='navbar-inner'>"
" <div class='container'>"
" <a class='btn btn-navbar' data-toggle='collapse' data-target='.nav-collapse'>"
" <span class='icon-bar'></span>"
" <span class='icon-bar'></span>"
" <span class='icon-bar'></span>"
" </a>"
" <a class='brand' href='/'>Impala</a>"
" <div class='nav-collapse collapse'>"
" <ul class='nav'>";
static const std::string NAVIGATION_BAR_SUFFIX =
" </ul>"
" </div>"
" </div>"
" </div>"
" </div>"
" <div class='container'>";
void WebPageHandler::bootstrap_page_header(std::stringstream* output) {
boost::mutex::scoped_lock lock(_map_lock);
(*output) << PAGE_HEADER;
(*output) << NAVIGATION_BAR_PREFIX;
for (auto& iter : _page_map) {
(*output) << "<li><a href=\"" << iter.first << "\">" << iter.first
<< "</a></li>";
}
(*output) << NAVIGATION_BAR_SUFFIX;
}
void WebPageHandler::bootstrap_page_footer(std::stringstream* output) {
(*output) << PAGE_FOOTER;
}
void WebPageHandler::root_handler(
const ArgumentMap& args,
std::stringstream* output) {
// _path_handler_lock already held by MongooseCallback
(*output) << "<h2>Version</h2>";
(*output) << "<pre>" << get_version_string(false) << "</pre>" << std::endl;
(*output) << "<h2>Hardware Info</h2>";
(*output) << "<pre>";
(*output) << CpuInfo::debug_string();
(*output) << MemInfo::debug_string();
(*output) << DiskInfo::debug_string();
(*output) << "</pre>";
(*output) << "<h2>Status Pages</h2>";
for (auto& iter : _page_map) {
(*output) << "<a href=\"" << iter.first << "\">" << iter.first << "</a><br/>";
}
}
}
| 32.207101 | 93 | 0.615653 | [
"render"
] |
a3af215272f2732599ee7950d7112b84e389e1ef | 34,302 | cpp | C++ | tests/Aql/EngineInfoContainerCoordinatorTest.cpp | corona3000/arangodb | e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da | [
"Apache-2.0"
] | null | null | null | tests/Aql/EngineInfoContainerCoordinatorTest.cpp | corona3000/arangodb | e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da | [
"Apache-2.0"
] | null | null | null | tests/Aql/EngineInfoContainerCoordinatorTest.cpp | corona3000/arangodb | e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// @brief test case for EngineInfoContainerCoordinator
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2017 ArangoDB GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Michael Hackstein
/// @author Copyright 2017, ArangoDB GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#include "gtest/gtest.h"
#include "fakeit.hpp"
#include "Aql/AqlItemBlock.h"
#include "Aql/AqlResult.h"
#include "Aql/EngineInfoContainerCoordinator.h"
#include "Aql/ExecutionBlock.h"
#include "Aql/ExecutionEngine.h"
#include "Aql/ExecutionNode.h"
#include "Aql/Query.h"
#include "Aql/QueryRegistry.h"
#include "Cluster/RebootTracker.h"
#include "Transaction/Methods.h"
using namespace arangodb;
using namespace arangodb::aql;
namespace arangodb {
namespace tests {
namespace engine_info_container_coordinator_test {
TEST(EngineInfoContainerTest, it_should_always_start_with_an_open_snippet) {
EngineInfoContainerCoordinator testee;
QueryId res = testee.closeSnippet();
ASSERT_EQ(res, 0);
}
TEST(EngineInfoContainerTest, it_should_be_able_to_add_more_snippets) {
EngineInfoContainerCoordinator testee;
size_t remote = 1;
testee.openSnippet(remote);
testee.openSnippet(remote);
QueryId res1 = testee.closeSnippet();
ASSERT_NE(res1, 0);
QueryId res2 = testee.closeSnippet();
ASSERT_NE(res2, res1);
ASSERT_NE(res2, 0);
QueryId res3 = testee.closeSnippet();
ASSERT_EQ(res3, 0);
}
///////////////////////////////////////////
// SECTION buildEngines
///////////////////////////////////////////
// Flow:
// 1. Clone the query for every snippet but the first
// 2. For every snippet:
// 1. create new Engine (e)
// 2. query->setEngine(e)
// 3. query->engine() -> e
// 5. engine->createBlocks()
// 6. Assert (engine->root() != nullptr)
// 7. For all but the first:
// 1. queryRegistry->insert(_id, query, 600.0);
// 3. query->engine();
TEST(EngineInfoContainerTest, it_should_create_an_executionengine_for_the_first_snippet) {
std::unordered_set<std::string> const restrictToShards;
MapRemoteToSnippet queryIds;
std::string const dbname = "TestDB";
// ------------------------------
// Section: Create Mock Instances
// ------------------------------
fakeit::Mock<ExecutionNode> singletonMock;
ExecutionNode& sNode = singletonMock.get();
fakeit::When(Method(singletonMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
fakeit::Mock<ExecutionEngine> mockEngine;
ExecutionEngine& myEngine = mockEngine.get();
fakeit::Mock<ExecutionBlock> rootBlockMock;
ExecutionBlock& rootBlock = rootBlockMock.get();
fakeit::Mock<Query> mockQuery;
Query& query = mockQuery.get();
fakeit::Mock<QueryRegistry> mockRegistry;
fakeit::When(Method(mockRegistry, defaultTTL)).AlwaysReturn(600.0);
QueryRegistry& registry = mockRegistry.get();
fakeit::Mock<transaction::Methods> mockTrx;
transaction::Methods& trx = mockTrx.get();
// ------------------------------
// Section: Mock Functions
// ------------------------------
fakeit::When(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine * ))).Do(
[](ExecutionEngine *eng) -> void {
// We expect that the snippet injects a new engine into our
// query.
// However we have to return a mocked engine later
ASSERT_NE(eng, nullptr);
// Throw it away
delete eng;
}
);
fakeit::When(Method(mockQuery, trx)).Return(&trx);
fakeit::When(Method(mockQuery, engine)).Return(&myEngine).Return(&myEngine);
fakeit::When(Method(mockEngine, createBlocks)).Return(Result{TRI_ERROR_NO_ERROR});
fakeit::When(ConstOverloadedMethod(mockEngine, root, ExecutionBlock * ())).AlwaysReturn(&rootBlock);
// ------------------------------
// Section: Run the test
// ------------------------------
EngineInfoContainerCoordinator testee;
testee.addNode(&sNode);
std::vector<uint64_t> coordinatorQueryIds{};
ExecutionEngineResult result =
testee.buildEngines(query, ®istry, dbname, restrictToShards, queryIds, coordinatorQueryIds);
ASSERT_TRUE(result.ok());
ExecutionEngine* engine = result.engine();
ASSERT_NE(engine, nullptr);
ASSERT_EQ(engine, &myEngine);
// The last engine should not be stored
// It is not added to the registry
ASSERT_TRUE(queryIds.empty());
// Validate that the query is wired up with the engine
fakeit::Verify(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine *))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockEngine, createBlocks)).Exactly(1);
}
TEST(EngineInfoContainerTest,
it_should_create_a_new_engine_and_register_it_for_the_second_snippet) {
std::unordered_set<std::string> const restrictToShards;
MapRemoteToSnippet queryIds;
size_t remoteId = 1337;
QueryId secondId = 0;
std::string dbname = "TestDB";
// ------------------------------
// Section: Create Mock Instances
// ------------------------------
fakeit::Mock<ExecutionNode> firstNodeMock;
ExecutionNode& fNode = firstNodeMock.get();
fakeit::When(Method(firstNodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
fakeit::Mock<ExecutionNode> secondNodeMock;
ExecutionNode& sNode = secondNodeMock.get();
fakeit::When(Method(secondNodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
// We need a block only for assertion
fakeit::Mock<ExecutionBlock> blockMock;
ExecutionBlock& block = blockMock.get();
// Mock engine for first snippet
fakeit::Mock<ExecutionEngine> mockEngine;
ExecutionEngine& myEngine = mockEngine.get();
// Mock engine for second snippet
fakeit::Mock<ExecutionEngine> mockSecondEngine;
ExecutionEngine& mySecondEngine = mockSecondEngine.get();
fakeit::Mock<QueryRegistry> mockRegistry;
fakeit::When(Method(mockRegistry, defaultTTL)).AlwaysReturn(600.0);
QueryRegistry& registry = mockRegistry.get();
fakeit::Mock<QueryOptions> mockQueryOptions;
QueryOptions& lqueryOptions = mockQueryOptions.get();
lqueryOptions.ttl = 600;
fakeit::Mock<Query> mockQuery;
Query& query = mockQuery.get();
fakeit::When(ConstOverloadedMethod(mockQuery, queryOptions, QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQuery, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
fakeit::Mock<Query> mockQueryClone;
Query& queryClone = mockQueryClone.get();
fakeit::When(ConstOverloadedMethod(mockQueryClone, queryOptions, QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQueryClone, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
fakeit::Mock<transaction::Methods> mockTrx;
transaction::Methods& trx = mockTrx.get();
fakeit::Mock<transaction::Methods> mockSecondTrx;
transaction::Methods& secondTrx = mockSecondTrx.get();
// ------------------------------
// Section: Mock Functions
// ------------------------------
fakeit::When(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine*))).Do([&](ExecutionEngine* eng) -> void {
// We expect that the snippet injects a new engine into our
// query.
// However we have to return a mocked engine later
ASSERT_NE(eng, nullptr);
// Throw it away
delete eng;
});
fakeit::When(Method(mockQuery, trx)).Return(&trx);
fakeit::When(Method(mockQuery, engine)).Return(&myEngine).Return(&myEngine);
fakeit::When(Method(mockEngine, createBlocks))
.Do([&](std::vector<ExecutionNode*> const& nodes,
std::unordered_set<std::string> const&, MapRemoteToSnippet const&) {
EXPECT_EQ(nodes.size(), 1);
EXPECT_EQ(nodes[0], &fNode);
return Result{TRI_ERROR_NO_ERROR};
});
fakeit::When(ConstOverloadedMethod(mockEngine, root, ExecutionBlock * ())).AlwaysReturn(&block);
// Mock query clone
fakeit::When(Method(mockQuery, clone)).Do([&](QueryPart part, bool withPlan) -> Query* {
EXPECT_EQ(part, PART_DEPENDENT);
EXPECT_FALSE(withPlan);
return &queryClone;
});
fakeit::When(OverloadedMethod(mockQueryClone, setEngine, void(ExecutionEngine * ))).Do(
[&](ExecutionEngine *eng) -> void {
// We expect that the snippet injects a new engine into our
// query.
// However we have to return a mocked engine later
ASSERT_NE(eng, nullptr);
// Throw it away
delete eng;
});
fakeit::When(Method(mockQueryClone, trx)).Return(&secondTrx);
fakeit::When(Method(mockQueryClone, engine)).Return(&mySecondEngine);
fakeit::When(Method(mockSecondEngine, createBlocks))
.Do([&](std::vector<ExecutionNode*> const& nodes,
std::unordered_set<std::string> const&, MapRemoteToSnippet const&) {
EXPECT_EQ(nodes.size(), 1);
EXPECT_EQ(nodes[0], &sNode);
return Result{TRI_ERROR_NO_ERROR};
});
fakeit::When(ConstOverloadedMethod(mockSecondEngine, root, ExecutionBlock * ()))
.AlwaysReturn(&block);
// Mock the Registry
fakeit::When(Method(mockRegistry, insert))
.Do([&](QueryId id, Query* query, double timeout, bool isPrepared, bool keepLease,
std::unique_ptr<arangodb::cluster::CallbackGuard>&) {
ASSERT_NE(id, 0);
ASSERT_NE(query, nullptr);
ASSERT_TRUE(isPrepared);
ASSERT_FALSE(keepLease);
ASSERT_EQ(timeout, 600.0);
ASSERT_EQ(query, &queryClone);
secondId = id;
});
// ------------------------------
// Section: Run the test
// ------------------------------
EngineInfoContainerCoordinator testee;
testee.addNode(&fNode);
// Open the Second Snippet
testee.openSnippet(remoteId);
// Inject a node
testee.addNode(&sNode);
// Close the second snippet
testee.closeSnippet();
std::vector<uint64_t> coordinatorQueryIds{};
ExecutionEngineResult result =
testee.buildEngines(query, ®istry, dbname, restrictToShards, queryIds, coordinatorQueryIds);
ASSERT_TRUE(result.ok());
ExecutionEngine* engine = result.engine();
ASSERT_NE(engine, nullptr);
ASSERT_EQ(engine, &myEngine);
// The second engine needs a generated id
ASSERT_NE(secondId, 0);
// We do not add anything to the ids
ASSERT_TRUE(queryIds.empty());
// Validate that the query is wired up with the engine
fakeit::Verify(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockEngine, createBlocks)).Exactly(1);
// Validate that the second query is wired up with the second engine
fakeit::Verify(OverloadedMethod(mockQueryClone, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockSecondEngine, createBlocks)).Exactly(1);
fakeit::Verify(Method(mockRegistry, insert)).Exactly(1);
}
TEST(EngineInfoContainerTest, snippets_are_a_stack_insert_node_always_into_top_snippet) {
std::unordered_set<std::string> const restrictToShards;
MapRemoteToSnippet queryIds;
size_t remoteId = 1337;
size_t secondRemoteId = 42;
QueryId secondId = 0;
QueryId thirdId = 0;
std::string dbname = "TestDB";
auto setEngineCallback = [](ExecutionEngine* eng) -> void {
// We expect that the snippet injects a new engine into our
// query.
// However we have to return a mocked engine later
ASSERT_NE(eng, nullptr);
// Throw it away
delete eng;
};
// We test the following:
// Base Snippet insert node
// New Snippet (A)
// Insert Node -> (A)
// Close (A)
// Insert Node -> Base
// New Snippet (B)
// Insert Node -> (B)
// Close (B)
// Insert Node -> Base
// Verfiy on Engines
// ------------------------------
// Section: Create Mock Instances
// ------------------------------
fakeit::Mock<ExecutionNode> firstBaseNodeMock;
ExecutionNode& fbNode = firstBaseNodeMock.get();
fakeit::When(Method(firstBaseNodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
fakeit::Mock<ExecutionNode> snipANodeMock;
ExecutionNode& aNode = snipANodeMock.get();
fakeit::When(Method(snipANodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
fakeit::Mock<ExecutionNode> secondBaseNodeMock;
ExecutionNode& sbNode = secondBaseNodeMock.get();
fakeit::When(Method(secondBaseNodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
fakeit::Mock<ExecutionNode> snipBNodeMock;
ExecutionNode& bNode = snipBNodeMock.get();
fakeit::When(Method(snipBNodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
fakeit::Mock<ExecutionNode> thirdBaseNodeMock;
ExecutionNode& tbNode = thirdBaseNodeMock.get();
fakeit::When(Method(thirdBaseNodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
// We need a block only for assertion
fakeit::Mock<ExecutionBlock> blockMock;
ExecutionBlock& block = blockMock.get();
// Mock engine for first snippet
fakeit::Mock<ExecutionEngine> mockEngine;
ExecutionEngine& myEngine = mockEngine.get();
// Mock engine for second snippet
fakeit::Mock<ExecutionEngine> mockSecondEngine;
ExecutionEngine& mySecondEngine = mockSecondEngine.get();
// Mock engine for second snippet
fakeit::Mock<ExecutionEngine> mockThirdEngine;
ExecutionEngine& myThirdEngine = mockThirdEngine.get();
fakeit::Mock<QueryOptions> mockQueryOptions;
QueryOptions& lqueryOptions = mockQueryOptions.get();
lqueryOptions.ttl = 600;
fakeit::Mock<Query> mockQuery;
Query& query = mockQuery.get();
fakeit::When(ConstOverloadedMethod(mockQuery, queryOptions, QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQuery, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
// We need two query clones
fakeit::Mock<Query> mockQueryClone;
Query& queryClone = mockQueryClone.get();
fakeit::When(ConstOverloadedMethod(mockQueryClone, queryOptions, QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQueryClone, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
fakeit::Mock<Query> mockQuerySecondClone;
Query& querySecondClone = mockQuerySecondClone.get();
fakeit::When(ConstOverloadedMethod(mockQuerySecondClone, queryOptions,
QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQuerySecondClone, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
fakeit::Mock<QueryRegistry> mockRegistry;
fakeit::When(Method(mockRegistry, defaultTTL)).AlwaysReturn(600.0);
QueryRegistry& registry = mockRegistry.get();
fakeit::Mock<transaction::Methods> mockTrx;
transaction::Methods& trx = mockTrx.get();
fakeit::Mock<transaction::Methods> mockSecondTrx;
transaction::Methods& secondTrx = mockSecondTrx.get();
fakeit::Mock<transaction::Methods> mockThirdTrx;
transaction::Methods& thirdTrx = mockThirdTrx.get();
// ------------------------------
// Section: Mock Functions
// ------------------------------
fakeit::When(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine*))).Do(setEngineCallback);
fakeit::When(Method(mockQuery, trx)).Return(&trx);
fakeit::When(Method(mockQuery, engine)).Return(&myEngine).Return(&myEngine);
fakeit::When(Method(mockEngine, createBlocks))
.Do([&](std::vector<ExecutionNode*> const& nodes,
std::unordered_set<std::string> const&, MapRemoteToSnippet const&) {
EXPECT_EQ(nodes.size(), 3);
EXPECT_EQ(nodes[0], &fbNode);
EXPECT_EQ(nodes[1], &sbNode);
EXPECT_EQ(nodes[2], &tbNode);
return Result{TRI_ERROR_NO_ERROR};
});
fakeit::When(ConstOverloadedMethod(mockEngine, root, ExecutionBlock * ())).AlwaysReturn(&block);
fakeit::When(Method(mockQuery, clone))
.Do([&](QueryPart part, bool withPlan) -> Query* {
EXPECT_EQ(part, PART_DEPENDENT);
EXPECT_FALSE(withPlan);
return &queryClone;
})
.Do([&](QueryPart part, bool withPlan) -> Query* {
EXPECT_EQ(part, PART_DEPENDENT);
EXPECT_FALSE(withPlan);
return &querySecondClone;
});
// Mock first clone
fakeit::When(OverloadedMethod(mockQueryClone, setEngine, void(ExecutionEngine*))).Do(setEngineCallback);
fakeit::When(Method(mockQueryClone, engine)).Return(&mySecondEngine);
fakeit::When(Method(mockQueryClone, trx)).Return(&secondTrx);
fakeit::When(Method(mockSecondEngine, createBlocks))
.Do([&](std::vector<ExecutionNode*> const& nodes,
std::unordered_set<std::string> const&, MapRemoteToSnippet const&) {
EXPECT_EQ(nodes.size(), 1);
EXPECT_EQ(nodes[0], &aNode);
return Result{TRI_ERROR_NO_ERROR};
});
fakeit::When(ConstOverloadedMethod(mockSecondEngine, root, ExecutionBlock * ()))
.AlwaysReturn(&block);
// Mock second clone
fakeit::When(OverloadedMethod(mockQuerySecondClone, setEngine, void(ExecutionEngine*))).Do(setEngineCallback);
fakeit::When(Method(mockQuerySecondClone, engine)).Return(&myThirdEngine);
fakeit::When(Method(mockQuerySecondClone, trx)).Return(&thirdTrx);
fakeit::When(Method(mockThirdEngine, createBlocks))
.Do([&](std::vector<ExecutionNode*> const& nodes,
std::unordered_set<std::string> const&, MapRemoteToSnippet const&) {
EXPECT_EQ(nodes.size(), 1);
EXPECT_EQ(nodes[0], &bNode);
return Result{TRI_ERROR_NO_ERROR};
});
fakeit::When(ConstOverloadedMethod(mockThirdEngine, root, ExecutionBlock * ()))
.AlwaysReturn(&block);
// Mock the Registry
// NOTE: This expects an ordering of the engines first of the stack will be
// handled first. With same fakeit magic we could make this ordering
// independent which is is fine as well for the production code.
fakeit::When(Method(mockRegistry, insert))
.Do([&](QueryId id, Query* query, double timeout, bool isPrepared, bool keepLease,
std::unique_ptr<arangodb::cluster::CallbackGuard>&) {
ASSERT_NE(id, 0);
ASSERT_NE(query, nullptr);
ASSERT_TRUE(isPrepared);
ASSERT_FALSE(keepLease);
ASSERT_EQ(timeout, 600.0);
ASSERT_EQ(query, &queryClone);
secondId = id;
})
.Do([&](QueryId id, Query* query, double timeout, bool isPrepared, bool keepLease,
std::unique_ptr<arangodb::cluster::CallbackGuard>&) {
ASSERT_NE(id, 0);
ASSERT_NE(query, nullptr);
ASSERT_EQ(timeout, 600.0);
ASSERT_FALSE(keepLease);
ASSERT_EQ(query, &querySecondClone);
thirdId = id;
});
// ------------------------------
// Section: Run the test
// ------------------------------
EngineInfoContainerCoordinator testee;
testee.addNode(&fbNode);
testee.openSnippet(remoteId);
testee.addNode(&aNode);
testee.closeSnippet();
testee.addNode(&sbNode);
testee.openSnippet(secondRemoteId);
testee.addNode(&bNode);
testee.closeSnippet();
testee.addNode(&tbNode);
std::vector<uint64_t> coordinatorQueryIds{};
ExecutionEngineResult result =
testee.buildEngines(query, ®istry, dbname, restrictToShards, queryIds, coordinatorQueryIds);
ASSERT_TRUE(result.ok());
ExecutionEngine* engine = result.engine();
ASSERT_NE(engine, nullptr);
ASSERT_EQ(engine, &myEngine);
// We do not add anything to the ids
ASSERT_TRUE(queryIds.empty());
// Validate that the query is wired up with the engine
fakeit::Verify(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockEngine, createBlocks)).Exactly(1);
// Validate that the second query is wired up with the second engine
fakeit::Verify(OverloadedMethod(mockQueryClone, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockSecondEngine, createBlocks)).Exactly(1);
// Validate that the second query is wired up with the second engine
fakeit::Verify(OverloadedMethod(mockQuerySecondClone, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockThirdEngine, createBlocks)).Exactly(1);
// Validate two queries are registered correctly
fakeit::Verify(Method(mockRegistry, insert)).Exactly(2);
}
TEST(EngineInfoContainerTest, error_cases_cloning_of_a_query_fails_throws_an_error) {
std::unordered_set<std::string> const restrictToShards;
MapRemoteToSnippet queryIds;
size_t remoteId = 1337;
QueryId secondId = 0;
std::string dbname = "TestDB";
// ------------------------------
// Section: Create Mock Instances
// ------------------------------
fakeit::Mock<ExecutionNode> firstNodeMock;
ExecutionNode& fNode = firstNodeMock.get();
fakeit::When(Method(firstNodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
// We need a block only for assertion
fakeit::Mock<ExecutionBlock> blockMock;
ExecutionBlock& block = blockMock.get();
// Mock engine for first snippet
fakeit::Mock<ExecutionEngine> mockEngine;
ExecutionEngine& myEngine = mockEngine.get();
// Mock engine for second snippet
fakeit::Mock<ExecutionEngine> mockSecondEngine;
ExecutionEngine& mySecondEngine = mockSecondEngine.get();
fakeit::Mock<QueryOptions> mockQueryOptions;
QueryOptions& lqueryOptions = mockQueryOptions.get();
lqueryOptions.ttl = 600;
fakeit::Mock<Query> mockQuery;
Query& query = mockQuery.get();
fakeit::When(ConstOverloadedMethod(mockQuery, queryOptions, QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQuery, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
fakeit::Mock<Query> mockQueryClone;
Query& queryClone = mockQueryClone.get();
fakeit::When(ConstOverloadedMethod(mockQueryClone, queryOptions, QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQueryClone, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
fakeit::Mock<QueryRegistry> mockRegistry;
fakeit::When(Method(mockRegistry, defaultTTL)).AlwaysReturn(600.0);
QueryRegistry& registry = mockRegistry.get();
fakeit::Mock<transaction::Methods> mockTrx;
transaction::Methods& trx = mockTrx.get();
fakeit::Mock<transaction::Methods> mockSecondTrx;
transaction::Methods& secondTrx = mockSecondTrx.get();
// ------------------------------
// Section: Mock Functions
// ------------------------------
fakeit::When(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine*))).Do([&](ExecutionEngine* eng) -> void {
// We expect that the snippet injects a new engine into our
// query.
// However we have to return a mocked engine later
ASSERT_NE(eng, nullptr);
// Throw it away
delete eng;
});
fakeit::When(Method(mockQuery, engine)).Return(&myEngine).Return(&myEngine);
fakeit::When(Method(mockQuery, trx)).Return(&trx);
fakeit::When(Method(mockEngine, createBlocks)).AlwaysReturn(Result{TRI_ERROR_NO_ERROR});
fakeit::When(ConstOverloadedMethod(mockEngine, root, ExecutionBlock * ())).AlwaysReturn(&block);
fakeit::When(OverloadedMethod(mockQueryClone, setEngine, void(ExecutionEngine*))).Do([&](ExecutionEngine* eng) -> void {
// We expect that the snippet injects a new engine into our
// query.
// However we have to return a mocked engine later
ASSERT_NE(eng, nullptr);
// Throw it away
delete eng;
});
fakeit::When(Method(mockQueryClone, engine)).Return(&mySecondEngine);
fakeit::When(Method(mockQueryClone, trx)).Return(&secondTrx);
fakeit::When(Method(mockSecondEngine, createBlocks)).AlwaysReturn(Result{TRI_ERROR_NO_ERROR});
fakeit::When(ConstOverloadedMethod(mockSecondEngine, root, ExecutionBlock * ()))
.AlwaysReturn(&block);
fakeit::When(OverloadedMethod(mockRegistry, destroy,
void(std::string const&, QueryId, int, bool)))
.Do([&](std::string const& vocbase, QueryId id, int errorCode, bool ignoreOpened) {
ASSERT_EQ(vocbase, dbname);
ASSERT_EQ(id, secondId);
ASSERT_EQ(errorCode, TRI_ERROR_INTERNAL);
});
// ------------------------------
// Section: Run the test
// ------------------------------
EngineInfoContainerCoordinator testee;
testee.addNode(&fNode);
// Open the Second Snippet
testee.openSnippet(remoteId);
// Inject a node
testee.addNode(&fNode);
testee.openSnippet(remoteId);
// Inject a node
testee.addNode(&fNode);
// Close the third snippet
testee.closeSnippet();
// Close the second snippet
testee.closeSnippet();
// Mock the Registry
fakeit::When(Method(mockRegistry, insert))
.Do([&](QueryId id, Query* query, double timeout, bool isPrepared, bool keepLease,
std::unique_ptr<arangodb::cluster::CallbackGuard>&) {
ASSERT_NE(id, 0);
ASSERT_NE(query, nullptr);
ASSERT_EQ(timeout, 600.0);
ASSERT_TRUE(isPrepared);
ASSERT_FALSE(keepLease);
ASSERT_EQ(query, &queryClone);
secondId = id;
});
// Mock query clone
fakeit::When(Method(mockQuery, clone))
.Do([&](QueryPart part, bool withPlan) -> Query* {
EXPECT_EQ(part, PART_DEPENDENT);
EXPECT_FALSE(withPlan);
return &queryClone;
})
.Throw(arangodb::basics::Exception(TRI_ERROR_DEBUG, __FILE__, __LINE__));
std::vector<uint64_t> coordinatorQueryIds{};
ExecutionEngineResult result =
testee.buildEngines(query, ®istry, dbname, restrictToShards, queryIds, coordinatorQueryIds);
ASSERT_FALSE(result.ok());
// Make sure we check the right thing here
ASSERT_EQ(result.errorNumber(), TRI_ERROR_DEBUG);
// Validate that the path up to intended error was taken
// Validate that the query is wired up with the engine
fakeit::Verify(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockEngine, createBlocks)).Exactly(1);
// Validate that the second query is wired up with the second engine
fakeit::Verify(OverloadedMethod(mockQueryClone, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockSecondEngine, createBlocks)).Exactly(1);
fakeit::Verify(Method(mockRegistry, insert)).Exactly(1);
// Assert unregister of second engine.
fakeit::Verify(OverloadedMethod(mockRegistry, destroy,
void(std::string const&, QueryId, int, bool)))
.Exactly(1);
}
TEST(EngineInfoContainerTest, error_cases_cloning_of_a_query_fails_returns_a_nullptr) {
std::unordered_set<std::string> const restrictToShards;
MapRemoteToSnippet queryIds;
size_t remoteId = 1337;
QueryId secondId = 0;
std::string dbname = "TestDB";
// ------------------------------
// Section: Create Mock Instances
// ------------------------------
fakeit::Mock<ExecutionNode> firstNodeMock;
ExecutionNode& fNode = firstNodeMock.get();
fakeit::When(Method(firstNodeMock, getType)).AlwaysReturn(ExecutionNode::SINGLETON);
// We need a block only for assertion
fakeit::Mock<ExecutionBlock> blockMock;
ExecutionBlock& block = blockMock.get();
// Mock engine for first snippet
fakeit::Mock<ExecutionEngine> mockEngine;
ExecutionEngine& myEngine = mockEngine.get();
// Mock engine for second snippet
fakeit::Mock<ExecutionEngine> mockSecondEngine;
ExecutionEngine& mySecondEngine = mockSecondEngine.get();
fakeit::Mock<QueryOptions> mockQueryOptions;
QueryOptions& lqueryOptions = mockQueryOptions.get();
lqueryOptions.ttl = 600;
fakeit::Mock<Query> mockQuery;
Query& query = mockQuery.get();
fakeit::When(ConstOverloadedMethod(mockQuery, queryOptions, QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQuery, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
fakeit::Mock<Query> mockQueryClone;
Query& queryClone = mockQueryClone.get();
fakeit::When(ConstOverloadedMethod(mockQueryClone, queryOptions, QueryOptions const&()))
.AlwaysDo([&]() -> QueryOptions const& { return lqueryOptions; });
fakeit::When(OverloadedMethod(mockQueryClone, queryOptions, QueryOptions & ()))
.AlwaysDo([&]() -> QueryOptions& { return lqueryOptions; });
fakeit::Mock<QueryRegistry> mockRegistry;
fakeit::When(Method(mockRegistry, defaultTTL)).AlwaysReturn(600.0);
QueryRegistry& registry = mockRegistry.get();
fakeit::Mock<transaction::Methods> mockTrx;
transaction::Methods& trx = mockTrx.get();
fakeit::Mock<transaction::Methods> mockSecondTrx;
transaction::Methods& secondTrx = mockSecondTrx.get();
// ------------------------------
// Section: Mock Functions
// ------------------------------
fakeit::When(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine*))).Do([&](ExecutionEngine* eng) -> void {
// We expect that the snippet injects a new engine into our
// query.
// However we have to return a mocked engine later
ASSERT_NE(eng, nullptr);
// Throw it away
delete eng;
});
fakeit::When(Method(mockQuery, engine)).Return(&myEngine).Return(&myEngine);
fakeit::When(Method(mockQuery, trx)).Return(&trx);
fakeit::When(Method(mockEngine, createBlocks)).AlwaysReturn(Result{TRI_ERROR_NO_ERROR});
fakeit::When(ConstOverloadedMethod(mockEngine, root, ExecutionBlock * ())).AlwaysReturn(&block);
fakeit::When(OverloadedMethod(mockQueryClone, setEngine, void(ExecutionEngine*))).Do([&](ExecutionEngine* eng) -> void {
// We expect that the snippet injects a new engine into our
// query.
// However we have to return a mocked engine later
ASSERT_NE(eng, nullptr);
// Throw it away
delete eng;
});
fakeit::When(Method(mockQueryClone, engine)).Return(&mySecondEngine);
fakeit::When(Method(mockQueryClone, trx)).Return(&secondTrx);
fakeit::When(Method(mockSecondEngine, createBlocks)).AlwaysReturn(Result{TRI_ERROR_NO_ERROR});
fakeit::When(ConstOverloadedMethod(mockSecondEngine, root, ExecutionBlock * ()))
.AlwaysReturn(&block);
fakeit::When(OverloadedMethod(mockRegistry, destroy,
void(std::string const&, QueryId, int, bool)))
.Do([&](std::string const& vocbase, QueryId id, int errorCode, bool ignoreOpened) {
ASSERT_EQ(vocbase, dbname);
ASSERT_EQ(id, secondId);
ASSERT_EQ(errorCode, TRI_ERROR_INTERNAL);
});
// ------------------------------
// Section: Run the test
// ------------------------------
EngineInfoContainerCoordinator testee;
testee.addNode(&fNode);
// Open the Second Snippet
testee.openSnippet(remoteId);
// Inject a node
testee.addNode(&fNode);
testee.openSnippet(remoteId);
// Inject a node
testee.addNode(&fNode);
// Close the third snippet
testee.closeSnippet();
// Close the second snippet
testee.closeSnippet();
// Mock the Registry
fakeit::When(Method(mockRegistry, insert))
.Do([&](QueryId id, Query* query, double timeout, bool isPrepared, bool keepLease,
std::unique_ptr<arangodb::cluster::CallbackGuard>&) {
ASSERT_NE(id, 0);
ASSERT_NE(query, nullptr);
ASSERT_EQ(timeout, 600.0);
ASSERT_TRUE(isPrepared);
ASSERT_FALSE(keepLease);
ASSERT_EQ(query, &queryClone);
secondId = id;
});
// Mock query clone
fakeit::When(Method(mockQuery, clone))
.Do([&](QueryPart part, bool withPlan) -> Query* {
EXPECT_EQ(part, PART_DEPENDENT);
EXPECT_FALSE(withPlan);
return &queryClone;
})
.Do([&](QueryPart part, bool withPlan) -> Query* {
EXPECT_EQ(part, PART_DEPENDENT);
EXPECT_FALSE(withPlan);
return nullptr;
});
std::vector<uint64_t> coordinatorQueryIds{};
ExecutionEngineResult result =
testee.buildEngines(query, ®istry, dbname, restrictToShards, queryIds, coordinatorQueryIds);
ASSERT_FALSE(result.ok());
// Make sure we check the right thing here
ASSERT_EQ(result.errorNumber(), TRI_ERROR_INTERNAL);
// Validate that the path up to intended error was taken
// Validate that the query is wired up with the engine
fakeit::Verify(OverloadedMethod(mockQuery, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockEngine, createBlocks)).Exactly(1);
// Validate that the second query is wired up with the second engine
fakeit::Verify(OverloadedMethod(mockQueryClone, setEngine, void(ExecutionEngine*))).Exactly(1);
// Validate that createBlocks has been called!
fakeit::Verify(Method(mockSecondEngine, createBlocks)).Exactly(1);
fakeit::Verify(Method(mockRegistry, insert)).Exactly(1);
// Assert unregister of second engine.
fakeit::Verify(OverloadedMethod(mockRegistry, destroy,
void(std::string const&, QueryId, int, bool)))
.Exactly(1);
}
} // namespace engine_info_container_coordinator_test
} // namespace tests
} // namespace arangodb
| 37.653128 | 122 | 0.68515 | [
"vector"
] |
a3b1e5e5dcf1008a019a357426fbe4eb0fb614b5 | 1,454 | hpp | C++ | Bitcoin/sighash.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 108 | 2020-10-01T17:12:40.000Z | 2022-03-30T09:18:03.000Z | Bitcoin/sighash.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 94 | 2020-10-03T13:40:30.000Z | 2022-03-30T09:18:00.000Z | Bitcoin/sighash.hpp | 3nprob/clboss | 0435b6c074347ce82e490a5988534054e9d7348d | [
"MIT"
] | 17 | 2020-10-29T13:27:59.000Z | 2022-03-18T13:05:03.000Z | #ifndef BITCOIN_SIGHASH_HPP
#define BITCOIN_SIGHASH_HPP
#include<cstddef>
#include<cstdint>
#include<stdexcept>
#include<vector>
namespace Bitcoin { class Tx; }
namespace Ln { class Amount; }
namespace Sha256 { class Hash; }
namespace Bitcoin {
enum SighashFlags
{ SIGHASH_ALL = 1
, SIGHASH_NONE = 2
, SIGHASH_SINGLE = 3
, SIGHASH_ANYONECANPAY = 0x80
};
struct InvalidSighash : public std::invalid_argument {
InvalidSighash() =delete;
InvalidSighash(std::string const& msg)
: std::invalid_argument(
std::string("Bitcoin::InvalidSighash: ") + msg
) { }
};
/** Bitcoin::sighash
*
* @brief computes the sighash for the
* given transaction, being signed with
* the given flags, and signing for the
* input nIn.
*
* @desc throws `Bitcoin::InvalidSighash`
* if the given `flags` is not recognized,
* or if `nIn` is out-of-range.
*
* The given `scriptCode` should consider
* `OP_CODESEPERATOR`.
* For P2WPKH it should be the constructed
* script "1976a914{20-byte-pubkey-hash}88ac".
* For P2WSH it should be the `witnessScript`
* whose hash is what is committed in the
* `scriptPubKey`, and which is the top of the
* witness stack.
*
* This is strictly for SegWit sighash
* algorithm.
*/
Sha256::Hash
sighash( Bitcoin::Tx const& tx
, SighashFlags flags
, std::size_t nIn
, Ln::Amount amount
, std::vector<std::uint8_t> const& scriptCode
);
}
#endif /* !defined(BITCOIN_SIGHASH_HPP) */
| 22.71875 | 54 | 0.698762 | [
"vector"
] |
a3b2e3bd73226d781ebcaa6aa7830362068cbee2 | 15,766 | cpp | C++ | lib/Core/Searcher.cpp | sysrel/SIFT | 32a952c9b5bcf576bbd91c6a7510182b6cb94748 | [
"Apache-2.0"
] | null | null | null | lib/Core/Searcher.cpp | sysrel/SIFT | 32a952c9b5bcf576bbd91c6a7510182b6cb94748 | [
"Apache-2.0"
] | null | null | null | lib/Core/Searcher.cpp | sysrel/SIFT | 32a952c9b5bcf576bbd91c6a7510182b6cb94748 | [
"Apache-2.0"
] | null | null | null | //===-- Searcher.cpp ------------------------------------------------------===//
//
// The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Searcher.h"
#include "CoreStats.h"
#include "Executor.h"
#include "PTree.h"
#include "StatsTracker.h"
#include "klee/ExecutionState.h"
#include "klee/MergeHandler.h"
#include "klee/Statistics.h"
#include "klee/Internal/Module/InstructionInfoTable.h"
#include "klee/Internal/Module/KInstruction.h"
#include "klee/Internal/Module/KModule.h"
#include "klee/Internal/ADT/DiscretePDF.h"
#include "klee/Internal/ADT/RNG.h"
#include "klee/Internal/Support/ModuleUtil.h"
#include "klee/Internal/System/Time.h"
#include "klee/Internal/Support/ErrorHandling.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#if LLVM_VERSION_CODE < LLVM_VERSION(3, 5)
#include "llvm/Support/CallSite.h"
#else
#include "llvm/IR/CallSite.h"
#endif
#include <cassert>
#include <fstream>
#include <climits>
using namespace klee;
using namespace llvm;
namespace klee {
extern RNG theRNG;
}
extern bool asyncMode;
Searcher::~Searcher() {
}
///
ExecutionState &DFSSearcher::selectState() {
return *states.back();
}
void DFSSearcher::stashState(ExecutionState *s) {
if (stashedStates.find(s) == stashedStates.end()) {
stashedStates.insert(s);
llvm::errs() << "Stashing state " << s << " \n";
for (auto it = states.begin(); it != states.end(); it++) {
if (*it == s) {
states.erase(it);
break;
}
}
}
}
void DFSSearcher::unstashState(ExecutionState *s) {
bool found = false;
for (auto it = states.begin(); it != states.end(); it++)
if (*it == s) {
found = true; break;
}
if (!found) {
states.push_back(s);
llvm::errs() << "Unstashing state " << s << "\n";
}
if (stashedStates.find(s) != stashedStates.end())
stashedStates.erase(s);
}
void DFSSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
states.insert(states.end(),
addedStates.begin(),
addedStates.end());
for (std::vector<ExecutionState *>::const_iterator it = removedStates.begin(),
ie = removedStates.end();
it != ie; ++it) {
ExecutionState *es = *it;
if (es == states.back()) {
states.pop_back();
} else {
bool ok = false;
for (std::vector<ExecutionState*>::iterator it = states.begin(),
ie = states.end(); it != ie; ++it) {
if (es==*it) {
states.erase(it);
ok = true;
break;
}
}
llvm::errs() << "Problem state = " << es << "\n";
(void) ok;
assert(ok && "invalid state removed");
}
}
}
///
ExecutionState &BFSSearcher::selectState() {
return *states.front();
}
void BFSSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
// Assumption: If new states were added KLEE forked, therefore states evolved.
// constraints were added to the current state, it evolved.
if (!addedStates.empty() && current &&
std::find(removedStates.begin(), removedStates.end(), current) ==
removedStates.end()) {
auto pos = std::find(states.begin(), states.end(), current);
assert(pos != states.end());
states.erase(pos);
states.push_back(current);
}
states.insert(states.end(),
addedStates.begin(),
addedStates.end());
for (std::vector<ExecutionState *>::const_iterator it = removedStates.begin(),
ie = removedStates.end();
it != ie; ++it) {
ExecutionState *es = *it;
if (es == states.front()) {
states.pop_front();
} else {
bool ok = false;
for (std::deque<ExecutionState*>::iterator it = states.begin(),
ie = states.end(); it != ie; ++it) {
if (es==*it) {
states.erase(it);
ok = true;
break;
}
}
(void) ok;
assert(ok && "invalid state removed");
}
}
}
///
ExecutionState &RandomSearcher::selectState() {
return *states[theRNG.getInt32()%states.size()];
}
void
RandomSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
states.insert(states.end(),
addedStates.begin(),
addedStates.end());
for (std::vector<ExecutionState *>::const_iterator it = removedStates.begin(),
ie = removedStates.end();
it != ie; ++it) {
ExecutionState *es = *it;
bool ok = false;
for (std::vector<ExecutionState*>::iterator it = states.begin(),
ie = states.end(); it != ie; ++it) {
if (es==*it) {
states.erase(it);
ok = true;
break;
}
}
assert(ok && "invalid state removed");
}
}
///
WeightedRandomSearcher::WeightedRandomSearcher(WeightType _type)
: states(new DiscretePDF<ExecutionState*>()),
type(_type) {
switch(type) {
case Depth:
updateWeights = false;
break;
case InstCount:
case CPInstCount:
case QueryCost:
case MinDistToUncovered:
case CoveringNew:
case CustomWeight:
updateWeights = true;
break;
default:
assert(0 && "invalid weight type");
}
}
WeightedRandomSearcher::~WeightedRandomSearcher() {
delete states;
}
ExecutionState &WeightedRandomSearcher::selectState() {
return *states->choose(theRNG.getDoubleL());
}
double WeightedRandomSearcher::getWeight(ExecutionState *es) {
switch(type) {
default:
case Depth:
return es->weight;
case CustomWeight: {
if (es->getCustomWeight() > ExecutionState::CustomWeightThreshold)
return es->getCustomWeight();
else return 0;
}
case InstCount: {
/* SYSREL extension */
uint64_t count;
if (!asyncMode || es->rtid < 0) {
if (!es->getWaitingForThreadsToTerminate()) // otherwise pc is not valid
count = theStatisticManager->getIndexedValue(stats::instructions,
es->pc->info->id);
}
else {
if (!es->threadTerminated(es->rtid)) // otherwise pc is not valid
count = theStatisticManager->getIndexedValue(stats::instructions,
es->threads[es->rtid].pc->info->id);
}
/* SYSTEL extension */
double inv = 1. / std::max((uint64_t) 1, count);
return inv * inv;
}
case CPInstCount: {
/* SYSREL extension */
uint64_t count;
if (!asyncMode || es->rtid < 0) {
StackFrame &sf = es->stack.back();
count = sf.callPathNode->statistics.getValue(stats::instructions);
}
else {
StackFrame &sf = es->threads[es->rtid].stack.back();
count = sf.callPathNode->statistics.getValue(stats::instructions);
}
/* SYSREL extension */
double inv = 1. / std::max((uint64_t) 1, count);
return inv;
}
case QueryCost:
return (es->queryCost < .1) ? 1. : 1./es->queryCost;
case CoveringNew:
case MinDistToUncovered: {
/* SYSTEL extension */
uint64_t md2u;
if (!asyncMode || es->rtid < 0) {
llvm::outs() << "main thread es->rtid=" << es->rtid << "\n";
if (!es->getWaitingForThreadsToTerminate()) { // otherwise pc is not valid
md2u = computeMinDistToUncovered(es->pc,
es->stack.back().minDistToUncoveredOnReturn);
}
}
else {
llvm::outs() << "es->rtid=" << es->rtid << "\n";
if (!es->threadTerminated(es->rtid)) { // otherwise pc is not valid
md2u = computeMinDistToUncovered(es->threads[es->rtid].pc,
es->threads[es->rtid].stack.back().minDistToUncoveredOnReturn);
}
}
/* SYSTEL extension */
double invMD2U = 1. / (md2u ? md2u : 10000);
if (type==CoveringNew) {
double invCovNew = 0.;
if (es->instsSinceCovNew)
invCovNew = 1. / std::max(1, (int) es->instsSinceCovNew - 1000);
return (invCovNew * invCovNew + invMD2U * invMD2U);
} else {
return invMD2U * invMD2U;
}
}
}
}
void WeightedRandomSearcher::update(
ExecutionState *current, const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
if (current && updateWeights &&
std::find(removedStates.begin(), removedStates.end(), current) ==
removedStates.end())
states->update(current, getWeight(current));
for (std::vector<ExecutionState *>::const_iterator it = addedStates.begin(),
ie = addedStates.end();
it != ie; ++it) {
ExecutionState *es = *it;
states->insert(es, getWeight(es));
}
for (std::vector<ExecutionState *>::const_iterator it = removedStates.begin(),
ie = removedStates.end();
it != ie; ++it) {
states->remove(*it);
}
}
bool WeightedRandomSearcher::empty() {
return states->empty();
}
///
RandomPathSearcher::RandomPathSearcher(Executor &_executor)
: executor(_executor) {
}
RandomPathSearcher::~RandomPathSearcher() {
}
ExecutionState &RandomPathSearcher::selectState() {
unsigned flips=0, bits=0;
PTree::Node *n = executor.processTree->root;
while (!n->data) {
if (!n->left) {
n = n->right;
} else if (!n->right) {
n = n->left;
} else {
if (bits==0) {
flips = theRNG.getInt32();
bits = 32;
}
--bits;
n = (flips&(1<<bits)) ? n->left : n->right;
}
}
return *n->data;
}
void
RandomPathSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
}
bool RandomPathSearcher::empty() {
return executor.states.empty();
}
///
MergingSearcher::MergingSearcher(Executor &_executor, Searcher *_baseSearcher)
: executor(_executor),
baseSearcher(_baseSearcher){}
MergingSearcher::~MergingSearcher() {
delete baseSearcher;
}
ExecutionState& MergingSearcher::selectState() {
assert(!baseSearcher->empty() && "base searcher is empty");
// Iterate through all MergeHandlers
for (auto cur_mergehandler: executor.mergeGroups) {
// Find one that has states that could be released
if (!cur_mergehandler->hasMergedStates()) {
continue;
}
// Find a state that can be prioritized
ExecutionState *es = cur_mergehandler->getPrioritizeState();
if (es) {
return *es;
} else {
if (DebugLogIncompleteMerge){
llvm::errs() << "Preemptively releasing states\n";
}
// If no state can be prioritized, they all exceeded the amount of time we
// are willing to wait for them. Release the states that already arrived at close_merge.
cur_mergehandler->releaseStates();
}
}
// If we were not able to prioritize a merging state, just return some state
return baseSearcher->selectState();
}
///
BatchingSearcher::BatchingSearcher(Searcher *_baseSearcher,
double _timeBudget,
unsigned _instructionBudget)
: baseSearcher(_baseSearcher),
timeBudget(_timeBudget),
instructionBudget(_instructionBudget),
lastState(0) {
}
BatchingSearcher::~BatchingSearcher() {
delete baseSearcher;
}
ExecutionState &BatchingSearcher::selectState() {
if (!lastState ||
(util::getWallTime()-lastStartTime)>timeBudget ||
(stats::instructions-lastStartInstructions)>instructionBudget) {
if (lastState) {
double delta = util::getWallTime()-lastStartTime;
if (delta>timeBudget*1.1) {
klee_message("increased time budget from %f to %f\n", timeBudget,
delta);
timeBudget = delta;
}
}
lastState = &baseSearcher->selectState();
lastStartTime = util::getWallTime();
lastStartInstructions = stats::instructions;
return *lastState;
} else {
return *lastState;
}
}
void
BatchingSearcher::update(ExecutionState *current,
const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
if (std::find(removedStates.begin(), removedStates.end(), lastState) !=
removedStates.end())
lastState = 0;
baseSearcher->update(current, addedStates, removedStates);
}
/***/
IterativeDeepeningTimeSearcher::IterativeDeepeningTimeSearcher(Searcher *_baseSearcher)
: baseSearcher(_baseSearcher),
time(1.) {
}
IterativeDeepeningTimeSearcher::~IterativeDeepeningTimeSearcher() {
delete baseSearcher;
}
ExecutionState &IterativeDeepeningTimeSearcher::selectState() {
ExecutionState &res = baseSearcher->selectState();
startTime = util::getWallTime();
return res;
}
void IterativeDeepeningTimeSearcher::update(
ExecutionState *current, const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
double elapsed = util::getWallTime() - startTime;
if (!removedStates.empty()) {
std::vector<ExecutionState *> alt = removedStates;
for (std::vector<ExecutionState *>::const_iterator
it = removedStates.begin(),
ie = removedStates.end();
it != ie; ++it) {
ExecutionState *es = *it;
std::set<ExecutionState*>::const_iterator it2 = pausedStates.find(es);
if (it2 != pausedStates.end()) {
pausedStates.erase(it2);
alt.erase(std::remove(alt.begin(), alt.end(), es), alt.end());
}
}
baseSearcher->update(current, addedStates, alt);
} else {
baseSearcher->update(current, addedStates, removedStates);
}
if (current &&
std::find(removedStates.begin(), removedStates.end(), current) ==
removedStates.end() &&
elapsed > time) {
pausedStates.insert(current);
baseSearcher->removeState(current);
}
if (baseSearcher->empty()) {
time *= 2;
klee_message("increased time budget to %f\n", time);
std::vector<ExecutionState *> ps(pausedStates.begin(), pausedStates.end());
baseSearcher->update(0, ps, std::vector<ExecutionState *>());
pausedStates.clear();
}
}
/***/
InterleavedSearcher::InterleavedSearcher(const std::vector<Searcher*> &_searchers)
: searchers(_searchers),
index(1) {
}
InterleavedSearcher::~InterleavedSearcher() {
for (std::vector<Searcher*>::const_iterator it = searchers.begin(),
ie = searchers.end(); it != ie; ++it)
delete *it;
}
ExecutionState &InterleavedSearcher::selectState() {
Searcher *s = searchers[--index];
if (index==0) index = searchers.size();
return s->selectState();
}
void InterleavedSearcher::update(
ExecutionState *current, const std::vector<ExecutionState *> &addedStates,
const std::vector<ExecutionState *> &removedStates) {
for (std::vector<Searcher*>::const_iterator it = searchers.begin(),
ie = searchers.end(); it != ie; ++it)
(*it)->update(current, addedStates, removedStates);
}
| 29.469159 | 109 | 0.602055 | [
"vector"
] |
a3b32c5b150400ebe38fcfeffe0ca144b6e7db10 | 62,525 | cc | C++ | pagespeed/kernel/image/gif_reader_test.cc | oschaaf/incubator-pagespeed-mod | 12a4d582a6eed9114aae6474b4e5fddfa7e4908c | [
"MIT"
] | null | null | null | pagespeed/kernel/image/gif_reader_test.cc | oschaaf/incubator-pagespeed-mod | 12a4d582a6eed9114aae6474b4e5fddfa7e4908c | [
"MIT"
] | null | null | null | pagespeed/kernel/image/gif_reader_test.cc | oschaaf/incubator-pagespeed-mod | 12a4d582a6eed9114aae6474b4e5fddfa7e4908c | [
"MIT"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// Test that basic GifReader operations succeed or fail as expected.
// Note that read-in file contents are tested against golden RGBA
// files in png_optimizer_test.cc, not here.
#include "pagespeed/kernel/image/gif_reader.h"
#include <cstddef>
#include <vector>
#include "pagespeed/kernel/base/gtest.h"
#include "pagespeed/kernel/base/message_handler.h"
#include "pagespeed/kernel/base/mock_message_handler.h"
#include "pagespeed/kernel/base/null_mutex.h"
#include "pagespeed/kernel/base/scoped_ptr.h"
#include "pagespeed/kernel/base/string.h"
#include "pagespeed/kernel/base/string_util.h"
#include "pagespeed/kernel/image/gif_square.h"
#include "pagespeed/kernel/image/image_util.h"
#include "pagespeed/kernel/image/png_optimizer.h"
#include "pagespeed/kernel/image/scanline_interface_frame_adapter.h"
#include "pagespeed/kernel/image/scanline_utils.h"
#include "pagespeed/kernel/image/test_utils.h"
namespace pagespeed {
namespace image_compression {
// Friend adapter so we can instantiate GifFrameReader.
class TestGifFrameReader : public GifFrameReader {
public:
explicit TestGifFrameReader(MessageHandler* handler) :
GifFrameReader(handler) {}
};
} // namespace image_compression
} // namespace pagespeed
namespace {
extern "C" {
#ifdef USE_SYSTEM_LIBPNG
#include "png.h" // NOLINT
#else
#include "external/libpng/png.h"
#endif
} // extern "C"
using net_instaweb::MockMessageHandler;
using net_instaweb::NullMutex;
using pagespeed::image_compression::kAlphaOpaque;
using pagespeed::image_compression::kAlphaTransparent;
using pagespeed::image_compression::kGifTestDir;
using pagespeed::image_compression::kPngSuiteGifTestDir;
using pagespeed::image_compression::kPngSuiteTestDir;
using pagespeed::image_compression::kPngTestDir;
using pagespeed::image_compression::kValidGifImageCount;
using pagespeed::image_compression::kValidGifImages;
using pagespeed::image_compression::size_px;
using pagespeed::image_compression::FrameSpec;
using pagespeed::image_compression::FrameToScanlineReaderAdapter;
using pagespeed::image_compression::GifDisposalToFrameSpecDisposal;
using pagespeed::image_compression::GifFrameReader;
using pagespeed::image_compression::GifReader;
using pagespeed::image_compression::GifSquare;
using pagespeed::image_compression::ImageFormat;
using pagespeed::image_compression::ImageSpec;
using pagespeed::image_compression::IMAGE_GIF;
using pagespeed::image_compression::IMAGE_PNG;
using pagespeed::image_compression::MultipleFrameReader;
using pagespeed::image_compression::PackAsArgb;
using pagespeed::image_compression::PixelFormat;
using pagespeed::image_compression::PixelFormat;
using pagespeed::image_compression::PixelRgbaChannels;
using pagespeed::image_compression::PngReaderInterface;
using pagespeed::image_compression::ReadTestFile;
using pagespeed::image_compression::ReadFile;
using pagespeed::image_compression::RgbaChannels;
using pagespeed::image_compression::QUIRKS_CHROME;
using pagespeed::image_compression::QUIRKS_FIREFOX;
using pagespeed::image_compression::QUIRKS_NONE;
using pagespeed::image_compression::RGB_888;
using pagespeed::image_compression::RGBA_8888;
using pagespeed::image_compression::RGBA_ALPHA;
using pagespeed::image_compression::RGBA_BLUE;
using pagespeed::image_compression::RGBA_GREEN;
using pagespeed::image_compression::RGBA_NUM_CHANNELS;
using pagespeed::image_compression::RGBA_RED;
using pagespeed::image_compression::ScanlineStatus;
using pagespeed::image_compression::ScopedPngStruct;
using pagespeed::image_compression::TestGifFrameReader;
using pagespeed::image_compression::kMessagePatternFailedToOpen;
using pagespeed::image_compression::kMessagePatternFailedToRead;
using pagespeed::image_compression::kMessagePatternLibpngError;
using pagespeed::image_compression::kMessagePatternLibpngWarning;
using pagespeed::image_compression::kMessagePatternUnexpectedEOF;
const char *kValidOpaqueGifImages[] = {
"basi0g01",
"basi0g02",
"basi0g04",
"basi0g08",
"basi3p01",
"basi3p02",
"basi3p04",
"basi3p08",
"basn0g01",
"basn0g02",
"basn0g04",
"basn0g08",
"basn3p01",
"basn3p02",
"basn3p04",
"basn3p08",
};
const char *kValidTransparentGifImages[] = {
"tr-basi4a08",
"tr-basn4a08"
};
const size_t kValidOpaqueGifImageCount = arraysize(kValidOpaqueGifImages);
const size_t kValidTransparentGifImageCount =
arraysize(kValidTransparentGifImages);
const char kAnimatedGif[] = "animated";
const char kBadGif[] = "bad";
const char kCompletelyTransparentImage[] = "completely_transparent";
const char kFrameSmallerThanScreen[] = "frame_smaller_than_screen";
const char kInterlacedImage[] = "interlaced";
const char kRedConforming[] = "red_conforming";
const char kRedEmptyScreen[] = "red_empty_screen";
const char kRedUnusedBackground[] = "red_unused_invalid_background";
const char kTransparentGif[] = "transparent";
const char kZeroSizeAnimatedGif[] = "zero_size_animation";
const char kInvalidPixelLocalPaletteGif[] = "bad_pixel_local_palette";
const char kInvalidPixelGlobalPaletteGif[] = "bad_pixel_global_palette";
// Message to ignore.
const char kMessagePatternMultipleFrameGif[] =
"Multiple frame GIF is not supported.";
class GifReaderTest : public testing::Test {
public:
GifReaderTest()
: message_handler_(new NullMutex),
gif_reader_(new GifReader(&message_handler_)),
read_(ScopedPngStruct::READ, &message_handler_) {
}
protected:
virtual void SetUp() {
message_handler_.AddPatternToSkipPrinting(kMessagePatternLibpngError);
message_handler_.AddPatternToSkipPrinting(kMessagePatternLibpngWarning);
}
protected:
MockMessageHandler message_handler_;
net_instaweb::scoped_ptr<PngReaderInterface> gif_reader_;
ScopedPngStruct read_;
private:
DISALLOW_COPY_AND_ASSIGN(GifReaderTest);
};
TEST_F(GifReaderTest, LoadValidGifsWithoutTransforms) {
GoogleString in, out;
for (size_t i = 0; i < kValidOpaqueGifImageCount; i++) {
ReadTestFile(
kPngSuiteGifTestDir, kValidOpaqueGifImages[i], "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_IDENTITY))
<< kValidOpaqueGifImages[i];
ASSERT_TRUE(read_.reset());
}
for (size_t i = 0; i < kValidTransparentGifImageCount; i++) {
ReadTestFile(
kPngSuiteGifTestDir, kValidTransparentGifImages[i], "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_IDENTITY))
<< kValidTransparentGifImages[i];
ASSERT_TRUE(read_.reset());
}
ReadTestFile(kGifTestDir, "transparent", "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_IDENTITY));
}
TEST_F(GifReaderTest, ExpandColorMapForValidGifs) {
GoogleString in, out;
for (size_t i = 0; i < kValidOpaqueGifImageCount; i++) {
ReadTestFile(
kPngSuiteGifTestDir, kValidOpaqueGifImages[i], "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_EXPAND))
<< kValidOpaqueGifImages[i];
ASSERT_TRUE(read_.reset());
}
for (size_t i = 0; i < kValidTransparentGifImageCount; i++) {
ReadTestFile(
kPngSuiteGifTestDir, kValidTransparentGifImages[i], "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_EXPAND))
<< kValidTransparentGifImages[i];
ASSERT_TRUE(read_.reset());
}
ReadTestFile(kGifTestDir, "transparent", "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_EXPAND));
}
TEST_F(GifReaderTest, RequireOpaqueForValidGifs) {
GoogleString in;
for (size_t i = 0; i < kValidOpaqueGifImageCount; i++) {
ReadTestFile(
kPngSuiteGifTestDir, kValidOpaqueGifImages[i], "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_IDENTITY, true))
<< kValidOpaqueGifImages[i];
ASSERT_TRUE(read_.reset());
}
for (size_t i = 0; i < kValidTransparentGifImageCount; i++) {
ReadTestFile(
kPngSuiteGifTestDir, kValidTransparentGifImages[i], "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_FALSE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_IDENTITY, true))
<< kValidTransparentGifImages[i];
ASSERT_TRUE(read_.reset());
}
ReadTestFile(kGifTestDir, "transparent", "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_FALSE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_IDENTITY, true));
}
TEST_F(GifReaderTest, ExpandColormapAndRequireOpaqueForValidGifs) {
GoogleString in;
for (size_t i = 0; i < kValidOpaqueGifImageCount; i++) {
ReadTestFile(
kPngSuiteGifTestDir, kValidOpaqueGifImages[i], "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_EXPAND, true))
<< kValidOpaqueGifImages[i];
ASSERT_TRUE(read_.reset());
}
for (size_t i = 0; i < kValidTransparentGifImageCount; i++) {
ReadTestFile(
kPngSuiteGifTestDir, kValidTransparentGifImages[i], "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_FALSE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_EXPAND, true))
<< kValidTransparentGifImages[i];
ASSERT_TRUE(read_.reset());
}
ReadTestFile(kGifTestDir, "transparent", "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_FALSE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_EXPAND, true));
}
TEST_F(GifReaderTest, StripAlpha) {
GoogleString in;
png_uint_32 height;
png_uint_32 width;
int bit_depth;
int color_type;
png_bytep trans;
int num_trans;
png_color_16p trans_values;
ReadTestFile(kGifTestDir, "transparent", "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_STRIP_ALPHA, false));
png_get_IHDR(read_.png_ptr(), read_.info_ptr(),
&width, &height, &bit_depth, &color_type,
NULL, NULL, NULL);
ASSERT_TRUE((color_type & PNG_COLOR_MASK_ALPHA) == 0); // NOLINT
ASSERT_EQ(static_cast<unsigned int>(0),
png_get_tRNS(read_.png_ptr(),
read_.info_ptr(),
&trans,
&num_trans,
&trans_values));
read_.reset();
ASSERT_TRUE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_STRIP_ALPHA |
PNG_TRANSFORM_EXPAND, false));
png_get_IHDR(read_.png_ptr(), read_.info_ptr(),
&width, &height, &bit_depth, &color_type,
NULL, NULL, NULL);
ASSERT_TRUE((color_type & PNG_COLOR_MASK_ALPHA) == 0); // NOLINT
ASSERT_EQ(static_cast<unsigned int>(0),
png_get_tRNS(read_.png_ptr(),
read_.info_ptr(),
&trans,
&num_trans,
&trans_values));
}
TEST_F(GifReaderTest, ExpandColormapOnZeroSizeCanvasAndCatchLibPngError) {
GoogleString in;
// This is a free image from
// <http://www.gifs.net/subcategory/40/0/20/Email>, with the canvas
// size information manually set to zero in order to trigger a
// libpng error.
ReadTestFile(kGifTestDir, "zero_size_animation", "gif", &in);
ASSERT_NE(static_cast<size_t>(0), in.length());
ASSERT_FALSE(gif_reader_->ReadPng(in, read_.png_ptr(), read_.info_ptr(),
PNG_TRANSFORM_EXPAND, true));
}
class GifScanlineReaderRawTest : public testing::Test {
public:
GifScanlineReaderRawTest()
: scanline_(NULL),
message_handler_(new NullMutex),
reader_(new TestGifFrameReader(&message_handler_)) {
}
bool Initialize(const char* file_name) {
if (!ReadTestFile(kGifTestDir, file_name, "gif", &input_image_)) {
PS_LOG_FATAL((&message_handler_), "Failed to read file: %s", file_name);
return false;
}
return reader_.Initialize(input_image_.c_str(), input_image_.length());
}
protected:
virtual void SetUp() {
message_handler_.AddPatternToSkipPrinting(kMessagePatternFailedToOpen);
message_handler_.AddPatternToSkipPrinting(kMessagePatternFailedToRead);
message_handler_.AddPatternToSkipPrinting(kMessagePatternMultipleFrameGif);
message_handler_.AddPatternToSkipPrinting(kMessagePatternUnexpectedEOF);
}
protected:
void* scanline_;
MockMessageHandler message_handler_;
FrameToScanlineReaderAdapter reader_;
GoogleString input_image_;
private:
DISALLOW_COPY_AND_ASSIGN(GifScanlineReaderRawTest);
};
TEST_F(GifScanlineReaderRawTest, CorruptHeader) {
ReadTestFile(kGifTestDir, kTransparentGif, "gif", &input_image_);
// Make GifRecordType invalid.
input_image_[781] = 0;
ASSERT_FALSE(reader_.Initialize(input_image_.c_str(),
input_image_.length()));
}
TEST_F(GifScanlineReaderRawTest, InitializeWithoutRead) {
ASSERT_TRUE(Initialize(kTransparentGif));
}
TEST_F(GifScanlineReaderRawTest, ReadOneRow) {
ASSERT_TRUE(Initialize(kTransparentGif));
EXPECT_TRUE(reader_.ReadNextScanline(&scanline_));
}
TEST_F(GifScanlineReaderRawTest, ReinitializeAfterOneRow) {
ASSERT_TRUE(Initialize(kTransparentGif));
EXPECT_TRUE(reader_.ReadNextScanline(&scanline_));
ASSERT_TRUE(Initialize(kInterlacedImage));
EXPECT_TRUE(reader_.ReadNextScanline(&scanline_));
}
TEST_F(GifScanlineReaderRawTest, ReInitializeAfterLastRow) {
ASSERT_TRUE(Initialize(kTransparentGif));
while (reader_.HasMoreScanLines()) {
EXPECT_TRUE(reader_.ReadNextScanline(&scanline_));
}
// After depleting the scanlines, any further call to
// ReadNextScanline leads to death in debugging mode, or a
// false in release mode.
#ifdef NDEBUG
EXPECT_FALSE(reader_.ReadNextScanline(&scanline_));
#else
EXPECT_DEATH(reader_.ReadNextScanline(&scanline_),
"The GIF image was not initialized or does not "
"have more scanlines.");
#endif
ASSERT_TRUE(Initialize(kInterlacedImage));
EXPECT_TRUE(reader_.ReadNextScanline(&scanline_));
}
// Animated GIF is not supported. Make sure GIF reader exits gracefully.
TEST_F(GifScanlineReaderRawTest, AnimatedGif) {
ASSERT_FALSE(Initialize(kAnimatedGif));
}
TEST_F(GifScanlineReaderRawTest, BadGif) {
ASSERT_FALSE(Initialize(kBadGif));
}
TEST_F(GifScanlineReaderRawTest, ZeroSizeGif) {
ASSERT_FALSE(Initialize(kZeroSizeAnimatedGif));
}
// Check the accuracy of the reader. Compare the decoded results with the gold
// data (".gif.rgba"). The test images include transparent and opaque ones.
TEST_F(GifScanlineReaderRawTest, ValidGifs) {
for (size_t i = 0; i < kValidGifImageCount; i++) {
GoogleString rgba_image, gif_image;
const char* file_name = kValidGifImages[i].filename;
ReadTestFile(kPngSuiteGifTestDir, file_name, "gif.rgba", &rgba_image);
ReadTestFile(kPngSuiteGifTestDir, file_name, "gif", &gif_image);
const uint8_t* reference_rgba =
reinterpret_cast<const uint8*>(rgba_image.data());
uint8* decoded_pixels = NULL;
ASSERT_TRUE(reader_.Initialize(gif_image.data(), gif_image.length()));
PixelFormat pixel_format = reader_.GetPixelFormat();
int width = reader_.GetImageWidth();
int height = reader_.GetImageHeight();
int bytes_per_row = reader_.GetBytesPerScanline();
int num_channels = GetNumChannelsFromPixelFormat(pixel_format,
&message_handler_);
EXPECT_EQ(kValidGifImages[i].width, width);
EXPECT_EQ(kValidGifImages[i].height, height);
if (kValidGifImages[i].transparency) {
EXPECT_EQ(pagespeed::image_compression::RGBA_8888, pixel_format);
EXPECT_EQ(4, num_channels);
} else {
EXPECT_EQ(pagespeed::image_compression::RGB_888, pixel_format);
EXPECT_EQ(3, num_channels);
}
EXPECT_EQ(width*num_channels, bytes_per_row);
// Decode and check the image a row at a time.
int row = 0;
while (reader_.HasMoreScanLines()) {
EXPECT_TRUE(reader_.ReadNextScanline(
reinterpret_cast<void**>(&decoded_pixels)));
for (int x = 0; x < width; ++x) {
int index_dec = x * num_channels;
int index_ref = (row * width + x) * 4;
// ASSERT_EQ is used in stead of EXPECT_EQ. Otherwise, the log will be
// spammed when an error happens.
ASSERT_EQ(0, memcmp(reference_rgba+index_ref, decoded_pixels+index_dec,
num_channels));
}
++row;
}
// Make sure both readers have exhausted all image rows.
EXPECT_EQ(height, row);
EXPECT_EQ(rgba_image.length(),
static_cast<size_t>(4 * height * width));
}
}
TEST_F(GifScanlineReaderRawTest, Interlaced) {
GoogleString png_image, gif_image;
ReadTestFile(kGifTestDir, kInterlacedImage, "png", &png_image);
ReadTestFile(kGifTestDir, kInterlacedImage, "gif", &gif_image);
DecodeAndCompareImages(IMAGE_PNG, png_image.c_str(), png_image.length(),
IMAGE_GIF, gif_image.c_str(), gif_image.length(),
false, // ignore_transparent_rgb
&message_handler_);
}
TEST_F(GifScanlineReaderRawTest, EmptyScreen) {
GoogleString png_image, gif_image;
ReadTestFile(kGifTestDir, kRedConforming, "png", &png_image);
ReadTestFile(kGifTestDir, kRedEmptyScreen, "gif", &gif_image);
DecodeAndCompareImages(IMAGE_PNG, png_image.c_str(), png_image.length(),
IMAGE_GIF, gif_image.c_str(), gif_image.length(),
false, // ignore_transparent_rgb
&message_handler_);
}
TEST_F(GifScanlineReaderRawTest, UnusedBackground) {
GoogleString png_image, gif_image;
ReadTestFile(kGifTestDir, kRedConforming, "png", &png_image);
ReadTestFile(kGifTestDir, kRedUnusedBackground, "gif", &gif_image);
DecodeAndCompareImages(IMAGE_PNG, png_image.c_str(), png_image.length(),
IMAGE_GIF, gif_image.c_str(), gif_image.length(),
false, // ignore_transparent_rgb
&message_handler_);
}
TEST_F(GifScanlineReaderRawTest, FrameSmallerThanImage) {
ASSERT_FALSE(Initialize(kFrameSmallerThanScreen));
EXPECT_EQ(1, message_handler_.MessagesOfType(net_instaweb::kInfo));
EXPECT_EQ(0, message_handler_.MessagesOfType(net_instaweb::kWarning));
EXPECT_EQ(0, message_handler_.MessagesOfType(net_instaweb::kError));
EXPECT_EQ(0, message_handler_.MessagesOfType(net_instaweb::kFatal));
}
TEST(GifReaderUtil, DisposalMethod) {
for (int i = -1; i < 4; ++i) {
FrameSpec::DisposalMethod actual_disposal =
GifDisposalToFrameSpecDisposal(i);
FrameSpec::DisposalMethod expected_disposal = FrameSpec::DISPOSAL_NONE;
switch (i) {
case 0:
// intentional fall-through
case 1:
expected_disposal = FrameSpec::DISPOSAL_NONE;
break;
case 2:
expected_disposal = FrameSpec::DISPOSAL_BACKGROUND;
break;
case 3:
expected_disposal = FrameSpec::DISPOSAL_RESTORE;
break;
}
EXPECT_EQ(expected_disposal, actual_disposal);
}
}
void CheckQuirksModeChangesToImageSpec(const FrameSpec& frame_spec,
const ImageSpec& original_spec,
const bool has_loop_count,
const ImageSpec& expected_noquirks_spec,
const ImageSpec& expected_firefox_spec,
const ImageSpec& expected_chrome_spec) {
ImageSpec noquirks_spec = original_spec;
ImageSpec firefox_spec = original_spec;
ImageSpec chrome_spec = original_spec;
GifFrameReader::ApplyQuirksModeToImage(QUIRKS_NONE, has_loop_count,
frame_spec, &noquirks_spec);
EXPECT_TRUE(noquirks_spec.Equals(expected_noquirks_spec));
GifFrameReader::ApplyQuirksModeToImage(QUIRKS_FIREFOX, has_loop_count,
frame_spec, &firefox_spec);
EXPECT_TRUE(firefox_spec.Equals(expected_firefox_spec))
<< "\nActual:\n" << firefox_spec.ToString()
<< "\nExpected:\n" << expected_firefox_spec.ToString();
GifFrameReader::ApplyQuirksModeToImage(QUIRKS_CHROME, has_loop_count,
frame_spec, &chrome_spec);
EXPECT_TRUE(chrome_spec.Equals(expected_chrome_spec))
<< "\nActual:\n" << chrome_spec.ToString()
<< "\nExpected:\n" << expected_chrome_spec.ToString();
}
void SetOpaqueBackground(PixelRgbaChannels rgba) {
static const PixelRgbaChannels kOpaqueBackground =
{0x80, 0x80, 0x80, kAlphaOpaque};
for (int channel = 0;
channel < static_cast<RgbaChannels>(channel);
++channel) {
rgba[channel] = kOpaqueBackground[channel];
}
}
TEST(ApplyQuirksModeToImage, TestFrameWidthLargerThanImageWidth) {
ImageSpec image_spec;
image_spec.width = 100;
image_spec.height = 100;
image_spec.num_frames = 2;
SetOpaqueBackground(image_spec.bg_color);
FrameSpec frame_spec;
frame_spec.width = 200;
frame_spec.height = 100;
frame_spec.top = 10;
frame_spec.left = 2;
ImageSpec expected_noquirks_spec = image_spec;
ImageSpec expected_firefox_spec = image_spec;
ImageSpec expected_chrome_spec = image_spec;
expected_chrome_spec.width = frame_spec.width;
expected_chrome_spec.height = frame_spec.height;
expected_chrome_spec.image_size_adjusted = true;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
image_spec.num_frames =
expected_noquirks_spec.num_frames =
expected_firefox_spec.num_frames =
expected_chrome_spec.num_frames = 1;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToImage, TestFrameHeightLargerThanImageHeight) {
ImageSpec image_spec;
image_spec.width = 100;
image_spec.height = 100;
image_spec.num_frames = 2;
SetOpaqueBackground(image_spec.bg_color);
FrameSpec frame_spec;
frame_spec.width = 100;
frame_spec.height = 200;
frame_spec.top = 10;
frame_spec.left = 2;
ImageSpec expected_noquirks_spec = image_spec;
ImageSpec expected_firefox_spec = image_spec;
ImageSpec expected_chrome_spec = image_spec;
expected_chrome_spec.width = frame_spec.width;
expected_chrome_spec.height = frame_spec.height;
expected_chrome_spec.image_size_adjusted = true;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
image_spec.num_frames =
expected_noquirks_spec.num_frames =
expected_firefox_spec.num_frames =
expected_chrome_spec.num_frames = 1;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToImage, TestFrameWidthSmallerThanImageWidth) {
ImageSpec image_spec;
image_spec.width = 100;
image_spec.height = 100;
image_spec.num_frames = 2;
SetOpaqueBackground(image_spec.bg_color);
FrameSpec frame_spec;
frame_spec.width = 50;
frame_spec.height = 100;
frame_spec.top = 10;
frame_spec.left = 2;
ImageSpec expected_noquirks_spec = image_spec;
ImageSpec expected_firefox_spec = image_spec;
ImageSpec expected_chrome_spec = image_spec;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
// With only one frame that is smaller than the image, the
// background color becomes fully transparent.
image_spec.num_frames =
expected_noquirks_spec.num_frames =
expected_firefox_spec.num_frames =
expected_chrome_spec.num_frames = 1;
expected_chrome_spec.bg_color[RGBA_ALPHA] = kAlphaTransparent;
expected_firefox_spec.bg_color[RGBA_ALPHA] = kAlphaTransparent;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToImage, TestFrameHeightSmallerThanImageHeight) {
ImageSpec image_spec;
image_spec.width = 100;
image_spec.height = 100;
image_spec.num_frames = 2;
SetOpaqueBackground(image_spec.bg_color);
FrameSpec frame_spec;
frame_spec.width = 100;
frame_spec.height = 50;
frame_spec.top = 10;
frame_spec.left = 2;
ImageSpec expected_noquirks_spec = image_spec;
ImageSpec expected_firefox_spec = image_spec;
ImageSpec expected_chrome_spec = image_spec;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
// With only one frame that is smaller than the image, the
// background color becomes fully transparent.
image_spec.num_frames =
expected_noquirks_spec.num_frames =
expected_firefox_spec.num_frames =
expected_chrome_spec.num_frames = 1;
expected_chrome_spec.bg_color[RGBA_ALPHA] = kAlphaTransparent;
expected_firefox_spec.bg_color[RGBA_ALPHA] = kAlphaTransparent;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToImage, TestFrameHeightSmallerWidthLargerThanImage) {
ImageSpec image_spec;
image_spec.width = 100;
image_spec.height = 100;
image_spec.num_frames = 2;
SetOpaqueBackground(image_spec.bg_color);
FrameSpec frame_spec;
frame_spec.width = 150;
frame_spec.height = 50;
frame_spec.top = 10;
frame_spec.left = 2;
ImageSpec expected_noquirks_spec = image_spec;
ImageSpec expected_firefox_spec = image_spec;
ImageSpec expected_chrome_spec = image_spec;
expected_chrome_spec.width = frame_spec.width;
expected_chrome_spec.height = frame_spec.height;
expected_chrome_spec.image_size_adjusted = true;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
// With only one frame that is smaller than the image, the
// background color becomes fully transparent.
image_spec.num_frames =
expected_noquirks_spec.num_frames =
expected_firefox_spec.num_frames =
expected_chrome_spec.num_frames = 1;
expected_chrome_spec.bg_color[RGBA_ALPHA] = kAlphaTransparent;
expected_firefox_spec.bg_color[RGBA_ALPHA] = kAlphaTransparent;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToImage, TestLoopCount) {
ImageSpec image_spec;
FrameSpec frame_spec;
image_spec.width = 100;
image_spec.height = 100;
image_spec.loop_count = 3;
frame_spec.width = 100;
frame_spec.height = 100;
frame_spec.top = 0;
frame_spec.left = 0;
ImageSpec expected_noquirks_spec = image_spec;
ImageSpec expected_firefox_spec = image_spec;
ImageSpec expected_chrome_spec = image_spec;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
expected_chrome_spec.loop_count = image_spec.loop_count + 1;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, true,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToImage, TestNoop) {
ImageSpec image_spec;
FrameSpec frame_spec;
image_spec.width = 100;
image_spec.height = 100;
frame_spec.width = 50;
frame_spec.height = 50;
frame_spec.top = 10;
frame_spec.left = 2;
ImageSpec expected_noquirks_spec = image_spec;
ImageSpec expected_firefox_spec = image_spec;
ImageSpec expected_chrome_spec = image_spec;
CheckQuirksModeChangesToImageSpec(frame_spec, image_spec, false,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
void CheckQuirksModeChangesToFirstFrameSpec(
const ImageSpec& image_spec,
const FrameSpec& original_spec,
const FrameSpec& expected_noquirks_spec,
const FrameSpec& expected_firefox_spec,
const FrameSpec& expected_chrome_spec) {
FrameSpec noquirks_spec = original_spec;
FrameSpec firefox_spec = original_spec;
FrameSpec chrome_spec = original_spec;
ImageSpec image = image_spec;
GifFrameReader::ApplyQuirksModeToImage(QUIRKS_NONE, false, noquirks_spec,
&image);
GifFrameReader::ApplyQuirksModeToFirstFrame(QUIRKS_NONE,
image, &noquirks_spec);
EXPECT_TRUE(noquirks_spec.Equals(expected_noquirks_spec))
<< " Got: " << noquirks_spec.ToString()
<< "\n Expected: " << expected_noquirks_spec.ToString();
image = image_spec;
GifFrameReader::ApplyQuirksModeToImage(QUIRKS_FIREFOX, false, firefox_spec,
&image);
GifFrameReader::ApplyQuirksModeToFirstFrame(QUIRKS_FIREFOX,
image, &firefox_spec);
EXPECT_TRUE(firefox_spec.Equals(expected_firefox_spec))
<< " Got: " << firefox_spec.ToString()
<< "\n Expected: " << expected_firefox_spec.ToString();
image = image_spec;
GifFrameReader::ApplyQuirksModeToImage(QUIRKS_CHROME, false, chrome_spec,
&image);
GifFrameReader::ApplyQuirksModeToFirstFrame(QUIRKS_CHROME,
image, &chrome_spec);
EXPECT_TRUE(chrome_spec.Equals(expected_chrome_spec))
<< " Got: " << chrome_spec.ToString()
<< "\n Expected: " << expected_chrome_spec.ToString();
}
TEST(ApplyQuirksModeToFirstFrame, TestWidth) {
ImageSpec image_spec;
FrameSpec frame_spec;
image_spec.width = 100;
image_spec.height = 100;
frame_spec.width = 200;
frame_spec.height = 50;
frame_spec.top = 10;
frame_spec.left = 2;
FrameSpec expected_noquirks_spec = frame_spec;
FrameSpec expected_firefox_spec = frame_spec;
FrameSpec expected_chrome_spec = frame_spec;
expected_firefox_spec.top = 0;
expected_firefox_spec.left = 0;
expected_firefox_spec.width = 0;
expected_firefox_spec.height = 0;
expected_chrome_spec.top = 0;
expected_chrome_spec.left = 0;
CheckQuirksModeChangesToFirstFrameSpec(image_spec, frame_spec,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToFirstFrame, TestHeight) {
ImageSpec image_spec;
FrameSpec frame_spec;
image_spec.width = 100;
image_spec.height = 100;
frame_spec.width = 50;
frame_spec.height = 200;
frame_spec.top = 10;
frame_spec.left = 2;
FrameSpec expected_noquirks_spec = frame_spec;
FrameSpec expected_firefox_spec = frame_spec;
FrameSpec expected_chrome_spec = frame_spec;
expected_firefox_spec.top = 0;
expected_firefox_spec.left = 0;
expected_firefox_spec.width = 0;
expected_firefox_spec.height = 0;
expected_chrome_spec.top = 0;
expected_chrome_spec.left = 0;
CheckQuirksModeChangesToFirstFrameSpec(image_spec, frame_spec,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToFirstFrame, TestZeroWidthFrame) {
ImageSpec image_spec;
FrameSpec frame_spec;
image_spec.width = 100;
image_spec.height = 120;
frame_spec.width = 0;
frame_spec.height = 50;
frame_spec.top = 10;
frame_spec.left = 2;
FrameSpec expected_noquirks_spec = frame_spec;
FrameSpec expected_chrome_spec = frame_spec;
FrameSpec expected_firefox_spec = frame_spec;
expected_chrome_spec.height = image_spec.height;
expected_chrome_spec.width = image_spec.width;
expected_chrome_spec.top = 0;
expected_chrome_spec.left = 0;
expected_firefox_spec.top = 0;
expected_firefox_spec.left = 0;
expected_firefox_spec.width = 0;
expected_firefox_spec.height = 0;
CheckQuirksModeChangesToFirstFrameSpec(image_spec, frame_spec,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToFirstFrame, TestZeroHeightFrame) {
ImageSpec image_spec;
FrameSpec frame_spec;
image_spec.width = 100;
image_spec.height = 120;
frame_spec.width = 50;
frame_spec.height = 0;
frame_spec.top = 10;
frame_spec.left = 2;
FrameSpec expected_noquirks_spec = frame_spec;
FrameSpec expected_chrome_spec = frame_spec;
FrameSpec expected_firefox_spec = frame_spec;
expected_chrome_spec.height = image_spec.height;
expected_chrome_spec.width = image_spec.width;
expected_chrome_spec.top = 0;
expected_chrome_spec.left = 0;
expected_firefox_spec.top = 0;
expected_firefox_spec.left = 0;
expected_firefox_spec.width = 0;
expected_firefox_spec.height = 0;
CheckQuirksModeChangesToFirstFrameSpec(image_spec, frame_spec,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToFirstFrame, TestNoopChrome) {
ImageSpec image_spec;
FrameSpec frame_spec;
image_spec.width = 100;
image_spec.height = 120;
frame_spec.width = 60;
frame_spec.height = 50;
frame_spec.top = 10;
frame_spec.left = 2;
FrameSpec expected_noquirks_spec = frame_spec;
FrameSpec expected_firefox_spec = frame_spec;
FrameSpec expected_chrome_spec = frame_spec;
expected_firefox_spec.top = 0;
expected_firefox_spec.left = 0;
expected_firefox_spec.width = 0;
expected_firefox_spec.height = 0;
CheckQuirksModeChangesToFirstFrameSpec(image_spec, frame_spec,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
TEST(ApplyQuirksModeToFirstFrame, TestNoop) {
ImageSpec image_spec;
FrameSpec frame_spec;
image_spec.width = 100;
image_spec.height = 120;
frame_spec.width = 100;
frame_spec.height = 120;
frame_spec.top = 0;
frame_spec.left = 0;
FrameSpec expected_noquirks_spec = frame_spec;
FrameSpec expected_firefox_spec = frame_spec;
FrameSpec expected_chrome_spec = frame_spec;
CheckQuirksModeChangesToFirstFrameSpec(image_spec, frame_spec,
expected_noquirks_spec,
expected_firefox_spec,
expected_chrome_spec);
}
class GifAnimationTest : public testing::Test {
public:
struct Image {
size_px width;
size_px height;
int bg_color_idx;
size_t loop_count;
};
struct Frame {
size_px width;
size_px height;
bool interlace;
int delay_cs;
int disposal;
const GifColorType* colormap;
int num_colors;
int transparent_idx;
int square_color_idx;
size_px top;
size_px left;
};
GifAnimationTest()
: scanline_(NULL),
message_handler_(new NullMutex),
gif_(true, &message_handler_),
reader_(new TestGifFrameReader(&message_handler_)),
read_all_scanlines_(true) {
}
void SynthesizeImage(const char* filename, const Image& image) {
// Note that these images are synthesized with QUIRKS_NONE.
filename_ = StrCat(net_instaweb::GTestTempDir(),
"/", filename, ".gif");
EXPECT_TRUE(gif_.Open(filename_));
PS_LOG_INFO((&message_handler_), "Generating image: %s", filename_.c_str());
gif_.PrepareScreen(true, image.width, image.height, kColorMap, kNumColors,
image.bg_color_idx, image.loop_count);
for (std::vector<Frame>::iterator frame = synth_frames_.begin();
frame != synth_frames_.end();
++frame) {
EXPECT_TRUE(gif_.PutImage(
frame->left, frame->top, frame->width, frame->height,
frame->colormap, frame->num_colors,
frame->square_color_idx, frame->transparent_idx,
frame->interlace, frame->delay_cs, frame->disposal));
}
EXPECT_TRUE(gif_.Close());
}
void ReadImage(const Image& image) {
if (!ReadFile(filename_, &input_image_)) {
PS_LOG_FATAL((&message_handler_),
"Failed to read file: %s", filename_.c_str());
return;
}
EXPECT_TRUE(reader_->Initialize(input_image_.c_str(),
input_image_.length()).Success());
ScanlineStatus status;
ImageSpec image_spec;
EXPECT_TRUE(reader_->GetImageSpec(&image_spec, &status));
EXPECT_EQ(image.width, image_spec.width);
EXPECT_EQ(image.height, image_spec.height);
EXPECT_EQ((image.loop_count == GifSquare::kNoLoopCountSpecified ?
1 : image.loop_count),
image_spec.loop_count);
EXPECT_EQ(synth_frames_.size(), image_spec.num_frames);
EXPECT_FALSE(image_spec.use_bg_color);
EXPECT_EQ(kColorMap[image.bg_color_idx].Red,
image_spec.bg_color[RGBA_RED]);
EXPECT_EQ(kColorMap[image.bg_color_idx].Green,
image_spec.bg_color[RGBA_GREEN]);
EXPECT_EQ(kColorMap[image.bg_color_idx].Blue,
image_spec.bg_color[RGBA_BLUE]);
EXPECT_EQ(kAlphaOpaque, image_spec.bg_color[RGBA_ALPHA]);
for (std::vector<Frame>::iterator set_frame = synth_frames_.begin();
set_frame != synth_frames_.end();
++set_frame) {
FrameSpec frame_spec;
EXPECT_TRUE(reader_->HasMoreFrames());
EXPECT_TRUE(reader_->PrepareNextFrame(&status));
EXPECT_TRUE(reader_->GetFrameSpec(&frame_spec, &status));
EXPECT_EQ(set_frame->delay_cs < 0 ?
0 : set_frame->delay_cs * 10, frame_spec.duration_ms);
EXPECT_EQ(set_frame->width, frame_spec.width);
EXPECT_EQ(set_frame->height, frame_spec.height);
EXPECT_EQ(set_frame->top, frame_spec.top);
EXPECT_EQ(set_frame->left, frame_spec.left);
EXPECT_EQ(set_frame->interlace, frame_spec.hint_progressive);
EXPECT_EQ(set_frame->transparent_idx >= 0 ?
RGBA_8888 : RGB_888, frame_spec.pixel_format);
FrameSpec::DisposalMethod frame_disposal =
GifDisposalToFrameSpecDisposal(set_frame->disposal);
EXPECT_EQ((frame_disposal == FrameSpec::DISPOSAL_UNKNOWN ?
FrameSpec::DISPOSAL_NONE : frame_disposal),
frame_spec.disposal);
const GifColorType* cmap = (set_frame->colormap == NULL ?
kColorMap : set_frame->colormap);
const int bytes_per_pixel = GetBytesPerPixel(frame_spec.pixel_format);
static const int kRgbBytes = 3;
if (read_all_scanlines_) {
for (int row = 0; row < frame_spec.height; ++row) {
EXPECT_TRUE(reader_->HasMoreScanlines());
const uint8_t* scanline;
ScanlineStatus status =
reader_->ReadNextScanline(
reinterpret_cast<const void **>(&scanline));
EXPECT_TRUE(status.Success());
for (int col = 0; col < frame_spec.width; ++col) {
// Since we're comparing pixel by pixel, correlated errors
// would generate huge output if we use EXPECT rather than
// ASSERT below.
if (frame_spec.pixel_format == RGBA_8888 &&
(set_frame->transparent_idx == set_frame->square_color_idx)) {
// This pixel is fully transparent so other channels do not
// matter.
ASSERT_EQ(kAlphaTransparent,
*(scanline + col * bytes_per_pixel + kRgbBytes));
const uint8 black_pixel[3] = {0, 0, 0};
ASSERT_EQ(0, memcmp(scanline + col * bytes_per_pixel, black_pixel,
kRgbBytes));
} else {
// This pixel must be opaque. Check all color channels.
ASSERT_EQ(0, memcmp(scanline + col * bytes_per_pixel,
cmap + set_frame->square_color_idx,
kRgbBytes));
if (frame_spec.pixel_format == RGBA_8888) {
ASSERT_EQ(kAlphaOpaque,
*(scanline + col * bytes_per_pixel + kRgbBytes));
}
}
}
}
EXPECT_FALSE(reader_->HasMoreScanlines());
}
}
EXPECT_FALSE(reader_->HasMoreFrames());
}
Image DefineImage() {
Image image;
image.width = 100;
image.height = 100;
image.bg_color_idx = 3;
image.loop_count = GifSquare::kNoLoopCountSpecified;
return image;
}
void SynthesizeAndRead(const char* name, const Image& image) {
SynthesizeImage(name, image);
ReadImage(image);
}
protected:
virtual void SetUp() {
message_handler_.AddPatternToSkipPrinting(kMessagePatternFailedToOpen);
message_handler_.AddPatternToSkipPrinting(kMessagePatternFailedToRead);
message_handler_.AddPatternToSkipPrinting(kMessagePatternMultipleFrameGif);
message_handler_.AddPatternToSkipPrinting(kMessagePatternUnexpectedEOF);
}
protected:
void* scanline_;
MockMessageHandler message_handler_;
GifSquare gif_;
net_instaweb::scoped_ptr<MultipleFrameReader> reader_;
bool read_all_scanlines_;
GoogleString filename_;
GoogleString input_image_;
std::vector<Frame> synth_frames_;
static const int kNumColors;
static const GifColorType kColorMap[];
static const GifColorType kAlternateColorMap[];
private:
DISALLOW_COPY_AND_ASSIGN(GifAnimationTest);
};
const int GifAnimationTest::kNumColors = 8;
const GifColorType GifAnimationTest::kColorMap[kNumColors] = {
GifSquare::kGifWhite,
GifSquare::kGifBlack,
GifSquare::kGifRed,
GifSquare::kGifGreen,
GifSquare::kGifBlue,
GifSquare::kGifYellow,
GifSquare::kGifGray,
GifSquare::kGifGray,
};
const GifColorType GifAnimationTest::kAlternateColorMap[kNumColors] = {
GifSquare::kGifBlue,
GifSquare::kGifRed,
GifSquare::kGifYellow,
GifSquare::kGifGreen,
GifSquare::kGifWhite,
GifSquare::kGifBlack,
GifSquare::kGifGray,
GifSquare::kGifGray,
};
// Note that the various test cases with "FallingOffImage" generate
// images that, when viewed on Chrome and Firefox, exhibit the quirky
// behavior that is captured in ImageSpec and FrameSpec when the
// appropriate QuirksMode is used. The test cases below use
// QUIRKS_NONE to test behavior to the spec.
// Non-animated, non-interlaced, only global colormap, varying disposals.
TEST_F(GifAnimationTest, ReadSingleFrameOpaque) {
const Frame frame = {10, 10, false, 0, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_opaque", DefineImage());
}
TEST_F(GifAnimationTest, ReadSingleFrameTransparency) {
const Frame frame = {10, 10, false, 0, 1, NULL, 0, 4, 2, 10, 10};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_transparency", DefineImage());
}
TEST_F(GifAnimationTest, ReadSingleFrameOpaqueFallingOffImage) {
const Frame frame = {10, 10, false, 0, 2, NULL, 0, -1, 2, 95, 95};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_opaque_falling_off_image", DefineImage());
}
TEST_F(GifAnimationTest, ReadSingleFrameOpaqueLargeFallingOffImage) {
const Frame frame = {250, 250, false, 0, 2, NULL, 0, -1, 2, 95, 95};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_opaque_large_falling_off_image",
DefineImage());
}
TEST_F(GifAnimationTest, ReadSingleFrameTransparencyFallingOffImage) {
const Frame frame = {10, 10, false, 0, 3, NULL, 0, 4, 2, 95, 95};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_transparent_falling_off_image",
DefineImage());
}
TEST_F(GifAnimationTest, ReadSingleFrameTransparencyFallingOffImageAtOrigin) {
const Frame frame = {250, 250, false, 0, 3, NULL, 0, 4, 2, 0, 0};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_transparent_falling_off_image_at_origin",
DefineImage());
}
TEST_F(GifAnimationTest, ReadSingleFrameOpaqueInZeroSizeImage) {
Image image = DefineImage();
image.width = 0;
image.height = 0;
const Frame frame = {10, 10, false, 0, 1, NULL, 0, 4, 2, 10, 10};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_opaque_in_zero_size_image", image);
}
TEST_F(GifAnimationTest, ReadSingleFrameOpaqueInZeroSizeImageAtOrigin) {
Image image = DefineImage();
image.width = 0;
image.height = 0;
const Frame frame = {10, 10, false, 0, 1, NULL, 0, 4, 2, 0, 0};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_opaque_in_zero_size_image_at_origin", image);
}
// Non-animated, interlaced, only global colormap, varying disposals.
TEST_F(GifAnimationTest, ReadSingleFrameInterlacedOpaque) {
const Frame frame = {10, 10, true, 0, 4, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_interlaced_opaque", DefineImage());
}
TEST_F(GifAnimationTest, ReadSingleFrameInterlacedTransparency) {
const Frame frame = {10, 10, true, 0, 0, NULL, 0, 4, 2, 10, 10};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_interlaced_transparency", DefineImage());
}
TEST_F(GifAnimationTest,
ReadSingleFrameInterlacedOpaqueFallingOffImage) {
const Frame frame = {10, 10, true, 0, 1, NULL, 0, -1, 2, 95, 95};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_interlaced_opaque_falling_off_image",
DefineImage());
}
TEST_F(GifAnimationTest,
ReadSingleFrameInterlacedTransparencyFallingOffImage) {
const Frame frame = {10, 10, true, 0, 2, NULL, 0, 4, 2, 95, 95};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_interlaced_transparent_falling_off_image",
DefineImage());
}
// Non-animated, non-interlaced, both global and per-frame colormap,
// varying disposals.
TEST_F(GifAnimationTest, ReadSingleFrameDualColormapsOpaque) {
const Frame frame =
{10, 10, false, 0, 3, kAlternateColorMap, kNumColors, -1, 2, 10, 10};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_colormaps_opaque", DefineImage());
}
TEST_F(GifAnimationTest, ReadSingleFrameDualColormapsTransparency) {
const Frame frame =
{10, 10, false, 0, 4, kAlternateColorMap, kNumColors, 4, 2, 10, 10};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_colormaps_transparency", DefineImage());
}
TEST_F(GifAnimationTest,
ReadSingleFrameDualColormapsOpaqueFallingOffImage) {
const Frame frame =
{10, 10, false, 0, 0, kAlternateColorMap, kNumColors, -1, 2, 95, 95};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_colormaps_opaque_falling_off_image",
DefineImage());
}
TEST_F(GifAnimationTest,
ReadSingleFrameDualColormapsTransparencyFallingOffImage) {
const Frame frame =
{10, 10, false, 0, 1, kAlternateColorMap, kNumColors, 4, 2, 95, 95};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_colormaps_transparent_falling_off_image",
DefineImage());
}
// Non-animated, non-interlaced, only global colormap, varying
// disposals, varying delays.
TEST_F(GifAnimationTest, ReadSingleFrameDelayOpaque) {
const Frame frame = {10, 10, true, 10, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame);
SynthesizeAndRead("single_frame_opaque", DefineImage());
}
// Animated images.
TEST_F(GifAnimationTest, ReadMultipleFrameOpaque) {
Frame frame1 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, true, 100, 0, NULL, 0, -1, 3, 20, 20};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque", DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueFirstFallingOffImage) {
Frame frame1 = {250, 250, true, 100, 0, NULL, 0, -1, 3, 90, 90};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 79, 79};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque_1st_falling_off_image",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueSecondFallingOffImage) {
Frame frame1 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 79, 79};
synth_frames_.push_back(frame1);
Frame frame2 = {250, 250, true, 100, 0, NULL, 0, -1, 3, 90, 90};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque_2nd_falling_off_image",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueFirstFallingOffImageAtOrigin) {
Frame frame1 = {250, 250, true, 100, 0, NULL, 0, -1, 3, 0, 0};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 79, 79};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque_1st_falling_off_image_at_origin",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueFirstFallingOffXImage) {
Frame frame1 = {250, 20, false, 100, 0, NULL, 0, -1, 3, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 79, 79};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque_1st_falling_off_x_image",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueFirstFallingOffYImage) {
Frame frame1 = {20, 250, false, 100, 0, NULL, 0, -1, 3, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 79, 79};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque_1st_falling_off_y_image",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueSecondFallingOffImageAtOrigin) {
Frame frame1 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 79, 79};
synth_frames_.push_back(frame1);
Frame frame2 = {250, 250, false, 100, 0, NULL, 0, -1, 3, 0, 0};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque_2nd_falling_off_image_at_origin",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueNoDelay) {
Frame frame1 = {20, 20, false, 0, 1, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 0, 2, NULL, 0, -1, 3, 20, 20};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque_nodelay", DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameTransparency) {
Frame frame1 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 100, 0, NULL, 0, 3, 3, 20, 20};
synth_frames_.push_back(frame2);
Frame frame3 = {20, 20, false, 100, 0, NULL, 0, 2, 3, 25, 25};
synth_frames_.push_back(frame3);
SynthesizeAndRead("multiple_frame_transparency", DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameNoDelay2FrameOpaque) {
// Tests that the transparency information for one frame is not
// carried to the next. By setting the transparent index, delay, and
// disposal to -1, the synthesized image will not have a Graphic
// Control Extension for the given frame, and we can test that
// transparent index was not carried over.
const int frame1_transparent_idx = 3;
const int frame2_color_idx = frame1_transparent_idx;
Frame frame1 =
{20, 20, false, 0, 0, NULL, 0, frame1_transparent_idx, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 =
{20, 20, false, -1, -1, NULL, 0, -1, frame2_color_idx, 20, 20};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_transparency_no_delay_2frame_opaque",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameTransparencySkipScanlines) {
read_all_scanlines_ = false;
Frame frame1 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 100, 0, NULL, 0, 3, 3, 20, 20};
synth_frames_.push_back(frame2);
Frame frame3 = {20, 20, false, 100, 0, NULL, 0, 2, 3, 25, 25};
synth_frames_.push_back(frame3);
SynthesizeAndRead("multiple_frame_transparency_skip_scanlines",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameTransparencyMixInterlaced) {
Frame frame1 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, true, 100, 0, NULL, 0, 3, 3, 20, 20};
synth_frames_.push_back(frame2);
Frame frame3 = {20, 20, false, 100, 0, NULL, 0, 2, 3, 25, 25};
synth_frames_.push_back(frame3);
SynthesizeAndRead("multiple_frame_transparency_mix_interlaced",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameTransparencyMixColormaps) {
Frame frame1 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 =
{20, 20, false, 100, 0, kAlternateColorMap, kNumColors, 3, 3, 20, 20};
synth_frames_.push_back(frame2);
Frame frame3 = {20, 20, false, 100, 0, NULL, 0, 2, 3, 25, 25};
synth_frames_.push_back(frame3);
SynthesizeAndRead("multiple_frame_transparency_mix_colormaps", DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueFallingOffImage) {
Frame frame1 = {10, 10, false, 0, 2, NULL, 0, -1, 2, 93, 93};
synth_frames_.push_back(frame1);
Frame frame2 = {10, 10, false, 0, 2, NULL, 0, -1, 4, 95, 95};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_opaque_falling_off_image", DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameTransparencyFallingOffImage) {
Frame frame1 = {10, 10, false, 0, 3, NULL, 0, 4, 2, 93, 93};
synth_frames_.push_back(frame1);
Frame frame2 = {10, 10, false, 0, 3, NULL, 0, 4, 4, 95, 95};
synth_frames_.push_back(frame2);
SynthesizeAndRead("multiple_frame_transparent_falling_off_image",
DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameOpaqueDisposal) {
Frame frame1 = {20, 20, false, 100, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 100, 0, NULL, 0, -1, 3, 20, 20};
synth_frames_.push_back(frame2);
Frame frame3 = {20, 20, false, 100, 2, NULL, 0, -1, 4, 15, 15};
synth_frames_.push_back(frame3);
Frame frame4 = {20, 20, false, 100, 3, NULL, 0, -1, 1, 0, 0};
synth_frames_.push_back(frame4);
Frame frame5 = {20, 20, false, 100, 1, NULL, 0, -1, 5, 30, 30};
synth_frames_.push_back(frame5);
SynthesizeAndRead("multiple_frame_opaque_disposal", DefineImage());
}
TEST_F(GifAnimationTest, ReadMultipleFrameTransparencyLoopInfinite) {
Image image = DefineImage();
image.loop_count = 0;
Frame frame1 = {20, 20, false, 50, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 50, 0, NULL, 0, 3, 3, 20, 20};
synth_frames_.push_back(frame2);
Frame frame3 = {20, 20, false, 50, 0, NULL, 0, 2, 3, 25, 25};
synth_frames_.push_back(frame3);
SynthesizeAndRead("multiple_frame_transparency_loop_infinite", image);
}
TEST_F(GifAnimationTest, ReadMultipleFrameTransparencyNoDelayLoopInfinite) {
Image image = DefineImage();
image.loop_count = 0;
Frame frame1 = {20, 20, false, 0, 1, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 0, 1, NULL, 0, 3, 3, 20, 20};
synth_frames_.push_back(frame2);
Frame frame3 = {20, 20, false, 0, 1, NULL, 0, 2, 3, 25, 25};
synth_frames_.push_back(frame3);
SynthesizeAndRead("multiple_frame_transparency_nodelay_loop_infinite", image);
}
TEST_F(GifAnimationTest, ReadMultipleFrameTransparencyLoopThrice) {
Image image = DefineImage();
image.loop_count = 3;
Frame frame1 = {20, 20, false, 50, 0, NULL, 0, -1, 2, 10, 10};
synth_frames_.push_back(frame1);
Frame frame2 = {20, 20, false, 50, 0, NULL, 0, 3, 3, 20, 20};
synth_frames_.push_back(frame2);
Frame frame3 = {20, 20, false, 50, 0, NULL, 0, 2, 3, 25, 25};
synth_frames_.push_back(frame3);
SynthesizeAndRead("multiple_frame_transparency_loop_thrice", image);
}
void CheckImageForOutOfBoundsPixel(const char* filename,
int first_invalid_frame) {
const PixelRgbaChannels kTransparentPixel = {0, 0, 0, kAlphaTransparent};
MockMessageHandler message_handler(new NullMutex);
net_instaweb::scoped_ptr<MultipleFrameReader>
reader(new TestGifFrameReader(&message_handler));
GoogleString input_image;
if (!ReadTestFile(kGifTestDir, filename, "gif", &input_image)) {
PS_LOG_FATAL((&message_handler),
"Failed to read file: %s", filename);
return;
}
EXPECT_TRUE(reader->Initialize(input_image.c_str(),
input_image.length()).Success());
ScanlineStatus status;
ImageSpec image_spec;
FrameSpec frame_spec;
EXPECT_TRUE(reader->GetImageSpec(&image_spec, &status));
EXPECT_GT(image_spec.num_frames, first_invalid_frame);
// Frames up to the first invalid frame should have format RGB_888.
for (size_px frame = 0; frame < first_invalid_frame; ++frame) {
EXPECT_TRUE(reader->HasMoreFrames());
EXPECT_TRUE(reader->PrepareNextFrame(&status));
EXPECT_TRUE(reader->GetFrameSpec(&frame_spec, &status));
EXPECT_EQ(RGB_888, frame_spec.pixel_format);
}
// The invalid frame should have format RGBA_8888, and all its
// pixels, which are out of palette bounds, should be reported
// as transparent.
EXPECT_TRUE(reader->HasMoreFrames());
EXPECT_TRUE(reader->PrepareNextFrame(&status));
EXPECT_TRUE(reader->GetFrameSpec(&frame_spec, &status));
EXPECT_EQ(RGBA_8888, frame_spec.pixel_format);
const uint8_t* scanline;
for (size_px row = 0; row < frame_spec.height; ++row) {
EXPECT_TRUE(reader->HasMoreScanlines());
EXPECT_TRUE(
reader->ReadNextScanline(
reinterpret_cast<const void **>(&scanline),
&status));
for (size_px col = 0; col < frame_spec.width; ++col) {
int cmp_result = memcmp(scanline + RGBA_NUM_CHANNELS * col,
&kTransparentPixel,
RGBA_NUM_CHANNELS * sizeof(uint8_t));
EXPECT_EQ(0, cmp_result);
if (cmp_result != 0) {
// Return eagerly to avoid excessive output in case of error.
return;
}
}
}
EXPECT_FALSE(reader->HasMoreScanlines());
// We don't check any additional frames
}
TEST(InvalidPixels, TestOutOfRangePixelValueInLocalPalette) {
// This image has a global palette as well as local palettes for all
// frames. For frame #3, the local palette is only four colors long
// but has pixels referring to color #4, which is out of range.
CheckImageForOutOfBoundsPixel(kInvalidPixelLocalPaletteGif, 3);
}
TEST(InvalidPixels, TestOutOfRangePixelValueInGlobalPalette) {
// This image has a four-color global palette as well as eight-color
// local palettes for frames 0-2. Frame #3 does not have a local
// palette (so it uses the global one) but has pixels referring to
// color #4, which is out of range.
CheckImageForOutOfBoundsPixel(kInvalidPixelGlobalPaletteGif, 3);
}
} // namespace
| 36.016705 | 80 | 0.689516 | [
"vector"
] |
a3be94efd96b0ba1a35a6256515c6142820277a4 | 4,074 | cpp | C++ | SmartPedal/Source/WaveNet.cpp | alansarkar/SmartGuitarPedal | 0a05ff7282b142b61d118732b98f261b2866e25c | [
"Apache-2.0"
] | 99 | 2020-11-05T16:11:18.000Z | 2022-03-30T03:20:51.000Z | SmartPedal/Source/WaveNet.cpp | damiangr/SmartGuitarPedal | f9e72432897e9f0d15d2114a52d3dd467e3fa619 | [
"Apache-2.0"
] | 3 | 2020-09-16T18:55:29.000Z | 2020-10-30T14:57:43.000Z | SmartPedal/Source/WaveNet.cpp | damiangr/SmartGuitarPedal | f9e72432897e9f0d15d2114a52d3dd467e3fa619 | [
"Apache-2.0"
] | 12 | 2020-12-08T18:35:58.000Z | 2021-09-29T21:47:15.000Z | /*
==============================================================================
WaveNet.cpp
Created: 14 Jan 2019 5:19:01pm
Author: Damskägg Eero-Pekka
==============================================================================
*/
#include "WaveNet.h"
WaveNet::WaveNet(int inputChannels, int outputChannels, int convolutionChannels,
int filterWidth, std::string activation, std::vector<int> dilations) :
convStack(convolutionChannels, filterWidth, dilations, activation),
inputLayer(inputChannels, convolutionChannels, 1),
outputLayer(convolutionChannels*dilations.size(), outputChannels, 1),
inputChannels(inputChannels),
outputChannels(outputChannels),
filterWidth(filterWidth),
skipChannels(convolutionChannels*(int)dilations.size()),
convolutionChannels(convolutionChannels),
memoryChannels(Activations::isGated(activation) ? convolutionChannels * 2 : convolutionChannels),
activation(activation),
dilations(dilations)
{
}
void WaveNet::readDilations(var config)
{
std::vector<int> newDilations;
if (auto dilationsArray = config.getProperty("dilations", var()).getArray())
{
for (int dil : *dilationsArray)
newDilations.push_back(dil);
}
dilations = newDilations;
}
void WaveNet::prepareToPlay(int newSamplesPerBlock)
{
samplesPerBlock = newSamplesPerBlock;
convData.setSize(1, samplesPerBlock*memoryChannels);
skipData.setSize(1, samplesPerBlock*skipChannels);
convStack.prepareToPlay(samplesPerBlock);
}
void WaveNet::copyInputData(const float **inputData, int numSamples)
{
float *writePtr = convData.getWritePointer(0);
for (int ch = 0; ch < inputChannels; ++ch)
{
int start_idx = idx(ch, 0, numSamples);
const float *chData = inputData[ch];
for (int i = 0; i < numSamples; ++i)
writePtr[start_idx + i] = chData[i];
}
}
void WaveNet::copyOutputData(float **outputData, int numSamples)
{
const float *readPtr = skipData.getReadPointer(0);
for (int ch = 0; ch < outputChannels; ++ch)
{
int start_idx = idx(ch, 0, numSamples);
float *chData = outputData[ch];
for (int i = 0; i < numSamples; ++i)
chData[i] = readPtr[start_idx + i];
}
}
void WaveNet::process(const float **inputData, float **outputData, int numSamples)
{
if (numSamples > samplesPerBlock)
prepareToPlay(numSamples);
copyInputData(inputData, numSamples);
inputLayer.process(convData.getWritePointer(0), numSamples);
convStack.process(convData.getWritePointer(0), skipData.getWritePointer(0), numSamples);
outputLayer.process(skipData.getWritePointer(0), numSamples);
copyOutputData(outputData, numSamples);
}
int WaveNet::idx(int ch, int i, int numSamples)
{
return ch * numSamples + i;
}
void WaveNet::setWeight(std::vector<float> W, int layerIdx, std::string name)
{
if (layerIdx < 0)
{
inputLayer.setWeight(W, name);
}
else if (layerIdx >= convStack.getNumLayers())
{
outputLayer.setWeight(W, name);
}
else
{
convStack.setWeight(W, layerIdx, name);
}
}
void WaveNet::setParams(int newInputChannels, int newOutputChannels, int newConvChannels,
int newFilterWidth, std::string newActivation,
std::vector<int> newDilations)
{
inputChannels = newInputChannels;
outputChannels = newOutputChannels;
activation = newActivation;
convolutionChannels = newConvChannels;
memoryChannels = Activations::isGated(activation) ? convolutionChannels * 2 : convolutionChannels;
filterWidth = newFilterWidth;
dilations = newDilations;
skipChannels = convolutionChannels * (int)dilations.size();
inputLayer.setParams(inputChannels, convolutionChannels, 1, 1, false, "linear");
outputLayer.setParams(skipChannels, outputChannels, 1, 1, false, "linear");
convStack.setParams(convolutionChannels, filterWidth, dilations, activation, true);
prepareToPlay(samplesPerBlock);
}
| 33.121951 | 102 | 0.664212 | [
"vector"
] |
a3c075a1c60949791d7a0609b98122c1f9359493 | 2,290 | cpp | C++ | doc/tutorial/introduction/introduction_align.cpp | dendisuhubdy/seqan3 | 6903e67267fe50907f377cca7ef3d51f1447c504 | [
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | doc/tutorial/introduction/introduction_align.cpp | dendisuhubdy/seqan3 | 6903e67267fe50907f377cca7ef3d51f1447c504 | [
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | doc/tutorial/introduction/introduction_align.cpp | dendisuhubdy/seqan3 | 6903e67267fe50907f377cca7ef3d51f1447c504 | [
"CC0-1.0",
"CC-BY-4.0"
] | null | null | null | #include <seqan3/io/sequence_file/output.hpp>
//! [sequence_input_include]
#include <seqan3/io/sequence_file/input.hpp> // for sequence_file_input
#include <seqan3/core/debug_stream.hpp> // for debug_stream
//! [sequence_input_include]
//! [alignment_include]
#include <tuple> // for std::make_pair
#include <seqan3/alignment/aligned_sequence/aligned_sequence_concept.hpp> // for alignment stream operator
#include <seqan3/alignment/pairwise/align_pairwise.hpp> // for align_pairwise
//! [alignment_include]
using namespace seqan3;
int main()
{
auto tmp_dir = std::filesystem::temp_directory_path();
std::string filename{tmp_dir/"seq.fasta"};
{
// Create a /tmp/my.fasta file.
sequence_file_output file_out{filename};
file_out.emplace_back("ACGTGATG"_dna4, std::string{"seq1"});
file_out.emplace_back("AGTGATACT"_dna4, std::string{"seq2"});
}
//! [sequence_input]
// Initialise a file input object with a FastA file.
sequence_file_input file_in{filename}; // filename: "seq.fasta"
// Retrieve the sequences and ids.
for (auto &[seq, id, qual] : file_in)
{
debug_stream << "ID: " << id << '\n';
debug_stream << "SEQ: " << seq << '\n';
debug_stream << "EMPTY QUAL." << qual << '\n'; // qual is empty for FastA files
}
//! [sequence_input]
std::vector<seqan3::dna5_vector> sequences{"ACGTGATG"_dna5, "AGTGATACT"_dna5};
//! [alignment]
// Call a pairwise alignment with edit distance and traceback.
for (auto && res : align_pairwise(std::tie(sequences[0], sequences[1]),
align_cfg::edit | align_cfg::result{with_alignment}))
{
// Print the resulting score and the alignment.
debug_stream << res.score() << '\n'; // => -4
debug_stream << res.alignment() << '\n'; // => 0 . :
// ACGTGATG--
// | |||||
// A-GTGATACT
}
//! [alignment]
std::filesystem::remove(filename);
return 0;
}
| 40.175439 | 106 | 0.552402 | [
"object",
"vector"
] |
a3c27acc066aaaad2a9ec53c0a0697c7677cd4ec | 43,771 | cpp | C++ | _studio/mfx_lib/decode/vp8/src/mfx_vp8_dec_decode_hw.cpp | walter-bai/oneVPL-intel-gpu | e139c5060ac5b0ab8b4be0025922688a3db9b082 | [
"MIT"
] | null | null | null | _studio/mfx_lib/decode/vp8/src/mfx_vp8_dec_decode_hw.cpp | walter-bai/oneVPL-intel-gpu | e139c5060ac5b0ab8b4be0025922688a3db9b082 | [
"MIT"
] | null | null | null | _studio/mfx_lib/decode/vp8/src/mfx_vp8_dec_decode_hw.cpp | walter-bai/oneVPL-intel-gpu | e139c5060ac5b0ab8b4be0025922688a3db9b082 | [
"MIT"
] | null | null | null | // Copyright (c) 2012-2020 Intel Corporation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#if defined(_MSC_VER) //MSVC compiler issue: complains about 'std::copy' with parameters that may be unsafe
#pragma warning(push)
#pragma warning(disable:4996)
#endif
#include <algorithm> /* for std::find on Linux/Android */
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#include "mfx_common.h"
#include "mfxvideo++int.h"
#if defined(MFX_ENABLE_VP8_VIDEO_DECODE)
#include "mfx_common_decode_int.h"
#include "mfx_vp8_dec_decode_hw.h"
#include "mfx_enc_common.h"
#include "mfx_vpx_dec_common.h"
#include "libmfx_core_vaapi.h"
#include "umc_va_base.h"
#include "vm_sys_info.h"
#include <va/va.h>
#include <va/va_dec_vp8.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include "mfx_vp8_dec_decode_common.h"
#define VP8_START_CODE_FOUND(ptr) ((ptr)[0] == 0x9d && (ptr)[1] == 0x01 && (ptr)[2] == 0x2a)
static void SetFrameType(const VP8Defs::vp8_FrameInfo &frame_info, mfxFrameSurface1 &surface_out)
{
auto extFrameInfo = reinterpret_cast<mfxExtDecodedFrameInfo *>(GetExtendedBuffer(surface_out.Data.ExtParam, surface_out.Data.NumExtParam, MFX_EXTBUFF_DECODED_FRAME_INFO));
if (extFrameInfo == nullptr)
return;
switch (frame_info.frameType)
{
case UMC::I_PICTURE:
extFrameInfo->FrameType = MFX_FRAMETYPE_I;
break;
case UMC::P_PICTURE:
extFrameInfo->FrameType = MFX_FRAMETYPE_P;
break;
default:
extFrameInfo->FrameType = MFX_FRAMETYPE_UNKNOWN;
}
}
VideoDECODEVP8_HW::VideoDECODEVP8_HW(VideoCORE *p_core, mfxStatus *sts)
: m_is_initialized(false)
, m_p_core(p_core)
, m_platform(MFX_PLATFORM_HARDWARE)
, m_init_w(0)
, m_init_h(0)
, m_in_framerate(0)
, m_frameOrder((mfxU16)MFX_FRAMEORDER_UNKNOWN)
, m_CodedCoeffTokenPartition(0)
, m_firstFrame(true)
, m_response()
, m_response_alien()
, m_stat()
, m_request()
, m_p_video_accelerator(NULL)
{
UMC_SET_ZERO(m_bs);
UMC_SET_ZERO(m_frame_info);
UMC_SET_ZERO(m_refresh_info);
UMC_SET_ZERO(m_frameProbs);
UMC_SET_ZERO(m_frameProbs_saved);
UMC_SET_ZERO(m_quantInfo);
gold_indx = 0;
altref_indx = 0;
lastrefIndex = 0;
if (sts)
*sts = MFX_ERR_NONE;
}
VideoDECODEVP8_HW::~VideoDECODEVP8_HW()
{
Close();
}
#ifdef _MSVC_LANG
#pragma warning (disable : 4189)
#endif
bool VideoDECODEVP8_HW::CheckHardwareSupport(VideoCORE *p_core, mfxVideoParam *p_video_param)
{
// IsGuidSupported checks p_video_param for nullptr
MFX_CHECK(p_core, false);
if (p_core->IsGuidSupported(sDXVA_Intel_ModeVP8_VLD, p_video_param) != MFX_ERR_NONE)
{
return false;
}
return true;
} // bool VideoDECODEVP8_HW::CheckHardwareSupport(VideoCORE *p_core, mfxVideoParam *p_video_param)
mfxStatus VideoDECODEVP8_HW::Init(mfxVideoParam *p_video_param)
{
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_API, "VideoDECODEVP8_HW::Init");
mfxStatus sts = MFX_ERR_NONE;
if (m_is_initialized)
return MFX_ERR_UNDEFINED_BEHAVIOR;
eMFXVAType vatype = m_p_core->GetVAType();
if(vatype == MFX_HW_D3D11)
{
return MFX_ERR_UNSUPPORTED;
}
m_platform = MFX_VP8_Utility::GetPlatform(m_p_core, p_video_param);
eMFXHWType type = m_p_core->GetHWType();
if (MFX_ERR_NONE > CheckVideoParamDecoders(p_video_param, type))
{
return MFX_ERR_INVALID_VIDEO_PARAM;
}
if(CheckHardwareSupport(m_p_core, p_video_param) == false)
{
return MFX_ERR_UNSUPPORTED;
}
if (MFX_VPX_Utility::CheckVideoParam(p_video_param, MFX_CODEC_VP8) == false)
{
return MFX_ERR_INVALID_VIDEO_PARAM;
}
m_on_init_video_params = *p_video_param;
m_init_w = p_video_param->mfx.FrameInfo.Width;
m_init_h = p_video_param->mfx.FrameInfo.Height;
if(m_on_init_video_params.mfx.FrameInfo.FrameRateExtN == 0 || m_on_init_video_params.mfx.FrameInfo.FrameRateExtD == 0)
{
m_on_init_video_params.mfx.FrameInfo.FrameRateExtD = 1000;
m_on_init_video_params.mfx.FrameInfo.FrameRateExtN = 30000;
}
m_in_framerate = (mfxF64) m_on_init_video_params.mfx.FrameInfo.FrameRateExtD / m_on_init_video_params.mfx.FrameInfo.FrameRateExtN;
m_video_params = m_on_init_video_params;
// allocate memory
mfxFrameAllocRequest request;
memset(&request, 0, sizeof(request));
memset(&m_response, 0, sizeof(m_response));
memset(&m_response_alien, 0, sizeof(m_response_alien));
sts = MFX_VPX_Utility::QueryIOSurfInternal(&m_video_params, &request);
MFX_CHECK_STS(sts);
mfxFrameAllocRequest request_internal = request;
request.AllocId = p_video_param->AllocId;
MFX_CHECK_STS(sts);
m_request = request;
try
{
m_surface_source.reset(new SurfaceSource(m_p_core, *p_video_param, m_platform, request, request_internal, m_response, m_response_alien));
}
catch (const mfx::mfxStatus_exception& ex)
{
MFX_CHECK_STS(ex.sts);
}
sts = m_p_core->CreateVA(&m_on_init_video_params, &request, &m_response, m_surface_source.get());
MFX_CHECK_STS(sts);
UMC::Status umcSts = UMC::UMC_OK;
bool isUseExternalFrames = (p_video_param->IOPattern & MFX_IOPATTERN_OUT_VIDEO_MEMORY);
m_p_core->GetVA((mfxHDL*)&m_p_video_accelerator, MFX_MEMTYPE_FROM_DECODE);
m_frameOrder = (mfxU16)0;
m_firstFrame = true;
m_is_initialized = true;
return MFX_ERR_NONE;
} // mfxStatus VideoDECODEVP8_HW::Init(mfxVideoParam *p_video_param)
mfxStatus VideoDECODEVP8_HW::QueryImplsDescription(
VideoCORE&,
mfxDecoderDescription::decoder& caps,
mfx::PODArraysHolder& ah)
{
const mfxU32 SupportedProfiles[] =
{
MFX_PROFILE_VP8_0
, MFX_PROFILE_VP8_1
, MFX_PROFILE_VP8_2
, MFX_PROFILE_VP8_3
};
const mfxResourceType SupportedMemTypes[] =
{
MFX_RESOURCE_SYSTEM_SURFACE
, MFX_RESOURCE_VA_SURFACE
};
const mfxU32 SupportedFourCC[] =
{
MFX_FOURCC_NV12
};
caps.CodecID = MFX_CODEC_VP8;
caps.MaxcodecLevel = MFX_LEVEL_UNKNOWN;
mfxStatus sts = MFX_ERR_NONE;
for (mfxU32 profile : SupportedProfiles)
{
auto& pfCaps = ah.PushBack(caps.Profiles);
pfCaps.Profile = profile;
for (auto memType : SupportedMemTypes)
{
auto& memCaps = ah.PushBack(pfCaps.MemDesc);
memCaps.MemHandleType = memType;
memCaps.Width = { 16, 4096, 16 };
memCaps.Height = { 16, 4096, 16 };
for (auto fcc : SupportedFourCC)
{
ah.PushBack(memCaps.ColorFormats) = fcc;
++memCaps.NumColorFormats;
}
++pfCaps.NumMemTypes;
}
++caps.NumProfiles;
}
return MFX_ERR_NONE;
}
static bool IsSameVideoParam(mfxVideoParam *newPar, mfxVideoParam *oldPar)
{
if (newPar->IOPattern != oldPar->IOPattern)
return false;
if (newPar->Protected != oldPar->Protected)
return false;
int32_t asyncDepth = std::min<int32_t>(newPar->AsyncDepth, MFX_MAX_ASYNC_DEPTH_VALUE);
if (asyncDepth != oldPar->AsyncDepth)
return false;
if (newPar->mfx.FrameInfo.Height != oldPar->mfx.FrameInfo.Height)
return false;
if (newPar->mfx.FrameInfo.Width != oldPar->mfx.FrameInfo.Width)
return false;
if (newPar->mfx.FrameInfo.ChromaFormat != oldPar->mfx.FrameInfo.ChromaFormat)
return false;
if (newPar->mfx.NumThread > oldPar->mfx.NumThread && oldPar->mfx.NumThread > 0) // need more surfaces for efficient decoding
return false;
return true;
}
mfxStatus VideoDECODEVP8_HW::Reset(mfxVideoParam *p_video_param)
{
if(m_is_initialized == false)
return MFX_ERR_NOT_INITIALIZED;
MFX_CHECK_NULL_PTR1(p_video_param);
eMFXHWType type = m_p_core->GetHWType();
if (MFX_ERR_NONE > CheckVideoParamDecoders(p_video_param, type))
MFX_RETURN(MFX_ERR_INVALID_VIDEO_PARAM);
if (MFX_VPX_Utility::CheckVideoParam(p_video_param, MFX_CODEC_VP8) == false)
MFX_RETURN(MFX_ERR_INVALID_VIDEO_PARAM);
if (!IsSameVideoParam(p_video_param, &m_on_init_video_params))
MFX_RETURN(MFX_ERR_INCOMPATIBLE_VIDEO_PARAM);
// need to sw acceleration
if (m_platform != m_p_core->GetPlatformType())
MFX_RETURN(MFX_ERR_INCOMPATIBLE_VIDEO_PARAM);
if (m_surface_source->Reset() != UMC::UMC_OK)
MFX_RETURN(MFX_ERR_MEMORY_ALLOC);
m_frameOrder = (mfxU16)0;
memset(&m_stat, 0, sizeof(m_stat));
m_on_init_video_params = *p_video_param;
m_video_params = m_on_init_video_params;
if (m_on_init_video_params.mfx.FrameInfo.FrameRateExtN == 0 || m_on_init_video_params.mfx.FrameInfo.FrameRateExtD == 0)
{
m_on_init_video_params.mfx.FrameInfo.FrameRateExtD = 1000;
m_on_init_video_params.mfx.FrameInfo.FrameRateExtN = 30000;
}
m_in_framerate = (mfxF64) m_on_init_video_params.mfx.FrameInfo.FrameRateExtD / m_on_init_video_params.mfx.FrameInfo.FrameRateExtN;
if(CheckHardwareSupport(m_p_core, p_video_param) == false)
{
//return MFX_WRN_PARTIAL_ACCELERATION;
}
gold_indx = 0;
altref_indx = 0;
lastrefIndex = 0;
m_bs.DataLength = 0;
for(size_t i = 0; i < m_frames.size(); i++)
{
m_surface_source.get()->DecreaseReference(m_frames[i].memId);
}
m_firstFrame = true;
m_frames.clear();
m_memIdReadyToFree.clear();
return MFX_ERR_NONE;
} // mfxStatus VideoDECODEVP8_HW::Reset(mfxVideoParam *p_video_param)
mfxStatus VideoDECODEVP8_HW::Close()
{
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_API, "VideoDECODEVP8_HW::Close");
if(m_is_initialized == false)
return MFX_ERR_NOT_INITIALIZED;
m_is_initialized = false;
m_surface_source->Close();
m_frameOrder = (mfxU16)0;
m_p_video_accelerator = 0;
memset(&m_stat, 0, sizeof(m_stat));
if (m_bs.Data)
{
delete[] m_bs.Data;
m_bs.DataLength = 0;
}
gold_indx = 0;
altref_indx = 0;
lastrefIndex = 0;
m_firstFrame = true;
return MFX_ERR_NONE;
} // mfxStatus VideoDECODEVP8_HW::Close()
mfxStatus VideoDECODEVP8_HW::Query(VideoCORE *p_core, mfxVideoParam *p_in, mfxVideoParam *p_out)
{
MFX_CHECK_NULL_PTR1(p_out);
eMFXHWType type = p_core->GetHWType();
if (!CheckHardwareSupport(p_core, p_in ? p_in : p_out))
{
return MFX_ERR_UNSUPPORTED;
}
return MFX_VP8_Utility::Query(p_core, p_in, p_out, type);
} // mfxStatus VideoDECODEVP8_HW::Query(VideoCORE *p_core, mfxVideoParam *p_in, mfxVideoParam *p_out)
mfxStatus VideoDECODEVP8_HW::QueryIOSurf(VideoCORE *p_core, mfxVideoParam *p_video_param, mfxFrameAllocRequest *p_request)
{
mfxStatus sts = MFX_ERR_NONE;
MFX_CHECK_NULL_PTR3(p_core, p_video_param, p_request);
mfxVideoParam p_params = *p_video_param;
if ( !(p_params.IOPattern & MFX_IOPATTERN_OUT_VIDEO_MEMORY)
&& !(p_params.IOPattern & MFX_IOPATTERN_OUT_SYSTEM_MEMORY))
{
return MFX_ERR_INVALID_VIDEO_PARAM;
}
if ((p_params.IOPattern & MFX_IOPATTERN_OUT_VIDEO_MEMORY)
&& (p_params.IOPattern & MFX_IOPATTERN_OUT_SYSTEM_MEMORY))
{
return MFX_ERR_INVALID_VIDEO_PARAM;
}
if(p_params.IOPattern & MFX_IOPATTERN_OUT_SYSTEM_MEMORY)
{
p_request->Info = p_params.mfx.FrameInfo;
p_request->NumFrameMin = 1;
p_request->NumFrameSuggested = p_request->NumFrameMin + (p_params.AsyncDepth ? p_params.AsyncDepth : MFX_AUTO_ASYNC_DEPTH_VALUE);
p_request->Type = MFX_MEMTYPE_SYSTEM_MEMORY | MFX_MEMTYPE_EXTERNAL_FRAME | MFX_MEMTYPE_FROM_DECODE;
}
else
{
sts = MFX_VPX_Utility::QueryIOSurfInternal(p_video_param, p_request);
}
if (!CheckHardwareSupport(p_core, p_video_param))
{
return MFX_ERR_UNSUPPORTED;
}
return sts;
} // mfxStatus VideoDECODEVP8_HW::QueryIOSurf(VideoCORE *p_core, mfxVideoParam *p_par, mfxFrameAllocRequest *p_request)
mfxStatus VideoDECODEVP8_HW::DecodeFrameCheck(mfxBitstream * /*p_bs*/, mfxFrameSurface1 * /*p_surface_work*/, mfxFrameSurface1 ** /*pp_surface_out*/)
{
return MFX_ERR_NONE;
} // mfxStatus VideoDECODEVP8_HW::DecodeFrameCheck(mfxBitstream *p_bs, mfxFrameSurface1 *p_surface_work, mfxFrameSurface1 **pp_surface_out)
mfxStatus VideoDECODEVP8_HW::GetOutputSurface(mfxFrameSurface1 **pp_surface_out, mfxFrameSurface1 *p_surface_work, UMC::FrameMemID index)
{
mfxFrameSurface1 *p_native_surface = m_surface_source->GetSurface(index, p_surface_work, &m_video_params);
(void)pp_surface_out;
if (!p_native_surface)
{
return MFX_ERR_UNDEFINED_BEHAVIOR;
}
return MFX_ERR_NONE;
}
#define VP8_START_CODE_FOUND(ptr) ((ptr)[0] == 0x9d && (ptr)[1] == 0x01 && (ptr)[2] == 0x2a)
mfxStatus VideoDECODEVP8_HW::PreDecodeFrame(mfxBitstream *p_bs, mfxU32& w, mfxU32& h)
{
mfxU8 *p_bitstream = p_bs->Data + p_bs->DataOffset;
mfxU8 *p_bitstream_end = p_bs->Data + p_bs->DataOffset + p_bs->DataLength;
while (p_bitstream < p_bitstream_end)
{
if (VP8_START_CODE_FOUND(p_bitstream)) // (0x9D && 0x01 && 0x2A)
{
break;
}
p_bitstream += 1;
}
w = ((p_bitstream[4] << 8) | p_bitstream[3]) & 0x3fff;
h = ((p_bitstream[6] << 8) | p_bitstream[5]) & 0x3fff;
w = (w + 15) & ~0x0f;
h = (h + 15) & ~0x0f;
if (m_init_w != w || m_init_h != h)
{
return MFX_ERR_INCOMPATIBLE_VIDEO_PARAM;
}
return MFX_ERR_NONE;
} // mfxStatus VideoDECODEVP8_HW::PreDecodeFrame(mfxBitstream *p_bs, mfxFrameSurface1 *p_surface)
mfxStatus VideoDECODEVP8_HW::ConstructFrame(mfxBitstream *p_in, mfxBitstream *p_out, VP8DecodeCommon::IVF_FRAME& frame)
{
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_HOTSPOTS, "VideoDECODEVP8_HW::ConstructFrame");
MFX_CHECK_NULL_PTR1(p_out);
if (p_in->DataLength == 0)
{
return MFX_ERR_MORE_DATA;
}
mfxU8 *p_bs_start = p_in->Data + p_in->DataOffset;
if (p_out->Data)
{
delete[] p_out->Data;
p_out->DataLength = 0;
}
p_out->Data = new uint8_t[p_in->DataLength];
std::copy(p_bs_start, p_bs_start + p_in->DataLength, p_out->Data);
p_out->DataLength = p_in->DataLength;
p_out->DataOffset = 0;
frame.frame_size = p_in->DataLength;
MoveBitstreamData(*p_in, p_in->DataLength);
return MFX_ERR_NONE;
} // mfxStatus VideoDECODEVP8_HW::ConstructFrame(mfxBitstream *p_in, mfxBitstream *p_out, IVF_FRAME& frame)
UMC::FrameMemID VideoDECODEVP8_HW::GetMemIdToUnlock()
{
size_t size = m_frames.size();
if(size == 1)
{
return -1;
}
UMC::FrameMemID memId = -1;
sFrameInfo info = {};
std::vector<sFrameInfo>::iterator i;
std::vector<UMC::FrameMemID>::iterator freeMemIdPos;
for(i = m_frames.begin();i != m_frames.end() && (i + 1) != m_frames.end();i++)
{
freeMemIdPos = std::find(m_memIdReadyToFree.begin(), m_memIdReadyToFree.end(), i->memId);
if(i->currIndex != gold_indx && i->currIndex != altref_indx && freeMemIdPos != m_memIdReadyToFree.end())
{
info = *i;
memId = info.memId;
m_frames.erase(i);
m_memIdReadyToFree.erase(freeMemIdPos);
break;
}
}
if(memId == -1) return -1;
return memId;
}
mfxStatus MFX_CDECL VP8DECODERoutine(void *p_state, void * /*pp_param*/, mfxU32 /*thread_number*/, mfxU32)
{
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_API, "VP8DECODERoutine");
mfxStatus sts = MFX_ERR_NONE;
VideoDECODEVP8_HW::VP8DECODERoutineData& data = *(VideoDECODEVP8_HW::VP8DECODERoutineData*)p_state;
VideoDECODEVP8_HW& decoder = *data.decoder;
{
UMC::Status status = decoder.m_p_video_accelerator->SyncTask(data.memId);
if (status != UMC::UMC_OK && status != UMC::UMC_ERR_TIMEOUT)
{
mfxStatus CriticalErrorStatus = (status == UMC::UMC_ERR_GPU_HANG) ? MFX_ERR_GPU_HANG : MFX_ERR_DEVICE_FAILED;
decoder.SetCriticalErrorOccured(CriticalErrorStatus);
return CriticalErrorStatus;
}
}
if (decoder.m_video_params.IOPattern & MFX_IOPATTERN_OUT_SYSTEM_MEMORY && data.surface_work)
{
sts = decoder.m_surface_source->PrepareToOutput(data.surface_work, data.memId, &decoder.m_on_init_video_params);
}
if(data.surface_work)
MFX_CHECK(!decoder.m_p_video_accelerator->UnwrapBuffer(data.surface_work->Data.MemId), MFX_ERR_UNDEFINED_BEHAVIOR);
UMC::AutomaticUMCMutex guard(decoder.m_mGuard);
decoder.m_memIdReadyToFree.push_back(data.memId);
UMC::FrameMemID memIdToUnlock = -1;
while ((memIdToUnlock = decoder.GetMemIdToUnlock()) != -1)
{
decoder.m_surface_source.get()->DecreaseReference(memIdToUnlock);
}
delete &data;
return sts;
}
static mfxStatus VP8CompleteProc(void *, void * /*pp_param*/, mfxStatus)
{
return MFX_ERR_NONE;
}
mfxStatus VideoDECODEVP8_HW::DecodeFrameCheck(mfxBitstream *p_bs, mfxFrameSurface1 *p_surface_work, mfxFrameSurface1 **pp_surface_out, MFX_ENTRY_POINT * p_entry_point)
{
UMC::AutomaticUMCMutex guard(m_mGuard);
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_HOTSPOTS, "VideoDECODEVP8_HW::DecodeFrameCheck");
mfxStatus sts = MFX_ERR_NONE;
if(m_is_initialized == false)
{
return MFX_ERR_NOT_INITIALIZED;
}
if (NeedToReturnCriticalStatus(p_bs))
return ReturningCriticalStatus();
bool allow_null_work_surface = Supports20FeatureSet(*m_p_core);
if (allow_null_work_surface)
{
MFX_CHECK_NULL_PTR1(pp_surface_out);
}
else
{
MFX_CHECK_NULL_PTR2(p_surface_work, pp_surface_out);
}
if (p_surface_work)
{
sts = CheckFrameInfoCodecs(&p_surface_work->Info, MFX_CODEC_VP8);
MFX_CHECK_STS(sts);
sts = CheckFrameData(p_surface_work);
MFX_CHECK_STS(sts);
}
UMC::FrameMemID memId;
do
{
sts = p_bs ? CheckBitstream(p_bs) : MFX_ERR_NONE;
MFX_CHECK_STS(sts);
if (p_bs == NULL)
return MFX_ERR_MORE_DATA;
bool show_frame;
UMC::FrameType frame_type;
if (p_bs->DataLength == 0)
return MFX_ERR_MORE_DATA;
sts = m_surface_source->SetCurrentMFXSurface(p_surface_work);
MFX_CHECK_STS(sts);
if (!m_surface_source->HasFreeSurface())
{
return MFX_WRN_DEVICE_BUSY;
}
mfxU8 *pTemp = p_bs->Data + p_bs->DataOffset;
frame_type = (pTemp[0] & 1) ? UMC::P_PICTURE : UMC::I_PICTURE; // 1 bits
show_frame = (pTemp[0] >> 4) & 0x1;
mfxU32 bs_width = 0;
mfxU32 bs_height = 0;
if (frame_type == UMC::I_PICTURE)
{
sts = PreDecodeFrame(p_bs, bs_width, bs_height);
MFX_CHECK_STS(sts);
}
if (m_firstFrame && frame_type != UMC::I_PICTURE)
{
MoveBitstreamData(*p_bs, p_bs->DataLength);
return MFX_ERR_MORE_DATA;
}
m_firstFrame = false;
VP8DecodeCommon::IVF_FRAME frame;
memset(&frame, 0, sizeof(VP8DecodeCommon::IVF_FRAME));
sts = ConstructFrame(p_bs, &m_bs, frame);
MFX_CHECK_STS(sts);
*pp_surface_out = 0;
sts = DecodeFrameHeader(&m_bs);
MFX_CHECK_STS(sts);
UMC::VideoDataInfo vdInfo;
vdInfo.Init(m_frame_info.frameSize.width, m_frame_info.frameSize.height, UMC::NV12, 8);
UMC::Status umc_sts = m_surface_source->Alloc(&memId, &vdInfo, 0);
MFX_CHECK(umc_sts == UMC::UMC_OK, MFX_ERR_MEMORY_ALLOC);
if (!p_surface_work && m_on_init_video_params.IOPattern & MFX_IOPATTERN_OUT_VIDEO_MEMORY)
{
p_surface_work = m_surface_source->GetSurfaceByIndex(memId);
MFX_CHECK_NULL_PTR1(p_surface_work);
}
if (p_surface_work)
{
p_surface_work->Info.CropW = p_surface_work->Info.CropW ? p_surface_work->Info.CropW : m_on_init_video_params.mfx.FrameInfo.CropW;
p_surface_work->Info.CropH = p_surface_work->Info.CropH ? p_surface_work->Info.CropH : m_on_init_video_params.mfx.FrameInfo.CropH;
MFX_CHECK(p_surface_work->Info.Width >= bs_width && p_surface_work->Info.Height >= bs_height, MFX_ERR_INCOMPATIBLE_VIDEO_PARAM)
}
sFrameInfo info;
info.frameType = m_frame_info.frameType;
info.memId = memId;
info.currIndex = static_cast<mfxU16>(memId);
info.goldIndex = gold_indx;
info.altrefIndex = altref_indx;
info.lastrefIndex = lastrefIndex;
if (m_frame_info.frameType == UMC::I_PICTURE)
{
gold_indx = altref_indx = lastrefIndex = info.currIndex;
}
else
{
mfxU16 oldgold_indx = gold_indx;
switch (m_refresh_info.copy2Golden)
{
case 1:
gold_indx = lastrefIndex;
break;
case 2:
gold_indx = altref_indx;
break;
case 0:
default:
break;
}
switch (m_refresh_info.copy2Altref)
{
case 1:
altref_indx = lastrefIndex;
break;
case 2:
altref_indx = oldgold_indx;
break;
case 0:
default:
break;
}
if ((m_refresh_info.refreshRefFrame & 2) != 0)
gold_indx = info.currIndex;
if ((m_refresh_info.refreshRefFrame & 1) != 0)
altref_indx = info.currIndex;
if (m_refresh_info.refreshLastFrame)
lastrefIndex = info.currIndex;
}
m_frames.push_back(info);
m_surface_source->IncreaseReference(memId);
PackHeaders(&m_bs);
{
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_HOTSPOTS, "VP8 decode DDISubmitTask");
if (m_p_video_accelerator->BeginFrame(memId, 0) == UMC::UMC_OK)
{
m_p_video_accelerator->Execute();
m_p_video_accelerator->EndFrame();
}
}
if (show_frame)
{
sts = GetOutputSurface(pp_surface_out, p_surface_work, memId);
MFX_CHECK_STS(sts);
(*pp_surface_out)->Info.CropW = (*pp_surface_out)->Info.CropW ? (*pp_surface_out)->Info.CropW : m_on_init_video_params.mfx.FrameInfo.CropW;
(*pp_surface_out)->Info.CropH = (*pp_surface_out)->Info.CropH ? (*pp_surface_out)->Info.CropH : m_on_init_video_params.mfx.FrameInfo.CropH;
MFX_CHECK((*pp_surface_out)->Info.Width >= bs_width && (*pp_surface_out)->Info.Height >= bs_height, MFX_ERR_INCOMPATIBLE_VIDEO_PARAM)
SetFrameType(m_frame_info, **pp_surface_out);
}
else
{
sts = MFX_ERR_MORE_DATA_SUBMIT_TASK;
if (p_surface_work)
{
pp_surface_out = nullptr;
}
else
{
m_memIdReadyToFree.push_back(memId);
UMC::FrameMemID memIdToUnlock = -1;
while ((memIdToUnlock = GetMemIdToUnlock()) != -1)
{
m_surface_source.get()->DecreaseReference(memIdToUnlock);
}
}
}
} while (sts == MFX_ERR_MORE_DATA_SUBMIT_TASK && !p_surface_work);
if (pp_surface_out)
{
(*pp_surface_out)->Data.Corrupted = 0;
(*pp_surface_out)->Data.FrameOrder = m_frameOrder;
//(*pp_surface_out)->Data.FrameOrder = p_surface_work->Data.FrameOrder;
m_frameOrder++;
(*pp_surface_out)->Data.TimeStamp = p_bs->TimeStamp;
(*pp_surface_out)->Info.FrameRateExtD = m_on_init_video_params.mfx.FrameInfo.FrameRateExtD;
(*pp_surface_out)->Info.FrameRateExtN = m_on_init_video_params.mfx.FrameInfo.FrameRateExtN;
(*pp_surface_out)->Info.AspectRatioW = 1;
(*pp_surface_out)->Info.AspectRatioH = 1;
(*pp_surface_out)->Info.PicStruct = m_on_init_video_params.mfx.FrameInfo.PicStruct;
}
p_entry_point->pRoutine = &VP8DECODERoutine;
p_entry_point->pCompleteProc = &VP8CompleteProc;
VP8DECODERoutineData* routineData = new VP8DECODERoutineData;
routineData->decoder = this;
routineData->memId = memId;
if(pp_surface_out)
routineData->surface_work = *pp_surface_out;
p_entry_point->pState = routineData;
p_entry_point->requiredNumThreads = 1;
return sts;
} // mfxStatus VideoDECODEVP8_HW::DecodeFrameCheck(mfxBitstream *p_bs, mfxFrameSurface1 *p_surface_work, mfxFrameSurface1 **pp_surface_out, MFX_ENTRY_POINT *p_entry_point)
void VideoDECODEVP8_HW::UpdateSegmentation(MFX_VP8_BoolDecoder &dec)
{
uint32_t bits;
int32_t i;
int32_t j;
int32_t res;
bits = dec.decode(2);
m_frame_info.updateSegmentMap = (uint8_t)bits >> 1;
m_frame_info.updateSegmentData = (uint8_t)bits & 1;
if (m_frame_info.updateSegmentData)
{
m_frame_info.segmentAbsMode = (uint8_t)dec.decode();
UMC_SET_ZERO(m_frame_info.segmentFeatureData);
for (i = 0; i < VP8Defs::VP8_NUM_OF_MB_FEATURES; i++)
{
for (j = 0; j < VP8_MAX_NUM_OF_SEGMENTS; j++)
{
bits = (uint8_t)dec.decode();
if (bits)
{
bits = (uint8_t)dec.decode(8 - i); // 7 bits for ALT_QUANT, 6 - for ALT_LOOP_FILTER; +sign
res = bits >> 1;
if (bits & 1)
res = -res;
m_frame_info.segmentFeatureData[i][j] = (int8_t)res;
}
}
}
}
if (m_frame_info.updateSegmentMap)
{
for (i = 0; i < VP8_NUM_OF_SEGMENT_TREE_PROBS; i++)
{
bits = (uint8_t)dec.decode();
if (bits)
m_frame_info.segmentTreeProbabilities[i] = (uint8_t)dec.decode(8);
else
m_frame_info.segmentTreeProbabilities[i] = 255;
}
}
} // VideoDECODEVP8_HW::UpdateSegmentation()
void VideoDECODEVP8_HW::UpdateLoopFilterDeltas(MFX_VP8_BoolDecoder &dec)
{
uint8_t bits;
int32_t i;
int32_t res;
for (i = 0; i < VP8Defs::VP8_NUM_OF_REF_FRAMES; i++)
{
if (dec.decode())
{
bits = (uint8_t)dec.decode(7);
res = bits >> 1;
if (bits & 1)
res = -res;
m_frame_info.refLoopFilterDeltas[i] = (int8_t)res;
}
}
for (i = 0; i < VP8_NUM_OF_MODE_LF_DELTAS; i++)
{
if (dec.decode())
{
bits = (uint8_t)dec.decode(7);
res = bits >> 1;
if (bits & 1)
res = -res;
m_frame_info.modeLoopFilterDeltas[i] = (int8_t)res;
}
}
} // VideoDECODEVP8_HW::UpdateLoopFilterDeltas()
#define DECODE_DELTA_QP(dec, res, shift) \
{ \
uint32_t mask = (1 << (shift - 1)); \
int32_t val; \
if (bits & mask) \
{ \
bits = (bits << 5) | dec.decode(5); \
val = (int32_t)((bits >> shift) & 0xF); \
res = (bits & mask) ? -val : val; \
} \
}
void VideoDECODEVP8_HW::DecodeInitDequantization(MFX_VP8_BoolDecoder &dec)
{
m_quantInfo.yacQP = (int32_t)dec.decode(7);
m_quantInfo.ydcDeltaQP = 0;
m_quantInfo.y2dcDeltaQP = 0;
m_quantInfo.y2acDeltaQP = 0;
m_quantInfo.uvdcDeltaQP = 0;
m_quantInfo.uvacDeltaQP = 0;
uint32_t bits = (uint8_t)dec.decode(5);
if (bits)
{
DECODE_DELTA_QP(dec, m_quantInfo.ydcDeltaQP, 5)
DECODE_DELTA_QP(dec, m_quantInfo.y2dcDeltaQP, 4)
DECODE_DELTA_QP(dec, m_quantInfo.y2acDeltaQP, 3)
DECODE_DELTA_QP(dec, m_quantInfo.uvdcDeltaQP, 2)
DECODE_DELTA_QP(dec, m_quantInfo.uvacDeltaQP, 1)
}
int32_t qp;
for(int32_t segment_id = 0; segment_id < VP8_MAX_NUM_OF_SEGMENTS; segment_id++)
{
if (m_frame_info.segmentationEnabled)
{
if (m_frame_info.segmentAbsMode)
qp = m_frame_info.segmentFeatureData[VP8Defs::VP8_ALT_QUANT][segment_id];
else
{
qp = m_quantInfo.yacQP + m_frame_info.segmentFeatureData[VP8Defs::VP8_ALT_QUANT][segment_id];
qp = mfx::clamp(qp, 0, VP8_MAX_QP);
}
}
else
qp = m_quantInfo.yacQP;
m_quantInfo.yacQ[segment_id] = qp;
m_quantInfo.ydcQ[segment_id] = mfx::clamp(qp + m_quantInfo.ydcDeltaQP, 0, VP8_MAX_QP);
m_quantInfo.y2acQ[segment_id] = mfx::clamp(qp + m_quantInfo.y2acDeltaQP, 0, VP8_MAX_QP);
m_quantInfo.y2dcQ[segment_id] = mfx::clamp(qp + m_quantInfo.y2dcDeltaQP, 0, VP8_MAX_QP);
m_quantInfo.uvacQ[segment_id] = mfx::clamp(qp + m_quantInfo.uvacDeltaQP, 0, VP8_MAX_QP);
m_quantInfo.uvdcQ[segment_id] = mfx::clamp(qp + m_quantInfo.uvdcDeltaQP, 0, VP8_MAX_QP);
}
}
mfxStatus VideoDECODEVP8_HW::DecodeFrameHeader(mfxBitstream *in)
{
MFX_AUTO_LTRACE(MFX_TRACE_LEVEL_HOTSPOTS, "VideoDECODEVP8_HW::DecodeFrameHeader");
using namespace VP8Defs;
mfxU8* data_in = 0;
mfxU8* data_in_end = 0;
mfxU8 version;
int width = 0;
int height = 0;
data_in = (uint8_t*)in->Data;
if(!data_in)
return MFX_ERR_NULL_PTR;
data_in_end = data_in + in->DataLength;
//suppose that Intraframes -> I_PICTURE ( == VP8_KEY_FRAME)
// Interframes -> P_PICTURE
m_frame_info.frameType = (data_in[0] & 1) ? UMC::P_PICTURE : UMC::I_PICTURE; // 1 bits
version = (data_in[0] >> 1) & 0x7; // 3 bits
m_frame_info.version = version;
m_frame_info.showFrame = (data_in[0] >> 4) & 0x01; // 1 bits
switch (version)
{
case 1:
case 2:
m_frame_info.interpolationFlags = VP8_BILINEAR_INTERP;
break;
case 3:
m_frame_info.interpolationFlags = VP8_BILINEAR_INTERP | VP8_CHROMA_FULL_PEL;
break;
case 0:
default:
m_frame_info.interpolationFlags = 0;
break;
}
mfxU32 first_partition_size = (data_in[0] >> 5) | // 19 bit
(data_in[1] << 3) |
(data_in[2] << 11);
m_frame_info.firstPartitionSize = first_partition_size;
m_frame_info.partitionSize[VP8_FIRST_PARTITION] = first_partition_size;
data_in += 3;
if (!m_refresh_info.refreshProbabilities)
{
m_frameProbs = m_frameProbs_saved;
std::copy(reinterpret_cast<const char*>(vp8_default_mv_contexts),
reinterpret_cast<const char*>(vp8_default_mv_contexts) + sizeof(vp8_default_mv_contexts),
reinterpret_cast<char*>(m_frameProbs.mvContexts));
}
if (m_frame_info.frameType == UMC::I_PICTURE) // if VP8_KEY_FRAME
{
if (first_partition_size > in->DataLength - 10)
return MFX_ERR_MORE_DATA;
if (!(VP8_START_CODE_FOUND(data_in))) // (0x9D && 0x01 && 0x2A)
return MFX_ERR_UNKNOWN;
width = ((data_in[4] << 8) | data_in[3]) & 0x3FFF;
m_frame_info.h_scale = data_in[4] >> 6;
height = ((data_in[6] << 8) | data_in[5]) & 0x3FFF;
m_frame_info.v_scale = data_in[6] >> 6;
m_frame_info.frameSize.width = width;
m_frame_info.frameSize.height = height;
width = (m_frame_info.frameSize.width + 15) & ~0xF;
height = (m_frame_info.frameSize.height + 15) & ~0xF;
if (width != m_frame_info.frameWidth || height != m_frame_info.frameHeight)
{
m_frame_info.frameWidth = (int16_t)width;
m_frame_info.frameHeight = (int16_t)height;
}
data_in += 7;
std::copy(reinterpret_cast<const char*>(vp8_default_coeff_probs),
reinterpret_cast<const char*>(vp8_default_coeff_probs) + sizeof(vp8_default_coeff_probs),
reinterpret_cast<char*>(m_frameProbs.coeff_probs));
UMC_SET_ZERO(m_frame_info.segmentFeatureData);
m_frame_info.segmentAbsMode = 0;
UMC_SET_ZERO(m_frame_info.refLoopFilterDeltas);
UMC_SET_ZERO(m_frame_info.modeLoopFilterDeltas);
m_refresh_info.refreshRefFrame = 3; // refresh alt+gold
m_refresh_info.copy2Golden = 0;
m_refresh_info.copy2Altref = 0;
// restore default probabilities for Inter frames
for (int i = 0; i < VP8Defs::VP8_NUM_MB_MODES_Y - 1; i++)
m_frameProbs.mbModeProbY[i] = VP8Defs::vp8_mb_mode_y_probs[i];
for (int i = 0; i < VP8Defs::VP8_NUM_MB_MODES_UV - 1; i++)
m_frameProbs.mbModeProbUV[i] = VP8Defs::vp8_mb_mode_uv_probs[i];
// restore default MV contexts
std::copy(reinterpret_cast<const char*>(VP8Defs::vp8_default_mv_contexts),
reinterpret_cast<const char*>(VP8Defs::vp8_default_mv_contexts) + sizeof(VP8Defs::vp8_default_mv_contexts),
reinterpret_cast<char*>(m_frameProbs.mvContexts));
}
m_boolDecoder[VP8_FIRST_PARTITION].init(data_in, (int32_t) (data_in_end - data_in));
if (m_frame_info.frameType == UMC::I_PICTURE) // if VP8_KEY_FRAME
{
uint32_t bits = m_boolDecoder[VP8_FIRST_PARTITION].decode(2);
m_frame_info.color_space_type = (uint8_t)(bits >> 1);
m_frame_info.clamping_type = (uint8_t)(bits & 1);
// supported only color_space_type == 0
// see "VP8 Data Format and Decoding Guide" ch.9.2
if(m_frame_info.color_space_type)
return MFX_ERR_UNSUPPORTED;
}
m_frame_info.segmentationEnabled = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode();
if (m_frame_info.segmentationEnabled)
{
UpdateSegmentation(m_boolDecoder[VP8_FIRST_PARTITION]);
}
else
{
m_frame_info.updateSegmentData = 0;
m_frame_info.updateSegmentMap = 0;
}
mfxU8 bits = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(7);
m_frame_info.loopFilterType = bits >> 6;
m_frame_info.loopFilterLevel = bits & 0x3F;
bits = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(4);
m_frame_info.sharpnessLevel = bits >> 1;
m_frame_info.mbLoopFilterAdjust = bits & 1;
m_frame_info.modeRefLoopFilterDeltaUpdate = 0;
if (m_frame_info.mbLoopFilterAdjust)
{
m_frame_info.modeRefLoopFilterDeltaUpdate = (uint8_t)m_boolDecoder[VP8Defs::VP8_FIRST_PARTITION].decode();
if (m_frame_info.modeRefLoopFilterDeltaUpdate)
{
UpdateLoopFilterDeltas(m_boolDecoder[VP8_FIRST_PARTITION]);
}
}
mfxU32 partitions;
bits = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(2);
m_CodedCoeffTokenPartition = bits;
partitions = 1 << bits;
m_frame_info.numTokenPartitions = 1 << bits;
m_frame_info.numPartitions = m_frame_info.numTokenPartitions;
partitions = m_frame_info.numPartitions;
mfxU8 *pTokenPartition = data_in + first_partition_size;
if (partitions > 1)
{
m_frame_info.partitionStart[0] = pTokenPartition + (partitions - 1) * 3;
for (uint32_t i = 0; i < partitions - 1; i++)
{
m_frame_info.partitionSize[i] = (int32_t)(pTokenPartition[0]) |
(pTokenPartition[1] << 8) |
(pTokenPartition[2] << 16);
pTokenPartition += 3;
m_frame_info.partitionStart[i+1] = m_frame_info.partitionStart[i] + m_frame_info.partitionSize[i];
if (m_frame_info.partitionStart[i+1] > data_in_end)
return MFX_ERR_MORE_DATA; //???
m_boolDecoder[i + 1].init(m_frame_info.partitionStart[i], m_frame_info.partitionSize[i]);
}
}
else
{
m_frame_info.partitionStart[0] = pTokenPartition;
}
m_frame_info.partitionSize[partitions - 1] = int32_t(data_in_end - m_frame_info.partitionStart[partitions - 1]);
m_boolDecoder[partitions].init(m_frame_info.partitionStart[partitions - 1], m_frame_info.partitionSize[partitions - 1]);
DecodeInitDequantization(m_boolDecoder[VP8_FIRST_PARTITION]);
if (m_frame_info.frameType != UMC::I_PICTURE) // data in header for non-KEY frames
{
m_refresh_info.refreshRefFrame = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(2);
if (!(m_refresh_info.refreshRefFrame & 2))
m_refresh_info.copy2Golden = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(2);
if (!(m_refresh_info.refreshRefFrame & 1))
m_refresh_info.copy2Altref = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(2);
uint8_t bias = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(2);
m_refresh_info.refFrameBiasTable[1] = (bias & 1)^(bias >> 1); // ALTREF and GOLD (3^2 = 1)
m_refresh_info.refFrameBiasTable[2] = (bias & 1); // ALTREF and LAST
m_refresh_info.refFrameBiasTable[3] = (bias >> 1); // GOLD and LAST
}
m_refresh_info.refreshProbabilities = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode();
if (!m_refresh_info.refreshProbabilities)
m_frameProbs_saved = m_frameProbs;
if (m_frame_info.frameType != UMC::I_PICTURE)
{
m_refresh_info.refreshLastFrame = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode();
}
else
m_refresh_info.refreshLastFrame = 1;
for (int i = 0; i < VP8_NUM_COEFF_PLANES; i++)
{
for (int j = 0; j < VP8_NUM_COEFF_BANDS; j++)
{
for (int k = 0; k < VP8_NUM_LOCAL_COMPLEXITIES; k++)
{
for (int l = 0; l < VP8_NUM_COEFF_NODES; l++)
{
mfxU8 prob = vp8_coeff_update_probs[i][j][k][l];
mfxU8 flag = (uint8_t)m_boolDecoder[VP8Defs::VP8_FIRST_PARTITION].decode(1, prob);
if (flag)
m_frameProbs.coeff_probs[i][j][k][l] = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(8);
}
}
}
}
m_frame_info.mbSkipEnabled = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode();
m_frame_info.skipFalseProb = 0;
if (m_frame_info.mbSkipEnabled)
m_frame_info.skipFalseProb = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(8);
if (m_frame_info.frameType != UMC::I_PICTURE)
{
m_frame_info.intraProb = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(8);
m_frame_info.lastProb = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(8);
m_frame_info.goldProb = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(8);
if (m_boolDecoder[VP8_FIRST_PARTITION].decode())
{
int i = 0;
do
{
m_frameProbs.mbModeProbY[i] = uint8_t(m_boolDecoder[VP8_FIRST_PARTITION].decode(8));
}
while (++i < 4);
}
if (m_boolDecoder[VP8_FIRST_PARTITION].decode())
{
int i = 0;
do
{
m_frameProbs.mbModeProbUV[i] = uint8_t(m_boolDecoder[VP8_FIRST_PARTITION].decode(8));
}
while (++i < 3);
}
int i = 0;
do
{
mfxU8 *up = (uint8_t *)&vp8_mv_update_probs[i];
mfxU8 *p = m_frameProbs.mvContexts[i];
mfxU8 *pstop = p + 19;
do
{
if (m_boolDecoder[VP8_FIRST_PARTITION].decode(1, *up++))
{
const uint8_t x = (uint8_t)m_boolDecoder[VP8_FIRST_PARTITION].decode(7);
*p = x ? x << 1 : 1;
}
}
while (++p < pstop);
}
while (++i < 2);
}
// Header info consumed bits
m_frame_info.entropyDecSize = m_boolDecoder[VP8_FIRST_PARTITION].pos() * 8 - 3 * 8 - m_boolDecoder[VP8_FIRST_PARTITION].bitcount();
// Subtract completely consumed bytes + current byte. Current is completely consumed if bitcount is 8.
m_frame_info.firstPartitionSize = first_partition_size - ((m_frame_info.entropyDecSize + 7) >> 3);
return MFX_ERR_NONE;
}
mfxStatus VideoDECODEVP8_HW::GetFrame(UMC::MediaData* /*in*/, UMC::FrameData** /*out*/)
{
return MFX_ERR_NONE;
}
mfxTaskThreadingPolicy VideoDECODEVP8_HW::GetThreadingPolicy()
{
return MFX_TASK_THREADING_INTRA;
}
mfxStatus VideoDECODEVP8_HW::GetVideoParam(mfxVideoParam *pPar)
{
if (!m_is_initialized)
return MFX_ERR_NOT_INITIALIZED;
MFX_CHECK_NULL_PTR1(pPar);
pPar->mfx = m_on_init_video_params.mfx;
pPar->Protected = m_on_init_video_params.Protected;
pPar->IOPattern = m_on_init_video_params.IOPattern;
pPar->AsyncDepth = m_on_init_video_params.AsyncDepth;
pPar->mfx.FrameInfo.FrameRateExtD = m_on_init_video_params.mfx.FrameInfo.FrameRateExtD;
pPar->mfx.FrameInfo.FrameRateExtN = m_on_init_video_params.mfx.FrameInfo.FrameRateExtN;
pPar->mfx.FrameInfo.AspectRatioH = m_on_init_video_params.mfx.FrameInfo.AspectRatioH;
pPar->mfx.FrameInfo.AspectRatioW = m_on_init_video_params.mfx.FrameInfo.AspectRatioW;
return MFX_ERR_NONE;
}
mfxStatus VideoDECODEVP8_HW::GetDecodeStat(mfxDecodeStat *pStat)
{
if (!m_is_initialized)
return MFX_ERR_NOT_INITIALIZED;
MFX_CHECK_NULL_PTR1(pStat);
m_stat.NumSkippedFrame = 0;
m_stat.NumCachedFrame = 0;
*pStat = m_stat;
return MFX_ERR_NONE;
}
mfxStatus VideoDECODEVP8_HW::DecodeFrame(mfxBitstream *, mfxFrameSurface1 *, mfxFrameSurface1 *)
{
return MFX_ERR_NONE;
}
mfxStatus VideoDECODEVP8_HW::GetUserData(mfxU8 *pUserData, mfxU32 *pSize, mfxU64 *pTimeStamp)
{
if (!m_is_initialized)
return MFX_ERR_NOT_INITIALIZED;
MFX_CHECK_NULL_PTR3(pUserData, pSize, pTimeStamp);
return MFX_ERR_UNSUPPORTED;
}
mfxStatus VideoDECODEVP8_HW::GetPayload(mfxU64 *pTimeStamp, mfxPayload *pPayload)
{
if (!m_is_initialized)
return MFX_ERR_NOT_INITIALIZED;
MFX_CHECK_NULL_PTR3(pTimeStamp, pPayload, pPayload->Data);
return MFX_ERR_UNSUPPORTED;
}
mfxStatus VideoDECODEVP8_HW::SetSkipMode(mfxSkipMode /*mode*/)
{
if (!m_is_initialized)
return MFX_ERR_NOT_INITIALIZED;
return MFX_ERR_NONE;
}
mfxFrameSurface1* VideoDECODEVP8_HW::GetSurface()
{
if (!m_surface_source)
{
std::ignore = MFX_STS_TRACE(MFX_ERR_NOT_INITIALIZED);
return nullptr;
}
return m_surface_source->GetSurface();
}
//////////////////////////////////////////////////////////////////////////////
// MFX_VP8_BoolDecoder
const int MFX_VP8_BoolDecoder::range_normalization_shift[64] =
{
7, 6, 5, 5, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
#endif //MFX_ENABLE_VP8_VIDEO_DECODE
| 30.609091 | 175 | 0.651687 | [
"vector"
] |
a3c27ae5128ba767584dd6200d3f793113f7579a | 4,483 | cpp | C++ | fdbserver/workloads/PubSubMultiples.actor.cpp | akashhansda/foundationdb | ad98d6479992d2fcf1f89ff59d20945479a54cf1 | [
"Apache-2.0"
] | 1 | 2022-02-23T07:17:32.000Z | 2022-02-23T07:17:32.000Z | fdbserver/workloads/PubSubMultiples.actor.cpp | akashhansda/foundationdb | ad98d6479992d2fcf1f89ff59d20945479a54cf1 | [
"Apache-2.0"
] | null | null | null | fdbserver/workloads/PubSubMultiples.actor.cpp | akashhansda/foundationdb | ad98d6479992d2fcf1f89ff59d20945479a54cf1 | [
"Apache-2.0"
] | 1 | 2022-03-01T12:28:03.000Z | 2022-03-01T12:28:03.000Z | /*
* PubSubMultiples.actor.cpp
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2022 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "fdbclient/NativeAPI.actor.h"
#include "fdbserver/pubsub.h"
#include "fdbserver/TesterInterface.actor.h"
#include "fdbserver/workloads/workloads.actor.h"
#include "flow/actorcompiler.h" // This must be the last #include.
struct PubSubMultiplesWorkload : TestWorkload {
double testDuration, messagesPerSecond;
int actorCount, inboxesPerActor;
std::vector<Future<Void>> inboxWatchers;
PerfIntCounter messages;
PubSubMultiplesWorkload(WorkloadContext const& wcx) : TestWorkload(wcx), messages("Messages") {
testDuration = getOption(options, LiteralStringRef("testDuration"), 10.0);
messagesPerSecond = getOption(options, LiteralStringRef("messagesPerSecond"), 500.0) / clientCount;
actorCount = getOption(options, LiteralStringRef("actorsPerClient"), 20);
inboxesPerActor = getOption(options, LiteralStringRef("inboxesPerActor"), 20);
}
std::string description() const override { return "PubSubMultiplesWorkload"; }
Future<Void> setup(Database const& cx) override { return createNodes(this, cx); }
Future<Void> start(Database const& cx) override {
Future<Void> _ = startTests(this, cx);
return delay(testDuration);
}
Future<bool> check(Database const& cx) override { return true; }
void getMetrics(std::vector<PerfMetric>& m) override { m.push_back(messages.getMetric()); }
Key keyForFeed(int i) { return StringRef(format("/PSM/feeds/%d", i)); }
Key keyForInbox(int i) { return StringRef(format("/PSM/inbox/%d", i)); }
Value valueForUInt(uint64_t i) { return StringRef(format("%llx", i)); }
ACTOR Future<Void> createNodeSwath(PubSubMultiplesWorkload* self, int actor, Database cx) {
state PubSub ps(cx);
state std::vector<uint64_t> feeds;
state std::vector<uint64_t> inboxes;
state int idx;
for (idx = 0; idx < self->inboxesPerActor; idx++) {
uint64_t feedIdx = wait(ps.createFeed(StringRef()));
feeds.push_back(feedIdx);
uint64_t inboxIdx = wait(ps.createInbox(StringRef()));
inboxes.push_back(inboxIdx);
}
state Transaction tr(cx);
loop {
try {
for (int idx = 0; idx < self->inboxesPerActor; idx++) {
int offset = (self->clientId * self->clientCount * self->actorCount * self->inboxesPerActor) +
(actor * self->actorCount * self->inboxesPerActor) + idx;
tr.set(self->keyForFeed(offset), self->valueForUInt(feeds[idx]));
tr.set(self->keyForInbox(offset), self->valueForUInt(inboxes[idx]));
}
wait(tr.commit());
break;
} catch (Error& e) {
wait(tr.onError(e));
}
}
return Void();
}
ACTOR Future<Void> createNodes(PubSubMultiplesWorkload* self, Database cx) {
state PubSub ps(cx);
std::vector<Future<Void>> actors;
actors.reserve(self->actorCount);
for (int i = 0; i < self->actorCount; i++)
actors.push_back(self->createNodeSwath(self, i, cx->clone()));
wait(waitForAll(actors));
TraceEvent("PSMNodesCreated").detail("ClientIdx", self->clientId);
return Void();
}
/*ACTOR*/ Future<Void> createSubscriptions(PubSubMultiplesWorkload* self, int actor, Database cx) {
// create the "multiples" subscriptions for each owned inbox
return Void();
}
/*ACTOR*/ Future<Void> messageSender(PubSubMultiplesWorkload* self, Database cx) {
// use a possion loop and post messages to feeds
return Void();
}
ACTOR Future<Void> startTests(PubSubMultiplesWorkload* self, Database cx) {
std::vector<Future<Void>> subscribers;
subscribers.reserve(self->actorCount);
for (int i = 0; i < self->actorCount; i++)
subscribers.push_back(self->createSubscriptions(self, i, cx));
wait(waitForAll(subscribers));
state Future<Void> sender = self->messageSender(self, cx);
return Void();
}
};
WorkloadFactory<PubSubMultiplesWorkload> PubSubMultiplesWorkloadFactory("PubSubMultiples");
| 37.991525 | 101 | 0.721838 | [
"vector"
] |
a3c59a9539fe1ab1731ee4f803c505212df99137 | 4,946 | hh | C++ | src/Waffle/Contract/Http/Message/StreamInterface.hh | azjezz/waffle | 3a880ac4e7bd10739bc7134aaf1a531bfb623ba3 | [
"MIT"
] | 5 | 2018-11-27T20:20:13.000Z | 2018-12-28T15:30:35.000Z | src/Waffle/Contract/Http/Message/StreamInterface.hh | azjezz/waffle | 3a880ac4e7bd10739bc7134aaf1a531bfb623ba3 | [
"MIT"
] | 3 | 2018-12-13T19:11:09.000Z | 2018-12-21T01:11:51.000Z | src/Waffle/Contract/Http/Message/StreamInterface.hh | azjezz/waffle | 3a880ac4e7bd10739bc7134aaf1a531bfb623ba3 | [
"MIT"
] | null | null | null | <?hh // strict
namespace Waffle\Contract\Http\Message;
use const SEEK_SET;
/**
* Describes a data stream.
*
* Typically, an instance will wrap a Hack stream; this interface provides
* a wrapper around the most common operations, including serialization of
* the entire stream to a string.
*/
interface StreamInterface
{
/**
* Reads all data from the stream into a string, from the beginning to end.
*
* This method MUST attempt to seek to the beginning of the stream before
* reading data and read the stream until the end is reached.
*
* Warning: This could attempt to load a large amount of data into memory.
*
* This method MUST NOT raise an exception in order to conform with Hack's
* string casting operations.
*
* @see http://php.net/manual/en/language.oop5.magic.php#object.tostring
* @return string
*/
public function __toString(): string;
/**
* Closes the stream and any underlying resources.
*
* @return void
*/
public function close(): void;
/**
* Separates any underlying resources from the stream.
*
* After the stream has been detached, the stream is in an unusable state.
*
* @return resource|null Underlying Hack stream, if any
*/
public function detach(): ?resource;
/**
* Get the size of the stream if known.
*
* @return int|null Returns the size in bytes if known, or null if unknown.
*/
public function getSize(): ?int;
/**
* Returns the current position of the file read/write pointer
*
* @return int Position of the file pointer
* @throws \RuntimeException on error.
*/
public function tell(): int;
/**
* Returns true if the stream is at the end of the stream.
*
* @return bool
*/
public function eof(): bool;
/**
* Returns whether or not the stream is seekable.
*
* @return bool
*/
public function isSeekable(): bool;
/**
* Seek to a position in the stream.
*
* @link http://www.php.net/manual/en/function.fseek.php
* @param int $offset Stream offset
* @param int $whence Specifies how the cursor position will be calculated
* based on the seek offset. Valid values are identical to the built-in
* Hack $whence values for `fseek()`. SEEK_SET: Set position equal to
* offset bytes SEEK_CUR: Set position to current location plus offset
* SEEK_END: Set position to end-of-stream plus offset.
* @throws \RuntimeException on failure.
*/
public function seek(int $offset, int $whence = SEEK_SET): void;
/**
* Seek to the beginning of the stream.
*
* If the stream is not seekable, this method will raise an exception;
* otherwise, it will perform a seek(0).
*
* @see seek()
* @link http://www.php.net/manual/en/function.fseek.php
*
* @throws \RuntimeException on failure.
*/
public function rewind(): void;
/**
* Returns whether or not the stream is writable.
*
* @return bool
*/
public function isWritable(): bool;
/**
* Write data to the stream.
*
* @param string $string The string that is to be written.
* @return int Returns the number of bytes written to the stream.
* @throws \RuntimeException on failure.
*/
public function write(string $string): int;
/**
* Returns whether or not the stream is readable.
*
* @return bool
*/
public function isReadable(): bool;
/**
* Read data from the stream.
*
* @param int $length Read up to $length bytes from the object and return
* them. Fewer than $length bytes may be returned if underlying stream
* call returns fewer bytes.
* @return string Returns the data read from the stream, or an empty string
* if no bytes are available.
* @throws \RuntimeException if an error occurs.
*/
public function read(int $length): string;
/**
* Returns the remaining contents in a string
*
* @return string
* @throws \RuntimeException if unable to read or an error occurs while
* reading.
*/
public function getContents(): string;
/**
* Get stream metadata as an associative container or retrieve a specific key.
*
* The keys returned are identical to the keys returned from Hack's
* stream_get_meta_data() function.
*
* @link http://php.net/manual/en/function.stream-get-meta-data.php
* @param string $key Specific metadata to retrieve.
* @return Container<mixed>|mixed|null Returns an associative container if no key is
* provided. Returns a specific key value if a key is provided and the
* value is found, or null if the key is not found.
*/
public function getMetadata(?string $key = null): mixed;
}
| 30.530864 | 88 | 0.633846 | [
"object"
] |
a3cb3dea791be3a2d50ab8f99f937aa5ff18716b | 3,055 | cpp | C++ | snippets/cpp/VS_Snippets_CLR_System/system.Array.Sort/CPP/arraysort.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2020-02-22T09:30:21.000Z | 2021-08-02T23:44:31.000Z | snippets/cpp/VS_Snippets_CLR_System/system.Array.Sort/CPP/arraysort.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 555 | 2019-09-23T22:22:58.000Z | 2021-07-15T18:51:12.000Z | snippets/cpp/VS_Snippets_CLR_System/system.Array.Sort/CPP/arraysort.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 3 | 2020-01-29T16:31:15.000Z | 2021-08-24T07:00:15.000Z |
// The following example shows how to sort the values in an array using the default comparer
// and a custom comparer that reverses the sort order.
// <Snippet1>
using namespace System;
using namespace System::Collections;
public ref class ReverseComparer : IComparer
{
public:
// Call CaseInsensitiveComparer::Compare with the parameters reversed.
virtual int Compare(Object^ x, Object^ y) = IComparer::Compare
{
return ((gcnew CaseInsensitiveComparer)->Compare(y, x));
}
};
void DisplayValues(array<String^>^ arr)
{
for (int i = arr->GetLowerBound(0); i <= arr->GetUpperBound(0); i++)
Console::WriteLine( " [{0}] : {1}", i, arr[ i ] );
Console::WriteLine();
}
int main()
{
// Create and initialize a new array. and a new custom comparer.
array<String^>^ words = { "The","QUICK","BROWN","FOX","jumps",
"over","the","lazy","dog" };
// Instantiate the reverse comparer.
IComparer^ revComparer = gcnew ReverseComparer();
// Display the values of the Array.
Console::WriteLine( "The original order of elements in the array:" );
DisplayValues(words);
// Sort a section of the array using the default comparer.
Array::Sort(words, 1, 3);
Console::WriteLine( "After sorting elements 1-3 by using the default comparer:");
DisplayValues(words);
// Sort a section of the array using the reverse case-insensitive comparer.
Array::Sort(words, 1, 3, revComparer);
Console::WriteLine( "After sorting elements 1-3 by using the reverse case-insensitive comparer:");
DisplayValues(words);
// Sort the entire array using the default comparer.
Array::Sort(words);
Console::WriteLine( "After sorting the entire array by using the default comparer:");
DisplayValues(words);
// Sort the entire array by using the reverse case-insensitive comparer.
Array::Sort(words, revComparer);
Console::WriteLine( "After sorting the entire array using the reverse case-insensitive comparer:");
DisplayValues(words);
}
/*
This code produces the following output.
The Array initially contains the following values:
[0] : The
[1] : QUICK
[2] : BROWN
[3] : FOX
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the default comparer:
[0] : The
[1] : BROWN
[2] : FOX
[3] : QUICK
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting a section of the Array using the reverse case-insensitive comparer:
[0] : The
[1] : QUICK
[2] : FOX
[3] : BROWN
[4] : jumps
[5] : over
[6] : the
[7] : lazy
[8] : dog
After sorting the entire Array using the default comparer:
[0] : BROWN
[1] : dog
[2] : FOX
[3] : jumps
[4] : lazy
[5] : over
[6] : QUICK
[7] : the
[8] : The
After sorting the entire Array using the reverse case-insensitive comparer:
[0] : the
[1] : The
[2] : QUICK
[3] : over
[4] : lazy
[5] : jumps
[6] : FOX
[7] : dog
[8] : BROWN
*/
// </Snippet1>
| 25.458333 | 102 | 0.63437 | [
"object"
] |
a3ccae81e0369575ac94d2f9b57731e622fbb1ca | 15,215 | cpp | C++ | Experimental/Graphics/D3D12/Source/ExperimentalD3D12.cpp | All8Up/cpf | 81c68fbb69619261a5aa058cda73e35812ed3543 | [
"MIT"
] | 6 | 2017-02-15T01:50:32.000Z | 2019-07-05T13:50:57.000Z | Experimental/Graphics/D3D12/Source/ExperimentalD3D12.cpp | All8Up/cpf | 81c68fbb69619261a5aa058cda73e35812ed3543 | [
"MIT"
] | 40 | 2017-04-06T13:29:02.000Z | 2018-04-20T23:39:21.000Z | Experimental/Graphics/D3D12/Source/ExperimentalD3D12.cpp | All8Up/cpf | 81c68fbb69619261a5aa058cda73e35812ed3543 | [
"MIT"
] | 3 | 2017-08-03T15:17:01.000Z | 2019-03-08T07:58:59.000Z | //////////////////////////////////////////////////////////////////////////
#include "ExperimentalD3D12.hpp"
#include "CPF/Application/iWindowedApplication.hpp"
#include "CPF/Logging.hpp"
#include "IntrusivePtr.hpp"
#include "Resources/iConfiguration.hpp"
#include "Threading.hpp"
#include "Threading/Thread.hpp"
#include "Graphics.hpp"
#include "iDebugUI.hpp"
#include "Concurrency/iScheduler.hpp"
#include "Concurrency/iFence.hpp"
#include "Math/Constants.hpp"
#include "Math/Matrix33v.hpp"
#include "IO/IO.hpp"
#include "IO/File.hpp"
#include "IO/Directory.hpp"
#include "MovementSystem.hpp"
#include "RenderSystem.hpp"
#include "EntityService.hpp"
#include "EntityService/Interfaces/iEntity.hpp"
#include "EntityService/Interfaces/Components/iTransformComponent.hpp"
#include "MultiCore.hpp"
#include "SDL2/CIDs.hpp"
#include "VTune/VTune.hpp"
using namespace CPF;
using namespace Math;
using namespace Graphics;
using namespace Threading;
using namespace Concurrency;
VTUNE_DOMAIN(Frame, "Frame");
//////////////////////////////////////////////////////////////////////////
#define WINDOW_TITLE "Stress Test: D3D12"
void ExperimentalD3D12::ReconfigurePipeline()
{
mpMultiCore->Configure(GetRegistry());
}
GOM::Result CPF_STDCALL ExperimentalD3D12::Initialize(Plugin::iRegistry* registry, GOM::ClassID* appCid)
{
mpRegistry = registry;
*appCid = SDL2::kWindowedApplicationCID;
// Setup initial working directory.
auto exePath = IO::File::GetExecutableFilePath();
exePath += "../resources/";
IO::Directory::SetWorkingDirectory(exePath);
GetRegistry()->Load("plugins/Resources.cfp");
GetRegistry()->Load("plugins/AdapterSDL2.cfp");
GetRegistry()->Load("plugins/AdapterD3D12.cfp");
GetRegistry()->Load("plugins/Concurrency.cfp");
return GOM::kOK;
}
void CPF_STDCALL ExperimentalD3D12::Shutdown()
{
}
GOM::Result ExperimentalD3D12::Main(iApplication* application)
{
VTUNE_THREAD_NAME("Main");
application->QueryInterface(iWindowedApplication::kIID.GetID(), reinterpret_cast<void**>(&mpApplication));
// Initialize logging.
CPF_INIT_LOG(Experimental);
CPF_LOG_LEVEL(Experimental, Info);
// Initialize the io library.
ScopedInitializer<IOInitializer> ioInit;
CPF_INIT_MULTICORE(GetRegistry(), "plugins");
CPF_INIT_ENTITYSERVICE(GetRegistry(), "plugins");
GetRegistry()->Load("plugins/DebugUI.cfp");
// Hack: Setup the view all cheezy like.
mViewportSize = 1.0f;
mFOV = kDegToRad * 33.0f;
float halfFov = tan(mFOV / 2.0f);
mViewportSize = halfFov;
mAspectRatio = 1.0f;
//////////////////////////////////////////////////////////////////////////
GetRegistry()->Create(nullptr, EntityService::kManagerCID.GetID(), EntityService::iManager::kIID.GetID(), mpEntityManager.AsVoidPP());
//////////////////////////////////////////////////////////////////////////
// Install object components.
MoverSystem::MoverComponent::Install(GetRegistry());
//////////////////////////////////////////////////////////////////////////
GetRegistry()->Create(nullptr, MultiCore::kExecutionPlanCID.GetID(), MultiCore::iExecutionPlan::kIID.GetID(), mpMultiCore.AsVoidPP());
// Install the systems this will use.
RenderSystem::Install(GetRegistry());
InstanceSystem::Install(GetRegistry());
MoverSystem::Install(GetRegistry());
//////////////////////////////////////////////////////////////////////////
IntrusivePtr<MultiCore::iTimer> gameTime;
IntrusivePtr<RenderSystem> renderSystem;
IntrusivePtr<InstanceSystem> instanceSystem;
#if 0
//////////////////////////////////////////////////////////////////////////
RenderSystem::Desc renderDesc;
renderDesc.mTimerID = SystemRef("Game Time");
renderDesc.mpApplication = this;
InstanceSystem::Desc instanceDesc;
instanceDesc.mRenderSystemID = SystemRef("Render System");
instanceDesc.mpApplication = this;
MoverSystem::Desc moverDesc;
moverDesc.mpApplication = this;
moverDesc.mTimerID = SystemRef("Game Time");
moverDesc.mInstanceID = SystemRef("Instance System");
SystemCreateDesc systems[] =
{
{gameTime.AsVoidPP(), MultiCore::kTimerCID, "Game Time", nullptr},
{renderSystem.AsVoidPP(), kRenderSystemCID, "Render System", &renderDesc},
{instanceSystem.AsVoidPP(), kInstanceSystemCID, "Instance System", &instanceDesc},
{mpMoverSystem.AsVoidPP(), kMoverSystemCID, "Mover", &moverDesc}
};
if (GOM::Success(mpMultiCore->CreateSystems(4, systems)))
{
MultiCore::Dependency systemDependencies[] =
{
{
// Rendering begins only after instances are prepared.
renderSystem->GetBody(), instanceSystem->GetStart(),
MultiCore::DependencyPolicy::eAfter
},
{
// Instance system finalizes only after rendering is complete.
instanceSystem->GetEnd(), renderSystem->GetEnd(),
MultiCore::DependencyPolicy::eAfter
},
{
// Instance system finalizes only after mover system fills in the instance data.
instanceSystem->GetEnd(), mpMoverSystem->GetEnd(),
MultiCore::DependencyPolicy::eAfter
},
{
// Mover system fills in instance data only after instance system has prepared the internal buffers.
mpMoverSystem->GetBody(), instanceSystem->GetBody(),
MultiCore::DependencyPolicy::eAfter
},
{
// Movement update can only happen after time has advanced.
mpMoverSystem->GetBody(), gameTime->GetEnd(),
MultiCore::DependencyPolicy::eBarrier
}
}
if (GOM::Success(mpMultiCore->Configure(5, systemDependencies)))
{}
}
#endif
// Create the primary game timer.
GetRegistry()->Create(nullptr, MultiCore::kTimerCID.GetID(), MultiCore::iTimer::kIID.GetID(), gameTime.AsVoidPP());
gameTime->Initialize(GetRegistry(), "Game Time", nullptr);
mpMultiCore->Install(gameTime);
// Create the render system.
RenderSystem::Desc renderDesc;
renderDesc.mTimerID = gameTime->GetID();
renderDesc.mpApplication = this;
GetRegistry()->Create(nullptr, kRenderSystemCID.GetID(), RenderSystem::kIID.GetID(), renderSystem.AsVoidPP());
renderSystem->Initialize(GetRegistry(), "Render System", &renderDesc);
mpMultiCore->Install(renderSystem);
// Create the instance management system.
InstanceSystem::Desc instanceDesc;
instanceDesc.mRenderSystemID = renderSystem->GetID();
instanceDesc.mpApplication = this;
GetRegistry()->Create(nullptr, kInstanceSystemCID.GetID(), InstanceSystem::kIID.GetID(), instanceSystem.AsVoidPP());
instanceSystem->Initialize(GetRegistry(), "Instance System", &instanceDesc);
mpMultiCore->Install(instanceSystem);
// Create the mover system.
MoverSystem::Desc moverDesc;
moverDesc.mpApplication = this;
moverDesc.mTimerID = gameTime->GetID();
moverDesc.mInstanceID = instanceSystem->GetID();
GetRegistry()->Create(nullptr, kMoverSystemCID.GetID(), MoverSystem::kIID.GetID(), mpMoverSystem.AsVoidPP());
mpMoverSystem->Initialize(GetRegistry(), "Mover", &moverDesc);
mpMultiCore->Install(mpMoverSystem);
//////////////////////////////////////////////////////////////////////////
// Add the required inter-system dependencies.
// Render system needs to draw after instancing is complete.
renderSystem->AddDependency({
{ renderSystem->GetID(), RenderSystem::kDrawInstances, MultiCore::iStage::kExecute },
{ instanceSystem->GetID(), InstanceSystem::kEnd, MultiCore::iStage::kExecute },
MultiCore::DependencyPolicy::eAfter
});
// Instance system needs to begin after render system begin.
// Instance system needs to end after movement update.
instanceSystem->AddDependency({
{ instanceSystem->GetID(), InstanceSystem::kBegin, MultiCore::iStage::kExecute },
{ renderSystem->GetID(), RenderSystem::kBeginFrame, MultiCore::iStage::kExecute },
MultiCore::DependencyPolicy::eAfter
});
instanceSystem->AddDependency({
{ instanceSystem->GetID(), InstanceSystem::kEnd, MultiCore::iStage::kExecute },
{ mpMoverSystem->GetID(), MoverSystem::kUpdate, MultiCore::iStage::kExecute },
MultiCore::DependencyPolicy::eAfter
});
// Mover updates must happen after game time update and instance begin.
mpMoverSystem->AddDependency({
{ mpMoverSystem->GetID(), MoverSystem::kUpdate, MultiCore::iStage::kExecute },
{ gameTime->GetID(), MultiCore::iStage::kStageID, MultiCore::iStage::kExecute },
MultiCore::DependencyPolicy::eBarrier
});
mpMoverSystem->AddDependency({
{ mpMoverSystem->GetID(), MoverSystem::kUpdate, MultiCore::iStage::kExecute },
{ instanceSystem->GetID(), InstanceSystem::kBegin, MultiCore::iStage::kExecute },
MultiCore::DependencyPolicy::eAfter
});
//////////////////////////////////////////////////////////////////////////
// Everything is installed in the pipeline, configure it.
ReconfigurePipeline();
// Create test objects.
for (int i = 0; i<kInstanceCount; ++i)
{
IntrusivePtr<EntityService::iEntity> entity(mpEntityManager->CreateEntity());
entity->CreateComponent<EntityService::iTransformComponent>(GetRegistry(), EntityService::kTransformComponentCID, nullptr);
entity->CreateComponent<iMoverComponent>(GetRegistry(), kMoverComponentCID, mpMoverSystem);
}
//////////////////////////////////////////////////////////////////////////
// Create the virtual file system locator.
Resources::iConfiguration* pConfig = nullptr;
GetRegistry()->Create(nullptr, Resources::kConfigurationCID.GetID(), Resources::iConfiguration::kIID.GetID(), reinterpret_cast<void**>(&pConfig));
pConfig->Initialize(GetRegistry(), "./Experimental/resource_config.json");
mpLocator.Adopt(pConfig->GetLocator());
// mpLocator.Adopt(Resources::Configuration(GetRegistry(), "./Experimental/resource_config.json").GetLocator());
if (!mpLocator)
{
// Do something with configuration error.
}
{
_CreateWindow();
//////////////////////////////////////////////////////////////////////////
// Get an instance of the installed device from the graphics factory.
{
//////////////////////////////////////////////////////////////////////////
// Find graphics driver implementations.
int32_t typeCount = 0;
GOM::ClassID selectedAPI;
if (GOM::Succeeded(GetRegistry()->GetClasses(Graphics::iInstance::kIID.GetID(), &typeCount, nullptr)))
{
Vector<uint64_t> classes(typeCount);
if (GOM::Succeeded(GetRegistry()->GetClasses(Graphics::iInstance::kIID.GetID(), &typeCount, classes.data())))
{
if (typeCount > 0)
selectedAPI = GOM::ClassID(classes[0]);
}
}
IntrusivePtr<iInstance> gfxInstance;
GetRegistry()->Create(nullptr, selectedAPI.GetID(), Graphics::iInstance::kIID.GetID(), gfxInstance.AsVoidPP());
if (gfxInstance && GOM::Succeeded(gfxInstance->Initialize(GetRegistry())))
{
IntrusivePtr<iAdapter> adapter;
if (!_SelectAdapter(gfxInstance, adapter.AsTypePP()))
{
// Error...
}
// TODO: Should select an output and associate it during device creation for full screen modes.
if (!_EnumerateOutputs(adapter))
{
// Error...
}
// Create a device on the desired adapter.
gfxInstance->CreateDevice(adapter, mpDevice.AsTypePP());
//////////////////////////////////////////////////////////////////////////
if (!_CreateSwapChain(gfxInstance))
{
// Do something with the error.
}
//////////////////////////////////////////////////////////////////////////
// Create command buffers for the 'overall' frame. This sets up the rendering
// and performs the presents as the first and last submitted command lists.
for (int i = 0; i < mBackBufferCount; ++i)
{
mpDevice->CreateCommandPool(mpPreCommandPool[i].AsTypePP());
mpDevice->CreateCommandBuffer(mpPreCommandPool[i], CommandBufferType::ePrimary, mpPreCommandBuffer[i].AsTypePP());
}
if (!_CreateResources())
{
// Do something with the error.
}
//
GetRegistry()->Create(nullptr, kDebugUICID.GetID(), iDebugUI::kIID.GetID(), mpDebugUI.AsVoidPP());
//////////////////////////////////////////////////////////////////////////
// Start up the threading system.
// Allocates a command pool and buffer per thread.
GetRegistry()->Create(nullptr, kSchedulerCID.GetID(), iScheduler::kIID.GetID(), mpScheduler.AsVoidPP());
mpScheduler->Initialize(Thread::GetHardwareThreadCount(),
SCHEDULED_CALL(ExperimentalD3D12, &ExperimentalD3D12::_CreateWorkerData),
SCHEDULED_CALL(ExperimentalD3D12, &ExperimentalD3D12::_DestroyWorkerData),
this
);
mThreadCountChanged = false;
mThreadCount = mpScheduler->GetMaxThreads();
//////////////////////////////////////////////////////////////////////////
mStartTime = Time::Now();
mCurrentTime = Time::Now() - mStartTime;
// Currently only a single frame. Will Eventually match the number of back buffers and other resources.
IntrusivePtr<Concurrency::iFence> concurrencyFence;
GetRegistry()->Create(nullptr, Concurrency::kFenceCID.GetID(), Concurrency::iFence::kIID.GetID(), concurrencyFence.AsVoidPP());
concurrencyFence->Signal();
// Create a graphics fence to track back buffers.
mpDevice->CreateFence(0, mpFence.AsTypePP());
{
if (!mpDebugUI->Initialize(mpDevice, mpApplication->GetInputManager(), mpWindow, mpLocator))
{
CPF_LOG(Experimental, Info) << "Failed to initialize the debug UI.";
}
int32_t w, h;
mpWindow->GetClientAreaSize(&w, &h);
mpDebugUI->SetWindowSize(w, h);
//
_UpdatePipelineDisplay();
VTUNE_SYNC_CREATE("Main dispatch", this, VTune::SyncType::eMutex);
while (mpApplication->IsRunning())
{
//////////////////////////////////////////////////////////////////////////
// Wait for the last frame of processing.
VTUNE_BEGIN_FRAME(Frame);
VTUNE_SYNC_PREPARE(this);
concurrencyFence->Wait();
VTUNE_SYNC_ACQUIRED(this);
if (mThreadCountChanged)
{
mThreadCountChanged = false;
mpScheduler->SetActiveThreads(mThreadCount);
}
// Poll the application OS events.
// TODO: this is done in between frames so resize doesn't conflict.
// This will need to be overlap aware and that means that resize will need the ability
// to flush the pipeline.
mpApplication->Poll();
// Handle any issued work from the scheduler side which needs to run in the main thread.
for (; mReactor.RunOne();)
;
mFrameIndex.fetch_add(1);
mSubmissionIndex.store(mFrameIndex.load() * 3);
mCurrentScheduledBuffer.store(1);
mCurrentBackbuffer.store(mpSwapChain->GetCurrentIndex());
auto now = Time::Now() - mStartTime;
mDeltaTime = now - mCurrentTime;
mCurrentTime = now;
//////////////////////////////////////////////////////////////////////////
// Issue all the stages.
mpMultiCore->Submit(mpScheduler);
//////////////////////////////////////////////////////////////////////////
// Notify that the frame of processing is complete.
mpScheduler->Submit(concurrencyFence);
VTUNE_SYNC_RELEASING(this);
VTUNE_END_FRAME(Frame);
}
// Guarantee last frame is complete before we tear everything down.
concurrencyFence->Wait();
mpDebugUI->Shutdown();
}
// Destroy all the resources.
_DestroyResources();
}
gfxInstance.Assign(nullptr);
}
}
return GOM::kOK;
}
CPF_CREATE_APPMAIN(CPF::ExperimentalD3D12);
| 35.632319 | 147 | 0.655274 | [
"render",
"object",
"vector"
] |
a3d208a8439f7d2e9b40319fd759aa2965950add | 17,904 | cpp | C++ | samples/imvim/main.cpp | ousttrue/NvimTexture | a19219abcf0e057940a3ba3ed2d671c2ec1d6677 | [
"MIT"
] | null | null | null | samples/imvim/main.cpp | ousttrue/NvimTexture | a19219abcf0e057940a3ba3ed2d671c2ec1d6677 | [
"MIT"
] | null | null | null | samples/imvim/main.cpp | ousttrue/NvimTexture | a19219abcf0e057940a3ba3ed2d671c2ec1d6677 | [
"MIT"
] | null | null | null | // Dear ImGui: standalone example application for DirectX 11
// If you are new to Dear ImGui, read documentation from the docs/ folder + read
// the top of imgui.cpp. Read online:
// https://github.com/ocornut/imgui/tree/master/docs
#include <Windows.h>
#include <d3d11.h>
#include <dxgi1_2.h>
#include <imgui.h>
#include <imgui_impl_dx11.h>
#include <imgui_impl_win32.h>
#include <imgui_internal.h>
#include <nvim_frontend.h>
#include <nvim_grid.h>
#include <nvim_renderer_d2d.h>
#include <nvim_win32_key_processor.h>
#include <optional>
#include <plog/Appenders/DebugOutputAppender.h>
#include <plog/Formatters/TxtFormatter.h>
#include <plog/Init.h>
#include <plog/Log.h>
#include <tchar.h>
#include <wrl/client.h>
template <class T> using ComPtr = Microsoft::WRL::ComPtr<T>;
// Forward declare message handler from imgui_impl_win32.cpp
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd,
UINT msg,
WPARAM wparam,
LPARAM lparam);
NvimWin32KeyProcessor g_nvimKey;
// Win32 message handler
LRESULT WINAPI WndProc(HWND hwnd, UINT msg, WPARAM wparam, LPARAM lparam) {
if (msg == WM_CREATE) {
auto createStruct = reinterpret_cast<LPCREATESTRUCT>(lparam);
SetWindowLongPtr(hwnd, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(createStruct->lpCreateParams));
return 0;
}
auto p = GetWindowLongPtr(hwnd, GWLP_USERDATA);
if (p) {
auto nvim = reinterpret_cast<NvimFrontend *>(p);
uint64_t out;
if (g_nvimKey.ProcessMessage(
hwnd, msg, wparam, lparam,
[nvim](const Nvim::InputEvent &input) { nvim->Input(input); },
&out)) {
// TODO: require nvim focus control
// return out;
}
}
if (ImGui_ImplWin32_WndProcHandler(hwnd, msg, wparam, lparam))
return true;
switch (msg) {
case WM_SIZE:
return 0;
case WM_SYSCOMMAND:
if ((wparam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hwnd, msg, wparam, lparam);
}
class Win32Window {
WNDCLASSEX _wc = {0};
HWND _hwnd = nullptr;
public:
~Win32Window() {
::DestroyWindow(_hwnd);
::UnregisterClass(_wc.lpszClassName, _wc.hInstance);
}
HWND Create(void *p) {
// Create application window
// ImGui_ImplWin32_EnableDpiAwareness();
_wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L,
GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
_T("ImGui Example"), NULL};
::RegisterClassEx(&_wc);
_hwnd = ::CreateWindow(
_wc.lpszClassName, _T("Dear ImGui DirectX11 Example"),
WS_OVERLAPPEDWINDOW, 100, 100, 1280, 800, NULL, NULL, _wc.hInstance, p);
return _hwnd;
}
};
class D3DManager {
public:
ComPtr<ID3D11Device> _pd3dDevice;
ComPtr<ID3D11DeviceContext> _pd3dDeviceContext;
ComPtr<IDXGISwapChain> _pSwapChain;
ComPtr<ID3D11RenderTargetView> _mainRenderTargetView;
DXGI_SWAP_CHAIN_DESC _desc;
~D3DManager() {}
bool Create(HWND hwnd) {
// Setup swap chain
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 2;
sd.BufferDesc.Width = 0;
sd.BufferDesc.Height = 0;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hwnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
sd.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
UINT createDeviceFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; // require D2D
#ifndef NDEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_FEATURE_LEVEL featureLevel;
const D3D_FEATURE_LEVEL featureLevelArray[2] = {
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_0,
};
if (D3D11CreateDeviceAndSwapChain(
NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, createDeviceFlags,
featureLevelArray, 2, D3D11_SDK_VERSION, &sd, &_pSwapChain,
&_pd3dDevice, &featureLevel, &_pd3dDeviceContext) != S_OK) {
return false;
}
_pSwapChain->GetDesc(&_desc);
return true;
}
void PrepareBackbuffer(UINT w, UINT h, const float *clear_color_with_alpha) {
if (_desc.BufferDesc.Width != w || _desc.BufferDesc.Height != h) {
// resize
_mainRenderTargetView.Reset();
_pSwapChain->ResizeBuffers(0, w, h, DXGI_FORMAT_UNKNOWN, 0);
_pSwapChain->GetDesc(&_desc);
}
if (!_mainRenderTargetView) {
ComPtr<ID3D11Texture2D> pBackBuffer;
_pSwapChain->GetBuffer(0, IID_PPV_ARGS(&pBackBuffer));
_pd3dDevice->CreateRenderTargetView(pBackBuffer.Get(), NULL,
&_mainRenderTargetView);
}
_pd3dDeviceContext->OMSetRenderTargets(
1, _mainRenderTargetView.GetAddressOf(), NULL);
_pd3dDeviceContext->ClearRenderTargetView(_mainRenderTargetView.Get(),
clear_color_with_alpha);
}
void Present() {
_pSwapChain->Present(1, 0); // Present with vsync
// g_pSwapChain->Present(0, 0); // Present without vsync
ID3D11RenderTargetView *tmp[1] = {nullptr};
_pd3dDeviceContext->OMSetRenderTargets(1, tmp, NULL);
}
};
using RenderTargetRenderer_t =
std::function<ID3D11ShaderResourceView *(int w, int h)>;
using Input_t = std::function<void(const Nvim::InputEvent &e)>;
struct DockNode {
std::string name;
ImGuiDir dir = {};
float fraction = 0.5f;
std::vector<DockNode> children;
ImGuiID id = {};
void split();
};
void DockNode::split() {
ImGui::DockBuilderDockWindow(name.c_str(), id);
if (!children.empty()) {
auto &first = children.front();
auto &second = children.back();
ImGui::DockBuilderSplitNode(id, dir, fraction, &first.id, &second.id);
first.split();
second.split();
}
}
auto LEFT = "LEFT";
auto CENTER = "CENTER";
auto RIGHT = "RIGHT";
class DockingSpace {
ImGuiDockNodeFlags dockspace_flags = ImGuiDockNodeFlags_None;
bool _first_time = true;
DockNode _layout_root = {
"Root",
ImGuiDir_Left,
0.3f,
{
{LEFT},
{"Right", ImGuiDir_Right, 0.4f, {{RIGHT}, {CENTER}}},
}};
public:
DockingSpace() {}
void Initialize() {
// enable
ImGuiIO &io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable;
}
void Draw() {
ImGuiWindowFlags window_flags =
ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
const ImGuiViewport *viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->WorkPos);
ImGui::SetNextWindowSize(viewport->WorkSize);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse |
ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
window_flags |=
ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace", nullptr, window_flags);
ImGui::PopStyleVar(3);
ImGuiID dockspace_id = ImGui::GetID("MyDockSpace");
ImGui::DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags);
// menubar
if (ImGui::BeginMenuBar()) {
ImGui::EndMenuBar();
}
if (_first_time) {
// layout dock nodes
_first_time = false;
ImGui::DockBuilderRemoveNode(dockspace_id); // clear any previous layout
_layout_root.id = ImGui::DockBuilderAddNode(
dockspace_id, dockspace_flags | ImGuiDockNodeFlags_DockSpace);
ImGui::DockBuilderSetNodeSize(_layout_root.id, viewport->Size);
_layout_root.split();
}
ImGui::End();
}
};
class Gui {
// Our state
ImVec4 _clear_color = ImVec4(0.45f, 0.55f, 0.60f, 1.00f);
DockingSpace _dock_space;
public:
float clear_color_with_alpha[4] = {0};
Gui(HWND hwnd, ID3D11Device *device, ID3D11DeviceContext *context) {
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO &io = ImGui::GetIO();
(void)io;
// io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable
// Keyboard Controls io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; //
// Enable Gamepad Controls
_dock_space.Initialize();
// Setup Dear ImGui style
ImGui::StyleColorsDark();
// ImGui::StyleColorsClassic();
// Setup Platform/Renderer backends
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(device, context);
// Load Fonts
// - If no fonts are loaded, dear imgui will use the default font. You can
// also load multiple fonts and use ImGui::PushFont()/PopFont() to select
// them.
// - AddFontFromFileTTF() will return the ImFont* so you can store it if you
// need to select the font among multiple.
// - If the file cannot be loaded, the function will return NULL. Please
// handle those errors in your application (e.g. use an assertion, or
// display an error and quit).
// - The fonts will be rasterized at a given size (w/ oversampling) and
// stored into a texture when calling
// ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame
// below will call.
// - Read 'docs/FONTS.md' for more instructions and details.
// - Remember that in C/C++ if you want to include a backslash \ in a string
// literal you need to write a double backslash \\ !
// io.Fonts->AddFontDefault();
// io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
// io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
// io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
// io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
// ImFont* font =
// io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f,
// NULL, io.Fonts->GetGlyphRangesJapanese()); IM_ASSERT(font != NULL);
}
~Gui() {
// Cleanup
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
}
void Render(const RenderTargetRenderer_t &render, const Input_t &input) {
// Start the Dear ImGui frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
_dock_space.Draw();
// 2. Show a simple window that we create ourselves. We use a Begin/End pair
// to created a named window.
{
static float f = 0.0f;
static int counter = 0;
ImGui::Begin(LEFT); // Create a window called "Hello, world!"
// and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can
// use a format strings too)
ImGui::SliderFloat("float", &f, 0.0f,
1.0f); // Edit 1 float using a slider from 0.0f to 1.0f
ImGui::ColorEdit3(
"clear color",
(float *)&_clear_color); // Edit 3 floats representing a color
if (ImGui::Button("Button")) // Buttons return true when clicked (most
// widgets return true when edited/activated)
counter++;
ImGui::SameLine();
ImGui::Text("counter = %d", counter);
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)",
1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::End();
}
// 3. Show another simple window.
{
ImGui::Begin(RIGHT); // Pass a pointer to our bool variable (the
// window will have a closing button that will
// clear the bool when clicked)
ImGui::Text("Hello from another window!");
ImGui::End();
}
{
// View
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
if (ImGui::Begin(CENTER, nullptr,
ImGuiWindowFlags_NoScrollbar |
ImGuiWindowFlags_NoScrollWithMouse)) {
if (ImGui::IsWindowFocused()) {
// Input(ImGui::GetIO().KeysDown, input);
}
auto size = ImGui::GetContentRegionAvail();
auto pos = ImGui::GetWindowPos();
auto frameHeight = ImGui::GetFrameHeight();
auto renderTarget =
render(static_cast<int>(size.x), static_cast<int>(size.y));
if (renderTarget) {
ImGui::ImageButton((ImTextureID)renderTarget, size,
ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), 0);
}
}
ImGui::End();
ImGui::PopStyleVar();
}
// Rendering
ImGui::Render();
clear_color_with_alpha[0] = _clear_color.x * _clear_color.w;
clear_color_with_alpha[1] = _clear_color.y * _clear_color.w;
clear_color_with_alpha[2] = _clear_color.z * _clear_color.w;
clear_color_with_alpha[3] = _clear_color.w;
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
}
};
class Renderer {
ComPtr<ID3D11Device> _device;
ComPtr<ID3D11Texture2D> _texture;
ComPtr<ID3D11ShaderResourceView> _srv;
D3D11_TEXTURE2D_DESC _desc = {0};
NvimFrontend &_nvim;
NvimRendererD2D _renderer;
public:
Renderer(NvimFrontend &nvim, const ComPtr<ID3D11Device> &device)
: _nvim(nvim), _device(device),
_renderer(device.Get(), nvim.DefaultAttribute()) {
// Attach the renderer now that the window size is determined
// auto [window_width, window_height] = window.Size();
auto [font_width, font_height] = _renderer.FontSize();
auto gridSize = Nvim::GridSize::FromWindowSize(640, 640, ceilf(font_width),
ceilf(font_height));
// nvim_attach_ui. start redraw message
_nvim.AttachUI(&_renderer, gridSize.rows, gridSize.cols);
}
ID3D11ShaderResourceView *Render(int w, int h) {
// update target size
GetOrCreate(w, h);
// update nvim gird size
auto [font_width, font_height] = _renderer.FontSize();
auto gridSize = Nvim::GridSize::FromWindowSize(w, h, ceilf(font_width),
ceilf(font_height));
if (_nvim.Sizing()) {
auto a = 0;
} else {
if (_nvim.GridSize() != gridSize) {
_nvim.SetSizing();
_nvim.ResizeGrid(gridSize.rows, gridSize.cols);
}
}
ComPtr<IDXGISurface2> surface;
auto hr = _texture.As(&surface);
assert(SUCCEEDED(hr));
_renderer.SetTarget(surface.Get());
_nvim.Process();
_renderer.SetTarget(nullptr);
return _srv.Get();
}
void Input(const Nvim::InputEvent &e) { _nvim.Input(e); }
private:
void GetOrCreate(int w, int h) {
if (_texture) {
if (_desc.Width == w && _desc.Height == h) {
return;
}
}
PLOGD << "srv: " << w << ", " << h;
_desc.Width = w;
_desc.Height = h;
_desc.MipLevels = 1;
_desc.ArraySize = 1;
_desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // D2D
_desc.SampleDesc.Count = 1;
_desc.SampleDesc.Quality = 0;
_desc.Usage = D3D11_USAGE_DEFAULT;
_desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
auto hr = _device->CreateTexture2D(&_desc, nullptr, &_texture);
if (FAILED(hr)) {
assert(false);
return;
}
hr = _device->CreateShaderResourceView(_texture.Get(), nullptr, &_srv);
if (FAILED(hr)) {
assert(false);
return;
}
}
};
// Main code
int main(int, char **) {
static plog::DebugOutputAppender<plog::TxtFormatter> debugOutputAppender;
plog::init(plog::verbose, &debugOutputAppender);
//
// launch nvim
//
NvimFrontend nvim;
//
// create window
//
Win32Window window;
auto hwnd = window.Create(&nvim);
if (!hwnd) {
return 1;
}
if (!nvim.Launch(L"nvim --embed", [hwnd]() {
PLOGD << "nvim terminated";
PostMessage(hwnd, WM_DESTROY, 0, 0);
})) {
return 3;
}
auto [font, size] = nvim.Initialize();
// Show the window
::ShowWindow(hwnd, SW_SHOWDEFAULT);
::UpdateWindow(hwnd);
D3DManager d3d;
if (!d3d.Create(hwnd)) {
return 2;
}
Renderer renderer(nvim, d3d._pd3dDevice);
Gui gui(hwnd, d3d._pd3dDevice.Get(), d3d._pd3dDeviceContext.Get());
// Main loop
bool done = false;
while (!done) {
// Poll and handle messages (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to
// tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to
// your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input
// data to your main application. Generally you may always pass all inputs
// to dear imgui, and hide them from your application based on those two
// flags.
MSG msg;
while (::PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE)) {
// ::TranslateMessage(&msg);
::DispatchMessage(&msg);
if (msg.message == WM_QUIT)
done = true;
}
if (done)
break;
RECT rect;
GetClientRect(hwnd, &rect);
d3d.PrepareBackbuffer(rect.right - rect.left, rect.bottom - rect.top,
gui.clear_color_with_alpha);
gui.Render(std::bind(&Renderer::Render, &renderer, std::placeholders::_1,
std::placeholders::_2),
std::bind(&Renderer::Input, &renderer, std::placeholders::_1));
d3d.Present();
}
return 0;
}
| 30.975779 | 83 | 0.64008 | [
"render",
"vector"
] |
a3d39f2481b53058828f40ee7dfa37cc93ae4e87 | 11,144 | cc | C++ | byteps/common/global.cc | haoxintong/byteps | 495f1372af5f6fd4832393d5e52d4b02b42a7a03 | [
"Apache-2.0"
] | 1 | 2019-07-01T10:08:00.000Z | 2019-07-01T10:08:00.000Z | byteps/common/global.cc | haoxintong/byteps | 495f1372af5f6fd4832393d5e52d4b02b42a7a03 | [
"Apache-2.0"
] | null | null | null | byteps/common/global.cc | haoxintong/byteps | 495f1372af5f6fd4832393d5e52d4b02b42a7a03 | [
"Apache-2.0"
] | 1 | 2021-02-02T02:58:37.000Z | 2021-02-02T02:58:37.000Z | // Copyright 2019 Bytedance Inc. or its affiliates. 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 "global.h"
#include <malloc.h>
#include <unistd.h>
#include <numa.h>
namespace byteps {
namespace common {
// Define and init global variables
std::mutex BytePSGlobal::_init_mutex;
volatile bool BytePSGlobal::_initialized = false;
volatile bool BytePSGlobal::_should_shutdown = false;
int BytePSGlobal::_rank = 0;
int BytePSGlobal::_local_rank = 0;
int BytePSGlobal::_size = 1;
int BytePSGlobal::_local_size = 1;
int BytePSGlobal::_worker_id = 0;
int BytePSGlobal::_num_worker = 1;
BytePSRole BytePSGlobal::_my_role;
bool BytePSGlobal::_is_root_device;
bool BytePSGlobal::_is_distributed_job;
bool BytePSGlobal::_is_cross_pcie_switch;
uint32_t BytePSGlobal::_partition_bytes = 4096000;
std::shared_ptr<BytePSComm> BytePSGlobal::_basic_comm;
std::shared_ptr<BytePSSharedMemory> BytePSGlobal::_shm_obj;
std::unordered_map<uint64_t, PSKV> BytePSGlobal::ps_kv_;
volatile BytePSScheduledQueue* BytePSGlobal::_queues[QueueNum] = {NULL};
std::mutex BytePSGlobal::_queues_mutex[QueueNum];
std::vector<std::thread*> BytePSGlobal::_threads;
std::mutex BytePSGlobal::_context_mutex;
ps::KVWorker<char>* BytePSGlobal::_ps = NULL;
std::mutex BytePSGlobal::_encode_mutex;
ReadyTable* BytePSGlobal::_reduce_table;
ReadyTable* BytePSGlobal::_pcie_reduce_table;
ReadyTable* BytePSGlobal::_broadcast_table;
ReadyTable* BytePSGlobal::_push_table;
ReadyTable* BytePSGlobal::_copy_table;
std::unordered_map<std::string, BPSContext> BytePSGlobal::_name_to_cxt;
unsigned int next_key_ = 0;
cudaStream_t* BytePSGlobal::_copy_device2host_stream;
cudaStream_t* BytePSGlobal::_copy_host2device_stream;
std::shared_ptr<NcclManager> BytePSGlobal::_nccl_manager;
std::shared_ptr<CpuReducer> BytePSGlobal::_cpu_reducer;
uint64_t BytePSGlobal::_sample_key = std::numeric_limits<uint64_t>::max();
BytePSScheduledQueue* BytePSGlobal::GetScheduledQueue(QueueType queueType) {
return (BytePSScheduledQueue*)_queues[queueType];
}
void BytePSGlobal::CreateScheduledQueue(QueueType queueType) {
std::lock_guard<std::mutex> lock(_queues_mutex[queueType]);
if (!_queues[queueType]) {
_queues[queueType] = new BytePSScheduledQueue(queueType);
}
return;
}
void BytePSGlobal::Init() {
std::lock_guard<std::mutex> lock(_init_mutex);
// We only init once
if (_initialized) {
return;
}
_basic_comm = std::make_shared<BytePSCommSocket>();
_basic_comm->init(&_rank, &_size, &_local_rank, &_local_size, &_worker_id, &_my_role);
_is_root_device = (_my_role == LOCAL_ROOT) ? true : false;
if (getenv("BYTEPS_PARTITION_BYTES")) {
_partition_bytes = atoi(getenv("BYTEPS_PARTITION_BYTES"));
}
BPS_LOG(DEBUG) << "Partition bound set to " << _partition_bytes << " bytes"
<< ", aligned to " << AlignTo(_partition_bytes, (8 * _local_size)) << " bytes";
// alignment for Reduce-Scatter/All-Gather
_partition_bytes = AlignTo(_partition_bytes, (8 * _local_size));
BPS_CHECK(getenv("DMLC_NUM_WORKER")) << "error: env DMLC_NUM_WORKER not set";
_num_worker = atoi(getenv("DMLC_NUM_WORKER"));
if (getenv("BYTEPS_FORCE_DISTRIBUTED")) {
_is_distributed_job = atoi(getenv("BYTEPS_FORCE_DISTRIBUTED"));
}
_is_distributed_job = (_num_worker>1) ? true : _is_distributed_job;
if (_is_distributed_job) {
BPS_CHECK(getenv("DMLC_NUM_SERVER")) << "error: launch distributed job, but env DMLC_NUM_SERVER not set";
}
BPS_LOG(DEBUG) << "Number of worker=" << _num_worker << ", launching "
<< (IsDistributed() ? "" : "non-") << "distributed job";
_shm_obj = std::make_shared<BytePSSharedMemory>(); // share memory obj
if (IsDistributed() && _my_role == BytePSRole::LOCAL_ROOT) { // only the root need to do networking
// init low-level ps implementation
_ps = new ps::KVWorker<char>(0, 0);
ps::StartAsync(0, "byteps\0");
if (!ps::Postoffice::Get()->is_recovery()) {
ps::Postoffice::Get()->Barrier(
0, ps::kWorkerGroup + ps::kServerGroup + ps::kScheduler);
}
}
// Set to associated GPU
CUDA_CALL(cudaSetDevice(_local_rank));
// Init NCCL
_nccl_manager = std::make_shared<NcclManager>(_basic_comm);
_is_cross_pcie_switch = (_local_size > _nccl_manager->GetSize());
// Bind to NUMA node
if (_is_cross_pcie_switch) {
auto numa_index = (GetPcieSwitchIndex() > numa_max_node()) ?
numa_max_node() : GetPcieSwitchIndex();
numa_bind(numa_parse_nodestring(std::to_string(numa_index).c_str()));
}
// Init CPU Reducer
if (_is_cross_pcie_switch) {
_cpu_reducer = std::make_shared<CpuReducer>(_basic_comm);
}
// ReadyTable for Push & Pull
if (_is_root_device) {
_push_table = new ReadyTable(_local_size-1, "PUSH");
}
else {
_copy_table = new ReadyTable(1, "COPY");
}
// ReadyTable for cross-PCIe-switch reduce
if (_is_cross_pcie_switch) {
if (_cpu_reducer->isRoot()) {
_pcie_reduce_table = new ReadyTable(GetPcieSwitchNum()-1, "PCIE_REDUCE");
}
}
// ReadyTable for per-PCIe-switch NCCL calls
if (_nccl_manager->IsSignalRoot()) {
_reduce_table = new ReadyTable(GetPcieSwitchSize()-1, "NCCL_REDUCE");
_broadcast_table = new ReadyTable(GetPcieSwitchSize()-1, "NCCL_BROADCAST");
}
// Create CUDA streams for GPU-CPU copies
_copy_host2device_stream = (cudaStream_t*) malloc(sizeof(cudaStream_t) * 1);
_copy_device2host_stream = (cudaStream_t*) malloc(sizeof(cudaStream_t) * 1);
CUDA_CALL(cudaStreamCreateWithFlags(_copy_host2device_stream, cudaStreamNonBlocking));
CUDA_CALL(cudaStreamCreateWithFlags(_copy_device2host_stream, cudaStreamNonBlocking));
CUDA_CALL(cudaStreamSynchronize(*_copy_host2device_stream));
CUDA_CALL(cudaStreamSynchronize(*_copy_device2host_stream));
// Create queues
for (int i = 0; i < QueueNum; i++) {
BPS_LOG(DEBUG) << "Create schedule queue " << i;
auto type = static_cast<QueueType>(i);
BytePSGlobal::CreateScheduledQueue(type);
}
_initialized = true;
BPS_LOG(DEBUG) << "Inited rank=" << _rank
<< " local_rank=" << _local_rank
<< " size=" << _size
<< " local_size=" << _local_size
<< " worker_id=" << _worker_id;
if (getenv("BYTEPS_DEBUG_SAMPLE_TENSOR")) {
_sample_key = strtoull(getenv("BYTEPS_DEBUG_SAMPLE_TENSOR"), nullptr, 0);
}
return;
}
void BytePSGlobal::Start(const std::vector<LoopFunction> &func) {
// Start background threads
for (size_t i = 0; i < func.size(); i++) {
_threads.push_back(new std::thread(func[i]));
}
BPS_LOG(DEBUG) << "Started " << func.size() << " background threads. rank=" << _local_rank;
}
const Status NOT_INITIALIZED_ERROR = Status::PreconditionError(
"BytePS has not been initialized; use bps.init().");
Status BytePSGlobal::CheckInit() {
if (_initialized) {
return Status::OK();
}
else {
return NOT_INITIALIZED_ERROR;
}
}
void BytePSGlobal::Shutdown() {
_should_shutdown = true;
for (size_t i = 0; i < _threads.size(); i++) {
if (_threads[i]->joinable()) {
_threads[i]->join();
delete _threads[i];
}
}
for (size_t i = 0; i < QueueNum; i++) {
if (_queues[i]) {
delete _queues[i];
}
}
if (_ps) {
ps::Finalize(0, false);
delete _ps;
}
CUDA_CALL(cudaStreamDestroy(*_copy_device2host_stream));
CUDA_CALL(cudaStreamDestroy(*_copy_host2device_stream));
if (_reduce_table) {
delete _reduce_table;
}
if (_pcie_reduce_table) {
delete _pcie_reduce_table;
}
if (_broadcast_table) {
delete _broadcast_table;
}
if (_push_table) {
delete _push_table;
}
if (_copy_table) {
delete _copy_table;
}
_basic_comm.reset();
_shm_obj.reset();
_cpu_reducer.reset();
_nccl_manager.reset();
BPS_LOG(DEBUG) << "Clear all BytePS resources";
return;
}
BPSContext& BytePSGlobal::GetContextFromName(const std::string &name) {
std::lock_guard<std::mutex> lock(_context_mutex);
BPS_CHECK(_name_to_cxt.find(name) != _name_to_cxt.end()) << name << " is not initialized";
return _name_to_cxt[name];
}
bool BytePSGlobal::IsTensorDeclared(const std::string &name) {
std::lock_guard<std::mutex> lock(_context_mutex);
if (_name_to_cxt.find(name) == _name_to_cxt.end()) {
_name_to_cxt[name].initialized = false;
_name_to_cxt[name].tensor_name = name.c_str(); // disable copy-on-write
_name_to_cxt[name].declared_key = (ps::Key) next_key_++;
BPS_LOG(DEBUG) << "Declared tensor " << name
<< ", declared key (not PS key): " << _name_to_cxt[name].declared_key
<< " rank=" << BytePSGlobal::GetLocalRank();
return false;
}
return true;
}
PSKV& BytePSGlobal::EncodeDefaultKey(uint64_t key, size_t len) {
std::lock_guard<std::mutex> lock(_encode_mutex);
PSKV& pskv = ps_kv_[key];
if (!pskv.keys.empty()) {
BPS_CHECK_EQ(static_cast<size_t>(pskv.size), len)
<< "The value size cannot be changed " << len
<< ". Key is " << key;
} else {
auto krs = ps::Postoffice::Get()->GetServerKeyRanges();
const int num_servers = krs.size();
BPS_CHECK_GT(num_servers, 0);
// send it to a single random picked server
int server = (((key >> 16) + key) * 9973) % num_servers;
BPS_LOG(DEBUG) << "key " << key << " assigned to server " << server;
ps::Key ps_key = krs[server].begin() + key;
BPS_CHECK_LT(ps_key, krs[server].end());
pskv.keys.push_back(ps_key);
pskv.lens.push_back(len);
pskv.size = len;
}
BPS_LOG(TRACE) << "key " << key << " is encoded to " << pskv.keys[0];
return pskv;
}
uint32_t BytePSGlobal::GetTensorCount() {
std::lock_guard<std::mutex> lock(_context_mutex);
return BytePSGlobal::_name_to_cxt.size();
}
cudaStream_t* BytePSGlobal::GetCopyDevice2HostStream() {
return BytePSGlobal::_copy_device2host_stream;
}
cudaStream_t* BytePSGlobal::GetCopyHost2DeviceStream() {
return BytePSGlobal::_copy_host2device_stream;
}
} // namespace common
} // namespace byteps
| 34.184049 | 113 | 0.66206 | [
"vector"
] |
a3d5ded8bd4ff1cfc3f0b020091953cbd9d241ef | 38,377 | cpp | C++ | code/engine.vc2008/xrGame/CustomZone.cpp | ipl-adm/xray-oxygen | 3ae4d4911f5b000e93bdf108eb68db25315b2fc6 | [
"Apache-2.0"
] | 1 | 2021-06-15T13:04:36.000Z | 2021-06-15T13:04:36.000Z | code/engine.vc2008/xrGame/CustomZone.cpp | ipl-adm/xray-oxygen | 3ae4d4911f5b000e93bdf108eb68db25315b2fc6 | [
"Apache-2.0"
] | null | null | null | code/engine.vc2008/xrGame/CustomZone.cpp | ipl-adm/xray-oxygen | 3ae4d4911f5b000e93bdf108eb68db25315b2fc6 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "../xrEngine/xr_ioconsole.h"
#include "customzone.h"
#include "hit.h"
#include "PHDestroyable.h"
#include "actor.h"
#include "../xrParticles/psystem.h"
#include "../xrParticles/ParticlesObject.h"
#include "xrserver_objects_alife_monsters.h"
#include "../xrEngine/LightAnimLibrary.h"
#include "level.h"
#include "game_cl_base.h"
#include "../xrEngine/igame_persistent.h"
#include "../xrengine/xr_collide_form.h"
#include "artefact.h"
#include "ai_object_location.h"
#include "../Include/xrRender/Kinematics.h"
#include "zone_effector.h"
#include "breakableobject.h"
#include "GamePersistent.h"
#define WIND_RADIUS (4*Radius()) //расстояние до актера, когда появляется ветер
#define FASTMODE_DISTANCE (50.f) //distance to camera from sphere, when zone switches to fast update sequence
CCustomZone::CCustomZone(void)
{
m_zone_flags.zero ();
m_fMaxPower = 100.f;
m_fAttenuation = 1.f;
m_fEffectiveRadius = 1.0f;
m_zone_flags.set (eZoneIsActive, FALSE);
m_eHitTypeBlowout = ALife::eHitTypeWound;
m_pIdleParticles = NULL;
m_pLight = NULL;
m_pIdleLight = NULL;
m_pIdleLAnim = NULL;
m_StateTime.resize(eZoneStateMax);
for(int i=0; i<eZoneStateMax; i++)
m_StateTime[i] = 0;
m_dwAffectFrameNum = 0;
m_fBlowoutWindPowerMax = m_fStoreWindPower = 0.f;
m_fDistanceToCurEntity = flt_max;
m_ef_weapon_type = u32(-1);
m_owner_id = u32(-1);
m_actor_effector = NULL;
m_zone_flags.set (eIdleObjectParticlesDontStop, FALSE);
m_zone_flags.set (eBlowoutWindActive, FALSE);
m_zone_flags.set (eFastMode, TRUE);
m_eZoneState = eZoneStateIdle;
}
CCustomZone::~CCustomZone(void)
{
m_idle_sound.destroy ();
m_accum_sound.destroy ();
m_awaking_sound.destroy ();
m_blowout_sound.destroy ();
m_hit_sound.destroy ();
m_entrance_sound.destroy ();
xr_delete (m_actor_effector);
}
void CCustomZone::Load(LPCSTR section)
{
inherited::Load(section);
m_iDisableHitTime = pSettings->r_s32(section, "disable_time");
m_iDisableHitTimeSmall = pSettings->r_s32(section, "disable_time_small");
m_iDisableIdleTime = pSettings->r_s32(section, "disable_idle_time");
m_fHitImpulseScale = pSettings->r_float(section, "hit_impulse_scale");
m_fEffectiveRadius = pSettings->r_float(section, "effective_radius");
m_eHitTypeBlowout = ALife::g_tfString2HitType(pSettings->r_string(section, "hit_type"));
m_zone_flags.set(eIgnoreNonAlive, pSettings->r_bool(section, "ignore_nonalive"));
m_zone_flags.set(eIgnoreSmall, pSettings->r_bool(section, "ignore_small"));
m_zone_flags.set(eIgnoreArtefact, pSettings->r_bool(section, "ignore_artefacts"));
//загрузить времена для зоны
m_StateTime[eZoneStateIdle] = -1;
m_StateTime[eZoneStateAwaking] = pSettings->r_s32(section, "awaking_time");
m_StateTime[eZoneStateBlowout] = pSettings->r_s32(section, "blowout_time");
m_StateTime[eZoneStateAccumulate] = pSettings->r_s32(section, "accamulate_time");
//////////////////////////////////////////////////////////////////////////
ISpatial* self = smart_cast<ISpatial*> (this);
if (self) self->spatial.type |= (STYPE_COLLIDEABLE|STYPE_SHAPE);
//////////////////////////////////////////////////////////////////////////
LPCSTR sound_str = NULL;
if(pSettings->line_exist(section,"idle_sound"))
{
sound_str = pSettings->r_string(section,"idle_sound");
m_idle_sound.create(sound_str, st_Effect,sg_SourceType);
}
if(pSettings->line_exist(section,"accum_sound"))
{
sound_str = pSettings->r_string(section,"accum_sound");
m_accum_sound.create(sound_str, st_Effect,sg_SourceType);
}
if(pSettings->line_exist(section,"awake_sound"))
{
sound_str = pSettings->r_string(section,"awake_sound");
m_awaking_sound.create(sound_str, st_Effect,sg_SourceType);
}
if(pSettings->line_exist(section,"blowout_sound"))
{
sound_str = pSettings->r_string(section,"blowout_sound");
m_blowout_sound.create(sound_str, st_Effect,sg_SourceType);
}
if(pSettings->line_exist(section,"hit_sound"))
{
sound_str = pSettings->r_string(section,"hit_sound");
m_hit_sound.create(sound_str, st_Effect,sg_SourceType);
}
if(pSettings->line_exist(section,"entrance_sound"))
{
sound_str = pSettings->r_string(section,"entrance_sound");
m_entrance_sound.create(sound_str, st_Effect,sg_SourceType);
}
if(pSettings->line_exist(section,"idle_particles"))
m_sIdleParticles = pSettings->r_string(section,"idle_particles");
if(pSettings->line_exist(section,"blowout_particles"))
m_sBlowoutParticles = pSettings->r_string(section,"blowout_particles");
m_bBlowoutOnce = FALSE;
if (pSettings->line_exist(section, "blowout_once"))
m_bBlowoutOnce = pSettings->r_bool(section,"blowout_once");
if(pSettings->line_exist(section,"accum_particles"))
m_sAccumParticles = pSettings->r_string(section,"accum_particles");
if(pSettings->line_exist(section,"awake_particles"))
m_sAwakingParticles = pSettings->r_string(section,"awake_particles");
if(pSettings->line_exist(section,"entrance_small_particles"))
m_sEntranceParticlesSmall = pSettings->r_string(section,"entrance_small_particles");
if(pSettings->line_exist(section,"entrance_big_particles"))
m_sEntranceParticlesBig = pSettings->r_string(section,"entrance_big_particles");
if(pSettings->line_exist(section,"hit_small_particles"))
m_sHitParticlesSmall = pSettings->r_string(section,"hit_small_particles");
if(pSettings->line_exist(section,"hit_big_particles"))
m_sHitParticlesBig = pSettings->r_string(section,"hit_big_particles");
if(pSettings->line_exist(section,"idle_small_particles"))
m_sIdleObjectParticlesBig = pSettings->r_string(section,"idle_big_particles");
if(pSettings->line_exist(section,"idle_big_particles"))
m_sIdleObjectParticlesSmall = pSettings->r_string(section,"idle_small_particles");
if(pSettings->line_exist(section,"idle_particles_dont_stop"))
m_zone_flags.set(eIdleObjectParticlesDontStop, pSettings->r_bool(section,"idle_particles_dont_stop"));
if(pSettings->line_exist(section,"postprocess"))
{
m_actor_effector = xr_new<CZoneEffector>();
m_actor_effector->Load (pSettings->r_string(section,"postprocess"));
};
if(pSettings->line_exist(section,"bolt_entrance_particles"))
{
m_sBoltEntranceParticles = pSettings->r_string(section, "bolt_entrance_particles");
m_zone_flags.set (eBoltEntranceParticles, (m_sBoltEntranceParticles.size()!=0));
}
if(pSettings->line_exist(section,"blowout_particles_time"))
{
m_dwBlowoutParticlesTime = pSettings->r_u32(section,"blowout_particles_time");
if (s32(m_dwBlowoutParticlesTime)>m_StateTime[eZoneStateBlowout]) {
m_dwBlowoutParticlesTime=m_StateTime[eZoneStateBlowout];
#ifndef MASTER_GOLD
Msg("! ERROR: invalid 'blowout_particles_time' in '%s'",section);
#endif // #ifndef MASTER_GOLD
}
}
else
m_dwBlowoutParticlesTime = 0;
if(pSettings->line_exist(section,"blowout_light_time"))
{
m_dwBlowoutLightTime = pSettings->r_u32(section,"blowout_light_time");
if (s32(m_dwBlowoutLightTime)>m_StateTime[eZoneStateBlowout]) {
m_dwBlowoutLightTime=m_StateTime[eZoneStateBlowout];
#ifndef MASTER_GOLD
Msg("! ERROR: invalid 'blowout_light_time' in '%s'",section);
#endif // #ifndef MASTER_GOLD
}
}
else
m_dwBlowoutLightTime = 0;
if(pSettings->line_exist(section,"blowout_sound_time"))
{
m_dwBlowoutSoundTime = pSettings->r_u32(section,"blowout_sound_time");
if (s32(m_dwBlowoutSoundTime)>m_StateTime[eZoneStateBlowout]) {
m_dwBlowoutSoundTime=m_StateTime[eZoneStateBlowout];
#ifndef MASTER_GOLD
Msg("! ERROR: invalid 'blowout_sound_time' in '%s'",section);
#endif // #ifndef MASTER_GOLD
}
}
else
m_dwBlowoutSoundTime = 0;
if(pSettings->line_exist(section,"blowout_explosion_time")) {
m_dwBlowoutExplosionTime = pSettings->r_u32(section,"blowout_explosion_time");
if (s32(m_dwBlowoutExplosionTime)>m_StateTime[eZoneStateBlowout]) {
m_dwBlowoutExplosionTime=m_StateTime[eZoneStateBlowout];
#ifndef MASTER_GOLD
Msg("! ERROR: invalid 'blowout_explosion_time' in '%s'",section);
#endif // #ifndef MASTER_GOLD
}
}
else
m_dwBlowoutExplosionTime = 0;
m_zone_flags.set(eBlowoutWind, pSettings->r_bool(section,"blowout_wind"));
if( m_zone_flags.test(eBlowoutWind) ){
m_dwBlowoutWindTimeStart = pSettings->r_u32(section,"blowout_wind_time_start");
m_dwBlowoutWindTimePeak = pSettings->r_u32(section,"blowout_wind_time_peak");
m_dwBlowoutWindTimeEnd = pSettings->r_u32(section,"blowout_wind_time_end");
R_ASSERT(m_dwBlowoutWindTimeStart < m_dwBlowoutWindTimePeak);
R_ASSERT(m_dwBlowoutWindTimePeak < m_dwBlowoutWindTimeEnd);
if((s32)m_dwBlowoutWindTimeEnd < m_StateTime[eZoneStateBlowout]){
m_dwBlowoutWindTimeEnd =u32( m_StateTime[eZoneStateBlowout]-1);
#ifndef MASTER_GOLD
Msg("! ERROR: invalid 'blowout_wind_time_end' in '%s'",section);
#endif // #ifndef MASTER_GOLD
}
m_fBlowoutWindPowerMax = pSettings->r_float(section,"blowout_wind_power");
}
//загрузить параметры световой вспышки от взрыва
m_zone_flags.set(eBlowoutLight, pSettings->r_bool (section, "blowout_light"));
if(m_zone_flags.test(eBlowoutLight) ){
sscanf(pSettings->r_string(section,"light_color"), "%f,%f,%f", &m_LightColor.r, &m_LightColor.g, &m_LightColor.b);
m_fLightRange = pSettings->r_float(section,"light_range");
m_fLightTime = pSettings->r_float(section,"light_time");
m_fLightTimeLeft = 0;
m_fLightHeight = pSettings->r_float(section,"light_height");
}
//загрузить параметры idle подсветки
m_zone_flags.set(eIdleLight, pSettings->r_bool (section, "idle_light"));
if( m_zone_flags.test(eIdleLight) )
{
m_fIdleLightRange = pSettings->r_float(section,"idle_light_range");
LPCSTR light_anim = pSettings->r_string(section,"idle_light_anim");
m_pIdleLAnim = LALib.FindItem(light_anim);
m_fIdleLightHeight = pSettings->r_float(section,"idle_light_height");
m_zone_flags.set(eIdleLightVolumetric,pSettings->r_bool (section, "idle_light_volumetric") );
m_zone_flags.set(eIdleLightShadow,pSettings->r_bool (section, "idle_light_shadow") );
m_zone_flags.set(eIdleLightR1,pSettings->r_bool (section, "idle_light_r1") );
}
bool use = !!READ_IF_EXISTS(pSettings, r_bool, section, "use_secondary_hit", false);
m_zone_flags.set(eUseSecondaryHit, use);
if(use)
m_fSecondaryHitPower = pSettings->r_float(section,"secondary_hit_power");
m_ef_anomaly_type = pSettings->r_u32(section,"ef_anomaly_type");
m_ef_weapon_type = pSettings->r_u32(section,"ef_weapon_type");
m_zone_flags.set (eAffectPickDOF, pSettings->r_bool (section, "pick_dof_effector"));
}
BOOL CCustomZone::net_Spawn(CSE_Abstract* DC)
{
if (!inherited::net_Spawn(DC))
return (FALSE);
CSE_Abstract *e = (CSE_Abstract*)(DC);
CSE_ALifeCustomZone *Z = smart_cast<CSE_ALifeCustomZone*>(e);
VERIFY (Z);
m_fMaxPower = pSettings->r_float(cNameSect(),"max_start_power");
m_fAttenuation = pSettings->r_float(cNameSect(),"attenuation");
m_owner_id = Z->m_owner_id;
if(m_owner_id != u32(-1))
m_ttl = Device.dwTimeGlobal + 40000;// 40 sec
else
m_ttl = u32(-1);
m_TimeToDisable = Z->m_disabled_time*1000;
m_TimeToEnable = Z->m_enabled_time*1000;
m_TimeShift = Z->m_start_time_shift*1000;
m_StartTime = Device.dwTimeGlobal;
m_zone_flags.set (eUseOnOffTime, (m_TimeToDisable!=0)&&(m_TimeToEnable!=0) );
//добавить источники света
bool br1 = (0==psDeviceFlags.test(rsR2|rsR3|rsR4));
bool render_ver_allowed = !br1 || (br1&&m_zone_flags.test(eIdleLightR1)) ;
if ( m_zone_flags.test(eIdleLight) && render_ver_allowed)
{
m_pIdleLight = ::Render->light_create();
m_pIdleLight->set_shadow(!!m_zone_flags.test(eIdleLightShadow));
if(m_zone_flags.test(eIdleLightVolumetric))
m_pIdleLight->set_volumetric (true);
}
else
m_pIdleLight = NULL;
if ( m_zone_flags.test(eBlowoutLight) )
{
m_pLight = ::Render->light_create();
m_pLight->set_shadow(true);
}else
m_pLight = NULL;
setEnabled (TRUE);
PlayIdleParticles ();
m_iPreviousStateTime = m_iStateTime = 0;
m_dwLastTimeMoved = Device.dwTimeGlobal;
m_vPrevPos.set (Position());
if(spawn_ini() && spawn_ini()->line_exist("fast_mode","always_fast"))
{
m_zone_flags.set(eAlwaysFastmode, spawn_ini()->r_bool("fast_mode","always_fast"));
}
return (TRUE);
}
void CCustomZone::net_Destroy()
{
StopIdleParticles ();
inherited::net_Destroy ();
StopWind ();
m_pLight.destroy ();
m_pIdleLight.destroy ();
CParticlesObject::Destroy(m_pIdleParticles);
if(m_actor_effector)
m_actor_effector->Stop ();
auto i = m_ObjectInfoMap.begin();
auto e = m_ObjectInfoMap.end();
for(;e!=i;++i)
exit_Zone(*i);
m_ObjectInfoMap.clear();
}
void CCustomZone::net_Import(NET_Packet& P)
{
inherited::net_Import(P);
}
void CCustomZone::net_Export(NET_Packet& P)
{
inherited::net_Export(P);
}
bool CCustomZone::IdleState()
{
UpdateOnOffState ();
return false;
}
bool CCustomZone::AwakingState()
{
if(m_iStateTime>=m_StateTime[eZoneStateAwaking])
{
SwitchZoneState(eZoneStateBlowout);
return true;
}
return false;
}
bool CCustomZone::BlowoutState()
{
if(m_iStateTime>=m_StateTime[eZoneStateBlowout])
{
SwitchZoneState(eZoneStateAccumulate);
if (m_bBlowoutOnce){
ZoneDisable();
}
return true;
}
return false;
}
bool CCustomZone::AccumulateState()
{
if(m_iStateTime>=m_StateTime[eZoneStateAccumulate])
{
if(m_zone_flags.test(eZoneIsActive) )
SwitchZoneState(eZoneStateBlowout);
else
SwitchZoneState(eZoneStateIdle);
return true;
}
return false;
}
void CCustomZone::UpdateWorkload (u32 dt)
{
m_iPreviousStateTime = m_iStateTime;
m_iStateTime += (int)dt;
if (!IsEnabled()) {
if (m_actor_effector)
m_actor_effector->Stop();
return;
};
UpdateIdleLight ();
switch(m_eZoneState)
{
case eZoneStateIdle:
IdleState();
break;
case eZoneStateAwaking:
AwakingState();
break;
case eZoneStateBlowout:
BlowoutState();
break;
case eZoneStateAccumulate:
AccumulateState();
break;
case eZoneStateDisabled:
break;
default: NODEFAULT;
}
if (Level().CurrentEntity())
{
Fvector P = Level().CurrentControlEntity()->Position();
P.y += 0.5f;
float radius = 1.0f;
CalcDistanceTo (P, m_fDistanceToCurEntity, radius);
if (m_actor_effector)
{
m_actor_effector->Update(m_fDistanceToCurEntity, radius, m_eHitTypeBlowout);
}
}
if(m_pLight && m_pLight->get_active())
UpdateBlowoutLight ();
if(m_zone_flags.test(eUseSecondaryHit) && m_eZoneState!=eZoneStateIdle && m_eZoneState!=eZoneStateDisabled)
{
UpdateSecondaryHit();
}
}
// called only in "fast-mode"
void CCustomZone::UpdateCL ()
{
inherited::UpdateCL ();
if (m_zone_flags.test(eFastMode))
UpdateWorkload (Device.dwTimeDelta);
}
// called as usual
void CCustomZone::shedule_Update(u32 dt)
{
m_zone_flags.set(eZoneIsActive, FALSE);
if (IsEnabled())
{
const Fsphere& s = CFORM()->getSphere();
Fvector P;
XFORM().transform_tiny (P,s.P);
// update
feel_touch_update (P,s.R);
//пройтись по всем объектам в зоне
//и проверить их состояние
for(auto it = m_ObjectInfoMap.begin();
m_ObjectInfoMap.end() != it; ++it)
{
CGameObject* pObject = (*it).object;
if (!pObject) continue;
CEntityAlive* pEntityAlive = smart_cast<CEntityAlive*>(pObject);
SZoneObjectInfo& info = (*it);
info.dw_time_in_zone += dt;
if((!info.small_object && m_iDisableHitTime != -1 && (int)info.dw_time_in_zone > m_iDisableHitTime) ||
(info.small_object && m_iDisableHitTimeSmall != -1 && (int)info.dw_time_in_zone > m_iDisableHitTimeSmall))
{
if(!pEntityAlive || !pEntityAlive->g_Alive())
info.zone_ignore = true;
}
if(m_iDisableIdleTime != -1 && (int)info.dw_time_in_zone > m_iDisableIdleTime)
{
if(!pEntityAlive || !pEntityAlive->g_Alive())
StopObjectIdleParticles( pObject );
}
//если есть хотя бы один не дисабленый объект, то
//зона считается активной
if(info.zone_ignore == false)
m_zone_flags.set(eZoneIsActive,TRUE);
}
if(eZoneStateIdle == m_eZoneState)
CheckForAwaking();
inherited::shedule_Update(dt);
// check "fast-mode" border
Fvector act_and_cam_pos = Level().CurrentControlEntity()->Position();
act_and_cam_pos.y += 0.4;
float act_distance = act_and_cam_pos.distance_to(P)-s.R;
if (act_distance>FASTMODE_DISTANCE && !m_zone_flags.test(eAlwaysFastmode) )
o_switch_2_slow ();
else
o_switch_2_fast ();
if (!m_zone_flags.test(eFastMode))
UpdateWorkload (dt);
};
UpdateOnOffState ();
}
void CCustomZone::CheckForAwaking()
{
if(m_zone_flags.test(eZoneIsActive) && eZoneStateIdle == m_eZoneState)
SwitchZoneState(eZoneStateAwaking);
}
void CCustomZone::feel_touch_new (CObject* O)
{
// if(smart_cast<CActor*>(O) && O == Level().CurrentEntity())
// m_pLocalActor = smart_cast<CActor*>(O);
CGameObject* pGameObject = smart_cast<CGameObject*>(O);
CEntityAlive* pEntityAlive = smart_cast<CEntityAlive*>(pGameObject);
CArtefact* pArtefact = smart_cast<CArtefact*>(pGameObject);
SZoneObjectInfo object_info ;
object_info.object = pGameObject;
if(pEntityAlive && pEntityAlive->g_Alive())
object_info.nonalive_object = false;
else
object_info.nonalive_object = true;
if(pGameObject->Radius()<SMALL_OBJECT_RADIUS)
object_info.small_object = true;
else
object_info.small_object = false;
if((object_info.small_object && m_zone_flags.test(eIgnoreSmall)) ||
(object_info.nonalive_object && m_zone_flags.test(eIgnoreNonAlive)) ||
(pArtefact && m_zone_flags.test(eIgnoreArtefact)))
object_info.zone_ignore = true;
else
object_info.zone_ignore = false;
enter_Zone(object_info);
m_ObjectInfoMap.push_back(object_info);
if (IsEnabled())
{
PlayEntranceParticles(pGameObject);
PlayObjectIdleParticles(pGameObject);
}
};
void CCustomZone::feel_touch_delete(CObject* O)
{
CGameObject* pGameObject =smart_cast<CGameObject*>(O);
if(!pGameObject->getDestroy())
{
StopObjectIdleParticles(pGameObject);
}
auto it = std::find(m_ObjectInfoMap.begin(),m_ObjectInfoMap.end(),pGameObject);
if(it!=m_ObjectInfoMap.end())
{
exit_Zone(*it);
m_ObjectInfoMap.erase(it);
}
}
BOOL CCustomZone::feel_touch_contact(CObject* O)
{
if (smart_cast<CCustomZone*>(O)) return FALSE;
if (smart_cast<CBreakableObject*>(O)) return FALSE;
if (0==smart_cast<IKinematics*>(O->Visual())) return FALSE;
if (O->ID() == ID())
return (FALSE);
CGameObject *object = smart_cast<CGameObject*>(O);
if (!object || !object->IsVisibleForZones())
return (FALSE);
if (!((CCF_Shape*)CFORM())->Contact(O))
return (FALSE);
return (object->feel_touch_on_contact(this));
}
float CCustomZone::RelativePower(float dist, float nearest_shape_radius)
{
float radius = effective_radius(nearest_shape_radius);
float power = (radius<dist) ? 0 : (1.f - m_fAttenuation*(dist/radius)*(dist/radius));
return (power<0.0f) ? 0.0f : power;
}
float CCustomZone::effective_radius(float nearest_shape_radius)
{
return /*Radius()*/nearest_shape_radius*m_fEffectiveRadius;
}
float CCustomZone::Power(float dist, float nearest_shape_radius)
{
return m_fMaxPower * RelativePower(dist, nearest_shape_radius);
}
void CCustomZone::PlayIdleParticles(bool bIdleLight)
{
m_idle_sound.play_at_pos(0, Position(), true);
if(*m_sIdleParticles)
{
if (!m_pIdleParticles)
{
m_pIdleParticles = CParticlesObject::Create(m_sIdleParticles.c_str(),FALSE);
m_pIdleParticles->UpdateParent(XFORM(),zero_vel);
m_pIdleParticles->UpdateParent(XFORM(),zero_vel);
m_pIdleParticles->Play(false);
}
}
if(bIdleLight)
StartIdleLight ();
}
void CCustomZone::StopIdleParticles(bool bIdleLight)
{
m_idle_sound.stop();
if(m_pIdleParticles)
{
m_pIdleParticles->Stop(FALSE);
CParticlesObject::Destroy(m_pIdleParticles);
}
if(bIdleLight)
StopIdleLight();
}
void CCustomZone::StartIdleLight ()
{
if(m_pIdleLight)
{
m_pIdleLight->set_range(m_fIdleLightRange);
Fvector pos = Position();
pos.y += m_fIdleLightHeight;
m_pIdleLight->set_position(pos);
m_pIdleLight->set_active(true);
}
}
void CCustomZone::StopIdleLight ()
{
if(m_pIdleLight)
m_pIdleLight->set_active(false);
}
void CCustomZone::UpdateIdleLight ()
{
if(!m_pIdleLight || !m_pIdleLight->get_active())
return;
VERIFY(m_pIdleLAnim);
int frame = 0;
u32 clr = m_pIdleLAnim->CalculateBGR(Device.fTimeGlobal,frame); // возвращает в формате BGR
Fcolor fclr;
fclr.set ((float)color_get_B(clr)/255.f,(float)color_get_G(clr)/255.f,(float)color_get_R(clr)/255.f,1.f);
float range = m_fIdleLightRange + 0.25f*::Random.randF(-1.f,1.f);
m_pIdleLight->set_range (range);
m_pIdleLight->set_color (fclr);
Fvector pos = Position();
pos.y += m_fIdleLightHeight;
m_pIdleLight->set_position(pos);
}
void CCustomZone::PlayBlowoutParticles()
{
if(!m_sBlowoutParticles) return;
CParticlesObject* pParticles;
pParticles = CParticlesObject::Create(*m_sBlowoutParticles,TRUE);
pParticles->UpdateParent(XFORM(),zero_vel);
pParticles->Play(false);
}
void CCustomZone::PlayHitParticles(CGameObject* pObject)
{
m_hit_sound.play_at_pos(0, pObject->Position());
shared_str particle_str = NULL;
if(pObject->Radius()<SMALL_OBJECT_RADIUS)
{
if(!m_sHitParticlesSmall) return;
particle_str = m_sHitParticlesSmall;
}
else
{
if(!m_sHitParticlesBig) return;
particle_str = m_sHitParticlesBig;
}
if( particle_str.size() )
{
CParticlesPlayer* PP = smart_cast<CParticlesPlayer*>(pObject);
if (PP){
u16 play_bone = PP->GetRandomBone();
if (play_bone!=BI_NONE)
PP->StartParticles (particle_str,play_bone,Fvector().set(0,1,0), ID());
}
}
}
#include "bolt.h"
void CCustomZone::PlayEntranceParticles(CGameObject* pObject)
{
m_entrance_sound.play_at_pos (0, pObject->Position());
LPCSTR particle_str = NULL;
if(pObject->Radius()<SMALL_OBJECT_RADIUS)
{
if(!m_sEntranceParticlesSmall)
return;
particle_str = m_sEntranceParticlesSmall.c_str();
}
else
{
if(!m_sEntranceParticlesBig)
return;
particle_str = m_sEntranceParticlesBig.c_str();
}
Fvector vel;
CPhysicsShellHolder* shell_holder=smart_cast<CPhysicsShellHolder*>(pObject);
if(shell_holder)
shell_holder->PHGetLinearVell(vel);
else
vel.set (0,0,0);
//выбрать случайную косточку на объекте
CParticlesPlayer* PP = smart_cast<CParticlesPlayer*>(pObject);
if (PP)
{
u16 play_bone = PP->GetRandomBone();
if (play_bone!=BI_NONE)
{
CParticlesObject* pParticles = CParticlesObject::Create(particle_str, TRUE);
Fmatrix xform;
Fvector dir;
if(fis_zero (vel.magnitude()))
dir.set (0,1,0);
else
{
dir.set (vel);
dir.normalize ();
}
PP->MakeXFORM (pObject,play_bone,dir,Fvector().set(0,0,0),xform);
pParticles->UpdateParent(xform, vel);
pParticles->Play (false);
}
}
if(m_zone_flags.test(eBoltEntranceParticles) && smart_cast<CBolt*>(pObject))
PlayBoltEntranceParticles();
}
void CCustomZone::PlayBoltEntranceParticles()
{
CCF_Shape* Sh = (CCF_Shape*)CFORM();
const Fmatrix& XF = XFORM();
Fmatrix PXF;
xr_vector<CCF_Shape::shape_def>& Shapes = Sh->Shapes();
Fvector sP0, sP1, vel;
CParticlesObject* pParticles = NULL;
xr_vector<CCF_Shape::shape_def>::iterator it = Shapes.begin();
xr_vector<CCF_Shape::shape_def>::iterator it_e = Shapes.end();
for(;it!=it_e;++it)
{
CCF_Shape::shape_def& s = *it;
switch (s.type)
{
case 0: // sphere
{
sP0 = s.data.sphere.P;
XF.transform_tiny (sP0);
float ki = 10.0f * s.data.sphere.R;
float c = 2.0f * s.data.sphere.R;
float quant_h = (PI_MUL_2/float(ki))*c;
float quant_p = (PI_DIV_2/float(ki));
for(float i=0; i<ki; ++i)
{
vel.setHP ( ::Random.randF(quant_h/2.0f, quant_h)*i,
::Random.randF(quant_p/2.0f, quant_p)*i
);
vel.mul (s.data.sphere.R);
sP1.add (sP0, vel);
PXF.identity ();
PXF.k.normalize (vel);
Fvector::generate_orthonormal_basis(PXF.k, PXF.j, PXF.i);
PXF.c = sP1;
pParticles = CParticlesObject::Create(m_sBoltEntranceParticles.c_str(), TRUE);
pParticles->UpdateParent(PXF,vel);
pParticles->Play (false);
}
}break;
case 1: // box
break;
}
}
}
void CCustomZone::PlayBulletParticles(Fvector& pos)
{
m_entrance_sound.play_at_pos(0, pos);
if(!m_sEntranceParticlesSmall) return;
CParticlesObject* pParticles;
pParticles = CParticlesObject::Create(*m_sEntranceParticlesSmall,TRUE);
Fmatrix M;
M = XFORM();
M.c.set(pos);
pParticles->UpdateParent(M,zero_vel);
pParticles->Play(false);
}
void CCustomZone::PlayObjectIdleParticles(CGameObject* pObject)
{
CParticlesPlayer* PP = smart_cast<CParticlesPlayer*>(pObject);
if(!PP) return;
shared_str particle_str = NULL;
//разные партиклы для объектов разного размера
if(pObject->Radius()<SMALL_OBJECT_RADIUS)
{
if(!m_sIdleObjectParticlesSmall) return;
particle_str = m_sIdleObjectParticlesSmall;
}
else
{
if(!m_sIdleObjectParticlesBig) return;
particle_str = m_sIdleObjectParticlesBig;
}
//запустить партиклы на объекте
//. new
PP->StopParticles (particle_str, BI_NONE, true);
PP->StartParticles (particle_str, Fvector().set(0,1,0), ID());
if (!IsEnabled())
PP->StopParticles (particle_str, BI_NONE, true);
}
void CCustomZone::StopObjectIdleParticles(CGameObject* pObject)
{
if (m_zone_flags.test(eIdleObjectParticlesDontStop) && !pObject->cast_actor())
return;
CParticlesPlayer* PP = smart_cast<CParticlesPlayer*>(pObject);
if(!PP) return;
auto it = std::find(m_ObjectInfoMap.begin(),m_ObjectInfoMap.end(),pObject);
if(m_ObjectInfoMap.end() == it) return;
shared_str particle_str = NULL;
//разные партиклы для объектов разного размера
if(pObject->Radius()<SMALL_OBJECT_RADIUS)
{
if(!m_sIdleObjectParticlesSmall) return;
particle_str = m_sIdleObjectParticlesSmall;
}
else
{
if(!m_sIdleObjectParticlesBig) return;
particle_str = m_sIdleObjectParticlesBig;
}
PP->StopParticles (particle_str, BI_NONE, true);
}
void CCustomZone::Hit (SHit* pHDS)
{
Fmatrix M;
M.identity();
M.translate_over (pHDS->p_in_bone_space);
M.mulA_43 (XFORM());
PlayBulletParticles (M.c);
}
void CCustomZone::StartBlowoutLight ()
{
if(!m_pLight || m_fLightTime<=0.f) return;
m_fLightTimeLeft = (float)Device.dwTimeGlobal + m_fLightTime*1000.0f;
m_pLight->set_color(m_LightColor.r, m_LightColor.g, m_LightColor.b);
m_pLight->set_range(m_fLightRange);
Fvector pos = Position();
pos.y += m_fLightHeight;
m_pLight->set_position(pos);
m_pLight->set_active(true);
}
void CCustomZone::StopBlowoutLight ()
{
m_fLightTimeLeft = 0.f;
m_pLight->set_active(false);
}
void CCustomZone::UpdateBlowoutLight ()
{
if(m_fLightTimeLeft > (float)Device.dwTimeGlobal)
{
float time_k = m_fLightTimeLeft - (float)Device.dwTimeGlobal;
// m_fLightTimeLeft -= Device.fTimeDelta;
clamp(time_k, 0.0f, m_fLightTime*1000.0f);
float scale = time_k/(m_fLightTime*1000.0f);
scale = powf(scale+EPS_L, 0.15f);
float r = m_fLightRange*scale;
VERIFY(_valid(r));
m_pLight->set_color(m_LightColor.r*scale,
m_LightColor.g*scale,
m_LightColor.b*scale);
m_pLight->set_range(r);
Fvector pos = Position();
pos.y += m_fLightHeight;
m_pLight->set_position(pos);
}
else
StopBlowoutLight ();
}
void CCustomZone::AffectObjects()
{
if(m_dwAffectFrameNum == Device.dwFrame)
return;
m_dwAffectFrameNum = Device.dwFrame;
if(Device.dwPrecacheFrame)
return;
for(auto it = m_ObjectInfoMap.begin(); m_ObjectInfoMap.end() != it; ++it)
{
if( !(*it).object->getDestroy() )
Affect( &(*it) );
}
}
void CCustomZone::UpdateBlowout()
{
if(m_dwBlowoutParticlesTime>=(u32)m_iPreviousStateTime &&
m_dwBlowoutParticlesTime<(u32)m_iStateTime)
PlayBlowoutParticles();
if(m_dwBlowoutLightTime>=(u32)m_iPreviousStateTime &&
m_dwBlowoutLightTime<(u32)m_iStateTime)
StartBlowoutLight ();
if(m_dwBlowoutSoundTime>=(u32)m_iPreviousStateTime &&
m_dwBlowoutSoundTime<(u32)m_iStateTime)
m_blowout_sound.play_at_pos (0, Position());
if(m_zone_flags.test(eBlowoutWind) && m_dwBlowoutWindTimeStart>=(u32)m_iPreviousStateTime &&
m_dwBlowoutWindTimeStart<(u32)m_iStateTime)
StartWind();
UpdateWind();
if(m_dwBlowoutExplosionTime>=(u32)m_iPreviousStateTime &&
m_dwBlowoutExplosionTime<(u32)m_iStateTime)
{
AffectObjects();
}
}
void CCustomZone::OnMove()
{
if(m_dwLastTimeMoved == 0)
{
m_dwLastTimeMoved = Device.dwTimeGlobal;
m_vPrevPos.set(Position());
}
else
{
float time_delta = float(Device.dwTimeGlobal - m_dwLastTimeMoved)/1000.f;
m_dwLastTimeMoved = Device.dwTimeGlobal;
Fvector vel;
if(fis_zero(time_delta))
vel = zero_vel;
else
{
vel.sub(Position(), m_vPrevPos);
vel.div(time_delta);
}
if (m_pIdleParticles)
m_pIdleParticles->UpdateParent(XFORM(), vel);
if(m_pLight && m_pLight->get_active())
m_pLight->set_position(Position());
if(m_pIdleLight && m_pIdleLight->get_active())
m_pIdleLight->set_position(Position());
}
}
void CCustomZone::OnEvent (NET_Packet& P, u16 type)
{
switch (type)
{
case GE_ZONE_STATE_CHANGE:
{
u8 S;
P.r_u8 (S);
OnStateSwitch (EZoneState(S));
break;
}
}
inherited::OnEvent(P, type);
};
void CCustomZone::OnStateSwitch (EZoneState new_state)
{
if (new_state==eZoneStateDisabled)
Disable();
else
Enable();
if(new_state==eZoneStateAccumulate)
PlayAccumParticles();
if(new_state==eZoneStateAwaking)
PlayAwakingParticles();
m_eZoneState = new_state;
m_iPreviousStateTime = m_iStateTime = 0;
};
void CCustomZone::SwitchZoneState(EZoneState new_state)
{
// !!! Just single entry for given state !!!
NET_Packet P;
u_EventGen (P,GE_ZONE_STATE_CHANGE,ID());
P.w_u8 (u8(new_state));
u_EventSend (P);
m_iPreviousStateTime = m_iStateTime = 0;
}
bool CCustomZone::Enable()
{
if (IsEnabled()) return false;
o_switch_2_fast();
for(auto it = m_ObjectInfoMap.begin();
m_ObjectInfoMap.end() != it; ++it)
{
CGameObject* pObject = (*it).object;
if (!pObject) continue;
PlayEntranceParticles(pObject);
PlayObjectIdleParticles(pObject);
}
PlayIdleParticles ();
return true;
};
bool CCustomZone::Disable()
{
if (!IsEnabled()) return false;
o_switch_2_slow();
for(auto it = m_ObjectInfoMap.begin(); m_ObjectInfoMap.end()!=it; ++it)
{
CGameObject* pObject = (*it).object;
if (!pObject)
continue;
StopObjectIdleParticles(pObject);
}
StopIdleParticles ();
if (m_actor_effector)
m_actor_effector->Stop();
return false;
};
void CCustomZone::ZoneEnable()
{
SwitchZoneState(eZoneStateIdle);
};
void CCustomZone::ZoneDisable()
{
SwitchZoneState(eZoneStateDisabled);
};
void CCustomZone::StartWind()
{
if(m_fDistanceToCurEntity>WIND_RADIUS) return;
m_zone_flags.set(eBlowoutWindActive, TRUE);
m_fStoreWindPower = g_pGamePersistent->Environment().wind_strength_factor;
clamp(g_pGamePersistent->Environment().wind_strength_factor, 0.f, 1.f);
}
void CCustomZone::StopWind()
{
if(!m_zone_flags.test(eBlowoutWindActive)) return;
m_zone_flags.set(eBlowoutWindActive, FALSE);
g_pGamePersistent->Environment().wind_strength_factor = m_fStoreWindPower;
}
void CCustomZone::UpdateWind()
{
if(!m_zone_flags.test(eBlowoutWindActive)) return;
if(m_fDistanceToCurEntity>WIND_RADIUS || m_dwBlowoutWindTimeEnd<(u32)m_iStateTime)
{
StopWind();
return;
}
if(m_dwBlowoutWindTimePeak > (u32)m_iStateTime)
{
g_pGamePersistent->Environment().wind_strength_factor = m_fBlowoutWindPowerMax + ( m_fStoreWindPower - m_fBlowoutWindPowerMax)*
float(m_dwBlowoutWindTimePeak - (u32)m_iStateTime)/
float(m_dwBlowoutWindTimePeak - m_dwBlowoutWindTimeStart);
clamp(g_pGamePersistent->Environment().wind_strength_factor, 0.f, 1.f);
}
else
{
g_pGamePersistent->Environment().wind_strength_factor = m_fBlowoutWindPowerMax + (m_fStoreWindPower - m_fBlowoutWindPowerMax)*
float((u32)m_iStateTime - m_dwBlowoutWindTimePeak)/
float(m_dwBlowoutWindTimeEnd - m_dwBlowoutWindTimePeak);
clamp(g_pGamePersistent->Environment().wind_strength_factor, 0.f, 1.f);
}
}
u32 CCustomZone::ef_anomaly_type() const
{
return (m_ef_anomaly_type);
}
u32 CCustomZone::ef_weapon_type() const
{
VERIFY (m_ef_weapon_type != u32(-1));
return (m_ef_weapon_type);
}
void CCustomZone::CreateHit(u16 id_to, u16 id_from, const Fvector& hit_dir, float hit_power, s16 bone_id, const Fvector& pos_in_bone, float hit_impulse, ALife::EHitType hit_type)
{
if (m_owner_id != u32(-1))
id_from = (u16)m_owner_id;
NET_Packet l_P;
Fvector hdir = hit_dir;
SHit Hit = SHit(hit_power, hdir, this, bone_id, pos_in_bone, hit_impulse, hit_type, 0.0f, false);
Hit.GenHeader(GE_HIT, id_to);
Hit.whoID = id_from;
Hit.weaponID = this->ID();
Hit.Write_Packet(l_P);
u_EventSend(l_P);
}
void CCustomZone::net_Relcase(CObject* O)
{
CGameObject* GO = smart_cast<CGameObject*>(O);
auto it = std::find(m_ObjectInfoMap.begin(),m_ObjectInfoMap.end(), GO);
if(it!=m_ObjectInfoMap.end())
{
exit_Zone (*it);
m_ObjectInfoMap.erase (it);
}
if(GO->ID()==m_owner_id) m_owner_id = u32(-1);
if(m_actor_effector && m_actor_effector->m_pActor && m_actor_effector->m_pActor->ID() == GO->ID())
m_actor_effector->Stop();
inherited::net_Relcase(O);
}
void CCustomZone::enter_Zone(SZoneObjectInfo& io)
{
if(m_zone_flags.test(eAffectPickDOF) && Level().CurrentEntity())
{
if(io.object->ID()==Level().CurrentEntity()->ID())
GamePersistent().SetPickableEffectorDOF(true);
}
}
void CCustomZone::exit_Zone (SZoneObjectInfo& io)
{
StopObjectIdleParticles(io.object);
if(m_zone_flags.test(eAffectPickDOF) && Level().CurrentEntity())
{
if(io.object->ID()==Level().CurrentEntity()->ID())
GamePersistent().SetPickableEffectorDOF(false);
}
}
void CCustomZone::PlayAccumParticles()
{
if(m_sAccumParticles.size())
{
CParticlesObject* pParticles;
pParticles = CParticlesObject::Create(*m_sAccumParticles,TRUE);
pParticles->UpdateParent(XFORM(),zero_vel);
pParticles->Play(false);
}
if(m_accum_sound._handle())
m_accum_sound.play_at_pos (0, Position());
}
void CCustomZone::PlayAwakingParticles()
{
if(m_sAwakingParticles.size())
{
CParticlesObject* pParticles;
pParticles = CParticlesObject::Create(*m_sAwakingParticles,TRUE);
pParticles->UpdateParent(XFORM(),zero_vel);
pParticles->Play(false);
}
if(m_awaking_sound._handle())
m_awaking_sound.play_at_pos (0, Position());
}
void CCustomZone::UpdateOnOffState()
{
if(!m_zone_flags.test(eUseOnOffTime)) return;
bool dest_state;
u32 t = (Device.dwTimeGlobal-m_StartTime+m_TimeShift) % (m_TimeToEnable+m_TimeToDisable);
if (t < m_TimeToEnable)
{
dest_state=true;
}else
if(t >=(m_TimeToEnable+m_TimeToDisable) )
{
dest_state=true;
}else
{
dest_state=false;
VERIFY(t<(m_TimeToEnable+m_TimeToDisable));
}
if( (eZoneStateDisabled==m_eZoneState) && dest_state)
{
GoEnabledState ();
}else
if( (eZoneStateIdle==m_eZoneState) && !dest_state)
{
GoDisabledState ();
}
}
void CCustomZone::GoDisabledState()
{
//switch to disable
NET_Packet P;
u_EventGen (P,GE_ZONE_STATE_CHANGE,ID());
P.w_u8 (u8(eZoneStateDisabled));
u_EventSend (P);
auto it = m_ObjectInfoMap.begin();
auto it_e = m_ObjectInfoMap.end();
for(;it!=it_e;++it)
exit_Zone(*it);
m_ObjectInfoMap.clear ();
feel_touch.clear ();
}
void CCustomZone::GoEnabledState()
{
//switch to idle
NET_Packet P;
u_EventGen (P,GE_ZONE_STATE_CHANGE,ID());
P.w_u8 (u8(eZoneStateIdle));
u_EventSend (P);
}
BOOL CCustomZone::feel_touch_on_contact (CObject *O)
{
if ((spatial.type | STYPE_VISIBLEFORAI) != spatial.type)
return (FALSE);
return (inherited::feel_touch_on_contact(O));
}
BOOL CCustomZone::AlwaysTheCrow()
{
bool b_idle = ZoneState()==eZoneStateIdle || ZoneState()==eZoneStateDisabled;
if(!b_idle || (m_zone_flags.test(eAlwaysFastmode) && IsEnabled()) )
return TRUE;
else
return inherited::AlwaysTheCrow();
}
void CCustomZone::CalcDistanceTo(const Fvector& P, float& dist, float& radius)
{
R_ASSERT (CFORM()->Type()==cftShape);
CCF_Shape* Sh = (CCF_Shape*)CFORM();
dist = P.distance_to(Position());
float sr = CFORM()->getSphere().R;
//quick test
if(Sh->Shapes().size()==1)
{
radius = sr;
return;
}
/*
//2nd quick test
Fvector SC;
float dist2;
XF.transform_tiny (SC,CFORM()->getSphere().P);
dist2 = P.distance_to(SC);
if(dist2>sr)
{
radius = sr;
return;
}
*/
//full test
const Fmatrix& XF = XFORM();
xr_vector<CCF_Shape::shape_def>& Shapes = Sh->Shapes();
CCF_Shape::shape_def* nearest_s = NULL;
float nearest = flt_max;
Fvector sP;
xr_vector<CCF_Shape::shape_def>::iterator it = Shapes.begin();
xr_vector<CCF_Shape::shape_def>::iterator it_e = Shapes.end();
for(;it!=it_e;++it)
{
CCF_Shape::shape_def& s = *it;
float d = 0.0f;
switch (s.type)
{
case 0: // sphere
sP = s.data.sphere.P;
break;
case 1: // box
sP = s.data.box.c;
break;
}
XF.transform_tiny(sP);
d = P.distance_to(sP);
if(d<nearest)
{
nearest = d;
nearest_s = &s;
}
}
R_ASSERT(nearest_s);
dist = nearest;
if(nearest_s->type==0)
radius = nearest_s->data.sphere.R;
else
{
float r1 = nearest_s->data.box.i.magnitude();
float r2 = nearest_s->data.box.j.magnitude();
float r3 = nearest_s->data.box.k.magnitude();
radius = std::max(r1,r2);
radius = std::max(radius,r3);
}
}
// Lain: added Start/Stop idle light calls
void CCustomZone::o_switch_2_fast ()
{
if (m_zone_flags.test(eFastMode)) return ;
m_zone_flags.set(eFastMode, TRUE);
StartIdleLight();
processing_activate ();
}
void CCustomZone::o_switch_2_slow ()
{
if (!m_zone_flags.test(eFastMode)) return ;
m_zone_flags.set(eFastMode, FALSE);
if ( !light_in_slow_mode() )
{
StopIdleLight();
}
processing_deactivate ();
}
void CCustomZone::save (NET_Packet &output_packet)
{
inherited::save (output_packet);
output_packet.w_u8 (static_cast<u8>(m_eZoneState));
}
void CCustomZone::load (IReader &input_packet)
{
inherited::load (input_packet);
CCustomZone::EZoneState temp = static_cast<CCustomZone::EZoneState>(input_packet.r_u8());
if (temp == eZoneStateDisabled)
m_eZoneState = eZoneStateDisabled;
else
m_eZoneState = eZoneStateIdle;
}
| 25.533599 | 178 | 0.720379 | [
"render",
"object"
] |
a3dbf4c4c6b356637a7d37c4c50a9692eb35d4f2 | 9,937 | cpp | C++ | src/featureVector.cpp | barbarabenato/libFL_finalproject | d671a69781722efd46477b0a9ea4b9d611a7bfad | [
"MIT"
] | null | null | null | src/featureVector.cpp | barbarabenato/libFL_finalproject | d671a69781722efd46477b0a9ea4b9d611a7bfad | [
"MIT"
] | null | null | null | src/featureVector.cpp | barbarabenato/libFL_finalproject | d671a69781722efd46477b0a9ea4b9d611a7bfad | [
"MIT"
] | 5 | 2017-03-18T00:32:00.000Z | 2019-03-24T05:58:43.000Z | //
// Created by deangeli on 3/27/17.
//
#include "featureVector.h"
FeatureVector* createFeatureVector(int size){
FeatureVector* featureVector = (FeatureVector*)calloc(1,sizeof(FeatureVector));
featureVector->size = size;
featureVector->features = (float*)calloc((size_t)size, sizeof(float));
return featureVector;
}
void destroyFeatureVector(FeatureVector** featureVector){
free((*featureVector)->features);
free((*featureVector));
(*featureVector) = NULL;
}
FeatureVector* createRandomNormalizedFeatureVector(int size){
FeatureVector* featureVector = (FeatureVector*)calloc(1,sizeof(FeatureVector));
featureVector->size = size;
featureVector->features = (float*)calloc((size_t)size, sizeof(float));
for (int i = 0; i < size; ++i) {
featureVector->features[i] = randomNormalized();
}
return featureVector;
}
void printFeatureVector(FeatureVector* featureVector){
if(featureVector == NULL){
printf("FeatureVector pointer is NULL\n");
return;
}
for (int i = 0; i < featureVector->size; ++i) {
printf("%f ",featureVector->features[i]);
}
printf("\n");
}
FeatureVector* mergeFeatureVectors(FeatureVector* vector1,FeatureVector* vector2){
FeatureVector *mergedVector = NULL;
if(vector1 == NULL || vector2 == NULL){
printf("vector1 or/and vector2 are NULL\n");
return mergedVector;
}
int mergedSize = vector1->size + vector2->size;
mergedVector = createFeatureVector(mergedSize);
for (int i = 0; i < vector1->size; ++i) {
mergedVector->features[i] = vector1->features[i];
}
for (int i = 0; i < vector2->size; ++i) {
mergedVector->features[i+vector1->size] = vector2->features[i];
}
return mergedVector;
}
FeatureVector* createFeatureVector(float* vec,int size){
FeatureVector* featureVector = (FeatureVector*)calloc(1,sizeof(FeatureVector));
featureVector->size = size;
featureVector->features = (float*)calloc((size_t)size,sizeof(float));
for (int i = 0; i < size; ++i) {
featureVector->features[i] = vec[i];
}
return featureVector;
}
void writeFeatureVectors(FeatureVector** vectors, int nVectors, char *filename){
FILE *fp = fopen(filename,"w");
for (int i = 0; i < nVectors; ++i) {
FeatureVector* vec = vectors[i];
for (int j = 0; j < vec->size; ++j) {
fprintf(fp,"%f",vec->features[j]);
if(!(j == vec->size-1)){
fprintf(fp," ");
}
}
fprintf(fp,"\n");
}
fclose(fp);
}
float vectorDifference(FeatureVector* vector1,FeatureVector* vector2){
if(vector1->size != vector2->size){
printf("vectors mismatch dimensions\n");
return -1.0;
}
float difference = 0;
FeatureVector* vector = createFeatureVector(vector1->size);
float diff;
for (int i = 0; i < vector1->size; ++i) {
diff = (vector1->features[i]-vector2->features[i]);
if(diff < 0){
diff *= -1;
}
vector->features[i] = diff;
//vector->features[i] = (vector1->features[i]-vector2->features[i])*(vector1->features[i]-vector2->features[i]);
//vector->features[i] = sqrtf(vector->features[i]);
difference += vector->features[i];
}
destroyFeatureVector(&vector);
return difference;
}
FeatureVector* copyFeatureVector(FeatureVector* featureVector){
return createFeatureVector(featureVector->features,featureVector->size);
}
double computeL1NormBetweenFeatureVectors(FeatureVector *featureVector1,FeatureVector *featureVector2){
double totalRelativeDistance = 0;
double featDistance = 0;
for (int i = 0; i < featureVector1->size; ++i) {
featDistance = (featureVector1->features[i]-featureVector2->features[i]);
if(featDistance < 0){
featDistance *= -1;
}
totalRelativeDistance += featDistance;
}
totalRelativeDistance /= featureVector1->size;
return totalRelativeDistance;
}
void featureVectorAdditionInplace(FeatureVector *featureVector1,FeatureVector *featureVector2){
for (int i = 0; i < featureVector2->size; ++i) {
featureVector2->features[i] = featureVector1->features[i]+featureVector1->features[i];
}
}
void setValueInFeatureVector(FeatureVector *featureVector,float value){
for (int i = 0; i < featureVector->size; ++i) {
featureVector->features[i] = value;
}
}
FeatureMatrix* createFeatureMatrix(){
FeatureMatrix* featureMatrix = NULL;
featureMatrix = (FeatureMatrix*)calloc(1,sizeof(FeatureMatrix));
featureMatrix->nFeaturesVectors = 0;
featureMatrix->featureVector = NULL;
return featureMatrix;
}
FeatureMatrix* createFeatureMatrix(int nFeaturesVectors){
FeatureMatrix* featureMatrix = NULL;
featureMatrix = (FeatureMatrix*)calloc(1,sizeof(FeatureMatrix));
featureMatrix->nFeaturesVectors = nFeaturesVectors;
featureMatrix->featureVector = (FeatureVector**)calloc((size_t)nFeaturesVectors,sizeof(FeatureVector*));
return featureMatrix;
}
FeatureMatrix* createFeatureMatrix(int nFeaturesVectors,int vectorSize){
FeatureMatrix* featureMatrix = NULL;
featureMatrix = (FeatureMatrix*)calloc(1,sizeof(FeatureMatrix));
featureMatrix->nFeaturesVectors = nFeaturesVectors;
featureMatrix->featureVector = (FeatureVector**)calloc((size_t)nFeaturesVectors,sizeof(FeatureVector*));
for (int i = 0; i < nFeaturesVectors; ++i) {
featureMatrix->featureVector[i] = createFeatureVector(vectorSize);
}
return featureMatrix;
}
void destroyFeatureMatrix(FeatureMatrix** featureMatrix){
if(*featureMatrix == NULL){
return ;
}
for (int i = 0; i < (*featureMatrix)->nFeaturesVectors; ++i) {
destroyFeatureVector( &((*featureMatrix)->featureVector[i]) );
}
free((*featureMatrix)->featureVector);
free((*featureMatrix));
*featureMatrix = NULL;
}
void writeFeatureMatrix(FeatureMatrix* featureMatrix, char *filename){
FILE *fp = fopen(filename,"w");
for (int i = 0; i < featureMatrix->nFeaturesVectors; ++i) {
FeatureVector* vec = featureMatrix->featureVector[i];
for (int j = 0; j < vec->size; ++j) {
fprintf(fp,"%f",vec->features[j]);
if(!(j == vec->size-1)){
fprintf(fp," ");
}
}
fprintf(fp,"\n");
}
fclose(fp);
}
void addNewLines(FeatureMatrix** featureMatrix, int numberNewLines){
FeatureMatrix* aux = *featureMatrix;
// int numberLines = aux->nFeaturesVectors+numberNewLines;
// FeatureVector** copy = (FeatureVector**)calloc(numberLines,sizeof(FeatureVector*));
// for (int i = 0; i < aux->nFeaturesVectors; ++i) {
// copy[i] = aux->featureVector[i];
// }
// free(aux->featureVector);
// aux->featureVector = copy;
// aux->nFeaturesVectors = numberLines;
int numberLines = aux->nFeaturesVectors+numberNewLines;
FeatureVector** newRows = (FeatureVector**)realloc(aux->featureVector,(numberLines)*sizeof(FeatureVector*));
aux->featureVector = newRows;
//aux->featureVector = (FeatureVector**)realloc(aux->featureVector,(numberLines)*sizeof(FeatureVector*));
aux->nFeaturesVectors = numberLines;
}
void printFeatureMatrix(FeatureMatrix* featureMatrix){
if(featureMatrix == NULL){
printf("FeatureMatrix pointer is NULL\n");
return;
}
for (int i = 0; i < featureMatrix->nFeaturesVectors; ++i) {
printFeatureVector(featureMatrix->featureVector[i]);
}
printf("\n");
}
FeatureMatrix* copyFeatureMatrix(FeatureMatrix* featureMatrix){
FeatureMatrix *copy = createFeatureMatrix(featureMatrix->nFeaturesVectors);
for (int i = 0; i < featureMatrix->nFeaturesVectors; ++i) {
copy->featureVector[i] = copyFeatureVector(featureMatrix->featureVector[i]);
}
return copy;
}
int findNearestVectorUsingL1Norm(FeatureMatrix* featureMatrix, FeatureVector *featureVector){
int nearestClusterIndex = -1;
double distance;
double minDistance = DBL_MAX;
for (int i = 0; i < featureMatrix->nFeaturesVectors; ++i) {
distance = computeL1NormBetweenFeatureVectors(featureVector,
featureMatrix->featureVector[i]);
if(minDistance > distance){
minDistance = distance;
nearestClusterIndex = i;
}
}
return nearestClusterIndex;
}
void writeFeatureMatrix(FeatureMatrix *featureMatrix, char *filename, bool sameSize){
if(featureMatrix == NULL){
printf("[wirteFeatureMatrix] feature matrix is null");
return ;
}
if(featureMatrix->nFeaturesVectors <= 0){
printf("[wirteFeatureMatrix] invalid number of features vectors");
return ;
}
FILE *fp = fopen(filename,"w");
if(sameSize){
fprintf(fp,",1\n"); //uniform
fprintf(fp,"%d %d\n",featureMatrix->nFeaturesVectors, featureMatrix->featureVector[0]->size);
for (int i = 0; i < featureMatrix->nFeaturesVectors; ++i) {
FeatureVector* vec = featureMatrix->featureVector[i];
for (int j = 0; j < vec->size; ++j) {
fprintf(fp,"%f",vec->features[j]);
if(!(j == vec->size-1)){
fprintf(fp," ");
}
}
fprintf(fp,"\n");
}
}else{
fprintf(fp,",2\n"); //not uniform
fprintf(fp,"%d\n",featureMatrix->nFeaturesVectors);
for (int i = 0; i < featureMatrix->nFeaturesVectors; ++i) {
FeatureVector* vec = featureMatrix->featureVector[i];
fprintf(fp,"%d\n",vec->size);
for (int j = 0; j < vec->size; ++j) {
fprintf(fp,"%f",vec->features[j]);
if(!(j == vec->size-1)){
fprintf(fp," ");
}
}
fprintf(fp,"\n");
}
}
}
| 33.79932 | 120 | 0.633592 | [
"vector"
] |
a3dd91aac2878a378c6116accd4218849b90392c | 18,041 | cpp | C++ | src/gpu/GrSurfaceContext.cpp | ilopX/skia | 5b1196bc29fff703df90025589136969fe28aff0 | [
"BSD-3-Clause"
] | 1 | 2020-05-27T15:41:50.000Z | 2020-05-27T15:41:50.000Z | src/gpu/GrSurfaceContext.cpp | ilopX/skia | 5b1196bc29fff703df90025589136969fe28aff0 | [
"BSD-3-Clause"
] | null | null | null | src/gpu/GrSurfaceContext.cpp | ilopX/skia | 5b1196bc29fff703df90025589136969fe28aff0 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "src/gpu/GrSurfaceContext.h"
#include "include/private/GrRecordingContext.h"
#include "src/core/SkAutoPixmapStorage.h"
#include "src/gpu/GrAuditTrail.h"
#include "src/gpu/GrClip.h"
#include "src/gpu/GrContextPriv.h"
#include "src/gpu/GrDataUtils.h"
#include "src/gpu/GrDrawingManager.h"
#include "src/gpu/GrGpu.h"
#include "src/gpu/GrOpList.h"
#include "src/gpu/GrRecordingContextPriv.h"
#include "src/gpu/GrRenderTargetContext.h"
#include "src/gpu/GrSurfaceContextPriv.h"
#include "src/gpu/GrSurfacePriv.h"
#include "src/gpu/GrTextureContext.h"
#include "src/gpu/SkGr.h"
#define ASSERT_SINGLE_OWNER \
SkDEBUGCODE(GrSingleOwner::AutoEnforce debug_SingleOwner(this->singleOwner());)
#define RETURN_FALSE_IF_ABANDONED if (this->fContext->priv().abandoned()) { return false; }
// In MDB mode the reffing of the 'getLastOpList' call's result allows in-progress
// GrOpLists to be picked up and added to by renderTargetContexts lower in the call
// stack. When this occurs with a closed GrOpList, a new one will be allocated
// when the renderTargetContext attempts to use it (via getOpList).
GrSurfaceContext::GrSurfaceContext(GrRecordingContext* context,
GrColorType colorType,
SkAlphaType alphaType,
sk_sp<SkColorSpace> colorSpace)
: fContext(context), fColorSpaceInfo(colorType, alphaType, std::move(colorSpace)) {}
GrAuditTrail* GrSurfaceContext::auditTrail() {
return fContext->priv().auditTrail();
}
GrDrawingManager* GrSurfaceContext::drawingManager() {
return fContext->priv().drawingManager();
}
const GrDrawingManager* GrSurfaceContext::drawingManager() const {
return fContext->priv().drawingManager();
}
#ifdef SK_DEBUG
GrSingleOwner* GrSurfaceContext::singleOwner() {
return fContext->priv().singleOwner();
}
#endif
bool GrSurfaceContext::readPixels(const GrPixelInfo& origDstInfo, void* dst, size_t rowBytes,
SkIPoint pt, GrContext* direct) {
ASSERT_SINGLE_OWNER
RETURN_FALSE_IF_ABANDONED
SkDEBUGCODE(this->validate();)
GR_AUDIT_TRAIL_AUTO_FRAME(this->auditTrail(), "GrSurfaceContext::readPixels");
if (!direct && !(direct = fContext->priv().asDirectContext())) {
return false;
}
if (!dst) {
return false;
}
size_t tightRowBytes = origDstInfo.minRowBytes();
if (!rowBytes) {
rowBytes = tightRowBytes;
} else if (rowBytes < tightRowBytes) {
return false;
}
if (!origDstInfo.isValid()) {
return false;
}
GrSurfaceProxy* srcProxy = this->asSurfaceProxy();
// MDB TODO: delay this instantiation until later in the method
if (!srcProxy->instantiate(direct->priv().resourceProvider())) {
return false;
}
GrSurface* srcSurface = srcProxy->peekSurface();
auto dstInfo = origDstInfo;
if (!dstInfo.clip(this->width(), this->height(), &pt, &dst, rowBytes)) {
return false;
}
// Our tight row bytes may have been changed by clipping.
tightRowBytes = dstInfo.minRowBytes();
bool premul = this->colorSpaceInfo().alphaType() == kUnpremul_SkAlphaType &&
dstInfo.alphaType() == kPremul_SkAlphaType;
bool unpremul = this->colorSpaceInfo().alphaType() == kPremul_SkAlphaType &&
dstInfo.alphaType() == kUnpremul_SkAlphaType;
bool needColorConversion = SkColorSpaceXformSteps::Required(this->colorSpaceInfo().colorSpace(),
dstInfo.colorSpace());
const GrCaps* caps = direct->priv().caps();
// This is the getImageData equivalent to the canvas2D putImageData fast path. We probably don't
// care so much about getImageData performance. However, in order to ensure putImageData/
// getImageData in "legacy" mode are round-trippable we use the GPU to do the complementary
// unpremul step to writeSurfacePixels's premul step (which is determined empirically in
// fContext->vaildaPMUPMConversionExists()).
bool canvas2DFastPath = unpremul && !needColorConversion &&
(GrColorType::kRGBA_8888 == dstInfo.colorType() ||
GrColorType::kBGRA_8888 == dstInfo.colorType()) &&
SkToBool(srcProxy->asTextureProxy()) &&
(srcProxy->config() == kRGBA_8888_GrPixelConfig ||
srcProxy->config() == kBGRA_8888_GrPixelConfig) &&
caps->isConfigRenderable(kRGBA_8888_GrPixelConfig) &&
direct->priv().validPMUPMConversionExists();
auto readFlag = caps->surfaceSupportsReadPixels(srcSurface);
if (readFlag == GrCaps::SurfaceReadPixelsSupport::kUnsupported) {
return false;
}
if (readFlag == GrCaps::SurfaceReadPixelsSupport::kCopyToTexture2D || canvas2DFastPath) {
GrColorType colorType = canvas2DFastPath ? GrColorType::kRGBA_8888
: this->colorSpaceInfo().colorType();
sk_sp<SkColorSpace> cs = canvas2DFastPath ? nullptr
: this->colorSpaceInfo().refColorSpace();
sk_sp<GrRenderTargetContext> tempCtx = direct->priv().makeDeferredRenderTargetContext(
SkBackingFit::kApprox, dstInfo.width(), dstInfo.height(), colorType, std::move(cs),
1, GrMipMapped::kNo, kTopLeft_GrSurfaceOrigin, nullptr, SkBudgeted::kYes);
if (!tempCtx) {
return false;
}
std::unique_ptr<GrFragmentProcessor> fp;
if (canvas2DFastPath) {
fp = direct->priv().createPMToUPMEffect(
GrSimpleTextureEffect::Make(sk_ref_sp(srcProxy->asTextureProxy()),
SkMatrix::I()));
if (dstInfo.colorType() == GrColorType::kBGRA_8888) {
fp = GrFragmentProcessor::SwizzleOutput(std::move(fp), GrSwizzle::BGRA());
dstInfo = dstInfo.makeColorType(GrColorType::kRGBA_8888);
}
// The render target context is incorrectly tagged as kPremul even though we're writing
// unpremul data thanks to the PMToUPM effect. Fake out the dst alpha type so we don't
// double unpremul.
dstInfo = dstInfo.makeAlphaType(kPremul_SkAlphaType);
} else {
fp = GrSimpleTextureEffect::Make(sk_ref_sp(srcProxy->asTextureProxy()), SkMatrix::I());
}
if (!fp) {
return false;
}
GrPaint paint;
paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
paint.addColorFragmentProcessor(std::move(fp));
tempCtx->asRenderTargetContext()->fillRectToRect(
GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(),
SkRect::MakeWH(dstInfo.width(), dstInfo.height()),
SkRect::MakeXYWH(pt.fX, pt.fY, dstInfo.width(), dstInfo.height()));
return tempCtx->readPixels(dstInfo, dst, rowBytes, {0, 0}, direct);
}
bool flip = srcProxy->origin() == kBottomLeft_GrSurfaceOrigin;
auto supportedRead = caps->supportedReadPixelsColorType(
srcProxy->config(), srcProxy->backendFormat(), dstInfo.colorType());
bool makeTight = !caps->readPixelsRowBytesSupport() && tightRowBytes != rowBytes;
bool convert = unpremul || premul || needColorConversion || flip || makeTight ||
(dstInfo.colorType() != supportedRead.fColorType) ||
supportedRead.fSwizzle != GrSwizzle::RGBA();
std::unique_ptr<char[]> tmpPixels;
GrPixelInfo tmpInfo;
void* readDst = dst;
size_t readRB = rowBytes;
if (convert) {
tmpInfo = {supportedRead.fColorType, this->colorSpaceInfo().alphaType(),
this->colorSpaceInfo().refColorSpace(), dstInfo.width(), dstInfo.height()};
size_t tmpRB = tmpInfo.minRowBytes();
size_t size = tmpRB * tmpInfo.height();
// Chrome MSAN bots require the data to be initialized (hence the ()).
tmpPixels.reset(new char[size]());
readDst = tmpPixels.get();
readRB = tmpRB;
pt.fY = flip ? srcSurface->height() - pt.fY - dstInfo.height() : pt.fY;
}
direct->priv().flushSurface(srcProxy);
if (!direct->priv().getGpu()->readPixels(srcSurface, pt.fX, pt.fY, dstInfo.width(),
dstInfo.height(), supportedRead.fColorType, readDst,
readRB)) {
return false;
}
if (convert) {
return GrConvertPixels(dstInfo, dst, rowBytes, tmpInfo, readDst, readRB, flip,
supportedRead.fSwizzle);
}
return true;
}
bool GrSurfaceContext::writePixels(const GrPixelInfo& origSrcInfo, const void* src, size_t rowBytes,
SkIPoint pt, GrContext* direct) {
ASSERT_SINGLE_OWNER
RETURN_FALSE_IF_ABANDONED
SkDEBUGCODE(this->validate();)
GR_AUDIT_TRAIL_AUTO_FRAME(this->auditTrail(), "GrSurfaceContext::writePixels");
if (!direct && !(direct = fContext->priv().asDirectContext())) {
return false;
}
if (this->asSurfaceProxy()->readOnly()) {
return false;
}
if (!src) {
return false;
}
size_t tightRowBytes = origSrcInfo.minRowBytes();
if (!rowBytes) {
rowBytes = tightRowBytes;
} else if (rowBytes < tightRowBytes) {
return false;
}
if (!origSrcInfo.isValid()) {
return false;
}
GrSurfaceProxy* dstProxy = this->asSurfaceProxy();
if (!dstProxy->instantiate(direct->priv().resourceProvider())) {
return false;
}
GrSurface* dstSurface = dstProxy->peekSurface();
auto srcInfo = origSrcInfo;
if (!srcInfo.clip(this->width(), this->height(), &pt, &src, rowBytes)) {
return false;
}
// Our tight row bytes may have been changed by clipping.
tightRowBytes = srcInfo.minRowBytes();
bool premul = this->colorSpaceInfo().alphaType() == kPremul_SkAlphaType &&
srcInfo.alphaType() == kUnpremul_SkAlphaType;
bool unpremul = this->colorSpaceInfo().alphaType() == kUnpremul_SkAlphaType &&
srcInfo.alphaType() == kPremul_SkAlphaType;
bool needColorConversion = SkColorSpaceXformSteps::Required(
srcInfo.colorSpace(), this->colorSpaceInfo().colorSpace());
const GrCaps* caps = direct->priv().caps();
// For canvas2D putImageData performance we have a special code path for unpremul RGBA_8888 srcs
// that are premultiplied on the GPU. This is kept as narrow as possible for now.
bool canvas2DFastPath = !caps->avoidWritePixelsFastPath() && premul && !needColorConversion &&
(srcInfo.colorType() == GrColorType::kRGBA_8888 ||
srcInfo.colorType() == GrColorType::kBGRA_8888) &&
SkToBool(this->asRenderTargetContext()) &&
(dstProxy->config() == kRGBA_8888_GrPixelConfig ||
dstProxy->config() == kBGRA_8888_GrPixelConfig) &&
direct->priv().caps()->isConfigTexturable(kRGBA_8888_GrPixelConfig) &&
direct->priv().validPMUPMConversionExists();
if (!caps->surfaceSupportsWritePixels(dstSurface) || canvas2DFastPath) {
GrSurfaceDesc desc;
desc.fWidth = srcInfo.width();
desc.fHeight = srcInfo.height();
desc.fSampleCnt = 1;
GrColorType colorType;
GrBackendFormat format;
SkAlphaType alphaType;
if (canvas2DFastPath) {
desc.fConfig = kRGBA_8888_GrPixelConfig;
colorType = GrColorType::kRGBA_8888;
format = caps->getBackendFormatFromColorType(kRGBA_8888_SkColorType);
alphaType = kUnpremul_SkAlphaType;
} else {
desc.fConfig = dstProxy->config();
colorType = this->colorSpaceInfo().colorType();
format = dstProxy->backendFormat().makeTexture2D();
if (!format.isValid()) {
return false;
}
alphaType = this->colorSpaceInfo().alphaType();
}
// It is more efficient for us to write pixels into a top left origin so we prefer that.
// However, if the final proxy isn't a render target then we must use a copy to move the
// data into it which requires the origins to match. If the final proxy is a render target
// we can use a draw instead which doesn't have this origin restriction. Thus for render
// targets we will use top left and otherwise we will make the origins match.
GrSurfaceOrigin tempOrigin =
this->asRenderTargetContext() ? kTopLeft_GrSurfaceOrigin : dstProxy->origin();
auto tempProxy = direct->priv().proxyProvider()->createProxy(
format, desc, tempOrigin, SkBackingFit::kApprox, SkBudgeted::kYes);
if (!tempProxy) {
return false;
}
auto tempCtx = direct->priv().drawingManager()->makeTextureContext(
tempProxy, colorType, alphaType, this->colorSpaceInfo().refColorSpace());
if (!tempCtx) {
return false;
}
// In the fast path we always write the srcData to the temp context as though it were RGBA.
// When the data is really BGRA the write will cause the R and B channels to be swapped in
// the intermediate surface which gets corrected by a swizzle effect when drawing to the
// dst.
if (canvas2DFastPath) {
srcInfo = srcInfo.makeColorType(GrColorType::kRGBA_8888);
}
if (!tempCtx->writePixels(srcInfo, src, rowBytes, {0, 0}, direct)) {
return false;
}
if (this->asRenderTargetContext()) {
std::unique_ptr<GrFragmentProcessor> fp;
if (canvas2DFastPath) {
fp = direct->priv().createUPMToPMEffect(
GrSimpleTextureEffect::Make(std::move(tempProxy), SkMatrix::I()));
// Important: check the original src color type here!
if (origSrcInfo.colorType() == GrColorType::kBGRA_8888) {
fp = GrFragmentProcessor::SwizzleOutput(std::move(fp), GrSwizzle::BGRA());
}
} else {
fp = GrSimpleTextureEffect::Make(std::move(tempProxy), SkMatrix::I());
}
if (!fp) {
return false;
}
GrPaint paint;
paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
paint.addColorFragmentProcessor(std::move(fp));
this->asRenderTargetContext()->fillRectToRect(
GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(),
SkRect::MakeXYWH(pt.fX, pt.fY, srcInfo.width(), srcInfo.height()),
SkRect::MakeWH(srcInfo.width(), srcInfo.height()));
} else {
SkIRect srcRect = SkIRect::MakeWH(srcInfo.width(), srcInfo.height());
SkIPoint dstPoint = SkIPoint::Make(pt.fX, pt.fY);
if (!this->copy(tempProxy.get(), srcRect, dstPoint)) {
return false;
}
}
return true;
}
GrColorType allowedColorType =
caps->supportedWritePixelsColorType(dstProxy->config(), srcInfo.colorType());
bool flip = dstProxy->origin() == kBottomLeft_GrSurfaceOrigin;
bool makeTight = !caps->writePixelsRowBytesSupport() && rowBytes != tightRowBytes;
bool convert = premul || unpremul || needColorConversion || makeTight ||
(srcInfo.colorType() != allowedColorType) || flip;
std::unique_ptr<char[]> tmpPixels;
GrColorType srcColorType = srcInfo.colorType();
if (convert) {
GrPixelInfo tmpInfo(allowedColorType, this->colorSpaceInfo().alphaType(),
this->colorSpaceInfo().refColorSpace(), srcInfo.width(),
srcInfo.height());
auto tmpRB = tmpInfo.minRowBytes();
tmpPixels.reset(new char[tmpRB * tmpInfo.height()]);
GrConvertPixels(tmpInfo, tmpPixels.get(), tmpRB, srcInfo, src, rowBytes, flip);
srcColorType = tmpInfo.colorType();
rowBytes = tmpRB;
src = tmpPixels.get();
pt.fY = flip ? dstSurface->height() - pt.fY - tmpInfo.height() : pt.fY;
}
// On platforms that prefer flushes over VRAM use (i.e., ANGLE) we're better off forcing a
// complete flush here. On platforms that prefer VRAM use over flushes we're better off
// giving the drawing manager the chance of skipping the flush (i.e., by passing in the
// destination proxy)
// TODO: should this policy decision just be moved into the drawing manager?
direct->priv().flushSurface(caps->preferVRAMUseOverFlushes() ? dstProxy : nullptr);
return direct->priv().getGpu()->writePixels(dstSurface, pt.fX, pt.fY, srcInfo.width(),
srcInfo.height(), srcColorType, src, rowBytes);
}
bool GrSurfaceContext::copy(GrSurfaceProxy* src, const SkIRect& srcRect, const SkIPoint& dstPoint) {
ASSERT_SINGLE_OWNER
RETURN_FALSE_IF_ABANDONED
SkDEBUGCODE(this->validate();)
GR_AUDIT_TRAIL_AUTO_FRAME(this->auditTrail(), "GrSurfaceContextPriv::copy");
SkASSERT(src->backendFormat().textureType() != GrTextureType::kExternal);
SkASSERT(src->origin() == this->asSurfaceProxy()->origin());
SkASSERT(src->config() == this->asSurfaceProxy()->config());
GrSurfaceProxy* dst = this->asSurfaceProxy();
if (!fContext->priv().caps()->canCopySurface(dst, src, srcRect, dstPoint)) {
return false;
}
return this->getOpList()->copySurface(fContext, dst, src, srcRect, dstPoint);
}
| 43.057279 | 100 | 0.621141 | [
"render"
] |
a3dd9ac4a498b6e9e296862edadb19ba898d5b33 | 13,076 | cpp | C++ | clang-tools-extra/clangd/JSONRPCDispatcher.cpp | nickbabcock/EECS381StyleCheck | 271a15140229e5dbc1798328edfe6ca8c632a7be | [
"MIT"
] | 3 | 2018-03-22T05:23:45.000Z | 2018-09-11T17:19:08.000Z | clang-tools-extra/clangd/JSONRPCDispatcher.cpp | nickbabcock/EECS381StyleCheck | 271a15140229e5dbc1798328edfe6ca8c632a7be | [
"MIT"
] | null | null | null | clang-tools-extra/clangd/JSONRPCDispatcher.cpp | nickbabcock/EECS381StyleCheck | 271a15140229e5dbc1798328edfe6ca8c632a7be | [
"MIT"
] | null | null | null | //===--- JSONRPCDispatcher.cpp - Main JSON parser entry point -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "JSONRPCDispatcher.h"
#include "Cancellation.h"
#include "ProtocolHandlers.h"
#include "Trace.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/Chrono.h"
#include "llvm/Support/Errno.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/JSON.h"
#include "llvm/Support/SourceMgr.h"
#include <istream>
using namespace llvm;
using namespace clang;
using namespace clangd;
namespace {
static Key<json::Value> RequestID;
static Key<JSONOutput *> RequestOut;
// When tracing, we trace a request and attach the response in reply().
// Because the Span isn't available, we find the current request using Context.
class RequestSpan {
RequestSpan(llvm::json::Object *Args) : Args(Args) {}
std::mutex Mu;
llvm::json::Object *Args;
static Key<std::unique_ptr<RequestSpan>> RSKey;
public:
// Return a context that's aware of the enclosing request, identified by Span.
static Context stash(const trace::Span &Span) {
return Context::current().derive(
RSKey, std::unique_ptr<RequestSpan>(new RequestSpan(Span.Args)));
}
// If there's an enclosing request and the tracer is interested, calls \p F
// with a json::Object where request info can be added.
template <typename Func> static void attach(Func &&F) {
auto *RequestArgs = Context::current().get(RSKey);
if (!RequestArgs || !*RequestArgs || !(*RequestArgs)->Args)
return;
std::lock_guard<std::mutex> Lock((*RequestArgs)->Mu);
F(*(*RequestArgs)->Args);
}
};
Key<std::unique_ptr<RequestSpan>> RequestSpan::RSKey;
} // namespace
void JSONOutput::writeMessage(const json::Value &Message) {
std::string S;
llvm::raw_string_ostream OS(S);
if (Pretty)
OS << llvm::formatv("{0:2}", Message);
else
OS << Message;
OS.flush();
{
std::lock_guard<std::mutex> Guard(StreamMutex);
Outs << "Content-Length: " << S.size() << "\r\n\r\n" << S;
Outs.flush();
}
vlog(">>> {0}\n", S);
}
void JSONOutput::log(Logger::Level Level,
const llvm::formatv_object_base &Message) {
if (Level < MinLevel)
return;
llvm::sys::TimePoint<> Timestamp = std::chrono::system_clock::now();
trace::log(Message);
std::lock_guard<std::mutex> Guard(StreamMutex);
Logs << llvm::formatv("{0}[{1:%H:%M:%S.%L}] {2}\n", indicator(Level),
Timestamp, Message);
Logs.flush();
}
void JSONOutput::mirrorInput(const Twine &Message) {
if (!InputMirror)
return;
*InputMirror << Message;
InputMirror->flush();
}
void clangd::reply(json::Value &&Result) {
auto ID = getRequestId();
if (!ID) {
elog("Attempted to reply to a notification!");
return;
}
RequestSpan::attach([&](json::Object &Args) { Args["Reply"] = Result; });
log("--> reply({0})", *ID);
Context::current()
.getExisting(RequestOut)
->writeMessage(json::Object{
{"jsonrpc", "2.0"},
{"id", *ID},
{"result", std::move(Result)},
});
}
void clangd::replyError(ErrorCode Code, const llvm::StringRef &Message) {
elog("Error {0}: {1}", static_cast<int>(Code), Message);
RequestSpan::attach([&](json::Object &Args) {
Args["Error"] = json::Object{{"code", static_cast<int>(Code)},
{"message", Message.str()}};
});
if (auto ID = getRequestId()) {
log("--> reply({0}) error: {1}", *ID, Message);
Context::current()
.getExisting(RequestOut)
->writeMessage(json::Object{
{"jsonrpc", "2.0"},
{"id", *ID},
{"error", json::Object{{"code", static_cast<int>(Code)},
{"message", Message}}},
});
}
}
void clangd::replyError(Error E) {
handleAllErrors(std::move(E),
[](const CancelledError &TCE) {
replyError(ErrorCode::RequestCancelled, TCE.message());
},
[](const ErrorInfoBase &EIB) {
replyError(ErrorCode::InvalidParams, EIB.message());
});
}
void clangd::call(StringRef Method, json::Value &&Params) {
RequestSpan::attach([&](json::Object &Args) {
Args["Call"] = json::Object{{"method", Method.str()}, {"params", Params}};
});
// FIXME: Generate/Increment IDs for every request so that we can get proper
// replies once we need to.
auto ID = 1;
log("--> {0}({1})", Method, ID);
Context::current()
.getExisting(RequestOut)
->writeMessage(json::Object{
{"jsonrpc", "2.0"},
{"id", ID},
{"method", Method},
{"params", std::move(Params)},
});
}
void JSONRPCDispatcher::registerHandler(StringRef Method, Handler H) {
assert(!Handlers.count(Method) && "Handler already registered!");
Handlers[Method] = std::move(H);
}
static void logIncomingMessage(const llvm::Optional<json::Value> &ID,
llvm::Optional<StringRef> Method,
const json::Object *Error) {
if (Method) { // incoming request
if (ID) // call
log("<-- {0}({1})", *Method, *ID);
else // notification
log("<-- {0}", *Method);
} else if (ID) { // response, ID must be provided
if (Error)
log("<-- reply({0}) error: {1}", *ID,
Error->getString("message").getValueOr("<no message>"));
else
log("<-- reply({0})", *ID);
}
}
bool JSONRPCDispatcher::call(const json::Value &Message,
JSONOutput &Out) const {
// Message must be an object with "jsonrpc":"2.0".
auto *Object = Message.getAsObject();
if (!Object || Object->getString("jsonrpc") != Optional<StringRef>("2.0"))
return false;
// ID may be any JSON value. If absent, this is a notification.
llvm::Optional<json::Value> ID;
if (auto *I = Object->get("id"))
ID = std::move(*I);
auto Method = Object->getString("method");
logIncomingMessage(ID, Method, Object->getObject("error"));
if (!Method) // We only handle incoming requests, and ignore responses.
return false;
// Params should be given, use null if not.
json::Value Params = nullptr;
if (auto *P = Object->get("params"))
Params = std::move(*P);
auto I = Handlers.find(*Method);
auto &Handler = I != Handlers.end() ? I->second : UnknownHandler;
// Create a Context that contains request information.
WithContextValue WithRequestOut(RequestOut, &Out);
llvm::Optional<WithContextValue> WithID;
if (ID)
WithID.emplace(RequestID, *ID);
// Create a tracing Span covering the whole request lifetime.
trace::Span Tracer(*Method);
if (ID)
SPAN_ATTACH(Tracer, "ID", *ID);
SPAN_ATTACH(Tracer, "Params", Params);
// Stash a reference to the span args, so later calls can add metadata.
WithContext WithRequestSpan(RequestSpan::stash(Tracer));
Handler(std::move(Params));
return true;
}
// Tries to read a line up to and including \n.
// If failing, feof() or ferror() will be set.
static bool readLine(std::FILE *In, std::string &Out) {
static constexpr int BufSize = 1024;
size_t Size = 0;
Out.clear();
for (;;) {
Out.resize(Size + BufSize);
// Handle EINTR which is sent when a debugger attaches on some platforms.
if (!llvm::sys::RetryAfterSignal(nullptr, ::fgets, &Out[Size], BufSize, In))
return false;
clearerr(In);
// If the line contained null bytes, anything after it (including \n) will
// be ignored. Fortunately this is not a legal header or JSON.
size_t Read = std::strlen(&Out[Size]);
if (Read > 0 && Out[Size + Read - 1] == '\n') {
Out.resize(Size + Read);
return true;
}
Size += Read;
}
}
// Returns None when:
// - ferror() or feof() are set.
// - Content-Length is missing or empty (protocol error)
static llvm::Optional<std::string> readStandardMessage(std::FILE *In,
JSONOutput &Out) {
// A Language Server Protocol message starts with a set of HTTP headers,
// delimited by \r\n, and terminated by an empty line (\r\n).
unsigned long long ContentLength = 0;
std::string Line;
while (true) {
if (feof(In) || ferror(In) || !readLine(In, Line))
return llvm::None;
Out.mirrorInput(Line);
llvm::StringRef LineRef(Line);
// We allow comments in headers. Technically this isn't part
// of the LSP specification, but makes writing tests easier.
if (LineRef.startswith("#"))
continue;
// Content-Length is a mandatory header, and the only one we handle.
if (LineRef.consume_front("Content-Length: ")) {
if (ContentLength != 0) {
elog("Warning: Duplicate Content-Length header received. "
"The previous value for this message ({0}) was ignored.",
ContentLength);
}
llvm::getAsUnsignedInteger(LineRef.trim(), 0, ContentLength);
continue;
} else if (!LineRef.trim().empty()) {
// It's another header, ignore it.
continue;
} else {
// An empty line indicates the end of headers.
// Go ahead and read the JSON.
break;
}
}
// The fuzzer likes crashing us by sending "Content-Length: 9999999999999999"
if (ContentLength > 1 << 30) { // 1024M
elog("Refusing to read message with long Content-Length: {0}. "
"Expect protocol errors",
ContentLength);
return llvm::None;
}
if (ContentLength == 0) {
log("Warning: Missing Content-Length header, or zero-length message.");
return llvm::None;
}
std::string JSON(ContentLength, '\0');
for (size_t Pos = 0, Read; Pos < ContentLength; Pos += Read) {
// Handle EINTR which is sent when a debugger attaches on some platforms.
Read = llvm::sys::RetryAfterSignal(0u, ::fread, &JSON[Pos], 1,
ContentLength - Pos, In);
Out.mirrorInput(StringRef(&JSON[Pos], Read));
if (Read == 0) {
elog("Input was aborted. Read only {0} bytes of expected {1}.", Pos,
ContentLength);
return llvm::None;
}
clearerr(In); // If we're done, the error was transient. If we're not done,
// either it was transient or we'll see it again on retry.
Pos += Read;
}
return std::move(JSON);
}
// For lit tests we support a simplified syntax:
// - messages are delimited by '---' on a line by itself
// - lines starting with # are ignored.
// This is a testing path, so favor simplicity over performance here.
// When returning None, feof() or ferror() will be set.
static llvm::Optional<std::string> readDelimitedMessage(std::FILE *In,
JSONOutput &Out) {
std::string JSON;
std::string Line;
while (readLine(In, Line)) {
auto LineRef = llvm::StringRef(Line).trim();
if (LineRef.startswith("#")) // comment
continue;
// found a delimiter
if (LineRef.rtrim() == "---")
break;
JSON += Line;
}
if (ferror(In)) {
elog("Input error while reading message!");
return llvm::None;
} else { // Including EOF
Out.mirrorInput(
llvm::formatv("Content-Length: {0}\r\n\r\n{1}", JSON.size(), JSON));
return std::move(JSON);
}
}
// The use of C-style std::FILE* IO deserves some explanation.
// Previously, std::istream was used. When a debugger attached on MacOS, the
// process received EINTR, the stream went bad, and clangd exited.
// A retry-on-EINTR loop around reads solved this problem, but caused clangd to
// sometimes hang rather than exit on other OSes. The interaction between
// istreams and signals isn't well-specified, so it's hard to get this right.
// The C APIs seem to be clearer in this respect.
void clangd::runLanguageServerLoop(std::FILE *In, JSONOutput &Out,
JSONStreamStyle InputStyle,
JSONRPCDispatcher &Dispatcher,
bool &IsDone) {
auto &ReadMessage =
(InputStyle == Delimited) ? readDelimitedMessage : readStandardMessage;
while (!IsDone && !feof(In)) {
if (ferror(In)) {
elog("IO error: {0}", llvm::sys::StrError());
return;
}
if (auto JSON = ReadMessage(In, Out)) {
if (auto Doc = json::parse(*JSON)) {
// Log the formatted message.
vlog(Out.Pretty ? "<<< {0:2}\n" : "<<< {0}\n", *Doc);
// Finally, execute the action for this JSON message.
if (!Dispatcher.call(*Doc, Out))
elog("JSON dispatch failed!");
} else {
// Parse error. Log the raw message.
vlog("<<< {0}\n", *JSON);
elog("JSON parse error: {0}", llvm::toString(Doc.takeError()));
}
}
}
}
const json::Value *clangd::getRequestId() {
return Context::current().get(RequestID);
}
| 34.052083 | 80 | 0.604696 | [
"object"
] |
a3dfad126c0518a941a0758f3bf285610a4abfaf | 7,960 | cpp | C++ | venv/boost_1_73_0/libs/graph/test/bfs.cpp | uosorio/heroku_face | 7d6465e71dba17a15d8edaef520adb2fcd09d91e | [
"Apache-2.0"
] | 106 | 2015-08-07T04:23:50.000Z | 2020-12-27T18:25:15.000Z | 3rdparty/boost_1_73_0/libs/graph/test/bfs.cpp | qingkouwei/mediaones | cec475e1bfd5807b5351cc7e38d244ac5298ca16 | [
"MIT"
] | 130 | 2016-06-22T22:11:25.000Z | 2020-11-29T20:24:09.000Z | Libs/boost_1_76_0/libs/graph/test/bfs.cpp | Antd23rus/S2DE | 47cc7151c2934cd8f0399a9856c1e54894571553 | [
"MIT"
] | 41 | 2015-07-08T19:18:35.000Z | 2021-01-14T16:39:56.000Z | //=======================================================================
// Copyright 2001 University of Notre Dame.
// Author: Andrew Janiszewski, Jeremy G. Siek
//
// 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 <boost/core/lightweight_test.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/random.hpp>
#include <boost/graph/graph_utility.hpp>
#include <boost/graph/graph_archetypes.hpp>
#include <boost/graph/breadth_first_search.hpp>
#include <boost/random/mersenne_twister.hpp>
#ifdef BOOST_NO_ARGUMENT_DEPENDENT_LOOKUP
using namespace boost;
#endif
template < typename DistanceMap, typename ParentMap, typename Graph,
typename ColorMap >
class bfs_testing_visitor
{
typedef typename boost::graph_traits< Graph >::vertex_descriptor Vertex;
typedef typename boost::graph_traits< Graph >::edge_descriptor Edge;
typedef typename boost::color_traits<
typename boost::property_traits< ColorMap >::value_type >
Color;
public:
bfs_testing_visitor(Vertex s, DistanceMap d, ParentMap p, ColorMap c)
: current_distance(0), distance(d), parent(p), color(c), src(s)
{
}
void initialize_vertex(const Vertex& u, const Graph&) const
{
BOOST_TEST(get(color, u) == Color::white());
}
void examine_vertex(const Vertex& u, const Graph&) const
{
current_vertex = u;
// Ensure that the distances monotonically increase.
BOOST_TEST(distance[u] == current_distance
|| distance[u] == current_distance + 1);
if (distance[u] == current_distance + 1) // new level
++current_distance;
}
void discover_vertex(const Vertex& u, const Graph&) const
{
BOOST_TEST(get(color, u) == Color::gray());
if (u == src)
{
current_vertex = src;
}
else
{
BOOST_TEST(parent[u] == current_vertex);
BOOST_TEST(distance[u] == current_distance + 1);
BOOST_TEST(distance[u] == distance[parent[u]] + 1);
}
}
void examine_edge(const Edge& e, const Graph& g) const
{
BOOST_TEST(source(e, g) == current_vertex);
}
void tree_edge(const Edge& e, const Graph& g) const
{
BOOST_TEST(get(color, target(e, g)) == Color::white());
Vertex u = source(e, g), v = target(e, g);
BOOST_TEST(distance[u] == current_distance);
parent[v] = u;
distance[v] = distance[u] + 1;
}
void non_tree_edge(const Edge& e, const Graph& g) const
{
BOOST_TEST(color[target(e, g)] != Color::white());
if (boost::is_directed(g))
// cross or back edge
BOOST_TEST(distance[target(e, g)] <= distance[source(e, g)] + 1);
else
{
// cross edge (or going backwards on a tree edge)
BOOST_TEST(distance[target(e, g)] == distance[source(e, g)]
|| distance[target(e, g)] == distance[source(e, g)] + 1
|| distance[target(e, g)] == distance[source(e, g)] - 1);
}
}
void gray_target(const Edge& e, const Graph& g) const
{
BOOST_TEST(color[target(e, g)] == Color::gray());
}
void black_target(const Edge& e, const Graph& g) const
{
BOOST_TEST(color[target(e, g)] == Color::black());
// All vertices adjacent to a black vertex must already be discovered
typename boost::graph_traits< Graph >::adjacency_iterator ai, ai_end;
for (boost::tie(ai, ai_end) = adjacent_vertices(target(e, g), g);
ai != ai_end; ++ai)
BOOST_TEST(color[*ai] != Color::white());
}
void finish_vertex(const Vertex& u, const Graph&) const
{
BOOST_TEST(color[u] == Color::black());
}
private:
mutable Vertex current_vertex;
mutable typename boost::property_traits< DistanceMap >::value_type
current_distance;
DistanceMap distance;
ParentMap parent;
ColorMap color;
Vertex src;
};
template < class Graph > struct bfs_test
{
typedef boost::graph_traits< Graph > Traits;
typedef typename Traits::vertices_size_type vertices_size_type;
static void go(vertices_size_type max_V)
{
typedef typename Traits::vertex_descriptor vertex_descriptor;
typedef boost::color_traits< boost::default_color_type > Color;
vertices_size_type i;
typename Traits::edges_size_type j;
typename Traits::vertex_iterator ui, ui_end;
boost::mt19937 gen;
for (i = 0; i < max_V; ++i)
for (j = 0; j < i * i; ++j)
{
Graph g;
boost::generate_random_graph(g, i, j, gen);
// declare the "start" variable
vertex_descriptor start = boost::random_vertex(g, gen);
// vertex properties
std::vector< int > distance(
i, (std::numeric_limits< int >::max)());
distance[start] = 0;
std::vector< vertex_descriptor > parent(i);
for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)
parent[*ui] = *ui;
std::vector< boost::default_color_type > color(i);
// Get vertex index map
typedef typename boost::property_map< Graph,
boost::vertex_index_t >::const_type idx_type;
idx_type idx = get(boost::vertex_index, g);
// Make property maps from vectors
typedef boost::iterator_property_map<
std::vector< int >::iterator, idx_type >
distance_pm_type;
distance_pm_type distance_pm(distance.begin(), idx);
typedef boost::iterator_property_map<
typename std::vector< vertex_descriptor >::iterator,
idx_type >
parent_pm_type;
parent_pm_type parent_pm(parent.begin(), idx);
typedef boost::iterator_property_map<
std::vector< boost::default_color_type >::iterator,
idx_type >
color_pm_type;
color_pm_type color_pm(color.begin(), idx);
// Create the testing visitor.
bfs_testing_visitor< distance_pm_type, parent_pm_type, Graph,
color_pm_type >
vis(start, distance_pm, parent_pm, color_pm);
boost::breadth_first_search(
g, start, visitor(vis).color_map(color_pm));
// All white vertices should be unreachable from the source.
for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)
if (color[*ui] == Color::white())
{
std::vector< boost::default_color_type > color2(
i, Color::white());
BOOST_TEST(!boost::is_reachable(
start, *ui, g, color_pm_type(color2.begin(), idx)));
}
// The shortest path to a child should be one longer than
// shortest path to the parent.
for (boost::tie(ui, ui_end) = vertices(g); ui != ui_end; ++ui)
if (parent[*ui] != *ui) // *ui not the root of the bfs tree
BOOST_TEST(distance[*ui] == distance[parent[*ui]] + 1);
}
}
};
int main(int argc, char* argv[])
{
using namespace boost;
int max_V = 7;
if (argc > 1)
max_V = atoi(argv[1]);
bfs_test< adjacency_list< vecS, vecS, directedS > >::go(max_V);
bfs_test< adjacency_list< vecS, vecS, undirectedS > >::go(max_V);
return boost::report_errors();
}
| 36.851852 | 80 | 0.563191 | [
"vector"
] |
a3e0891dd91801f24d33ca65fb15b27101b1c493 | 32,059 | cpp | C++ | Code/GraphMol/ChemTransforms/ChemTransforms.cpp | jungb-basf/rdkit | 5d0eb77c655b6ba91f0891e7dc51e658aced3d00 | [
"BSD-3-Clause"
] | 1 | 2020-04-04T18:15:17.000Z | 2020-04-04T18:15:17.000Z | Code/GraphMol/ChemTransforms/ChemTransforms.cpp | jungb-basf/rdkit | 5d0eb77c655b6ba91f0891e7dc51e658aced3d00 | [
"BSD-3-Clause"
] | 9 | 2016-08-08T13:53:40.000Z | 2020-03-08T05:52:07.000Z | Code/GraphMol/ChemTransforms/ChemTransforms.cpp | bp-kelley/rdkit | e0de7c9622ce73894b1e7d9568532f6d5638058a | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright (C) 2006-2020 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <RDGeneral/utils.h>
#include <RDGeneral/Invariant.h>
#include <RDGeneral/RDLog.h>
#include <GraphMol/RDKitQueries.h>
#include <RDGeneral/Exceptions.h>
#include <GraphMol/RDKitBase.h>
#include <GraphMol/Substruct/SubstructMatch.h>
#include <RDGeneral/BoostStartInclude.h>
#include <boost/dynamic_bitset.hpp>
#include <boost/tokenizer.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string.hpp>
#include <RDGeneral/BoostEndInclude.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <sstream>
#include <GraphMol/SmilesParse/SmilesParse.h>
#include <RDGeneral/StreamOps.h>
#include <RDGeneral/FileParseException.h>
#include <RDGeneral/BadFileException.h>
#include <GraphMol/ChemTransforms/ChemTransforms.h>
namespace RDKit {
namespace {
void updateSubMolConfs(const ROMol &mol, RWMol &res,
boost::dynamic_bitset<> &removedAtoms) {
// update conformer information:
res.clearConformers();
for (auto citer = mol.beginConformers(); citer != mol.endConformers();
++citer) {
auto *newConf = new Conformer(res.getNumAtoms());
newConf->setId((*citer)->getId());
newConf->set3D((*citer)->is3D());
int aIdx = 0;
for (unsigned int i = 0; i < mol.getNumAtoms(); ++i) {
if (!removedAtoms[i]) {
newConf->setAtomPos(aIdx, (*citer)->getAtomPos(i));
++aIdx;
}
}
res.addConformer(newConf, false);
}
}
struct SideChainMapping {
int molIndex;
int coreIndex;
bool useMatch;
SideChainMapping(int molIndex)
: molIndex(molIndex), coreIndex(-1), useMatch(false) {}
SideChainMapping(int molIndex, int coreIndex, bool useMatch)
: molIndex(molIndex), coreIndex(coreIndex), useMatch(useMatch) {}
};
} // namespace
ROMol *deleteSubstructs(const ROMol &mol, const ROMol &query, bool onlyFrags,
bool useChirality) {
auto *res = new RWMol(mol, false);
std::vector<MatchVectType> fgpMatches;
std::vector<MatchVectType>::const_iterator mati;
VECT_INT_VECT
matches; // all matches on the molecule - list of list of atom ids
MatchVectType::const_iterator mi;
// do the substructure matching and get the atoms that match the query
const bool uniquify = true;
const bool recursionPossible = true;
SubstructMatch(*res, query, fgpMatches, uniquify, recursionPossible,
useChirality);
// if didn't find any matches nothing to be done here
// simply return a copy of the molecule
if (fgpMatches.size() == 0) {
return res;
}
for (mati = fgpMatches.begin(); mati != fgpMatches.end(); mati++) {
INT_VECT match; // each match onto the molecule - list of atoms ids
for (mi = mati->begin(); mi != mati->end(); mi++) {
match.push_back(mi->second);
}
matches.push_back(match);
}
// now loop over the list of matches and check if we can delete any of them
INT_VECT delList;
VECT_INT_VECT_I mxi, fi;
if (onlyFrags) {
VECT_INT_VECT frags;
MolOps::getMolFrags(*res, frags);
for (fi = frags.begin(); fi != frags.end(); fi++) {
std::sort(fi->begin(), fi->end());
for (mxi = matches.begin(); mxi != matches.end(); mxi++) {
std::sort(mxi->begin(), mxi->end());
if ((*fi) == (*mxi)) {
INT_VECT tmp;
Union((*mxi), delList, tmp);
delList = tmp;
break;
} // end of if we found a matching fragment
} // endof loop over matches
} // end of loop over fragments
} // end of if onlyFrags
else {
// in this case we want to delete any matches we find
// simply loop over the matches and collect the atoms that need to
// be removed
for (mxi = matches.begin(); mxi != matches.end(); mxi++) {
INT_VECT tmp;
Union((*mxi), delList, tmp);
delList = tmp;
}
}
// now loop over the union list and delete the atoms
res->beginBatchEdit();
boost::dynamic_bitset<> removedAtoms(mol.getNumAtoms());
for (auto idx : delList) {
removedAtoms.set(idx);
res->removeAtom(idx);
}
res->commitBatchEdit();
// if we removed any atoms, clear the computed properties:
if (delList.size()) {
updateSubMolConfs(mol, *res, removedAtoms);
res->clearComputedProps(true);
// update our properties, but allow unhappiness:
res->updatePropertyCache(false);
}
return res;
}
std::vector<ROMOL_SPTR> replaceSubstructs(
const ROMol &mol, const ROMol &query, const ROMol &replacement,
bool replaceAll, unsigned int replacementConnectionPoint,
bool useChirality) {
PRECONDITION(replacementConnectionPoint < replacement.getNumAtoms(),
"bad replacementConnectionPoint");
std::vector<ROMOL_SPTR> res;
std::vector<MatchVectType> fgpMatches;
boost::dynamic_bitset<> removedAtoms(mol.getNumAtoms());
// do the substructure matching and get the atoms that match the query
const bool uniquify = true;
const bool recursionPossible = true;
SubstructMatch(mol, query, fgpMatches, uniquify, recursionPossible,
useChirality);
// if we didn't find any matches, there's nothing to be done here
// simply return a list with a copy of the starting molecule
if (fgpMatches.size() == 0) {
res.push_back(ROMOL_SPTR(new ROMol(mol, false)));
res[0]->clearComputedProps(false);
return res;
}
INT_VECT delList;
// now loop over the list of matches and replace them:
for (std::vector<MatchVectType>::const_iterator mati = fgpMatches.begin();
mati != fgpMatches.end(); mati++) {
INT_VECT match; // each match onto the molecule - list of atoms ids
for (const auto &mi : *mati) {
match.push_back(mi.second);
}
INT_VECT sortMatch = match;
std::sort(sortMatch.begin(), sortMatch.end());
if (!replaceAll || !res.size()) {
res.push_back(ROMOL_SPTR(new ROMol(mol, false)));
}
RWMol *newMol = static_cast<RWMol *>(res.rbegin()->get());
// we need a tab to the orig number of atoms because the
// new molecule will start numbered above this:
int numOrigAtoms = newMol->getNumAtoms();
// Add the atoms and bonds from the replacement:
newMol->insertMol(replacement);
// loop over the central atom's (the first atom in match) bonds
// and duplicate any that connect to the remainder of the molecule:
Atom *origAtom = newMol->getAtomWithIdx(match[0]);
ROMol::ADJ_ITER nbrIdx, endNbrs;
boost::tie(nbrIdx, endNbrs) = newMol->getAtomNeighbors(origAtom);
while (nbrIdx != endNbrs) {
// we don't want to duplicate any "intra-match" bonds:
if (!std::binary_search(sortMatch.begin(), sortMatch.end(),
int(*nbrIdx))) {
Bond *oBond = newMol->getBondBetweenAtoms(match[0], *nbrIdx);
CHECK_INVARIANT(oBond, "required bond not found");
newMol->addBond(numOrigAtoms + replacementConnectionPoint, *nbrIdx,
oBond->getBondType());
}
nbrIdx++;
}
if (replaceAll) {
// we'll accumulate a list of atoms to be removed:
INT_VECT tmp;
Union(sortMatch, delList, tmp);
delList = tmp;
} else {
// just delete the atoms now:
newMol->beginBatchEdit();
for (auto idx : sortMatch) {
removedAtoms.set(idx);
newMol->removeAtom(idx);
}
newMol->commitBatchEdit();
}
}
if (delList.size()) {
if (replaceAll) {
// remove the atoms from the delList:
auto *newMol = static_cast<RWMol *>(res[0].get());
newMol->beginBatchEdit();
for (auto idx : delList) {
removedAtoms.set(idx);
newMol->removeAtom(idx);
}
newMol->commitBatchEdit();
}
// clear conformers and computed props and do basic updates
// on the resulting molecules, but allow unhappiness:
for (auto &re : res) {
updateSubMolConfs(mol, *(RWMol *)re.get(), removedAtoms);
re->clearComputedProps(true);
re->updatePropertyCache(false);
}
}
return res;
}
ROMol *replaceSidechains(const ROMol &mol, const ROMol &coreQuery,
bool useChirality) {
MatchVectType matchV;
// do the substructure matching and get the atoms that match the query
const bool recursionPossible = true;
bool matchFound =
SubstructMatch(mol, coreQuery, matchV, recursionPossible, useChirality);
// if we didn't find any matches, there's nothing to be done here
// simply return null to indicate the problem
if (!matchFound || matchV.size() == 0) {
return nullptr;
}
boost::dynamic_bitset<> matchingIndices(mol.getNumAtoms());
for (MatchVectType::const_iterator mvit = matchV.begin();
mvit != matchV.end(); ++mvit) {
matchingIndices[mvit->second] = 1;
}
auto *newMol = new RWMol(mol);
boost::dynamic_bitset<> keepSet(newMol->getNumAtoms());
std::vector<unsigned int> dummyIndices;
for (MatchVectType::const_iterator mvit = matchV.begin();
mvit != matchV.end(); ++mvit) {
keepSet.set(mvit->second);
// if the atom in the molecule has higher degree than the atom in the
// core, we have an attachment point:
if (newMol->getAtomWithIdx(mvit->second)->getDegree() >
coreQuery.getAtomWithIdx(mvit->first)->getDegree()) {
ROMol::ADJ_ITER nbrIdx, endNbrs;
boost::tie(nbrIdx, endNbrs) =
newMol->getAtomNeighbors(newMol->getAtomWithIdx(mvit->second));
while (nbrIdx != endNbrs) {
if (!matchingIndices[*nbrIdx]) {
// this neighbor isn't in the match, convert it to a dummy atom and
// save it
keepSet.set(*nbrIdx);
dummyIndices.push_back(*nbrIdx);
Atom *at = newMol->getAtomWithIdx(*nbrIdx);
Bond *b = newMol->getBondBetweenAtoms(mvit->second, *nbrIdx);
if (b) {
b->setIsAromatic(false);
b->setBondType(Bond::SINGLE);
}
at->setAtomicNum(0);
at->setNumExplicitHs(0);
at->setIsAromatic(false);
at->setIsotope(dummyIndices.size());
}
++nbrIdx;
}
}
}
boost::dynamic_bitset<> removedAtoms(mol.getNumAtoms());
newMol->beginBatchEdit();
for (const auto at : newMol->atoms()) {
if (!keepSet.test(at->getIdx())) {
newMol->removeAtom(at);
removedAtoms.set(at->getIdx());
}
}
// Remove bonds between newly added dummies (if any)
if (dummyIndices.size() > 1) {
for (size_t i = 0; i < dummyIndices.size() - 1; ++i) {
for (size_t j = i + 1; j < dummyIndices.size(); ++j) {
const auto b =
newMol->getBondBetweenAtoms(dummyIndices.at(i), dummyIndices.at(j));
if (b) {
newMol->removeBond(dummyIndices.at(i), dummyIndices.at(j));
}
}
}
}
newMol->commitBatchEdit();
updateSubMolConfs(mol, *newMol, removedAtoms);
// clear computed props and do basic updates on the
// the resulting molecule, but allow unhappiness:
newMol->clearComputedProps(true);
newMol->updatePropertyCache(false);
return static_cast<ROMol *>(newMol);
}
ROMol *replaceCore(const ROMol &mol, const ROMol &coreQuery,
bool replaceDummies, bool labelByIndex,
bool requireDummyMatch, bool useChirality) {
MatchVectType matchV;
// do the substructure matching and get the atoms that match the query
const bool recursionPossible = true;
bool matchFound =
SubstructMatch(mol, coreQuery, matchV, recursionPossible, useChirality);
// if we didn't find any matches, there's nothing to be done here
// simply return null to indicate the problem
if (!matchFound || matchV.size() == 0) {
return nullptr;
}
return replaceCore(mol, coreQuery, matchV, replaceDummies, labelByIndex,
requireDummyMatch);
}
ROMol *replaceCore(const ROMol &mol, const ROMol &core,
const MatchVectType &matchV, bool replaceDummies,
bool labelByIndex, bool requireDummyMatch) {
unsigned int origNumAtoms = mol.getNumAtoms();
std::vector<std::pair<int, SideChainMapping>> matches;
matches.reserve(origNumAtoms);
std::vector<int> matchingIndices(origNumAtoms, -1);
std::vector<int> allIndices(origNumAtoms, -1);
boost::dynamic_bitset<> molAtomsMapped(origNumAtoms);
boost::dynamic_bitset<> multipleMappedMolAtoms(origNumAtoms);
for (const auto &mvit : matchV) {
if (mvit.first < 0 || mvit.first >= rdcast<int>(core.getNumAtoms())) {
throw ValueErrorException(
"Supplied MatchVect indices out of bounds of the core molecule");
}
if (mvit.second < 0 || mvit.second >= rdcast<int>(mol.getNumAtoms())) {
throw ValueErrorException(
"Supplied MatchVect indices out of bounds of the target molecule");
}
bool useMatch = false;
if (replaceDummies || core.getAtomWithIdx(mvit.first)->getAtomicNum() > 0) {
matchingIndices[mvit.second] = mvit.first;
useMatch = true;
}
allIndices[mvit.second] = mvit.first;
SideChainMapping mapping(mvit.second, mvit.first, useMatch);
matches.emplace_back(mvit.second, mapping);
if (molAtomsMapped[mvit.second]) {
multipleMappedMolAtoms.set(mvit.second);
}
molAtomsMapped.set(mvit.second);
}
boost::dynamic_bitset<> multipleOwnedBonds(mol.getNumBonds());
if (multipleMappedMolAtoms.any()) {
for (const auto &match : matches) {
const auto &mappingInfo = match.second;
if (multipleMappedMolAtoms[mappingInfo.molIndex]) {
auto coreAtom = core.getAtomWithIdx(mappingInfo.coreIndex);
CHECK_INVARIANT(
coreAtom->getDegree() == 1,
"Multiple core atoms match a mol atom, but one of the core "
"atoms has degree > 1 ");
auto coreNeighborIdx = core[*core.getAtomNeighbors(coreAtom).first]->getIdx();
auto molNeighborIdx =
std::find_if(matchV.cbegin(), matchV.cend(),
[coreNeighborIdx](std::pair<int, int> p) {
return p.first == static_cast<int>(coreNeighborIdx);
})
->second;
if (molNeighborIdx > -1) {
auto connectingBond =
mol.getBondBetweenAtoms(mappingInfo.molIndex, molNeighborIdx);
CHECK_INVARIANT(connectingBond,"expected bond in molecule not found");
multipleOwnedBonds.set(connectingBond->getIdx());
}
}
}
}
auto *newMol = new RWMol(mol);
std::vector<Atom *> keepList;
std::map<int, Atom *> dummyAtomMap;
// go through the matches in query order, not target molecule
// order
for (unsigned int i = 0; i < origNumAtoms; ++i) {
if (!molAtomsMapped[i]) {
SideChainMapping mapping(i);
matches.emplace_back(i, mapping);
}
}
std::sort(matches.begin(), matches.end(),
[](const std::pair<int, SideChainMapping> &p1,
const std::pair<int, SideChainMapping> &p2) {
if (p1.second.coreIndex == p2.second.coreIndex) {
return p1.first < p2.first;
}
return p1.second.coreIndex < p2.second.coreIndex;
});
std::vector<std::pair<int, Atom *>> dummies;
for (const auto &match : matches) {
const auto &mappingInfo = match.second;
if (!mappingInfo.useMatch) {
Atom *sidechainAtom = newMol->getAtomWithIdx(mappingInfo.molIndex);
// we're keeping the sidechain atoms:
keepList.push_back(sidechainAtom);
// loop over our neighbors and see if any are in the match:
std::list<unsigned int> nbrList;
ROMol::ADJ_ITER nbrIter, endNbrs;
boost::tie(nbrIter, endNbrs) = newMol->getAtomNeighbors(sidechainAtom);
while (nbrIter != endNbrs && (*nbrIter) < origNumAtoms) {
// we need to add bonds and atoms to the molecule while looping
// over neighbors. This invalidates iterators, so collect a list
// of our neighbors now:
nbrList.push_back(*nbrIter);
++nbrIter;
}
unsigned int whichNbr = 0;
std::list<Bond *> newBonds;
for (std::list<unsigned int>::const_iterator lIter = nbrList.begin();
lIter != nbrList.end(); ++lIter) {
unsigned int nbrIdx = *lIter;
Bond *connectingBond =
newMol->getBondBetweenAtoms(mappingInfo.molIndex, nbrIdx);
bool bondToCore = matchingIndices[nbrIdx] > -1;
auto coreBond =
bondToCore && allIndices[nbrIdx] > -1 && mappingInfo.coreIndex > -1
? core.getBondBetweenAtoms(mappingInfo.coreIndex,
allIndices[nbrIdx])
: nullptr;
if (bondToCore && multipleMappedMolAtoms[mappingInfo.molIndex] &&
mappingInfo.coreIndex > -1) {
// The core has multiple atoms that map onto this mol atom - check we
// have matched correct core bond.
// Otherwise we can use this bond only if nobody else owns it.
if (coreBond == nullptr &&
multipleOwnedBonds[connectingBond->getIdx()]) {
bondToCore = false;
}
}
if (bondToCore) {
// we've matched an atom in the core.
if (requireDummyMatch &&
core.getAtomWithIdx(matchingIndices[nbrIdx])->getAtomicNum() !=
0) {
delete newMol;
return nullptr;
}
auto *newAt = new Atom(0);
// if we were not in the matching list, still keep
// the original indices (replaceDummies=False)
int mapping = mappingInfo.coreIndex;
// If we don't have a core bond, the label belongs to the neighbor
if (coreBond == nullptr) {
mapping = allIndices[nbrIdx];
}
// we want to order the dummies in the same orders as
// the mappings, if not labelling by Index they are in arbitrary
// order
// right now so save and sort later.
if (mapping != -1) {
dummies.emplace_back(mapping, newAt);
} else {
dummies.emplace_back(matchingIndices[nbrIdx], newAt);
}
newMol->addAtom(newAt, false, true);
dummyAtomMap[nbrIdx] = newAt;
keepList.push_back(newAt);
Bond *bnd = connectingBond->copy();
if (bnd->getBeginAtomIdx() ==
static_cast<size_t>(mappingInfo.molIndex)) {
bnd->setEndAtomIdx(newAt->getIdx());
} else {
bnd->setBeginAtomIdx(newAt->getIdx());
}
newBonds.push_back(bnd);
// we may be changing the bond ordering at the atom.
// e.g. replacing the N in C[C@](Cl)(N)F gives an atom ordering of
// C[C?](Cl)(F)[X]
// so we need the SMILES C[C@@](Cl)(F)[X] to maintain the appropriate
// chirality
// check for these cases and adjust our chirality flags as
// appropriate.
//
if (sidechainAtom->getChiralTag() == Atom::CHI_TETRAHEDRAL_CW ||
sidechainAtom->getChiralTag() == Atom::CHI_TETRAHEDRAL_CCW) {
bool switchIt = false;
switch (newMol->getAtomDegree(sidechainAtom)) {
case 4:
// start: ordering: swap?
// N[C@](F)(Cl)C -> F[C@@](Cl)(C)X yes
// F[C@](N)(Cl)C -> F[C@](Cl)(C)X no
// F[C@](Cl)(N)C -> F[C@@](Cl)(C)X yes
// F[C@](Cl)(C)N -> F[C@](Cl)(C)X no
if (!(whichNbr % 2)) {
switchIt = true;
}
break;
case 3:
// things are different in the degree three case because of the
// implicit H:
// start: ordering: swap?
// N[C@H](F)C -> [C@H](F)(C)X yes
// [C@H](N)(F)C -> [C@H](F)(C)X no
// F[C@H](N)C -> F[C@@H](C)X yes
// F[C@H](C)N -> F[C@H](C)X no
if (whichNbr == 1) {
switchIt = true;
}
break;
}
if (switchIt) {
sidechainAtom->invertChirality();
}
}
}
++whichNbr;
}
// add the bonds now, after we've finished the loop over neighbors:
for (auto &newBond : newBonds) {
newMol->addBond(newBond, true);
auto beginAtom = newBond->getBeginAtom();
auto endAtom = newBond->getEndAtom();
if (newMol->getNumConformers()) {
if (endAtom->getAtomicNum() == 0) {
MolOps::setTerminalAtomCoords(*newMol, endAtom->getIdx(),
beginAtom->getIdx());
} else {
MolOps::setTerminalAtomCoords(*newMol, beginAtom->getIdx(),
endAtom->getIdx());
}
}
}
}
}
if (!labelByIndex) {
// sort the mapping indices, but label from 1..N
std::stable_sort(dummies.begin(), dummies.end());
for (size_t nDummy = 0; nDummy < dummies.size(); ++nDummy) {
dummies[nDummy].second->setIsotope(nDummy + 1);
}
} else {
// don't sort, just label by the index
for (auto &dummy : dummies) {
dummy.second->setIsotope(dummy.first);
}
}
std::vector<Atom *> delList;
boost::dynamic_bitset<> removedAtoms(mol.getNumAtoms());
newMol->beginBatchEdit();
for (const auto at : newMol->atoms()) {
if (std::find(keepList.begin(), keepList.end(), at) == keepList.end()) {
newMol->removeAtom(at);
removedAtoms.set(at->getIdx());
}
}
newMol->commitBatchEdit();
updateSubMolConfs(mol, *newMol, removedAtoms);
// make a guess at the position of the dummy atoms showing the attachment
// point:
for (auto citer = mol.beginConformers(); citer != mol.endConformers();
++citer) {
Conformer &newConf = newMol->getConformer((*citer)->getId());
for (std::map<int, Atom *>::const_iterator iter = dummyAtomMap.begin();
iter != dummyAtomMap.end(); ++iter) {
newConf.setAtomPos(iter->second->getIdx(),
(*citer)->getAtomPos(iter->first));
}
}
// clear computed props and do basic updates on
// the resulting molecule, but allow unhappiness:
newMol->clearComputedProps(true);
newMol->updatePropertyCache(false);
return static_cast<ROMol *>(newMol);
}
ROMol *MurckoDecompose(const ROMol &mol) {
auto *res = new RWMol(mol);
unsigned int nAtoms = res->getNumAtoms();
if (!nAtoms) {
return res;
}
// start by getting the shortest paths matrix:
MolOps::getDistanceMat(mol, false, false, true);
boost::shared_array<int> pathMat;
mol.getProp(common_properties::DistanceMatrix_Paths, pathMat);
boost::dynamic_bitset<> keepAtoms(nAtoms);
const RingInfo *ringInfo = res->getRingInfo();
for (unsigned int i = 0; i < nAtoms; ++i) {
if (ringInfo->numAtomRings(i)) {
keepAtoms[i] = 1;
}
}
const VECT_INT_VECT &rings = ringInfo->atomRings();
// std::cerr<<" rings: "<<rings.size()<<std::endl;
// now find the shortest paths between each ring system and mark the atoms
// along each as being keepers:
for (auto ringsItI = rings.begin(); ringsItI != rings.end(); ++ringsItI) {
for (auto ringsItJ = ringsItI + 1; ringsItJ != rings.end(); ++ringsItJ) {
int atomI = (*ringsItI)[0];
int atomJ = (*ringsItJ)[0];
// std::cerr<<atomI<<" -> "<<atomJ<<": ";
while (atomI != atomJ) {
keepAtoms[atomI] = 1;
atomI = pathMat[atomJ * nAtoms + atomI];
// test for the disconnected case:
if (atomI < 0) {
break;
}
// std::cerr<<atomI<<" ";
}
// std::cerr<<std::endl;
}
}
boost::dynamic_bitset<> removedAtoms(nAtoms);
res->beginBatchEdit();
for (unsigned int i = 0; i < nAtoms; ++i) {
if (!keepAtoms[i]) {
Atom *atom = res->getAtomWithIdx(i);
bool removeIt = true;
// check if the atom has a neighboring keeper:
ROMol::ADJ_ITER nbrIdx, endNbrs;
boost::tie(nbrIdx, endNbrs) = res->getAtomNeighbors(atom);
while (nbrIdx != endNbrs) {
Atom *nbr = (*res)[*nbrIdx];
if (keepAtoms[nbr->getIdx()]) {
if (res->getBondBetweenAtoms(atom->getIdx(), nbr->getIdx())
->getBondType() == Bond::DOUBLE) {
removeIt = false;
break;
} else if (nbr->getIsAromatic() && nbr->getAtomicNum() != 6) {
// fix aromatic heteroatoms:
nbr->setNumExplicitHs(1);
} else if (nbr->getIsAromatic() && nbr->getAtomicNum() == 6 &&
nbr->getFormalCharge() == 1) {
// fix aromatic carbocations
nbr->setNumExplicitHs(1);
} else if (nbr->getNoImplicit() ||
nbr->getChiralTag() != Atom::CHI_UNSPECIFIED) {
nbr->setNoImplicit(false);
nbr->setNumExplicitHs(0);
nbr->setChiralTag(Atom::CHI_UNSPECIFIED);
}
}
++nbrIdx;
}
if (removeIt) {
res->removeAtom(atom);
removedAtoms.set(atom->getIdx());
}
}
}
res->commitBatchEdit();
updateSubMolConfs(mol, *res, removedAtoms);
res->clearComputedProps();
return (ROMol *)res;
}
ROMol *combineMols(const ROMol &mol1, const ROMol &mol2,
RDGeom::Point3D offset) {
auto *res = new RWMol(mol1);
int nAtoms1 = res->getNumAtoms();
res->insertMol(mol2);
// copy over coordinates
if (mol1.getNumConformers() && mol2.getNumConformers()) {
if (mol1.getNumConformers() != mol2.getNumConformers()) {
BOOST_LOG(rdWarningLog)
<< "combineMols: molecules have unequal numbers of conformers"
<< std::endl;
}
for (auto conf1It = res->beginConformers(); conf1It != res->endConformers();
++conf1It) {
Conformer *conf1 = (*conf1It).get();
try {
const Conformer *conf2 = &mol2.getConformer(conf1->getId());
for (unsigned int i = 0; i < mol2.getNumAtoms(); ++i) {
conf1->setAtomPos(i + nAtoms1, conf2->getAtomPos(i) + offset);
}
} catch (ConformerException &) {
BOOST_LOG(rdWarningLog) << "combineMols: conformer id "
<< conf1->getId() << " not found in mol2";
}
}
}
res->clearComputedProps(true);
return (ROMol *)res;
}
void addRecursiveQueries(
ROMol &mol, const std::map<std::string, ROMOL_SPTR> &queries,
const std::string &propName,
std::vector<std::pair<unsigned int, std::string>> *reactantLabels) {
std::string delim = ",";
boost::char_separator<char> sep(delim.c_str());
if (reactantLabels != nullptr) {
(*reactantLabels).resize(0);
}
ROMol::VERTEX_ITER atBegin, atEnd;
boost::tie(atBegin, atEnd) = mol.getVertices();
while (atBegin != atEnd) {
Atom *at = mol[*atBegin];
++atBegin;
if (!at->hasProp(propName)) {
continue;
}
std::string pval;
at->getProp(propName, pval);
std::string maybeSmarts =
pval; // keep unmodified in case we are a smarts string
boost::algorithm::to_lower(pval);
if (reactantLabels != nullptr) {
std::pair<unsigned int, std::string> label(at->getIdx(), pval);
(*reactantLabels).push_back(label);
}
QueryAtom::QUERYATOM_QUERY *qToAdd = nullptr;
bool notFound = false;
if (pval.find(delim) != std::string::npos) {
boost::tokenizer<boost::char_separator<char>> tokens(pval, sep);
boost::tokenizer<boost::char_separator<char>>::iterator token;
qToAdd = new ATOM_OR_QUERY();
qToAdd->setDescription("AtomOr");
for (token = tokens.begin(); token != tokens.end(); ++token) {
auto iter = queries.find(*token);
if (iter == queries.end()) {
delete qToAdd;
notFound = true;
break;
}
auto *tqp = new RecursiveStructureQuery(new ROMol(*(iter->second)));
std::shared_ptr<RecursiveStructureQuery> nq(tqp);
qToAdd->addChild(nq);
}
} else {
auto iter = queries.find(pval);
if (iter == queries.end()) {
notFound = true;
} else {
qToAdd = new RecursiveStructureQuery(new ROMol(*(iter->second)));
}
}
if (notFound) {
// See if we are actually a smarts expression already
RWMol *m = nullptr;
try {
m = SmartsToMol(maybeSmarts);
if (!m) {
throw KeyErrorException(pval);
}
qToAdd = new RecursiveStructureQuery(m);
} catch (...) {
throw KeyErrorException(pval);
}
}
if (!at->hasQuery()) {
QueryAtom qAt(*at);
unsigned int idx = at->getIdx();
static_cast<RWMol &>(mol).replaceAtom(idx, &qAt);
at = mol.getAtomWithIdx(idx);
}
at->expandQuery(qToAdd, Queries::COMPOSITE_AND);
}
}
void parseQueryDefFile(std::istream *inStream,
std::map<std::string, ROMOL_SPTR> &queryDefs,
bool standardize, const std::string &delimiter,
const std::string &comment, unsigned int nameColumn,
unsigned int smartsColumn) {
PRECONDITION(inStream, "no stream");
queryDefs.clear();
boost::char_separator<char> sep(delimiter.c_str());
unsigned int line = 0;
std::string tempStr;
while (!inStream->eof() && !inStream->fail()) {
line++;
tempStr = getLine(inStream);
if (tempStr == "" || tempStr.find(comment) == 0) {
continue;
}
boost::tokenizer<boost::char_separator<char>> tokens(tempStr, sep);
unsigned int tpos;
boost::tokenizer<boost::char_separator<char>>::iterator token;
std::string qname = "";
std::string qval = "";
for (token = tokens.begin(), tpos = 0; token != tokens.end();
++token, ++tpos) {
if (tpos == nameColumn) {
qname = *token;
} else if (tpos == smartsColumn) {
qval = *token;
}
}
boost::trim_if(qname, boost::is_any_of(" \t"));
boost::trim_if(qval, boost::is_any_of(" \t"));
if (qname == "" || qval == "") {
continue;
}
RWMol *m = nullptr;
try {
m = SmartsToMol(qval);
} catch (...) {
m = nullptr;
}
if (!m) {
BOOST_LOG(rdWarningLog) << "cannot convert SMARTS " << qval
<< " to molecule at line " << line << std::endl;
continue;
}
ROMOL_SPTR msptr(m);
if (standardize) {
boost::algorithm::to_lower(qname);
}
queryDefs[qname] = msptr;
}
}
void parseQueryDefFile(const std::string &filename,
std::map<std::string, ROMOL_SPTR> &queryDefs,
bool standardize, const std::string &delimiter,
const std::string &comment, unsigned int nameColumn,
unsigned int smartsColumn) {
std::ifstream inStream(filename.c_str());
if (!inStream || (inStream.bad())) {
std::ostringstream errout;
errout << "Bad input file " << filename;
throw BadFileException(errout.str());
}
parseQueryDefFile(&inStream, queryDefs, standardize, delimiter, comment,
nameColumn, smartsColumn);
}
void parseQueryDefText(const std::string &queryDefText,
std::map<std::string, ROMOL_SPTR> &queryDefs,
bool standardize, const std::string &delimiter,
const std::string &comment, unsigned int nameColumn,
unsigned int smartsColumn) {
std::stringstream inStream(queryDefText);
parseQueryDefFile(&inStream, queryDefs, standardize, delimiter, comment,
nameColumn, smartsColumn);
}
} // end of namespace RDKit
| 35.38521 | 86 | 0.598709 | [
"vector"
] |
a3e1364663683fb96195e4e93e01557c49317867 | 4,629 | cpp | C++ | node_modules/react-native-windows/ReactUWP/Modules/AppThemeModuleUwp.cpp | ashimiblessing/gopays | 424024a2890a4595b9c56479477bae080fdbab3b | [
"MIT"
] | null | null | null | node_modules/react-native-windows/ReactUWP/Modules/AppThemeModuleUwp.cpp | ashimiblessing/gopays | 424024a2890a4595b9c56479477bae080fdbab3b | [
"MIT"
] | null | null | null | node_modules/react-native-windows/ReactUWP/Modules/AppThemeModuleUwp.cpp | ashimiblessing/gopays | 424024a2890a4595b9c56479477bae080fdbab3b | [
"MIT"
] | null | null | null | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "pch.h"
#include "AppThemeModuleUwp.h"
#include <Utils\ValueUtils.h>
#if _MSC_VER <= 1913
// VC 19 (2015-2017.6) cannot optimize co_await/cppwinrt usage
#pragma optimize("", off)
#endif
namespace winrt {
using namespace Windows::UI::Xaml;
using namespace Windows::UI::ViewManagement;
} // namespace winrt
namespace react::uwp {
//
// AppTheme
//
AppTheme::AppTheme(
const std::shared_ptr<IReactInstance> &reactInstance,
const std::shared_ptr<facebook::react::MessageQueueThread> &defaultQueueThread)
: m_wkReactInstance(reactInstance), m_queueThread(defaultQueueThread) {
m_currentTheme = winrt::Application::Current().RequestedTheme();
m_isHighContrast = m_accessibilitySettings.HighContrast();
m_highContrastColors = getHighContrastColors();
m_highContrastChangedRevoker =
m_accessibilitySettings.HighContrastChanged(winrt::auto_revoke, [this](const auto &, const auto &) {
folly::dynamic eventData = folly::dynamic::object("highContrastColors", getHighContrastColors())(
"isHighContrast", getIsHighContrast());
fireEvent("highContrastChanged", std::move(eventData));
});
m_colorValuesChangedRevoker = m_uiSettings.ColorValuesChanged(winrt::auto_revoke, [this](const auto &, const auto &) {
m_queueThread->runOnQueue([this]() {
if (m_currentTheme != winrt::Application::Current().RequestedTheme() && !m_accessibilitySettings.HighContrast()) {
m_currentTheme = winrt::Application::Current().RequestedTheme();
folly::dynamic eventData = folly::dynamic::object("currentTheme", getCurrentTheme());
fireEvent("appThemeChanged", std::move(eventData));
}
});
});
}
std::string AppTheme::getCurrentTheme() {
return m_currentTheme == winrt::ApplicationTheme::Light ? AppTheme::Light : AppTheme::Dark;
}
bool AppTheme::getIsHighContrast() {
return m_accessibilitySettings.HighContrast();
;
}
// Returns the RBG values for the 8 relevant High Contrast elements.
folly::dynamic AppTheme::getHighContrastColors() {
winrt::Windows::UI::Color ButtonFaceColor = m_uiSettings.UIElementColor(winrt::UIElementType::ButtonFace);
winrt::Windows::UI::Color ButtonTextColor = m_uiSettings.UIElementColor(winrt::UIElementType::ButtonText);
winrt::Windows::UI::Color GrayTextColor = m_uiSettings.UIElementColor(winrt::UIElementType::GrayText);
winrt::Windows::UI::Color HighlightColor = m_uiSettings.UIElementColor(winrt::UIElementType::Highlight);
winrt::Windows::UI::Color HighlightTextColor = m_uiSettings.UIElementColor(winrt::UIElementType::HighlightText);
winrt::Windows::UI::Color HotlightColor = m_uiSettings.UIElementColor(winrt::UIElementType::Hotlight);
winrt::Windows::UI::Color WindowColor = m_uiSettings.UIElementColor(winrt::UIElementType::Window);
winrt::Windows::UI::Color WindowTextColor = m_uiSettings.UIElementColor(winrt::UIElementType::WindowText);
folly::dynamic rbgValues = folly::dynamic::object("ButtonFaceColor", formatRGB(ButtonFaceColor))(
"ButtonTextColor", formatRGB(ButtonTextColor))("GrayTextColor", formatRGB(GrayTextColor))(
"HighlightColor", formatRGB(HighlightColor))("HighlightTextColor", formatRGB(HighlightTextColor))(
"HotlightColor", formatRGB(HotlightColor))("WindowColor", formatRGB(WindowColor))(
"WindowTextColor", formatRGB(WindowTextColor));
return rbgValues;
}
std::string AppTheme::formatRGB(winrt::Windows::UI::Color ElementColor) {
char colorChars[8];
sprintf_s(colorChars, "#%02x%02x%02x", ElementColor.R, ElementColor.G, ElementColor.B);
return colorChars;
}
void AppTheme::fireEvent(std::string const &eventName, folly::dynamic &&eventData) {
if (auto instance = m_wkReactInstance.lock()) {
instance->CallJsFunction("RCTDeviceEventEmitter", "emit", folly::dynamic::array(eventName, std::move(eventData)));
}
}
AppThemeModule::AppThemeModule(std::shared_ptr<AppTheme> &&appTheme) : m_appTheme(std::move(appTheme)) {}
auto AppThemeModule::getConstants() -> std::map<std::string, folly::dynamic> {
return {{"initialAppTheme", folly::dynamic{m_appTheme->getCurrentTheme()}},
{"initialHighContrast", folly::dynamic{m_appTheme->getIsHighContrast()}},
{"initialHighContrastColors", folly::dynamic{m_appTheme->getHighContrastColors()}}};
}
auto AppThemeModule::getMethods() -> std::vector<facebook::xplat::module::CxxModule::Method> {
return {};
}
} // namespace react::uwp
| 42.861111 | 121 | 0.727587 | [
"object",
"vector"
] |
9cad44cb0e6d8b70df4a8c6a3be762f076e19a1e | 24,087 | cpp | C++ | quakelib/src/QuakeLibEvent.cpp | kwschultz/VirtualCalifornia | 1e6b0a70f00f953018e8bd5336f8f94c5dad04b9 | [
"MIT"
] | null | null | null | quakelib/src/QuakeLibEvent.cpp | kwschultz/VirtualCalifornia | 1e6b0a70f00f953018e8bd5336f8f94c5dad04b9 | [
"MIT"
] | null | null | null | quakelib/src/QuakeLibEvent.cpp | kwschultz/VirtualCalifornia | 1e6b0a70f00f953018e8bd5336f8f94c5dad04b9 | [
"MIT"
] | null | null | null | // Copyright (c) 2012 Eric Heien <emheien@ucdavis.edu>
//
// 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 "QuakeLib.h"
#include <iomanip>
#include <iostream>
#include <math.h>
quakelib::Vec<2> quakelib::Event::event_center(void) {
if (_event_center[0] == DBL_MAX || _event_center[1] == DBL_MAX) {
Vec<2> center(0.0,0.0), pt1, pt2;
float num_points = 0;
for(EventElementList::size_type ele_id = 0; ele_id != involved_elements.size(); ele_id++) {
pt1[0] = involved_elements[ele_id].vert(0)[0];
pt1[1] = involved_elements[ele_id].vert(0)[1];
pt2[0] = involved_elements[ele_id].vert(3)[0];
pt2[1] = involved_elements[ele_id].vert(3)[1];
num_points += 2.0;
//std::cout << pt1[0] << " " << pt1[1] << std::endl << pt2[0] << " " << pt2[1] << std::endl;
center += pt1 + pt2;
}
_event_center = center * (1.0/num_points);
//std::cout << std::endl << _event_center[0] << " " << _event_center[1] << std::endl;
}
return _event_center;
};
double quakelib::Event::event_radius(void) {
if (_event_radius == DBL_MAX) {
float curr_distance;
_event_radius = 0.0;
for(EventElementList::size_type ele_id = 0; ele_id != involved_elements.size(); ele_id++) {
curr_distance =(Vec<2>(involved_elements[ele_id].vert(0)[0], involved_elements[ele_id].vert(0)[1]) - event_center()).mag();
if (curr_distance > _event_radius)
_event_radius = curr_distance;
curr_distance =(Vec<2>(involved_elements[ele_id].vert(3)[0], involved_elements[ele_id].vert(3)[1]) - event_center()).mag();
if (curr_distance > _event_radius)
_event_radius = curr_distance;
}
}
return _event_radius;
};
quakelib::FloatList quakelib::Event::event_gravity_changes(const VectorList &points, const float &lambda, const float &mu, const float &cutoff) {
quakelib::FloatList gravity_changes;
Okada block_okada;
double gravity_change, slip, US, UD, UT, L, W, c, rake_cos, rake_sin, strike_cos, strike_sin, dip, strike, xp0, yp0, xp3, yp3, x, y, xp, yp;
if (lambda <= 0 || mu <= 0) {
throw std::invalid_argument("Lambda and mu must be greater than zero.");
}
for(VectorList::size_type point_id = 0; point_id != points.size(); point_id++) {
gravity_changes.push_back(0.0);
}
for(EventElementList::size_type ele_id = 0; ele_id != involved_elements.size(); ele_id++) {
slip = involved_elements[ele_id].slip();
std::cout << "element: " << ele_id << " slip: " << slip << std::endl;
c = fabs(involved_elements[ele_id].max_depth());
rake_cos = cos(involved_elements[ele_id].rake());
rake_sin = sin(involved_elements[ele_id].rake());
if (fabs(rake_cos) < TRIG_TOLERANCE) {
rake_cos = 0.0;
}
if (fabs(rake_sin) < TRIG_TOLERANCE) {
rake_sin = 0.0;
}
US = slip * rake_cos;
UD = slip * rake_sin;
UT = 0.0;
L = (involved_elements[ele_id].vert(3) - involved_elements[ele_id].vert(0)).mag();
W = (involved_elements[ele_id].vert(3) - involved_elements[ele_id].vert(2)).mag();
dip = involved_elements[ele_id].dip();
strike = involved_elements[ele_id].strike();
strike_cos = cos(strike);
strike_sin = sin(strike);
if (fabs(strike_cos) < TRIG_TOLERANCE) {
strike_cos = 0.0;
}
if (fabs(strike_sin) < TRIG_TOLERANCE) {
strike_sin = 0.0;
}
xp0 = involved_elements[ele_id].vert(0)[0];
yp0 = involved_elements[ele_id].vert(0)[1];
xp3 = involved_elements[ele_id].vert(3)[0];
yp3 = involved_elements[ele_id].vert(3)[1];
for(VectorList::size_type point_id = 0; point_id != points.size(); point_id++) {
x = points[point_id][0];
y = points[point_id][1];
//if (pow(x-event_center()[0], 2) + pow(y-event_center()[1], 2) > pow( event_radius() * cutoff ,2) ) {
// Gotta figure the cutoff for gravity changes out
if (sqrt(pow((x-(xp0 + xp3)/2.0),2)+pow((y-(yp0+yp3)/2.0),2))/sqrt(L*W) > (cutoff + slip - 1.0) ) {
gravity_change = 0.0;
} else {
xp = (x-xp0) * strike_sin - (y-yp0) * strike_cos;
yp = (x-xp0) * strike_cos + (y-yp0) * strike_sin;
gravity_change = block_okada.calc_dg(quakelib::Vec<2>(xp,yp), c, dip, L, W, US, UD, UT, lambda, mu);
//dx = displacement[0] * strike_sin + displacement[1] * strike_cos;
//dy = -displacement[0] * strike_cos + displacement[1] * strike_sin;
//dz = displacement[2];
}
//std::cout << sqrt(pow((x-(xp0 + xp3)/2.0),2)+pow((y-(yp0 + yp3)/2.0),2))/sqrt(L*W) << " " << gravity_change << std::endl;
gravity_changes[point_id] += gravity_change;
}
}
return gravity_changes;
};
//Gravity changes as seen from satellite, the dilatational gravity changes arise from only compression/dilatation
quakelib::FloatList quakelib::Event::event_dilat_gravity_changes(const VectorList &points, const float &lambda, const float &mu, const float &cutoff) {
quakelib::FloatList gravity_changes;
Okada block_okada;
double gravity_change, slip, US, UD, UT, L, W, c, rake_cos, rake_sin, strike_cos, strike_sin, dip, strike, xp0, yp0, xp3, yp3, x, y, xp, yp;
if (lambda <= 0 || mu <= 0) {
throw std::invalid_argument("Lambda and mu must be greater than zero.");
}
for(VectorList::size_type point_id = 0; point_id != points.size(); point_id++) {
gravity_changes.push_back(0.0);
}
for(EventElementList::size_type ele_id = 0; ele_id != involved_elements.size(); ele_id++) {
slip = involved_elements[ele_id].slip();
c = fabs(involved_elements[ele_id].max_depth());
rake_cos = cos(involved_elements[ele_id].rake());
rake_sin = sin(involved_elements[ele_id].rake());
if (fabs(rake_cos) < TRIG_TOLERANCE) {
rake_cos = 0.0;
}
if (fabs(rake_sin) < TRIG_TOLERANCE) {
rake_sin = 0.0;
}
US = slip * rake_cos;
UD = slip * rake_sin;
UT = 0.0;
L = (involved_elements[ele_id].vert(3) - involved_elements[ele_id].vert(0)).mag();
W = (involved_elements[ele_id].vert(3) - involved_elements[ele_id].vert(2)).mag();
dip = involved_elements[ele_id].dip();
strike = involved_elements[ele_id].strike();
strike_cos = cos(strike);
strike_sin = sin(strike);
if (fabs(strike_cos) < TRIG_TOLERANCE) {
strike_cos = 0.0;
}
if (fabs(strike_sin) < TRIG_TOLERANCE) {
strike_sin = 0.0;
}
xp0 = involved_elements[ele_id].vert(0)[0];
yp0 = involved_elements[ele_id].vert(0)[1];
xp3 = involved_elements[ele_id].vert(3)[0];
yp3 = involved_elements[ele_id].vert(3)[1];
for(VectorList::size_type point_id = 0; point_id != points.size(); point_id++) {
x = points[point_id][0];
y = points[point_id][1];
//if (pow(x-event_center()[0], 2) + pow(y-event_center()[1], 2) > pow( event_radius() * cutoff ,2) ) {
// Gotta figure the cutoff for gravity changes out
if (sqrt(pow((x-(xp0 + xp3)/2.0),2)+pow((y-(yp0+yp3)/2.0),2))/sqrt(L*W) > (cutoff + slip - 1.0) ) {
gravity_change = 0.0;
} else {
xp = (x-xp0) * strike_sin - (y-yp0) * strike_cos;
yp = (x-xp0) * strike_cos + (y-yp0) * strike_sin;
gravity_change = block_okada.calc_dg_dilat(quakelib::Vec<2>(xp,yp), c, dip, L, W, US, UD, UT, lambda, mu);
}
//std::cout << sqrt(pow((x-(xp0 + xp3)/2.0),2)+pow((y-(yp0 + yp3)/2.0),2))/sqrt(L*W) << " " << gravity_change << std::endl;
gravity_changes[point_id] += gravity_change;
}
}
return gravity_changes;
}
quakelib::VectorList quakelib::Event::event_displacements(const VectorList &points, const float &lambda, const float &mu, const float &cutoff) {
quakelib::VectorList displacements;
Okada block_okada;
quakelib::Vec<3> displacement;
double slip, US, UD, UT, L, W, c, rake_cos, rake_sin, strike_cos, strike_sin, dip, strike, xp0, yp0, x, y, xp, yp, dx, dy, dz;
if (lambda <= 0 || mu <= 0) {
throw std::invalid_argument("Lambda and mu must be greater than zero.");
}
for(VectorList::size_type point_id = 0; point_id != points.size(); point_id++) {
displacements.push_back(quakelib::Vec<3>(0.0,0.0,0.0));
}
for(EventElementList::size_type ele_id = 0; ele_id != involved_elements.size(); ele_id++) {
slip = involved_elements[ele_id].slip();
c = involved_elements[ele_id].max_depth();
rake_cos = cos(involved_elements[ele_id].rake());
rake_sin = sin(involved_elements[ele_id].rake());
if (fabs(rake_cos) < TRIG_TOLERANCE) {
rake_cos = 0.0;
}
if (fabs(rake_sin) < TRIG_TOLERANCE) {
rake_sin = 0.0;
}
US = slip * rake_cos;
UD = slip * rake_sin;
UT = 0.0;
L = (involved_elements[ele_id].vert(3) - involved_elements[ele_id].vert(0)).mag();
W = (involved_elements[ele_id].vert(3) - involved_elements[ele_id].vert(2)).mag();
c = fabs(involved_elements[ele_id].vert(1)[2]);
dip = involved_elements[ele_id].dip();
strike = involved_elements[ele_id].strike();
strike_cos = cos(strike);
strike_sin = sin(strike);
if (fabs(strike_cos) < TRIG_TOLERANCE) {
strike_cos = 0.0;
}
if (fabs(strike_sin) < TRIG_TOLERANCE) {
strike_sin = 0.0;
}
xp0 = involved_elements[ele_id].vert(0)[0];
yp0 = involved_elements[ele_id].vert(0)[1];
/*
std::cout << "v1: <" << involved_elements[ele_id].vert(0)[0] << ", " << involved_elements[ele_id].vert(0)[1] << ", " << involved_elements[ele_id].vert(0)[2] << ">" << std::endl;
std::cout << "v2: <" << involved_elements[ele_id].vert(1)[0] << ", " << involved_elements[ele_id].vert(1)[1] << ", " << involved_elements[ele_id].vert(1)[2] << ">" << std::endl;
std::cout << "v3: <" << involved_elements[ele_id].vert(2)[0] << ", " << involved_elements[ele_id].vert(2)[1] << ", " << involved_elements[ele_id].vert(2)[2] << ">" << std::endl;
std::cout << "v4: <" << involved_elements[ele_id].vert(3)[0] << ", " << involved_elements[ele_id].vert(3)[1] << ", " << involved_elements[ele_id].vert(3)[2] << ">" << std::endl;
std::cout << "L: " << L << std::endl;
std::cout << "W: " << W << std::endl;
std::cout << "c: " << c << std::endl;
std::cout << "US: " << US << std::endl;
std::cout << "UD: " << UD << std::endl;
std::cout << "UT: " << UT << std::endl;
std::cout << "dip: " << dip << std::endl;
std::cout << "strike: " << strike << std::endl;
std::cout << "xp0: " << xp0 << std::endl;
std::cout << "yp0: " << yp0 << std::endl;
*/
for(VectorList::size_type point_id = 0; point_id != points.size(); point_id++) {
x = points[point_id][0];
y = points[point_id][1];
//if (pow(x-event_center()[0], 2) + pow(y-event_center()[1], 2) > pow( event_radius() * cutoff ,2) ) {
if (sqrt(pow((x-xp0),2)+pow((y-yp0),2))/sqrt(L*W) > (cutoff + slip - 1.0) ) {
dx = 0.0;
dy = 0.0;
dz = 0.0;
} else {
xp = (x-xp0) * strike_sin - (y-yp0) * strike_cos;
yp = (x-xp0) * strike_cos + (y-yp0) * strike_sin;
displacement = block_okada.calc_displacement_vector(quakelib::Vec<3>(xp,yp,0.0), c, dip, L, W, US, UD, UT, lambda, mu);
dx = displacement[0] * strike_sin + displacement[1] * strike_cos;
dy = -displacement[0] * strike_cos + displacement[1] * strike_sin;
dz = displacement[2];
}
//std::cout << pow(x-event_center[0], 2) + pow(y-event_center[1], 2) << " " << pow(event_radius * cutoff,2) << std::endl;
displacements[point_id][0] += dx;
displacements[point_id][1] += dy;
displacements[point_id][2] += dz;
}
}
return displacements;
}
void quakelib::EQSimEventWriter::flush(void) {
std::vector<unsigned int>::const_iterator it;
quakelib::EQSimMetadataWriter::write();
for (it=entries_to_flush.begin();it!=entries_to_flush.end();++it) {
event_summaries.at(*it).write(out_stream);
}
entries_to_flush.clear();
out_stream.flush();
}
void quakelib::EQSimEventSummary::parse(const int &line_num, std::istringstream &line_stream) {
_line_num = line_num;
line_stream >> _event_id // Field 1: Event ID number (positive integers, in order, need not be consecutive)
>> _magnitude // Field 2: Event magnitude
>> _time // Field 3: Starting time of event (seconds)
>> _duration // Field 4: Duration of event (seconds)
>> _sid // Field 5: Fault section ID number (positive integer)
>> _depth_lo // Field 6: Lowest value of depth in the rupture (meters, negative underground)
>> _depth_hi // Field 7: Highest value of depth in the rupture (meters, negative underground)
>> _das_lo // Field 8: Lowest value of distance-along-strike in the rupture (meters)
>> _das_hi // Field 9: Highest value of distance-along-strike in the rupture (meters)
>> _hypo_depth // Field 10: Hypocenter depth (meters, negative underground)
>> _hypo_das // Field 11: Hypocenter distance-along-strike (meters)
>> _area // Field 12: Rupture area (square meters)
>> _mean_slip // Field 13: Average slip (meters)
>> _moment // Field 14: Seismic moment (Newton-meters)
>> _shear_before // Field 15: Shear stress before event (Pascal)
>> _shear_after // Field 16: Shear stress after event (Pascal)
>> _normal_before // Field 17: Normal stress before event (Pascal)
>> _normal_after; // Field 18: Normal stress after event (Pascal)
}
void quakelib::EQSimEventReader::parse_event_summary(const int &line_num, std::istringstream &line_stream) {
quakelib::EQSimEventSummary es;
es.parse(line_num, line_stream);
event_summaries.push_back(es);
}
void quakelib::EQSimEventSlipMap::parse(const int &line_num, std::istringstream &line_stream) {
_line_num = line_num;
line_stream >> _depth_lo // Field 1: Lowest value of depth (meters, negative underground)
>> _depth_hi // Field 2: Highest value of depth in the rupture (meters, negative underground)
>> _das_lo // Field 3: Lowest value of distance-along-strike in the rupture (meters)
>> _das_hi // Field 4: Highest value of distance-along-strike in the rupture (meters)
>> _area // Field 5: Rupture area (square meters)
>> _mean_slip // Field 6: Average slip (meters)
>> _moment // Field 7: Seismic moment (Newton-meters)
>> _shear_before // Field 8: Shear stress before event (Pascal)
>> _shear_after // Field 9: Shear stress after event (Pascal)
>> _normal_before // Field 10: Normal stress before event (Pascal)
>> _normal_after // Field 11: Normal stress after event (Pascal)
>> _element_id; // Field 12: Element ID number (positive integer), or negative of element count (zero if no element info)
}
void quakelib::EQSimEventReader::parse_event_slip_map(const int &line_num, std::istringstream &line_stream) {
quakelib::EQSimEventSlipMap sm;
if (event_summaries.size() == 0) throw std::exception();
sm.parse(line_num, line_stream);
event_summaries.back().add_slip_map(sm);
}
void quakelib::EQSimEventReader::parse_event_slip_element(const int &line_num, std::istringstream &line_stream) {
unsigned int elem_id;
if (event_summaries.size() == 0 || event_summaries.back().slip_maps.size() == 0) throw std::exception();
line_stream >> elem_id;
event_summaries.back().slip_maps.back().add_slip_entry(EQSimEventSlipElement(elem_id, line_num));
}
void quakelib::EQSimEventSummary::write(std::ostream &out_stream) const {
std::vector<EQSimEventSlipMap>::const_iterator it;
std::streamsize old_prec;
old_prec = out_stream.precision();
out_stream << "200"
<< " " << _event_id // Field 1: Event ID number (positive integers, in order, need not be consecutive)
<< " " << _magnitude // Field 2: Event magnitude
<< " " << std::setprecision(16)
<< _time // Field 3: Starting time of event (seconds)
<< " " << std::setprecision(old_prec)
<< _duration // Field 4: Duration of event (seconds)
<< " " << _sid // Field 5: Fault section ID number (positive integer)
<< " " << _depth_lo // Field 6: Lowest value of depth in the rupture (meters, negative underground)
<< " " << _depth_hi // Field 7: Highest value of depth in the rupture (meters, negative underground)
<< " " << _das_lo // Field 8: Lowest value of distance-along-strike in the rupture (meters)
<< " " << _das_hi // Field 9: Highest value of distance-along-strike in the rupture (meters)
<< " " << _hypo_depth // Field 10: Hypocenter depth (meters, negative underground)
<< " " << _hypo_das // Field 11: Hypocenter distance-along-strike (meters)
<< " " << _area // Field 12: Rupture area (square meters)
<< " " << _mean_slip // Field 13: Average slip (meters)
<< " " << _moment // Field 14: Seismic moment (Newton-meters)
<< " " << _shear_before // Field 15: Shear stress before event (Pascal)
<< " " << _shear_after // Field 16: Shear stress after event (Pascal)
<< " " << _normal_before // Field 17: Normal stress before event (Pascal)
<< " " << _normal_after // Field 18: Normal stress after event (Pascal)
<< "\n";
for (it=slip_maps.begin();it!=slip_maps.end();++it) {
it->write(out_stream);
}
}
void quakelib::EQSimEventSlipMap::write(std::ostream &out_stream) const {
std::vector<EQSimEventSlipElement>::const_iterator it;
out_stream << "201"
<< " " << _depth_lo // Field 1: Lowest value of depth (meters, negative underground)
<< " " << _depth_hi // Field 2: Highest value of depth in the rupture (meters, negative underground)
<< " " << _das_lo // Field 3: Lowest value of distance-along-strike in the rupture (meters)
<< " " << _das_hi // Field 4: Highest value of distance-along-strike in the rupture (meters)
<< " " << _area // Field 5: Rupture area (square meters)
<< " " << _mean_slip // Field 6: Average slip (meters)
<< " " << _moment // Field 7: Seismic moment (Newton-meters)
<< " " << _shear_before // Field 8: Shear stress before event (Pascal)
<< " " << _shear_after // Field 9: Shear stress after event (Pascal)
<< " " << _normal_before // Field 10: Normal stress before event (Pascal)
<< " " << _normal_after; // Field 11: Normal stress after event (Pascal)
// Field 12: Element ID number (positive integer), or negative of element count (zero if no element info)
if (slip_elements.size() == 0) {
out_stream << " " << 0 << "\n";
} else if (slip_elements.size() == 1) {
out_stream << " " << slip_elements.back().element_id() << "\n";
} else {
out_stream << " -" << slip_elements.size() << "\n";
for (it=slip_elements.begin();it!=slip_elements.end();++it) it->write(out_stream);
}
}
void quakelib::EQSimEventSlipElement::write(std::ostream &out_stream) const {
out_stream << "202"
<< " " << _element_id
<< "\n";
}
bool quakelib::EQSimEventReader::parse_line(const int &rec_num, const int &line_num, std::istringstream &line_stream) {
switch (rec_num) {
case 200: parse_event_summary(line_num, line_stream); return true;
case 201: parse_event_slip_map(line_num, line_stream); return true;
case 202: parse_event_slip_element(line_num, line_stream); return true;
default: return false;
}
}
quakelib::EQSimEventWriter::EQSimEventWriter(void) {
quakelib::internal::RecordDesc event_summary_rec, slip_map_rec, slip_elem_rec;
set_spec_level(2);
meta_add_record(META_SIGNATURE, "EQSim_Output_Event_2");
event_summary_rec = internal::RecordDesc(0, "event_summary", 18, "Record 200: Event summary");
event_summary_rec.add_field(1, internal::FieldDesc("event_id", 1, 1, "Event ID number (positive integers, in order, need not be consecutive)"));
event_summary_rec.add_field(2, internal::FieldDesc("magnitude", 2, 2, "Event magnitude"));
event_summary_rec.add_field(3, internal::FieldDesc("time", 2, 3, "Starting time of event (seconds)"));
event_summary_rec.add_field(4, internal::FieldDesc("duration", 2, 4, "Duration of event (seconds)"));
event_summary_rec.add_field(5, internal::FieldDesc("sid", 1, 5, "Fault section ID number (positive integer)"));
event_summary_rec.add_field(6, internal::FieldDesc("depth_lo", 2, 6, "Lowest value of depth in the rupture (meters, negative underground)"));
event_summary_rec.add_field(7, internal::FieldDesc("depth_hi", 2, 7, "Highest value of depth in the rupture (meters, negative underground)"));
event_summary_rec.add_field(8, internal::FieldDesc("das_lo", 2, 8, "Lowest value of distance-along-strike in the rupture (meters)"));
event_summary_rec.add_field(9, internal::FieldDesc("das_hi", 2, 9, "Highest value of distance-along-strike in the rupture (meters)"));
event_summary_rec.add_field(10, internal::FieldDesc("hypo_depth", 2, 10, "Hypocenter depth (meters, negative underground)"));
event_summary_rec.add_field(11, internal::FieldDesc("hypo_das", 2, 11, "Hypocenter distance-along-strike (meters)"));
event_summary_rec.add_field(12, internal::FieldDesc("area", 2, 12, "Rupture area (square meters)"));
event_summary_rec.add_field(13, internal::FieldDesc("mean_slip", 2, 13, "Average slip (meters)"));
event_summary_rec.add_field(14, internal::FieldDesc("moment", 2, 14, "Seismic moment (Newton-meters)"));
event_summary_rec.add_field(15, internal::FieldDesc("shear_before", 2, 15, "Shear stress before event (Pascal)"));
event_summary_rec.add_field(16, internal::FieldDesc("shear_after", 2, 16, "Shear stress after event (Pascal)"));
event_summary_rec.add_field(17, internal::FieldDesc("normal_before", 2, 17, "Normal stress before event (Pascal)"));
event_summary_rec.add_field(18, internal::FieldDesc("normal_after", 2, 18, "Normal stress after event (Pascal)"));
slip_map_rec = internal::RecordDesc(0, "slip_map", 12, "Record 201: Slip map entry");
slip_map_rec.add_field(1, internal::FieldDesc("depth_lo", 2, 1, "Lowest value of depth (meters, negative underground)"));
slip_map_rec.add_field(2, internal::FieldDesc("depth_hi", 2, 2, "Highest value of depth (meters, negative underground)"));
slip_map_rec.add_field(3, internal::FieldDesc("das_lo", 2, 3, "Lowest value of distance-along-strike (meters)"));
slip_map_rec.add_field(4, internal::FieldDesc("das_hi", 2, 4, "Highest value of distance-along-strike (meters)"));
slip_map_rec.add_field(5, internal::FieldDesc("area", 2, 5, "Area (square meters)"));
slip_map_rec.add_field(6, internal::FieldDesc("mean_slip", 2, 6, "Average slip (meters)"));
slip_map_rec.add_field(7, internal::FieldDesc("moment", 2, 7, "Seismic moment (Newton-meters)"));
slip_map_rec.add_field(8, internal::FieldDesc("shear_before", 2, 8, "Shear stress before event (Pascal)"));
slip_map_rec.add_field(9, internal::FieldDesc("shear_after", 2, 9, "Shear stress after event (Pascal)"));
slip_map_rec.add_field(10, internal::FieldDesc("normal_before", 2, 10, "Normal stress before event (Pascal)"));
slip_map_rec.add_field(11, internal::FieldDesc("normal_after", 2, 11, "Normal stress after event (Pascal)"));
slip_map_rec.add_field(12, internal::FieldDesc("element_id", 1, 12, "Element ID number (positive integer), or negative of element count (zero if no element info)"));
slip_elem_rec = internal::RecordDesc(0, "slip_element", 1, "Record 202: Slip element list entry");
slip_elem_rec.add_field(1, internal::FieldDesc("element_id", 1, 1, "Element ID number (positive integer)"));
add_record_desc_record(200, event_summary_rec);
add_record_desc_record(201, slip_map_rec);
add_record_desc_record(202, slip_elem_rec);
}
| 43.95438 | 179 | 0.671109 | [
"vector"
] |
9cb0ba71246dc71f06c916cbed23b7b1f995b9f3 | 816 | cpp | C++ | src/utils.cpp | chris-pikul/mos6502 | 173332cc25aeb83ec727d2696e3f8b45c3734fca | [
"MIT"
] | null | null | null | src/utils.cpp | chris-pikul/mos6502 | 173332cc25aeb83ec727d2696e3f8b45c3734fca | [
"MIT"
] | null | null | null | src/utils.cpp | chris-pikul/mos6502 | 173332cc25aeb83ec727d2696e3f8b45c3734fca | [
"MIT"
] | 1 | 2022-02-17T17:06:36.000Z | 2022-02-17T17:06:36.000Z | /*
* MOS-6502 Emulator
* ===================
* Simple emulator recreating the processes of the famous MOS-6502 processor.
*
* Copyright (c) 2021 Chris Pikul.
* MIT License. See file "LICENSE.txt" for full license.
*/
#include "utils.h"
#include <iomanip>
#include <sstream>
namespace mos6502 {
std::vector<byte> ConvertHexStringToBytes(const std::string& str) {
std::stringstream ss;
ss << str; // Load the string into the stream
std::vector<byte> results;
std::string tmp;
while (!ss.eof()) {
ss >> tmp;
results.push_back(static_cast<byte>(std::stoul(tmp, nullptr, 16)));
}
return results;
}
std::string Hex(byte val) { return ToHex<byte>(val, 2); }
std::string Hex(word val) { return ToHex<word>(val, 4); }
std::string Hex(address val) { return ToHex<word>(val.value, 4); }
} | 24 | 77 | 0.654412 | [
"vector"
] |
9cb3ad79a9c4a5198e4a6c9eec62080b05a96c22 | 1,678 | cpp | C++ | aws-cpp-sdk-firehose/source/model/CopyCommand.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-firehose/source/model/CopyCommand.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-firehose/source/model/CopyCommand.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/firehose/model/CopyCommand.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Firehose
{
namespace Model
{
CopyCommand::CopyCommand() :
m_dataTableNameHasBeenSet(false),
m_dataTableColumnsHasBeenSet(false),
m_copyOptionsHasBeenSet(false)
{
}
CopyCommand::CopyCommand(JsonView jsonValue) :
m_dataTableNameHasBeenSet(false),
m_dataTableColumnsHasBeenSet(false),
m_copyOptionsHasBeenSet(false)
{
*this = jsonValue;
}
CopyCommand& CopyCommand::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("DataTableName"))
{
m_dataTableName = jsonValue.GetString("DataTableName");
m_dataTableNameHasBeenSet = true;
}
if(jsonValue.ValueExists("DataTableColumns"))
{
m_dataTableColumns = jsonValue.GetString("DataTableColumns");
m_dataTableColumnsHasBeenSet = true;
}
if(jsonValue.ValueExists("CopyOptions"))
{
m_copyOptions = jsonValue.GetString("CopyOptions");
m_copyOptionsHasBeenSet = true;
}
return *this;
}
JsonValue CopyCommand::Jsonize() const
{
JsonValue payload;
if(m_dataTableNameHasBeenSet)
{
payload.WithString("DataTableName", m_dataTableName);
}
if(m_dataTableColumnsHasBeenSet)
{
payload.WithString("DataTableColumns", m_dataTableColumns);
}
if(m_copyOptionsHasBeenSet)
{
payload.WithString("CopyOptions", m_copyOptions);
}
return payload;
}
} // namespace Model
} // namespace Firehose
} // namespace Aws
| 18.644444 | 69 | 0.733015 | [
"model"
] |
9cb526458593f884bf1252bae3e749742b512c7e | 16,395 | cpp | C++ | version3/cpp/hash.cpp | mastersingh24/amcl | 17fe79cb251c4badedb991170948ee05c0a613d8 | [
"Apache-2.0"
] | null | null | null | version3/cpp/hash.cpp | mastersingh24/amcl | 17fe79cb251c4badedb991170948ee05c0a613d8 | [
"Apache-2.0"
] | null | null | null | version3/cpp/hash.cpp | mastersingh24/amcl | 17fe79cb251c4badedb991170948ee05c0a613d8 | [
"Apache-2.0"
] | null | null | null | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
/*
* Implementation of the Secure Hashing Algorithm (SHA-256/384/512 and SHA3)
*
* Generates a message digest. It should be impossible to come
* come up with two messages that hash to the same value ("collision free").
*
* For use with byte-oriented messages only. Could/Should be speeded
* up by unwinding loops in HASH_transform(), and assembly patches.
*/
#include "arch.h"
#include "amcl.h"
using namespace amcl;
#define H0_256 0x6A09E667L
#define H1_256 0xBB67AE85L
#define H2_256 0x3C6EF372L
#define H3_256 0xA54FF53AL
#define H4_256 0x510E527FL
#define H5_256 0x9B05688CL
#define H6_256 0x1F83D9ABL
#define H7_256 0x5BE0CD19L
static const unsign32 K_256[64]=
{
0x428a2f98L,0x71374491L,0xb5c0fbcfL,0xe9b5dba5L,0x3956c25bL,0x59f111f1L,0x923f82a4L,0xab1c5ed5L,
0xd807aa98L,0x12835b01L,0x243185beL,0x550c7dc3L,0x72be5d74L,0x80deb1feL,0x9bdc06a7L,0xc19bf174L,
0xe49b69c1L,0xefbe4786L,0x0fc19dc6L,0x240ca1ccL,0x2de92c6fL,0x4a7484aaL,0x5cb0a9dcL,0x76f988daL,
0x983e5152L,0xa831c66dL,0xb00327c8L,0xbf597fc7L,0xc6e00bf3L,0xd5a79147L,0x06ca6351L,0x14292967L,
0x27b70a85L,0x2e1b2138L,0x4d2c6dfcL,0x53380d13L,0x650a7354L,0x766a0abbL,0x81c2c92eL,0x92722c85L,
0xa2bfe8a1L,0xa81a664bL,0xc24b8b70L,0xc76c51a3L,0xd192e819L,0xd6990624L,0xf40e3585L,0x106aa070L,
0x19a4c116L,0x1e376c08L,0x2748774cL,0x34b0bcb5L,0x391c0cb3L,0x4ed8aa4aL,0x5b9cca4fL,0x682e6ff3L,
0x748f82eeL,0x78a5636fL,0x84c87814L,0x8cc70208L,0x90befffaL,0xa4506cebL,0xbef9a3f7L,0xc67178f2L
};
#define PAD 0x80
#define ZERO 0
/* functions */
#define S(m,n,x) (((x)>>n) | ((x)<<(m-n)))
#define R(n,x) ((x)>>n)
#define Ch(x,y,z) ((x&y)^(~(x)&z))
#define Maj(x,y,z) ((x&y)^(x&z)^(y&z))
#define Sig0_256(x) (S(32,2,x)^S(32,13,x)^S(32,22,x))
#define Sig1_256(x) (S(32,6,x)^S(32,11,x)^S(32,25,x))
#define theta0_256(x) (S(32,7,x)^S(32,18,x)^R(3,x))
#define theta1_256(x) (S(32,17,x)^S(32,19,x)^R(10,x))
#define Sig0_512(x) (S(64,28,x)^S(64,34,x)^S(64,39,x))
#define Sig1_512(x) (S(64,14,x)^S(64,18,x)^S(64,41,x))
#define theta0_512(x) (S(64,1,x)^S(64,8,x)^R(7,x))
#define theta1_512(x) (S(64,19,x)^S(64,61,x)^R(6,x))
/* SU= 72 */
static void HASH256_transform(hash256 *sh)
{
/* basic transformation step */
unsign32 a,b,c,d,e,f,g,h,t1,t2;
int j;
for (j=16; j<64; j++)
sh->w[j]=theta1_256(sh->w[j-2])+sh->w[j-7]+theta0_256(sh->w[j-15])+sh->w[j-16];
a=sh->h[0];
b=sh->h[1];
c=sh->h[2];
d=sh->h[3];
e=sh->h[4];
f=sh->h[5];
g=sh->h[6];
h=sh->h[7];
for (j=0; j<64; j++)
{
/* 64 times - mush it up */
t1=h+Sig1_256(e)+Ch(e,f,g)+K_256[j]+sh->w[j];
t2=Sig0_256(a)+Maj(a,b,c);
h=g;
g=f;
f=e;
e=d+t1;
d=c;
c=b;
b=a;
a=t1+t2;
}
sh->h[0]+=a;
sh->h[1]+=b;
sh->h[2]+=c;
sh->h[3]+=d;
sh->h[4]+=e;
sh->h[5]+=f;
sh->h[6]+=g;
sh->h[7]+=h;
}
/* Initialise Hash function */
void amcl::HASH256_init(hash256 *sh)
{
/* re-initialise */
int i;
for (i=0; i<64; i++) sh->w[i]=0L;
sh->length[0]=sh->length[1]=0L;
sh->h[0]=H0_256;
sh->h[1]=H1_256;
sh->h[2]=H2_256;
sh->h[3]=H3_256;
sh->h[4]=H4_256;
sh->h[5]=H5_256;
sh->h[6]=H6_256;
sh->h[7]=H7_256;
sh->hlen=32;
}
/* process a single byte */
void amcl::HASH256_process(hash256 *sh,int byte)
{
/* process the next message byte */
int cnt;
//printf("byt= %x\n",byte);
cnt=(int)((sh->length[0]/32)%16);
sh->w[cnt]<<=8;
sh->w[cnt]|=(unsign32)(byte&0xFF);
sh->length[0]+=8;
if (sh->length[0]==0L)
{
sh->length[1]++;
sh->length[0]=0L;
}
if ((sh->length[0]%512)==0) HASH256_transform(sh);
}
/* SU= 24 */
/* Generate 32-byte Hash */
void amcl::HASH256_hash(hash256 *sh,char *digest)
{
/* pad message and finish - supply digest */
int i;
unsign32 len0,len1;
len0=sh->length[0];
len1=sh->length[1];
HASH256_process(sh,PAD);
while ((sh->length[0]%512)!=448) HASH256_process(sh,ZERO);
sh->w[14]=len1;
sh->w[15]=len0;
HASH256_transform(sh);
for (i=0; i<sh->hlen; i++)
{
/* convert to bytes */
digest[i]=(char)((sh->h[i/4]>>(8*(3-i%4))) & 0xffL);
}
HASH256_init(sh);
}
#define H0_512 0x6a09e667f3bcc908
#define H1_512 0xbb67ae8584caa73b
#define H2_512 0x3c6ef372fe94f82b
#define H3_512 0xa54ff53a5f1d36f1
#define H4_512 0x510e527fade682d1
#define H5_512 0x9b05688c2b3e6c1f
#define H6_512 0x1f83d9abfb41bd6b
#define H7_512 0x5be0cd19137e2179
#define H8_512 0xcbbb9d5dc1059ed8
#define H9_512 0x629a292a367cd507
#define HA_512 0x9159015a3070dd17
#define HB_512 0x152fecd8f70e5939
#define HC_512 0x67332667ffc00b31
#define HD_512 0x8eb44a8768581511
#define HE_512 0xdb0c2e0d64f98fa7
#define HF_512 0x47b5481dbefa4fa4
/* */
static const unsign64 K_512[80]=
{
0x428a2f98d728ae22 ,0x7137449123ef65cd ,0xb5c0fbcfec4d3b2f ,0xe9b5dba58189dbbc ,
0x3956c25bf348b538 ,0x59f111f1b605d019 ,0x923f82a4af194f9b ,0xab1c5ed5da6d8118 ,
0xd807aa98a3030242 ,0x12835b0145706fbe ,0x243185be4ee4b28c ,0x550c7dc3d5ffb4e2 ,
0x72be5d74f27b896f ,0x80deb1fe3b1696b1 ,0x9bdc06a725c71235 ,0xc19bf174cf692694 ,
0xe49b69c19ef14ad2 ,0xefbe4786384f25e3 ,0x0fc19dc68b8cd5b5 ,0x240ca1cc77ac9c65 ,
0x2de92c6f592b0275 ,0x4a7484aa6ea6e483 ,0x5cb0a9dcbd41fbd4 ,0x76f988da831153b5 ,
0x983e5152ee66dfab ,0xa831c66d2db43210 ,0xb00327c898fb213f ,0xbf597fc7beef0ee4 ,
0xc6e00bf33da88fc2 ,0xd5a79147930aa725 ,0x06ca6351e003826f ,0x142929670a0e6e70 ,
0x27b70a8546d22ffc ,0x2e1b21385c26c926 ,0x4d2c6dfc5ac42aed ,0x53380d139d95b3df ,
0x650a73548baf63de ,0x766a0abb3c77b2a8 ,0x81c2c92e47edaee6 ,0x92722c851482353b ,
0xa2bfe8a14cf10364 ,0xa81a664bbc423001 ,0xc24b8b70d0f89791 ,0xc76c51a30654be30 ,
0xd192e819d6ef5218 ,0xd69906245565a910 ,0xf40e35855771202a ,0x106aa07032bbd1b8 ,
0x19a4c116b8d2d0c8 ,0x1e376c085141ab53 ,0x2748774cdf8eeb99 ,0x34b0bcb5e19b48a8 ,
0x391c0cb3c5c95a63 ,0x4ed8aa4ae3418acb ,0x5b9cca4f7763e373 ,0x682e6ff3d6b2b8a3 ,
0x748f82ee5defb2fc ,0x78a5636f43172f60 ,0x84c87814a1f0ab72 ,0x8cc702081a6439ec ,
0x90befffa23631e28 ,0xa4506cebde82bde9 ,0xbef9a3f7b2c67915 ,0xc67178f2e372532b ,
0xca273eceea26619c ,0xd186b8c721c0c207 ,0xeada7dd6cde0eb1e ,0xf57d4f7fee6ed178 ,
0x06f067aa72176fba ,0x0a637dc5a2c898a6 ,0x113f9804bef90dae ,0x1b710b35131c471b ,
0x28db77f523047d84 ,0x32caab7b40c72493 ,0x3c9ebe0a15c9bebc ,0x431d67c49c100d4c ,
0x4cc5d4becb3e42b6 ,0x597f299cfc657e2a ,0x5fcb6fab3ad6faec ,0x6c44198c4a475817
};
static void HASH512_transform(hash512 *sh)
{
/* basic transformation step */
unsign64 a,b,c,d,e,f,g,h,t1,t2;
int j;
for (j=16; j<80; j++)
sh->w[j]=theta1_512(sh->w[j-2])+sh->w[j-7]+theta0_512(sh->w[j-15])+sh->w[j-16];
a=sh->h[0];
b=sh->h[1];
c=sh->h[2];
d=sh->h[3];
e=sh->h[4];
f=sh->h[5];
g=sh->h[6];
h=sh->h[7];
for (j=0; j<80; j++)
{
/* 80 times - mush it up */
t1=h+Sig1_512(e)+Ch(e,f,g)+K_512[j]+sh->w[j];
t2=Sig0_512(a)+Maj(a,b,c);
h=g;
g=f;
f=e;
e=d+t1;
d=c;
c=b;
b=a;
a=t1+t2;
}
sh->h[0]+=a;
sh->h[1]+=b;
sh->h[2]+=c;
sh->h[3]+=d;
sh->h[4]+=e;
sh->h[5]+=f;
sh->h[6]+=g;
sh->h[7]+=h;
}
void amcl::HASH384_init(hash384 *sh)
{
/* re-initialise */
int i;
for (i=0; i<80; i++) sh->w[i]=0;
sh->length[0]=sh->length[1]=0;
sh->h[0]=H8_512;
sh->h[1]=H9_512;
sh->h[2]=HA_512;
sh->h[3]=HB_512;
sh->h[4]=HC_512;
sh->h[5]=HD_512;
sh->h[6]=HE_512;
sh->h[7]=HF_512;
sh->hlen=48;
}
void amcl::HASH384_process(hash384 *sh,int byte)
{
/* process the next message byte */
HASH512_process(sh,byte);
}
void amcl::HASH384_hash(hash384 *sh,char *hash)
{
/* pad message and finish - supply digest */
HASH512_hash(sh,hash);
}
void amcl::HASH512_init(hash512 *sh)
{
/* re-initialise */
int i;
for (i=0; i<80; i++) sh->w[i]=0;
sh->length[0]=sh->length[1]=0;
sh->h[0]=H0_512;
sh->h[1]=H1_512;
sh->h[2]=H2_512;
sh->h[3]=H3_512;
sh->h[4]=H4_512;
sh->h[5]=H5_512;
sh->h[6]=H6_512;
sh->h[7]=H7_512;
sh->hlen=64;
}
void amcl::HASH512_process(hash512 *sh,int byte)
{
/* process the next message byte */
int cnt;
cnt=(int)((sh->length[0]/64)%16);
sh->w[cnt]<<=8;
sh->w[cnt]|=(unsign64)(byte&0xFF);
sh->length[0]+=8;
if (sh->length[0]==0L)
{
sh->length[1]++;
sh->length[0]=0L;
}
if ((sh->length[0]%1024)==0) HASH512_transform(sh);
}
void amcl::HASH512_hash(hash512 *sh,char *hash)
{
/* pad message and finish - supply digest */
int i;
unsign64 len0,len1;
len0=sh->length[0];
len1=sh->length[1];
HASH512_process(sh,PAD);
while ((sh->length[0]%1024)!=896) HASH512_process(sh,ZERO);
sh->w[14]=len1;
sh->w[15]=len0;
HASH512_transform(sh);
for (i=0; i<sh->hlen; i++)
{
/* convert to bytes */
hash[i]=(char)((sh->h[i/8]>>(8*(7-i%8))) & 0xffL);
}
HASH512_init(sh);
}
/* SHA3 */
#define SHA3_ROUNDS 24
#define rotl(x,n) (((x)<<n) | ((x)>>(64-n)))
/* round constants */
static const unsign64 RC[24]={
0x0000000000000001UL,0x0000000000008082UL,0x800000000000808AUL,0x8000000080008000UL,
0x000000000000808BUL,0x0000000080000001UL,0x8000000080008081UL,0x8000000000008009UL,
0x000000000000008AUL,0x0000000000000088UL,0x0000000080008009UL,0x000000008000000AUL,
0x000000008000808BUL,0x800000000000008BUL,0x8000000000008089UL,0x8000000000008003UL,
0x8000000000008002UL,0x8000000000000080UL,0x000000000000800AUL,0x800000008000000AUL,
0x8000000080008081UL,0x8000000000008080UL,0x0000000080000001UL,0x8000000080008008UL};
/* permutation */
static void SHA3_transform(sha3 *sh)
{
int i,j,k;
unsign64 C[5],D[5],B[5][5];
for (k=0;k<SHA3_ROUNDS;k++)
{
C[0]=sh->S[0][0]^sh->S[0][1]^sh->S[0][2]^sh->S[0][3]^sh->S[0][4];
C[1]=sh->S[1][0]^sh->S[1][1]^sh->S[1][2]^sh->S[1][3]^sh->S[1][4];
C[2]=sh->S[2][0]^sh->S[2][1]^sh->S[2][2]^sh->S[2][3]^sh->S[2][4];
C[3]=sh->S[3][0]^sh->S[3][1]^sh->S[3][2]^sh->S[3][3]^sh->S[3][4];
C[4]=sh->S[4][0]^sh->S[4][1]^sh->S[4][2]^sh->S[4][3]^sh->S[4][4];
D[0]=C[4]^rotl(C[1],1);
D[1]=C[0]^rotl(C[2],1);
D[2]=C[1]^rotl(C[3],1);
D[3]=C[2]^rotl(C[4],1);
D[4]=C[3]^rotl(C[0],1);
for (i=0;i<5;i++)
for (j=0;j<5;j++)
sh->S[i][j]^=D[i]; /* let the compiler unroll it! */
B[0][0]=sh->S[0][0];
B[1][3]=rotl(sh->S[0][1],36);
B[2][1]=rotl(sh->S[0][2],3);
B[3][4]=rotl(sh->S[0][3],41);
B[4][2]=rotl(sh->S[0][4],18);
B[0][2]=rotl(sh->S[1][0],1);
B[1][0]=rotl(sh->S[1][1],44);
B[2][3]=rotl(sh->S[1][2],10);
B[3][1]=rotl(sh->S[1][3],45);
B[4][4]=rotl(sh->S[1][4],2);
B[0][4]=rotl(sh->S[2][0],62);
B[1][2]=rotl(sh->S[2][1],6);
B[2][0]=rotl(sh->S[2][2],43);
B[3][3]=rotl(sh->S[2][3],15);
B[4][1]=rotl(sh->S[2][4],61);
B[0][1]=rotl(sh->S[3][0],28);
B[1][4]=rotl(sh->S[3][1],55);
B[2][2]=rotl(sh->S[3][2],25);
B[3][0]=rotl(sh->S[3][3],21);
B[4][3]=rotl(sh->S[3][4],56);
B[0][3]=rotl(sh->S[4][0],27);
B[1][1]=rotl(sh->S[4][1],20);
B[2][4]=rotl(sh->S[4][2],39);
B[3][2]=rotl(sh->S[4][3],8);
B[4][0]=rotl(sh->S[4][4],14);
for (i=0;i<5;i++)
for (j=0;j<5;j++)
sh->S[i][j]=B[i][j]^(~B[(i+1)%5][j]&B[(i+2)%5][j]);
sh->S[0][0]^=RC[k];
}
}
/* Re-Initialize. olen is output length in bytes -
should be 28, 32, 48 or 64 (224, 256, 384, 512 bits resp.) */
void amcl::SHA3_init(sha3 *sh,int olen)
{
int i,j;
for (i=0;i<5;i++)
for (j=0;j<5;j++)
sh->S[i][j]=0; /* 5x5x8 bytes = 200 bytes of state */
sh->length=0;
sh->len=olen;
sh->rate=200-2*olen; /* number of bytes consumed in one gulp. Note that some bytes in the
state ("capacity") are not touched. Gulps are smaller for larger digests.
Important that olen<rate */
}
/* process a single byte */
void amcl::SHA3_process(sha3 *sh,int byte)
{
int cnt=(int)(sh->length%sh->rate);
int i,j,b=cnt%8;
cnt/=8;
i=cnt%5; j=cnt/5; /* process by columns! */
sh->S[i][j]^=((unsign64)byte<<(8*b));
sh->length++;
if (sh->length%sh->rate==0) SHA3_transform(sh);
}
/* squeeze the sponge */
void amcl::SHA3_squeeze(sha3 *sh,char *buff,int len)
{
int done,i,j,k,m=0;
unsign64 el;
/* extract by columns */
done=0;
for (;;)
{
for (j=0;j<5;j++)
{
for (i=0;i<5;i++)
{
el=sh->S[i][j];
for (k=0;k<8;k++)
{
buff[m++]=(el&0xff);
if (m>=len || m%sh->rate==0) {done=1; break;}
el>>=8;
}
if (done) break;
}
if (done) break;
}
if (m>=len) break;
done=0;
SHA3_transform(sh);
}
}
void amcl::SHA3_hash(sha3 *sh,char *hash)
{ /* generate a SHA3 hash of appropriate size */
int q=sh->rate-(sh->length%sh->rate);
if (q==1) SHA3_process(sh,0x86);
else
{
SHA3_process(sh,0x06); /* 0x06 for SHA-3 */
while (sh->length%sh->rate!=sh->rate-1) SHA3_process(sh,0x00);
SHA3_process(sh,0x80); /* this will force a final transform */
}
SHA3_squeeze(sh,hash,sh->len);
}
void amcl::SHA3_shake(sha3 *sh,char *buff,int len)
{ /* SHAKE out a buffer of variable length len */
int q=sh->rate-(sh->length%sh->rate);
if (q==1) SHA3_process(sh,0x9f);
else
{
SHA3_process(sh,0x1f); // 0x06 for SHA-3 !!!!
while (sh->length%sh->rate!=sh->rate-1) SHA3_process(sh,0x00);
SHA3_process(sh,0x80); /* this will force a final transform */
}
SHA3_squeeze(sh,buff,len);
}
/* test program: should produce digest
160 bit
84983e44 1c3bd26e baae4aa1 f95129e5 e54670f1
256 bit
248d6a61 d20638b8 e5c02693 0c3e6039 a33ce459 64ff2167 f6ecedd4 19db06c1
512 bit
8e959b75dae313da 8cf4f72814fc143f 8f7779c6eb9f7fa1 7299aeadb6889018
501d289e4900f7e4 331b99dec4b5433a c7d329eeb6dd2654 5e96e55b874be909
384 bit
09330c33f71147e8 3d192fc782cd1b47 53111b173b3b05d2 2fa08086e3b0f712
fcc7c71a557e2db9 66c3e9fa91746039
*/
/*
#include <stdio.h>
char test160[]="abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
char test256[]="abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq";
char test512[]="abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu";
int main()
{
char digest[100];
int i;
hash256 sh256;
hash384 sh384;
hash512 sh512;
sha3 SHA3;
HASH256_init(&sh256);
for (i=0;test256[i]!=0;i++) HASH256_process(&sh256,test256[i]);
HASH256_hash(&sh256,digest);
for (i=0;i<32;i++) printf("%02x",(unsigned char)digest[i]);
printf("\n");
HASH384_init(&sh384);
for (i=0;test512[i]!=0;i++) HASH384_process(&sh384,test512[i]);
HASH384_hash(&sh384,digest);
for (i=0;i<48;i++) printf("%02x",(unsigned char)digest[i]);
printf("\n");
HASH512_init(&sh512);
for (i=0;test512[i]!=0;i++) HASH512_process(&sh512,test512[i]);
HASH512_hash(&sh512,digest);
for (i=0;i<64;i++) printf("%02x",(unsigned char)digest[i]);
printf("\n");
SHA3_init(&SHA3,SHA3_HASH256);
for (i=0;test512[i]!=0;i++) SHA3_process(&SHA3,test512[i]);
SHA3_hash(&sh512,digest);
for (i=0;i<32;i++) printf("%02x",(unsigned char)digest[i]);
printf("\n");
SHA3_init(&SHA3,SHA3_HASH512);
for (i=0;test512[i]!=0;i++) SHA3_process(&SHA3,test512[i]);
SHA3_hash(&sh512,digest);
for (i=0;i<64;i++) printf("%02x",(unsigned char)digest[i]);
printf("\n");
SHA3_init(&SHA3,SHAKE256);
for (i=0;test512[i]!=0;i++) SHA3_process(&SHA3,test512[i]);
SHA3_shake(&sh512,digest,72);
for (i=0;i<72;i++) printf("%02x",(unsigned char)digest[i]);
printf("\n");
return 0;
}
*/
| 27.325 | 130 | 0.635926 | [
"transform"
] |
9cb74af42a7f1c29c1b70b49700774aa9e7d6b70 | 9,078 | cpp | C++ | Gems/Atom/RHI/DX12/Code/Source/RHI/PipelineState.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T12:39:24.000Z | 2021-07-20T12:39:24.000Z | Gems/Atom/RHI/DX12/Code/Source/RHI/PipelineState.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/RHI/DX12/Code/Source/RHI/PipelineState.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include "RHI/Atom_RHI_DX12_precompiled.h"
#include <RHI/PipelineState.h>
#include <RHI/PipelineLibrary.h>
#include <Atom/RHI.Reflect/DX12/ShaderStageFunction.h>
#include <RHI/Conversions.h>
#include <RHI/Device.h>
#include <AzCore/Debug/EventTrace.h>
namespace AZ
{
namespace DX12
{
RHI::Ptr<PipelineState> PipelineState::Create()
{
return aznew PipelineState;
}
const PipelineLayout& PipelineState::GetPipelineLayout() const
{
return *m_pipelineLayout;
}
ID3D12PipelineState* PipelineState::Get() const
{
return m_pipelineState.get();
}
const PipelineStateData& PipelineState::GetPipelineStateData() const
{
return m_pipelineStateData;
}
D3D12_SHADER_BYTECODE D3D12BytecodeFromView(ShaderByteCodeView view)
{
return D3D12_SHADER_BYTECODE{ view.data(), view.size() };
}
RHI::ResultCode PipelineState::InitInternal(
RHI::Device& deviceBase,
const RHI::PipelineStateDescriptorForDraw& descriptor,
RHI::PipelineLibrary* pipelineLibraryBase)
{
Device& device = static_cast<Device&>(deviceBase);
D3D12_GRAPHICS_PIPELINE_STATE_DESC pipelineStateDesc = {};
pipelineStateDesc.NodeMask = 1;
pipelineStateDesc.SampleMask = 0xFFFFFFFFu;
pipelineStateDesc.SampleDesc.Count = descriptor.m_renderStates.m_multisampleState.m_samples;
pipelineStateDesc.SampleDesc.Quality = descriptor.m_renderStates.m_multisampleState.m_quality;
// Shader state.
RHI::ConstPtr<PipelineLayout> pipelineLayout = device.AcquirePipelineLayout(*descriptor.m_pipelineLayoutDescriptor);
pipelineStateDesc.pRootSignature = pipelineLayout->Get();
if (const ShaderStageFunction* vertexFunction = azrtti_cast<const ShaderStageFunction*>(descriptor.m_vertexFunction.get()))
{
pipelineStateDesc.VS = D3D12BytecodeFromView(vertexFunction->GetByteCode());
}
if (const ShaderStageFunction* tessellationFunction = azrtti_cast<const ShaderStageFunction*>(descriptor.m_tessellationFunction.get()))
{
pipelineStateDesc.HS = D3D12BytecodeFromView(tessellationFunction->GetByteCode(ShaderSubStage::TessellationHull));
pipelineStateDesc.DS = D3D12BytecodeFromView(tessellationFunction->GetByteCode(ShaderSubStage::TessellationDomain));
}
if (const ShaderStageFunction* fragmentFunction = azrtti_cast<const ShaderStageFunction*>(descriptor.m_fragmentFunction.get()))
{
pipelineStateDesc.PS = D3D12BytecodeFromView(fragmentFunction->GetByteCode());
}
const RHI::RenderAttachmentConfiguration& renderAttachmentConfiguration = descriptor.m_renderAttachmentConfiguration;
pipelineStateDesc.DSVFormat = ConvertFormat(renderAttachmentConfiguration.GetDepthStencilFormat());
pipelineStateDesc.NumRenderTargets = renderAttachmentConfiguration.GetRenderTargetCount();
for (uint32_t targetIdx = 0; targetIdx < pipelineStateDesc.NumRenderTargets; ++targetIdx)
{
pipelineStateDesc.RTVFormats[targetIdx] = ConvertFormat(renderAttachmentConfiguration.GetRenderTargetFormat(targetIdx));
}
AZStd::vector<D3D12_INPUT_ELEMENT_DESC> inputElements = ConvertInputElements(descriptor.m_inputStreamLayout);
pipelineStateDesc.InputLayout.NumElements = uint32_t(inputElements.size());
pipelineStateDesc.InputLayout.pInputElementDescs = inputElements.data();
pipelineStateDesc.PrimitiveTopologyType = ConvertToTopologyType(descriptor.m_inputStreamLayout.GetTopology());
pipelineStateDesc.BlendState = ConvertBlendState(descriptor.m_renderStates.m_blendState);
pipelineStateDesc.RasterizerState = ConvertRasterState(descriptor.m_renderStates.m_rasterState);
pipelineStateDesc.DepthStencilState = ConvertDepthStencilState(descriptor.m_renderStates.m_depthStencilState);
PipelineLibrary* pipelineLibrary = static_cast<PipelineLibrary*>(pipelineLibraryBase);
RHI::Ptr<ID3D12PipelineState> pipelineState;
if (pipelineLibrary && pipelineLibrary->IsInitialized())
{
pipelineState = pipelineLibrary->CreateGraphicsPipelineState(static_cast<uint64_t>(descriptor.GetHash()), pipelineStateDesc);
}
else
{
Microsoft::WRL::ComPtr<ID3D12PipelineState> pipelineStateComPtr;
device.GetDevice()->CreateGraphicsPipelineState(&pipelineStateDesc, IID_GRAPHICS_PPV_ARGS(pipelineStateComPtr.GetAddressOf()));
pipelineState = pipelineStateComPtr.Get();
}
if (pipelineState)
{
m_pipelineLayout = AZStd::move(pipelineLayout);
m_pipelineState = AZStd::move(pipelineState);
m_pipelineStateData.m_type = RHI::PipelineStateType::Draw;
m_pipelineStateData.m_drawData = PipelineStateDrawData{ descriptor.m_renderStates.m_multisampleState, descriptor.m_inputStreamLayout.GetTopology() };
return RHI::ResultCode::Success;
}
else
{
AZ_Error("PipelineState", false, "Failed to compile graphics pipeline state. Check the D3D12 debug layer for more info.");
return RHI::ResultCode::Fail;
}
}
RHI::ResultCode PipelineState::InitInternal(
RHI::Device& deviceBase,
const RHI::PipelineStateDescriptorForDispatch& descriptor,
RHI::PipelineLibrary* pipelineLibraryBase)
{
Device& device = static_cast<Device&>(deviceBase);
D3D12_COMPUTE_PIPELINE_STATE_DESC pipelineStateDesc = {};
pipelineStateDesc.NodeMask = 1;
RHI::ConstPtr<PipelineLayout> pipelineLayout = device.AcquirePipelineLayout(*descriptor.m_pipelineLayoutDescriptor);
pipelineStateDesc.pRootSignature = pipelineLayout->Get();
if (const ShaderStageFunction* computeFunction = azrtti_cast<const ShaderStageFunction*>(descriptor.m_computeFunction.get()))
{
pipelineStateDesc.CS = D3D12BytecodeFromView(computeFunction->GetByteCode());
}
PipelineLibrary* pipelineLibrary = static_cast<PipelineLibrary*>(pipelineLibraryBase);
RHI::Ptr<ID3D12PipelineState> pipelineState;
if (pipelineLibrary && pipelineLibrary->IsInitialized())
{
pipelineState = pipelineLibrary->CreateComputePipelineState(static_cast<uint64_t>(descriptor.GetHash()), pipelineStateDesc);
}
else
{
Microsoft::WRL::ComPtr<ID3D12PipelineState> pipelineStateComPtr;
device.GetDevice()->CreateComputePipelineState(&pipelineStateDesc, IID_GRAPHICS_PPV_ARGS(pipelineStateComPtr.GetAddressOf()));
pipelineState = pipelineStateComPtr.Get();
}
if (pipelineState)
{
m_pipelineLayout = AZStd::move(pipelineLayout);
m_pipelineState = AZStd::move(pipelineState);
m_pipelineStateData.m_type = RHI::PipelineStateType::Dispatch;
return RHI::ResultCode::Success;
}
else
{
AZ_Error("PipelineState", false, "Failed to compile graphics pipeline state. Check the D3D12 debug layer for more info.");
return RHI::ResultCode::Fail;
}
}
RHI::ResultCode PipelineState::InitInternal(
RHI::Device& deviceBase,
const RHI::PipelineStateDescriptorForRayTracing& descriptor,
[[maybe_unused]] RHI::PipelineLibrary* pipelineLibraryBase)
{
Device& device = static_cast<Device&>(deviceBase);
RHI::ConstPtr<PipelineLayout> pipelineLayout = device.AcquirePipelineLayout(*descriptor.m_pipelineLayoutDescriptor);
m_pipelineLayout = AZStd::move(pipelineLayout);
m_pipelineStateData.m_type = RHI::PipelineStateType::RayTracing;
return RHI::ResultCode::Success;
}
void PipelineState::ShutdownInternal()
{
// ray tracing shaders do not have a traditional pipeline state object
if (m_pipelineStateData.m_type != RHI::PipelineStateType::RayTracing)
{
static_cast<Device&>(GetDevice()).QueueForRelease(AZStd::move(m_pipelineState));
}
m_pipelineState = nullptr;
m_pipelineLayout = nullptr;
}
}
}
| 45.848485 | 165 | 0.664574 | [
"object",
"vector",
"3d"
] |
9cbb1cd93857928a275e2fea4526a7ed76c34c72 | 20,979 | cpp | C++ | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dglyphpainter.cpp | jonfortescue/wpf | 6d35e1a0539cc5cc7a6111a11b781f52cfc71fc2 | [
"MIT"
] | 5,937 | 2018-12-04T16:32:50.000Z | 2022-03-31T09:48:37.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dglyphpainter.cpp | jonfortescue/wpf | 6d35e1a0539cc5cc7a6111a11b781f52cfc71fc2 | [
"MIT"
] | 4,151 | 2018-12-04T16:38:19.000Z | 2022-03-31T18:41:14.000Z | src/Microsoft.DotNet.Wpf/src/WpfGfx/core/hw/d3dglyphpainter.cpp | jonfortescue/wpf | 6d35e1a0539cc5cc7a6111a11b781f52cfc71fc2 | [
"MIT"
] | 1,084 | 2018-12-04T16:24:21.000Z | 2022-03-30T13:52:03.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.
//+-----------------------------------------------------------------------------
//
//
// $TAG ENGR
// $Module: win_mil_graphics_text
// $Keywords:
//
// $Description:
// see comments in header file.
//
// $ENDTAG
//
//------------------------------------------------------------------------------
#include "precomp.hpp"
CD3DGlyphRunPainter::CD3DGlyphRunPainter()
{
m_data.m_pHwColorSource = NULL;
}
CD3DGlyphRunPainter::~CD3DGlyphRunPainter()
{
ReleaseInterfaceNoNULL(m_data.m_pHwColorSource);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CD3DGlyphRunPainter::Paint
//
// Synopsis:
// execute glyphrun rendering
//
//------------------------------------------------------------------------------
HRESULT
CD3DGlyphRunPainter::Paint(
__in_ecount(1) DrawGlyphsParameters &pars,
bool fTargetSupportsClearType,
__inout_ecount(1) CD3DDeviceLevel1* pDevice,
MilPixelFormat::Enum fmtTargetSurface
)
{
HRESULT hr = S_OK;
m_pDevice = pDevice;
BOOL fVisible = FALSE;
MilPointAndSizeL rcClip;
Assert(pars.pContextState);
FLOAT flAlphaScale = pars.pBrushRealizer->GetOpacityFromRealizedBrush();
m_pDevice->GetClipRect(&rcClip);
{
// Do a rough check for glyph run visibility.
// We need it, at least, to protect against
// overflows in rendering routines.
CRectF<CoordinateSpace::Device> rcClipF(
static_cast<float>(rcClip.X),
static_cast<float>(rcClip.Y),
static_cast<float>(rcClip.Width),
static_cast<float>(rcClip.Height),
XYWH_Parameters
);
if (!pars.rcBounds.Device().DoesIntersect(rcClipF))
goto Cleanup;
}
fVisible = Init(
m_pDevice->GetGlyphBank()->GetGlyphPainterMemory(),
pars.pGlyphRun,
pars.pContextState
);
if (!fVisible) goto Cleanup;
IFC(ValidateGlyphRun());
IFC(m_pGlyphRun->ValidateGeometry(this));
if (m_pGlyphRun->IsEmpty())
{
// This is legal, for example if the glyph run is realized at such a small scale that
// there is nothing to draw.
goto Cleanup;
}
bool fClearType = (m_recommendedBlendMode == ClearType) && fTargetSupportsClearType;
// Rendering preparation:
// Choose rendering branch (set m_pfnDrawRectangle)
// Set rendering state
IFC(InspectBrush(pars, fmtTargetSurface));
if (m_data.m_pHwColorSource == NULL)
{ // solid brush
// if the brush has zero alpha then skip drawing
if (MIL_COLOR_GET_ALPHA(m_data.color) == 0)
goto Cleanup;
// We should not get here with alpha effect.
// It should be combined with solid brush already.
Assert(flAlphaScale == 1);
if (fClearType)
{
m_pfnDrawRectangle = m_pDevice->CanDrawTextUsingPS20()
? sc_pfnDrawRectangle_CVertM1_CT_1Pass
: sc_pfnDrawRectangle_CVertM3_1Pass;
IFC(m_pDevice->SetRenderState_Text_ClearType_SolidBrush(m_data.color, pars.pGlyphRun->GetGammaIndex()));
}
else
{
m_pfnDrawRectangle = sc_pfnDrawRectangle_CVertM1_1Pass;
IFC(m_pDevice->SetRenderState_Text_GreyScale_SolidBrush(m_data.color, pars.pGlyphRun->GetGammaIndex()));
}
}
else
{ // textured brush
if (fClearType)
{
m_pfnDrawRectangle = sc_pfnDrawRectangle_CVertBM_3Pass;
IFC(m_pDevice->SetRenderState_Text_ClearType_TextureBrush(pars.pGlyphRun->GetGammaIndex(), flAlphaScale));
}
else
{
m_pfnDrawRectangle = sc_pfnDrawRectangle_CVertBM_1Pass;
IFC(m_pDevice->SetRenderState_Text_GreyScale_TextureBrush(pars.pGlyphRun->GetGammaIndex(), flAlphaScale));
}
}
//
// do rendering
//
for (m_pSubGlyph = m_pGlyphRun->GetFirstSubGlyph(); m_pSubGlyph; m_pSubGlyph = m_pSubGlyph->GetNext())
{
RECT const &r = m_pSubGlyph->GetFilteredRect();
m_xMin = (float(r.left ) + float(DX9_SUBGLYPH_OVERLAP_X) * .5f) * (1.f / 3);
m_xMax = (float(r.right ) - float(DX9_SUBGLYPH_OVERLAP_X) * .5f) * (1.f / 3);
m_yMin = float(r.top ) + float(DX9_SUBGLYPH_OVERLAP_Y) * .5f;
m_yMax = float(r.bottom) - float(DX9_SUBGLYPH_OVERLAP_Y) * .5f;
if (m_pGlyphRun->IsBig() && IsSubglyphClippedOut(&rcClip)) continue;
if (!m_pSubGlyph->IsAlphaMapValid())
{
#if D3DLOG_ENABLED
D3DLOG_INC(subglyphsRegenerated);
D3DLOG_ADD(pixelsRegenerated, (r.right - r.left) * (r.bottom - r.top));
if (m_pGlyphRun->IsPersistent())
{
D3DLOG_INC(persSubglyphsRegenerated);
}
if (m_pSubGlyph->WasEvicted())
{
D3DLOG_INC(subglyphsEvicted);
}
#endif //D3DLOG_ENABLED
IFC(m_pSubGlyph->ValidateAlphaMap(this));
}
else
{
D3DLOG_INC(subglyphsReused);
D3DLOG_ADD(pixelsReused, (r.right - r.left) * (r.bottom - r.top));
}
m_data.pxfGlyphWR = &m_xfGlyphWR;
float widTextureRc = m_pSubGlyph->GetWidTextureRc();
float heiTextureRc = m_pSubGlyph->GetHeiTextureRc();
SIZE const& offset = m_pSubGlyph->GetOffset();
// scaling transform from work space to glyph texture space
m_data.kxWT = widTextureRc * 3;
m_data.kyWT = heiTextureRc;
m_data.dxWT = widTextureRc * (float(offset.cx));
m_data.dyWT = heiTextureRc * (float(offset.cy));
m_data.pMaskTexture = m_pSubGlyph->GetTank()->GetTextureNoAddref();
m_pSubGlyph->GetTank()->AddUsefulArea((r.right - r.left) * (r.bottom - r.top));
float
blueOffset = pars.pGlyphRun->BlueSubpixelOffset(),
dxW = blueOffset * m_xfGlyphRW.m_00,
dyW = blueOffset * m_xfGlyphRW.m_01;
m_data.blueOffset = blueOffset;
m_data.ds = dxW * m_data.kxWT;
m_data.dt = dyW * m_data.kyWT;
MIL_THR((this->*m_pfnDrawRectangle)());
if (!m_pGlyphRun->IsPersistent())
{
m_pSubGlyph->FreeAlphaMap();
}
if (FAILED(hr)) goto Cleanup;
}
Cleanup:
RRETURN(hr);
}
//+-----------------------------------------------------------------------------
//
// Member:
// CD3DGlyphRunPainter::IsSubglyphClippedOut
//
// Synopsis:
// Do a fast "pre-clip" check.
//
// Return values:
// true: Current subglyph is definitely outside the given clipping rectangle
// false: Current subglyph might be visible
//
//------------------------------------------------------------------------------
MIL_FORCEINLINE bool
CD3DGlyphRunPainter::IsSubglyphClippedOut(MilPointAndSizeL const* prcClip) const
{
float
x0 = m_xMin*m_xfGlyphWR.m_00 + m_yMin*m_xfGlyphWR.m_10 + m_xfGlyphWR.m_20,
y0 = m_xMin*m_xfGlyphWR.m_01 + m_yMin*m_xfGlyphWR.m_11 + m_xfGlyphWR.m_21,
x1 = m_xMax*m_xfGlyphWR.m_00 + m_yMin*m_xfGlyphWR.m_10 + m_xfGlyphWR.m_20,
y1 = m_xMax*m_xfGlyphWR.m_01 + m_yMin*m_xfGlyphWR.m_11 + m_xfGlyphWR.m_21,
x2 = m_xMax*m_xfGlyphWR.m_00 + m_yMax*m_xfGlyphWR.m_10 + m_xfGlyphWR.m_20,
y2 = m_xMax*m_xfGlyphWR.m_01 + m_yMax*m_xfGlyphWR.m_11 + m_xfGlyphWR.m_21,
x3 = m_xMin*m_xfGlyphWR.m_00 + m_yMax*m_xfGlyphWR.m_10 + m_xfGlyphWR.m_20,
y3 = m_xMin*m_xfGlyphWR.m_01 + m_yMax*m_xfGlyphWR.m_11 + m_xfGlyphWR.m_21,
lef = float(prcClip->X ),
rig = float(prcClip->X + prcClip->Width ),
top = float(prcClip->Y ),
bot = float(prcClip->Y + prcClip->Height);
return
x0 > rig && x1 > rig && x2 > rig && x3 > rig ||
x0 < lef && x1 < lef && x2 < lef && x3 < lef ||
y0 > bot && y1 > bot && y2 > bot && y3 > bot ||
y0 < top && y1 < top && y2 < top && y3 < top;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CD3DGlyphRunPainter::ValidateGlyphRun
//
// Synopsis:
// Create device specific CD3DGlyphRun if not yet created
//
//------------------------------------------------------------------------------
HRESULT
CD3DGlyphRunPainter::ValidateGlyphRun()
{
HRESULT hr = S_OK;
IMILResourceCache::ValidIndex uCacheIndex;
IFC(m_pDevice->GetCacheIndex(&uCacheIndex));
IFC(GetRealizationNoRef()->GetD3DGlyphRun(uCacheIndex, &m_pGlyphRun));
if (!m_pGlyphRun)
{
m_pGlyphRun = new CD3DGlyphRun();
IFCOOM(m_pGlyphRun);
GetRealizationNoRef()->SetD3DGlyphRun(uCacheIndex, m_pGlyphRun);
}
else
{
m_pGlyphRun->SetPersistent();
}
Cleanup:
return hr;
}
//+-----------------------------------------------------------------------------
//
// Member:
// CD3DGlyphRunPainter::InspectBrush
//
// Synopsis:
// Inspect brush type and debug settings. Prepare either solid color value
// in m_data.color or pointer to CHwTexturedColorSource in
// m_data.m_pHwColorSource.
//
//------------------------------------------------------------------------------
MIL_FORCEINLINE HRESULT
CD3DGlyphRunPainter::InspectBrush(
__in_ecount(1) DrawGlyphsParameters &pars,
MilPixelFormat::Enum fmtTargetSurface
)
{
HRESULT hr = S_OK;
BOOL fUseBorder = FALSE;
CContextState const *pContextState = pars.pContextState;
CMILBrush* pMILBrush = pars.pBrushRealizer->GetRealizedBrushNoRef(false /* fConvertNULLToTransparent */);
Assert(pMILBrush);
switch (pMILBrush->GetType())
{
case BrushSolid:
{
const CMILBrushSolid* pMILBrushSolid = DYNCAST(CMILBrushSolid, pMILBrush);
Assert(pMILBrushSolid);
m_data.color = Convert_MilColorF_scRGB_To_MilColorB_sRGB(&pMILBrushSolid->m_SolidColor);
break;
}
case BrushBitmap:
{
const CMILBrushBitmap *pBitmapBrush = DYNCAST(const CMILBrushBitmap, pMILBrush);
Assert(pBitmapBrush);
fUseBorder = pBitmapBrush->HasSourceClip();
if (fUseBorder)
{
Assert(m_pDevice->SupportsBorderColor());
Assert(pBitmapBrush->SourceClipIsEntireSource());
}
// fall thru to default
}
__fallthrough;
default:
{
//
// For 2D rendering, local rendering and world sampling spaces are identical
//
const CMatrix<CoordinateSpace::BaseSampling,CoordinateSpace::Device> &
matBaseSamplingToDevice =
ReinterpretLocalRenderingAsBaseSampling(pContextState->WorldToDevice);
CHwBrushContext hwBrushContext(
pContextState,
matBaseSamplingToDevice, // matWorld2DToSampleSpace -- In 2D the sample space is the same as the Device space.
fmtTargetSurface,
TRUE // fCanFallback
);
hwBrushContext.SetDeviceSamplingBounds(pars.rcBounds.Device());
Assert(m_data.m_pHwColorSource == NULL);
IFC(m_pDevice->DeriveHWTexturedColorSource(
pMILBrush,
hwBrushContext,
&m_data.m_pHwColorSource
));
IFC(m_data.m_pHwColorSource->Realize());
if (fUseBorder)
{
m_data.m_pHwColorSource->ForceBorder();
}
m_data.xfBrushRT = m_data.m_pHwColorSource->GetDevicePointToTextureUV();
}
}
Cleanup:
RRETURN(hr);
}
//==============================================================================
HRESULT
CD3DGlyphRunPainter::EnsureAlphaMap()
{
if (!HasAlphaArray())
{
// If we don't have an alpha map array, create one from the realization.
Assert(m_pGlyphRun);
MakeAlphaMap(m_pGlyphRun);
}
RRETURN(S_OK);
}
//+-----------------------------------------------------------------------------
//
// Class:
// CRenderFan1Pass
//
// Synopsis:
// Draws the accumulated vertex buffer as a fan primitive
//
//------------------------------------------------------------------------------
class CRenderFan1Pass
{
public:
template<class TVertexBuffer>
static HRESULT Draw(
CD3DDeviceLevel1* pDev,
TVertexBuffer *pBuffer,
char* pvb,
int stride,
DWORD color,
float blueOffset
)
{
return pDev->EndPrimitiveFan(pBuffer);
}
};
//+-----------------------------------------------------------------------------
//
// Class:
// CRenderFan3Pass
//
// Synopsis:
// Draw the accumulated vertex buffer as a fan primitive producing clear
// type text rendering, with pixel shader that makes gamma correction.
//
// The final image is generated in three passes, one per each color
// component.
//
//------------------------------------------------------------------------------
class CRenderFan3Pass
{
public:
template<class TVertexBuffer>
static HRESULT Draw(
CD3DDeviceLevel1* pDev,
TVertexBuffer *pBuffer,
char* pvb,
int stride,
DWORD color,
float blueOffset
)
{
HRESULT hr = S_OK;
// Draw the green
IFC( pDev->SetColorChannelGreen() );
IFC( pDev->EndPrimitiveFan(pBuffer) );
// Draw the red:
// shift all the x-coordinates right by 1/3 pixel
// (LCD display will shift them back as far as the red stripes
// lay in left part of the pixel consisting of R,G and B stripes)
// For BGR display use oppose shift direction.
// This choice is controlled by DisplaySettings::BlueSubpixelOffset
// that is 1/3 for default RGB display and -1/3 for BGR.
{
float offset = blueOffset;
*(float*)(pvb + stride*0) += offset;
*(float*)(pvb + stride*1) += offset;
*(float*)(pvb + stride*2) += offset;
*(float*)(pvb + stride*3) += offset;
}
IFC( pDev->SetColorChannelRed() );
IFC( pDev->EndPrimitiveFan(pBuffer) );
// Draw the blue
// Do the shift in opposite direction
{
float offset = 2*blueOffset;
*(float*)(pvb + stride*0) -= offset;
*(float*)(pvb + stride*1) -= offset;
*(float*)(pvb + stride*2) -= offset;
*(float*)(pvb + stride*3) -= offset;
}
IFC( pDev->SetColorChannelBlue() );
IFC( pDev->EndPrimitiveFan(pBuffer) );
Cleanup:
// restore the default settings
{
MIL_THR_SECONDARY(pDev->RestoreColorChannels());
}
RRETURN(hr);
}
};
template<class TVertex, class TRender> HRESULT
CD3DGlyphRunPainter::TDrawRectangle()
{
HRESULT hr = S_OK;
TVertex* vertices = NULL;
TVertex::buffer *pBuffer;
IFC(m_pDevice->StartPrimitive(&pBuffer));
IFC(pBuffer->GetNewVertices(
4,
(TVertex::base **)&vertices
));
vertices[0].Set(m_xMin, m_yMin, &m_data);
vertices[1].Set(m_xMax, m_yMin, &m_data);
vertices[2].Set(m_xMax, m_yMax, &m_data);
vertices[3].Set(m_xMin, m_yMax, &m_data);
IFC( TVertex::SetTextures(m_pDevice, &m_data) );
IFC( TRender::Draw(
m_pDevice,
pBuffer,
(char*)vertices,
sizeof(TVertex),
m_data.color,
m_data.blueOffset
) );
Cleanup:
return hr;
}
//==============================================================================
// Vertex classes
// 1 mask
class CVertM1 : public CD3DVertexXYZDUV2
{
public:
typedef CD3DVertexXYZDUV2 base;
typedef CD3DVertexBufferDUV2 buffer;
MIL_FORCEINLINE void
Set(float xW, float yW, const VertexFillData* pData)
{
MILMatrix3x2 const &mWR = *pData->pxfGlyphWR;
float xR = xW*mWR.m_00 + yW*mWR.m_10 + mWR.m_20,
yR = xW*mWR.m_01 + yW*mWR.m_11 + mWR.m_21;
float u0 = xW*pData->kxWT + pData->dxWT;
float v0 = yW*pData->kyWT + pData->dyWT;
SetXYUV0(xR, yR, u0, v0);
}
static MIL_FORCEINLINE HRESULT
SetTextures(CD3DDeviceLevel1* pDevice, const VertexFillData* pData)
{
HRESULT hr = S_OK;
IFC( pDevice->SetD3DTexture(0, pData->pMaskTexture));
IFC( pDevice->DisableTextureTransform(0));
Cleanup:
return hr;
}
};
class CVertM1_CT : public CVertM1
{
public:
static MIL_FORCEINLINE HRESULT
SetTextures(CD3DDeviceLevel1* pDevice, const VertexFillData* pData)
{
HRESULT hr = S_OK;
IFC( pDevice->SetClearTypeOffsets(pData->ds, pData->dt) );
IFC( pDevice->SetD3DTexture(0, pData->pMaskTexture) );
IFC( pDevice->DisableTextureTransform(0) );
Cleanup:
return hr;
}
};
// brush + mask
class CVertBM : public CD3DVertexXYZDUV2
{
public:
typedef CD3DVertexXYZDUV2 base;
typedef CD3DVertexBufferDUV2 buffer;
MIL_FORCEINLINE void
Set(float xW, float yW, const VertexFillData* pData)
{
MILMatrix3x2 const &mWR = *pData->pxfGlyphWR;
float xR = xW*mWR.m_00 + yW*mWR.m_10 + mWR.m_20,
yR = xW*mWR.m_01 + yW*mWR.m_11 + mWR.m_21;
MILMatrix3x2 const &mRT = pData->xfBrushRT;
SetXYUV1(xR, // X
yR, // Y
xR*mRT.m_00 + yR*mRT.m_10 + mRT.m_20, // U0
xR*mRT.m_01 + yR*mRT.m_11 + mRT.m_21, // V0
xW*pData->kxWT + pData->dxWT, // U1
yW*pData->kyWT + pData->dyWT // V1
);
}
static MIL_FORCEINLINE HRESULT
SetTextures(CD3DDeviceLevel1* pDevice, const VertexFillData* pData)
{
HRESULT hr = S_OK;
//
// ResetForPipelineReuse must be called any time
// SendDeviceStates is called outside the normal pipeline.
//
pData->m_pHwColorSource->ResetForPipelineReuse();
IFC( pData->m_pHwColorSource->SendDeviceStates(0, 0) );
IFC( pDevice->SetD3DTexture(1, pData->pMaskTexture));
IFC( pDevice->DisableTextureTransform(1));
Cleanup:
return hr;
}
};
// 3 masks
class CVertM3 : public CD3DVertexXYZDUV6
{
public:
typedef CD3DVertexXYZDUV6 base;
typedef CD3DVertexBufferDUV6 buffer;
MIL_FORCEINLINE void
Set(float xW, float yW, const VertexFillData* pData)
{
MILMatrix3x2 const &mWR = *pData->pxfGlyphWR;
float xR = xW*mWR.m_00 + yW*mWR.m_10 + mWR.m_20,
yR = xW*mWR.m_01 + yW*mWR.m_11 + mWR.m_21;
float u1 = xW*pData->kxWT + pData->dxWT; // green channel
float v1 = yW*pData->kyWT + pData->dyWT;
float u0 = u1 - pData->ds; // red channel
float v0 = v1 - pData->dt;
float u2 = u1 + pData->ds; // blue channel
float v2 = v1 + pData->dt;
SetXYUV2( xR, // X
yR, // Y
u0, v0, // U0, V0
u1, v1, // U1, V1
u2, v2 // U2, V2
);
}
static MIL_FORCEINLINE HRESULT
SetTextures(CD3DDeviceLevel1* pDevice, const VertexFillData* pData)
{
HRESULT hr = S_OK;
IFC( pDevice->SetD3DTexture(0, pData->pMaskTexture) );
IFC( pDevice->DisableTextureTransform(0) );
IFC( pDevice->SetD3DTexture(1, pData->pMaskTexture) );
IFC( pDevice->DisableTextureTransform(1) );
IFC( pDevice->SetD3DTexture(2, pData->pMaskTexture) );
IFC( pDevice->DisableTextureTransform(2) );
Cleanup:
return hr;
}
};
//
// [pfx_parse] - workaround for PREfix parse problems
//
#ifndef _PREFIX_
HRESULT (CD3DGlyphRunPainter::*const CD3DGlyphRunPainter::sc_pfnDrawRectangle_CVertM1_1Pass)() = &CD3DGlyphRunPainter::TDrawRectangle<CVertM1, CRenderFan1Pass>;
HRESULT (CD3DGlyphRunPainter::*const CD3DGlyphRunPainter::sc_pfnDrawRectangle_CVertBM_1Pass)() = &CD3DGlyphRunPainter::TDrawRectangle<CVertBM, CRenderFan1Pass>;
HRESULT (CD3DGlyphRunPainter::*const CD3DGlyphRunPainter::sc_pfnDrawRectangle_CVertM3_1Pass)() = &CD3DGlyphRunPainter::TDrawRectangle<CVertM3, CRenderFan1Pass>;
HRESULT (CD3DGlyphRunPainter::*const CD3DGlyphRunPainter::sc_pfnDrawRectangle_CVertBM_3Pass)() = &CD3DGlyphRunPainter::TDrawRectangle<CVertBM, CRenderFan3Pass>;
HRESULT (CD3DGlyphRunPainter::*const CD3DGlyphRunPainter::sc_pfnDrawRectangle_CVertM1_CT_1Pass)() = &CD3DGlyphRunPainter::TDrawRectangle<CVertM1_CT, CRenderFan1Pass>;
#endif // !_PREFIX_
| 30.316474 | 166 | 0.57324 | [
"transform",
"solid"
] |
9cbd637704ed11123d0df1f8b7c652b8e65e0aae | 45,642 | cc | C++ | chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/chromeos/extensions/file_manager/private_api_drive.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/extensions/file_manager/private_api_drive.h"
#include <map>
#include <memory>
#include <set>
#include <utility>
#include "base/command_line.h"
#include "base/memory/ptr_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/drive/drive_integration_service.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/browser/chromeos/extensions/file_manager/private_api_util.h"
#include "chrome/browser/chromeos/file_manager/file_tasks.h"
#include "chrome/browser/chromeos/file_manager/fileapi_util.h"
#include "chrome/browser/chromeos/file_manager/url_util.h"
#include "chrome/browser/chromeos/file_system_provider/mount_path_util.h"
#include "chrome/browser/chromeos/file_system_provider/provided_file_system_interface.h"
#include "chrome/browser/chromeos/fileapi/external_file_url_util.h"
#include "chrome/browser/chromeos/fileapi/file_system_backend.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/extensions/api/file_manager_private_internal.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/network/network_handler.h"
#include "chromeos/network/network_state_handler.h"
#include "components/drive/drive_app_registry.h"
#include "components/drive/event_logger.h"
#include "components/signin/core/browser/profile_oauth2_token_service.h"
#include "components/signin/core/browser/signin_manager.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/drive/auth_service.h"
#include "google_apis/drive/drive_api_url_generator.h"
#include "google_apis/drive/drive_switches.h"
#include "storage/common/fileapi/file_system_info.h"
#include "storage/common/fileapi/file_system_util.h"
#include "url/gurl.h"
using content::BrowserThread;
using chromeos::file_system_provider::EntryMetadata;
using chromeos::file_system_provider::ProvidedFileSystemInterface;
using chromeos::file_system_provider::util::FileSystemURLParser;
using extensions::api::file_manager_private::EntryProperties;
using extensions::api::file_manager_private::EntryPropertyName;
using file_manager::util::EntryDefinition;
using file_manager::util::EntryDefinitionCallback;
using file_manager::util::EntryDefinitionList;
using file_manager::util::EntryDefinitionListCallback;
using file_manager::util::FileDefinition;
using file_manager::util::FileDefinitionList;
using google_apis::DriveApiUrlGenerator;
namespace extensions {
namespace {
// List of connection types of drive.
// Keep this in sync with the DriveConnectionType in common/js/util.js.
const char kDriveConnectionTypeOffline[] = "offline";
const char kDriveConnectionTypeMetered[] = "metered";
const char kDriveConnectionTypeOnline[] = "online";
// List of reasons of kDriveConnectionType*.
// Keep this in sync with the DriveConnectionReason in common/js/util.js.
const char kDriveConnectionReasonNotReady[] = "not_ready";
const char kDriveConnectionReasonNoNetwork[] = "no_network";
const char kDriveConnectionReasonNoService[] = "no_service";
// Maximum dimension of thumbnail in file manager. File manager shows 180x180
// thumbnail. Given that we support hdpi devices, maximum dimension is 360.
const int kFileManagerMaximumThumbnailDimension = 360;
// Copies properties from |entry_proto| to |properties|. |shared_with_me| is
// given from the running profile.
void FillEntryPropertiesValueForDrive(const drive::ResourceEntry& entry_proto,
bool shared_with_me,
EntryProperties* properties) {
properties->shared_with_me.reset(new bool(shared_with_me));
properties->shared.reset(new bool(entry_proto.shared()));
properties->starred.reset(new bool(entry_proto.starred()));
const drive::PlatformFileInfoProto& file_info = entry_proto.file_info();
properties->size.reset(new double(file_info.size()));
properties->modification_time.reset(new double(
base::Time::FromInternalValue(file_info.last_modified()).ToJsTime()));
properties->modification_by_me_time.reset(new double(
base::Time::FromInternalValue(entry_proto.last_modified_by_me())
.ToJsTime()));
if (entry_proto.has_alternate_url()) {
properties->alternate_url.reset(
new std::string(entry_proto.alternate_url()));
// Set |share_url| to a modified version of |alternate_url| that opens the
// sharing dialog for files and folders (add ?userstoinvite="" to the URL).
// TODO(sashab): Add an endpoint to the Drive API that generates this URL,
// instead of manually modifying it here.
GURL share_url = GURL(entry_proto.alternate_url());
GURL::Replacements replacements;
std::string new_query =
(share_url.has_query() ? share_url.query() + "&" : "") +
"userstoinvite=%22%22";
replacements.SetQueryStr(new_query);
properties->share_url.reset(
new std::string(share_url.ReplaceComponents(replacements).spec()));
}
if (!entry_proto.has_file_specific_info())
return;
const drive::FileSpecificInfo& file_specific_info =
entry_proto.file_specific_info();
if (!entry_proto.resource_id().empty()) {
DriveApiUrlGenerator url_generator(
(GURL(google_apis::DriveApiUrlGenerator::kBaseUrlForProduction)),
(GURL(google_apis::DriveApiUrlGenerator::
kBaseThumbnailUrlForProduction)),
google_apis::GetTeamDrivesIntegrationSwitch());
properties->thumbnail_url.reset(new std::string(
url_generator.GetThumbnailUrl(entry_proto.resource_id(),
500 /* width */, 500 /* height */,
false /* not cropped */).spec()));
properties->cropped_thumbnail_url.reset(new std::string(
url_generator.GetThumbnailUrl(
entry_proto.resource_id(),
kFileManagerMaximumThumbnailDimension /* width */,
kFileManagerMaximumThumbnailDimension /* height */,
true /* cropped */).spec()));
}
if (file_specific_info.has_image_width()) {
properties->image_width.reset(
new int(file_specific_info.image_width()));
}
if (file_specific_info.has_image_height()) {
properties->image_height.reset(
new int(file_specific_info.image_height()));
}
if (file_specific_info.has_image_rotation()) {
properties->image_rotation.reset(
new int(file_specific_info.image_rotation()));
}
properties->hosted.reset(new bool(file_specific_info.is_hosted_document()));
properties->content_mime_type.reset(
new std::string(file_specific_info.content_mime_type()));
properties->pinned.reset(
new bool(file_specific_info.cache_state().is_pinned()));
properties->dirty.reset(
new bool(file_specific_info.cache_state().is_dirty()));
properties->present.reset(
new bool(file_specific_info.cache_state().is_present()));
if (file_specific_info.cache_state().is_present()) {
properties->available_offline.reset(new bool(true));
} else if (file_specific_info.is_hosted_document() &&
file_specific_info.has_document_extension()) {
const std::string file_extension = file_specific_info.document_extension();
// What's available offline? See the 'Web' column at:
// https://support.google.com/drive/answer/1628467
properties->available_offline.reset(
new bool(file_extension == ".gdoc" || file_extension == ".gdraw" ||
file_extension == ".gsheet" || file_extension == ".gslides"));
} else {
properties->available_offline.reset(new bool(false));
}
properties->available_when_metered.reset(
new bool(file_specific_info.cache_state().is_present() ||
file_specific_info.is_hosted_document()));
}
// Creates entry definition list for (metadata) search result info list.
template <class T>
void ConvertSearchResultInfoListToEntryDefinitionList(
Profile* profile,
const std::string& extension_id,
const std::vector<T>& search_result_info_list,
const EntryDefinitionListCallback& callback) {
FileDefinitionList file_definition_list;
for (size_t i = 0; i < search_result_info_list.size(); ++i) {
FileDefinition file_definition;
file_definition.virtual_path =
file_manager::util::ConvertDrivePathToRelativeFileSystemPath(
profile, extension_id, search_result_info_list.at(i).path);
file_definition.is_directory = search_result_info_list.at(i).is_directory;
file_definition_list.push_back(file_definition);
}
file_manager::util::ConvertFileDefinitionListToEntryDefinitionList(
profile,
extension_id,
file_definition_list, // Safe, since copied internally.
callback);
}
class SingleEntryPropertiesGetterForDrive {
public:
typedef base::Callback<void(std::unique_ptr<EntryProperties> properties,
base::File::Error error)>
ResultCallback;
// Creates an instance and starts the process.
static void Start(const base::FilePath local_path,
const std::set<EntryPropertyName>& names,
Profile* const profile,
const ResultCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
SingleEntryPropertiesGetterForDrive* instance =
new SingleEntryPropertiesGetterForDrive(local_path, names, profile,
callback);
instance->StartProcess();
// The instance will be destroyed by itself.
}
virtual ~SingleEntryPropertiesGetterForDrive() {}
private:
SingleEntryPropertiesGetterForDrive(
const base::FilePath local_path,
const std::set<EntryPropertyName>& /* names */,
Profile* const profile,
const ResultCallback& callback)
: callback_(callback),
local_path_(local_path),
running_profile_(profile),
properties_(new EntryProperties),
file_owner_profile_(NULL),
weak_ptr_factory_(this) {
DCHECK(!callback_.is_null());
DCHECK(profile);
}
void StartProcess() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
file_path_ = drive::util::ExtractDrivePath(local_path_);
file_owner_profile_ = drive::util::ExtractProfileFromPath(local_path_);
if (!file_owner_profile_ ||
!g_browser_process->profile_manager()->IsValidProfile(
file_owner_profile_)) {
CompleteGetEntryProperties(drive::FILE_ERROR_FAILED);
return;
}
// Start getting the file info.
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(file_owner_profile_);
if (!file_system) {
// |file_system| is NULL if Drive is disabled or not mounted.
CompleteGetEntryProperties(drive::FILE_ERROR_FAILED);
return;
}
file_system->GetResourceEntry(
file_path_,
base::Bind(&SingleEntryPropertiesGetterForDrive::OnGetFileInfo,
weak_ptr_factory_.GetWeakPtr()));
}
void OnGetFileInfo(drive::FileError error,
std::unique_ptr<drive::ResourceEntry> entry) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != drive::FILE_ERROR_OK) {
CompleteGetEntryProperties(error);
return;
}
DCHECK(entry);
owner_resource_entry_.swap(entry);
if (running_profile_->IsSameProfile(file_owner_profile_)) {
StartParseFileInfo(owner_resource_entry_->shared_with_me());
return;
}
// If the running profile does not own the file, obtain the shared_with_me
// flag from the running profile's value.
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(running_profile_);
if (!file_system) {
CompleteGetEntryProperties(drive::FILE_ERROR_FAILED);
return;
}
file_system->GetPathFromResourceId(
owner_resource_entry_->resource_id(),
base::Bind(&SingleEntryPropertiesGetterForDrive::OnGetRunningPath,
weak_ptr_factory_.GetWeakPtr()));
}
void OnGetRunningPath(drive::FileError error,
const base::FilePath& file_path) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != drive::FILE_ERROR_OK) {
// The running profile does not know the file.
StartParseFileInfo(false);
return;
}
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(running_profile_);
if (!file_system) {
// The drive is disable for the running profile.
StartParseFileInfo(false);
return;
}
file_system->GetResourceEntry(
file_path,
base::Bind(&SingleEntryPropertiesGetterForDrive::OnGetShareInfo,
weak_ptr_factory_.GetWeakPtr()));
}
void OnGetShareInfo(drive::FileError error,
std::unique_ptr<drive::ResourceEntry> entry) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != drive::FILE_ERROR_OK) {
CompleteGetEntryProperties(error);
return;
}
DCHECK(entry.get());
StartParseFileInfo(entry->shared_with_me());
}
void StartParseFileInfo(bool shared_with_me) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
FillEntryPropertiesValueForDrive(
*owner_resource_entry_, shared_with_me, properties_.get());
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(file_owner_profile_);
drive::DriveAppRegistry* const app_registry =
drive::util::GetDriveAppRegistryByProfile(file_owner_profile_);
if (!file_system || !app_registry) {
// |file_system| or |app_registry| is NULL if Drive is disabled.
CompleteGetEntryProperties(drive::FILE_ERROR_FAILED);
return;
}
// The properties meaningful for directories are already filled in
// FillEntryPropertiesValueForDrive().
if (!owner_resource_entry_->has_file_specific_info()) {
CompleteGetEntryProperties(drive::FILE_ERROR_OK);
return;
}
const drive::FileSpecificInfo& file_specific_info =
owner_resource_entry_->file_specific_info();
// Get drive WebApps that can accept this file. We just need to extract the
// doc icon for the drive app, which is set as default.
std::vector<drive::DriveAppInfo> drive_apps;
app_registry->GetAppsForFile(file_path_.Extension(),
file_specific_info.content_mime_type(),
&drive_apps);
if (!drive_apps.empty()) {
std::string default_task_id =
file_manager::file_tasks::GetDefaultTaskIdFromPrefs(
*file_owner_profile_->GetPrefs(),
file_specific_info.content_mime_type(),
file_path_.Extension());
file_manager::file_tasks::TaskDescriptor default_task;
file_manager::file_tasks::ParseTaskID(default_task_id, &default_task);
DCHECK(default_task_id.empty() || !default_task.app_id.empty());
for (size_t i = 0; i < drive_apps.size(); ++i) {
const drive::DriveAppInfo& app_info = drive_apps[i];
if (default_task.app_id == app_info.app_id) {
// The drive app is set as default. The Files app should use the doc
// icon.
const GURL doc_icon = drive::util::FindPreferredIcon(
app_info.document_icons, drive::util::kPreferredIconSize);
properties_->custom_icon_url.reset(new std::string(doc_icon.spec()));
}
}
}
CompleteGetEntryProperties(drive::FILE_ERROR_OK);
}
void CompleteGetEntryProperties(drive::FileError error) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!callback_.is_null());
callback_.Run(std::move(properties_),
drive::FileErrorToBaseFileError(error));
BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, this);
}
// Given parameters.
const ResultCallback callback_;
const base::FilePath local_path_;
Profile* const running_profile_;
// Values used in the process.
std::unique_ptr<EntryProperties> properties_;
Profile* file_owner_profile_;
base::FilePath file_path_;
std::unique_ptr<drive::ResourceEntry> owner_resource_entry_;
base::WeakPtrFactory<SingleEntryPropertiesGetterForDrive> weak_ptr_factory_;
}; // class SingleEntryPropertiesGetterForDrive
class SingleEntryPropertiesGetterForFileSystemProvider {
public:
typedef base::Callback<void(std::unique_ptr<EntryProperties> properties,
base::File::Error error)>
ResultCallback;
// Creates an instance and starts the process.
static void Start(const storage::FileSystemURL file_system_url,
const std::set<EntryPropertyName>& names,
const ResultCallback& callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
SingleEntryPropertiesGetterForFileSystemProvider* instance =
new SingleEntryPropertiesGetterForFileSystemProvider(file_system_url,
names, callback);
instance->StartProcess();
// The instance will be destroyed by itself.
}
virtual ~SingleEntryPropertiesGetterForFileSystemProvider() {}
private:
SingleEntryPropertiesGetterForFileSystemProvider(
const storage::FileSystemURL& file_system_url,
const std::set<EntryPropertyName>& names,
const ResultCallback& callback)
: callback_(callback),
file_system_url_(file_system_url),
names_(names),
properties_(new EntryProperties),
weak_ptr_factory_(this) {
DCHECK(!callback_.is_null());
}
void StartProcess() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
FileSystemURLParser parser(file_system_url_);
if (!parser.Parse()) {
CompleteGetEntryProperties(base::File::FILE_ERROR_NOT_FOUND);
return;
}
ProvidedFileSystemInterface::MetadataFieldMask field_mask =
ProvidedFileSystemInterface::METADATA_FIELD_NONE;
if (names_.find(api::file_manager_private::ENTRY_PROPERTY_NAME_SIZE) !=
names_.end()) {
field_mask |= ProvidedFileSystemInterface::METADATA_FIELD_SIZE;
}
if (names_.find(
api::file_manager_private::ENTRY_PROPERTY_NAME_MODIFICATIONTIME) !=
names_.end()) {
field_mask |=
ProvidedFileSystemInterface::METADATA_FIELD_MODIFICATION_TIME;
}
if (names_.find(
api::file_manager_private::ENTRY_PROPERTY_NAME_CONTENTMIMETYPE) !=
names_.end()) {
field_mask |= ProvidedFileSystemInterface::METADATA_FIELD_MIME_TYPE;
}
if (names_.find(
api::file_manager_private::ENTRY_PROPERTY_NAME_THUMBNAILURL) !=
names_.end()) {
field_mask |= ProvidedFileSystemInterface::METADATA_FIELD_THUMBNAIL;
}
parser.file_system()->GetMetadata(
parser.file_path(), field_mask,
base::Bind(&SingleEntryPropertiesGetterForFileSystemProvider::
OnGetMetadataCompleted,
weak_ptr_factory_.GetWeakPtr()));
}
void OnGetMetadataCompleted(std::unique_ptr<EntryMetadata> metadata,
base::File::Error result) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (result != base::File::FILE_OK) {
CompleteGetEntryProperties(result);
return;
}
if (names_.find(api::file_manager_private::ENTRY_PROPERTY_NAME_SIZE) !=
names_.end()) {
properties_->size.reset(new double(*metadata->size.get()));
}
if (names_.find(
api::file_manager_private::ENTRY_PROPERTY_NAME_MODIFICATIONTIME) !=
names_.end()) {
properties_->modification_time.reset(
new double(metadata->modification_time->ToJsTime()));
}
if (names_.find(
api::file_manager_private::ENTRY_PROPERTY_NAME_CONTENTMIMETYPE) !=
names_.end() &&
metadata->mime_type.get()) {
properties_->content_mime_type.reset(
new std::string(*metadata->mime_type));
}
if (names_.find(
api::file_manager_private::ENTRY_PROPERTY_NAME_THUMBNAILURL) !=
names_.end() &&
metadata->thumbnail.get()) {
properties_->thumbnail_url.reset(new std::string(*metadata->thumbnail));
}
CompleteGetEntryProperties(base::File::FILE_OK);
}
void CompleteGetEntryProperties(base::File::Error result) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!callback_.is_null());
callback_.Run(std::move(properties_), result);
BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, this);
}
// Given parameters.
const ResultCallback callback_;
const storage::FileSystemURL file_system_url_;
const std::set<EntryPropertyName> names_;
// Values used in the process.
std::unique_ptr<EntryProperties> properties_;
base::WeakPtrFactory<SingleEntryPropertiesGetterForFileSystemProvider>
weak_ptr_factory_;
}; // class SingleEntryPropertiesGetterForDrive
} // namespace
FileManagerPrivateInternalGetEntryPropertiesFunction::
FileManagerPrivateInternalGetEntryPropertiesFunction()
: processed_count_(0) {
}
FileManagerPrivateInternalGetEntryPropertiesFunction::
~FileManagerPrivateInternalGetEntryPropertiesFunction() {
}
bool FileManagerPrivateInternalGetEntryPropertiesFunction::RunAsync() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
using api::file_manager_private_internal::GetEntryProperties::Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
scoped_refptr<storage::FileSystemContext> file_system_context =
file_manager::util::GetFileSystemContextForRenderFrameHost(
GetProfile(), render_frame_host());
properties_list_.resize(params->urls.size());
const std::set<EntryPropertyName> names_as_set(params->names.begin(),
params->names.end());
for (size_t i = 0; i < params->urls.size(); i++) {
const GURL url = GURL(params->urls[i]);
const storage::FileSystemURL file_system_url =
file_system_context->CrackURL(url);
switch (file_system_url.type()) {
case storage::kFileSystemTypeDrive:
SingleEntryPropertiesGetterForDrive::Start(
file_system_url.path(), names_as_set, GetProfile(),
base::Bind(&FileManagerPrivateInternalGetEntryPropertiesFunction::
CompleteGetEntryProperties,
this, i, file_system_url));
break;
case storage::kFileSystemTypeProvided:
SingleEntryPropertiesGetterForFileSystemProvider::Start(
file_system_url, names_as_set,
base::Bind(&FileManagerPrivateInternalGetEntryPropertiesFunction::
CompleteGetEntryProperties,
this, i, file_system_url));
break;
default:
// TODO(yawano) Change this to support other voluems (e.g. local) ,and
// integrate fileManagerPrivate.getMimeType to this method.
LOG(ERROR) << "Not supported file system type.";
CompleteGetEntryProperties(i, file_system_url,
base::WrapUnique(new EntryProperties),
base::File::FILE_ERROR_INVALID_OPERATION);
}
}
return true;
}
void FileManagerPrivateInternalGetEntryPropertiesFunction::
CompleteGetEntryProperties(size_t index,
const storage::FileSystemURL& url,
std::unique_ptr<EntryProperties> properties,
base::File::Error error) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(0 <= processed_count_ && processed_count_ < properties_list_.size());
if (error == base::File::FILE_OK) {
properties->external_file_url.reset(
new std::string(chromeos::FileSystemURLToExternalFileURL(url).spec()));
}
properties_list_[index] = std::move(*properties);
processed_count_++;
if (processed_count_ < properties_list_.size())
return;
results_ = extensions::api::file_manager_private_internal::
GetEntryProperties::Results::Create(properties_list_);
SendResponse(true);
}
bool FileManagerPrivateInternalPinDriveFileFunction::RunAsync() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
using extensions::api::file_manager_private_internal::PinDriveFile::Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) // |file_system| is NULL if Drive is disabled.
return false;
const base::FilePath drive_path =
drive::util::ExtractDrivePath(file_manager::util::GetLocalPathFromURL(
render_frame_host(), GetProfile(), GURL(params->url)));
if (params->pin) {
file_system->Pin(
drive_path,
base::Bind(
&FileManagerPrivateInternalPinDriveFileFunction::OnPinStateSet,
this));
} else {
file_system->Unpin(
drive_path,
base::Bind(
&FileManagerPrivateInternalPinDriveFileFunction::OnPinStateSet,
this));
}
return true;
}
void FileManagerPrivateInternalPinDriveFileFunction::OnPinStateSet(
drive::FileError error) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error == drive::FILE_ERROR_OK) {
SendResponse(true);
} else {
SetError(drive::FileErrorToString(error));
SendResponse(false);
}
}
bool FileManagerPrivateInternalEnsureFileDownloadedFunction::RunAsync() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
using extensions::api::file_manager_private_internal::EnsureFileDownloaded::
Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
const base::FilePath drive_path =
drive::util::ExtractDrivePath(file_manager::util::GetLocalPathFromURL(
render_frame_host(), GetProfile(), GURL(params->url)));
if (drive_path.empty()) {
// Not under Drive. No need to fill the cache.
SendResponse(true);
return true;
}
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) // |file_system| is NULL if Drive is disabled.
return false;
file_system->GetFile(
drive_path,
base::Bind(&FileManagerPrivateInternalEnsureFileDownloadedFunction::
OnDownloadFinished,
this));
return true;
}
void FileManagerPrivateInternalEnsureFileDownloadedFunction::OnDownloadFinished(
drive::FileError error,
const base::FilePath& file_path,
std::unique_ptr<drive::ResourceEntry> entry) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error == drive::FILE_ERROR_OK) {
SendResponse(true);
} else {
SetError(drive::FileErrorToString(error));
SendResponse(false);
}
}
bool FileManagerPrivateInternalCancelFileTransfersFunction::RunAsync() {
using extensions::api::file_manager_private_internal::CancelFileTransfers::
Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
drive::DriveIntegrationService* integration_service =
drive::DriveIntegrationServiceFactory::FindForProfile(GetProfile());
if (!integration_service || !integration_service->IsMounted())
return false;
drive::JobListInterface* const job_list = integration_service->job_list();
DCHECK(job_list);
const std::vector<drive::JobInfo> jobs = job_list->GetJobInfoList();
// Create the mapping from file path to job ID.
typedef std::map<base::FilePath, std::vector<drive::JobID>> PathToIdMap;
PathToIdMap path_to_id_map;
for (size_t i = 0; i < jobs.size(); ++i) {
if (drive::IsActiveFileTransferJobInfo(jobs[i]))
path_to_id_map[jobs[i].file_path].push_back(jobs[i].job_id);
}
for (size_t i = 0; i < params->urls.size(); ++i) {
base::FilePath file_path = file_manager::util::GetLocalPathFromURL(
render_frame_host(), GetProfile(), GURL(params->urls[i]));
if (file_path.empty())
continue;
file_path = drive::util::ExtractDrivePath(file_path);
DCHECK(file_path.empty());
// Cancel all the jobs for the file.
PathToIdMap::iterator it = path_to_id_map.find(file_path);
if (it != path_to_id_map.end()) {
for (size_t i = 0; i < it->second.size(); ++i)
job_list->CancelJob(it->second[i]);
}
}
SendResponse(true);
return true;
}
bool FileManagerPrivateCancelAllFileTransfersFunction::RunAsync() {
drive::DriveIntegrationService* const integration_service =
drive::DriveIntegrationServiceFactory::FindForProfile(GetProfile());
if (!integration_service || !integration_service->IsMounted())
return false;
drive::JobListInterface* const job_list = integration_service->job_list();
DCHECK(job_list);
const std::vector<drive::JobInfo> jobs = job_list->GetJobInfoList();
for (size_t i = 0; i < jobs.size(); ++i) {
if (drive::IsActiveFileTransferJobInfo(jobs[i]))
job_list->CancelJob(jobs[i].job_id);
}
SendResponse(true);
return true;
}
bool FileManagerPrivateSearchDriveFunction::RunAsync() {
using extensions::api::file_manager_private::SearchDrive::Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) {
// |file_system| is NULL if Drive is disabled.
return false;
}
file_system->Search(
params->search_params.query, GURL(params->search_params.next_feed),
base::Bind(&FileManagerPrivateSearchDriveFunction::OnSearch, this));
return true;
}
void FileManagerPrivateSearchDriveFunction::OnSearch(
drive::FileError error,
const GURL& next_link,
std::unique_ptr<SearchResultInfoList> results) {
if (error != drive::FILE_ERROR_OK) {
SendResponse(false);
return;
}
// Outlives the following conversion, since the pointer is bound to the
// callback.
DCHECK(results.get());
const SearchResultInfoList& results_ref = *results.get();
ConvertSearchResultInfoListToEntryDefinitionList(
GetProfile(),
extension_->id(),
results_ref,
base::Bind(&FileManagerPrivateSearchDriveFunction::OnEntryDefinitionList,
this,
next_link,
base::Passed(&results)));
}
void FileManagerPrivateSearchDriveFunction::OnEntryDefinitionList(
const GURL& next_link,
std::unique_ptr<SearchResultInfoList> search_result_info_list,
std::unique_ptr<EntryDefinitionList> entry_definition_list) {
DCHECK_EQ(search_result_info_list->size(), entry_definition_list->size());
auto entries = std::make_unique<base::ListValue>();
// Convert Drive files to something File API stack can understand.
for (EntryDefinitionList::const_iterator it = entry_definition_list->begin();
it != entry_definition_list->end();
++it) {
auto entry = std::make_unique<base::DictionaryValue>();
entry->SetString("fileSystemName", it->file_system_name);
entry->SetString("fileSystemRoot", it->file_system_root_url);
entry->SetString("fileFullPath", "/" + it->full_path.AsUTF8Unsafe());
entry->SetBoolean("fileIsDirectory", it->is_directory);
entries->Append(std::move(entry));
}
std::unique_ptr<base::DictionaryValue> result(new base::DictionaryValue());
result->Set("entries", std::move(entries));
result->SetString("nextFeed", next_link.spec());
SetResult(std::move(result));
SendResponse(true);
}
bool FileManagerPrivateSearchDriveMetadataFunction::RunAsync() {
using api::file_manager_private::SearchDriveMetadata::Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
drive::EventLogger* logger = file_manager::util::GetLogger(GetProfile());
if (logger) {
logger->Log(
logging::LOG_INFO, "%s[%d] called. (types: '%s', maxResults: '%d')",
name(), request_id(),
api::file_manager_private::ToString(params->search_params.types),
params->search_params.max_results);
}
set_log_on_completion(true);
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) {
// |file_system| is NULL if Drive is disabled.
return false;
}
int options = -1;
switch (params->search_params.types) {
case api::file_manager_private::SEARCH_TYPE_EXCLUDE_DIRECTORIES:
options = drive::SEARCH_METADATA_EXCLUDE_DIRECTORIES;
break;
case api::file_manager_private::SEARCH_TYPE_SHARED_WITH_ME:
options = drive::SEARCH_METADATA_SHARED_WITH_ME;
break;
case api::file_manager_private::SEARCH_TYPE_OFFLINE:
options = drive::SEARCH_METADATA_OFFLINE;
break;
case api::file_manager_private::SEARCH_TYPE_ALL:
options = drive::SEARCH_METADATA_ALL;
break;
case api::file_manager_private::SEARCH_TYPE_NONE:
break;
}
DCHECK_NE(options, -1);
file_system->SearchMetadata(
params->search_params.query, options, params->search_params.max_results,
drive::MetadataSearchOrder::LAST_ACCESSED,
base::Bind(
&FileManagerPrivateSearchDriveMetadataFunction::OnSearchMetadata,
this));
return true;
}
void FileManagerPrivateSearchDriveMetadataFunction::OnSearchMetadata(
drive::FileError error,
std::unique_ptr<drive::MetadataSearchResultVector> results) {
if (error != drive::FILE_ERROR_OK) {
SendResponse(false);
return;
}
// Outlives the following conversion, since the pointer is bound to the
// callback.
DCHECK(results.get());
const drive::MetadataSearchResultVector& results_ref = *results.get();
ConvertSearchResultInfoListToEntryDefinitionList(
GetProfile(),
extension_->id(),
results_ref,
base::Bind(
&FileManagerPrivateSearchDriveMetadataFunction::OnEntryDefinitionList,
this,
base::Passed(&results)));
}
void FileManagerPrivateSearchDriveMetadataFunction::OnEntryDefinitionList(
std::unique_ptr<drive::MetadataSearchResultVector> search_result_info_list,
std::unique_ptr<EntryDefinitionList> entry_definition_list) {
DCHECK_EQ(search_result_info_list->size(), entry_definition_list->size());
std::unique_ptr<base::ListValue> results_list(new base::ListValue());
// Convert Drive files to something File API stack can understand. See
// file_browser_handler_custom_bindings.cc and
// file_manager_private_custom_bindings.js for how this is magically
// converted to a FileEntry.
for (size_t i = 0; i < entry_definition_list->size(); ++i) {
auto result_dict = std::make_unique<base::DictionaryValue>();
// FileEntry fields.
auto entry = std::make_unique<base::DictionaryValue>();
entry->SetString(
"fileSystemName", entry_definition_list->at(i).file_system_name);
entry->SetString(
"fileSystemRoot", entry_definition_list->at(i).file_system_root_url);
entry->SetString(
"fileFullPath",
"/" + entry_definition_list->at(i).full_path.AsUTF8Unsafe());
entry->SetBoolean("fileIsDirectory",
entry_definition_list->at(i).is_directory);
result_dict->Set("entry", std::move(entry));
result_dict->SetString(
"highlightedBaseName",
search_result_info_list->at(i).highlighted_base_name);
results_list->Append(std::move(result_dict));
}
SetResult(std::move(results_list));
SendResponse(true);
}
ExtensionFunction::ResponseAction
FileManagerPrivateGetDriveConnectionStateFunction::Run() {
api::file_manager_private::DriveConnectionState result;
switch (drive::util::GetDriveConnectionStatus(
Profile::FromBrowserContext(browser_context()))) {
case drive::util::DRIVE_DISCONNECTED_NOSERVICE:
result.type = kDriveConnectionTypeOffline;
result.reason.reset(new std::string(kDriveConnectionReasonNoService));
break;
case drive::util::DRIVE_DISCONNECTED_NONETWORK:
result.type = kDriveConnectionTypeOffline;
result.reason.reset(new std::string(kDriveConnectionReasonNoNetwork));
break;
case drive::util::DRIVE_DISCONNECTED_NOTREADY:
result.type = kDriveConnectionTypeOffline;
result.reason.reset(new std::string(kDriveConnectionReasonNotReady));
break;
case drive::util::DRIVE_CONNECTED_METERED:
result.type = kDriveConnectionTypeMetered;
break;
case drive::util::DRIVE_CONNECTED:
result.type = kDriveConnectionTypeOnline;
break;
}
result.has_cellular_network_access =
chromeos::NetworkHandler::Get()
->network_state_handler()
->FirstNetworkByType(chromeos::NetworkTypePattern::Mobile());
drive::EventLogger* logger = file_manager::util::GetLogger(
Profile::FromBrowserContext(browser_context()));
if (logger)
logger->Log(logging::LOG_INFO, "%s succeeded.", name());
return RespondNow(ArgumentList(
api::file_manager_private::GetDriveConnectionState::Results::Create(
result)));
}
bool FileManagerPrivateRequestAccessTokenFunction::RunAsync() {
using extensions::api::file_manager_private::RequestAccessToken::Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
drive::DriveServiceInterface* const drive_service =
drive::util::GetDriveServiceByProfile(GetProfile());
if (!drive_service) {
// DriveService is not available.
SetResult(std::make_unique<base::Value>(std::string()));
SendResponse(true);
return true;
}
// If refreshing is requested, then clear the token to refetch it.
if (params->refresh)
drive_service->ClearAccessToken();
// Retrieve the cached auth token (if available), otherwise the AuthService
// instance will try to refetch it.
drive_service->RequestAccessToken(
base::Bind(&FileManagerPrivateRequestAccessTokenFunction::
OnAccessTokenFetched, this));
return true;
}
void FileManagerPrivateRequestAccessTokenFunction::OnAccessTokenFetched(
google_apis::DriveApiErrorCode code,
const std::string& access_token) {
SetResult(std::make_unique<base::Value>(access_token));
SendResponse(true);
}
bool FileManagerPrivateInternalGetShareUrlFunction::RunAsync() {
using extensions::api::file_manager_private_internal::GetShareUrl::Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
const base::FilePath path = file_manager::util::GetLocalPathFromURL(
render_frame_host(), GetProfile(), GURL(params->url));
DCHECK(drive::util::IsUnderDriveMountPoint(path));
const base::FilePath drive_path = drive::util::ExtractDrivePath(path);
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) {
// |file_system| is NULL if Drive is disabled.
return false;
}
file_system->GetShareUrl(
drive_path,
GURL("chrome-extension://" + extension_id()), // embed origin
base::Bind(&FileManagerPrivateInternalGetShareUrlFunction::OnGetShareUrl,
this));
return true;
}
void FileManagerPrivateInternalGetShareUrlFunction::OnGetShareUrl(
drive::FileError error,
const GURL& share_url) {
if (error != drive::FILE_ERROR_OK) {
SetError("Share Url for this item is not available.");
SendResponse(false);
return;
}
SetResult(std::make_unique<base::Value>(share_url.spec()));
SendResponse(true);
}
bool FileManagerPrivateInternalRequestDriveShareFunction::RunAsync() {
using extensions::api::file_manager_private_internal::RequestDriveShare::
Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
const base::FilePath path = file_manager::util::GetLocalPathFromURL(
render_frame_host(), GetProfile(), GURL(params->url));
const base::FilePath drive_path = drive::util::ExtractDrivePath(path);
Profile* const owner_profile = drive::util::ExtractProfileFromPath(path);
if (!owner_profile)
return false;
drive::FileSystemInterface* const owner_file_system =
drive::util::GetFileSystemByProfile(owner_profile);
if (!owner_file_system)
return false;
const user_manager::User* const user =
chromeos::ProfileHelper::Get()->GetUserByProfile(GetProfile());
if (!user || !user->is_logged_in())
return false;
google_apis::drive::PermissionRole role =
google_apis::drive::PERMISSION_ROLE_READER;
switch (params->share_type) {
case api::file_manager_private::DRIVE_SHARE_TYPE_NONE:
NOTREACHED();
return false;
case api::file_manager_private::DRIVE_SHARE_TYPE_CAN_EDIT:
role = google_apis::drive::PERMISSION_ROLE_WRITER;
break;
case api::file_manager_private::DRIVE_SHARE_TYPE_CAN_COMMENT:
role = google_apis::drive::PERMISSION_ROLE_COMMENTER;
break;
case api::file_manager_private::DRIVE_SHARE_TYPE_CAN_VIEW:
role = google_apis::drive::PERMISSION_ROLE_READER;
break;
}
// Share |drive_path| in |owner_file_system| to
// |user->GetAccountId().GetUserEmail()|.
owner_file_system->AddPermission(
drive_path, user->GetAccountId().GetUserEmail(), role,
base::Bind(
&FileManagerPrivateInternalRequestDriveShareFunction::OnAddPermission,
this));
return true;
}
void FileManagerPrivateInternalRequestDriveShareFunction::OnAddPermission(
drive::FileError error) {
SendResponse(error == drive::FILE_ERROR_OK);
}
FileManagerPrivateInternalGetDownloadUrlFunction::
FileManagerPrivateInternalGetDownloadUrlFunction() {}
FileManagerPrivateInternalGetDownloadUrlFunction::
~FileManagerPrivateInternalGetDownloadUrlFunction() {}
bool FileManagerPrivateInternalGetDownloadUrlFunction::RunAsync() {
using extensions::api::file_manager_private_internal::GetShareUrl::Params;
const std::unique_ptr<Params> params(Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params);
// Start getting the file info.
drive::FileSystemInterface* const file_system =
drive::util::GetFileSystemByProfile(GetProfile());
if (!file_system) {
// |file_system| is NULL if Drive is disabled or not mounted.
SetError("Drive is disabled or not mounted.");
// Intentionally returns a blank.
SetResult(std::make_unique<base::Value>(std::string()));
return false;
}
const base::FilePath path = file_manager::util::GetLocalPathFromURL(
render_frame_host(), GetProfile(), GURL(params->url));
if (!drive::util::IsUnderDriveMountPoint(path)) {
SetError("The given file is not in Drive.");
// Intentionally returns a blank.
SetResult(std::make_unique<base::Value>(std::string()));
return false;
}
base::FilePath file_path = drive::util::ExtractDrivePath(path);
file_system->GetResourceEntry(
file_path,
base::Bind(
&FileManagerPrivateInternalGetDownloadUrlFunction::OnGetResourceEntry,
this));
return true;
}
void FileManagerPrivateInternalGetDownloadUrlFunction::OnGetResourceEntry(
drive::FileError error,
std::unique_ptr<drive::ResourceEntry> entry) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (error != drive::FILE_ERROR_OK) {
SetError("Download Url for this item is not available.");
// Intentionally returns a blank.
SetResult(std::make_unique<base::Value>(std::string()));
SendResponse(false);
return;
}
DriveApiUrlGenerator url_generator(
(GURL(google_apis::DriveApiUrlGenerator::kBaseUrlForProduction)),
(GURL(
google_apis::DriveApiUrlGenerator::kBaseThumbnailUrlForProduction)),
google_apis::GetTeamDrivesIntegrationSwitch());
download_url_ = url_generator.GenerateDownloadFileUrl(entry->resource_id());
ProfileOAuth2TokenService* oauth2_token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(GetProfile());
SigninManagerBase* signin_manager =
SigninManagerFactory::GetForProfile(GetProfile());
const std::string& account_id = signin_manager->GetAuthenticatedAccountId();
std::vector<std::string> scopes;
scopes.push_back("https://www.googleapis.com/auth/drive.readonly");
auth_service_.reset(
new google_apis::AuthService(oauth2_token_service,
account_id,
GetProfile()->GetRequestContext(),
scopes));
auth_service_->StartAuthentication(base::Bind(
&FileManagerPrivateInternalGetDownloadUrlFunction::OnTokenFetched, this));
}
void FileManagerPrivateInternalGetDownloadUrlFunction::OnTokenFetched(
google_apis::DriveApiErrorCode code,
const std::string& access_token) {
if (code != google_apis::HTTP_SUCCESS) {
SetError("Not able to fetch the token.");
// Intentionally returns a blank.
SetResult(std::make_unique<base::Value>(std::string()));
SendResponse(false);
return;
}
const std::string url =
download_url_.Resolve("?alt=media&access_token=" + access_token).spec();
SetResult(std::make_unique<base::Value>(url));
SendResponse(true);
}
} // namespace extensions
| 37.289216 | 88 | 0.711209 | [
"vector"
] |
9cbdb9c50f336b48b5f6bc373a167573821b12d2 | 3,644 | cxx | C++ | Modules/Filtering/ImageIntensity/test/itkVectorToRGBImageAdaptorTest.cxx | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | 1 | 2015-10-12T00:14:09.000Z | 2015-10-12T00:14:09.000Z | Modules/Filtering/ImageIntensity/test/itkVectorToRGBImageAdaptorTest.cxx | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/ImageIntensity/test/itkVectorToRGBImageAdaptorTest.cxx | itkvideo/ITK | 5882452373df23463c2e9410c50bc9882ca1e8de | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
/**
*
* This program tests the VectorToRGBImageAdaptor.
*
* This class allows to take an image of pixel type RGBPixel,
* and use it as if it was an image of pixel type itk::Vector<>.
*
*/
#include "itkVectorToRGBImageAdaptor.h"
#include "itkImageRegionIteratorWithIndex.h"
//-------------------------
//
// Main code
//
//-------------------------
int itkVectorToRGBImageAdaptorTest(int, char* [] ) {
//-------------------------------------
// Typedefs for convenience
//-------------------------------------
typedef float ValueType;
const unsigned int numberOfComponents = 3;
typedef itk::Vector< ValueType,
numberOfComponents > VectorPixelType;
const unsigned int ImageDimension = 2;
typedef itk::Image< VectorPixelType, ImageDimension > ImageType;
typedef itk::VectorToRGBImageAdaptor< ImageType > ImageAdaptorType;
typedef itk::ImageRegionIteratorWithIndex< ImageType > IteratorType;
typedef itk::ImageRegionIteratorWithIndex< ImageAdaptorType > RGBIteratorType;
ImageType::SizeType size;
size[0] = 2;
size[1] = 2;
ImageType::IndexType index;
index[0] = 0;
index[1] = 0;
ImageType::RegionType region;
region.SetIndex( index );
region.SetSize( size );
ImageType::Pointer image = ImageType::New();
image->SetLargestPossibleRegion( region );
image->SetBufferedRegion( region );
image->SetRequestedRegion( region );
image->Allocate();
IteratorType it1( image, image->GetRequestedRegion() );
// Value to initialize the pixels
ImageType::PixelType vector;
vector[0] = 1.2;
vector[1] = 1.3;
vector[2] = 1.4;
// Initializing all the pixel in the image
it1.GoToBegin();
while( !it1.IsAtEnd() )
{
it1.Set( vector );
++it1;
}
// Reading the values to verify the image content
std::cout << "--- Before --- " << std::endl;
it1.GoToBegin();
while( !it1.IsAtEnd() )
{
const ImageType::PixelType c( it1.Get() );
std::cout << c[0] << " ";
std::cout << c[1] << " ";
std::cout << c[2] << std::endl;
++it1;
}
ImageAdaptorType::Pointer adaptor = ImageAdaptorType::New();
adaptor->SetImage( image );
RGBIteratorType it2( adaptor, adaptor->GetRequestedRegion() );
// Set the values of the image, using the adaptor
typedef ImageAdaptorType::AccessorType::ExternalType RGBPixelType;
RGBPixelType color;
color[0] = 13;
color[1] = 17;
color[2] = 19;
it2.GoToBegin();
while( !it2.IsAtEnd() )
{
it2.Set( color );
++it2;
}
std::cout << "--- After --- " << std::endl;
it1.GoToBegin();
while( !it1.IsAtEnd() )
{
const ImageType::PixelType c( it1.Get() );
std::cout << c[0] << " ";
std::cout << c[1] << " ";
std::cout << c[2] << std::endl;
++it1;
}
return EXIT_SUCCESS;
}
| 22.775 | 79 | 0.60483 | [
"vector"
] |
9cbdc213df324e1fd42adc6a6980c746b55e74a2 | 10,627 | cpp | C++ | common/osqp_interface/src/osqp_interface.cpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | 58 | 2021-11-30T09:03:46.000Z | 2022-03-31T15:25:17.000Z | common/osqp_interface/src/osqp_interface.cpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | 425 | 2021-11-30T02:24:44.000Z | 2022-03-31T10:26:37.000Z | common/osqp_interface/src/osqp_interface.cpp | meliketanrikulu/autoware.universe | 04f2b53ae1d7b41846478641ad6ff478c3d5a247 | [
"Apache-2.0"
] | 69 | 2021-11-30T02:09:18.000Z | 2022-03-31T15:38:29.000Z | // Copyright 2021 The Autoware 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 "osqp_interface/osqp_interface.hpp"
#include "osqp/osqp.h"
#include "osqp_interface/csc_matrix_conv.hpp"
#include <chrono>
#include <iostream>
#include <limits>
#include <memory>
#include <string>
#include <tuple>
#include <vector>
namespace autoware
{
namespace common
{
namespace osqp
{
OSQPInterface::OSQPInterface(const c_float eps_abs, const bool8_t polish)
: m_work{nullptr, OSQPWorkspaceDeleter}
{
m_settings = std::make_unique<OSQPSettings>();
m_data = std::make_unique<OSQPData>();
if (m_settings) {
osqp_set_default_settings(m_settings.get());
m_settings->alpha = 1.6; // Change alpha parameter
m_settings->eps_rel = 1.0E-4;
m_settings->eps_abs = eps_abs;
m_settings->eps_prim_inf = 1.0E-4;
m_settings->eps_dual_inf = 1.0E-4;
m_settings->warm_start = true;
m_settings->max_iter = 4000;
m_settings->verbose = false;
m_settings->polish = polish;
}
m_exitflag = 0;
}
OSQPInterface::OSQPInterface(
const Eigen::MatrixXd & P, const Eigen::MatrixXd & A, const std::vector<float64_t> & q,
const std::vector<float64_t> & l, const std::vector<float64_t> & u, const c_float eps_abs)
: OSQPInterface(eps_abs)
{
initializeProblem(P, A, q, l, u);
}
OSQPInterface::OSQPInterface(
const CSC_Matrix & P, const CSC_Matrix & A, const std::vector<float64_t> & q,
const std::vector<float64_t> & l, const std::vector<float64_t> & u, const c_float eps_abs)
: OSQPInterface(eps_abs)
{
initializeProblem(P, A, q, l, u);
}
void OSQPInterface::OSQPWorkspaceDeleter(OSQPWorkspace * ptr) noexcept
{
if (ptr != nullptr) {
osqp_cleanup(ptr);
}
}
void OSQPInterface::updateP(const Eigen::MatrixXd & P_new)
{
/*
// Transform 'P' into an 'upper trapezoidal matrix'
Eigen::MatrixXd P_trap = P_new.triangularView<Eigen::Upper>();
// Transform 'P' into a sparse matrix and extract data as dynamic arrays
Eigen::SparseMatrix<double> P_sparse = P_trap.sparseView();
double *P_val_ptr = P_sparse.valuePtr();
// Convert dynamic 'int' arrays to 'c_int' arrays (OSQP input type)
c_int P_elem_N = P_sparse.nonZeros();
*/
CSC_Matrix P_csc = calCSCMatrixTrapezoidal(P_new);
osqp_update_P(
m_work.get(), P_csc.m_vals.data(), OSQP_NULL, static_cast<c_int>(P_csc.m_vals.size()));
}
void OSQPInterface::updateCscP(const CSC_Matrix & P_csc)
{
osqp_update_P(
m_work.get(), P_csc.m_vals.data(), OSQP_NULL, static_cast<c_int>(P_csc.m_vals.size()));
}
void OSQPInterface::updateA(const Eigen::MatrixXd & A_new)
{
/*
// Transform 'A' into a sparse matrix and extract data as dynamic arrays
Eigen::SparseMatrix<double> A_sparse = A_new.sparseView();
double *A_val_ptr = A_sparse.valuePtr();
// Convert dynamic 'int' arrays to 'c_int' arrays (OSQP input type)
c_int A_elem_N = A_sparse.nonZeros();
*/
CSC_Matrix A_csc = calCSCMatrix(A_new);
osqp_update_A(
m_work.get(), A_csc.m_vals.data(), OSQP_NULL, static_cast<c_int>(A_csc.m_vals.size()));
return;
}
void OSQPInterface::updateCscA(const CSC_Matrix & A_csc)
{
osqp_update_A(
m_work.get(), A_csc.m_vals.data(), OSQP_NULL, static_cast<c_int>(A_csc.m_vals.size()));
}
void OSQPInterface::updateQ(const std::vector<double> & q_new)
{
std::vector<double> q_tmp(q_new.begin(), q_new.end());
double * q_dyn = q_tmp.data();
osqp_update_lin_cost(m_work.get(), q_dyn);
}
void OSQPInterface::updateL(const std::vector<double> & l_new)
{
std::vector<double> l_tmp(l_new.begin(), l_new.end());
double * l_dyn = l_tmp.data();
osqp_update_lower_bound(m_work.get(), l_dyn);
}
void OSQPInterface::updateU(const std::vector<double> & u_new)
{
std::vector<double> u_tmp(u_new.begin(), u_new.end());
double * u_dyn = u_tmp.data();
osqp_update_upper_bound(m_work.get(), u_dyn);
}
void OSQPInterface::updateBounds(
const std::vector<double> & l_new, const std::vector<double> & u_new)
{
std::vector<double> l_tmp(l_new.begin(), l_new.end());
std::vector<double> u_tmp(u_new.begin(), u_new.end());
double * l_dyn = l_tmp.data();
double * u_dyn = u_tmp.data();
osqp_update_bounds(m_work.get(), l_dyn, u_dyn);
}
void OSQPInterface::updateEpsAbs(const double eps_abs)
{
m_settings->eps_abs = eps_abs; // for default setting
if (m_work_initialized) {
osqp_update_eps_abs(m_work.get(), eps_abs); // for current work
}
}
void OSQPInterface::updateEpsRel(const double eps_rel)
{
m_settings->eps_rel = eps_rel; // for default setting
if (m_work_initialized) {
osqp_update_eps_rel(m_work.get(), eps_rel); // for current work
}
}
void OSQPInterface::updateMaxIter(const int max_iter)
{
m_settings->max_iter = max_iter; // for default setting
if (m_work_initialized) {
osqp_update_max_iter(m_work.get(), max_iter); // for current work
}
}
void OSQPInterface::updateVerbose(const bool is_verbose)
{
m_settings->verbose = is_verbose; // for default setting
if (m_work_initialized) {
osqp_update_verbose(m_work.get(), is_verbose); // for current work
}
}
void OSQPInterface::updateRhoInterval(const int rho_interval)
{
m_settings->adaptive_rho_interval = rho_interval; // for default setting
}
void OSQPInterface::updateRho(const double rho)
{
m_settings->rho = rho;
if (m_work_initialized) {
osqp_update_rho(m_work.get(), rho);
}
}
void OSQPInterface::updateAlpha(const double alpha)
{
m_settings->alpha = alpha;
if (m_work_initialized) {
osqp_update_alpha(m_work.get(), alpha);
}
}
int64_t OSQPInterface::initializeProblem(
const Eigen::MatrixXd & P, const Eigen::MatrixXd & A, const std::vector<float64_t> & q,
const std::vector<float64_t> & l, const std::vector<float64_t> & u)
{
// check if arguments are valid
std::stringstream ss;
if (P.rows() != P.cols()) {
ss << "P.rows() and P.cols() are not the same. P.rows() = " << P.rows()
<< ", P.cols() = " << P.cols();
throw std::invalid_argument(ss.str());
}
if (P.rows() != static_cast<int>(q.size())) {
ss << "P.rows() and q.size() are not the same. P.rows() = " << P.rows()
<< ", q.size() = " << q.size();
throw std::invalid_argument(ss.str());
}
if (P.rows() != A.cols()) {
ss << "P.rows() and A.cols() are not the same. P.rows() = " << P.rows()
<< ", A.cols() = " << A.cols();
throw std::invalid_argument(ss.str());
}
if (A.rows() != static_cast<int>(l.size())) {
ss << "A.rows() and l.size() are not the same. A.rows() = " << A.rows()
<< ", l.size() = " << l.size();
throw std::invalid_argument(ss.str());
}
if (A.rows() != static_cast<int>(u.size())) {
ss << "A.rows() and u.size() are not the same. A.rows() = " << A.rows()
<< ", u.size() = " << u.size();
throw std::invalid_argument(ss.str());
}
CSC_Matrix P_csc = calCSCMatrixTrapezoidal(P);
CSC_Matrix A_csc = calCSCMatrix(A);
return initializeProblem(P_csc, A_csc, q, l, u);
}
int64_t OSQPInterface::initializeProblem(
CSC_Matrix P_csc, CSC_Matrix A_csc, const std::vector<float64_t> & q,
const std::vector<float64_t> & l, const std::vector<float64_t> & u)
{
// Dynamic float arrays
std::vector<float64_t> q_tmp(q.begin(), q.end());
std::vector<float64_t> l_tmp(l.begin(), l.end());
std::vector<float64_t> u_tmp(u.begin(), u.end());
float64_t * q_dyn = q_tmp.data();
float64_t * l_dyn = l_tmp.data();
float64_t * u_dyn = u_tmp.data();
/**********************
* OBJECTIVE FUNCTION
**********************/
m_param_n = static_cast<int>(q.size());
m_data->m = static_cast<int>(l.size());
/*****************
* POPULATE DATA
*****************/
m_data->n = m_param_n;
m_data->P = csc_matrix(
m_data->n, m_data->n, static_cast<c_int>(P_csc.m_vals.size()), P_csc.m_vals.data(),
P_csc.m_row_idxs.data(), P_csc.m_col_idxs.data());
m_data->q = q_dyn;
m_data->A = csc_matrix(
m_data->m, m_data->n, static_cast<c_int>(A_csc.m_vals.size()), A_csc.m_vals.data(),
A_csc.m_row_idxs.data(), A_csc.m_col_idxs.data());
m_data->l = l_dyn;
m_data->u = u_dyn;
// Setup workspace
OSQPWorkspace * workspace;
m_exitflag = osqp_setup(&workspace, m_data.get(), m_settings.get());
m_work.reset(workspace);
m_work_initialized = true;
return m_exitflag;
}
std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t>
OSQPInterface::solve()
{
// Solve Problem
osqp_solve(m_work.get());
/********************
* EXTRACT SOLUTION
********************/
float64_t * sol_x = m_work->solution->x;
float64_t * sol_y = m_work->solution->y;
std::vector<float64_t> sol_primal(sol_x, sol_x + m_param_n);
std::vector<float64_t> sol_lagrange_multiplier(sol_y, sol_y + m_data->m);
int64_t status_polish = m_work->info->status_polish;
int64_t status_solution = m_work->info->status_val;
int64_t status_iteration = m_work->info->iter;
// Result tuple
std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t> result =
std::make_tuple(
sol_primal, sol_lagrange_multiplier, status_polish, status_solution, status_iteration);
m_latest_work_info = *(m_work->info);
return result;
}
std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t>
OSQPInterface::optimize()
{
// Run the solver on the stored problem representation.
std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t> result =
solve();
return result;
}
std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t>
OSQPInterface::optimize(
const Eigen::MatrixXd & P, const Eigen::MatrixXd & A, const std::vector<float64_t> & q,
const std::vector<float64_t> & l, const std::vector<float64_t> & u)
{
// Allocate memory for problem
initializeProblem(P, A, q, l, u);
// Run the solver on the stored problem representation.
std::tuple<std::vector<float64_t>, std::vector<float64_t>, int64_t, int64_t, int64_t> result =
solve();
m_work.reset();
m_work_initialized = false;
return result;
}
} // namespace osqp
} // namespace common
} // namespace autoware
| 31.164223 | 96 | 0.680248 | [
"vector",
"transform"
] |
9cbe0bf3acf3fd601bbbc3962dadf4908e9bbce9 | 3,651 | cpp | C++ | test/auto_contiguous_test.cpp | sjw36/AMDMIGraphX | c310bc5cf9b3f8ea44823a386a1b8bd72014bf09 | [
"MIT"
] | null | null | null | test/auto_contiguous_test.cpp | sjw36/AMDMIGraphX | c310bc5cf9b3f8ea44823a386a1b8bd72014bf09 | [
"MIT"
] | 1 | 2022-02-10T07:11:54.000Z | 2022-02-10T07:11:54.000Z | test/auto_contiguous_test.cpp | sjw36/AMDMIGraphX | c310bc5cf9b3f8ea44823a386a1b8bd72014bf09 | [
"MIT"
] | null | null | null | #include <migraphx/auto_contiguous.hpp>
#include <migraphx/instruction.hpp>
#include <migraphx/pass_manager.hpp>
#include <basic_ops.hpp>
#include <migraphx/make_op.hpp>
#include <test.hpp>
void run_pass(migraphx::module& m) { migraphx::run_passes(m, {migraphx::auto_contiguous{}}); }
// TODO: Add this test case
void literal_broadcast()
{
migraphx::module m;
m.add_literal(get_2_broadcasted());
EXPECT(not m.get_output_shapes().back().standard());
EXPECT(m.get_output_shapes().back().broadcasted());
run_pass(m);
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().broadcasted());
}
TEST_CASE(literal_transpose)
{
migraphx::module m;
m.add_literal(get_2x2_transposed());
EXPECT(not m.get_output_shapes().back().standard());
EXPECT(m.get_output_shapes().back().transposed());
run_pass(m);
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().transposed());
}
TEST_CASE(after_literal_transpose)
{
migraphx::module m;
auto l = m.add_literal(get_2x2());
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().transposed());
auto t = m.add_instruction(migraphx::make_op("transpose", {{"dims", {1, 0}}}), l);
m.add_instruction(pass_op{}, t);
EXPECT(not m.get_output_shapes().back().standard());
EXPECT(m.get_output_shapes().back().transposed());
run_pass(m);
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().transposed());
}
TEST_CASE(after_literal_broadcast)
{
migraphx::module m;
auto l1 = m.add_literal(get_2x2());
auto l2 = m.add_literal(get_2());
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().broadcasted());
auto b = m.add_instruction(
migraphx::make_op("broadcast", {{"axis", 0}, {"dims", l1->get_shape().lens()}}), l2);
m.add_instruction(pass_op{}, b);
EXPECT(not m.get_output_shapes().back().standard());
EXPECT(m.get_output_shapes().back().broadcasted());
run_pass(m);
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().broadcasted());
}
TEST_CASE(after_param_transpose)
{
migraphx::module m;
auto l = m.add_parameter("2x2", {migraphx::shape::float_type, {2, 2}});
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().transposed());
auto t = m.add_instruction(migraphx::make_op("transpose", {{"dims", {1, 0}}}), l);
m.add_instruction(pass_op{}, t);
EXPECT(not m.get_output_shapes().back().standard());
EXPECT(m.get_output_shapes().back().transposed());
run_pass(m);
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().transposed());
}
TEST_CASE(after_param_broadcast)
{
migraphx::module m;
auto l1 = m.add_parameter("2x2", {migraphx::shape::float_type, {2, 2}});
auto l2 = m.add_parameter("2", {migraphx::shape::float_type, {2}});
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().broadcasted());
auto b = m.add_instruction(
migraphx::make_op("broadcast", {{"axis", 0}, {"dims", l1->get_shape().lens()}}), l2);
m.add_instruction(pass_op{}, b);
EXPECT(not m.get_output_shapes().back().standard());
EXPECT(m.get_output_shapes().back().broadcasted());
run_pass(m);
EXPECT(m.get_output_shapes().back().standard());
EXPECT(not m.get_output_shapes().back().broadcasted());
}
int main(int argc, const char* argv[]) { test::run(argc, argv); }
| 34.771429 | 94 | 0.670501 | [
"shape"
] |
9cc8b998037618f66eeaea1d6aa11fe8b8b6849e | 1,212 | cxx | C++ | ParaViewCore/VTKExtensions/vtkMaterialInterfaceProcessLoading.cxx | XiaoboFu/ParaViewGeo | 0089927885fd67a3d70a22a28977a291bed3fcdd | [
"BSD-2-Clause",
"BSD-3-Clause"
] | 17 | 2015-02-17T00:30:26.000Z | 2022-03-17T06:13:02.000Z | ParaViewCore/VTKExtensions/vtkMaterialInterfaceProcessLoading.cxx | aashish24/paraview-climate-3.11.1 | c8ea429f56c10059dfa4450238b8f5bac3208d3a | [
"BSD-3-Clause"
] | null | null | null | ParaViewCore/VTKExtensions/vtkMaterialInterfaceProcessLoading.cxx | aashish24/paraview-climate-3.11.1 | c8ea429f56c10059dfa4450238b8f5bac3208d3a | [
"BSD-3-Clause"
] | 10 | 2015-08-31T18:20:17.000Z | 2022-02-02T15:16:21.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile$
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 "vtkMaterialInterfaceProcessLoading.h"
using vtksys_ios::ostream;
using vtksys_ios::endl;
using vtkstd::vector;
//
ostream &operator<<(ostream &sout, vtkMaterialInterfaceProcessLoading &fp)
{
sout << "(" << fp.GetId() << "," << fp.GetLoadFactor() << ")";
return sout;
}
//
ostream &operator<<(ostream &sout, vector<vtkMaterialInterfaceProcessLoading> &vfp)
{
int n=vfp.size();
vtkIdType total=0;
for (int i=0; i<n; ++i)
{
total+=vfp[i].GetLoadFactor();
sout << "(" << vfp[i].GetId() << "," << vfp[i].GetLoadFactor() << ")" << endl;
}
sout << "Total loading:" << total << endl;
return sout;
}
| 29.560976 | 83 | 0.589934 | [
"vector"
] |
9ccaee93a6614c6a542096dadec4647dba165b2b | 3,497 | cpp | C++ | examples/undocumented/libshogun/features_copy_subset_sparse_features.cpp | Arpit2601/shogun | e509f8c57f47dc74b3f791d450a70b770d11582a | [
"BSD-3-Clause"
] | 1 | 2019-10-02T11:10:08.000Z | 2019-10-02T11:10:08.000Z | examples/undocumented/libshogun/features_copy_subset_sparse_features.cpp | Arpit2601/shogun | e509f8c57f47dc74b3f791d450a70b770d11582a | [
"BSD-3-Clause"
] | null | null | null | examples/undocumented/libshogun/features_copy_subset_sparse_features.cpp | Arpit2601/shogun | e509f8c57f47dc74b3f791d450a70b770d11582a | [
"BSD-3-Clause"
] | 1 | 2020-06-02T09:15:40.000Z | 2020-06-02T09:15:40.000Z | /*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Authors: Heiko Strathmann, Soeren Sonnenburg, Sergey Lisitsyn, Thoralf Klein,
* Viktor Gal
*/
#include <shogun/features/SparseFeatures.h>
#include <shogun/features/Subset.h>
using namespace shogun;
void test()
{
index_t num_vectors=10;
index_t num_dimensions=7;
index_t num_features=3;
/* create some sparse data */
SGSparseMatrix<float64_t> data=SGSparseMatrix<float64_t>(num_dimensions,
num_vectors);
for (index_t i=0; i<num_vectors; ++i)
{
/* put elements only at even indices */
data.sparse_matrix[i]=SGSparseVector<float64_t>(num_features);
/* fill */
for (index_t j=0; j<num_features; ++j)
{
data.sparse_matrix[i].features[j].entry=i+j;
data.sparse_matrix[i].features[j].feat_index=3*j;
}
}
CSparseFeatures<float64_t>* f=new CSparseFeatures<float64_t>(data);
/* display sparse matrix */
SG_SPRINT("original data\n");
for (index_t i=0; i<num_vectors; ++i)
{
SG_SPRINT("sparse vector at %i: [", i);
for (index_t j=0; j<num_features; ++j)
SG_SPRINT("%f, ", data.sparse_matrix[i].features[j].entry);
SG_SPRINT("]\n");
}
/* indices for a subset */
index_t offset_subset=1;
SGVector<index_t> feature_subset(8);
SGVector<index_t>::range_fill_vector(feature_subset.vector, feature_subset.vlen,
offset_subset);
SGVector<index_t>::display_vector(feature_subset.vector, feature_subset.vlen,
"feature subset");
/* set subset and print data */
f->add_subset(feature_subset);
SG_SPRINT("feature vectors after setting subset on original data:\n");
for (index_t i=0; i<f->get_num_vectors(); ++i)
{
SGSparseVector<float64_t> vec=f->get_sparse_feature_vector(i);
SG_SPRINT("sparse vector at %i: ", i);
for (index_t j=0; j<num_features; ++j)
SG_SPRINT("%f, ", vec.features[j].entry);
SG_SPRINT("]\n");
f->free_sparse_feature_vector(i);
}
/* indices that are to copy */
index_t offset_copy=2;
SGVector<index_t> feature_copy_subset(4);
SGVector<index_t>::range_fill_vector(feature_copy_subset.vector,
feature_copy_subset.vlen, offset_copy);
SGVector<index_t>::display_vector(feature_copy_subset.vector, feature_copy_subset.vlen,
"indices that are to be copied");
/* copy a subset of features */
CSparseFeatures<float64_t>* subset_copy=
(CSparseFeatures<float64_t>*)f->copy_subset(feature_copy_subset);
/* print copied subset */
SG_SPRINT("copied features:\n");
for (index_t i=0; i<subset_copy->get_num_vectors(); ++i)
{
SGSparseVector<float64_t> vec=subset_copy->get_sparse_feature_vector(i);
SG_SPRINT("sparse vector at %i: ", i);
for (index_t j=0; j<num_features; ++j)
SG_SPRINT("%f, ", vec.features[j].entry);
SG_SPRINT("]\n");
subset_copy->free_sparse_feature_vector(i);
}
/* test if all elements are copied correctly */
for (index_t i=0; i<subset_copy->get_num_vectors(); ++i)
{
SGSparseVector<float64_t> vec=subset_copy->get_sparse_feature_vector(i);
index_t ind=i+offset_copy+offset_subset+1;
for (index_t j=0; j<vec.num_feat_entries; ++j)
{
float64_t a_entry=vec.features[j].entry;
float64_t b_entry=data.sparse_matrix[ind].features[j].entry;
index_t a_idx=vec.features[j].feat_index;
index_t b_idx=data.sparse_matrix[ind].features[j].feat_index;
ASSERT(a_entry==b_entry);
ASSERT(a_idx==b_idx);
}
subset_copy->free_sparse_feature_vector(i);
}
SG_UNREF(f);
SG_UNREF(subset_copy);
}
int main(int argc, char **argv)
{
test();
return 0;
}
| 27.753968 | 88 | 0.716614 | [
"vector"
] |
9ccbcd8055ea04de9ca79062f9193e0b96a78d86 | 1,782 | cpp | C++ | test/martin/MartinTest3.cpp | bajric/eeros | 157dcfa87f87f55bc2fec703ea2c4eb1c27a35c8 | [
"Apache-2.0"
] | null | null | null | test/martin/MartinTest3.cpp | bajric/eeros | 157dcfa87f87f55bc2fec703ea2c4eb1c27a35c8 | [
"Apache-2.0"
] | null | null | null | test/martin/MartinTest3.cpp | bajric/eeros | 157dcfa87f87f55bc2fec703ea2c4eb1c27a35c8 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <eeros/logger/Logger.hpp>
#include <eeros/logger/StreamLogWriter.hpp>
#include <eeros/math/CoordinateSystem.hpp>
#include <eeros/math/Frame.hpp>
#include <eeros/safety/SafetyProperties.hpp>
using namespace eeros::logger;
using namespace eeros::math;
class SafetyProp : public eeros::safety::SafetyProperties {
public:
enum { off = 0, temp = 10 };
enum { doSomething };
SafetyProp() {
levels = {
{ off, "OFF" } ,
{ temp, "TEMP" }
};
level(off).addEvent(doSomething, temp, eeros::safety::kPublicEvent);
}
};
int main() {
// Create and initialize logger
StreamLogWriter w(std::cout);
Logger<LogWriter>::setDefaultWriter(&w);
Logger<LogWriter> log;
log.info() << "Martin Test 3 started...";
int i = -1;
unsigned int u = 5;
float f = 1.23456789;
double d = 2 * f;
char z = 'z';
std::string s("Hello World");
Matrix<4, 1, int> v; v << 1, 2, 3, 4;
Matrix<3, 3, int> m; m << 1, 4, 7,
2, 5, 8,
3, 6, 9;
CoordinateSystem a("a");
CoordinateSystem b("b");
CoordinateSystem c("c");
Frame fab(a, b);
Frame fba(b, a);
Frame fac(a, c);
Frame fbc(b, c);
std::cout << v << std::endl;
std::cout << m << std::endl;
log.info() << "Integer: " << i;
log.info() << "Unsigned Integer: " << u;
log.info() << "Float: " << f;
log.info() << "Double: " << d;
log.info() << "Char: " << z;
log.info() << "String: " << s;
// log.info() << "Vector: " << v; // not yet implemented
// log.info() << "Matrix 4x4: " << m;
if(Frame::getFrame(a, b) == nullptr) log.error() << "Error: Frame(a, b) not found!";
SafetyProp sp;
log.info() << "Martin Test 3 finished...";
}
| 24.410959 | 85 | 0.549383 | [
"vector"
] |
9ccd554c3c162f4527b5caf3a2387388859349e6 | 4,740 | cxx | C++ | Examples/Statistics/PointSetToAdaptor.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | 2 | 2019-09-15T10:17:06.000Z | 2019-09-15T10:19:06.000Z | Examples/Statistics/PointSetToAdaptor.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | null | null | null | Examples/Statistics/PointSetToAdaptor.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | 1 | 2021-09-23T08:33:37.000Z | 2021-09-23T08:33:37.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.
*
*=========================================================================*/
// Software Guide : BeginLatex
//
// We will describe how to use \doxygen{PointSet} as a \code{Sample}
// using an adaptor in this example.
//
// \index{itk::Sample!PointSetToListSampleAdaptor}
//
// \subdoxygen{Statistics}{PointSetToListSampleAdaptor} class requires the type
// of input \doxygen{PointSet} object. The \doxygen{PointSet} class is an
// associative data container. Each point in a \code{PointSet} object can have
// its associated data value (optional). For the statistics subsystem, current
// implementation of \code{PointSetToListSampleAdaptor} takes only the point part
// into consideration. In other words, the measurement vectors from a
// \code{PointSetToListSampleAdaptor} object are points from the \code{PointSet}
// object that is plugged-into the adaptor object.
//
// To use, an \doxygen{PointSetToListSampleAdaptor} object, we include the
// header file for the class.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "itkPointSetToListSampleAdaptor.h"
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Since, we are using an adaptor, we also include the header file for
// the \doxygen{PointSet} class.
//
// Software Guide :EndLatex
// Software Guide : BeginCodeSnippet
#include "itkPointSet.h"
// Software Guide : EndCodeSnippet
int
main()
{
// Software Guide : BeginLatex
//
// We assume you already know how to create an \doxygen{PointSet} object. The
// following code snippet will create a 2D image of float pixels filled
// with random values.
//
// Software Guide :EndLatex
// Software Guide : BeginCodeSnippet
using FloatPointSet2DType = itk::PointSet<float, 2>;
itk::RandomPointSetSource<FloatPointSet2DType>::Pointer random;
random = itk::RandomPointSetSource<FloatPointSet2DType>::New();
random->SetMin(0.0);
random->SetMax(1000.0);
unsigned long size[2] = { 20, 20 };
random->SetSize(size);
float spacing[2] = { 0.7, 2.1 };
random->SetSpacing(spacing);
float origin[2] = { 15, 400 };
random->SetOrigin(origin);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We now have an \doxygen{PointSet} object and need to cast it to an
// \doxygen{PointSet} object with array type (anything derived from
// the \doxygen{FixedArray} class) pixels.
//
// Since, the \doxygen{PointSet} object's pixel type is \code{float},
// We will use single element \code{float} \doxygen{FixedArray}
// as our measurement vector type. And that will also be our pixel
// type for the cast filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using MeasurementVectorType = itk::FixedArray<float, 1>;
using ArrayPointSetType = itk::PointSet<MeasurementVectorType, 2>;
using CasterType =
itk::ScalarToArrayCastPointSetFilter<FloatPointSet2DType, ArrayPointSetType>;
CasterType::Pointer caster = CasterType::New();
caster->SetInput(random->GetOutput());
caster->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Up to now, we spend most of time to prepare an \doxygen{PointSet} object
// suitable for the adaptor. Actually, the hard part of this example is
// done. Now, we must define an adaptor with the image type and
// instantiate an object.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
using SampleType = itk::Statistics::PointSetToListSampleAdaptor<ArrayPointSetType>;
SampleType::Pointer sample = SampleType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The final thing we have to is to plug-in the image object to the adaptor.
// After that, we can use the common methods and iterator interfaces
// shown in \ref{sec:SampleInterface}.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
sample->SetPointSet(caster->GetOutput());
// Software Guide : EndCodeSnippet
return EXIT_SUCCESS;
}
| 35.111111 | 85 | 0.702321 | [
"object",
"vector"
] |
9ccfa829345372523e1f3970f755b0ec9215b150 | 3,892 | cc | C++ | test/extensions/wasm/wasm_speed_test.cc | JimmyCYJ/envoy-wasm | 25e3aae35b83d2a382983c6cacdd79ff1e27b3f7 | [
"Apache-2.0"
] | 1 | 2021-01-07T10:58:06.000Z | 2021-01-07T10:58:06.000Z | test/extensions/wasm/wasm_speed_test.cc | yangminzhu/envoy-wasm | 9cf22b854ed48b8d62bf480c6a2730fa958740de | [
"Apache-2.0"
] | null | null | null | test/extensions/wasm/wasm_speed_test.cc | yangminzhu/envoy-wasm | 9cf22b854ed48b8d62bf480c6a2730fa958740de | [
"Apache-2.0"
] | null | null | null | /**
* Simple WASM speed test.
*
* Run with:
* TEST_SRCDIR=`pwd` TEST_WORKSPACE=bazel-$(basename `pwd`) bazel run --define wasm=enabled
* --config=libc++ -c opt //test/extensions/wasm:wasm_speed_test
* Note: "--linkopt -fuse-ld=ldd" may be required as well depending on the build environment.
*/
#include <stdio.h>
#include "common/event/dispatcher_impl.h"
#include "common/stats/isolated_store_impl.h"
#include "extensions/common/wasm/wasm.h"
#include "test/mocks/server/mocks.h"
#include "test/mocks/upstream/mocks.h"
#include "test/test_common/environment.h"
#include "test/test_common/utility.h"
#include "absl/types/optional.h"
#include "benchmark/benchmark.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "tools/cpp/runfiles/runfiles.h"
using bazel::tools::cpp::runfiles::Runfiles;
using testing::Eq;
namespace Envoy {
namespace Extensions {
namespace Wasm {
class TestRoot : public Envoy::Extensions::Common::Wasm::Context {
public:
TestRoot() {}
void scriptLog(spdlog::level::level_enum level, absl::string_view message) override {
scriptLog_(level, message);
}
MOCK_METHOD2(scriptLog_, void(spdlog::level::level_enum level, absl::string_view message));
};
static void BM_WasmSimpleCallSpeedTest(benchmark::State& state, std::string vm) {
Envoy::Logger::Registry::getLog(Logger::Id::wasm).set_level(spdlog::level::off);
Stats::IsolatedStoreImpl stats_store;
Api::ApiPtr api = Api::createApiForTest(stats_store);
Upstream::MockClusterManager cluster_manager;
Event::DispatcherPtr dispatcher(api->allocateDispatcher());
auto scope = Stats::ScopeSharedPtr(stats_store.createScope("wasm."));
NiceMock<LocalInfo::MockLocalInfo> local_info;
auto root_context = new TestRoot();
auto name = "";
auto root_id = "";
auto vm_id = "";
auto vm_configuration = "";
auto plugin = std::make_shared<Extensions::Common::Wasm::Plugin>(
name, root_id, vm_id, envoy::api::v2::core::TrafficDirection::UNSPECIFIED, local_info,
nullptr);
auto wasm = std::make_unique<Extensions::Common::Wasm::Wasm>(
absl::StrCat("envoy.wasm.runtime.", vm), vm_id, vm_configuration, scope, cluster_manager,
*dispatcher);
std::string code;
if (vm == "null") {
code = "null_vm_plugin";
} else {
code = TestEnvironment::readFileToStringForTest(
TestEnvironment::runfilesPath("test/extensions/wasm/test_data/speed_cpp.wasm"));
}
EXPECT_FALSE(code.empty());
EXPECT_TRUE(wasm->initialize(code, false));
wasm->setContext(root_context);
wasm->startForTesting(std::unique_ptr<Common::Wasm::Context>(root_context), plugin);
EXPECT_NE(wasm, nullptr);
for (auto _ : state) {
wasm->tickHandler(root_context->id());
}
}
BENCHMARK_CAPTURE(BM_WasmSimpleCallSpeedTest, V8SpeedTest, std::string("v8"));
#if defined(ENVOY_WASM_WAVM)
BENCHMARK_CAPTURE(BM_WasmSimpleCallSpeedTest, WavmSpeedTest, std::string("wavm"));
#endif
BENCHMARK_CAPTURE(BM_WasmSimpleCallSpeedTest, NullSpeedTest, std::string("null"));
} // namespace Wasm
} // namespace Extensions
} // namespace Envoy
int main(int argc, char** argv) {
::benchmark::Initialize(&argc, argv);
Envoy::TestEnvironment::initializeOptions(argc, argv);
// Create a Runfiles object for runfiles lookup.
// https://github.com/bazelbuild/bazel/blob/master/tools/cpp/runfiles/runfiles_src.h#L32
std::string error;
std::unique_ptr<Runfiles> runfiles(Runfiles::Create(argv[0], &error));
RELEASE_ASSERT(Envoy::TestEnvironment::getOptionalEnvVar("NORUNFILES").has_value() ||
runfiles != nullptr,
error);
Envoy::TestEnvironment::setRunfiles(runfiles.get());
Envoy::TestEnvironment::setEnvVar("ENVOY_IP_TEST_VERSIONS", "all", 0);
Envoy::Event::Libevent::Global::initialize();
if (::benchmark::ReportUnrecognizedArguments(argc, argv)) {
return 1;
}
::benchmark::RunSpecifiedBenchmarks();
return 0;
}
| 35.706422 | 95 | 0.725591 | [
"object"
] |
9cd0ee9d13bc819dc1d05511badac75b7f6389ec | 19,882 | cpp | C++ | src/esp/metadata/managers/StageAttributesManager.cpp | narekvslife/habitat-sim | 69ae4848503d5dcc74d6b5920957c1a641ef0a9b | [
"MIT"
] | 1 | 2020-08-05T22:25:02.000Z | 2020-08-05T22:25:02.000Z | src/esp/metadata/managers/StageAttributesManager.cpp | narekvslife/habitat-sim | 69ae4848503d5dcc74d6b5920957c1a641ef0a9b | [
"MIT"
] | null | null | null | src/esp/metadata/managers/StageAttributesManager.cpp | narekvslife/habitat-sim | 69ae4848503d5dcc74d6b5920957c1a641ef0a9b | [
"MIT"
] | null | null | null | // Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include <Corrade/Utility/String.h>
#include <utility>
#include "AbstractObjectAttributesManagerBase.h"
#include "StageAttributesManager.h"
#include "esp/assets/Asset.h"
#include "esp/assets/ResourceManager.h"
#include "esp/io/Io.h"
#include "esp/io/Json.h"
namespace esp {
using assets::AssetType;
using core::managedContainers::ManagedObjectAccess;
namespace metadata {
using attributes::AbstractObjectAttributes;
using attributes::StageAttributes;
namespace managers {
StageAttributesManager::StageAttributesManager(
ObjectAttributesManager::ptr objectAttributesMgr,
PhysicsAttributesManager::ptr physicsAttributesManager)
: AbstractObjectAttributesManager<StageAttributes,
ManagedObjectAccess::Copy>::
AbstractObjectAttributesManager("Stage", "stage_config.json"),
objectAttributesMgr_(std::move(objectAttributesMgr)),
physicsAttributesManager_(std::move(physicsAttributesManager)),
cfgLightSetup_(NO_LIGHT_KEY) {
// build this manager's copy constructor map
this->copyConstructorMap_["StageAttributes"] =
&StageAttributesManager::createObjectCopy<attributes::StageAttributes>;
// create none-type stage attributes and set as undeletable
// based on default
auto tmplt = this->postCreateRegister(
StageAttributesManager::initNewObjectInternal("NONE", false), true);
std::string tmpltHandle = tmplt->getHandle();
this->undeletableObjectNames_.insert(tmpltHandle);
} // StageAttributesManager::ctor
int StageAttributesManager::registerObjectFinalize(
StageAttributes::ptr stageAttributes,
const std::string& stageAttributesHandle,
bool forceRegistration) {
if (stageAttributes->getRenderAssetHandle() == "") {
ESP_ERROR()
<< "Attributes template named" << stageAttributesHandle
<< "does not have a valid render asset handle specified. Aborting.";
return ID_UNDEFINED;
}
// Handles for rendering and collision assets
std::string renderAssetHandle = stageAttributes->getRenderAssetHandle();
std::string collisionAssetHandle = stageAttributes->getCollisionAssetHandle();
// verify these represent legitimate assets
if (StageAttributesManager::isValidPrimitiveAttributes(renderAssetHandle)) {
// If renderAssetHandle corresponds to valid/existing primitive attributes
// then setRenderAssetIsPrimitive to true and set map of IDs->Names to
// physicsSynthObjTmpltLibByID_
stageAttributes->setRenderAssetIsPrimitive(true);
} else if (Cr::Utility::Directory::exists(renderAssetHandle)) {
// Check if renderAssetHandle is valid file name and is found in file
// system
// - if so then setRenderAssetIsPrimitive to false and set map of
// IDs->Names to physicsFileObjTmpltLibByID_ - verify file exists
stageAttributes->setRenderAssetIsPrimitive(false);
} else if (std::string::npos != stageAttributesHandle.find("NONE")) {
// Render asset handle will be NONE as well - force type to be unknown
stageAttributes->setRenderAssetType(static_cast<int>(AssetType::UNKNOWN));
stageAttributes->setRenderAssetIsPrimitive(false);
} else if (forceRegistration) {
ESP_WARNING()
<< "Render asset template handle :" << renderAssetHandle
<< "specified in stage template with handle :" << stageAttributesHandle
<< "does not correspond to any existing file or primitive render "
"asset. This attributes is not in a valid state.";
} else {
// If renderAssetHandle is not valid file name needs to fail
ESP_ERROR()
<< "Render asset template handle :" << renderAssetHandle
<< "specified in stage template with handle :" << stageAttributesHandle
<< "does not correspond to any existing file or primitive render "
"asset. Aborting.";
return ID_UNDEFINED;
}
if (StageAttributesManager::isValidPrimitiveAttributes(
collisionAssetHandle)) {
// If collisionAssetHandle corresponds to valid/existing primitive
// attributes then setCollisionAssetIsPrimitive to true
stageAttributes->setCollisionAssetIsPrimitive(true);
} else if (Cr::Utility::Directory::exists(collisionAssetHandle)) {
// Check if collisionAssetHandle is valid file name and is found in file
// system - if so then setCollisionAssetIsPrimitive to false
stageAttributes->setCollisionAssetIsPrimitive(false);
} else if (std::string::npos != stageAttributesHandle.find("NONE")) {
// Collision asset handle will be NONE as well - force type to be unknown
stageAttributes->setCollisionAssetType(
static_cast<int>(AssetType::UNKNOWN));
stageAttributes->setCollisionAssetIsPrimitive(false);
} else {
// Else, means no collision data specified, use specified render data
ESP_DEBUG()
<< "Collision asset template handle :" << collisionAssetHandle
<< "specified in stage template with handle :" << stageAttributesHandle
<< "does not correspond to any existing file or primitive render "
"asset. Overriding with given render asset handle :"
<< renderAssetHandle << ".";
stageAttributes->setCollisionAssetHandle(renderAssetHandle);
stageAttributes->setCollisionAssetIsPrimitive(
stageAttributes->getRenderAssetIsPrimitive());
}
// Clear dirty flag from when asset handles are changed
stageAttributes->setIsClean();
// adds template to library, and returns either the ID of the existing
// template referenced by stageAttributesHandle, or the next available ID
// if not found.
int stageTemplateID =
this->addObjectToLibrary(stageAttributes, stageAttributesHandle);
return stageTemplateID;
} // StageAttributesManager::registerAttributesTemplate
StageAttributes::ptr StageAttributesManager::createPrimBasedAttributesTemplate(
const std::string& primAssetHandle,
bool registerTemplate) {
// verify that a primitive asset with the given handle exists
if (!StageAttributesManager::isValidPrimitiveAttributes(primAssetHandle)) {
ESP_ERROR(Mn::Debug::Flag::NoSpace)
<< "No primitive with handle '" << primAssetHandle
<< "' exists so cannot build physical object. Aborting.";
return nullptr;
}
// construct a stageAttributes
auto stageAttributes = initNewObjectInternal(primAssetHandle, false);
// set margin to be 0
stageAttributes->setMargin(0.0);
// set render mesh handle
int primType = static_cast<int>(AssetType::PRIMITIVE);
stageAttributes->setRenderAssetType(primType);
// set collision mesh/primitive handle and default for primitives to not use
// mesh collisions
stageAttributes->setCollisionAssetType(primType);
stageAttributes->setUseMeshCollision(false);
// NOTE to eventually use mesh collisions with primitive objects, a
// collision primitive mesh needs to be configured and set in MeshMetaData
// and CollisionMesh
return this->postCreateRegister(stageAttributes, registerTemplate);
} // StageAttributesManager::createPrimBasedAttributesTemplate
StageAttributes::ptr StageAttributesManager::initNewObjectInternal(
const std::string& attributesHandle,
bool builtFromConfig) {
// If default template exists from some source, create this template as a
// copy
StageAttributes::ptr newAttributes =
this->constructFromDefault(attributesHandle);
bool createNewAttributes = (nullptr == newAttributes);
if (createNewAttributes) {
newAttributes = StageAttributes::create(attributesHandle);
}
// set the attributes source filedirectory, from the attributes name
this->setFileDirectoryFromHandle(newAttributes);
if (!createNewAttributes) {
// default exists and was used to create this attributes - investigate any
// filename fields that may have %%USE_FILENAME%% directive specified in the
// default attributes.
// Render asset handle
setHandleFromDefaultTag(newAttributes,
newAttributes->getRenderAssetHandle(),
[newAttributes](const std::string& newHandle) {
newAttributes->setRenderAssetHandle(newHandle);
});
// Collision asset handle
setHandleFromDefaultTag(newAttributes,
newAttributes->getCollisionAssetHandle(),
[newAttributes](const std::string& newHandle) {
newAttributes->setCollisionAssetHandle(newHandle);
});
// navmesh asset handle
setHandleFromDefaultTag(newAttributes,
newAttributes->getNavmeshAssetHandle(),
[newAttributes](const std::string& newHandle) {
newAttributes->setNavmeshAssetHandle(newHandle);
});
// Semantic Scene Descriptor text filehandle
setHandleFromDefaultTag(
newAttributes, newAttributes->getSemanticDescriptorFilename(),
[newAttributes](const std::string& newHandle) {
newAttributes->setSemanticDescriptorFilename(newHandle);
});
// Semantic Scene asset handle
setHandleFromDefaultTag(newAttributes,
newAttributes->getSemanticAssetHandle(),
[newAttributes](const std::string& newHandle) {
newAttributes->setSemanticAssetHandle(newHandle);
});
}
// set defaults that config files or other constructive processes might
// override
// set defaults from SimulatorConfig values;
newAttributes->setLightSetupKey(cfgLightSetup_);
newAttributes->setForceFlatShading(cfgLightSetup_ == NO_LIGHT_KEY);
// set value from config so not necessary to be passed as argument
newAttributes->setFrustumCulling(cfgFrustumCulling_);
// only set handle defaults if attributesHandle is not a config file (which
// would never be a valid render or collision asset name). Otherise, expect
// handles to be set when config is read.
if (!builtFromConfig) {
if (newAttributes->getRenderAssetHandle().empty()) {
newAttributes->setRenderAssetHandle(attributesHandle);
}
if (newAttributes->getCollisionAssetHandle().empty()) {
newAttributes->setCollisionAssetHandle(attributesHandle);
}
if (attributesHandle != "NONE") {
// TODO when all datasets have configuration support, get rid of all these
// default settings
// set defaults for navmesh, semantic mesh and lexicon handles
// start with root stage name, including path but without final extension
// default navmesh should have .navmesh ext
if (newAttributes->getNavmeshAssetHandle().empty()) {
std::string navmeshFilename =
this->findFilenameUsingCriteria(attributesHandle, {".navmesh"});
// if present, file was found, so set value (overriding attributes
// default)
if (!navmeshFilename.empty()) {
newAttributes->setNavmeshAssetHandle(navmeshFilename);
}
}
if (newAttributes->getSemanticDescriptorFilename().empty()) {
// Build default semantic descriptor file name, using extensions of
std::string ssdFileName = this->findFilenameUsingCriteria(
attributesHandle, {".house", ".scn", "_semantic.txt"});
// if not present, set hacky defaults for back compat expectations.
if (ssdFileName.empty()) {
if (attributesHandle.find("/replica_dataset") != std::string::npos) {
// replica hack until dataset gets appropriate configuration support
ssdFileName = Cr::Utility::Directory::join(
newAttributes->getFileDirectory(), "info_semantic.json");
} else {
// hack to support back-compat until configs are implemented for all
// datasets
ssdFileName =
Cr::Utility::Directory::splitExtension(attributesHandle).first +
".scn";
}
}
newAttributes->setSemanticDescriptorFilename(ssdFileName);
}
if (newAttributes->getSemanticAssetHandle().empty()) {
// Build default semantic mesh filename as root stage name ending with
// "_semantic.ply", for back-compat with Mp3d
std::string semanticMeshFilename = this->findFilenameUsingCriteria(
attributesHandle, {"_semantic.ply"});
// if present, file was found, so set value (overriding attributes
// default)
if (!semanticMeshFilename.empty()) {
newAttributes->setSemanticAssetHandle(semanticMeshFilename);
}
}
} // do not populate defaults for NONE scene
// set default origin and orientation values based on file name
// from AssetInfo::fromPath
// set defaults for passed render asset handles
StageAttributesManager::setDefaultAssetNameBasedAttributes(
newAttributes, createNewAttributes,
newAttributes->getRenderAssetHandle(), [newAttributes](auto&& PH1) {
newAttributes->setRenderAssetType(std::forward<decltype(PH1)>(PH1));
});
// set defaults for passed collision asset handles
StageAttributesManager::setDefaultAssetNameBasedAttributes(
newAttributes, false, newAttributes->getCollisionAssetHandle(),
[newAttributes](auto&& PH1) {
newAttributes->setCollisionAssetType(
std::forward<decltype(PH1)>(PH1));
});
// set defaults for passed semantic asset handles
StageAttributesManager::setDefaultAssetNameBasedAttributes(
newAttributes, false, newAttributes->getSemanticAssetHandle(),
[newAttributes](auto&& PH1) {
newAttributes->setSemanticAssetType(std::forward<decltype(PH1)>(PH1));
});
// TODO : get rid of this once the hardcoded mesh-type handling is removed,
// but for now force all semantic assets to be instance_mesh
newAttributes->setSemanticAssetType(
static_cast<int>(AssetType::INSTANCE_MESH));
}
// set default physical quantities specified in physics manager attributes
if (physicsAttributesManager_->getObjectLibHasHandle(
physicsManagerAttributesHandle_)) {
auto physMgrAttributes = physicsAttributesManager_->getObjectByHandle(
physicsManagerAttributesHandle_);
newAttributes->setGravity(physMgrAttributes->getGravity());
newAttributes->setFrictionCoefficient(
physMgrAttributes->getFrictionCoefficient());
newAttributes->setRestitutionCoefficient(
physMgrAttributes->getRestitutionCoefficient());
}
return newAttributes;
} // StageAttributesManager::initNewObjectInternal
void StageAttributesManager::setDefaultAssetNameBasedAttributes(
StageAttributes::ptr attributes,
bool setFrame,
const std::string& fileName,
const std::function<void(int)>& assetTypeSetter) {
// TODO : support future mesh-name specific type setting?
using Corrade::Utility::String::endsWith;
Magnum::Vector3 up, up1{0, 1, 0}, up2{0, 0, 1};
Magnum::Vector3 fwd, fwd1{0, 0, -1}, fwd2{0, 1, 0};
// set default origin and orientation values based on file name
// from AssetInfo::fromPath
up = up1;
fwd = fwd1;
if (endsWith(fileName, "_semantic.ply")) {
assetTypeSetter(static_cast<int>(AssetType::INSTANCE_MESH));
} else if (endsWith(fileName, "mesh.ply")) {
assetTypeSetter(static_cast<int>(AssetType::FRL_PTEX_MESH));
up = up2;
fwd = fwd2;
} else if (endsWith(fileName, ".glb")) {
// assumes MP3D glb with gravity = -Z
assetTypeSetter(static_cast<int>(AssetType::MP3D_MESH));
// Create a coordinate for the mesh by rotating the default ESP
// coordinate frame to -Z gravity
up = up2;
fwd = fwd2;
} else if (StageAttributesManager::isValidPrimitiveAttributes(fileName)) {
assetTypeSetter(static_cast<int>(AssetType::PRIMITIVE));
} else {
assetTypeSetter(static_cast<int>(AssetType::UNKNOWN));
}
if (setFrame) {
attributes->setOrientUp(up);
attributes->setOrientFront(fwd);
}
} // StageAttributesManager::setDefaultAssetNameBasedAttributes
void StageAttributesManager::setValsFromJSONDoc(
attributes::StageAttributes::ptr stageAttributes,
const io::JsonGenericValue& jsonConfig) {
this->loadAbstractObjectAttributesFromJson(stageAttributes, jsonConfig);
// directory location where stage files are found
std::string stageLocFileDir = stageAttributes->getFileDirectory();
// now parse stage-specific fields.
// load stage specific gravity
io::jsonIntoConstSetter<Magnum::Vector3>(
jsonConfig, "gravity", [stageAttributes](auto&& PH1) {
stageAttributes->setGravity(std::forward<decltype(PH1)>(PH1));
});
// load stage specific origin
io::jsonIntoConstSetter<Magnum::Vector3>(
jsonConfig, "origin", [stageAttributes](auto&& PH1) {
stageAttributes->setOrigin(std::forward<decltype(PH1)>(PH1));
});
// load stage semantic asset specific up orientation
io::jsonIntoConstSetter<Magnum::Vector3>(
jsonConfig, "semantic_up", [stageAttributes](const Magnum::Vector3& up) {
stageAttributes->setSemanticOrientUp(up);
});
// load stage semantic asset specific front orientation
io::jsonIntoConstSetter<Magnum::Vector3>(
jsonConfig, "semantic_front",
[stageAttributes](const Magnum::Vector3& front) {
stageAttributes->setSemanticOrientFront(front);
});
// populate specified semantic file name if specified in json - defaults
// are overridden only if specified in json.
std::string navmeshFName = "";
std::string semanticSceneDescriptor = "";
std::string lightSetup = "";
// populate semantic mesh type if present
std::string semanticFName = stageAttributes->getSemanticAssetHandle();
semanticFName = this->setJSONAssetHandleAndType(
stageAttributes, jsonConfig, "semantic_asset_type", "semantic_asset",
semanticFName, [stageAttributes](auto&& PH1) {
stageAttributes->setSemanticAssetType(std::forward<decltype(PH1)>(PH1));
});
// if "semantic mesh" is specified in stage json to non-empty value, set
// value (override default).
stageAttributes->setSemanticAssetHandle(semanticFName);
// TODO eventually remove this, but currently semantic mesh must be
// instance
stageAttributes->setSemanticAssetType(
static_cast<int>(AssetType::INSTANCE_MESH));
if (io::readMember<std::string>(jsonConfig, "nav_asset", navmeshFName)) {
// if "nav mesh" is specified in stage json set value (override default).
// navmesh filename might already be fully qualified; if not, might just be
// file name
if (!Corrade::Utility::Directory::exists(navmeshFName)) {
navmeshFName =
Cr::Utility::Directory::join(stageLocFileDir, navmeshFName);
}
stageAttributes->setNavmeshAssetHandle(navmeshFName);
}
if (io::readMember<std::string>(jsonConfig, "semantic_descriptor_filename",
semanticSceneDescriptor)) {
// if "semantic_descriptor_filename" is specified in stage json, set value
// (override default).
// semanticSceneDescriptor filename might already be fully qualified; if
// not, might just be file name
if (!Corrade::Utility::Directory::exists(semanticSceneDescriptor)) {
semanticSceneDescriptor = Cr::Utility::Directory::join(
stageLocFileDir, semanticSceneDescriptor);
}
stageAttributes->setSemanticDescriptorFilename(semanticSceneDescriptor);
}
// check for user defined attributes
this->parseUserDefinedJsonVals(stageAttributes, jsonConfig);
} // StageAttributesManager::setValsFromJSONDoc
} // namespace managers
} // namespace metadata
} // namespace esp
| 43.986726 | 80 | 0.707273 | [
"mesh",
"render",
"object"
] |
9cd160f91446b804b7cb86a11f4449feadd214f8 | 14,984 | cpp | C++ | src/CppParser/Bindings/CLI/Target.cpp | SonyaSa/CppSharp | 784a939c66f0cf170d89334b36c95f4888decff8 | [
"MIT"
] | null | null | null | src/CppParser/Bindings/CLI/Target.cpp | SonyaSa/CppSharp | 784a939c66f0cf170d89334b36c95f4888decff8 | [
"MIT"
] | null | null | null | src/CppParser/Bindings/CLI/Target.cpp | SonyaSa/CppSharp | 784a939c66f0cf170d89334b36c95f4888decff8 | [
"MIT"
] | null | null | null | #include "Target.h"
using namespace System;
using namespace System::Runtime::InteropServices;
CppSharp::Parser::ParserTargetInfo::ParserTargetInfo(::CppSharp::CppParser::ParserTargetInfo* native)
: __ownsNativeInstance(false)
{
NativePtr = native;
}
CppSharp::Parser::ParserTargetInfo^ CppSharp::Parser::ParserTargetInfo::__CreateInstance(::System::IntPtr native)
{
return ::CppSharp::Parser::ParserTargetInfo::__CreateInstance(native, false);
}
CppSharp::Parser::ParserTargetInfo^ CppSharp::Parser::ParserTargetInfo::__CreateInstance(::System::IntPtr native, bool __ownsNativeInstance)
{
::CppSharp::Parser::ParserTargetInfo^ result = gcnew ::CppSharp::Parser::ParserTargetInfo((::CppSharp::CppParser::ParserTargetInfo*) native.ToPointer());
result->__ownsNativeInstance = __ownsNativeInstance;
return result;
}
CppSharp::Parser::ParserTargetInfo::~ParserTargetInfo()
{
if (__ownsNativeInstance)
delete NativePtr;
}
CppSharp::Parser::ParserTargetInfo::ParserTargetInfo()
{
__ownsNativeInstance = true;
NativePtr = new ::CppSharp::CppParser::ParserTargetInfo();
}
CppSharp::Parser::ParserTargetInfo::ParserTargetInfo(CppSharp::Parser::ParserTargetInfo^ _0)
{
__ownsNativeInstance = true;
auto &arg0 = *(::CppSharp::CppParser::ParserTargetInfo*)_0->NativePtr;
NativePtr = new ::CppSharp::CppParser::ParserTargetInfo(arg0);
}
System::IntPtr CppSharp::Parser::ParserTargetInfo::__Instance::get()
{
return System::IntPtr(NativePtr);
}
void CppSharp::Parser::ParserTargetInfo::__Instance::set(System::IntPtr object)
{
NativePtr = (::CppSharp::CppParser::ParserTargetInfo*)object.ToPointer();
}
System::String^ CppSharp::Parser::ParserTargetInfo::ABI::get()
{
auto __ret = ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->getABI();
if (__ret == nullptr) return nullptr;
return clix::marshalString<clix::E_UTF8>(__ret);
}
void CppSharp::Parser::ParserTargetInfo::ABI::set(System::String^ s)
{
auto _arg0 = clix::marshalString<clix::E_UTF8>(s);
auto arg0 = _arg0.c_str();
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->setABI(arg0);
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::Char16Type::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char16Type;
}
void CppSharp::Parser::ParserTargetInfo::Char16Type::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char16Type = (::CppSharp::CppParser::ParserIntType)value;
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::Char32Type::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char32Type;
}
void CppSharp::Parser::ParserTargetInfo::Char32Type::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char32Type = (::CppSharp::CppParser::ParserIntType)value;
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::Int64Type::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Int64Type;
}
void CppSharp::Parser::ParserTargetInfo::Int64Type::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Int64Type = (::CppSharp::CppParser::ParserIntType)value;
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::IntMaxType::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntMaxType;
}
void CppSharp::Parser::ParserTargetInfo::IntMaxType::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntMaxType = (::CppSharp::CppParser::ParserIntType)value;
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::IntPtrType::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntPtrType;
}
void CppSharp::Parser::ParserTargetInfo::IntPtrType::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntPtrType = (::CppSharp::CppParser::ParserIntType)value;
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::SizeType::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->SizeType;
}
void CppSharp::Parser::ParserTargetInfo::SizeType::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->SizeType = (::CppSharp::CppParser::ParserIntType)value;
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::UIntMaxType::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->UIntMaxType;
}
void CppSharp::Parser::ParserTargetInfo::UIntMaxType::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->UIntMaxType = (::CppSharp::CppParser::ParserIntType)value;
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::WCharType::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->WCharType;
}
void CppSharp::Parser::ParserTargetInfo::WCharType::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->WCharType = (::CppSharp::CppParser::ParserIntType)value;
}
CppSharp::Parser::ParserIntType CppSharp::Parser::ParserTargetInfo::WIntType::get()
{
return (CppSharp::Parser::ParserIntType)((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->WIntType;
}
void CppSharp::Parser::ParserTargetInfo::WIntType::set(CppSharp::Parser::ParserIntType value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->WIntType = (::CppSharp::CppParser::ParserIntType)value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::BoolAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->BoolAlign;
}
void CppSharp::Parser::ParserTargetInfo::BoolAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->BoolAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::BoolWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->BoolWidth;
}
void CppSharp::Parser::ParserTargetInfo::BoolWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->BoolWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::CharAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->CharAlign;
}
void CppSharp::Parser::ParserTargetInfo::CharAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->CharAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::CharWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->CharWidth;
}
void CppSharp::Parser::ParserTargetInfo::CharWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->CharWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::Char16Align::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char16Align;
}
void CppSharp::Parser::ParserTargetInfo::Char16Align::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char16Align = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::Char16Width::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char16Width;
}
void CppSharp::Parser::ParserTargetInfo::Char16Width::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char16Width = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::Char32Align::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char32Align;
}
void CppSharp::Parser::ParserTargetInfo::Char32Align::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char32Align = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::Char32Width::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char32Width;
}
void CppSharp::Parser::ParserTargetInfo::Char32Width::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->Char32Width = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::HalfAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->HalfAlign;
}
void CppSharp::Parser::ParserTargetInfo::HalfAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->HalfAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::HalfWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->HalfWidth;
}
void CppSharp::Parser::ParserTargetInfo::HalfWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->HalfWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::FloatAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->FloatAlign;
}
void CppSharp::Parser::ParserTargetInfo::FloatAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->FloatAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::FloatWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->FloatWidth;
}
void CppSharp::Parser::ParserTargetInfo::FloatWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->FloatWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::DoubleAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->DoubleAlign;
}
void CppSharp::Parser::ParserTargetInfo::DoubleAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->DoubleAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::DoubleWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->DoubleWidth;
}
void CppSharp::Parser::ParserTargetInfo::DoubleWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->DoubleWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::ShortAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->ShortAlign;
}
void CppSharp::Parser::ParserTargetInfo::ShortAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->ShortAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::ShortWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->ShortWidth;
}
void CppSharp::Parser::ParserTargetInfo::ShortWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->ShortWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::IntAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntAlign;
}
void CppSharp::Parser::ParserTargetInfo::IntAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::IntWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntWidth;
}
void CppSharp::Parser::ParserTargetInfo::IntWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::IntMaxTWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntMaxTWidth;
}
void CppSharp::Parser::ParserTargetInfo::IntMaxTWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->IntMaxTWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::LongAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongAlign;
}
void CppSharp::Parser::ParserTargetInfo::LongAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::LongWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongWidth;
}
void CppSharp::Parser::ParserTargetInfo::LongWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::LongDoubleAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongDoubleAlign;
}
void CppSharp::Parser::ParserTargetInfo::LongDoubleAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongDoubleAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::LongDoubleWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongDoubleWidth;
}
void CppSharp::Parser::ParserTargetInfo::LongDoubleWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongDoubleWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::LongLongAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongLongAlign;
}
void CppSharp::Parser::ParserTargetInfo::LongLongAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongLongAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::LongLongWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongLongWidth;
}
void CppSharp::Parser::ParserTargetInfo::LongLongWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->LongLongWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::PointerAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->PointerAlign;
}
void CppSharp::Parser::ParserTargetInfo::PointerAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->PointerAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::PointerWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->PointerWidth;
}
void CppSharp::Parser::ParserTargetInfo::PointerWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->PointerWidth = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::WCharAlign::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->WCharAlign;
}
void CppSharp::Parser::ParserTargetInfo::WCharAlign::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->WCharAlign = value;
}
unsigned int CppSharp::Parser::ParserTargetInfo::WCharWidth::get()
{
return ((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->WCharWidth;
}
void CppSharp::Parser::ParserTargetInfo::WCharWidth::set(unsigned int value)
{
((::CppSharp::CppParser::ParserTargetInfo*)NativePtr)->WCharWidth = value;
}
| 33.521253 | 157 | 0.750734 | [
"object"
] |
9cd52ef50f60fb4431f8d7e2f304e48ee97d25c5 | 652 | cpp | C++ | test/src/box/test_sbgp.cpp | steinwurf/petro | d06485f0c1748c425d5f30444638883e62aedf62 | [
"BSD-3-Clause"
] | 3 | 2017-08-24T14:14:53.000Z | 2018-05-14T02:48:16.000Z | test/src/box/test_sbgp.cpp | steinwurf/petro | d06485f0c1748c425d5f30444638883e62aedf62 | [
"BSD-3-Clause"
] | 10 | 2016-06-17T07:10:25.000Z | 2021-12-14T13:37:29.000Z | test/src/box/test_sbgp.cpp | steinwurf/petro | d06485f0c1748c425d5f30444638883e62aedf62 | [
"BSD-3-Clause"
] | 3 | 2017-06-12T19:22:27.000Z | 2019-01-03T19:18:24.000Z | // Copyright (c) Steinwurf ApS 2016.
// All Rights Reserved
//
// Distributed under the "BSD License". See the accompanying LICENSE.rst file.
#include <petro/box/data_box.hpp>
#include <petro/box/sbgp.hpp>
#include <gtest/gtest.h>
#include <cstdint>
#include <memory>
#include <system_error>
#include <vector>
TEST(box_test_sbgp, construct)
{
std::vector<uint8_t> buffer = {0x00, 0x00, 0x00, 0x00, 's', 'b', 'g', 'p'};
auto sbgp_box =
std::make_shared<petro::box::sbgp>(buffer.data(), buffer.size());
std::error_code error;
sbgp_box->parse(error);
ASSERT_FALSE(bool(error));
EXPECT_EQ("sbgp", sbgp_box->type());
}
| 23.285714 | 79 | 0.670245 | [
"vector"
] |
9cd7ab291e3fca3b6d1b459d55718fbafef0642f | 3,211 | cpp | C++ | src/tests/collision/collision.cpp | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 522 | 2020-01-19T05:59:00.000Z | 2022-03-25T04:36:52.000Z | src/tests/collision/collision.cpp | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 87 | 2020-02-23T09:56:48.000Z | 2022-03-25T13:35:15.000Z | src/tests/collision/collision.cpp | collector-m/cupoch | 1b2bb3f806695b93d6d0dd87855cf2a4da8d1ce1 | [
"MIT"
] | 74 | 2020-01-27T15:33:30.000Z | 2022-03-27T11:58:22.000Z | /**
* Copyright (c) 2020 Neka-Nat
* 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 "cupoch/collision/collision.h"
#include "cupoch/geometry/voxelgrid.h"
#include "cupoch/geometry/lineset.h"
#include "tests/test_utility/raw.h"
#include "tests/test_utility/unit_test.h"
using namespace Eigen;
using namespace cupoch;
using namespace std;
using namespace unit_test;
TEST(Collision, VoxelVoxel) {
geometry::VoxelGrid voxel1;
geometry::VoxelGrid voxel2;
auto res1 = collision::ComputeIntersection(voxel1, voxel2);
EXPECT_FALSE(res1->IsCollided());
voxel1.voxel_size_ = 1.0;
voxel2.voxel_size_ = 1.0;
voxel1.AddVoxel(geometry::Voxel(Eigen::Vector3i(0, 0, 0)));
voxel2.AddVoxel(geometry::Voxel(Eigen::Vector3i(0, 0, 0)));
auto res2 = collision::ComputeIntersection(voxel1, voxel2);
EXPECT_TRUE(res2->IsCollided());
voxel1.AddVoxel(geometry::Voxel(Eigen::Vector3i(5, 0, 0)));
voxel2.AddVoxel(geometry::Voxel(Eigen::Vector3i(10, 0, 0)));
auto res3 = collision::ComputeIntersection(voxel1, voxel2);
EXPECT_EQ(res3->collision_index_pairs_.size(), 1);
EXPECT_EQ(res3->GetCollisionIndexPairs()[0], Eigen::Vector2i(0, 0));
}
TEST(Collision, VoxelLineSet) {
geometry::VoxelGrid voxel;
geometry::LineSet<3> lineset;
auto res1 = collision::ComputeIntersection(voxel, lineset);
EXPECT_FALSE(res1->IsCollided());
voxel.voxel_size_ = 1.0;
voxel.AddVoxel(geometry::Voxel(Eigen::Vector3i(0, 0, 0)));
voxel.AddVoxel(geometry::Voxel(Eigen::Vector3i(5, 0, 0)));
thrust::host_vector<Eigen::Vector3f> points;
points.push_back(Eigen::Vector3f(-0.1, -0.1, -0.1));
points.push_back(Eigen::Vector3f(-0.1, -0.1, 1.1));
points.push_back(Eigen::Vector3f(1.1, 1.1, 1.1));
thrust::host_vector<Eigen::Vector2i> lines;
lines.push_back(Eigen::Vector2i(0, 1));
lines.push_back(Eigen::Vector2i(0, 2));
lineset.SetPoints(points);
lineset.SetLines(lines);
auto res2 = collision::ComputeIntersection(voxel, lineset);
EXPECT_TRUE(res2->IsCollided());
EXPECT_EQ(res2->collision_index_pairs_.size(), 1);
EXPECT_EQ(res2->GetCollisionIndexPairs()[0], Eigen::Vector2i(0, 1));
} | 43.986301 | 80 | 0.725319 | [
"geometry"
] |
9cd7fcfc9992c9840851877b0a13e22940af78cb | 7,457 | cc | C++ | CalibMuon/RPCCalibration/src/RPCCalibSetUp.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-08-09T08:42:11.000Z | 2019-08-09T08:42:11.000Z | CalibMuon/RPCCalibration/src/RPCCalibSetUp.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | null | null | null | CalibMuon/RPCCalibration/src/RPCCalibSetUp.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 1 | 2019-04-03T19:23:27.000Z | 2019-04-03T19:23:27.000Z | #include "FWCore/Framework/interface/EDProducer.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "Geometry/Records/interface/MuonGeometryRecord.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "CalibMuon/RPCCalibration/interface/RPCCalibSetUp.h"
#include "DataFormats/MuonDetId/interface/RPCDetId.h"
#include <cmath>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iostream>
#include<cstring>
#include<string>
#include<vector>
#include<cstdlib>
#include <utility>
#include <map>
using namespace std;
RPCCalibSetUp::RPCCalibSetUp(const edm::ParameterSet& ps) {
_mapDetIdNoise.clear();
_mapDetIdEff.clear();
_bxmap.clear();
_mapDetClsMap.clear();
//------------------------ Noise Reading ----------------------------
edm::FileInPath fp1 = ps.getParameter<edm::FileInPath>("noisemapfile");
std::ifstream _infile1(fp1.fullPath().c_str(), std::ios::in);
std::vector<float> vnoise;
int rpcdetid = 0;
std::string buff;
std::vector< std::string > words;
int count = 0;
while( getline(_infile1, buff, '\n') ){
words.clear();
vnoise.clear();
stringstream ss;
std::string chname;
ss<<buff;
ss>>chname>>rpcdetid;
std::string::size_type pos = 0, prev_pos = 0;
while ( (pos = buff.find(" ",pos)) != string::npos){
words.push_back(buff.substr(prev_pos, pos - prev_pos));
prev_pos = ++pos;
}
words.push_back(buff.substr(prev_pos, pos - prev_pos));
for(unsigned int i = 2; i < words.size(); ++i){
float value = atof( ((words)[i]).c_str() );
vnoise.push_back(value);
}
_mapDetIdNoise.insert(make_pair(static_cast<uint32_t>(rpcdetid),vnoise));
count++;
}
_infile1.close();
//------------------------ Eff Reading ----------------------------
edm::FileInPath fp2 = ps.getParameter<edm::FileInPath>("effmapfile");
std::ifstream _infile2(fp2.fullPath().c_str(), std::ios::in);
std::vector<float> veff ;
rpcdetid = 0;
while( getline(_infile2, buff, '\n') ){
words.clear();
veff.clear();
stringstream ss;
std::string chname;
ss<<buff;
ss>>chname>>rpcdetid;
std::string::size_type pos = 0, prev_pos = 0;
while ( (pos = buff.find(" ",pos)) != string::npos){
words.push_back(buff.substr(prev_pos, pos - prev_pos));
prev_pos = ++pos;
}
words.push_back(buff.substr(prev_pos, pos - prev_pos));
for(unsigned int i = 2; i < words.size(); ++i){
float value = atof(((words)[i]).c_str());
veff.push_back(value);
}
_mapDetIdEff.insert(make_pair(static_cast<uint32_t>(rpcdetid),veff));
}
_infile2.close();
//---------------------- Timing reading ------------------------------------
edm::FileInPath fp3 = ps.getParameter<edm::FileInPath>("timingMap");
std::ifstream _infile3(fp3.fullPath().c_str(), std::ios::in);
uint32_t detUnit = 0;
float timing = 0.;
while(!_infile3.eof()){
_infile3>>detUnit>>timing;
_bxmap[RPCDetId(detUnit)] = timing;
}
_infile3.close();
//---------------------- Cluster size --------------------------------------
edm::FileInPath fp4 = ps.getParameter<edm::FileInPath>("clsmapfile");
std::ifstream _infile4(fp4.fullPath().c_str(), ios::in);
string buffer;
double sum = 0;
unsigned int counter = 1;
unsigned int row = 1;
std::vector<double> sum_clsize;
while ( _infile4 >> buffer ) {
const char *buffer1 = buffer.c_str();
double dato = atof(buffer1);
sum += dato;
sum_clsize.push_back(sum);
if(counter == row*20) {
_clsMap[row] = sum_clsize;
row++;
sum = 0;
sum_clsize.clear();
}
counter++;
}
_infile4.close();
//---------------------- Cluster size Chamber by Chamber -------------------
edm::FileInPath fp5 = ps.getParameter<edm::FileInPath>("clsidmapfile");
std::ifstream _infile5(fp5.fullPath().c_str(), ios::in);
std::vector<double> vClsDistrib ;
rpcdetid = 0;
while( getline(_infile5, buff, '\n') ){
words.clear();
vClsDistrib.clear();
stringstream ss1;
ss1<<buff;
ss1>>rpcdetid;
std::string::size_type pos = 0, prev_pos = 0;
while ( (pos = buff.find(" ",pos)) != string::npos){
words.push_back(buff.substr(prev_pos, pos - prev_pos));
prev_pos = ++pos;
}
words.push_back(buff.substr(prev_pos, pos - prev_pos));
float clusterSizeSumData(0.);
for(unsigned int i = 1; i < words.size(); ++i){
float value = atof(((words)[i]).c_str());
clusterSizeSumData+=value;
vClsDistrib.push_back(clusterSizeSumData);
if(!(i%20)){
clusterSizeSumData=0.;
}
}
if(vClsDistrib.size()!=100){
throw cms::Exception("DataCorrupt")
<< "Exception comming from RPCCalibSetUp - cluster size - a wrong format "<< std::endl;
}
_mapDetClsMap.insert(make_pair(static_cast<uint32_t>(rpcdetid),vClsDistrib));
std::cout<<"_mapDetClsMap.size()\t"<<_mapDetClsMap.size()<<std::endl;
}
_infile5.close();
}
std::vector<float> RPCCalibSetUp::getNoise(uint32_t id)
{
map<uint32_t,std::vector<float> >::iterator iter = _mapDetIdNoise.find(id);
if(iter == _mapDetIdNoise.end()){
throw cms::Exception("DataCorrupt")
<< "Exception comming from RPCCalibSetUp - no noise information for DetId\t"<<id<< std::endl;
}
return (iter->second);
}
std::vector<float> RPCCalibSetUp::getEff(uint32_t id)
{
map<uint32_t,std::vector<float> >::iterator iter = _mapDetIdEff.find(id);
if(iter == _mapDetIdEff.end()){
throw cms::Exception("DataCorrupt")
<< "Exception comming from RPCCalibSetUp - no efficiency information for DetId\t"<<id<< std::endl;
}
if((iter->second).size() != 96){
throw cms::Exception("DataCorrupt")
<< "Exception comming from RPCCalibSetUp - efficiency information in a wrong format for DetId\t"<<id<< std::endl;
}
return iter->second;
}
float RPCCalibSetUp::getTime(uint32_t id)
{
RPCDetId rpcid(id);
std::map<RPCDetId, float>::iterator iter = _bxmap.find(rpcid);
if(iter == _bxmap.end()){
throw cms::Exception("DataCorrupt")
<< "Exception comming from RPCCalibSetUp - no timing information for rpcid.rawId()\t"<<rpcid.rawId()<< std::endl;
}
return iter->second;
}
std::map< int, std::vector<double> > RPCCalibSetUp::getClsMap()
{
if(_clsMap.size()!=5){
throw cms::Exception("DataCorrupt")
<< "Exception comming from RPCCalibSetUp - cluster size - a wrong format "<< std::endl;
}
return _clsMap;
}
std::vector<double> RPCCalibSetUp::getCls(uint32_t id){
std::map<uint32_t,std::vector<double> >::iterator iter = _mapDetClsMap.find(id);
if(iter == _mapDetClsMap.end()){
throw cms::Exception("DataCorrupt")
<< "Exception comming from RPCCalibSetUp - no cluster size information for DetId\t"<<id<< std::endl;
}
if((iter->second).size() != 100){
throw cms::Exception("DataCorrupt")
<< "Exception comming from RPCCalibSetUp - cluster size information in a wrong format for DetId\t"<<id<< std::endl;
}
return iter->second;
}
RPCCalibSetUp::~RPCCalibSetUp(){}
| 28.680769 | 121 | 0.629878 | [
"geometry",
"vector"
] |
9cd8d055297df73b70bce49e0709b3b4eceedabe | 720 | cpp | C++ | UVa 1346 - Songs/sample/1346 - Songs.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 1346 - Songs/sample/1346 - Songs.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 1346 - Songs/sample/1346 - Songs.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <algorithm>
using namespace std;
const int MAXN = 65536;
struct Song {
int id;
double length, freq;
void read() {
scanf("%d %lf %lf", &id, &length, &freq);
}
} songs[MAXN];
// like UVa 12589 - Learning Vector, greedy
// if a-th song early than b-th song early, then sat. b.freq * a.length < a.freq * b.length,
// otherwise, b-th song early then a-th song.
bool cmp(Song a, Song b) { // a.length / a.freq < b.length / b.freq
return b.freq * a.length < a.freq * b.length;
}
int main() {
int N, Idx;
while (scanf("%d", &N) == 1) {
for (int i = 0; i < N; i++)
songs[i].read();
scanf("%d", &Idx);
sort(songs, songs + N, cmp);
printf("%d\n", songs[Idx-1].id);
}
return 0;
}
| 24.827586 | 92 | 0.597222 | [
"vector"
] |
9cda3498e056e0aef86cfe1fad1237c0dd84f735 | 6,161 | cpp | C++ | src/libanalyze/MeshHealing/Geometry.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 83 | 2021-03-10T05:54:52.000Z | 2022-03-31T16:33:46.000Z | src/libanalyze/MeshHealing/Geometry.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 13 | 2021-06-24T17:07:48.000Z | 2022-03-31T15:31:33.000Z | src/libanalyze/MeshHealing/Geometry.cpp | lf-/brlcad | f91ea585c1a930a2e97c3f5a8274db8805ebbb46 | [
"BSD-4-Clause",
"BSD-3-Clause"
] | 54 | 2021-03-10T07:57:06.000Z | 2022-03-28T23:20:37.000Z | /* G E O M E T R Y . C P P
* BRL-CAD
*
* Copyright (c) 2016-2021 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file Geometry.cpp
*
* Implementations of all the geometry functions required by the mesh healing module
*
*/
#include "common.h"
/* interface header */
#include "./Geometry.h"
/* system implementation headers */
#include <cmath>
/* Calculates the determinant of a 3x3 matrix */
double
calcDet(const double m[3][3])
{
double d;
d = m[0][0] * (m[1][1]*m[2][2] - m[1][2] * m[2][1]);
d -= m[0][1] * (m[1][0]*m[2][2] - m[1][2] * m[2][0]);
d += m[0][2] * (m[1][0]*m[2][1] - m[1][1] * m[2][0]);
return d;
}
void
findOrthogonalProjection(const double line_point1[3], const double line_point2[3], const double point[3], double ortho[3])
{
/* Parameter in the line equation of AB */
double t;
double BA[3];
double CA[3];
for (int i = 0; i < 3; ++i) {
BA[i] = line_point2[i] - line_point1[i];
CA[i] = point[i] - line_point1[i];
}
/* Finding parameter t for a point D on line AB such that AB and DC are perpendicular to each other using the formula:
* t = dot(B-A, C-A)/dot(B-A, B-A) */
double num = DOT_PROD(BA, CA);
double den = DOT_PROD(BA, BA);
t = num / den;
/* t=0 and t=1 correspond to the end points */
if (t < 0)
t = 0;
else if (t > 1)
t = 1;
for (int i = 0; i < 3; ++i) {
ortho[i] = line_point1[i] + t * BA[i];
}
}
bool
isOrthoProjPossible(const double line_point1[3], const double line_point2[3], const double point[3])
{
/* Parameter in the line equation of AB */
double t;
double BA[3];
double CA[3];
for (int i = 0; i < 3; ++i) {
BA[i] = line_point2[i] - line_point1[i];
CA[i] = point[i] - line_point1[i];
}
/* Finding parameter t for a point D on line AB such that AB and DC are perpendicular to each other using this formula:
* t = dot(B-A, C-A)/dot(B-A, B-A)
*/
double num = DOT_PROD(BA, CA);
double den = DOT_PROD(BA, BA);
t = num / den;
if (t > 0 && t < 1)
return true;
return false;
}
double
shortestDistBwPoints(const double A[3], const double B[3])
{
double dist = 0;
for (int i = 0; i < 3; i++) {
dist += (A[i] - B[i]) * (A[i] - B[i]);
}
dist = std::sqrt(dist);
return dist;
}
double
shortestDistToLine(const double line_point1[3], const double line_point2[3], const double point[3])
{
double dist;
double ortho[3];
findOrthogonalProjection(line_point1, line_point2, point, ortho);
dist = shortestDistBwPoints(point, ortho);
return dist;
}
bool
checkIfIntersectsInterior(const double line1_point1[3], const double line1_point2[3], const double line2_point1[3], const double line2_point2[3])
{
int o1, o2, o3, o4;
o1 = orientation(line1_point1, line1_point2, line2_point1);
o2 = orientation(line1_point1, line1_point2, line2_point2);
o3 = orientation(line2_point1, line2_point2, line1_point1);
o4 = orientation(line2_point1, line2_point2, line1_point2);
if (o1 != o2 && o3 != o4 && o1 != COLL && o2 != COLL && o3 != COLL && o4 != COLL)
return true;
return false;
}
bool
checkIfCollinear(const double line1_point1[3], const double line1_point2[3], const double line2_point1[3], const double line2_point2[3])
{
int o1, o2, o3, o4;
o1 = orientation(line1_point1, line1_point2, line2_point1);
o2 = orientation(line1_point1, line1_point2, line2_point2);
o3 = orientation(line2_point1, line2_point2, line1_point1);
o4 = orientation(line2_point1, line2_point2, line1_point2);
if(o1 == COLL && o2 == COLL && o3 == COLL && o4 == COLL)
return true;
return false;
}
int
orientation(const double A[3], const double B[3], const double C[3])
{
double m[3][3];
double det;
for (int i = 0; i < 3; i++) {
m[0][i] = A[i];
m[1][i] = B[i];
m[2][i] = C[i];
}
if(NEAR_0(m[0][2]) && NEAR_0(m[1][2]) && NEAR_0(m[2][2])) {
m[0][2] = 1;
m[1][2] = 1;
m[2][2] = 1;
}
/*
for (int i = 0; i < 3; i++) {
m[0][i] = 1;
m[1][i] = B[i] - A[i];
m[2][i] = C[i] - A[i];
}
*/
det = calcDet(m);
if(NEAR_0(det))
return COLL;
else if (det > 0)
return CCW;
else
return CW;
}
void
twoDimCoords(const double coordinates[3], double twod_coords[3])
{
twod_coords[0] = coordinates[0];
twod_coords[1] = coordinates[1];
twod_coords[2] = 0;
}
bool
coplanar(const double A[3], const double B[3], const double C[3], const double D[3])
{
double m[4][4];
for(int i = 0; i < 3; i++) {
m[0][i] = A[i];
m[1][i] = B[i];
m[2][i] = C[i];
m[3][i] = D[i];
}
for(int i = 0; i < 4; i++) {
m[i][3] = 1;
}
return NEAR_0(calcDetFour(m)) ? true : false;
}
double
perimeter(const double A[3], const double B[3], const double C[3])
{
double dist;
dist = shortestDistBwPoints(A, B);
dist += shortestDistBwPoints(B, C);
dist += shortestDistBwPoints(C, A);
return dist;
}
double
calcDetFour(const double m[4][4])
{
double det = 0;
double temp[3][3];
int col;
for(int i = 0; i < 4; i++) {
for(int j = 1; j < 4; j++) {
col = 0;
for(int k = 0; k < 4; k++) {
if(k == i)
continue;
temp[j - 1][col] = m[j][k];
col++;
}
}
if(i % 2 == 0)
det += m[0][i]*calcDet(temp);
else
det -= m[0][i]*calcDet(temp);
}
return det;
}
/*
* Local Variables:
* mode: C
* tab-width: 8
* indent-tabs-mode: t
* c-file-style: "stroustrup"
* End:
* ex: shiftwidth=4 tabstop=8
*/
| 22.567766 | 145 | 0.598442 | [
"cad",
"mesh",
"geometry"
] |
9cdba21e3a834d80d4afa80d787a9c69e791a28b | 5,762 | cpp | C++ | modules/base/rotation/staticrotation.cpp | Danielwbolson/OpenSpace | 5ed7ffd885dd5fbe8f68d4b208e4188f3c8c2e50 | [
"MIT"
] | null | null | null | modules/base/rotation/staticrotation.cpp | Danielwbolson/OpenSpace | 5ed7ffd885dd5fbe8f68d4b208e4188f3c8c2e50 | [
"MIT"
] | null | null | null | modules/base/rotation/staticrotation.cpp | Danielwbolson/OpenSpace | 5ed7ffd885dd5fbe8f68d4b208e4188f3c8c2e50 | [
"MIT"
] | null | null | null | /*****************************************************************************************
* *
* OpenSpace *
* *
* Copyright (c) 2014-2020 *
* *
* 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 <modules/base/rotation/staticrotation.h>
#include <openspace/documentation/documentation.h>
#include <openspace/documentation/verifier.h>
namespace {
constexpr openspace::properties::Property::PropertyInfo RotationInfo = {
"Rotation",
"Rotation",
"This value is the used as a 3x3 rotation matrix that is applied to the scene "
"graph node that this transformation is attached to relative to its parent."
};
// Conversion from rotation matrix to euler angles, given that the rotation is a pure
// rotation matrix.
// Inspired by: https://www.learnopencv.com/rotation-matrix-to-euler-angles/
glm::dvec3 rotationMatrixToEulerAngles(glm::dmat4 mat) {
const double sy = glm::sqrt(mat[0][0] * mat[0][0] + mat[0][1] * mat[0][1]);
bool singular = sy < 1e-6;
glm::dvec3 res;
if (singular) {
res.x = glm::atan(-mat[2][1], mat[1][1]);
res.y = glm::atan(-mat[0][2], sy);
res.z = 0;
}
else {
res.x = glm::atan(mat[1][2], mat[2][2]);
res.y = glm::atan(-mat[0][2], sy);
res.z = glm::atan(mat[0][1], mat[0][0]);
}
return res;
}
} // namespace
namespace openspace {
documentation::Documentation StaticRotation::Documentation() {
using namespace openspace::documentation;
return {
"Static Rotation",
"base_transform_rotation_static",
{
{
"Type",
new StringEqualVerifier("StaticRotation"),
Optional::No
},
{
RotationInfo.identifier,
new OrVerifier({
new DoubleVector3Verifier(),
new DoubleVector4Verifier(),
new DoubleMatrix3Verifier()
}),
Optional::No,
"Stores the static rotation as a vector containing Euler angles, "
" a quaternion or a rotation matrix."
}
}
};
}
StaticRotation::StaticRotation()
: _eulerRotation(
RotationInfo,
glm::vec3(0.f),
glm::vec3(-glm::pi<float>()),
glm::vec3(glm::pi<float>())
)
{
addProperty(_eulerRotation);
_eulerRotation.onChange([this]() {
_matrixIsDirty = true;
requireUpdate();
});
}
StaticRotation::StaticRotation(const ghoul::Dictionary& dictionary) : StaticRotation() {
documentation::testSpecificationAndThrow(
Documentation(),
dictionary,
"StaticRotation"
);
if (dictionary.hasKeyAndValue<glm::dvec3>(RotationInfo.identifier)) {
_eulerRotation = static_cast<glm::vec3>(
dictionary.value<glm::dvec3>(RotationInfo.identifier)
);
_matrixIsDirty = true;
}
else if (dictionary.hasKeyAndValue<glm::dvec4>(RotationInfo.identifier)) {
glm::dvec4 data = dictionary.value<glm::dvec4>(RotationInfo.identifier);
_eulerRotation = rotationMatrixToEulerAngles(
glm::mat3_cast(glm::dquat(data.w, data.x, data.y, data.z))
);
_matrixIsDirty = true;
}
else if (dictionary.hasKeyAndValue<glm::dmat3>(RotationInfo.identifier)) {
_eulerRotation = rotationMatrixToEulerAngles(
dictionary.value<glm::dmat3>(RotationInfo.identifier)
);
_matrixIsDirty = true;
}
}
glm::dmat3 StaticRotation::matrix(const UpdateData&) const {
if (_matrixIsDirty) {
_cachedMatrix = glm::mat3_cast(glm::quat(_eulerRotation.value()));
_matrixIsDirty = false;
}
return _cachedMatrix;
}
} // namespace openspace
| 41.157143 | 90 | 0.521867 | [
"vector"
] |
9ce04220290f12bd7fc33338d308d87919e60d41 | 19,056 | cpp | C++ | app/medInria/medHomepageArea.cpp | gpasquie/medInria-public | 1efa82292698695f6ee69fe00114aabce5431246 | [
"BSD-4-Clause"
] | null | null | null | app/medInria/medHomepageArea.cpp | gpasquie/medInria-public | 1efa82292698695f6ee69fe00114aabce5431246 | [
"BSD-4-Clause"
] | null | null | null | app/medInria/medHomepageArea.cpp | gpasquie/medInria-public | 1efa82292698695f6ee69fe00114aabce5431246 | [
"BSD-4-Clause"
] | null | null | null | /*=========================================================================
medInria
Copyright (c) INRIA 2013. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include "medHomepageArea.h"
#ifdef MEDINRIA_HAS_REVISIONS
#include <medRevisions.h>
#endif
#include <medHomepageButton.h>
#include <medWorkspace.h>
#include <medToolBoxFactory.h>
#include <medWorkspaceFactory.h>
#include <medSettingsManager.h>
#include "medPluginWidget.h"
#include <medSettingsEditor.h>
class medHomepageAreaPrivate
{
public:
QStackedWidget* stackedWidget;
QWidget * navigationWidget;
QPropertyAnimation * navigationAnimation;
QWidget * userWidget;
QPropertyAnimation * userAnimation;
QWidget * infoWidget;
QPropertyAnimation * infoAnimation;
QWidget * aboutWidget;
QTabWidget * aboutTabWidget;
QWidget * pluginWidget;
QWidget * settingsWidget;
medSettingsEditor* settingsEditor;
QParallelAnimationGroup * animation;
};
medHomepageArea::medHomepageArea ( QWidget * parent ) : QWidget ( parent ), d ( new medHomepageAreaPrivate )
{
//Setup navigation widget (with buttons for accessing available workspaces)
d->navigationWidget = new QWidget ( this );
d->navigationWidget->setMinimumWidth ( 250 );
//Setup the widget where the medInria general information are displayed
d->infoWidget = new QWidget ( this );
d->infoWidget->setMinimumSize(400,300);
//Setup the widget with about, settings, plugins and documentation buttons
d->userWidget = new QWidget ( this );
d->userWidget->setMinimumWidth ( 250 );
d->userWidget->setMaximumWidth ( 350 ); //TODO: find the right solution
d->userWidget->setMinimumHeight ( 40 );
//Setup the about container widget (with a QTabWidget inside)
d->aboutWidget = new QWidget ( this );
d->aboutWidget->setMinimumSize(400,300);
d->aboutWidget->hide();
//User widget content with settings, about and help buttons
QHBoxLayout * userButtonsLayout = new QHBoxLayout(d->userWidget);
medHomepageButton * helpButton = new medHomepageButton ( this );
helpButton->setText ( "Help" );
helpButton->setToolTip(tr("Open Online Documentation"));
helpButton->setMinimumHeight ( 30 );
helpButton->setMaximumWidth ( 150 );
helpButton->setMinimumWidth ( 150 );
helpButton->setFocusPolicy ( Qt::NoFocus );
helpButton->setIcon ( QIcon ( ":icons/help.svg" ) );
helpButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( helpButton,SIGNAL ( clicked() ),this, SLOT ( onShowHelp() ) );
medHomepageButton * aboutButton = new medHomepageButton ( this );
aboutButton->setText ( "About" );
aboutButton->setMinimumHeight ( 30 );
aboutButton->setMaximumWidth ( 150 );
aboutButton->setMinimumWidth ( 150 );
aboutButton->setToolTip(tr("About medInria"));
aboutButton->setFocusPolicy ( Qt::NoFocus );
aboutButton->setIcon ( QIcon ( ":icons/about.png" ) );
aboutButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( aboutButton,SIGNAL ( clicked() ),this, SLOT ( onShowAbout() ) );
medHomepageButton * pluginButton = new medHomepageButton ( this );
pluginButton->setText ( "Plugins" );
pluginButton->setMinimumHeight ( 30 );
pluginButton->setMaximumWidth ( 150 );
pluginButton->setMinimumWidth ( 150 );
pluginButton->setToolTip(tr("Information on loaded plugins"));
pluginButton->setFocusPolicy ( Qt::NoFocus );
pluginButton->setIcon ( QIcon ( ":icons/medInriaPlugin.png" ) );
pluginButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( pluginButton,SIGNAL ( clicked() ),this, SLOT ( onShowPlugin() ) );
medHomepageButton * settingsButton = new medHomepageButton ( this );
settingsButton->setText ( "Settings" );
settingsButton->setMinimumHeight ( 30 );
settingsButton->setMaximumWidth ( 150 );
settingsButton->setMinimumWidth ( 150 );
settingsButton->setToolTip(tr("Configure medInria"));
settingsButton->setFocusPolicy ( Qt::NoFocus );
settingsButton->setIcon ( QIcon ( ":icons/settings.svg" ) );
settingsButton->setToolButtonStyle ( Qt::ToolButtonTextBesideIcon );
QObject::connect ( settingsButton,SIGNAL ( clicked() ),this, SLOT ( onShowSettings() ) );
userButtonsLayout->insertWidget ( 0, settingsButton );
userButtonsLayout->insertWidget ( 1, pluginButton );
userButtonsLayout->insertWidget ( 2, aboutButton );
userButtonsLayout->insertWidget ( 3, helpButton );
//no need to set the layout the userWidget is the parent of the layout already.
// d->userWidget->setLayout ( userButtonsLayout );
// Info widget : medInria logo, medInria description, etc. QtWebkit ?
QVBoxLayout * infoLayout = new QVBoxLayout(d->infoWidget);
QLabel * medInriaLabel = new QLabel ( this );
QPixmap medLogo( ":pixmaps/medInria-logo-homepage.png" );
medInriaLabel->setPixmap ( medLogo );
// QLabel * textLabel = new QLabel;
QTextEdit * textEdit = new QTextEdit(this);
textEdit->setHtml ( tr("<b>medInria</b> is a multi-platform medical image "
"processing and visualization software, "
"and it's <b>free</b>. Through an intuitive user "
"interface, <b>medInria</b> offers from standard "
"to cutting-edge processing functionalities for "
"your medical images such as 2D/3D/4D image "
"visualization, image registration, or diffusion "
"MR processing and tractography." ));
textEdit->setReadOnly ( true );
textEdit->setFocusPolicy ( Qt::NoFocus );
textEdit->setMaximumHeight ( 200 );
infoLayout->insertWidget ( 0,medInriaLabel );
infoLayout->insertWidget ( 1, textEdit );
infoLayout->addStretch();
//no need to set the layout, the infoWidget is the parent of the layout already.
// d->infoWidget->setLayout ( infoLayout );
d->infoWidget->setMaximumHeight ( medInriaLabel->height() + textEdit->height() );
//About widget
QVBoxLayout * aboutLayout = new QVBoxLayout(d->aboutWidget);
d->aboutTabWidget = new QTabWidget(this);
d->aboutTabWidget->setObjectName("aboutTabWidget");
QLabel * medInriaLabel2 = new QLabel ( this );
medInriaLabel2->setPixmap ( medLogo );
QTextEdit * aboutTextEdit = new QTextEdit(this);
QString aboutText = QString(tr("<br/><br/>"
"medInria %1 is the medical imaging platform developed at "
"Inria<br/><br/>"
"<center>Inria, Copyright 2013</center>"))
.arg(qApp->applicationVersion());
#ifdef MEDINRIA_HAS_REVISIONS
aboutText += QString::fromLocal8Bit(REVISIONS);
#endif
aboutTextEdit->setHtml (aboutText);
aboutTextEdit->setFocusPolicy ( Qt::NoFocus );
QTextBrowser * aboutAuthorTextBrowser = new QTextBrowser(this);
aboutAuthorTextBrowser->setSource(QUrl("qrc:authors.html" ));
aboutAuthorTextBrowser->setFocusPolicy ( Qt::NoFocus );
QTextEdit * aboutLicenseTextEdit = new QTextEdit(this);
QFile license ( ":LICENSE.txt" );
license.open ( QIODevice::ReadOnly | QIODevice::Text );
QString licenseContent = license.readAll();
license.close();
aboutLicenseTextEdit->setText ( licenseContent );
aboutLicenseTextEdit->setFocusPolicy ( Qt::NoFocus );
QTextEdit * releaseNotesTextEdit = new QTextEdit(this);
QFile releaseNotes ( ":RELEASE_NOTES.txt" );
releaseNotes.open ( QIODevice::ReadOnly | QIODevice::Text );
QString releaseNotesContent = releaseNotes.readAll();
releaseNotes.close();
releaseNotesTextEdit->setText ( releaseNotesContent );
releaseNotesTextEdit->setFocusPolicy ( Qt::NoFocus );
//no parent, this layout is added to an other layout.
QHBoxLayout * aboutButtonLayout = new QHBoxLayout();
QPushButton * hideAboutButton = new QPushButton ( this );
hideAboutButton->setText ( tr("Hide") );
hideAboutButton->setFocusPolicy ( Qt::NoFocus );
hideAboutButton->setToolTip( tr("Hide the About section") );
QObject::connect ( hideAboutButton, SIGNAL ( clicked() ), this, SLOT ( onShowInfo() ) );
aboutButtonLayout->addStretch();
aboutButtonLayout->addWidget ( hideAboutButton );
aboutButtonLayout->addStretch();
d->aboutTabWidget->addTab ( aboutTextEdit, tr("About") );
d->aboutTabWidget->addTab ( aboutAuthorTextBrowser, tr("Authors") );
d->aboutTabWidget->addTab ( releaseNotesTextEdit, tr("Release Notes") );
d->aboutTabWidget->addTab ( aboutLicenseTextEdit, tr("License") );
aboutLayout->addWidget ( medInriaLabel2 );
aboutLayout->addWidget ( d->aboutTabWidget );
aboutLayout->addLayout ( aboutButtonLayout );
//Create the plugin widget.
d->pluginWidget = new QWidget(this);
QVBoxLayout * pluginLayout = new QVBoxLayout(d->pluginWidget);
QHBoxLayout * pluginHideButtonLayout = new QHBoxLayout();
QPushButton * hidePluginButton = new QPushButton ( this );
hidePluginButton->setText ( tr("Hide") );
hidePluginButton->setFocusPolicy ( Qt::NoFocus );
hidePluginButton->setToolTip( tr("Hide the Plugins section") );
QObject::connect ( hidePluginButton, SIGNAL ( clicked() ), this, SLOT ( onShowInfo() ) );
pluginHideButtonLayout->addStretch();
pluginHideButtonLayout->addWidget ( hidePluginButton );
pluginHideButtonLayout->addStretch();
QLabel * medInriaLabel3 = new QLabel ( this );
medInriaLabel3->setPixmap ( medLogo );
medPluginWidget * pWid = new medPluginWidget(d->pluginWidget);
pluginLayout->addWidget(medInriaLabel3);
pluginLayout->addWidget(pWid);
pluginLayout->addLayout(pluginHideButtonLayout);
//Create the setttings widget.
d->settingsWidget = new QWidget(this);
d->settingsWidget->setObjectName("settingsWidget");
QVBoxLayout * settingsLayout = new QVBoxLayout(d->settingsWidget);
QHBoxLayout * settingsHideButtonLayout = new QHBoxLayout();
QPushButton * hideSettingsButton = new QPushButton ( this );
hideSettingsButton->setText ( tr("Hide") );
hideSettingsButton->setFocusPolicy ( Qt::NoFocus );
hideSettingsButton->setToolTip( tr("Hide the Settings section") );
QObject::connect ( hideSettingsButton, SIGNAL ( clicked() ), this, SLOT ( onShowInfo() ) );
settingsHideButtonLayout->addStretch();
settingsHideButtonLayout->addWidget ( hideSettingsButton );
settingsHideButtonLayout->addStretch();
QLabel * medInriaLabel4 = new QLabel ( this );
medInriaLabel4->setPixmap ( medLogo );
d->settingsEditor = new medSettingsEditor(d->settingsWidget,true);
settingsLayout->addWidget(medInriaLabel4);
settingsLayout->addWidget(d->settingsEditor);
settingsLayout->addLayout(settingsHideButtonLayout);
//Set the position of the widgets
d->navigationWidget->setProperty ( "pos", QPoint ( 100 , this->height() / 4 ) );
d->userWidget->setProperty ( "pos", QPoint ( this->width() - 350 , this->height() - 90 ) );
//Create a Stacked Widget in which to put info widget, about widget and plugin Widget
d->stackedWidget = new QStackedWidget( this );
d->stackedWidget->setMinimumSize ( 400,300 );
d->stackedWidget->setProperty ( "pos", QPoint ( this->width() / 2 ,
this->height() / 5) );
int stackedWidgetHeight = d->userWidget->pos().y() - d->stackedWidget->pos().y();
if (d->stackedWidget->minimumHeight() > stackedWidgetHeight)
stackedWidgetHeight = d->stackedWidget->minimumHeight();
d->stackedWidget->setMaximumHeight(stackedWidgetHeight);
d->stackedWidget->setMaximumWidth(this->width() / 2-50);
d->stackedWidget->addWidget(d->infoWidget);
d->stackedWidget->addWidget(d->aboutWidget);
d->stackedWidget->addWidget(d->pluginWidget);
d->stackedWidget->addWidget(d->settingsWidget);
d->stackedWidget->setCurrentIndex(0);//d->infoWidget
d->stackedWidget->setSizePolicy(QSizePolicy::Maximum,QSizePolicy::Maximum);
//Setup homepage animations
d->animation = new QParallelAnimationGroup ( this );
d->navigationAnimation = new QPropertyAnimation ( d->navigationWidget, "pos" );
d->navigationAnimation->setDuration ( 750 );
d->navigationAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->navigationAnimation->setStartValue ( QPoint ( - 300, this->height() / 4 ) );
d->navigationAnimation->setEndValue ( QPoint ( 100 , this->height() / 4 ) );
d->userAnimation = new QPropertyAnimation ( d->userWidget, "pos" );
d->userAnimation->setDuration ( 750 );
d->userAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->userAnimation->setStartValue ( QPoint ( this->width() + 250, this->height() - 90 ) );
d->userAnimation->setEndValue ( QPoint ( this->width() * 0.8 , this->height() - 90 ) );
d->infoAnimation = new QPropertyAnimation ( d->stackedWidget, "pos" );
d->infoAnimation->setDuration ( 750 );
d->infoAnimation->setEasingCurve ( QEasingCurve::OutCubic );
d->infoAnimation->setStartValue ( QPoint ( this->width() + 100 , this->height() / 5 ) );
d->infoAnimation->setEndValue ( QPoint ( this->width() / 2 , this->height() / 5 ) );
d->animation->addAnimation ( d->navigationAnimation );
d->animation->addAnimation ( d->userAnimation );
d->animation->addAnimation ( d->infoAnimation );
}
medHomepageArea::~medHomepageArea()
{
delete d;
d = NULL;
}
void medHomepageArea::resizeEvent ( QResizeEvent * event )
{
//Recompute the widgets position when the window is resized
d->navigationWidget->setProperty ( "pos", QPoint ( 100 , this->height() / 4 ) );
d->userWidget->setProperty ( "pos", QPoint ( this->width() - 350 , this->height() - 90 ) );
d->stackedWidget->setProperty ( "pos", QPoint ( this->width() / 2 , this->height() / 5 ) );
int stackedWidgetHeight = d->userWidget->pos().y() - d->stackedWidget->pos().y();
if (d->stackedWidget->minimumHeight() > stackedWidgetHeight)
stackedWidgetHeight = d->stackedWidget->minimumHeight();
d->stackedWidget->setMaximumHeight(stackedWidgetHeight);
int stackedWidgetWidth = this->width() / 2 - 50 ;
d->stackedWidget->setMaximumWidth(stackedWidgetWidth);
//TODO: this is ugly, find a way to use the right policy here...
d->stackedWidget->resize(stackedWidgetWidth,stackedWidgetHeight);
// qDebug()<< d->stackedWidget->maximumSize();
//Update the animations as well
d->navigationAnimation->setStartValue ( QPoint ( - 300, this->height() / 4 ) );
d->navigationAnimation->setEndValue ( QPoint ( 100 , this->height() / 4 ) );
d->userAnimation->setStartValue ( QPoint ( this->width() + 50, this->height() - 90 ) );
d->userAnimation->setEndValue ( QPoint ( this->width() - 350 , this->height() - 90 ) );
d->infoAnimation->setStartValue ( QPoint ( this->width() , this->height() / 5 ) );
d->infoAnimation->setEndValue ( QPoint ( this->width() / 2 , this->height() / 5 ) );
}
void medHomepageArea::initPage()
{
//Initialization of the navigation widget with available workspaces
QHash<QString,medWorkspaceDetails*> workspaceDetails =
medWorkspaceFactory::instance()->workspaceDetails();
QVBoxLayout * workspaceButtonsLayout = new QVBoxLayout;
workspaceButtonsLayout->setSpacing ( 10 );
QLabel * workspaceLabel = new QLabel ( "<b>Available workspaces</b>" );
workspaceLabel->setTextFormat(Qt::RichText);
workspaceLabel->setAlignment(Qt::AlignHCenter);
workspaceButtonsLayout->addWidget ( workspaceLabel );
medHomepageButton * browserButton = new medHomepageButton ( this );
browserButton->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
browserButton->setIcon ( QIcon ( ":/icons/folder.png" ) );
browserButton->setText ( "Browser" );
browserButton->setMinimumHeight ( 40 );
browserButton->setMaximumWidth ( 250 );
browserButton->setMinimumWidth ( 250 );
browserButton->setFocusPolicy ( Qt::NoFocus );
workspaceButtonsLayout->addWidget ( browserButton );
QObject::connect ( browserButton, SIGNAL ( clicked() ),this, SLOT ( onShowBrowser() ) );
foreach ( QString id, workspaceDetails.keys())
{
medHomepageButton * button = new medHomepageButton ( this );
medWorkspaceDetails* detail = workspaceDetails.value(id);
button->setText ( detail->name );
button->setFocusPolicy ( Qt::NoFocus );
button->setToolButtonStyle ( Qt::ToolButtonTextUnderIcon );
button->setMinimumHeight ( 40 );
button->setMaximumWidth ( 250 );
button->setMinimumWidth ( 250 );
button->setToolTip(detail->description);
button->setIdentifier(id);
workspaceButtonsLayout->addWidget ( button );
QObject::connect ( button, SIGNAL ( clicked ( QString ) ),this, SLOT ( onShowWorkspace ( QString ) ) );
if (!(medWorkspaceFactory::instance()->isUsable(id)))
{
button->setDisabled(true);
button->setToolTip("No useful plugin has been found for this workspace.");
}
}
workspaceButtonsLayout->addStretch();
d->navigationWidget->setLayout ( workspaceButtonsLayout );
d->navigationWidget->setProperty ( "pos", QPoint ( 100, 100 ) );
d->navigationWidget->setMinimumHeight ( 55 * ( 1 + workspaceDetails.size() ) );
}
QParallelAnimationGroup* medHomepageArea::getAnimation()
{
return d->animation;
}
void medHomepageArea::onShowBrowser()
{
emit showBrowser();
}
void medHomepageArea::onShowWorkspace ( QString workspace )
{
emit showWorkspace ( workspace );
}
void medHomepageArea::onShowAbout()
{
d->stackedWidget->setCurrentWidget(d->aboutWidget);
d->aboutWidget->setFocus();
}
void medHomepageArea::onShowPlugin()
{
d->stackedWidget->setCurrentWidget(d->pluginWidget);
d->pluginWidget->setFocus();
}
void medHomepageArea::onShowInfo()
{
d->stackedWidget->setCurrentWidget(d->infoWidget);
d->infoWidget->setFocus();
}
void medHomepageArea::onShowHelp()
{
QDesktopServices::openUrl(QUrl("http://med.inria.fr/help/documentation"));
// QMessageBox * msgBox = new QMessageBox ( QApplication::activeWindow() );
// msgBox->setIcon ( QMessageBox::Information );
// msgBox->setText ( "Help ! Help !" );
// msgBox->exec();
// delete msgBox;
}
void medHomepageArea::onShowSettings()
{
// emit showSettings is not deprecated here
// emit showSettings();
d->settingsEditor->setTabPosition(QTabWidget::North);
d->settingsEditor->initialize();
d->settingsEditor->queryWidgets();
d->stackedWidget->setCurrentWidget(d->settingsWidget);
d->settingsWidget->setFocus();
}
| 41.426087 | 111 | 0.678894 | [
"3d"
] |
9ce15e94d18bf58f572fd225b18fe6e0721b1948 | 35,238 | cpp | C++ | be/src/storage/rowset/beta_rowset_writer.cpp | JoyBeginner/starrocks | c19c72e2ba85915a557bf0ca5b9f4f351b1bc350 | [
"Zlib",
"PSF-2.0",
"Apache-2.0"
] | 1 | 2021-09-08T01:55:04.000Z | 2021-09-08T01:55:04.000Z | be/src/storage/rowset/beta_rowset_writer.cpp | JoyBeginner/starrocks | c19c72e2ba85915a557bf0ca5b9f4f351b1bc350 | [
"Zlib",
"PSF-2.0",
"Apache-2.0"
] | null | null | null | be/src/storage/rowset/beta_rowset_writer.cpp | JoyBeginner/starrocks | c19c72e2ba85915a557bf0ca5b9f4f351b1bc350 | [
"Zlib",
"PSF-2.0",
"Apache-2.0"
] | null | null | null | // This file is made available under Elastic License 2.0.
// This file is based on code available under the Apache license here:
// https://github.com/apache/incubator-doris/blob/master/be/src/olap/rowset/beta_rowset_writer.cpp
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "storage/rowset/beta_rowset_writer.h"
#include <ctime>
#include <memory>
#include "column/chunk.h"
#include "common/config.h"
#include "common/logging.h"
#include "env/env.h"
#include "gutil/strings/substitute.h"
#include "runtime/exec_env.h"
#include "storage/fs/fs_util.h"
#include "storage/olap_define.h"
#include "storage/rowset/beta_rowset.h"
#include "storage/rowset/rowset_factory.h"
#include "storage/rowset/segment_v2/segment_writer.h"
#include "storage/rowset/vectorized/segment_options.h"
#include "storage/storage_engine.h"
#include "storage/vectorized/aggregate_iterator.h"
#include "storage/vectorized/chunk_helper.h"
#include "storage/vectorized/merge_iterator.h"
#include "storage/vectorized/type_utils.h"
#include "storage/vectorized/union_iterator.h"
#include "util/defer_op.h"
#include "util/pretty_printer.h"
namespace starrocks {
BetaRowsetWriter::BetaRowsetWriter(const RowsetWriterContext& context)
: _context(context),
_rowset_meta(nullptr),
_num_segment(0),
_num_rows_written(0),
_total_row_size(0),
_total_data_size(0),
_total_index_size(0) {}
OLAPStatus BetaRowsetWriter::init() {
DCHECK(!(_context.tablet_schema->contains_format_v1_column() &&
_context.tablet_schema->contains_format_v2_column()));
auto real_data_format = _context.storage_format_version;
auto tablet_format = real_data_format;
if (_context.tablet_schema->contains_format_v1_column()) {
tablet_format = kDataFormatV1;
} else if (_context.tablet_schema->contains_format_v2_column()) {
tablet_format = kDataFormatV2;
}
// StarRocks is built on earlier work on Apache Doris and is compatible with its data format but
// has newly designed storage formats for DATA/DATETIME/DECIMAL for better performance.
// When loading data into a tablet created by Apache Doris, the real data format will
// be different from the tablet schema, so here we create a new schema matched with the
// real data format to init `SegmentWriter`.
if (real_data_format != tablet_format) {
_rowset_schema = _context.tablet_schema->convert_to_format(real_data_format);
}
_rowset_meta = std::make_shared<RowsetMeta>();
_rowset_meta->set_rowset_id(_context.rowset_id);
_rowset_meta->set_partition_id(_context.partition_id);
_rowset_meta->set_tablet_id(_context.tablet_id);
_rowset_meta->set_tablet_schema_hash(_context.tablet_schema_hash);
_rowset_meta->set_rowset_type(_context.rowset_type);
_rowset_meta->set_rowset_state(_context.rowset_state);
_rowset_meta->set_segments_overlap(_context.segments_overlap);
if (_context.rowset_state == PREPARED || _context.rowset_state == COMMITTED) {
_is_pending = true;
_rowset_meta->set_txn_id(_context.txn_id);
_rowset_meta->set_load_id(_context.load_id);
} else {
_rowset_meta->set_version(_context.version);
}
_rowset_meta->set_tablet_uid(_context.tablet_uid);
return OLAP_SUCCESS;
}
RowsetSharedPtr BetaRowsetWriter::build() {
_rowset_meta->set_num_rows(_num_rows_written);
_rowset_meta->set_total_row_size(_total_row_size);
_rowset_meta->set_total_disk_size(_total_data_size);
_rowset_meta->set_data_disk_size(_total_data_size);
_rowset_meta->set_index_disk_size(_total_index_size);
// TODO write zonemap to meta
_rowset_meta->set_empty(_num_rows_written == 0);
_rowset_meta->set_creation_time(time(nullptr));
_rowset_meta->set_num_segments(_num_segment);
// newly created rowset do not have rowset_id yet, use 0 instead
_rowset_meta->set_rowset_seg_id(0);
// updatable tablet require extra processing
if (_context.tablet_schema->keys_type() == KeysType::PRIMARY_KEYS) {
if (_segment_has_deletes.size() >= 1 && _segment_has_deletes[0]) {
_rowset_meta->set_num_delete_files(1);
} else {
_rowset_meta->set_num_delete_files(0);
}
_rowset_meta->set_segments_overlap(NONOVERLAPPING);
} else {
if (_num_segment <= 1) {
_rowset_meta->set_segments_overlap(NONOVERLAPPING);
}
}
if (_is_pending) {
_rowset_meta->set_rowset_state(COMMITTED);
} else {
_rowset_meta->set_rowset_state(VISIBLE);
}
RowsetSharedPtr rowset;
auto status =
RowsetFactory::create_rowset(_context.tablet_schema, _context.rowset_path_prefix, _rowset_meta, &rowset);
if (!status.ok()) {
LOG(WARNING) << "Fail to create rowset: " << status;
return nullptr;
}
_already_built = true;
return rowset;
}
Status BetaRowsetWriter::flush_src_rssids(uint32_t segment_id) {
auto path = BetaRowset::segment_srcrssid_file_path(_context.rowset_path_prefix, _context.rowset_id, segment_id);
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions opts({path});
Status st = _context.block_mgr->create_block(opts, &wblock);
if (!st.ok()) {
return st;
}
st = wblock->append(Slice((const char*)(_src_rssids->data()), _src_rssids->size() * sizeof(uint32_t)));
if (!st.ok()) {
return Status::IOError("flush_src_rssids WritableBlock.append error");
}
st = wblock->finalize();
if (!st.ok()) {
return Status::IOError("flush_src_rssids WritableBlock.finalize error");
}
st = wblock->close();
if (!st.ok()) {
return Status::IOError("flush_src_rssids WritableBlock.close error");
}
_src_rssids->clear();
_src_rssids.reset();
return Status::OK();
}
HorizontalBetaRowsetWriter::HorizontalBetaRowsetWriter(const RowsetWriterContext& context)
: BetaRowsetWriter(context), _segment_writer(nullptr) {}
HorizontalBetaRowsetWriter::~HorizontalBetaRowsetWriter() {
// TODO(lingbin): Should wrapper exception logic, no need to know file ops directly.
if (!_already_built) { // abnormal exit, remove all files generated
_segment_writer.reset(); // ensure all files are closed
if (_context.tablet_schema->keys_type() == KeysType::PRIMARY_KEYS) {
for (const auto& tmp_segment_file : _tmp_segment_files) {
// Even if an error is encountered, these files that have not been cleaned up
// will be cleaned up by the GC background. So here we only print the error
// message when we encounter an error.
auto st = _context.env->delete_file(tmp_segment_file);
LOG_IF(WARNING, !st.ok()) << "Fail to delete file=" << tmp_segment_file << ", " << st.to_string();
}
_tmp_segment_files.clear();
for (auto i = 0; i < _num_segment; ++i) {
auto path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, i);
// Even if an error is encountered, these files that have not been cleaned up
// will be cleaned up by the GC background. So here we only print the error
// message when we encounter an error.
auto st = _context.env->delete_file(path);
LOG_IF(WARNING, !st.ok()) << "Fail to delete file=" << path << ", " << st.to_string();
}
for (auto i = 0; i < _segment_has_deletes.size(); ++i) {
if (!_segment_has_deletes[i]) {
auto path = BetaRowset::segment_del_file_path(_context.rowset_path_prefix, _context.rowset_id, i);
auto st = _context.env->delete_file(path);
LOG_IF(WARNING, !st.ok()) << "Fail to delete file=" << path << ", " << st.to_string();
}
}
//// only deleting segment files may not delete all delete files or temporary files
//// during final merge, should iterate directory and delete all files with rowset_id prefix
//std::vector<std::string> files;
//Status st = _context.env->get_children(_context.rowset_path_prefix, &files);
//if (!st.ok()) {
// LOG(WARNING) << "list dir failed: " << _context.rowset_path_prefix << " "
// << st.to_string();
//}
//string prefix = _context.rowset_id.to_string();
//for (auto& f : files) {
// if (strncmp(f.c_str(), prefix.c_str(), prefix.size()) == 0) {
// string path = _context.rowset_path_prefix + "/" + f;
// // Even if an error is encountered, these files that have not been cleaned up
// // will be cleaned up by the GC background. So here we only print the error
// // message when we encounter an error.
// Status st = _context.env->delete_file(path);
// LOG_IF(WARNING, !st.ok())
// << "Fail to delete file=" << path << ", " << st.to_string();
// }
//}
} else {
for (int i = 0; i < _num_segment; ++i) {
auto path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, i);
// Even if an error is encountered, these files that have not been cleaned up
// will be cleaned up by the GC background. So here we only print the error
// message when we encounter an error.
auto st = _context.env->delete_file(path);
LOG_IF(WARNING, !st.ok()) << "Fail to delete file=" << path << ", " << st.to_string();
}
}
}
}
std::unique_ptr<segment_v2::SegmentWriter> HorizontalBetaRowsetWriter::_create_segment_writer() {
std::lock_guard<std::mutex> l(_lock);
std::string path;
if ((_context.tablet_schema->keys_type() == KeysType::PRIMARY_KEYS &&
_context.segments_overlap != NONOVERLAPPING) ||
_context.write_tmp) {
path = BetaRowset::segment_temp_file_path(_context.rowset_path_prefix, _context.rowset_id, _num_segment);
_tmp_segment_files.emplace_back(path);
} else {
// for update final merge scenario, we marked segments_overlap to NONOVERLAPPING in
// function _final_merge, so we create segment data file here, rather than
// temporary segment files.
path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, _num_segment);
}
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions opts({path});
Status st = _context.block_mgr->create_block(opts, &wblock);
if (!st.ok()) {
LOG(WARNING) << "Fail to create writable block=" << path << ", " << st.to_string();
return nullptr;
}
DCHECK(wblock != nullptr);
segment_v2::SegmentWriterOptions writer_options;
writer_options.storage_format_version = _context.storage_format_version;
const auto* schema = _rowset_schema != nullptr ? _rowset_schema.get() : _context.tablet_schema;
writer_options.global_dicts = _context.global_dicts != nullptr ? _context.global_dicts : nullptr;
std::unique_ptr<segment_v2::SegmentWriter> segment_writer =
std::make_unique<segment_v2::SegmentWriter>(std::move(wblock), _num_segment, schema, writer_options);
auto s = segment_writer->init();
if (!s.ok()) {
LOG(WARNING) << "Fail to init segment writer, " << s.to_string();
segment_writer.reset(nullptr);
return nullptr;
}
++_num_segment;
return segment_writer;
}
OLAPStatus HorizontalBetaRowsetWriter::add_chunk(const vectorized::Chunk& chunk) {
if (_segment_writer == nullptr) {
_segment_writer = _create_segment_writer();
} else if (_segment_writer->estimate_segment_size() >= config::max_segment_file_size ||
_segment_writer->num_rows_written() + chunk.num_rows() >= _context.max_rows_per_segment) {
RETURN_NOT_OK(_flush_segment_writer(&_segment_writer));
_segment_writer = _create_segment_writer();
}
if (_segment_writer == nullptr) {
return OLAP_ERR_INIT_FAILED;
}
auto s = _segment_writer->append_chunk(chunk);
if (!s.ok()) {
LOG(WARNING) << "Fail to append chunk, " << s.to_string();
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
_num_rows_written += chunk.num_rows();
_total_row_size += chunk.bytes_usage();
return OLAP_SUCCESS;
}
OLAPStatus HorizontalBetaRowsetWriter::add_chunk_with_rssid(const vectorized::Chunk& chunk,
const vector<uint32_t>& rssid) {
if (_segment_writer == nullptr) {
_segment_writer = _create_segment_writer();
} else if (_segment_writer->estimate_segment_size() >= config::max_segment_file_size ||
_segment_writer->num_rows_written() + chunk.num_rows() >= _context.max_rows_per_segment) {
RETURN_NOT_OK(_flush_segment_writer(&_segment_writer));
_segment_writer = _create_segment_writer();
}
if (_segment_writer == nullptr) {
return OLAP_ERR_INIT_FAILED;
}
auto s = _segment_writer->append_chunk(chunk);
if (!_src_rssids) {
_src_rssids = std::make_unique<vector<uint32_t>>();
}
_src_rssids->insert(_src_rssids->end(), rssid.begin(), rssid.end());
if (!s.ok()) {
LOG(WARNING) << "Fail to append chunk, " << s.to_string();
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
_num_rows_written += chunk.num_rows();
_total_row_size += chunk.bytes_usage();
return OLAP_SUCCESS;
}
OLAPStatus HorizontalBetaRowsetWriter::flush_chunk(const vectorized::Chunk& chunk) {
std::unique_ptr<segment_v2::SegmentWriter> segment_writer = _create_segment_writer();
if (segment_writer == nullptr) {
return OLAP_ERR_INIT_FAILED;
}
auto s = segment_writer->append_chunk(chunk);
if (!s.ok()) {
LOG(WARNING) << "Fail to append chunk, " << s.to_string();
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
{
std::lock_guard<std::mutex> l(_lock);
_num_rows_written += chunk.num_rows();
_total_row_size += chunk.bytes_usage();
}
RETURN_NOT_OK(_flush_segment_writer(&segment_writer));
return OLAP_SUCCESS;
}
OLAPStatus HorizontalBetaRowsetWriter::flush_chunk_with_deletes(const vectorized::Chunk& upserts,
const vectorized::Column& deletes) {
if (!deletes.empty()) {
auto path = BetaRowset::segment_del_file_path(_context.rowset_path_prefix, _context.rowset_id, _num_segment);
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions opts({path});
Status st = _context.block_mgr->create_block(opts, &wblock);
if (!st.ok()) {
LOG(WARNING) << "Fail to create writable block=" << path << ", " << st.to_string();
return OLAP_ERR_INIT_FAILED;
}
size_t sz = deletes.serialize_size();
// TODO(cbl): temp buffer doubles the memory usage, need to optimize
string content;
content.resize(sz);
const_cast<vectorized::Column&>(deletes).serialize_column((uint8_t*)(content.data()));
st = wblock->append(Slice(content.data(), content.size()));
if (!st.ok()) {
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
st = wblock->finalize();
if (!st.ok()) {
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
st = wblock->close();
if (!st.ok()) {
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
_segment_has_deletes.resize(_num_segment + 1, false);
_segment_has_deletes[_num_segment] = true;
}
return flush_chunk(upserts);
}
OLAPStatus HorizontalBetaRowsetWriter::add_rowset(RowsetSharedPtr rowset) {
assert(rowset->rowset_meta()->rowset_type() == BETA_ROWSET);
if (!rowset->link_files_to(_context.rowset_path_prefix, _context.rowset_id).ok()) {
return OLAP_ERR_OTHER_ERROR;
}
_num_rows_written += rowset->num_rows();
_total_row_size += rowset->total_row_size();
_total_data_size += rowset->rowset_meta()->data_disk_size();
_total_index_size += rowset->rowset_meta()->index_disk_size();
_num_segment += rowset->num_segments();
// TODO update zonemap
if (rowset->rowset_meta()->has_delete_predicate()) {
_rowset_meta->set_delete_predicate(rowset->rowset_meta()->delete_predicate());
}
return OLAP_SUCCESS;
}
OLAPStatus HorizontalBetaRowsetWriter::add_rowset_for_linked_schema_change(RowsetSharedPtr rowset,
const SchemaMapping& schema_mapping) {
// TODO use schema_mapping to transfer zonemap
return add_rowset(rowset);
}
OLAPStatus HorizontalBetaRowsetWriter::flush() {
if (_segment_writer != nullptr) {
RETURN_NOT_OK(_flush_segment_writer(&_segment_writer));
}
return OLAP_SUCCESS;
}
RowsetSharedPtr HorizontalBetaRowsetWriter::build() {
if (!_tmp_segment_files.empty()) {
auto s = _final_merge();
if (!s.ok()) {
LOG(WARNING) << "final merge error: " << s.to_string();
return nullptr;
}
}
// When building a rowset, we must ensure that the current _segment_writer has been
// flushed, that is, the current _segment_wirter is nullptr
DCHECK(_segment_writer == nullptr) << "segment must be null when build rowset";
return BetaRowsetWriter::build();
}
// why: when the data is large, multi segment files created, may be OVERLAPPINGed.
// what: do final merge for NONOVERLAPPING state among segment files
// when: segment files number larger than one, no delete files(for now, ignore it when just one segment)
// how: for final merge scenario, temporary files created at first, merge them, create final segment files.
Status HorizontalBetaRowsetWriter::_final_merge() {
if (_num_segment == 1) {
auto old_path = BetaRowset::segment_temp_file_path(_context.rowset_path_prefix, _context.rowset_id, 0);
auto new_path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, 0);
auto st = _context.env->rename_file(old_path, new_path);
RETURN_IF_ERROR_WITH_WARN(st, "Fail to rename file");
return Status::OK();
}
if (!std::all_of(_segment_has_deletes.cbegin(), _segment_has_deletes.cend(), std::logical_not<bool>())) {
return Status::NotSupported("multi-segments with delete not supported.");
}
MonotonicStopWatch timer;
timer.start();
auto schema = vectorized::ChunkHelper::convert_schema_to_format_v2(*_context.tablet_schema);
std::vector<vectorized::ChunkIteratorPtr> seg_iterators;
seg_iterators.reserve(_num_segment);
vectorized::SegmentReadOptions seg_options;
seg_options.block_mgr = _context.block_mgr;
OlapReaderStatistics stats;
seg_options.stats = &stats;
for (int seg_id = 0; seg_id < _num_segment; ++seg_id) {
std::string tmp_segment_file =
BetaRowset::segment_temp_file_path(_context.rowset_path_prefix, _context.rowset_id, seg_id);
auto segment_ptr = segment_v2::Segment::open(ExecEnv::GetInstance()->tablet_meta_mem_tracker(),
fs::fs_util::block_manager(), tmp_segment_file, seg_id,
_context.tablet_schema);
if (!segment_ptr.ok()) {
LOG(WARNING) << "Fail to open " << tmp_segment_file << ": " << segment_ptr.status();
return segment_ptr.status();
}
if ((*segment_ptr)->num_rows() == 0) {
continue;
}
auto res = (*segment_ptr)->new_iterator(schema, seg_options);
if (res.status().is_end_of_file()) {
continue;
} else if (!res.ok()) {
return res.status();
} else if (res.value() == nullptr) {
continue;
} else {
seg_iterators.emplace_back(res.value());
}
}
ChunkIteratorPtr itr = nullptr;
// schema change vecotrized
// schema change with sorting create temporary segment files first
// merge them and create final segment files if _context.write_tmp is true
if (_context.write_tmp) {
if (_context.tablet_schema->keys_type() == KeysType::UNIQUE_KEYS) {
itr = new_heap_merge_iterator(seg_iterators);
} else if (_context.tablet_schema->keys_type() == KeysType::AGG_KEYS) {
itr = new_aggregate_iterator(new_heap_merge_iterator(seg_iterators), 0);
} else {
for (int seg_id = 0; seg_id < _num_segment; ++seg_id) {
auto old_path =
BetaRowset::segment_temp_file_path(_context.rowset_path_prefix, _context.rowset_id, seg_id);
auto new_path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, seg_id);
RETURN_IF_ERROR_WITH_WARN(_context.env->rename_file(old_path, new_path), "Fail to rename file");
}
_context.write_tmp = false;
return Status::OK();
}
_context.write_tmp = false;
} else {
itr = new_aggregate_iterator(new_heap_merge_iterator(seg_iterators), 0);
}
itr->init_encoded_schema(vectorized::EMPTY_GLOBAL_DICTMAPS);
auto chunk_shared_ptr = vectorized::ChunkHelper::new_chunk(schema, config::vector_chunk_size);
auto chunk = chunk_shared_ptr.get();
_num_segment = 0;
_num_rows_written = 0;
_total_data_size = 0;
_total_index_size = 0;
// since the segment already NONOVERLAPPING here, make the _create_segment_writer
// method to create segment data files, rather than temporary segment files.
_context.segments_overlap = NONOVERLAPPING;
auto char_field_indexes = vectorized::ChunkHelper::get_char_field_indexes(schema);
size_t total_rows = 0;
size_t total_chunk = 0;
while (true) {
chunk->reset();
auto st = itr->get_next(chunk);
if (st.is_end_of_file()) {
break;
} else if (st.ok()) {
vectorized::ChunkHelper::padding_char_columns(char_field_indexes, schema, *_context.tablet_schema, chunk);
total_rows += chunk->num_rows();
total_chunk++;
add_chunk(*chunk);
} else {
return st;
}
}
itr->close();
flush();
timer.stop();
LOG(INFO) << "rowset writer final merge finished. tablet:" << _context.tablet_id
<< " #key:" << schema.num_key_fields() << " input("
<< "entry=" << seg_iterators.size() << " rows=" << stats.raw_rows_read
<< " bytes=" << PrettyPrinter::print(stats.bytes_read, TUnit::UNIT) << ") output(rows=" << total_rows
<< " chunk=" << total_chunk << " bytes=" << PrettyPrinter::print(total_data_size(), TUnit::UNIT)
<< ") duration: " << timer.elapsed_time() / 1000000 << "ms";
for (const auto& tmp_segment_file : _tmp_segment_files) {
// Even if an error is encountered, these files that have not been cleaned up
// will be cleaned up by the GC background. So here we only print the error
// message when we encounter an error.
auto st = _context.env->delete_file(tmp_segment_file);
RETURN_IF_ERROR_WITH_WARN(st, "Fail to delete segment temp file");
}
_tmp_segment_files.clear();
return Status::OK();
}
OLAPStatus HorizontalBetaRowsetWriter::_flush_segment_writer(
std::unique_ptr<segment_v2::SegmentWriter>* segment_writer) {
uint64_t segment_size;
uint64_t index_size;
Status s = (*segment_writer)->finalize(&segment_size, &index_size);
if (!s.ok()) {
LOG(WARNING) << "Fail to finalize segment, " << s.to_string();
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
{
std::lock_guard<std::mutex> l(_lock);
_total_data_size += segment_size;
_total_index_size += index_size;
}
if (_src_rssids) {
Status st = flush_src_rssids(_segment_writer->segment_id());
if (!st.ok()) {
LOG(WARNING) << "flush_src_rssids error: " << st.to_string();
return OLAP_ERR_IO_ERROR;
}
}
// check global_dict efficacy
const auto& seg_global_dict_columns_valid_info = (*segment_writer)->global_dict_columns_valid_info();
for (const auto& it : seg_global_dict_columns_valid_info) {
if (it.second == false) {
_global_dict_columns_valid_info[it.first] = false;
} else {
if (const auto& iter = _global_dict_columns_valid_info.find(it.first);
iter == _global_dict_columns_valid_info.end()) {
_global_dict_columns_valid_info[it.first] = true;
}
}
}
(*segment_writer).reset();
return OLAP_SUCCESS;
}
VerticalBetaRowsetWriter::VerticalBetaRowsetWriter(const RowsetWriterContext& context) : BetaRowsetWriter(context) {}
VerticalBetaRowsetWriter::~VerticalBetaRowsetWriter() {
if (!_already_built) {
for (auto& segment_writer : _segment_writers) {
segment_writer.reset();
}
for (int i = 0; i < _num_segment; ++i) {
auto path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, i);
// Even if an error is encountered, these files that have not been cleaned up
// will be cleaned up by the GC background. So here we only print the error
// message when we encounter an error.
auto st = _context.env->delete_file(path);
LOG_IF(WARNING, !st.ok()) << "Fail to delete file=" << path << ", " << st.to_string();
}
}
}
OLAPStatus VerticalBetaRowsetWriter::add_columns(const vectorized::Chunk& chunk,
const std::vector<uint32_t>& column_indexes, bool is_key) {
auto segment_writer_add_chunk = [&](const vectorized::Chunk& chunk) -> OLAPStatus {
auto s = _segment_writers[_current_writer_index]->append_chunk(chunk);
if (!s.ok()) {
LOG(WARNING) << "Fail to append chunk by columns. st=" << s.to_string();
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
return OLAP_SUCCESS;
};
size_t chunk_num_rows = chunk.num_rows();
if (_segment_writers.empty()) {
DCHECK(is_key);
std::unique_ptr<segment_v2::SegmentWriter> segment_writer = _create_segment_writer(column_indexes, is_key);
if (segment_writer == nullptr) {
return OLAP_ERR_INIT_FAILED;
}
_segment_writers.emplace_back(std::move(segment_writer));
_current_writer_index = 0;
RETURN_NOT_OK(segment_writer_add_chunk(chunk));
} else if (is_key) {
// key columns
if (_segment_writers[_current_writer_index]->num_rows_written() + chunk_num_rows >=
_context.max_rows_per_segment) {
RETURN_NOT_OK(_flush_columns(&_segment_writers[_current_writer_index]));
std::unique_ptr<segment_v2::SegmentWriter> segment_writer = _create_segment_writer(column_indexes, is_key);
if (segment_writer == nullptr) {
return OLAP_ERR_INIT_FAILED;
}
_segment_writers.emplace_back(std::move(segment_writer));
++_current_writer_index;
}
RETURN_NOT_OK(segment_writer_add_chunk(chunk));
} else {
// non key columns
uint32_t num_rows_written = _segment_writers[_current_writer_index]->num_rows_written();
uint32_t segment_num_rows = _segment_writers[_current_writer_index]->num_rows();
DCHECK_LE(num_rows_written, segment_num_rows);
// init segment writer
if (_current_writer_index == 0 && num_rows_written == 0) {
auto s = _segment_writers[_current_writer_index]->init(column_indexes, is_key);
if (!s.ok()) {
LOG(WARNING) << "Fail to init segment writer, " << s.to_string();
return OLAP_ERR_INIT_FAILED;
}
}
if (num_rows_written + chunk_num_rows <= segment_num_rows) {
RETURN_NOT_OK(segment_writer_add_chunk(chunk));
} else {
// split into multi chunks and write into multi segments
auto write_chunk = chunk.clone_empty();
size_t num_left_rows = chunk_num_rows;
size_t offset = 0;
while (num_left_rows > 0) {
if (segment_num_rows == num_rows_written) {
RETURN_NOT_OK(_flush_columns(&_segment_writers[_current_writer_index]));
++_current_writer_index;
auto s = _segment_writers[_current_writer_index]->init(column_indexes, is_key);
if (!s.ok()) {
LOG(WARNING) << "Fail to init segment writer, " << s.to_string();
return OLAP_ERR_INIT_FAILED;
}
num_rows_written = _segment_writers[_current_writer_index]->num_rows_written();
segment_num_rows = _segment_writers[_current_writer_index]->num_rows();
}
size_t write_size = segment_num_rows - num_rows_written;
if (write_size > num_left_rows) {
write_size = num_left_rows;
}
write_chunk->append(chunk, offset, write_size);
RETURN_NOT_OK(segment_writer_add_chunk(*write_chunk));
write_chunk->reset();
num_left_rows -= write_size;
offset += write_size;
num_rows_written = _segment_writers[_current_writer_index]->num_rows_written();
}
DCHECK_EQ(0, num_left_rows);
DCHECK_EQ(offset, chunk_num_rows);
}
}
if (is_key) {
_num_rows_written += chunk_num_rows;
}
_total_row_size += chunk.bytes_usage();
return OLAP_SUCCESS;
}
OLAPStatus VerticalBetaRowsetWriter::add_columns_with_rssid(const vectorized::Chunk& chunk,
const std::vector<uint32_t>& column_indexes,
const std::vector<uint32_t>& rssid) {
RETURN_NOT_OK(add_columns(chunk, column_indexes, true));
if (!_src_rssids) {
_src_rssids = std::make_unique<std::vector<uint32_t>>();
}
_src_rssids->insert(_src_rssids->end(), rssid.begin(), rssid.end());
return OLAP_SUCCESS;
}
OLAPStatus VerticalBetaRowsetWriter::flush_columns() {
if (_segment_writers.empty()) {
return OLAP_SUCCESS;
}
DCHECK(_segment_writers[_current_writer_index]);
RETURN_NOT_OK(_flush_columns(&_segment_writers[_current_writer_index]));
_current_writer_index = 0;
return OLAP_SUCCESS;
}
OLAPStatus VerticalBetaRowsetWriter::final_flush() {
if (_segment_writers.empty()) {
return OLAP_SUCCESS;
}
for (auto& segment_writer : _segment_writers) {
uint64_t segment_size = 0;
Status s = segment_writer->finalize_footer(&segment_size);
if (!s.ok()) {
LOG(WARNING) << "Fail to finalize segment footer, " << s.to_string();
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
{
std::lock_guard<std::mutex> l(_lock);
_total_data_size += segment_size;
}
// check global_dict efficacy
const auto& seg_global_dict_columns_valid_info = segment_writer->global_dict_columns_valid_info();
for (const auto& it : seg_global_dict_columns_valid_info) {
if (!it.second) {
_global_dict_columns_valid_info[it.first] = false;
} else {
if (const auto& iter = _global_dict_columns_valid_info.find(it.first);
iter == _global_dict_columns_valid_info.end()) {
_global_dict_columns_valid_info[it.first] = true;
}
}
}
segment_writer.reset();
}
return OLAP_SUCCESS;
}
std::unique_ptr<segment_v2::SegmentWriter> VerticalBetaRowsetWriter::_create_segment_writer(
const std::vector<uint32_t>& column_indexes, bool is_key) {
std::lock_guard<std::mutex> l(_lock);
std::string path = BetaRowset::segment_file_path(_context.rowset_path_prefix, _context.rowset_id, _num_segment);
std::unique_ptr<fs::WritableBlock> wblock;
fs::CreateBlockOptions opts({path});
Status st = _context.block_mgr->create_block(opts, &wblock);
if (!st.ok()) {
LOG(WARNING) << "Fail to create writable block=" << path << ", " << st.to_string();
return nullptr;
}
DCHECK(wblock != nullptr);
segment_v2::SegmentWriterOptions writer_options;
writer_options.storage_format_version = _context.storage_format_version;
const auto* schema = _rowset_schema != nullptr ? _rowset_schema.get() : _context.tablet_schema;
writer_options.global_dicts = _context.global_dicts != nullptr ? _context.global_dicts : nullptr;
std::unique_ptr<segment_v2::SegmentWriter> segment_writer =
std::make_unique<segment_v2::SegmentWriter>(std::move(wblock), _num_segment, schema, writer_options);
auto s = segment_writer->init(column_indexes, is_key);
if (!s.ok()) {
LOG(WARNING) << "Fail to init segment writer, " << s.to_string();
segment_writer.reset(nullptr);
return nullptr;
}
++_num_segment;
return segment_writer;
}
OLAPStatus VerticalBetaRowsetWriter::_flush_columns(std::unique_ptr<segment_v2::SegmentWriter>* segment_writer) {
uint64_t index_size = 0;
Status s = (*segment_writer)->finalize_columns(&index_size);
if (!s.ok()) {
LOG(WARNING) << "Fail to finalize segment columns, " << s.to_string();
return OLAP_ERR_WRITER_DATA_WRITE_ERROR;
}
{
std::lock_guard<std::mutex> l(_lock);
_total_index_size += index_size;
}
if (_src_rssids) {
Status st = flush_src_rssids((*segment_writer)->segment_id());
if (!st.ok()) {
LOG(WARNING) << "flush_src_rssids error: " << st.to_string();
return OLAP_ERR_IO_ERROR;
}
}
return OLAP_SUCCESS;
}
} // namespace starrocks
| 43.719603 | 119 | 0.648022 | [
"vector"
] |
9ce1d97da432b7347eae7554173d6fd108ca838e | 15,155 | cpp | C++ | libs/outcome/doc/src/snippets/finale.cpp | ztchu/boost_1_70_0 | f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250 | [
"BSL-1.0"
] | 32 | 2018-05-14T23:26:54.000Z | 2020-06-14T10:13:20.000Z | libs/outcome/doc/src/snippets/finale.cpp | ztchu/boost_1_70_0 | f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250 | [
"BSL-1.0"
] | 79 | 2018-08-01T11:50:45.000Z | 2020-11-17T13:40:06.000Z | libs/outcome/doc/src/snippets/finale.cpp | ztchu/boost_1_70_0 | f86bf1a4ad9efe7b2d76e4878ea240ac35ca4250 | [
"BSL-1.0"
] | 14 | 2021-01-08T05:05:19.000Z | 2022-03-27T14:56:56.000Z | /* Example of how to marshall Outcomes at namespace boundaries
(C) 2017-2019 Niall Douglas <http://www.nedproductions.biz/> (149 commits)
Boost Software License - Version 1.0 - August 17th, 2003
Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:
The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.
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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include "../../../include/boost/outcome.hpp"
#if __has_include("../../../../quickcpplib/include/string_view.hpp")
#include "../../../../quickcpplib/include/string_view.hpp"
#else
#include "../../../include/boost/outcome/quickcpplib/include/string_view.hpp"
#endif
#include <cstring> // for memcpy
#include <experimental/filesystem>
//! [httplib]
// This is some standalone library implementing high level HTTP
namespace httplib
{
// These are the error code that this HTTP library can return
enum class status_code
{
success = 0, // not the HTTP success code of 200
// A subset of all HTTP status codes for brevity
bad_request = 400,
access_denied = 401,
logon_failed = 402,
forbidden = 403,
not_found = 404,
internal_error = 500
};
// This is the error type that this HTTP library can return
struct failure
{
status_code status{status_code::success};
std::string url{}; // The failing URL
};
// Localise a result implementation to this library, holding
// the logic error of incorrect observation to mean program
// termination.
template <class T>
using result = //
BOOST_OUTCOME_V2_NAMESPACE::result<T, failure, BOOST_OUTCOME_V2_NAMESPACE::policy::terminate>;
/* Performs a HTTP GET on the url, returning the body if successful,
a failure with status_code if unsuccessful at the HTTP level, or a
C++ exception throw if something catastrophic happened e.g. bad_alloc
*/
result<std::string> get(std::string url);
} // namespace httplib
//! [httplib]
namespace httplib
{
result<std::string> get(std::string url)
{
(void) url;
#if 1
return "hello world";
#else
return failure{status_code::not_found, url};
#endif
}
} // namespace httplib
namespace filelib
{
using QUICKCPPLIB_NAMESPACE::string_view::string_view;
using std::experimental::filesystem::filesystem_error;
using std::experimental::filesystem::path;
} // namespace filelib
namespace app
{
using QUICKCPPLIB_NAMESPACE::string_view::string_view;
}
//! [filelib]
// You may remember this from the tutorial section on Custom Payloads
namespace filelib
{
// Error code + paths related to a failure. Also causes ADL discovery
// to check this namespace.
struct failure_info
{
std::error_code ec;
path path1{}, path2{};
};
// Tell Outcome that failure_info is to be treated as a std::error_code
inline const std::error_code &make_error_code(const failure_info &fi) { return fi.ec; }
// Tell Outcome that no-value observation should throw a custom exception
inline void outcome_throw_as_system_error_with_payload(failure_info fi)
{
// If the error code is not filesystem related e.g. ENOMEM, throw that
// as a standard STL exception.
BOOST_OUTCOME_V2_NAMESPACE::try_throw_std_exception_from_error(fi.ec);
// Throw the exact same filesystem_error exception which the throwing
// copy_file() edition does.
throw filesystem_error(fi.ec.message(), std::move(fi.path1), std::move(fi.path2), fi.ec);
}
// Localise a result implementation specific to this namespace.
template <class T> using result = BOOST_OUTCOME_V2_NAMESPACE::result<T, failure_info>;
// Writes a chunk of data to some file. Returns bytes written, or
// failure_info. Never throws exceptions.
result<size_t> write_file(string_view chunk) noexcept;
} // namespace filelib
//! [filelib]
namespace filelib
{
result<size_t> write_file(string_view chunk) noexcept
{
(void) chunk;
return failure_info{make_error_code(std::errc::no_space_on_device), "somepath"};
}
} // namespace filelib
//! [tidylib]
// There actually is a library for tidying HTML into XHTML called HTMLTidy
// See http://www.html-tidy.org/
// HTMLTidy is actually a great tool for dealing with 1990s-era tag soup
// HTML, I highly recommend it.
// This isn't the API for Tidy, but let's assume it's a C library returning
// errno domained error codes. out must be freed with free() after use.
extern "C" int tidy_html(char **out, size_t *outlen, const char *in, size_t inlen);
//! [tidylib]
extern "C" int tidy_html(char **out, size_t *outlen, const char *in, size_t inlen)
{
#if 1
*out = (char *) malloc(inlen + 1);
memcpy(*out, in, inlen + 1);
*outlen = inlen;
return 0;
#else
// return ENOMEM;
return EROFS;
#endif
}
//! [app]
// This is the namespace of the application which is connecting together the httplib,
// filelib and tidylib libraries into a solution.
namespace app
{
// Create an ADL bridge so copy/move hooks will be searched for in this namespace
struct error_code : public std::error_code
{
// passthrough
using std::error_code::error_code;
error_code() = default;
error_code(std::error_code ec)
: std::error_code(ec)
{
}
};
// Localise an outcome implementation for this namespace
template <class T>
using outcome = //
BOOST_OUTCOME_V2_NAMESPACE::outcome<T, error_code /*, std::exception_ptr */>;
using BOOST_OUTCOME_V2_NAMESPACE::success;
} // namespace app
//! [app]
//! [app_map_httplib1]
namespace app
{
// Specialise an exception type for httplib errors
struct httplib_error : std::runtime_error
{
// passthrough
using std::runtime_error::runtime_error;
httplib_error(httplib::failure _failure, std::string msg)
: std::runtime_error(std::move(msg))
, failure(std::move(_failure))
{
}
// the original failure
httplib::failure failure;
};
// Type erase httplib::result<U> into a httplib_error exception ptr
template <class U> //
inline std::exception_ptr make_httplib_exception(const httplib::result<U> &src)
{
std::string str("httplib failed with error ");
switch(src.error().status)
{
case httplib::status_code::success:
str.append("success");
break;
case httplib::status_code::bad_request:
str.append("bad request");
break;
case httplib::status_code::access_denied:
str.append("access denied");
break;
case httplib::status_code::logon_failed:
str.append("logon failed");
break;
case httplib::status_code::forbidden:
str.append("forbidden");
break;
case httplib::status_code::not_found:
str.append("not found");
break;
case httplib::status_code::internal_error:
str.append("internal error");
break;
}
str.append(" [url was ");
str.append(src.error().url);
str.append("]");
return std::make_exception_ptr(httplib_error(src.error(), std::move(str)));
}
} // namespace app
//! [app_map_httplib1]
//! [app_map_httplib2]
// Inject custom ValueOrError conversion
BOOST_OUTCOME_V2_NAMESPACE_BEGIN
namespace convert
{
// Provide custom ValueOrError conversion from
// httplib::result<U> into any app::outcome<T>
template <class T, class U> //
struct value_or_error<app::outcome<T>, httplib::result<U>>
{
// False to indicate that this converter wants `result`/`outcome`
// to NOT reject all other `result`
static constexpr bool enable_result_inputs = true;
// False to indicate that this converter wants `outcome` to NOT
// reject all other `outcome`
static constexpr bool enable_outcome_inputs = true;
template <class X, //
typename = std::enable_if_t<std::is_same<httplib::result<U>, std::decay_t<X>>::value //
&& std::is_constructible<T, U>::value>> //
constexpr app::outcome<T> operator()(X &&src)
{
// Forward any successful value, else synthesise an exception ptr
return src.has_value() ? //
app::outcome<T>{std::forward<X>(src).value()} //
:
app::outcome<T>{app::make_httplib_exception(std::forward<X>(src))};
}
};
} // namespace convert
BOOST_OUTCOME_V2_NAMESPACE_END
//! [app_map_httplib2]
namespace app
{
static outcome<int> test_value_or_error2 = BOOST_OUTCOME_V2_NAMESPACE::convert::value_or_error<outcome<int>, httplib::result<int>>{}(httplib::result<int>{5});
static outcome<int> test_value_or_error3(httplib::result<int>{5});
} // namespace app
//! [app_map_filelib]
// Inject custom ValueOrError conversion
BOOST_OUTCOME_V2_NAMESPACE_BEGIN
namespace convert
{
// Provide custom ValueOrError conversion from filelib::result<U>
// into any app::outcome<T>
template <class T, class U> //
struct value_or_error<app::outcome<T>, filelib::result<U>>
{
// True to indicate that this converter wants `result`/`outcome`
// to NOT reject all other `result`
static constexpr bool enable_result_inputs = true;
// False to indicate that this converter wants `outcome` to NOT
// reject all other `outcome`
static constexpr bool enable_outcome_inputs = true;
template <class X, //
typename = std::enable_if_t<std::is_same<filelib::result<U>, std::decay_t<X>>::value //
&& std::is_constructible<T, U>::value>> //
constexpr app::outcome<T> operator()(X &&src)
{
// Forward any successful value
if(src.has_value())
{
return {std::forward<X>(src).value()};
}
// Synthesise a filesystem_error, exactly as if someone had
// called src.value()
auto &fi = src.error();
BOOST_OUTCOME_V2_NAMESPACE::try_throw_std_exception_from_error(fi.ec); // might throw
return {std::make_exception_ptr( //
filelib::filesystem_error(fi.ec.message(), std::move(fi.path1), std::move(fi.path2), fi.ec))};
}
};
} // namespace convert
BOOST_OUTCOME_V2_NAMESPACE_END
//! [app_map_filelib]
//! [app_map_tidylib]
namespace app
{
// Specialise an exception type for tidylib errors
struct tidylib_error : std::system_error
{
// passthrough
using std::system_error::system_error;
tidylib_error() = default;
explicit tidylib_error(int c)
: std::system_error(c, std::generic_category())
{
}
};
// Create a C++ invoking wrapper for the tidylib C API, modifying data with the returned data,
// returing a unique_ptr to release storage on scope exit.
struct call_free
{
template <class T> void operator()(T *p) { ::free(p); }
};
inline outcome<std::unique_ptr<char, call_free>> tidy_html(string_view &data)
{
char *out = nullptr;
size_t outlen = 0;
int errcode = ::tidy_html(&out, &outlen, data.data(), data.size());
if(errcode != 0)
{
// If the error code matches a standard STL exception, throw as that.
BOOST_OUTCOME_V2_NAMESPACE::try_throw_std_exception_from_error(std::error_code(errcode, std::generic_category()));
// Otherwise wrap the error code into a tidylib_error exception throw
return std::make_exception_ptr(tidylib_error(errcode));
}
// Reset input view to tidied html
data = string_view(out, outlen);
// Return a unique ptr to release storage on scope exit
return std::unique_ptr<char, call_free>(out);
}
} // namespace app
//! [app_map_tidylib]
//! [app_go]
namespace app
{
// A markup function to indicate when we are ValueOrError converting
template <class T> inline outcome<typename T::value_type> ext(T &&v)
{ //
return outcome<typename T::value_type>(std::move(v));
}
outcome<void> go() // NOT noexcept, this can throw STL exceptions e.g. bad_alloc
{
// Note that explicit construction is required when converting between differing types
// of outcome and result. This makes it explicit what you intend to do as conversion
// may be a lot more expensive than moves.
// Try to GET this URL. If an unsuccessful HTTP status is returned, serialise a string
// containing a description of the HTTP status code and the URL which failed, storing
// that into a httplib_error exception type which is stored as an exception ptr. The
// TRY operation below will return that exception ptr to be rethrown in the caller.
// Otherwise the fetched data is returned in a std::string data.
BOOST_OUTCOME_TRY(data, ext(httplib::get("http://www.nedproductions.biz/")));
string_view data_view(data);
// HTML tidy the fetched data. If the C library fails due to an error corresponding to
// a standard library exception type, throw that. Otherwise, synthesise an exception
// ptr of type tidylib_error which stores the error code returned in an error code with
// generic category (i.e. errno domain).
// TRY operation below will return that exception ptr to be rethrown in the caller.
// Otherwise the tidied data is returned into holdmem, with the string view updated to
// point at the tidied data.
BOOST_OUTCOME_TRY(holdmem, ext(tidy_html(data_view)));
// Write the tidied data to some file. If the write fails, synthesise a filesystem_error
// exception ptr exactly as if one called filelib::write_file(data_view).value().
BOOST_OUTCOME_TRY(written, ext(filelib::write_file(data_view)));
return success();
}
} // namespace app
//! [app_go]
int main()
{
try
{
app::go().value();
}
catch(const filelib::filesystem_error &e)
{
std::cerr << "Exception thrown, " << e.what() //
<< " (path1 = " << e.path1() << ", path2 = " << e.path2() << ")" //
<< std::endl;
return 1;
}
catch(const std::exception &e)
{
std::cerr << "Exception thrown, " << e.what() << std::endl;
return 1;
}
return 0;
} | 35.408879 | 160 | 0.681755 | [
"object"
] |
9ce312c2119960a9d168ce69ec1ae7dbf07dc161 | 648 | cc | C++ | codeforces/1305/a.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | codeforces/1305/a.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | codeforces/1305/a.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://codeforces.com/contest/1305/problem/A
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ii = tuple<int, int>;
using vi = vector<ll>;
using vii = vector<ii>;
using vvi = vector<vi>;
using si = set<ll>;
int main() {
cin.tie(0), ios::sync_with_stdio(0);
ll n, t;
cin >> t;
while (t--) {
cin >> n;
vi a(n), b(n);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) cin >> b[i];
sort(a.begin(), a.end());
sort(b.begin(), b.end());
for (int i = 0; i < n; i++) cout << a[i] << " \n"[i == n-1];
for (int i = 0; i < n; i++) cout << b[i] << " \n"[i == n-1];
}
}
| 24 | 64 | 0.49537 | [
"vector"
] |
9ce3c4f17475678fe50005ffa8774ec5d00efaa4 | 7,716 | cpp | C++ | REDSI_1160929_1161573/boost_1_67_0/libs/detail/test/binary_search_test.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 32 | 2019-02-27T06:57:07.000Z | 2021-08-29T10:56:19.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/detail/test/binary_search_test.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 1 | 2019-04-04T18:00:00.000Z | 2019-04-04T18:00:00.000Z | REDSI_1160929_1161573/boost_1_67_0/libs/detail/test/binary_search_test.cpp | Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo | eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8 | [
"MIT"
] | 5 | 2019-08-20T13:45:04.000Z | 2022-03-01T18:23:49.000Z | // (C) Copyright David Abrahams 2000.
// 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 <vector>
#include <string>
#include <memory>
#include <climits>
#include <iostream>
#include <cassert>
#include <stdlib.h> // for rand(). Would use cstdlib but VC6.4 doesn't put it in std::
#include <list>
#include <algorithm>
#include <boost/detail/binary_search.hpp>
#include <boost/detail/workaround.hpp>
#include <cstddef>
#if defined(__SGI_STL_PORT) ? defined(__SGI_STL_OWN_IOSTREAMS) : (!defined(__GNUC__) || __GNUC__ > 2)
# define USE_SSTREAM
#endif
#ifdef USE_SSTREAM
# include <sstream>
#else
# include <strstream>
#endif
namespace {
// In order to get ADL to find the comparison operators defined below, they have
struct mystring : std::string
{
typedef std::string base;
mystring(std::string const& x)
: base(x) {}
};
typedef std::vector<mystring> string_vector;
const std::size_t sequence_length = 1000;
unsigned random_number()
{
return static_cast<unsigned>(::rand()) % sequence_length;
}
# ifndef USE_SSTREAM
class unfreezer {
public:
unfreezer(std::ostrstream& s) : m_stream(s) {}
~unfreezer() { m_stream.freeze(false); }
private:
std::ostrstream& m_stream;
};
# endif
template <class T>
void push_back_random_number_string(T& seq)
{
unsigned value = random_number();
# if defined(__SGI_STL_PORT) ? defined(__SGI_STL_OWN_IOSTREAMS) : (!defined(__GNUC__) || __GNUC__ > 2)
std::ostringstream s;
s << value;
seq.push_back(s.str());
# else
std::ostrstream s;
auto unfreezer unfreeze(s);
s << value << char(0);
seq.push_back(std::string(s.str()));
# endif
}
inline unsigned to_int(unsigned x) { return x; }
inline unsigned to_int(const std::string& x) { return atoi(x.c_str()); }
struct cmp
{
template <class A1, class A2>
inline bool operator()(const A1& a1, const A2& a2) const
{
return to_int(a1) < to_int(a2);
}
};
inline bool operator<(const mystring& x, const unsigned y)
{
return to_int(x) < y;
}
inline bool operator<(const unsigned y, const mystring& x)
{
return y < to_int(x);
}
template <class T>
void sort_by_value(T& x);
template <class T>
void sort_by_value_(T& v, long)
{
std::sort(v.begin(), v.end(), cmp());
}
template <class T>
void random_sorted_sequence(T& seq)
{
seq.clear();
for (std::size_t i = 0; i < sequence_length; ++i)
{
push_back_random_number_string(seq);
}
sort_by_value(seq);
}
template <class T, class A>
void sort_by_value_(std::list<T,A>& l, int)
{
# if BOOST_WORKAROUND(BOOST_DINKUMWARE_STDLIB, == 1) && !defined(__SGI_STL_PORT)
// VC6's standard lib doesn't have a template member function for list::sort()
std::vector<T> seq;
seq.reserve(sequence_length);
std::copy(l.begin(), l.end(), std::back_inserter(seq));
sort_by_value(seq);
std::copy(seq.begin(), seq.end(), l.begin());
# else
l.sort(cmp());
# endif
}
template <class T>
void sort_by_value(T& x)
{
(sort_by_value_)(x, 1);
}
// A way to select the comparisons with/without a Compare parameter for testing.
template <class Compare> struct searches
{
template <class Iterator, class Key>
static Iterator lower_bound(Iterator start, Iterator finish, Key key, Compare cmp)
{ return boost::detail::lower_bound(start, finish, key, cmp); }
template <class Iterator, class Key>
static Iterator upper_bound(Iterator start, Iterator finish, Key key, Compare cmp)
{ return boost::detail::upper_bound(start, finish, key, cmp); }
template <class Iterator, class Key>
static std::pair<Iterator, Iterator> equal_range(Iterator start, Iterator finish, Key key, Compare cmp)
{ return boost::detail::equal_range(start, finish, key, cmp); }
template <class Iterator, class Key>
static bool binary_search(Iterator start, Iterator finish, Key key, Compare cmp)
{ return boost::detail::binary_search(start, finish, key, cmp); }
};
struct no_compare {};
template <> struct searches<no_compare>
{
template <class Iterator, class Key>
static Iterator lower_bound(Iterator start, Iterator finish, Key key, no_compare)
{ return boost::detail::lower_bound(start, finish, key); }
template <class Iterator, class Key>
static Iterator upper_bound(Iterator start, Iterator finish, Key key, no_compare)
{ return boost::detail::upper_bound(start, finish, key); }
template <class Iterator, class Key>
static std::pair<Iterator, Iterator> equal_range(Iterator start, Iterator finish, Key key, no_compare)
{ return boost::detail::equal_range(start, finish, key); }
template <class Iterator, class Key>
static bool binary_search(Iterator start, Iterator finish, Key key, no_compare)
{ return boost::detail::binary_search(start, finish, key); }
};
template <class Sequence, class Compare>
void test_loop(Sequence& x, Compare cmp, unsigned long test_count)
{
typedef typename Sequence::const_iterator const_iterator;
for (unsigned long i = 0; i < test_count; ++i)
{
random_sorted_sequence(x);
const const_iterator start = x.begin();
const const_iterator finish = x.end();
unsigned key = random_number();
const const_iterator l = searches<Compare>::lower_bound(start, finish, key, cmp);
const const_iterator u = searches<Compare>::upper_bound(start, finish, key, cmp);
bool found_l = false;
bool found_u = false;
std::size_t index = 0;
std::size_t count = 0;
unsigned last_value = 0;
(void)last_value;
for (const_iterator p = start; p != finish; ++p)
{
if (p == l)
found_l = true;
if (p == u)
{
assert(found_l);
found_u = true;
}
unsigned value = to_int(*p);
assert(value >= last_value);
last_value = value;
if (!found_l)
{
++index;
assert(to_int(*p) < key);
}
else if (!found_u)
{
++count;
assert(to_int(*p) == key);
}
else
assert(to_int(*p) > key);
}
assert(found_l || l == finish);
assert(found_u || u == finish);
std::pair<const_iterator, const_iterator>
range = searches<Compare>::equal_range(start, finish, key, cmp);
assert(range.first == l);
assert(range.second == u);
bool found = searches<Compare>::binary_search(start, finish, key, cmp);
(void)found;
assert(found == (u != l));
std::cout << "found " << count << " copies of " << key << " at index " << index << "\n";
}
}
}
int main()
{
string_vector x;
std::cout << "=== testing random-access iterators with <: ===\n";
test_loop(x, no_compare(), 25);
std::cout << "=== testing random-access iterators with compare: ===\n";
test_loop(x, cmp(), 25);
std::list<mystring> y;
std::cout << "=== testing bidirectional iterators with <: ===\n";
test_loop(y, no_compare(), 25);
std::cout << "=== testing bidirectional iterators with compare: ===\n";
test_loop(y, cmp(), 25);
std::cerr << "******TEST PASSED******\n";
return 0;
}
| 29.563218 | 108 | 0.609642 | [
"vector"
] |
9ce7e8d429492c8e1d3073469773e9fa0976a968 | 4,354 | cpp | C++ | libs/quadwild/libs/vcglib/apps/sample/trimesh_pointcloud_sampling/trimesh_pointcloud_sampling.cpp | Pentacode-IAFA/Quad-Remeshing | f8fd4c10abf1c54656b38a00b8a698b952a85fe2 | [
"Apache-2.0"
] | null | null | null | libs/quadwild/libs/vcglib/apps/sample/trimesh_pointcloud_sampling/trimesh_pointcloud_sampling.cpp | Pentacode-IAFA/Quad-Remeshing | f8fd4c10abf1c54656b38a00b8a698b952a85fe2 | [
"Apache-2.0"
] | null | null | null | libs/quadwild/libs/vcglib/apps/sample/trimesh_pointcloud_sampling/trimesh_pointcloud_sampling.cpp | Pentacode-IAFA/Quad-Remeshing | f8fd4c10abf1c54656b38a00b8a698b952a85fe2 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
* VCGLib o o *
* Visual and Computer Graphics Library o o *
* _ O _ *
* Copyright(C) 2004-2016 \/)\/ *
* Visual Computing Lab /\/| *
* ISTI - Italian National Research Council | *
* \ *
* All rights reserved. *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt) *
* for more details. *
* *
****************************************************************************/
#include<vcg/complex/complex.h>
#include<wrap/io_trimesh/import.h>
#include<wrap/io_trimesh/export.h>
#include<vcg/complex/algorithms/point_sampling.h>
#include<vcg/complex/algorithms/clustering.h>
using namespace vcg;
using namespace std;
class MyEdge;
class MyFace;
class MyVertex;
struct MyUsedTypes : public UsedTypes< Use<MyVertex> ::AsVertexType,
Use<MyEdge> ::AsEdgeType,
Use<MyFace> ::AsFaceType>{};
class MyVertex : public Vertex<MyUsedTypes, vertex::Coord3f, vertex::Normal3f, vertex::BitFlags >{};
class MyFace : public Face< MyUsedTypes, face::FFAdj, face::Normal3f, face::VertexRef, face::BitFlags > {};
class MyEdge : public Edge<MyUsedTypes>{};
class MyMesh : public tri::TriMesh< vector<MyVertex>, vector<MyFace> , vector<MyEdge> > {};
int main( int argc, char **argv )
{
if(argc<3)
{
printf("Usage trimesh_base <meshfilename> radius (as perc) (\n");
return -1;
}
MyMesh m;
MyMesh subM;
MyMesh cluM;
MyMesh rndM;
tri::MeshSampler<MyMesh> mps(subM);
tri::MeshSampler<MyMesh> mrs(rndM);
if(tri::io::Importer<MyMesh>::Open(m,argv[1])!=0)
{
printf("Error reading file %s\n",argv[1]);
exit(0);
}
tri::SurfaceSampling<MyMesh,tri::TrivialSampler<MyMesh> >::SamplingRandomGenerator().initialize(time(0));
float perc = atof(argv[2]);
float radius = m.bbox.Diag() * perc;
printf("Subsampling a PointCloud of %i vert with %f radius\n",m.VN(),radius);
tri::SurfaceSampling<MyMesh,tri::MeshSampler<MyMesh> >::PoissonDiskParam pp;
pp.bestSampleChoiceFlag=false;
tri::SurfaceSampling<MyMesh,tri::MeshSampler<MyMesh> >::PoissonDiskPruning(mps, m, radius, pp);
tri::io::ExporterPLY<MyMesh>::Save(subM,"PoissonMesh.ply");
printf("Sampled %i vertices in %5.2f\n",subM.VN(), float(pp.pds.pruneTime+pp.pds.gridTime)/float(CLOCKS_PER_SEC));
int t0=clock();
tri::Clustering<MyMesh, vcg::tri::AverageColorCell<MyMesh> > ClusteringGrid;
ClusteringGrid.Init(m.bbox,100000,radius*sqrt(2.0f));
ClusteringGrid.AddPointSet(m);
ClusteringGrid.ExtractMesh(cluM);
int t1=clock();
tri::io::ExporterPLY<MyMesh>::Save(cluM,"ClusterMesh.ply");
printf("Sampled %i vertices in %5.2f\n",cluM.VN(), float(t1-t0)/float(CLOCKS_PER_SEC));
int t2=clock();
int sampleNum = (cluM.VN()+subM.VN())/2;
tri::SurfaceSampling<MyMesh,tri::MeshSampler<MyMesh> >::VertexUniform(m, mrs,sampleNum);
int t3=clock();
tri::io::ExporterPLY<MyMesh>::Save(rndM,"RandomMesh.ply");
printf("Sampled %i vertices in %5.2f\n",rndM.VN(), float(t3-t2)/float(CLOCKS_PER_SEC));
return 0;
}
| 44.886598 | 116 | 0.538356 | [
"vector"
] |
9cea461d8591ea8c00415f1cd80be30086916d12 | 9,750 | cpp | C++ | src/util/func.cpp | mfournial/Faasm | f6c48b8b38b78c1b14a7b5557f3bccad9d4424ae | [
"Apache-2.0"
] | 1 | 2020-04-21T07:33:42.000Z | 2020-04-21T07:33:42.000Z | src/util/func.cpp | mfournial/Faasm | f6c48b8b38b78c1b14a7b5557f3bccad9d4424ae | [
"Apache-2.0"
] | 4 | 2020-02-03T18:54:32.000Z | 2020-05-13T18:28:28.000Z | src/util/func.cpp | mfournial/Faasm | f6c48b8b38b78c1b14a7b5557f3bccad9d4424ae | [
"Apache-2.0"
] | null | null | null | #include "func.h"
#include <iomanip>
#include <sstream>
#include <boost/filesystem.hpp>
#include <util/environment.h>
#include <util/random.h>
#include <util/gids.h>
#include <util/config.h>
#include <boost/algorithm/string.hpp>
#include <util/logging.h>
#include <util/json.h>
namespace util {
const static std::string pyFile = "function.py";
const static std::string funcFile = "function.wasm";
const static std::string symFile = "function.symbols";
const static std::string objFile = "function.wasm.o";
const static std::string confFile = "conf.json";
std::string getRootUrl() {
std::string rootUrl = util::getEnvVar("FILESERVER_URL", "");
if (rootUrl.empty()) {
throw std::runtime_error("Fileserver URL not set");
}
return rootUrl;
}
std::string getUrl(const message::Message &msg, const std::string &urlPart) {
std::string rootUrl = getRootUrl();
std::string funcUrl = rootUrl + "/" + urlPart + "/" + msg.user() + "/" + msg.function();
return funcUrl;
}
std::string getSharedObjectUrl() {
std::string rootUrl = getRootUrl();
return rootUrl + "/sobjwasm";
}
std::string getSharedObjectObjectUrl() {
std::string rootUrl = getRootUrl();
return rootUrl + "/sobjobj";
}
std::string getSharedFileUrl() {
std::string rootUrl = getRootUrl();
return rootUrl + "/file";
}
std::string getFunctionUrl(const message::Message &msg) {
return getUrl(msg, "f");
}
std::string getFunctionObjectUrl(const message::Message &msg) {
return getUrl(msg, "fo");
}
std::string getPythonFunctionUrl(const message::Message &msg) {
return getUrl(msg, "p");
}
std::string _doGetPythonFunctionFile(const message::Message &msg, const std::string &parentDir, bool createDirs) {
if (!msg.ispython()) {
throw std::runtime_error(
"Getting python function file for non-Python function " + funcToString(msg, false)
);
}
if(msg.pythonuser().empty() || msg.pythonfunction().empty()) {
throw std::runtime_error(
"Invalid Python call: user=" + msg.pythonuser() + " func=" + msg.pythonfunction()
);
}
boost::filesystem::path path(parentDir);
path.append(PYTHON_FUNC_DIR);
path.append(msg.pythonuser());
path.append(msg.pythonfunction());
if (createDirs) {
boost::filesystem::create_directories(path);
}
path.append(pyFile);
return path.string();
}
boost::filesystem::path _doGetDir(std::string baseDir, const message::Message &msg, bool create) {
boost::filesystem::path path(baseDir);
path.append(msg.user());
path.append(msg.function());
// Create directory if doesn't exist
if (create) {
boost::filesystem::create_directories(path);
}
return path;
}
boost::filesystem::path getFunctionDir(const message::Message &msg, bool create = true) {
SystemConfig &conf = util::getSystemConfig();
return _doGetDir(conf.functionDir, msg, create);
}
boost::filesystem::path getObjectDir(const message::Message &msg, bool create = true) {
SystemConfig &conf = util::getSystemConfig();
return _doGetDir(conf.objectFileDir, msg, create);
}
bool isValidFunction(const message::Message &msg) {
if (msg.user().empty() || msg.function().empty()) {
return false;
}
auto path = getFunctionDir(msg, false);
path.append("function.wasm");
bool isValid = boost::filesystem::exists(path);
return isValid;
}
std::string getFunctionKey(const message::Message &msg) {
std::string key = "wasm";
key += "/";
key += msg.user();
key += "/";
key += msg.function();
key += "/";
key += funcFile;
return key;
}
std::string getFunctionObjectKey(const message::Message &msg) {
std::string key = "wasm";
key += "/";
key += msg.user();
key += "/";
key += msg.function();
key += "/";
key += objFile;
return key;
}
std::string getPythonFunctionFile(const message::Message &msg) {
// Python functions are stored as shared files to make it easier to
// share them through the system
return _doGetPythonFunctionFile(msg, util::getSystemConfig().sharedFilesStorageDir, true);
}
std::string getPythonFunctionFileSharedPath(const message::Message &msg) {
// This is the shared path of the form faasm:// used to access the Python file
return _doGetPythonFunctionFile(msg, SHARED_FILE_PREFIX, false);
}
std::string getPythonRuntimeFunctionFile(const message::Message &msg) {
// This is the path where the file is placed at runtime to be
// accessible to the function
return _doGetPythonFunctionFile(msg, util::getSystemConfig().runtimeFilesDir, true);
}
std::string getFunctionFile(const message::Message &msg) {
auto path = getFunctionDir(msg);
path.append(funcFile);
return path.string();
}
std::string getFunctionSymbolsFile(const message::Message &msg) {
auto path = getFunctionDir(msg);
path.append(symFile);
return path.string();
}
std::string getFunctionObjectFile(const message::Message &msg) {
auto path = getObjectDir(msg);
path.append(objFile);
return path.string();
}
std::string getSharedObjectObjectFile(const std::string &realPath) {
boost::filesystem::directory_entry f(realPath);
const std::string directory = f.path().parent_path().string();
const std::string fileName = f.path().filename().string();
// Work out the final destination for the object file. This will be the
// object path with the directory of the original file appended
util::SystemConfig &conf = util::getSystemConfig();
boost::filesystem::path objPath(conf.objectFileDir);
objPath.append(directory);
// Create directory (if necessary)
create_directories(objPath);
// Add the filename
std::string outputFile = objPath.append(fileName).string();
outputFile += SHARED_OBJ_EXT;
return outputFile;
}
std::string getSharedFileFile(const std::string &path) {
SystemConfig &conf = util::getSystemConfig();
boost::filesystem::path p(conf.sharedFilesStorageDir);
p.append(path);
if (!boost::filesystem::exists(p.parent_path())) {
boost::filesystem::create_directories(p.parent_path());
}
return p.string();
}
std::vector<uint8_t> messageToBytes(const message::Message &msg) {
size_t byteSize = msg.ByteSizeLong();
uint8_t buffer[byteSize];
msg.SerializeToArray(buffer, (int) byteSize);
std::vector<uint8_t> inputData(buffer, buffer + byteSize);
return inputData;
}
std::string funcToString(const message::Message &msg, bool includeId) {
std::string str = msg.user() + "/" + msg.function();
if (includeId) {
str += ":" + std::to_string(msg.id());
}
return str;
}
std::string buildAsyncResponse(const message::Message &msg) {
if (msg.id() == 0) {
throw std::runtime_error("Message must have id to build async response");
}
return std::to_string(msg.id());
}
message::Message messageFactory(const std::string &user, const std::string &function) {
message::Message msg;
msg.set_user(user);
msg.set_function(function);
setMessageId(msg);
return msg;
}
void convertMessageToPython(message::Message &msg) {
msg.set_ispython(true);
msg.set_pythonfunction(msg.function());
msg.set_pythonuser(msg.user());
msg.set_user(PYTHON_USER);
msg.set_function(PYTHON_FUNC);
}
unsigned int setMessageId(message::Message &msg) {
// If message already has an ID, just make sure the keys are set up
unsigned int messageId;
if (msg.id() > 0) {
messageId = msg.id();
} else {
// Generate a random ID
messageId = util::generateGid();
msg.set_id(messageId);
}
std::string resultKey = resultKeyFromMessageId(messageId);
msg.set_resultkey(resultKey);
std::string statusKey = statusKeyFromMessageId(messageId);
msg.set_statuskey(statusKey);
return messageId;
}
std::string resultKeyFromMessageId(unsigned int mid) {
std::string k = "result_";
k += std::to_string(mid);
return k;
}
std::string statusKeyFromMessageId(unsigned int mid) {
std::string k = "status_";
k += std::to_string(mid);
return k;
}
std::vector<std::string> getArgvForMessage(const message::Message &msg) {
// We always have some arbitrary script name as argv[0]
std::vector<std::string> argv = {"function.wasm"};
std::string cmdlineArgs = msg.cmdline();
if (cmdlineArgs.empty()) {
return argv;
}
// Split the extra args
std::vector<std::string> extraArgs;
std::string copy(msg.cmdline());
boost::split(extraArgs, copy, [](char c) { return c == ' '; });
// Build the final list
argv.insert(argv.end(), extraArgs.begin(), extraArgs.end());
return argv;
}
}
| 30.092593 | 118 | 0.602154 | [
"object",
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.