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
a9bd14a7519bc34553ca1ee6844a68b3aa674746
3,664
cpp
C++
apps/standalone/cpu/registration/3d/register_CK_3d.cpp
roopchansinghv/gadgetron
fb6c56b643911152c27834a754a7b6ee2dd912da
[ "MIT" ]
1
2022-02-22T21:06:36.000Z
2022-02-22T21:06:36.000Z
apps/standalone/cpu/registration/3d/register_CK_3d.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
apps/standalone/cpu/registration/3d/register_CK_3d.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
/* An example of how to register two 3d volumes using Cornelius-Kanade optical flow */ // Gadgetron includes #include "hoCKOpticalFlowSolver.h" #include "hoLinearResampleOperator.h" #include "hoNDArray.h" #include "hoNDArray_fileio.h" #include "parameterparser.h" // Std includes #include <iostream> using namespace Gadgetron; using namespace std; // Define desired precision typedef float _real; int main(int argc, char** argv) { // // Parse command line // ParameterParser parms; parms.add_parameter( 'f', COMMAND_LINE_STRING, 1, "Fixed image file name (.real)", true ); parms.add_parameter( 'm', COMMAND_LINE_STRING, 1, "Moving image file name (.real)", true ); parms.add_parameter( 'r', COMMAND_LINE_STRING, 1, "Result file name", true, "displacement_field.real" ); parms.add_parameter( 'a', COMMAND_LINE_FLOAT, 1, "Regularization weight (alpha)", true, "0.05" ); parms.add_parameter( 'b', COMMAND_LINE_FLOAT, 1, "Regularization weight (beta)", true, "1.0" ); parms.add_parameter( 'l', COMMAND_LINE_INT, 1, "Number of multiresolution levels", true, "3" ); parms.parse_parameter_list(argc, argv); if( parms.all_required_parameters_set() ){ cout << " Running registration with the following parameters: " << endl; parms.print_parameter_list(); } else{ cout << " Some required parameters are missing: " << endl; parms.print_parameter_list(); parms.print_usage(); return 1; } // Load sample data from disk // boost::shared_ptr< hoNDArray<_real> > fixed_image = read_nd_array<_real>((char*)parms.get_parameter('f')->get_string_value()); boost::shared_ptr< hoNDArray<_real> > moving_image = read_nd_array<_real>((char*)parms.get_parameter('m')->get_string_value()); if( !fixed_image.get() || !moving_image.get() ){ cout << endl << "One of the input images is not found. Quitting!\n" << endl; return 1; } size_t num_fixed_dims = fixed_image->get_number_of_dimensions(); size_t num_moving_dims = moving_image->get_number_of_dimensions(); if( !(num_fixed_dims == 3 || num_fixed_dims == 4) ){ cout << endl << "The fixed image is not three- or four-dimensional. Quitting!\n" << endl; return 1; } if( !(num_moving_dims == 3 || num_moving_dims == 4) ){ cout << endl << "The moving image is not three- or four-dimensional. Quitting!\n" << endl; return 1; } _real alpha = (_real) parms.get_parameter('a')->get_float_value(); _real beta = (_real) parms.get_parameter('b')->get_float_value(); unsigned int multires_levels = parms.get_parameter('l')->get_int_value(); // Use trilinear interpolation for resampling // boost::shared_ptr< hoLinearResampleOperator<_real,3> > R( new hoLinearResampleOperator<_real,3>() ); // Setup solver // hoCKOpticalFlowSolver<_real,3> CK; CK.set_interpolator( R ); CK.set_output_mode( hoCKOpticalFlowSolver<_real,3>::OUTPUT_VERBOSE ); CK.set_max_num_iterations_per_level( 500 ); CK.set_num_multires_levels( multires_levels ); CK.set_alpha(alpha); CK.set_beta(beta); CK.set_limit(0.01f); // Run registration // boost::shared_ptr< hoNDArray<_real> > result = CK.solve( fixed_image.get(), moving_image.get() ); if( !result.get() ){ cout << endl << "Registration solver failed. Quitting!\n" << endl; return 1; } boost::shared_ptr< hoNDArray<_real> > deformed_moving = CK.deform( moving_image.get(), result ); // All done, write out the result // write_nd_array<_real>(result.get(), (char*)parms.get_parameter('r')->get_string_value()); write_nd_array<_real>(deformed_moving.get(), "def_moving.real" ); return 0; }
31.586207
106
0.690229
[ "3d" ]
a9c2bb604f5f5a4a0520e8655da3e39398cd4519
16,186
cc
C++
test/integration/joint_universal.cc
tommy91/Gazebo-Ardupilot
03ff6d3e6787eddaf650a681adb56dc06cf82294
[ "ECL-2.0", "Apache-2.0" ]
3
2018-07-17T00:17:13.000Z
2020-05-26T08:39:25.000Z
test/integration/joint_universal.cc
tommy91/Gazebo-Ardupilot
03ff6d3e6787eddaf650a681adb56dc06cf82294
[ "ECL-2.0", "Apache-2.0" ]
1
2022-02-03T18:32:35.000Z
2022-02-03T18:32:35.000Z
test/integration/joint_universal.cc
mingfeisun/gazebo
f3eae789c738f040b8fb27c2dc16dc4c06f2495c
[ "ECL-2.0", "Apache-2.0" ]
2
2016-04-25T22:05:09.000Z
2020-03-08T08:45:12.000Z
/* * Copyright (C) 2014 Open Source Robotics Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #include <string> #include "gazebo/physics/physics.hh" #include "gazebo/test/ServerFixture.hh" #include "gazebo/test/helper_physics_generator.hh" using namespace gazebo; const double g_tolerance = 1e-4; class JointTestUniversal : public ServerFixture, public testing::WithParamInterface<const char*> { /// \brief Test setting and enforcing joint limits. /// \param[in] _physicsEngine Type of physics engine to use. public: void Limits(const std::string &_physicsEngine); /// \brief Test calling SetVelocity for multiple axes per timestep. /// \param[in] _physicsEngine Type of physics engine to use. public: void SetVelocity(const std::string &_physicsEngine); /// \brief Test universal joint implementation with SetWorldPose. /// Set links world poses then check joint angles. /// \param[in] _physicsEngine Type of physics engine to use. public: void UniversalJointSetWorldPose(const std::string &_physicsEngine); /// \brief Test universal joint implementation with forces. /// Apply force to universal joint links, check position and/velocity. /// \param[in] _physicsEngine Type of physics engine to use. public: void UniversalJointForce(const std::string &_physicsEngine); }; ///////////////////////////////////////////////// void JointTestUniversal::Limits(const std::string &_physicsEngine) { // Load our universal joint test world Load("worlds/universal_joint_test.world", true, _physicsEngine); // Get a pointer to the world, make sure world loads physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); // Verify physics engine type physics::PhysicsEnginePtr physics = world->Physics(); ASSERT_TRUE(physics != NULL); EXPECT_EQ(physics->GetType(), _physicsEngine); // get model and joints physics::ModelPtr model = world->ModelByName("model_1"); ASSERT_TRUE(model != NULL); physics::JointPtr jointUpper = model->GetJoint("joint_00"); physics::JointPtr jointLower = model->GetJoint("joint_01"); ASSERT_TRUE(jointUpper != NULL); ASSERT_TRUE(jointLower != NULL); physics::LinkPtr linkLower = jointLower->GetChild(); ASSERT_TRUE(linkLower != NULL); // check joint limits from sdf EXPECT_NEAR(1.4, jointLower->UpperLimit(0), g_tolerance); EXPECT_NEAR(1.27, jointLower->UpperLimit(1), g_tolerance); EXPECT_NEAR(-1.4, jointLower->LowerLimit(0), g_tolerance); EXPECT_NEAR(-1.27, jointLower->LowerLimit(1), g_tolerance); // freeze upper joint jointUpper->SetUpperLimit(0, 1e-6); jointUpper->SetUpperLimit(1, 1e-6); jointUpper->SetLowerLimit(0, -1e-6); jointUpper->SetLowerLimit(1, -1e-6); EXPECT_NEAR(0.0, jointUpper->UpperLimit(0), g_tolerance); EXPECT_NEAR(0.0, jointUpper->UpperLimit(1), g_tolerance); EXPECT_NEAR(0.0, jointUpper->LowerLimit(0), g_tolerance); EXPECT_NEAR(0.0, jointUpper->LowerLimit(1), g_tolerance); EXPECT_NEAR(0.0, jointUpper->Position(0), g_tolerance); EXPECT_NEAR(0.0, jointUpper->Position(1), g_tolerance); // set asymmetric limits on lower joints double hi0 = 0.4; double hi1 = 0.2; double lo0 = -0.1; double lo1 = -0.3; jointLower->SetUpperLimit(0, hi0); jointLower->SetUpperLimit(1, hi1); jointLower->SetLowerLimit(0, lo0); jointLower->SetLowerLimit(1, lo1); EXPECT_NEAR(hi0, jointLower->UpperLimit(0), g_tolerance); EXPECT_NEAR(hi1, jointLower->UpperLimit(1), g_tolerance); EXPECT_NEAR(lo0, jointLower->LowerLimit(0), g_tolerance); EXPECT_NEAR(lo1, jointLower->LowerLimit(1), g_tolerance); for (int i = 0; i < 4; ++i) { // toggle signs for gx, gy // gx gy // i=0: + + // i=1: + - // i=2: - + // i=3: - - double gravityMag = 5.0; double gx = pow(-1, i / 2) * gravityMag; double gy = pow(-1, i % 2) * gravityMag; // Set gravity to push horizontally physics->SetGravity(ignition::math::Vector3d(gx, gy, 0)); world->Step(1000); // jointLower: axis[0] = {1, 0, 0} // jointLower: axis[1] = {0, 1, 0} // offset from anchor to c.g. is r = {0, 0, -L} // gravity moment r x g // a negative gy causes negative rotation about axis[0] double des0 = (gy < 0) ? lo0 : hi0; // a positive gx causes negative rotation about axis[1] double des1 = (gx > 0) ? lo1 : hi1; gzdbg << "Setting gravity " << "gx " << gx << ' ' << "gy " << gy << ' ' << "pose " << jointLower->GetChild()->WorldPose() << std::endl; EXPECT_NEAR(0.0, jointUpper->Position(0), g_tolerance); EXPECT_NEAR(0.0, jointUpper->Position(1), g_tolerance); EXPECT_NEAR(des0, jointLower->Position(0), 1e-2); EXPECT_NEAR(des1, jointLower->Position(1), 1e-2); // Also test expected pose of body, math is approximate auto eulerAngles = linkLower->WorldPose().Rot().Euler(); EXPECT_NEAR(des0, eulerAngles.X(), 0.05); EXPECT_NEAR(des1, eulerAngles.Y(), 0.05); } } ///////////////////////////////////////////////// void JointTestUniversal::SetVelocity(const std::string &_physicsEngine) { // Load our universal joint test world Load("worlds/universal_joint_test.world", true, _physicsEngine); // Get a pointer to the world, make sure world loads physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); // Verify physics engine type physics::PhysicsEnginePtr physics = world->Physics(); ASSERT_TRUE(physics != NULL); EXPECT_EQ(physics->GetType(), _physicsEngine); // get model and joints physics::ModelPtr model = world->ModelByName("model_1"); ASSERT_TRUE(model != NULL); physics::JointPtr jointLower = model->GetJoint("joint_01"); ASSERT_TRUE(jointLower != NULL); // Call SetVelocity on both axes of lower joint const double vel = 1.0; jointLower->SetVelocity(0, vel); jointLower->SetVelocity(1, vel); // Expect GetVelocity to match EXPECT_NEAR(jointLower->GetVelocity(0), vel, g_tolerance); EXPECT_NEAR(jointLower->GetVelocity(1), vel, g_tolerance); // Expect child link velocity to match parent at joint anchor { auto childOffset = jointLower->WorldPose().Pos() - jointLower->GetChild()->WorldPose().Pos(); auto parentOffset = jointLower->WorldPose().Pos() - jointLower->GetParent()->WorldPose().Pos(); ignition::math::Quaterniond q; ignition::math::Vector3d childVel = jointLower->GetChild()->WorldLinearVel(childOffset, q); ignition::math::Vector3d parentVel = jointLower->GetParent()->WorldLinearVel(parentOffset, q); EXPECT_NEAR(childVel.X(), parentVel.X(), g_tolerance); EXPECT_NEAR(childVel.Y(), parentVel.Y(), g_tolerance); EXPECT_NEAR(childVel.Z(), parentVel.Z(), g_tolerance); } } ///////////////////////////////////////////////// void JointTestUniversal::UniversalJointSetWorldPose( const std::string &_physicsEngine) { if (_physicsEngine == "dart") { gzerr << "DART Universal Joint is not yet working. See issue #1011.\n"; return; } // Load our universal joint test world Load("worlds/universal_joint_test.world", true, _physicsEngine); // Get a pointer to the world, make sure world loads physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); // Verify physics engine type physics::PhysicsEnginePtr physics = world->Physics(); ASSERT_TRUE(physics != NULL); EXPECT_EQ(physics->GetType(), _physicsEngine); physics->SetGravity(ignition::math::Vector3d::Zero); // simulate 1 step world->Step(1); double t = world->SimTime().Double(); // get time step size double dt = world->Physics()->GetMaxStepSize(); EXPECT_GT(dt, 0); gzlog << "dt : " << dt << "\n"; // verify that time moves forward EXPECT_DOUBLE_EQ(t, dt); gzlog << "t after one step : " << t << "\n"; // get model, joint and links physics::ModelPtr model_1 = world->ModelByName("model_1"); physics::LinkPtr link_00 = model_1->GetLink("link_00"); physics::LinkPtr link_01 = model_1->GetLink("link_01"); physics::JointPtr joint_00 = model_1->GetJoint("joint_00"); physics::JointPtr joint_01 = model_1->GetJoint("joint_01"); // both initial angles should be zero EXPECT_NEAR(joint_00->Position(0), 0, g_tolerance); EXPECT_NEAR(joint_00->Position(1), 0, g_tolerance); // move child link to it's initial location link_00->SetWorldPose(ignition::math::Pose3d(0, 0, 2, 0, 0, 0)); EXPECT_NEAR(joint_00->Position(0), 0, g_tolerance); EXPECT_NEAR(joint_00->Position(1), 0, g_tolerance); EXPECT_EQ(joint_00->GlobalAxis(0), ignition::math::Vector3d::UnitX); EXPECT_EQ(joint_00->GlobalAxis(1), ignition::math::Vector3d::UnitY); gzdbg << "joint angles [" << joint_00->Position(0) << ", " << joint_00->Position(1) << "] axis1 [" << joint_00->GlobalAxis(0) << "] axis2 [" << joint_00->GlobalAxis(1) << "]\n"; // move child link 45deg about x link_00->SetWorldPose(ignition::math::Pose3d(0, 0, 2, 0.25*IGN_PI, 0, 0)); EXPECT_NEAR(joint_00->Position(0), 0.25*IGN_PI, g_tolerance); EXPECT_NEAR(joint_00->Position(1), 0, g_tolerance); EXPECT_EQ(joint_00->GlobalAxis(0), ignition::math::Vector3d::UnitX); EXPECT_EQ(joint_00->GlobalAxis(1), ignition::math::Vector3d(0, cos(0.25*IGN_PI), sin(0.25*IGN_PI))); gzdbg << "joint angles [" << joint_00->Position(0) << ", " << joint_00->Position(1) << "] axis1 [" << joint_00->GlobalAxis(0) << "] axis2 [" << joint_00->GlobalAxis(1) << "]\n"; // move child link 45deg about y link_00->SetWorldPose(ignition::math::Pose3d(0, 0, 2, 0, 0.25*IGN_PI, 0)); EXPECT_NEAR(joint_00->Position(0), 0, g_tolerance); EXPECT_NEAR(joint_00->Position(1), 0.25*IGN_PI, g_tolerance); EXPECT_EQ(joint_00->GlobalAxis(0), ignition::math::Vector3d::UnitX); EXPECT_EQ(joint_00->GlobalAxis(1), ignition::math::Vector3d::UnitY); gzdbg << "joint angles [" << joint_00->Position(0) << ", " << joint_00->Position(1) << "] axis1 [" << joint_00->GlobalAxis(0) << "] axis2 [" << joint_00->GlobalAxis(1) << "]\n"; // move child link 90deg about both x and "rotated y axis" (z) link_00->SetWorldPose(ignition::math::Pose3d( 0, 0, 2, 0.5*IGN_PI, 0, 0.5*IGN_PI)); EXPECT_NEAR(joint_00->Position(1), 0.5*IGN_PI, g_tolerance); EXPECT_EQ(joint_00->GlobalAxis(0), ignition::math::Vector3d::UnitX); EXPECT_EQ(joint_00->GlobalAxis(1), ignition::math::Vector3d(0, cos(0.5*IGN_PI), sin(0.5*IGN_PI))); gzdbg << "joint angles [" << joint_00->Position(0) << ", " << joint_00->Position(1) << "] axis1 [" << joint_00->GlobalAxis(0) << "] axis2 [" << joint_00->GlobalAxis(1) << "]\n"; if (_physicsEngine == "bullet") { gzerr << "Bullet Universal Joint dynamics broken, see issue #1081.\n"; return; } else { EXPECT_NEAR(joint_00->Position(0), 0.5*IGN_PI, g_tolerance); } } ////////////////////////////////////////////////// void JointTestUniversal::UniversalJointForce(const std::string &_physicsEngine) { if (_physicsEngine == "bullet") { gzerr << "Bullet Universal Joint dynamics broken, see issue #1081.\n"; return; } if (_physicsEngine == "dart") { gzerr << "DART Universal Joint is not yet working. See issue #1011.\n"; return; } // Load our universal joint test world Load("worlds/universal_joint_test.world", true, _physicsEngine); // Get a pointer to the world, make sure world loads physics::WorldPtr world = physics::get_world("default"); ASSERT_TRUE(world != NULL); // Verify physics engine type physics::PhysicsEnginePtr physics = world->Physics(); ASSERT_TRUE(physics != NULL); EXPECT_EQ(physics->GetType(), _physicsEngine); physics->SetGravity(ignition::math::Vector3d::Zero); // simulate 1 step world->Step(1); double t = world->SimTime().Double(); // get time step size double dt = world->Physics()->GetMaxStepSize(); EXPECT_GT(dt, 0); gzlog << "dt : " << dt << "\n"; // verify that time moves forward EXPECT_DOUBLE_EQ(t, dt); gzlog << "t after one step : " << t << "\n"; // get model, joints and get links physics::ModelPtr model_1 = world->ModelByName("model_1"); physics::LinkPtr link_00 = model_1->GetLink("link_00"); physics::LinkPtr link_01 = model_1->GetLink("link_01"); physics::JointPtr joint_00 = model_1->GetJoint("joint_00"); physics::JointPtr joint_01 = model_1->GetJoint("joint_01"); // both initial angles should be zero EXPECT_NEAR(joint_00->Position(0), 0, g_tolerance); EXPECT_NEAR(joint_00->Position(1), 0, g_tolerance); // set new upper limit for joint_00 joint_00->SetUpperLimit(0, 0.3); // push joint_00 till it hits new upper limit int count = 0; while (joint_00->Position(0) < 0.4 && count < 1220) { count++; joint_00->SetForce(0, 0.1); world->Step(1); // check link pose double angle_00_0 = joint_00->Position(0); auto pose_00 = link_00->WorldPose(); EXPECT_NEAR(pose_00.Rot().Euler().X(), angle_00_0, 1e-8); EXPECT_LT(pose_00.Rot().Euler().X(), 0.35); } // push it back to 0 then lock joint_00->SetLowerLimit(0, 0.0); count = 0; while (joint_00->Position(0) > 0.1 && count < 1220) { count++; joint_00->SetForce(0, -0.1); world->Step(1); // check link pose double angle_00_0 = joint_00->Position(0); auto pose_00 = link_00->WorldPose(); EXPECT_NEAR(pose_00.Rot().Euler().X(), angle_00_0, 1e-8); EXPECT_GT(pose_00.Rot().Euler().X(), -0.05); } // lock joint at this location by setting lower limit here too joint_00->SetUpperLimit(0, 0.0); // set joint_01 upper limit to 1.0 joint_01->SetUpperLimit(0, 0.0); joint_01->SetLowerLimit(0, 0.0); joint_01->SetUpperLimit(1, 2.0); // push joint_01 until limit is reached count = 0; while (joint_01->Position(1) < 2.1 && count < 2700) { count++; joint_01->SetForce(0, 0.1); world->Step(1); // check link pose auto pose_01 = link_01->WorldPose(); double angle_00_1 = joint_00->Position(1); double angle_01_1 = joint_01->Position(1); EXPECT_NEAR(pose_01.Rot().Euler().Y(), angle_00_1 + angle_01_1, 1e-8); EXPECT_LT(pose_01.Rot().Euler().Y(), 2.05); } // push joint_01 the other way until -1 is reached joint_01->SetLowerLimit(1, -1.0); count = 0; while (joint_01->Position(1) > -1.1 && count < 2100) { count++; joint_01->SetForce(1, -0.1); world->Step(1); // check link pose auto pose_01 = link_01->WorldPose(); double angle_00_0 = joint_00->Position(0); double angle_00_1 = joint_00->Position(1); double angle_01_0 = joint_01->Position(0); double angle_01_1 = joint_01->Position(1); EXPECT_NEAR(pose_01.Rot().Euler().X(), angle_00_0 + angle_01_0, 1e-6); EXPECT_NEAR(pose_01.Rot().Euler().Y(), angle_00_1 + angle_01_1, 1e-6); } } ///////////////////////////////////////////////// TEST_P(JointTestUniversal, Limits) { Limits(GetParam()); } ///////////////////////////////////////////////// TEST_P(JointTestUniversal, SetVelocity) { SetVelocity(GetParam()); } ///////////////////////////////////////////////// TEST_P(JointTestUniversal, UniversalJointSetWorldPose) { UniversalJointSetWorldPose(GetParam()); } ///////////////////////////////////////////////// TEST_P(JointTestUniversal, UniversalJointForce) { UniversalJointForce(GetParam()); } INSTANTIATE_TEST_CASE_P(PhysicsEngines, JointTestUniversal, PHYSICS_ENGINE_VALUES); ///////////////////////////////////////////////// int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
34.292373
79
0.653342
[ "model" ]
a9c364ada72b3415b2cd0bb07ac3fe1c5265f946
1,329
hpp
C++
source/backend/cpu/CPUDeconvolution.hpp
loveltyoic/MNN
ff405a307819a7228e0d1fc02c00c68021745b0a
[ "Apache-2.0" ]
1
2021-02-03T07:50:59.000Z
2021-02-03T07:50:59.000Z
source/backend/cpu/CPUDeconvolution.hpp
sunnythree/MNN
166fe68cd1ba05d02b018537bf6af03374431690
[ "Apache-2.0" ]
null
null
null
source/backend/cpu/CPUDeconvolution.hpp
sunnythree/MNN
166fe68cd1ba05d02b018537bf6af03374431690
[ "Apache-2.0" ]
1
2021-01-15T06:28:11.000Z
2021-01-15T06:28:11.000Z
// // CPUDeconvolution.hpp // MNN // // Created by MNN on 2018/07/20. // Copyright © 2018, Alibaba Group Holding Limited // #ifndef CPUDeconvolution_hpp #define CPUDeconvolution_hpp #include <stdio.h> #include <mutex> #include "AutoStorage.h" #include "CPUConvolution.hpp" namespace MNN { class CPUDeconvolutionCommon : public CPUConvolution { public: CPUDeconvolutionCommon(const Op *convOp, Backend *b); virtual ~CPUDeconvolutionCommon(); virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; protected: std::shared_ptr<Tensor> mBias; int mSrcCount; }; class CPUDeconvolution : public CPUDeconvolutionCommon { public: CPUDeconvolution(const Op *convOp, Backend *b); virtual ~CPUDeconvolution(); virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; private: std::shared_ptr<Tensor> mWeight; std::shared_ptr<Tensor> mTempSrcBuffer; std::shared_ptr<Tensor> mTempColBuffer; std::mutex mLock; std::function<void(const float *, float *, int)> mFunction; int mThreadNumber = 1; }; } // namespace MNN #endif /* CPUDeconvolution_hpp */
28.891304
116
0.725357
[ "vector" ]
a9c5b74f7568c38e52a25f267d0d3ff45ee19154
26,023
cpp
C++
src/articulation/urdf_loader.cpp
haosulab/SAPIEN
6bc3f4e2be910199b793f185aea5791d9f193e4c
[ "MIT" ]
21
2021-10-13T11:56:45.000Z
2022-03-30T16:09:21.000Z
src/articulation/urdf_loader.cpp
haosulab/SAPIEN
6bc3f4e2be910199b793f185aea5791d9f193e4c
[ "MIT" ]
25
2021-10-20T20:14:37.000Z
2022-03-30T05:55:15.000Z
src/articulation/urdf_loader.cpp
haosulab/SAPIEN
6bc3f4e2be910199b793f185aea5791d9f193e4c
[ "MIT" ]
5
2021-10-31T17:43:52.000Z
2022-03-01T09:45:53.000Z
#include "urdf_loader.h" #include "articulation_builder.h" #include "sapien_articulation.h" #include "sapien_kinematic_articulation.h" #include "sapien_link.h" #include "sapien_scene.h" #include <eigen3/Eigen/Eigenvalues> #include <experimental/filesystem> namespace sapien { namespace URDF { using namespace tinyxml2; using namespace physx; namespace fs = std::filesystem; static PxTransform poseFromOrigin(const Origin &origin, float scale = 1.f) { PxQuat q = PxQuat(origin.rpy.z, {0, 0, 1}) * PxQuat(origin.rpy.y, {0, 1, 0}) * PxQuat(origin.rpy.x, {1, 0, 0}); return PxTransform(origin.xyz * scale, q); } static std::string getAbsPath(const std::string &urdfPath, const std::string &filePath) { if (urdfPath.empty()) { return filePath; } if (filePath.length() == 0) { fprintf(stderr, "Empty file path in URDF\n"); exit(1); } if (filePath[0] == '/') { return filePath; } auto path = fs::path(urdfPath); return fs::canonical(path).remove_filename().string() + filePath; } std::optional<std::string> findSRDF(const std::string &urdfName) { std::string srdfName = urdfName.substr(0, urdfName.length() - 4) + "srdf"; if (fs::is_regular_file(srdfName)) { return srdfName; } return {}; } URDFLoader::URDFLoader(SScene *scene) : mScene(scene) {} struct LinkTreeNode { Link *link; Joint *joint; LinkTreeNode *parent; std::vector<LinkTreeNode *> children; std::shared_ptr<LinkBuilder> linkBuilder = nullptr; }; std::tuple<std::shared_ptr<ArticulationBuilder>, std::vector<SensorRecord>> URDFLoader::parseRobotDescription(XMLDocument const &urdfDoc, XMLDocument const *srdfDoc, const std::string &urdfFilename, bool isKinematic, URDFConfig const &config) { std::optional<SRDF::Robot> srdf; if (srdfDoc) { srdf = SRDF::Robot(*srdfDoc->RootElement()); } std::unique_ptr<Robot> robot; if (strcmp("robot", urdfDoc.RootElement()->Name()) == 0) { robot = std::make_unique<Robot>(*urdfDoc.RootElement()); } else { std::cerr << "Invalid URDF: root is not <robot/>" << std::endl; exit(1); } std::vector<std::unique_ptr<LinkTreeNode>> treeNodes; std::map<std::string, LinkTreeNode *> linkName2treeNode; std::map<std::string, LinkTreeNode *> jointName2treeNode; if (robot->link_array.size() >= 64 && !isKinematic) { spdlog::get("SAPIEN")->error("cannot build dynamic articulation with more than 64 links"); return {nullptr, std::vector<SensorRecord>()}; } // process link for (const auto &link : robot->link_array) { std::string name = link->name; if (linkName2treeNode.find(name) != linkName2treeNode.end()) { std::cerr << "Duplicated link name: " << name << std::endl; exit(1); } std::unique_ptr<LinkTreeNode> treeNode = std::make_unique<LinkTreeNode>(); treeNode->link = link.get(); treeNode->joint = nullptr; treeNode->parent = nullptr; treeNode->children = std::vector<LinkTreeNode *>(); linkName2treeNode[name] = treeNode.get(); treeNodes.push_back(std::move(treeNode)); } // process joint for (const auto &joint : robot->joint_array) { std::string name = joint->name; if (jointName2treeNode.find(name) != jointName2treeNode.end()) { std::cerr << "Duplicated joint name: " << name << std::endl; exit(1); } std::string parent = joint->parent->link; std::string child = joint->child->link; if (linkName2treeNode.find(parent) == linkName2treeNode.end()) { spdlog::get("SAPIEN")->error("Failed to load URDF: parent of joint {} does not exist", name); return {nullptr, std::vector<SensorRecord>()}; } if (linkName2treeNode.find(child) == linkName2treeNode.end()) { spdlog::get("SAPIEN")->error("Failed to load URDF: child of joint {} does not exist", name); return {nullptr, std::vector<SensorRecord>()}; } LinkTreeNode *parentNode = linkName2treeNode[parent]; LinkTreeNode *childNode = linkName2treeNode[child]; if (childNode->parent) { std::cerr << "Error: link with name " << child << " has multiple parents." << std::endl; exit(1); } childNode->joint = joint.get(); childNode->parent = parentNode; parentNode->children.push_back(childNode); jointName2treeNode[name] = childNode; } std::vector<LinkTreeNode *> roots; // find root LinkTreeNode *root = nullptr; for (const auto &node : treeNodes) { if (!node->parent) { roots.push_back(node.get()); } } if (roots.size() > 1) { spdlog::get("SAPIEN")->error( "Failed to load URDF: multiple root nodes detected in a single URDF"); return {nullptr, std::vector<SensorRecord>()}; } if (roots.size() == 0) { spdlog::get("SAPIEN")->error("Failed to load URDF: no root node found"); return {nullptr, std::vector<SensorRecord>()}; } root = roots[0]; // check tree property std::map<LinkTreeNode *, bool> link2visited; std::vector<LinkTreeNode *> stack = {root}; while (!stack.empty()) { LinkTreeNode *current = stack.back(); stack.pop_back(); if (link2visited.find(current) != link2visited.end()) { std::cerr << "Error: kinetic loop detected." << std::endl; exit(1); } link2visited[current] = true; for (auto c : current->children) { stack.push_back(c); } } auto builder = mScene->createArticulationBuilder(); stack = {root}; while (!stack.empty()) { LinkTreeNode *current = stack.back(); stack.pop_back(); const PxTransform tJoint2Parent = current->joint ? poseFromOrigin(*current->joint->origin, scale) : PxTransform(PxIdentity); current->linkBuilder = builder->createLinkBuilder(current->parent ? current->parent->linkBuilder : nullptr); current->linkBuilder->setName(current->link->name); current->linkBuilder->setJointName(current->joint ? current->joint->name : ""); auto currentLinkBuilder = current->linkBuilder; // inertial const Inertial &currentInertial = *current->link->inertial; const Inertia &currentInertia = *currentInertial.inertia; if (currentInertia.ixx == 0 && currentInertia.iyy == 0 && currentInertia.izz == 0 && currentInertia.ixy == 0 && currentInertia.ixz == 0 && currentInertia.iyz == 0) { // in this case inertia is not correctly specified } else { // mass is specified const PxTransform tInertial2Link = poseFromOrigin(*currentInertial.origin, scale); PxVec3 eigs; PxTransform tInertia2Inertial; if (currentInertia.ixy == 0 && currentInertia.ixz == 0 && currentInertia.iyz == 0) { tInertia2Inertial = PxTransform(PxVec3(0), PxIdentity); eigs = {currentInertia.ixx, currentInertia.iyy, currentInertia.izz}; } else { Eigen::Matrix3f inertia; inertia(0, 0) = currentInertia.ixx; inertia(1, 1) = currentInertia.iyy; inertia(2, 2) = currentInertia.izz; inertia(0, 1) = currentInertia.ixy; inertia(1, 0) = currentInertia.ixy; inertia(0, 2) = currentInertia.ixz; inertia(2, 0) = currentInertia.ixz; inertia(1, 2) = currentInertia.iyz; inertia(2, 1) = currentInertia.iyz; Eigen::SelfAdjointEigenSolver<Eigen::Matrix3f> es; es.compute(inertia); eigs = {es.eigenvalues().x(), es.eigenvalues().y(), es.eigenvalues().z()}; Eigen::Matrix3f m; auto eig_vecs = es.eigenvectors(); PxVec3 col0 = {eig_vecs(0, 0), eig_vecs(1, 0), eig_vecs(2, 0)}; PxVec3 col1 = {eig_vecs(0, 1), eig_vecs(1, 1), eig_vecs(2, 1)}; PxVec3 col2 = {eig_vecs(0, 2), eig_vecs(1, 2), eig_vecs(2, 2)}; PxMat33 mat = PxMat33(col0, col1, col2); tInertia2Inertial = PxTransform(PxVec3(0), PxQuat(mat).getNormalized()); } if (!tInertia2Inertial.isSane()) { printf("Got insane inertia-inertial pose!\n"); exit(1); } const PxTransform tInertia2Link = tInertial2Link * tInertia2Inertial; if (!tInertia2Link.isSane()) { printf("Got insane inertial-link pose!\n"); exit(1); } float scale3 = scale * scale * scale; currentLinkBuilder->setMassAndInertia(currentInertial.mass->value * scale3, tInertia2Link, {scale3 * eigs.x, scale3 * eigs.y, scale * eigs.z}); } // visual for (const auto &visual : current->link->visual_array) { PxVec3 color = {1, 1, 1}; if (visual->material) { if (visual->material->color) { color = {visual->material->color->rgba.x, visual->material->color->rgba.y, visual->material->color->rgba.z}; } else { for (auto &m : robot->material_array) { if (m->name == visual->material->name) { color = {m->color->rgba.x, m->color->rgba.y, m->color->rgba.z}; break; } } } } const PxTransform tVisual2Link = poseFromOrigin(*visual->origin, scale); switch (visual->geometry->type) { case Geometry::BOX: currentLinkBuilder->addBoxVisual(tVisual2Link, visual->geometry->size * scale / 2.f, color, visual->name); break; case Geometry::CYLINDER: spdlog::get("SAPIEN")->error("Cylinder visual is not supported. Replaced with a capsule"); currentLinkBuilder->addCapsuleVisual( tVisual2Link * PxTransform({{0, 0, 0}, PxQuat(1.57079633, {0, 1, 0})}), visual->geometry->radius * scale, std::max(0.f, visual->geometry->length * scale / 2.f - visual->geometry->radius * scale), color, visual->name); break; case Geometry::CAPSULE: currentLinkBuilder->addCapsuleVisual( tVisual2Link * PxTransform({{0, 0, 0}, PxQuat(1.57079633, {0, 1, 0})}), visual->geometry->radius * scale, visual->geometry->length * scale / 2.f, color, visual->name); break; case Geometry::SPHERE: currentLinkBuilder->addSphereVisual(tVisual2Link, visual->geometry->radius * scale, color, visual->name); break; case Geometry::MESH: currentLinkBuilder->addVisualFromFile(getAbsPath(urdfFilename, visual->geometry->filename), tVisual2Link, visual->geometry->scale * scale, nullptr, visual->name); break; } } // collision for (uint32_t collision_idx = 0; collision_idx < current->link->collision_array.size(); ++collision_idx) { const auto &collision = current->link->collision_array[collision_idx]; std::shared_ptr<SPhysicalMaterial> material; float patchRadius; float minPatchRadius; float density; auto it = config.link.find(current->link->name); if (it != config.link.end()) { auto it2 = it->second.shape.find(collision_idx); if (it2 != it->second.shape.end()) { material = it2->second.material; patchRadius = it2->second.patchRadius; minPatchRadius = it2->second.minPatchRadius; density = it2->second.density; } else { material = it->second.material; patchRadius = it->second.patchRadius; minPatchRadius = it->second.minPatchRadius; density = it->second.density; } } else { patchRadius = 0.f; minPatchRadius = 0.f; material = config.material; density = config.density; } const PxTransform tCollision2Link = poseFromOrigin(*collision->origin, scale); // TODO: add physical material support (may require URDF extension) switch (collision->geometry->type) { case Geometry::BOX: currentLinkBuilder->addBoxShape(tCollision2Link, collision->geometry->size * scale / 2.f, material, density, patchRadius, minPatchRadius); if (collisionIsVisual) { currentLinkBuilder->addBoxVisual( tCollision2Link, collision->geometry->size * scale / 2.f, PxVec3{1, 1, 1}, ""); } break; case Geometry::CYLINDER: if (collision->geometry->length / 2.0f - collision->geometry->radius < 1e-4) { spdlog::get("SAPIEN")->error( "Cylinder collision is not supported. Replaced with a sphere"); currentLinkBuilder->addSphereShape( tCollision2Link * PxTransform({{0, 0, 0}, PxQuat(1.57079633, {0, 1, 0})}), collision->geometry->radius * scale, material, density, patchRadius, minPatchRadius); } else { spdlog::get("SAPIEN")->error( "Cylinder collision is not supported. Replaced with a capsule"); currentLinkBuilder->addCapsuleShape( tCollision2Link * PxTransform({{0, 0, 0}, PxQuat(1.57079633, {0, 1, 0})}), collision->geometry->radius * scale, std::max(0.f, collision->geometry->length * scale / 2.0f - collision->geometry->radius * scale), material, density, patchRadius, minPatchRadius); } if (collisionIsVisual) { currentLinkBuilder->addCapsuleVisual( tCollision2Link * PxTransform({{0, 0, 0}, PxQuat(1.57079633, {0, 1, 0})}), collision->geometry->radius * scale, std::max(0.f, collision->geometry->length * scale / 2.0f - collision->geometry->radius * scale), PxVec3{1, 1, 1}, ""); } case Geometry::CAPSULE: currentLinkBuilder->addCapsuleShape( tCollision2Link * PxTransform({{0, 0, 0}, PxQuat(1.57079633, {0, 1, 0})}), collision->geometry->radius * scale, collision->geometry->length * scale / 2.0f, material, density, patchRadius, minPatchRadius); if (collisionIsVisual) { currentLinkBuilder->addCapsuleVisual( tCollision2Link * PxTransform({{0, 0, 0}, PxQuat(1.57079633, {0, 1, 0})}), collision->geometry->radius * scale, collision->geometry->length * scale / 2.f, PxVec3{1, 1, 1}, ""); } break; case Geometry::SPHERE: currentLinkBuilder->addSphereShape(tCollision2Link, collision->geometry->radius * scale, material, density, patchRadius, minPatchRadius); if (collisionIsVisual) { currentLinkBuilder->addSphereVisual(tCollision2Link, collision->geometry->radius * scale, PxVec3{1, 1, 1}, ""); } break; case Geometry::MESH: if (multipleMeshesInOneFile) { currentLinkBuilder->addMultipleConvexShapesFromFile( getAbsPath(urdfFilename, collision->geometry->filename), tCollision2Link, collision->geometry->scale * scale, material, density, patchRadius, minPatchRadius); } else { currentLinkBuilder->addConvexShapeFromFile( getAbsPath(urdfFilename, collision->geometry->filename), tCollision2Link, collision->geometry->scale * scale, material, density, patchRadius, minPatchRadius); } if (collisionIsVisual) { currentLinkBuilder->addVisualFromFile( getAbsPath(urdfFilename, collision->geometry->filename), tCollision2Link, collision->geometry->scale * scale, nullptr, ""); } break; } } // joint if (current->joint) { PxReal friction = 0; PxReal damping = 0; if (current->joint->dynamics) { friction = current->joint->dynamics->friction; damping = current->joint->dynamics->damping; } if (current->joint->axis->xyz.magnitudeSquared() < 0.01) { current->joint->axis->xyz = {1, 0, 0}; } PxVec3 axis1 = current->joint->axis->xyz.getNormalized(); PxVec3 axis2; if (std::abs(axis1.dot({1, 0, 0})) > 0.9) { axis2 = axis1.cross({0, 0, 1}).getNormalized(); } else { axis2 = axis1.cross({1, 0, 0}).getNormalized(); } PxVec3 axis3 = axis1.cross(axis2); const PxTransform tAxis2Joint = {PxVec3(0), PxQuat(PxMat33(axis1, axis2, axis3))}; if (!tAxis2Joint.isSane()) { spdlog::get("SAPIEN")->critical("URDF loading failed: invalid joint pose"); exit(1); } const PxTransform tAxis2Parent = tJoint2Parent * tAxis2Joint; if (current->joint->type == "revolute") { currentLinkBuilder->setJointProperties( PxArticulationJointType::eREVOLUTE, {{current->joint->limit->lower, current->joint->limit->upper}}, tAxis2Parent, tAxis2Joint, friction, damping); } else if (current->joint->type == "continuous") { currentLinkBuilder->setJointProperties( PxArticulationJointType::eREVOLUTE, {{-std::numeric_limits<float>::infinity(), std::numeric_limits<float>::infinity()}}, tAxis2Parent, tAxis2Joint, friction, damping); } else if (current->joint->type == "prismatic") { currentLinkBuilder->setJointProperties( PxArticulationJointType::ePRISMATIC, {{current->joint->limit->lower * scale, current->joint->limit->upper * scale}}, tAxis2Parent, tAxis2Joint, friction, damping); } else if (current->joint->type == "fixed") { currentLinkBuilder->setJointProperties(PxArticulationJointType::eFIX, {}, tAxis2Parent, tAxis2Joint, friction, damping); } else if (current->joint->type == "floating") { std::cerr << "Currently not supported: " + current->joint->type << std::endl; exit(1); } else if (current->joint->type == "planar") { std::cerr << "Currently not supported type: " + current->joint->type << std::endl; exit(1); } else { std::cerr << "Unreconized joint type: " + current->joint->type << std::endl; exit(1); } } // Reverse iterate over children and push into the stack for (auto c = current->children.rbegin(); c != current->children.rend(); c++) { stack.push_back(*c); } } if (srdf) { uint32_t groupCount = 0; for (auto &dc : srdf->disable_collisions_array) { if (dc->reason == std::string("Default")) { if (linkName2treeNode.find(dc->link1) == linkName2treeNode.end()) { spdlog::get("SAPIEN")->error("SRDF link name not found: {}", dc->link1); continue; } if (linkName2treeNode.find(dc->link2) == linkName2treeNode.end()) { spdlog::get("SAPIEN")->error("SRDF link name not found: {}", dc->link2); continue; } LinkTreeNode *l1 = linkName2treeNode[dc->link1]; LinkTreeNode *l2 = linkName2treeNode[dc->link2]; if (l1->parent == l2 || l2->parent == l1) { continue; // ignored by default } groupCount += 1; if (groupCount == 32) { spdlog::get("SAPIEN")->critical("Collision group exhausted, please simplify the SRDF"); throw std::runtime_error("Too many collision groups"); } l1->linkBuilder->addCollisionGroup(0, 0, groupCount, 0); l2->linkBuilder->addCollisionGroup(0, 0, groupCount, 0); } } spdlog::get("SAPIEN")->info("SRDF: ignored {} pairs", groupCount); } std::vector<SensorRecord> sensorRecords; for (auto &gazebo : robot->gazebo_array) { for (auto &sensor : gazebo->sensor_array) { switch (sensor->type) { case Sensor::Type::RAY: case Sensor::Type::UNKNOWN: break; case Sensor::Type::CAMERA: case Sensor::Type::DEPTH: sensorRecords.push_back(SensorRecord{ "camera", sensor->name, gazebo->reference, poseFromOrigin(*sensor->origin, scale), sensor->camera->width, sensor->camera->height, sensor->camera->fovx, sensor->camera->fovy, sensor->camera->near, sensor->camera->far}); } } } return {std::move(builder), sensorRecords}; } SArticulation *URDFLoader::load(const std::string &filename, URDFConfig const &config) { if (filename.substr(filename.length() - 4) != std::string("urdf")) { throw std::invalid_argument("Non-URDF file passed to URDF loader"); } auto srdfName = findSRDF(filename); std::unique_ptr<XMLDocument> srdfDoc = nullptr; if (srdfName) { srdfDoc = std::make_unique<XMLDocument>(); if (srdfDoc->LoadFile(srdfName.value().c_str())) { srdfDoc = nullptr; spdlog::get("SAPIEN")->error("SRDF loading faild for {}", filename); } } XMLDocument urdfDoc; if (urdfDoc.LoadFile(filename.c_str())) { spdlog::get("SAPIEN")->error("Failed to open URDF file: {}", filename); return nullptr; } auto [builder, records] = parseRobotDescription(urdfDoc, srdfDoc.get(), filename, false, config); auto articulation = builder->build(fixRootLink); for (auto &record : records) { if (record.type == "camera") { std::vector<SLinkBase *> links = articulation->getBaseLinks(); auto it = std::find_if(links.begin(), links.end(), [&](SLinkBase *link) { return link->getName() == record.linkName; }); if (it == links.end()) { spdlog::get("SAPIEN")->error("Failed to find the link to mount camera: ", record.linkName); continue; } auto cam = mScene->addCamera(record.name, record.width, record.height, record.fovy, record.near, record.far); cam->setParent(*it); cam->setLocalPose(record.localPose); // mScene->addMountedCamera(record.name, *it, record.localPose, record.width, record.height, // record.fovx, record.fovy, record.near, record.far); } } return articulation; } SKArticulation *URDFLoader::loadKinematic(const std::string &filename, URDFConfig const &config) { if (filename.substr(filename.length() - 4) != std::string("urdf")) { throw std::invalid_argument("Non-URDF file passed to URDF loader"); } auto srdfName = findSRDF(filename); std::unique_ptr<XMLDocument> srdfDoc = nullptr; if (srdfName) { srdfDoc = std::make_unique<XMLDocument>(); if (srdfDoc->LoadFile(srdfName.value().c_str())) { srdfDoc = nullptr; spdlog::get("SAPIEN")->error("SRDF loading faild for {}", filename); } } XMLDocument urdfDoc; if (urdfDoc.LoadFile(filename.c_str())) { spdlog::get("SAPIEN")->error("Failed to open URDF file: {}", filename); return nullptr; } auto [builder, records] = parseRobotDescription(urdfDoc, srdfDoc.get(), filename, true, config); auto articulation = builder->buildKinematic(); for (auto &record : records) { if (record.type == "camera") { std::vector<SLinkBase *> links = articulation->getBaseLinks(); auto it = std::find_if(links.begin(), links.end(), [&](SLinkBase *link) { return link->getName() == record.linkName; }); if (it == links.end()) { spdlog::get("SAPIEN")->error("Failed to find the link to mount camera: ", record.linkName); continue; } auto cam = mScene->addCamera(record.name, record.width, record.height, record.fovy, record.near, record.far); cam->setParent(*it); cam->setLocalPose(record.localPose); } } return articulation; } std::shared_ptr<ArticulationBuilder> URDFLoader::loadFileAsArticulationBuilder(const std::string &filename, URDFConfig const &config) { if (filename.substr(filename.length() - 4) != std::string("urdf")) { throw std::invalid_argument("Non-URDF file passed to URDF loader"); } auto srdfName = findSRDF(filename); std::unique_ptr<XMLDocument> srdfDoc = nullptr; if (srdfName) { srdfDoc = std::make_unique<XMLDocument>(); if (srdfDoc->LoadFile(srdfName.value().c_str())) { srdfDoc = nullptr; spdlog::get("SAPIEN")->error("SRDF loading faild for {}", filename); } } XMLDocument urdfDoc; if (urdfDoc.LoadFile(filename.c_str())) { spdlog::get("SAPIEN")->error("Failed to open URDF file: {}", filename); return nullptr; } return std::move( std::get<0>(parseRobotDescription(urdfDoc, srdfDoc.get(), filename, true, config))); } SArticulation *URDFLoader::loadFromXML(const std::string &URDFString, const std::string &SRDFString, URDFConfig const &config) { XMLDocument urdfDoc; if (urdfDoc.Parse(URDFString.c_str(), URDFString.length())) { spdlog::get("SAPIEN")->error("Failed to parse URDF string"); return nullptr; } std::unique_ptr<XMLDocument> srdfDoc = nullptr; if (!SRDFString.empty()) { srdfDoc = std::make_unique<XMLDocument>(); if (srdfDoc->Parse(SRDFString.c_str(), SRDFString.length())) { spdlog::get("SAPIEN")->error("Failed parsing given SRDF string."); } } auto [builder, records] = parseRobotDescription(urdfDoc, srdfDoc.get(), "", false, config); auto articulation = builder->build(fixRootLink); for (auto &record : records) { if (record.type == "camera") { std::vector<SLinkBase *> links = articulation->getBaseLinks(); auto it = std::find_if(links.begin(), links.end(), [&](SLinkBase *link) { return link->getName() == record.linkName; }); if (it == links.end()) { spdlog::get("SAPIEN")->error("Failed to find the link to mount camera: ", record.linkName); continue; } auto cam = mScene->addCamera(record.name, record.width, record.height, record.fovy, record.near, record.far); cam->setParent(*it); cam->setLocalPose(record.localPose); } } return articulation; }; } // namespace URDF } // namespace sapien
38.782414
99
0.608846
[ "mesh", "geometry", "shape", "vector" ]
a9c668312e34391dd0f28abe13b7a9dff42cc019
10,992
cxx
C++
Libs/MRML/Core/Testing/vtkMRMLHierarchyNodeTest3.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Libs/MRML/Core/Testing/vtkMRMLHierarchyNodeTest3.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
Libs/MRML/Core/Testing/vtkMRMLHierarchyNodeTest3.cxx
TheInterventionCentre/NorMIT-Plan-App
765ed9a5dccc1cc134b65ccabe93fc132baeb2ea
[ "MIT" ]
null
null
null
/*=auto========================================================================= Portions (c) Copyright 2005 Brigham and Women's Hospital (BWH) All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Program: 3D Slicer =========================================================================auto=*/ // MRML includes #include "vtkMRMLCoreTestingMacros.h" #include "vtkMRMLModelHierarchyNode.h" #include "vtkMRMLModelDisplayNode.h" #include "vtkMRMLModelNode.h" #include "vtkMRMLScene.h" // VTK includes #include <vtkNew.h> // STD includes #include <sstream> // helper methods to check children ordering static void PrintNames(std::vector< vtkMRMLHierarchyNode *> kids) { for (unsigned int i = 0; i < kids.size(); i++) { std::cout << "\t" << i << " name = " << kids[i]->GetName() << std::endl; } } // test more ordered node hierachy uses int vtkMRMLHierarchyNodeTest3(int , char * [] ) { vtkNew<vtkMRMLScene> scene; vtkNew<vtkMRMLDisplayableHierarchyNode> hnode1; hnode1->SetName("Level 0"); scene->AddNode(hnode1.GetPointer()); vtkNew<vtkMRMLModelDisplayNode> hdnode1; hdnode1->SetName("Level 0 Display"); scene->AddNode(hdnode1.GetPointer()); if (hdnode1->GetID()) { hnode1->SetAndObserveDisplayNodeID(hdnode1->GetID()); } else { std::cerr << "Error setting up a display node for the first hierarchy node: " << "id is null on hierarchy display node" << std::endl;; return EXIT_FAILURE; } vtkNew<vtkMRMLDisplayableHierarchyNode> hnode2; scene->AddNode(hnode2.GetPointer()); vtkNew<vtkMRMLModelDisplayNode> hdnode2; scene->AddNode(hdnode2.GetPointer()); if (hdnode2->GetID()) { hnode2->SetName("Level 1"); hdnode2->SetName("Level 1 Display"); hnode2->SetAndObserveDisplayNodeID(hdnode2->GetID()); hnode2->SetParentNodeID(hnode1->GetID()); } else { std::cerr << "Error setting up a display node for the second hierarchy node: " << "id is null on hierarchy display node" << std::endl; return EXIT_FAILURE; } // now add model nodes which will be children of the level 1 hierarchy std::vector<vtkSmartPointer<vtkMRMLModelNode> > modelNodes; std::vector<vtkSmartPointer<vtkMRMLModelDisplayNode> > modelDisplayNodes; std::vector<vtkSmartPointer<vtkMRMLModelHierarchyNode> > modelHierarchyNodes; unsigned int numModels = 5; for (unsigned int m = 0; m < numModels; m++) { modelNodes.push_back(vtkSmartPointer<vtkMRMLModelNode>::New()); modelDisplayNodes.push_back(vtkSmartPointer<vtkMRMLModelDisplayNode>::New()); scene->AddNode(modelNodes[m]); scene->AddNode(modelDisplayNodes[m]); if (!modelNodes[m] || !modelDisplayNodes[m] || !modelDisplayNodes[m]->GetID()) { std::cerr << "Error setting up a display node for the " << m << "th model node\n"; return EXIT_FAILURE; } std::stringstream ss; ss << m; ss << "th Model"; std::string nameString; ss >> nameString; modelNodes[m]->SetName(nameString.c_str()); ss << " Display"; ss >> nameString; modelDisplayNodes[m]->SetName(nameString.c_str()); modelNodes[m]->SetAndObserveDisplayNodeID(modelDisplayNodes[m]->GetID()); // now set up a hierarchy for this model modelHierarchyNodes.push_back(vtkSmartPointer<vtkMRMLModelHierarchyNode>::New()); std::stringstream ss2; ss2 << m; ss2 << "th Model Hierarchy"; nameString = ss2.str(); modelHierarchyNodes[m]->SetName(nameString.c_str()); scene->AddNode(modelHierarchyNodes[m]); modelHierarchyNodes[m]->SetParentNodeID(hnode2->GetID()); modelHierarchyNodes[m]->SetDisplayableNodeID(modelNodes[m]->GetID()); } std::cout << "Model nodes size = " << modelNodes.size() << std::endl; std::cout << "Model display nodes size = " << modelDisplayNodes.size() << std::endl; std::cout << "Model hierarchy nodes size = " << modelHierarchyNodes.size() << std::endl; // check that the top level hierarchy returns all the children std::vector< vtkMRMLHierarchyNode *> allChildren; hnode1->GetAllChildrenNodes(allChildren); std::cout << "Top level hierarchy children:" << std::endl; PrintNames(allChildren); if (allChildren.size() != 1 + numModels) { std::cerr << "ERROR: Top level hiearchy returned " << allChildren.size() << " total children instead of " << 1 + numModels << std::endl; return EXIT_FAILURE; } else { std::cout << "Top level hierarchy has " << allChildren.size() << " total children" << std::endl; } // check for the immediate children of the top level std::vector< vtkMRMLHierarchyNode *> immediateChildren = hnode1->GetChildrenNodes(); std::cout << "Top level hierarchy immediate children:" << std::endl; PrintNames(immediateChildren); if (immediateChildren.size() != 1) { std::cerr << "ERROR: Top level hierarchy returned " << immediateChildren.size() << " total children instead of " << 1 << std::endl; return EXIT_FAILURE; } else { std::cout << "Top level hiearachy has " << immediateChildren.size() << " immediate children" << std::endl; } // check that the second level hierarchy returns all the children std::vector< vtkMRMLHierarchyNode *> allChildren2; hnode2->GetAllChildrenNodes(allChildren2); std::cout << "Second level hierarchy children:" << std::endl; PrintNames(allChildren2); if (allChildren2.size() != numModels) { std::cerr << "ERROR: Second level hierarchy has " << allChildren2.size() << " total children insted of " << numModels << std::endl; return EXIT_FAILURE; } else { std::cout << "Second level hierarchy has " << allChildren2.size() << " total children" << std::endl; } // check for the immediate children of the second level std::vector< vtkMRMLHierarchyNode *> immediateChildren2 = hnode2->GetChildrenNodes(); std::cout << "Second level hierarchy immediate children:" << std::endl; PrintNames(immediateChildren2); if (immediateChildren2.size() != numModels) { std::cerr<< "ERROR: Second level hierarachy has " << immediateChildren2.size() << " immediate children instead of " << numModels << std::endl; return EXIT_FAILURE; } else { std::cout << "Second level hiearachy has " << immediateChildren2.size() << " immediate children" << std::endl; } // now check that the children are in the order they were added for (unsigned int i = 0; i < numModels; i++) { int indexInParent = modelHierarchyNodes[i]->GetIndexInParent(); std::cout << "Model hierarchy node " << i << " is at index " << indexInParent << std::endl; if (indexInParent != (int)i) { std::cerr << "Index mismatch!" << std::endl; return EXIT_FAILURE; } } // move the first node down in the hierarchy int oldIndexInParent = modelHierarchyNodes[0]->GetIndexInParent(); int newIndexInParent = oldIndexInParent + 1; modelHierarchyNodes[0]->SetIndexInParent(newIndexInParent); int currentIndexInParent = modelHierarchyNodes[0]->GetIndexInParent(); if (currentIndexInParent != newIndexInParent) { std::cerr << "Error moving first hierarchy node in list from index " << oldIndexInParent << " to " << newIndexInParent << ", current index in parent is " << currentIndexInParent << std::endl; return EXIT_FAILURE; } // move the last one up in the hierarchy oldIndexInParent = modelHierarchyNodes[numModels-1]->GetIndexInParent(); newIndexInParent = oldIndexInParent - 1; modelHierarchyNodes[numModels-1]->SetIndexInParent(newIndexInParent); currentIndexInParent = modelHierarchyNodes[numModels-1]->GetIndexInParent(); if (currentIndexInParent != newIndexInParent) { std::cerr << "Error moving last hierarchy node in list from index " << oldIndexInParent << " to " << newIndexInParent << ", current index in parent is " << currentIndexInParent << std::endl; return EXIT_FAILURE; } // get the second hierarchy child and move it to be the first vtkMRMLHierarchyNode *node1 = hnode2->GetNthChildNode(1); if (node1) { oldIndexInParent = node1->GetIndexInParent(); node1->SetIndexInParent(0); currentIndexInParent = node1->GetIndexInParent(); if (currentIndexInParent != 0) { std::cerr << "Error moving second hierarchy child to be the first. Started at index " << oldIndexInParent << ", moved it to 0, now at " << currentIndexInParent << std::endl; return EXIT_FAILURE; } } // get the second last and move it to be the last node1 = hnode2->GetNthChildNode(numModels-2); if (node1) { oldIndexInParent = node1->GetIndexInParent(); node1->SetIndexInParent(numModels-1); currentIndexInParent = node1->GetIndexInParent(); if (currentIndexInParent != (int)numModels-1) { std::cerr << "Error moving second last hierarchy child to be the last. Started at index " << oldIndexInParent << ", moved it to " << numModels-1 << ", now at " << currentIndexInParent << std::endl; return EXIT_FAILURE; } } // move one down node1 = hnode2->GetNthChildNode(numModels/2); if (node1) { oldIndexInParent = node1->GetIndexInParent(); node1->MoveInParent(-1); currentIndexInParent = node1->GetIndexInParent(); if (currentIndexInParent != (int)oldIndexInParent-1) { std::cerr << "Error moving child one down. Started at index " << oldIndexInParent << ", now at " << currentIndexInParent << std::endl; return EXIT_FAILURE; } } // move one up node1 = hnode2->GetNthChildNode(numModels/2); if (node1) { oldIndexInParent = node1->GetIndexInParent(); node1->MoveInParent(1); currentIndexInParent = node1->GetIndexInParent(); if (currentIndexInParent != (int)oldIndexInParent+1) { std::cerr << "Error moving child one up. Started at index " << oldIndexInParent << ", now at " << currentIndexInParent << std::endl; return EXIT_FAILURE; } } // move two down node1 = hnode2->GetNthChildNode(numModels/2); if (node1) { oldIndexInParent = node1->GetIndexInParent(); node1->MoveInParent(-2); currentIndexInParent = node1->GetIndexInParent(); if (currentIndexInParent != (int)oldIndexInParent-2) { std::cerr << "Error moving child two down. Started at index " << oldIndexInParent << ", now at " << currentIndexInParent << std::endl; return EXIT_FAILURE; } } // move two up node1 = hnode2->GetNthChildNode(numModels/2); if (node1) { oldIndexInParent = node1->GetIndexInParent(); node1->MoveInParent(2); currentIndexInParent = node1->GetIndexInParent(); if (currentIndexInParent != (int)oldIndexInParent+2) { std::cerr << "Error moving child two up. Started at index " << oldIndexInParent << ", now at " << currentIndexInParent << std::endl; return EXIT_FAILURE; } } return EXIT_SUCCESS; }
36.397351
203
0.663301
[ "vector", "model", "3d" ]
a9cae49ea3c16d005891557d942487edcdb8a791
6,425
cpp
C++
src/GUI/SpellButtonGroup.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
279
2015-05-06T19:04:07.000Z
2022-03-21T21:33:38.000Z
src/GUI/SpellButtonGroup.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
222
2016-10-26T15:56:25.000Z
2021-10-03T15:30:18.000Z
src/GUI/SpellButtonGroup.cpp
tizian/Cendric2
5b0438c73a751bcc0d63c3af839af04ab0fb21a3
[ "MIT" ]
49
2015-10-01T21:23:03.000Z
2022-03-19T20:11:31.000Z
#include "GUI/SpellButtonGroup.h" #include "GUI/ButtonInterface.h" #include "GUI/SelectableWindow.h" #include "Controller/InputController.h" SpellButtonGroup::SpellButtonGroup() { m_selectedButtonIndexX = -1; m_selectedButtonIndexY = -1; m_isEnabled = true; m_isGamepadEnabled = true; m_isWindowLock = false; } SpellButtonGroup::~SpellButtonGroup() { } void SpellButtonGroup::render(sf::RenderTarget& renderTarget) { for (auto& buttonRow : m_buttons) { for (auto button : buttonRow) { button->render(renderTarget); } } } void SpellButtonGroup::update(const sf::Time& frameTime) { if (!m_isEnabled) return; for (int y = 0; y < static_cast<int>(m_buttons.size()); ++y) { for (int x = 0; x < static_cast<int>(m_buttons[y].size()); ++x) { if (!m_buttons[y][x]->isVisibleAndEnabled()) { continue; } m_buttons[y][x]->update(frameTime); if (m_buttons[y][x]->isPressed()) { selectButton(y, x); } } } if (!m_isGamepadEnabled) return; updateSelection(); } void SpellButtonGroup::setEnabled(bool enabled) { m_isEnabled = enabled; for (auto& buttonRow : m_buttons) { for (auto button : buttonRow) { button->setEnabled(enabled); } } } void SpellButtonGroup::setGamepadEnabled(bool enabled) { m_isGamepadEnabled = enabled; } void SpellButtonGroup::addButton(ButtonInterface* button, int yIndex) { if (yIndex < 0 || yIndex > static_cast<int>(m_buttons.size())) { return; } if (yIndex > static_cast<int>(m_buttons.size() - 1)) { m_buttons.push_back(std::vector<ButtonInterface*>()); } m_buttons[yIndex].push_back(button); int xIndex = static_cast<int>(m_buttons[yIndex].size()) - 1; if (m_selectedButtonIndexX == -1 && m_buttons[yIndex][xIndex]->isActive()) { selectButton(yIndex, xIndex); m_buttons[yIndex][xIndex]->notifyFirstSelection(); } } ButtonInterface* SpellButtonGroup::getSelectedButton() const { if (m_selectedButtonIndexX == -1) { return nullptr; } return m_buttons[m_selectedButtonIndexY][m_selectedButtonIndexX]; } int SpellButtonGroup::getSelectedButtonIdX() const { return m_selectedButtonIndexX; } int SpellButtonGroup::getSelectedButtonIdY() const { return m_selectedButtonIndexY; } ButtonInterface* SpellButtonGroup::getButton(int yIndex, int xIndex) const { if (yIndex < 0 || yIndex > static_cast<int>(m_buttons.size()) - 1) { return nullptr; } if (xIndex < 0 || xIndex > static_cast<int>(m_buttons[yIndex].size()) - 1) { return nullptr; } return m_buttons[yIndex][xIndex]; } void SpellButtonGroup::updateSelection() { if (g_inputController->isActionLocked()) { return; } if (m_selectedButtonIndexX == -1) { if (g_inputController->isJustLeft() && !m_isWindowLock) { if (m_selectableWindow) { m_selectableWindow->setLeftWindowSelected(); g_inputController->lockAction(); } } else if (g_inputController->isJustRight() && !m_isWindowLock) { if (m_selectableWindow) { m_selectableWindow->setRightWindowSelected(); g_inputController->lockAction(); } } return; } if (g_inputController->isJustLeft()) { setNextButtonSelectedX(false); } else if (g_inputController->isJustRight()) { setNextButtonSelectedX(true); } else if (g_inputController->isJustUp()) { setNextButtonSelectedY(false); } else if (g_inputController->isJustDown()) { setNextButtonSelectedY(true); } auto button = getSelectedButton(); if (button->isActive() && g_inputController->isKeyJustPressed(Key::Confirm)) { button->click(); } } void SpellButtonGroup::setNextButtonSelectedX(bool forward) { selectButton(m_selectedButtonIndexY, getNextEnabledButtonX(forward)); } void SpellButtonGroup::setNextButtonSelectedY(bool forward) { selectButton(getNextEnabledButtonY(forward), m_selectedButtonIndexX); } int SpellButtonGroup::getNextEnabledButtonX(bool forward) { auto const& buttonRow = m_buttons[m_selectedButtonIndexY]; if (forward) { if (m_selectedButtonIndexX + 1 == static_cast<int>(buttonRow.size())) { if (m_selectableWindow && !m_isWindowLock) { m_selectableWindow->setRightWindowSelected(); g_inputController->lockAction(); } } for (int i = m_selectedButtonIndexX + 1; i < static_cast<int>(buttonRow.size()); i++) { if (buttonRow[i]->isActive()) { return i; } } } else { if (m_selectedButtonIndexX == 0) { if (m_selectableWindow && !m_isWindowLock) { m_selectableWindow->setLeftWindowSelected(); g_inputController->lockAction(); } } for (int i = m_selectedButtonIndexX - 1; i > -1; i--) { if (buttonRow[i]->isActive()) { return i; } } } return m_selectedButtonIndexX; } int SpellButtonGroup::getNextEnabledButtonY(bool forward) { if (m_selectedButtonIndexX == -1) { return -1; } if (forward) { for (int i = m_selectedButtonIndexY + 1; i < static_cast<int>(m_buttons.size()); ++i) { if (static_cast<int>(m_buttons[i].size()) > m_selectedButtonIndexX && m_buttons[i][m_selectedButtonIndexX]->isActive()) { return i; } } } else { for (int i = m_selectedButtonIndexY - 1; i > -1; --i) { if (static_cast<int>(m_buttons[i].size()) > m_selectedButtonIndexX && m_buttons[i][m_selectedButtonIndexX]->isActive()) { return i; } } } return m_selectedButtonIndexY; } void SpellButtonGroup::selectButton(int yIndex, int xIndex) { if (yIndex < 0 || yIndex > static_cast<int>(m_buttons.size()) - 1) { return; } if (xIndex < 0 || xIndex > static_cast<int>(m_buttons[yIndex].size()) - 1) { return; } if (xIndex == m_selectedButtonIndexX && yIndex == m_selectedButtonIndexY) { return; } if (m_selectedButtonIndexX != -1) { getSelectedButton()->setSelected(false); } m_selectedButtonIndexY = yIndex; m_selectedButtonIndexX = xIndex; getSelectedButton()->setSelected(true); getSelectedButton()->notifySelection(); g_inputController->lockAction(); } void SpellButtonGroup::notifyButtonSelected(int yIndex, int xIndex) { if (yIndex < 0 || yIndex > static_cast<int>(m_buttons.size()) - 1) { return; } if (xIndex < 0 || xIndex > static_cast<int>(m_buttons[yIndex].size()) - 1) { return; } m_selectedButtonIndexY = yIndex; m_selectedButtonIndexX = xIndex; } void SpellButtonGroup::setWindowLock(bool isLocked) { m_isWindowLock = isLocked; } void SpellButtonGroup::setSelectableWindow(SelectableWindow* window) { m_selectableWindow = window; } GameObjectType SpellButtonGroup::getConfiguredType() const { return GameObjectType::_Button; }
24.903101
124
0.707549
[ "render", "vector" ]
a9cb4e0413ce6b042f9709de4c136aefa9c0d98b
891
cpp
C++
src/process.cpp
nalinraut/System-Monitor
cd51a040455bad43d835606fb3013b35a40f4fc4
[ "MIT" ]
null
null
null
src/process.cpp
nalinraut/System-Monitor
cd51a040455bad43d835606fb3013b35a40f4fc4
[ "MIT" ]
null
null
null
src/process.cpp
nalinraut/System-Monitor
cd51a040455bad43d835606fb3013b35a40f4fc4
[ "MIT" ]
null
null
null
#include <unistd.h> #include <cctype> #include <sstream> #include <string> #include <vector> #include "process.h" #include "linux_parser.h" Process::Process(int pid) : _pid(pid) { _cpu_util = Process::CpuUtilization(); _cmd = LinuxParser::Command(_pid); } int Process::Pid() { return _pid; } float Process::CpuUtilization() { long int frequency = sysconf(_SC_CLK_TCK); _total_time = LinuxParser::ActiveJiffies(_pid)/frequency; _seconds = LinuxParser::UpTime(_pid); return _total_time/_seconds; } std::string Process::Command() { return _cmd; } std::string Process::Ram() { return LinuxParser::Ram(_pid); } std::string Process::User() { return LinuxParser::User(_pid); } long int Process::UpTime() { return LinuxParser::UpTime(_pid); } bool Process::operator<(Process const& a) const { return _cpu_util > a._cpu_util; }
18.957447
61
0.673401
[ "vector" ]
a9cc620cc0f99ddd1bca0938a2252f8388051b46
6,071
cc
C++
ns-3-dev-git/src/wifi/model/ht-configuration.cc
rahul0324/Upgrade-AQM-Evaluation-Suite-of-ns-3
9d46441749da1059b2e9525d72fce61cb0e42150
[ "MIT" ]
1
2022-03-23T13:55:42.000Z
2022-03-23T13:55:42.000Z
ns-3-dev-git/src/wifi/model/ht-configuration.cc
rahulkumdas/Upgrade-AQM-Evaluation-Suite-of-ns-3
9d46441749da1059b2e9525d72fce61cb0e42150
[ "MIT" ]
null
null
null
ns-3-dev-git/src/wifi/model/ht-configuration.cc
rahulkumdas/Upgrade-AQM-Evaluation-Suite-of-ns-3
9d46441749da1059b2e9525d72fce61cb0e42150
[ "MIT" ]
null
null
null
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2018 Sébastien Deronne * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation; * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Sébastien Deronne <sebastien.deronne@gmail.com> */ #include "ns3/log.h" #include "ns3/boolean.h" #include "ns3/uinteger.h" #include "ht-configuration.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("HtConfiguration"); NS_OBJECT_ENSURE_REGISTERED (HtConfiguration); HtConfiguration::HtConfiguration () { NS_LOG_FUNCTION (this); } HtConfiguration::~HtConfiguration () { NS_LOG_FUNCTION (this); } TypeId HtConfiguration::GetTypeId (void) { static ns3::TypeId tid = ns3::TypeId ("ns3::HtConfiguration") .SetParent<Object> () .SetGroupName ("Wifi") .AddConstructor<HtConfiguration> () .AddAttribute ("ShortGuardIntervalSupported", "Whether or not short guard interval is supported.", BooleanValue (false), MakeBooleanAccessor (&HtConfiguration::GetShortGuardIntervalSupported, &HtConfiguration::SetShortGuardIntervalSupported), MakeBooleanChecker ()) .AddAttribute ("GreenfieldSupported", "Whether or not Greenfield is supported.", BooleanValue (false), MakeBooleanAccessor (&HtConfiguration::GetGreenfieldSupported, &HtConfiguration::SetGreenfieldSupported), MakeBooleanChecker ()) .AddAttribute ("RifsSupported", "Whether or not RIFS is supported.", BooleanValue (false), MakeBooleanAccessor (&HtConfiguration::SetRifsSupported, &HtConfiguration::GetRifsSupported), MakeBooleanChecker ()) .AddAttribute ("VoMaxAmsduSize", "Maximum length in bytes of an A-MSDU for AC_VO access class. " "Value 0 means A-MSDU is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&HtConfiguration::m_voMaxAmsduSize), MakeUintegerChecker<uint16_t> (0, 7935)) .AddAttribute ("ViMaxAmsduSize", "Maximum length in bytes of an A-MSDU for AC_VI access class." "Value 0 means A-MSDU is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&HtConfiguration::m_viMaxAmsduSize), MakeUintegerChecker<uint16_t> (0, 7935)) .AddAttribute ("BeMaxAmsduSize", "Maximum length in bytes of an A-MSDU for AC_BE access class." "Value 0 means A-MSDU is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&HtConfiguration::m_beMaxAmsduSize), MakeUintegerChecker<uint16_t> (0, 7935)) .AddAttribute ("BkMaxAmsduSize", "Maximum length in bytes of an A-MSDU for AC_BK access class." "Value 0 means A-MSDU is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&HtConfiguration::m_bkMaxAmsduSize), MakeUintegerChecker<uint16_t> (0, 7935)) .AddAttribute ("VoMaxAmpduSize", "Maximum length in bytes of an A-MPDU for AC_VO access class." "Value 0 means A-MPDU is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&HtConfiguration::m_voMaxAmpduSize), MakeUintegerChecker<uint32_t> (0, 65535)) .AddAttribute ("ViMaxAmpduSize", "Maximum length in bytes of an A-MPDU for AC_VI access class." "Value 0 means A-MPDU is disabled for that AC.", UintegerValue (65535), MakeUintegerAccessor (&HtConfiguration::m_viMaxAmpduSize), MakeUintegerChecker<uint32_t> (0, 65535)) .AddAttribute ("BeMaxAmpduSize", "Maximum length in bytes of an A-MPDU for AC_BE access class." "Value 0 means A-MPDU is disabled for that AC.", UintegerValue (65535), MakeUintegerAccessor (&HtConfiguration::m_beMaxAmpduSize), MakeUintegerChecker<uint32_t> (0, 65535)) .AddAttribute ("BkMaxAmpduSize", "Maximum length in bytes of an A-MPDU for AC_BK access class." "Value 0 means A-MPDU is disabled for that AC.", UintegerValue (0), MakeUintegerAccessor (&HtConfiguration::m_bkMaxAmpduSize), MakeUintegerChecker<uint32_t> (0, 65535)) ; return tid; } void HtConfiguration::SetShortGuardIntervalSupported (bool enable) { NS_LOG_FUNCTION (this << enable); m_sgiSupported = enable; } bool HtConfiguration::GetShortGuardIntervalSupported (void) const { return m_sgiSupported; } void HtConfiguration::SetGreenfieldSupported (bool enable) { NS_LOG_FUNCTION (this << enable); m_greenfieldSupported = enable; } bool HtConfiguration::GetGreenfieldSupported (void) const { return m_greenfieldSupported; } void HtConfiguration::SetRifsSupported (bool enable) { NS_LOG_FUNCTION (this << enable); m_rifsSupported = enable; } bool HtConfiguration::GetRifsSupported (void) const { return m_rifsSupported; } } //namespace ns3
38.18239
90
0.62395
[ "object" ]
a9d0d7a77d0c5d7c65df21ddc79a96b5b3322502
53,929
cpp
C++
psl/rkisp1/ControlUnit.cpp
TinkerEdgeR-Android/hardware_rockchip_camera
652ac45aee3decc561c92c6956b2451d5a633154
[ "Apache-2.0" ]
null
null
null
psl/rkisp1/ControlUnit.cpp
TinkerEdgeR-Android/hardware_rockchip_camera
652ac45aee3decc561c92c6956b2451d5a633154
[ "Apache-2.0" ]
null
null
null
psl/rkisp1/ControlUnit.cpp
TinkerEdgeR-Android/hardware_rockchip_camera
652ac45aee3decc561c92c6956b2451d5a633154
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2017 Intel Corporation. * Copyright (c) 2017, Fuzhou Rockchip Electronics Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "ControlUnit" #include <sys/stat.h> #include "LogHelper.h" #include "PerformanceTraces.h" #include "ControlUnit.h" #include "RKISP1CameraHw.h" #include "ImguUnit.h" #include "CameraStream.h" #include "RKISP1CameraCapInfo.h" #include "CameraMetadataHelper.h" #include "PlatformData.h" #include "ProcUnitSettings.h" #include "SettingsProcessor.h" #include "Metadata.h" #include "MediaEntity.h" #include "rkcamera_vendor_tags.h" #include "TuningServer.h" USING_METADATA_NAMESPACE; static const int SETTINGS_POOL_SIZE = MAX_REQUEST_IN_PROCESS_NUM * 2; namespace android { namespace camera2 { SocCamFlashCtrUnit::SocCamFlashCtrUnit(const char* name, int CameraId) : mFlSubdev(new V4L2Subdevice(name)), mV4lFlashMode(V4L2_FLASH_LED_MODE_NONE), mAePreTrigger(0), mAeTrigFrms(0), mAeFlashMode(ANDROID_FLASH_MODE_OFF), mAeMode(ANDROID_CONTROL_AE_MODE_ON), mAeState(ANDROID_CONTROL_AE_STATE_INACTIVE) { LOGD("%s:%d", __FUNCTION__, __LINE__); if (mFlSubdev.get()) mFlSubdev->open(); } SocCamFlashCtrUnit::~SocCamFlashCtrUnit() { LOGD("%s:%d", __FUNCTION__, __LINE__); if (mFlSubdev.get()) { setV4lFlashMode(CAM_AE_FLASH_MODE_OFF, 100, 0, 0); mFlSubdev->close(); } } int SocCamFlashCtrUnit::setFlashSettings(const CameraMetadata *settings) { int ret = 0; // parse flash mode, ae mode, ae precap trigger uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON; camera_metadata_ro_entry entry = settings->find(ANDROID_CONTROL_AE_MODE); if (entry.count == 1) aeMode = entry.data.u8[0]; uint8_t flash_mode = ANDROID_FLASH_MODE_OFF; entry = settings->find(ANDROID_FLASH_MODE); if (entry.count == 1) { flash_mode = entry.data.u8[0]; } mAeFlashMode = flash_mode; mAeMode = aeMode; // if aemode is *_flash, overide the flash mode of ANDROID_FLASH_MODE int flashMode; if (aeMode == ANDROID_CONTROL_AE_MODE_ON_AUTO_FLASH) flashMode = CAM_AE_FLASH_MODE_AUTO; // TODO: set always on for soc now else if (aeMode == ANDROID_CONTROL_AE_MODE_ON_ALWAYS_FLASH) flashMode = CAM_AE_FLASH_MODE_ON; else if (flash_mode == ANDROID_FLASH_MODE_TORCH) flashMode = CAM_AE_FLASH_MODE_TORCH; else if (flash_mode == ANDROID_FLASH_MODE_SINGLE) flashMode = CAM_AE_FLASH_MODE_SINGLE; else flashMode = CAM_AE_FLASH_MODE_OFF; // TODO: set always on for soc now if (flashMode == CAM_AE_FLASH_MODE_AUTO || flashMode == CAM_AE_FLASH_MODE_SINGLE) flashMode = CAM_AE_FLASH_MODE_ON; if (flashMode == CAM_AE_FLASH_MODE_ON) { entry = settings->find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER); if (entry.count == 1) { if (!(entry.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE && mAePreTrigger == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START)) mAePreTrigger = entry.data.u8[0]; } } mAeState = ANDROID_CONTROL_AE_STATE_CONVERGED; int setToDrvFlMode = flashMode; if (flashMode == CAM_AE_FLASH_MODE_TORCH) setToDrvFlMode = CAM_AE_FLASH_MODE_TORCH; else if (flashMode == CAM_AE_FLASH_MODE_ON) { // assume SoC sensor has only torch flash mode, and for // ANDROID_CONTROL_CAPTURE_INTENT usecase, flash should keep // on until the jpeg image captured. if (mAePreTrigger == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START) { setToDrvFlMode = CAM_AE_FLASH_MODE_TORCH; mAeState = ANDROID_CONTROL_AE_STATE_PRECAPTURE; mAeTrigFrms++; // keep on precap for 10 frames to wait flash ae stable if (mAeTrigFrms > 10) mAeState = ANDROID_CONTROL_AE_STATE_CONVERGED; // keep flash on another 10 frames to make sure capture the // flashed frame if (mAeTrigFrms > 20) { setToDrvFlMode = CAM_AE_FLASH_MODE_OFF; mAeTrigFrms = 0; mAePreTrigger = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL; mAeState = ANDROID_CONTROL_AE_STATE_CONVERGED; } } else if (mAePreTrigger == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_CANCEL) { setToDrvFlMode = CAM_AE_FLASH_MODE_OFF; mAeTrigFrms = 0; } LOGD("aePreTrigger %d, mAeTrigFrms %d", mAePreTrigger, mAeTrigFrms); } else setToDrvFlMode = CAM_AE_FLASH_MODE_OFF; LOGD("%s:%d aePreTrigger %d, mAeTrigFrms %d, setToDrvFlMode %d", __FUNCTION__, __LINE__, mAePreTrigger, mAeTrigFrms, setToDrvFlMode); return setV4lFlashMode(setToDrvFlMode, 100, 500, 0); } int SocCamFlashCtrUnit::updateFlashResult(CameraMetadata *result) { result->update(ANDROID_CONTROL_AE_MODE, &mAeMode, 1); result->update(ANDROID_CONTROL_AE_STATE, &mAeState, 1); result->update(ANDROID_FLASH_MODE, &mAeFlashMode, 1); uint8_t flashState = ANDROID_FLASH_STATE_READY; if (mV4lFlashMode == V4L2_FLASH_LED_MODE_FLASH || mV4lFlashMode == V4L2_FLASH_LED_MODE_TORCH) flashState = ANDROID_FLASH_STATE_FIRED; //# ANDROID_METADATA_Dynamic android.flash.state done result->update(ANDROID_FLASH_STATE, &flashState, 1); return 0; } int SocCamFlashCtrUnit::setV4lFlashMode(int mode, int power, int timeout, int strobe) { struct v4l2_control control; int fl_v4l_mode; #define set_fl_contol_to_dev(control_id,val) \ memset(&control, 0, sizeof(control)); \ control.id = control_id; \ control.value = val; \ if (mFlSubdev.get()) { \ if (pioctl(mFlSubdev->getFd(), VIDIOC_S_CTRL, &control, 0) < 0) { \ LOGE(" set fl %s to %d failed", #control_id, val); \ return -1; \ } \ LOGD("set fl %s to %d, success", #control_id, val); \ } \ if (mode == CAM_AE_FLASH_MODE_OFF) fl_v4l_mode = V4L2_FLASH_LED_MODE_NONE; else if (mode == CAM_AE_FLASH_MODE_ON) fl_v4l_mode = V4L2_FLASH_LED_MODE_FLASH; else if (mode == CAM_AE_FLASH_MODE_TORCH) fl_v4l_mode = V4L2_FLASH_LED_MODE_TORCH; else { LOGE(" set fl to mode %d failed", mode); return -1; } if (mV4lFlashMode == fl_v4l_mode) return 0; if (fl_v4l_mode == V4L2_FLASH_LED_MODE_NONE) { set_fl_contol_to_dev(V4L2_CID_FLASH_LED_MODE, V4L2_FLASH_LED_MODE_NONE); } else if (fl_v4l_mode == V4L2_FLASH_LED_MODE_FLASH) { set_fl_contol_to_dev(V4L2_CID_FLASH_LED_MODE, V4L2_FLASH_LED_MODE_FLASH); set_fl_contol_to_dev(V4L2_CID_FLASH_TIMEOUT, timeout * 1000); // TODO: should query intensity range before setting /* set_fl_contol_to_dev(V4L2_CID_FLASH_INTENSITY, fl_intensity); */ set_fl_contol_to_dev(strobe ? V4L2_CID_FLASH_STROBE : V4L2_CID_FLASH_STROBE_STOP, 0); } else if (fl_v4l_mode == V4L2_FLASH_LED_MODE_TORCH) { // TODO: should query intensity range before setting /* set_fl_contol_to_dev(V4L2_CID_FLASH_TORCH_INTENSITY, fl_intensity); */ set_fl_contol_to_dev(V4L2_CID_FLASH_LED_MODE, V4L2_FLASH_LED_MODE_TORCH); } else { LOGE("setV4lFlashMode error fl mode %d", mode); return -1; } mV4lFlashMode = fl_v4l_mode; return 0; } ControlUnit::ControlUnit(ImguUnit *thePU, int cameraId, IStreamConfigProvider &aStreamCfgProv, std::shared_ptr<MediaController> mc) : mRequestStatePool("CtrlReqState"), mCaptureUnitSettingsPool("CapUSettings"), mProcUnitSettingsPool("ProcUSettings"), mLatestRequestId(-1), mImguUnit(thePU), mCtrlLoop(nullptr), mEnable3A(true), mCameraId(cameraId), mMediaCtl(mc), mThreadRunning(false), mMessageQueue("CtrlUnitThread", static_cast<int>(MESSAGE_ID_MAX)), mMessageThread(nullptr), mStreamCfgProv(aStreamCfgProv), mSettingsProcessor(nullptr), mMetadata(nullptr), mSensorSettingsDelay(0), mGainDelay(0), mLensSupported(false), mSofSequence(0), mShutterDoneReqId(-1), mSensorSubdev(nullptr), mSocCamFlashCtrUnit(nullptr), mStillCapSyncNeeded(0), mStillCapSyncState(STILL_CAP_SYNC_STATE_TO_ENGINE_IDLE), mFlushForUseCase(FLUSH_FOR_NOCHANGE) { cl_result_callback_ops::metadata_result_callback = &sMetadatCb; } status_t ControlUnit::getDevicesPath() { std::shared_ptr<MediaEntity> mediaEntity = nullptr; std::string entityName; const CameraHWInfo* camHwInfo = PlatformData::getCameraHWInfo(); std::shared_ptr<V4L2Subdevice> subdev = nullptr; status_t status = OK; // get lens device path if (camHwInfo->mSensorInfo[mCameraId].mModuleLensDevName == "") { LOGW("%s: No lens found", __FUNCTION__); } else { struct stat sb; int PathExists = stat(camHwInfo->mSensorInfo[mCameraId].mModuleLensDevName.c_str(), &sb); if (PathExists != 0) { LOGE("Error, could not find lens subdev %s !", entityName.c_str()); } else { mDevPathsMap[KDevPathTypeLensNode] = camHwInfo->mSensorInfo[mCameraId].mModuleLensDevName; } } #if 0 // get flashlight device path if (camHwInfo->mSensorInfo[mCameraId].mModuleFlashDevName == "") { LOGW("%s: No flashlight found", __FUNCTION__); } else { struct stat sb; int PathExists = stat(camHwInfo->mSensorInfo[mCameraId].mModuleFlashDevName.c_str(), &sb); if (PathExists != 0) { LOGE("Error, could not find flashlight subdev %s !", entityName.c_str()); } else { mDevPathsMap[KDevPathTypeFlNode] = camHwInfo->mSensorInfo[mCameraId].mModuleFlashDevName; } } #endif // get isp subdevice path entityName = "rkisp1-isp-subdev"; status = mMediaCtl->getMediaEntity(mediaEntity, entityName.c_str()); if (mediaEntity == nullptr || status != NO_ERROR) { LOGE("Could not retrieve media entity %s", entityName.c_str()); return UNKNOWN_ERROR; } mediaEntity->getDevice((std::shared_ptr<V4L2DeviceBase>&) subdev); if (subdev.get()) mDevPathsMap[KDevPathTypeIspDevNode] = subdev->name(); // get sensor device path camHwInfo->getSensorEntityName(mCameraId, entityName); if (entityName == "none") { LOGE("%s: No pixel_array found", __FUNCTION__); return UNKNOWN_ERROR; } else { status = mMediaCtl->getMediaEntity(mediaEntity, entityName.c_str()); if (mediaEntity == nullptr || status != NO_ERROR) { LOGE("Could not retrieve media entity %s", entityName.c_str()); return UNKNOWN_ERROR; } mediaEntity->getDevice((std::shared_ptr<V4L2DeviceBase>&) subdev); if (subdev.get()) { mDevPathsMap[KDevPathTypeSensorNode] = subdev->name(); mSensorSubdev = subdev; } } // get isp input params device path entityName = "rkisp1-input-params"; status = mMediaCtl->getMediaEntity(mediaEntity, entityName.c_str()); if (mediaEntity == nullptr || status != NO_ERROR) { LOGE("%s, Could not retrieve Media Entity %s", __FUNCTION__, entityName.c_str()); return UNKNOWN_ERROR; } mediaEntity->getDevice((std::shared_ptr<V4L2DeviceBase>&) subdev); if (subdev.get()) mDevPathsMap[KDevPathTypeIspInputParamsNode] = subdev->name(); // get isp stats device path entityName = "rkisp1-statistics"; status = mMediaCtl->getMediaEntity(mediaEntity, entityName.c_str()); if (mediaEntity == nullptr || status != NO_ERROR) { LOGE("%s, Could not retrieve Media Entity %s", __FUNCTION__, entityName.c_str()); return UNKNOWN_ERROR; } mediaEntity->getDevice((std::shared_ptr<V4L2DeviceBase>&) subdev); if (subdev.get()) mDevPathsMap[KDevPathTypeIspStatsNode] = subdev->name(); return OK; } /** * initStaticMetadata * * Create CameraMetadata object to retrieve the static tags used in this class * we cache them as members so that we do not need to query CameraMetadata class * everytime we need them. This is more efficient since find() is not cheap */ status_t ControlUnit::initStaticMetadata() { //Initialize the CameraMetadata object with the static metadata tags camera_metadata_t* plainStaticMeta; plainStaticMeta = (camera_metadata_t*)PlatformData::getStaticMetadata(mCameraId); if (plainStaticMeta == nullptr) { LOGE("Failed to get camera %d StaticMetadata", mCameraId); return UNKNOWN_ERROR; } CameraMetadata staticMeta(plainStaticMeta); camera_metadata_entry entry; entry = staticMeta.find(ANDROID_LENS_INFO_MINIMUM_FOCUS_DISTANCE); if (entry.count == 1) { LOGI("camera %d minimum focus distance:%f", mCameraId, entry.data.f[0]); mLensSupported = (entry.data.f[0] > 0) ? true : false; LOGI("Lens movement %s for camera id %d", mLensSupported ? "supported" : "NOT supported", mCameraId); } staticMeta.release(); const RKISP1CameraCapInfo *cap = getRKISP1CameraCapInfo(mCameraId); if (cap == nullptr) { LOGE("Failed to get cameraCapInfo"); return UNKNOWN_ERROR; } mSensorSettingsDelay = MAX(cap->mExposureLag, cap->mGainLag); mGainDelay = cap->mGainLag; return NO_ERROR; } status_t ControlUnit::init() { HAL_TRACE_CALL(CAM_GLBL_DBG_HIGH); status_t status = OK; const char *sensorName = nullptr; //Cache the static metadata values we are going to need in the capture unit if (initStaticMetadata() != NO_ERROR) { LOGE("Cannot initialize static metadata"); return NO_INIT; } mMessageThread = std::unique_ptr<MessageThread>(new MessageThread(this, "CtrlUThread")); mMessageThread->run(); const RKISP1CameraCapInfo *cap = getRKISP1CameraCapInfo(mCameraId); if (!cap) { LOGE("Not enough information for getting NVM data"); return UNKNOWN_ERROR; } else { sensorName = cap->getSensorName(); } // In the case: CAMERA_DUMP_RAW + no rawPath, disable 3a. // because isp is bypassed in this case // Note: only isp support rawPath, hal report the raw capability, // so the case "raw stream + no rawPath" shouln't exists if (cap->sensorType() == SENSOR_TYPE_RAW && !(LogHelper::isDumpTypeEnable(CAMERA_DUMP_RAW) && !PlatformData::getCameraHWInfo()->isIspSupportRawPath())) { mCtrlLoop = new RkCtrlLoop(mCameraId); if (mCtrlLoop->init(sensorName, this) != NO_ERROR) { LOGE("Error initializing 3A control"); return UNKNOWN_ERROR; } } else { LOGW("No need 3A control, isSocSensor: %s, rawDump:%d", cap->sensorType() == SENSOR_TYPE_SOC ? "Yes" : "No", LogHelper::isDumpTypeEnable(CAMERA_DUMP_RAW)); //return UNKNOWN_ERROR; } mSettingsProcessor = new SettingsProcessor(mCameraId, mStreamCfgProv); mSettingsProcessor->init(); mMetadata = new Metadata(mCameraId); status = mMetadata->init(); if (CC_UNLIKELY(status != OK)) { LOGE("Error Initializing metadata"); return UNKNOWN_ERROR; } /* * init the pools of Request State structs and CaptureUnit settings * and Processing Unit Settings */ mRequestStatePool.init(MAX_REQUEST_IN_PROCESS_NUM, RequestCtrlState::reset); mCaptureUnitSettingsPool.init(SETTINGS_POOL_SIZE + 2); mProcUnitSettingsPool.init(SETTINGS_POOL_SIZE, ProcUnitSettings::reset); mSettingsHistory.clear(); /* Set digi gain support */ bool supportDigiGain = false; if (cap) supportDigiGain = cap->digiGainOnSensor(); getDevicesPath(); const CameraHWInfo* camHwInfo = PlatformData::getCameraHWInfo(); if (cap->sensorType() == SENSOR_TYPE_SOC && camHwInfo->mSensorInfo[mCameraId].mFlashNum > 0) { mSocCamFlashCtrUnit = std::unique_ptr<SocCamFlashCtrUnit>( new SocCamFlashCtrUnit( // TODO: support only one flash for SoC now camHwInfo->mSensorInfo[mCameraId].mModuleFlashDevName[0].c_str(), mCameraId)); } return status; } /** * reset * * This method is called by the SharedPoolItem when the item is recycled * At this stage we can cleanup before recycling the struct. * In this case we reset the TracingSP of the capture unit settings and buffers * to remove this reference. Other references may be still alive. */ void RequestCtrlState::reset(RequestCtrlState* me) { if (CC_LIKELY(me != nullptr)) { me->captureSettings.reset(); me->processingSettings.reset(); me->graphConfig.reset(); } else { LOGE("Trying to reset a null CtrlState structure !! - BUG "); } } void RequestCtrlState::init(Camera3Request *req, std::shared_ptr<GraphConfig> aGraphConfig) { request = req; graphConfig = aGraphConfig; if (CC_LIKELY(captureSettings)) { captureSettings->aeRegion.init(0); captureSettings->makernote.data = nullptr; captureSettings->makernote.size = 0; } else { LOGE(" Failed to init Ctrl State struct: no capture settings!! - BUG"); return; } if (CC_LIKELY(processingSettings.get() != nullptr)) { processingSettings->captureSettings = captureSettings; processingSettings->graphConfig = aGraphConfig; processingSettings->request = req; } else { LOGE(" Failed to init Ctrl State: no processing settings!! - BUG"); return; } ctrlUnitResult = request->getPartialResultBuffer(CONTROL_UNIT_PARTIAL_RESULT); shutterDone = false; intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW; if (CC_UNLIKELY(ctrlUnitResult == nullptr)) { LOGE("no partial result buffer - BUG"); return; } mClMetaReceived = false; mShutterMetaReceived = false; mImgProcessDone = false; /** * Apparently we need to have this tags in the results */ const CameraMetadata* settings = request->getSettings(); if (CC_UNLIKELY(settings == nullptr)) { LOGE("no settings in request - BUG"); return; } int64_t id = request->getId(); camera_metadata_ro_entry entry; entry = settings->find(ANDROID_REQUEST_ID); if (entry.count == 1) { ctrlUnitResult->update(ANDROID_REQUEST_ID, (int *)&id, entry.count); } ctrlUnitResult->update(ANDROID_SYNC_FRAME_NUMBER, &id, 1); entry = settings->find(ANDROID_CONTROL_CAPTURE_INTENT); if (entry.count == 1) { intent = entry.data.u8[0]; } LOGI("%s:%d: request id(%lld), capture_intent(%d)", __FUNCTION__, __LINE__, id, intent); ctrlUnitResult->update(ANDROID_CONTROL_CAPTURE_INTENT, entry.data.u8, entry.count); } ControlUnit::~ControlUnit() { HAL_TRACE_CALL(CAM_GLBL_DBG_HIGH); mSettingsHistory.clear(); requestExitAndWait(); if (mMessageThread != nullptr) { mMessageThread.reset(); mMessageThread = nullptr; } if (mSettingsProcessor) { delete mSettingsProcessor; mSettingsProcessor = nullptr; } if (mCtrlLoop) { mCtrlLoop->deinit(); delete mCtrlLoop; mCtrlLoop = nullptr; } delete mMetadata; mMetadata = nullptr; } status_t ControlUnit::configStreams(std::vector<camera3_stream_t*> &activeStreams, bool configChanged) { PERFORMANCE_ATRACE_NAME("ControlUnit::configStreams"); LOGI("@%s %d: configChanged :%d", __FUNCTION__, __LINE__, configChanged); status_t status = OK; if(configChanged) { // this will be necessary when configStream called twice without calling // destruct function which called in the close camera stack mLatestRequestId = -1; mWaitingForCapture.clear(); mSettingsHistory.clear(); struct rkisp_cl_prepare_params_s prepareParams; memset(&prepareParams, 0, sizeof(struct rkisp_cl_prepare_params_s)); prepareParams.staticMeta = PlatformData::getStaticMetadata(mCameraId); if (prepareParams.staticMeta == nullptr) { LOGE("Failed to get camera %d StaticMetadata for CL", mCameraId); return UNKNOWN_ERROR; } //start 3a when config video stream done for (auto &it : mDevPathsMap) { switch (it.first) { case KDevPathTypeIspDevNode: prepareParams.isp_sd_node_path = it.second.c_str(); break; case KDevPathTypeIspStatsNode: prepareParams.isp_vd_stats_path = it.second.c_str(); break; case KDevPathTypeIspInputParamsNode: prepareParams.isp_vd_params_path = it.second.c_str(); break; case KDevPathTypeSensorNode: prepareParams.sensor_sd_node_path = it.second.c_str(); break; case KDevPathTypeLensNode: prepareParams.lens_sd_node_path = it.second.c_str(); break; // deprecated case KDevPathTypeFlNode: prepareParams.flashlight_sd_node_path[0] = it.second.c_str(); break; default: continue; } } const CameraHWInfo* camHwInfo = PlatformData::getCameraHWInfo(); for (int i = 0; i < camHwInfo->mSensorInfo[mCameraId].mFlashNum; i++) { prepareParams.flashlight_sd_node_path[i] = camHwInfo->mSensorInfo[mCameraId].mModuleFlashDevName[i].c_str(); } mEnable3A = true; for (auto it = activeStreams.begin(); it != activeStreams.end(); ++it) { if((*it)->format == HAL_PIXEL_FORMAT_RAW_OPAQUE && !PlatformData::getCameraHWInfo()->isIspSupportRawPath()) { mEnable3A = false; break; } } LOGD("@%s : mEnable3A :%d", __FUNCTION__, mEnable3A); if (mCtrlLoop && mEnable3A ) { status = mCtrlLoop->start(prepareParams); if (CC_UNLIKELY(status != OK)) { LOGE("Failed to start 3a control loop!"); return status; } } } return NO_ERROR; } status_t ControlUnit::requestExitAndWait() { Message msg; msg.id = MESSAGE_ID_EXIT; status_t status = mMessageQueue.send(&msg, MESSAGE_ID_EXIT); status |= mMessageThread->requestExitAndWait(); return status; } status_t ControlUnit::handleMessageExit() { mThreadRunning = false; return NO_ERROR; } /** * acquireRequestStateStruct * * acquire a free request control state structure. * Since this structure contains also a capture settings item that are also * stored in a pool we need to acquire one of those as well. * */ status_t ControlUnit::acquireRequestStateStruct(std::shared_ptr<RequestCtrlState>& state) { status_t status = NO_ERROR; status = mRequestStatePool.acquireItem(state); if (status != NO_ERROR) { LOGE("Failed to acquire free request state struct - BUG"); /* * This should not happen since AAL is holding clients to send more * requests than we can take */ return UNKNOWN_ERROR; } status = mCaptureUnitSettingsPool.acquireItem(state->captureSettings); if (status != NO_ERROR) { LOGE("Failed to acquire free CapU settings struct - BUG"); /* * This should not happen since AAL is holding clients to send more * requests than we can take */ return UNKNOWN_ERROR; } // set a unique ID for the settings state->captureSettings->settingsIdentifier = systemTime(); status = mProcUnitSettingsPool.acquireItem(state->processingSettings); if (status != NO_ERROR) { LOGE("Failed to acquire free ProcU settings struct - BUG"); /* * This should not happen since AAL is holding clients to send more * requests than we can take */ return UNKNOWN_ERROR; } return OK; } /** * processRequest * * Acquire the control structure to keep the state of the request in the control * unit and send the message to be handled in the internal message thread. */ status_t ControlUnit::processRequest(Camera3Request* request, std::shared_ptr<GraphConfig> graphConfig) { Message msg; status_t status = NO_ERROR; std::shared_ptr<RequestCtrlState> state; status = acquireRequestStateStruct(state); if (CC_UNLIKELY(status != OK) || CC_UNLIKELY(state.get() == nullptr)) { return status; // error log already done in the helper method } state->init(request, graphConfig); msg.id = MESSAGE_ID_NEW_REQUEST; msg.state = state; status = mMessageQueue.send(&msg); return status; } status_t ControlUnit::handleNewRequest(Message &msg) { HAL_TRACE_CALL(CAM_GLBL_DBG_HIGH); status_t status = NO_ERROR; std::shared_ptr<RequestCtrlState> reqState = msg.state; /** * PHASE 1: Process the settings * In this phase we analyze the request's metadata settings and convert them * into either: * - input parameters for 3A algorithms * - parameters used for SoC sensors * - Capture Unit settings * - Processing Unit settings */ const CameraMetadata *reqSettings = reqState->request->getSettings(); if (reqSettings == nullptr) { LOGE("no settings in request - BUG"); return UNKNOWN_ERROR; } status = mSettingsProcessor->processRequestSettings(*reqSettings, *reqState); if (status != NO_ERROR) { LOGE("Could not process all settings, reporting request as invalid"); } status = processRequestForCapture(reqState); if (CC_UNLIKELY(status != OK)) { LOGE("Failed to process req %d for capture [%d]", reqState->request->getId(), status); // TODO: handle error ! } return status; } status_t ControlUnit::processSoCSettings(const CameraMetadata *settings) { // fill target fps range, it needs to be proper in results anyway camera_metadata_ro_entry entry = settings->find(ANDROID_CONTROL_AE_TARGET_FPS_RANGE); if (entry.count == 2) { int32_t maxFps = entry.data.i32[1]; // set to driver if (mSensorSubdev.get()) mSensorSubdev->setFramerate(0, maxFps); } if (mSocCamFlashCtrUnit.get()) { int ret = mSocCamFlashCtrUnit->setFlashSettings(settings); if (ret < 0) LOGE("%s:%d set flash settings failed", __FUNCTION__, __LINE__); } return OK; } /** * processRequestForCapture * * Run 3A algorithms and send the results to capture unit for capture * * This is the second phase in the request processing flow. * * The request settings have been processed in the first phase * * If this step is successful the request will be moved to the * mWaitingForCapture waiting for the pixel buffers. */ status_t ControlUnit::processRequestForCapture(std::shared_ptr<RequestCtrlState> &reqState) { status_t status = NO_ERROR; if (CC_UNLIKELY(reqState.get() == nullptr)) { LOGE("Invalid parameters passed- request not captured - BUG"); return BAD_VALUE; } reqState->request->dumpSetting(); if (CC_UNLIKELY(reqState->captureSettings.get() == nullptr)) { LOGE("capture Settings not given - BUG"); return BAD_VALUE; } /* Write the dump flag into capture settings, so that the PAL dump can be * done all the way down at PgParamAdaptor. For the time being, only dump * during jpeg captures. */ reqState->processingSettings->dump = LogHelper::isDumpTypeEnable(CAMERA_DUMP_RAW) && reqState->request->getBufferCountOfFormat(HAL_PIXEL_FORMAT_BLOB) > 0; // dump the PAL run from ISA also reqState->captureSettings->dump = reqState->processingSettings->dump; int reqId = reqState->request->getId(); /** * Move the request to the vector mWaitingForCapture */ mWaitingForCapture.insert(std::make_pair(reqId, reqState)); mLatestRequestId = reqId; int jpegBufCount = reqState->request->getBufferCountOfFormat(HAL_PIXEL_FORMAT_BLOB); int implDefinedBufCount = reqState->request->getBufferCountOfFormat(HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED); int yuv888BufCount = reqState->request->getBufferCountOfFormat(HAL_PIXEL_FORMAT_YCbCr_420_888); LOGD("@%s jpegs:%d impl defined:%d yuv888:%d inputbufs:%d req id %d", __FUNCTION__, jpegBufCount, implDefinedBufCount, yuv888BufCount, reqState->request->getNumberInputBufs(), reqState->request->getId()); if (jpegBufCount > 0) { // NOTE: Makernote should be get after isp_bxt_run() // NOTE: makernote.data deleted in JpegEncodeTask::handleMakernote() /* TODO */ /* const unsigned mknSize = MAKERNOTE_SECTION1_SIZE + MAKERNOTE_SECTION2_SIZE; */ /* MakernoteData mkn = {nullptr, mknSize}; */ /* mkn.data = new char[mknSize]; */ /* m3aWrapper->getMakerNote(ia_mkn_trg_section_2, mkn); */ /* reqState->captureSettings->makernote = mkn; */ } else { // No JPEG buffers in request. Reset MKN info, just in case. reqState->captureSettings->makernote.data = nullptr; reqState->captureSettings->makernote.size = 0; } // if this request is a reprocess request, no need to setFrameParam to CL. if (reqState->request->getNumberInputBufs() == 0) { if (mCtrlLoop && mEnable3A) { const CameraMetadata *settings = reqState->request->getSettings(); rkisp_cl_frame_metadata_s frame_metas; /* frame_metas.metas = settings->getAndLock(); */ /* frame_metas.id = reqId; */ CameraMetadata tempCamMeta = *settings; camera_metadata_ro_entry entry = settings->find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER); if (entry.count == 1) { if (entry.data.u8[0] == ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START) { mStillCapSyncState = STILL_CAP_SYNC_STATE_TO_ENGINE_PRECAP; } } if(jpegBufCount == 0) { uint8_t intent = ANDROID_CONTROL_CAPTURE_INTENT_PREVIEW; tempCamMeta.update(ANDROID_CONTROL_CAPTURE_INTENT, &intent, 1); } else { if (mStillCapSyncNeeded) { if (mStillCapSyncState == STILL_CAP_SYNC_STATE_TO_ENGINE_IDLE) { LOGD("forcely trigger ae precapture"); uint8_t precap = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START; tempCamMeta.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &precap, 1); mStillCapSyncState = STILL_CAP_SYNC_STATE_TO_ENGINE_PRECAP; } if (mStillCapSyncState == STILL_CAP_SYNC_STATE_TO_ENGINE_PRECAP) { uint8_t stillCapSync = RKCAMERA3_PRIVATEDATA_STILLCAP_SYNC_CMD_SYNCSTART; tempCamMeta.update(RKCAMERA3_PRIVATEDATA_STILLCAP_SYNC_CMD, &stillCapSync, 1); mStillCapSyncState = STILL_CAP_SYNC_STATE_WAITING_ENGINE_DONE; } else LOGW("already in stillcap_sync state %d", mStillCapSyncState); } } TuningServer *pserver = TuningServer::GetInstance(); if (pserver && pserver->isTuningMode()) { pserver->set_tuning_params(tempCamMeta); } frame_metas.metas = tempCamMeta.getAndLock(); frame_metas.id = reqId; status = mCtrlLoop->setFrameParams(&frame_metas); if (status != OK) LOGE("CtrlLoop setFrameParams error"); /* status = settings->unlock(frame_metas.metas); */ status = tempCamMeta.unlock(frame_metas.metas); if (status != OK) { LOGE("unlock frame frame_metas failed"); return UNKNOWN_ERROR; } int max_counts = 500; while (mStillCapSyncState == STILL_CAP_SYNC_STATE_WAITING_ENGINE_DONE && max_counts > 0) { LOGD("waiting for stillcap_sync_done"); usleep(10*1000); max_counts--; } if (max_counts == 0) { mStillCapSyncState = STILL_CAP_SYNC_STATE_FROM_ENGINE_DONE; LOGW("waiting for stillcap_sync_done timeout!"); } if (mStillCapSyncState == STILL_CAP_SYNC_STATE_FROM_ENGINE_DONE) { mStillCapSyncState = STILL_CAP_SYNC_STATE_WATING_JPEG_FRAME; } LOGD("%s:%d, stillcap_sync_state %d", __FUNCTION__, __LINE__, mStillCapSyncState); } else { // set SoC sensor's params const CameraMetadata *settings = reqState->request->getSettings(); processSoCSettings(settings); } } else { LOGD("@%s %d: reprocess request:%d, no need setFrameParam", __FUNCTION__, __LINE__, reqId); reqState->mClMetaReceived = true; /* Result as reprocessing request: The HAL can expect that a reprocessing request is a copy */ /* of one of the output results with minor allowed setting changes. */ reqState->ctrlUnitResult->append(*reqState->request->getSettings()); } /*TODO, needn't this anymore ? zyc*/ status = completeProcessing(reqState); if (status != OK) LOGE("Cannot complete the buffer processing - fix the bug!"); return status; } status_t ControlUnit::fillMetadata(std::shared_ptr<RequestCtrlState> &reqState) { /** * Apparently we need to have this tags in the results */ const CameraMetadata* settings = reqState->request->getSettings(); CameraMetadata* ctrlUnitResult = reqState->ctrlUnitResult; if (CC_UNLIKELY(settings == nullptr)) { LOGE("no settings in request - BUG"); return UNKNOWN_ERROR; } camera_metadata_ro_entry entry; entry = settings->find(ANDROID_CONTROL_MODE); if (entry.count == 1) { ctrlUnitResult->update(ANDROID_CONTROL_MODE, entry.data.u8, entry.count); } //# ANDROID_METADATA_Dynamic android.control.videoStabilizationMode copied entry = settings->find(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE); if (entry.count == 1) { ctrlUnitResult->update(ANDROID_CONTROL_VIDEO_STABILIZATION_MODE, entry.data.u8, entry.count); } //# ANDROID_METADATA_Dynamic android.lens.opticalStabilizationMode copied entry = settings->find(ANDROID_LENS_OPTICAL_STABILIZATION_MODE); if (entry.count == 1) { ctrlUnitResult->update(ANDROID_LENS_OPTICAL_STABILIZATION_MODE, entry.data.u8, entry.count); } //# ANDROID_METADATA_Dynamic android.control.effectMode done entry = settings->find(ANDROID_CONTROL_EFFECT_MODE); if (entry.count == 1) { ctrlUnitResult->update(ANDROID_CONTROL_EFFECT_MODE, entry.data.u8, entry.count); } //# ANDROID_METADATA_Dynamic android.noiseReduction.mode done entry = settings->find(ANDROID_NOISE_REDUCTION_MODE); if (entry.count == 1) { ctrlUnitResult->update(ANDROID_NOISE_REDUCTION_MODE, entry.data.u8, entry.count); } //# ANDROID_METADATA_Dynamic android.edge.mode done entry = settings->find(ANDROID_EDGE_MODE); if (entry.count == 1) { ctrlUnitResult->update(ANDROID_EDGE_MODE, entry.data.u8, entry.count); } /** * We don't have AF, so just update metadata now */ // return 0.0f for the fixed-focus if (!mLensSupported) { float focusDistance = 0.0f; reqState->ctrlUnitResult->update(ANDROID_LENS_FOCUS_DISTANCE, &focusDistance, 1); // framework says it can't be off mode for zsl, // so we report EDOF for fixed focus // TODO: need to judge if the request is ZSL ? /* uint8_t afMode = ANDROID_CONTROL_AF_MODE_EDOF; */ uint8_t afMode = ANDROID_CONTROL_AF_MODE_OFF; ctrlUnitResult->update(ANDROID_CONTROL_AF_MODE, &afMode, 1); uint8_t afTrigger = ANDROID_CONTROL_AF_TRIGGER_IDLE; ctrlUnitResult->update(ANDROID_CONTROL_AF_TRIGGER, &afTrigger, 1); uint8_t afState = ANDROID_CONTROL_AF_STATE_INACTIVE; ctrlUnitResult->update(ANDROID_CONTROL_AF_STATE, &afState, 1); } bool flash_available = false; uint8_t flash_mode = ANDROID_FLASH_MODE_OFF; mSettingsProcessor->getStaticMetadataCache().getFlashInfoAvailable(flash_available); if (!flash_available) { reqState->ctrlUnitResult->update(ANDROID_FLASH_MODE, &flash_mode, 1); uint8_t flashState = ANDROID_FLASH_STATE_UNAVAILABLE; //# ANDROID_METADATA_Dynamic android.flash.state done reqState->ctrlUnitResult->update(ANDROID_FLASH_STATE, &flashState, 1); } mMetadata->writeJpegMetadata(*reqState); uint8_t pipelineDepth; mSettingsProcessor->getStaticMetadataCache().getPipelineDepth(pipelineDepth); //# ANDROID_METADATA_Dynamic android.request.pipelineDepth done reqState->ctrlUnitResult->update(ANDROID_REQUEST_PIPELINE_DEPTH, &pipelineDepth, 1); // for soc camera if (!mCtrlLoop || !mEnable3A) { uint8_t awbMode = ANDROID_CONTROL_AWB_MODE_AUTO; ctrlUnitResult->update(ANDROID_CONTROL_AWB_MODE, &awbMode, 1); uint8_t awbState = ANDROID_CONTROL_AWB_STATE_CONVERGED; ctrlUnitResult->update(ANDROID_CONTROL_AWB_STATE, &awbState, 1); if (mSocCamFlashCtrUnit.get()) { mSocCamFlashCtrUnit->updateFlashResult(ctrlUnitResult); } else { uint8_t aeMode = ANDROID_CONTROL_AE_MODE_ON; ctrlUnitResult->update(ANDROID_CONTROL_AE_MODE, &aeMode, 1); uint8_t aeState = ANDROID_CONTROL_AE_STATE_CONVERGED; ctrlUnitResult->update(ANDROID_CONTROL_AE_STATE, &aeState, 1); } reqState->mClMetaReceived = true; } return OK; } status_t ControlUnit::handleNewRequestDone(Message &msg) { status_t status = OK; std::shared_ptr<RequestCtrlState> reqState = nullptr; int reqId = msg.requestId; std::map<int, std::shared_ptr<RequestCtrlState>>::iterator it = mWaitingForCapture.find(reqId); if (it == mWaitingForCapture.end()) { LOGE("Unexpected request done event received for request %d - Fix the bug", reqId); return UNKNOWN_ERROR; } reqState = it->second; if (CC_UNLIKELY(reqState.get() == nullptr || reqState->request == nullptr)) { LOGE("No valid state or settings for request Id = %d" "- Fix the bug!", reqId); return UNKNOWN_ERROR; } reqState->mImgProcessDone = true; Camera3Request* request = reqState->request; // when deviceError, should not wait for meta and metadataDone an error index if ((!reqState->mClMetaReceived) && !request->getError()) return OK; request->mCallback->metadataDone(request, request->getError() ? -1 : CONTROL_UNIT_PARTIAL_RESULT); /* * Remove the request from Q once we have received all pixel data buffers * we expect from ISA. Query the graph config for that. */ mWaitingForCapture.erase(reqId); return status; } /** * completeProcessing * * Forward the pixel buffer to the Processing Unit to complete the processing. * If all the buffers from Capture Unit have arrived then: * - it updates the metadata * - it removes the request from the vector mWaitingForCapture. * * The metadata update is now transferred to the ProcessingUnit. * This is done only on arrival of the last pixel data buffer. ControlUnit still * keeps the state, so it is responsible for triggering the update. */ status_t ControlUnit::completeProcessing(std::shared_ptr<RequestCtrlState> &reqState) { HAL_TRACE_CALL(CAM_GLBL_DBG_HIGH); int reqId = reqState->request->getId(); if (CC_LIKELY((reqState->request != nullptr) && (reqState->captureSettings.get() != nullptr))) { /* TODO: cleanup * This struct copy from state is only needed for JPEG creation. * Ideally we should directly write inside members of processingSettings * whatever settings are needed for Processing Unit. * This should be moved to any of the processXXXSettings. */ fillMetadata(reqState); mImguUnit->completeRequest(reqState->processingSettings, true); } else { LOGE("request or captureSetting is nullptr - Fix the bug!"); return UNKNOWN_ERROR; } return NO_ERROR; } status_t ControlUnit::handleNewShutter(Message &msg) { HAL_TRACE_CALL(CAM_GLBL_DBG_HIGH); std::shared_ptr<RequestCtrlState> reqState = nullptr; int reqId = msg.data.shutter.requestId; //check whether this reqId has been shutter done if (reqId <= mShutterDoneReqId) return OK; std::map<int, std::shared_ptr<RequestCtrlState>>::iterator it = mWaitingForCapture.find(reqId); if (it == mWaitingForCapture.end()) { LOGE("Unexpected shutter event received for request %d - Fix the bug", reqId); return UNKNOWN_ERROR; } reqState = it->second; if (CC_UNLIKELY(reqState.get() == nullptr || reqState->captureSettings.get() == nullptr)) { LOGE("No valid state or settings for request Id = %d" "- Fix the bug!", reqId); return UNKNOWN_ERROR; } const CameraMetadata* metaData = reqState->request->getSettings(); if (metaData == nullptr) { LOGE("Metadata should not be nullptr. Fix the bug!"); return UNKNOWN_ERROR; } int jpegBufCount = reqState->request->getBufferCountOfFormat(HAL_PIXEL_FORMAT_BLOB); if (jpegBufCount && (mStillCapSyncState == STILL_CAP_SYNC_STATE_WATING_JPEG_FRAME)) { mStillCapSyncState = STILL_CAP_SYNC_STATE_JPEG_FRAME_DONE; status_t status = OK; const CameraMetadata *settings = reqState->request->getSettings(); rkisp_cl_frame_metadata_s frame_metas; CameraMetadata tempCamMeta = *settings; uint8_t stillCapSyncEnd = RKCAMERA3_PRIVATEDATA_STILLCAP_SYNC_CMD_SYNCEND; tempCamMeta.update(RKCAMERA3_PRIVATEDATA_STILLCAP_SYNC_CMD, &stillCapSyncEnd, 1); mStillCapSyncState = STILL_CAP_SYNC_STATE_TO_ENGINE_IDLE; frame_metas.metas = tempCamMeta.getAndLock(); frame_metas.id = -1; status = mCtrlLoop->setFrameParams(&frame_metas); if (status != OK) LOGE("CtrlLoop setFrameParams error"); /* status = settings->unlock(frame_metas.metas); */ status = tempCamMeta.unlock(frame_metas.metas); if (status != OK) { LOGE("unlock frame frame_metas failed"); return UNKNOWN_ERROR; } LOGD("%s:%d, stillcap_sync_state %d", __FUNCTION__, __LINE__, mStillCapSyncState); } int64_t ts = msg.data.shutter.tv_sec * 1000000000; // seconds to nanoseconds ts += msg.data.shutter.tv_usec * 1000; // microseconds to nanoseconds //# ANDROID_METADATA_Dynamic android.sensor.timestamp done reqState->ctrlUnitResult->update(ANDROID_SENSOR_TIMESTAMP, &ts, 1); reqState->mShutterMetaReceived = true; if(reqState->mClMetaReceived) { mMetadata->writeRestMetadata(*reqState); reqState->request->notifyFinalmetaFilled(); } reqState->request->mCallback->shutterDone(reqState->request, ts); reqState->shutterDone = true; reqState->captureSettings->timestamp = ts; mShutterDoneReqId = reqId; return NO_ERROR; } status_t ControlUnit::flush(int configChanged) { PERFORMANCE_ATRACE_NAME("ControlUnit::flush"); HAL_TRACE_CALL(CAM_GLBL_DBG_HIGH); Message msg; msg.id = MESSAGE_ID_FLUSH; msg.configChanged = configChanged; mMessageQueue.remove(MESSAGE_ID_NEW_REQUEST); mMessageQueue.remove(MESSAGE_ID_NEW_SHUTTER); mMessageQueue.remove(MESSAGE_ID_NEW_REQUEST_DONE); return mMessageQueue.send(&msg, MESSAGE_ID_FLUSH); } status_t ControlUnit::handleMessageFlush(Message &msg) { HAL_TRACE_CALL(CAM_GLBL_DBG_HIGH); status_t status = NO_ERROR; if (CC_UNLIKELY(status != OK)) { LOGE("Failed to stop 3a control loop!"); } mFlushForUseCase = msg.configChanged; if(msg.configChanged && mCtrlLoop && mEnable3A) { if (mStillCapSyncNeeded && mStillCapSyncState != STILL_CAP_SYNC_STATE_TO_ENGINE_PRECAP && mFlushForUseCase == FLUSH_FOR_STILLCAP) { rkisp_cl_frame_metadata_s frame_metas; // force precap uint8_t precap = ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START; mLatestCamMeta.update(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER, &precap, 1); frame_metas.metas = mLatestCamMeta.getAndLock(); frame_metas.id = -1; status = mCtrlLoop->setFrameParams(&frame_metas); if (status != OK) LOGE("CtrlLoop setFrameParams error"); status = mLatestCamMeta.unlock(frame_metas.metas); if (status != OK) { LOGE("unlock frame frame_metas failed"); return UNKNOWN_ERROR; } mStillCapSyncState = STILL_CAP_SYNC_STATE_FORCE_TO_ENGINE_PRECAP; // wait precap 3A done while (mStillCapSyncState != STILL_CAP_SYNC_STATE_FORCE_PRECAP_DONE) { LOGD("%d:wait forceprecap done...", __LINE__); usleep(10*1000); } mStillCapSyncState = STILL_CAP_SYNC_STATE_TO_ENGINE_PRECAP; } mCtrlLoop->stop(); } mImguUnit->flush(); mWaitingForCapture.clear(); mSettingsHistory.clear(); return NO_ERROR; } void ControlUnit::messageThreadLoop() { LOGD("@%s - Start", __FUNCTION__); mThreadRunning = true; while (mThreadRunning) { status_t status = NO_ERROR; PERFORMANCE_ATRACE_BEGIN("CtlU-PollMsg"); Message msg; mMessageQueue.receive(&msg); PERFORMANCE_ATRACE_END(); PERFORMANCE_ATRACE_NAME_SNPRINTF("CtlU-%s", ENUM2STR(CtlUMsg_stringEnum, msg.id)); PERFORMANCE_HAL_ATRACE_PARAM1("msg", msg.id); LOGD("@%s, receive message id:%d", __FUNCTION__, msg.id); switch (msg.id) { case MESSAGE_ID_EXIT: status = handleMessageExit(); break; case MESSAGE_ID_NEW_REQUEST: status = handleNewRequest(msg); break; case MESSAGE_ID_NEW_SHUTTER: status = handleNewShutter(msg); break; case MESSAGE_ID_NEW_REQUEST_DONE: status = handleNewRequestDone(msg); break; case MESSAGE_ID_METADATA_RECEIVED: status = handleMetadataReceived(msg); break; case MESSAGE_ID_FLUSH: status = handleMessageFlush(msg); break; default: LOGE("ERROR Unknown message %d", msg.id); status = BAD_VALUE; break; } if (status != NO_ERROR) LOGE("error %d in handling message: %d", status, static_cast<int>(msg.id)); LOGD("@%s, finish message id:%d", __FUNCTION__, msg.id); mMessageQueue.reply(msg.id, status); PERFORMANCE_ATRACE_END(); } LOGD("%s: Exit", __FUNCTION__); } bool ControlUnit::notifyCaptureEvent(CaptureMessage *captureMsg) { HAL_TRACE_CALL(CAM_GLBL_DBG_HIGH); if (captureMsg == nullptr) { return false; } if (captureMsg->id == CAPTURE_MESSAGE_ID_ERROR) { // handle capture error return true; } Message msg; switch (captureMsg->data.event.type) { case CAPTURE_EVENT_SHUTTER: msg.id = MESSAGE_ID_NEW_SHUTTER; msg.data.shutter.requestId = captureMsg->data.event.reqId; msg.data.shutter.tv_sec = captureMsg->data.event.timestamp.tv_sec; msg.data.shutter.tv_usec = captureMsg->data.event.timestamp.tv_usec; mMessageQueue.send(&msg, MESSAGE_ID_NEW_SHUTTER); break; case CAPTURE_EVENT_NEW_SOF: mSofSequence = captureMsg->data.event.sequence; LOGD("sof event sequence = %u", mSofSequence); break; case CAPTURE_REQUEST_DONE: msg.id = MESSAGE_ID_NEW_REQUEST_DONE; msg.requestId = captureMsg->data.event.reqId; mMessageQueue.send(&msg, MESSAGE_ID_NEW_REQUEST_DONE); break; default: LOGW("Unsupported Capture event "); break; } return true; } status_t ControlUnit::metadataReceived(int id, const camera_metadata_t *metas) { Message msg; status_t status = NO_ERROR; camera_metadata_entry entry; static std::map<int,uint8_t> sLastAeStateMap; CameraMetadata result(const_cast<camera_metadata_t*>(metas)); entry = result.find(RKCAMERA3_PRIVATEDATA_STILLCAP_SYNC_NEEDED); if (entry.count == 1) { mStillCapSyncNeeded = !!entry.data.u8[0]; } entry = result.find(RKCAMERA3_PRIVATEDATA_STILLCAP_SYNC_CMD); if (entry.count == 1) { if (entry.data.u8[0] == RKCAMERA3_PRIVATEDATA_STILLCAP_SYNC_CMD_SYNCDONE && (mStillCapSyncState == STILL_CAP_SYNC_STATE_WAITING_ENGINE_DONE || mFlushForUseCase == FLUSH_FOR_STILLCAP)) mStillCapSyncState = STILL_CAP_SYNC_STATE_FROM_ENGINE_DONE; LOGD("%s:%d, stillcap_sync_state %d", __FUNCTION__, __LINE__, mStillCapSyncState); } entry = result.find(ANDROID_CONTROL_AE_STATE); if (entry.count == 1) { if (id == -1 && entry.data.u8[0] == ANDROID_CONTROL_AE_STATE_CONVERGED && mStillCapSyncState == STILL_CAP_SYNC_STATE_FORCE_TO_ENGINE_PRECAP && sLastAeStateMap[mCameraId] == ANDROID_CONTROL_AE_STATE_PRECAPTURE) { mStillCapSyncState = STILL_CAP_SYNC_STATE_FORCE_PRECAP_DONE; sLastAeStateMap[mCameraId] = 0; LOGD("%s:%d, stillcap_sync_state %d", __FUNCTION__, __LINE__, mStillCapSyncState); } sLastAeStateMap[mCameraId] = entry.data.u8[0]; } result.release(); if (id != -1) { msg.id = MESSAGE_ID_METADATA_RECEIVED; msg.requestId = id; msg.metas = metas; status = mMessageQueue.send(&msg); } return status; } status_t ControlUnit::handleMetadataReceived(Message &msg) { status_t status = OK; std::shared_ptr<RequestCtrlState> reqState = nullptr; int reqId = msg.requestId; std::map<int, std::shared_ptr<RequestCtrlState>>::iterator it = mWaitingForCapture.find(reqId); if(reqId == -1) return OK; if (it == mWaitingForCapture.end()) { LOGE("Unexpected request done event received for request %d - Fix the bug", reqId); return UNKNOWN_ERROR; } reqState = it->second; if (CC_UNLIKELY(reqState.get() == nullptr || reqState->request == nullptr)) { LOGE("No valid state or request for request Id = %d" "- Fix the bug!", reqId); return UNKNOWN_ERROR; } mLatestCamMeta = msg.metas; //Metadata reuslt are mainly divided into three parts //1. some settings from app //2. 3A metas from Control loop //3. some items like sensor timestamp from shutter reqState->ctrlUnitResult->append(msg.metas); reqState->mClMetaReceived = true; if(reqState->mShutterMetaReceived) { mMetadata->writeRestMetadata(*reqState); reqState->request->notifyFinalmetaFilled(); } if (!reqState->mImgProcessDone) return OK; Camera3Request* request = reqState->request; request->mCallback->metadataDone(request, request->getError() ? -1 : CONTROL_UNIT_PARTIAL_RESULT); mWaitingForCapture.erase(reqId); return status; } /** * Static callback forwarding methods from CL to instance */ void ControlUnit::sMetadatCb(const struct cl_result_callback_ops* ops, struct rkisp_cl_frame_metadata_s *result) { LOGI("@%s %d: frame %d result meta received", __FUNCTION__, __LINE__, result->id); TuningServer *pserver = TuningServer::GetInstance(); ControlUnit *ctl = const_cast<ControlUnit*>(static_cast<const ControlUnit*>(ops)); ctl->metadataReceived(result->id, result->metas); if(pserver && pserver->isTuningMode()){ CameraMetadata uvcCamMeta(const_cast<camera_metadata_t*>(result->metas)); pserver->get_tuning_params(uvcCamMeta); uvcCamMeta.release(); } } } // namespace camera2 } // namespace android
36.024716
113
0.651004
[ "object", "vector" ]
a9d77e79bd2e0cdb26044f1bd90d24498d9c99f8
14,091
cpp
C++
Sources/Scene.cpp
Leo-Besancon/RayTracer
4603d9abf95f36bfd58f18184e63a1d994049686
[ "MIT" ]
null
null
null
Sources/Scene.cpp
Leo-Besancon/RayTracer
4603d9abf95f36bfd58f18184e63a1d994049686
[ "MIT" ]
null
null
null
Sources/Scene.cpp
Leo-Besancon/RayTracer
4603d9abf95f36bfd58f18184e63a1d994049686
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Scene.h" Scene::~Scene() { // Delete Lights for (int i = 0; i < _lights.size(); i++) { if (_lights[i] != nullptr) delete _lights[i]; } _lights.clear(); // Delete Objects for (int i = 0; i < _objects.size(); i++) { if (_objects[i] != nullptr) delete _objects[i]; } _objects.clear(); } std::tuple<Vector*, Vector*, IObject*, Vector> Scene::computeIntersection(Ray r, double time) const { IObject* current_Object = nullptr; Vector* intersection = nullptr; Vector* current_n = nullptr; Vector current_color; double current_t = std::numeric_limits<double>::max(); for (int k = 0; k < _objects.size(); k++) { IObject* o = _objects[k]; r.reverse_animations(o->get_animations(), time); std::tuple<double, Vector*, Vector> tuple = o->intersection(r); r.apply_animations(o->get_animations(), time); double t = std::get<0>(tuple); Vector* n = std::get<1>(tuple); Vector color = std::get<2>(tuple); if (t != -1 && t < current_t) { current_t = t; current_Object = o; current_color = color; if (current_n != nullptr) { delete current_n; } current_n = n; } else { if (n != nullptr) { delete n; } } } if (current_Object != nullptr) { r.reverse_animations(current_Object->get_animations(), time); intersection = new Vector(r.getPoint(current_t)); r.apply_animations(current_Object->get_animations(), time); Ray r2 = Ray(*intersection, *current_n); r2.apply_animations(current_Object->get_animations(), time); *intersection = r2.get_center(); *current_n = r2.get_dir(); } return std::tuple<Vector*, Vector*, IObject*, Vector>(intersection, current_n, current_Object, current_color); } double Scene::computeFresnel(Ray r, double n_air, double n_object, Vector* n) const { double k0, R, T; Vector i; k0 = pow((n_air - n_object) / (n_air + n_object), 2.); if (r.get_dir().scalar(*n) < 0) { i = r.get_dir() * (-1); } else { Vector n2 = *n * (-1); i = r.get_dir() * (n_object / n_air) - n2 * (n_object / n_air * r.get_dir().scalar(n2) + sqrt(1 - n_object * n_object / (n_air * n_air) * (1 - r.get_dir().scalar(n2) * r.get_dir().scalar(n2)))); } i.normalize(); R = k0 + (1.0 - k0) * pow((1 - i.scalar(*n)), 5.); T = 1. - R; return T; } bool Scene::computeShadows(Vector nudged, Vector center, double time) const { bool b = false; #ifdef SHADOWS Vector dir = center - nudged; Ray r = Ray(nudged, dir); r.normalize(); std::tuple<Vector*, Vector*, IObject*, Vector> tuple = computeIntersection(r, time); Vector* intersection2 = std::get<0>(tuple); Vector* n2 = std::get<1>(tuple); if (intersection2 != nullptr) { Vector dir2 = *intersection2 - nudged; if (dir2.get_norm2() + _epsilon < dir.get_norm2()) { b = true; } } delete n2; delete intersection2; #endif return b; } Vector Scene::computeIntensityMirror(Ray r, Vector* intersection, IObject* o, Vector* n, Vector color, int nombre_rebonds, double time, bool showEmissiveSurfaces, bool fromTransparent) const { Vector intensity = Vector(0., 0., 0.); if (o->get_material()._mirror || fromTransparent) { Vector nudged2 = *intersection + *n * _epsilon; Vector dir2 = r.get_dir() - (*n * 2 * r.get_dir().scalar(*n)); Ray r2 = Ray(nudged2, dir2); std::tuple<Vector*, Vector*, IObject*, Vector> tuple2 = computeIntersection(r2, time); Vector* intersection2 = std::get<0>(tuple2); Vector* n2 = std::get<1>(tuple2); IObject* o2 = std::get<2>(tuple2); Vector color2 = std::get<3>(tuple2); if (intersection2 != nullptr) { #ifdef RUSSIAN_ROULETTE double rand = distrib(engine); if (rand < 0.9) intensity = computeIntensity(r2, intersection2, o2, n2, color2, nombre_rebonds - 1, time) * o->get_material()._specular_color / 0.9; #else intensity = computeIntensity(r2, intersection2, o2, n2, color2, nombre_rebonds - 1, time) * o->get_material()._specular_color; #endif } delete n2; delete intersection2; } return intensity; } Vector Scene::computeIntensityTransparent(Ray r, Vector* intersection, IObject* o, Vector* n, Vector color, int nombre_rebonds, double time, bool showEmissiveSurfaces) const { Vector intensity = Vector(0, 0, 0); if (o->get_material()._transparent) { double n_object = o->get_material()._n_object; double T = 1.0; double rand = distrib(engine); #ifdef FRESNEL T = computeFresnel(r, _n_air, n_object, n); #endif if (rand < T) { double n_1 = _n_air; double n_2 = n_object; Vector* normal = n; if (r.get_dir().scalar(*n) >= 0) { n_1 = n_object; n_2 = _n_air; *normal = *normal * (-1.); } if (1 - n_1 * n_1 / (n_2 * n_2) * (1 - r.get_dir().scalar(*n) * r.get_dir().scalar(*n)) >= 0) { Vector* intersection2 = nullptr; Vector* n2 = nullptr; IObject* o2 = nullptr; Vector color2; Ray r2; Vector dir2 = r.get_dir() * (n_1 / n_2) - *normal * (n_1 / n_2 * r.get_dir().scalar(*normal) + sqrt(1 - n_1 * n_1 / (n_2 * n_2) * (1 - r.get_dir().scalar(*normal) * r.get_dir().scalar(*normal)))); Vector nudged2 = *intersection - *normal * _epsilon; r2 = Ray(nudged2, dir2); std::tuple<Vector*, Vector*, IObject*, Vector> tuple3 = computeIntersection(r2, time); intersection2 = std::get<0>(tuple3); n2 = std::get<1>(tuple3); o2 = std::get<2>(tuple3); color2 = std::get<3>(tuple3); if (intersection2 != nullptr) { #ifdef RUSSIAN_ROULETTE double rand2 = distrib(engine); if (rand2 < 0.9) intensity = computeIntensity(r2, intersection2, o2, n2, color2, nombre_rebonds - 1, time, showEmissiveSurfaces) / 0.9; #else intensity = computeIntensity(r2, intersection2, o2, n2, color2, nombre_rebonds - 1, time, showEmissiveSurfaces); #endif } delete n2; delete intersection2; } else { #ifdef RUSSIAN_ROULETTE double rand2 = distrib(engine); double proba = 0.9; if (rand2 < proba) intensity = computeIntensityMirror(r, intersection, o, n, color, nombre_rebonds - 1, time, showEmissiveSurfaces, true) / 0.9; #else intensity = computeIntensityMirror(r, intersection, o, n, color, nombre_rebonds - 1, time, showEmissiveSurfaces, true); #endif } } else { #ifdef RUSSIAN_ROULETTE double rand = distrib(engine); double proba = 0.9; if (rand < proba) intensity = computeIntensityMirror(r, intersection, o, n, color, nombre_rebonds - 1, time, showEmissiveSurfaces, true) / 0.9; #else intensity = computeIntensityMirror(r, intersection, o, n, color, nombre_rebonds - 1, time, showEmissiveSurfaces, true); #endif } } return intensity; } Vector Scene::computeIntensityIndirect(Ray r, Vector * intersection, IObject * o, Vector * n, Vector color, int nombre_rebonds, double time, bool showEmissiveSurfaces) const { Vector intensity = Vector(0., 0., 0.); #ifdef INDIRECT_LIGHT Vector* intersection2 = nullptr; Vector* n2 = nullptr; IObject* o2 = nullptr; Vector color2; Vector nudged2 = *intersection + *n * _epsilon; Ray r2; double p = o->get_material()._phong ? 0.5 : 1.; Vector reflected = r.get_dir() - (*n * 2 * r.get_dir().scalar(*n)); double exponent = o->get_material()._phong_exponent; double rand = distrib(engine); if (o->get_material()._phong == true && rand > p) { r2 = Ray::getRandRayPhong(*intersection, reflected, exponent); if (r2.get_dir().scalar(*n) <= 0.) return Vector(0., 0., 0.); if (r2.get_dir().scalar(reflected) <= 0.) return Vector(0., 0., 0.); } else { r2 = Ray::getRandRay(nudged2, *n); } std::tuple<Vector*, Vector*, IObject*, Vector> tuple2 = computeIntersection(r2, time); intersection2 = std::get<0>(tuple2); n2 = std::get<1>(tuple2); o2 = std::get<2>(tuple2); color2 = std::get<3>(tuple2); Vector indirect_intensity = Vector(0, 0, 0); if (intersection2 != nullptr) { #ifdef RUSSIAN_ROULETTE double rand2 = distrib(engine); double proba = (color.get_x() + color.get_y() + color.get_z()) / 3.5; if (rand2 < proba) indirect_intensity = computeIntensity(r2, intersection2, o2, n2, color2, nombre_rebonds - 1, time, false) / proba; #else indirect_intensity = computeIntensity(r2, intersection2, o2, n2, color2, nombre_rebonds - 1, time, false); #endif double proba_phong = (exponent + 1.) * std::pow((r2.get_dir().scalar(reflected)), exponent); double proba_diffuse = n->scalar(r2.get_dir()); double proba = p * proba_diffuse + (1. - p) * proba_phong; if (o->get_material()._phong == true && rand > p) intensity += indirect_intensity * n->scalar(r2.get_dir()) * (exponent + 2.) * std::pow((r2.get_dir().scalar(reflected)), exponent) * o->get_material()._specular_color / (2. * M_PI) / proba; else intensity += indirect_intensity * n->scalar(r2.get_dir()) * color / (2. * M_PI) / proba; } delete n2; delete intersection2; #endif return intensity; } Vector Scene::computeIntensityEmissive(Ray r, Vector * intersection, IObject * o, Vector * n, Vector color, int nombre_rebonds, double time, bool showEmissiveSurfaces) const { Vector intensity = Vector(0., 0., 0.); #ifdef EMISSIVE_LIGHT if (o->get_material()._emissive && showEmissiveSurfaces) { intensity += o->get_material()._color * o->get_material()._emissivity; } #endif return intensity; } Vector Scene::computeIntensityDirect(Ray r, Vector * intersection, IObject * o, Vector * n, Vector color, int nombre_rebonds, double time, bool showEmissiveSurfaces) const { Vector intensity = Vector(0., 0., 0.); #ifdef DIRECT_LIGHT Ray r2; // We aim one of the emissive object (with chances proportional to total light intensity of the object) double rand = distrib(engine); double sum = 0; std::vector<double> proba; for (int i = 0; i < _lights_objects.size(); i++) { proba.push_back(_lights_objects[i]->get_material()._emissivity / _lights_objects[i]->get_surfaceArea()); sum += proba[i]; } for (int i = 0; i < _lights_objects.size(); i++) { if (rand*sum <= proba[i]) { // We get a random direction (giving us a point on the Sphere) IAnimatable* light_object_i = _lights_objects[i]; Vector light_center = light_object_i->get_center(); Vector dir_center_light = (*intersection - light_center).normalize(); r2 = Ray::getRandRayAngleUniform(light_center, _lights_objects[i]->get_surfaceArea(), dir_center_light); Vector randResultPoint = r2.get_center(); Vector randResultDir = r2.get_dir().normalize(); Vector randResultDirtoIntersection = (*intersection - randResultPoint).normalize(); double d = (*intersection - randResultPoint).get_norm2(); Vector nudged = *intersection + *n * _epsilon; if (computeShadows(nudged, randResultPoint, time) == false) { if (o->get_material()._phong == true) { Vector reflected = r.get_dir() - (*n * 2 * r.get_dir().scalar(*n)); double exponent = o->get_material()._phong_exponent; double Phong = pow(reflected.scalar(randResultDirtoIntersection), exponent)*(exponent + 2.) / (2.*M_PI); Vector color_phonged = (color + o->get_material()._specular_color * (Phong - 1)); /*if(n->scalar(randResultDirtoIntersection * (-1)) <= 0.) std::cout << "" << n->scalar(randResultDirtoIntersection * (-1)) << std::endl;*/ intensity = _lights_objects[i]->get_material()._color * std::max(0., n->scalar(randResultDirtoIntersection * (-1))) * _lights_objects[i]->get_material()._emissivity * _lights_objects[i]->get_surfaceArea() * std::max(0., randResultDir.scalar(randResultDirtoIntersection)) * color_phonged / (std::max(0., (dir_center_light.scalar(randResultDir))) * d * 4 * M_PI); } else { intensity = _lights_objects[i]->get_material()._color * std::max(0., n->scalar(randResultDirtoIntersection * (-1))) * _lights_objects[i]->get_material()._emissivity * _lights_objects[i]->get_surfaceArea() * std::max(0., randResultDir.scalar(randResultDirtoIntersection)) * color / (std::max(0., (dir_center_light.scalar(randResultDir))) * d * 4 * M_PI); } } break; } } #endif return intensity; } Vector Scene::computeIntensityPointLight(Ray r, Vector * intersection, IObject * o, Vector * n, Vector color, int nombre_rebonds, double time, bool showEmissiveSurfaces) const { Vector intensity = Vector(0., 0., 0.); #ifdef POINT_LIGHT for (int k = 0; k < _lights.size(); k++) { Light* light = _lights[k]; double d = (*intersection - light->get_center(time)).get_norm2(); Vector l = (light->get_center(time) - *intersection).normalize(); Vector nudged = *intersection + *n * _epsilon; if (computeShadows(nudged, light->get_center(time), time) == false) { #ifdef INTENSITY intensity += light->get_intensity() * color * std::max(0., l.scalar(*n)) / (d * M_PI); #else intensity += light->get_intensity() * _color / d; #endif } } #endif return intensity; } Vector Scene::computeIntensity(Ray r, Vector* intersection, IObject* o, Vector* n, Vector color, int nombre_rebonds, double time, bool showEmissiveSurfaces) const { Vector intensity = Vector(0.,0.,0.); #ifndef RUSSIAN_ROULETTE if (nombre_rebonds == 0) return Vector(0, 0, 0); #endif Vector intensity_mirror = computeIntensityMirror(r, intersection, o, n, color, nombre_rebonds, time, showEmissiveSurfaces).max(0.); Vector intensity_transparent = computeIntensityTransparent(r, intersection, o, n, color, nombre_rebonds, time, showEmissiveSurfaces).max(0.); Vector intensity_indirect = computeIntensityIndirect(r, intersection, o, n, color, nombre_rebonds, time, showEmissiveSurfaces).max(0.); Vector intensity_direct = computeIntensityDirect(r, intersection, o, n, color, nombre_rebonds, time, showEmissiveSurfaces).max(0.); Vector intensity_emissive = computeIntensityEmissive(r, intersection, o, n, color, nombre_rebonds, time, showEmissiveSurfaces).max(0.); Vector intensity_point_light = computeIntensityPointLight(r, intersection, o, n, color, nombre_rebonds, time, showEmissiveSurfaces).max(0.); intensity = intensity_mirror + intensity_transparent + intensity_indirect + intensity_direct + intensity_emissive + intensity_point_light; return intensity; }
30.434125
200
0.674757
[ "object", "vector" ]
a9dbb69c776738bad6f5a41d7221b039cd7cfbd2
9,882
cpp
C++
fileInit.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
fileInit.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
fileInit.cpp
neelsoumya/cycells
a3a6e632addf0a91c75c0a579ad0d41ad9d7a089
[ "Naumen", "Condor-1.1", "MS-PL" ]
3
2018-06-20T21:55:11.000Z
2020-10-21T19:04:54.000Z
/************************************************************************ * * * Copyright (C) 2004 Christina Warrender * * * * This file is part of CyCells. * * * * CyCells 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. * * * * CyCells 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 CyCells; if not, write to the Free Software Foundation, * * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * * ************************************************************************/ /************************************************************************ * file fileInit.cc * * Routines for reading model initialization from file * ************************************************************************/ #include "fileInit.h" #include <iostream> #include <stdio.h> #include <string.h> #include "tissue.h" #include "random.h" #include "util.h" using namespace std; #define REVNO 4 /************************************************************************ * initFromFile() * * Reads model initialization data from specified input file. * * * * Parameters * * * * Returns - nothing * ************************************************************************/ void FileInit::initFromFile(Tissue *pt, const char *filename) { // open file ifstream infile(filename); if (!infile) error("FileInit: could not open file", filename); char buff[20]; // for input strings int num; // for input values Cells *pcs = pt->getCellsPtr(); // for access to Cells routines // check file format; should read: #InitFormat REVNO infile >> buff; if (strcmp(buff, "#InitFormat") != 0) error("FileInit: expected first line to read #InitFormat n"); infile >> num; if (num != REVNO) error("FileInit: expected format", REVNO); // loop through file to find initialization keywords while (!infile.eof()) { infile >> ws; // skip leading whitespace infile >> buff; // read keyword if (strcmp( buff, "geometry") == 0) readGeometry(pt, infile); else if (strcmp( buff, "timestamp:") == 0) { double value; infile >> value; pt->setTime(value); cout << "set time to " << value << endl; } else if (strcmp( buff, "seed:") == 0) { long int value; infile >> value; pt->setSeed(value); cout << "set seed to " << value << endl; } else if (strcmp( buff, "molecule_uniform:") == 0) { infile >> buff; Molecule *pm = pt->getMolecule(buff); if (!pm) error("FileInit: can't find molecule type", buff); Molecule::Conc value; double stddev; infile >> value >> stddev; pm->setUniformConc(value, stddev); } else if (strcmp( buff, "molecule_reset:") == 0) { infile >> buff; double interval; Molecule::Conc value; double stddev; infile >> interval >> value >> stddev; pt->setMolReset(buff, interval, value, stddev); } else if (strcmp( buff, "molecule_detail:") == 0) { infile >> buff; Molecule *pm = pt->getMolecule(buff); if (!pm) error("FileInit: can't find molecule type", buff); pm->initFromFile(infile); } else if (strcmp( buff, "cell_detail:") == 0) { pcs->initFromFile(infile); } else if (strcmp( buff, "cell_list:") == 0) // read individual cell info - not organized by type readCells(pt, infile); else if (strcmp( buff, "cell_sheet:") == 0) { double zpos; infile >> buff >> zpos; // type name, zpos pcs->addSheet(buff, zpos); cout << "added sheet at z = " << zpos << endl; } else if (strcmp( buff, "cell_hexsheet:") == 0) { double zpos; infile >> buff >> zpos ; // type name, zpos pcs->addHexSheet(buff, zpos); cout << "added hex sheet at z = " << zpos << endl; } else if (strcmp( buff, "cell_hexmix:") == 0) { // type1 type2 perc1 zpos char buff2[20]; double perc, zpos; infile >> buff >> buff2 >> perc >> zpos ; pcs->addHexMix(buff, buff2, perc, zpos); cout << "added hex mix at z = " << zpos << endl; } else if (strcmp( buff, "cell_hexmix_index:") == 0) { // type1 type2 perc1 zpos char buff2[20]; double perc, zpos; infile >> buff >> buff2 >> perc >> zpos ; pcs->addHexMixIndex(buff, buff2, perc, zpos); cout << "added hex mix at z = " << zpos << endl; } else if (strcmp( buff, "cell_grid:") == 0) { int size; infile >> buff >> size; pcs->addGrid(buff, size); cout << "added grid of size " << size << endl; } else if (strcmp( buff, "cell_mixed_grid:") == 0) { int size; char buff2[20]; infile >> buff >> buff2 >> size; pcs->addMixedGrid(buff, buff2, size); cout << "added mixed grid of size " << size << endl; } else if (strcmp( buff, "cell_grid2D:") == 0) { int size; double zpos; infile >> buff >> size >> zpos; pcs->addGrid2D(buff, size, zpos); cout << "added 2D grid of size " << size << " at z = " << zpos << endl; } else if (strcmp( buff, "cell_count:") == 0) { infile >> buff >> num; // type name and number of cells pcs->addRandomly(buff, num); cout << "added " << num << " " << buff << " cells" << endl; } else if (strcmp( buff, "cell_count2D:") == 0) { double zpos; infile >> buff >> num >> zpos; // type name, number and z position pcs->addRandomly2D(buff, num, zpos); cout << "added " << num << " " << buff << " cells" << endl; } else // unknown type error("FileInit: unknown keyword", buff); infile >> ws; // skip whitespace } // end loop through file pcs->initialize(); // close file infile.close(); } /************************************************************************ * readCells() * * Reads list of individual cells from already-open file; calls * * Tissue object to add them to model * * * * Parameters * * ifstream &infile: open file containing data * * * * Returns - nothing * ************************************************************************/ void FileInit::readCells(Tissue *pt, ifstream &infile) { char buff[20]; int i, count; double x, y, z; // for reading cell position Cells *pcs = pt->getCellsPtr(); // read and store number of cells infile >> count; // use temp variable because // addCell updates num_new_cells // and mergeNew updates num_cells cout << "read number of cells = " << count << endl; for (i=0; i<count; i++) { // read info as written in writeDefinition infile >> buff; // type name infile >> x; infile >> y; infile >> z; cout << "read: " << buff << " at " << x << " " << y << " " << z << endl; pcs->addCell(buff, SimPoint(x,y,z), false); } } /************************************************************************ * readGeometry() * * Reads geometry definition from already-open file; calls Tissue * * object to set geometry * * * * Parameters * * Tissue *pt: points to Tissue to be initialized * * ifstream &infile: open file containing data * * * * Returns - nothing * ************************************************************************/ void FileInit::readGeometry(Tissue *pt, ifstream &s) { // read size info char ch; int xsize, ysize, zsize, molgridsize, cellgridsize; // all sizes in microns s >> xsize; s >> ch; if (ch != 'x') error("FileInit: missing 'x' in geometry description"); s >> ysize; s >> ch; if (ch != 'x') error("FileInit: missing 'x' in geometry description"); s >> zsize; char buff[20]; s >> buff; // "microns" if (strcmp(buff, "microns;") != 0) error("FileInit: missing 'microns;' in geometry description"); s >> buff; // "mol_res:" if (strcmp(buff, "mol_res:") != 0) error("FileInit: missing 'mol_res:' in geometry description"); s >> molgridsize; s >> buff; // "cell_res:" if (strcmp(buff, "cell_res:") != 0) error("FileInit: missing 'cell_res:' in geometry description"); s >> cellgridsize; // Tissue routine will make sure all internal geometry refs are consistent pt->setGeometry(xsize, ysize, zsize, molgridsize, cellgridsize); }
33.612245
77
0.478344
[ "geometry", "object", "model" ]
a9e31483c05e8cf73a12d80818229f860f8fd562
1,914
cc
C++
leetcode/14_longest_common_prefix.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
leetcode/14_longest_common_prefix.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
leetcode/14_longest_common_prefix.cc
norlanliu/algorithm
1684db2631f259b4de567164b3ee866351e5b1b6
[ "MIT" ]
null
null
null
/* * ===================================================================================== * * Filename: 14_longest_common_prefix.cc * * Description: * * Version: 1.0 * Created: 03/10/2015 08:33:20 AM * Revision: none * Compiler: gcc * * Author: (Qi Liu), liuqi.edward@gmail.com * Organization: antq.com * * ===================================================================================== */ #include<climits> #include<iostream> #include<string> #include<vector> using namespace std; class Solution{ public: string longestCommonPrefix_old(vector<string> &strs){ string ans; char character; unsigned int i, min_length; min_length = strs.size() == 0 ? 0 : INT_MAX; for(auto str : strs){ if(str.length() < min_length) min_length = str.length(); } for(i = 0; i < min_length; ++i) { character = strs[0][i]; for(auto str : strs){ if(str[i] != character) return ans; } ans += character; } return ans; } string longestCommonPrefix(vector<string> &strs){ if(strs.size() == 0) return ""; string tmp; bool result; int left, right, middle; unsigned int min_length; min_length = INT_MAX; for(auto str : strs){ if(str.length() < min_length) min_length = str.length(); } left = 0; right = min_length - 1; while(left <= right){ result = true; middle = (left + right) / 2; tmp = strs[0].substr(left, middle - left + 1); for(auto str : strs){ if(tmp.compare(str.substr(left, middle - left + 1)) != 0) { result = false; break; } } if(result) left = middle + 1; else right = middle - 1; } return strs[0].substr(0, left); } }; int main() { vector<string> strs = {"floor"}; Solution sln; string ans = sln.longestCommonPrefix(strs); cout<<ans<<endl; return 0; }
21.75
88
0.519331
[ "vector" ]
a9e953ca1318618e12a155531bfc72e9dc966a16
7,311
cpp
C++
src/plugins/tiling/rule.cpp
janderland/chunkwm
1af190cc0f3f43fee271e147a5e7a8242734c945
[ "MIT" ]
null
null
null
src/plugins/tiling/rule.cpp
janderland/chunkwm
1af190cc0f3f43fee271e147a5e7a8242734c945
[ "MIT" ]
null
null
null
src/plugins/tiling/rule.cpp
janderland/chunkwm
1af190cc0f3f43fee271e147a5e7a8242734c945
[ "MIT" ]
null
null
null
#include "rule.h" #include "controller.h" #include "misc.h" #include "../../common/misc/assert.h" #include "../../common/accessibility/display.h" #include "../../common/accessibility/window.h" #include "../../common/accessibility/application.h" #include "../../common/misc/assert.h" #include <stdlib.h> #include <string.h> #include <regex.h> #include <vector> #include <map> #define internal static typedef std::map<uint32_t, macos_window *> macos_window_map; typedef macos_window_map::iterator macos_window_map_it; extern macos_window_map CopyWindowCache(); extern void TileWindow(macos_window *Window); internal std::vector<window_rule *> WindowRules; internal inline bool RegexMatchPattern(regex_t *Regex, const char *Match, const char *Pattern) { int Error = regcomp(Regex, Pattern, REG_EXTENDED); if (!Error) { Error = regexec(Regex, Match, 0, NULL, 0); regfree(Regex); } else { c_log(C_LOG_LEVEL_WARN, "chunkwm-tiling: window rule - could not compile regex!\n"); } return Error == 0; } internal inline void ApplyWindowRuleState(macos_window *Window, window_rule *Rule) { if (StringEquals(Rule->State, "float")) { if (!AXLibHasFlags(Window, Window_Float)) { UntileWindow(Window); FloatWindow(Window); } } else if (StringEquals(Rule->State, "sticky")) { ExtendedDockSetWindowSticky(Window, 1); AXLibAddFlags(Window, Window_Sticky); if (!AXLibHasFlags(Window, Window_Float)) { UntileWindow(Window); FloatWindow(Window); } } else if (StringEquals(Rule->State, "tile")) { if (!AXLibHasFlags(Window, Window_ForceTile)) { UnfloatWindow(Window); AXLibAddFlags(Window, Window_ForceTile); if (!AXLibHasFlags(Window, Window_Minimized)) { macos_space *Space; bool Success = AXLibActiveSpace(&Space); ASSERT(Success); if (AXLibSpaceHasWindow(Space->Id, Window->Id)) { TileWindow(Window); AXLibAddFlags(Window, Rule_State_Tiled); } AXLibDestroySpace(Space); } } } else if (StringEquals(Rule->State, "native-fullscreen")) { if (!AXLibIsWindowFullscreen(Window->Ref)) { AXLibSetWindowFullscreen(Window->Ref, true); AXLibAddFlags(Window, Rule_Desktop_Changed); } } else { c_log(C_LOG_LEVEL_WARN, "chunkwm-tiling: window rule - invalid state '%s', ignored..\n", Rule->State); } } internal inline void ApplyWindowRuleDesktop(macos_window *Window, window_rule *Rule) { if (SendWindowToDesktop(Window, Rule->Desktop)) { AXLibAddFlags(Window, Rule_Desktop_Changed); if (Rule->FollowDesktop) { FocusDesktop(Rule->Desktop); AXLibSetFocusedWindow(Window->Ref); AXLibSetFocusedApplication(Window->Owner->PSN); } } } internal inline void ApplyWindowRuleMonitor(macos_window *Window, window_rule *Rule) { if (SendWindowToMonitor(Window, Rule->Monitor)) { AXLibAddFlags(Window, Rule_Desktop_Changed); if (Rule->FollowDesktop) { FocusMonitor(Rule->Monitor); AXLibSetFocusedWindow(Window->Ref); AXLibSetFocusedApplication(Window->Owner->PSN); } } } internal inline void ApplyWindowRuleLevel(macos_window *Window, window_rule *Rule) { int LevelKey; if (sscanf(Rule->Level, "%d", &LevelKey) == 1) { ExtendedDockSetWindowLevel(Window, LevelKey); } } internal inline void ApplyWindowRuleAlpha(macos_window *Window, window_rule *Rule) { float Alpha; if (sscanf(Rule->Alpha, "%f", &Alpha) == 1) { ExtendedDockSetWindowAlpha(Window->Id, Alpha); AXLibAddFlags(Window, Rule_Alpha_Changed); } } internal inline void ApplyWindowRuleGridLayout(macos_window *Window, window_rule *Rule) { GridLayout(Window, Rule->GridLayout); } internal inline void ApplyWindowRule(macos_window *Window, window_rule *Rule) { regex_t Regex; bool Match = true; if (Rule->Owner && Window->Owner->Name) { Match = RegexMatchPattern(&Regex, Window->Owner->Name, Rule->Owner); if (!Match) return; } if (Rule->Name && Window->Name) { Match &= RegexMatchPattern(&Regex, Window->Name, Rule->Name); if (!Match) return; } if (Rule->Role && Window->Mainrole) { Match &= CFEqual(Rule->Role, Window->Mainrole); if (!Match) return; } if (Rule->Subrole && Window->Subrole) { Match &= CFEqual(Rule->Subrole, Window->Subrole); if (!Match) return; } if (Rule->Except && Window->Name) { Match &= !RegexMatchPattern(&Regex, Window->Name, Rule->Except); if (!Match) return; } if (Rule->MaxHeight) { double MaxH = atof(Rule->MaxHeight); Match &= (MaxH > 0) && (MaxH > (double)(Window->Size.height)); if (!Match) return; } if (Rule->MaxWidth) { double MaxW = atof(Rule->MaxWidth); Match &= (MaxW > 0) && (MaxW > (double)(Window->Size.width)); if (!Match) return; } if (Rule->Desktop) ApplyWindowRuleDesktop(Window, Rule); if (Rule->Monitor) ApplyWindowRuleMonitor(Window, Rule); if (Rule->State) ApplyWindowRuleState(Window, Rule); if (Rule->Level) ApplyWindowRuleLevel(Window, Rule); if (Rule->Alpha) ApplyWindowRuleAlpha(Window, Rule); if (Rule->GridLayout) ApplyWindowRuleGridLayout(Window, Rule); } void ApplyRulesForWindow(macos_window *Window) { for (size_t Index = 0; Index < WindowRules.size(); ++Index) { window_rule *Rule = WindowRules[Index]; ApplyWindowRule(Window, Rule); } } void ApplyRulesForWindowOnTitleChanged(macos_window *Window) { for (size_t Index = 0; Index < WindowRules.size(); ++Index) { window_rule *Rule = WindowRules[Index]; if (Rule->Name || Rule->Except) { ApplyWindowRule(Window, Rule); } } } internal void ApplyRuleToExistingWindows(window_rule *Rule) { macos_window_map Windows = CopyWindowCache(); for (macos_window_map_it It = Windows.begin(); It != Windows.end(); ++It) { macos_window *Window = It->second; ApplyWindowRule(Window, Rule); } } void AddWindowRule(window_rule *Rule) { window_rule *Result = (window_rule *) malloc(sizeof(window_rule)); memcpy(Result, Rule, sizeof(window_rule)); WindowRules.push_back(Result); ApplyRuleToExistingWindows(Result); } internal void FreeWindowRule(window_rule *Rule) { ASSERT(Rule); if (Rule->Owner) free(Rule->Owner); if (Rule->Name) free(Rule->Name); if (Rule->Role) CFRelease(Rule->Role); if (Rule->Subrole) CFRelease(Rule->Subrole); if (Rule->Except) free(Rule->Except); if (Rule->State) free(Rule->State); if (Rule->Level) free(Rule->Level); if (Rule->Alpha) free(Rule->Alpha); if (Rule->GridLayout) free(Rule->GridLayout); free(Rule); } void FreeWindowRules() { for (size_t Index = 0; Index < WindowRules.size(); ++Index) { window_rule *Rule = WindowRules[Index]; FreeWindowRule(Rule); } WindowRules.clear(); }
29.361446
110
0.631241
[ "vector" ]
a9eaf9e5f7e8230947c0291947c9cbaa2fcce563
56,826
cpp
C++
Development/nmos/sdp_utils.cpp
rufusu-sony/nmos-cpp
bf746c701891cb4291e4abf50660266330cb1d7e
[ "Apache-2.0" ]
null
null
null
Development/nmos/sdp_utils.cpp
rufusu-sony/nmos-cpp
bf746c701891cb4291e4abf50660266330cb1d7e
[ "Apache-2.0" ]
null
null
null
Development/nmos/sdp_utils.cpp
rufusu-sony/nmos-cpp
bf746c701891cb4291e4abf50660266330cb1d7e
[ "Apache-2.0" ]
null
null
null
#include "nmos/sdp_utils.h" #include <map> #include <boost/algorithm/string/case_conv.hpp> #include <boost/asio/ip/address.hpp> #include <boost/range/adaptor/filtered.hpp> #include <boost/range/adaptor/transformed.hpp> #include "cpprest/basic_utils.h" #include "nmos/clock_ref_type.h" #include "nmos/channels.h" #include "nmos/format.h" #include "nmos/interlace_mode.h" #include "nmos/json_fields.h" #include "nmos/media_type.h" #include "nmos/transport.h" namespace nmos { namespace details { std::logic_error sdp_creation_error(const std::string& message) { return std::logic_error{ "sdp creation error - " + message }; } std::pair<sdp::address_type, bool> get_address_type_multicast(const utility::string_t& address) { #if BOOST_VERSION >= 106600 const auto ip_address = boost::asio::ip::make_address(utility::us2s(address)); #else const auto ip_address = boost::asio::ip::address::from_string(utility::us2s(address)); #endif return{ ip_address.is_v4() ? sdp::address_types::IP4 : sdp::address_types::IP6, ip_address.is_multicast() }; } std::vector<sdp_parameters::ts_refclk_t> make_ts_refclk(const web::json::value& node, const web::json::value& source, const web::json::value& sender) { const auto& clock_name = nmos::fields::clock_name(source); if (clock_name.is_null()) throw sdp_creation_error("no source clock"); const auto& clocks = nmos::fields::clocks(node); const auto clock = std::find_if(clocks.begin(), clocks.end(), [&](const web::json::value& clock) { return nmos::fields::name(clock) == clock_name.as_string(); }); if (clocks.end() == clock) throw sdp_creation_error("source clock not found"); const auto& interface_bindings = nmos::fields::interface_bindings(sender); if (0 == interface_bindings.size()) throw sdp_creation_error("no sender interface_bindings"); const nmos::clock_ref_type ref_type{ nmos::fields::ref_type(*clock) }; if (nmos::clock_ref_types::ptp == ref_type) { const sdp::ptp_version version{ nmos::fields::ptp_version(*clock) }; // since 'gmid' is required, always indicate it rather than 'traceable' return{ interface_bindings.size(), sdp_parameters::ts_refclk_t::ptp(version, boost::algorithm::to_upper_copy(nmos::fields::gmid(*clock))) }; } else if (nmos::clock_ref_types::internal == ref_type) { const auto& interfaces = nmos::fields::interfaces(node); return boost::copy_range<std::vector<sdp_parameters::ts_refclk_t>>(interface_bindings | boost::adaptors::transformed([&](const web::json::value& interface_binding) { const auto& interface_name = interface_binding.as_string(); const auto interface = std::find_if(interfaces.begin(), interfaces.end(), [&](const web::json::value& interface) { return nmos::fields::name(interface) == interface_name; }); if (interfaces.end() == interface) throw sdp_creation_error("sender interface not found"); return sdp_parameters::ts_refclk_t::local_mac(boost::algorithm::to_upper_copy(nmos::fields::port_id(*interface))); })); } else throw sdp_creation_error("unexpected clock ref_type"); } sdp::sampling make_sampling(const web::json::array& components) { // https://tools.ietf.org/html/rfc4175#section-6.1 // convert json to component name vs dimension lookup for easy access, // as components can be in any order inside the json struct dimension { int width; int height; }; const auto dimensions = boost::copy_range<std::map<utility::string_t, dimension>>(components | boost::adaptors::transformed([](const web::json::value& component) { return std::map<utility::string_t, dimension>::value_type{ nmos::fields::name(component), dimension{ nmos::fields::width(component), nmos::fields::height(component) } }; })); const auto de = dimensions.end(); if (de != dimensions.find(U("R")) && de != dimensions.find(U("G")) && de != dimensions.find(U("B")) && de != dimensions.find(U("A"))) { return sdp::samplings::RGBA; } else if (de != dimensions.find(U("R")) && de != dimensions.find(U("G")) && de != dimensions.find(U("B"))) { return sdp::samplings::RGB; } else if (de != dimensions.find(U("Y")) && de != dimensions.find(U("Cb")) && de != dimensions.find(U("Cr"))) { const auto& Y = dimensions.at(U("Y")); const auto& Cb = dimensions.at(U("Cb")); const auto& Cr = dimensions.at(U("Cr")); if (Cb.width != Cr.width || Cb.height != Cr.height) throw sdp_creation_error("unsupported YCbCr dimensions"); const auto& C = Cb; if (Y.height == C.height) { if (Y.width == C.width) return sdp::samplings::YCbCr_4_4_4; else if (Y.width / 2 == C.width) return sdp::samplings::YCbCr_4_2_2; else if (Y.width / 4 == C.width) return sdp::samplings::YCbCr_4_1_1; else throw sdp_creation_error("unsupported YCbCr dimensions"); } else if (Y.height / 2 == C.height) { if (Y.width / 2 == C.width) return sdp::samplings::YCbCr_4_2_0; else throw sdp_creation_error("unsupported YCbCr dimensions"); } else throw sdp_creation_error("unsupported YCbCr dimensions"); } else throw sdp_creation_error("unsupported components"); } } static sdp_parameters make_video_sdp_parameters(const web::json::value& node, const web::json::value& source, const web::json::value& flow, const web::json::value& sender, const std::vector<utility::string_t>& media_stream_ids) { sdp_parameters::video_t params; params.tp = sdp::type_parameters::type_N; // colorimetry map directly to flow_video json "colorspace" params.colorimetry = sdp::colorimetry{ nmos::fields::colorspace(flow) }; // use flow json "components" to work out sampling const auto& components = nmos::fields::components(flow); params.sampling = details::make_sampling(components); params.width = nmos::fields::frame_width(flow); params.height = nmos::fields::frame_height(flow); params.depth = nmos::fields::bit_depth(components.at(0)); // also maps directly params.tcs = sdp::transfer_characteristic_system{ nmos::fields::transfer_characteristic(flow) }; const auto& interlace_mode = nmos::fields::interlace_mode(flow); params.interlace = !interlace_mode.empty() && nmos::interlace_modes::progressive.name != interlace_mode; params.segmented = !interlace_mode.empty() && nmos::interlace_modes::interlaced_psf.name == interlace_mode; params.top_field_first = !interlace_mode.empty() && nmos::interlace_modes::interlaced_tff.name == interlace_mode; // grain_rate is optional in the flow, but if it's not there, for a video flow, it must be in the source const auto& grain_rate = nmos::fields::grain_rate(flow.has_field(nmos::fields::grain_rate) ? flow : source); params.exactframerate = nmos::rational(nmos::fields::numerator(grain_rate), nmos::fields::denominator(grain_rate)); return{ sender.at(nmos::fields::label).as_string(), params, 96, media_stream_ids, details::make_ts_refclk(node, source, sender) }; } static sdp_parameters make_audio_sdp_parameters(const web::json::value& node, const web::json::value& source, const web::json::value& flow, const web::json::value& sender, const std::vector<utility::string_t>& media_stream_ids) { sdp_parameters::audio_t params; // rtpmap params.channel_count = (uint32_t)nmos::fields::channels(source).size(); params.bit_depth = nmos::fields::bit_depth(flow); const auto& sample_rate(flow.at(nmos::fields::sample_rate)); params.sample_rate = nmos::rational(nmos::fields::numerator(sample_rate), nmos::fields::denominator(sample_rate)); // format_specific_parameters const auto channel_symbols = boost::copy_range<std::vector<nmos::channel_symbol>>(nmos::fields::channels(source) | boost::adaptors::transformed([](const web::json::value& channel) { return channel_symbol{ nmos::fields::symbol(channel) }; })); params.channel_order = nmos::make_fmtp_channel_order(channel_symbols); // ptime params.packet_time = 1; return{ sender.at(nmos::fields::label).as_string(), params, 97, media_stream_ids, details::make_ts_refclk(node, source, sender) }; } static sdp_parameters make_data_sdp_parameters(const web::json::value& node, const web::json::value& source, const web::json::value& flow, const web::json::value& sender, const std::vector<utility::string_t>& media_stream_ids) { sdp_parameters::data_t params; // format_specific_parameters // did_sdid map directly to flow_sdianc_data "DID_SDID" params.did_sdids = boost::copy_range<std::vector<nmos::did_sdid>>(nmos::fields::DID_SDID(flow).as_array() | boost::adaptors::transformed([](const web::json::value& did_sdid) { return nmos::parse_did_sdid(did_sdid); })); // hm, no vpid_code in the flow return{ sender.at(nmos::fields::label).as_string(), params, 100, media_stream_ids, details::make_ts_refclk(node, source, sender) }; } sdp_parameters make_sdp_parameters(const web::json::value& node, const web::json::value& source, const web::json::value& flow, const web::json::value& sender, const std::vector<utility::string_t>& media_stream_ids) { const auto& format = nmos::fields::format(flow); if (nmos::formats::video.name == format) return make_video_sdp_parameters(node, source, flow, sender, media_stream_ids); else if (nmos::formats::audio.name == format) return make_audio_sdp_parameters(node, source, flow, sender, media_stream_ids); else if (nmos::formats::data.name == format) return make_data_sdp_parameters(node, source, flow, sender, media_stream_ids); else throw details::sdp_creation_error("unsuported media format"); } static web::json::value make_session_description(const sdp_parameters& sdp_params, const web::json::value& transport_params, const web::json::value& ptime, const web::json::value& rtpmap, const web::json::value& fmtp) { using web::json::value; using web::json::value_of; using web::json::array; // check to ensure enough media_stream_ids for multi-leg transport_params if (transport_params.size() > 1 && transport_params.size() > sdp_params.group.media_stream_ids.size()) { throw details::sdp_creation_error("not enough sdp parameters media stream ids for transport_params"); } // for backward compatibility, use default ts-refclk when not (enough) specified const auto ts_refclk_default = sdp_parameters::ts_refclk_t::ptp_traceable(); // so far so good, now build the session_description const bool keep_order = true; const auto& destination_ip = nmos::fields::destination_ip(transport_params.at(0)).as_string(); const auto address_type_multicast = details::get_address_type_multicast(destination_ip); auto session_description = value_of({ // Protocol Version // See https://tools.ietf.org/html/rfc4566#section-5.1 { sdp::fields::protocol_version, 0 }, // Origin // See https://tools.ietf.org/html/rfc4566#section-5.2 { sdp::fields::origin, value_of({ { sdp::fields::user_name, sdp_params.origin.user_name }, { sdp::fields::session_id, sdp_params.origin.session_id }, { sdp::fields::session_version, sdp_params.origin.session_version }, { sdp::fields::network_type, sdp::network_types::internet.name }, { sdp::fields::address_type, address_type_multicast.first.name }, { sdp::fields::unicast_address, nmos::fields::source_ip(transport_params.at(0)) } }, keep_order) }, // Session Name // See https://tools.ietf.org/html/rfc4566#section-5.3 { sdp::fields::session_name, sdp_params.session_name }, // Time Descriptions // See https://tools.ietf.org/html/rfc4566#section-5 { sdp::fields::time_descriptions, value_of({ value_of({ { sdp::fields::timing, web::json::value_of({ { sdp::fields::start_time, sdp_params.timing.start_time }, { sdp::fields::stop_time, sdp_params.timing.stop_time } }) } }, keep_order) }) } }, keep_order); // group & mid attributes // see https://tools.ietf.org/html/rfc5888 auto mids = value::array(); // build media_descriptions with given media_stream_ids // Media Descriptions // See https://tools.ietf.org/html/rfc4566#section-5 auto media_descriptions = value::array(); size_t leg = 0; for (const auto& transport_param : transport_params.as_array()) { const auto& ts_refclk = sdp_params.ts_refclk.size() > leg ? sdp_params.ts_refclk[leg] : ts_refclk_default; // build media_description auto media_description = value_of({ // Media // See https://tools.ietf.org/html/rfc4566#section-5.14 { sdp::fields::media, value_of({ { sdp::fields::media_type, sdp_params.media_type.name }, { sdp::fields::port, transport_param.at(nmos::fields::destination_port) }, { sdp::fields::protocol, sdp_params.protocol.name }, { sdp::fields::formats, value_of({ utility::ostringstreamed(sdp_params.rtpmap.payload_type) }) } }, keep_order) }, // Connection Data // See https://tools.ietf.org/html/rfc4566#section-5.7 { sdp::fields::connection_data, value_of({ value_of({ { sdp::fields::network_type, sdp::network_types::internet.name }, { sdp::fields::address_type, address_type_multicast.first.name }, { sdp::fields::connection_address, sdp::address_types::IP4 == address_type_multicast.first && address_type_multicast.second ? nmos::fields::destination_ip(transport_param).as_string() + U("/") + utility::ostringstreamed(sdp_params.connection_data.ttl) : nmos::fields::destination_ip(transport_param).as_string() } }, keep_order) }) }, // Attributes // See https://tools.ietf.org/html/rfc4566#section-5.13 { sdp::fields::attributes, value_of({ // a=ts-refclk:ptp=<ptp version>:<ptp gmid>[:<ptp domain>] // a=ts-refclk:ptp=<ptp version>:traceable // See https://tools.ietf.org/html/rfc7273 // a=ts-refclk:localmac=<mac-address-of-sender> // See SMPTE ST 2110-10:2017 Professional Media Over Managed IP Networks: System Timing and Definitions, Section 8.2 Reference Clock value_of({ { sdp::fields::name, sdp::attributes::ts_refclk }, { sdp::fields::value, sdp::ts_refclk_sources::ptp == ts_refclk.clock_source ? ts_refclk.ptp_server.empty() ? value_of({ { sdp::fields::clock_source, sdp::ts_refclk_sources::ptp.name }, { sdp::fields::ptp_version, ts_refclk.ptp_version.name }, { sdp::fields::traceable, true } }, keep_order) : value_of({ { sdp::fields::clock_source, sdp::ts_refclk_sources::ptp.name }, { sdp::fields::ptp_version, ts_refclk.ptp_version.name }, { sdp::fields::ptp_server, ts_refclk.ptp_server } }, keep_order) : sdp::ts_refclk_sources::local_mac == ts_refclk.clock_source ? value_of({ { sdp::fields::clock_source, sdp::ts_refclk_sources::local_mac.name }, { sdp::fields::mac_address, ts_refclk.mac_address } }, keep_order) : value::null() } }, keep_order), // a=mediaclk:[id=<clock id> ]<clock source>[=<clock parameters>] // See https://tools.ietf.org/html/rfc7273#section-5 value_of({ { sdp::fields::name, sdp::attributes::mediaclk }, { sdp::fields::value, sdp_params.mediaclk.clock_source.name + U("=") + sdp_params.mediaclk.clock_parameters } }, keep_order) }) } //attribues }, keep_order); //media_description // insert source-filter if multicast if (address_type_multicast.second) { auto& attributes = media_description.at(sdp::fields::attributes); // a=source-filter: <filter-mode> <nettype> <address-types> <dest-address> <src-list> // See https://tools.ietf.org/html/rfc4570 web::json::push_back( attributes, value_of({ { sdp::fields::name, sdp::attributes::source_filter }, { sdp::fields::value, value_of({ { sdp::fields::filter_mode, sdp::filter_modes::incl.name }, { sdp::fields::network_type, sdp::network_types::internet.name }, { sdp::fields::address_types, address_type_multicast.first.name }, { sdp::fields::destination_address, transport_param.at(nmos::fields::destination_ip) }, { sdp::fields::source_addresses, value_of({ transport_param.at(nmos::fields::source_ip) }) } }, keep_order) } }, keep_order) ); } // insert ptime if set // a=ptime:<packet time> // See https://tools.ietf.org/html/rfc4566#section-6 if (!ptime.is_null()) { auto& attributes = media_description.at(sdp::fields::attributes); web::json::push_back(attributes, ptime); } // insert rtpmap if set // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encoding parameters>] // See https://tools.ietf.org/html/rfc4566#section-6 if (!rtpmap.is_null()) { auto& attributes = media_description.at(sdp::fields::attributes); web::json::push_back(attributes, rtpmap); } // insert fmtp if set // a=fmtp:<format> <format specific parameters> // See https://tools.ietf.org/html/rfc4566#section-6 if (!fmtp.is_null()) { auto& attributes = media_description.at(sdp::fields::attributes); web::json::push_back(attributes, fmtp); } // insert "media stream identification" if there are more than 1 leg // a=mid:<identification-tag> // See https://tools.ietf.org/html/rfc5888 if (transport_params.size() > 1) { const auto& mid = sdp_params.group.media_stream_ids[leg]; // build up mids based on group::media_stream_ids web::json::push_back(mids, mid); auto& attributes = media_description.at(sdp::fields::attributes); web::json::push_back( attributes, value_of({ { sdp::fields::name, sdp::attributes::mid }, { sdp::fields::value, mid } }, keep_order) ); } web::json::push_back(media_descriptions, media_description); ++leg; } // add group attribute if there are more than 1 leg // a=group:<semantics>[ <identification-tag>]* // See https://tools.ietf.org/html/rfc5888 if (mids.size() > 1) { session_description[sdp::fields::attributes] = value_of({ web::json::value_of({ { sdp::fields::name, sdp::attributes::group }, { sdp::fields::value, web::json::value_of({ { sdp::fields::semantics, sdp_params.group.semantics.name }, { sdp::fields::mids, mids } }, keep_order) }, }, keep_order) }); } session_description[sdp::fields::media_descriptions] = media_descriptions; return session_description; } static web::json::value make_video_session_description(const sdp_parameters& sdp_params, const web::json::value& transport_params) { using web::json::value_of; const bool keep_order = true; // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encoding parameters>] // See https://tools.ietf.org/html/rfc4566#section-6 const auto rtpmap = value_of({ { sdp::fields::name, sdp::attributes::rtpmap }, { sdp::fields::value, web::json::value_of({ { sdp::fields::payload_type, sdp_params.rtpmap.payload_type }, { sdp::fields::encoding_name, sdp_params.rtpmap.encoding_name }, { sdp::fields::clock_rate, sdp_params.rtpmap.clock_rate } }, keep_order) } }, keep_order); // a=fmtp:<format> <format specific parameters> // for simplicity, following the order of parameters given in VSF TR-05:2017 // See https://tools.ietf.org/html/rfc4566#section-6 // and http://www.videoservicesforum.org/download/technical_recommendations/VSF_TR-05_2018-06-23.pdf // and comments regarding the fmtp attribute parameters in get_session_description_sdp_parameters auto format_specific_parameters = value_of({ sdp::named_value(sdp::fields::width, utility::ostringstreamed(sdp_params.video.width)), sdp::named_value(sdp::fields::height, utility::ostringstreamed(sdp_params.video.height)), sdp::named_value(sdp::fields::exactframerate, sdp_params.video.exactframerate.denominator() != 1 ? utility::ostringstreamed(sdp_params.video.exactframerate.numerator()) + U("/") + utility::ostringstreamed(sdp_params.video.exactframerate.denominator()) : utility::ostringstreamed(sdp_params.video.exactframerate.numerator())) }); if (sdp_params.video.interlace) web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::interlace)); if (sdp_params.video.segmented) web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::segmented)); if (sdp_params.video.top_field_first) web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::top_field_first)); web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::sampling, sdp_params.video.sampling.name)); web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::depth, utility::ostringstreamed(sdp_params.video.depth))); web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::colorimetry, sdp_params.video.colorimetry.name)); if (!sdp_params.video.tcs.name.empty()) web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::transfer_characteristic_system, sdp_params.video.tcs.name)); web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::packing_mode, sdp::packing_modes::general.name)); // or block... web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::smpte_standard_number, sdp::smpte_standard_numbers::ST2110_20_2017.name)); if (!sdp_params.video.tp.name.empty()) web::json::push_back(format_specific_parameters, sdp::named_value(sdp::fields::type_parameter, sdp_params.video.tp.name)); const auto fmtp = web::json::value_of({ { sdp::fields::name, sdp::attributes::fmtp }, { sdp::fields::value, web::json::value_of({ { sdp::fields::format, utility::ostringstreamed(sdp_params.rtpmap.payload_type) }, { sdp::fields::format_specific_parameters, format_specific_parameters } }, keep_order) } }, keep_order); return make_session_description(sdp_params, transport_params, {}, rtpmap, fmtp); } static web::json::value make_audio_session_description(const sdp_parameters& sdp_params, const web::json::value& transport_params) { using web::json::value; using web::json::value_of; const bool keep_order = true; // a=ptime:<packet time> // See https://tools.ietf.org/html/rfc4566#section-6 const auto ptime = value_of({ { sdp::fields::name, sdp::attributes::ptime }, { sdp::fields::value, sdp_params.audio.packet_time } }, keep_order); // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encoding parameters>] // See https://tools.ietf.org/html/rfc4566#section-6 const auto rtpmap = value_of({ { sdp::fields::name, sdp::attributes::rtpmap }, { sdp::fields::value, value_of({ { sdp::fields::payload_type, sdp_params.rtpmap.payload_type }, { sdp::fields::encoding_name, sdp_params.rtpmap.encoding_name }, { sdp::fields::clock_rate, sdp_params.rtpmap.clock_rate }, { sdp::fields::encoding_parameters, sdp_params.audio.channel_count } }, keep_order) } }, keep_order); // a=fmtp:<format> <format specific parameters> // See https://tools.ietf.org/html/rfc4566#section-6 const auto format_specific_parameters = sdp_params.audio.channel_order.empty() ? value::array() : value_of({ sdp::named_value(sdp::fields::channel_order, sdp_params.audio.channel_order) }); const auto fmtp = value_of({ { sdp::fields::name, sdp::attributes::fmtp }, { sdp::fields::value, value_of({ { sdp::fields::format, utility::ostringstreamed(sdp_params.rtpmap.payload_type) }, { sdp::fields::format_specific_parameters, format_specific_parameters } }, keep_order) } }, keep_order); return make_session_description(sdp_params, transport_params, ptime, rtpmap, fmtp); } static web::json::value make_data_format_specific_parameters(const sdp_parameters::data_t& data_params) { auto result = web::json::value_from_elements(data_params.did_sdids | boost::adaptors::transformed([](const nmos::did_sdid& did_sdid) { return sdp::named_value(sdp::fields::DID_SDID, make_fmtp_did_sdid(did_sdid)); })); if (0 != data_params.vpid_code) { web::json::push_back(result, sdp::named_value(sdp::fields::VPID_Code, utility::ostringstreamed(data_params.vpid_code))); } return result; } static web::json::value make_data_session_description(const sdp_parameters& sdp_params, const web::json::value& transport_params) { using web::json::value; using web::json::value_of; const bool keep_order = true; // a=rtpmap:<payload type> <encoding name>/<clock rate>[/<encoding parameters>] // See https://tools.ietf.org/html/rfc4566#section-6 const auto rtpmap = value_of({ { sdp::fields::name, sdp::attributes::rtpmap }, { sdp::fields::value, value_of({ { sdp::fields::payload_type, sdp_params.rtpmap.payload_type }, { sdp::fields::encoding_name, sdp_params.rtpmap.encoding_name }, { sdp::fields::clock_rate, sdp_params.rtpmap.clock_rate } }, keep_order) } }, keep_order); // a=fmtp:<format> <format specific parameters> // See https://tools.ietf.org/html/rfc4566#section-6 const auto fmtp = sdp_params.data.did_sdids.empty() && 0 == sdp_params.data.vpid_code ? value::null() : value_of({ { sdp::fields::name, sdp::attributes::fmtp }, { sdp::fields::value, value_of({ { sdp::fields::format, utility::ostringstreamed(sdp_params.rtpmap.payload_type) }, { sdp::fields::format_specific_parameters, make_data_format_specific_parameters(sdp_params.data) } }, keep_order) } }, keep_order); return make_session_description(sdp_params, transport_params, {}, rtpmap, fmtp); } namespace details { nmos::format get_format(const sdp_parameters& sdp_params) { if (sdp::media_types::video == sdp_params.media_type && U("raw") == sdp_params.rtpmap.encoding_name) return nmos::formats::video; if (sdp::media_types::audio == sdp_params.media_type) return nmos::formats::audio; if (sdp::media_types::video == sdp_params.media_type && U("smpte291") == sdp_params.rtpmap.encoding_name) return nmos::formats::data; return{}; } nmos::media_type get_media_type(const sdp_parameters& sdp_params) { return nmos::media_type{ sdp_params.media_type.name + U("/") + sdp_params.rtpmap.encoding_name }; } } web::json::value make_session_description(const sdp_parameters& sdp_params, const web::json::value& transport_params) { const auto format = details::get_format(sdp_params); if (nmos::formats::video == format) return make_video_session_description(sdp_params, transport_params); if (nmos::formats::audio == format) return make_audio_session_description(sdp_params, transport_params); if (nmos::formats::data == format) return make_data_session_description(sdp_params, transport_params); throw details::sdp_creation_error("unsupported ST2110 media"); } namespace details { // Syntax of <connection-address> depends on <addrtype>: // IP4 <unicast address> // IP6 <unicast address> // IP4 <base multicast address>/<ttl>[/<number of addresses>] // IP6 <base multicast address>[/<number of addresses>] // See https://tools.ietf.org/html/rfc4566#section-5.7 struct connection_address { utility::string_t base_address; uint32_t ttl; uint32_t number_of_addresses; connection_address(const utility::string_t& base_address, uint32_t ttl, uint32_t number_of_addresses) : base_address(base_address) , ttl(ttl) , number_of_addresses(number_of_addresses) {} }; connection_address parse_connection_address(const sdp::address_type& address_type, const utility::string_t& connection_address) { const auto slash = connection_address.find(U('/')); if (utility::string_t::npos == slash) return{ connection_address, 0, 1 }; if (sdp::address_types::IP6 == address_type) { return{ connection_address.substr(0, slash), 0, utility::istringstreamed<uint32_t>(connection_address.substr(slash + 1)) }; } else // if (sdp::address_types::IP4 == address_type) { const auto slash2 = connection_address.find(U('/'), slash + 1); return{ connection_address.substr(0, slash), utility::string_t::npos == slash2 ? utility::istringstreamed<uint32_t>(connection_address.substr(slash + 1)) : utility::istringstreamed<uint32_t>(connection_address.substr(slash + 1, slash2 - (slash + 1))), utility::string_t::npos == slash2 ? 1 : utility::istringstreamed<uint32_t>(connection_address.substr(slash2 + 1)) }; } } // Set appropriate transport parameters depending on whether the specified address is multicast void set_multicast_ip_interface_ip(web::json::value& params, const utility::string_t& address) { using web::json::value; if (details::get_address_type_multicast(address).second) { // any-source multicast, unless there's a source-filter params[nmos::fields::source_ip] = value::null(); params[nmos::fields::multicast_ip] = value::string(address); params[nmos::fields::interface_ip] = value::string(U("auto")); } else { params[nmos::fields::multicast_ip] = value::null(); params[nmos::fields::interface_ip] = value::string(address); } } } // Get transport parameters from the parsed SDP file web::json::value get_session_description_transport_params(const web::json::value& session_description) { using web::json::value; using web::json::value_of; web::json::value transport_params; // There isn't much of a specification for interpreting SDP files and updating the // equivalent transport parameters, just some examples... // See https://github.com/AMWA-TV/nmos-device-connection-management/blob/v1.0/docs/4.1.%20Behaviour%20-%20RTP%20Transport%20Type.md#interpretation-of-sdp-files // For now, this function should handle the following cases identified in the documentation: // * Unicast // * Source Specific Multicast // * Any Source Multicast // * Operation with SMPTE 2022-7 - Separate Source Addresses // * Operation with SMPTE 2022-7 - Separate Destination Addresses // The following cases are not yet handled: // * Operation with SMPTE 2022-5 // * Operation with SMPTE 2022-7 - Temporal Redundancy // * Operation with RTCP auto& media_descriptions = sdp::fields::media_descriptions(session_description); for (size_t leg = 0; leg < 2; ++leg) { web::json::value params; params[nmos::fields::source_ip] = value::string(sdp::fields::unicast_address(sdp::fields::origin(session_description))); // session connection data is the default for each media description auto& session_connection_data = sdp::fields::connection_data(session_description); if (!session_connection_data.is_null()) { // hmm, how to handle multiple connection addresses? const auto address_type = sdp::address_type{ sdp::fields::address_type(session_connection_data) }; const auto connection_address = details::parse_connection_address(address_type, sdp::fields::connection_address(session_connection_data)); details::set_multicast_ip_interface_ip(params, connection_address.base_address); } // Look for the media description corresponding to this element in the transport parameters auto& mda = media_descriptions.as_array(); auto source_address = leg; for (auto md = mda.begin(); mda.end() != md; ++md) { auto& media_description = *md; auto& media = sdp::fields::media(media_description); // check transport protocol (cf. "UDP/FEC" for Operation with SMPTE 2022-5) const sdp::protocol protocol{ sdp::fields::protocol(media) }; if (sdp::protocols::RTP_AVP != protocol) continue; // check media type, e.g. "video" // (vs. IS-04 receiver's caps.media_types) const sdp::media_type media_type{ sdp::fields::media_type(media) }; if (!(sdp::media_types::video == media_type || sdp::media_types::audio == media_type)) continue; // media connection data overrides session connection data auto& media_connection_data = sdp::fields::connection_data(media_description); if (!media_connection_data.is_null() && 0 != media_connection_data.size()) { // hmm, how to handle multiple connection addresses? const auto address_type = sdp::address_type{ sdp::fields::address_type(media_connection_data.at(0)) }; const auto connection_address = details::parse_connection_address(address_type, sdp::fields::connection_address(media_connection_data.at(0))); details::set_multicast_ip_interface_ip(params, connection_address.base_address); } // take account of the number of source addresses (cf. Operation with SMPTE 2022-7 - Separate Source Addresses) auto& media_attributes = sdp::fields::attributes(media_description); if (!media_attributes.is_null()) { auto& ma = media_attributes.as_array(); auto source_filter = sdp::find_name(ma, sdp::attributes::source_filter); if (ma.end() != source_filter) { auto& sf = sdp::fields::value(*source_filter); auto& sa = sdp::fields::source_addresses(sf); if (sa.size() <= source_address) { source_address -= sa.size(); continue; } details::set_multicast_ip_interface_ip(params, sdp::fields::destination_address(sf)); params[nmos::fields::source_ip] = sdp::fields::source_addresses(sf).at(source_address); source_address = 0; } } if (0 != source_address) { --source_address; continue; } params[nmos::fields::destination_port] = value::number(sdp::fields::port(media)); params[nmos::fields::rtp_enabled] = value::boolean(true); web::json::push_back(transport_params, params); break; } } return transport_params; } namespace details { std::runtime_error sdp_processing_error(const std::string& message) { return std::runtime_error{ "sdp processing error - " + message }; } } sdp_parameters get_session_description_sdp_parameters(const web::json::value& sdp) { using web::json::value; using web::json::value_of; sdp_parameters sdp_params; // Protocol Version // See https://tools.ietf.org/html/rfc4566#section-5.1 if (0 != sdp::fields::protocol_version(sdp)) throw details::sdp_processing_error("unsupported protocol version"); // Origin // See https://tools.ietf.org/html/rfc4566#section-5.2 const auto& origin = sdp::fields::origin(sdp); sdp_params.origin = { sdp::fields::user_name(origin), sdp::fields::session_id(origin), sdp::fields::session_version(origin) }; // Session Name // See https://tools.ietf.org/html/rfc4566#section-5.3 sdp_params.session_name = sdp::fields::session_name(sdp); // Time Descriptions // See https://tools.ietf.org/html/rfc4566#section-5 const auto& time_descriptions = sdp::fields::time_descriptions(sdp).as_array(); if (time_descriptions.size()) { const auto& timing = sdp::fields::timing(time_descriptions.at(0)); sdp_params.timing = { sdp::fields::start_time(timing), sdp::fields::stop_time(timing) }; } // Connection Data // See https://tools.ietf.org/html/rfc4566#section-5.7 { const auto& session_connection_data = sdp::fields::connection_data(sdp); if (!session_connection_data.is_null()) { // hmm, how to handle multiple connection addresses? const auto address_type = sdp::address_type{ sdp::fields::address_type(session_connection_data) }; const auto connection_address = details::parse_connection_address(address_type, sdp::fields::connection_address(session_connection_data)); sdp_params.connection_data.ttl = connection_address.ttl; } } // hmm, this code does not handle Synchronization Source (SSRC) level grouping or attributes // i.e. the 'ssrc-group' attribute or 'ssrc' used to convey e.g. 'fmtp', 'mediaclk' or 'ts-refclk' // see https://tools.ietf.org/html/rfc7104#section-3.2 // and https://tools.ietf.org/html/rfc5576 // and https://www.iana.org/assignments/sdp-parameters/sdp-parameters.xhtml#sdp-att-field // Group // a=group:<semantics>[ <identification-tag>]* // See https://tools.ietf.org/html/rfc5888 auto sdp_attributes = sdp::fields::attributes(sdp).as_array(); if (sdp_attributes.size()) { auto group = sdp::find_name(sdp_attributes, sdp::attributes::group); if (sdp_attributes.end() != group) { const auto& value = sdp::fields::value(*group); sdp_params.group.semantics = sdp::group_semantics_type{ sdp::fields::semantics(value) }; for (const auto& mid : sdp::fields::mids(value)) { sdp_params.group.media_stream_ids.push_back(mid.as_string()); } } } // Media Descriptions // See https://tools.ietf.org/html/rfc4566#section-5 const auto& media_descriptions = sdp::fields::media_descriptions(sdp); // ts-refclk attributes // See https://tools.ietf.org/html/rfc7273 sdp_params.ts_refclk = boost::copy_range<std::vector<sdp_parameters::ts_refclk_t>>(media_descriptions.as_array() | boost::adaptors::filtered([](const value& media_description) { auto& attributes = sdp::fields::attributes(media_description).as_array(); auto ts_refclk = sdp::find_name(attributes, sdp::attributes::ts_refclk); return attributes.end() != ts_refclk; }) | boost::adaptors::transformed([](const value& media_description) { auto& attributes = sdp::fields::attributes(media_description).as_array(); auto ts_refclk = sdp::find_name(attributes, sdp::attributes::ts_refclk); const auto& value = sdp::fields::value(*ts_refclk); sdp::ts_refclk_source clock_source{ sdp::fields::clock_source(value) }; if (sdp::ts_refclk_sources::ptp == clock_source) { // no ptp-server implies traceable return sdp_parameters::ts_refclk_t::ptp(sdp::ptp_version{ sdp::fields::ptp_version(value) }, sdp::fields::ptp_server(value)); } else if (sdp::ts_refclk_sources::local_mac == clock_source) { return sdp_parameters::ts_refclk_t::local_mac(sdp::fields::mac_address(value)); } else throw details::sdp_processing_error("unsupported timestamp reference clock source"); })); // hmm, for simplicity, the remainder of this code assumes that format-related information must be the same // in every media description, so reads it only from the first one! if (0 == media_descriptions.size()) throw details::sdp_processing_error("missing media descriptions"); const auto& media_description = media_descriptions.at(0); // Connection Data // get default multicast_ip via Connection Data // See https://tools.ietf.org/html/rfc4566#section-5.7 { const auto& media_connection_data = sdp::fields::connection_data(media_description); if (!media_connection_data.is_null() && 0 != media_connection_data.size()) { // hmm, how to handle multiple connection addresses? const auto address_type = sdp::address_type{ sdp::fields::address_type(media_connection_data.at(0)) }; const auto connection_address = details::parse_connection_address(address_type, sdp::fields::connection_address(media_connection_data.at(0))); sdp_params.connection_data.ttl = connection_address.ttl; } } // Media // See https://tools.ietf.org/html/rfc4566#section-5.14 const auto& media = sdp::fields::media(media_description); sdp_params.media_type = sdp::media_type{ sdp::fields::media_type(media) }; sdp_params.protocol = sdp::protocol{ sdp::fields::protocol(media) }; // media description attributes auto& attributes = sdp::fields::attributes(media_description).as_array(); // mediaclk attribute // See https://tools.ietf.org/html/rfc7273 auto mediaclk = sdp::find_name(attributes, sdp::attributes::mediaclk); if (attributes.end() != mediaclk) { const auto& value = sdp::fields::value(*mediaclk).as_string(); const auto eq = value.find(U('=')); sdp_params.mediaclk = { sdp::media_clock_source{ value.substr(0, eq) }, utility::string_t::npos != eq ? value.substr(eq + 1) : utility::string_t{} }; } // rtpmap attribute // See https://tools.ietf.org/html/rfc4566#section-6 auto rtpmap = sdp::find_name(attributes, sdp::attributes::rtpmap); if (attributes.end() == rtpmap) throw details::sdp_processing_error("missing attribute: rtpmap"); const auto& rtpmap_value = sdp::fields::value(*rtpmap); sdp_params.rtpmap.encoding_name = sdp::fields::encoding_name(rtpmap_value); sdp_params.rtpmap.payload_type = sdp::fields::payload_type(rtpmap_value); sdp_params.rtpmap.clock_rate = sdp::fields::clock_rate(rtpmap_value); const auto format = details::get_format(sdp_params); const auto is_video_sdp = nmos::formats::video == format; const auto is_audio_sdp = nmos::formats::audio == format; const auto is_data_sdp = nmos::formats::data == format; if (is_audio_sdp) { const auto& encoding_name = sdp::fields::encoding_name(rtpmap_value); sdp_params.audio.bit_depth = !encoding_name.empty() && U('L') == encoding_name.front() ? utility::istringstreamed<uint32_t>(encoding_name.substr(1)) : 0; sdp_params.audio.sample_rate = nmos::rational{ (nmos::rational::int_type)sdp::fields::clock_rate(rtpmap_value) }; sdp_params.audio.channel_count = (uint32_t)sdp::fields::encoding_parameters(rtpmap_value); } // ptime attribute // See https://tools.ietf.org/html/rfc4566#section-6 { auto ptime = sdp::find_name(attributes, sdp::attributes::ptime); if (is_audio_sdp) { if (attributes.end() == ptime) throw details::sdp_processing_error("missing attribute: ptime"); sdp_params.audio.packet_time = sdp::fields::value(*ptime).as_integer(); } } // fmtp attribute // See https://tools.ietf.org/html/rfc4566#section-6 auto fmtp = sdp::find_name(attributes, sdp::attributes::fmtp); if (is_video_sdp) { if (attributes.end() == fmtp) throw details::sdp_processing_error("missing attribute: fmtp"); const auto& fmtp_value = sdp::fields::value(*fmtp); const auto& format_specific_parameters = sdp::fields::format_specific_parameters(fmtp_value); // See SMPTE ST 2110-20:2017 Section 7.2 Required Media Type Parameters // and Section 7.3 Media Type Parameters with default values const auto width = sdp::find_name(format_specific_parameters, sdp::fields::width); if (format_specific_parameters.end() == width) throw details::sdp_processing_error("missing format parameter: width"); sdp_params.video.width = utility::istringstreamed<uint32_t>(sdp::fields::value(*width).as_string()); const auto height = sdp::find_name(format_specific_parameters, sdp::fields::height); if (format_specific_parameters.end() == height) throw details::sdp_processing_error("missing format parameter: height"); sdp_params.video.height = utility::istringstreamed<uint32_t>(sdp::fields::value(*height).as_string()); auto parse_rational = [](const utility::string_t& rational_string) { const auto slash = rational_string.find(U('/')); return nmos::rational(utility::istringstreamed<uint64_t>(rational_string.substr(0, slash)), utility::string_t::npos != slash ? utility::istringstreamed<uint64_t>(rational_string.substr(slash + 1)) : 1); }; const auto exactframerate = sdp::find_name(format_specific_parameters, sdp::fields::exactframerate); if (format_specific_parameters.end() == exactframerate) throw details::sdp_processing_error("missing format parameter: exactframerate"); sdp_params.video.exactframerate = parse_rational(sdp::fields::value(*exactframerate).as_string()); // optional const auto interlace = sdp::find_name(format_specific_parameters, sdp::fields::interlace); sdp_params.video.interlace = format_specific_parameters.end() != interlace; // optional const auto segmented = sdp::find_name(format_specific_parameters, sdp::fields::segmented); sdp_params.video.segmented = format_specific_parameters.end() != segmented; // optional const auto top_field_first = sdp::find_name(format_specific_parameters, sdp::fields::top_field_first); sdp_params.video.top_field_first = format_specific_parameters.end() != top_field_first; const auto sampling = sdp::find_name(format_specific_parameters, sdp::fields::sampling); if (format_specific_parameters.end() == sampling) throw details::sdp_processing_error("missing format parameter: sampling"); sdp_params.video.sampling = sdp::sampling{ sdp::fields::value(*sampling).as_string() }; const auto depth = sdp::find_name(format_specific_parameters, sdp::fields::depth); if (format_specific_parameters.end() == depth) throw details::sdp_processing_error("missing format parameter: depth"); sdp_params.video.depth = utility::istringstreamed<uint32_t>(sdp::fields::value(*depth).as_string()); // optional const auto tcs = sdp::find_name(format_specific_parameters, sdp::fields::transfer_characteristic_system); if (format_specific_parameters.end() != tcs) { sdp_params.video.tcs = sdp::transfer_characteristic_system{ sdp::fields::value(*tcs).as_string() }; } // else sdp_params.video.tcs = sdp::transfer_characteristic_systems::SDR; // but better to let the caller distinguish that it's been defaulted? const auto colorimetry = sdp::find_name(format_specific_parameters, sdp::fields::colorimetry); if (format_specific_parameters.end() == colorimetry) throw details::sdp_processing_error("missing format parameter: colorimetry"); sdp_params.video.colorimetry = sdp::colorimetry{ sdp::fields::value(*colorimetry).as_string() }; // don't examine required parameters "PM" (packing mode), "SSN" (SMPTE standard number) // don't examine optional parameters "segmented", "RANGE", "MAXUDP", "PAR" // "Senders and Receivers compliant to [ST 2110-20] shall comply with the provisions of SMPTE ST 2110-21." // See SMPTE ST 2110-20:2017 Section 6.1.1 // See SMPTE ST 2110-21:2017 Section 8.1 Required Parameters // and Section 8.2 Optional Parameters // hmm, "TP" (type parameter) is required, but currently omitted by several vendors, so allow that for now... const auto tp = sdp::find_name(format_specific_parameters, sdp::fields::type_parameter); if (format_specific_parameters.end() != tp) { sdp_params.video.tp = sdp::type_parameter{ sdp::fields::value(*tp).as_string() }; } // else sdp_params.video.tp = {}; // don't examine optional parameters "TROFF", "CMAX" } else if (is_audio_sdp && attributes.end() != fmtp) { const auto& fmtp_value = sdp::fields::value(*fmtp); const auto& format_specific_parameters = sdp::fields::format_specific_parameters(fmtp_value); // optional const auto channel_order = sdp::find_name(format_specific_parameters, sdp::fields::channel_order); if (format_specific_parameters.end() != channel_order) { sdp_params.audio.channel_order = sdp::fields::value(*channel_order).as_string(); } } else if (is_data_sdp && attributes.end() != fmtp) { const auto& fmtp_value = sdp::fields::value(*fmtp); const auto& format_specific_parameters = sdp::fields::format_specific_parameters(fmtp_value); // "The SDP object shall be constructed as described in IETF RFC 8331" // See SMPTE ST 2110-40:2018 Section 6 // and https://tools.ietf.org/html/rfc8331 // optional sdp_params.data.did_sdids = boost::copy_range<std::vector<nmos::did_sdid>>(format_specific_parameters | boost::adaptors::filtered([](const web::json::value& nv) { return sdp::fields::DID_SDID.key == sdp::fields::name(nv); }) | boost::adaptors::transformed([](const web::json::value& did_sdid) { return parse_fmtp_did_sdid(did_sdid.as_string()); })); // optional const auto vpid_code = sdp::find_name(format_specific_parameters, sdp::fields::VPID_Code); if (format_specific_parameters.end() != vpid_code) { sdp_params.data.vpid_code = (nmos::vpid_code)utility::istringstreamed<uint32_t>(sdp::fields::value(*vpid_code).as_string()); } } return sdp_params; } std::pair<sdp_parameters, web::json::value> parse_session_description(const web::json::value& session_description) { return{ get_session_description_sdp_parameters(session_description), get_session_description_transport_params(session_description) }; } void validate_sdp_parameters(const web::json::value& receiver, const sdp_parameters& sdp_params) { const auto format = details::get_format(sdp_params); const auto media_type = details::get_media_type(sdp_params); if (nmos::format{ nmos::fields::format(receiver) } != format) throw details::sdp_processing_error("unexpected media type/encoding name"); const auto& caps = receiver.at(U("caps")); if (caps.has_field(U("media_types"))) { const auto& media_types = caps.at(U("media_types")).as_array(); const auto found = std::find(media_types.begin(), media_types.end(), web::json::value::string(media_type.name)); if (media_types.end() == found) throw details::sdp_processing_error("unsupported encoding name"); } } }
51.754098
231
0.612308
[ "object", "vector" ]
a9eb55be78ea6448e111494a32559a67bca0b1d0
1,056
hpp
C++
src/interfaces/trigger_factory.hpp
lxwinspur/telemetry
93064d8fcef2c6fde1f61c0cedacb46b21eab039
[ "Apache-2.0" ]
null
null
null
src/interfaces/trigger_factory.hpp
lxwinspur/telemetry
93064d8fcef2c6fde1f61c0cedacb46b21eab039
[ "Apache-2.0" ]
null
null
null
src/interfaces/trigger_factory.hpp
lxwinspur/telemetry
93064d8fcef2c6fde1f61c0cedacb46b21eab039
[ "Apache-2.0" ]
null
null
null
#pragma once #include "interfaces/json_storage.hpp" #include "interfaces/trigger.hpp" #include "interfaces/trigger_manager.hpp" #include "types/trigger_types.hpp" #include <boost/asio/spawn.hpp> #include <sdbusplus/message/types.hpp> #include <memory> #include <utility> namespace interfaces { class TriggerFactory { public: virtual ~TriggerFactory() = default; virtual std::unique_ptr<interfaces::Trigger> make( const std::string& name, bool isDiscrete, bool logToJournal, bool logToRedfish, bool updateReport, const std::vector<std::string>& reportNames, interfaces::TriggerManager& triggerManager, interfaces::JsonStorage& triggerStorage, const LabeledTriggerThresholdParams& labeledThresholdParams, const std::vector<LabeledSensorInfo>& labeledSensorsInfo) const = 0; virtual std::vector<LabeledSensorInfo> getLabeledSensorsInfo(boost::asio::yield_context& yield, const SensorsInfo& sensorsInfo) const = 0; }; } // namespace interfaces
28.540541
76
0.717803
[ "vector" ]
a9ec39a9d84d6900f0c312aba0f2e8e7371a0f43
1,487
cpp
C++
LinkedList/DeleteDuplicates2.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
LinkedList/DeleteDuplicates2.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
LinkedList/DeleteDuplicates2.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *deleteDuplicates(ListNode *A) { if (!A || !A->next) { return A; } ListNode *head = new ListNode(-1); head->next = A; ListNode *curr = head; ListNode *temp, *curr_inner; int val; while (curr->next->next != NULL) { if (curr->next->val == curr->next->next->val) { val = curr->next->val; while (val == curr->next->val && curr->next->next != NULL) { temp = curr->next->next; free(curr->next); curr->next = temp; } } else { curr = curr->next; } } if (val == curr->next->val) { free(curr->next); curr->next = NULL; } return A; } int main() { vector<int> v1{2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20}; ListNode *temp = new ListNode(v1[0]); ListNode *A = temp; ListNode *prevTemp = temp; for (int i = 1; i < v1.size(); i++) { temp = new ListNode(v1[i]); prevTemp->next = temp; prevTemp = temp; } ListNode *v2 = deleteDuplicates(A); cout << v2->val << endl; temp = v2; while (temp != NULL) { cout << temp->val << " "; temp = temp->next; } return 0; }
19.311688
279
0.511769
[ "vector" ]
a9ed3c5bf602891f2adbe935cce778116f1593a9
2,500
cc
C++
cpp/sudoku_check.cc
powernit/epicode
e81d4387d2ae442d21631dfc958690d424e1d84d
[ "MIT" ]
258
2016-07-18T03:28:15.000Z
2021-12-05T09:08:44.000Z
cpp/sudoku_check.cc
powernit/epicode
e81d4387d2ae442d21631dfc958690d424e1d84d
[ "MIT" ]
7
2016-08-13T22:12:29.000Z
2022-02-25T17:50:11.000Z
cpp/sudoku_check.cc
powernit/epicode
e81d4387d2ae442d21631dfc958690d424e1d84d
[ "MIT" ]
154
2016-07-18T06:29:24.000Z
2021-09-20T18:33:05.000Z
// Copyright (c) 2015 Elements of Programming Interviews. All rights reserved. #include <cassert> #include <cmath> #include <deque> #include <vector> using std::deque; using std::vector; bool HasDuplicate(const vector<vector<int>>&, int, int, int, int); // @include // Check if a partially filled matrix has any conflicts. bool IsValidSudoku(const vector<vector<int>>& partial_assignment) { // Check row constraints. for (int i = 0; i < partial_assignment.size(); ++i) { if (HasDuplicate(partial_assignment, i, i + 1, 0, partial_assignment.size())) { return false; } } // Check column constraints. for (int j = 0; j < partial_assignment.size(); ++j) { if (HasDuplicate(partial_assignment, 0, partial_assignment.size(), j, j + 1)) { return false; } } // Check region constraints. int region_size = sqrt(partial_assignment.size()); for (int I = 0; I < region_size; ++I) { for (int J = 0; J < region_size; ++J) { if (HasDuplicate(partial_assignment, region_size * I, region_size * (I + 1), region_size * J, region_size * (J + 1))) { return false; } } } return true; } // Return true if subarray partial_assignment[start_row : end_row - // 1][start_col : end_col - 1] contains any duplicates in {1, 2, ..., // partial_assignment.size()}; otherwise return false. bool HasDuplicate(const vector<vector<int>>& partial_assignment, int start_row, int end_row, int start_col, int end_col) { deque<bool> is_present(partial_assignment.size() + 1, false); for (int i = start_row; i < end_row; ++i) { for (int j = start_col; j < end_col; ++j) { if (partial_assignment[i][j] != 0 && is_present[partial_assignment[i][j]]) { return true; } is_present[partial_assignment[i][j]] = true; } } return false; } // @exclude int main(int argc, char* argv[]) { vector<vector<int>> A(9, vector<int>(9, 0)); A[0] = {0, 2, 6, 0, 0, 0, 8, 1, 0}; A[1] = {3, 0, 0, 7, 0, 8, 0, 0, 6}; A[2] = {4, 0, 0, 0, 5, 0, 0, 0, 7}; A[3] = {0, 5, 0, 1, 0, 7, 0, 9, 0}; A[4] = {0, 0, 3, 9, 0, 5, 1, 0, 0}; A[5] = {0, 4, 0, 3, 0, 2, 0, 5, 0}; A[6] = {1, 0, 0, 0, 3, 0, 0, 0, 2}; A[7] = {5, 0, 0, 2, 0, 4, 0, 0, 9}; A[8] = {0, 3, 8, 0, 0, 0, 4, 6, 0}; assert(IsValidSudoku(A)); // There are two 3s. A[8] = {3, 3, 8, 0, 0, 0, 4, 6, 0}; assert(!IsValidSudoku(A)); return 0; }
30.487805
78
0.5652
[ "vector" ]
a9ef187d746c236feeff429aee59e3d38e02cbb7
34,895
cc
C++
ggeo/GMaterialLib.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
11
2020-07-05T02:39:32.000Z
2022-03-20T18:52:44.000Z
ggeo/GMaterialLib.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
null
null
null
ggeo/GMaterialLib.cc
hanswenzel/opticks
b75b5929b6cf36a5eedeffb3031af2920f75f9f0
[ "Apache-2.0" ]
4
2020-09-03T20:36:32.000Z
2022-01-19T07:42:21.000Z
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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 <limits> #include <csignal> #include "SPath.hh" #include "BStr.hh" #include "BMeta.hh" #include "NPY.hpp" #include "Opticks.hh" #include "GDomain.hh" #include "GProperty.hh" #include "GPropertyMap.hh" #include "GMaterialLib.hh" #include "GMaterial.hh" #include "GItemList.hh" #include "GConstant.hh" #include "PLOG.hh" const plog::Severity GMaterialLib::LEVEL = PLOG::EnvLevel("GMaterialLib", "DEBUG") ; const GMaterialLib* GMaterialLib::INSTANCE = NULL ; const GMaterialLib* GMaterialLib::Get(){ return INSTANCE ; } bool GMaterialLib::IsUnset(unsigned index){ return GItemList::IsUnset(index) ; } // static const double GMaterialLib::MATERIAL_UNSET = 0.f ; const char* GMaterialLib::refractive_index = "refractive_index" ; const char* GMaterialLib::absorption_length = "absorption_length" ; const char* GMaterialLib::scattering_length = "scattering_length" ; const char* GMaterialLib::reemission_prob = "reemission_prob" ; const char* GMaterialLib::group_velocity = "group_velocity" ; const char* GMaterialLib::extra_y = "extra_y" ; const char* GMaterialLib::extra_z = "extra_z" ; const char* GMaterialLib::extra_w = "extra_w" ; const char* GMaterialLib::refractive_index_local = "RINDEX" ; const char* GMaterialLib::keyspec = "refractive_index:RINDEX," "absorption_length:ABSLENGTH," "scattering_length:RAYLEIGH," "reemission_prob:REEMISSIONPROB," "group_velocity:GROUPVEL," "extra_y:EXTRA_Y," "extra_z:EXTRA_Z," "extra_w:EXTRA_W," "detect:EFFICIENCY," ; /** m_keys = size=8 { [0] = "detect" [1] = "absorb" [2] = "reflect_specular" [3] = "reflect_diffuse" [4] = "extra_x" [5] = "extra_y" [6] = "extra_z" [7] = "extra_w" } **/ void GMaterialLib::save() { LOG(LEVEL) << "[" ; saveToCache(); LOG(LEVEL) << "]" ; } GMaterialLib* GMaterialLib::load(Opticks* ok) { GMaterialLib* mlib = new GMaterialLib(ok); mlib->loadFromCache(); mlib->postLoadFromCache(); return mlib ; } void GMaterialLib::postLoadFromCache() { bool nore = m_ok->hasOpt("nore") ; bool noab = m_ok->hasOpt("noab") ; bool nosc = m_ok->hasOpt("nosc") ; bool xxre = m_ok->hasOpt("xxre") ; bool xxab = m_ok->hasOpt("xxab") ; bool xxsc = m_ok->hasOpt("xxsc") ; bool fxre = m_ok->hasOpt("fxre") ; bool fxab = m_ok->hasOpt("fxab") ; bool fxsc = m_ok->hasOpt("fxsc") ; //bool groupvel = !m_ok->hasOpt("nogroupvel") ; LOG(LEVEL) << " nore " << nore << " noab " << noab << " nosc " << nosc << " xxre " << xxre << " xxab " << xxab << " xxsc " << xxsc << " fxre " << fxre << " fxab " << fxab << " fxsc " << fxsc // << " groupvel " << groupvel ; if(nore || xxre || fxre) { double reemission_prob = 0. ; if(nore) reemission_prob = 0. ; if(xxre) reemission_prob = 0.5 ; // not 1.0 in order to leave some AB, otherwise too unphysical if(fxre) reemission_prob = m_ok->getFxRe(); LOG(fatal) << "GMaterialLib::postLoadFromCache --nore/--xxre/--fxre option postCache modifying reemission_prob " ; setMaterialPropertyValues("GdDopedLS", "reemission_prob", reemission_prob ); setMaterialPropertyValues("LiquidScintillator", "reemission_prob", reemission_prob ); } if(noab || xxab || fxab) { double absorption_length = 0. ; if(noab) absorption_length = std::numeric_limits<double>::max() ; if(xxab) absorption_length = 100. ; if(fxab) absorption_length = m_ok->getFxAb(); LOG(fatal) << "GMaterialLib::postLoadFromCache --noab/--xxab/--fxab option postCache modifying absorption_length: " << absorption_length ; setMaterialPropertyValues("*", "absorption_length", absorption_length ); } if(nosc || xxsc || fxsc) { double scattering_length = 0. ; if(nosc) scattering_length = std::numeric_limits<double>::max() ; if(xxsc) scattering_length = 100.f ; if(fxsc) scattering_length = m_ok->getFxSc(); LOG(fatal) << "GMaterialLib::postLoadFromCache --nosc/--xxsc/--fxsc option postCache modifying scattering_length: " << scattering_length ; setMaterialPropertyValues("*", "scattering_length", scattering_length ); } /* TRYING TO MOVE THIS beforeClose if(groupvel) // unlike the other material changes : this one is ON by default, so long at not swiched off with --nogroupvel { bool debug = false ; replaceGROUPVEL(debug); } */ if(nore || noab || nosc || xxre || xxab || xxsc || fxre || fxsc || fxab ) { // need to replace the loaded buffer with a new one with the changes for Opticks to see it NPY<double>* mbuf = createBuffer(); setBuffer(mbuf); } } unsigned GMaterialLib::getNumMaterials() const { return m_materials.size(); } unsigned GMaterialLib::getNumRawMaterials() const { return m_materials_raw.size(); } GMaterialLib::GMaterialLib(Opticks* ok, GMaterialLib* basis) : GPropertyLib(ok, "GMaterialLib"), m_basis(basis), m_material_order(ORDER_BY_PREFERENCE) { init(); } GMaterialLib::GMaterialLib(GMaterialLib* src, GDomain<double>* domain, GMaterialLib* basis) // hmm think basis never used with this ctor ? : GPropertyLib(src, domain), m_basis(basis), m_material_order(ORDER_BY_PREFERENCE) { init(); initInterpolatingCopy(src, domain); } void GMaterialLib::init() { INSTANCE = this ; setKeyMap(keyspec); defineDefaults(getDefaults()); } void GMaterialLib::initInterpolatingCopy(GMaterialLib* src, GDomain<double>* domain) { unsigned nmat = src->getNumMaterials(); for(unsigned i=0 ; i < nmat ; i++) { GMaterial* smat = src->getMaterial(i); GMaterial* dmat = new GMaterial(smat, domain ); // interpolating "copy" ctor addDirect(dmat); } } void GMaterialLib::defineDefaults(GPropertyMap<double>* defaults) { defaults->addConstantProperty( refractive_index, 1. ); defaults->addConstantProperty( absorption_length, 1e6 ); defaults->addConstantProperty( scattering_length, 1e6 ); defaults->addConstantProperty( reemission_prob, 0. ); if(NUM_FLOAT4 > 1) { defaults->addConstantProperty( group_velocity, 300. ); defaults->addConstantProperty( extra_y, MATERIAL_UNSET ); defaults->addConstantProperty( extra_z, MATERIAL_UNSET ); defaults->addConstantProperty( extra_w, MATERIAL_UNSET ); } } const char* GMaterialLib::propertyName(unsigned int k) { assert(k < 4*NUM_FLOAT4); if(k == 0) return refractive_index ; if(k == 1) return absorption_length ; if(k == 2) return scattering_length ; if(k == 3) return reemission_prob ; if(NUM_FLOAT4 > 1) { if(k == 4) return group_velocity ; if(k == 5) return extra_y ; if(k == 6) return extra_z ; if(k == 7) return extra_w ; } return "?" ; } void GMaterialLib::Summary(const char* msg) const { LOG(info) << msg << " NumMaterials " << getNumMaterials() << " NumFloat4 " << NUM_FLOAT4 ; } /** GMaterialLib::add ------------------- A translated "standardized" material is added to the lib. **/ // invoked pre-cache by GGeo::add(GMaterial* material) AssimpGGeo::convertMaterials void GMaterialLib::add(GMaterial* mat) { bool has_efficiency = mat->hasProperty("EFFICIENCY") ; LOG(LEVEL) << " matname " << mat->getName() << " pre-count " << m_materials.size() << ( has_efficiency ? " WITH EFFICIENCY " : " " ) ; if(has_efficiency) { //setCathode(mat) ; addSensitiveMaterial(mat); } bool with_lowercase_efficiency = mat->hasProperty("efficiency") ; assert( !with_lowercase_efficiency ); assert(!isClosed()); m_materials.push_back(createStandardMaterial(mat)); } /** HMM: tis confusing the GPropertyLib base class has separate vectors of GPropertyMap<double> m_raw and m_raw_energy which have advantage of save/load into geocache with:: GPropertyLib::saveRaw GPropertyLib::saveRawEnergy This persisting is used by GScintillatorLib::save GScintillatorLib::load The only slight advantage with GMaterialLib::m_materials_raw and GMaterialLib::m_materials is that the vectors hold the higher level GMaterial pointers **/ void GMaterialLib::addRaw(GMaterial* mat) { m_materials_raw.push_back(mat); } void GMaterialLib::addDirect(GMaterial* mat) { assert(!isClosed()); m_materials.push_back(mat); } /** GMaterialLib::createStandardMaterial ------------------------------------- Standardization of material(and surface) properties is done to prepare these for inclusion into a GPU texture. Standardization involves: 1. selection of a subset of properties, namely: * refractive_index * absorption_length * scattering_length * reemission_prob * group_velocity 2. use of a common wavelength domain for all properties The subset of properties are the only properties needed on the GPU for the propagation. See also *GSurfaceLib* for analogous preparation of surface properties. Surface and material properties are interleaved together by *GBndLib* into the boundary array that *optixrap/OBndLib* uses to create the GPU "boundary texture". Scintillation properties SLOWCOMPONENT and FASTCOMPONENT are treated separately, they are used to construct the "reemission_texture", see GScintillatorLib. **/ GMaterial* GMaterialLib::createStandardMaterial(GMaterial* src) { assert(src); // materials must always be defined assert(src->isMaterial()); assert(getStandardDomain()->isEqual(src->getStandardDomain())); GMaterial* dst = new GMaterial(src); if(dst->hasStandardDomain()) { assert(dst->getStandardDomain()->isEqual(src->getStandardDomain())); } else { dst->setStandardDomain(src->getStandardDomain()); } dst->addPropertyStandardized(refractive_index, getPropertyOrDefault( src, refractive_index )); dst->addPropertyStandardized(absorption_length,getPropertyOrDefault( src, absorption_length )); dst->addPropertyStandardized(scattering_length,getPropertyOrDefault( src, scattering_length )); dst->addPropertyStandardized(reemission_prob ,getPropertyOrDefault( src, reemission_prob )); if(NUM_FLOAT4 > 1) { dst->addPropertyStandardized(group_velocity, getPropertyOrDefault( src, group_velocity)); dst->addPropertyStandardized(extra_y , getPropertyOrDefault( src, extra_y)); dst->addPropertyStandardized(extra_z , getPropertyOrDefault( src, extra_z)); dst->addPropertyStandardized(extra_w , getPropertyOrDefault( src, extra_w)); } return dst ; } /** GMaterialLib::operator() ------------------------- Defines the sort order of the materials based upon the order map keyed on the material short names. The reason to rearrange the order, is to get important materials at low indices to allow highly compressed step by step recording of millions of photons on GPU using only 4 bits to record the material index. **/ bool GMaterialLib::order_by_preference(const GMaterial& a_, const GMaterial& b_) { const char* a = a_.getShortName(); const char* b = b_.getShortName(); typedef std::map<std::string, unsigned> MSU ; MSU& order = getOrder(); MSU::const_iterator end = order.end() ; unsigned int ia = order.find(a) == end ? UINT_MAX : order[a] ; unsigned int ib = order.find(b) == end ? UINT_MAX : order[b] ; return ia < ib ; } bool GMaterialLib::order_by_srcidx(const GMaterial& a_, const GMaterial& b_) { // large default so test material additions which have no srcidx stay at the end int ia = a_.getMetaKV<int>("srcidx", "1000"); int ib = b_.getMetaKV<int>("srcidx", "1000"); return ia < ib ; } bool GMaterialLib::operator()(const GMaterial& a_, const GMaterial& b_) { bool order = false ; switch(m_material_order) { case ORDER_ASIS : assert(0) ; break ; case ORDER_BY_SRCIDX : order = order_by_srcidx(a_, b_) ; break ; case ORDER_BY_PREFERENCE : order = order_by_preference(a_, b_) ; break ; } return order ; } const char* GMaterialLib::ORDER_ASIS_ = "ORDER_ASIS" ; const char* GMaterialLib::ORDER_BY_SRCIDX_ = "ORDER_BY_SRCIDX" ; const char* GMaterialLib::ORDER_BY_PREFERENCE_ = "ORDER_BY_PREFERENCE" ; const char* GMaterialLib::getMaterialOrdering() const { const char* s = NULL ; switch(m_material_order) { case ORDER_ASIS : s = ORDER_ASIS_ ; break ; case ORDER_BY_SRCIDX : s = ORDER_BY_SRCIDX_ ; break ; case ORDER_BY_PREFERENCE : s = ORDER_BY_PREFERENCE_ ; break ; } return s ; } /** GMaterialLib::sort -------------------- This is invoked from the base when the proplib is closed. **/ void GMaterialLib::sort() { LOG(LEVEL) << getMaterialOrdering() ; if( m_material_order == ORDER_ASIS ) { return ; } else if( m_material_order == ORDER_BY_PREFERENCE ) { typedef std::map<std::string, unsigned> MSU ; MSU& order = getOrder(); if(order.size() == 0) return ; } std::stable_sort( m_materials.begin(), m_materials.end(), *this ); } GItemList* GMaterialLib::createNames() { GItemList* names = new GItemList(getType()); unsigned int ni = getNumMaterials(); for(unsigned int i=0 ; i < ni ; i++) { GMaterial* mat = m_materials[i] ; names->add(mat->getShortName()); } return names ; } unsigned int GMaterialLib::getMaterialIndex(const GMaterial* qmaterial) { unsigned int ni = getNumMaterials(); for(unsigned int i=0 ; i < ni ; i++) { GMaterial* mat = m_materials[i] ; if(mat == qmaterial) return i ; } return UINT_MAX ; } BMeta* GMaterialLib::createMeta() { LOG(LEVEL) << "[" ; BMeta* libmeta = new BMeta ; unsigned int ni = getNumMaterials(); std::vector<std::string> names ; for(unsigned int i=0 ; i < ni ; i++) { GMaterial* mat = m_materials[i] ; const char* name = mat->getShortName(); names.push_back(name); } BMeta* abbrevmeta = GPropertyLib::CreateAbbrevMeta(names); libmeta->setObj("abbrev", abbrevmeta ); LOG(LEVEL) << "]" ; return libmeta ; } NPY<double>* GMaterialLib::createBuffer() { return createBufferForTex2d<double>() ; } /** GMaterialLib::createBufferForTex2d ------------------------------------ 1. buffer is created of shape like (38, 2, 39, 4) where 38 is the number of materials 2. GProperty<double> values from the m_materials vector of GMaterial are copied into the buffer Memory layout of this buffer is constrained at one end by requirements of tex2d<float4> and at the other by matching the number of materials making it only possible to change in the middle number of groups. **/ template <typename T> NPY<T>* GMaterialLib::createBufferForTex2d() { unsigned int ni = getNumMaterials(); unsigned int nj = NUM_FLOAT4 ; unsigned int nk = getStandardDomain()->getLength(); unsigned int nl = 4 ; if(ni == 0 || nj == 0) { LOG(error) << "GMaterialLib::createBufferForTex2d" << " NO MATERIALS ? " << " ni " << ni << " nj " << nj ; return NULL ; } NPY<T>* mbuf = NPY<T>::make(ni, nj, nk, nl); // materials/payload-category/wavelength-samples/4prop mbuf->zero(); T* data = mbuf->getValues(); for(unsigned int i=0 ; i < ni ; i++) { GMaterial* mat = m_materials[i] ; GProperty<double> *p0,*p1,*p2,*p3 ; for(unsigned int j=0 ; j < nj ; j++) { p0 = mat->getPropertyByIndex(j*4+0); p1 = mat->getPropertyByIndex(j*4+1); p2 = mat->getPropertyByIndex(j*4+2); p3 = mat->getPropertyByIndex(j*4+3); for( unsigned int k = 0; k < nk; k++ ) // over wavelength-samples { unsigned int offset = i*nj*nk*nl + j*nk*nl + k*nl ; data[offset+0] = p0 ? T(p0->getValue(k)) : T(MATERIAL_UNSET) ; data[offset+1] = p1 ? T(p1->getValue(k)) : T(MATERIAL_UNSET) ; data[offset+2] = p2 ? T(p2->getValue(k)) : T(MATERIAL_UNSET) ; data[offset+3] = p3 ? T(p3->getValue(k)) : T(MATERIAL_UNSET) ; } } } return mbuf ; } void GMaterialLib::import() { if(m_buffer == NULL) { setValid(false); LOG(warning) << "GMaterialLib::import NULL buffer " ; return ; } if( m_buffer->getNumItems() != m_names->getNumKeys() ) { LOG(fatal) << "GMaterialLib::import numItems != numKeys " << " buffer numItems " << m_buffer->getNumItems() << " names numKeys " << m_names->getNumKeys() ; } assert( m_buffer->getNumItems() == m_names->getNumKeys() ); LOG(debug) << "GMaterialLib::import" << " buffer shape " << m_buffer->getShapeString() ; importForTex2d(); } /** GMaterialLib::importForTex2d ------------------------------ m_materials vector of GMaterial instances is reconstituted from the buffer (ni, nj, nk, nl) (38, 2, 39, 4) **/ void GMaterialLib::importForTex2d() { unsigned int ni = m_buffer->getShape(0); unsigned int nj = m_buffer->getShape(1); unsigned int nk = m_buffer->getShape(2); unsigned int nl = m_buffer->getShape(3); unsigned int domLen = m_standard_domain->getLength() ; bool expected = domLen == nk && nj == NUM_FLOAT4 && nl == 4 ; if(!expected ) LOG(fatal) << "GMaterialLib::importForTex2d" << " UNEXPECTED BUFFER SHAPE " << m_buffer->getShapeString() << " domLen " << domLen << " nk " << nk << " (recreate geocache by running with -G)" ; assert(expected); double* data = m_buffer->getValues(); for(unsigned int i=0 ; i < ni ; i++) { const char* key = m_names->getKey(i); LOG(debug) << std::setw(3) << i << " " << key ; GMaterial* mat = new GMaterial(key, i); for(unsigned int j=0 ; j < nj ; j++) // over the two groups { import(mat, data + i*nj*nk*nl + j*nk*nl, nk, nl , j); } m_materials.push_back(mat); } } void GMaterialLib::import( GMaterial* mat, double* data, unsigned nj, unsigned nk, unsigned jcat ) { double* domain = m_standard_domain->getValues(); for(unsigned k = 0 ; k < nk ; k++) // over 4 props of the float4 { double* values = new double[nj] ; for(unsigned j = 0 ; j < nj ; j++) values[j] = data[j*nk+k]; // un-interleaving GProperty<double>* prop = new GProperty<double>( values, domain, nj ); mat->addPropertyAsis(propertyName(k+4*jcat), prop); // not-standardizing as importing previously standardized (?) } } void GMaterialLib::beforeClose() { LOG(LEVEL) << "." ; bool debug = false ; replaceGROUPVEL(debug); } /** GMaterialLib::replaceGROUPVEL ------------------------------ Use the refractive index of each Opticks GMaterial to calculate the groupvel and replace the GROUPVEL property of the material. Huh : requiring the buffer is odd... it prevents invoking this before the close. Fixed this to not require the buffer so it can be invoked before saving to cache or after. **/ void GMaterialLib::replaceGROUPVEL(bool debug) { //unsigned ni = m_buffer->getShape(0); unsigned ni = getNumMaterials() ; // from the vector LOG(LEVEL) << "GMaterialLib::replaceGROUPVEL " << " ni " << ni ; const char* base = "$TMP/replaceGROUPVEL" ; if(debug) { LOG(warning) << "GMaterialLib::replaceGROUPVEL debug active : saving refractive_index.npy and group_velocity.npy beneath " << base ; } /* for(unsigned i=0 ; i < ni ; i++) std::cout << " i " << std::setw(2) << i << m_materials[i]->dump_ptr() << std::endl ; */ for(unsigned i=0 ; i < ni ; i++) { GMaterial* mat = getMaterial(i); assert( m_materials[i] == mat ); const char* key = mat->getName() ; GProperty<double>* vg = mat->getProperty(group_velocity); GProperty<double>* ri = mat->getProperty(refractive_index); assert(vg); assert(ri); GProperty<double>* vg_calc = GProperty<double>::make_GROUPVEL(ri); assert(vg_calc); LOG(verbose) << " i " << std::setw(2) << i << " n " << std::setw(2) << m_materials.size() << " mat " << mat << " vg " << vg << " ri " << ri << " vg_calc " << vg_calc << " k " << key ; double wldelta = 1e-4 ; vg->copyValuesFrom(vg_calc, wldelta); // <-- replacing the property inside the GMaterial instance if(debug) { LOG(info) << " i " << std::setw(3) << i << " key " << std::setw(35) << key << " vg " << vg << " vg_calc " << vg_calc ; dump(mat, "replaceGROUPVEL"); ri->save(base, key, "refractive_index.npy" ); vg_calc->save(base, key, "vg_calc.npy" ); vg->save(base, key, "group_velocity.npy" ); } } } bool GMaterialLib::setMaterialPropertyValues(const char* matname, const char* propname, double val) { bool ret = true ; if(matname && matname[0] == '*') { unsigned ni = m_buffer->getShape(0); LOG(info) << " wildcard GMaterialLib::setMaterialPropertyValues " << propname << " val " << val << " ni " << ni ; for(unsigned i=0 ; i < ni ; i++) { const char* key = m_names->getKey(i); GMaterial* mat = getMaterial(key); LOG(info) << " i " << std::setw(3) << i << " key " << std::setw(35) << key ; ret = mat->setPropertyValues( propname, val ); } } else { GMaterial* mat = getMaterial(matname); if(!mat) { LOG(fatal) << " no material with name " << matname ; assert(0); return false ; } ret = mat->setPropertyValues( propname, val ); assert(ret); } return ret ; } void GMaterialLib::dump(const char* msg) const { Summary(msg); unsigned int ni = getNumMaterials() ; int index = m_ok->getLastArgInt(); const char* lastarg = m_ok->getLastArg(); if(hasMaterial(index)) { dump(index); } else if(hasMaterial(lastarg)) { GMaterial* mat = getMaterial(lastarg); dump(mat); } else { for(unsigned int i=0 ; i < ni ; i++) dump(i); } } std::string GMaterialLib::desc() const { std::stringstream ss ; unsigned num_materials = getNumMaterials() ; ss << "GMaterialLib::desc NumMaterials " << num_materials << "[" << std::endl ; for(unsigned i=0 ; i < num_materials ; i++ ) { GMaterial* mat = getMaterial(i); ss << mat->description() << std::endl ; } ss << "]" ; std::string s = ss.str(); return s; } void GMaterialLib::dump(unsigned int index) const { GMaterial* mat = getMaterial(index); dump(mat); } // static void GMaterialLib::dump(GMaterial* mat) { dump(mat, mat->description().c_str()); } // static void GMaterialLib::dump( GMaterial* mat, const char* msg) { GProperty<double>* _refractive_index = mat->getProperty(refractive_index); GProperty<double>* _absorption_length = mat->getProperty(absorption_length); GProperty<double>* _scattering_length = mat->getProperty(scattering_length); GProperty<double>* _reemission_prob = mat->getProperty(reemission_prob); GProperty<double>* _group_velocity = mat->getProperty(group_velocity); unsigned int fw = 20 ; double dscale = 1.0f ; bool dreciprocal = false ; //f loat(GConstant::h_Planck*GConstant::c_light/GConstant::nanometer) ; // no need for scaling or taking reciprocal, as GMaterial domains // are already in nm std::string table = GProperty<double>::make_table( fw, dscale, dreciprocal, _refractive_index, refractive_index, _absorption_length, absorption_length, _scattering_length, scattering_length, _reemission_prob, reemission_prob, _group_velocity, group_velocity ); std::cout << table << std::endl ; LOG(warning) << msg << " " << mat->getName() ; } const char* GMaterialLib::getNameCheck(unsigned int i) { GMaterial* mat = getMaterial(i); const char* name1 = mat->getShortName(); const char* name2 = getName(i); assert(strcmp(name1, name2) == 0); return name1 ; } bool GMaterialLib::hasMaterial(const char* name) const { return getMaterial(name) != NULL ; } bool GMaterialLib::hasMaterial(unsigned int index) const { return getMaterial(index) != NULL ; } /* // this old way only works after closing geometry, or from loaded // as uses the names buffer GMaterial* GMaterialLib::getMaterial(const char* name) { unsigned int index = getIndex(name); return getMaterial(index); } */ // // NB cannot get a live index whilst still adding // as materials are priority order sorted on GPropertyLib::close // GMaterial* GMaterialLib::getMaterial(const char* name) const { if(!name) return NULL ; GMaterial* mat = NULL ; for(unsigned i=0 ; i < m_materials.size() ; i++) { GMaterial* m = m_materials[i] ; const char* mname = m->getName() ; assert( mname ) ; if( strcmp( mname, name ) == 0 ) { mat = m ; break ; } } return mat ; } GMaterial* GMaterialLib::getMaterial(unsigned int index) const { return index < m_materials.size() ? m_materials[index] : NULL ; } GMaterial* GMaterialLib::getMaterialWithIndex(unsigned aindex) const { GMaterial* mat = NULL ; for(unsigned int i=0 ; i < m_materials.size() ; i++ ) { if(m_materials[i]->getIndex() == aindex ) { mat = m_materials[i] ; break ; } } return mat ; } GPropertyMap<double>* GMaterialLib::findMaterial(const char* shortname) const { GMaterial* mat = NULL ; for(unsigned int i=0 ; i < m_materials.size() ; i++ ) { std::string sn = m_materials[i]->getShortNameString(); if(strcmp(sn.c_str(), shortname)==0) { mat = m_materials[i] ; break ; } } return (GPropertyMap<double>*)mat ; } GPropertyMap<double>* GMaterialLib::findRawMaterial(const char* shortname) const { GMaterial* mat = NULL ; for(unsigned int i=0 ; i < m_materials_raw.size() ; i++ ) { std::string sn = m_materials_raw[i]->getShortNameString(); //printf("GGeo::findRawMaterial %d %s \n", i, sn.c_str()); if(strcmp(sn.c_str(), shortname)==0) { mat = m_materials_raw[i] ; break ; } } return (GPropertyMap<double>*)mat ; } GProperty<double>* GMaterialLib::findRawMaterialProperty(const char* shortname, const char* propname) const { GPropertyMap<double>* mat = findRawMaterial(shortname); GProperty<double>* prop = mat->getProperty(propname); prop->Summary(); return prop ; } void GMaterialLib::dumpRawMaterialProperties(const char* msg) const { LOG(info) << msg ; for(unsigned int i=0 ; i < m_materials_raw.size() ; i++) { GMaterial* mat = m_materials_raw[i]; //mat->Summary(); std::cout << std::setw(30) << mat->getShortName() << " keys: " << mat->getKeysString() << std::endl ; } } std::vector<GMaterial*> GMaterialLib::getRawMaterialsWithProperties(const char* props, char delim) const { std::vector<std::string> elem ; BStr::split(elem, props, delim); LOG(LEVEL) << props << " m_materials_raw.size() " << m_materials_raw.size() ; std::vector<GMaterial*> selected ; for(unsigned int i=0 ; i < m_materials_raw.size() ; i++) { GMaterial* mat = m_materials_raw[i]; unsigned int found(0); for(unsigned int p=0 ; p < elem.size() ; p++) { if(mat->hasProperty(elem[p].c_str())) found+=1 ; } if(found == elem.size()) selected.push_back(mat); } return selected ; } GMaterial* GMaterialLib::getBasisMaterial(const char* name) const { return m_basis ? m_basis->getMaterial(name) : NULL ; } void GMaterialLib::reuseBasisMaterial(const char* name) { GMaterial* mat = getBasisMaterial(name); if(!mat) LOG(fatal) << "reuseBasisMaterial requires basis library to be present and to contain the material " << name ; assert( mat ); addDirect( mat ); } GMaterial* GMaterialLib::makeRaw(const char* name) { GMaterial* raw = new GMaterial(name, getNumMaterials() ); return raw ; } /** GMaterialLib::addTestMaterials -------------------------------- Invoked by:: GGeo::prepareMaterialLib GGeo::afterConvertMaterials AssimpGGeo::convert AssimpGGeo::load GGeo::loadFromG4DAE **/ void GMaterialLib::addTestMaterials() { //std::raise(SIGINT); typedef std::pair<std::string, std::string> SS ; typedef std::vector<SS> VSS ; VSS rix ; rix.push_back(SS("GlassSchottF2", "$OPTICKS_INSTALL_PREFIX/opticksaux/refractiveindex/tmp/glass/schott/F2.npy")); rix.push_back(SS("MainH2OHale", "$OPTICKS_INSTALL_PREFIX/opticksaux/refractiveindex/tmp/main/H2O/Hale.npy")); // NB when adding test materials also need to set in prefs ~/.opticks/GMaterialLib // // * priority order (for transparent materials arrange to be less than 16 for material sequence tracking) // * color // * two letter abbreviation // // for these settings to be acted upon must rebuild the geocache with : "ggv -G" // for(VSS::const_iterator it=rix.begin() ; it != rix.end() ; it++) { std::string name = it->first ; std::string path_ = it->second ; const char* path = SPath::Resolve(path_.c_str()); LOG(LEVEL) << " name " << std::setw(30) << name << " path " << path ; GProperty<double>* rif = GProperty<double>::AdjustLoad(path); if(!rif) continue ; GMaterial* raw = makeRaw(name.c_str()); raw->addPropertyStandardized( GMaterialLib::refractive_index_local, rif ); add(raw); } } /** GMaterialLib::addSensitiveMaterial ------------------------------------ Invoked by GMaterialLib::add with raw (non-standarized) materials. **/ void GMaterialLib::addSensitiveMaterial(GMaterial* mt) { bool added_already = std::find(m_sensitive_materials.begin(), m_sensitive_materials.end(), mt) != m_sensitive_materials.end() ; if(added_already) return ; bool is_sensitive = mt->hasNonZeroProperty("EFFICIENCY") ; LOG(LEVEL) << " add sensitive material " << " GMaterial : " << mt << " name : " << mt->getName() ; if(!is_sensitive) LOG(fatal) << " material does not have non-zero EFFICIENCY prop " << mt->getName() ; assert( is_sensitive ) ; m_sensitive_materials.push_back(mt); } unsigned GMaterialLib::getNumSensitiveMaterials() const { return m_sensitive_materials.size(); } GMaterial* GMaterialLib::getSensitiveMaterial(unsigned index) const { return m_sensitive_materials[index] ; } void GMaterialLib::dumpSensitiveMaterials(const char* msg) const { unsigned num_sensitive_materials = getNumSensitiveMaterials() ; LOG(info) << msg << " num_sensitive_materials " << num_sensitive_materials ; for(unsigned i=0 ; i < num_sensitive_materials ; i++) { GMaterial* mt = getSensitiveMaterial(i); std::cout << std::setw(2) << i << " : " << std::setw(30) << mt->getName() << std::endl ; } } #ifdef OLD_CATHODE void GMaterialLib::setCathode(GMaterial* cathode) { assert( cathode ) ; if( cathode && m_cathode && cathode == m_cathode ) { LOG(fatal) << " have already set that cathode GMaterial : " << cathode->getName() ; return ; } if( cathode && m_cathode && cathode != m_cathode ) { LOG(fatal) << " not expecting to change cathode GMaterial from " << m_cathode->getName() << " to " << cathode->getName() ; assert(0); } LOG(LEVEL) << " setting cathode " << " GMaterial : " << cathode << " name : " << cathode->getName() ; //cathode->Summary(); LOG(LEVEL) << cathode->prop_desc() ; assert( cathode->hasNonZeroProperty("EFFICIENCY") ); m_cathode = cathode ; m_cathode_material_name = strdup( cathode->getName() ) ; } GMaterial* GMaterialLib::getCathode() const { return m_cathode ; } const char* GMaterialLib::getCathodeMaterialName() const { return m_cathode_material_name ; } #endif
26.536122
147
0.600459
[ "geometry", "shape", "vector" ]
a9f08746ea4fc4323e15e7f2e78bcfdcda07d12d
7,215
cpp
C++
src/ofxGlyph.cpp
tcoppex/ofxFontSampler
65906f8b1694fab18a047c102ed944dba7e54496
[ "MIT" ]
2
2021-04-15T00:58:05.000Z
2021-04-15T01:35:08.000Z
src/ofxGlyph.cpp
tcoppex/ofxFontSampler
65906f8b1694fab18a047c102ed944dba7e54496
[ "MIT" ]
2
2021-04-17T00:05:30.000Z
2022-01-17T16:00:34.000Z
src/ofxGlyph.cpp
tcoppex/ofxFontSampler
65906f8b1694fab18a047c102ed944dba7e54496
[ "MIT" ]
1
2021-04-15T10:05:25.000Z
2021-04-15T10:05:25.000Z
#include "ofxGlyph.h" /* -------------------------------------------------------------------------- */ namespace { /* Return the normal of a segment. */ ofPoint CalculateNormal(const ofPoint &vertex0, const ofPoint &vertex1) { return (vertex1 - vertex0).rotate(90.0f, ofVec3f(0,0,-1)).normalize(); } }; // namespace /* -------------------------------------------------------------------------- */ ofxGlyph::ofxGlyph(Glyph *glyph) : fs_glyph_(glyph) , outer_path(nullptr) { // Find first outer path. for (int i = 0; i < fs_glyph_->getNumPaths(); ++i) { if (!fs_glyph_->isInnerPath(i)) { outer_path = fs_glyph_->getPath(i); break; } } } /* -------------------------------------------------------------------------- */ ofxGlyph::~ofxGlyph() { if (fs_glyph_) { delete fs_glyph_; } } /* -------------------------------------------------------------------------- */ ofPoint ofxGlyph::getMinBound() const { const auto &v = outer_path->getMinBound(); return ofPoint(v.x, v.y); } /* -------------------------------------------------------------------------- */ ofPoint ofxGlyph::getMaxBound() const { const auto &v = outer_path->getMaxBound(); return ofPoint(v.x, v.y); } /* -------------------------------------------------------------------------- */ ofPoint ofxGlyph::getCentroid() const { const auto &v = outer_path->getCentroid(); return ofPoint(v.x, v.y); } /* -------------------------------------------------------------------------- */ void ofxGlyph::extractPath(ofPath &path) const { path.clear(); for (int i = 0; i < fs_glyph_->getNumPaths(); ++i) { const auto &gp = fs_glyph_->getPath(i); const bool is_inner = fs_glyph_->isInnerPath(i); const int inc = (is_inner) ? -1 : +1; // first vertex { vertex_t v(gp->getVertex(0)); GlyphPath::FlagBits flag(gp->getFlag(0)); if (flag & GlyphPath::ON_CURVE) { path.moveTo(v.x, v.y, 0.0f); } } // rest of the curve bool next_point_on_curve = false; for (int i = 0; i < gp->getNumVertices(); i += (next_point_on_curve) ? 1 : 2) { const int i0 = ofWrap(inc*i, 0, gp->getNumVertices()); const int i1 = ofWrap(i0 + inc, 0, gp->getNumVertices()); const int i2 = ofWrap(i1 + inc, 0, gp->getNumVertices()); const vertex_t &v0(gp->getVertex(i0)); const vertex_t &v1(gp->getVertex(i1)); const vertex_t &v2(gp->getVertex(i2)); const GlyphPath::FlagBits &f1(gp->getFlag(i1)); if (f1 & GlyphPath::ON_CURVE) { path.lineTo(v1.x, v1.y, 0.0f); next_point_on_curve = true; } else { path.quadBezierTo( v0.x, v0.y, 0.0f, v1.x, v1.y, 0.0f, v2.x, v2.y, 0.0f ); next_point_on_curve = false; } } path.close(); } } /* -------------------------------------------------------------------------- */ void ofxGlyph::extractMeshData( int subsamples, bool enable_segments_sampling, std::vector<glm::vec3> &vertices, std::vector<glm::ivec2> &segments, std::vector<glm::vec3> &holes ) { vertices.clear(); segments.clear(); holes.clear(); int first_index = 0; int vertex_index = first_index; for (int i = 0; i < fs_glyph_->getNumPaths(); ++i) { GlyphPath::Sampling_t sampling; auto const *path(fs_glyph_->getPath(i)); path->sample( sampling, subsamples, enable_segments_sampling ); ofPoint centroid(0.0f, 0.0f); const int num_vertices = sampling.vertices.size(); for (const auto& v : sampling.vertices) { // Vertex. ofPoint vertex(v.x, v.y); vertices.push_back(vertex); centroid += vertex; // Segment indices. const int next_index = first_index + (vertex_index+1 - first_index) % num_vertices; segments.push_back(glm::ivec2(vertex_index++, next_index)); } centroid *= 1.0f / num_vertices; first_index = vertex_index; // Holes. if (fs_glyph_->isInnerPath(i)) { holes.push_back(centroid); } else { outer_sampling_ = sampling; } } } /* -------------------------------------------------------------------------- */ void ofxGlyph::constructContourPolyline( int samples, ofPolyline &pl ) const { const float sampling_step = 1.0f / samples; pl.clear(); for (int i = 0; i < samples; ++i) { const float t = i * sampling_step; const auto v = outer_sampling_.evaluate(t); ofPoint vertex(v.x, v.y); pl.addVertex(vertex); } pl.addVertex(pl.getVertices()[0]); } /* -------------------------------------------------------------------------- */ void ofxGlyph::extractMeshData( int subsamples, bool enable_segments_sampling, std::vector<glm::vec3> &vertices, std::vector<glm::ivec2> &segments, std::vector<glm::vec3> &holes, int gradient_step, updateVertexFunc_t updateVertex ) { extractMeshData(subsamples, enable_segments_sampling, vertices, segments, holes); std::vector<glm::vec3> points(vertices.size()); int prev_vertex_index = -1; int first_vertex_index = -1; int last_vertex_index = -1; // Postprocess the vertex data using a custome gradient functor. const int num_segments = static_cast<int>(segments.size()); for (int i = 0; i < num_segments; ++i) { const auto &s = segments[i]; // if new path : look for the last segment looping the path. if (prev_vertex_index != s.x) { first_vertex_index = s.x; int j; for (j=i+1; segments[j].y != first_vertex_index; ++j); last_vertex_index = segments[j].x; } prev_vertex_index = s.y; // Calculate normal. const int i0 = ofWrap(s.x-gradient_step, first_vertex_index, last_vertex_index); const int i1 = ofWrap(s.x+gradient_step, first_vertex_index, last_vertex_index); const auto normal = CalculateNormal(vertices[i0], vertices[i1]); points[i] = vertices[s.x]; updateVertex(points[i], s.x, normal); } std::swap(vertices, points);// = points; } /* -------------------------------------------------------------------------- */ void ofxGlyph::constructContourPolyline( int samples, ofPolyline &pl, float gradient_step_factor, updateVertexFunc_t updateVertex ) { const float sampling_step = 1.0f / samples; const float gradient_sampling_step = gradient_step_factor * sampling_step; pl.clear(); for (int i = 0; i < samples; ++i) { const float t = i * sampling_step; // Calculate normal. const auto v0 = outer_sampling_.evaluate(t - gradient_sampling_step); const auto v1 = outer_sampling_.evaluate(t + gradient_sampling_step); const ofPoint vertex0(v0.x, v0.y); const ofPoint vertex1(v1.x, v1.y); const ofPoint normal = CalculateNormal(vertex0, vertex1); const vertex_t& v = outer_sampling_.evaluate(t); auto vertex = glm::vec3(v.x, v.y, 0); updateVertex(vertex, i, normal); pl.addVertex(vertex); } // Close the polyline. pl.addVertex(pl.getVertices()[0]); } /* -------------------------------------------------------------------------- */
27.643678
89
0.538739
[ "vector" ]
a9f29f850581731f3b0f2b66033b853609c73121
11,583
cpp
C++
source/HybridManager2.cpp
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
1
2020-06-27T18:43:36.000Z
2020-06-27T18:43:36.000Z
source/HybridManager2.cpp
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/HybridManager2.cpp
cxwx/VecGeom
c86c00bd7d4db08f4fc20a625020da329784aaac
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * HybridManager.cpp * * Created on: 03.08.2015 * Author: yang.zhang@cern.ch */ #include "VecGeom/management/HybridManager2.h" #include "VecGeom/volumes/LogicalVolume.h" #include "VecGeom/volumes/PlacedVolume.h" #include "VecGeom/management/GeoManager.h" #include "VecGeom/management/ABBoxManager.h" #include "VecGeom/base/SOA3D.h" #include "VecGeom/volumes/utilities/VolumeUtilities.h" #include <map> #include <vector> #include <sstream> #include <queue> #include <set> namespace vecgeom { inline namespace VECGEOM_IMPL_NAMESPACE { void HybridManager2::InitStructure(LogicalVolume const *lvol) { auto numregisteredlvols = GeoManager::Instance().GetRegisteredVolumesCount(); if (fStructureHolder.size() != numregisteredlvols) { fStructureHolder.resize(numregisteredlvols, nullptr); } if (fStructureHolder[lvol->id()] != nullptr) { RemoveStructure(lvol); } BuildStructure_v(lvol); } /** * build bvh bruteforce AND vectorized */ void HybridManager2::BuildStructure_v(LogicalVolume const *vol) { // for a logical volume we are referring to the functions that builds everything giving just bounding // boxes int nDaughters{0}; // get the boxes (and number of boxes), must be called before the BuildStructure // function call since otherwise nDaughters is not guaranteed to be initialized auto boxes = ABBoxManager::Instance().GetABBoxes(vol, nDaughters); auto structure = BuildStructure(boxes, nDaughters); fStructureHolder[vol->id()] = structure; assert((int)vol->GetDaughters().size() == nDaughters); assert(structure == nullptr || structure->fNumberOfOriginalBoxes != 0); } /** * build bvh bruteforce AND vectorized */ HybridManager2::HybridBoxAccelerationStructure *HybridManager2::BuildStructure(ABBoxManager::ABBoxContainer_t abboxes, size_t numberofdaughters) const { if (numberofdaughters == 0) return nullptr; constexpr auto kVS = vecCore::VectorSize<HybridManager2::Float_v>(); size_t numberOfFirstLevelNodes = numberofdaughters / kVS + (numberofdaughters % kVS == 0 ? 0 : 1); size_t vectorsize = numberOfFirstLevelNodes / kVS + (numberOfFirstLevelNodes % kVS == 0 ? 0 : 1) + numberOfFirstLevelNodes; std::vector<std::vector<int>> clusters(numberOfFirstLevelNodes); SOA3D<Precision> centers(numberOfFirstLevelNodes); SOA3D<Precision> allvolumecenters(numberofdaughters); InitClustersWithKMeans(abboxes, numberofdaughters, clusters, centers, allvolumecenters); // EqualizeClusters(clusters, centers, allvolumecenters, HybridManager2::vecCore::VectorSize<Float_v>()); HybridBoxAccelerationStructure *structure = new HybridBoxAccelerationStructure(); using VectorOfInts = std::vector<int>; // to avoid clang-format error structure->fNodeToDaughters = new VectorOfInts[numberOfFirstLevelNodes]; ABBoxContainer_v boxes_v = new ABBox_v[vectorsize * 2]; for (size_t i = 0; i < numberOfFirstLevelNodes; ++i) { for (size_t d = 0; d < clusters[i].size(); ++d) { int daughterIndex = clusters[i][d]; structure->fNodeToDaughters[i].push_back(daughterIndex); } } // init boxes_v to -inf int vectorindex_v = 0; for (size_t i = 0; i < vectorsize * 2; i++) { boxes_v[i] = -InfinityLength<typename HybridManager2::Float_v>(); } // init internal nodes for vectorized for (size_t i = 0; i < numberOfFirstLevelNodes; ++i) { if (i % kVS == 0) { vectorindex_v += 2; } Vector3D<Precision> lowerCornerFirstLevelNode(kInfLength), upperCornerFirstLevelNode(-kInfLength); for (size_t d = 0; d < clusters[i].size(); ++d) { int daughterIndex = clusters[i][d]; Vector3D<Precision> lowerCorner = abboxes[2 * daughterIndex]; Vector3D<Precision> upperCorner = abboxes[2 * daughterIndex + 1]; using vecCore::AssignLane; AssignLane(boxes_v[vectorindex_v].x(), d, lowerCorner.x()); AssignLane(boxes_v[vectorindex_v].y(), d, lowerCorner.y()); AssignLane(boxes_v[vectorindex_v].z(), d, lowerCorner.z()); AssignLane(boxes_v[vectorindex_v + 1].x(), d, upperCorner.x()); AssignLane(boxes_v[vectorindex_v + 1].y(), d, upperCorner.y()); AssignLane(boxes_v[vectorindex_v + 1].z(), d, upperCorner.z()); for (int axis = 0; axis < 3; axis++) { lowerCornerFirstLevelNode[axis] = std::min(lowerCornerFirstLevelNode[axis], lowerCorner[axis]); upperCornerFirstLevelNode[axis] = std::max(upperCornerFirstLevelNode[axis], upperCorner[axis]); } } vectorindex_v += 2; // insert internal node ABBOX in boxes_v int indexForInternalNode = i / kVS; indexForInternalNode = 2 * (kVS + 1) * indexForInternalNode; int offsetForInternalNode = i % kVS; using vecCore::AssignLane; AssignLane(boxes_v[indexForInternalNode].x(), offsetForInternalNode, lowerCornerFirstLevelNode.x()); AssignLane(boxes_v[indexForInternalNode].y(), offsetForInternalNode, lowerCornerFirstLevelNode.y()); AssignLane(boxes_v[indexForInternalNode].z(), offsetForInternalNode, lowerCornerFirstLevelNode.z()); AssignLane(boxes_v[indexForInternalNode + 1].x(), offsetForInternalNode, upperCornerFirstLevelNode.x()); AssignLane(boxes_v[indexForInternalNode + 1].y(), offsetForInternalNode, upperCornerFirstLevelNode.y()); AssignLane(boxes_v[indexForInternalNode + 1].z(), offsetForInternalNode, upperCornerFirstLevelNode.z()); } structure->fNumberOfOriginalBoxes = numberofdaughters; structure->fABBoxes_v = boxes_v; return structure; } void HybridManager2::RemoveStructure(LogicalVolume const *lvol) { // FIXME: take care of memory deletion within acceleration structure if (fStructureHolder[lvol->id()]) delete fStructureHolder[lvol->id()]; } /** * assign daughter volumes to its closest cluster using the cluster centers stored in centers. * clusters need to be empty before this function is called */ void HybridManager2::AssignVolumesToClusters(std::vector<std::vector<int>> &clusters, SOA3D<Precision> const &centers, SOA3D<Precision> const &allvolumecenters) { assert(centers.size() == clusters.size()); int numberOfDaughers = allvolumecenters.size(); int numberOfClusters = clusters.size(); Precision minDistance; int closestCluster; for (int d = 0; d < numberOfDaughers; d++) { minDistance = kInfLength; closestCluster = -1; Precision dist; for (int c = 0; c < numberOfClusters; ++c) { dist = (allvolumecenters[d] - centers[c]).Length2(); if (dist < minDistance) { minDistance = dist; closestCluster = c; } } clusters.at(closestCluster).push_back(d); } } void HybridManager2::RecalculateCentres(SOA3D<Precision> &centers, SOA3D<Precision> const &allvolumecenters, std::vector<std::vector<int>> const &clusters) { assert(centers.size() == clusters.size()); auto numberOfClusters = centers.size(); for (size_t c = 0; c < numberOfClusters; ++c) { Vector3D<Precision> newCenter(0); for (size_t clustersize = 0; clustersize < clusters[c].size(); ++clustersize) { int daughterIndex = clusters[c][clustersize]; newCenter += allvolumecenters[daughterIndex]; } newCenter /= clusters[c].size(); centers.set(c, newCenter); } } template <typename Container_t> void HybridManager2::InitClustersWithKMeans(ABBoxManager::ABBoxContainer_t boxes, int numberOfDaughters, Container_t &clusters, SOA3D<Precision> &centers, SOA3D<Precision> &allvolumecenters, int const numberOfIterations) const { int numberOfClusters = clusters.size(); Vector3D<Precision> meanCenter(0); std::set<int> daughterSet; for (int i = 0; i < numberOfDaughters; ++i) { Vector3D<Precision> center = 0.5 * (boxes[2 * i] + boxes[2 * i + 1]); allvolumecenters.set(i, center); daughterSet.insert(i); meanCenter += allvolumecenters[i]; } meanCenter /= numberOfDaughters; size_t clustersize = (numberOfDaughters + numberOfClusters - 1) / numberOfClusters; for (int clusterindex = 0; clusterindex < numberOfClusters && !daughterSet.empty(); ++clusterindex) { Vector3D<Precision> clusterMean(0); while (clusters[clusterindex].size() < clustersize) { // parametrized lambda used in std::max_element + std::min_element below auto sortlambda = [&](Vector3D<Precision> const &center) { return [&, center](int a, int b) { return (allvolumecenters[a] - center).Mag2() < (allvolumecenters[b] - center).Mag2(); }; }; int addDaughter = clusters[clusterindex].size() == 0 ? *std::max_element(daughterSet.begin(), daughterSet.end(), sortlambda(meanCenter)) : *std::min_element(daughterSet.begin(), daughterSet.end(), sortlambda(clusterMean)); daughterSet.erase(addDaughter); clusters[clusterindex].emplace_back(addDaughter); if (daughterSet.empty()) break; meanCenter = (meanCenter * (daughterSet.size() + 1) - allvolumecenters[addDaughter]) / daughterSet.size(); clusterMean = (clusterMean * (clusters[clusterindex].size() - 1) + allvolumecenters[addDaughter]) / clusters[clusterindex].size(); } // end while } } template <typename Container_t> void HybridManager2::EqualizeClusters(Container_t &clusters, SOA3D<Precision> &centers, SOA3D<Precision> const &allvolumecenters, size_t const maxNodeSize) { // clusters need to be sorted size_t numberOfClusters = clusters.size(); sort(clusters, IsBiggerCluster); for (size_t c = 0; c < numberOfClusters; ++c) { size_t clustersize = clusters[c].size(); if (clustersize > maxNodeSize) { RecalculateCentres(centers, allvolumecenters, clusters); distanceQueue clusterelemToCenterMap; // pairs of index of elem in cluster and distance to cluster center for (size_t clusterElem = 0; clusterElem < clustersize; ++clusterElem) { Precision distance2 = (centers[c] - allvolumecenters[clusters[c][clusterElem]]).Length2(); clusterelemToCenterMap.push(std::make_pair(clusters[c][clusterElem], distance2)); } while (clusters[c].size() > maxNodeSize) { // int daughterIndex = clusters[c][it]; int daughterIndex = clusterelemToCenterMap.top().first; clusterelemToCenterMap.pop(); distanceQueue clusterToCenterMap2; for (size_t nextclusterIndex = c + 1; nextclusterIndex < numberOfClusters; nextclusterIndex++) { if (clusters[nextclusterIndex].size() < maxNodeSize) { Precision distanceToOtherCenters = (centers[nextclusterIndex] - allvolumecenters[daughterIndex]).Length2(); clusterToCenterMap2.push(std::make_pair(nextclusterIndex, -distanceToOtherCenters)); } } // find nearest cluster to daughterIndex clusters[c].erase(std::find(clusters[c].begin(), clusters[c].end(), daughterIndex)); clusters[clusterToCenterMap2.top().first].push_back(daughterIndex); // RecalculateCentres(centers, allvolumecenters, clusters); } std::sort(clusters.begin() + c + 1, clusters.end(), IsBiggerCluster); } } } VPlacedVolume const *HybridManager2::PrintHybrid(LogicalVolume const *lvol) const { return 0; } } // namespace VECGEOM_IMPL_NAMESPACE } // namespace vecgeom
41.967391
119
0.684624
[ "vector" ]
a9f76c03323c9b3769e25b4cbcacb6e3fac2962f
2,336
cpp
C++
graph/bridge_finding_with_tarjan_algorithm.cpp
aneee004/C-Plus-Plus
c959c3dc467c879b33f16aa1fd8bcd2d5931d1de
[ "MIT" ]
1
2020-12-04T11:25:46.000Z
2020-12-04T11:25:46.000Z
graph/bridge_finding_with_tarjan_algorithm.cpp
Sahil-k1509/C-Plus-Plus
1fb344c627872e61227bd7976a152efe2691d6ce
[ "MIT" ]
null
null
null
graph/bridge_finding_with_tarjan_algorithm.cpp
Sahil-k1509/C-Plus-Plus
1fb344c627872e61227bd7976a152efe2691d6ce
[ "MIT" ]
1
2020-12-13T08:47:49.000Z
2020-12-13T08:47:49.000Z
/* * Copyright : 2020 , MIT * Author : Amit Kumar (offamitkumar) * Last Modified Date: May 24, 2020 * */ #include <algorithm> // for min & max #include <iostream> // for cout #include <vector> // for std::vector class Solution { std::vector<std::vector<int>> graph; std::vector<int> in_time, out_time; int timer = 0; std::vector<std::vector<int>> bridge; std::vector<bool> visited; void dfs(int current_node, int parent) { visited.at(current_node) = true; in_time[current_node] = out_time[current_node] = timer++; for (auto& itr : graph[current_node]) { if (itr == parent) { continue; } if (!visited[itr]) { dfs(itr, current_node); if (out_time[itr] > in_time[current_node]) { bridge.push_back({itr, current_node}); } } out_time[current_node] = std::min(out_time[current_node], out_time[itr]); } } public: std::vector<std::vector<int>> search_bridges( int n, const std::vector<std::vector<int>>& connections) { timer = 0; graph.resize(n); in_time.assign(n, 0); visited.assign(n, false); out_time.assign(n, 0); for (auto& itr : connections) { graph.at(itr[0]).push_back(itr[1]); graph.at(itr[1]).push_back(itr[0]); } dfs(0, -1); return bridge; } }; /** * Main function */ int main() { Solution s1; int number_of_node = 5; std::vector<std::vector<int>> node; node.push_back({0, 1}); node.push_back({1, 3}); node.push_back({1, 2}); node.push_back({2, 4}); /* * 0 <--> 1 <---> 2 * ^ ^ * | | * | | * \/ \/ * 3 4 * * In this graph there are 4 bridges [0,2] , [2,4] , [3,5] , [1,2] * * I assumed that the graph is bi-directional and connected. * */ std::vector<std::vector<int>> bridges = s1.search_bridges(number_of_node, node); std::cout << bridges.size() << " bridges found!\n"; for (auto& itr : bridges) { std::cout << itr[0] << " --> " << itr[1] << '\n'; } return 0; }
28.144578
85
0.490154
[ "vector" ]
a9fc540bce1a5aef012b73c88fef365b98a6812c
39,202
cpp
C++
Source/BodyState/Private/BodyStateAnimInstance.cpp
getnamo/BodyState-ue4
085ee80e0eeed2e4a5a0c6c082aad61a6f9a9cbf
[ "MIT" ]
7
2016-03-14T14:04:57.000Z
2018-05-16T05:43:00.000Z
Source/BodyState/Private/BodyStateAnimInstance.cpp
getnamo/BodyState-ue4
085ee80e0eeed2e4a5a0c6c082aad61a6f9a9cbf
[ "MIT" ]
1
2016-05-25T15:10:20.000Z
2016-05-25T15:10:20.000Z
Source/BodyState/Private/BodyStateAnimInstance.cpp
getnamo/BodyState-ue4
085ee80e0eeed2e4a5a0c6c082aad61a6f9a9cbf
[ "MIT" ]
5
2016-10-10T12:06:14.000Z
2020-02-05T15:13:19.000Z
/************************************************************************************************************************************* *The MIT License(MIT) * *Copyright(c) 2016 Jan Kaniewski(Getnamo) *Modified work Copyright(C) 2019 - 2021 Ultraleap, Inc. * *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 "BodyStateAnimInstance.h" #include "BodyStateBPLibrary.h" #include "BodyStateUtility.h" #include "Kismet/KismetMathLibrary.h" #if WITH_EDITOR #include "Misc/MessageDialog.h" #include "PersonaUtils.h" #endif // static FName UBodyStateAnimInstance::GetBoneNameFromRef(const FBPBoneReference& BoneRef) { return BoneRef.MeshBone.BoneName; } UBodyStateAnimInstance::UBodyStateAnimInstance(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { // Defaults DefaultBodyStateIndex = 0; bIncludeMetaCarpels = true; AutoMapTarget = EBodyStateAutoRigType::HAND_LEFT; } void UBodyStateAnimInstance::AddBSBoneToMeshBoneLink( UPARAM(ref) FMappedBoneAnimData& InMappedBoneData, EBodyStateBasicBoneType BSBone, FName MeshBone) { FBoneReference BoneRef; BoneRef.BoneName = MeshBone; BoneRef.Initialize(CurrentSkeleton); FBPBoneReference MeshBPBone; MeshBPBone.MeshBone = BoneRef; InMappedBoneData.BoneMap.Add(BSBone, MeshBPBone); SyncMappedBoneDataCache(InMappedBoneData); } void UBodyStateAnimInstance::RemoveBSBoneLink(UPARAM(ref) FMappedBoneAnimData& InMappedBoneData, EBodyStateBasicBoneType BSBone) { InMappedBoneData.BoneMap.Remove(BSBone); SyncMappedBoneDataCache(InMappedBoneData); } void UBodyStateAnimInstance::SetAnimSkeleton(UBodyStateSkeleton* InSkeleton) { for (auto& Map : MappedBoneList) { Map.BodyStateSkeleton = InSkeleton; // Re-cache our results SyncMappedBoneDataCache(Map); } } TMap<EBodyStateBasicBoneType, FBPBoneReference> UBodyStateAnimInstance::AutoDetectHandBones( USkeletalMeshComponent* Component, EBodyStateAutoRigType RigTargetType, bool& Success, TArray<FString>& FailedBones) { auto IndexedMap = AutoDetectHandIndexedBones(Component, RigTargetType, Success, FailedBones); return ToBoneReferenceMap(IndexedMap); } FRotator UBodyStateAnimInstance::AdjustRotationByMapBasis(const FRotator& InRotator, const FMappedBoneAnimData& ForMap) { const FRotator Temp = FBodyStateUtility::CombineRotators(ForMap.PreBaseRotation, InRotator); return FBodyStateUtility::CombineRotators(Temp, ForMap.OffsetTransform.Rotator()); } FVector UBodyStateAnimInstance::AdjustPositionByMapBasis(const FVector& InPosition, const FMappedBoneAnimData& ForMap) { return ForMap.OffsetTransform.GetRotation().RotateVector(InPosition); } FString UBodyStateAnimInstance::BoneMapSummary() { FString Result = TEXT("+== Bone Summary ==+"); // Concatenate indexed bones for (auto Bone : IndexedBoneMap) { FBodyStateIndexedBone& IndexedBone = Bone.Value; Result += FString::Printf( TEXT("BoneString: %s:%d(%d)\n"), *IndexedBone.BoneName.ToString(), IndexedBone.Index, IndexedBone.ParentIndex); } return Result; } void UBodyStateAnimInstance::SyncMappedBoneDataCache(UPARAM(ref) FMappedBoneAnimData& InMappedBoneData) { InMappedBoneData.SyncCachedList(CurrentSkeleton); } ////////////// /////Protected // Local data only used for auto-mapping algorithm struct FChildIndices { int32 Index; TArray<int32> ChildIndices; }; struct FIndexParentsCount { TArray<FChildIndices> ParentsList; int32 FindCount(int32 ParentIndex) { int32 DidFindIndex = -1; for (int32 i = 0; i < ParentsList.Num(); i++) { if (ParentsList[i].Index == ParentIndex) { return i; } } return DidFindIndex; } // run after filling our index TArray<int32> FindParentsWithCount(int32 Count) { TArray<int32> ResultArray; for (auto Parent : ParentsList) { if (Parent.ChildIndices.Num() == Count) { ResultArray.Add(Parent.Index); } } return ResultArray; } }; int32 UBodyStateAnimInstance::SelectFirstBone(const TArray<FString>& Definitions) { TArray<int32> IndicesFound = SelectBones(Definitions); if (IndicesFound.Num()) { return IndicesFound[0]; } else { return -1; } } TArray<int32> UBodyStateAnimInstance::SelectBones(const TArray<FString>& Definitions) { TArray<int32> BoneIndicesFound; for (auto& Definition : Definitions) { for (auto& Bone : BoneLookupList.SortedBones) { const FString& CompareString = Bone.BoneName.ToString().ToLower(); if (CompareString.Contains(Definition)) { BoneIndicesFound.Add(Bone.Index); } } } return BoneIndicesFound; } TMap<EBodyStateBasicBoneType, FBodyStateIndexedBone> UBodyStateAnimInstance::AutoDetectHandIndexedBones( USkeletalMeshComponent* Component, EBodyStateAutoRigType HandType, bool& Success, TArray<FString>& FailedBones) { TMap<EBodyStateBasicBoneType, FBodyStateIndexedBone> AutoBoneMap; Success = true; if (Component == nullptr) { return AutoBoneMap; } // Get bones and parent indices USkeletalMesh* SkeletalMesh = Component->SkeletalMesh; #if ENGINE_MAJOR_VERSION >= 5 || (ENGINE_MAJOR_VERSION >= 4 && ENGINE_MINOR_VERSION >= 27) FReferenceSkeleton& RefSkeleton = SkeletalMesh->GetRefSkeleton(); #else FReferenceSkeleton& RefSkeleton = SkeletalMesh->RefSkeleton; #endif // Finger roots int32 ThumbBone = InvalidBone; int32 IndexBone = InvalidBone; int32 MiddleBone = InvalidBone; int32 RingBone = InvalidBone; int32 PinkyBone = InvalidBone; // Re-organize our bone information BoneLookupList.SetFromRefSkeleton(RefSkeleton, bUseSortedBoneNames); int32 WristBone = InvalidBone; int32 LowerArmBone = InvalidBone; WristBone = SelectFirstBone(SearchNames.WristNames); LowerArmBone = SelectFirstBone(SearchNames.ArmNames); ThumbBone = SelectFirstBone(SearchNames.ThumbNames); IndexBone = SelectFirstBone(SearchNames.IndexNames); MiddleBone = SelectFirstBone(SearchNames.MiddleNames); RingBone = SelectFirstBone(SearchNames.RingNames); PinkyBone = SelectFirstBone(SearchNames.PinkyNames); int32 LongestChildTraverse = NoMetaCarpelsFingerBoneCount; if (IndexBone > InvalidBone) { LongestChildTraverse = BoneLookupList.LongestChildTraverseForBone(BoneLookupList.TreeIndexFromSortedIndex(IndexBone)); } int32 BonesPerFinger = LongestChildTraverse + 1; // allow the user to turn off metacarpels if (!bIncludeMetaCarpels) { BonesPerFinger = NoMetaCarpelsFingerBoneCount; } // UE_LOG(LogTemp, Log, TEXT("T:%d, I:%d, M: %d, R: %d, P: %d"), ThumbBone, IndexBone, MiddleBone, RingBone, PinkyBone); // Based on the passed hand type map the indexed bones to our EBodyStateBasicBoneType enums if (HandType == EBodyStateAutoRigType::HAND_LEFT) { if (LowerArmBone >= 0) { AutoBoneMap.Add(EBodyStateBasicBoneType::BONE_LOWERARM_L, BoneLookupList.SortedBones[LowerArmBone]); } if (WristBone >= 0) { AutoBoneMap.Add(EBodyStateBasicBoneType::BONE_HAND_WRIST_L, BoneLookupList.SortedBones[WristBone]); } if (ThumbBone >= 0) { // Thumbs will always be ~ 3 bones AddFingerToMap(EBodyStateBasicBoneType::BONE_THUMB_0_METACARPAL_L, ThumbBone, AutoBoneMap); } if (IndexBone >= 0) { if (BonesPerFinger > NoMetaCarpelsFingerBoneCount) { AddFingerToMap(EBodyStateBasicBoneType::BONE_INDEX_0_METACARPAL_L, IndexBone, AutoBoneMap, BonesPerFinger); } else { AddFingerToMap(EBodyStateBasicBoneType::BONE_INDEX_1_PROXIMAL_L, IndexBone, AutoBoneMap); } } if (MiddleBone >= 0) { if (BonesPerFinger > NoMetaCarpelsFingerBoneCount) { AddFingerToMap(EBodyStateBasicBoneType::BONE_MIDDLE_0_METACARPAL_L, MiddleBone, AutoBoneMap, BonesPerFinger); } else { AddFingerToMap(EBodyStateBasicBoneType::BONE_MIDDLE_1_PROXIMAL_L, MiddleBone, AutoBoneMap); } } if (RingBone >= 0) { if (BonesPerFinger > NoMetaCarpelsFingerBoneCount) { AddFingerToMap(EBodyStateBasicBoneType::BONE_RING_0_METACARPAL_L, RingBone, AutoBoneMap, BonesPerFinger); } else { AddFingerToMap(EBodyStateBasicBoneType::BONE_RING_1_PROXIMAL_L, RingBone, AutoBoneMap); } } if (PinkyBone >= 0) { if (BonesPerFinger > NoMetaCarpelsFingerBoneCount) { AddFingerToMap(EBodyStateBasicBoneType::BONE_PINKY_0_METACARPAL_L, PinkyBone, AutoBoneMap, BonesPerFinger); } else { AddFingerToMap(EBodyStateBasicBoneType::BONE_PINKY_1_PROXIMAL_L, PinkyBone, AutoBoneMap); } } } // Right Hand else { if (LowerArmBone >= 0) { AutoBoneMap.Add(EBodyStateBasicBoneType::BONE_LOWERARM_R, BoneLookupList.SortedBones[LowerArmBone]); } if (WristBone >= 0) { AutoBoneMap.Add(EBodyStateBasicBoneType::BONE_HAND_WRIST_R, BoneLookupList.SortedBones[WristBone]); } if (ThumbBone >= 0) { // Thumbs will always be ~ 3 bones AddFingerToMap(EBodyStateBasicBoneType::BONE_THUMB_0_METACARPAL_R, ThumbBone, AutoBoneMap); } if (IndexBone >= 0) { if (BonesPerFinger > NoMetaCarpelsFingerBoneCount) { AddFingerToMap(EBodyStateBasicBoneType::BONE_INDEX_0_METACARPAL_R, IndexBone, AutoBoneMap, BonesPerFinger); } else { AddFingerToMap(EBodyStateBasicBoneType::BONE_INDEX_1_PROXIMAL_R, IndexBone, AutoBoneMap); } } if (MiddleBone >= 0) { if (BonesPerFinger > NoMetaCarpelsFingerBoneCount) { AddFingerToMap(EBodyStateBasicBoneType::BONE_MIDDLE_0_METACARPAL_R, MiddleBone, AutoBoneMap, BonesPerFinger); } else { AddFingerToMap(EBodyStateBasicBoneType::BONE_MIDDLE_1_PROXIMAL_R, MiddleBone, AutoBoneMap); } } if (RingBone >= 0) { if (BonesPerFinger > NoMetaCarpelsFingerBoneCount) { AddFingerToMap(EBodyStateBasicBoneType::BONE_RING_0_METACARPAL_R, RingBone, AutoBoneMap, BonesPerFinger); } else { AddFingerToMap(EBodyStateBasicBoneType::BONE_RING_1_PROXIMAL_R, RingBone, AutoBoneMap); } } if (PinkyBone >= 0) { if (BonesPerFinger > NoMetaCarpelsFingerBoneCount) { AddFingerToMap(EBodyStateBasicBoneType::BONE_PINKY_0_METACARPAL_R, PinkyBone, AutoBoneMap, BonesPerFinger); } else { AddFingerToMap(EBodyStateBasicBoneType::BONE_PINKY_1_PROXIMAL_R, PinkyBone, AutoBoneMap); } } } // failure states, it's common not find an arm so don't flag that as fail to map if (IndexBone < 0 || RingBone < 0 || PinkyBone < 0 || MiddleBone < 0 || ThumbBone < 0 || WristBone < 0) { if (IndexBone < 0) { FailedBones.Add("Index"); } if (RingBone < 0) { FailedBones.Add("Ring"); } if (MiddleBone < 0) { FailedBones.Add("Middle"); } if (PinkyBone < 0) { FailedBones.Add("Pinky"); } if (ThumbBone < 0) { FailedBones.Add("Thumb"); } if (WristBone < 0) { FailedBones.Add("Wrist"); } } // create empty skeleton for easy config if (AutoBoneMap.Num() < 2) { UE_LOG(LogTemp, Log, TEXT("Auto mapping bone names - Cannot automatically find any bones, please manually map them")); Success = false; CreateEmptyBoneMap(AutoBoneMap, HandType); } return AutoBoneMap; } void UBodyStateAnimInstance::CreateEmptyBoneMap( TMap<EBodyStateBasicBoneType, FBodyStateIndexedBone>& AutoBoneMap, const EBodyStateAutoRigType HandType) { static const int BonesPerFinger = 4; if (HandType == EBodyStateAutoRigType::HAND_LEFT) { AutoBoneMap.Add(EBodyStateBasicBoneType::BONE_LOWERARM_L, FBodyStateIndexedBone()); AutoBoneMap.Add(EBodyStateBasicBoneType::BONE_HAND_WRIST_L, FBodyStateIndexedBone()); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_THUMB_0_METACARPAL_L, AutoBoneMap); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_INDEX_0_METACARPAL_L, AutoBoneMap, BonesPerFinger); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_MIDDLE_0_METACARPAL_L, AutoBoneMap, BonesPerFinger); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_RING_0_METACARPAL_L, AutoBoneMap, BonesPerFinger); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_PINKY_0_METACARPAL_L, AutoBoneMap, BonesPerFinger); } else { AutoBoneMap.Add(EBodyStateBasicBoneType::BONE_LOWERARM_R, FBodyStateIndexedBone()); AutoBoneMap.Add(EBodyStateBasicBoneType::BONE_HAND_WRIST_R, FBodyStateIndexedBone()); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_THUMB_0_METACARPAL_R, AutoBoneMap); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_INDEX_0_METACARPAL_R, AutoBoneMap, BonesPerFinger); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_MIDDLE_0_METACARPAL_R, AutoBoneMap, BonesPerFinger); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_RING_0_METACARPAL_R, AutoBoneMap, BonesPerFinger); AddEmptyFingerToMap(EBodyStateBasicBoneType::BONE_PINKY_0_METACARPAL_R, AutoBoneMap, BonesPerFinger); } } FQuat LookRotation(const FVector& lookAt, const FVector& upDirection) { FVector forward = lookAt; FVector up = upDirection; forward = forward.GetSafeNormal(); up = up - (forward * FVector::DotProduct(up, forward)); up = up.GetSafeNormal(); /////////////////////// FVector vector = forward.GetSafeNormal(); FVector vector2 = FVector::CrossProduct(up, vector); FVector vector3 = FVector::CrossProduct(vector, vector2); float m00 = vector2.X; float m01 = vector2.Y; float m02 = vector2.Z; float m10 = vector3.X; float m11 = vector3.Y; float m12 = vector3.Z; float m20 = vector.X; float m21 = vector.Y; float m22 = vector.Z; float num8 = (m00 + m11) + m22; FQuat quaternion = FQuat(); if (num8 > 0.0f) { float num = (float) FMath::Sqrt(num8 + 1.0f); quaternion.W = num * 0.5f; num = 0.5f / num; quaternion.X = (m12 - m21) * num; quaternion.Y = (m20 - m02) * num; quaternion.Z = (m01 - m10) * num; return (quaternion); } if ((m00 >= m11) && (m00 >= m22)) { float num7 = (float) FMath::Sqrt(((1.0f + m00) - m11) - m22); float num4 = 0.5f / num7; quaternion.X = 0.5f * num7; quaternion.Y = (m01 + m10) * num4; quaternion.Z = (m02 + m20) * num4; quaternion.W = (m12 - m21) * num4; return (quaternion); } if (m11 > m22) { float num6 = (float) FMath::Sqrt(((1.0f + m11) - m00) - m22); float num3 = 0.5f / num6; quaternion.X = (m10 + m01) * num3; quaternion.Y = 0.5f * num6; quaternion.Z = (m21 + m12) * num3; quaternion.W = (m20 - m02) * num3; return (quaternion); } float num5 = (float) FMath::Sqrt(((1.0f + m22) - m00) - m11); float num2 = 0.5f / num5; quaternion.X = (m20 + m02) * num2; quaternion.Y = (m21 + m12) * num2; quaternion.Z = 0.5f * num5; quaternion.W = (m01 - m10) * num2; return quaternion; } /* Find an orthonormal basis for the set of vectors q * using the Gram-Schmidt Orthogonalization process */ void OrthoNormalize2(TArray<FVector>& Vectors) { int i, j; for (i = 1; i < Vectors.Num(); ++i) { for (j = 0; j < i; ++j) { double scaling_factor = FVector::DotProduct(Vectors[j], Vectors[i]) / FVector::DotProduct(Vectors[j], Vectors[j]); /* Subtract each scaled component of q_j from q_i */ Vectors[i] -= scaling_factor * Vectors[j]; } } /* Now normalize all the 'n' orthogonal vectors */ for (i = 0; i < Vectors.Num(); ++i) { Vectors[i].Normalize(); } } void OrthNormalize2(FVector& Normal, FVector& Tangent, FVector& Binormal) { TArray<FVector> Vectors = {Normal, Tangent, Binormal}; OrthoNormalize2(Vectors); Normal = Vectors[0]; Tangent = Vectors[1]; Binormal = Vectors[2]; } FTransform UBodyStateAnimInstance::GetTransformFromBoneEnum(const FMappedBoneAnimData& ForMap, const EBodyStateBasicBoneType BoneType, const TArray<FName>& Names, const TArray<FNodeItem>& NodeItems, bool& BoneFound) const { FBoneReference Bone = ForMap.BoneMap.Find(BoneType)->MeshBone; int Index = Names.Find(Bone.BoneName); BoneFound = false; if (Index > InvalidBone) { BoneFound = true; return NodeItems[Index].Transform; } return FTransform(); } FTransform UBodyStateAnimInstance::GetTransformFromBoneEnum(const FMappedBoneAnimData& ForMap, const EBodyStateBasicBoneType BoneType, const TArray<FName>& Names, const TArray<FTransform>& ComponentSpaceTransforms, bool& BoneFound) const { FBoneReference Bone = ForMap.BoneMap.Find(BoneType)->MeshBone; int Index = Names.Find(Bone.BoneName); BoneFound = false; if (Index > InvalidBone && Index < ComponentSpaceTransforms.Num()) { BoneFound = true; return ComponentSpaceTransforms[Index]; } return FTransform(); } FTransform UBodyStateAnimInstance::GetCurrentWristPose( const FMappedBoneAnimData& ForMap, const EBodyStateAutoRigType RigTargetType) const { FTransform Ret; USkeletalMeshComponent* Component = GetSkelMeshComponent(); // Get bones and parent indices USkeletalMesh* SkeletalMesh = Component->SkeletalMesh; TArray<FName> Names; TArray<FNodeItem> NodeItems; INodeMappingProviderInterface* INodeMapping = Cast<INodeMappingProviderInterface>(SkeletalMesh); if (!INodeMapping) { UE_LOG(LogTemp, Log, TEXT("UBodyStateAnimInstance::GetCurrentWristPose INodeMapping is NULL so cannot proceed")); return Ret; } INodeMapping->GetMappableNodeData(Names, NodeItems); EBodyStateBasicBoneType Wrist = EBodyStateBasicBoneType::BONE_HAND_WRIST_L; if (RigTargetType == EBodyStateAutoRigType::HAND_RIGHT) { Wrist = EBodyStateBasicBoneType::BONE_HAND_WRIST_R; } bool WristBoneFound = false; Ret = GetTransformFromBoneEnum(ForMap, Wrist, Names, NodeItems, WristBoneFound); return Ret; } // for debugging only, calcs debug rotations normalized for Unity (has no effect on the main path through the code) #define DEBUG_ROTATIONS_AS_UNITY 0 #if DEBUG_ROTATIONS_AS_UNITY // useful for comparing with Unity when debugging (unused) void Normalize360(FRotator& InPlaceRot) { if (InPlaceRot.Yaw < 0) { InPlaceRot.Yaw += 360; } if (InPlaceRot.Pitch < 0) { InPlaceRot.Pitch += 360; } if (InPlaceRot.Roll < 0) { InPlaceRot.Roll += 360; } } #endif // DEBUG_ROTATIONS_AS_UNITY // based on the logic in HandBinderAutoBinder.cs from the Unity Hand Modules. void UBodyStateAnimInstance::EstimateAutoMapRotation(FMappedBoneAnimData& ForMap, const EBodyStateAutoRigType RigTargetType) { USkeletalMeshComponent* Component = GetSkelMeshComponent(); const TArray<FTransform>& ComponentSpaceTransforms = Component->GetComponentSpaceTransforms(); // Get bones and parent indices USkeletalMesh* SkeletalMesh = Component->SkeletalMesh; TArray<FName> Names; TArray<FNodeItem> NodeItems; INodeMappingProviderInterface* INodeMapping = Cast<INodeMappingProviderInterface>(SkeletalMesh); if (!INodeMapping) { UE_LOG(LogTemp, Log, TEXT("UBodyStateAnimInstance::EstimateAutoMapRotation INodeMapping is NULL so cannot proceed")); return; } INodeMapping->GetMappableNodeData(Names, NodeItems); EBodyStateBasicBoneType Index = EBodyStateBasicBoneType::BONE_INDEX_1_PROXIMAL_L; EBodyStateBasicBoneType Middle = EBodyStateBasicBoneType::BONE_MIDDLE_1_PROXIMAL_L; EBodyStateBasicBoneType Pinky = EBodyStateBasicBoneType::BONE_PINKY_1_PROXIMAL_L; EBodyStateBasicBoneType Wrist = EBodyStateBasicBoneType::BONE_HAND_WRIST_L; if (RigTargetType == EBodyStateAutoRigType::HAND_RIGHT) { Index = EBodyStateBasicBoneType::BONE_INDEX_1_PROXIMAL_R; Middle = EBodyStateBasicBoneType::BONE_MIDDLE_1_PROXIMAL_R; Pinky = EBodyStateBasicBoneType::BONE_PINKY_1_PROXIMAL_R; Wrist = EBodyStateBasicBoneType::BONE_HAND_WRIST_R; } auto RefIndex = ForMap.BoneMap.Find(Index); if (!RefIndex) { ForMap.AutoCorrectRotation = FQuat(FRotator(ForceInitToZero)); UE_LOG(LogTemp, Log, TEXT("UBodyStateAnimInstance::EstimateAutoMapRotation Cannot find the index bone")); return; } FBoneReference IndexBone = RefIndex->MeshBone; bool IndexBoneFound = false; bool MiddleBoneFound = false; bool PinkyBoneFound = false; bool WristBoneFound = false; FTransform IndexPose = GetTransformFromBoneEnum(ForMap, Index, Names, ComponentSpaceTransforms, IndexBoneFound); FTransform MiddlePose = GetTransformFromBoneEnum(ForMap, Middle, Names, ComponentSpaceTransforms, MiddleBoneFound); FTransform PinkyPose = GetTransformFromBoneEnum(ForMap, Pinky, Names, ComponentSpaceTransforms, PinkyBoneFound); FTransform WristPose = GetTransformFromBoneEnum(ForMap, Wrist, Names, ComponentSpaceTransforms, WristBoneFound); if (!(IndexBoneFound && MiddleBoneFound && PinkyBoneFound && WristBoneFound)) { ForMap.AutoCorrectRotation = FQuat(FRotator(ForceInitToZero)); UE_LOG(LogTemp, Log, TEXT("UBodyStateAnimInstance::EstimateAutoMapRotation Cannot find all finger bones")); return; } FBoneReference Bone = ForMap.BoneMap.Find(Wrist)->MeshBone; // Calculate the Model's rotation // direct port from c# Unity version HandBinderAutoBinder.cs FVector Forward = MiddlePose.GetLocation() - WristPose.GetLocation(); FVector Right = IndexPose.GetLocation() - PinkyPose.GetLocation(); if (RigTargetType == EBodyStateAutoRigType::HAND_RIGHT) { Right = -Right; } FVector Up = FVector::CrossProduct(Forward, Right); // we need a three param version of this. OrthNormalize2(Forward, Up, Right); // in Unity this was Quat.LookRotation(forward,up). FQuat ModelRotation; ModelRotation = LookRotation(Forward, Up); // In unity, this came from the wrist in the world/scene coords FQuat WristPoseQuat(WristPose.GetRotation()); #if DEBUG_ROTATIONS_AS_UNITY // debug FRotator WristSourceRotation = WristPose.GetRotation().Rotator(); Normalize360(WristSourceRotation); FRotator ModelDebugRotation = ModelRotation.Rotator(); Normalize360(ModelDebugRotation); // end debug #endif // DEBUG_ROTATIONS_AS_UNITY FRotator WristRotation = (ModelRotation.Inverse() * WristPoseQuat).Rotator(); #if DEBUG_ROTATIONS_AS_UNITY FRotator WristDebugRotation = WristRotation; Normalize360(WristDebugRotation); #endif // DEBUG_ROTATIONS_AS_UNITY // correct to UE space as defined by control hands if (ForMap.FlipModelLeftRight) { WristRotation += FRotator(-90, 0, -180); } else { WristRotation += FRotator(90, 0, 0); } #if DEBUG_ROTATIONS_AS_UNITY WristDebugRotation = WristRotation; Normalize360(WristDebugRotation); #endif // DEBUG_ROTATIONS_AS_UNITY ForMap.AutoCorrectRotation = FQuat(WristRotation); } float UBodyStateAnimInstance::CalculateElbowLength(const FMappedBoneAnimData& ForMap, const EBodyStateAutoRigType RigTargetType) { float ElbowLength = 0; USkeletalMeshComponent* Component = GetSkelMeshComponent(); // Get bones and parent indices USkeletalMesh* SkeletalMesh = Component->SkeletalMesh; TArray<FName> Names; TArray<FNodeItem> NodeItems; INodeMappingProviderInterface* INodeMapping = Cast<INodeMappingProviderInterface>(SkeletalMesh); if (!INodeMapping) { UE_LOG(LogTemp, Log, TEXT("UBodyStateAnimInstance::EstimateAutoMapRotation INodeMapping is NULL so cannot proceed")); return 0; } INodeMapping->GetMappableNodeData(Names, NodeItems); EBodyStateBasicBoneType LowerArm = EBodyStateBasicBoneType::BONE_LOWERARM_L; EBodyStateBasicBoneType Wrist = EBodyStateBasicBoneType::BONE_HAND_WRIST_L; if (RigTargetType == EBodyStateAutoRigType::HAND_RIGHT) { LowerArm = EBodyStateBasicBoneType::BONE_LOWERARM_R; Wrist = EBodyStateBasicBoneType::BONE_HAND_WRIST_R; } FBoneReference LowerArmBone; const FBPBoneReference* MapRef = ForMap.BoneMap.Find(LowerArm); if (MapRef) { LowerArmBone = MapRef->MeshBone; } FBoneReference WristBone; MapRef = ForMap.BoneMap.Find(Wrist); if (MapRef) { WristBone = MapRef->MeshBone; } int32 LowerArmBoneIndex = Names.Find(LowerArmBone.BoneName); int32 WristBoneIndex = Names.Find(WristBone.BoneName); if (LowerArmBoneIndex > InvalidBone && WristBoneIndex > InvalidBone) { FTransform LowerArmPose = NodeItems[LowerArmBoneIndex].Transform; FTransform WristPose = NodeItems[WristBoneIndex].Transform; ElbowLength = FVector::Distance(WristPose.GetLocation(), LowerArmPose.GetLocation()); } return ElbowLength; } void UBodyStateAnimInstance::AutoMapBoneDataForRigType( FMappedBoneAnimData& ForMap, EBodyStateAutoRigType RigTargetType, bool& Success, TArray<FString>& FailedBones) { // Grab our skel mesh component USkeletalMeshComponent* Component = GetSkelMeshComponent(); IndexedBoneMap = AutoDetectHandIndexedBones(Component, RigTargetType, Success, FailedBones); auto OldMap = ForMap.BoneMap; ForMap.BoneMap = ToBoneReferenceMap(IndexedBoneMap); // Default preset rotations - Note order is different than in BP if (ForMap.PreBaseRotation.IsNearlyZero()) { if (RigTargetType == EBodyStateAutoRigType::HAND_LEFT) { ForMap.PreBaseRotation = FRotator(0, 0, -90); } else if (RigTargetType == EBodyStateAutoRigType::HAND_RIGHT) { ForMap.PreBaseRotation = FRotator(0, 180, 90); } } ForMap.ElbowLength = CalculateElbowLength(ForMap, RigTargetType); // Reset specified keys from defaults /*for (auto Pair : OldMap) { Pair.Value.MeshBone.Initialize(CurrentSkeleton); ForMap.BoneMap.Add(Pair.Key, Pair.Value); }*/ } int32 UBodyStateAnimInstance::TraverseLengthForIndex(int32 Index) { if (Index == InvalidBone || Index >= BoneLookupList.Bones.Num()) { return 0; // this is the root or invalid bone } else { FBodyStateIndexedBone& Bone = BoneLookupList.Bones[Index]; // Add our parent traversal + 1 return TraverseLengthForIndex(Bone.ParentIndex) + 1; } } void UBodyStateAnimInstance::AddEmptyFingerToMap(EBodyStateBasicBoneType BoneType, TMap<EBodyStateBasicBoneType, FBodyStateIndexedBone>& BoneMap, int32 InBonesPerFinger /*= BonesPerFinger*/) { int32 FingerRoot = (int32) BoneType; BoneMap.Add(EBodyStateBasicBoneType(FingerRoot), FBodyStateIndexedBone()); BoneMap.Add(EBodyStateBasicBoneType(FingerRoot + 1), FBodyStateIndexedBone()); BoneMap.Add(EBodyStateBasicBoneType(FingerRoot + 2), FBodyStateIndexedBone()); if (InBonesPerFinger > NoMetaCarpelsFingerBoneCount) { BoneMap.Add(EBodyStateBasicBoneType(FingerRoot + 3), FBodyStateIndexedBone()); } } void UBodyStateAnimInstance::AddFingerToMap(EBodyStateBasicBoneType BoneType, int32 BoneIndex, TMap<EBodyStateBasicBoneType, FBodyStateIndexedBone>& BoneMap, int32 InBonesPerFinger /*= BonesPerFinger*/) { int32 FingerRoot = (int32) BoneType; BoneMap.Add(EBodyStateBasicBoneType(FingerRoot), BoneLookupList.SortedBones[BoneIndex]); BoneMap.Add(EBodyStateBasicBoneType(FingerRoot + 1), BoneLookupList.SortedBones[BoneIndex + 1]); BoneMap.Add(EBodyStateBasicBoneType(FingerRoot + 2), BoneLookupList.SortedBones[BoneIndex + 2]); if (InBonesPerFinger > NoMetaCarpelsFingerBoneCount) { BoneMap.Add(EBodyStateBasicBoneType(FingerRoot + 3), BoneLookupList.SortedBones[BoneIndex + 3]); } } TMap<EBodyStateBasicBoneType, FBPBoneReference> UBodyStateAnimInstance::ToBoneReferenceMap( TMap<EBodyStateBasicBoneType, FBodyStateIndexedBone> InIndexedMap) { TMap<EBodyStateBasicBoneType, FBPBoneReference> ReferenceMap; for (auto BonePair : IndexedBoneMap) { FBPBoneReference BoneBPReference; FBoneReference BoneReference; BoneReference.BoneName = BonePair.Value.BoneName; BoneReference.Initialize(CurrentSkeleton); BoneBPReference.MeshBone = BoneReference; ReferenceMap.Add(BonePair.Key, BoneBPReference); } return ReferenceMap; } void UBodyStateAnimInstance::HandleLeftRightFlip(const FMappedBoneAnimData& ForMap) { // the user can manually specify that the model is flipped (left to right or right to left) // Setting the scale on the component flips the view // if we do this here, the anim preview works as well as in scene and in actors USkeletalMeshComponent* Component = GetSkelMeshComponent(); if (!Component) { return; } if (ForMap.FlipModelLeftRight) { Component->SetRelativeScale3D(FVector(1, 1, -1)); // Unreal doesn't deal with mirrored scale when in comes to updating the mesh bounds // this means that at 1 bounds scale, the skeletel mesh gets occluded as the bounds are not following the skeleton // Until this is fixed in the engine, we have to force the bounds to be huge to always render. Component->SetBoundsScale(10); } else { Component->SetRelativeScale3D(FVector(1, 1, 1)); Component->SetBoundsScale(1); } } void UBodyStateAnimInstance::NativeInitializeAnimation() { Super::NativeInitializeAnimation(); // Get our default bodystate skeleton UBodyStateSkeleton* Skeleton = UBodyStateBPLibrary::SkeletonForDevice(this, 0); SetAnimSkeleton(Skeleton); // One hand mapping if (AutoMapTarget != EBodyStateAutoRigType::BOTH_HANDS) { if (MappedBoneList.Num() > 0) { FMappedBoneAnimData& OneHandMap = MappedBoneList[0]; HandleLeftRightFlip(OneHandMap); if (bDetectHandRotationDuringAutoMapping) { EstimateAutoMapRotation(OneHandMap, AutoMapTarget); } else { OneHandMap.AutoCorrectRotation = FQuat(FRotator(ForceInitToZero)); } } } else { // Make two maps if missing if (MappedBoneList.Num() > 1) { // Map one hand each FMappedBoneAnimData& LeftHandMap = MappedBoneList[0]; FMappedBoneAnimData& RightHandMap = MappedBoneList[1]; HandleLeftRightFlip(LeftHandMap); HandleLeftRightFlip(RightHandMap); if (bDetectHandRotationDuringAutoMapping) { EstimateAutoMapRotation(LeftHandMap, EBodyStateAutoRigType::HAND_LEFT); EstimateAutoMapRotation(RightHandMap, EBodyStateAutoRigType::HAND_RIGHT); } else { RightHandMap.AutoCorrectRotation = LeftHandMap.AutoCorrectRotation = FQuat(FRotator(ForceInitToZero)); } } } // Cache all results if (BodyStateSkeleton == nullptr) { BodyStateSkeleton = UBodyStateBPLibrary::SkeletonForDevice(this, 0); SetAnimSkeleton(BodyStateSkeleton); // this will sync all the bones } else { for (auto& BoneMap : MappedBoneList) { SyncMappedBoneDataCache(BoneMap); } } } void UBodyStateAnimInstance::NativeUpdateAnimation(float DeltaSeconds) { Super::NativeUpdateAnimation(DeltaSeconds); // SN: may want to optimize this at some pt if (BodyStateSkeleton == nullptr) { BodyStateSkeleton = UBodyStateBPLibrary::SkeletonForDevice(this, 0); SetAnimSkeleton(BodyStateSkeleton); } if (BodyStateSkeleton) { BodyStateSkeleton->bTrackingActive = !bFreezeTracking; IsTracking = CalcIsTracking(); } } // static const FName& UBodyStateAnimInstance::GetMeshBoneNameFromCachedBoneLink(const FCachedBoneLink& CachedBoneLink) { return CachedBoneLink.MeshBone.BoneName; } // do not call this from the anim thread bool UBodyStateAnimInstance::CalcIsTracking() { if (!BodyStateSkeleton) { return false; } bool Ret = false; switch (AutoMapTarget) { case EBodyStateAutoRigType::HAND_LEFT: { Ret = BodyStateSkeleton->LeftArm()->Hand->Wrist->IsTracked(); } break; case EBodyStateAutoRigType::HAND_RIGHT: { Ret = BodyStateSkeleton->RightArm()->Hand->Wrist->IsTracked(); } break; case EBodyStateAutoRigType::BOTH_HANDS: { Ret = BodyStateSkeleton->LeftArm()->Hand->Wrist->IsTracked() || BodyStateSkeleton->RightArm()->Hand->Wrist->IsTracked(); } break; } return Ret; } void UBodyStateAnimInstance::ExecuteAutoMapping() { bool AutoMapSuccess = false; TArray<FString> FailedBones; // One hand mapping if (AutoMapTarget != EBodyStateAutoRigType::BOTH_HANDS) { // Make one map if missing if (MappedBoneList.Num() < 1) { FMappedBoneAnimData Map; MappedBoneList.Add(Map); } FMappedBoneAnimData& OneHandMap = MappedBoneList[0]; // reset on auto map button, otherwise flipping left to right won't set this up OneHandMap.PreBaseRotation = FRotator::ZeroRotator; AutoMapBoneDataForRigType(OneHandMap, AutoMapTarget, AutoMapSuccess, FailedBones); } // Two hand mapping else { // Make two maps if missing while (MappedBoneList.Num() < 2) { FMappedBoneAnimData Map; MappedBoneList.Add(Map); } // Map one hand each FMappedBoneAnimData& LeftHandMap = MappedBoneList[0]; AutoMapBoneDataForRigType(LeftHandMap, EBodyStateAutoRigType::HAND_LEFT, AutoMapSuccess, FailedBones); FMappedBoneAnimData& RightHandMap = MappedBoneList[1]; AutoMapBoneDataForRigType(RightHandMap, EBodyStateAutoRigType::HAND_RIGHT, AutoMapSuccess, FailedBones); } // One hand mapping if (AutoMapTarget != EBodyStateAutoRigType::BOTH_HANDS) { if (MappedBoneList.Num() > 0) { FMappedBoneAnimData& OneHandMap = MappedBoneList[0]; HandleLeftRightFlip(OneHandMap); if (bDetectHandRotationDuringAutoMapping) { EstimateAutoMapRotation(OneHandMap, AutoMapTarget); } else { OneHandMap.AutoCorrectRotation = FQuat(FRotator(ForceInitToZero)); } } } else { // Make two maps if missing if (MappedBoneList.Num() > 1) { // Map one hand each FMappedBoneAnimData& LeftHandMap = MappedBoneList[0]; FMappedBoneAnimData& RightHandMap = MappedBoneList[1]; HandleLeftRightFlip(LeftHandMap); HandleLeftRightFlip(RightHandMap); if (bDetectHandRotationDuringAutoMapping) { EstimateAutoMapRotation(LeftHandMap, EBodyStateAutoRigType::HAND_LEFT); EstimateAutoMapRotation(RightHandMap, EBodyStateAutoRigType::HAND_RIGHT); } else { RightHandMap.AutoCorrectRotation = LeftHandMap.AutoCorrectRotation = FQuat(FRotator(ForceInitToZero)); } } } // Cache all results if (BodyStateSkeleton == nullptr) { BodyStateSkeleton = UBodyStateBPLibrary::SkeletonForDevice(this, 0); SetAnimSkeleton(BodyStateSkeleton); // this will sync all the bones } else { for (auto& BoneMap : MappedBoneList) { SyncMappedBoneDataCache(BoneMap); } } #if WITH_EDITOR // this is what happens when the user clicks apply in the property previewer PersonaUtils::CopyPropertiesToCDO(this); FString Title("Ultraleap auto bone mapping"); FText TitleText = FText::FromString(*Title); FString Message("Auto mapping succeeded! Compile to continue"); if (!AutoMapSuccess) { Message = "We couldn't automatically map all bones.\n\nThe following bones couldn't be auto mapped:\n\n"; for (auto BoneName : FailedBones) { Message += BoneName; Message += "\n"; } Message += "\n\nEdit the mappings manually in 'Mapped Bone List -> Bone Map' in the preview panel to continue."; } FMessageDialog::Open(EAppMsgType::Ok, FText::FromString(*Message), &TitleText); #endif } #if WITH_EDITOR void UBodyStateAnimInstance::PostEditChangeProperty(struct FPropertyChangedEvent& PropertyChangedEvent) { Super::PostEditChangeProperty(PropertyChangedEvent); } void UBodyStateAnimInstance::PostEditChangeChainProperty(struct FPropertyChangedChainEvent& PropertyChangedEvent) { Super::PostEditChangeChainProperty(PropertyChangedEvent); // if we want to trigger an action when the user manually changed a bone mapping , do it in here if (PropertyChangedEvent.GetPropertyName() == "BoneName") { } } #endif // WITH_EDITOR void FMappedBoneAnimData::SyncCachedList(const USkeleton* LinkedSkeleton) { // Clear our current list CachedBoneList.Empty(); // We require a bodystate skeleton to do the mapping if (BodyStateSkeleton == nullptr) { return; } // Todo: optimize multiple calls with no / small changes // 1) traverse indexed bone list, store all the traverse lengths // this can happen on an animation worker thread // set bUseMultiThreadedAnimationUpdate = false if we want to do everything on engine tick FScopeLock ScopeLock(&BodyStateSkeleton->BoneDataLock); for (auto Pair : BoneMap) { FCachedBoneLink TraverseResult; TraverseResult.MeshBone = Pair.Value.MeshBone; TraverseResult.MeshBone.Initialize(LinkedSkeleton); TraverseResult.BSBone = BodyStateSkeleton->BoneForEnum(Pair.Key); // Costly function and we don't need it after all, and it won't work anymore now that it depends on external data // TraverseResult.TraverseCount = TraverseLengthForIndex(TraverseResult.MeshBone.BoneIndex); CachedBoneList.Add(TraverseResult); } // 2) reorder according to shortest traverse list CachedBoneList.Sort([](const FCachedBoneLink& One, const FCachedBoneLink& Two) { // return One.TraverseCount < Two.TraverseCount; return One.MeshBone.BoneIndex < Two.MeshBone.BoneIndex; }); UE_LOG(LogTemp, Log, TEXT("Bone cache synced: %d"), CachedBoneList.Num()); } bool FMappedBoneAnimData::BoneHasValidTags(const UBodyStateBone* QueryBone) { // Early exit optimization if (TrackingTagLimit.Num() == 0) { return true; } FBodyStateBoneMeta UniqueMeta = ((UBodyStateBone*) QueryBone)->UniqueMeta(); for (FString& LimitTag : TrackingTagLimit) { if (!UniqueMeta.TrackingTags.Contains(LimitTag)) { return false; } } return true; } bool FMappedBoneAnimData::SkeletonHasValidTags() { return BodyStateSkeleton->HasValidTrackingTags(TrackingTagLimit); } TArray<int32> FBodyStateIndexedBoneList::FindBoneWithChildCount(int32 Count) { TArray<int32> ResultArray; for (auto& Bone : Bones) { if (Bone.Children.Num() == Count) { ResultArray.Add(Bone.Index); } } return ResultArray; } void FBodyStateIndexedBoneList::SetFromRefSkeleton(const FReferenceSkeleton& RefSkeleton, bool SortBones) { for (int32 i = 0; i < RefSkeleton.GetNum(); i++) { FBodyStateIndexedBone Bone; Bone.BoneName = RefSkeleton.GetBoneName(i); Bone.ParentIndex = RefSkeleton.GetParentIndex(i); Bone.Index = i; SortedBones.Add(Bone); } if (SortBones) { SortedBones.Sort(); for (int i = 0; i < SortedBones.Num(); ++i) { SortedBones[i].Index = i; } } Bones.Empty(RefSkeleton.GetNum()); for (int32 i = 0; i < RefSkeleton.GetNum(); i++) { FBodyStateIndexedBone Bone; Bone.BoneName = RefSkeleton.GetBoneName(i); Bone.ParentIndex = RefSkeleton.GetParentIndex(i); Bone.Index = i; Bones.Add(Bone); // If we're not the root bone, add ourselves to the parent's child list if (Bone.ParentIndex != -1) { Bones[Bone.ParentIndex].Children.Add(Bone.Index); } else { RootBoneIndex = i; } } } int32 FBodyStateIndexedBoneList::TreeIndexFromSortedIndex(int32 SortedIndex) { auto& Bone = SortedBones[SortedIndex]; for (auto& BoneTreeBone : Bones) { if (BoneTreeBone.BoneName == Bone.BoneName) { return BoneTreeBone.Index; } } return 0; } int32 FBodyStateIndexedBoneList::LongestChildTraverseForBone(int32 BoneIndex) { auto& Bone = Bones[BoneIndex]; if (Bone.Children.Num() == 0) { return 0; } else { int32 Count = 0; for (int32 Child : Bone.Children) { int32 ChildCount = LongestChildTraverseForBone(Child); if (ChildCount > Count) { Count = ChildCount; } } return Count + 1; } } FORCEINLINE bool FBodyStateIndexedBone::operator<(const FBodyStateIndexedBone& Other) const { return BoneName.FastLess(Other.BoneName); }
30.295209
135
0.752921
[ "mesh", "render", "vector", "model", "transform" ]
a9febf0a52a10d453776779682c6ca5c513d1bdb
44,642
cpp
C++
source/Irrlicht/COgreMeshFileLoader.cpp
dgt0011/irrlicht-ogl-es
9664e30cfdfb7086e41e4dec3970183db5c0024a
[ "IJG" ]
41
2015-05-03T03:15:39.000Z
2020-11-26T04:05:25.000Z
source/Irrlicht/COgreMeshFileLoader.cpp
dgt0011/irrlicht-ogl-es
9664e30cfdfb7086e41e4dec3970183db5c0024a
[ "IJG" ]
5
2015-06-27T01:26:04.000Z
2018-01-21T06:01:30.000Z
source/Irrlicht/COgreMeshFileLoader.cpp
dgt0011/irrlicht-ogl-es
9664e30cfdfb7086e41e4dec3970183db5c0024a
[ "IJG" ]
28
2015-02-28T06:22:22.000Z
2021-02-22T12:15:28.000Z
// Copyright (C) 2002-2012 Nikolaus Gebhardt // This file is part of the "Irrlicht Engine". // For conditions of distribution and use, see copyright notice in irrlicht.h // orginally written by Christian Stehno, modified by Nikolaus Gebhardt #include "IrrCompileConfig.h" #ifdef _IRR_COMPILE_WITH_OGRE_LOADER_ #include "COgreMeshFileLoader.h" #include "CMeshTextureLoader.h" #include "os.h" #include "SMeshBuffer.h" #include "SAnimatedMesh.h" #include "IReadFile.h" #include "fast_atof.h" #include "coreutil.h" #ifdef _DEBUG #define IRR_OGRE_LOADER_DEBUG #endif namespace irr { namespace scene { namespace { enum OGRE_CHUNKS { // Main Chunks COGRE_HEADER= 0x1000, COGRE_SKELETON= 0x2000, COGRE_MESH= 0x3000, // sub chunks of COGRE_MESH COGRE_SUBMESH= 0x4000, COGRE_GEOMETRY= 0x5000, COGRE_SKELETON_LINK= 0x6000, COGRE_BONE_ASSIGNMENT= 0x7000, COGRE_MESH_LOD= 0x8000, COGRE_MESH_BOUNDS= 0x9000, COGRE_MESH_SUBMESH_NAME_TABLE= 0xA000, COGRE_MESH_EDGE_LISTS= 0xB000, // sub chunks of COGRE_SKELETON COGRE_BONE_PARENT= 0x3000, COGRE_ANIMATION= 0x4000, COGRE_ANIMATION_TRACK= 0x4100, COGRE_ANIMATION_KEYFRAME= 0x4110, COGRE_ANIMATION_LINK= 0x5000, // sub chunks of COGRE_SUBMESH COGRE_SUBMESH_OPERATION= 0x4010, COGRE_SUBMESH_BONE_ASSIGNMENT= 0x4100, COGRE_SUBMESH_TEXTURE_ALIAS= 0x4200, // sub chunks of COGRE_GEOMETRY COGRE_GEOMETRY_VERTEX_DECLARATION= 0x5100, COGRE_GEOMETRY_VERTEX_ELEMENT= 0x5110, COGRE_GEOMETRY_VERTEX_BUFFER= 0x5200, COGRE_GEOMETRY_VERTEX_BUFFER_DATA= 0x5210 }; } //! Constructor COgreMeshFileLoader::COgreMeshFileLoader(io::IFileSystem* fs, video::IVideoDriver* driver) : FileSystem(fs), Driver(driver), SwapEndian(false), Mesh(0), NumUV(0) { #ifdef _DEBUG setDebugName("COgreMeshFileLoader"); #endif if (FileSystem) FileSystem->grab(); if (Driver) Driver->grab(); TextureLoader = new CMeshTextureLoader( FileSystem, Driver ); } //! destructor COgreMeshFileLoader::~COgreMeshFileLoader() { clearMeshes(); if (FileSystem) FileSystem->drop(); if (Driver) Driver->drop(); if (Mesh) Mesh->drop(); } //! returns true if the file maybe is able to be loaded by this class //! based on the file extension (e.g. ".bsp") bool COgreMeshFileLoader::isALoadableFileExtension(const io::path& filename) const { return core::hasFileExtension ( filename, "mesh" ); } //! creates/loads an animated mesh from the file. //! \return Pointer to the created mesh. Returns 0 if loading failed. //! If you no longer need the mesh, you should call IAnimatedMesh::drop(). //! See IReferenceCounted::drop() for more information. IAnimatedMesh* COgreMeshFileLoader::createMesh(io::IReadFile* file) { if ( !file ) return 0; if ( getMeshTextureLoader() ) getMeshTextureLoader()->setMeshFile(file); s16 id; file->read(&id, 2); if (id == COGRE_HEADER) SwapEndian=false; else if (id == 0x0010) SwapEndian=true; else return 0; ChunkData data; readString(file, data, Version); if ((Version != "[MeshSerializer_v1.30]") && (Version != "[MeshSerializer_v1.40]") && (Version != "[MeshSerializer_v1.41]")) return 0; clearMeshes(); if (Mesh) Mesh->drop(); CurrentlyLoadingFromPath = FileSystem->getFileDir(file->getFileName()); loadMaterials(file); if (readChunk(file)) { // delete data loaded from file clearMeshes(); if (Skeleton.Bones.size()) { ISkinnedMesh* tmp = static_cast<CSkinnedMesh*>(Mesh); static_cast<CSkinnedMesh*>(Mesh)->updateBoundingBox(); Skeleton.Animations.clear(); Skeleton.Bones.clear(); Mesh=0; return tmp; } else { for (u32 i=0; i<Mesh->getMeshBufferCount(); ++i) ((SMeshBuffer*)Mesh->getMeshBuffer(i))->recalculateBoundingBox(); ((SMesh*)Mesh)->recalculateBoundingBox(); SAnimatedMesh* am = new SAnimatedMesh(); am->Type = EAMT_3DS; am->addMesh(Mesh); am->recalculateBoundingBox(); Mesh->drop(); Mesh = 0; return am; } } Mesh->drop(); Mesh = 0; return 0; } bool COgreMeshFileLoader::readChunk(io::IReadFile* file) { while(file->getPos() < file->getSize()) { ChunkData data; readChunkData(file, data); switch(data.header.id) { case COGRE_MESH: { Meshes.push_back(OgreMesh()); readObjectChunk(file, data, Meshes.getLast()); if (Skeleton.Bones.size()) Mesh = new CSkinnedMesh(); else Mesh = new SMesh(); composeObject(); } break; default: return true; } } return true; } bool COgreMeshFileLoader::readObjectChunk(io::IReadFile* file, ChunkData& parent, OgreMesh& mesh) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Object Chunk", ELL_DEBUG); #endif readBool(file, parent, mesh.SkeletalAnimation); bool skeleton_loaded=false; while ((parent.read < parent.header.length)&&(file->getPos() < file->getSize())) { ChunkData data; readChunkData(file, data); switch(data.header.id) { case COGRE_GEOMETRY: readGeometry(file, data, mesh.Geometry); break; case COGRE_SUBMESH: mesh.SubMeshes.push_back(OgreSubMesh()); readSubMesh(file, data, mesh.SubMeshes.getLast()); break; case COGRE_MESH_BOUNDS: { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Mesh Bounds", ELL_DEBUG); #endif readVector(file, data, mesh.BBoxMinEdge); readVector(file, data, mesh.BBoxMaxEdge); readFloat(file, data, &mesh.BBoxRadius); } break; case COGRE_SKELETON_LINK: { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Skeleton link", ELL_DEBUG); #endif core::stringc name; readString(file, data, name); loadSkeleton(file, name); skeleton_loaded=true; } break; case COGRE_BONE_ASSIGNMENT: { mesh.BoneAssignments.push_back(OgreBoneAssignment()); readInt(file, data, &mesh.BoneAssignments.getLast().VertexID); readShort(file, data, &mesh.BoneAssignments.getLast().BoneID); readFloat(file, data, &mesh.BoneAssignments.getLast().Weight); } break; case COGRE_MESH_LOD: case COGRE_MESH_SUBMESH_NAME_TABLE: case COGRE_MESH_EDGE_LISTS: // ignore chunk file->seek(data.header.length-data.read, true); data.read += data.header.length-data.read; break; default: #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Skipping", core::stringc(data.header.id), ELL_DEBUG); #endif // ignore chunk file->seek(data.header.length-data.read, true); data.read += data.header.length-data.read; break; } parent.read += data.read; } if (!skeleton_loaded) loadSkeleton(file, FileSystem->getFileBasename(file->getFileName(), false)); return true; } bool COgreMeshFileLoader::readGeometry(io::IReadFile* file, ChunkData& parent, OgreGeometry& geometry) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Geometry", ELL_DEBUG); #endif readInt(file, parent, &geometry.NumVertex); while(parent.read < parent.header.length) { ChunkData data; readChunkData(file, data); switch(data.header.id) { case COGRE_GEOMETRY_VERTEX_DECLARATION: readVertexDeclaration(file, data, geometry); break; case COGRE_GEOMETRY_VERTEX_BUFFER: readVertexBuffer(file, data, geometry); break; default: // ignore chunk #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Skipping", core::stringc(data.header.id), ELL_DEBUG); #endif file->seek(data.header.length-data.read, true); data.read += data.header.length-data.read; } parent.read += data.read; } if (parent.read != parent.header.length) os::Printer::log("Incorrect geometry length. File might be corrupted."); return true; } bool COgreMeshFileLoader::readVertexDeclaration(io::IReadFile* file, ChunkData& parent, OgreGeometry& geometry) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Vertex Declaration", ELL_DEBUG); #endif NumUV = 0; while(parent.read < parent.header.length) { ChunkData data; readChunkData(file, data); switch(data.header.id) { case COGRE_GEOMETRY_VERTEX_ELEMENT: { geometry.Elements.push_back(OgreVertexElement()); OgreVertexElement& elem = geometry.Elements.getLast(); readShort(file, data, &elem.Source); readShort(file, data, &elem.Type); readShort(file, data, &elem.Semantic); if (elem.Semantic == 7) //Tex coords { ++NumUV; } readShort(file, data, &elem.Offset); elem.Offset /= sizeof(f32); readShort(file, data, &elem.Index); } break; default: // ignore chunk file->seek(data.header.length-data.read, true); data.read += data.header.length-data.read; } parent.read += data.read; } if (parent.read != parent.header.length) os::Printer::log("Incorrect vertex declaration length. File might be corrupted."); return true; } bool COgreMeshFileLoader::readVertexBuffer(io::IReadFile* file, ChunkData& parent, OgreGeometry& geometry) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Vertex Buffer", ELL_DEBUG); #endif OgreVertexBuffer buf; readShort(file, parent, &buf.BindIndex); readShort(file, parent, &buf.VertexSize); buf.VertexSize /= sizeof(f32); ChunkData data; readChunkData(file, data); if (data.header.id == COGRE_GEOMETRY_VERTEX_BUFFER_DATA) { buf.Data.set_used(geometry.NumVertex*buf.VertexSize); readFloat(file, data, buf.Data.pointer(), geometry.NumVertex*buf.VertexSize); } geometry.Buffers.push_back(buf); parent.read += data.read; if (parent.read != parent.header.length) os::Printer::log("Incorrect vertex buffer length. File might be corrupted."); return true; } bool COgreMeshFileLoader::readSubMesh(io::IReadFile* file, ChunkData& parent, OgreSubMesh& subMesh) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Submesh", ELL_DEBUG); #endif readString(file, parent, subMesh.Material); #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("using material", subMesh.Material, ELL_DEBUG); #endif readBool(file, parent, subMesh.SharedVertices); s32 numIndices; readInt(file, parent, &numIndices); subMesh.Indices.set_used(numIndices); readBool(file, parent, subMesh.Indices32Bit); if (subMesh.Indices32Bit) readInt(file, parent, subMesh.Indices.pointer(), numIndices); else { for (s32 i=0; i<numIndices; ++i) { u16 num; readShort(file, parent, &num); subMesh.Indices[i]=num; } } while(parent.read < parent.header.length) { ChunkData data; readChunkData(file, data); switch(data.header.id) { case COGRE_GEOMETRY: readGeometry(file, data, subMesh.Geometry); break; case COGRE_SUBMESH_OPERATION: readShort(file, data, &subMesh.Operation); #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Submesh Operation",core::stringc(subMesh.Operation), ELL_DEBUG); #endif if (subMesh.Operation != 4) os::Printer::log("Primitive type != trilist not yet implemented", ELL_WARNING); break; case COGRE_SUBMESH_TEXTURE_ALIAS: { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Submesh Texture Alias", ELL_DEBUG); #endif core::stringc texture, alias; readString(file, data, texture); readString(file, data, alias); subMesh.TextureAliases.push_back(OgreTextureAlias(texture,alias)); } break; case COGRE_SUBMESH_BONE_ASSIGNMENT: { subMesh.BoneAssignments.push_back(OgreBoneAssignment()); readInt(file, data, &subMesh.BoneAssignments.getLast().VertexID); readShort(file, data, &subMesh.BoneAssignments.getLast().BoneID); readFloat(file, data, &subMesh.BoneAssignments.getLast().Weight); } break; default: #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Skipping", core::stringc(data.header.id), ELL_DEBUG); #endif parent.read=parent.header.length; file->seek(-(long)sizeof(ChunkHeader), true); return true; } parent.read += data.read; } if (parent.read != parent.header.length) os::Printer::log("Incorrect submesh length. File might be corrupted."); #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Done with submesh", ELL_DEBUG); #endif return true; } void COgreMeshFileLoader::composeMeshBufferMaterial(scene::IMeshBuffer* mb, const core::stringc& materialName) { video::SMaterial& material=mb->getMaterial(); for (u32 k=0; k<Materials.size(); ++k) { if ((materialName==Materials[k].Name)&&(Materials[k].Techniques.size())&&(Materials[k].Techniques[0].Passes.size())) { material=Materials[k].Techniques[0].Passes[0].Material; for (u32 i=0; i<Materials[k].Techniques[0].Passes[0].Texture.Filename.size(); ++i) { video::ITexture * texture = NULL; if ( getMeshTextureLoader() ) { texture = getMeshTextureLoader()->getTexture(Materials[k].Techniques[0].Passes[0].Texture.Filename[i]); if ( texture ) material.setTexture(i, texture); } } break; } } } scene::SMeshBuffer* COgreMeshFileLoader::composeMeshBuffer(const core::array<s32>& indices, const OgreGeometry& geom) { scene::SMeshBuffer *mb=new scene::SMeshBuffer(); u32 i; mb->Indices.set_used(indices.size()); for (i=0; i<indices.size(); ++i) mb->Indices[i]=indices[i]; mb->Vertices.set_used(geom.NumVertex); for (i=0; i<geom.Elements.size(); ++i) { if (geom.Elements[i].Semantic==1) //Pos { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; for (s32 k=0; k<geom.NumVertex; ++k) { mb->Vertices[k].Color=mb->Material.DiffuseColor; mb->Vertices[k].Pos.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]); ePos += eSize; } } } } if (geom.Elements[i].Semantic==4) //Normal { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; for (s32 k=0; k<geom.NumVertex; ++k) { mb->Vertices[k].Normal.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]); ePos += eSize; } } } } if (geom.Elements[i].Semantic==7) //TexCoord { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; for (s32 k=0; k<geom.NumVertex; ++k) { mb->Vertices[k].TCoords.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1]); ePos += eSize; } } } } } return mb; } scene::SMeshBufferLightMap* COgreMeshFileLoader::composeMeshBufferLightMap(const core::array<s32>& indices, const OgreGeometry& geom) { scene::SMeshBufferLightMap *mb=new scene::SMeshBufferLightMap(); u32 i; mb->Indices.set_used(indices.size()); for (i=0; i<indices.size(); ++i) mb->Indices[i]=indices[i]; mb->Vertices.set_used(geom.NumVertex); for (i=0; i<geom.Elements.size(); ++i) { if (geom.Elements[i].Semantic==1) //Pos { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; for (s32 k=0; k<geom.NumVertex; ++k) { mb->Vertices[k].Color=mb->Material.DiffuseColor; mb->Vertices[k].Pos.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]); ePos += eSize; } } } } if (geom.Elements[i].Semantic==4) //Normal { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; for (s32 k=0; k<geom.NumVertex; ++k) { mb->Vertices[k].Normal.set(geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]); ePos += eSize; } } } } if (geom.Elements[i].Semantic==7) //TexCoord { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; // make sure we have data for a second texture coord const bool secondCoord = (eSize>ePos+3); for (s32 k=0; k<geom.NumVertex; ++k) { mb->Vertices[k].TCoords.set(geom.Buffers[j].Data[ePos], geom.Buffers[j].Data[ePos+1]); if (secondCoord) mb->Vertices[k].TCoords2.set(geom.Buffers[j].Data[ePos+2], geom.Buffers[j].Data[ePos+3]); else mb->Vertices[k].TCoords2.set(geom.Buffers[j].Data[ePos], geom.Buffers[j].Data[ePos+1]); ePos += eSize; } } } } } return mb; } scene::IMeshBuffer* COgreMeshFileLoader::composeMeshBufferSkinned(scene::CSkinnedMesh& mesh, const core::array<s32>& indices, const OgreGeometry& geom) { scene::SSkinMeshBuffer *mb=mesh.addMeshBuffer(); if (NumUV>1) { mb->convertTo2TCoords(); mb->Vertices_2TCoords.set_used(geom.NumVertex); } else mb->Vertices_Standard.set_used(geom.NumVertex); u32 i; mb->Indices.set_used(indices.size()); for (i=0; i<indices.size(); i+=3) { mb->Indices[i+0]=indices[i+2]; mb->Indices[i+1]=indices[i+1]; mb->Indices[i+2]=indices[i+0]; } for (i=0; i<geom.Elements.size(); ++i) { if (geom.Elements[i].Semantic==1) //Pos { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; for (s32 k=0; k<geom.NumVertex; ++k) { if (NumUV>1) mb->Vertices_2TCoords[k].Color=mb->Material.DiffuseColor; else mb->Vertices_Standard[k].Color=mb->Material.DiffuseColor; mb->getPosition(k).set(-geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]); ePos += eSize; } } } } if (geom.Elements[i].Semantic==4) //Normal { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; for (s32 k=0; k<geom.NumVertex; ++k) { mb->getNormal(k).set(-geom.Buffers[j].Data[ePos],geom.Buffers[j].Data[ePos+1],geom.Buffers[j].Data[ePos+2]); ePos += eSize; } } } } if (geom.Elements[i].Semantic==7) //TexCoord { for (u32 j=0; j<geom.Buffers.size(); ++j) { if (geom.Elements[i].Source==geom.Buffers[j].BindIndex) { u32 eSize=geom.Buffers[j].VertexSize; u32 ePos=geom.Elements[i].Offset; // make sure we have data for a second texture coord const bool secondCoord = (eSize>ePos+3); for (s32 k=0; k<geom.NumVertex; ++k) { mb->getTCoords(k).set(geom.Buffers[j].Data[ePos], geom.Buffers[j].Data[ePos+1]); if (NumUV>1) { if (secondCoord) mb->Vertices_2TCoords[k].TCoords2.set(geom.Buffers[j].Data[ePos+2], geom.Buffers[j].Data[ePos+3]); else mb->Vertices_2TCoords[k].TCoords2.set(geom.Buffers[j].Data[ePos], geom.Buffers[j].Data[ePos+1]); } ePos += eSize; } } } } } return mb; } void COgreMeshFileLoader::composeObject(void) { for (u32 i=0; i<Meshes.size(); ++i) { for (u32 j=0; j<Meshes[i].SubMeshes.size(); ++j) { IMeshBuffer* mb; if (Meshes[i].SubMeshes[j].SharedVertices) { if (Skeleton.Bones.size()) { mb = composeMeshBufferSkinned(*(CSkinnedMesh*)Mesh, Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry); } else if (NumUV < 2) { mb = composeMeshBuffer(Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry); } else { mb = composeMeshBufferLightMap(Meshes[i].SubMeshes[j].Indices, Meshes[i].Geometry); } } else { if (Skeleton.Bones.size()) { mb = composeMeshBufferSkinned(*(CSkinnedMesh*)Mesh, Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry); } else if (NumUV < 2) { mb = composeMeshBuffer(Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry); } else { mb = composeMeshBufferLightMap(Meshes[i].SubMeshes[j].Indices, Meshes[i].SubMeshes[j].Geometry); } } if (mb != 0) { composeMeshBufferMaterial(mb, Meshes[i].SubMeshes[j].Material); if (!Skeleton.Bones.size()) { ((SMesh*)Mesh)->addMeshBuffer(mb); mb->drop(); } } } } if (Skeleton.Bones.size()) { CSkinnedMesh* m = (CSkinnedMesh*)Mesh; // Create Joints for (u32 i=0; i<Skeleton.Bones.size(); ++i) { ISkinnedMesh::SJoint* joint = m->addJoint(); joint->Name=Skeleton.Bones[i].Name; // IRR_TEST_BROKEN_QUATERNION_USE: TODO - switched to getMatrix_transposed instead of getMatrix for downward compatibility. // Not tested so far if this was correct or wrong before quaternion fix! Skeleton.Bones[i].Orientation.getMatrix_transposed(joint->LocalMatrix); if (Skeleton.Bones[i].Scale != core::vector3df(1,1,1)) { core::matrix4 scaleMatrix; scaleMatrix.setScale( Skeleton.Bones[i].Scale ); joint->LocalMatrix *= scaleMatrix; } joint->LocalMatrix.setTranslation( Skeleton.Bones[i].Position ); } // Joints hierarchy for (u32 i=0; i<Skeleton.Bones.size(); ++i) { if (Skeleton.Bones[i].Parent<m->getJointCount()) { m->getAllJoints()[Skeleton.Bones[i].Parent]->Children.push_back(m->getAllJoints()[Skeleton.Bones[i].Handle]); } } // Weights u32 bufCount=0; for (u32 i=0; i<Meshes.size(); ++i) { for (u32 j=0; j<Meshes[i].SubMeshes.size(); ++j) { for (u32 k=0; k<Meshes[i].SubMeshes[j].BoneAssignments.size(); ++k) { const OgreBoneAssignment& ba = Meshes[i].SubMeshes[j].BoneAssignments[k]; if (ba.BoneID<m->getJointCount()) { ISkinnedMesh::SWeight* w = m->addWeight(m->getAllJoints()[ba.BoneID]); w->strength=ba.Weight; w->vertex_id=ba.VertexID; w->buffer_id=bufCount; } } ++bufCount; } } for (u32 i=0; i<Skeleton.Animations.size(); ++i) { for (u32 j=0; j<Skeleton.Animations[i].Keyframes.size(); ++j) { OgreKeyframe& frame = Skeleton.Animations[i].Keyframes[j]; ISkinnedMesh::SJoint* keyjoint = m->getAllJoints()[frame.BoneID]; ISkinnedMesh::SPositionKey* poskey = m->addPositionKey(keyjoint); poskey->frame=frame.Time*25; poskey->position=keyjoint->LocalMatrix.getTranslation()+frame.Position; ISkinnedMesh::SRotationKey* rotkey = m->addRotationKey(keyjoint); rotkey->frame=frame.Time*25; // IRR_TEST_BROKEN_QUATERNION_USE: TODO - switched from keyjoint->LocalMatrix to keyjoint->LocalMatrix.getTransposed() for downward compatibility. // Not tested so far if this was correct or wrong before quaternion fix! rotkey->rotation=core::quaternion(keyjoint->LocalMatrix.getTransposed())*frame.Orientation; ISkinnedMesh::SScaleKey* scalekey = m->addScaleKey(keyjoint); scalekey->frame=frame.Time*25; scalekey->scale=frame.Scale; } } m->finalize(); } } void COgreMeshFileLoader::getMaterialToken(io::IReadFile* file, core::stringc& token, bool noNewLine) { bool parseString=false; c8 c=0; token = ""; if (file->getPos() >= file->getSize()) return; file->read(&c, sizeof(c8)); // search for word beginning while ( core::isspace(c) && (file->getPos() < file->getSize())) { if (noNewLine && c=='\n') { file->seek(-1, true); return; } file->read(&c, sizeof(c8)); } // check if we read a string if (c=='"') { parseString = true; file->read(&c, sizeof(c8)); } do { if (c=='/') { file->read(&c, sizeof(c8)); // check for comments, cannot be part of strings if (!parseString && (c=='/')) { // skip comments while(c!='\n') file->read(&c, sizeof(c8)); if (!token.size()) { // if we start with a comment we need to skip // following whitespaces, so restart getMaterialToken(file, token, noNewLine); return; } else { // else continue with next character file->read(&c, sizeof(c8)); continue; } } else { // else append first slash and check if second char // ends this token token.append('/'); if ((!parseString && core::isspace(c)) || (parseString && (c=='"'))) return; } } token.append(c); file->read(&c, sizeof(c8)); // read until a token delimiter is found } while (((!parseString && !core::isspace(c)) || (parseString && (c!='"'))) && (file->getPos() < file->getSize())); // we want to skip the last quotes of a string , but other chars might be the next // token already. if (!parseString) file->seek(-1, true); } bool COgreMeshFileLoader::readColor(io::IReadFile* file, video::SColor& col) { core::stringc token; getMaterialToken(file, token); if (token!="vertexcolour") { video::SColorf col_f; col_f.r=core::fast_atof(token.c_str()); getMaterialToken(file, token); col_f.g=core::fast_atof(token.c_str()); getMaterialToken(file, token); col_f.b=core::fast_atof(token.c_str()); getMaterialToken(file, token, true); if (token.size()) col_f.a=core::fast_atof(token.c_str()); else col_f.a=1.0f; if ((col_f.r==0.0f)&&(col_f.g==0.0f)&&(col_f.b==0.0f)) col.set(255,255,255,255); else col=col_f.toSColor(); return false; } return true; } void COgreMeshFileLoader::readPass(io::IReadFile* file, OgreTechnique& technique) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Pass"); #endif core::stringc token; technique.Passes.push_back(OgrePass()); OgrePass& pass=technique.Passes.getLast(); getMaterialToken(file, token); //open brace or name if (token != "{") getMaterialToken(file, token); //open brace getMaterialToken(file, token); if (token == "}") return; u32 inBlocks=1; u32 textureUnit=0; while(inBlocks) { if (token=="ambient") pass.AmbientTokenColor=readColor(file, pass.Material.AmbientColor); else if (token=="diffuse") pass.DiffuseTokenColor=readColor(file, pass.Material.DiffuseColor); else if (token=="specular") { pass.SpecularTokenColor=readColor(file, pass.Material.SpecularColor); getMaterialToken(file, token); pass.Material.Shininess=core::fast_atof(token.c_str()); } else if (token=="emissive") pass.EmissiveTokenColor=readColor(file, pass.Material.EmissiveColor); else if (token=="scene_blend") { // TODO: Choose correct values getMaterialToken(file, token); if (token=="add") pass.Material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR; else if (token=="modulate") pass.Material.MaterialType=video::EMT_SOLID; else if (token=="alpha_blend") pass.Material.MaterialType=video::EMT_TRANSPARENT_ALPHA_CHANNEL; else if (token=="colour_blend") pass.Material.MaterialType=video::EMT_TRANSPARENT_VERTEX_ALPHA; else getMaterialToken(file, token); } else if (token=="depth_check") { getMaterialToken(file, token); if (token!="on") pass.Material.ZBuffer=video::ECFN_DISABLED; } else if (token=="depth_write") { getMaterialToken(file, token); pass.Material.ZWriteEnable=(token=="on"); } else if (token=="depth_func") { getMaterialToken(file, token); // Function name if (token=="always_fail") pass.Material.ZBuffer=video::ECFN_NEVER; else if (token=="always_pass") pass.Material.ZBuffer=video::ECFN_ALWAYS; else if (token=="equal") pass.Material.ZBuffer=video::ECFN_EQUAL; else if (token=="greater") pass.Material.ZBuffer=video::ECFN_GREATER; else if (token=="greater_equal") pass.Material.ZBuffer=video::ECFN_GREATEREQUAL; else if (token=="less") pass.Material.ZBuffer=video::ECFN_LESS; else if (token=="less_equal") pass.Material.ZBuffer=video::ECFN_LESSEQUAL; else if (token=="not_equal") pass.Material.ZBuffer=video::ECFN_NOTEQUAL; } else if (token=="normalise_normals") { getMaterialToken(file, token); pass.Material.NormalizeNormals=(token=="on"); } else if (token=="depth_bias") { getMaterialToken(file, token); // bias value } else if (token=="alpha_rejection") { getMaterialToken(file, token); // function name getMaterialToken(file, token); // value pass.Material.MaterialTypeParam=core::fast_atof(token.c_str()); } else if (token=="alpha_to_coverage") { getMaterialToken(file, token); if (token=="on") pass.Material.AntiAliasing |= video::EAAM_ALPHA_TO_COVERAGE; } else if (token=="colour_write") { getMaterialToken(file, token); pass.Material.ColorMask = (token=="on")?video::ECP_ALL:video::ECP_NONE; } else if (token=="cull_hardware") { getMaterialToken(file, token); // rotation name } else if (token=="cull_software") { getMaterialToken(file, token); // culling side } else if (token=="lighting") { getMaterialToken(file, token); pass.Material.Lighting=(token=="on"); } else if (token=="shading") { getMaterialToken(file, token); // We take phong as gouraud pass.Material.GouraudShading=(token!="flat"); } else if (token=="polygon_mode") { getMaterialToken(file, token); pass.Material.Wireframe=(token=="wireframe"); pass.Material.PointCloud=(token=="points"); } else if (token=="max_lights") { getMaterialToken(file, token); pass.MaxLights=core::strtoul10(token.c_str()); } else if (token=="point_size") { getMaterialToken(file, token); pass.PointSize=core::fast_atof(token.c_str()); } else if (token=="point_sprites") { getMaterialToken(file, token); pass.PointSprites=(token=="on"); } else if (token=="point_size_min") { getMaterialToken(file, token); pass.PointSizeMin=core::strtoul10(token.c_str()); } else if (token=="point_size_max") { getMaterialToken(file, token); pass.PointSizeMax=core::strtoul10(token.c_str()); } else if (token=="texture_unit") { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Texture unit", ELL_DEBUG); #endif getMaterialToken(file, token); //open brace getMaterialToken(file, token); while(token != "}") { if (token=="texture") { getMaterialToken(file, token); pass.Texture.Filename.push_back(token); #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Texture", token, ELL_DEBUG); #endif getMaterialToken(file, pass.Texture.CoordsType, true); getMaterialToken(file, pass.Texture.MipMaps, true); getMaterialToken(file, pass.Texture.Alpha, true); // Hmm, we might need more hints for other material types using two textures... if (textureUnit>0) pass.Material.MaterialType=video::EMT_LIGHTMAP; } else if (token=="filtering") { getMaterialToken(file, token); pass.Material.TextureLayer[textureUnit].AnisotropicFilter=0; if (token=="point") { pass.Material.TextureLayer[textureUnit].BilinearFilter=false; pass.Material.TextureLayer[textureUnit].TrilinearFilter=false; getMaterialToken(file, token); getMaterialToken(file, token); } else if (token=="linear") { getMaterialToken(file, token); if (token=="point") { pass.Material.TextureLayer[textureUnit].BilinearFilter=false; pass.Material.TextureLayer[textureUnit].TrilinearFilter=false; getMaterialToken(file, token); } else { pass.Material.TextureLayer[textureUnit].BilinearFilter=true; getMaterialToken(file, token); pass.Material.TextureLayer[textureUnit].TrilinearFilter=(token=="linear"); } } else { pass.Material.TextureLayer[textureUnit].BilinearFilter=(token=="bilinear"); pass.Material.TextureLayer[textureUnit].TrilinearFilter=(token=="trilinear"); pass.Material.TextureLayer[textureUnit].AnisotropicFilter=(token=="anisotropic")?2:1; } } else if (token=="max_anisotropy") { getMaterialToken(file, token); pass.Material.TextureLayer[textureUnit].AnisotropicFilter=(u8)core::strtoul10(token.c_str()); } else if (token=="texture_alias") { getMaterialToken(file, pass.Texture.Alias); } else if (token=="mipmap_bias") { getMaterialToken(file, token); pass.Material.TextureLayer[textureUnit].LODBias=(s8)core::fast_atof(token.c_str()); } else if (token=="colour_op") { // TODO: Choose correct values getMaterialToken(file, token); if (token=="add") pass.Material.MaterialType=video::EMT_TRANSPARENT_ADD_COLOR; else if (token=="modulate") pass.Material.MaterialType=video::EMT_SOLID; else if (token=="alpha_blend") pass.Material.MaterialType=video::EMT_TRANSPARENT_ALPHA_CHANNEL; else if (token=="colour_blend") pass.Material.MaterialType=video::EMT_TRANSPARENT_VERTEX_ALPHA; else getMaterialToken(file, token); } getMaterialToken(file, token); } ++textureUnit; } else if (token=="shadow_caster_program_ref") { do { getMaterialToken(file, token); } while (token != "}"); } else if (token=="shadow_caster_vertex_program_ref") { do { getMaterialToken(file, token); } while (token != "}"); } else if (token=="vertex_program_ref") { do { getMaterialToken(file, token); } while (token != "}"); } //fog_override, iteration, point_size_attenuation //not considered yet! getMaterialToken(file, token); if (token=="{") ++inBlocks; else if (token=="}") --inBlocks; } } void COgreMeshFileLoader::readTechnique(io::IReadFile* file, OgreMaterial& mat) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Read Technique"); #endif core::stringc token; mat.Techniques.push_back(OgreTechnique()); OgreTechnique& technique=mat.Techniques.getLast(); getMaterialToken(file, technique.Name); //open brace or name if (technique.Name != "{") getMaterialToken(file, token); //open brace else technique.Name=core::stringc((int)mat.Techniques.size()); getMaterialToken(file, token); while (token != "}") { if (token == "pass") readPass(file, technique); else if (token == "scheme") getMaterialToken(file, token); else if (token == "lod_index") getMaterialToken(file, token); getMaterialToken(file, token); } } void COgreMeshFileLoader::loadMaterials(io::IReadFile* meshFile) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Load Materials", ELL_DEBUG); #endif core::stringc token; io::IReadFile* file = 0; io::path filename = FileSystem->getFileBasename(meshFile->getFileName(), false) + ".material"; if (FileSystem->existFile(filename)) file = FileSystem->createAndOpenFile(filename); else file = FileSystem->createAndOpenFile(FileSystem->getFileDir(meshFile->getFileName())+"/"+filename); if (!file) { os::Printer::log("Could not load OGRE material", filename); return; } getMaterialToken(file, token); while (file->getPos() < file->getSize()) { if ((token == "fragment_program") || (token == "vertex_program")) { // skip whole block u32 blocks=1; do { getMaterialToken(file, token); } while (token != "{"); do { getMaterialToken(file, token); if (token == "{") ++blocks; else if (token == "}") --blocks; } while (blocks); getMaterialToken(file, token); continue; } if (token != "material") { if (token.trim().size()) os::Printer::log("Unknown material group", token.c_str()); break; } Materials.push_back(OgreMaterial()); OgreMaterial& mat = Materials.getLast(); getMaterialToken(file, mat.Name); #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Load Material", mat.Name.c_str(), ELL_DEBUG); #endif getMaterialToken(file, token); //open brace getMaterialToken(file, token); while(token != "}") { if (token=="lod_distances") // can have several items getMaterialToken(file, token); else if (token=="receive_shadows") { getMaterialToken(file, token); mat.ReceiveShadows=(token=="on"); } else if (token=="transparency_casts_shadows") { getMaterialToken(file, token); mat.TransparencyCastsShadows=(token=="on"); } else if (token=="set_texture_alias") { getMaterialToken(file, token); getMaterialToken(file, token); } else if (token=="technique") readTechnique(file, mat); getMaterialToken(file, token); } getMaterialToken(file, token); } file->drop(); #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Finished loading Materials", ELL_DEBUG); #endif } bool COgreMeshFileLoader::loadSkeleton(io::IReadFile* meshFile, const core::stringc& name) { #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Load Skeleton", name, ELL_DEBUG); #endif io::IReadFile* file = 0; io::path filename; if (FileSystem->existFile(name)) file = FileSystem->createAndOpenFile(name); else if (FileSystem->existFile(filename = FileSystem->getFileDir(meshFile->getFileName())+"/"+name)) file = FileSystem->createAndOpenFile(filename); else if (FileSystem->existFile(filename = FileSystem->getFileBasename(meshFile->getFileName(), false) + ".skeleton")) file = FileSystem->createAndOpenFile(filename); else file = FileSystem->createAndOpenFile(FileSystem->getFileDir(meshFile->getFileName())+"/"+filename); if (!file) { os::Printer::log("Could not load matching skeleton", name); return false; } s16 id; file->read(&id, 2); if (SwapEndian) id = os::Byteswap::byteswap(id); if (id != COGRE_HEADER) { file->drop(); return false; } core::stringc skeletonVersion; ChunkData head; readString(file, head, skeletonVersion); if (skeletonVersion != "[Serializer_v1.10]") { file->drop(); return false; } u16 bone=0; f32 animationTotal=0.f; while(file->getPos() < file->getSize()) { ChunkData data; readChunkData(file, data); switch(data.header.id) { case COGRE_SKELETON: { Skeleton.Bones.push_back(OgreBone()); OgreBone& bone = Skeleton.Bones.getLast(); readString(file, data, bone.Name); readShort(file, data, &bone.Handle); readVector(file, data, bone.Position); readQuaternion(file, data, bone.Orientation); #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Bone", bone.Name+" ("+core::stringc(bone.Handle)+")", ELL_DEBUG); os::Printer::log("Position", core::stringc(bone.Position.X)+" "+core::stringc(bone.Position.Y)+" "+core::stringc(bone.Position.Z), ELL_DEBUG); os::Printer::log("Rotation quat", core::stringc(bone.Orientation.W)+" "+core::stringc(bone.Orientation.X)+" "+core::stringc(bone.Orientation.Y)+" "+core::stringc(bone.Orientation.Z), ELL_DEBUG); // core::vector3df rot; // bone.Orientation.toEuler(rot); // rot *= core::RADTODEG; // os::Printer::log("Rotation", core::stringc(rot.X)+" "+core::stringc(rot.Y)+" "+core::stringc(rot.Z)); #endif if (data.read<(data.header.length-bone.Name.size())) { readVector(file, data, bone.Scale); bone.Scale.X *= -1.f; } else bone.Scale=core::vector3df(1,1,1); bone.Parent=0xffff; } break; case COGRE_BONE_PARENT: { u16 parent; readShort(file, data, &bone); readShort(file, data, &parent); if (bone<Skeleton.Bones.size() && parent<Skeleton.Bones.size()) Skeleton.Bones[bone].Parent=parent; } break; case COGRE_ANIMATION: { if (Skeleton.Animations.size()) animationTotal+=Skeleton.Animations.getLast().Length; Skeleton.Animations.push_back(OgreAnimation()); OgreAnimation& anim = Skeleton.Animations.getLast(); readString(file, data, anim.Name); readFloat(file, data, &anim.Length); #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Animation", anim.Name, ELL_DEBUG); os::Printer::log("Length", core::stringc(anim.Length), ELL_DEBUG); #endif } break; case COGRE_ANIMATION_TRACK: #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("for Bone ", core::stringc(bone), ELL_DEBUG); #endif readShort(file, data, &bone); // store current bone break; case COGRE_ANIMATION_KEYFRAME: { Skeleton.Animations.getLast().Keyframes.push_back(OgreKeyframe()); OgreKeyframe& keyframe = Skeleton.Animations.getLast().Keyframes.getLast(); readFloat(file, data, &keyframe.Time); keyframe.Time+=animationTotal; readQuaternion(file, data, keyframe.Orientation); readVector(file, data, keyframe.Position); if (data.read<data.header.length) { readVector(file, data, keyframe.Scale); keyframe.Scale.X *= -1.f; } else keyframe.Scale=core::vector3df(1,1,1); keyframe.BoneID=bone; } break; case COGRE_ANIMATION_LINK: #ifdef IRR_OGRE_LOADER_DEBUG os::Printer::log("Animation link", ELL_DEBUG); #endif break; default: break; } } file->drop(); return true; } void COgreMeshFileLoader::readChunkData(io::IReadFile* file, ChunkData& data) { file->read(&data.header, sizeof(ChunkHeader)); if (SwapEndian) { data.header.id = os::Byteswap::byteswap(data.header.id); data.header.length = os::Byteswap::byteswap(data.header.length); } data.read += sizeof(ChunkHeader); } void COgreMeshFileLoader::readString(io::IReadFile* file, ChunkData& data, core::stringc& out) { c8 c = 0; out = ""; while (c!='\n') { file->read(&c, sizeof(c8)); if (c!='\n') out.append(c); } data.read+=out.size()+1; } void COgreMeshFileLoader::readBool(io::IReadFile* file, ChunkData& data, bool& out) { // normal C type because we read a bit string char c = 0; file->read(&c, sizeof(char)); out=(c!=0); ++data.read; } void COgreMeshFileLoader::readInt(io::IReadFile* file, ChunkData& data, s32* out, u32 num) { // normal C type because we read a bit string file->read(out, sizeof(int)*num); if (SwapEndian) { for (u32 i=0; i<num; ++i) out[i] = os::Byteswap::byteswap(out[i]); } data.read+=sizeof(int)*num; } void COgreMeshFileLoader::readShort(io::IReadFile* file, ChunkData& data, u16* out, u32 num) { // normal C type because we read a bit string file->read(out, sizeof(short)*num); if (SwapEndian) { for (u32 i=0; i<num; ++i) out[i] = os::Byteswap::byteswap(out[i]); } data.read+=sizeof(short)*num; } void COgreMeshFileLoader::readFloat(io::IReadFile* file, ChunkData& data, f32* out, u32 num) { // normal C type because we read a bit string file->read(out, sizeof(float)*num); if (SwapEndian) { for (u32 i=0; i<num; ++i) out[i] = os::Byteswap::byteswap(out[i]); } data.read+=sizeof(float)*num; } void COgreMeshFileLoader::readVector(io::IReadFile* file, ChunkData& data, core::vector3df& out) { readFloat(file, data, &out.X); readFloat(file, data, &out.Y); readFloat(file, data, &out.Z); out.X *= -1.f; } void COgreMeshFileLoader::readQuaternion(io::IReadFile* file, ChunkData& data, core::quaternion& out) { readVector(file, data, *((core::vector3df*)&out.X)); readFloat(file, data, &out.W); } void COgreMeshFileLoader::clearMeshes() { for (u32 i=0; i<Meshes.size(); ++i) { for (int k=0; k<(int)Meshes[i].Geometry.Buffers.size(); ++k) Meshes[i].Geometry.Buffers[k].Data.clear(); for (u32 j=0; j<Meshes[i].SubMeshes.size(); ++j) { for (int h=0; h<(int)Meshes[i].SubMeshes[j].Geometry.Buffers.size(); ++h) Meshes[i].SubMeshes[j].Geometry.Buffers[h].Data.clear(); } } Meshes.clear(); } } // end namespace scene } // end namespace irr #endif // _IRR_COMPILE_WITH_OGRE_LOADER_
27.81433
199
0.647843
[ "mesh", "geometry", "object" ]
e701802d3654cb2f938d72613122bcc89b45303e
3,955
cpp
C++
Sources/External/node/elastos/nodeutils/ElastosUtil.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/External/node/elastos/nodeutils/ElastosUtil.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/External/node/elastos/nodeutils/ElastosUtil.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
/* * Copyright 2007, The Android Open Source Project * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define LOG_TAG "webcoreglue" #include "config.h" #include "IntRect.h" #include <wtf/text/CString.h> #include "wtf/Vector.h" #include "NotImplemented.h" #include <utils/Log.h> #include "ElastosUtil.h" namespace Elastos { struct ElaNativeUtilCallback sElaNativeUtilCallback; struct ElaBitmapCallback sElaBitmapCallback; struct ElaInputStreamCallback sElaInputStreamCallback; #ifdef __cplusplus extern "C" { #endif WK_EXPORT void Elastos_NativeUtil_InitCallback(Int32 cb) { struct ElaNativeUtilCallback *pCallback = (struct ElaNativeUtilCallback*)cb; sElaNativeUtilCallback = *pCallback; } WK_EXPORT void Elastos_Bitmap_InitCallback(Int32 cb) { struct ElaBitmapCallback* pCallback = (struct ElaBitmapCallback*)cb; sElaBitmapCallback = *pCallback; } WK_EXPORT void Elastos_InputStream_InitCallback(Int32 cb) { struct ElaInputStreamCallback* pCallback = (struct ElaInputStreamCallback*)cb; sElaInputStreamCallback = *pCallback; } #ifdef __cplusplus } #endif AutoPtr<IInterface> getRealObject( /* [in] */ AutoPtr<IWeakReference> obj) { AutoPtr<IInterface> ws; obj->Resolve(EIID_IInterface, (IInterface**)&ws); return ws; } WTF::String ElstringToWtfString( /* [in] */ const Elastos::String& str) { if (str.IsNull()) { return WTF::String(); } WTF::String ret; if (str.GetLength() == str.GetByteLength())//ascii { ret = WTF::String(str.string()); } else//multi-byte charset { AutoPtr<ArrayOf<Char16> > pArray = str.GetChar16s(); ret = WTF::String(pArray->GetPayload(), str.GetLength()); } /* optional solution for multi-byte for(int i = 0; i < str.GetLength(); ++i) { Int32 c = str.GetChar(i); if (!c) ret.append(WTF::String()); else if(c > 0xffff) { UChar lead = U16_LEAD(c); UChar trail = U16_TRAIL(c); UChar utf16[2] = {lead, trail}; ret.append(WTF::String(utf16, 2)); } else { UChar n = (UChar)c; ret.append(WTF::String(&n, 1)); } } */ return ret; } Elastos::String WtfStringToElstring( /* [in] */ const WTF::String& str) { return Elastos::String(str.utf8().data()); } std::string ElstringToStdString( /* [in] */ const Elastos::String& str) { if (str.IsNull()) { return std::string(); } std::string ret(str.string()); return ret; } Elastos::String StdStringToElstring( /* [in] */ const std::string& str) { return Elastos::String(str.c_str()); } } // namespace Elastos
28.453237
82
0.680657
[ "vector" ]
e7076351204ae4209a2305e5a825e20233edf566
2,162
cc
C++
third_party/logcabin/Core/STLUtilTest.cc
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
1,564
2015-01-05T15:17:11.000Z
2022-03-28T06:48:44.000Z
third_party/logcabin/Core/STLUtilTest.cc
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
193
2015-01-05T19:04:11.000Z
2022-01-24T14:30:25.000Z
third_party/logcabin/Core/STLUtilTest.cc
jessesleeping/my_peloton
a19426cfe34a04692a11008eaffc9c3c9b49abc4
[ "Apache-2.0" ]
307
2015-01-05T22:41:30.000Z
2022-03-13T07:26:04.000Z
/* Copyright (c) 2011-2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <map> #include <string> #include <vector> #include <gtest/gtest.h> #include "Core/STLUtil.h" namespace LogCabin { namespace Core { namespace STLUtil { namespace { using std::map; using std::pair; using std::string; using std::vector; const map<int, string> empty {}; const map<int, string> digits { { 1, "one" }, { 2, "two" }, { 3, "three" }, }; TEST(CoreSTLUtilTest, sorted) { EXPECT_EQ((vector<int> {}), sorted(vector<int> {})); EXPECT_EQ((vector<int> { 1, 5, 7}), sorted(vector<int> {5, 1, 7})); } TEST(CoreSTLUtilTest, getKeys) { EXPECT_EQ((vector<int>{}), getKeys(empty)); EXPECT_EQ((vector<int>{ 1, 2, 3 }), getKeys(digits)); } TEST(CoreSTLUtilTest, getValues) { EXPECT_EQ((vector<string>{}), getValues(empty)); EXPECT_EQ((vector<string>{ "one", "two", "three" }), getValues(digits)); } TEST(CoreSTLUtilTest, getItems) { EXPECT_EQ((vector<pair<int, string>>{}), getItems(empty)); EXPECT_EQ((vector<pair<int, string>>{ {1, "one"}, {2, "two"}, {3, "three"}, }), getItems(digits)); } } // namespace LogCabin::Core::STLUtil::<anonymous> } // namespace LogCabin::Core::STLUtil } // namespace LogCabin::Core } // namespace LogCabin
28.077922
77
0.629972
[ "vector" ]
e70d557f551c509e73aa707fdb7eb29e77a694be
4,994
cc
C++
ext/candc/src/lib/tagger/_baseimpl.cc
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
6
2020-01-27T12:08:02.000Z
2020-02-28T19:30:28.000Z
pack/logicmoo_nlu/prolog/candc/src/lib/tagger/_baseimpl.cc
logicmoo/old_logicmoo_workspace
44025b6e389e2f2f7d86b46c1301cab0604bba26
[ "MIT" ]
1
2020-02-02T13:12:34.000Z
2020-02-02T13:12:34.000Z
ext/candc/src/lib/tagger/_baseimpl.cc
TeamSPoon/logicmoo_nlu
5c3e5013a3048da7d68a8a43476ad84d3ea4bb47
[ "MIT" ]
null
null
null
// C&C NLP tools // Copyright (c) Universities of Edinburgh, Oxford and Sydney // Copyright (c) James R. Curran // // This software is covered by a non-commercial use licence. // See LICENCE.txt for the full text of the licence. // // If LICENCE.txt is not included in this distribution // please email candc@it.usyd.edu.au to obtain a copy. // NLP::Tagger::_BaseImpl // provides some common services for the tagger classes // including the NLP::Tagger::State class which holds the // Beam search lattice representation, the tagger buffer // and some frequently used temporary probability distribution // arrays #include "tagger/_baseimpl.h" using namespace NLP::Model; namespace NLP { namespace Taggers { void Tagger::Impl::reg_attributes(void){ registry.reg(Types::pppw, w_attribs); registry.reg(Types::ppw, w_attribs); registry.reg(Types::pw, w_attribs); registry.reg(Types::w, w_attribs); registry.reg(Types::nw, w_attribs); registry.reg(Types::nnw, w_attribs); registry.reg(Types::nnnw, w_attribs); registry.reg(Types::pppw_ppw_b, ww_attribs); registry.reg(Types::ppw_pw_b, ww_attribs); registry.reg(Types::pw_w_b, ww_attribs); registry.reg(Types::pw_nw_b, ww_attribs); registry.reg(Types::w_nw_b, ww_attribs); registry.reg(Types::nw_nnw_b, ww_attribs); registry.reg(Types::nnw_nnnw_b, ww_attribs); registry.reg(Types::pppw_ppw_pw_c, www_attribs); registry.reg(Types::ppw_pw_w_c, www_attribs); registry.reg(Types::pw_w_nw_c, www_attribs); registry.reg(Types::w_nw_nnw_c, www_attribs); registry.reg(Types::nw_nnw_nnnw_c, www_attribs); } // model/features is read into the features vector // and we create the mapping between attribute identifiers // and feature pointers (Attrib2Feats) void Tagger::Impl::_read_features(const Model::Model &cfg, const Model::Info &info, Attrib2Feats &attrib2feats){ features.reserve(info.nfeatures()); attrib2feats.reserve(info.nattributes() + 1); ifstream stream(cfg.weights().c_str()); if(!stream) throw NLP::IOException("could not open weights file", cfg.weights()); ulong nlines = 0; read_preface(cfg.weights(), stream, nlines); ulong previous = static_cast<ulong>(-1); ulong klass, attrib; double lambda; while(stream >> klass >> attrib >> lambda){ ++nlines; features.push_back(Feature(klass, static_cast<float>(exp(lambda)))); if(attrib != previous){ attrib2feats.push_back(&features.back()); previous = attrib; } } if(!stream.eof()) throw NLP::IOException("could not parse feature tuple", cfg.weights(), nlines); if(features.size() != info.nfeatures()) throw NLP::IOException("number of features read != configuration value", cfg.weights(), nlines); attrib2feats.push_back(&features.back() + 1); if(attrib2feats.size() != info.nattributes() + 1) throw NLP::IOException("number of attributes read != configuration value", cfg.weights(), nlines); } void Tagger::Impl::_read_attributes(const Model::Model &cfg, const Model::Info &info, vector<Feature *> &attrib2feats){ ulong nlines = 0; std::string filename = cfg.attributes(); try { ulong id = 0; // now the contextual elements ifstream stream(filename.c_str()); if(!stream) throw NLP::IOException("could not open attributes file", filename); read_preface(filename, stream, nlines); std::string type; ulong freq = 0; while(stream >> type){ ++nlines; if(id >= info.nattributes()) throw NLP::IOException("inconsistent attribute index (>= nattributes)", filename, nlines); Attribute &attrib = registry.load(type, stream); if(!(stream >> freq)) { stream >> type; printf("failed to read freq value - got: %s\n", type.c_str()); break; } if(stream.get() != '\n') throw IOException("expected a newline after the attribute", filename, nlines); attrib.begin = attrib2feats[id]; attrib.end = attrib2feats[id + 1]; ++id; } if(!stream.eof()) throw NLP::IOException("could not parse attribute", filename, nlines); if(id != info.nattributes()) throw NLP::IOException("number of attributes read != info file value", filename, nlines); }catch(NLP::Exception e){ throw NLP::IOException(e.msg, filename, nlines); } } Tagger::Impl::Impl(const std::string &name, Tagger::Config &cfg) : name(name), klasses("klasses", cfg.model.klasses()), lexicon("lexicon", cfg.model.lexicon()), tagdict("tagdict", cfg.tagdict(), cfg.tagdict_ratio(), cfg.tagdict_min(), klasses, lexicon), registry("registry"), pk_attribs(klasses), ppkpk_attribs(klasses), w_attribs(lexicon), ww_attribs(lexicon), www_attribs(lexicon), rare_cutoff(cfg.rare_cutoff()), beam_width(cfg.beam_width()), beam_ratio(log(cfg.beam_ratio())), forward_beam_ratio(cfg.forward_beam_ratio()), maxwords(cfg.maxwords()){} Tagger::Impl::~Impl(void){} } }
32.012821
102
0.682619
[ "vector", "model" ]
e714ba9163842789fc350ed9c1a68ebfa894daee
763
cpp
C++
Sequential Digits.cpp
chaitanyks/fuzzy-disco
bc52f779c68da3f259f116cc1f41c464db290fbf
[ "MIT" ]
1
2021-12-12T05:55:44.000Z
2021-12-12T05:55:44.000Z
Sequential Digits.cpp
chaitanyks/fuzzy-disco
bc52f779c68da3f259f116cc1f41c464db290fbf
[ "MIT" ]
null
null
null
Sequential Digits.cpp
chaitanyks/fuzzy-disco
bc52f779c68da3f259f116cc1f41c464db290fbf
[ "MIT" ]
null
null
null
// https://leetcode.com/problems/sequential-digits/submissions/ // 1291. Sequential Digits class Solution { public: vector<int> sequentialDigits(int low, int high) { vector<int> ans; vector<int> digit; for (int i = 0; i <= 9; i++) digit.push_back(i); int val; for (int len = 2; len <= 9; len++) { for (int d = 0; d < digit.size() - len; d++) { val = 0; for (int i = 1; i <= len; i++) { val = val * 10 + digit[d + i]; } // cout<<val<<" "; if (val >= low && val <= high) ans.push_back(val); } } return ans; } };
25.433333
63
0.397117
[ "vector" ]
e7165116c18f7a8fe63a5019390ad82cfa9aed92
4,025
cpp
C++
apps/void/app.cpp
ContentsViewer/nodec
40b414a2f48d2e4718b69e0fa630e3f85e90e083
[ "Apache-2.0" ]
2
2022-01-03T12:01:03.000Z
2022-01-04T18:11:25.000Z
apps/void/app.cpp
ContentsViewer/nodec
40b414a2f48d2e4718b69e0fa630e3f85e90e083
[ "Apache-2.0" ]
null
null
null
apps/void/app.cpp
ContentsViewer/nodec
40b414a2f48d2e4718b69e0fa630e3f85e90e083
[ "Apache-2.0" ]
null
null
null
#include "app.hpp" // //#include "test_cube.hpp" //#include "player.hpp" using namespace nodec_engine; using namespace scene_set; using namespace screen; class HelloWorld { public: HelloWorld(NodecEngine& engine) { engine.stepped().connect([=](NodecEngine& engine) { on_step(engine); }); engine.initialized().connect([=](NodecEngine& engine) { on_initialized(engine); }); nodec::logging::InfoStream(__FILE__, __LINE__) << "[HelloWorld::HelloWorld] >>> Hello :)"; } ~HelloWorld() { nodec::logging::InfoStream(__FILE__, __LINE__) << "[HelloWorld::~HelloWorld] >>> See you ;)"; } private: void on_step(NodecEngine& engine) { //auto& scene = engine.get_module<Scene>(); //auto entity = scene.create_entity("OOO"); //nodec::logging::InfoStream(__FILE__, __LINE__) << "[HelloWorld::on_step] engine time: " << engine.engine_time(); } void on_initialized(NodecEngine& engine) { nodec::logging::InfoStream(__FILE__, __LINE__) << "[HelloWorld::on_initialized] engine time: " << engine.engine_time(); auto& scene = engine.get_module<Scene>(); auto entity = scene.create_entity("Hello World!!"); } }; void nodec_engine::on_boot(NodecEngine& engine) { using namespace nodec; logging::InfoStream(__FILE__, __LINE__) << "[App] >>> booting..."; logging::InfoStream(__FILE__, __LINE__) << "[App] >>> Hello world!"; auto& screen = engine.get_module<Screen>(); screen.set_size({ 1920, 1080 }); screen.set_resolution({ 1280, 720 }); screen.set_title("[ void ]"); engine.add_module(std::make_shared<HelloWorld>(engine)); } // //using namespace nodec; //using namespace game_engine; //using namespace nodec_modules::rendering::interfaces; //using namespace nodec_modules::screen::interfaces; //using namespace nodec_extentions::material_set; // //NodecObject::Reference<Camera> App::main_camera; // // //void game_engine::on_boot(GameEngine& engine) //{ // nodec::logging::info("booting... in application layer", __FILE__, __LINE__); // nodec::logging::info("HELLO WORLD!", __FILE__, __LINE__); // // engine.screen().set_size({ 1280, 720 }); // engine.screen().set_resolution({ 1920, 1080 }); // engine.screen().set_title("[ void ]"); // // // auto player = NodecObject::instanciate<scene_set::SceneObject>("Player"); // player->add_component<Player>(); // App::main_camera = player->add_component<Camera>(); // engine.root_scene_object().append_child(player); // // // auto test_object_1 = NodecObject::instanciate<nodec::scene_set::SceneObject>("test_1"); // test_object_1->add_component<TestCube>(); // test_object_1->transform().local_position.y = 1.6; // test_object_1->transform().local_position.z = 2; // //player->append_child(test_object_1); // engine.root_scene_object().append_child(test_object_1); // // //} // //void game_engine::on_boot(game_engine::GameEngine& engine) { // logging::info("booting... in application layer", __FILE__, __LINE__); // logging::info("HELLO WORLD!", __FILE__, __LINE__); // // // // //engine.screen().set_size({ 1920, 1080 }); // engine.screen().set_size({ 1280, 720 }); // engine.screen().set_resolution({ 1280, 720 }); // engine.screen().set_title("[ void ]"); // // auto root = engine.scene_registry().create_entity(); // auto child1 = engine.scene_registry().create_entity(); // auto child1_1 = engine.scene_registry().create_entity(); // auto child2 = engine.scene_registry().create_entity(); // // scene_set::systems::append_child(engine.scene_registry(), root, child1); // scene_set::systems::append_child(engine.scene_registry(), root, child2); // scene_set::systems::append_child(engine.scene_registry(), child1, child1_1); // // engine.scene_registry().emplace_component<scene_set::components::Name>(root); // engine.scene_registry().get_component<scene_set::components::Name>(root).name = "root"; // // //}
32.991803
127
0.663602
[ "transform" ]
e717f09dc6bc0561a84abbae04d64e27899b85ff
6,703
cpp
C++
Graphics/GraphicsEngineD3D11/src/D3D11TypeConversions.cpp
dtcxzyw/DiligentCore
e3891d4936956bb6228f1e949ea57810ab7cb08c
[ "Apache-2.0" ]
15
2021-07-03T17:20:50.000Z
2022-03-20T23:39:09.000Z
Graphics/GraphicsEngineD3D11/src/D3D11TypeConversions.cpp
dtcxzyw/DiligentCore
e3891d4936956bb6228f1e949ea57810ab7cb08c
[ "Apache-2.0" ]
1
2021-08-09T15:10:17.000Z
2021-09-30T06:47:04.000Z
Graphics/GraphicsEngineD3D11/src/D3D11TypeConversions.cpp
dtcxzyw/DiligentCore
e3891d4936956bb6228f1e949ea57810ab7cb08c
[ "Apache-2.0" ]
9
2021-07-21T10:53:59.000Z
2022-03-03T10:27:33.000Z
/* * Copyright 2019-2020 Diligent Graphics LLC * Copyright 2015-2019 Egor Yusov * * 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. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "pch.h" #include "D3D11TypeConversions.hpp" #include "D3D11TypeDefinitions.h" #include "D3DTypeConversionImpl.hpp" #include "D3DViewDescConversionImpl.hpp" namespace Diligent { D3D11_FILTER FilterTypeToD3D11Filter(FILTER_TYPE MinFilter, FILTER_TYPE MagFilter, FILTER_TYPE MipFilter) { return FilterTypeToD3DFilter<D3D11_FILTER>(MinFilter, MagFilter, MipFilter); } D3D11_TEXTURE_ADDRESS_MODE TexAddressModeToD3D11AddressMode(TEXTURE_ADDRESS_MODE Mode) { return TexAddressModeToD3DAddressMode<D3D11_TEXTURE_ADDRESS_MODE>(Mode); } D3D11_COMPARISON_FUNC ComparisonFuncToD3D11ComparisonFunc(COMPARISON_FUNCTION Func) { return ComparisonFuncToD3DComparisonFunc<D3D11_COMPARISON_FUNC>(Func); } void DepthStencilStateDesc_To_D3D11_DEPTH_STENCIL_DESC(const DepthStencilStateDesc& DepthStencilDesc, D3D11_DEPTH_STENCIL_DESC& d3d11DSSDesc) { DepthStencilStateDesc_To_D3D_DEPTH_STENCIL_DESC<D3D11_DEPTH_STENCIL_DESC, D3D11_DEPTH_STENCILOP_DESC, D3D11_STENCIL_OP, D3D11_COMPARISON_FUNC>(DepthStencilDesc, d3d11DSSDesc); } void RasterizerStateDesc_To_D3D11_RASTERIZER_DESC(const RasterizerStateDesc& RasterizerDesc, D3D11_RASTERIZER_DESC& d3d11RSDesc) { RasterizerStateDesc_To_D3D_RASTERIZER_DESC<D3D11_RASTERIZER_DESC, D3D11_FILL_MODE, D3D11_CULL_MODE>(RasterizerDesc, d3d11RSDesc); d3d11RSDesc.ScissorEnable = RasterizerDesc.ScissorEnable ? TRUE : FALSE; } void BlendStateDesc_To_D3D11_BLEND_DESC(const BlendStateDesc& BSDesc, D3D11_BLEND_DESC& d3d11BSDesc) { BlendStateDescToD3DBlendDesc<D3D11_BLEND_DESC, D3D11_BLEND, D3D11_BLEND_OP>(BSDesc, d3d11BSDesc); for (int i = 0; i < 8; ++i) { const auto& SrcRTDesc = BSDesc.RenderTargets[i]; if (SrcRTDesc.LogicOperationEnable) { LOG_ERROR("Logical operations on render targets are not supported by D3D11 device"); } } } void LayoutElements_To_D3D11_INPUT_ELEMENT_DESCs(const InputLayoutDesc& InputLayout, std::vector<D3D11_INPUT_ELEMENT_DESC, STDAllocatorRawMem<D3D11_INPUT_ELEMENT_DESC>>& D3D11InputElements) { LayoutElements_To_D3D_INPUT_ELEMENT_DESCs<D3D11_INPUT_ELEMENT_DESC>(InputLayout, D3D11InputElements); } D3D11_PRIMITIVE_TOPOLOGY TopologyToD3D11Topology(PRIMITIVE_TOPOLOGY Topology) { return TopologyToD3DTopology<D3D11_PRIMITIVE_TOPOLOGY>(Topology); } void TextureViewDesc_to_D3D11_SRV_DESC(const TextureViewDesc& TexViewDesc, D3D11_SHADER_RESOURCE_VIEW_DESC& D3D11SRVDesc, Uint32 SampleCount) { TextureViewDesc_to_D3D_SRV_DESC(TexViewDesc, D3D11SRVDesc, SampleCount); } void TextureViewDesc_to_D3D11_RTV_DESC(const TextureViewDesc& TexViewDesc, D3D11_RENDER_TARGET_VIEW_DESC& D3D11RTVDesc, Uint32 SampleCount) { TextureViewDesc_to_D3D_RTV_DESC(TexViewDesc, D3D11RTVDesc, SampleCount); } void TextureViewDesc_to_D3D11_DSV_DESC(const TextureViewDesc& TexViewDesc, D3D11_DEPTH_STENCIL_VIEW_DESC& D3D11DSVDesc, Uint32 SampleCount) { TextureViewDesc_to_D3D_DSV_DESC(TexViewDesc, D3D11DSVDesc, SampleCount); } void TextureViewDesc_to_D3D11_UAV_DESC(const TextureViewDesc& TexViewDesc, D3D11_UNORDERED_ACCESS_VIEW_DESC& D3D11UAVDesc) { TextureViewDesc_to_D3D_UAV_DESC(TexViewDesc, D3D11UAVDesc); } void BufferViewDesc_to_D3D11_SRV_DESC(const BufferDesc& BuffDesc, const BufferViewDesc& SRVDesc, D3D11_SHADER_RESOURCE_VIEW_DESC& D3D11SRVDesc) { if (BuffDesc.Mode == BUFFER_MODE_RAW && SRVDesc.Format.ValueType == VT_UNDEFINED) { // Raw buffer view UINT ElementByteStride = 4; DEV_CHECK_ERR((SRVDesc.ByteOffset % 16) == 0, "Byte offest (", SRVDesc.ByteOffset, ") is not multiple of 16"); DEV_CHECK_ERR((SRVDesc.ByteWidth % ElementByteStride) == 0, "Byte width (", SRVDesc.ByteWidth, ") is not multiple of 4"); D3D11SRVDesc.BufferEx.FirstElement = SRVDesc.ByteOffset / ElementByteStride; D3D11SRVDesc.BufferEx.NumElements = SRVDesc.ByteWidth / ElementByteStride; D3D11SRVDesc.BufferEx.Flags = D3D11_BUFFEREX_SRV_FLAG_RAW; D3D11SRVDesc.Format = DXGI_FORMAT_R32_TYPELESS; D3D11SRVDesc.ViewDimension = D3D_SRV_DIMENSION_BUFFEREX; } else { BufferViewDesc_to_D3D_SRV_DESC(BuffDesc, SRVDesc, D3D11SRVDesc); } } void BufferViewDesc_to_D3D11_UAV_DESC(const BufferDesc& BuffDesc, const BufferViewDesc& UAVDesc, D3D11_UNORDERED_ACCESS_VIEW_DESC& D3D11UAVDesc) { BufferViewDesc_to_D3D_UAV_DESC(BuffDesc, UAVDesc, D3D11UAVDesc); } } // namespace Diligent
43.525974
179
0.688199
[ "render", "vector" ]
e71c1114a75b9ab88c262229890cb3942465ac9b
466
hpp
C++
src/include/trcp/common/SRoad.hpp
AntonMyrhorod/Traffic-Capacity
a8f744a8e9b9016c34f0cb47a7fae09627117aa2
[ "MIT" ]
null
null
null
src/include/trcp/common/SRoad.hpp
AntonMyrhorod/Traffic-Capacity
a8f744a8e9b9016c34f0cb47a7fae09627117aa2
[ "MIT" ]
null
null
null
src/include/trcp/common/SRoad.hpp
AntonMyrhorod/Traffic-Capacity
a8f744a8e9b9016c34f0cb47a7fae09627117aa2
[ "MIT" ]
null
null
null
#pragma once // Standard includes #include <string> #include <vector> // Third-party includes // Non-local includes // Local includes #include "SPoint.hpp" #include "STimeInterval.hpp" namespace trcp { namespace data { struct SRoad { std::string m_name; SPoint m_start; SPoint m_finish; float m_distance = 0; // kilometers [km] int m_lines = 0; std::vector<STimeInterval> m_timeIntervals; }; } // namespace data } // namespace trcp
13.314286
47
0.684549
[ "vector" ]
e7216b2d457ecf66a3b74835794ada0befa58648
6,461
cc
C++
tensorflow/core/common_runtime/data/standalone_test.cc
MathMachado/tensorflow
56afda20b15f234c23e8393f7e337e7dd2659c2d
[ "Apache-2.0" ]
848
2019-12-03T00:16:17.000Z
2022-03-31T22:53:17.000Z
tensorflow/core/common_runtime/data/standalone_test.cc
MathMachado/tensorflow
56afda20b15f234c23e8393f7e337e7dd2659c2d
[ "Apache-2.0" ]
656
2019-12-03T00:48:46.000Z
2022-03-31T18:41:54.000Z
tensorflow/core/common_runtime/data/standalone_test.cc
MathMachado/tensorflow
56afda20b15f234c23e8393f7e337e7dd2659c2d
[ "Apache-2.0" ]
506
2019-12-03T00:46:26.000Z
2022-03-30T10:34:56.000Z
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/common_runtime/data/standalone.h" #include <memory> #include <vector> #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace data { namespace standalone { namespace { constexpr const char* const kRangeGraphProto = R"proto( node { name: "Const/_0" op: "Const" attr { key: "dtype" value { type: DT_INT64 } } attr { key: "value" value { tensor { dtype: DT_INT64 tensor_shape {} int64_val: 0 } } } } node { name: "Const/_1" op: "Const" attr { key: "dtype" value { type: DT_INT64 } } attr { key: "value" value { tensor { dtype: DT_INT64 tensor_shape {} int64_val: 10 } } } } node { name: "Const/_2" op: "Const" attr { key: "dtype" value { type: DT_INT64 } } attr { key: "value" value { tensor { dtype: DT_INT64 tensor_shape {} int64_val: 1 } } } } node { name: "RangeDataset/_3" op: "RangeDataset" input: "Const/_0" input: "Const/_1" input: "Const/_2" attr { key: "output_shapes" value { list { shape {} } } } attr { key: "output_types" value { list { type: DT_INT64 } } } } node { name: "dataset" op: "_Retval" input: "RangeDataset/_3" attr { key: "T" value { type: DT_VARIANT } } attr { key: "index" value { i: 0 } } } library {} versions { producer: 96 } )proto"; // range(10).map(lambda x: x*x) constexpr const char* const kMapGraphProto = R"proto( node { name: "Const/_0" op: "Const" attr { key: "dtype" value { type: DT_INT64 } } attr { key: "value" value { tensor { dtype: DT_INT64 tensor_shape {} int64_val: 0 } } } } node { name: "Const/_1" op: "Const" attr { key: "dtype" value { type: DT_INT64 } } attr { key: "value" value { tensor { dtype: DT_INT64 tensor_shape {} int64_val: 10 } } } } node { name: "Const/_2" op: "Const" attr { key: "dtype" value { type: DT_INT64 } } attr { key: "value" value { tensor { dtype: DT_INT64 tensor_shape {} int64_val: 1 } } } } node { name: "RangeDataset/_3" op: "RangeDataset" input: "Const/_0" input: "Const/_1" input: "Const/_2" attr { key: "output_shapes" value { list { shape {} } } } attr { key: "output_types" value { list { type: DT_INT64 } } } } node { name: "MapDataset/_4" op: "MapDataset" input: "RangeDataset/_3" attr { key: "Targuments" value { list {} } } attr { key: "f" value { func { name: "__inference_Dataset_map_<lambda>_67" } } } attr { key: "output_shapes" value { list { shape {} } } } attr { key: "output_types" value { list { type: DT_INT64 } } } attr { key: "preserve_cardinality" value { b: false } } attr { key: "use_inter_op_parallelism" value { b: true } } } node { name: "dataset" op: "_Retval" input: "MapDataset/_4" attr { key: "T" value { type: DT_VARIANT } } attr { key: "index" value { i: 0 } } } library { function { signature { name: "__inference_Dataset_map_<lambda>_67" input_arg { name: "args_0" type: DT_INT64 } output_arg { name: "identity" type: DT_INT64 } } node_def { name: "mul" op: "Mul" input: "args_0" input: "args_0" attr { key: "T" value { type: DT_INT64 } } } node_def { name: "Identity" op: "Identity" input: "mul:z:0" attr { key: "T" value { type: DT_INT64 } } } ret { key: "identity" value: "Identity:output:0" } arg_attr { key: 0 value { attr { key: "_user_specified_name" value { s: "args_0" } } } } } } versions { producer: 96 min_consumer: 12 } )proto"; TEST(Scalar, Standalone) { struct TestCase { string graph_string; std::vector<int64> expected_outputs; }; auto test_cases = { TestCase{kRangeGraphProto, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}, TestCase{kMapGraphProto, {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}}, }; for (auto test_case : test_cases) { GraphDef graph_def; protobuf::TextFormat::ParseFromString(test_case.graph_string, &graph_def); std::unique_ptr<Dataset> dataset; auto s = Dataset::FromGraph({}, graph_def, &dataset); TF_EXPECT_OK(s); std::unique_ptr<Iterator> iterator; s = dataset->MakeIterator(&iterator); TF_EXPECT_OK(s); bool end_of_input = false; for (int num_outputs = 0; !end_of_input; ++num_outputs) { std::vector<tensorflow::Tensor> outputs; s = iterator->GetNext(&outputs, &end_of_input); TF_EXPECT_OK(s); if (!end_of_input) { EXPECT_EQ(outputs[0].scalar<int64>()(), test_case.expected_outputs[num_outputs]); } else { EXPECT_EQ(test_case.expected_outputs.size(), num_outputs); } } } } } // namespace } // namespace standalone } // namespace data } // namespace tensorflow
20.977273
80
0.526699
[ "shape", "vector" ]
e72367784be9d55955315bd2ef320e97d72f5e47
21,695
cpp
C++
SampleCode/StdDriver/USBD_HID_Transfer_CTRL/WindowsTool/HIDCtrlTransferTest/HIDCtrlTransferTestDlg.cpp
OpenNuvoton/M253BSP
519fbc802cdd0077a9f50b0d82a9ef353ff67cdf
[ "Apache-2.0" ]
null
null
null
SampleCode/StdDriver/USBD_HID_Transfer_CTRL/WindowsTool/HIDCtrlTransferTest/HIDCtrlTransferTestDlg.cpp
OpenNuvoton/M253BSP
519fbc802cdd0077a9f50b0d82a9ef353ff67cdf
[ "Apache-2.0" ]
null
null
null
SampleCode/StdDriver/USBD_HID_Transfer_CTRL/WindowsTool/HIDCtrlTransferTest/HIDCtrlTransferTestDlg.cpp
OpenNuvoton/M253BSP
519fbc802cdd0077a9f50b0d82a9ef353ff67cdf
[ "Apache-2.0" ]
null
null
null
// HIDCtrlTransferTestDlg.cpp : implementation file // #include "stdafx.h" #include "HIDCtrlTransferTest.h" #include "HIDCtrlTransferTestDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif extern "C" { // This file is in the Windows DDK available from Microsoft. #include "hidsdi.h" #include "setupapi.h" #include <dbt.h> } // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CHIDCtrlTransferTestDlg dialog CHIDCtrlTransferTestDlg::CHIDCtrlTransferTestDlg(CWnd* pParent /*=NULL*/) : CDialog(CHIDCtrlTransferTestDlg::IDD, pParent) { m_ProductIDString = _T("0520"); m_VendorIDString = _T("0416"); m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } //Application global variables HIDP_CAPS Capabilities; PSP_DEVICE_INTERFACE_DETAIL_DATA detailData; HANDLE DeviceHandle; DWORD dwError; HANDLE hEventObject; HANDLE hDevInfo; GUID HidGuid; OVERLAPPED HIDOverlapped; char InputReport[256]; ULONG Length; LPOVERLAPPED lpOverLap; bool MyDeviceDetected = FALSE; CString MyDevicePathName; DWORD NumberOfBytesRead; char OutputReport[256]; HANDLE ReadHandle; ULONG Required; HANDLE WriteHandle; int VendorID = 0x0416; int ProductID = 0x5020; void CHIDCtrlTransferTestDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_VendorIDString); DDX_Text(pDX, IDC_EDIT2, m_ProductIDString); DDX_Control(pDX, IDC_BUTTON3, m_SendAndReceive); DDX_Control(pDX, IDC_LIST2, m_ResultsList); } BEGIN_MESSAGE_MAP(CHIDCtrlTransferTestDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON1, &CHIDCtrlTransferTestDlg::OnBnClickedButton1) ON_EN_CHANGE(IDC_EDIT2, &CHIDCtrlTransferTestDlg::OnEnChangeEdit2) ON_BN_CLICKED(IDC_BUTTON3, &CHIDCtrlTransferTestDlg::OnBnClickedButton3) ON_WM_TIMER() ON_MESSAGE(WM_DEVICECHANGE, Main_OnDeviceChange) END_MESSAGE_MAP() // CHIDCtrlTransferTestDlg message handlers BOOL CHIDCtrlTransferTestDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { CString strAboutMenu; strAboutMenu.LoadString(IDS_ABOUTBOX); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon // TODO: Add extra initialization here MyDeviceDetected=FALSE; return TRUE; // return TRUE unless you set the focus to a control } void CHIDCtrlTransferTestDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CHIDCtrlTransferTestDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CHIDCtrlTransferTestDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CHIDCtrlTransferTestDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: Add your message handler code here and/or call default //The timer event. //Read and Write one pair of reports. ReadAndWriteToDevice(); CDialog::OnTimer(nIDEvent); } void CHIDCtrlTransferTestDlg::DisplayData(CString cstrDataToDisplay) { //Display data in the log List Box USHORT Index; Index=m_ResultsList.InsertString(-1, (LPCTSTR)cstrDataToDisplay); ScrollToBottomOfListBox(Index); } BOOL CHIDCtrlTransferTestDlg::DeviceNameMatch(LPARAM lParam) { // Compare the device path name of a device recently attached or removed // with the device path name of the device we want to communicate with. PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam; DisplayData(_T("MyDevicePathName = ") + MyDevicePathName); if (lpdb->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE) { PDEV_BROADCAST_DEVICEINTERFACE lpdbi = (PDEV_BROADCAST_DEVICEINTERFACE)lParam; CString DeviceNameString; //The dbch_devicetype parameter indicates that the event applies to a device interface. //So the structure in LParam is actually a DEV_BROADCAST_INTERFACE structure, //which begins with a DEV_BROADCAST_HDR. //The dbcc_name parameter of DevBroadcastDeviceInterface contains the device name. //Compare the name of the newly attached device with the name of the device //the application is accessing (myDevicePathName). DeviceNameString = lpdbi->dbcc_name; DisplayData(_T("DeviceNameString = ") + DeviceNameString); if ((DeviceNameString.CompareNoCase(MyDevicePathName)) == 0) { //The name matches. return true; } else { //It's a different device. return false; } } else { return false; } } void CHIDCtrlTransferTestDlg::CloseHandles() { //Close open handles. if (DeviceHandle != INVALID_HANDLE_VALUE) { CloseHandle(DeviceHandle); } if (ReadHandle != INVALID_HANDLE_VALUE) { CloseHandle(ReadHandle); } if (WriteHandle != INVALID_HANDLE_VALUE) { CloseHandle(WriteHandle); } } LRESULT CHIDCtrlTransferTestDlg::Main_OnDeviceChange(WPARAM wParam, LPARAM lParam) { //DisplayData("Device change detected."); PDEV_BROADCAST_HDR lpdb = (PDEV_BROADCAST_HDR)lParam; switch(wParam) { // Find out if a device has been attached or removed. // If yes, see if the name matches the device path name of the device we want to access. case DBT_DEVICEARRIVAL: DisplayData(_T("A device has been attached.")); if (DeviceNameMatch(lParam)) { DisplayData(_T("Device has been attached.")); } return TRUE; case DBT_DEVICEREMOVECOMPLETE: DisplayData(_T("Device has been removed.")); if (DeviceNameMatch(lParam)) { DisplayData(_T("Device has been removed.")); // Look for the device on the next transfer attempt. MyDeviceDetected = false; } return TRUE; default: return TRUE; } } void CHIDCtrlTransferTestDlg::GetDeviceCapabilities() { //Get the Capabilities structure for the device. PHIDP_PREPARSED_DATA PreparsedData; /* API function: HidD_GetPreparsedData Returns: a pointer to a buffer containing the information about the device's capabilities. Requires: A handle returned by CreateFile. There's no need to access the buffer directly, but HidP_GetCaps and other API functions require a pointer to the buffer. */ HidD_GetPreparsedData (DeviceHandle, &PreparsedData); /* API function: HidP_GetCaps Learn the device's capabilities. For standard devices such as joysticks, you can find out the specific capabilities of the device. For a custom device, the software will probably know what the device is capable of, and the call only verifies the information. Requires: the pointer to the buffer returned by HidD_GetPreparsedData. Returns: a Capabilities structure containing the information. */ HidP_GetCaps(PreparsedData, &Capabilities); HidD_FreePreparsedData(PreparsedData); } void CHIDCtrlTransferTestDlg::DisplayInputReport() { USHORT ByteNumber; //Display the received data in the log and the Bytes Received List boxes. //Start at the top of the List Box. // m_ResultsList.ResetContent(); //Step through the received bytes and display each. for (ByteNumber=0; ByteNumber < Capabilities.InputReportByteLength; ByteNumber++) { //Get a byte. CHAR ReceivedByte = InputReport[ByteNumber]; //Display it. if(ByteNumber>0) DisplayReceivedData(ReceivedByte); } DisplayData(_T("HID Transfer test ok!")); } void CHIDCtrlTransferTestDlg::DisplayReceivedData(char ReceivedByte) { //Display data received from the device. CString strByteRead; //Convert the value to a 2-character Cstring. strByteRead.Format(_T("%02X"), ReceivedByte); strByteRead = strByteRead.Right(2); //Display the value in the Bytes Received List Box. m_ResultsList.InsertString(-1, strByteRead); } void CHIDCtrlTransferTestDlg::OnBnClickedButton1() { // TODO: Add your control notification handler code here ConnectHID(); } bool CHIDCtrlTransferTestDlg::ConnectHID() { //Use a series of API calls to find a HID with a specified Vendor IF and Product ID. HIDD_ATTRIBUTES Attributes; DWORD DeviceUsage; SP_DEVICE_INTERFACE_DATA devInfoData; bool LastDevice = FALSE; int MemberIndex = 0; CString UsageDescription; CString DebugStr; Length = 0; detailData = NULL; DeviceHandle=NULL; /* API function: HidD_GetHidGuid Get the GUID for all system HIDs. Returns: the GUID in HidGuid. */ HidD_GetHidGuid(&HidGuid); /* API function: SetupDiGetClassDevs Returns: a handle to a device information set for all installed devices. Requires: the GUID returned by GetHidGuid. */ hDevInfo=SetupDiGetClassDevs (&HidGuid, NULL, NULL, DIGCF_PRESENT|DIGCF_INTERFACEDEVICE); devInfoData.cbSize = sizeof(devInfoData); //Step through the available devices looking for the one we want. //Quit on detecting the desired device or checking all available devices without success. MemberIndex = 0; LastDevice = FALSE; do { /* API function: SetupDiEnumDeviceInterfaces On return, MyDeviceInterfaceData contains the handle to a SP_DEVICE_INTERFACE_DATA structure for a detected device. Requires: The DeviceInfoSet returned in SetupDiGetClassDevs. The HidGuid returned in GetHidGuid. An index to specify a device. */ LONG Result=SetupDiEnumDeviceInterfaces (hDevInfo, 0, &HidGuid, MemberIndex, &devInfoData); if (Result != 0) { //A device has been detected, so get more information about it. /* API function: SetupDiGetDeviceInterfaceDetail Returns: an SP_DEVICE_INTERFACE_DETAIL_DATA structure containing information about a device. To retrieve the information, call this function twice. The first time returns the size of the structure in Length. The second time returns a pointer to the data in DeviceInfoSet. Requires: A DeviceInfoSet returned by SetupDiGetClassDevs The SP_DEVICE_INTERFACE_DATA structure returned by SetupDiEnumDeviceInterfaces. The final parameter is an optional pointer to an SP_DEV_INFO_DATA structure. This application doesn't retrieve or use the structure. If retrieving the structure, set MyDeviceInfoData.cbSize = length of MyDeviceInfoData. and pass the structure's address. */ //Get the Length value. //The call will return with a "buffer too small" error which can be ignored. SetupDiGetDeviceInterfaceDetail (hDevInfo, &devInfoData, NULL, 0, &Length, NULL); //Allocate memory for the hDevInfo structure, using the returned Length. detailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(Length); //Set cbSize in the detailData structure. detailData -> cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA); //Call the function again, this time passing it the returned buffer size. SetupDiGetDeviceInterfaceDetail (hDevInfo, &devInfoData, detailData, Length, &Required, NULL); // Open a handle to the device. // To enable retrieving information about a system mouse or keyboard, // don't request Read or Write access for this handle. /* API function: CreateFile Returns: a handle that enables reading and writing to the device. Requires: The DevicePath in the detailData structure returned by SetupDiGetDeviceInterfaceDetail. */ DeviceHandle=CreateFile (detailData->DevicePath, 0, FILE_SHARE_READ|FILE_SHARE_WRITE, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, 0, NULL); /* API function: HidD_GetAttributes Requests information from the device. Requires: the handle returned by CreateFile. Returns: a HIDD_ATTRIBUTES structure containing the Vendor ID, Product ID, and Product Version Number. Use this information to decide if the detected device is the one we're looking for. */ //Set the Size to the number of bytes in the structure. Attributes.Size = sizeof(Attributes); Result = HidD_GetAttributes (DeviceHandle, &Attributes); //Is it the desired device? MyDeviceDetected = FALSE; if (Attributes.VendorID == VendorID) { if (Attributes.ProductID == ProductID) { //Both the Vendor ID and Product ID match. MyDeviceDetected = TRUE; MyDevicePathName = detailData->DevicePath; DisplayData(_T("Device detected")); //Register to receive device notifications. RegisterForDeviceNotifications(); //Get the device's capablities. GetDeviceCapabilities(); // 利用HID Report Descriptor來辨識HID Transfer裝置 DeviceUsage = (Capabilities.UsagePage * 256) + Capabilities.Usage; if (DeviceUsage != 0xFF0001) // Report Descriptor continue; // Get a handle for writing Output reports. WriteHandle=CreateFile (detailData->DevicePath, GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, 0, NULL); // Prepare to read reports using Overlapped I/O. PrepareForOverlappedTransfer(); } //if (Attributes.ProductID == ProductID) else //The Product ID doesn't match. CloseHandle(DeviceHandle); } //if (Attributes.VendorID == VendorID) else //The Vendor ID doesn't match. CloseHandle(DeviceHandle); //Free the memory used by the detailData structure (no longer needed). free(detailData); } //if (Result != 0) else //SetupDiEnumDeviceInterfaces returned 0, so there are no more devices to check. LastDevice=TRUE; //If we haven't found the device yet, and haven't tried every available device, //try the next one. MemberIndex = MemberIndex + 1; } //do while ((LastDevice == FALSE) && (MyDeviceDetected == FALSE)); if (MyDeviceDetected == FALSE) DisplayData(_T("Device not detected")); else DisplayData(_T("Device detected")); //Free the memory reserved for hDevInfo by SetupDiClassDevs. SetupDiDestroyDeviceInfoList(hDevInfo); return MyDeviceDetected; } void CHIDCtrlTransferTestDlg::OnEnChangeEdit2() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here CString ProductIDtext; // Get the text in the edit box. CEdit* m_ProductID1 = (CEdit*) GetDlgItem(IDC_EDIT2); m_ProductID1->GetWindowText(ProductIDtext); // Convert the hex string in the edit box to an integer. ProductID = wcstoul(ProductIDtext, 0, 16); MyDeviceDetected=false; } void CHIDCtrlTransferTestDlg::RegisterForDeviceNotifications() { // Request to receive messages when a device is attached or removed. // Also see WM_DEVICECHANGE in BEGIN_MESSAGE_MAP(CUsbhidiocDlg, CDialog). DEV_BROADCAST_DEVICEINTERFACE DevBroadcastDeviceInterface; DevBroadcastDeviceInterface.dbcc_size = sizeof(DevBroadcastDeviceInterface); DevBroadcastDeviceInterface.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; DevBroadcastDeviceInterface.dbcc_classguid = HidGuid; RegisterDeviceNotification(m_hWnd, &DevBroadcastDeviceInterface, DEVICE_NOTIFY_WINDOW_HANDLE); } void CHIDCtrlTransferTestDlg::ScrollToBottomOfListBox(USHORT Index) { /* Scroll to the bottom of the list box. To do so, add a line and set it as the current selection, possibly scrolling the window. Then deselect the line, leaving the list box scrolled to the bottom with nothing selected. */ m_ResultsList.SetCurSel( Index ); m_ResultsList.SetCurSel( -1 ); } void CHIDCtrlTransferTestDlg::PrepareForOverlappedTransfer() { //Get a handle to the device for the overlapped ReadFiles. ReadHandle=CreateFile (detailData->DevicePath, GENERIC_READ, FILE_SHARE_READ|FILE_SHARE_WRITE, (LPSECURITY_ATTRIBUTES)NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL); //Get an event object for the overlapped structure. /*API function: CreateEvent Requires: Security attributes or Null Manual reset (true). Use ResetEvent to set the event object's state to non-signaled. Initial state (true = signaled) Event object name (optional) Returns: a handle to the event object */ if (hEventObject == 0) { hEventObject = CreateEvent (NULL, TRUE, TRUE, _T("")); //Set the members of the overlapped structure. HIDOverlapped.hEvent = hEventObject; HIDOverlapped.Offset = 0; HIDOverlapped.OffsetHigh = 0; } } void CHIDCtrlTransferTestDlg::OnBnClickedButton3() { // TODO: Add your control notification handler code here //Click the Continuous button to //begin or stop requesting and sending periodic reports. CString Caption; //Find out whether Continuous is currently selected //and take appropriate action. m_SendAndReceive.GetWindowText(Caption); //ReadAndWriteToDevice(); if (Caption == _T("Start")) { //Enable periodic exchanges of reports. //Change the button caption. m_SendAndReceive.SetWindowText(_T("Stop")); //Start by reading and writing one pair of reports. ReadAndWriteToDevice(); //Enable the timer to cause periodic exchange of reports. //The second parameter is the number of milliseconds between report requests. SetTimer(ID_CLOCK_TIMER, 5000, NULL); } else { //Stop periodic exchanges of reports. //Change the button caption. m_SendAndReceive.SetWindowText(_T("Start")); //Disable the timer. KillTimer(ID_CLOCK_TIMER); } } void CHIDCtrlTransferTestDlg::ReadAndWriteToDevice() { //If necessary, find the device and learn its capabilities. //Then send a report and request a report. DisplayData(_T("***HID Test Report***")); //If the device hasn't been detected already, look for it. if (MyDeviceDetected == FALSE) { MyDeviceDetected = ConnectHID(); } // Do nothing if the device isn't detected. if (MyDeviceDetected==TRUE) { // Output and Input Reports //Write a report to the device. WriteOutputReport(); //Read a report from the device. ReadInputReport(); } } void CHIDCtrlTransferTestDlg::WriteOutputReport() { //Send a report to the device. UpdateData(true); for(int i = 0; i < 64; i++) OutputReport[i] = i; //Send a report to the device. /* HidD_SetOutputReport Sends a report to the device. Returns: success or failure. Requires: The device handle returned by CreateFile. A buffer that holds the report. The Output Report length returned by HidP_GetCaps, */ if (WriteHandle != INVALID_HANDLE_VALUE) { ULONG Result = HidD_SetOutputReport (WriteHandle, OutputReport, Capabilities.OutputReportByteLength); if (Result) { DisplayData(_T("An Output report was written to the device.")); } else { //The write attempt failed, so close the handles, display a message, //and set MyDeviceDetected to FALSE so the next attempt will look for the device. CloseHandles(); DisplayData(_T("Can't write to device")); MyDeviceDetected = FALSE; } } } void CHIDCtrlTransferTestDlg::ReadInputReport() { // Retrieve an Input report from the device. DWORD Result; // Find out if the "Use Control Transfers Only" check box is checked. UpdateData(true); //Read a report from the device using a control transfer. /* HidD_GetInputReport Returns: True on success Requires: A device handle returned by CreateFile. A buffer to hold the report. The report length returned by HidP_GetCaps in Capabilities.InputReportByteLength. */ if (ReadHandle != INVALID_HANDLE_VALUE) { Result = HidD_GetInputReport (ReadHandle, InputReport, Capabilities.InputReportByteLength); } else { Result = FALSE; } if (!Result) { //The read attempt failed, so close the handles, display a message, //and set MyDeviceDetected to FALSE so the next attempt will look for the device. CloseHandles(); DisplayData(_T("Can't read from device")); MyDeviceDetected = FALSE; } else { DisplayData(_T("Received Input report: ")); //Display the report data. DisplayInputReport(); } }
24.186176
95
0.730629
[ "object", "model" ]
e72633182d37159c19129e50eaf1922a5b49f640
4,849
cpp
C++
PackingGeneration/Parallelism/Source/FileLock.cpp
MINATILO/packing-generation
4d4f5d037e0687b57178602b989431e82a5c8b96
[ "MIT" ]
79
2015-08-23T12:05:30.000Z
2022-03-31T16:39:56.000Z
PackingGeneration/Parallelism/Source/FileLock.cpp
MINATILO/packing-generation
4d4f5d037e0687b57178602b989431e82a5c8b96
[ "MIT" ]
31
2015-07-20T17:57:08.000Z
2022-03-02T10:31:50.000Z
PackingGeneration/Parallelism/Source/FileLock.cpp
MINATILO/packing-generation
4d4f5d037e0687b57178602b989431e82a5c8b96
[ "MIT" ]
36
2015-10-14T02:43:16.000Z
2022-03-18T12:51:03.000Z
// Copyright (c) 2013 Vasili Baranau // Distributed under the MIT software license // See the accompanying file License.txt or http://opensource.org/licenses/MIT #include "../Headers/FileLock.h" #include <stdio.h> #include <climits> #include "Core/Headers/Exceptions.h" #include "Core/Headers/MpiManager.h" #include "Core/Headers/StlUtilities.h" #include "Core/Headers/Math.h" #include "Core/Headers/Path.h" #include "Core/Headers/ScopedFile.h" #include "Core/Headers/Utilities.h" using namespace std; using namespace Core; namespace Parallelism { const string FileLock::semaphorePostfix = ".sem"; FileLock::FileLock(string filePath) { this->filePath = filePath; LockFile(filePath); } FileLock::~FileLock() { ReleaseFileLock(filePath); } void FileLock::LockFile(string filePath) { bool fileLocked = TryLockFile(filePath); while (!fileLocked) { Utilities::Sleep(200); fileLocked = TryLockFile(filePath); } } void FileLock::ReleaseFileLock(string filePath) { string semaphoreFilePath = GetSemaphoreFilePath(filePath); Path::DeleteFile(semaphoreFilePath); } string FileLock::GetSemaphoreFilePath(string filePath) { return filePath + "_" + Utilities::ConvertToString(MpiManager::GetInstance()->GetCurrentRank()) + semaphorePostfix; } bool FileLock::TryLockFile(string filePath) { // Get semaphore files for filePath vector<string> semaphoreFilePaths; FillSemaphoreFilePaths(filePath, &semaphoreFilePaths); // If exist, return false if (semaphoreFilePaths.size() > 0) { return false; } // Create a semaphore file string currentSemaphoreFilePath = GetSemaphoreFilePath(filePath); ScopedFile<ExceptionErrorHandler> semaphore(currentSemaphoreFilePath, FileOpenMode::Write); semaphore.Close(); // Wait for 100ms Utilities::Sleep(100); // Get semaphore files for filePath FillSemaphoreFilePaths(filePath, &semaphoreFilePaths); if (semaphoreFilePaths.size() == 1) // the only semaphore is the created one { return true; } else // some other semaphores have been created while we were creating ours { bool currentSemaphoreIsTheEarliest = CurrentSemaphoreIsTheEarliest(currentSemaphoreFilePath, semaphoreFilePaths); if (!currentSemaphoreIsTheEarliest) { Path::DeleteFile(currentSemaphoreFilePath); return false; } else { // Ours is the earliest one return true; } } } int FileLock::GetProcessRankBySemaphorePath(std::string semaphorePath) { string fileName = Path::GetFileName(semaphorePath); int rankStartIndex = fileName.find_last_of("_"); string rankAndPostfix = fileName.substr(rankStartIndex + 1); int postfixStartIndex = rankAndPostfix.find_last_of("."); string rankString = rankAndPostfix.substr(0, postfixStartIndex); return Utilities::ParseInt(rankString.c_str()); } bool FileLock::CurrentSemaphoreIsTheEarliest(string currentSemaphoreFilePath, const vector<string>& semaphoreFilePaths) { int minRank = INT_MAX; for (size_t i = 0; i < semaphoreFilePaths.size(); ++i) { // Avoid actual reading of semaphore files, as the current semaphore might have been the true lock, and was already released. // Or this semaphore might have been not the earliest lock, and might have already been deleted by the owner. // We may also lock the file prior to deletion, etc. int rank = GetProcessRankBySemaphorePath(semaphoreFilePaths[i]); bool semaphoreIsEarlier = rank < minRank; if (semaphoreIsEarlier) { minRank = rank; } } return minRank == MpiManager::GetInstance()->GetCurrentRank(); } void FileLock::FillSemaphoreFilePaths(string filePath, vector<string>* semaphoreFilePaths) { string folderPath = Path::GetParentPath(filePath); string fileNameToCheck = Path::GetFileName(filePath); vector<string> fileNames; Path::FillFileNames(folderPath, &fileNames); semaphoreFilePaths->clear(); for (size_t i = 0; i < fileNames.size(); ++i) { string fileName = fileNames[i]; if (Utilities::StringStartsWith(fileName, fileNameToCheck) && Utilities::StringEndsWith(fileName, semaphorePostfix)) { semaphoreFilePaths->push_back(Path::Append(folderPath, fileName)); } } } }
32.986395
137
0.638895
[ "vector" ]
e7294cb3e060f2caffcd8af76c6a1f301e2e84a2
8,844
cc
C++
tensorflow/core/kernels/transpose_op.cc
jylinman/tensorflow
5248d111c3aeaf9f560cd77bff0f183f38e31e0b
[ "Apache-2.0" ]
3
2017-03-05T01:56:21.000Z
2018-02-04T17:03:22.000Z
tensorflow/core/kernels/transpose_op.cc
jylinman/tensorflow
5248d111c3aeaf9f560cd77bff0f183f38e31e0b
[ "Apache-2.0" ]
null
null
null
tensorflow/core/kernels/transpose_op.cc
jylinman/tensorflow
5248d111c3aeaf9f560cd77bff0f183f38e31e0b
[ "Apache-2.0" ]
3
2017-02-23T03:20:29.000Z
2018-03-31T11:35:04.000Z
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/array_ops.cc. #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/transpose_op.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/kernels/transpose_op_functor.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/logging.h" namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; typedef Eigen::GpuDevice GPUDevice; // inv = InvertPermutationOp(T<int32> p) takes a permutation of // integers 0, 1, ..., n - 1 and returns the inverted // permutation of p. I.e., inv[p[i]] == i, for i in [0 .. n). // // REQUIRES: input is a vector of int32. // REQUIRES: input is a permutation of 0, 1, ..., n-1. class InvertPermutationOp : public OpKernel { public: explicit InvertPermutationOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor& input = context->input(0); OP_REQUIRES( context, TensorShapeUtils::IsVector(input.shape()), errors::InvalidArgument("invert_permutation expects a 1D vector.")); auto Tin = input.vec<int32>(); const int N = Tin.size(); Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, input.shape(), &output)); auto Tout = output->vec<int32>(); std::fill_n(Tout.data(), N, -1); for (int i = 0; i < N; ++i) { const int32 d = Tin(i); OP_REQUIRES(context, 0 <= d && d < N, errors::InvalidArgument(d, " is not between 0 and ", N)); OP_REQUIRES(context, Tout(d) == -1, errors::InvalidArgument(d, " is duplicated in the input.")); Tout(d) = i; } } }; REGISTER_KERNEL_BUILDER(Name("InvertPermutation").Device(DEVICE_CPU), InvertPermutationOp); REGISTER_KERNEL_BUILDER(Name("InvertPermutation") .Device(DEVICE_GPU) .HostMemory("x") .HostMemory("y"), InvertPermutationOp); // output = TransposeOp(T<any> input, T<int32> perm) takes a tensor // of type T and rank N, and a permutation of 0, 1, ..., N-1. It // shuffles the dimensions of the input tensor according to permutation. // // Specifically, the returned tensor output meets the following condition: // 1) output.dims() == input.dims(); // 2) output.dim_size(i) == input.dim_size(perm[i]); // 3) output.tensor<T, N>(i_0, i_1, ..., i_N-1) == // input.tensor<T, N>(j_0, j_1, ..., j_N-1), // where i_s == j_{perm[s]} // // REQUIRES: perm is a vector of int32. // REQUIRES: input.dims() == perm.size(). // REQUIRES: perm is a permutation. template <typename Device, typename T> TransposeOp<Device, T>::TransposeOp(OpKernelConstruction* context) : OpKernel(context) {} template <typename Device, typename T> void TransposeOp<Device, T>::Compute(OpKernelContext* context) { const Tensor& input = context->input(0); const Tensor& perm = context->input(1); // Preliminary validation of sizes. OP_REQUIRES(context, TensorShapeUtils::IsVector(perm.shape()), errors::InvalidArgument("perm must be a vector, not ", perm.shape().DebugString())); auto Vperm = perm.vec<int32>(); const int dims = input.dims(); static const int kMinDims = 0; static const int kMaxDims = 10; OP_REQUIRES(context, kMinDims <= dims && dims <= kMaxDims, errors::Unimplemented("Transposing a tensor of rank ", dims, " is not implemented.")); OP_REQUIRES(context, dims == Vperm.size(), errors::InvalidArgument( "transpose expects a vector of size ", input.dims(), ". But input(1) is a vector of size ", Vperm.size())); gtl::ArraySlice<int32> permutation( reinterpret_cast<const int32*>(Vperm.data()), dims); TensorShape shape; // Check whether permutation is a permutation of integers of [0 .. dims). gtl::InlinedVector<bool, 8> bits(dims); for (const int32 d : permutation) { OP_REQUIRES( context, 0 <= d && d < dims, errors::InvalidArgument(d, " is out of range [0 .. ", dims, ")")); bits[d] = true; shape.AddDim(input.dim_size(d)); } for (int i = 0; i < dims; ++i) { OP_REQUIRES(context, bits[i], errors::InvalidArgument( i, " is missing from {", str_util::Join(permutation, ","), "}.")); } // 0-D and 1-D transposes do nothing if (dims <= 1) { context->set_output(0, input); return; } Tensor* output = nullptr; OP_REQUIRES_OK(context, context->allocate_output(0, shape, &output)); TransposeTensor<Device, T>(context->eigen_device<Device>(), input, input.shape().dim_sizes(), permutation, output); } template <typename Device, typename T> void TransposeTensor(const Device& device, const Tensor& input, const gtl::ArraySlice<int64> input_shape, gtl::ArraySlice<int32> permutation, Tensor* output) { const int dims = input_shape.size(); CHECK(permutation.size() == dims); if (input.NumElements() == 0) { return; } switch (dims) { #define EXPAND_DIM(N) \ case N: { \ functor::TransposeFunctor<Device, T, N> func; \ func(device, output->tensor<T, N>(), input.shaped<T, N>(input_shape), \ permutation.data()); \ break; \ } EXPAND_DIM(2); EXPAND_DIM(3); EXPAND_DIM(4); EXPAND_DIM(5); EXPAND_DIM(6); EXPAND_DIM(7); EXPAND_DIM(8); EXPAND_DIM(9); EXPAND_DIM(10); default: LOG(FATAL) << "Unexpected dims: " << dims; } #undef EXPAND_CASE } namespace functor { template <typename Device, typename T, int NDIMS> void TransposeMaybeInline(const Device& d, typename TTypes<T, NDIMS>::Tensor out, typename TTypes<T, NDIMS>::ConstTensor in, const int* perm) { // perm[] is a permutation of 0, 1, ..., NDIMS-1. perm[] is on CPU. Eigen::array<int, NDIMS> p; for (int i = 0; i < NDIMS; ++i) p[i] = perm[i]; if (out.size() * sizeof(T) < 131072) { // Small transpose on a CPU: do inline out = in.shuffle(p); } else { out.device(d) = in.shuffle(p); } } template <typename T, int NDIMS> struct TransposeFunctor<CPUDevice, T, NDIMS> { void operator()(const CPUDevice& d, typename TTypes<T, NDIMS>::Tensor out, typename TTypes<T, NDIMS>::ConstTensor in, const int* perm) { TransposeMaybeInline<CPUDevice, T, NDIMS>(d, out, in, perm); } }; } // namespace functor #define REGISTER(D, T) \ template class TransposeOp<D##Device, T>; \ REGISTER_KERNEL_BUILDER(Name("Transpose") \ .Device(DEVICE_##D) \ .TypeConstraint<T>("T") \ .HostMemory("perm"), \ TransposeOp<D##Device, T>); \ template void TransposeTensor<D##Device, T>( \ const D##Device&, const Tensor&, const gtl::ArraySlice<int64>, \ gtl::ArraySlice<int32>, Tensor*); REGISTER(CPU, float); REGISTER(CPU, double); REGISTER(CPU, complex64); REGISTER(CPU, uint8); REGISTER(CPU, int8); REGISTER(CPU, int16); REGISTER(CPU, int32); REGISTER(CPU, int64); REGISTER(CPU, string); REGISTER(CPU, bool); #if GOOGLE_CUDA REGISTER(GPU, uint8); REGISTER(GPU, int8); REGISTER(GPU, int16); REGISTER(GPU, int32); REGISTER(GPU, int64); REGISTER(GPU, float); REGISTER(GPU, double); REGISTER(GPU, complex64); REGISTER(GPU, bool); #endif #undef REGISTER } // namespace tensorflow
37.159664
80
0.590796
[ "shape", "vector" ]
e72bfeb62fc94a81bfdcfc3e1c8ebb85dc6129fb
7,446
cpp
C++
cvs/objects/reporting/source/input_output_table.cpp
zcranmer/OWEProject
67d2367d6bdb5dd2a0aa0285be7e33ce64348677
[ "ECL-2.0" ]
null
null
null
cvs/objects/reporting/source/input_output_table.cpp
zcranmer/OWEProject
67d2367d6bdb5dd2a0aa0285be7e33ce64348677
[ "ECL-2.0" ]
null
null
null
cvs/objects/reporting/source/input_output_table.cpp
zcranmer/OWEProject
67d2367d6bdb5dd2a0aa0285be7e33ce64348677
[ "ECL-2.0" ]
null
null
null
/* * LEGAL NOTICE * This computer software was prepared by Battelle Memorial Institute, * hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830 * with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE * CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY * LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this * sentence must appear on any copies of this computer software. * * EXPORT CONTROL * User agrees that the Software will not be shipped, transferred or * exported into any country or used in any manner prohibited by the * United States Export Administration Act or any other applicable * export laws, restrictions or regulations (collectively the "Export Laws"). * Export of the Software may require some form of license or other * authority from the U.S. Government, and failure to obtain such * export control license may result in criminal liability under * U.S. laws. In addition, if the Software is identified as export controlled * items under the Export Laws, User represents and warrants that User * is not a citizen, or otherwise located within, an embargoed nation * (including without limitation Iran, Syria, Sudan, Cuba, and North Korea) * and that User is not otherwise prohibited * under the Export Laws from receiving the Software. * * Copyright 2011 Battelle Memorial Institute. All Rights Reserved. * Distributed as open-source under the terms of the Educational Community * License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php * * For further details, see: http://www.globalchange.umd.edu/models/gcam/ * */ /*! * \file input_output_table.cpp * \ingroup Objects * \brief The InputOutputTable class source file. * * \author Josh Lurz */ #include "util/base/include/definitions.h" #include <string> #include <vector> #include "reporting/include/input_output_table.h" #include "functions/include/iinput.h" #include "functions/include/demand_input.h" #include "functions/include/production_input.h" #include "technologies/include/production_technology.h" #include "technologies/include/ioutput.h" #include "reporting/include/storage_table.h" #include "sectors/include/sector.h" #include "sectors/include/factor_supply.h" #include "containers/include/region_cge.h" #include "containers/include/scenario.h" // only for modeltime #include "util/base/include/model_time.h" #include "consumers/include/consumer.h" extern Scenario* scenario; using namespace std; //! Default Constructor InputOutputTable::InputOutputTable( const string& aRegionName, ostream& aFile ): mFile( aFile ), mRegionName( aRegionName ), mInternalTable( new StorageTable ), mParsingConsumer( false ), mUseInput( false ){ } /*! \brief Output the IOTable to a CSV * * \author Josh Lurz */ void InputOutputTable::finish() const { mFile << "-----------------------------" << endl; mFile << "Regional Input Output Table" << endl; mFile << "-----------------------------" << endl << endl; // Get the column labels which are sector names. const vector<string> colNames = mInternalTable->getColLabels(); for( vector<string>::const_iterator col = colNames.begin(); col != colNames.end(); ++col ){ mFile << ',' << *col; } mFile << endl; // Write out each row of the IOTable. const vector<string> rowNames = mInternalTable->getRowLabels(); for ( vector<string>::const_iterator row = rowNames.begin(); row != rowNames.end(); ++row ){ mFile << *row; // Iterate through the columns. for( vector<string>::const_iterator col = colNames.begin(); col != colNames.end(); ++col ) { mFile << ',' << mInternalTable->getValue( *row, *col ); } mFile << endl; } mFile << endl; } //! Update the region. void InputOutputTable::startVisitRegionCGE( const RegionCGE* aRegion, const int aPeriod ){ // Loop through the sectors and add a blank item for each just to set the ordering. for( unsigned int i = 0; i < aRegion->supplySector.size(); ++i ){ mInternalTable->setType( aRegion->supplySector[ i ]->getName(), aRegion->supplySector[ i ]->getName(), 0 ); } // Add factor supplies at the end. right? for( unsigned int i = 0; i < aRegion->factorSupply.size(); ++i ){ mInternalTable->setType( aRegion->factorSupply[ i ]->getName(), aRegion->factorSupply[ i ]->getName(), 0 ); } } void InputOutputTable::startVisitSector( const Sector* sector, const int aPeriod ) { // Add a column for ourselves. mInternalTable->addColumn( sector->getName() ); // Store the sector name as we'll need it at the technology level. mCurrSectorName = sector->getName(); } void InputOutputTable::startVisitProductionTechnology( const ProductionTechnology* prodTechnology, const int aPeriod ) { if( aPeriod == -1 || ( prodTechnology->isAvailable( aPeriod ) && !prodTechnology->isRetired( aPeriod ) ) ) { mUseInput = true; // Add the technologies output as a negative demand on the diagonal. mInternalTable->addToType( mCurrSectorName, mCurrSectorName, -1 * prodTechnology->mOutputs[ 0 ]->getCurrencyOutput( aPeriod ) ); if( prodTechnology->isNewInvestment( aPeriod ) ) { mInternalTable->addToType( "Capital", mCurrSectorName, prodTechnology->mAnnualInvestment ); } // Everything else will be updated at the input level. mParsingConsumer = false; // set that we aren't currently parsing a consumer. } else { mUseInput = false; } } void InputOutputTable::startVisitFactorSupply( const FactorSupply* factorSupply, const int aPeriod ){ // Add factor supplies to the household column. mInternalTable->addToType( factorSupply->getName(), "Household", -1 * factorSupply->getSupply( mRegionName, aPeriod ) ); } //! Update the inputs contribution to the IOTable. void InputOutputTable::startVisitProductionInput( const ProductionInput* aProdInput, const int aPeriod ) { if( mUseInput ) { // Add the currency demand. // The capital row is not truly capital but other value added. // The row is only the OVA row in ProductionSectors, it behaves as capital in Consumers. if( aProdInput->hasTypeFlag( IInput::CAPITAL ) && !mParsingConsumer ){ mInternalTable->addToType( "OVA", mCurrSectorName, aProdInput->getCurrencyDemand( aPeriod ) ); } else { mInternalTable->addToType( aProdInput->getName(), mCurrSectorName, aProdInput->getCurrencyDemand( aPeriod ) ); } } } //! Update the inputs contribution to the IOTable. void InputOutputTable::startVisitDemandInput( const DemandInput* aDemandInput, const int aPeriod ){ if( mUseInput ) { mInternalTable->addToType( aDemandInput->getName(), mCurrSectorName, aDemandInput->getCurrencyDemand( aPeriod ) ); } } //! Update the consumer. Set that the current state is parsing a consumer, not a production tech. void InputOutputTable::startVisitConsumer( const Consumer* aConsumer, const int aPeriod ){ if( aConsumer->getYear() == scenario->getModeltime()->getper_to_yr( aPeriod ) ) { mParsingConsumer = true; mUseInput = true; } else { mUseInput = false; } }
40.032258
140
0.682783
[ "vector" ]
e72da69ab29f8ccc925fbd0675b2310eadfab39f
17,084
hpp
C++
pencil-benchmarks-imageproc/hog/HogDescriptor.hpp
rbaghdadi/pencil-benchmark
9c8b0cf9a4a31fbd30c01f23a732d99d5b741575
[ "MIT" ]
6
2015-10-14T19:44:44.000Z
2021-02-26T02:24:49.000Z
pencil-benchmarks-imageproc/hog/HogDescriptor.hpp
rbaghdadi/pencil-benchmark
9c8b0cf9a4a31fbd30c01f23a732d99d5b741575
[ "MIT" ]
4
2015-10-13T15:06:41.000Z
2015-10-27T14:08:50.000Z
pencil-benchmarks-imageproc/hog/HogDescriptor.hpp
rbaghdadi/pencil-benchmark
9c8b0cf9a4a31fbd30c01f23a732d99d5b741575
[ "MIT" ]
3
2015-10-13T15:17:40.000Z
2017-05-07T10:07:01.000Z
#ifndef HOGDESCRIPTOR_H #error This is a private implementation file for HogDescriptor.h, do not include directly #endif #ifdef WITH_TBB #include <tbb/parallel_for.h> #include <tbb/blocked_range.h> #endif namespace { template<typename T> inline int fast_floor(T f) { static_assert(std::is_floating_point<T>::value, "fast_floor: Parameter must be floating point."); return static_cast<int>(f)-(f < T(0)); } template<typename T> inline int fast_ceil(T f) { static_assert(std::is_floating_point<T>::value, "fast_ceil: Parameter must be floating point."); return static_cast<int>(f)+(f > T(0)); } inline size_t round_to_multiple(size_t num, size_t factor) { return num + factor - 1 - (num - 1) % factor; } } template<int numberOfCells, int numberOfBins, bool gauss, bool spinterp, bool _signed, bool static_> nel::HOGDescriptorCPP<numberOfCells, numberOfBins, gauss, spinterp, _signed, static_>::HOGDescriptorCPP() { m_lookupTable.resize(512 * 512); for (int mdy = -255; mdy < 256; ++mdy) for (int mdx = -255; mdx < 256; ++mdx) { m_lookupTable[(mdy + 255) * 512 + mdx + 255].first = get_orientation(mdy,mdx); m_lookupTable[(mdy + 255) * 512 + mdx + 255].second = static_cast<float>(std::hypot(mdx, mdy)); } } template<int numberOfCells, int numberOfBins, bool gauss, bool spinterp, bool _signed, bool static_> int nel::HOGDescriptorCPP<numberOfCells, numberOfBins, gauss, spinterp, _signed, static_>::getNumberOfBins() { return numberOfCells * numberOfCells * numberOfBins; } template<int numberOfCells, int numberOfBins, bool gauss, bool spinterp, bool _signed, bool static_> float nel::HOGDescriptorCPP<numberOfCells, numberOfBins, gauss, spinterp, _signed, static_>::get_orientation(int mdy, int mdx) { if (_signed) { return static_cast<float>(std::atan2(mdy, mdx) * M_1_PI * 0.5); } else { return static_cast<float>(std::atan2(mdy, mdx) * M_1_PI + 0.5); } } template<int numberOfCells, int numberOfBins, bool gauss, bool spinterp, bool _signed, bool static_> cv::Mat_<float> nel::HOGDescriptorCPP<numberOfCells, numberOfBins, gauss, spinterp, _signed, static_> ::compute( const cv::Mat_<uint8_t> &image , const cv::Mat_<float> &locations , const BlockSizeParameter<static_> &blocksizes ) const { assert(2 == locations.cols); cv::Mat_<float> descriptors(locations.rows, getNumberOfBins(), static_cast<float>(0.0)); #ifdef WITH_TBB tbb::parallel_for(tbb::blocked_range<size_t>(0, locations.rows, 5), [&](const tbb::blocked_range<size_t> range) { for (size_t n = range.begin(); n != range.end(); ++n) { #else for (size_t n = 0; n < (size_t)locations.rows; ++n) { #endif const float &blocksizeX = blocksizes(n, 0); const float &blocksizeY = blocksizes(n, 1); const float &centerx = locations (n, 0); const float &centery = locations (n, 1); const float inv_cellsizeX = numberOfCells / blocksizeX; const float inv_cellsizeY = numberOfCells / blocksizeY; const float halfblocksizeX = blocksizeX * static_cast<float>(0.5); const float halfblocksizeY = blocksizeY * static_cast<float>(0.5); const float minx = centerx - halfblocksizeX; const float miny = centery - halfblocksizeY; const float maxx = centerx + halfblocksizeX; const float maxy = centery + halfblocksizeY; const int minxi = std::max(fast_ceil(minx) , 1); const int minyi = std::max(fast_ceil(miny) , 1); const int maxxi = std::min(fast_floor(maxx), image.cols - 2); const int maxyi = std::min(fast_floor(maxy), image.rows - 2); cv::Matx<float, numberOfCells * numberOfCells, numberOfBins> hist(0.0f); float m1p2sigmaX2; float m1p2sigmaY2; if (gauss) { float sigmaX = halfblocksizeX; float sigmaY = halfblocksizeY; float sigmaX2 = sigmaX*sigmaX; float sigmaY2 = sigmaY*sigmaY; m1p2sigmaX2 = static_cast<float>(-0.5) / sigmaX2; m1p2sigmaY2 = static_cast<float>(-0.5) / sigmaY2; } // compute edges, magnitudes, orientations and the histogram for (int pointy = minyi; pointy <= maxyi; pointy++) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wmaybe-uninitialized" int cellyi; float yscale0; float yscale1; if (spinterp) { //Relative position of the pixel compared to the cell centers - y dimension float relative_pos_y = (pointy - miny) * inv_cellsizeY - static_cast<float>(0.5); //Calculate the integral part and the fractional part of the relative position - y dimension cellyi = fast_floor(relative_pos_y); yscale1 = relative_pos_y - cellyi; yscale0 = static_cast<float>(1.0) - yscale1; } float dy2; if (gauss) { float dy = pointy - centery; dy2 = dy*dy; } for (int pointx = minxi; pointx <= maxxi; pointx++) { int mdxi = image(pointy, pointx + 1) - image(pointy, pointx - 1); int mdyi = image(pointy + 1, pointx) - image(pointy - 1, pointx); float magnitude = m_lookupTable[(mdyi + 255) * 512 + mdxi + 255].second; float orientation = m_lookupTable[(mdyi + 255) * 512 + mdxi + 255].first; if (gauss) { float dx = pointx - centerx; float dx2 = dx*dx; float B = std::exp(dx2 * m1p2sigmaX2 + dy2 * m1p2sigmaY2); magnitude *= B; } // linear/trilinear interpolation of magnitudes float relative_orientation = orientation * numberOfBins - static_cast<float>(0.5); int bin1 = fast_ceil(relative_orientation); int bin0 = bin1 - 1; float magscale0 = magnitude * (bin1 - relative_orientation); float magscale1 = magnitude * (relative_orientation - bin0); int binidx0 = (bin0 + numberOfBins) % numberOfBins; int binidx1 = (bin1 + numberOfBins) % numberOfBins; if (spinterp) { //Relative position of the pixel compared to the cell centers - x dimension float relative_pos_x = (pointx - minx) * inv_cellsizeX - static_cast<float>(0.5); //Calculate the integral part and the fractional part of the relative position - x dimension int cellxi = fast_floor(relative_pos_x); float xscale1 = relative_pos_x - cellxi; float xscale0 = static_cast<float>(1.0) - xscale1; if (cellyi >= 0 && cellxi >= 0) { hist((cellyi + 0) * numberOfCells + cellxi + 0, binidx0) += yscale0 * xscale0 * magscale0; hist((cellyi + 0) * numberOfCells + cellxi + 0, binidx1) += yscale0 * xscale0 * magscale1; } if (cellyi >= 0 && cellxi < numberOfCells - 1) { hist((cellyi + 0) * numberOfCells + cellxi + 1, binidx0) += yscale0 * xscale1 * magscale0; hist((cellyi + 0) * numberOfCells + cellxi + 1, binidx1) += yscale0 * xscale1 * magscale1; } if (cellyi < numberOfCells - 1 && cellxi >= 0) { hist((cellyi + 1) * numberOfCells + cellxi + 0, binidx0) += yscale1 * xscale0 * magscale0; hist((cellyi + 1) * numberOfCells + cellxi + 0, binidx1) += yscale1 * xscale0 * magscale1; } if (cellyi < numberOfCells - 1 && cellxi < numberOfCells - 1) { hist((cellyi + 1) * numberOfCells + cellxi + 1, binidx0) += yscale1 * xscale1 * magscale0; hist((cellyi + 1) * numberOfCells + cellxi + 1, binidx1) += yscale1 * xscale1 * magscale1; } } else { if (numberOfCells == 1) { hist(0, binidx0) += magscale0; hist(0, binidx1) += magscale1; } else { int cellxi = fast_floor((pointx - minx) * inv_cellsizeX); int cellyi = fast_floor((pointy - miny) * inv_cellsizeY); assert(cellxi < numberOfCells); assert(cellyi < numberOfCells); assert(cellxi >= 0); assert(cellyi >= 0); hist(cellyi * numberOfCells + cellxi, binidx0) += magscale0; hist(cellyi * numberOfCells + cellxi, binidx1) += magscale1; } } } #pragma GCC diagnostic pop } cv::Mat_<float> destRow = descriptors.row(n); cv::Mat(hist).reshape(0,1).copyTo(destRow); } #ifdef WITH_TBB }); #endif return descriptors; } template<size_t numberOfCells, size_t numberOfBins, bool gauss, bool spinterp, bool _signed, bool _static> typename nel::HOGDescriptorOCL<numberOfCells, numberOfBins, gauss, spinterp, _signed, _static>::HOGAlgorithmType nel::HOGDescriptorOCL<numberOfCells, numberOfBins, gauss, spinterp, _signed, _static>::getAlgorithmType() const { if (getNumberOfBins() <= 36) return use_private; if (m_has_local_memory) return use_local; else return use_global; } template<size_t numberOfCells, size_t numberOfBins, bool gauss, bool spinterp, bool _signed, bool _static> nel::HOGDescriptorOCL<numberOfCells, numberOfBins, gauss, spinterp, _signed, _static>::HOGDescriptorOCL() { assert(numberOfCells > 1 || !spinterp); //Get the used device std::vector<cl::Device> devices; cl::Platform::getDefault().getDevices(CL_DEVICE_TYPE_DEFAULT, &devices); m_device = devices.at(0); //Create context m_context = cl::Context(m_device); m_has_local_memory = (CL_LOCAL == m_device.getInfo<CL_DEVICE_LOCAL_MEM_TYPE>()); //Load source std::ifstream source_file{ "HogDescriptor.cl" }; std::string source{ std::istreambuf_iterator<char>{source_file}, std::istreambuf_iterator<char>{} }; //Create program cl::Program program(m_context, source); std::string functionname = "hog" + std::to_string(numberOfCells) + 'x' + std::to_string(numberOfCells); //Build options std::stringstream build_opts; build_opts << " -cl-single-precision-constant"; build_opts << " -cl-denorms-are-zero"; build_opts << " -cl-mad-enable"; build_opts << " -cl-no-signed-zeros"; build_opts << " -cl-finite-math-only"; build_opts << " -Werror"; build_opts << " -D NUMBER_OF_CELLS=" << numberOfCells; build_opts << " -D NUMBER_OF_BINS=" << numberOfBins; build_opts << " -D GAUSSIAN_WEIGHTS=" << (gauss ? "1" : "0"); build_opts << " -D SPARTIAL_WEIGHTS=" << (spinterp ? "1" : "0"); build_opts << " -D SIGNED_HOG=" << (_signed ? "1" : "0"); build_opts << " -D STATIC_BLOCK_SIZE="<< (_static ? "1" : "0"); build_opts << " -D FUNCTIONNAME=" << functionname; build_opts << " -D VECTOR_SIZE=" << ms_calchog_vector_size; switch (getAlgorithmType()) { case use_private: build_opts << " -D USE_PRIVATE=1"; break; case use_local : build_opts << " -D USE_LOCAL=1"; break; case use_global: default: break; } #ifndef NDEBUG build_opts << " -D DEBUG"; #endif //Build program try { program.build(build_opts.str().c_str()); } catch (const cl::Error&) { auto buildlog = program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(m_device); std::cerr << "OpenCL compilation error: " << buildlog << std::endl; throw; } //Create queue m_queue = cl::CommandQueue(m_context, m_device, CL_QUEUE_PROFILING_ENABLE); //Query kernels and work group infos m_calc_hog = cl::Kernel(program, functionname.c_str()); m_calc_hog_preferred_multiple = m_calc_hog.getWorkGroupInfo<CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE>(m_device); m_calc_hog_group_size = m_calc_hog.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(m_device); } template<size_t numberOfCells, size_t numberOfBins, bool gauss, bool spinterp, bool _signed, bool _static> size_t nel::HOGDescriptorOCL<numberOfCells, numberOfBins, gauss, spinterp, _signed, _static>::getNumberOfBins() { return numberOfCells * numberOfCells * numberOfBins; } template<size_t numberOfCells, size_t numberOfBins, bool gauss, bool spinterp, bool _signed, bool _static> cv::Mat_<float> nel::HOGDescriptorOCL<numberOfCells, numberOfBins, gauss, spinterp, _signed, _static> ::compute( const cv::Mat_<uint8_t> &image , const cv::Mat_<float> &locations , const BlockSizeParameter<_static> &blocksizes ) const { assert(2 == locations.cols); assert(locations.isContinuous()); assert(blocksizes.compatiblewith(locations)); int num_locations = locations.rows; cv::Mat_<float> descriptors(num_locations, getNumberOfBins()); assert(descriptors.isContinuous()); //Events to track execution time cl::Event event; //OPENCL START assert(image.elemSize() == sizeof(cl_uchar)); static_assert(sizeof(cl_float) == sizeof(float), "Error: float and cl_float must be the same type"); size_t image_bytes = image.elemSize()*image.rows*image.step1(); size_t locations_bytes = sizeof(cl_float2)*num_locations; size_t descriptor_bytes = sizeof(cl_float)*getNumberOfBins()*num_locations; //Allocate OpenCL buffers cl::Buffer image_cl = cl::Buffer(m_context, CL_MEM_READ_ONLY , image_bytes); cl::Buffer locations_cl = cl::Buffer(m_context, CL_MEM_READ_ONLY , locations_bytes); cl::Buffer descriptor_cl = cl::Buffer(m_context, CL_MEM_READ_WRITE, descriptor_bytes); //Write input buffers to device m_queue.enqueueWriteBuffer( image_cl, CL_FALSE, 0, image_bytes, image.data); m_queue.enqueueWriteBuffer( locations_cl, CL_FALSE, 0, locations_bytes, locations.data); auto blocksizes_cl = blocksizes.convert_to_opencl_data(m_context, m_queue); //If dynamic: creates cl::Buffer like the rest. If static: creates a functor that returns the static value as cl_float #ifndef LWS_X #define LWS_X 4 #endif #ifndef LWS_Y #define LWS_Y 8 #endif #ifndef LWS_Z #define LWS_Z std::min( std::max<size_t>(num_locations / m_device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>(), 1), m_calc_hog_group_size / (lws_x * lws_y)) #endif { //Figure out the work group sizes const size_t lws_x = LWS_X; const size_t lws_y = LWS_Y; const size_t lws_z = LWS_Z; cl::NDRange local_work_size(lws_x, lws_y, lws_z); const size_t gws_x = lws_x; const size_t gws_y = lws_y; const size_t gws_z = round_to_multiple(num_locations, lws_z); cl::NDRange global_work_size(gws_x, gws_y, gws_z); cl_int2 image_size = { image.cols, image.rows }; //Execute the kernel { //ADD MULTITHREAD LOCK HERE (if needed) m_calc_hog.setArg(0, (cl_int2)image_size ); m_calc_hog.setArg(1, (cl_uint)image.step1() ); m_calc_hog.setArg(2, (cl_mem )image_cl() ); m_calc_hog.setArg(3, (cl_uint)num_locations ); m_calc_hog.setArg(4, (cl_mem )locations_cl() ); m_calc_hog.setArg(5, blocksizes_cl()); //Static: cl_float, Dynamic: cl_mem m_calc_hog.setArg(6, (cl_mem )descriptor_cl()); switch (getAlgorithmType()) { case use_private: m_calc_hog.setArg(7, (size_t)(sizeof(cl_float) * lws_x * lws_y * lws_z * ms_calchog_vector_size), nullptr); break; case use_local: m_calc_hog.setArg(7, (size_t)(sizeof(cl_float) * getNumberOfBins() * lws_z), nullptr); break; case use_global: //nothing to do break; default: assert(false); } } m_queue.enqueueNDRangeKernel(m_calc_hog, cl::NullRange, global_work_size, local_work_size, nullptr, &event); } //Read result buffer from device m_queue.enqueueReadBuffer(descriptor_cl, CL_TRUE, 0, descriptor_bytes, descriptors.data); //Calculate kernel-only execution time double kernel_ns = event.getProfilingInfo<CL_PROFILING_COMMAND_END>() - event.getProfilingInfo<CL_PROFILING_COMMAND_START>(); double kernel_ms = kernel_ns * 1e-6; std::cout << "calc_hog execution time: " << std::fixed << std::setprecision(6) << std::setw(8) << kernel_ms << " ms\n"; return descriptors; }
44.839895
200
0.614376
[ "vector" ]
e72e16d189e673c28a18b930795328476b7ac8ff
6,081
cpp
C++
deps/CoinCore/src/CoinNodeAbstractListener.cpp
anypath/CoinVault
ec9fb9bdf557086b8bcad273c232319ed04442b9
[ "Unlicense", "OpenSSL", "MIT" ]
null
null
null
deps/CoinCore/src/CoinNodeAbstractListener.cpp
anypath/CoinVault
ec9fb9bdf557086b8bcad273c232319ed04442b9
[ "Unlicense", "OpenSSL", "MIT" ]
null
null
null
deps/CoinCore/src/CoinNodeAbstractListener.cpp
anypath/CoinVault
ec9fb9bdf557086b8bcad273c232319ed04442b9
[ "Unlicense", "OpenSSL", "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // CoinNodeAbstractListener.cpp // // Copyright (c) 2011-2013 Eric Lombrozo // // 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 "CoinNodeAbstractListener.h" #include <boost/thread/locks.hpp> using namespace Coin; uint64_t getRandomNonce64() { // TODO: Use better RNG srand(time(NULL)); uint64_t nonce = 0; for (uint i = 0; i < 4; i++) { nonce <<= 8; nonce |= rand() % 0xff; } return nonce; } void coinMessageHandler(CoinNodeSocket* pNodeSocket, CoinNodeAbstractListener* pListener, const CoinNodeMessage& message) { std::string command = message.getCommand(); /* if (command == "tx" || command == "block") pNodeSocket->pListener->lockHandler(); */ try { if (command == "version") { VerackMessage verackMessage; CoinNodeMessage msg(pNodeSocket->getMagic(), &verackMessage); pNodeSocket->sendMessage(msg); } else if (command == "inv") { Inventory* pInventory = static_cast<Inventory*>(message.getPayload()); GetDataMessage getData(*pInventory); CoinNodeMessage msg(pNodeSocket->getMagic(), &getData); pNodeSocket->sendMessage(msg); } else if (command == "tx") { Transaction* pTx = static_cast<Transaction*>(message.getPayload()); pListener->onTx(*pTx); } else if (command == "block") { CoinBlock* pBlock = static_cast<CoinBlock*>(message.getPayload()); pListener->onBlock(*pBlock); } else if (command == "addr") { AddrMessage* pAddr = static_cast<AddrMessage*>(message.getPayload()); pListener->onAddr(*pAddr); } else if (command == "headers") { HeadersMessage* pHeaders = static_cast<HeadersMessage*>(message.getPayload()); pListener->onHeaders(*pHeaders); } } catch (const std::exception& e) { std::cout << "Exception in coinMessageHandler(): " << e.what() << std::endl; } /* if (command == "tx" || command == "block") pNodeSocket->pListener->unlockHandler();*/ } void socketClosedHandler(CoinNodeSocket* pNodeSocket, CoinNodeAbstractListener* pListener, int code) { pListener->onSocketClosed(code); } void CoinNodeAbstractListener::start() { m_nodeSocket.open(coinMessageHandler, m_magic, m_version, m_peerHostname.c_str(), m_port, socketClosedHandler); m_nodeSocket.doHandshake(m_version, NODE_NETWORK, time(NULL), m_peerAddress, m_listenerAddress, getRandomNonce64(), "", 0); m_nodeSocket.waitOnHandshakeComplete(); } void CoinNodeAbstractListener::askForBlock(const std::string& hash) { InventoryItem block(MSG_BLOCK, uchar_vector(hash)); Inventory inv; inv.addItem(block); GetDataMessage getData(inv); CoinNodeMessage msg(this->getMagic(), &getData); this->sendMessage(msg); } void CoinNodeAbstractListener::getBlocks(const std::vector<std::string>& locatorHashes, const std::string& hashStop) { GetBlocksMessage getBlocks; getBlocks.version = m_version; for (unsigned int i = 0; i < locatorHashes.size(); i++) { getBlocks.blockLocatorHashes.push_back(locatorHashes[i]); } getBlocks.hashStop = hashStop; CoinNodeMessage msg(this->getMagic(), &getBlocks); this->sendMessage(msg); } void CoinNodeAbstractListener::getBlocks(const std::vector<uchar_vector>& locatorHashes, const uchar_vector& hashStop) { GetBlocksMessage getBlocks(m_version, locatorHashes, hashStop); CoinNodeMessage msg(this->getMagic(), &getBlocks); this->sendMessage(msg); } void CoinNodeAbstractListener::getHeaders(const std::vector<std::string>& locatorHashes, const std::string& hashStop) { GetHeadersMessage getHeaders; getHeaders.version = m_version; for (unsigned int i = 0; i < locatorHashes.size(); i++) { getHeaders.blockLocatorHashes.push_back(locatorHashes[i]); } getHeaders.hashStop = hashStop; CoinNodeMessage msg(this->getMagic(), &getHeaders); this->sendMessage(msg); } void CoinNodeAbstractListener::getHeaders(const std::vector<uchar_vector>& locatorHashes, const uchar_vector& hashStop) { GetHeadersMessage getHeaders(m_version, locatorHashes, hashStop); CoinNodeMessage msg(this->getMagic(), &getHeaders); this->sendMessage(msg); } void CoinNodeAbstractListener::askForTx(const std::string& hash) { InventoryItem block(MSG_TX, uchar_vector(hash)); Inventory inv; inv.addItem(block); GetDataMessage getData(inv); CoinNodeMessage msg(this->getMagic(), &getData); this->sendMessage(msg); } void CoinNodeAbstractListener::askForPeers() { BlankMessage mempool("getaddr"); CoinNodeMessage msg(this->getMagic(), &mempool); this->sendMessage(msg); } void CoinNodeAbstractListener::askForMempool() { BlankMessage mempool("mempool"); CoinNodeMessage msg(this->getMagic(), &mempool); this->sendMessage(msg); }
35.561404
127
0.681467
[ "vector" ]
e72e7d3c98b5c3b2e84b5c29bbff23015fa6ba71
4,034
cc
C++
src/Modules/Legacy/DataIO/ReadField.cc
mhansen1/SCIRun
9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba
[ "Unlicense" ]
null
null
null
src/Modules/Legacy/DataIO/ReadField.cc
mhansen1/SCIRun
9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba
[ "Unlicense" ]
null
null
null
src/Modules/Legacy/DataIO/ReadField.cc
mhansen1/SCIRun
9719c570a6d6911a9eb8df584bd2c4ad8b8cd2ba
[ "Unlicense" ]
null
null
null
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2015 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /// /// @file ReadField.cc /// /// @author /// Steven G. Parker /// Department of Computer Science /// University of Utah /// @date July 1994 /// #include <Dataflow/Network/Ports/FieldPort.h> #include <Dataflow/Modules/DataIO/GenericReader.h> #include <Core/ImportExport/Field/FieldIEPlugin.h> namespace SCIRun { template class GenericReader<FieldHandle>; /// @class ReadField /// @brief This module reads a field from file /// /// (a SCIRun .fld file and various other formats using a plugin system). class ReadField : public GenericReader<FieldHandle> { protected: GuiString gui_types_; GuiString gui_filetype_; GuiString gui_filename_base_; GuiInt gui_number_in_series_; GuiInt gui_delay_; virtual bool call_importer(const std::string &filename, FieldHandle &fHandle); public: ReadField(GuiContext* ctx); virtual ~ReadField() {} virtual void execute(); }; DECLARE_MAKER(ReadField) ReadField::ReadField(GuiContext* ctx) : GenericReader<FieldHandle>("ReadField", ctx, "DataIO", "SCIRun"), gui_types_(get_ctx()->subVar("types", false)), gui_filetype_(get_ctx()->subVar("filetype")), gui_filename_base_(get_ctx()->subVar("filename_base"), ""), gui_number_in_series_(get_ctx()->subVar("number_in_series"), 0), gui_delay_(get_ctx()->subVar("delay"), 0) { FieldIEPluginManager mgr; std::vector<std::string> importers; mgr.get_importer_list(importers); std::string importtypes = "{"; importtypes += "{{SCIRun Field File} {.fld} } "; for (unsigned int i = 0; i < importers.size(); i++) { FieldIEPlugin *pl = mgr.get_plugin(importers[i]); if (pl->fileextension != "") { importtypes += "{{" + importers[i] + "} {" + pl->fileextension + "} } "; } else { importtypes += "{{" + importers[i] + "} {.*} } "; } } importtypes += "}"; gui_types_.set(importtypes); } bool ReadField::call_importer(const std::string &filename, FieldHandle & fHandle) { const std::string ftpre = gui_filetype_.get(); const std::string::size_type loc = ftpre.find(" ("); const std::string ft = ftpre.substr(0, loc); FieldIEPluginManager mgr; FieldIEPlugin *pl = mgr.get_plugin(ft); if (pl) { fHandle = pl->filereader(this, filename.c_str()); return fHandle.get_rep(); } return false; } void ReadField::execute() { if (gui_types_.changed() || gui_filetype_.changed()) inputs_changed_ = true; const std::string ftpre = gui_filetype_.get(); const std::string::size_type loc = ftpre.find(" ("); const std::string ft = ftpre.substr(0, loc); importing_ = !(ft == "" || ft == "SCIRun Field File" || ft == "SCIRun Field Any"); GenericReader<FieldHandle>::execute(); } } // End namespace SCIRun
28.814286
82
0.688151
[ "vector" ]
e7306df859b7e2f96b18bae1760bcbc3389f99f7
7,854
cc
C++
mindspore/lite/src/runtime/kernel/arm/int8/matmul_dynamic_sdot_int8.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
1
2022-03-05T02:59:21.000Z
2022-03-05T02:59:21.000Z
mindspore/lite/src/runtime/kernel/arm/int8/matmul_dynamic_sdot_int8.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
mindspore/lite/src/runtime/kernel/arm/int8/matmul_dynamic_sdot_int8.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2022 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "src/runtime/kernel/arm/int8/matmul_dynamic_sdot_int8.h" #include <vector> #include "nnacl/int8/dynamic_matmul_int8.h" #include "nnacl/int8/matmul_int8.h" using mindspore::lite::RET_ERROR; using mindspore::lite::RET_MEMORY_FAILED; using mindspore::lite::RET_OK; namespace mindspore::kernel { namespace { int Arm64SdotPreRun(void *cdata, int task_id, float, float) { CHECK_NULL_RETURN(cdata); auto op = reinterpret_cast<MatMulDynamicSdotInt8Kernel *>(cdata); auto ret = op->MatMulDynamicArm64SdotPre(task_id); if (ret != RET_OK) { MS_LOG(ERROR) << "MatmulInt8Run error task_id[" << task_id << "] error_code[" << ret << "]"; return ret; } return RET_OK; } int Arm64SdotRun(void *cdata, int task_id, float, float) { CHECK_NULL_RETURN(cdata); auto op = reinterpret_cast<MatMulDynamicSdotInt8Kernel *>(cdata); auto ret = op->MatMulDynamicArm64SdotImpl(task_id); if (ret != RET_OK) { MS_LOG(ERROR) << "MatmulInt8Run error task_id[" << task_id << "] error_code[" << ret << "]"; return ret; } return RET_OK; } } // namespace int MatMulDynamicSdotInt8Kernel::MatMulDynamicArm64SdotPre(int task_id) { int row_thread_count = MSMIN(op_parameter_->thread_num_, UP_DIV(param_->row_align_, row_tile_)); int row_stride = UP_DIV(UP_DIV(param_->row_align_, row_tile_), row_thread_count) * row_tile_; int row_current_stride = task_id * row_stride; int row_res_stride = param_->row_ - row_current_stride; int cur_r = MSMIN(row_res_stride, row_stride); if (cur_r <= 0) { return RET_OK; } auto current_a_pack = pack_a_ptr_ + row_current_stride * param_->deep_align_; int weight_zp = quant_param_->filter_zp_[0]; if (param_->a_transpose_) { auto current_src_a = batch_input_ptr_ + row_current_stride; if (weight_zp == 0) { PackInput2Col4x4(current_src_a, current_a_pack, param_->deep_, cur_r, param_->row_); } else { PackInput2Col4x4AndInputSumPert(current_src_a, current_a_pack, input_sums_ + row_current_stride, param_->deep_, cur_r, param_->row_, weight_zp); } } else { auto current_src_a = batch_input_ptr_ + row_current_stride * param_->deep_; if (weight_zp == 0) { PackInput4x4(current_src_a, current_a_pack, param_->deep_, cur_r); } else { PackInput4x4AndInputSumPert(current_src_a, current_a_pack, input_sums_ + row_current_stride, param_->deep_, cur_r, weight_zp); } } return RET_OK; } int MatMulDynamicSdotInt8Kernel::MatMulDynamicArm64SdotImpl(int task_id) { // Multi-thread split by col. int stride = thread_stride_ * col_tile_; int cur_stride = task_id * stride; int res_stride = param_->col_ - cur_stride; int cur_oc = MSMIN(stride, res_stride); if (cur_oc <= 0) { return RET_OK; } auto current_sums = batch_sums_ + cur_stride; if (!param_->b_const_) { auto current_b_pack = batch_b_ptr_ + cur_stride * param_->deep_align_; if (param_->b_transpose_) { auto current_weight = batch_weight_ptr_ + cur_stride * param_->deep_; RowMajor2Row4x16MajorInt8(current_weight, current_b_pack, cur_oc, param_->deep_); CalcPartWeightSums(current_weight, param_->deep_, param_->col_, cur_oc, current_sums, ColMajor); } else { auto current_weight = batch_weight_ptr_ + cur_stride; RowMajor2Col4x16MajorPartInt8(current_weight, current_b_pack, param_->deep_, param_->col_, cur_oc); CalcPartWeightSums(current_weight, param_->deep_, param_->col_, cur_oc, current_sums, RowMajor); } } std::vector<float> multi_scale(cur_oc); for (int i = 0; i < cur_oc; ++i) { if (!param_->b_const_) { multi_scale[i] = quant_param_->input_scale_ * quant_param_->filter_scale_[0]; } else { multi_scale[i] = quant_param_->input_scale_ * quant_param_->filter_scale_[cur_stride + i]; } } auto out_stride = param_->col_ * sizeof(float); for (int r = 0; r < param_->row_; r += C4NUM) { size_t row = MSMIN(C4NUM, param_->row_ - r); auto a_ptr = pack_a_ptr_ + r * param_->deep_align_; int *input_sums_ptr = input_sums_ + r; for (int c = 0; c < cur_oc; c += C16NUM) { size_t col = MSMIN(C16NUM, cur_oc - c); auto col_offset = cur_stride + c; auto b_ptr = batch_b_ptr_ + col_offset * param_->deep_align_; int *weight_sums_ptr = current_sums + c; auto out_ptr = batch_c_ptr_ + r * param_->col_ + col_offset; auto bias = fp32_bias_ptr_; if (bias != nullptr) { bias += col_offset; } #if defined(ENABLE_ARM64) && !defined(SUPPORT_NNIE) && (!defined(MACHINE_LINUX_ARM64)) DynamicMatmulSdot4x4x16AIWI(a_ptr, b_ptr, out_ptr, param_->deep_align_, multi_scale.data() + c, bias, row, col, out_stride, input_sums_ptr, weight_sums_ptr, quant_param_->input_zp_, quant_param_->filter_zp_[0] * param_->deep_); #else DynamicMatmul4x4x16AIWI(a_ptr, b_ptr, out_ptr, param_->deep_align_, multi_scale.data() + c, bias, row, col, out_stride, input_sums_ptr, weight_sums_ptr, quant_param_->input_zp_, quant_param_->filter_zp_[0] * param_->deep_); #endif } } return RET_OK; } void MatMulDynamicSdotInt8Kernel::InitParameter() { param_->a_const_ = (in_tensors_[0]->data() != nullptr); param_->b_const_ = (in_tensors_[1]->data() != nullptr); row_tile_ = C4NUM; col_tile_ = C16NUM; deep_tile_ = C4NUM; if (param_->b_transpose_) { b_pack_func_ = RowMajor2Row4x16MajorInt8; } else { b_pack_func_ = RowMajor2Col4x16MajorInt8; } return; } int MatMulDynamicSdotInt8Kernel::MatMulDynamicRunArm64Sdot() { int8_t *a_ptr = reinterpret_cast<int8_t *>(in_tensors_.at(0)->data()); int8_t *b_ptr = reinterpret_cast<int8_t *>(in_tensors_.at(1)->data()); float *c_ptr = reinterpret_cast<float *>(out_tensors_.at(0)->data()); CHECK_NULL_RETURN(a_ptr); CHECK_NULL_RETURN(b_ptr); CHECK_NULL_RETURN(c_ptr); for (int i = 0; i < param_->batch; i++) { batch_input_ptr_ = a_ptr + i * param_->row_ * param_->deep_; auto ret = ParallelLaunch(this->ms_context_, Arm64SdotPreRun, this, op_parameter_->thread_num_); if (ret != RET_OK) { MS_LOG(ERROR) << "Arm64SdotPreRun error: [" << ret << "]"; return ret; } batch_weight_ptr_ = b_ptr + i * param_->col_ * param_->deep_; batch_sums_ = weight_sums_ + i * param_->col_align_; batch_b_ptr_ = pack_b_ptr_ + i * param_->col_align_ * param_->deep_align_; batch_c_ptr_ = c_ptr + i * param_->row_ * param_->col_; ret = ParallelLaunch(this->ms_context_, Arm64SdotRun, this, thread_count_); if (ret != RET_OK) { MS_LOG(ERROR) << "Arm64SdotRun error: [" << ret << "]"; return ret; } } return RET_OK; } int MatMulDynamicSdotInt8Kernel::Run() { auto ret = InitInputQuantParam(); if (ret != RET_OK) { MS_LOG(ERROR) << "Init input quant param failed."; return ret; } if (!param_->b_const_) { ret = InitFilterQuantParam(); if (ret != RET_OK) { MS_LOG(ERROR) << "Init filter quant param failed."; FreeQuantParam(); return ret; } } return MatMulDynamicRunArm64Sdot(); } } // namespace mindspore::kernel
37.759615
120
0.681309
[ "vector" ]
e7358bc23df7c30806520e25be32d4560dbed211
5,082
hpp
C++
src/mlpack/methods/svdplusplus/svdplusplus.hpp
RMaron/mlpack
a179a2708d9555ab7ee4b1e90e0c290092edad2e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2015-01-04T04:20:29.000Z
2016-07-21T23:30:34.000Z
src/mlpack/methods/svdplusplus/svdplusplus.hpp
RMaron/mlpack
a179a2708d9555ab7ee4b1e90e0c290092edad2e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-01-23T18:39:30.000Z
2021-07-15T13:58:34.000Z
src/mlpack/methods/svdplusplus/svdplusplus.hpp
RMaron/mlpack
a179a2708d9555ab7ee4b1e90e0c290092edad2e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-01-20T00:54:34.000Z
2020-05-16T05:34:32.000Z
/** * @file svdplusplus.hpp * @author Siddharth Agrawal * @author Wenhao Huang * * An implementation of SVD++. * * mlpack is free software; you may redistribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #ifndef MLPACK_METHODS_SVDPLUSPLUS_SVDPLUSPLUS_HPP #define MLPACK_METHODS_SVDPLUSPLUS_SVDPLUSPLUS_HPP #include <mlpack/prereqs.hpp> #include <mlpack/methods/cf/cf.hpp> #include <ensmallen.hpp> #include "svdplusplus_function.hpp" namespace mlpack { namespace svd { /** * SVD++ is a matrix decomposition tenique used in collaborative filtering. * SVD++ is similar to BiasSVD, but it is a more expressive model because * SVD++ also models implicit feedback. SVD++ outputs user/item latent * vectors, user/item bias, and item vectors with regard to implicit feedback. * Parameters are optmized by Stochastic Gradient Desent(SGD). The updates also * penalize the learning of large feature values by means of regularization. * * For more information, see the following paper: * * @inproceedings{koren2008factorization, * title={Factorization meets the neighborhood: a multifaceted collaborative * filtering model}, * author={Koren, Yehuda}, * booktitle={Proceedings of the 14th ACM SIGKDD international conference on * Knowledge discovery and data mining}, * pages={426--434}, * year={2008}, * organization={ACM} * } * * An example of how to use the interface is shown below: * * @code * arma::mat data; // Rating data in the form of coordinate list. * * // Implicit feedback data in the form of coordinate list. * arma::mat implicitData; * * const size_t rank = 10; // Rank used for the decomposition. * const size_t iterations = 10; // Number of iterations used for optimization. * * const double alpha = 0.001 // Learning rate for the SGD optimizer. * const double lambda = 0.1 // Regularization parameter for the optimization. * * // Make a SVD++ object. * SVDPlusPlus<> svdPP(iterations, alpha, lambda); * * arma::mat u, v; // Item and User matrices. * arma::vec p, q; // Item and User bias. * arma::mat y; // Item matrix with respect to implicit feedback. * * // Use the Apply() method to get a factorization. * svdPP.Apply(data, implicitData, rank, u, v, p, q, y); * @endcode */ template<typename OptimizerType = ens::StandardSGD> class SVDPlusPlus { public: /** * Constructor of SVDPlusPlus. By default SGD optimizer is used in * SVDPlusPlus. The optimizer uses a template specialization of Optimize(). * * @param iterations Number of optimization iterations. * @param alpha Learning rate for the SGD optimizer. * @param lambda Regularization parameter for the optimization. */ SVDPlusPlus(const size_t iterations = 10, const double alpha = 0.001, const double lambda = 0.1); /** * Trains the model and obtains user/item matrices, user/item bias, and * item implicit matrix. * * @param data Rating data matrix. * @param implicitData Implicit feedback. * @param rank Rank parameter to be used for optimization. * @param u Item matrix obtained on decomposition. * @param v User matrix obtained on decomposition. * @param p Item bias. * @param q User bias. * @param y Item matrix with respect to implicit feedback. */ void Apply(const arma::mat& data, const arma::mat& implicitData, const size_t rank, arma::mat& u, arma::mat& v, arma::vec& p, arma::vec& q, arma::mat& y); /** * Trains the model and obtains user/item matrices, user/item bias, and * item implicit matrix. Whether a user rates an item is used as implicit * feedback. * * @param data Rating data matrix. * @param rank Rank parameter to be used for optimization. * @param u Item matrix obtained on decomposition. * @param v User matrix obtained on decomposition. * @param p Item bias. * @param q User bias. * @param y Item matrix with respect to implicit feedback. Each column is a * latent vector of an item with respect to implicit feedback. */ void Apply(const arma::mat& data, const size_t rank, arma::mat& u, arma::mat& v, arma::vec& p, arma::vec& q, arma::mat& y); /** * Converts the User, Item matrix of implicit data to Item-User Table. */ static void CleanData(const arma::mat& implicitData, arma::sp_mat& cleanedData, const arma::mat& data); private: //! Number of optimization iterations. size_t iterations; //! Learning rate for the SGD optimizer. double alpha; //! Regularization parameter for the optimization. double lambda; }; } // namespace svd } // namespace mlpack // Include implementation. #include "svdplusplus_impl.hpp" #endif
32.576923
79
0.674341
[ "object", "vector", "model" ]
e739dcc39cad91a0435a1ea3058bc4c5ff107edc
3,937
cpp
C++
tests/adaptivefloat/add.cpp
jtodd440/universal
3d8c946691be0dca091579da34f91ced82e1136a
[ "MIT" ]
null
null
null
tests/adaptivefloat/add.cpp
jtodd440/universal
3d8c946691be0dca091579da34f91ced82e1136a
[ "MIT" ]
null
null
null
tests/adaptivefloat/add.cpp
jtodd440/universal
3d8c946691be0dca091579da34f91ced82e1136a
[ "MIT" ]
null
null
null
// add.cpp: functional tests for addition on adaptive precision linear floating point // // Copyright (C) 2017-2021 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <iostream> #include <iomanip> #include <string> #include <cmath> #include <limits> // minimum set of include files to reflect source code dependencies #include <universal/number/adaptivefloat/adaptivefloat.hpp> #include <universal/verification/test_status.hpp> // ReportTestResult // generate specific test case that you can trace with the trace conditions in mpreal.hpp // for most bugs they are traceable with _trace_conversion and _trace_add template<typename Ty> void GenerateTestCase(Ty _a, Ty _b) { Ty ref; sw::universal::adaptivefloat a, b, aref, asum; a = _a; b = _b; asum = a + b; ref = _a + _b; aref = ref; auto precision = std::cout.precision(); constexpr size_t ndigits = std::numeric_limits<Ty>::digits10; std::cout << std::setprecision(ndigits); std::cout << std::setw(ndigits) << _a << " + " << std::setw(ndigits) << _b << " = " << std::setw(ndigits) << ref << std::endl; std::cout << a << " + " << b << " = " << asum << " (reference: " << aref << ") " ; std::cout << (aref == asum ? "PASS" : "FAIL") << std::endl << std::endl; std::cout << std::setprecision(precision); } // progressions void Progressions(uint32_t digit) { using namespace std; using BlockType = uint32_t; sw::universal::adaptivefloat f; vector<BlockType> coef; constexpr size_t digitsInWord = 9; coef.clear(); coef.push_back(digit); for (size_t i = 0; i < digitsInWord; ++i) { f.test(false, -1, coef); cout << "(+, exp = -1, coef = " << coef[0] << ") = " << f << endl; coef[0] *= 10; coef[0] += digit; } coef.clear(); coef.push_back(digit); for (size_t i = 0; i < digitsInWord; ++i) { f.test(false, 0, coef); cout << "(+, exp = 0, coef = " << coef[0] << ") = " << f << endl; coef[0] *= 10; coef[0] += digit; } coef.clear(); coef.push_back(digit); for (size_t i = 0; i < digitsInWord; ++i) { f.test(false, 1, coef); cout << "(+, exp = 1, coef = " << coef[0] << ") = " << f << endl; coef[0] *= 10; coef[0] += digit; } } #define MANUAL_TESTING 1 #define STRESS_TESTING 0 int main(int argc, char** argv) try { using namespace std; using namespace sw::universal; int nrOfFailedTestCases = 0; std::string tag = "adaptive precision linear float addition failed: "; #if MANUAL_TESTING // bool bReportIndividualTestCases = false; // generate individual testcases to hand trace/debug GenerateTestCase(INFINITY, INFINITY); adaptivefloat f; f = 0; cout << f << endl; vector<uint32_t> coef; Progressions(1); Progressions(9); coef.clear(); coef.push_back(0); f.test(false, 0, coef); for (int i = 0; i < 13; ++i) { coef[0] += 1; f.test(false, 0, coef); cout << "(+, exp = 0, coef = " << coef[0] << ") = " << f << endl; } coef[0] = 999999999; f.test(false, 0, coef); cout << "(+, exp = 0, coef = " << coef[0] << ") = " << f << endl; coef.push_back(0); for (int i = 0; i < 13; ++i) { coef[0] = 0; coef[1] += 1; f.test(false, 0, coef); cout << "(+, exp = 0, coef = " << coef[0] << ", " << coef[1] << ") = " << f << endl; coef[0] = 999999999; f.test(false, 0, coef); cout << "(+, exp = 0, coef = " << coef[0] << ", " << coef[1] << ") = " << f << endl; } #else cout << "adaptive precision linear float addition validation" << endl; #if STRESS_TESTING #endif // STRESS_TESTING #endif // MANUAL_TESTING return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); } catch (char const* msg) { std::cerr << msg << std::endl; return EXIT_FAILURE; } catch (const std::runtime_error& err) { std::cerr << "Uncaught runtime exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << std::endl; return EXIT_FAILURE; }
26.965753
127
0.618237
[ "vector" ]
e73ba2750a563c44eb910c7bb0d251740dbffa45
2,033
cc
C++
cc/hmap/ReformatDate.cc
zihengCat/leetcode-collections
e94d6ee7d17cc72c8f34162d60e8d869164cbd53
[ "MIT" ]
4
2021-12-08T15:36:36.000Z
2022-03-23T12:21:06.000Z
cc/hmap/ReformatDate.cc
zihengCat/leetcode-collections
e94d6ee7d17cc72c8f34162d60e8d869164cbd53
[ "MIT" ]
null
null
null
cc/hmap/ReformatDate.cc
zihengCat/leetcode-collections
e94d6ee7d17cc72c8f34162d60e8d869164cbd53
[ "MIT" ]
null
null
null
#include <string> #include <cstdio> #include <unordered_map> #include <vector> using namespace std; /** * LeetCode 1507. Reformat Date * https://leetcode.com/problems/reformat-date/ */ class ReformatDate { public: string reformatDate(string date) { unordered_map<string, string> monthMap; string v; char str[32]; for (int i = 0; i < 12; i++) { if (i + 1 < 10) { sprintf(str, "0%d", i + 1); } else { sprintf(str, "%d", i + 1); } v.append(str); monthMap[monthArr[i]] = v; v.clear(); } string year; string month; string day; vector<string> splitedDate = split(date, ' '); year = splitedDate[2]; month = monthMap[splitedDate[1]]; day = parseDay(splitedDate[0]); sprintf(str, "%s-%s-%s", year.c_str(), month.c_str(), day.c_str()); v.clear(); v.append(str); return v; } private: string monthArr[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", }; vector<string> split(string s, char c) { vector<string> vec; string v; int lastIdx = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == c) { v.append(s, lastIdx, i - lastIdx); vec.push_back(v); v.clear(); lastIdx = i + 1; } } v.clear(); v.append(s, lastIdx, s.size() - lastIdx); vec.push_back(v); return vec; } string parseDay(string s) { string r; for (int i = 0; i < s.size(); i++) { if (!isdigit(s[i])) { if (i < 2) { r.append("0"); } r.append(s, 0, i); break; } } return r; } }; int main(int argc, char const *argv[]) { // ... return 0; } /* EOF */
24.493976
75
0.432858
[ "vector" ]
e7405ad5a3d3e55d6c28d3222a92c7ab5d825551
9,367
cpp
C++
package/win32/android/gameplay/src/VertexAttributeBinding.cpp
sharkpp/openhsp
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
[ "BSD-3-Clause" ]
1
2021-06-17T02:16:22.000Z
2021-06-17T02:16:22.000Z
package/win32/android/gameplay/src/VertexAttributeBinding.cpp
sharkpp/openhsp
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
[ "BSD-3-Clause" ]
null
null
null
package/win32/android/gameplay/src/VertexAttributeBinding.cpp
sharkpp/openhsp
0d412fd8f79a6ccae1d33c13addc06fb623fb1fe
[ "BSD-3-Clause" ]
1
2021-04-06T14:58:08.000Z
2021-04-06T14:58:08.000Z
#include "Base.h" #include "VertexAttributeBinding.h" #include "Mesh.h" #include "Effect.h" namespace gameplay { static GLuint __maxVertexAttribs = 0; static std::vector<VertexAttributeBinding*> __vertexAttributeBindingCache; VertexAttributeBinding::VertexAttributeBinding() : _handle(0), _attributes(NULL), _mesh(NULL), _effect(NULL) { } VertexAttributeBinding::~VertexAttributeBinding() { // Delete from the vertex attribute binding cache. std::vector<VertexAttributeBinding*>::iterator itr = std::find(__vertexAttributeBindingCache.begin(), __vertexAttributeBindingCache.end(), this); if (itr != __vertexAttributeBindingCache.end()) { __vertexAttributeBindingCache.erase(itr); } SAFE_RELEASE(_mesh); SAFE_RELEASE(_effect); SAFE_DELETE_ARRAY(_attributes); if (_handle) { GL_ASSERT( glDeleteVertexArrays(1, &_handle) ); _handle = 0; } } VertexAttributeBinding* VertexAttributeBinding::create(Mesh* mesh, Effect* effect) { GP_ASSERT(mesh); // Search for an existing vertex attribute binding that can be used. VertexAttributeBinding* b; for (size_t i = 0, count = __vertexAttributeBindingCache.size(); i < count; ++i) { b = __vertexAttributeBindingCache[i]; GP_ASSERT(b); if (b->_mesh == mesh && b->_effect == effect) { // Found a match! b->addRef(); return b; } } b = create(mesh, mesh->getVertexFormat(), 0, effect); // Add the new vertex attribute binding to the cache. if (b) { __vertexAttributeBindingCache.push_back(b); } return b; } VertexAttributeBinding* VertexAttributeBinding::create(const VertexFormat& vertexFormat, void* vertexPointer, Effect* effect) { return create(NULL, vertexFormat, vertexPointer, effect); } VertexAttributeBinding* VertexAttributeBinding::create(Mesh* mesh, const VertexFormat& vertexFormat, void* vertexPointer, Effect* effect) { GP_ASSERT(effect); // One-time initialization. if (__maxVertexAttribs == 0) { GLint temp; GL_ASSERT( glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &temp) ); __maxVertexAttribs = temp; if (__maxVertexAttribs <= 0) { GP_ERROR("The maximum number of vertex attributes supported by OpenGL on the current device is 0 or less."); return NULL; } } // Create a new VertexAttributeBinding. VertexAttributeBinding* b = new VertexAttributeBinding(); #ifdef USE_VAO if (mesh && glGenVertexArrays) { GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, 0) ); GL_ASSERT( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0) ); // Use hardware VAOs. GL_ASSERT( glGenVertexArrays(1, &b->_handle) ); if (b->_handle == 0) { GP_ERROR("Failed to create VAO handle."); SAFE_DELETE(b); return NULL; } // Bind the new VAO. GL_ASSERT( glBindVertexArray(b->_handle) ); // Bind the Mesh VBO so our glVertexAttribPointer calls use it. GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, mesh->getVertexBuffer()) ); } else #endif { // Construct a software representation of a VAO. VertexAttribute* attribs = new VertexAttribute[__maxVertexAttribs]; for (unsigned int i = 0; i < __maxVertexAttribs; ++i) { // Set GL defaults attribs[i].enabled = GL_FALSE; attribs[i].size = 4; attribs[i].stride = 0; attribs[i].type = GL_FLOAT; attribs[i].normalized = GL_FALSE; attribs[i].pointer = 0; } b->_attributes = attribs; } if (mesh) { b->_mesh = mesh; mesh->addRef(); } b->_effect = effect; effect->addRef(); // Call setVertexAttribPointer for each vertex element. std::string name; unsigned int offset = 0; for (unsigned int i = 0, count = vertexFormat.getElementCount(); i < count; ++i) { const VertexFormat::Element& e = vertexFormat.getElement(i); gameplay::VertexAttribute attrib; // Constructor vertex attribute name expected in shader. switch (e.usage) { case VertexFormat::POSITION: attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_POSITION_NAME); break; case VertexFormat::NORMAL: attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_NORMAL_NAME); break; case VertexFormat::COLOR: attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_COLOR_NAME); break; case VertexFormat::TANGENT: attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_TANGENT_NAME); break; case VertexFormat::BINORMAL: attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_BINORMAL_NAME); break; case VertexFormat::BLENDWEIGHTS: attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_BLENDWEIGHTS_NAME); break; case VertexFormat::BLENDINDICES: attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_BLENDINDICES_NAME); break; case VertexFormat::TEXCOORD0: if ((attrib = effect->getVertexAttribute(VERTEX_ATTRIBUTE_TEXCOORD_PREFIX_NAME)) != -1) break; /*// Try adding a "0" after the texcoord attrib name (flexible name for this case). if (attrib == -1) { name = VERTEX_ATTRIBUTE_TEXCOORD_PREFIX_NAME; name += '0'; attrib = effect->getVertexAttribute(name.c_str()); } break;*/ case VertexFormat::TEXCOORD1: case VertexFormat::TEXCOORD2: case VertexFormat::TEXCOORD3: case VertexFormat::TEXCOORD4: case VertexFormat::TEXCOORD5: case VertexFormat::TEXCOORD6: case VertexFormat::TEXCOORD7: name = VERTEX_ATTRIBUTE_TEXCOORD_PREFIX_NAME; name += '0' + (e.usage - VertexFormat::TEXCOORD0); attrib = effect->getVertexAttribute(name.c_str()); break; default: // This happens whenever vertex data contains extra information (not an error). attrib = -1; break; } if (attrib == -1) { //GP_WARN("Warning: Vertex element with usage '%s' in mesh '%s' does not correspond to an attribute in effect '%s'.", VertexFormat::toString(e.usage), mesh->getUrl(), effect->getId()); } else { void* pointer = vertexPointer ? (void*)(((unsigned char*)vertexPointer) + offset) : (void*)offset; b->setVertexAttribPointer(attrib, (GLint)e.size, GL_FLOAT, GL_FALSE, (GLsizei)vertexFormat.getVertexSize(), pointer); } offset += e.size * sizeof(float); } if (b->_handle) { GL_ASSERT( glBindVertexArray(0) ); } return b; } void VertexAttributeBinding::setVertexAttribPointer(GLuint indx, GLint size, GLenum type, GLboolean normalize, GLsizei stride, void* pointer) { GP_ASSERT(indx < (GLuint)__maxVertexAttribs); if (_handle) { // Hardware mode. GL_ASSERT( glVertexAttribPointer(indx, size, type, normalize, stride, pointer) ); GL_ASSERT( glEnableVertexAttribArray(indx) ); } else { // Software mode. GP_ASSERT(_attributes); _attributes[indx].enabled = true; _attributes[indx].size = size; _attributes[indx].type = type; _attributes[indx].normalized = normalize; _attributes[indx].stride = stride; _attributes[indx].pointer = pointer; } } void VertexAttributeBinding::bind() { if (_handle) { // Hardware mode GL_ASSERT( glBindVertexArray(_handle) ); } else { // Software mode if (_mesh) { GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, _mesh->getVertexBuffer()) ); } else { GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, 0) ); } GP_ASSERT(_attributes); for (unsigned int i = 0; i < __maxVertexAttribs; ++i) { VertexAttribute& a = _attributes[i]; if (a.enabled) { GL_ASSERT( glVertexAttribPointer(i, a.size, a.type, a.normalized, a.stride, a.pointer) ); GL_ASSERT( glEnableVertexAttribArray(i) ); } } } } void VertexAttributeBinding::unbind() { if (_handle) { // Hardware mode GL_ASSERT( glBindVertexArray(0) ); } else { // Software mode if (_mesh) { GL_ASSERT( glBindBuffer(GL_ARRAY_BUFFER, 0) ); } GP_ASSERT(_attributes); for (unsigned int i = 0; i < __maxVertexAttribs; ++i) { if (_attributes[i].enabled) { GL_ASSERT( glDisableVertexAttribArray(i) ); } } } } }
30.711475
197
0.582043
[ "mesh", "vector" ]
e740e875db977c6188ce536bf3c62d1137511d76
2,440
hpp
C++
src/Renderer/Shader.hpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
src/Renderer/Shader.hpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
src/Renderer/Shader.hpp
charlieSewell/YOKAI
4fb39975e58e9a49bc984bc6e844721a7ad9462e
[ "MIT" ]
null
null
null
#pragma once #include <GL/glew.h> #include <glm/glm.hpp> #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> /** * @class Shader * @brief class used for createing GLSL shaders */ class Shader { public: /** * @brief Constructor for a shader * @param const char* - vertexPath * @param const char* - fragmentPath */ Shader(const char* vertexPath, const char* fragmentPath); /** * @brief Construct a new Compute Shader * @param computePath */ Shader(const char* computePath); /** * @brief Binds the Shader for use */ void UseShader() const; /** * @brief Sets a Bool uniform in the shader * @param string& - uniformName * @param bool - value */ void SetBool(const std::string &uniformName, bool value) const; /** * @brief Sets an Int uniform in the shader * @param string& - uniformName * @param int - value */ void SetInt(const std::string &uniformName, int value) const; /** * @brief Sets a Float uniform in the shader * @param string& - uniformName * @param float - value */ void SetFloat(const std::string &uniformName, float value) const; /** * @brief Sets a 2Iv uniform in the shader * @param string& - uniformName * @param ivec2& - value */ void SetIvec2(const std::string &name, glm::ivec2 screenSize); /** * @brief Sets a mat4 uniform in the shader * @param string& - uniformName * @param mat4& - value */ void SetMat4(const std::string &uniformName, const glm::mat4 &mat) const; /** * @brief Sets a mat4 vec uniform in the shader * @param string& - uniformName * @param vector<mat4>& - value */ void SetVecMat4(const std::string &uniformName, const std::vector<glm::mat4> &mat) const; /** * @brief Sets a vec3 uniform in the shader * @param string& - uniformName * @param vec3& - value */ void SetVec3(const std::string &uniformName, const glm::vec3 &vec) const; /** * Returns the shadersID * @return unsigned int */ unsigned int GetShaderID(){return m_shaderID;} private: /** * @brief Checks for shader Compiler Errors * @param shader * @param type */ void CheckCompileErrors(GLuint shader, std::string type); ///Shaders ID unsigned int m_shaderID; };
26.813187
93
0.609836
[ "vector" ]
8d44e11ee25d115afe439eb6f3bb7335526baddb
2,703
cpp
C++
src/Screens/Experimental/HelloTriangleScreen.cpp
adamkewley/opensim-creator
322874255166884deb7731b202895a4813fea3b1
[ "Apache-2.0" ]
12
2021-08-31T08:44:27.000Z
2022-01-31T14:32:36.000Z
src/Screens/Experimental/HelloTriangleScreen.cpp
ComputationalBiomechanicsLab/opensim-creator
e5c4b24f5ef3bffe10c84899d0a0c79037020b6d
[ "Apache-2.0" ]
180
2022-01-27T15:25:15.000Z
2022-03-30T13:41:12.000Z
src/Screens/Experimental/HelloTriangleScreen.cpp
ComputationalBiomechanicsLab/opensim-creator
e5c4b24f5ef3bffe10c84899d0a0c79037020b6d
[ "Apache-2.0" ]
null
null
null
#include "HelloTriangleScreen.hpp" #include "src/App.hpp" #include "src/3D/Gl.hpp" #include "src/3D/GlGlm.hpp" #include "src/Screens/Experimental/ExperimentsScreen.hpp" #include <glm/vec3.hpp> #include <glm/vec4.hpp> using namespace osc; static constexpr char const g_VertexShader[] = R"( #version 330 core in vec3 aPos; void main() { gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); } )"; static constexpr char const g_FragmentShader[] = R"( #version 330 core out vec4 FragColor; uniform vec4 uColor; void main() { FragColor = uColor; } )"; namespace { struct BasicShader final { gl::Program program = gl::CreateProgramFrom( gl::CompileFromSource<gl::VertexShader>(g_VertexShader), gl::CompileFromSource<gl::FragmentShader>(g_FragmentShader)); gl::AttributeVec3 aPos = gl::GetAttribLocation(program, "aPos"); gl::UniformVec4 uColor = gl::GetUniformLocation(program, "uColor"); }; } static gl::VertexArray createVAO(BasicShader& shader, gl::ArrayBuffer<glm::vec3> const& points) { gl::VertexArray rv; gl::BindVertexArray(rv); gl::BindBuffer(points); gl::VertexAttribPointer(shader.aPos, false, sizeof(glm::vec3), 0); gl::EnableVertexAttribArray(shader.aPos); gl::BindVertexArray(); return rv; } struct osc::HelloTriangleScreen::Impl final { BasicShader shader; gl::ArrayBuffer<glm::vec3> points = { {-1.0f, -1.0f, 0.0f}, {+1.0f, -1.0f, 0.0f}, {+0.0f, +1.0f, 0.0f}, }; gl::VertexArray vao = createVAO(shader, points); float fadeSpeed = 1.0f; glm::vec4 color = {1.0f, 0.0f, 0.0f, 1.0f}; }; // public API osc::HelloTriangleScreen::HelloTriangleScreen() : m_Impl{new Impl{}} { } osc::HelloTriangleScreen::~HelloTriangleScreen() noexcept = default; void osc::HelloTriangleScreen::onEvent(SDL_Event const& e) { if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE) { App::cur().requestTransition<ExperimentsScreen>(); } } void osc::HelloTriangleScreen::tick(float dt) { if (m_Impl->color.r < 0.0f || m_Impl->color.r > 1.0f) { m_Impl->fadeSpeed = -m_Impl->fadeSpeed; } m_Impl->color.r -= dt * m_Impl->fadeSpeed; } void osc::HelloTriangleScreen::draw() { gl::Viewport(0, 0, App::cur().idims().x, App::cur().idims().y); gl::ClearColor(1.0f, 1.0f, 1.0f, 1.0f); gl::Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); gl::UseProgram(m_Impl->shader.program); gl::Uniform(m_Impl->shader.uColor, m_Impl->color); gl::BindVertexArray(m_Impl->vao); gl::DrawArrays(GL_TRIANGLES, 0, m_Impl->points.sizei()); gl::BindVertexArray(); }
25.5
97
0.647429
[ "3d" ]
8d450963096d3af2f7bbdb0c2587aebeb8d6200b
8,997
hpp
C++
datastructures/RnBTree.hpp
arupa-loka/lrep
7ef6ce39e7527693f8fb7d62b80a69fa29adc295
[ "Apache-2.0" ]
null
null
null
datastructures/RnBTree.hpp
arupa-loka/lrep
7ef6ce39e7527693f8fb7d62b80a69fa29adc295
[ "Apache-2.0" ]
null
null
null
datastructures/RnBTree.hpp
arupa-loka/lrep
7ef6ce39e7527693f8fb7d62b80a69fa29adc295
[ "Apache-2.0" ]
null
null
null
/* 1 - root is everytime black 2 - leaves are everytime black 3 - from the root each path toward the leaves includes exactly the same number of black nodes 4 - a red node can have only black children */ #ifndef __RED_AND_BLACK_TREE_HPP #define __RED_AND_BLACK_TREE_HPP #include <cstdio> #include <cstdlib> #include <cstddef> #include <cassert> // toGraphviz #include <iostream> #include <fstream> #include "Stack2.hpp" enum NODE_COLOR { RED=0, BLACK=1 }; template<class T> struct RnBNode { RnBNode(NODE_COLOR color=RED, RnBNode<T> * parent=NULL, RnBNode<T> * left=NULL, RnBNode<T> * right=NULL) : m_color(color), m_parent(parent), m_left(left), m_right(right) {} NODE_COLOR m_color; T m_value; RnBNode<T>* m_parent; RnBNode<T>* m_left; RnBNode<T>* m_right; RnBNode<T> * grandparent() { if (m_parent != NULL) { return m_parent->m_parent; } return NULL; } RnBNode<T> * uncle() { RnBNode<T> * grandparent = this->grandparent(); if (grandparent != NULL) { if (grandparent->m_left == m_parent) return grandparent->m_right; else return grandparent->m_left; } return NULL; } }; template<class T> class RnBTree { public: RnBTree(): m_root(NULL) {} ~RnBTree() {} // call normal insert binary tree and then rebalance the tree bool insert(T & value) { RnBNode<T> * new_node = insert_binary_tree(value); if (new_node != NULL) { insert_case_1(new_node); return true; } // otherwise do nothing, value already exists return false; } void remove(T & value) { // TODO } void toGraphViz(const char* iFilePath); private: RnBNode<T> * m_root; static RnBNode<T> m_leaf; void rotate_left(RnBNode<T> * n) { RnBNode<T> * p = n->m_parent; // parent RnBNode<T> * c = n->m_right; // child n->m_right = c->m_left; n->m_right->m_parent = n; c->m_left = n; n->m_parent = c; if (p!=NULL) { if (p->m_left == n) p->m_left = c; else p->m_right = c; c->m_parent = p; } else { c->m_parent = NULL; m_root = c; } } void rotate_right(RnBNode<T> * n) { RnBNode<T> * p = n->m_parent; RnBNode<T> * c = n->m_left; n->m_left = c->m_right; n->m_left->m_parent = n; c->m_right = n; n->m_parent = c; if (p!=NULL) { if (p->m_left == n) p->m_left = c; else p->m_right = c; c->m_parent = p; } else { c->m_parent = NULL; m_root = c; } } // insert as in binary tree taking into account the extra leaves nodes at // the end RnBNode<T> * insert_binary_tree(T & value) { RnBNode<T> * new_node = NULL; if (m_root != NULL) { RnBNode<T> * curr_node = m_root; // notice that we cannot rely on the m_leaf.parent value // then we have to save the leaf parent in curr_node while (1) { if (value < curr_node->m_value) if (curr_node->m_left != &m_leaf) curr_node = curr_node->m_left; else break; // leaf node reached else if (curr_node->m_value < value) if (curr_node->m_right != &m_leaf) { curr_node = curr_node->m_right; } else { break; // leaf node reached } else return NULL; // value already exists } // insert all new nodes as RED nodes new_node = new RnBNode<T>(RED, // color curr_node,// parent &m_leaf, // left child &m_leaf); // right child new_node->m_value = value; if (value < curr_node->m_value) { curr_node->m_left = new_node; } else { curr_node->m_right = new_node; } } else { // root node must be BLACK m_root = new RnBNode<T>(BLACK, NULL, &m_leaf, &m_leaf); m_root->m_value = value; new_node = m_root; } return new_node; } // case 1 root is NULL void insert_case_1(RnBNode<T> * new_node) { if (m_root==new_node) { // This is redoundant only the first time we create a root // but then can be called recursively from insert_case_3() // and in that case the root could be RED again m_root->m_color = BLACK; } else { insert_case_2(new_node); } } // case 2 parent is black void insert_case_2(RnBNode<T> * new_node) { assert(m_root->m_color == BLACK); if (new_node->m_parent->m_color == BLACK) { // do nothing return; } insert_case_3(new_node); } // insert_case_3 // parent and uncle are RED and grandparent is BLACK void insert_case_3(RnBNode<T> * new_node) { //assert(m_root->m_color == BLACK); assert(new_node->m_parent->m_color == RED); assert(new_node->grandparent()->m_color == BLACK); RnBNode<T> * uncle = new_node->uncle(); // If parent is RED then it cannot be the root, // then it must have a grandparent that is BLACK, // then it must have an uncle as well (thanks to the black leaves) assert(uncle != NULL); if (uncle->m_color == RED) { // parent RED and uncle RED // set them black and check grandparent RnBNode<T> * grandparent = new_node->grandparent(); new_node->m_parent->m_color = BLACK; uncle->m_color = BLACK; grandparent->m_color = RED; // TODO recursion, can make it iterative insert_case_1(grandparent); } else { // uncle is BLACK insert_case_4(new_node); } } // insert_case_4 void insert_case_4(RnBNode<T> * new_node) { RnBNode<T> * grandparent = new_node->grandparent(); RnBNode<T> * parent = new_node->m_parent; assert(grandparent->m_color == BLACK); assert(parent->m_color == RED); assert(new_node->uncle()->m_color == BLACK); if (new_node == parent->m_right && parent == grandparent->m_left) { // apply left rotation on parent rotate_left(parent); // now new_node is the node that was parent in the line above new_node = new_node->m_left; } else if (new_node == parent->m_left && parent == grandparent->m_right) { // apply right rotation on parent rotate_right(parent); // now new_node is the node that was parent in the line above new_node = new_node->m_right; } insert_case_5(new_node); } // insert_case_5 void insert_case_5(RnBNode<T> * new_node) { RnBNode<T> * grandparent = new_node->grandparent(); assert(new_node->m_color == RED); assert(new_node->m_parent->m_color == RED); assert(grandparent->m_color == BLACK); assert((new_node == new_node->m_parent->m_left && new_node->m_parent == grandparent->m_left) || (new_node == new_node->m_parent->m_right && new_node->m_parent == grandparent->m_right)); grandparent->m_color = RED; new_node->m_parent->m_color = BLACK; // TODO check this check //if (new_node == new_node->m_parent->m_left) { if (new_node->m_parent == grandparent->m_left) { // rotate right on grandparent rotate_right(grandparent); } else { // rotate left on grandparent rotate_left(grandparent); } } }; template<typename T> RnBNode<T> RnBTree<T>::m_leaf(BLACK); template < typename T > void RnBTree<T>::toGraphViz(const char * iFilePath) { std::ofstream out(iFilePath); if (!out.is_open()) { printf("Error: unable to open file: %s\n", iFilePath); return; } Stack2<RnBNode<T>*> stack; out << "digraph RnBTree {\n"; out << "node [ shape=record, fixedsize=false];\n"; //out << "{ rankdir=RL; }\n"; //out << "{ rank=same; "; if (m_root) stack.push(m_root); while( !stack.empty() ) { RnBNode<T>* p = stack.getTop(); stack.pop(); out << "\"" << p << "\""; out << "["; if (p->m_color==RED) out << "color=red "; else out << "color=black "; out << "label=\"" << p << " | "; out << "<f" << 0 << "> | "; out << "<f" << 1 << "> " << p->m_value << " | "; if (p->m_left) stack.push(p->m_left); out << "<f" << 2 << ">\"];\n"; if (p->m_right) stack.push(p->m_right); if (p->m_left) { out << "\"" << p << "\""; out << ":"; out << "f" << 0 << " -> "; out << "\"" << p->m_left << "\":f1;\n"; } if (p->m_right) { out << "\"" << p << "\""; out << ":"; out << "f" << 2 << " -> "; out << "\"" << p->m_right << "\":f1;\n"; } } out << "}\n"; out.close(); } #endif
27.429878
77
0.542514
[ "shape" ]
8d48a461ac12367cdb46c33b0f144fd840cafbc9
6,507
cpp
C++
src/backend/cpp/cover.cpp
wadymwadim/normandeau
2995a3293b22df269b88c3486e4f4009a1a5d76f
[ "Xnet", "X11" ]
null
null
null
src/backend/cpp/cover.cpp
wadymwadim/normandeau
2995a3293b22df269b88c3486e4f4009a1a5d76f
[ "Xnet", "X11" ]
null
null
null
src/backend/cpp/cover.cpp
wadymwadim/normandeau
2995a3293b22df269b88c3486e4f4009a1a5d76f
[ "Xnet", "X11" ]
null
null
null
#include <boost/algorithm/string.hpp> #include "cover.hpp" #include "parse.hpp" ClosedRectangleQ load_square(const std::string& dir) { auto line = read_file(dir + "/square.txt"); boost::trim(line); const auto coords = split(line, " "); if (coords.size() != 4) { std::ostringstream err{}; err << "load_square: expected 4 coordinates, got " << coords.size(); throw std::runtime_error(err.str()); } const Rational x_min{coords.at(0)}; const Rational x_max{coords.at(1)}; const Rational y_min{coords.at(2)}; const Rational y_max{coords.at(3)}; const ClosedRectangleQ square{{x_min, x_max}, {y_min, y_max}}; if (!square.is_square()) { throw std::runtime_error("load_square: not a square"); } return square; } OpenConvexPolygonQ load_polygon(const std::string& dir) { auto polygon_str = read_file(dir + "/polygon.txt"); boost::trim(polygon_str); std::vector<PointQ> vertices{}; const auto lines = split(polygon_str, "\n"); for (const auto& line : lines) { const auto coords = split(line, " "); if (coords.size() != 2) { std::ostringstream err{}; err << "load_polygon: expected 2 coordinates, got " << coords.size(); throw std::runtime_error(err.str()); } const Rational x{coords.at(0)}; const Rational y{coords.at(1)}; vertices.emplace_back(x, y); } return OpenConvexPolygonQ{vertices}; } std::vector<CodePair> load_singles(const std::string& dir) { // TODO rename to singles.txt auto singles_str = read_file(dir + "/stables.txt"); boost::trim(singles_str); auto lines = split(singles_str, "\n"); std::vector<CodePair> singles{}; size_t i = 0; for (auto& line : lines) { // Makes it easier to parse boost::algorithm::replace_first(line, ":", ","); auto comps = split(line, ","); if (comps.size() != 3) { std::ostringstream err{}; err << "load_singles: expected 3 components, got " << comps.size(); throw std::runtime_error(err.str()); } for (auto& str : comps) { boost::trim(str); } const auto index = boost::lexical_cast<size_t>(comps.at(0)); const auto stable = parse_code_sequence(comps.at(1)); const auto initial_angles = parse_initial_angles(comps.at(2)); // The indices must be in order if (index != i) { std::ostringstream err{}; err << "load_singles: mismatched indices: expected " << i << ", got " << index; throw std::runtime_error(err.str()); } singles.emplace_back(stable, initial_angles); ++i; } return singles; } std::vector<TriplePair> load_triples(const std::string& dir) { auto triples_str = read_file(dir + "/triples.txt"); boost::trim(triples_str); std::vector<TriplePair> triples{}; auto lines = split(triples_str, "\n"); size_t i = 0; for (auto& line : lines) { // Makes it easier to parse boost::algorithm::replace_first(line, ":", ","); boost::algorithm::replace_all(line, ";", ","); auto comps = split(line, ","); if (comps.size() != 7) { std::ostringstream err{}; err << "load_triples: expected 7 components, got " << comps.size(); throw std::runtime_error(err.str()); } for (auto& str : comps) { boost::trim(str); } const auto index = boost::lexical_cast<size_t>(comps.at(0)); const auto stable_neg_sequence = parse_code_sequence(comps.at(1)); const auto stable_neg_angles = parse_initial_angles(comps.at(2)); const auto unstable_sequence = parse_code_sequence(comps.at(3)); const auto unstable_angles = parse_initial_angles(comps.at(4)); const auto stable_pos_sequence = parse_code_sequence(comps.at(5)); const auto stable_pos_angles = parse_initial_angles(comps.at(6)); // The indices must be in order if (index != i) { std::ostringstream err{}; err << "load_triples: mismatched indices: expected " << i << ", got " << index; throw std::runtime_error(err.str()); } const CodePair stable_neg{stable_neg_sequence, stable_neg_angles}; const CodePair unstable{unstable_sequence, unstable_angles}; const CodePair stable_pos{stable_pos_sequence, stable_pos_angles}; triples.emplace_back(stable_neg, unstable, stable_pos); ++i; } return triples; } template <typename It> class Iterator final { private: It current; It end; public: explicit Iterator(const It start, const It end_) : current{start}, end{end_} {} const typename std::iterator_traits<It>::value_type& next() { if (current == end) { throw std::runtime_error("Iterator::next: iterator out of range"); } else { return *current++; } } }; static cover::Cover parse_cover(Iterator<std::vector<std::string>::const_iterator>& iter) { const auto& token = iter.next(); if (token == "E") { return cover::Empty{}; } else if (token == "S") { const auto& str = iter.next(); const auto index = boost::lexical_cast<size_t>(str); return cover::Single{index}; } else if (token == "T") { const auto& str = iter.next(); const auto index = boost::lexical_cast<size_t>(str); return cover::Triple{index}; } else if (token == "D") { auto cover0 = parse_cover(iter); auto cover1 = parse_cover(iter); auto cover2 = parse_cover(iter); auto cover3 = parse_cover(iter); return cover::Divide{std::move(cover0), std::move(cover1), std::move(cover2), std::move(cover3)}; } else { throw std::runtime_error("parse_cover: unknown token: " + token); } } cover::Cover load_cover(const std::string& dir) { auto str = read_file(dir + "/cover.txt"); boost::trim(str); const auto vec = split(str, " "); Iterator<std::vector<std::string>::const_iterator> iter{std::cbegin(vec), std::cend(vec)}; return parse_cover(iter); } uint32_t load_digits(const std::string& dir) { // TODO change this to digits.txt auto str = read_file(dir + "/precision.txt"); boost::trim(str); return boost::lexical_cast<uint32_t>(str); }
27.225941
105
0.595051
[ "vector" ]
8d48fb39de5bb1271658ed2b201838a1eaae8361
3,662
cpp
C++
shared/ebm_native/ebm_native_test/RandomNumbers.cpp
prateekiiest/interpret
b5530a587251a77516ab443037fc37f71708564c
[ "MIT" ]
null
null
null
shared/ebm_native/ebm_native_test/RandomNumbers.cpp
prateekiiest/interpret
b5530a587251a77516ab443037fc37f71708564c
[ "MIT" ]
null
null
null
shared/ebm_native/ebm_native_test/RandomNumbers.cpp
prateekiiest/interpret
b5530a587251a77516ab443037fc37f71708564c
[ "MIT" ]
1
2021-06-21T07:13:11.000Z
2021-06-21T07:13:11.000Z
// Copyright (c) 2018 Microsoft Corporation // Licensed under the MIT license. // Author: Paul Koch <code@koch.ninja> #include "PrecompiledHeaderEbmNativeTest.h" #include "ebm_native.h" #include "EbmNativeTest.h" #include "RandomStreamTest.h" static const TestPriority k_filePriority = TestPriority::RandomNumbers; TEST_CASE("GenerateRandomNumber, 0 0") { SeedEbmType ret = GenerateRandomNumber(0, 0); CHECK(1557540150 == ret); } TEST_CASE("GenerateRandomNumber, 1 3 (it gives us a negative return value)") { SeedEbmType ret = GenerateRandomNumber(1, 3); CHECK(-1784761967 == ret); } TEST_CASE("GenerateRandomNumber, -1 0") { SeedEbmType ret = GenerateRandomNumber(-1, 0); CHECK(237524772 == ret); } TEST_CASE("GenerateRandomNumber, max") { SeedEbmType ret = GenerateRandomNumber(std::numeric_limits<SeedEbmType>::max(), 0); CHECK(1266972904 == ret); } TEST_CASE("GenerateRandomNumber, lowest") { SeedEbmType ret = GenerateRandomNumber(std::numeric_limits<SeedEbmType>::lowest(), 0); CHECK(879100963 == ret); } TEST_CASE("SampleWithoutReplacement, stress test") { constexpr size_t cSamples = 1000; IntEbmType samples[cSamples]; RandomStreamTest randomStream(k_randomSeed); if(!randomStream.IsSuccess()) { exit(1); } SeedEbmType randomSeed = k_randomSeed; SeedEbmType stageRandomizationMix = SeedEbmType { 34298572 }; for(IntEbmType iRun = 0; iRun < 10000; ++iRun) { size_t cRandomSamples = randomStream.Next(cSamples + 1); size_t cTrainingSamples = randomStream.Next(cRandomSamples + size_t { 1 }); size_t cValidationSamples = cRandomSamples - cTrainingSamples; randomSeed = GenerateRandomNumber(randomSeed, stageRandomizationMix); SampleWithoutReplacement( randomSeed, static_cast<IntEbmType>(cTrainingSamples), static_cast<IntEbmType>(cValidationSamples), samples ); size_t cTrainingSamplesVerified = 0; size_t cValidationSamplesVerified = 0; for(size_t i = 0; i < cRandomSamples; ++i) { const IntEbmType val = samples[i]; CHECK(-1 == val || 1 == val); if(0 < val) { ++cTrainingSamplesVerified; } if(val < 0) { ++cValidationSamplesVerified; } } CHECK(cTrainingSamplesVerified == cTrainingSamples); CHECK(cValidationSamplesVerified == cValidationSamples); CHECK(cTrainingSamplesVerified + cValidationSamplesVerified == cRandomSamples); } } TEST_CASE("test random number generator equivalency") { TestApi test = TestApi(2); test.AddFeatures({ FeatureTest(2) }); test.AddFeatureGroups({ { 0 } }); std::vector<ClassificationSample> samples; for(int i = 0; i < 1000; ++i) { samples.push_back(ClassificationSample(i % 2, { 0 == (i * 7) % 3 })); } test.AddTrainingSamples(samples); test.AddValidationSamples({ ClassificationSample(0, { 0 }), ClassificationSample(1, { 1 }) }); test.InitializeBoosting(2); for(int iEpoch = 0; iEpoch < 100; ++iEpoch) { for(size_t iFeatureGroup = 0; iFeatureGroup < test.GetFeatureGroupsCount(); ++iFeatureGroup) { test.Boost(iFeatureGroup); } } FloatEbmType modelValue = test.GetCurrentModelPredictorScore(0, { 0 }, 1); // this is meant to be an exact check for this value. We are testing here if we can generate identical results // accross different OSes and C/C++ libraries. We specificed 2 inner samples, which will use the random generator // and if there are any differences between environments then this will catch those CHECK_APPROX(modelValue, -0.023961911283299608); }
32.990991
117
0.690606
[ "vector" ]
8d4a03b68e660f562b8c6e004742714d23803276
4,444
cpp
C++
Stars/src/Conversions.cpp
timgates42/Cinder-Samples
198ad7e352f5c7a6e8cf87d77a69e7c5270f2c02
[ "Unlicense" ]
300
2015-01-01T07:16:53.000Z
2022-03-26T09:28:44.000Z
Stars/src/Conversions.cpp
timgates42/Cinder-Samples
198ad7e352f5c7a6e8cf87d77a69e7c5270f2c02
[ "Unlicense" ]
7
2015-10-14T00:08:42.000Z
2020-12-24T12:54:38.000Z
Stars/src/Conversions.cpp
timgates42/Cinder-Samples
198ad7e352f5c7a6e8cf87d77a69e7c5270f2c02
[ "Unlicense" ]
86
2015-01-07T09:22:10.000Z
2021-10-08T14:27:40.000Z
/* Copyright (c) 2010-2012, Paul Houx - All rights reserved. This code is intended for use with the Cinder C++ library: http://libcinder.org Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Conversions.h" #include <boost/algorithm/string.hpp> #include <boost/tokenizer.hpp> #include <map> #include <sstream> using namespace ci; using namespace std; Color Conversions::toColor( uint32_t hex ) { float r = ( ( hex & 0x00FF0000 ) >> 16 ) / 255.0f; float g = ( ( hex & 0x0000FF00 ) >> 8 ) / 255.0f; float b = ( ( hex & 0x000000FF ) ) / 255.0f; return Color( r, g, b ); } ColorA Conversions::toColorA( uint32_t hex ) { float a = ( ( hex & 0xFF000000 ) >> 24 ) / 255.0f; float r = ( ( hex & 0x00FF0000 ) >> 16 ) / 255.0f; float g = ( ( hex & 0x0000FF00 ) >> 8 ) / 255.0f; float b = ( ( hex & 0x000000FF ) ) / 255.0f; return ColorA( r, g, b, a ); } int Conversions::toInt( const std::string &str ) { int x; std::istringstream i( str ); if( !( i >> x ) ) throw std::exception(); return x; } float Conversions::toFloat( const std::string &str ) { float x; std::istringstream i( str ); if( !( i >> x ) ) throw std::exception(); return x; } double Conversions::toDouble( const std::string &str ) { double x; std::istringstream i( str ); if( !( i >> x ) ) throw std::exception(); return x; } // void Conversions::mergeNames( ci::DataSourceRef hyg, ci::DataSourceRef ciel ) { // read star names std::string stars = loadString( ciel ); std::vector<std::string> tokens; std::map<uint32_t, std::string> names; std::vector<std::string> lines; // boost::algorithm::split( lines, stars, boost::is_any_of("\r\n"), boost::token_compress_on ); lines = ci::split( stars, "\r\n", true ); std::vector<std::string>::iterator itr; for( itr = lines.begin(); itr != lines.end(); ++itr ) { std::string line = boost::trim_copy( *itr ); if( line.empty() ) continue; if( line.substr( 0, 1 ) == ";" ) continue; try { uint32_t hr = Conversions::toInt( itr->substr( 0, 9 ) ); boost::algorithm::split( tokens, itr->substr( 9 ), boost::is_any_of( ";" ), boost::token_compress_off ); names.insert( std::pair<uint32_t, std::string>( hr, tokens[0] ) ); } catch( ... ) { } } // merge star names with HYG stars = loadString( hyg ); boost::algorithm::split( lines, stars, boost::is_any_of( "\n\r" ), boost::token_compress_on ); for( itr = lines.begin(); itr != lines.end(); ++itr ) { std::string line = boost::trim_copy( *itr ); boost::algorithm::split( tokens, line, boost::is_any_of( ";" ), boost::token_compress_off ); if( tokens.size() >= 4 && !tokens[4].empty() ) { try { uint32_t hr = Conversions::toInt( tokens[3] ); if( !names[hr].empty() ) { tokens[6] = names[hr]; } } catch( ... ) { } } *itr = boost::algorithm::join( tokens, ";" ); } stars = boost::algorithm::join( lines, "\r\n" ); DataTargetPathRef target = writeFile( hyg->getFilePath() ); OStreamRef stream = target->getStream(); stream->write( stars ); }
30.648276
110
0.637714
[ "vector" ]
8d4b41a3ca43c17b8675c7892302a88d5eb5eb15
11,756
cpp
C++
tests/unit/security/tpm/back-end.t.cpp
gtorresz/ndn-cxx-PEC
0b97a060a5eb67ee82c639f7120bc8147c8e1f52
[ "OpenSSL" ]
null
null
null
tests/unit/security/tpm/back-end.t.cpp
gtorresz/ndn-cxx-PEC
0b97a060a5eb67ee82c639f7120bc8147c8e1f52
[ "OpenSSL" ]
null
null
null
tests/unit/security/tpm/back-end.t.cpp
gtorresz/ndn-cxx-PEC
0b97a060a5eb67ee82c639f7120bc8147c8e1f52
[ "OpenSSL" ]
1
2022-03-29T08:17:27.000Z
2022-03-29T08:17:27.000Z
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright (c) 2013-2019 Regents of the University of California. * * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions). * * ndn-cxx library is free software: you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later version. * * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received copies of the GNU General Public License and GNU Lesser * General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see * <http://www.gnu.org/licenses/>. * * See AUTHORS.md for complete list of ndn-cxx authors and contributors. */ #include "ndn-cxx/security/tpm/back-end.hpp" #include "ndn-cxx/encoding/buffer-stream.hpp" #include "ndn-cxx/security/pib/key.hpp" #include "ndn-cxx/security/transform/bool-sink.hpp" #include "ndn-cxx/security/transform/buffer-source.hpp" #include "ndn-cxx/security/transform/private-key.hpp" #include "ndn-cxx/security/transform/public-key.hpp" #include "ndn-cxx/security/transform/verifier-filter.hpp" #include "tests/unit/security/tpm/back-end-wrapper-file.hpp" #include "tests/unit/security/tpm/back-end-wrapper-mem.hpp" #ifdef NDN_CXX_HAVE_OSX_FRAMEWORKS #include "tests/unit/security/tpm/back-end-wrapper-osx.hpp" #endif // NDN_CXX_HAVE_OSX_FRAMEWORKS #include "tests/boost-test.hpp" #include <boost/mpl/vector.hpp> #include <set> namespace ndn { namespace security { namespace tpm { namespace tests { BOOST_AUTO_TEST_SUITE(Security) BOOST_AUTO_TEST_SUITE(Tpm) BOOST_AUTO_TEST_SUITE(TestBackEnd) using tpm::Tpm; using TestBackEnds = boost::mpl::vector< #ifdef NDN_CXX_HAVE_OSX_FRAMEWORKS BackEndWrapperOsx, #endif // NDN_CXX_HAVE_OSX_FRAMEWORKS BackEndWrapperMem, BackEndWrapperFile>; BOOST_AUTO_TEST_CASE_TEMPLATE(KeyManagement, T, TestBackEnds) { T wrapper; BackEnd& tpm = wrapper.getTpm(); Name identity("/Test/KeyName"); name::Component keyId("1"); Name keyName = v2::constructKeyName(identity, keyId); // key should not exist BOOST_CHECK_EQUAL(tpm.hasKey(keyName), false); BOOST_CHECK(tpm.getKeyHandle(keyName) == nullptr); // create key, should exist BOOST_CHECK(tpm.createKey(identity, RsaKeyParams(keyId)) != nullptr); BOOST_CHECK(tpm.hasKey(keyName)); BOOST_CHECK(tpm.getKeyHandle(keyName) != nullptr); // create a key with the same name, should throw error BOOST_CHECK_THROW(tpm.createKey(identity, RsaKeyParams(keyId)), Tpm::Error); // delete key, should not exist tpm.deleteKey(keyName); BOOST_CHECK_EQUAL(tpm.hasKey(keyName), false); BOOST_CHECK(tpm.getKeyHandle(keyName) == nullptr); } BOOST_AUTO_TEST_CASE(CreateHmacKey) { Name identity("/Test/Identity/HMAC"); BackEndWrapperMem mem; BackEnd& memTpm = mem.getTpm(); auto key = memTpm.createKey(identity, HmacKeyParams()); BOOST_REQUIRE(key != nullptr); BOOST_CHECK(!key->getKeyName().empty()); BOOST_CHECK(memTpm.hasKey(key->getKeyName())); BackEndWrapperFile file; BackEnd& fileTpm = file.getTpm(); BOOST_CHECK_THROW(fileTpm.createKey(identity, HmacKeyParams()), std::invalid_argument); #ifdef NDN_CXX_HAVE_OSX_FRAMEWORKS BackEndWrapperOsx osx; BackEnd& osxTpm = osx.getTpm(); BOOST_CHECK_THROW(osxTpm.createKey(identity, HmacKeyParams()), std::invalid_argument); #endif // NDN_CXX_HAVE_OSX_FRAMEWORKS } BOOST_AUTO_TEST_CASE_TEMPLATE(RsaSigning, T, TestBackEnds) { T wrapper; BackEnd& tpm = wrapper.getTpm(); // create an RSA key Name identity("/Test/RSA/KeyName"); unique_ptr<KeyHandle> key = tpm.createKey(identity, RsaKeyParams()); Name keyName = key->getKeyName(); const uint8_t content[] = {0x01, 0x02, 0x03, 0x04}; auto sigValue = key->sign(DigestAlgorithm::SHA256, content, sizeof(content)); BOOST_REQUIRE(sigValue != nullptr); Block sigBlock(tlv::SignatureValue, sigValue); transform::PublicKey pubKey; ConstBufferPtr pubKeyBits = key->derivePublicKey(); pubKey.loadPkcs8(pubKeyBits->data(), pubKeyBits->size()); bool result; { using namespace transform; bufferSource(content, sizeof(content)) >> verifierFilter(DigestAlgorithm::SHA256, pubKey, sigBlock.value(), sigBlock.value_size()) >> boolSink(result); } BOOST_CHECK_EQUAL(result, true); tpm.deleteKey(keyName); BOOST_CHECK_EQUAL(tpm.hasKey(keyName), false); } BOOST_AUTO_TEST_CASE_TEMPLATE(RsaDecryption, T, TestBackEnds) { T wrapper; BackEnd& tpm = wrapper.getTpm(); // create an RSA key Name identity("/Test/KeyName"); unique_ptr<KeyHandle> key = tpm.createKey(identity, RsaKeyParams()); Name keyName = key->getKeyName(); const uint8_t content[] = {0x01, 0x02, 0x03, 0x04}; transform::PublicKey pubKey; ConstBufferPtr pubKeyBits = key->derivePublicKey(); pubKey.loadPkcs8(pubKeyBits->data(), pubKeyBits->size()); ConstBufferPtr cipherText = pubKey.encrypt(content, sizeof(content)); ConstBufferPtr plainText = key->decrypt(cipherText->data(), cipherText->size()); BOOST_CHECK_EQUAL_COLLECTIONS(content, content + sizeof(content), plainText->begin(), plainText->end()); tpm.deleteKey(keyName); BOOST_CHECK_EQUAL(tpm.hasKey(keyName), false); } BOOST_AUTO_TEST_CASE_TEMPLATE(EcdsaSigning, T, TestBackEnds) { T wrapper; BackEnd& tpm = wrapper.getTpm(); // create an EC key Name identity("/Test/EC/KeyName"); unique_ptr<KeyHandle> key = tpm.createKey(identity, EcKeyParams()); Name ecKeyName = key->getKeyName(); const uint8_t content[] = {0x01, 0x02, 0x03, 0x04}; auto sigValue = key->sign(DigestAlgorithm::SHA256, content, sizeof(content)); BOOST_REQUIRE(sigValue != nullptr); Block sigBlock(tlv::SignatureValue, sigValue); transform::PublicKey pubKey; ConstBufferPtr pubKeyBits = key->derivePublicKey(); pubKey.loadPkcs8(pubKeyBits->data(), pubKeyBits->size()); bool result; { using namespace transform; bufferSource(content, sizeof(content)) >> verifierFilter(DigestAlgorithm::SHA256, pubKey, sigBlock.value(), sigBlock.value_size()) >> boolSink(result); } BOOST_CHECK_EQUAL(result, true); tpm.deleteKey(ecKeyName); BOOST_CHECK_EQUAL(tpm.hasKey(ecKeyName), false); } BOOST_AUTO_TEST_CASE(HmacSigningAndVerifying) { BackEndWrapperMem wrapper; BackEnd& tpm = wrapper.getTpm(); // create an HMAC key Name identity("/Test/HMAC/KeyName"); unique_ptr<KeyHandle> key = tpm.createKey(identity, HmacKeyParams()); Name hmacKeyName = key->getKeyName(); const uint8_t content[] = {0x01, 0x02, 0x03, 0x04}; auto sigValue = key->sign(DigestAlgorithm::SHA256, content, sizeof(content)); BOOST_REQUIRE(sigValue != nullptr); Block sigBlock(tlv::SignatureValue, sigValue); bool result = key->verify(DigestAlgorithm::SHA256, content, sizeof(content), sigBlock.value(), sigBlock.value_size()); BOOST_CHECK_EQUAL(result, true); tpm.deleteKey(hmacKeyName); BOOST_CHECK_EQUAL(tpm.hasKey(hmacKeyName), false); } BOOST_AUTO_TEST_CASE_TEMPLATE(ImportExport, T, TestBackEnds) { const std::string privKeyPkcs1 = "MIIEpAIBAAKCAQEAw0WM1/WhAxyLtEqsiAJgWDZWuzkYpeYVdeeZcqRZzzfRgBQT\n" "sNozS5t4HnwTZhwwXbH7k3QN0kRTV826Xobws3iigohnM9yTK+KKiayPhIAm/+5H\n" "GT6SgFJhYhqo1/upWdueojil6RP4/AgavHhopxlAVbk6G9VdVnlQcQ5Zv0OcGi73\n" "c+EnYD/YgURYGSngUi/Ynsh779p2U69/te9gZwIL5PuE9BiO6I39cL9z7EK1SfZh\n" "OWvDe/qH7YhD/BHwcWit8FjRww1glwRVTJsA9rH58ynaAix0tcR/nBMRLUX+e3rU\n" "RHg6UbSjJbdb9qmKM1fTGHKUzL/5pMG6uBU0ywIDAQABAoIBADQkckOIl4IZMUTn\n" "W8LFv6xOdkJwMKC8G6bsPRFbyY+HvC2TLt7epSvfS+f4AcYWaOPcDu2E49vt2sNr\n" "cASly8hgwiRRAB3dHH9vcsboiTo8bi2RFvMqvjv9w3tK2yMxVDtmZamzrrnaV3YV\n" "Q+5nyKo2F/PMDjQ4eUAKDOzjhBuKHsZBTFnA1MFNI+UKj5X4Yp64DFmKlxTX/U2b\n" "wzVywo5hzx2Uhw51jmoLls4YUvMJXD0wW5ZtYRuPogXvXb/of9ef/20/wU11WFKg\n" "Xb4gfR8zUXaXS1sXcnVm3+24vIs9dApUwykuoyjOqxWqcHRec2QT2FxVGkFEraze\n" "CPa4rMECgYEA5Y8CywomIcTgerFGFCeMHJr8nQGqY2V/owFb3k9maczPnC9p4a9R\n" "c5szLxA9FMYFxurQZMBWSEG2JS1HR2mnjigx8UKjYML/A+rvvjZOMe4M6Sy2ggh4\n" "SkLZKpWTzjTe07ByM/j5v/SjNZhWAG7sw4/LmPGRQkwJv+KZhGojuOkCgYEA2cOF\n" "T6cJRv6kvzTz9S0COZOVm+euJh/BXp7oAsAmbNfOpckPMzqHXy8/wpdKl6AAcB57\n" "OuztlNfV1D7qvbz7JuRlYwQ0cEfBgbZPcz1p18HHDXhwn57ZPb8G33Yh9Omg0HNA\n" "Imb4LsVuSqxA6NwSj7cpRekgTedrhLFPJ+Ydb5MCgYEAsM3Q7OjILcIg0t6uht9e\n" "vrlwTsz1mtCV2co2I6crzdj9HeI2vqf1KAElDt6G7PUHhglcr/yjd8uEqmWRPKNX\n" "ddnnfVZB10jYeP/93pac6z/Zmc3iU4yKeUe7U10ZFf0KkiiYDQd59CpLef/2XScS\n" "HB0oRofnxRQjfjLc4muNT+ECgYEAlcDk06MOOTly+F8lCc1bA1dgAmgwFd2usDBd\n" "Y07a3e0HGnGLN3Kfl7C5i0tZq64HvxLnMd2vgLVxQlXGPpdQrC1TH+XLXg+qnlZO\n" "ivSH7i0/gx75bHvj75eH1XK65V8pDVDEoSPottllAIs21CxLw3N1ObOZWJm2EfmR\n" "cuHICmsCgYAtFJ1idqMoHxES3mlRpf2JxyQudP3SCm2WpGmqVzhRYInqeatY5sUd\n" "lPLHm/p77RT7EyxQHTlwn8FJPuM/4ZH1rQd/vB+Y8qAtYJCexDMsbvLW+Js+VOvk\n" "jweEC0nrcL31j9mF0vz5E6tfRu4hhJ6L4yfWs0gSejskeVB/w8QY4g==\n"; const std::string password("password"); const std::string wrongPassword("wrong"); T wrapper; BackEnd& tpm = wrapper.getTpm(); Name keyName("/Test/KeyName/KEY/1"); tpm.deleteKey(keyName); BOOST_REQUIRE_EQUAL(tpm.hasKey(keyName), false); transform::PrivateKey sKey; sKey.loadPkcs1Base64(reinterpret_cast<const uint8_t*>(privKeyPkcs1.data()), privKeyPkcs1.size()); OBufferStream os; sKey.savePkcs8(os, password.data(), password.size()); auto pkcs8 = os.buf(); // import with wrong password BOOST_CHECK_THROW(tpm.importKey(keyName, pkcs8->data(), pkcs8->size(), wrongPassword.data(), wrongPassword.size()), Tpm::Error); BOOST_CHECK_EQUAL(tpm.hasKey(keyName), false); // import with correct password tpm.importKey(keyName, pkcs8->data(), pkcs8->size(), password.data(), password.size()); BOOST_CHECK_EQUAL(tpm.hasKey(keyName), true); // import already present key BOOST_CHECK_THROW(tpm.importKey(keyName, pkcs8->data(), pkcs8->size(), password.data(), password.size()), Tpm::Error); // test derivePublicKey with the imported key auto keyHdl = tpm.getKeyHandle(keyName); auto pubKey = keyHdl->derivePublicKey(); BOOST_CHECK(pubKey != nullptr); // export auto exportedKey = tpm.exportKey(keyName, password.data(), password.size()); BOOST_CHECK_EQUAL(tpm.hasKey(keyName), true); transform::PrivateKey sKey2; sKey2.loadPkcs8(exportedKey->data(), exportedKey->size(), password.data(), password.size()); OBufferStream os2; sKey.savePkcs1Base64(os2); auto pkcs1 = os2.buf(); // verify that the exported key is identical to the key that was imported BOOST_CHECK_EQUAL_COLLECTIONS(privKeyPkcs1.begin(), privKeyPkcs1.end(), pkcs1->begin(), pkcs1->end()); // export nonexistent key tpm.deleteKey(keyName); BOOST_CHECK_EQUAL(tpm.hasKey(keyName), false); BOOST_CHECK_THROW(tpm.exportKey(keyName, password.data(), password.size()), Tpm::Error); } BOOST_AUTO_TEST_CASE(RandomKeyId) { BackEndWrapperMem wrapper; BackEnd& tpm = wrapper.getTpm(); Name identity("/Test/KeyName"); std::set<Name> keyNames; for (int i = 0; i < 100; i++) { auto key = tpm.createKey(identity, RsaKeyParams()); Name keyName = key->getKeyName(); BOOST_CHECK(keyNames.insert(keyName).second); } } BOOST_AUTO_TEST_SUITE_END() // TestBackEnd BOOST_AUTO_TEST_SUITE_END() // Tpm BOOST_AUTO_TEST_SUITE_END() // Security } // namespace tests } // namespace tpm } // namespace security } // namespace ndn
35.95107
117
0.747958
[ "vector", "transform" ]
8d4d0d8c05210cb91d0d1d46d2fff80343cb6ce6
2,729
cpp
C++
trees/102_binary_tree_level_order_traversal.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
1
2019-08-21T21:25:34.000Z
2019-08-21T21:25:34.000Z
trees/102_binary_tree_level_order_traversal.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
null
null
null
trees/102_binary_tree_level_order_traversal.cpp
rspezialetti/leetcode
4614ffe2a4923aae02f93096b6200239e6f201c1
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void bfsTraversal(TreeNode* root, vector<vector<int>>& ints, unordered_map<int,int>& dephts) { if(!root) return; queue<TreeNode*> nodes; nodes.push(root); while(!nodes.empty()) { const TreeNode* current = nodes.front(); nodes.pop(); const int idx_depth = dephts[(*current).val]; ints[idx_depth].push_back(current->val); if(current->left) nodes.push(current->left); if(current->right) nodes.push(current->right); } } void getDepth(TreeNode* current, TreeNode* parent, unordered_map<int,int>& dephts, int& max_depth) { if(!current) return; if(parent != nullptr) { dephts[current->val] = dephts[parent->val] + 1; max_depth = max(max_depth, dephts[current->val]); } else dephts[current->val] = 0; getDepth(current->left, current, dephts, max_depth); getDepth(current->right, current, dephts, max_depth); } vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> values; if(!root) return values; unordered_map<int,int> dephts; int max_depth = 0; getDepth(root, nullptr, dephts, max_depth); values.resize(max_depth + 1, vector<int>()); bfsTraversal(root, values, dephts); return values; } vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> values; if(!root) return values; queue<TreeNode*> nodes; nodes.push(root); while(!nodes.empty()) { vector<int> v_level; const int size_queue = nodes.size(); for(size_t i = 0; i < size_queue ; ++i) { const TreeNode* current = nodes.front(); v_level.push_back(current->val); nodes.pop(); if(current->left) nodes.push(current->left); if(current->right) nodes.push(current->right); } values.push_back(v_level); } return values; } };
25.504673
102
0.469036
[ "vector" ]
8d4e23e9ed243580bdd74a0b2980f38a8f34d969
7,057
cpp
C++
AVSCommon/AVS/src/Attachment/AttachmentManager.cpp
AndersSpringborg/avs-device-sdk
8e77a64c5be5a0b7b19c53549d91b0c45c37df3a
[ "Apache-2.0" ]
null
null
null
AVSCommon/AVS/src/Attachment/AttachmentManager.cpp
AndersSpringborg/avs-device-sdk
8e77a64c5be5a0b7b19c53549d91b0c45c37df3a
[ "Apache-2.0" ]
null
null
null
AVSCommon/AVS/src/Attachment/AttachmentManager.cpp
AndersSpringborg/avs-device-sdk
8e77a64c5be5a0b7b19c53549d91b0c45c37df3a
[ "Apache-2.0" ]
null
null
null
/* * Copyright Amazon.com, 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file 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 <vector> #include "AVSCommon/AVS/Attachment/InProcessAttachment.h" #include "AVSCommon/Utils/Logger/Logger.h" #include "AVSCommon/Utils/Memory/Memory.h" #include "AVSCommon/AVS/Attachment/AttachmentManager.h" namespace alexaClientSDK { namespace avsCommon { namespace avs { namespace attachment { using namespace alexaClientSDK::avsCommon::utils; using namespace alexaClientSDK::avsCommon::utils::memory; /// String to identify log entries originating from this file. static const std::string TAG("AttachmentManager"); /** * Create a LogEntry using this file's TAG and the specified event string. * * @param The event string for this @c LogEntry. */ #define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event) // The definition for these two static class members. constexpr std::chrono::minutes AttachmentManager::ATTACHMENT_MANAGER_TIMOUT_MINUTES_DEFAULT; constexpr std::chrono::minutes AttachmentManager::ATTACHMENT_MANAGER_TIMOUT_MINUTES_MINIMUM; // Used within generateAttachmentId(). static const std::string ATTACHMENT_ID_COMBINING_SUBSTRING = ":"; AttachmentManager::AttachmentManagementDetails::AttachmentManagementDetails() : creationTime{std::chrono::steady_clock::now()} { } std::shared_ptr<AttachmentManagerInterface> AttachmentManager::createInProcessAttachmentManagerInterface() { return std::make_shared<AttachmentManager>(AttachmentType::IN_PROCESS); } AttachmentManager::AttachmentManager(AttachmentType attachmentType) : m_attachmentType{attachmentType}, m_attachmentExpirationMinutes{ATTACHMENT_MANAGER_TIMOUT_MINUTES_DEFAULT} { } std::string AttachmentManager::generateAttachmentId(const std::string& contextId, const std::string& contentId) const { if (contextId.empty() && contentId.empty()) { ACSDK_ERROR(LX("generateAttachmentIdFailed") .d("reason", "contextId and contentId are empty") .d("result", "empty string")); return ""; } if (contextId.empty()) { ACSDK_WARN(LX("generateAttachmentIdWarning").d("reason", "contextId is empty").d("result", "contentId")); return contentId; } if (contentId.empty()) { ACSDK_WARN(LX("generateAttachmentIdWarning").d("reason", "contentId is empty").d("result", "contextId")); return contextId; } return contextId + ATTACHMENT_ID_COMBINING_SUBSTRING + contentId; } bool AttachmentManager::setAttachmentTimeoutMinutes(std::chrono::minutes minutes) { if (minutes < ATTACHMENT_MANAGER_TIMOUT_MINUTES_MINIMUM) { int minimumMinutes = ATTACHMENT_MANAGER_TIMOUT_MINUTES_MINIMUM.count(); std::string minutePrintString = (1 == minimumMinutes) ? " minute" : " minutes"; ACSDK_ERROR(LX("setAttachmentTimeoutError") .d("reason", "timeout parameter less than minimum value") .d("attemptedSetting", std::to_string(minimumMinutes) + minutePrintString)); return false; } std::lock_guard<std::mutex> lock(m_mutex); m_attachmentExpirationMinutes = minutes; return true; } AttachmentManager::AttachmentManagementDetails& AttachmentManager::getDetailsLocked(const std::string& attachmentId) { // This call ensures the details object exists, whether updated previously, or as a new object. auto& details = m_attachmentDetailsMap[attachmentId]; // If it's a new object, the inner attachment has not yet been created. Let's go do that. if (!details.attachment) { // Lack of default case will allow compiler to generate warnings if a case is unhandled. switch (m_attachmentType) { // The in-process attachment type. case AttachmentType::IN_PROCESS: details.attachment = alexaClientSDK::avsCommon::utils::memory::make_unique<InProcessAttachment>(attachmentId); break; } // In code compiled with no warnings, the following test should never pass. // Still, let's make sure the right thing happens if it does. Also, assign nullptr's so that application code // can detect the error and react accordingly. if (!details.attachment) { ACSDK_ERROR(LX("getDetailsLockedError").d("reason", "Unsupported attachment type")); } } return details; } std::unique_ptr<AttachmentWriter> AttachmentManager::createWriter( const std::string& attachmentId, utils::sds::WriterPolicy policy) { std::lock_guard<std::mutex> lock(m_mutex); auto& details = getDetailsLocked(attachmentId); if (!details.attachment) { ACSDK_ERROR(LX("createWriterFailed").d("reason", "Could not access attachment")); return nullptr; } auto writer = details.attachment->createWriter(policy); removeExpiredAttachmentsLocked(); return writer; } std::unique_ptr<AttachmentReader> AttachmentManager::createReader( const std::string& attachmentId, sds::ReaderPolicy policy) { std::lock_guard<std::mutex> lock(m_mutex); auto& details = getDetailsLocked(attachmentId); if (!details.attachment) { ACSDK_ERROR(LX("createWriterFailed").d("reason", "Could not access attachment")); return nullptr; } auto reader = details.attachment->createReader(policy); removeExpiredAttachmentsLocked(); return reader; } void AttachmentManager::removeExpiredAttachmentsLocked() { std::vector<std::string> idsToErase; auto now = std::chrono::steady_clock::now(); for (auto& iter : m_attachmentDetailsMap) { auto& details = iter.second; /* * Our criteria for releasing an AttachmentManagementDetails object - either: * - Both futures have been returned, which means the attachment now has a reader and writer. Great! * - Only the reader or writer future was returned, and the attachment has exceeded its lifetime limit. */ auto attachmentLifetime = std::chrono::duration_cast<std::chrono::minutes>(now - details.creationTime); if ((details.attachment->hasCreatedReader() && details.attachment->hasCreatedWriter()) || attachmentLifetime > m_attachmentExpirationMinutes) { idsToErase.push_back(iter.first); } } for (auto id : idsToErase) { m_attachmentDetailsMap.erase(id); } } } // namespace attachment } // namespace avs } // namespace avsCommon } // namespace alexaClientSDK
38.353261
119
0.704265
[ "object", "vector" ]
8d52114db7fc7d48c38c2f46ce2f0663af620a9e
3,265
cpp
C++
src/tests/Library/LibraryQml/librarymodel.cpp
aliakseis/FVD
8d549834fcf9e8fdd5ebecdcaf9410074876b2ed
[ "MIT" ]
null
null
null
src/tests/Library/LibraryQml/librarymodel.cpp
aliakseis/FVD
8d549834fcf9e8fdd5ebecdcaf9410074876b2ed
[ "MIT" ]
null
null
null
src/tests/Library/LibraryQml/librarymodel.cpp
aliakseis/FVD
8d549834fcf9e8fdd5ebecdcaf9410074876b2ed
[ "MIT" ]
null
null
null
#include "librarymodel.h" #include <QFileInfo> #include <QDebug> #ifndef DEVELOPER_DISABLE_SETTINGS #include "settings_declaration.h" #else #include <QDesktopServices> #endif #include <QDateTime> int LibraryModel::counter = 0; LibraryModel::LibraryModel(QObject* parent) : QAbstractListModel(parent), m_fakeRows(0) { m_urls.append("http://tuxpaint.org/stamps/stamps/animals/birds/cartoon/tux.png"); m_urls.append("http://upload.wikimedia.org/wikipedia/commons/4/47/Moon.png"); m_urls.append("http://2lx.ru/uploads/2012/05/qtcreator.png"); m_urls.append("http://www.wpclipart.com/space/moon/far_side_of_the_Moon.png"); m_urls.append("http://www.google.by/images/srpr/logo3w.png"); update(); } void LibraryModel::update() { qDebug() << "Update library model"; m_items.clear(); m_itemsName.clear(); QStringList videoFilesMask; videoFilesMask << "*.mp4" << "*.flv"; beginResetModel(); #ifndef DEVELOPER_DISABLE_SETTINGS m_dir = GET_SETTING(saveVideoPath); #else QStringList paths = QStandardPaths::standardLocations(QStandardPaths::MoviesLocation); m_dir = !paths.empty() ? paths.at(0) : QString(); #endif m_filesList = m_dir.entryInfoList(videoFilesMask); foreach(QFileInfo fi, m_filesList) { m_items.append(++counter); m_itemsName.append(fi.fileName()); } endResetModel(); } void LibraryModel::addFakeRow() { qDebug() << "addFakeRow"; //beginInsertRows(QModelIndex(), m_items.count(), m_items.count()); beginInsertRows(QModelIndex(), 0, 0); m_items.prepend(++counter); m_itemsName.append(QString("Name %1").arg(counter)); endInsertRows(); } int LibraryModel::rowCount(const QModelIndex& /*parent*/) const { return m_items.count(); } QVariant LibraryModel::data(const QModelIndex& index, int role) const { if (!index.isValid()) { return QVariant(); } QVariant result; switch (role) { case Qt::DisplayRole: { if (index.row() < m_items.count()) { result = m_itemsName.at(index.row()); } else { result = "random name"; } } break; case RoleThumbnail: { if (index.row() < m_urls.size()) { result = m_urls.at(index.row()); } else { result = "http://tcuttrissweb.files.wordpress.com/2012/02/youtube_logo.png"; } } break; case RoleTitle: { if (index.row() < m_items.count()) { result = m_itemsName.at(index.row()); } else { result = "random text"; } } break; case RoleDate: { result = QDateTime::currentDateTime().toString(Qt::SystemLocaleShortDate).left(10); } break; case RoleSize: { result = m_items.at(index.row()); } break; } return result; } bool LibraryModel::removeRows(int row, int count, const QModelIndex& parent) { qDebug() << "remove Rows LibraryModel " << row; if (row < 0) { return false; } int rowCount = this->rowCount(parent); if (row < rowCount) { int lastRow = row + count - 1; beginRemoveRows(parent, row, lastRow); for (int i = lastRow; i >= row; i--) { m_items.removeAt(i); m_itemsName.removeAt(i); } endRemoveRows(); return true; } return false; } QHash<int, QByteArray> LibraryModel::roleNames() const { QHash<int, QByteArray> roles; roles[RoleThumbnail] = "thumb"; roles[RoleTitle] = "title"; roles[RoleDate] = "fileCreated"; roles[RoleSize] = "fileSize"; return roles; }
19.787879
87
0.687902
[ "model" ]
8d52ee096ec4a7ec6c0d6124d8d920d197e4ff46
5,107
hpp
C++
src/httpp/http/client/Connection.hpp
dohse/httpp
dd997c59ca52c17b8cacd688b857480442ee907c
[ "BSD-2-Clause" ]
173
2015-01-06T21:25:05.000Z
2022-02-28T12:59:11.000Z
src/httpp/http/client/Connection.hpp
dohse/httpp
dd997c59ca52c17b8cacd688b857480442ee907c
[ "BSD-2-Clause" ]
19
2015-06-03T18:26:58.000Z
2021-02-27T09:12:02.000Z
src/httpp/http/client/Connection.hpp
dohse/httpp
dd997c59ca52c17b8cacd688b857480442ee907c
[ "BSD-2-Clause" ]
35
2015-01-08T15:25:25.000Z
2021-09-20T18:09:27.000Z
/* * Part of HTTPP. * * Distributed under the 2-clause BSD licence (See LICENCE.TXT file at the * project root). * * Copyright (c) 2014 Thomas Sanchez. All rights reserved. * */ #ifndef HTTPP_HTTP_CLIENT_DETAIL_CONNECTION_HPP_ #define HTTPP_HTTP_CLIENT_DETAIL_CONNECTION_HPP_ #include <atomic> #include <curl/curl.h> #include <future> #include <memory> #include <mutex> #include <vector> #include <boost/asio.hpp> #include <commonpp/core/LoggingInterface.hpp> #include <commonpp/thread/ThreadPool.hpp> #include "httpp/detail/config.hpp" #include "httpp/http/Protocol.hpp" #include "httpp/http/client/Request.hpp" #include "httpp/http/client/Response.hpp" namespace HTTPP { namespace HTTP { namespace client { void parseCurlResponseHeader(const std::vector<char>& headers, Response& response); namespace detail { struct Manager; FWD_DECLARE_LOGGER(client_connection_logger, commonpp::core::Logger); struct Connection : public std::enable_shared_from_this<Connection> { using ConnectionPtr = std::shared_ptr<Connection>; using ThreadPool = commonpp::thread::ThreadPool; template <typename T> using Promise = HTTPP::detail::Promise<T>; template <typename T> using Future = HTTPP::detail::Future<T>; using ExceptionPtr = HTTPP::detail::ExceptionPtr; using CompletionHandler = std::function<void(Future<Response>&&)>; Connection(Manager& manager, boost::asio::io_service& service); Connection(const Connection&) = delete; Connection& operator=(const Connection&) = delete; ~Connection(); template <typename T> void conn_setopt(CURLoption opt, T t) { auto rc = curl_easy_setopt(handle, opt, t); if (rc != CURLE_OK) { LOG(client_connection_logger, error) << "Error setting curl option: " << curl_easy_strerror(rc); throw std::runtime_error("Cannot set option on curl"); } } template <typename T> T conn_getinfo(CURLINFO info) { T data; auto rc = curl_easy_getinfo(handle, info, std::addressof(data)); if (rc != CURLE_OK) { LOG(client_connection_logger, error) << "Can't get info: " << curl_easy_strerror(rc); throw std::runtime_error(curl_easy_strerror(rc)); } return data; } void init(std::map<curl_socket_t, boost::asio::ip::tcp::socket*>& sockets); static ConnectionPtr createConnection(Manager& manager, boost::asio::io_service& service); static size_t writefn(char* buffer, size_t size, size_t nmemb, void* userdata); static size_t writeHd(char* buffer, size_t size, size_t nmemb, void* userdata); static curl_socket_t opensocket(void* clientp, curlsocktype purpose, struct curl_sockaddr* address); static int closesocket(void* clientp, curl_socket_t socket); void configureRequest(HTTPP::HTTP::Method method); void cancel(); void buildResponse(CURLcode code); void complete(ExceptionPtr ex = ExceptionPtr()); void setSocket(curl_socket_t socket); template <typename Cb> void poll(int action, Cb cb) { LOG(client_connection_logger, trace) << "Poll socket: " << socket << ", socket native_handle: " << socket->native_handle(); switch (action) { default: LOG(client_connection_logger, error) << "Unknow poll operation requested: " << action; complete(HTTPP::detail::make_exception_ptr( std::runtime_error("Unknow poll operation requested"))); break; case CURL_POLL_IN: socket->async_read_some(boost::asio::null_buffers(), cb); break; case CURL_POLL_OUT: socket->async_write_some(boost::asio::null_buffers(), cb); break; case CURL_POLL_INOUT: socket->async_read_some(boost::asio::null_buffers(), cb); socket->async_write_some(boost::asio::null_buffers(), cb); break; } } void cancelPoll() { if (socket) { socket->cancel(); } } Manager& handler; ThreadPool* dispatch = nullptr; CURL* handle = nullptr; int poll_action = 0; std::atomic_bool cancelled = {false}; char error_buffer[CURL_ERROR_SIZE] = {0}; boost::asio::io_service& service; boost::asio::ip::tcp::socket* socket = nullptr; std::map<curl_socket_t, boost::asio::ip::tcp::socket*>* sockets = nullptr; client::Request request; client::Response response; Promise<client::Response> promise; CompletionHandler completion_handler; bool expect_continue = false; std::vector<char> header; std::vector<char> buffer; std::atomic_bool result_notified = {true}; struct curl_slist* http_headers = nullptr; }; } // namespace detail } // namespace client } // namespace HTTP } // namespace HTTPP #endif // !HTTPP_HTTP_CLIENT_DETAIL_CONNECTION_HPP_
28.06044
83
0.64206
[ "vector" ]
8d530ac5bd3bbc5a55c7b8326867459a686a2d0d
15,859
cpp
C++
GA/ga_3.cpp
Epicato/MSA
aea757c2a311cc6d902dac1f8c6efa0080b829b0
[ "MIT" ]
null
null
null
GA/ga_3.cpp
Epicato/MSA
aea757c2a311cc6d902dac1f8c6efa0080b829b0
[ "MIT" ]
null
null
null
GA/ga_3.cpp
Epicato/MSA
aea757c2a311cc6d902dac1f8c6efa0080b829b0
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include <fstream> #include <algorithm> #include <vector> #include <queue> #include <string> #include <ctime> #include <cmath> using namespace std; vector<string> query = {"IPZJJLMLTKJULOSTKTJOGLKJOBLTXGKTPLUWWKOMOYJBGALJUKLGLOSVHWBPGWSLUKOBSOPLOOKUKSARPPJ", "IWTJBGTJGJTWGBJTPKHAXHAGJJSJJPPJAPJHJHJHJHJHJHJHJHJPKSTJJUWXHGPHGALKLPJTPJPGVXPLBJHHJPKWPPDJSG"}; const int N = 100; class Gene { const int GAP = 2; const int MISMATCH = 3; const double CROSS_RATE = 0.8; const double MUTE_RATE = 0.5; const int ITERS = 100; int it = 0; string seq1; string seq2; string seq3; vector<string> first_population[N]; int first_cost[N]; int last_cost[N]; vector<string> select_population[N]; vector<string> cross_population[N]; public: string res1; string res2; string res3; int bestcost; Gene(string s1,string s2,string s3):seq1(s1),seq2(s2),seq3(s3){}; void iteration(); void init_population(); void cost_eval(vector<string>* pop,int* costList); void selection(); void crossover(); void mutation(); void mix(); void print(); void calculate_best(); }; void Gene::iteration() { init_population(); cost_eval(first_population,first_cost); for(it = 0;it<ITERS;it++) { selection(); crossover(); mutation(); mix(); } calculate_best(); //print(); } void Gene::init_population() { for(int i =0;i<N;i++) { string s1,s2,s3; s1 = seq1; s2 = seq2; s3 = seq3; int max_size = max({s1.size(),s2.size(),s3.size()}); if(max_size == s1.size()) //s1 is the longest { while(s2.size()<s1.size()) { s2.insert(rand()%(s2.size()+1),"-"); } while(s3.size()<s1.size()) { s3.insert(rand()%(s3.size()+1),"-"); } } else if(max_size == s2.size()) //s2 is the longest { while(s1.size()<s2.size()) { s1.insert(rand()%(s1.size()+1),"-"); } while(s3.size()<s2.size()) { s3.insert(rand()%(s3.size()+1),"-"); } } else //s3 is the longest { while(s1.size()<s3.size()) { s1.insert(rand()%(s1.size()+1),"-"); } while(s2.size()<s3.size()) { s2.insert(rand()%(s2.size()+1),"-"); } } first_population[i].push_back(s1); first_population[i].push_back(s2); first_population[i].push_back(s3); //cout<<first_population[i][0]<<' '<<first_population[i][1]<<endl; } } void Gene::cost_eval(vector<string>* pop,int* costList) { for(int i =0;i<N;i++) { int cost=0; //cout<<pop[i][0].size()<<' '<<pop[i][1].size()<<endl; for(int idx = 0;idx<pop[i][0].size();idx++) { if(pop[i][0][idx] != pop[i][1][idx]) { if(pop[i][0][idx] == '-' || pop[i][1][idx] == '-') cost += GAP; else cost += MISMATCH; } if(pop[i][0][idx] != pop[i][2][idx]) { if(pop[i][0][idx] == '-' || pop[i][2][idx] == '-') cost += GAP; else cost += MISMATCH; } if(pop[i][2][idx] != pop[i][1][idx]) { if(pop[i][2][idx] == '-' || pop[i][1][idx] == '-') cost += GAP; else cost += MISMATCH; } // else if(pop[i][0][idx] == '-') //eliminate both'-' Better not use!!! Bad performance! // { // pop[i][0].erase(idx,1); // pop[i][1].erase(idx,1); // pop[i][2].erase(idx,1); // idx--; // } } costList[i] = cost; //cout<<costlist[i]<<endl; } } void Gene::selection() { double all_weight = 0; double weight[N]; double accumulated_weight = 0; double probability[N]; for(int i = 0;i<N;i++) { weight[i] = 1/(double)first_cost[i]; all_weight += weight[i]; } for(int i=0;i<N;i++) { accumulated_weight += weight[i]; probability[i] = accumulated_weight / all_weight; //cout<<weight[i]<<' '; } for(int i=0;i<N;i++) { double threshold = (double)rand()/RAND_MAX; for(int idx=0;idx<N;idx++) { if(threshold <= probability[idx]) //pick idx-th individual { select_population[i] = first_population[idx]; //cout<<endl<<idx; break; } } } } void Gene::crossover() { int child_idx = 0; for(int i=0;i<N/2;i++) { //pick parent individuals int father_idx,mother_idx; father_idx = rand()%N; mother_idx = rand()%N; while(mother_idx == father_idx) mother_idx = rand()%N; cross_population[child_idx] = select_population[father_idx]; cross_population[child_idx+1] = select_population[mother_idx]; double rate = (double)rand()/RAND_MAX; if(rate<=CROSS_RATE) { //exchange one of the sequences int num = rand()%3; string temp = cross_population[child_idx][num]; cross_population[child_idx][num] = cross_population[child_idx+1][num]; cross_population[child_idx+1][num] = temp; while(cross_population[child_idx][0].size()<max({cross_population[child_idx][0].size(),cross_population[child_idx][1].size(),cross_population[child_idx][2].size()})) { cross_population[child_idx][0] += "-"; } while(cross_population[child_idx][1].size()<max({cross_population[child_idx][0].size(),cross_population[child_idx][1].size(),cross_population[child_idx][2].size()})) { cross_population[child_idx][1] += "-"; } while(cross_population[child_idx][2].size()<max({cross_population[child_idx][0].size(),cross_population[child_idx][1].size(),cross_population[child_idx][2].size()})) { cross_population[child_idx][2] += "-"; } while(cross_population[child_idx+1][0].size()<max({cross_population[child_idx+1][0].size(),cross_population[child_idx+1][1].size(),cross_population[child_idx+1][2].size()})) { cross_population[child_idx+1][0] += "-"; } while(cross_population[child_idx+1][1].size()<max({cross_population[child_idx+1][0].size(),cross_population[child_idx+1][1].size(),cross_population[child_idx+1][2].size()})) { cross_population[child_idx+1][1] += "-"; } while(cross_population[child_idx+1][2].size()<max({cross_population[child_idx+1][0].size(),cross_population[child_idx+1][1].size(),cross_population[child_idx+1][2].size()})) { cross_population[child_idx+1][2] += "-"; } } child_idx += 2; } } void Gene::mutation() { for(int i=0;i<N;i++) { double rate = (double)rand()/RAND_MAX; if(rate<=MUTE_RATE) //mutation:insert a gap to both sequences { int mute_idx = rand()%(cross_population[i][0].size()+1); cross_population[i][0].insert(mute_idx,"-"); cross_population[i][1].insert(mute_idx,"-"); cross_population[i][2].insert(mute_idx,"-"); } //cout<<cross_population[i][0]<<endl<<cross_population[i][1]<<endl<<endl; } } void Gene::mix() { vector<string> next_population[N]; int next_cost[N]; int next_idx = 0; cost_eval(cross_population,last_cost); int temp[N],index[N]; //pick 70% from the cross_population int cross_num = round(0.7*N); copy(last_cost,last_cost+N,temp); sort(temp,temp+N); for(int i=0;i<N;i++) { index[i] = find(last_cost,last_cost+N,temp[i])-last_cost; temp[i] = -1; } for(int i=0;i<cross_num;i++) { next_cost[next_idx] = last_cost[index[i]]; next_population[next_idx] = cross_population[index[i]]; next_idx++; } //pick 20% from the first_population int first_num = round(0.2*N); copy(first_cost,first_cost+N,temp); sort(temp,temp+N); for(int i=0;i<N;i++) { index[i] = find(first_cost,first_cost+N,temp[i])-first_cost; temp[i] = -1; } for(int i=0;i<first_num;i++) { next_cost[next_idx] = first_cost[index[i]]; next_population[next_idx] = first_population[index[i]]; next_idx++; } //pick 10% from the new_population int new_num = N-first_num-cross_num; for(int i =0;i<new_num;i++) { string s1,s2,s3; s1 = seq1; s2 = seq2; s3 = seq3; int max_size = max({s1.size(),s2.size(),s3.size()}); if(max_size == s1.size()) //s1 is the longest { while(s2.size()<s1.size()) { s2.insert(rand()%(s2.size()+1),"-"); } while(s3.size()<s1.size()) { s3.insert(rand()%(s3.size()+1),"-"); } } else if(max_size == s2.size()) //s2 is the longest { while(s1.size()<s2.size()) { s1.insert(rand()%(s1.size()+1),"-"); } while(s3.size()<s2.size()) { s3.insert(rand()%(s3.size()+1),"-"); } } else //s3 is the longest { while(s1.size()<s3.size()) { s1.insert(rand()%(s1.size()+1),"-"); } while(s2.size()<s3.size()) { s2.insert(rand()%(s2.size()+1),"-"); } } next_population[next_idx].push_back(s1); next_population[next_idx].push_back(s2); next_population[next_idx].push_back(s3); int cost=0; for(int idx = 0;idx<s1.size();idx++) { if(s1[idx] != s2[idx]) { if(s1[idx] == '-' || s2[idx] == '-') cost += GAP; else cost += MISMATCH; } if(s1[idx] != s3[idx]) { if(s1[idx] == '-' || s3[idx] == '-') cost += GAP; else cost += MISMATCH; } if(s3[idx] != s2[idx]) { if(s3[idx] == '-' || s2[idx] == '-') cost += GAP; else cost += MISMATCH; } } next_cost[next_idx] = cost; next_idx ++; } //pass to the next iteration copy(next_cost,next_cost+N,first_cost); copy(next_population,next_population+N,first_population); } void Gene::print() { //cout<<"The best of ITERATION "<<it<<" is: "<<endl; cout<<"The best alignment is:"<<endl; int idx = 0; int minCost = INT_MAX; for(int i=0;i<N;i++) { if(first_cost[i]<minCost) { minCost = first_cost[i]; idx = i; } } for(int i=0;i<first_population[idx][0].size();i++) //eliminate both'-' { while(first_population[idx][0][i] == '-' && first_population[idx][1][i] == '-' && first_population[idx][2][i] == '-') { first_population[idx][0].erase(i,1); first_population[idx][1].erase(i,1); first_population[idx][2].erase(i,1); } } cout<<first_population[idx][0]<<endl<<first_population[idx][1]<<endl<<first_population[idx][2]<<endl; cout<<"The minCost is: "<<minCost<<endl; } void Gene::calculate_best() { int idx = 0; int minCost = INT_MAX; for(int i=0;i<N;i++) { if(first_cost[i]<minCost) { minCost = first_cost[i]; idx = i; } } for(int i=0;i<first_population[idx][0].size();i++) //eliminate both'-' { while(first_population[idx][0][i] == '-' && first_population[idx][1][i] == '-' && first_population[idx][2][i] == '-') { first_population[idx][0].erase(i,1); first_population[idx][1].erase(i,1); first_population[idx][2].erase(i,1); } } bestcost = minCost; res1 = first_population[idx][0]; res2 = first_population[idx][1]; res3 = first_population[idx][2]; } void findBestseq(string seq1,vector<string>& database,int &best_cost,int &idx1,int &idx2,string &res1,string &res2,string &res3) { for(int m = 0;m<database.size();m++) { for(int i = m+1;i<database.size();i++) { Gene new_gene(seq1,database[m],database[i]); new_gene.iteration(); if(new_gene.bestcost<best_cost) { best_cost = new_gene.bestcost; idx1 = m; idx2 = i; } } } // for the best seq, find the sub-optimal alignment for(int i=0;i<100;i++) { Gene new_gene(seq1,database[idx1],database[idx2]); new_gene.iteration(); if(new_gene.bestcost<best_cost) { best_cost = new_gene.bestcost; res1 = new_gene.res1; res2 = new_gene.res2; res3 = new_gene.res3; } } } int main() { srand(time(NULL)); clock_t start,end,mid1,mid2; start = clock(); mid1 = start; ifstream infile; infile.open("../data/MSA_database.txt",ios::in); if (!infile.is_open()) { cout << "read file error" << endl; return 0; } string data_seq; vector<string> database; while (getline(infile,data_seq)) { database.push_back(data_seq); } infile.close(); //2 queries in all for(int i=0;i<query.size();i++) { srand(time(NULL)); int best_cost = INT_MAX; int idx1 = -1; int idx2 = -1; string res1,res2,res3; findBestseq(query[i],database,best_cost,idx1,idx2,res1,res2,res3); cout<<"Best cost for query "<<i<<": "<<best_cost<<endl; cout<<"Best alignment:"<<endl; cout<<res1<<endl<<res2<<endl<<res3<<endl; mid2 = clock(); cout<<"time"<<i<<" = "<<double(mid2-mid1)/CLOCKS_PER_SEC<<"s"<<endl; mid1 = clock(); } // int cost = INT_MAX; // int idx = -1; // string res1,res2,res3; // string s2 = "IWTJBGTJGJTWGBJTPKHAXHAGJJXJJKPJTPJHJHJHJHJHJHJHJHJHKUTJJUWXHGHHGALKLPJTPJPGVXPLBJHH"; // string s3 = "WPIWTJBGTJGJTHGBJOXKHTXHAGJJXJJPPJTPJHJHJHJHJHJHJHJPKUAJJUWXHGHHGALKLPJTPJPGVXPLBJHHJPK"; // for(int i=0;i<100;i++) // { // Gene new_gene(query[1],s2,s3); // new_gene.iteration(); // if(new_gene.bestcost<cost) // { // cost = new_gene.bestcost; // res1 = new_gene.res1; // res2 = new_gene.res2; // res3 = new_gene.res3; // } // } // cout<<cost<<endl; // cout<<res1<<endl<<res2<<endl<<res3<<endl; end = clock(); cout<<"whole time = "<<double(end-start)/CLOCKS_PER_SEC<<"s"<<endl; return 0; }
29.922642
186
0.489817
[ "vector" ]
8d580af0b6170b36c2a49a5406a2fcd276a64367
6,892
cpp
C++
src/arch/MemoryCard/MemoryCardDriverThreaded_Windows.cpp
fpmuniz/stepmania
984dc8668f1fedacf553f279a828acdebffc5625
[ "MIT" ]
1,514
2015-01-02T17:00:28.000Z
2022-03-30T14:11:21.000Z
src/arch/MemoryCard/MemoryCardDriverThreaded_Windows.cpp
fpmuniz/stepmania
984dc8668f1fedacf553f279a828acdebffc5625
[ "MIT" ]
1,462
2015-01-01T10:53:29.000Z
2022-03-27T04:35:53.000Z
src/arch/MemoryCard/MemoryCardDriverThreaded_Windows.cpp
fpmuniz/stepmania
984dc8668f1fedacf553f279a828acdebffc5625
[ "MIT" ]
552
2015-01-02T05:34:41.000Z
2022-03-26T05:19:19.000Z
#include "global.h" #include "MemoryCardDriverThreaded_Windows.h" #include "RageUtil.h" #include "RageLog.h" #include "archutils/Win32/ErrorStrings.h" #include "PlayerNumber.h" #include "MemoryCardManager.h" MemoryCardDriverThreaded_Windows::MemoryCardDriverThreaded_Windows() { m_dwLastLogicalDrives = 0; } MemoryCardDriverThreaded_Windows::~MemoryCardDriverThreaded_Windows() { } static bool TestReady( const RString &sDrive, RString &sVolumeLabelOut ) { TCHAR szVolumeNameBuffer[MAX_PATH]; DWORD dwVolumeSerialNumber; DWORD dwMaximumComponentLength; DWORD lpFileSystemFlags; TCHAR szFileSystemNameBuffer[MAX_PATH]; if( !GetVolumeInformation( sDrive, szVolumeNameBuffer, sizeof(szVolumeNameBuffer), &dwVolumeSerialNumber, &dwMaximumComponentLength, &lpFileSystemFlags, szFileSystemNameBuffer, sizeof(szFileSystemNameBuffer)) ) return false; sVolumeLabelOut = szVolumeNameBuffer; return true; } bool MemoryCardDriverThreaded_Windows::TestWrite( UsbStorageDevice* pDevice ) { /* Try to write a file, to check if the device is writable and that we have write permission. * Use FILE_ATTRIBUTE_TEMPORARY to try to avoid actually writing to the device. This reduces * the chance of corruption if the user removes the device immediately, without doing anything. */ for( int i = 0; i < 10; ++i ) { HANDLE hFile = CreateFile( ssprintf( "%stmp%i", pDevice->sOsMountDir.c_str(), RandomInt(100000)), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr ); if( hFile == INVALID_HANDLE_VALUE ) { DWORD iError = GetLastError(); LOG->Warn( werr_ssprintf(iError, "Couldn't write to %s", pDevice->sOsMountDir.c_str()) ); if( iError == ERROR_FILE_EXISTS ) continue; break; } CloseHandle( hFile ); return true; } pDevice->SetError( "TestFailed" ); return false; } static bool IsFloppyDrive( const RString &sDrive ) { char szBuf[1024]; int iRet = QueryDosDevice( sDrive, szBuf, 1024 ); if( iRet == 0 ) { LOG->Warn( werr_ssprintf(GetLastError(), "QueryDosDevice(%s)", sDrive.c_str()) ); return false; } // Make sure szBuf is terminated with two nulls. This only may be needed if the buffer filled. szBuf[iRet-2] = 0; szBuf[iRet-1] = 0; const char *p = szBuf; while( *p ) { if( BeginsWith(p, "\\Device\\Floppy") ) return true; p += strlen(p)+1; } return false; } void MemoryCardDriverThreaded_Windows::GetUSBStorageDevices( vector<UsbStorageDevice>& vDevicesOut ) { LOG->Trace( "MemoryCardDriverThreaded_Windows::GetUSBStorageDevices" ); DWORD dwLogicalDrives = ::GetLogicalDrives(); m_dwLastLogicalDrives = dwLogicalDrives; const int MAX_DRIVES = 26; for( int i=0; i<MAX_DRIVES; ++i ) { DWORD mask = (1 << i); if( !(m_dwLastLogicalDrives & mask) ) continue; // drive letter is invalid RString sDrive = ssprintf( "%c:", 'A'+i%26 ); LOG->Trace( sDrive ); if( IsFloppyDrive(sDrive) ) { LOG->Trace( "IsFloppyDrive" ); continue; } // Testing hack: Allow non-removable drive letters to be used if that // driver letter is specified as a m_sMemoryCardOsMountPoint. bool bIsSpecifiedMountPoint = false; FOREACH_ENUM( PlayerNumber, p ) bIsSpecifiedMountPoint |= MEMCARDMAN->m_sMemoryCardOsMountPoint[p].Get().EqualsNoCase(sDrive); RString sDrivePath = sDrive + "\\"; if( bIsSpecifiedMountPoint ) { LOG->Trace( "'%s' is a specified mount point. Allowing...", sDrive.c_str() ); } else { if( GetDriveType(sDrivePath) != DRIVE_REMOVABLE ) { LOG->Trace( "not DRIVE_REMOVABLE" ); continue; } } RString sVolumeLabel; if( !TestReady(sDrivePath, sVolumeLabel) ) { LOG->Trace( "not TestReady" ); continue; } vDevicesOut.push_back( UsbStorageDevice() ); UsbStorageDevice &usbd = vDevicesOut.back(); usbd.SetOsMountDir( sDrive ); usbd.sDevice = "\\\\.\\" + sDrive; usbd.sVolumeLabel = sVolumeLabel; } for( size_t i = 0; i < vDevicesOut.size(); ++i ) { UsbStorageDevice &usbd = vDevicesOut[i]; // TODO: fill in bus/level/port with this: // http://www.codeproject.com/system/EnumDeviceProperties.asp // find volume size DWORD dwSectorsPerCluster; DWORD dwBytesPerSector; DWORD dwNumberOfFreeClusters; DWORD dwTotalNumberOfClusters; if( GetDiskFreeSpace( usbd.sOsMountDir, &dwSectorsPerCluster, &dwBytesPerSector, &dwNumberOfFreeClusters, &dwTotalNumberOfClusters ) ) { usbd.iVolumeSizeMB = (int)roundf( dwTotalNumberOfClusters * (float)dwSectorsPerCluster * dwBytesPerSector / (1024*1024) ); } } } bool MemoryCardDriverThreaded_Windows::USBStorageDevicesChanged() { return ::GetLogicalDrives() != m_dwLastLogicalDrives; } bool MemoryCardDriverThreaded_Windows::Mount( UsbStorageDevice* pDevice ) { // nothing to do here... return true; } void MemoryCardDriverThreaded_Windows::Unmount( UsbStorageDevice* pDevice ) { /* Try to flush the device before returning. This requires administrator priviliges. */ HANDLE hDevice = CreateFile( pDevice->sDevice, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr ); if( hDevice == INVALID_HANDLE_VALUE ) { LOG->Warn( werr_ssprintf(GetLastError(), "Couldn't open memory card device to flush (%s): CreateFile", pDevice->sDevice.c_str()) ); return; } if( !FlushFileBuffers(hDevice) ) LOG->Warn( werr_ssprintf(GetLastError(), "Couldn't flush memory card device (%s): FlushFileBuffers", pDevice->sDevice.c_str()) ); CloseHandle( hDevice ); } /* * (c) 2003-2004 Chris Danford * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
29.579399
133
0.731283
[ "vector" ]
8d5d28338975d23bf721c5e3eec32c5064726dc9
7,621
cxx
C++
main/slideshow/source/engine/shapes/externalshapebase.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/slideshow/source/engine/shapes/externalshapebase.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/slideshow/source/engine/shapes/externalshapebase.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include <canvas/debug.hxx> #include <tools/diagnose_ex.h> #include <canvas/verbosetrace.hxx> #include <comphelper/anytostring.hxx> #include <cppuhelper/exc_hlp.hxx> #include "externalshapebase.hxx" #include "eventmultiplexer.hxx" #include "vieweventhandler.hxx" #include "intrinsicanimationeventhandler.hxx" #include "tools.hxx" #include <boost/noncopyable.hpp> using namespace ::com::sun::star; namespace slideshow { namespace internal { class ExternalShapeBase::ExternalShapeBaseListener : public ViewEventHandler, public IntrinsicAnimationEventHandler, private boost::noncopyable { public: explicit ExternalShapeBaseListener( ExternalShapeBase& rBase ) : mrBase( rBase ) {} private: // ViewEventHandler // ------------------------------------------------- virtual void viewAdded( const UnoViewSharedPtr& ) {} virtual void viewRemoved( const UnoViewSharedPtr& ) {} virtual void viewChanged( const UnoViewSharedPtr& rView ) { mrBase.implViewChanged(rView); } virtual void viewsChanged() { mrBase.implViewsChanged(); } // IntrinsicAnimationEventHandler // ------------------------------------------------- virtual bool enableAnimations() { return mrBase.implStartIntrinsicAnimation(); } virtual bool disableAnimations() { return mrBase.implEndIntrinsicAnimation(); } ExternalShapeBase& mrBase; }; ExternalShapeBase::ExternalShapeBase( const uno::Reference< drawing::XShape >& xShape, double nPrio, const SlideShowContext& rContext ) : mxComponentContext( rContext.mxComponentContext ), mxShape( xShape ), mpListener( new ExternalShapeBaseListener(*this) ), mpShapeManager( rContext.mpSubsettableShapeManager ), mrEventMultiplexer( rContext.mrEventMultiplexer ), mnPriority( nPrio ), // TODO(F1): When ZOrder someday becomes usable: make this ( getAPIShapePrio( xShape ) ), maBounds( getAPIShapeBounds( xShape ) ) { ENSURE_OR_THROW( mxShape.is(), "ExternalShapeBase::ExternalShapeBase(): Invalid XShape" ); mpShapeManager->addIntrinsicAnimationHandler( mpListener ); mrEventMultiplexer.addViewHandler( mpListener ); } // --------------------------------------------------------------------- ExternalShapeBase::~ExternalShapeBase() { try { mrEventMultiplexer.removeViewHandler( mpListener ); mpShapeManager->removeIntrinsicAnimationHandler( mpListener ); } catch (uno::Exception &) { OSL_ENSURE( false, rtl::OUStringToOString( comphelper::anyToString( cppu::getCaughtException() ), RTL_TEXTENCODING_UTF8 ).getStr() ); } } // --------------------------------------------------------------------- uno::Reference< drawing::XShape > ExternalShapeBase::getXShape() const { return mxShape; } // --------------------------------------------------------------------- void ExternalShapeBase::play() { implStartIntrinsicAnimation(); } // --------------------------------------------------------------------- void ExternalShapeBase::stop() { implEndIntrinsicAnimation(); } // --------------------------------------------------------------------- void ExternalShapeBase::pause() { implPauseIntrinsicAnimation(); } // --------------------------------------------------------------------- bool ExternalShapeBase::isPlaying() const { return implIsIntrinsicAnimationPlaying(); } // --------------------------------------------------------------------- void ExternalShapeBase::setMediaTime(double fTime) { implSetIntrinsicAnimationTime(fTime); } // --------------------------------------------------------------------- bool ExternalShapeBase::update() const { return render(); } // --------------------------------------------------------------------- bool ExternalShapeBase::render() const { if( maBounds.getRange().equalZero() ) { // zero-sized shapes are effectively invisible, // thus, we save us the rendering... return true; } return implRender( maBounds ); } // --------------------------------------------------------------------- bool ExternalShapeBase::isContentChanged() const { return true; } // --------------------------------------------------------------------- ::basegfx::B2DRectangle ExternalShapeBase::getBounds() const { return maBounds; } // --------------------------------------------------------------------- ::basegfx::B2DRectangle ExternalShapeBase::getDomBounds() const { return maBounds; } // --------------------------------------------------------------------- ::basegfx::B2DRectangle ExternalShapeBase::getUpdateArea() const { return maBounds; } // --------------------------------------------------------------------- bool ExternalShapeBase::isVisible() const { return true; } // --------------------------------------------------------------------- double ExternalShapeBase::getPriority() const { return mnPriority; } // --------------------------------------------------------------------- bool ExternalShapeBase::isBackgroundDetached() const { // external shapes always have their own window/surface return true; } } }
31.36214
122
0.462538
[ "render" ]
8d6155e973e6f472965003c6c91ab446fd43a57d
1,900
cpp
C++
android-28/android/media/ImageReader.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/media/ImageReader.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-28/android/media/ImageReader.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./Image.hpp" #include "../os/Handler.hpp" #include "../view/Surface.hpp" #include "./ImageReader.hpp" namespace android::media { // Fields // QJniObject forward ImageReader::ImageReader(QJniObject obj) : JObject(obj) {} // Constructors // Methods android::media::ImageReader ImageReader::newInstance(jint arg0, jint arg1, jint arg2, jint arg3) { return callStaticObjectMethod( "android.media.ImageReader", "newInstance", "(IIII)Landroid/media/ImageReader;", arg0, arg1, arg2, arg3 ); } android::media::Image ImageReader::acquireLatestImage() const { return callObjectMethod( "acquireLatestImage", "()Landroid/media/Image;" ); } android::media::Image ImageReader::acquireNextImage() const { return callObjectMethod( "acquireNextImage", "()Landroid/media/Image;" ); } void ImageReader::close() const { callMethod<void>( "close", "()V" ); } void ImageReader::discardFreeBuffers() const { callMethod<void>( "discardFreeBuffers", "()V" ); } jint ImageReader::getHeight() const { return callMethod<jint>( "getHeight", "()I" ); } jint ImageReader::getImageFormat() const { return callMethod<jint>( "getImageFormat", "()I" ); } jint ImageReader::getMaxImages() const { return callMethod<jint>( "getMaxImages", "()I" ); } android::view::Surface ImageReader::getSurface() const { return callObjectMethod( "getSurface", "()Landroid/view/Surface;" ); } jint ImageReader::getWidth() const { return callMethod<jint>( "getWidth", "()I" ); } void ImageReader::setOnImageAvailableListener(JObject arg0, android::os::Handler arg1) const { callMethod<void>( "setOnImageAvailableListener", "(Landroid/media/ImageReader$OnImageAvailableListener;Landroid/os/Handler;)V", arg0.object(), arg1.object() ); } } // namespace android::media
18.627451
97
0.667368
[ "object" ]
8d6391fdbf228ab6072b5eaad77ca4b235ab2459
4,146
cpp
C++
src/appleseed-max-impl/logtarget.cpp
usakhelo/appleseed-max-experiments
a4f1fc5abce4b00a6b43d0d96b383857ed87ce8e
[ "MIT" ]
null
null
null
src/appleseed-max-impl/logtarget.cpp
usakhelo/appleseed-max-experiments
a4f1fc5abce4b00a6b43d0d96b383857ed87ce8e
[ "MIT" ]
null
null
null
src/appleseed-max-impl/logtarget.cpp
usakhelo/appleseed-max-experiments
a4f1fc5abce4b00a6b43d0d96b383857ed87ce8e
[ "MIT" ]
null
null
null
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2016-2018 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "logtarget.h" // appleseed-max headers. #include "utilities.h" // appleseed.foundation headers. #include "foundation/platform/windows.h" // include before 3ds Max headers #include "foundation/utility/string.h" // Boost headers. #include "boost/thread/locks.hpp" #include "boost/thread/mutex.hpp" // 3ds Max headers. #include <log.h> #include <max.h> // Standard headers. #include <string> #include <vector> namespace asf = foundation; namespace { typedef std::vector<std::string> StringVec; void emit_message(const DWORD type, const StringVec& lines) { for (const auto& line : lines) { GetCOREInterface()->Log()->LogEntry( type, FALSE, L"appleseed", L"[appleseed] %s", utf8_to_wide(line).c_str()); } } struct Message { DWORD m_type; StringVec m_lines; }; boost::mutex g_message_queue_mutex; std::vector<Message> g_message_queue; void push_message(const DWORD type, const StringVec& lines) { boost::mutex::scoped_lock lock(g_message_queue_mutex); Message message; message.m_type = type; message.m_lines = lines; g_message_queue.push_back(message); } void emit_pending_messages() { boost::mutex::scoped_lock lock(g_message_queue_mutex); for (const auto& message : g_message_queue) emit_message(message.m_type, message.m_lines); g_message_queue.clear(); } const UINT WM_TRIGGER_CALLBACK = WM_USER + 4764; bool is_main_thread() { return GetCOREInterface15()->GetMainThreadID() == GetCurrentThreadId(); } } void LogTarget::release() { delete this; } void LogTarget::write( const asf::LogMessage::Category category, const char* file, const size_t line, const char* header, const char* message) { DWORD type; switch (category) { case asf::LogMessage::Debug: type = SYSLOG_DEBUG; break; case asf::LogMessage::Info: type = SYSLOG_INFO; break; case asf::LogMessage::Warning: type = SYSLOG_WARN; break; case asf::LogMessage::Error: case asf::LogMessage::Fatal: default: type = SYSLOG_ERROR; break; } std::vector<std::string> lines; asf::split(message, "\n", lines); if (is_main_thread()) emit_message(type, lines); else { push_message(type, lines); PostMessage( GetCOREInterface()->GetMAXHWnd(), WM_TRIGGER_CALLBACK, reinterpret_cast<WPARAM>(emit_pending_messages), 0); } }
28.204082
80
0.645924
[ "vector" ]
8d664a489b35596b8256eec4fd3c339e4ef0263a
6,558
cxx
C++
Source/MeshTools/ReflectMeshes/source/ReflectMesh.cxx
SCIInstitute/ShapeWorks-Prep
7a3cb1eadf84c93e85874d9da230bb5eebb09bf3
[ "MIT" ]
null
null
null
Source/MeshTools/ReflectMeshes/source/ReflectMesh.cxx
SCIInstitute/ShapeWorks-Prep
7a3cb1eadf84c93e85874d9da230bb5eebb09bf3
[ "MIT" ]
1
2020-08-04T22:37:34.000Z
2020-08-05T06:17:43.000Z
Source/MeshTools/ReflectMeshes/source/ReflectMesh.cxx
SCIInstitute/ShapeWorks-Prep
7a3cb1eadf84c93e85874d9da230bb5eebb09bf3
[ "MIT" ]
null
null
null
#include "vtkSmartPointer.h" #include "vtkPolyDataReader.h" #include "vtkPolyDataWriter.h" #include "vtkReflectionFilter.h" #include "vtkGeometryFilter.h" #include "vtkDataSetSurfaceFilter.h" #include "vtkMatrix4x4.h" #include "vtkTransform.h" #include "vtkTransformPolyDataFilter.h" #include <vtkPLYReader.h> #include <vtkPLYWriter.h> #include "vtkUnstructuredGridReader.h" #include "vtkUnstructuredGridWriter.h" #include "vtkUnstructuredGrid.h" #include <vector> #include <string> #include <float.h> #include <fstream> #include <sstream> #include <vtkPolyDataNormals.h> #include <vtkReverseSense.h> #include "OptionParser.h" optparse::OptionParser buildParser() { const std::string usage = "%prog [OPTION]"; const std::string version = "%prog 0.1"; const std::string desc = "A command line tool that reflect meshes with respect to a specified center and specific axis...."; //const std::string epilog = "note: --numthreads 0 means use system default (usually max number supported).\n"; const std::string epilog = ""; optparse::OptionParser parser = optparse::OptionParser() .usage(usage) .version(version) .description(desc) .epilog(epilog); parser.add_option("--inFilename").action("store").type("string").set_default("").help("Mesh file to be reflected."); parser.add_option("--outFilename").action("store").type("string").set_default("").help("The filename of the output reflection mesh."); parser.add_option("--reflectCenterFilename").action("store").type("string").set_default("empty").help("The filename for origin about which reflection occurs."); parser.add_option("--inputDirection").action("store").type("int").set_default(0).help("Direction along which it needs to be reflected"); parser.add_option("--meshFormat").action("store").type("string").set_default("vtk").help("The IO mesh format"); return parser; } void convertUnstructuredGridToPolyData( vtkSmartPointer<vtkUnstructuredGrid> data, vtkSmartPointer<vtkPolyData> &output) { vtkSmartPointer<vtkPoints> verts = vtkSmartPointer<vtkPoints>::New(); for(vtkIdType n = 0; n < data->GetNumberOfPoints(); n++) { double pt[3]; data->GetPoint(n, pt); verts->InsertNextPoint(pt[0], pt[1], pt[2]); } output = vtkSmartPointer<vtkPolyData>::New(); output->SetPoints( verts ); vtkCellArray* cells = data->GetCells(); output->SetPolys( cells ); } int main(int argc, char* argv[]) { // read the command line parameters using the option parser optparse::OptionParser parser = buildParser(); optparse::Values & options = parser.parse_args(argc,argv); std::vector<std::string> args = parser.args(); if(argc < 2) { parser.print_help(); return EXIT_FAILURE; } std::string inFilename = (std::string) options.get("inFilename"); std::string outFilename = (std::string) options.get("outFilename"); std::string refCFilename = (std::string) options.get("reflectCenterFilename"); int inputDirection = (int) options.get("inputDirection"); std::string pref = (std::string) options.get("meshFormat"); vtkSmartPointer<vtkPolyData> mesh = vtkSmartPointer<vtkPolyData>::New(); if (pref == "ply") { vtkSmartPointer<vtkPLYReader> reader = vtkSmartPointer<vtkPLYReader>::New(); reader->SetFileName( inFilename.c_str()); reader->Update(); mesh->DeepCopy( reader->GetOutput() ); } else { vtkSmartPointer<vtkPolyDataReader> reader_pd = vtkSmartPointer<vtkPolyDataReader>::New(); reader_pd->SetFileName( inFilename.c_str() ); reader_pd->Update(); mesh->DeepCopy( reader_pd->GetOutput() ); } double cx, cy, cz; if(refCFilename == "empty"){ // find the center of the bounding box double max_x = -1*FLT_MAX, min_x = FLT_MAX; double max_y = -1*FLT_MAX, min_y = FLT_MAX; double max_z = -1*FLT_MAX, min_z = FLT_MAX; for(vtkIdType i = 0; i < mesh->GetNumberOfPoints(); i++){ double p[3]; mesh->GetPoint(i, p); if(max_x < p[0]) max_x = p[0]; if(max_y < p[1]) max_y = p[1]; if(max_z < p[2]) max_z = p[2]; if(min_x > p[0]) min_x = p[0]; if(min_y > p[1]) min_y = p[1]; if(min_z > p[2]) min_z = p[2]; } cx = -1*(max_x + min_x) / 2; cy = -1*(max_y + min_y) / 2; cz = -1*(max_z + min_z) / 2; std::cout << max_x << ", " << max_y << ", " << max_z <<std::endl; std::cout << min_x << ", " << min_y << ", " << min_z <<std::endl; } else{ std::ifstream infile; infile.open( refCFilename.c_str()); infile >> cx >> cy >> cz; } std::cout << cx << ", " << cy << ", " << cz <<std::endl; vtkSmartPointer<vtkTransform> tr = vtkSmartPointer<vtkTransform>::New(); double dir[3] = {1.0, 1.0, 1.0}; if(inputDirection == 0) { dir[0] = -1.0; } else if(inputDirection == 1) { dir[1] = -1.0; } else if(inputDirection == 2) { dir[2] = -1.0; } else { std::cerr << "Unknown direction\n"; return EXIT_FAILURE; } tr->Translate(-cx, -cy, -cz); tr->Scale(dir[0], dir[1], dir[2]); tr->Translate(cx, cy, cz); // in order to handle flipping normals under negative scaling vtkSmartPointer<vtkReverseSense> reverseSense = vtkSmartPointer<vtkReverseSense>::New(); reverseSense->SetInput(mesh); reverseSense->ReverseNormalsOff(); reverseSense->ReverseCellsOn(); reverseSense->Update(); vtkSmartPointer<vtkTransformPolyDataFilter> transform = vtkSmartPointer<vtkTransformPolyDataFilter>::New(); transform->SetTransform( tr ); transform->SetInput( reverseSense->GetOutput() ); transform->Update(); vtkSmartPointer<vtkPolyData> inp = vtkSmartPointer<vtkPolyData>::New(); // inp->ShallowCopy( normalGenerator->GetOutput() ); inp->ShallowCopy( transform->GetOutput() ); if (pref == "ply") { vtkSmartPointer<vtkPLYWriter> writer = vtkSmartPointer<vtkPLYWriter>::New(); writer->SetInput( inp ); writer->SetFileName( outFilename.c_str() ); writer->Update(); } else { vtkSmartPointer<vtkPolyDataWriter> writer = vtkSmartPointer<vtkPolyDataWriter>::New(); writer->SetInput( inp ); writer->SetFileName( outFilename.c_str() ); writer->Update(); } return EXIT_SUCCESS; }
36.842697
164
0.628088
[ "mesh", "vector", "transform" ]
8d66f10200789686efe02b880c66e4a60da6e201
24,600
cpp
C++
ARK2D/src/ARK2D/Core/Platform/GameContainerWindowsPhone8.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
6
2015-08-25T19:16:20.000Z
2021-04-19T16:47:58.000Z
ARK2D/src/ARK2D/Core/Platform/GameContainerWindowsPhone8.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
1
2015-09-17T14:03:12.000Z
2015-09-17T14:03:12.000Z
ARK2D/src/ARK2D/Core/Platform/GameContainerWindowsPhone8.cpp
ashleygwinnell/ark2d
bbfbee742ace9c52841dad4fab74d0d120ffe662
[ "Unlicense" ]
1
2018-10-02T19:59:47.000Z
2018-10-02T19:59:47.000Z
/* * GameContainerWindows.cpp * * Created on: 27 Feb 2011 * Author: ashley */ #include "GameContainerWindowsPhone8.h" #include "../GameContainer.h" #include "../../ARK2D.h" #include "../../Namespaces.h" #include "../../Includes.h" #include "../../Geometry/Shape.h" #include "../../Geometry/Circle.h" #include "../../Geometry/Line.h" #include "../../Geometry/Rectangle.h" #if defined(ARK2D_WINDOWS_PHONE_8) #include "../../Geometry/GigaRectangle.h" #include "../../Windres.h" #include "../../Graphics/Image.h" #include "../../Util/Log.h" namespace ARK { namespace Core { GameContainer::GameContainer(Game& g, int width, int height, int bpp, bool fullscreen): m_timer(), m_game(g), m_input(), m_graphics(), m_gamepads(), scene(NULL), m_originalWidth(width), m_originalHeight(height), m_width(width), m_height(height), m_screenWidth(0), m_screenHeight(0), m_scaleLock(false), m_scale(1.0f), m_scaleX(1.0f), m_scaleY(1.0f), m_translateX(0), m_translateY(0), m_bpp(bpp), m_fullscreen(fullscreen), m_resizable(false), m_scaleToWindow(true), m_touchMode(true), m_screenOrientationPrevious(ORIENTATION_DUMMY), m_orientationInverted(false), m_2in1enabled(false), m_bRunning(false), m_clearColor(Color::black), m_resizeBehaviour(RESIZE_BEHAVIOUR_SCALE), m_showingFPS(false), m_willLoadDefaultFont(true), m_platformSpecific() { m_platformSpecific.m_container = this; m_input.setGameContainer(this); //m_platformSpecific.m_hInstance = GetModuleHandle(NULL); ARK2D::s_container = this; ARK2D::s_game = &m_game; ARK2D::s_graphics = &m_graphics; ARK2D::s_input = &m_input; ARK2D::s_log = ARK::Util::Log::getInstance(); scene = new Scene(); scene->addChild(ARK2D::s_game); scene->addChild(ARK2D::s_log); ARK2D::getRenderer()->preinit(); } void GameContainer::setSize(int width, int height) { if (width == (signed int) m_width && height == (signed int) m_height) { return; } m_screenWidth = width; m_screenHeight = height; resizeBehaviour(width, height); resizeWindowToFitViewport(); } void GameContainer::setFullscreen(bool fullscreen) { this->m_fullscreen = fullscreen; } void GameContainer::setIcon(const std::string& path) { //m_platformSpecific.m_iconpath = path; } void GameContainer::initGamepads() { } void GameContainer::setCursorVisible(bool b) { //ShowCursor(b); } void GameContainer::resizeWindowToFitViewport() { ARK2D::getRenderer()->setScissorTestEnabled(false); } // Enable OpenGL // void GameContainerPlatform::enableOpenGL(HWND hWnd, HDC* hDC, HGLRC* hRC) // { // // // } void GameContainer::processGamepadInput() { } void GameContainer::start() { // Seed the random Random::init(); // populate the gamepads. ARK2D::getLog()->i("Initialising Gamepads... "); initGamepads(); ARK2D::getLog()->i("done."); // Initialise platform... //m_platformSpecific.initialize(); // Enable OpenGL ARK2D::getLog()->i("Initialising OpenGL... "); ARK2D::getRenderer()->init(); //gl2dxInit(m_platformSpecific.m_device, m_platformSpecific.m_deviceContext); //m_platformSpecific.enableOpenGL(m_platformSpecific.m_hWindow, &m_platformSpecific.m_hDeviceContext, &m_platformSpecific.m_hRenderingContext); this->enable2D(); ARK2D::getLog()->i("done."); // Load default Font - relies on Image so must be done after OpenGL is initted. //BMFont* fnt = new BMFont("data/fonts/default.fnt", "data/fonts/default.png"); //Image* fntImg = new Image((unsigned int) ARK2D_FONT_PNG, ARK2D_RESOURCE_TYPE_PNG); if (m_willLoadDefaultFont) { //ARK::Font::BMFont* fnt = new ARK::Font::BMFont(ARK2D_FONT_FNT, ARK2D_FONT_PNG, ARK2D_RESOURCE_TYPE_PNG); ARK::Font::BMFont* fnt = Resource::get("ark2d/fonts/default.fnt")->asFont()->asBMFont(); fnt->scale(0.5f); m_graphics.m_DefaultFont = fnt; m_graphics.m_Font = fnt; } else { m_graphics.m_DefaultFont = NULL; m_graphics.m_Font = NULL; } // Enable OpenAL Sound::initialiseXAudio(); ARK2D::getLog()->i("done."); ARK2D::getLog()->i("Initialising Window... "); //ShowWindow(m_platformSpecific.m_hWindow, SW_SHOWNORMAL); //UpdateWindow(m_platformSpecific.m_hWindow); //ClipCursor(&m_windowRect); ARK2D::getLog()->i("done."); ARK2D::getLog()->i("Initialising Log"); ARK2D::s_log->init(); ARK2D::getLog()->i("Initialising Localisations"); initLocalisation(); ARK2D::getLog()->i("Initialising "); ARK2D::getLog()->i(m_game.getTitle()); ARK2D::getLog()->i("..."); m_game.init(this); ARK2D::getLog()->i("Initialised "); ARK2D::getLog()->i(m_game.getTitle()); ARK2D::getLog()->i("..."); //Image::showAnyGlErrorAndExit(); m_bRunning = true; return; } void GameContainer::close() const { ARK2D::getContainer()->m_bRunning = false; Windows::ApplicationModel::Core::CoreApplication::Exit(); //Windows::Phone::UI::Input::BackPressedEventArgs^ args = ref new Windows::Phone::UI::Input::BackPressedEventArgs(); //m_platformSpecific.m_nativeGame->OnBackButtonPressed(NULL, args); } void GameContainerPlatform::swapBuffers() { // The first argument instructs DXGI to block until VSync, putting the application // to sleep until the next VSync. This ensures we don't waste any cycles rendering // frames that will never be displayed to the screen. HRESULT hr = m_swapChain->Present(1, 0); // Discard the contents of the render target. // This is a valid operation only when the existing contents will be entirely // overwritten. If dirty or scroll rects are used, this call should be removed. //m_deviceContext->DiscardView(m_renderTargetView); // Discard the contents of the depth stencil. //m_deviceContext->DiscardView(m_depthStencilView); // If the device was removed either by a disconnect or a driver upgrade, we // must recreate all device resources. if (hr == DXGI_ERROR_DEVICE_REMOVED) { handleDeviceLost(); } else { DX::ThrowIfFailed(hr); } } void GameContainer::swapBuffers() { //SwapBuffers(m_platformSpecific.m_hDeviceContext); m_platformSpecific.swapBuffers(); } int GameContainer::getGlobalMouseX() const { //DWORD mousepos = GetMessagePos(); //POINTS mouseXY = MAKEPOINTS(mousepos); //return mouseXY.x; ARK2D::getLog()->w("getGlobalMouseX not implemented"); return 0; } int GameContainer::getGlobalMouseY() const { //DWORD mousepos = GetMessagePos(); //POINTS mouseXY = MAKEPOINTS(mousepos); //return mouseXY.y; ARK2D::getLog()->w("getGlobalMouseY not implemented"); return 0; } // Disable OpenGL //void GameContainerPlatform::disableOpenGL(HWND hWnd, HDC hDC, HGLRC hRC) //{ //wglMakeCurrent( NULL, NULL ); //wglDeleteContext( hRC ); //ReleaseDC( hWnd, hDC ); //} void GameContainerPlatform::initialize( Windows::UI::Core::CoreWindow^ window, Windows::ApplicationModel::Core::IFrameworkView^ nativeGame) { m_window = window; m_nativeGame = m_nativeGame; createDeviceResources(); createWindowSizeDependentResources(); //gl2dxInit(*(&device), *(&context)); } // These are the resources that depend on the device. void GameContainerPlatform::createDeviceResources() { // This flag adds support for surfaces with a different color channel ordering // than the API default. It is required for compatibility with Direct2D. UINT creationFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; #if defined(_DEBUG) || defined(ARK2D_DEBUG) // If the project is in a debug build, enable debugging via SDK Layers with this flag. creationFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif // This array defines the set of DirectX hardware feature levels this app will support. // Note the ordering should be preserved. // Don't forget to declare your application's minimum required feature level in its // description. All applications are assumed to support 9.1 unless otherwise stated. D3D_FEATURE_LEVEL featureLevels[] = { //D3D_FEATURE_LEVEL_11_1, //D3D_FEATURE_LEVEL_11_0, //D3D_FEATURE_LEVEL_10_1, //D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3 }; // Create the Direct3D 11 API device object and a corresponding context. //ComPtr<ID3D11Device> device; //ComPtr<ID3D11DeviceContext> context; DX::ThrowIfFailed( D3D11CreateDevice( nullptr, // Specify nullptr to use the default adapter. D3D_DRIVER_TYPE_HARDWARE, nullptr, creationFlags, // Set set debug and Direct2D compatibility flags. featureLevels, // List of feature levels this app can support. ARRAYSIZE(featureLevels), D3D11_SDK_VERSION, // Always set this to D3D11_SDK_VERSION. &m_device, // Returns the Direct3D device created. &m_featureLevel, // Returns feature level of device created. &m_deviceContext // Returns the device immediate context. ) ); // Get the Direct3D 11.1 API device and context interfaces. //ComPtr<ID3D11Device1> d3dDevice; //ComPtr<ID3D11DeviceContext1> d3dContext; /*DX::ThrowIfFailed( device.As(&m_device) ); DX::ThrowIfFailed( context.As(&m_deviceContext) );*/ //m_d3dDevice = d3dDevice.Get(); //m_d3dContext = d3dContext.Get(); } void GameContainerPlatform::createWindowSizeDependentResources() { m_windowBounds = m_window->Bounds; // Calculate the necessary swap chain and render target size in pixels. m_renderTargetSize.Width = convertDipsToPixels(m_windowBounds.Width); m_renderTargetSize.Height = convertDipsToPixels(m_windowBounds.Height); DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {0}; swapChainDesc.Width = static_cast<UINT>(m_renderTargetSize.Width); // Match the size of the window. swapChainDesc.Height = static_cast<UINT>(m_renderTargetSize.Height); swapChainDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; // This is the most common swap chain format. swapChainDesc.Stereo = false; swapChainDesc.SampleDesc.Count = 1; // Don't use multi-sampling. swapChainDesc.SampleDesc.Quality = 0; swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc.BufferCount = 1; // On phone, only single buffering is supported. swapChainDesc.Scaling = DXGI_SCALING_STRETCH; // On phone, only stretch and aspect-ratio stretch scaling are allowed. swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD; // On phone, no swap effects are supported. swapChainDesc.Flags = 0; IDXGIDevice1* dxgiDevice = NULL; HRESULT hr = m_device->QueryInterface(__uuidof(IDXGIDevice1), (void**)&dxgiDevice); if (FAILED(hr)) { ARK2D::getLog()->e("Could not QueryInterface for IDXGIDevice1..."); exit(0); } IDXGIAdapter* dxgiAdapter; DX::ThrowIfFailed( dxgiDevice->GetAdapter(&dxgiAdapter) ); ComPtr<IDXGIFactory2> dxgiFactory; DX::ThrowIfFailed( dxgiAdapter->GetParent( __uuidof(IDXGIFactory2), &dxgiFactory ) ); Windows::UI::Core::CoreWindow^ window = m_window.Get(); DX::ThrowIfFailed( dxgiFactory->CreateSwapChainForCoreWindow( m_device, reinterpret_cast<IUnknown*>(window), &swapChainDesc, nullptr, // Allow on all displays. &m_swapChain ) ); // Ensure that DXGI does not queue more than one frame at a time. This both reduces latency and // ensures that the application will only render after each VSync, minimizing power consumption. DX::ThrowIfFailed( dxgiDevice->SetMaximumFrameLatency(1) ); // Create a render target view of the swap chain back buffer. ComPtr<ID3D11Texture2D> backBuffer; DX::ThrowIfFailed( m_swapChain->GetBuffer( 0, __uuidof(ID3D11Texture2D), &backBuffer ) ); DX::ThrowIfFailed( m_device->CreateRenderTargetView( backBuffer.Get(), nullptr, &m_renderTargetView ) ); // Create a depth stencil view. CD3D11_TEXTURE2D_DESC depthStencilDesc( DXGI_FORMAT_D24_UNORM_S8_UINT, static_cast<UINT>(m_renderTargetSize.Width), static_cast<UINT>(m_renderTargetSize.Height), 1, 1, D3D11_BIND_DEPTH_STENCIL ); ComPtr<ID3D11Texture2D> depthStencil; DX::ThrowIfFailed( m_device->CreateTexture2D( &depthStencilDesc, nullptr, &depthStencil ) ); D3D11_DEPTH_STENCIL_DESC actualDepthStencilDesc; ZeroMemory(&actualDepthStencilDesc, sizeof(actualDepthStencilDesc)); // Set up the description of the stencil state. actualDepthStencilDesc.DepthEnable = false; actualDepthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; actualDepthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; actualDepthStencilDesc.StencilEnable = false; actualDepthStencilDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK;// 0xFF; actualDepthStencilDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK;// 0xFF; // Stencil operations if pixel is front-facing. actualDepthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; actualDepthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP;// D3D11_STENCIL_OP_INCR; actualDepthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_REPLACE;// D3D11_STENCIL_OP_KEEP; actualDepthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Stencil operations if pixel is back-facing. actualDepthStencilDesc.BackFace = actualDepthStencilDesc.FrontFace; //actualDepthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; //actualDepthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR; //actualDepthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; //actualDepthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; // Create the depth stencil state. DX::ThrowIfFailed(m_device->CreateDepthStencilState(&actualDepthStencilDesc, &m_depthStencilState)); m_deviceContext->OMSetDepthStencilState(m_depthStencilState, 0); // 1); // Depth stencil view..? CD3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc(D3D11_DSV_DIMENSION_TEXTURE2D); DX::ThrowIfFailed( m_device->CreateDepthStencilView( depthStencil.Get(), &depthStencilViewDesc, &m_depthStencilView ) ); // alpha blend state D3D11_BLEND_DESC blendStateDesc; ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC)); blendStateDesc.AlphaToCoverageEnable = false; blendStateDesc.IndependentBlendEnable = false; blendStateDesc.RenderTarget[0].BlendEnable = TRUE; blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; // D3D11_BLEND_SRC_ALPHA;// D3D11_BLEND_INV_DEST_ALPHA;//D3D11_BLEND_SRC_ALPHA; blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; //D3D11_BLEND_DEST_ALPHA;// D3D11_BLEND_ONE;//D3D11_BLEND_DEST_ALPHA; blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;//D3D11_BLEND_OP_ADD; blendStateDesc.RenderTarget[0].RenderTargetWriteMask = 0x0f;//D3D11_COLOR_WRITE_ENABLE_ALL; HRESULT rs = m_device->CreateBlendState(&blendStateDesc, &m_blendState); if (FAILED(rs)) { ARK2D::getLog()->e("Failed To Create Blend State"); exit(0); } float blendFactor[] = { 0.0f, 0.0f, 0.0f, 0.0f }; m_deviceContext->OMSetBlendState(m_blendState, blendFactor, 0xFFFFFFFF); // alpha blend state D3D11_BLEND_DESC blendStateDesc2; ZeroMemory(&blendStateDesc2, sizeof(D3D11_BLEND_DESC)); blendStateDesc2.AlphaToCoverageEnable = false; blendStateDesc2.IndependentBlendEnable = false; blendStateDesc2.RenderTarget[0].BlendEnable = TRUE; blendStateDesc2.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; blendStateDesc2.RenderTarget[0].DestBlend = D3D11_BLEND_ONE; blendStateDesc2.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; blendStateDesc2.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; // D3D11_BLEND_SRC_ALPHA;// D3D11_BLEND_INV_DEST_ALPHA;//D3D11_BLEND_SRC_ALPHA; blendStateDesc2.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; //D3D11_BLEND_DEST_ALPHA;// D3D11_BLEND_ONE;//D3D11_BLEND_DEST_ALPHA; blendStateDesc2.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;//D3D11_BLEND_OP_ADD; blendStateDesc2.RenderTarget[0].RenderTargetWriteMask = 0x0f;//D3D11_COLOR_WRITE_ENABLE_ALL; HRESULT rs2 = m_device->CreateBlendState(&blendStateDesc2, &m_blendStateAdditive); if (FAILED(rs2)) { ARK2D::getLog()->e("Failed To Create (Additive) Blend State"); exit(0); } // render things that are backfacing. D3D11_RASTERIZER_DESC rasterDesc; rasterDesc.AntialiasedLineEnable = true; rasterDesc.CullMode = D3D11_CULL_NONE; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = false; rasterDesc.FillMode = D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.ScissorEnable = true; rasterDesc.SlopeScaledDepthBias = 0.0f; DX::ThrowIfFailed( m_device->CreateRasterizerState( &rasterDesc, &m_rasterStateSolid ) ); // render things that are backfacing. //D3D11_RASTERIZER_DESC rasterDesc; rasterDesc.AntialiasedLineEnable = true; rasterDesc.CullMode = D3D11_CULL_NONE; rasterDesc.DepthBias = 0; rasterDesc.DepthBiasClamp = false; rasterDesc.FillMode = D3D11_FILL_WIREFRAME; //D3D11_FILL_SOLID; rasterDesc.FrontCounterClockwise = false; rasterDesc.ScissorEnable = true; rasterDesc.SlopeScaledDepthBias = 0.0f; DX::ThrowIfFailed( m_device->CreateRasterizerState( &rasterDesc, &m_rasterStateWireframe ) ); m_deviceContext->RSSetState(m_rasterStateSolid); // Set the rendering viewport to target the entire window. CD3D11_VIEWPORT viewport( 0.0f, 0.0f, //m_container->m_width, //m_container->m_height m_renderTargetSize.Width, m_renderTargetSize.Height ); m_deviceContext->RSSetViewports(1, &viewport); //m_device->SetRenderState(D3DRS_LIGHTING, FALSE); // turn off the 3D lighting //d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE); //m_deviceContext->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); ID3D11RenderTargetView *const targets[1] = { m_renderTargetView }; m_deviceContext->OMSetRenderTargets(1, targets, NULL);// m_depthStencilView); } void GameContainerPlatform::updateAndRender() { ARK2D::getLog()->w("Platform::updateAndRender"); if (m_container->m_bRunning) { ARK2D::getLog()->w("Still loading..."); return; } m_container->m_timer.tick(); m_container->m_game.preUpdate(m_container, &m_container->m_timer); m_container->m_game.update(m_container, &m_container->m_timer); m_container->m_game.postUpdate(m_container, &m_container->m_timer); ARK2D::getInput()->clearKeyPressedRecord(); //arklog->i("native render"); //fillRect(100,100,10,10); RendererStats::reset(); Renderer* r = ARK2D::getRenderer(); // glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); beginDXFrame(); m_container->m_game.preRender(m_container, r); m_container->m_game.render(m_container, r); m_container->m_game.postRender(m_container, r); if (m_container->isShowingFPS()) { m_container->renderFPS(); } ARK2D::getLog()->render(m_container, r); ARK2D::getRenderer()->finish(); } void GameContainerPlatform::beginDXFrame() { //const float midnightBlue[] = { 0.098f, 0.098f, 0.439f, 1.000f }; const float midnightBlue[] = { m_container->m_clearColor.getRedf(), m_container->m_clearColor.getGreenf(), m_container->m_clearColor.getBluef(), m_container->m_clearColor.getAlphaf() }; m_deviceContext->ClearRenderTargetView( m_renderTargetView, midnightBlue ); m_deviceContext->ClearDepthStencilView( m_depthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 ); } // This method is called in the event handler for the SizeChanged event. void GameContainerPlatform::updateForWindowSizeChange() { //std::cout << "Window. Width: " << m_window->Bounds.Width << ". Height: " << m_window->Bounds.Height << "."; //MessageBox.Show("lol"); if (m_window->Bounds.Width != m_windowBounds.Width || m_window->Bounds.Height != m_windowBounds.Height) { ID3D11RenderTargetView* nullViews[] = {nullptr}; m_deviceContext->OMSetRenderTargets(ARRAYSIZE(nullViews), nullViews, nullptr); m_renderTargetView = nullptr; m_depthStencilView = nullptr; m_deviceContext->Flush(); createWindowSizeDependentResources(); } } // Recreate all device resources and set them back to the current state. void GameContainerPlatform::handleDeviceLost() { // Reset these member variables to ensure that UpdateForWindowSizeChange recreates all resources. m_windowBounds.Width = 0; m_windowBounds.Height = 0; m_swapChain = nullptr; createDeviceResources(); updateForWindowSizeChange(); } void GameContainerPlatform::releaseResourcesForSuspending() { // Phone applications operate in a memory-constrained environment, so when entering // the background it is a good idea to free memory-intensive objects that will be // easy to restore upon reactivation. The swapchain and backbuffer are good candidates // here, as they consume a large amount of memory and can be reinitialized quickly. m_swapChain = nullptr; m_renderTargetView = nullptr; m_depthStencilView = nullptr; } // Method to convert a length in device-independent pixels (DIPs) to a length in physical pixels. float GameContainerPlatform::convertDipsToPixels(float dips) { static const float dipsPerInch = 96.0f; #ifdef NTDDI_PHONE8 return floor(dips * DisplayProperties::LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer. #elif defined(NTDDI_WINBLUE) return floor(dips * DisplayInformation::GetForCurrentView()->LogicalDpi / dipsPerInch + 0.5f); // Round to nearest integer. #endif //return dips; } bool GameContainerPlatform::initOpenAL() { //IXAudio2* pXAudio2 = NULL; //HRESULT hr; //if ( FAILED(hr = XAudio2Create( &pXAudio2, 0, XAUDIO2_DEFAULT_PROCESSOR ) ) ) // return hr; //return hr; return false; } bool GameContainerPlatform::deinitOpenAL() { return true; } void GameContainerPlatform::setTitle(std::string title) { //SetWindowTextA(m_hWindow, title.c_str()); } string GameContainerPlatform::getResourcePath() const { //#ifdef ARK2D_WINDOWS_VS // return "data/"; //#else return "./data/"; //#endif } GameContainerARK2DResource GameContainerPlatform::getARK2DResourceWithLength(int resourceId, int resourceType) { ARK2D::getLog()->e("GameContainerPlatform::getARK2DResourceWithLength not implemented."); GameContainerARK2DResource retval; retval.data = NULL; retval.length = 0; return retval; } void* GameContainerPlatform::getARK2DResource(int resourceId, int resourceType) { GameContainerARK2DResource resource = getARK2DResourceWithLength(resourceId, resourceType); return resource.data; } } } #endif
33.606557
190
0.681789
[ "geometry", "render", "object", "shape", "3d" ]
8d69881b030bde797e1a3e64ac1ffff8332bef3a
7,913
cpp
C++
src/planet_loc.cpp
TehSnappy/lib_lunar_ex
a4cd4a3cdec44c2adaefbf1791b8863db568cbbd
[ "MIT" ]
null
null
null
src/planet_loc.cpp
TehSnappy/lib_lunar_ex
a4cd4a3cdec44c2adaefbf1791b8863db568cbbd
[ "MIT" ]
null
null
null
src/planet_loc.cpp
TehSnappy/lib_lunar_ex
a4cd4a3cdec44c2adaefbf1791b8863db568cbbd
[ "MIT" ]
1
2019-10-12T03:23:41.000Z
2019-10-12T03:23:41.000Z
#include <iostream> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "lunar-master/watdefs.h" #include "lunar-master/mpc_func.h" #include "lunar-master/lunar.h" #include "lunar-master/afuncs.h" #include "lunar-master/date.h" #include <ei.h> #include <unistd.h> #include <sys/select.h> #define J2000 2451545.0 #define PI 3.1415926535897932384626433832795028841971693993751058209749445923 #define EARTH_MOON_BALANCE 81.300569404492336 #define J2000_OBLIQUITY (23.4392911 * PI / 180) void erlcmd_send(char *response, size_t len) { uint16_t be_len = htons(len - sizeof(uint16_t)); memcpy(response, &be_len, sizeof(be_len)); size_t wrote = 0; do { ssize_t amount_written = write(STDOUT_FILENO, response + wrote, len - wrote); if (amount_written < 0) { if (errno == EINTR) continue; exit(0); } wrote += amount_written; } while (wrote < len); } static double make_ra_dec_string( double *vect, char *buff) { double ra = atan2( vect[1], vect[0]) * 12. / PI; const double dist = sqrt( vect[0] * vect[0] + vect[1] * vect[1] + vect[2] * vect[2]); double dec = asin( vect[2] / dist) * 180. / PI; long units; if( ra < 0.) ra += 24.; char resp[2048]; int resp_index = sizeof(uint16_t); units = (long)( ra * 3600. * 10000.); ei_encode_version(resp, &resp_index); ei_encode_map_header(resp, &resp_index, 2); ei_encode_atom(resp, &resp_index, "ra"); ei_encode_map_header(resp, &resp_index, 3); ei_encode_atom(resp, &resp_index, "h"); ei_encode_long(resp, &resp_index, units / 36000000L); ei_encode_atom(resp, &resp_index, "m"); ei_encode_long(resp, &resp_index, (units / 600000L) % 60L); ei_encode_atom(resp, &resp_index, "s"); ei_encode_long(resp, &resp_index, (units / 10000L) % 60L); sprintf( buff, "%02ldh %02ldm %02ld.%04lds ", units / 36000000L, (units / 600000L) % 60L, (units / 10000L) % 60L, units % 10000L); buff += strlen( buff); int make_neg = 1; if( dec < 0.) { *buff++ = '-'; dec = -dec; make_neg = -1; } else *buff++ = '+'; units = (long)( dec * 3600. * 1000.); sprintf( buff, "%02ld %02ld' %02ld.%03ld\" ", units / 3600000L, (units / 60000L) % 60L, (units / 1000L) % 60L, units % 1000L); ei_encode_atom(resp, &resp_index, "dec"); ei_encode_map_header(resp, &resp_index, 3); ei_encode_atom(resp, &resp_index, "d"); ei_encode_long(resp, &resp_index, units / 3600000L * make_neg); ei_encode_atom(resp, &resp_index, "m"); ei_encode_long(resp, &resp_index, (units / 60000L) % 60L); ei_encode_atom(resp, &resp_index, "s"); ei_encode_long(resp, &resp_index, (units / 1000L) % 60L); erlcmd_send(resp, resp_index); return( dist); } #define EARTH_MAJOR_AXIS 6378137. #define EARTH_MINOR_AXIS 6356752. static void compute_topocentric_offset( double *earth_vect, const double lat, const double lon, const double alt_in_meters, const double jd_ut) { double precess_matrix[9]; double rho_cos_phi, rho_sin_phi; int i; lat_alt_to_parallax( lat, alt_in_meters, &rho_cos_phi, &rho_sin_phi, EARTH_MAJOR_AXIS, EARTH_MINOR_AXIS); rho_cos_phi *= EARTH_MAJOR_AXIS / AU_IN_METERS; rho_sin_phi *= EARTH_MAJOR_AXIS / AU_IN_METERS; calc_planet_orientation( 3, 0, jd_ut, precess_matrix); spin_matrix( precess_matrix, precess_matrix + 3, lon); for( i = 0; i < 3; i++) earth_vect[i] = (rho_cos_phi * precess_matrix[i] + rho_sin_phi * precess_matrix[i + 6]); } #define N_PASSES 3 int main(int argc, char** argv) { { double xyz[4], xyz_topo[3], topo_offset[3]; double jd_utc = 2458386.354977; double earth_vect[6]; double lon = -73.133 * PI / 180.; /* Project Pluto corporate headquarters is */ double lat = 40.927 * PI / 180.; /* roughly at W 69.9, N 44.01, 100 meters alt */ double alt_in_meters = 0.; int i, planet_no, opt; char buff[80]; void *p; char priv_path[1024] = "priv"; char codepath[1024]; FILE *ifile; static const char *planet_names[10] = { "Sun", "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" }; while ((opt = getopt(argc, argv, "l:n:d:t:p:c:")) != -1) { switch (opt) { case 'l': lat = atof(optarg) * PI / 180.; break; case 'n': lon = atof(optarg) * PI / 180.; break; case 'd': jd_utc = atof(optarg); break; case 'p': planet_no = atoi(optarg); break; case 'c': strcpy(priv_path, optarg); break; default: fprintf(stderr, "Usage: %s [-criapdh] [file...]\n", argv[0]); exit(EXIT_FAILURE); } } double jd_td = jd_utc + td_minus_utc( jd_utc) / seconds_per_day; double jd_ut = jd_td - td_minus_ut( jd_utc) / seconds_per_day; // fprintf(stderr, "working with data %f, %f, %f, %d\n\n", lat, lon, jd_utc, planet_no); if (planet_no == 10) { sprintf(codepath, "%s/elp82.dat", priv_path); ifile = fopen( codepath, "rb"); if( !ifile) { fprintf(stderr, "Couldn't find 'elp82.dat'\n"); return( -1); } compute_elp_xyz( ifile, (jd_td - J2000) / 36525., 0., xyz); // fprintf(stderr, "Lunar distance from geocenter: %15.5f km\n", xyz[3]); /* Rotate from ecliptic J2000 to equatorial J2000: */ rotate_vector( xyz, J2000_OBLIQUITY, 0); for( i = 0; i < 3; i++) /* cvt earth-moon vector from km */ xyz[i] /= AU_IN_KM; /* into AU */ // fprintf(stderr, "after Lunar distance from geocenter\n"); compute_topocentric_offset( topo_offset, lat, lon, alt_in_meters, jd_ut); for( i = 0; i < 3; i++) /* make a topocentric version of the */ xyz_topo[i] = xyz[i] - topo_offset[i]; /* earth-moon vector */ make_ra_dec_string( xyz_topo, buff); // fprintf(stderr, "Topocentric Lunar position: %s\n", buff); fclose( ifile); } // else if( planet_no == 3) // { // char *vsop_data = load_file_into_memory( codepath, NULL); // pdata->ecliptic_lon = calc_vsop_loc( vsop_data, planet_no, 0, t_centuries, 0.) + pi; // pdata->ecliptic_lat = -calc_vsop_loc( vsop_data, planet_no, 1, t_centuries, 0.); // pdata->r = calc_vsop_loc( vsop_data, planet_no, 2, t_centuries, 0.); // } else if( planet_no != 3) { sprintf(codepath, "%s/ps_1996.dat", priv_path); ifile = fopen(codepath, "rb"); if( !ifile) { fprintf(stderr, "Couldn't find 'ps_1996.dat'\n"); return( -1); } p = load_ps1996_series( ifile, jd_td, 3); if( !p) { fprintf(stderr, "No planetary data before 1900 or after 2100\n"); return( -2); } // fprintf(stderr, "about to get_ps1996_position\n"); get_ps1996_position( jd_td, p, earth_vect, 0); // fprintf(stderr, "about to free load_ps1996_series\n"); free( p); for( i = 0; i < 3; i++) earth_vect[i] -= xyz[i] / (EARTH_MOON_BALANCE + 1.); for( i = 0; i < 3; i++) earth_vect[i] += topo_offset[i]; // fprintf(stderr, "about to load_ps1996_series\n"); p = load_ps1996_series( ifile, jd_td, planet_no); if( !p) fprintf( stderr, "No data for that time"); else { double dist = 0., state_vect[6], delta[3]; int pass; // fprintf(stderr, "about to take passes\n"); for( pass = 0; pass < N_PASSES; pass++) { get_ps1996_position( jd_td - dist * AU_IN_KM / (SPEED_OF_LIGHT * seconds_per_day), p, state_vect, 0); dist = 0.; for( i = 0; i < 3; i++) { delta[i] = state_vect[i] - earth_vect[i]; dist += delta[i] * delta[i]; } dist = sqrt( dist); } free( p); make_ra_dec_string( delta, buff); } // fprintf(stderr, "%-10s %s\n", planet_names[planet_no], buff); fclose( ifile); } } exit(EXIT_SUCCESS); }
31.400794
92
0.608492
[ "vector" ]
8d6a46c7ace2d0472174e7d11cc33c393c93c91a
1,370
cpp
C++
operator.cpp
lucas-stoltman/CPP-Playground
1b098141245806d57f3fb82ae44dc2374c6c662a
[ "MIT" ]
null
null
null
operator.cpp
lucas-stoltman/CPP-Playground
1b098141245806d57f3fb82ae44dc2374c6c662a
[ "MIT" ]
null
null
null
operator.cpp
lucas-stoltman/CPP-Playground
1b098141245806d57f3fb82ae44dc2374c6c662a
[ "MIT" ]
null
null
null
#include "operator.h" #include <iostream> #include <string> using namespace std; // constructors Operator::Operator(string newName, int n) : name(newName), num(n) {} Operator::Operator(int n) : num(n) {} Operator::~Operator() {} // getters int Operator::getNum() { return num; } string Operator::getName() { return name; } // setters void Operator::setNum(int n) { num = n; } void Operator::setName(string n) { name = n; } // actions void Operator::print() { cout << name << ": " << num << endl; } // ------------------------------------ // operator overloads // ------------------------------------ // << // void Operator::operator<<(Operator& op) { // cout << op.getName() << ": " << op.getNum() << endl; // } // = void Operator::operator=(int integer) { setNum(integer); } // + void Operator::operator+(int n) { setNum(num + n); } // object addition int Operator::operator+(Operator& op1) { int n; n = this->num + op1.getNum(); return n; } // ++prefix Operator& Operator::operator++() { ++num; return *this; } // - void Operator::operator-(int n) { setNum(num - n); } // object subtraction int Operator::operator-(Operator& op1) { int n; n = this->num - op1.getNum(); return n; } // / void Operator::operator/(int integer) { setNum(num / integer); } // * void Operator::operator*(int integer) { setNum(num * integer); }
19.295775
68
0.578832
[ "object" ]
8d734fa27f0802f96912a908a4a3d387e9b09dd7
5,734
hpp
C++
libs/network/include/network/service/feed_subscription_manager.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
3
2019-07-11T08:49:27.000Z
2021-09-07T16:49:15.000Z
libs/network/include/network/service/feed_subscription_manager.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
null
null
null
libs/network/include/network/service/feed_subscription_manager.hpp
devjsc/ledger-1
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
[ "Apache-2.0" ]
2
2019-07-13T12:45:22.000Z
2021-03-12T08:48:57.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ namespace fetch { namespace service { class Protocol; class FeedSubscriptionManager; } // namespace service } // namespace fetch #include "core/mutex.hpp" #include "network/details/thread_pool.hpp" #include "network/generics/work_items_queue.hpp" #include "network/message.hpp" #include "network/service/abstract_publication_feed.hpp" #include "network/service/message_types.hpp" #include "network/service/types.hpp" #include <condition_variable> #include <iterator> #include <vector> namespace fetch { namespace service { /* This is a subscription manager that is used on the server side. * * This class manages the client subscriptions. It is added to the * protocol and used by the service unit. * * A limitation of this implementation is that it does not have * multi-service support yet. This is, however, easily implmented at a * later point. */ class ServiceServerInterface; class FeedSubscriptionManager { public: using mutex_type = fetch::mutex::Mutex; using lock_type = std::lock_guard<fetch::mutex::Mutex>; using service_type = fetch::service::ServiceServerInterface; using connection_handle_type = uint64_t; using publishing_workload_type = std::tuple<service_type *, connection_handle_type, network::message_type const>; static constexpr char const *LOGGING_NAME = "FeedSubscriptionManager"; /* A feed that services can subscribe to. * @feed is the feed number defined in the protocol. * @publisher is an implementation class that subclasses * <AbstractPublicationFeed>. * * The subscription manager takes a publisher and manages its * subscribers. It when a protocol is added to the service, the feed * manager is bridges to the service via the * <AttachToService> function. The service * must implement a Send function that fulfills the concept given for * a service. */ FeedSubscriptionManager(feed_handler_type const &feed, AbstractPublicationFeed *publisher) : subscribe_mutex_(__LINE__, __FILE__) , feed_(feed) , publisher_(publisher) { workers_ = network::MakeThreadPool(3, "FeedSubscriptionManager"); } /* Attaches a feed to a given service. * @T is the type of the service * @service is a pointer to the service * * This function attaches a service to the feed. It ensures that * messages published by the publisher are packed and send to the * right client. */ void AttachToService(ServiceServerInterface *service); void PublishAll(std::vector<publishing_workload_type> &workload) { publishing_workload_.Add(workload.begin(), workload.end()); workload.clear(); workers_->Post([this]() { this->PublishingProcessor(); }); } void PublishingProcessor(); /* Subscribe client to feed. * @client is the client id. * @id is the subscription id allocated on the client side. * * This function is intended to be used by the <Protocol> through * which services can subscribe their clients to the feed. */ void Subscribe(uint64_t const &client, subscription_handler_type const &id) { LOG_STACK_TRACE_POINT; subscribe_mutex_.lock(); subscribers_.push_back({client, id}); subscribe_mutex_.unlock(); } /* Unsubscribe client to feed. * @client is the client id. * @id is the subscription id allocated on the client side. * * This function is intended to be used by the <Protocol> through * which services can unsubscribe their clients to the feed. */ void Unsubscribe(uint64_t const &client, subscription_handler_type const &id) { LOG_STACK_TRACE_POINT; subscribe_mutex_.lock(); std::vector<std::size_t> ids; for (std::size_t i = 0; i < subscribers_.size(); ++i) { if ((subscribers_[i].client == client) && (subscribers_[i].id == id)) { ids.push_back(i); } } std::reverse(ids.begin(), ids.end()); for (auto &i : ids) { subscribers_.erase(std::next(subscribers_.begin(), int64_t(i))); } subscribe_mutex_.unlock(); } /* Returns the feed type. * * @return the feed type. */ feed_handler_type const &feed() const { return feed_; } /* Returns a pointer to the abstract publisher. * * @return the publisher. */ fetch::service::AbstractPublicationFeed *publisher() const { return publisher_; } private: struct ClientSubscription { uint64_t client; // TODO(issue 21): change uint64_t to global client id. subscription_handler_type id; }; std::vector<ClientSubscription> subscribers_; fetch::mutex::Mutex subscribe_mutex_; feed_handler_type feed_; fetch::service::AbstractPublicationFeed *publisher_ = nullptr; generics::WorkItemsQueue<publishing_workload_type> publishing_workload_; network::ThreadPool workers_; }; } // namespace service } // namespace fetch
30.994595
94
0.679979
[ "vector" ]
8d74a267448858b1d3d9b3f412a471fec27b2af5
3,422
cpp
C++
openarcrt/omp_helper.cpp
swiftcurrent2018/openarc
0661581e5ab00f1093323ecc5e294b84e3e8a645
[ "BSD-3-Clause" ]
6
2020-02-02T11:04:22.000Z
2021-12-27T06:12:31.000Z
openarcrt/omp_helper.cpp
swiftcurrent2018/openarc
0661581e5ab00f1093323ecc5e294b84e3e8a645
[ "BSD-3-Clause" ]
null
null
null
openarcrt/omp_helper.cpp
swiftcurrent2018/openarc
0661581e5ab00f1093323ecc5e294b84e3e8a645
[ "BSD-3-Clause" ]
null
null
null
#include "omp_helper.h" #include "omp_helper_ext.h" int q_max = OMP_HELPER_QUEUE_MAX; int q_off = OMP_HELPER_QUEUE_OFF; omp_depend* depends[OMP_HELPER_QUEUE_DEPTH]; int depends_args[OMP_HELPER_QUEUE_DEPTH]; std::vector<omp_depend*> queues[OMP_HELPER_QUEUE_DEPTH][OMP_HELPER_QUEUE_MAX]; int depth; int q_wait_bits[OMP_HELPER_QUEUE_DEPTH]; int q_last_used[OMP_HELPER_QUEUE_DEPTH]; int q_cur; #ifdef _OPENMP #pragma omp threadprivate(depends, depends_args, queues, depth, q_wait_bits, q_last_used, q_cur) #endif void omp_helper_set_queue_max(int max) { q_max = max; } void omp_helper_set_queue_off(int off) { q_off = off; } void omp_helper_task_depend_check(omp_depend* d, int* wait_bits) { for (int i = 0; i < q_max; i++) { std::vector<omp_depend*> *q = queues[depth] + i; for (std::vector<omp_depend*>::iterator it = q->begin(); it != q->end(); ++it) { omp_depend* qr = *it; //printf("[%s:%d] qr[%llx:%llx] d[%llx,%llx]\n", __FILE__, __LINE__, qr->s, qr->e, d->s, d->e); if (qr->e < d->s || d->e < qr->s) continue; *wait_bits |= (1 << i); break; } } } void omp_helper_task_enter(int args, int* types, void** values) { int wait_bits = 0; omp_depend* d = new omp_depend[args]; for (int i = 0; i < args; i++) { d[i].t = types[i]; d[i].s = (size_t) values[i * 2 + 0]; d[i].e = (size_t) values[i * 2 + 1]; if (types[i] & oh_in) omp_helper_task_depend_check(d + i, &wait_bits); } //printf("[%s:%d] wait_bits[%x]\n", __FILE__, __LINE__, wait_bits); q_wait_bits[depth] = wait_bits; if (depends[depth]) delete[] depends[depth]; depends[depth] = d; depends_args[depth] = args; depth++; } void omp_helper_task_exit() { depth--; omp_depend* d = depends[depth]; for (int i = 0; i < depends_args[depth]; i++) { if (d[i].t & oh_out) { for (int j = 0; j < q_max; j++) { if (q_last_used[depth + 1] & (1 << j)) queues[depth][j].push_back(d + i); } } } q_last_used[depth + 1] = 0; } void omp_helper_task_exec(int args, int* types, void** values, int* async, int* waits) { int q = q_cur; int wait_bits = 0; omp_depend* d = new omp_depend[args]; for (int i = 0; i < args; i++) { d[i].t = types[i]; d[i].s = (size_t) values[i * 2 + 0]; d[i].e = (size_t) values[i * 2 + 1]; //printf("[%s:%d] R[%d] [%llx:%llx]\n", __FILE__, __LINE__, i, d[i].s, d[i].e); if (types[i] & oh_in) omp_helper_task_depend_check(d + i, &wait_bits); } // printf("[%s:%d] wait_bits[%x] q_cur[%d]\n", __FILE__, __LINE__, wait_bits, q_cur); for (int i = q_cur, j = 0; j < q_max; i++, j++) { if (wait_bits & (1 << i)) { q = i; wait_bits &= ~(1 << i); break; } if (i == q_max - 1) i = -1; if (j == q_max - 1) q_cur = q_cur + 1 == q_max ? 0 : q_cur + 1; } for (int i = 0; i < args; i++) { if (types[i] & oh_out) queues[depth][q].push_back(d + i); } q_last_used[depth] |= (1 << q); q += q_off; if (async) *async = q; if (waits) { if (depth > 0) wait_bits |= q_wait_bits[depth - 1]; for (int i = 0; i < q_max; i++) { waits[i] = wait_bits & (1 << i) ? i + q_off : q; } } }
28.04918
107
0.540327
[ "vector" ]
8d7528a458c65056e2774405b3cc45e968bf7ee8
687
cpp
C++
Problem Solving Paradigms/Greedy/Classical, Usually Easier/The Bus Driver Problem.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
Problem Solving Paradigms/Greedy/Classical, Usually Easier/The Bus Driver Problem.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
Problem Solving Paradigms/Greedy/Classical, Usually Easier/The Bus Driver Problem.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef vector <int> vi; typedef long long ll; int t, n, counter, d, r; ll sum = 0; vi a, b; int main(){ ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("in.txt", "r", stdin); freopen("out.txt", "w", stdout); while(cin >> n >> d >> r, n){ a.resize(n); b.resize(n); for(int i=0; i<n; i++) cin >> a[i]; for(int j=0; j<n; j++) cin >> b[j]; sort(a.begin(), a.end()); sort(b.begin(), b.end(), greater<int>()); counter = 0; for(int i=0; i<n; i++){ counter += max(0, (a[i]+b[i] - d)*r); } cout << counter << endl; } }
23.689655
49
0.475983
[ "vector" ]
8d77c5acc4dde1abf03c2d6831903ed69eff3ced
1,709
cc
C++
mindspore/ccsrc/common/graph_kernel/expanders/softplus.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
1
2022-03-05T02:59:21.000Z
2022-03-05T02:59:21.000Z
mindspore/ccsrc/common/graph_kernel/expanders/softplus.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/common/graph_kernel/expanders/softplus.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <memory> #include <vector> #include "common/graph_kernel/expanders/expander_factory.h" #include "ir/dtype.h" namespace mindspore::graphkernel::expanders { class Softplus : public OpDesc { public: Softplus() {} ~Softplus() = default; protected: bool CheckInputs() override { const auto &input_x = inputs_info_[0]; if (input_x.type != kNumberTypeFloat32 && input_x.type != kNumberTypeFloat16) { MS_LOG(INFO) << "In Softplus, input_x's dtype must be float16 or float32"; return false; } return true; } NodePtrList Expand() override { const auto &inputs = gb.Get()->inputs(); const auto &input_x = inputs[0]; auto exp_x = gb.Emit("Exp", {input_x}); tensor::TensorPtr data = std::make_shared<tensor::Tensor>(static_cast<double>(1.0), TypeIdToType(input_x->type)); auto const_one = gb.Value(data); auto exp_x_add_one = gb.Emit("Add", {exp_x, const_one}); auto result = gb.Emit("Log", {exp_x_add_one}); return {result}; } }; OP_EXPANDER_REGISTER("Softplus", Softplus); } // namespace mindspore::graphkernel::expanders
32.865385
117
0.70275
[ "vector" ]
8d7a31ce9203bca43c7af6f4c0e188a8bf897b28
1,806
cpp
C++
boboleetcode/Play-Leetcode-master/0542-01-Matrix/cpp-0542/main.cpp
yaominzh/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
2
2021-03-25T05:26:55.000Z
2021-04-20T03:33:24.000Z
boboleetcode/Play-Leetcode-master/0542-01-Matrix/cpp-0542/main.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
6
2019-12-04T06:08:32.000Z
2021-05-10T20:22:47.000Z
boboleetcode/Play-Leetcode-master/0542-01-Matrix/cpp-0542/main.cpp
mcuallen/CodeLrn2019
adc727d92904c5c5d445a2621813dfa99474206d
[ "Apache-2.0" ]
null
null
null
/// Source : https://leetcode.com/problems/01-matrix/description/ /// Author : liuyubobobo /// Time : 2018-09-29 #include <iostream> #include <vector> #include <queue> #include <cassert> using namespace std; /// BFS /// Time Complexity: O(m*n) /// Space Complexity: O(m*n) class Solution { private: const int d[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int m, n; public: vector<vector<int>> updateMatrix(vector<vector<int>>& matrix) { if(matrix.size() == 0 || matrix[0].size() == 0) return matrix; m = matrix.size(); n = matrix[0].size(); vector<vector<int>> res(m, vector<int>(n, INT_MAX)); for(int i = 0; i < m; i ++) for(int j = 0; j < n; j ++) if(matrix[i][j] == 0) res[i][j] = 0; for(int i = 0; i < m; i ++) for(int j = 0; j < n; j ++) if(matrix[i][j] == 0) bfs(matrix, i, j, res); return res; } void bfs(const vector<vector<int>>& matrix, int sx, int sy, vector<vector<int>>& res){ queue<pair<int, int>> q; q.push(make_pair(sx * n + sy, 0)); while(!q.empty()){ int x = q.front().first / n; int y = q.front().first % n; int step = q.front().second; q.pop(); for(int k = 0; k < 4; k ++){ int newX = x + d[k][0], newY = y + d[k][1]; if(inArea(newX, newY) && step + 1 < res[newX][newY]){ res[newX][newY] = step + 1; q.push(make_pair(newX * n + newY, step + 1)); } } } } bool inArea(int x, int y){ return x >= 0 && x < m && y >= 0 && y < n; } }; int main() { return 0; }
23.763158
69
0.437984
[ "vector" ]
8d7f269e9cdb6529438d8f3a2e70e77a51339d81
2,943
cpp
C++
cisstICP/cisstICP/algDirPDTree_BoundedAngle.cpp
sbillin/IMLP
38cbf6f528747ab5421f02f50b9bc3cd416cff8c
[ "BSD-3-Clause" ]
14
2015-05-15T08:54:19.000Z
2021-12-14T06:16:37.000Z
cisstICP/algDirPDTree_BoundedAngle.cpp
Xingorno/cisstICP
dfa00db642a25500946a0c70a900fbc68e5af248
[ "BSD-3-Clause" ]
3
2017-01-11T15:10:31.000Z
2020-12-28T16:16:32.000Z
cisstICP/algDirPDTree_BoundedAngle.cpp
Xingorno/cisstICP
dfa00db642a25500946a0c70a900fbc68e5af248
[ "BSD-3-Clause" ]
8
2015-01-07T20:28:12.000Z
2018-07-13T15:40:39.000Z
// **************************************************************************** // // Copyright (c) 2014, Seth Billings, Russell Taylor, Johns Hopkins University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // **************************************************************************** #include "algDirPDTree_BoundedAngle.h" #include "DirPDTreeNode.h" //#include "utilities.h" // PD Tree Methods int algDirPDTree_BoundedAngle::NodeMightBeCloser( const vct3 &Xp, const vct3 &Xn, DirPDTreeNode const *node, double ErrorBound) { // // Match Error: // // cost: ||Xp - Yp||^2 such that angle between Xn & Yn < maxMatchAngle // // --- Compute Lower Bound on Orientation Error --- // double cos_dThetaAvg = Xn.DotProduct(node->Navg); if (cos_dThetaAvg < cos(node->dThetaMax + maxMatchAngle)) { // all orientations in this node exceed the maximum angular match error return 0; } //double dThetaAvg = acos(Xn.DotProduct(node->Navg)); //if (dThetaAvg > node->dThetaMax + maxMatchAngle) //{ // all orientations in this node exceed the maximum angular match error // return 0; //} // --- Positional Node Distance Test --- // // transform point into local coordinate system of node vct3 Xp_node = node->F*Xp; // check if node lies within the closest match distance found so far return node->Bounds.Includes(Xp_node, ErrorBound); }
39.77027
81
0.679918
[ "transform" ]
8d801a1a79c8b21de0da12a6b911dc6a7c635fae
10,953
cpp
C++
Source/WebKit/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMTreeWalker.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
Source/WebKit/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMTreeWalker.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Source/WebKit/WebProcess/InjectedBundle/API/gtk/DOM/WebKitDOMTreeWalker.cpp
ijsf/DeniseEmbeddableWebKit
57dfc6783d60f8f59b7129874e60f84d8c8556c9
[ "BSD-3-Clause" ]
null
null
null
/* * This file is part of the WebKit open source project. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "WebKitDOMTreeWalker.h" #include <WebCore/CSSImportRule.h> #include "DOMObjectCache.h" #include <WebCore/Document.h> #include <WebCore/ExceptionCode.h> #include <WebCore/JSMainThreadExecState.h> #include "WebKitDOMNodeFilterPrivate.h" #include "WebKitDOMNodePrivate.h" #include "WebKitDOMPrivate.h" #include "WebKitDOMTreeWalkerPrivate.h" #include "ConvertToUTF8String.h" #include <wtf/GetPtr.h> #include <wtf/RefPtr.h> #define WEBKIT_DOM_TREE_WALKER_GET_PRIVATE(obj) G_TYPE_INSTANCE_GET_PRIVATE(obj, WEBKIT_DOM_TYPE_TREE_WALKER, WebKitDOMTreeWalkerPrivate) typedef struct _WebKitDOMTreeWalkerPrivate { RefPtr<WebCore::TreeWalker> coreObject; } WebKitDOMTreeWalkerPrivate; namespace WebKit { WebKitDOMTreeWalker* kit(WebCore::TreeWalker* obj) { if (!obj) return 0; if (gpointer ret = DOMObjectCache::get(obj)) return WEBKIT_DOM_TREE_WALKER(ret); return wrapTreeWalker(obj); } WebCore::TreeWalker* core(WebKitDOMTreeWalker* request) { return request ? static_cast<WebCore::TreeWalker*>(WEBKIT_DOM_OBJECT(request)->coreObject) : 0; } WebKitDOMTreeWalker* wrapTreeWalker(WebCore::TreeWalker* coreObject) { ASSERT(coreObject); return WEBKIT_DOM_TREE_WALKER(g_object_new(WEBKIT_DOM_TYPE_TREE_WALKER, "core-object", coreObject, nullptr)); } } // namespace WebKit G_DEFINE_TYPE(WebKitDOMTreeWalker, webkit_dom_tree_walker, WEBKIT_DOM_TYPE_OBJECT) enum { PROP_0, PROP_ROOT, PROP_WHAT_TO_SHOW, PROP_FILTER, PROP_CURRENT_NODE, }; static void webkit_dom_tree_walker_finalize(GObject* object) { WebKitDOMTreeWalkerPrivate* priv = WEBKIT_DOM_TREE_WALKER_GET_PRIVATE(object); WebKit::DOMObjectCache::forget(priv->coreObject.get()); priv->~WebKitDOMTreeWalkerPrivate(); G_OBJECT_CLASS(webkit_dom_tree_walker_parent_class)->finalize(object); } static void webkit_dom_tree_walker_get_property(GObject* object, guint propertyId, GValue* value, GParamSpec* pspec) { WebKitDOMTreeWalker* self = WEBKIT_DOM_TREE_WALKER(object); switch (propertyId) { case PROP_ROOT: g_value_set_object(value, webkit_dom_tree_walker_get_root(self)); break; case PROP_WHAT_TO_SHOW: g_value_set_ulong(value, webkit_dom_tree_walker_get_what_to_show(self)); break; case PROP_FILTER: g_value_set_object(value, webkit_dom_tree_walker_get_filter(self)); break; case PROP_CURRENT_NODE: g_value_set_object(value, webkit_dom_tree_walker_get_current_node(self)); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, propertyId, pspec); break; } } static GObject* webkit_dom_tree_walker_constructor(GType type, guint constructPropertiesCount, GObjectConstructParam* constructProperties) { GObject* object = G_OBJECT_CLASS(webkit_dom_tree_walker_parent_class)->constructor(type, constructPropertiesCount, constructProperties); WebKitDOMTreeWalkerPrivate* priv = WEBKIT_DOM_TREE_WALKER_GET_PRIVATE(object); priv->coreObject = static_cast<WebCore::TreeWalker*>(WEBKIT_DOM_OBJECT(object)->coreObject); WebKit::DOMObjectCache::put(priv->coreObject.get(), object); return object; } static void webkit_dom_tree_walker_class_init(WebKitDOMTreeWalkerClass* requestClass) { GObjectClass* gobjectClass = G_OBJECT_CLASS(requestClass); g_type_class_add_private(gobjectClass, sizeof(WebKitDOMTreeWalkerPrivate)); gobjectClass->constructor = webkit_dom_tree_walker_constructor; gobjectClass->finalize = webkit_dom_tree_walker_finalize; gobjectClass->get_property = webkit_dom_tree_walker_get_property; g_object_class_install_property( gobjectClass, PROP_ROOT, g_param_spec_object( "root", "TreeWalker:root", "read-only WebKitDOMNode* TreeWalker:root", WEBKIT_DOM_TYPE_NODE, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, PROP_WHAT_TO_SHOW, g_param_spec_ulong( "what-to-show", "TreeWalker:what-to-show", "read-only gulong TreeWalker:what-to-show", 0, G_MAXULONG, 0, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, PROP_FILTER, g_param_spec_object( "filter", "TreeWalker:filter", "read-only WebKitDOMNodeFilter* TreeWalker:filter", WEBKIT_DOM_TYPE_NODE_FILTER, WEBKIT_PARAM_READABLE)); g_object_class_install_property( gobjectClass, PROP_CURRENT_NODE, g_param_spec_object( "current-node", "TreeWalker:current-node", "read-only WebKitDOMNode* TreeWalker:current-node", WEBKIT_DOM_TYPE_NODE, WEBKIT_PARAM_READABLE)); } static void webkit_dom_tree_walker_init(WebKitDOMTreeWalker* request) { WebKitDOMTreeWalkerPrivate* priv = WEBKIT_DOM_TREE_WALKER_GET_PRIVATE(request); new (priv) WebKitDOMTreeWalkerPrivate(); } WebKitDOMNode* webkit_dom_tree_walker_parent_node(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); auto result = item->parentNode(); if (result.hasException()) return nullptr; RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(result.releaseReturnValue()); return WebKit::kit(gobjectResult.get()); } WebKitDOMNode* webkit_dom_tree_walker_first_child(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); auto result = item->firstChild(); if (result.hasException()) return nullptr; RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(result.releaseReturnValue()); return WebKit::kit(gobjectResult.get()); } WebKitDOMNode* webkit_dom_tree_walker_last_child(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); auto result = item->lastChild(); if (result.hasException()) return nullptr; RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(result.releaseReturnValue()); return WebKit::kit(gobjectResult.get()); } WebKitDOMNode* webkit_dom_tree_walker_previous_sibling(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); auto result = item->previousSibling(); if (result.hasException()) return nullptr; RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(result.releaseReturnValue()); return WebKit::kit(gobjectResult.get()); } WebKitDOMNode* webkit_dom_tree_walker_next_sibling(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); auto result = item->nextSibling(); if (result.hasException()) return nullptr; RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(result.releaseReturnValue()); return WebKit::kit(gobjectResult.get()); } WebKitDOMNode* webkit_dom_tree_walker_previous_node(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); auto result = item->previousNode(); if (result.hasException()) return nullptr; RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(result.releaseReturnValue()); return WebKit::kit(gobjectResult.get()); } WebKitDOMNode* webkit_dom_tree_walker_next_node(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); auto result = item->nextNode(); if (result.hasException()) return nullptr; RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(result.releaseReturnValue()); return WebKit::kit(gobjectResult.get()); } WebKitDOMNode* webkit_dom_tree_walker_get_root(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(item->root()); return WebKit::kit(gobjectResult.get()); } gulong webkit_dom_tree_walker_get_what_to_show(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); gulong result = item->whatToShow(); return result; } WebKitDOMNodeFilter* webkit_dom_tree_walker_get_filter(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); RefPtr<WebCore::NodeFilter> gobjectResult = WTF::getPtr(item->filter()); return WebKit::kit(gobjectResult.get()); } WebKitDOMNode* webkit_dom_tree_walker_get_current_node(WebKitDOMTreeWalker* self) { WebCore::JSMainThreadNullState state; g_return_val_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self), 0); WebCore::TreeWalker* item = WebKit::core(self); RefPtr<WebCore::Node> gobjectResult = WTF::getPtr(item->currentNode()); return WebKit::kit(gobjectResult.get()); } void webkit_dom_tree_walker_set_current_node(WebKitDOMTreeWalker* self, WebKitDOMNode* value, GError** error) { WebCore::JSMainThreadNullState state; g_return_if_fail(WEBKIT_DOM_IS_TREE_WALKER(self)); g_return_if_fail(WEBKIT_DOM_IS_NODE(value)); UNUSED_PARAM(error); WebCore::TreeWalker* item = WebKit::core(self); WebCore::Node* convertedValue = WebKit::core(value); item->setCurrentNode(*convertedValue); }
33.910217
140
0.740163
[ "object" ]
8d8f559d9fcdf4f5c16401128703352a8b3a6e7a
1,499
hpp
C++
examples/jacobi_smp/jacobi_nonuniform_omp.hpp
bhumitattarde/hpx
5b34d8d77b1664fa552445d44cd98e51dc69a74a
[ "BSL-1.0" ]
1,822
2015-01-03T11:22:37.000Z
2022-03-31T14:49:59.000Z
examples/jacobi_smp/jacobi_nonuniform_omp.hpp
deepaksuresh1411/hpx
aa18024d35fe9884a977d4b6076c764dbb8b26d1
[ "BSL-1.0" ]
3,288
2015-01-05T17:00:23.000Z
2022-03-31T18:49:41.000Z
examples/jacobi_smp/jacobi_nonuniform_omp.hpp
msimberg/hpx
70ef8024c7e5a7f7de018eb88bfe446ba83d48e5
[ "BSL-1.0" ]
431
2015-01-07T06:22:14.000Z
2022-03-31T14:50:04.000Z
// Copyright (c) 2011-2013 Thomas Heller // // 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 <hpx/local/chrono.hpp> #include <cstddef> #include <cstdint> #include <iostream> #include <memory> #include <string> #include <utility> #include <vector> #include "jacobi_nonuniform.hpp" namespace jacobi_smp { void jacobi(crs_matrix<double> const& A, std::vector<double> const& b, std::size_t iterations, std::size_t block_size) { typedef std::vector<double> vector_type; std::shared_ptr<vector_type> dst(new vector_type(b)); std::shared_ptr<vector_type> src(new vector_type(b)); hpx::chrono::high_resolution_timer t; for (std::size_t i = 0; i < iterations; ++i) { // MSVC is unhappy if the OMP loop variable is unsigned #pragma omp parallel for schedule(JACOBI_SMP_OMP_SCHEDULE) for (std::int64_t row = 0; row < std::int64_t(b.size()); ++row) { jacobi_kernel_nonuniform(A, *dst, *src, b, row); } std::swap(dst, src); } double time_elapsed = t.elapsed(); std::cout << dst->size() << " " << ((double(dst->size() * iterations) / 1e6) / time_elapsed) << " MLUPS/s\n" << std::flush; } } // namespace jacobi_smp
30.591837
80
0.60507
[ "vector" ]
8d99660d1a20c87d043d18293eebfc9b680bb43c
17,563
cc
C++
third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder_test.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder_test.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/layout/ng/inline/ng_inline_items_builder_test.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 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 "core/layout/ng/inline/ng_inline_items_builder.h" #include "core/layout/LayoutInline.h" #include "core/layout/ng/inline/ng_inline_node.h" #include "core/layout/ng/inline/ng_offset_mapping_builder.h" #include "core/style/ComputedStyle.h" #include "testing/gtest/include/gtest/gtest.h" namespace blink { namespace { static PassRefPtr<ComputedStyle> CreateWhitespaceStyle(EWhiteSpace whitespace) { RefPtr<ComputedStyle> style(ComputedStyle::Create()); style->SetWhiteSpace(whitespace); return style; } static String GetCollapsed(const NGOffsetMappingBuilder& builder) { Vector<unsigned> mapping = builder.DumpOffsetMappingForTesting(); Vector<unsigned> collapsed_indexes; for (unsigned i = 0; i + 1 < mapping.size(); ++i) { if (mapping[i] == mapping[i + 1]) collapsed_indexes.push_back(i); } StringBuilder result; result.Append('{'); bool first = true; for (unsigned index : collapsed_indexes) { if (!first) result.Append(", "); result.AppendNumber(index); first = false; } result.Append('}'); return result.ToString(); } class NGInlineItemsBuilderTest : public ::testing::Test { protected: void SetUp() override { style_ = ComputedStyle::Create(); } void SetWhiteSpace(EWhiteSpace whitespace) { style_->SetWhiteSpace(whitespace); } const String& TestAppend(const String inputs[], int size) { items_.clear(); NGInlineItemsBuilderForOffsetMapping builder(&items_); for (int i = 0; i < size; i++) builder.Append(inputs[i], style_.Get()); text_ = builder.ToString(); collapsed_ = GetCollapsed(builder.GetOffsetMappingBuilder()); ValidateItems(); return text_; } const String& TestAppend(const String& input) { String inputs[] = {input}; return TestAppend(inputs, 1); } const String& TestAppend(const String& input1, const String& input2) { String inputs[] = {input1, input2}; return TestAppend(inputs, 2); } const String& TestAppend(const String& input1, const String& input2, const String& input3) { String inputs[] = {input1, input2, input3}; return TestAppend(inputs, 3); } void ValidateItems() { unsigned current_offset = 0; for (unsigned i = 0; i < items_.size(); i++) { const NGInlineItem& item = items_[i]; EXPECT_EQ(current_offset, item.StartOffset()); EXPECT_LT(item.StartOffset(), item.EndOffset()); current_offset = item.EndOffset(); } EXPECT_EQ(current_offset, text_.length()); } Vector<NGInlineItem> items_; String text_; String collapsed_; RefPtr<ComputedStyle> style_; }; #define TestWhitespaceValue(expected_text, expected_collapsed, input, \ whitespace) \ SetWhiteSpace(whitespace); \ EXPECT_EQ(expected_text, TestAppend(input)) << "white-space: " #whitespace; \ EXPECT_EQ(expected_collapsed, collapsed_); TEST_F(NGInlineItemsBuilderTest, CollapseSpaces) { String input("text text text text"); String collapsed("text text text text"); String collapsed_indexes("{10, 16, 17}"); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kNormal); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kNowrap); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kWebkitNowrap); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kPreLine); TestWhitespaceValue(input, "{}", input, EWhiteSpace::kPre); TestWhitespaceValue(input, "{}", input, EWhiteSpace::kPreWrap); } TEST_F(NGInlineItemsBuilderTest, CollapseTabs) { String input("text text text text"); String collapsed("text text text text"); String collapsed_indexes("{10, 16, 17}"); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kNormal); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kNowrap); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kWebkitNowrap); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kPreLine); TestWhitespaceValue(input, "{}", input, EWhiteSpace::kPre); TestWhitespaceValue(input, "{}", input, EWhiteSpace::kPreWrap); } TEST_F(NGInlineItemsBuilderTest, CollapseNewLines) { String input("text\ntext \n text\n\ntext"); String collapsed("text text text text"); String collapsed_indexes("{10, 11, 17}"); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kNormal); TestWhitespaceValue(collapsed, collapsed_indexes, input, EWhiteSpace::kNowrap); TestWhitespaceValue("text\ntext\ntext\n\ntext", "{9, 11}", input, EWhiteSpace::kPreLine); TestWhitespaceValue(input, "{}", input, EWhiteSpace::kPre); TestWhitespaceValue(input, "{}", input, EWhiteSpace::kPreWrap); } TEST_F(NGInlineItemsBuilderTest, CollapseNewlinesAsSpaces) { EXPECT_EQ("text text", TestAppend("text\ntext")); EXPECT_EQ("{}", collapsed_); EXPECT_EQ("text text", TestAppend("text\n\ntext")); EXPECT_EQ("{5}", collapsed_); EXPECT_EQ("text text", TestAppend("text \n\n text")); EXPECT_EQ("{5, 6, 7}", collapsed_); EXPECT_EQ("text text", TestAppend("text \n \n text")); EXPECT_EQ("{5, 6, 7, 8}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseAcrossElements) { EXPECT_EQ("text text", TestAppend("text ", " text")) << "Spaces are collapsed even when across elements."; EXPECT_EQ("{5}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseLeadingSpaces) { EXPECT_EQ("text", TestAppend(" text")); EXPECT_EQ("{0, 1}", collapsed_); EXPECT_EQ("text", TestAppend(" ", "text")); EXPECT_EQ("{0}", collapsed_); EXPECT_EQ("text", TestAppend(" ", " text")); EXPECT_EQ("{0, 1}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseTrailingSpaces) { EXPECT_EQ("text", TestAppend("text ")); EXPECT_EQ("{4, 5}", collapsed_); EXPECT_EQ("text", TestAppend("text", " ")); EXPECT_EQ("{4}", collapsed_); EXPECT_EQ("text", TestAppend("text ", " ")); EXPECT_EQ("{4, 5}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseAllSpaces) { EXPECT_EQ("", TestAppend(" ")); EXPECT_EQ("{0, 1}", collapsed_); EXPECT_EQ("", TestAppend(" ", " ")); EXPECT_EQ("{0, 1, 2, 3}", collapsed_); EXPECT_EQ("", TestAppend(" ", "\n")); EXPECT_EQ("{0, 1, 2}", collapsed_); EXPECT_EQ("", TestAppend("\n", " ")); EXPECT_EQ("{0, 1, 2}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseLeadingNewlines) { EXPECT_EQ("text", TestAppend("\ntext")); EXPECT_EQ("{0}", collapsed_); EXPECT_EQ("text", TestAppend("\n\ntext")); EXPECT_EQ("{0, 1}", collapsed_); EXPECT_EQ("text", TestAppend("\n", "text")); EXPECT_EQ("{0}", collapsed_); EXPECT_EQ("text", TestAppend("\n\n", "text")); EXPECT_EQ("{0, 1}", collapsed_); EXPECT_EQ("text", TestAppend(" \n", "text")); EXPECT_EQ("{0, 1}", collapsed_); EXPECT_EQ("text", TestAppend("\n", " text")); EXPECT_EQ("{0, 1}", collapsed_); EXPECT_EQ("text", TestAppend("\n\n", " text")); EXPECT_EQ("{0, 1, 2}", collapsed_); EXPECT_EQ("text", TestAppend(" \n", " text")); EXPECT_EQ("{0, 1, 2}", collapsed_); EXPECT_EQ("text", TestAppend("\n", "\ntext")); EXPECT_EQ("{0, 1}", collapsed_); EXPECT_EQ("text", TestAppend("\n\n", "\ntext")); EXPECT_EQ("{0, 1, 2}", collapsed_); EXPECT_EQ("text", TestAppend(" \n", "\ntext")); EXPECT_EQ("{0, 1, 2}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseTrailingNewlines) { EXPECT_EQ("text", TestAppend("text\n")); EXPECT_EQ("{4}", collapsed_); EXPECT_EQ("text", TestAppend("text", "\n")); EXPECT_EQ("{4}", collapsed_); EXPECT_EQ("text", TestAppend("text\n", "\n")); EXPECT_EQ("{4, 5}", collapsed_); EXPECT_EQ("text", TestAppend("text\n", " ")); EXPECT_EQ("{4, 5}", collapsed_); EXPECT_EQ("text", TestAppend("text ", "\n")); EXPECT_EQ("{4, 5}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseBeforeNewlineAcrossElements) { EXPECT_EQ("text text", TestAppend("text ", "\ntext")); EXPECT_EQ("{5}", collapsed_); EXPECT_EQ("text text", TestAppend("text", " ", "\ntext")); EXPECT_EQ("{5}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseBeforeAndAfterNewline) { SetWhiteSpace(EWhiteSpace::kPreLine); EXPECT_EQ("text\ntext", TestAppend("text \n text")) << "Spaces before and after newline are removed."; EXPECT_EQ("{4, 5, 7, 8}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapsibleSpaceAfterNonCollapsibleSpaceAcrossElements) { NGInlineItemsBuilderForOffsetMapping builder(&items_); RefPtr<ComputedStyle> pre_wrap(CreateWhitespaceStyle(EWhiteSpace::kPreWrap)); builder.Append("text ", pre_wrap.Get()); builder.Append(" text", style_.Get()); EXPECT_EQ("text text", builder.ToString()) << "The whitespace in constructions like '<span style=\"white-space: " "pre-wrap\">text <span><span> text</span>' does not collapse."; EXPECT_EQ("{}", GetCollapsed(builder.GetOffsetMappingBuilder())); } TEST_F(NGInlineItemsBuilderTest, CollapseZeroWidthSpaces) { EXPECT_EQ(String(u"text\u200Btext"), TestAppend(u"text\u200B\ntext")) << "Newline is removed if the character before is ZWS."; EXPECT_EQ("{5}", collapsed_); EXPECT_EQ(String(u"text\u200Btext"), TestAppend(u"text\n\u200Btext")) << "Newline is removed if the character after is ZWS."; EXPECT_EQ("{4}", collapsed_); EXPECT_EQ(String(u"text\u200B\u200Btext"), TestAppend(u"text\u200B\n\u200Btext")) << "Newline is removed if the character before/after is ZWS."; EXPECT_EQ("{5}", collapsed_); EXPECT_EQ(String(u"text\u200Btext"), TestAppend(u"text\n", u"\u200Btext")) << "Newline is removed if the character after across elements is ZWS."; EXPECT_EQ("{4}", collapsed_); EXPECT_EQ(String(u"text\u200Btext"), TestAppend(u"text\u200B", u"\ntext")) << "Newline is removed if the character before is ZWS even across " "elements."; EXPECT_EQ("{5}", collapsed_); EXPECT_EQ(String(u"text\u200Btext"), TestAppend(u"text \n", u"\u200Btext")) << "Collapsible space before newline does not affect the result."; EXPECT_EQ("{4, 5}", collapsed_); EXPECT_EQ(String(u"text\u200Btext"), TestAppend(u"text\u200B\n", u" text")) << "Collapsible space after newline is removed even when the " "newline was removed."; EXPECT_EQ("{5, 6}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, CollapseEastAsianWidth) { EXPECT_EQ(String(u"\u4E00\u4E00"), TestAppend(u"\u4E00\n\u4E00")) << "Newline is removed when both sides are Wide."; EXPECT_EQ("{1}", collapsed_); EXPECT_EQ(String(u"\u4E00 A"), TestAppend(u"\u4E00\nA")) << "Newline is not removed when after is Narrow."; EXPECT_EQ("{}", collapsed_); EXPECT_EQ(String(u"A \u4E00"), TestAppend(u"A\n\u4E00")) << "Newline is not removed when before is Narrow."; EXPECT_EQ("{}", collapsed_); EXPECT_EQ(String(u"\u4E00\u4E00"), TestAppend(u"\u4E00\n", u"\u4E00")) << "Newline at the end of elements is removed when both sides are Wide."; EXPECT_EQ("{1}", collapsed_); EXPECT_EQ(String(u"\u4E00\u4E00"), TestAppend(u"\u4E00", u"\n\u4E00")) << "Newline at the beginning of elements is removed " "when both sides are Wide."; EXPECT_EQ("{1}", collapsed_); } TEST_F(NGInlineItemsBuilderTest, OpaqueToSpaceCollapsing) { NGInlineItemsBuilderForOffsetMapping builder(&items_); builder.Append("Hello ", style_.Get()); builder.AppendOpaque(NGInlineItem::kBidiControl, kFirstStrongIsolateCharacter); builder.Append(" ", style_.Get()); builder.AppendOpaque(NGInlineItem::kBidiControl, kFirstStrongIsolateCharacter); builder.Append(" World", style_.Get()); EXPECT_EQ(String(u"Hello \u2068\u2068World"), builder.ToString()); EXPECT_EQ("{7, 9}", GetCollapsed(builder.GetOffsetMappingBuilder())); } TEST_F(NGInlineItemsBuilderTest, CollapseAroundReplacedElement) { NGInlineItemsBuilderForOffsetMapping builder(&items_); builder.Append("Hello ", style_.Get()); builder.Append(NGInlineItem::kAtomicInline, kObjectReplacementCharacter); builder.Append(" World", style_.Get()); EXPECT_EQ(String(u"Hello \uFFFC World"), builder.ToString()); EXPECT_EQ("{}", GetCollapsed(builder.GetOffsetMappingBuilder())); } TEST_F(NGInlineItemsBuilderTest, CollapseNewlineAfterObject) { NGInlineItemsBuilderForOffsetMapping builder(&items_); builder.Append(NGInlineItem::kAtomicInline, kObjectReplacementCharacter); builder.Append("\n", style_.Get()); builder.Append(NGInlineItem::kAtomicInline, kObjectReplacementCharacter); EXPECT_EQ(String(u"\uFFFC \uFFFC"), builder.ToString()); EXPECT_EQ(3u, items_.size()); EXPECT_EQ(nullptr, items_[0].Style()); EXPECT_EQ(style_.Get(), items_[1].Style()); EXPECT_EQ(nullptr, items_[2].Style()); EXPECT_EQ("{}", GetCollapsed(builder.GetOffsetMappingBuilder())); } TEST_F(NGInlineItemsBuilderTest, AppendEmptyString) { EXPECT_EQ("", TestAppend("")); EXPECT_EQ("{}", collapsed_); EXPECT_EQ(0u, items_.size()); } TEST_F(NGInlineItemsBuilderTest, NewLines) { SetWhiteSpace(EWhiteSpace::kPre); EXPECT_EQ("apple\norange\ngrape\n", TestAppend("apple\norange\ngrape\n")); EXPECT_EQ("{}", collapsed_); EXPECT_EQ(6u, items_.size()); EXPECT_EQ(NGInlineItem::kText, items_[0].Type()); EXPECT_EQ(NGInlineItem::kControl, items_[1].Type()); EXPECT_EQ(NGInlineItem::kText, items_[2].Type()); EXPECT_EQ(NGInlineItem::kControl, items_[3].Type()); EXPECT_EQ(NGInlineItem::kText, items_[4].Type()); EXPECT_EQ(NGInlineItem::kControl, items_[5].Type()); } TEST_F(NGInlineItemsBuilderTest, Empty) { Vector<NGInlineItem> items; NGInlineItemsBuilderForOffsetMapping builder(&items); RefPtr<ComputedStyle> block_style(ComputedStyle::Create()); builder.EnterBlock(block_style.Get()); builder.ExitBlock(); EXPECT_EQ("", builder.ToString()); EXPECT_EQ("{}", GetCollapsed(builder.GetOffsetMappingBuilder())); } TEST_F(NGInlineItemsBuilderTest, BidiBlockOverride) { Vector<NGInlineItem> items; NGInlineItemsBuilderForOffsetMapping builder(&items); RefPtr<ComputedStyle> block_style(ComputedStyle::Create()); block_style->SetUnicodeBidi(UnicodeBidi::kBidiOverride); block_style->SetDirection(TextDirection::kRtl); builder.EnterBlock(block_style.Get()); builder.Append("Hello", style_.Get()); builder.ExitBlock(); // Expected control characters as defined in: // https://drafts.csswg.org/css-writing-modes-3/#bidi-control-codes-injection-table EXPECT_EQ(String(u"\u202E" u"Hello" u"\u202C"), builder.ToString()); EXPECT_EQ("{}", GetCollapsed(builder.GetOffsetMappingBuilder())); } static std::unique_ptr<LayoutInline> CreateLayoutInline( void (*initialize_style)(ComputedStyle*)) { RefPtr<ComputedStyle> style(ComputedStyle::Create()); initialize_style(style.Get()); std::unique_ptr<LayoutInline> node = WTF::MakeUnique<LayoutInline>(nullptr); node->SetStyleInternal(std::move(style)); return node; } TEST_F(NGInlineItemsBuilderTest, BidiIsolate) { Vector<NGInlineItem> items; NGInlineItemsBuilderForOffsetMapping builder(&items); builder.Append("Hello ", style_.Get()); std::unique_ptr<LayoutInline> isolate_rtl( CreateLayoutInline([](ComputedStyle* style) { style->SetUnicodeBidi(UnicodeBidi::kIsolate); style->SetDirection(TextDirection::kRtl); })); builder.EnterInline(isolate_rtl.get()); builder.Append(u"\u05E2\u05D1\u05E8\u05D9\u05EA", style_.Get()); builder.ExitInline(isolate_rtl.get()); builder.Append(" World", style_.Get()); // Expected control characters as defined in: // https://drafts.csswg.org/css-writing-modes-3/#bidi-control-codes-injection-table EXPECT_EQ(String(u"Hello " u"\u2067" u"\u05E2\u05D1\u05E8\u05D9\u05EA" u"\u2069" u" World"), builder.ToString()); EXPECT_EQ("{}", GetCollapsed(builder.GetOffsetMappingBuilder())); } TEST_F(NGInlineItemsBuilderTest, BidiIsolateOverride) { Vector<NGInlineItem> items; NGInlineItemsBuilderForOffsetMapping builder(&items); builder.Append("Hello ", style_.Get()); std::unique_ptr<LayoutInline> isolate_override_rtl( CreateLayoutInline([](ComputedStyle* style) { style->SetUnicodeBidi(UnicodeBidi::kIsolateOverride); style->SetDirection(TextDirection::kRtl); })); builder.EnterInline(isolate_override_rtl.get()); builder.Append(u"\u05E2\u05D1\u05E8\u05D9\u05EA", style_.Get()); builder.ExitInline(isolate_override_rtl.get()); builder.Append(" World", style_.Get()); // Expected control characters as defined in: // https://drafts.csswg.org/css-writing-modes-3/#bidi-control-codes-injection-table EXPECT_EQ(String(u"Hello " u"\u2068\u202E" u"\u05E2\u05D1\u05E8\u05D9\u05EA" u"\u202C\u2069" u" World"), builder.ToString()); EXPECT_EQ("{}", GetCollapsed(builder.GetOffsetMappingBuilder())); } } // namespace } // namespace blink
38.431072
85
0.681546
[ "vector" ]
8d9f4921d621c2baa905a0a96eecf9971a6caa8e
3,107
hpp
C++
source/LibFgBase/src/FgGuiApiSplit.hpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
41
2016-04-09T07:48:10.000Z
2022-03-01T15:46:08.000Z
source/LibFgBase/src/FgGuiApiSplit.hpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
9
2015-09-23T10:54:50.000Z
2020-01-04T21:16:57.000Z
source/LibFgBase/src/FgGuiApiSplit.hpp
SingularInversions/FaceGenBaseLibrary
e928b482fa78597cfcf3923f7252f7902ec0dfa9
[ "MIT" ]
29
2015-10-01T14:44:42.000Z
2022-01-05T01:28:43.000Z
// // Coypright (c) 2021 Singular Inversions Inc. (facegen.com) // Use, modification and distribution is subject to the MIT License, // see accompanying file LICENSE.txt or facegen.com/base_library_license.txt // #ifndef FGGUIAPISPLIT_HPP #define FGGUIAPISPLIT_HPP #include "FgGuiApiBase.hpp" #include "FgImageBase.hpp" namespace Fg { // This function must be defined in the corresponding OS-specific implementation: struct GuiSplit; GuiImplPtr guiGetOsImpl(GuiSplit const & guiApi); // Algorithmically proportioned split window with all contents viewable: struct GuiSplit : GuiBase { Img<GuiPtr> panes; virtual GuiImplPtr getInstance() {return guiGetOsImpl(*this); } }; // Checks for case of 1x1 image and just returns the single GuiPtr in that case: GuiPtr guiSplit(Img<GuiPtr> const & panes); // Horizontal array of panes: inline GuiPtr guiSplitH(GuiPtrs const & panes) {return guiSplit(Img<GuiPtr>{panes.size(),1,panes}); } // Vertical array of panes: inline GuiPtr guiSplitV(GuiPtrs const & panes) {return guiSplit(Img<GuiPtr>{1,panes.size(),panes}); } // This function must be defined in the corresponding OS-specific implementation: struct GuiSplitAdj; GuiImplPtr guiGetOsImpl(GuiSplitAdj const & guiApi); // Adjustable split dual window with central divider: struct GuiSplitAdj : GuiBase { bool horiz; GuiPtr pane0; GuiPtr pane1; GuiSplitAdj(bool h,GuiPtr p0,GuiPtr p1) : horiz(h), pane0(p0), pane1(p1) {} virtual GuiImplPtr getInstance() {return guiGetOsImpl(*this); } }; inline GuiPtr guiSplitAdj(bool horiz,GuiPtr p0,GuiPtr p1) {return std::make_shared<GuiSplitAdj>(horiz,p0,p1); } // This function must be defined in the corresponding OS-specific implementation: struct GuiSplitScroll; GuiImplPtr guiGetOsImpl(GuiSplitScroll const & guiApi); // Vertically scrollable split window (panes thickness is fixed to minimum): struct GuiSplitScroll : GuiBase { DfgFPtr updateFlag; // Has the panes info been updated ? // This function must not depend on the same guigraph node depended on by its children or // the windows will be destroyed and recreated with each child update and thus not work: Sfun<GuiPtrs(void)> getPanes; Vec2UI minSize; // Of client area (not including scroll bar) uint spacing; // Insert this spacing above each sub-win GuiSplitScroll() : minSize(300,300), spacing(0) {} virtual GuiImplPtr getInstance() {return guiGetOsImpl(*this); } }; GuiPtr guiSplitScroll(GuiPtrs const & panes,uint spacing=0); GuiPtr guiSplitScroll(Sfun<GuiPtrs(void)> const & getPanes); GuiPtr guiSplitScroll( DfgFPtr const & updateNodeIdx, // Must be unique to this object Sfun<GuiPtrs(void)> const & getPanes, uint spacing=0); } #endif
35.712644
118
0.6598
[ "object" ]
8da5a9cfcd271020acb47a1ae050eadeaa566b4b
1,490
cpp
C++
backup/2/leetcode/c++/find-positive-integer-solution-for-a-given-equation.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
21
2019-11-16T19:08:35.000Z
2021-11-12T12:26:01.000Z
backup/2/leetcode/c++/find-positive-integer-solution-for-a-given-equation.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
1
2022-02-04T16:02:53.000Z
2022-02-04T16:02:53.000Z
backup/2/leetcode/c++/find-positive-integer-solution-for-a-given-equation.cpp
yangyanzhan/code-camp
4272564e916fc230a4a488f92ae32c07d355dee0
[ "Apache-2.0" ]
4
2020-05-15T19:39:41.000Z
2021-10-30T06:40:31.000Z
// Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel (Yanzhan Yang's Youtube Channel) : https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber or my Twitter Account (Yanzhan Yang's Twitter) : https://twitter.com/YangYanzhan or my GitHub HomePage (Yanzhan Yang's GitHub HomePage) : https://yanzhan.site . // For this specific algothmic problem, visit my Youtube Video : . // It's fascinating to solve algothmic problems, follow Yanzhan to learn more! // Blog URL for this problem: https://yanzhan.site/leetcode/find-positive-integer-solution-for-a-given-equation.html . /* * // This is the custom function interface. * // You should not implement it, or speculate about its implementation * class CustomFunction { * public: * // Returns f(x, y) for any given positive integers x and y. * // Note that f(x, y) is increasing with respect to both x and y. * // i.e. f(x, y) < f(x + 1, y), f(x, y) < f(x, y + 1) * int f(int x, int y); * }; */ class Solution { public: vector<vector<int>> findSolution(CustomFunction &customfunction, int z) { vector<vector<int>> res; for (int i = 1; i <= 1000; i++) { for (int j = 1; j <= 1000; j++) { int v = customfunction.f(i, j); if (v == z) { res.push_back({i, j}); } else if (v > z) { break; } } } return res; } };
42.571429
345
0.595973
[ "vector" ]
8daec7a6615bb63772be89d4d59af198626bd549
2,121
hpp
C++
lite/backends/fpga/KD/pes/relu_pe.hpp
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
1,799
2019-08-19T03:29:38.000Z
2022-03-31T14:30:50.000Z
lite/backends/fpga/KD/pes/relu_pe.hpp
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
3,767
2019-08-19T03:36:04.000Z
2022-03-31T14:37:26.000Z
lite/backends/fpga/KD/pes/relu_pe.hpp
wanglei91/Paddle-Lite
8b2479f4cdd6970be507203d791bede5a453c09d
[ "Apache-2.0" ]
798
2019-08-19T02:28:23.000Z
2022-03-31T08:31:54.000Z
/* Copyright (c) 2019 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. */ #pragma once #include "lite/backends/fpga/KD/pe.hpp" #include "lite/backends/fpga/KD/pe_params.hpp" namespace paddle { namespace zynqmp { class ReluPE : public PE { public: bool init() { Tensor* output = param_.output; output->setAligned(param_.input->aligned()); output->setDataLocation(Device); return true; } void apply() { Shape& input_shape = param_.input->shape(); bypass_args_.input_data_type = DATA_TYPE_FP16; bypass_args_.output_data_type = DATA_TYPE_FP16; bypass_args_.input_layout_type = LAYOUT_HWC; bypass_args_.output_layout_type = LAYOUT_HWC; bypass_args_.image.address = param_.input->data<void>(); bypass_args_.image.scale_address = param_.input->max(); bypass_args_.image.channels = input_shape.channel(); bypass_args_.image.height = input_shape.height(); bypass_args_.image.width = input_shape.width(); bypass_args_.output.address = param_.output->data<void>(); bypass_args_.output.scale_address = param_.output->max(); bypass_args_.inplace.active_param.type = TYPE_RELU; bypass_args_.inplace.active_param.leaky_relu_factor = float_to_half(param_.activeParam.leaky_relu_factor); } bool dispatch() { // fpga compute through bypass param_.input->syncToDevice(); perform_bypass(bypass_args_); return true; } InputParam& param() { return param_; } private: InputParam param_; BypassArgs bypass_args_; float16 zero = float_to_half(0.0f); }; } // namespace zynqmp } // namespace paddle
31.191176
72
0.738331
[ "shape" ]
8dbad43ae124d55a5e4812681f164b7942784e9e
9,600
cpp
C++
harfang/foundation/string.cpp
harfang3dadmin/harfang3d
b4920c18fd53cdab6b3a08f262bd4844364829b4
[ "BSD-2-Clause" ]
43
2021-10-16T06:33:48.000Z
2022-03-25T07:55:46.000Z
harfang/foundation/string.cpp
harfang3dadmin/harfang3d
b4920c18fd53cdab6b3a08f262bd4844364829b4
[ "BSD-2-Clause" ]
1
2022-01-25T09:21:47.000Z
2022-01-25T20:50:01.000Z
harfang/foundation/string.cpp
harfang3dadmin/harfang3d
b4920c18fd53cdab6b3a08f262bd4844364829b4
[ "BSD-2-Clause" ]
8
2021-10-14T08:49:20.000Z
2022-03-04T21:54:33.000Z
// HARFANG(R) Copyright (C) 2021 Emmanuel Julien, NWNC HARFANG. Released under GPL/LGPL/Commercial Licence, see licence.txt for details. #include "foundation/string.h" #include "foundation/assert.h" #include "foundation/utf8-cpp/utf8.h" #include "foundation/utf8.h" #include <algorithm> #include <cctype> #include <locale> #include <sstream> #include <codecvt> namespace hg { /* * Copyright (c) 1999 by David I. Bell * Permission is granted to use, distribute, or modify this source, * provided that this copyright notice remains intact. * */ /* * Routine to see if a text string is matched by a wildcard pattern. * Returns TRUE if the text is matched, or FALSE if it is not matched * or if the pattern is invalid. * * matches zero or more characters * ? matches a single character * [abc] matches 'a', 'b' or 'c' * \c quotes character c * Adapted from code written by Ingo Wilken. */ bool match_wildcard(const char *text, const char *pattern) { if (text == nullptr) return false; const char *retryPat = nullptr; const char *retryText = text; bool found; while (*text || *pattern) { int ch = *pattern++; switch (ch) { case '*': retryPat = pattern; retryText = text; break; case '[': found = false; while ((ch = *pattern++) != ']') { if (ch == '\\') ch = *pattern++; if (ch == '\0') return false; if (*text == ch) found = true; } if (!found) { pattern = retryPat; text = ++retryText; } // fall into next case case '?': if (*text++ == '\0') return false; break; case '\\': ch = *pattern++; if (ch == '\0') return false; // fall into next case default: if (*text == ch) { if (*text) text++; break; } if (*text) { pattern = retryPat; text = ++retryText; break; } return false; } if (!pattern) return false; } return true; } std::string slice(const std::string &str, ptrdiff_t from, ptrdiff_t count) { auto l = str.length(); if (from < 0) from += l; // start from right of std::string if (from < 0) from = 0; // clamp to start if (count == 0) count = l - from; // all characters left else if (count < 0) count += l - from; // all characters left - count if (count > (ptrdiff_t(l) - from)) count = l - from; // clamp to length return count > 0 ? str.substr(from, count) : ""; } std::string left(const std::string &str, size_t count) { return slice(str, 0, count); } std::string right(const std::string &str, size_t count) { return slice(str, -(ptrdiff_t)count, 0); } size_t replace_all(std::string &value, const std::string &what, const std::string &by) { auto what_len = what.length(), by_len = by.length(); int count = 0; for (std::string::size_type i = 0; (i = value.find(what, i)) != std::string::npos;) { value.replace(i, what_len, by); i += by_len; ++count; } return count; } bool contains(const std::string &in, const std::string &what) { return in.find(what) != std::string::npos; } std::vector<std::string> split(const std::string &value, const std::string &separator, const std::string &trim) { std::vector<std::string> elements; // keep here to help NVRO elements.reserve(8); auto value_length = value.length(); auto separator_length = separator.length(); auto trim_length = trim.length(); for (std::string::size_type s = 0, i = 0; i != std::string::npos;) { i = value.find(separator, i); if (i == std::string::npos) { auto v = value.substr(s); if (!v.empty()) elements.push_back(std::move(v)); break; } else { std::string element(value.substr(s, i - s)); if (trim_length) replace_all(element, trim, ""); elements.push_back(std::move(element)); } i += separator_length; s = i; if (i >= value_length) i = std::string::npos; } return elements; } std::string trim(const std::string &str, const std::string &pattern) { const auto str_begin = str.find_first_not_of(pattern); if (str_begin == std::string::npos) return ""; // no content const auto str_end = str.find_last_not_of(pattern); const auto str_range = str_end - str_begin + 1; return str.substr(str_begin, str_range); } std::string reduce(const std::string &str, const std::string &fill, const std::string &pattern) { // trim first auto result = trim(str, pattern); // replace sub ranges auto begin_space = result.find_first_of(pattern); while (begin_space != std::string::npos) { const auto endSpace = result.find_first_not_of(pattern, begin_space); const auto range = endSpace - begin_space; result.replace(begin_space, range, fill); const auto newStart = begin_space + fill.length(); begin_space = result.find_first_of(pattern, newStart); } return result; } // std::string lstrip(const std::string &str, const std::string &pattern) { const auto str_begin = str.find_first_not_of(pattern); if (str_begin == std::string::npos) return str; return str.substr(str_begin, str.length() - str_begin); } std::string rstrip(const std::string &str, const std::string &pattern) { const auto str_end = str.find_last_not_of(pattern); if (str_end == std::string::npos) return str; return str.substr(0, str_end + 1); } std::string strip(const std::string &str, const std::string &pattern) { return lstrip(rstrip(str, pattern), pattern); } // std::string lstrip_space(const std::string &str) { size_t i = 0; for (; i < str.size(); ++i) if (!std::isspace(str[i])) break; return slice(str, i); } std::string rstrip_space(const std::string &str) { auto i = str.size(); for (; i > 0; --i) if (!std::isspace(str[i - 1])) break; return slice(str, 0, i); } std::string strip_space(const std::string &str) { return lstrip_space(rstrip_space(str)); } // std::string strip_prefix(const std::string &str, const std::string &prefix) { return starts_with(str, prefix) ? slice(str, prefix.length()) : str; } std::string strip_suffix(const std::string &str, const std::string &suffix) { return ends_with(str, suffix) ? slice(str, 0, -int(suffix.length())) : str; } // std::string utf32_to_utf8(const std::u32string &str) { std::vector<unsigned char> utf8string; utf8::utf32to8(str.begin(), str.end(), std::back_inserter(utf8string)); return std::string((char *)utf8string.data(), utf8string.size()); } std::u32string utf8_to_utf32(const std::string &str) { std::vector<char32_t> utf32string; utf8::utf8to32(str.begin(), str.end(), std::back_inserter(utf32string)); return std::u32string(utf32string.data(), utf32string.size()); } std::string wchar_to_utf8(const std::wstring &str) { std::wstring_convert<std::codecvt_utf8<wchar_t>> wcv; return wcv.to_bytes(str); } std::wstring utf8_to_wchar(const std::string &str) { std::wstring_convert<std::codecvt_utf8<wchar_t>> wcv; return wcv.from_bytes(str); } std::wstring ansi_to_wchar(const std::string &str) { std::wstring ret; std::mbstate_t state = {}; const char *src = str.data(); size_t len = std::mbsrtowcs(nullptr, &src, 0, &state); if (static_cast<size_t>(-1) != len) { std::unique_ptr<wchar_t[]> buff(new wchar_t[len + 1]); len = std::mbsrtowcs(buff.get(), &src, len, &state); if (static_cast<size_t>(-1) != len) { ret.assign(buff.get(), len); } } return ret; } std::string ansi_to_utf8(const std::string &string) { return wchar_to_utf8(ansi_to_wchar(string)); } // void tolower_inplace(std::string &str, size_t start, size_t end) { transform(std::begin(str) + start, end ? std::begin(str) + end : std::end(str), std::begin(str) + start, [](char c) -> char { return c >= 65 && c <= 90 ? c + (97 - 65) : c; }); } std::string tolower(std::string str, size_t start, size_t end) { tolower_inplace(str, start, end); return str; } void toupper_inplace(std::string &str, size_t start, size_t end) { transform(std::begin(str) + start, end ? std::begin(str) + end : std::end(str), std::begin(str) + start, [](char c) -> char { return c >= 97 && c <= 122 ? c - (97 - 65) : c; }); } std::string toupper(std::string str, size_t start, size_t end) { toupper_inplace(str, start, end); return str; } void normalize_eol(std::string &inplace_normalize, EOLConvention eol_convention) { if (eol_convention == EOLUnix) replace_all(inplace_normalize, "\r\n", "\n"); else replace_all(inplace_normalize, "\n", "\r\n"); } std::string word_wrap(const std::string &str, int width, int lead, char lead_char) { if (width < 1) width = 1; std::string o; o.reserve(str.length() + (str.length() / width) * (lead + 1)); const std::string lead_str(lead, lead_char); int n = width; for (auto &c : str) { if (c == '\n') { o += c; o += lead_str; n = width; } else { const bool is_split_possible = (c == ' ') || (c == ';'); if (is_split_possible && n <= 0) { if (c != ' ') o += c; o += '\n'; o += lead_str; n = width; } else { o += c; --n; } } } return o; } std::string name_to_path(std::string name) { name = tolower(name); static const std::vector<std::string> blacklist = {" ", "\\", "/", "!", "@"}; for (const auto &s : blacklist) replace_all(name, s, "-"); return name; } std::string pad_left(const std::string &str, int padded_width, char padding_char) { int count = padded_width - int(str.size()); if (count <= 0) return str; return std::string(count, padding_char) + str; } std::string pad_right(const std::string &str, int padded_width, char padding_char) { int count = padded_width - int(str.size()); if (count <= 0) return str; return str + std::string(count, padding_char); } } // namespace hg
25.806452
155
0.642083
[ "vector", "transform" ]
8dbb5c52e47cf77ffc3a5f382defe6707e83b5c8
15,808
cpp
C++
openstudiocore/src/model/ZoneHVACBaseboardRadiantConvectiveWater.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
openstudiocore/src/model/ZoneHVACBaseboardRadiantConvectiveWater.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
openstudiocore/src/model/ZoneHVACBaseboardRadiantConvectiveWater.cpp
Acidburn0zzz/OpenStudio
8d7aa85fe5df7987cb6983984d4ce8698f1bd0bd
[ "MIT" ]
null
null
null
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * (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 any contributors may be used to endorse or promote products * derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works * may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior * written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE 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 "ZoneHVACBaseboardRadiantConvectiveWater.hpp" #include "ZoneHVACBaseboardRadiantConvectiveWater_Impl.hpp" #include "Schedule.hpp" #include "Schedule_Impl.hpp" #include "Surface.hpp" #include "Surface_Impl.hpp" #include "ThermalZone.hpp" #include "ThermalZone_Impl.hpp" #include "HVACComponent.hpp" #include "HVACComponent_Impl.hpp" #include "CoilHeatingWaterBaseboardRadiant.hpp" #include "CoilHeatingWaterBaseboardRadiant_Impl.hpp" #include "Model.hpp" #include "Space.hpp" #include "ScheduleTypeLimits.hpp" #include "ScheduleTypeRegistry.hpp" #include <utilities/idd/IddFactory.hxx> #include <utilities/idd/OS_ZoneHVAC_Baseboard_RadiantConvective_Water_FieldEnums.hxx> #include "../utilities/core/Assert.hpp" namespace openstudio { namespace model { namespace detail { ZoneHVACBaseboardRadiantConvectiveWater_Impl::ZoneHVACBaseboardRadiantConvectiveWater_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle) : ZoneHVACComponent_Impl(idfObject,model,keepHandle) { OS_ASSERT(idfObject.iddObject().type() == ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType()); } ZoneHVACBaseboardRadiantConvectiveWater_Impl::ZoneHVACBaseboardRadiantConvectiveWater_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle) : ZoneHVACComponent_Impl(other,model,keepHandle) { OS_ASSERT(other.iddObject().type() == ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType()); } ZoneHVACBaseboardRadiantConvectiveWater_Impl::ZoneHVACBaseboardRadiantConvectiveWater_Impl(const ZoneHVACBaseboardRadiantConvectiveWater_Impl& other, Model_Impl* model, bool keepHandle) : ZoneHVACComponent_Impl(other,model,keepHandle) {} const std::vector<std::string>& ZoneHVACBaseboardRadiantConvectiveWater_Impl::outputVariableNames() const { static std::vector<std::string> result{ "Baseboard Total Heating Rate", "Baseboard Convective Heating Rate", "Baseboard Radiant Heating Rate", "Baseboard Total Heating Energy", "Baseboard Total Heating Energy", "Baseboard Convective Heating Energy", "Baseboard Radiant Heating Energy" }; return result; } IddObjectType ZoneHVACBaseboardRadiantConvectiveWater_Impl::iddObjectType() const { return ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType(); } std::vector<ScheduleTypeKey> ZoneHVACBaseboardRadiantConvectiveWater_Impl::getScheduleTypeKeys(const Schedule& schedule) const { std::vector<ScheduleTypeKey> result; UnsignedVector fieldIndices = getSourceIndices(schedule.handle()); UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end()); if (std::find(b,e,OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::AvailabilityScheduleName) != e) { result.push_back(ScheduleTypeKey("ZoneHVACBaseboardRadiantConvectiveWater","Availability")); } return result; } unsigned ZoneHVACBaseboardRadiantConvectiveWater_Impl::inletPort() const { return 0; // this object has no inlet or outlet node } unsigned ZoneHVACBaseboardRadiantConvectiveWater_Impl::outletPort() const { return 0; // this object has no inlet or outlet node } boost::optional<ThermalZone> ZoneHVACBaseboardRadiantConvectiveWater_Impl::thermalZone() const { ModelObject thisObject = this->getObject<ModelObject>(); auto const thermalZones = this->model().getConcreteModelObjects<ThermalZone>(); for( auto const & thermalZone : thermalZones ) { std::vector<ModelObject> equipment = thermalZone.equipment(); if( std::find(equipment.begin(),equipment.end(),thisObject) != equipment.end() ) { return thermalZone; } } return boost::none; } bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::addToThermalZone(ThermalZone & thermalZone) { Model m = this->model(); if( thermalZone.model() != m || thermalZone.isPlenum() ) { return false; } removeFromThermalZone(); thermalZone.setUseIdealAirLoads(false); thermalZone.addEquipment(this->getObject<ZoneHVACComponent>()); return true; } void ZoneHVACBaseboardRadiantConvectiveWater_Impl::removeFromThermalZone() { if ( auto thermalZone = this->thermalZone() ) { thermalZone->removeEquipment(this->getObject<ZoneHVACComponent>()); } } std::vector<Surface> ZoneHVACBaseboardRadiantConvectiveWater_Impl::surfaces() const { //vector to hold all of the surfaces that this radiant system is attached to std::vector<Surface> surfaces; //get the thermal zone this equipment belongs to if (auto const thermalZone = this->thermalZone()) { //loop through all the spaces in this zone for (auto const & space : thermalZone->spaces()){ //loop through all the surfaces in this space for (auto const & surface : space.surfaces()){ surfaces.push_back(surface); } } } return surfaces; } std::vector<ModelObject> ZoneHVACBaseboardRadiantConvectiveWater_Impl::children() const { std::vector<ModelObject> result; if (OptionalHVACComponent intermediate = optionalHeatingCoil()) { result.push_back(*intermediate); } return result; } ModelObject ZoneHVACBaseboardRadiantConvectiveWater_Impl::clone(Model model) const { auto baseboardRadConvWaterClone = ZoneHVACComponent_Impl::clone(model).cast<ZoneHVACBaseboardRadiantConvectiveWater>(); auto t_heatingCoil = heatingCoil(); auto heatingCoilClone = t_heatingCoil.clone(model).cast<HVACComponent>(); baseboardRadConvWaterClone.setHeatingCoil(heatingCoilClone); if( model == this->model() ) { if( auto plant = t_heatingCoil.plantLoop() ) { plant->addDemandBranchForComponent(heatingCoilClone); } } return baseboardRadConvWaterClone; } std::vector<IdfObject> ZoneHVACBaseboardRadiantConvectiveWater_Impl::remove() { if( auto waterHeatingCoil = heatingCoil().optionalCast<CoilHeatingWaterBaseboardRadiant>() ) { if( boost::optional<PlantLoop> plantLoop = waterHeatingCoil->plantLoop() ) { plantLoop->removeDemandBranchWithComponent( waterHeatingCoil.get() ); } } return ZoneHVACComponent_Impl::remove(); } Schedule ZoneHVACBaseboardRadiantConvectiveWater_Impl::availabilitySchedule() const { boost::optional<Schedule> value = optionalAvailabilitySchedule(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Availability Schedule attached."); } return value.get(); } double ZoneHVACBaseboardRadiantConvectiveWater_Impl::fractionRadiant() const { boost::optional<double> value = getDouble(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::FractionRadiant,true); OS_ASSERT(value); return value.get(); } double ZoneHVACBaseboardRadiantConvectiveWater_Impl::fractionofRadiantEnergyIncidentonPeople() const { boost::optional<double> value = getDouble(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::FractionofRadiantEnergyIncidentonPeople,true); OS_ASSERT(value); return value.get(); } HVACComponent ZoneHVACBaseboardRadiantConvectiveWater_Impl::heatingCoil() const { boost::optional<HVACComponent> value = optionalHeatingCoil(); if (!value) { LOG_AND_THROW(briefDescription() << " does not have an Heating Coil attached."); } return value.get(); } bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::setAvailabilitySchedule(Schedule& schedule) { bool result = setSchedule(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::AvailabilityScheduleName, "ZoneHVACBaseboardRadiantConvectiveWater", "Availability", schedule); return result; } bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::setFractionRadiant(double fractionRadiant) { bool result = setDouble(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::FractionRadiant, fractionRadiant); return result; } bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::setFractionofRadiantEnergyIncidentonPeople(double fractionofRadiantEnergyIncidentonPeople) { bool result = setDouble(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::FractionofRadiantEnergyIncidentonPeople, fractionofRadiantEnergyIncidentonPeople); return result; } bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::setHeatingCoil(const HVACComponent& radBaseboardHeatingCoil) { bool result = setPointer(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::HeatingCoilName, radBaseboardHeatingCoil.handle()); return result; } boost::optional<Schedule> ZoneHVACBaseboardRadiantConvectiveWater_Impl::optionalAvailabilitySchedule() const { return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::AvailabilityScheduleName); } boost::optional<HVACComponent> ZoneHVACBaseboardRadiantConvectiveWater_Impl::optionalHeatingCoil() const { return getObject<ModelObject>().getModelObjectTarget<HVACComponent>(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::HeatingCoilName); } std::vector<EMSActuatorNames> ZoneHVACBaseboardRadiantConvectiveWater_Impl::emsActuatorNames() const { std::vector<EMSActuatorNames> actuators{ { "ZoneBaseboard:OutdoorTemperatureControlled", "Power Level" } }; return actuators; } std::vector<std::string> ZoneHVACBaseboardRadiantConvectiveWater_Impl::emsInternalVariableNames() const { std::vector<std::string> types{ "Simple Zone Baseboard Capacity At Low Temperature", "Simple Zone Baseboard Capacity At High Temperature" }; return types; } } // detail ZoneHVACBaseboardRadiantConvectiveWater::ZoneHVACBaseboardRadiantConvectiveWater(const Model& model) : ZoneHVACComponent(ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType(),model) { OS_ASSERT(getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()); bool ok = true; auto alwaysOn = model.alwaysOnDiscreteSchedule(); ok = setAvailabilitySchedule( alwaysOn ); OS_ASSERT(ok); ok = setFractionRadiant( 0.3 ); OS_ASSERT(ok); ok = setFractionofRadiantEnergyIncidentonPeople( 0.3 ); OS_ASSERT(ok); CoilHeatingWaterBaseboardRadiant coil( model ); ok = setHeatingCoil( coil ); OS_ASSERT(ok); } IddObjectType ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType() { return IddObjectType(IddObjectType::OS_ZoneHVAC_Baseboard_RadiantConvective_Water); } Schedule ZoneHVACBaseboardRadiantConvectiveWater::availabilitySchedule() const { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->availabilitySchedule(); } double ZoneHVACBaseboardRadiantConvectiveWater::fractionRadiant() const { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->fractionRadiant(); } double ZoneHVACBaseboardRadiantConvectiveWater::fractionofRadiantEnergyIncidentonPeople() const { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->fractionofRadiantEnergyIncidentonPeople(); } HVACComponent ZoneHVACBaseboardRadiantConvectiveWater::heatingCoil() const { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->heatingCoil(); } bool ZoneHVACBaseboardRadiantConvectiveWater::setAvailabilitySchedule(Schedule& schedule) { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->setAvailabilitySchedule(schedule); } bool ZoneHVACBaseboardRadiantConvectiveWater::setFractionRadiant(double fractionRadiant) { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->setFractionRadiant(fractionRadiant); } bool ZoneHVACBaseboardRadiantConvectiveWater::setFractionofRadiantEnergyIncidentonPeople(double fractionofRadiantEnergyIncidentonPeople) { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->setFractionofRadiantEnergyIncidentonPeople(fractionofRadiantEnergyIncidentonPeople); } bool ZoneHVACBaseboardRadiantConvectiveWater::setHeatingCoil(const HVACComponent& radBaseboardHeatingCoil) { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->setHeatingCoil(radBaseboardHeatingCoil); } boost::optional<ThermalZone> ZoneHVACBaseboardRadiantConvectiveWater::thermalZone() { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->thermalZone(); } bool ZoneHVACBaseboardRadiantConvectiveWater::addToThermalZone(ThermalZone & thermalZone) { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->addToThermalZone(thermalZone); } void ZoneHVACBaseboardRadiantConvectiveWater::removeFromThermalZone() { return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->removeFromThermalZone(); } /// @cond ZoneHVACBaseboardRadiantConvectiveWater::ZoneHVACBaseboardRadiantConvectiveWater(std::shared_ptr<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl> impl) : ZoneHVACComponent(std::move(impl)) {} /// @endcond } // model } // openstudio
43.191257
163
0.741966
[ "object", "vector", "model" ]
8dc26169ae56b9f8249f7cef696b83091adbae77
14,735
cpp
C++
source/mclib/mlr/mlrsortbyorder.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
38
2015-04-10T13:31:03.000Z
2021-09-03T22:34:05.000Z
source/mclib/mlr/mlrsortbyorder.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
1
2020-07-09T09:48:44.000Z
2020-07-12T12:41:43.000Z
source/mclib/mlr/mlrsortbyorder.cpp
mechasource/mechcommander2
b2c7cecf001cec1f535aa8d29c31bdc30d9aa983
[ "BSD-2-Clause" ]
12
2015-06-29T08:06:57.000Z
2021-10-13T13:11:41.000Z
//===========================================================================// // Copyright (C) Microsoft Corporation. All rights reserved. // //===========================================================================// #include "stdinc.h" #include "mlr/mlrsortbyorder.h" namespace MidLevelRenderer { //############################################################################# //############################ MLRSortByOrder //################################ //############################################################################# extern uint32_t gEnableTextureSort, gEnableAlphaSort, gEnableLightMaps; MLRSortByOrder::ClassData* MLRSortByOrder::DefaultData = nullptr; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::InitializeClass() { _ASSERT(!DefaultData); // _ASSERT(gos_GetCurrentHeap() == StaticHeap); DefaultData = new ClassData( MLRSortByOrderClassID, "MidLevelRenderer::MLRSortByOrder", MLRSorter::DefaultData); Register_Object(DefaultData); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::TerminateClass() { Unregister_Object(DefaultData); delete DefaultData; DefaultData = nullptr; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // MLRSortByOrder::MLRSortByOrder(MLRTexturePool* tp) : MLRSorter(DefaultData, tp) { // _ASSERT(gos_GetCurrentHeap() == Heap); int32_t i; gos_PushCurrentHeap(StaticHeap); for (i = 0; i < MLRState::PriorityCount; i++) { lastUsedInBucket[i] = 0; priorityBuckets[i].SetLength( Limits::Max_Number_Primitives_Per_Frame + Limits::Max_Number_ScreenQuads_Per_Frame); } alphaSort.SetLength(2 * Limits::Max_Number_Vertices_Per_Frame); for (i = 0; i < alphaSort.GetLength(); i++) { alphaSort[i] = new SortAlpha; } gos_PopCurrentHeap(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // MLRSortByOrder::~MLRSortByOrder() { int32_t i; gos_PushCurrentHeap(StaticHeap); for (i = 0; i < alphaSort.GetLength(); i++) { delete alphaSort[i]; } alphaSort.SetLength(0); gos_PopCurrentHeap(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::Reset() { // Check_Object(this); int32_t i; for (i = 0; i < MLRState::PriorityCount; i++) { lastUsedInBucket[i] = 0; } MLRSorter::Reset(); } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::AddPrimitive(MLRPrimitiveBase* pt, uint32_t pass) { // Check_Object(this); Check_Object(pt); SortData* sd = nullptr; switch (pt->GetSortDataMode()) { case SortData::TriList: case SortData::TriIndexedList: sd = SetRawData(pt, pass); break; } uint32_t priority = pt->GetCurrentState(pass).GetPriority(); if (sd != nullptr) { priorityBuckets[priority][lastUsedInBucket[priority]++] = sd; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::AddEffect(MLREffect* ef, const MLRState& state) { // Check_Object(this); Check_Object(ef); SortData* sd = nullptr; switch (ef->GetSortDataMode()) { case SortData::PointCloud: sd = SetRawData(ef->GetGOSVertices(), ef->GetNumGOSVertices(), state, SortData::PointCloud); sd->numIndices = ef->GetType(0); break; case SortData::LineCloud: sd = SetRawData(ef->GetGOSVertices(), ef->GetNumGOSVertices(), state, SortData::LineCloud); sd->numIndices = ef->GetType(0); break; case SortData::TriList: sd = SetRawData(ef->GetGOSVertices(), ef->GetNumGOSVertices(), state, SortData::TriList); break; case SortData::TriIndexedList: { MLRIndexedTriangleCloud* itc = Cast_Object(MLRIndexedTriangleCloud*, ef); sd = SetRawIndexedData(itc->GetGOSVertices(), itc->GetNumGOSVertices(), itc->GetGOSIndices(), itc->GetNumGOSIndices(), state, SortData::TriIndexedList); } break; } uint32_t priority = state.GetPriority(); if (sd != nullptr) { priorityBuckets[priority][lastUsedInBucket[priority]++] = sd; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::AddScreenQuads(GOSVertex* vertices, const DrawScreenQuadsInformation* dInfo) { _ASSERT(dInfo->currentNrOfQuads != 0 && (dInfo->currentNrOfQuads & 3) == 0); SortData* sd = SetRawData(vertices, dInfo->currentNrOfQuads, dInfo->state, SortData::Quads); uint32_t priority = dInfo->state.GetPriority(); if (sd != nullptr) { priorityBuckets[priority][lastUsedInBucket[priority]++] = sd; } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::AddSortRawData(SortData* sd) { // Check_Object(this); if (sd == nullptr) { return; } uint32_t priority = sd->state.GetPriority(); priorityBuckets[priority][lastUsedInBucket[priority]++] = sd; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::RenderNow() { // Check_Object(this); // // So GameOS knows how int32_t the transform and clip and lighting took of // update renderers // std::vector<SortData*>* priorityBucket; std::vector<ToBeDrawnPrimitive*>* priorityBucketNotDrawn; GOSVertex::farClipReciprocal = farClipReciprocal; int32_t i, j, k; // Limits::Max_Number_Primitives_Per_Frame + // Max_Number_ScreenQuads_Per_Frame MLRPrimitiveBase* primitive; for (i = 0; i < MLRState::PriorityCount; i++) { #ifdef CalDraw ToBeDrawnPrimitive* tbdp; int32_t alphaToSort = 0; if (lastUsedInBucketNotDrawn[i]) { _ASSERT(lastUsedInBucketNotDrawn[i] <= Limits::Max_Number_Primitives_Per_Frame + Limits::Max_Number_ScreenQuads_Per_Frame); if (gEnableTextureSort && i != MLRState::AlphaPriority) { Start_Timer(Texture_Sorting_Time); // do a shell sort int32_t ii, jj, hh; ToBeDrawnPrimitive* tempSortData; priorityBucketNotDrawn = &priorityBucketsNotDrawn[i]; for (hh = 1; hh < lastUsedInBucketNotDrawn[i] / 9; hh = 3 * hh + 1) ; for (; hh > 0; hh /= 3) { for (ii = hh; ii < lastUsedInBucketNotDrawn[i]; ii++) { tempSortData = (*priorityBucketNotDrawn)[ii]; jj = ii; while (jj >= hh && (*priorityBucketNotDrawn)[jj - hh]->state.GetTextureHandle() > tempSortData->state.GetTextureHandle()) { (*priorityBucketNotDrawn)[jj] = (*priorityBucketNotDrawn)[jj - hh]; jj -= hh; } (*priorityBucketNotDrawn)[jj] = tempSortData; } } Stop_Timer(Texture_Sorting_Time); } if (i != MLRState::AlphaPriority) { for (j = 0; j < lastUsedInBucketNotDrawn[i]; j++) { tbdp = priorityBucketsNotDrawn[i][j]; Check_Pointer(tbdp); primitive = tbdp->primitive; Check_Object(primitive); int32_t nrOfLightMaps = 0; for (k = 0; k < tbdp->nrOfActiveLights; k++) { Check_Object(tbdp->activeLights[k]); nrOfLightMaps += (tbdp->activeLights[k]->GetLightMap() != nullptr) ? 1 : 0; tbdp->activeLights[k]->SetLightToShapeMatrix(tbdp->worldToShape); } if (!gEnableLightMaps) { nrOfLightMaps = 0; } if (nrOfLightMaps) { MLRLightMap::SetDrawData(ToBeDrawnPrimitive::allVerticesToDraw, &tbdp->shapeToClipMatrix, tbdp->clippingFlags, tbdp->state); } if (primitive->FindBackFace(tbdp->cameraPosition)) { primitive->Lighting(tbdp->activeLights, tbdp->nrOfActiveLights); if (tbdp->clippingFlags.GetClippingState() != 0) { if (primitive->TransformAndClip(&tbdp->shapeToClipMatrix, tbdp->clippingFlags, ToBeDrawnPrimitive::allVerticesToDraw, true)) { if (primitive->GetVisible()) { for (k = 0; k < primitive->GetNumPasses(); k++) { DrawPrimitive(primitive, k); } } } } else { primitive->TransformNoClip(&tbdp->shapeToClipMatrix, ToBeDrawnPrimitive::allVerticesToDraw, true); for (k = 0; k < primitive->GetNumPasses(); k++) { DrawPrimitive(primitive, k); } } #ifdef LAB_ONLY Set_Statistic(Number_Of_Primitives, Number_Of_Primitives + 1); if (primitive->IsDerivedFrom(MLRIndexedPrimitiveBase::DefaultData)) { Point3D* coords; uint16_t* indices; int32_t nr; (Cast_Pointer(MLRIndexedPrimitiveBase*, primitive)) ->GetIndexData(&indices, &nr); Set_Statistic(NumAllIndices, NumAllIndices + nr); primitive->GetCoordData(&coords, &nr); Set_Statistic(NumAllVertices, NumAllVertices + nr); Set_Statistic(Index_Over_Vertex_Ratio, (float)NumAllIndices / (float)NumAllVertices); } #endif } if (nrOfLightMaps) { MLRLightMap::DrawLightMaps(this); } } } else { SortData* sd = nullptr; for (j = 0; j < lastUsedInBucketNotDrawn[i]; j++) { tbdp = priorityBucketsNotDrawn[i][j]; primitive = tbdp->primitive; if (primitive->FindBackFace(tbdp->cameraPosition)) { primitive->Lighting(tbdp->activeLights, tbdp->nrOfActiveLights); if (tbdp->clippingFlags.GetClippingState() != 0) { if (primitive->TransformAndClip(&tbdp->shapeToClipMatrix, tbdp->clippingFlags, ToBeDrawnPrimitive::allVerticesToDraw, true)) { if (!primitive->GetVisible()) { continue; } } } else { primitive->TransformNoClip(&tbdp->shapeToClipMatrix, ToBeDrawnPrimitive::allVerticesToDraw, true); } #ifdef LAB_ONLY Set_Statistic(Number_Of_Primitives, Number_Of_Primitives + 1); if (primitive->IsDerivedFrom(MLRIndexedPrimitiveBase::DefaultData)) { Point3D* coords; uint16_t* indices; int32_t nr; (Cast_Pointer(MLRIndexedPrimitiveBase*, primitive)) ->GetIndexData(&indices, &nr); Set_Statistic(NumAllIndices, NumAllIndices + nr); primitive->GetCoordData(&coords, &nr); Set_Statistic(NumAllVertices, NumAllVertices + nr); Set_Statistic(Index_Over_Vertex_Ratio, (float)NumAllIndices / (float)NumAllVertices); } #endif } else { continue; } if (primitive->GetNumGOSVertices() > 0) for (k = 0; k < primitive->GetNumPasses(); k++) { sd = SetRawData(primitive, k); Check_Pointer(sd); if (gEnableAlphaSort && (sd->type == SortData::TriList || sd->type == SortData::TriIndexedList)) { SortData::LoadSortAlphaFunc alphaFunc = sd->LoadSortAlpha[sd->type]; _ASSERT(alphaToSort + sd->numVertices / 3 < 2 * Limits::Max_Number_Vertices_Per_Frame); alphaToSort += (sd->*alphaFunc)(alphaSort.GetData() + alphaToSort); } else { if (theCurrentState != sd->state) { SetDifferences(theCurrentState, sd->state); theCurrentState = sd->state; } SortData::DrawFunc drawFunc = sd->Draw[sd->type]; (sd->*drawFunc)(); } } } } } #endif if (lastUsedInBucket[i]) { _ASSERT(lastUsedInBucket[i] <= Limits::Max_Number_Primitives_Per_Frame + Limits::Max_Number_ScreenQuads_Per_Frame); if (gEnableTextureSort && i != MLRState::AlphaPriority) { Start_Timer(Texture_Sorting_Time); // do a shell sort int32_t ii, jj, hh; SortData* tempSortData; priorityBucket = &priorityBuckets[i]; for (hh = 1; hh < lastUsedInBucket[i] / 9; hh = 3 * hh + 1) ; for (; hh > 0; hh /= 3) { for (ii = hh; ii < lastUsedInBucket[i]; ii++) { tempSortData = (*priorityBucket)[ii]; jj = ii; while (jj >= hh && (*priorityBucket)[jj - hh]->state.GetTextureHandle() > tempSortData->state.GetTextureHandle()) { (*priorityBucket)[jj] = (*priorityBucket)[jj - hh]; jj -= hh; } (*priorityBucket)[jj] = tempSortData; } } Stop_Timer(Texture_Sorting_Time); } if (i != MLRState::AlphaPriority) { for (j = 0; j < lastUsedInBucket[i]; j++) { SortData* sd = priorityBuckets[i][j]; Check_Pointer(sd); if (theCurrentState != sd->state) { SetDifferences(theCurrentState, sd->state); theCurrentState = sd->state; } SortData::DrawFunc drawFunc = sd->Draw[sd->type]; // _clear87(); (sd->*drawFunc)(); // _clear87(); } } else { for (j = 0; j < lastUsedInBucket[i]; j++) { SortData* sd = priorityBuckets[i][j]; Check_Pointer(sd); if (gEnableAlphaSort && (sd->type == SortData::TriList || sd->type == SortData::TriIndexedList)) { SortData::LoadSortAlphaFunc alphaFunc = sd->LoadSortAlpha[sd->type]; _ASSERT(alphaToSort + sd->numVertices / 3 < 2 * Limits::Max_Number_Vertices_Per_Frame); alphaToSort += (sd->*alphaFunc)(alphaSort.GetData() + alphaToSort); } else { if (theCurrentState != sd->state) { SetDifferences(theCurrentState, sd->state); theCurrentState = sd->state; } SortData::DrawFunc drawFunc = sd->Draw[sd->type]; (sd->*drawFunc)(); } } } } if (alphaToSort > 0) { Start_Timer(Alpha_Sorting_Time); // do a shell sort int32_t ii, jj, hh; SortAlpha* tempSortAlpha; std::vector<SortAlpha*>* alphaArray; alphaArray = &alphaSort; for (hh = 1; hh < alphaToSort / 9; hh = 3 * hh + 1) ; for (; hh > 0; hh /= 3) { for (ii = hh; ii < alphaToSort; ii++) { tempSortAlpha = (*alphaArray)[ii]; jj = ii; while (jj >= hh && (*alphaArray)[jj - hh]->distance < tempSortAlpha->distance) { (*alphaArray)[jj] = (*alphaArray)[jj - hh]; jj -= hh; } (*alphaArray)[jj] = tempSortAlpha; } } Stop_Timer(Alpha_Sorting_Time); for (ii = 0; ii < alphaToSort; ii++) { if (theCurrentState != *alphaSort[ii]->state) { SetDifferences(theCurrentState, *alphaSort[ii]->state); theCurrentState = *alphaSort[ii]->state; } Start_Timer(GOS_Draw_Time); if ((alphaSort[ii]->triangle[0].z >= 0.0f) && (alphaSort[ii]->triangle[0].z < 1.0f) && (alphaSort[ii]->triangle[1].z >= 0.0f) && (alphaSort[ii]->triangle[1].z < 1.0f) && (alphaSort[ii]->triangle[2].z >= 0.0f) && (alphaSort[ii]->triangle[2].z < 1.0f)) { gos_DrawTriangles(&(alphaSort[ii]->triangle[0]), 3); } Stop_Timer(GOS_Draw_Time); } Set_Statistic(NumberOfAlphaSortedTriangles, NumberOfAlphaSortedTriangles + alphaToSort); } } } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // void MLRSortByOrder::TestInstance(void) const { _ASSERT(IsDerivedFrom(DefaultData)); } } // namespace MidLevelRenderer
29.588353
254
0.586088
[ "vector", "transform" ]
8dc2992b65616d921e6b0c457881063d129b9dda
3,500
cpp
C++
uci-analyser/evaluation.cpp
DrNixx/PGN-Spy
accffa11bfd4d67f7921d0cf19dc998c1722205e
[ "MIT" ]
48
2016-07-12T23:58:35.000Z
2022-02-20T13:16:10.000Z
uci-analyser/evaluation.cpp
DrNixx/PGN-Spy
accffa11bfd4d67f7921d0cf19dc998c1722205e
[ "MIT" ]
8
2017-03-22T13:57:49.000Z
2021-09-02T07:47:50.000Z
uci-analyser/evaluation.cpp
DrNixx/PGN-Spy
accffa11bfd4d67f7921d0cf19dc998c1722205e
[ "MIT" ]
14
2018-03-28T22:55:07.000Z
2022-01-18T19:56:06.000Z
/* * Program: uci-analyser: a UCI-based Chess Game Analyser * Copyright (C) 1994-2015 David Barnes * 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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * David Barnes may be contacted as D.J.Barnes@kent.ac.uk * http://www.cs.kent.ac.uk/people/staff/djb/ * * This software has been modified for compatibility with PGN Spy. The original may be found at: * https://www.cs.kent.ac.uk/people/staff/djb/chessplag/ * */ #include <iostream> #include <sstream> #include "evaluation.h" #include "utils.h" using namespace std; /* * Extract the evaluation details from an "info" * output from the engine. */ void Evaluation::extractInfo(const vector<string> &tokens, const string& info) { int numTokens = tokens.size(); this->cpValue = 0; this->lowerBound = false; this->upperBound = false; this->variation = 0; this->forcedMate = false; this->mateInMoves = 0; for (int t = 1; t < numTokens;) { string token = tokens[t]; t++; if (token == "depth") { string value = tokens[t]; t++; this->depth = strToInt(value); } else if (token == "seldepth") { string depth = tokens[t]; t++; } else if (token == "score") { string scoreType = tokens[t]; t++; if (scoreType == "cp") { string value = tokens[t]; t++; cpValue = strToInt(value); } else if (scoreType == "mate") { string moves = tokens[t]; t++; forcedMate = true; mateInMoves = strToInt(moves); } string nextToken = tokens[t]; if (nextToken == "lowerbound") { lowerBound = true; t++; } else if (nextToken == "upperbound") { upperBound = true; t++; } } else if (token == "multipv") { string multipv = tokens[t]; t++; this->variation = strToInt(multipv); } else if (token == "nodes") { this->nodes = strToInt(tokens[t]); t++; } else if (token == "nps") { string nps = tokens[t]; t++; } else if (token == "pv") { // Remaining tokens are the moves of the line. for (; t < numTokens; t++) { this->moves.push_back(tokens[t]); } } else if (token == "time") { this->time = tokens[t]; t++; } else { //unrecognised token; ignore instead of reporting error // cout << "# Unrecognised token " << token << " in: " << endl; // cout << "# " << info << endl; } } }
33.653846
98
0.525429
[ "vector" ]
8dc353714cb6405523b009bf4a68ecdf64320174
3,660
cpp
C++
src/Storages/MergeTree/MergeTreeIndexGranularity.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
15,577
2019-09-23T11:57:53.000Z
2022-03-31T18:21:48.000Z
src/Storages/MergeTree/MergeTreeIndexGranularity.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
16,476
2019-09-23T11:47:00.000Z
2022-03-31T23:06:01.000Z
src/Storages/MergeTree/MergeTreeIndexGranularity.cpp
pdv-ru/ClickHouse
0ff975bcf3008fa6c6373cbdfed16328e3863ec5
[ "Apache-2.0" ]
3,633
2019-09-23T12:18:28.000Z
2022-03-31T15:55:48.000Z
#include <Storages/MergeTree/MergeTreeIndexGranularity.h> #include <Common/Exception.h> #include <IO/WriteHelpers.h> namespace DB { namespace ErrorCodes { extern const int LOGICAL_ERROR; } MergeTreeIndexGranularity::MergeTreeIndexGranularity(const std::vector<size_t> & marks_rows_partial_sums_) : marks_rows_partial_sums(marks_rows_partial_sums_) { } MergeTreeIndexGranularity::MergeTreeIndexGranularity(size_t marks_count, size_t fixed_granularity) : marks_rows_partial_sums(marks_count, fixed_granularity) { } /// Rows after mark to next mark size_t MergeTreeIndexGranularity::getMarkRows(size_t mark_index) const { if (mark_index >= getMarksCount()) throw Exception(ErrorCodes::LOGICAL_ERROR, "Trying to get non existing mark {}, while size is {}", mark_index, getMarksCount()); if (mark_index == 0) return marks_rows_partial_sums[0]; else return marks_rows_partial_sums[mark_index] - marks_rows_partial_sums[mark_index - 1]; } size_t MergeTreeIndexGranularity::getMarkStartingRow(size_t mark_index) const { if (mark_index == 0) return 0; return marks_rows_partial_sums[mark_index - 1]; } size_t MergeTreeIndexGranularity::getMarksCount() const { return marks_rows_partial_sums.size(); } size_t MergeTreeIndexGranularity::getTotalRows() const { if (marks_rows_partial_sums.empty()) return 0; return marks_rows_partial_sums.back(); } void MergeTreeIndexGranularity::appendMark(size_t rows_count) { if (marks_rows_partial_sums.empty()) marks_rows_partial_sums.push_back(rows_count); else marks_rows_partial_sums.push_back(marks_rows_partial_sums.back() + rows_count); } void MergeTreeIndexGranularity::addRowsToLastMark(size_t rows_count) { if (marks_rows_partial_sums.empty()) marks_rows_partial_sums.push_back(rows_count); else marks_rows_partial_sums.back() += rows_count; } void MergeTreeIndexGranularity::popMark() { if (!marks_rows_partial_sums.empty()) marks_rows_partial_sums.pop_back(); } size_t MergeTreeIndexGranularity::getRowsCountInRange(size_t begin, size_t end) const { size_t subtrahend = 0; if (begin != 0) subtrahend = marks_rows_partial_sums[begin - 1]; return marks_rows_partial_sums[end - 1] - subtrahend; } size_t MergeTreeIndexGranularity::getRowsCountInRange(const MarkRange & range) const { return getRowsCountInRange(range.begin, range.end); } size_t MergeTreeIndexGranularity::getRowsCountInRanges(const MarkRanges & ranges) const { size_t total = 0; for (const auto & range : ranges) total += getRowsCountInRange(range); return total; } size_t MergeTreeIndexGranularity::countMarksForRows(size_t from_mark, size_t number_of_rows, size_t offset_in_rows) const { size_t rows_before_mark = getMarkStartingRow(from_mark); size_t last_row_pos = rows_before_mark + offset_in_rows + number_of_rows; auto position = std::upper_bound(marks_rows_partial_sums.begin(), marks_rows_partial_sums.end(), last_row_pos); size_t to_mark; if (position == marks_rows_partial_sums.end()) to_mark = marks_rows_partial_sums.size(); else to_mark = position - marks_rows_partial_sums.begin(); return getRowsCountInRange(from_mark, std::max(1UL, to_mark)) - offset_in_rows; } void MergeTreeIndexGranularity::resizeWithFixedGranularity(size_t size, size_t fixed_granularity) { marks_rows_partial_sums.resize(size); size_t prev = 0; for (size_t i = 0; i < size; ++i) { marks_rows_partial_sums[i] = fixed_granularity + prev; prev = marks_rows_partial_sums[i]; } } }
28.59375
136
0.74918
[ "vector" ]
44f3032c7f373d8ee1e3f0a3b5da0134e7012420
1,875
cpp
C++
src/render/Drawable/AutoscaleDrawableModificator.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/render/Drawable/AutoscaleDrawableModificator.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
src/render/Drawable/AutoscaleDrawableModificator.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <glm/gtx/transform.hpp> #include <mtt/render/Drawable/AutoscaleDrawableModificator.h> #include <mtt/render/DrawPlan/DrawPlanBuildInfo.h> #include <mtt/render/SceneGraph/CameraNode.h> #include <mtt/utilities/ScopedSetter.h> using namespace mtt; AutoscaleDrawableModificator::AutoscaleDrawableModificator() : _mode(PIXEL_SCALE_MODE) { } void AutoscaleDrawableModificator::draw(DrawPlanBuildInfo& buildInfo, DrawableModificator** next, size_t modifiactorsLeft, Drawable& drawable) const { if(_mode == NO_SCALE_MODE) { drawNext(buildInfo, next, modifiactorsLeft, drawable); return; } ValueRestorer<DrawMatrices> restoreMatrices(buildInfo.drawMatrices); glm::vec3 viewSpacePoint = buildInfo.drawMatrices.localToViewMatrix * glm::vec4(0, 0, 0, 1); if(_mode == VIEWPORT_SCALE_MODE) { glm::vec2 screenSize = buildInfo.rootViewInfo.screenSize(viewSpacePoint); float maxSize = glm::max(screenSize.x, screenSize.y); buildInfo.drawMatrices.localToViewMatrix *= glm::scale(glm::vec3(maxSize)); } else { float scale = buildInfo.rootViewInfo.mppx(viewSpacePoint); buildInfo.drawMatrices.localToViewMatrix *= glm::scale(glm::vec3(scale)); } drawNext(buildInfo, next, modifiactorsLeft, drawable); } float AutoscaleDrawableModificator::scale(const glm::vec3& position, const ViewInfo& viewInfo, Mode mode) noexcept { if(mode == NO_SCALE_MODE) return 1.f; if(mode == VIEWPORT_SCALE_MODE) { glm::vec2 screenSize = viewInfo.screenSize(position); return glm::max(screenSize.x, screenSize.y); } else { return viewInfo.mppx(position); } }
30.737705
80
0.645867
[ "render", "transform" ]
44f8794a07736e08ba7a4270c754f1411017a758
3,573
cpp
C++
dali/internal/canvas-renderer/tizen/drawable-group-impl-tizen.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
6
2016-11-18T10:26:46.000Z
2021-11-01T12:29:05.000Z
dali/internal/canvas-renderer/tizen/drawable-group-impl-tizen.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
5
2020-07-15T11:30:49.000Z
2020-12-11T19:13:46.000Z
dali/internal/canvas-renderer/tizen/drawable-group-impl-tizen.cpp
dalihub/dali-adaptor
b7943ae5aeb7ddd069be7496a1c1cee186b740c5
[ "Apache-2.0", "BSD-3-Clause" ]
7
2019-05-17T07:14:40.000Z
2021-05-24T07:25:26.000Z
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // CLASS HEADER #include <dali/internal/canvas-renderer/tizen/drawable-group-impl-tizen.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> #include <dali/public-api/object/type-registry.h> // INTERNAL INCLUDES #include <dali/internal/canvas-renderer/common/drawable-impl.h> namespace Dali { namespace Internal { namespace Adaptor { namespace // unnamed namespace { // Type Registration Dali::BaseHandle Create() { return Dali::BaseHandle(); } Dali::TypeRegistration type(typeid(Dali::CanvasRenderer::DrawableGroup), typeid(Dali::BaseHandle), Create); } // unnamed namespace DrawableGroupTizen* DrawableGroupTizen::New() { return new DrawableGroupTizen(); } DrawableGroupTizen::DrawableGroupTizen() #ifdef THORVG_SUPPORT : mTvgScene(nullptr) #endif { Initialize(); } DrawableGroupTizen::~DrawableGroupTizen() { } void DrawableGroupTizen::Initialize() { #ifdef THORVG_SUPPORT mTvgScene = tvg::Scene::gen().release(); if(!mTvgScene) { DALI_LOG_ERROR("DrawableGroup is null [%p]\n", this); } Drawable::Create(); Drawable::SetObject(static_cast<void*>(mTvgScene)); Drawable::SetType(Drawable::Types::DRAWABLE_GROUP); #endif } bool DrawableGroupTizen::AddDrawable(Dali::CanvasRenderer::Drawable& drawable) { #ifdef THORVG_SUPPORT if(!Drawable::GetObject() || !mTvgScene) { DALI_LOG_ERROR("DrawableGroup is null\n"); return false; } Internal::Adaptor::Drawable& drawableImpl = Dali::GetImplementation(drawable); if(drawableImpl.IsAdded()) { DALI_LOG_ERROR("Already added [%p][%p]\n", this, &drawable); return false; } drawableImpl.SetAdded(true); mDrawables.push_back(drawable); Drawable::SetChanged(true); return true; #else return false; #endif } bool DrawableGroupTizen::RemoveDrawable(Dali::CanvasRenderer::Drawable drawable) { #ifdef THORVG_SUPPORT DrawableGroup::DrawableVector::iterator it = std::find(mDrawables.begin(), mDrawables.end(), drawable); if(it != mDrawables.end()) { Internal::Adaptor::Drawable& drawableImpl = Dali::GetImplementation(*it); drawableImpl.SetAdded(false); mDrawables.erase(it); Drawable::SetChanged(true); return true; } #endif return false; } bool DrawableGroupTizen::RemoveAllDrawables() { #ifdef THORVG_SUPPORT if(!Drawable::GetObject() || !mTvgScene) { DALI_LOG_ERROR("DrawableGroup is null\n"); return false; } for(auto& it : mDrawables) { Internal::Adaptor::Drawable& drawableImpl = Dali::GetImplementation(it); drawableImpl.SetAdded(false); } mDrawables.clear(); if(static_cast<tvg::Scene*>(mTvgScene)->clear() != tvg::Result::Success) { DALI_LOG_ERROR("RemoveAllDrawables() fail.\n"); return false; } Drawable::SetChanged(true); return true; #else return false; #endif } DrawableGroup::DrawableVector DrawableGroupTizen::GetDrawables() const { return mDrawables; } } // namespace Adaptor } // namespace Internal } // namespace Dali
21.654545
107
0.723202
[ "object" ]
44fa8cba27bc6ad0b9ae91d1de051f219db41a69
15,050
cpp
C++
Plugin~/Src/MeshSync/SceneCache/SceneCacheInputFile.cpp
Mu-L/MeshSync
6290618f6cc60802394bda8e2aa177648fcf5cfd
[ "Apache-2.0" ]
null
null
null
Plugin~/Src/MeshSync/SceneCache/SceneCacheInputFile.cpp
Mu-L/MeshSync
6290618f6cc60802394bda8e2aa177648fcf5cfd
[ "Apache-2.0" ]
null
null
null
Plugin~/Src/MeshSync/SceneCache/SceneCacheInputFile.cpp
Mu-L/MeshSync
6290618f6cc60802394bda8e2aa177648fcf5cfd
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "MeshSync/SceneCache/msSceneCacheInputFile.h" #include "MeshUtils/muLog.h" //muLogError #include "Utils/msDebug.h" //msProfileScope #include "SceneCache/BufferEncoder.h" namespace ms { SceneCacheInputFile::~SceneCacheInputFile() { WaitAllPreloads(); } bool SceneCacheInputFile::IsValid() const { return !m_records.empty(); } //---------------------------------------------------------------------------------------------------------------------- SceneCacheInputFilePtr SceneCacheInputFile::Open(const char *path, const SceneCacheInputSettings& iscs) { return SceneCacheInputFilePtr(OpenRaw(path, iscs)); } SceneCacheInputFile* SceneCacheInputFile::OpenRaw(const char *path, const SceneCacheInputSettings& iscs) { SceneCacheInputFile* ret = new SceneCacheInputFile(); ret->Init(path, iscs); if (ret->IsValid()) { return ret; } else { delete ret; return nullptr; } } //---------------------------------------------------------------------------------------------------------------------- float SceneCacheInputFile::GetSampleRateV() const { return m_header.exportSettings.sampleRate; } size_t SceneCacheInputFile::GetNumScenesV() const { if (!IsValid()) return 0; return m_records.size(); } TimeRange SceneCacheInputFile::GetTimeRangeV() const { if (!IsValid()) return {0.0f, 0.0f}; return { m_records.front().time, m_records.back().time }; } float SceneCacheInputFile::GetTimeV(int i) const { if (!IsValid()) return 0.0f; if (i <= 0) return m_records.front().time; if (i >= m_records.size()) return m_records.back().time; return m_records[i].time; } int SceneCacheInputFile::GetFrameByTimeV(const float time) const { if (!IsValid()) return 0; const float sampleRate = m_header.exportSettings.sampleRate; if (sampleRate > 0.0f) { return std::floor(time * sampleRate); } //variable sample rate const auto p = std::lower_bound(m_records.begin(), m_records.end(), time, [](const SceneRecord& a, const float t){ return a.time < t; }); if (p != m_records.end()) { const int d = static_cast<int>(std::distance(m_records.begin(), p)); return p->time == time ? d : d - 1; } return 0; } //---------------------------------------------------------------------------------------------------------------------- void SceneCacheInputFile::Init(const char *path, const SceneCacheInputSettings& iscs) { m_stream = CreateStream(path, iscs); SetSettings(iscs); if (!m_stream || !(*m_stream)) return; m_header.version = 0; m_stream->read(reinterpret_cast<char*>(&m_header), sizeof(m_header)); if (m_header.version != msProtocolVersion) return; m_encoder = BufferEncoder::CreateEncoder(m_header.exportSettings.encoding, m_header.exportSettings.encoderSettings); if (!m_encoder) { // encoder associated with m_settings.encoding is not available return; } m_records.reserve(512); for (;;) { // enumerate all scene headers CacheFileSceneHeader sh; m_stream->read(reinterpret_cast<char*>(&sh), sizeof(sh)); if (sh.bufferCount == 0) { // empty header is a terminator break; } else { SceneRecord rec; rec.time = sh.time; rec.bufferSizes.resize_discard(sh.bufferCount); m_stream->read(reinterpret_cast<char*>(rec.bufferSizes.data()), rec.bufferSizes.size_in_byte()); rec.pos = static_cast<uint64_t>(m_stream->tellg()); rec.bufferSizeTotal = 0; for (uint64_t s : rec.bufferSizes) rec.bufferSizeTotal += s; rec.segments.resize(sh.bufferCount); m_records.emplace_back(std::move(rec)); m_stream->seekg(rec.bufferSizeTotal, std::ios::cur); } } const size_t scene_count = m_records.size(); std::sort(m_records.begin(), m_records.end(), [](auto& a, auto& b) { return a.time < b.time; }); TAnimationCurve<float> curve(GetTimeCurve()); curve.resize(scene_count); for (size_t i = 0; i < scene_count; ++i) { TAnimationCurve<float>::key_t& kvp = curve[i]; kvp.time = kvp.value = m_records[i].time; } { RawVector<char> encoded_buf, tmp_buf; // read meta data CacheFileMetaHeader mh; m_stream->read(reinterpret_cast<char*>(&mh), sizeof(mh)); encoded_buf.resize(static_cast<size_t>(mh.size)); m_stream->read(encoded_buf.data(), encoded_buf.size()); m_encoder->DecodeV(tmp_buf, encoded_buf); m_entityMeta.resize_discard(tmp_buf.size() / sizeof(CacheFileEntityMeta)); tmp_buf.copy_to(reinterpret_cast<char*>(m_entityMeta.data())); } if (m_header.exportSettings.stripUnchanged) m_baseScene = LoadByFrameInternal(0); //PreloadAll(); // for test } SceneCacheInputFile::StreamPtr SceneCacheInputFile::CreateStream(const char *path, const SceneCacheInputSettings& /*iscs*/) { if (!path) return nullptr; std::shared_ptr<std::basic_ifstream<char>> ret = std::make_shared<std::ifstream>(); ret->open(path, std::ios::binary); return *ret ? ret : nullptr; } //---------------------------------------------------------------------------------------------------------------------- // thread safe ScenePtr SceneCacheInputFile::LoadByFrameInternal(const size_t sceneIndex, const bool waitPreload) { if (!IsValid() || sceneIndex >= m_records.size()) return nullptr; SceneRecord& rec = m_records[sceneIndex]; if (waitPreload && rec.preload.valid()) { // wait preload rec.preload.wait(); rec.preload = {}; } ScenePtr& ret = rec.scene; if (ret) return ret; // already loaded const mu::nanosec load_begin = mu::Now(); const size_t seg_count = rec.bufferSizes.size(); rec.segments.resize(seg_count); { // get exclusive file access std::unique_lock<std::mutex> lock(m_mutex); m_stream->seekg(rec.pos, std::ios::beg); for (size_t si = 0; si < seg_count; ++si) { SceneSegment& seg = rec.segments[si]; seg.encodedSize = rec.bufferSizes[si]; // read segment { msProfileScope("SceneCacheInputFile: [%d] read segment (%d - %u byte)", (int)sceneIndex, (int)si, (uint32_t)seg.encodedSize); mu::ScopedTimer timer; seg.encodedBuf.resize(static_cast<size_t>(seg.encodedSize)); m_stream->read(seg.encodedBuf.data(), seg.encodedBuf.size()); seg.readTime = timer.elapsed(); } // launch async decode seg.task = std::async(std::launch::async, [this, &seg, sceneIndex, si]() { msProfileScope("SceneCacheInputFile: [%d] decode segment (%d)", (int)sceneIndex, (int)si); mu::ScopedTimer timer; RawVector<char> tmp_buf; m_encoder->DecodeV(tmp_buf, seg.encodedBuf); seg.decodedSize = tmp_buf.size(); std::shared_ptr<Scene> ret = Scene::create(); mu::MemoryStream scene_buf(std::move(tmp_buf)); try { ret->deserialize(scene_buf); // keep scene buffer alive. Meshes will use it as vertex buffers ret->scene_buffers.push_back(scene_buf.moveBuffer()); seg.segment = ret; // count vertices seg.vertexCount = 0; for (std::vector<std::shared_ptr<Transform>>::value_type& e : seg.segment->entities) seg.vertexCount += e->vertexCount(); } catch (std::runtime_error& e) { muLogError("exception: %s\n", e.what()); ret = nullptr; seg.error = true; } seg.decodeTime = timer.elapsed(); }); } } // concat segmented scenes for (size_t si = 0; si < seg_count; ++si) { SceneSegment& seg = rec.segments[si]; seg.task.wait(); if (seg.error) break; if (si == 0) ret = seg.segment; else ret->concat(*seg.segment, true); } if (ret) { // sort entities by ID std::sort(ret->entities.begin(), ret->entities.end(), [](auto& a, auto& b) { return a->id < b->id; }); // update profile data SceneProfileData& prof = ret->profile_data; prof = {}; prof.load_time = mu::NS2MS(mu::Now() - load_begin); for (std::vector<SceneSegment>::value_type& seg : rec.segments) { prof.size_encoded += seg.encodedSize; prof.size_decoded += seg.decodedSize; prof.read_time += seg.readTime; prof.decode_time += seg.decodeTime; prof.vertex_count += seg.vertexCount; } { msProfileScope("SceneCacheInputFile: [%d] merge & import", static_cast<int>(sceneIndex)); mu::ScopedTimer timer; if (m_header.exportSettings.stripUnchanged && m_baseScene) { // set cache flags size_t n = ret->entities.size(); if (m_entityMeta.size() == n) { mu::enumerate(m_entityMeta, ret->entities, [](CacheFileEntityMeta& meta, auto& e) { if (meta.id == e->id) { e->cache_flags.constant = meta.constant; e->cache_flags.constant_topology = meta.constantTopology; } }); } // merge ret->merge(*m_baseScene); } // do import const SceneCacheInputSettings& settings = GetSettings(); ret->import(settings.importSettings); prof.setup_time = timer.elapsed(); } } rec.segments.clear(); // push & pop history if (!m_header.exportSettings.stripUnchanged || sceneIndex != 0) { m_history.push_back(sceneIndex); PopOverflowedSamples(); } return ret; } ScenePtr SceneCacheInputFile::PostProcess(ScenePtr& sp, const size_t sceneIndex) { if (!sp) return sp; ScenePtr ret; // m_lastScene and m_lastDiff keep reference counts and keep scenes alive. // (plugin APIs return raw scene pointers. someone needs to keep its reference counts) const SceneCacheInputSettings& settings = GetSettings(); if (m_lastScene && (settings.enableDiff && m_header.exportSettings.stripUnchanged)) { msProfileScope("SceneCacheInputFile: [%d] diff", static_cast<int>(sceneIndex)); m_lastDiff = Scene::create(); m_lastDiff->diff(*sp, *m_lastScene); m_lastScene = sp; ret = m_lastDiff; } else { m_lastDiff = nullptr; m_lastScene = sp; ret = sp; } // kick preload PreloadV(static_cast<int>(sceneIndex)); return ret; } bool SceneCacheInputFile::KickPreload(size_t i) { SceneRecord& rec = m_records[i]; if (rec.scene || rec.preload.valid()) return false; // already loaded or loading rec.preload = std::async(std::launch::async, [this, i]() { LoadByFrameInternal(i, false); }); return true; } void SceneCacheInputFile::WaitAllPreloads() { for (std::vector<SceneRecord>::value_type& rec : m_records) { if (rec.preload.valid()) { rec.preload.wait(); rec.preload = {}; } } } ScenePtr SceneCacheInputFile::LoadByFrameV(const int32_t frame) { if (!IsValid()) return nullptr; //already loaded if (m_loadedFrame0 == frame && m_loadedFrame1 == frame) return nullptr; m_loadedFrame0 = m_loadedFrame1 = frame; ScenePtr ret = LoadByFrameInternal(frame); return PostProcess(ret, frame); } ScenePtr SceneCacheInputFile::LoadByTimeV(const float time, const bool interpolation) { if (!IsValid()) return nullptr; if (time == m_lastTime) { return nullptr; } ScenePtr ret; const TimeRange time_range = GetTimeRangeV(); //start/end check if (time <= time_range.start) { return LoadByFrameV(0); } else if (time >= time_range.end) { const int sceneCount = static_cast<int>(m_records.size()); return LoadByFrameV(sceneCount - 1); } const int frame= GetFrameByTimeV(time); if (!interpolation){ return LoadByFrameV(frame); } //interpolation const float t1 = m_records[frame + 0].time; const float t2 = m_records[frame + 1].time; KickPreload(frame + 1); const ScenePtr s1 = LoadByFrameInternal(frame + 0); const ScenePtr s2 = LoadByFrameInternal(frame + 1); { msProfileScope("SceneCacheInputFile: [%d] lerp", (int)si); mu::ScopedTimer timer; const float t = (time - t1) / (t2 - t1); ret = Scene::create(); ret->lerp(*s1, *s2, t); // keep a reference for s1 (s2 is not needed) ret->data_sources.push_back(s1); ret->profile_data.lerp_time = timer.elapsed(); } m_loadedFrame0 = frame; m_loadedFrame1 = frame + 1; m_lastTime = time; return PostProcess(ret, m_loadedFrame1); } void SceneCacheInputFile::RefreshV() { m_loadedFrame0 = m_loadedFrame1 = -1; m_lastTime = -1.0f; m_lastScene = nullptr; m_lastDiff = nullptr; } void SceneCacheInputFile::PreloadV(const int frame) { // kick preload const int32_t preloadLength = GetPreloadLength(); if (preloadLength> 0 && frame + 1 < m_records.size()) { const int begin_frame = frame + 1; const int end_frame = std::min(frame + preloadLength, static_cast<int>(m_records.size())); for (int f = begin_frame; f < end_frame; ++f) KickPreload(f); } PopOverflowedSamples(); } void SceneCacheInputFile::PreloadAll() { const size_t n = m_records.size(); SetMaxLoadedSamples(static_cast<int>(n) + 1); for (size_t i = 0; i < n; ++i) KickPreload(i); } void SceneCacheInputFile::PopOverflowedSamples() { const int32_t maxSamples = GetMaxLoadedSamples(); while (m_history.size() > maxSamples) { m_records[m_history.front()].scene.reset(); m_history.pop_front(); } } const AnimationCurvePtr SceneCacheInputFile::GetFrameCurveV(const int baseFrame) { // generate on the fly const size_t sceneCount = m_records.size(); m_frameCurve = AnimationCurve::create(); TAnimationCurve<int> curve(m_frameCurve); curve.resize(sceneCount); for (size_t i = 0; i < sceneCount; ++i) { TAnimationCurve<int>::key_t& kvp = curve[i]; kvp.time = m_records[i].time; kvp.value = static_cast<int>(i) + baseFrame; } return m_frameCurve; } } // namespace ms
30.465587
141
0.580731
[ "vector", "transform" ]
44fd02fe05169094ac4e08134b54af7bcd8e6e4e
996
hpp
C++
source/FAST/Data/SpatialDataObject.hpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Data/SpatialDataObject.hpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
source/FAST/Data/SpatialDataObject.hpp
andreped/FAST
361819190ea0ae5a2f068e7bd808a1c70af5a171
[ "BSD-2-Clause" ]
null
null
null
#pragma once #include "FAST/Data/DataObject.hpp" #include "DataBoundingBox.hpp" #include "FAST/SceneGraph.hpp" namespace fast { /** * @brief Abstract base class for all spatial data objects * * Spatial data objects are data which have a location in 2D/3D space. */ class FAST_EXPORT SpatialDataObject : public DataObject { public: typedef std::shared_ptr<SpatialDataObject> pointer; SpatialDataObject(); void setTransform(Transform::pointer transform, bool disconnectParentSceneGraphNode = false); Transform::pointer getTransform(bool getFullTransform = false); virtual DataBoundingBox getBoundingBox() const; virtual DataBoundingBox getTransformedBoundingBox() const; SceneGraphNode::pointer getSceneGraphNode() const; static std::string getStaticNameOfClass() { return ""; }; protected: DataBoundingBox mBoundingBox; private: SceneGraphNode::pointer mSceneGraphNode; }; }
29.294118
101
0.707831
[ "transform", "3d" ]
44ff9169b7c990c328d4b49fe6982797766d5c4f
16,435
cpp
C++
tests/symmetric/cipher/stream/test_api_stream_cipher_salsa20.cpp
samleybrize/cryptopp-bindings-api
247eb69ed1953b34878c9ce3c4d2e47ad6a6333b
[ "MIT" ]
null
null
null
tests/symmetric/cipher/stream/test_api_stream_cipher_salsa20.cpp
samleybrize/cryptopp-bindings-api
247eb69ed1953b34878c9ce3c4d2e47ad6a6333b
[ "MIT" ]
null
null
null
tests/symmetric/cipher/stream/test_api_stream_cipher_salsa20.cpp
samleybrize/cryptopp-bindings-api
247eb69ed1953b34878c9ce3c4d2e47ad6a6333b
[ "MIT" ]
null
null
null
/* * This file is part of cryptopp-bindings-api. * * (c) Stephen Berquet <stephen.berquet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ #include "src/exception/api_exception.h" #include "src/symmetric/cipher/stream/api_stream_cipher_salsa20.h" #include "src/utils/api_hex_utils.h" #include "tests/test_api_assertions.h" #include <gtest/gtest.h> TEST(StreamCipherSalsa20Test, inheritance) { CryptoppApi::StreamCipherSalsa20 cipher; EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::SymmetricCipherInterface*>(&cipher)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::SymmetricTransformationInterface*>(&cipher)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::StreamCipherInterface*>(&cipher)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::StreamCipherAbstract*>(&cipher)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::SymmetricKeyAbstract*>(&cipher)); EXPECT_TRUE(0 != dynamic_cast<CryptoppApi::SymmetricIvAbstract*>(&cipher)); } TEST(StreamCipherSalsa20Test, infos) { CryptoppApi::StreamCipherSalsa20 cipher; EXPECT_STREQ("salsa20", cipher.getName()); EXPECT_EQ(1, cipher.getBlockSize()); } TEST(StreamCipherSalsa20Test, isValidKeyLength) { CryptoppApi::StreamCipherSalsa20 cipher; EXPECT_TRUE(cipher.isValidKeyLength(16)); EXPECT_TRUE(cipher.isValidKeyLength(32)); EXPECT_FALSE(cipher.isValidKeyLength(9)); EXPECT_FALSE(cipher.isValidKeyLength(0)); EXPECT_FALSE(cipher.isValidKeyLength(33)); } TEST(StreamCipherSalsa20Test, isValidIvLength) { CryptoppApi::StreamCipherSalsa20 cipher; EXPECT_TRUE(cipher.isValidIvLength(8)); EXPECT_FALSE(cipher.isValidIvLength(16)); EXPECT_FALSE(cipher.isValidIvLength(17)); } TEST(StreamCipherSalsa20Test, setGetKey) { CryptoppApi::StreamCipherSalsa20 cipher; // build keys byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("0102030405060708090a0b0c0d0e0f10", 32, &key, keyLength); // set/get keys size_t key0Length = cipher.getKeyLength(); cipher.setKey(key, keyLength); size_t keyGetLength = cipher.getKeyLength(); byte keyGet[keyGetLength]; cipher.getKey(keyGet); // test keys EXPECT_EQ(0, key0Length); EXPECT_BYTE_ARRAY_EQ(key, keyLength, keyGet, keyGetLength); delete[] key; } TEST(StreamCipherSalsa20Test, setGetIv) { CryptoppApi::StreamCipherSalsa20 cipher; // build iv byte *iv; size_t ivLength = 0; CryptoppApi::HexUtils::hex2bin("0102030405060708", 16, &iv, ivLength); // set/get iv size_t iv0Length = cipher.getIvLength(); cipher.setIv(iv, ivLength); size_t ivGetLength = cipher.getIvLength(); byte ivGet[ivGetLength]; cipher.getIv(ivGet); // test ivs EXPECT_EQ(0, iv0Length); EXPECT_BYTE_ARRAY_EQ(iv, ivLength, ivGet, ivGetLength); delete[] iv; } TEST(StreamCipherSalsa20Test, encrypt) { CryptoppApi::StreamCipherSalsa20 cipher; size_t dataSize = 16; byte output1[dataSize]; byte output2[dataSize]; byte *expected1; byte *expected2; // build key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("a7c083feb7aabbff1122334455667788", 32, &key, keyLength); // build iv byte *iv; size_t ivLength = 0; CryptoppApi::HexUtils::hex2bin("0011223344556677", 16, &iv, ivLength); // build block byte *block; size_t dummyLength = 0; CryptoppApi::HexUtils::hex2bin("00000000000000000000000000000000", 32, &block, dummyLength); // calculate actual data CryptoppApi::HexUtils::hex2bin("03ad21c7d699f686d0039c12603242bf", 32, &expected1, dummyLength); CryptoppApi::HexUtils::hex2bin("a566b2365dfb197b61a549b299e2149a", 32, &expected2, dummyLength); cipher.setKey(key, keyLength); cipher.setIv(iv, ivLength); cipher.encrypt(block, output1, dataSize); cipher.encrypt(block, output2, dataSize); EXPECT_BYTE_ARRAY_EQ(expected1, dataSize, output1, dataSize); EXPECT_BYTE_ARRAY_EQ(expected2, dataSize, output2, dataSize); delete[] expected1; delete[] expected2; delete[] key; delete[] iv; delete[] block; } TEST(StreamCipherSalsa20Test, decrypt) { CryptoppApi::StreamCipherSalsa20 cipher; size_t dataSize = 16; byte output1[dataSize]; byte output2[dataSize]; byte *block1; byte *block2; // build key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("a7c083feb7aabbff1122334455667788", 32, &key, keyLength); // build iv byte *iv; size_t ivLength = 0; CryptoppApi::HexUtils::hex2bin("0011223344556677", 16, &iv, ivLength); // build expected data byte *expected; size_t dummyLength = 0; CryptoppApi::HexUtils::hex2bin("00000000000000000000000000000000", 32, &expected, dummyLength); // calculate actual data CryptoppApi::HexUtils::hex2bin("03ad21c7d699f686d0039c12603242bf", 32, &block1, dummyLength); CryptoppApi::HexUtils::hex2bin("a566b2365dfb197b61a549b299e2149a", 32, &block2, dummyLength); cipher.setKey(key, keyLength); cipher.setIv(iv, ivLength); cipher.decrypt(block1, output1, dataSize); cipher.decrypt(block2, output2, dataSize); EXPECT_BYTE_ARRAY_EQ(expected, dataSize, output1, dataSize); EXPECT_BYTE_ARRAY_EQ(expected, dataSize, output2, dataSize); delete[] block1; delete[] block2; delete[] key; delete[] iv; delete[] expected; } TEST(StreamCipherSalsa20Test, encrypt12Rounds) { CryptoppApi::StreamCipherSalsa20 cipher(12); size_t dataSize = 16; byte output1[dataSize]; byte output2[dataSize]; byte *expected1; byte *expected2; // build key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("a7c083feb7aabbff1122334455667788", 32, &key, keyLength); // build iv byte *iv; size_t ivLength = 0; CryptoppApi::HexUtils::hex2bin("0011223344556677", 16, &iv, ivLength); // build block byte *block; size_t dummyLength = 0; CryptoppApi::HexUtils::hex2bin("00000000000000000000000000000000", 32, &block, dummyLength); // calculate actual data CryptoppApi::HexUtils::hex2bin("c7619d385ff57fad9c9ab9e7d2fa6334", 32, &expected1, dummyLength); CryptoppApi::HexUtils::hex2bin("9067a70e21e095f254c482f8e0fc2161", 32, &expected2, dummyLength); cipher.setKey(key, keyLength); cipher.setIv(iv, ivLength); cipher.encrypt(block, output1, dataSize); cipher.encrypt(block, output2, dataSize); EXPECT_BYTE_ARRAY_EQ(expected1, dataSize, output1, dataSize); EXPECT_BYTE_ARRAY_EQ(expected2, dataSize, output2, dataSize); delete[] expected1; delete[] expected2; delete[] key; delete[] iv; delete[] block; } TEST(StreamCipherSalsa20Test, decrypt12Rounds) { CryptoppApi::StreamCipherSalsa20 cipher(12); size_t dataSize = 16; byte output1[dataSize]; byte output2[dataSize]; byte *block1; byte *block2; // build key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("a7c083feb7aabbff1122334455667788", 32, &key, keyLength); // build iv byte *iv; size_t ivLength = 0; CryptoppApi::HexUtils::hex2bin("0011223344556677", 16, &iv, ivLength); // build expected data byte *expected; size_t dummyLength = 0; CryptoppApi::HexUtils::hex2bin("00000000000000000000000000000000", 32, &expected, dummyLength); // calculate actual data CryptoppApi::HexUtils::hex2bin("c7619d385ff57fad9c9ab9e7d2fa6334", 32, &block1, dummyLength); CryptoppApi::HexUtils::hex2bin("9067a70e21e095f254c482f8e0fc2161", 32, &block2, dummyLength); cipher.setKey(key, keyLength); cipher.setIv(iv, ivLength); cipher.decrypt(block1, output1, dataSize); cipher.decrypt(block2, output2, dataSize); EXPECT_BYTE_ARRAY_EQ(expected, dataSize, output1, dataSize); EXPECT_BYTE_ARRAY_EQ(expected, dataSize, output2, dataSize); delete[] block1; delete[] block2; delete[] key; delete[] iv; delete[] expected; } TEST(StreamCipherSalsa20Test, encrypt8Rounds) { CryptoppApi::StreamCipherSalsa20 cipher(8); size_t dataSize = 16; byte output1[dataSize]; byte output2[dataSize]; byte *expected1; byte *expected2; // build key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("a7c083feb7aabbff1122334455667788", 32, &key, keyLength); // build iv byte *iv; size_t ivLength = 0; CryptoppApi::HexUtils::hex2bin("0011223344556677", 16, &iv, ivLength); // build block byte *block; size_t dummyLength = 0; CryptoppApi::HexUtils::hex2bin("00000000000000000000000000000000", 32, &block, dummyLength); // calculate actual data CryptoppApi::HexUtils::hex2bin("4e26530489778baff97e6c8c6f650e3f", 32, &expected1, dummyLength); CryptoppApi::HexUtils::hex2bin("f9e95b4282bac9253d552bad7f7890a6", 32, &expected2, dummyLength); cipher.setKey(key, keyLength); cipher.setIv(iv, ivLength); cipher.encrypt(block, output1, dataSize); cipher.encrypt(block, output2, dataSize); EXPECT_BYTE_ARRAY_EQ(expected1, dataSize, output1, dataSize); EXPECT_BYTE_ARRAY_EQ(expected2, dataSize, output2, dataSize); delete[] expected1; delete[] expected2; delete[] key; delete[] iv; delete[] block; } TEST(StreamCipherSalsa20Test, decrypt8Rounds) { CryptoppApi::StreamCipherSalsa20 cipher(8); size_t dataSize = 16; byte output1[dataSize]; byte output2[dataSize]; byte *block1; byte *block2; // build key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("a7c083feb7aabbff1122334455667788", 32, &key, keyLength); // build iv byte *iv; size_t ivLength = 0; CryptoppApi::HexUtils::hex2bin("0011223344556677", 16, &iv, ivLength); // build expected data byte *expected; size_t dummyLength = 0; CryptoppApi::HexUtils::hex2bin("00000000000000000000000000000000", 32, &expected, dummyLength); // calculate actual data CryptoppApi::HexUtils::hex2bin("4e26530489778baff97e6c8c6f650e3f", 32, &block1, dummyLength); CryptoppApi::HexUtils::hex2bin("f9e95b4282bac9253d552bad7f7890a6", 32, &block2, dummyLength); cipher.setKey(key, keyLength); cipher.setIv(iv, ivLength); cipher.decrypt(block1, output1, dataSize); cipher.decrypt(block2, output2, dataSize); EXPECT_BYTE_ARRAY_EQ(expected, dataSize, output1, dataSize); EXPECT_BYTE_ARRAY_EQ(expected, dataSize, output2, dataSize); delete[] block1; delete[] block2; delete[] key; delete[] iv; delete[] expected; } TEST(StreamCipherSalsa20Test, restartEncryption) { CryptoppApi::StreamCipherSalsa20 cipher; size_t dataSize = 16; byte output1[dataSize]; byte output2[dataSize]; byte *expected; // build key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("a7c083feb7aabbff1122334455667788", 32, &key, keyLength); // build iv byte *iv; size_t ivLength; CryptoppApi::HexUtils::hex2bin("0011223344556677", 16, &iv, ivLength); cipher.setIv(iv, ivLength); // build blocks byte *block; size_t dummyLength = 0; CryptoppApi::HexUtils::hex2bin("00000000000000000000000000000000", 32, &block, dummyLength); // calculate actual data CryptoppApi::HexUtils::hex2bin("03ad21c7d699f686d0039c12603242bf", 32, &expected, dummyLength); cipher.setKey(key, keyLength); cipher.encrypt(block, output1, dataSize); cipher.restart(); cipher.encrypt(block, output2, dataSize); EXPECT_BYTE_ARRAY_EQ(expected, dataSize, output1, dataSize); EXPECT_BYTE_ARRAY_EQ(expected, dataSize, output2, dataSize); delete[] key; delete[] iv; delete[] block; delete[] expected; } TEST(StreamCipherSalsa20Test, restartDecryption) { CryptoppApi::StreamCipherSalsa20 cipher; size_t dataSize = 16; byte output1[dataSize]; byte output2[dataSize]; byte *expected1; byte *expected2; // build key byte *key; size_t keyLength = 0; CryptoppApi::HexUtils::hex2bin("a7c083feb7aabbff1122334455667788", 32, &key, keyLength); // build iv byte *iv; size_t ivLength; CryptoppApi::HexUtils::hex2bin("0011223344556677", 16, &iv, ivLength); cipher.setIv(iv, ivLength); // build blocks byte *block1; byte *block2; size_t dummyLength = 0; CryptoppApi::HexUtils::hex2bin("03ad21c7d699f686d0039c12603242bf", 32, &block1, dummyLength); CryptoppApi::HexUtils::hex2bin("a566b2365dfb197b61a549b299e2149a", 32, &block2, dummyLength); // calculate actual data CryptoppApi::HexUtils::hex2bin("00000000000000000000000000000000", 32, &expected1, dummyLength); CryptoppApi::HexUtils::hex2bin("a6cb93f18b62effdb1a6d5a0f9d05625", 32, &expected2, dummyLength); cipher.setKey(key, keyLength); cipher.decrypt(block1, output1, dataSize); cipher.restart(); cipher.decrypt(block2, output2, dataSize); EXPECT_BYTE_ARRAY_EQ(expected1, dataSize, output1, dataSize); EXPECT_BYTE_ARRAY_EQ(expected2, dataSize, output2, dataSize); delete[] key; delete[] iv; delete[] block1; delete[] block2; delete[] expected1; delete[] expected2; } TEST(StreamCipherSalsa20Test, largeData) { CryptoppApi::StreamCipherSalsa20 cipher; std::string key("1234567890123456"); std::string iv("12345678"); cipher.setKey(reinterpret_cast<const byte*>(key.c_str()), key.length()); cipher.setIv(reinterpret_cast<const byte*>(iv.c_str()), iv.length()); size_t dataSize = 10485760; byte *input = new byte[dataSize]; byte *output = new byte[dataSize]; memset(input, 125, dataSize); cipher.encrypt(input, output, dataSize); cipher.decrypt(input, output, dataSize); delete[] input; delete[] output; } TEST(StreamCipherSalsa20Test, isStream) { CryptoppApi::StreamCipherSalsa20 cipher; std::string key("1234567890123456"); std::string iv("12345678"); cipher.setKey(reinterpret_cast<const byte*>(key.c_str()), key.length()); cipher.setIv(reinterpret_cast<const byte*>(iv.c_str()), iv.length()); std::string dataStr("12345678901234567"); const byte *data = reinterpret_cast<const byte*>(dataStr.c_str()); size_t dataLength = dataStr.length(); byte output[dataLength]; cipher.encrypt(data, output, dataLength); cipher.decrypt(data, output, dataLength); } TEST(StreamCipherSalsa20Test, invalidKey) { CryptoppApi::StreamCipherSalsa20 cipher; byte key1[33]; byte key2[0]; memset(key1, 0, 33); EXPECT_THROW_MSG(cipher.setKey(key1, 33), CryptoppApi::Exception, "33 is not a valid key length"); EXPECT_THROW_MSG(cipher.setKey(key2, 0), CryptoppApi::Exception, "a key is required"); } TEST(StreamCipherSalsa20Test, invalidIv) { CryptoppApi::StreamCipherSalsa20 cipher; byte iv1[] = {45, 12, 14}; byte iv2[0]; EXPECT_THROW_MSG(cipher.setIv(iv1, 3), CryptoppApi::Exception, "3 is not a valid initialization vector length"); EXPECT_THROW_MSG(cipher.setIv(iv2, 0), CryptoppApi::Exception, "an initialization vector is required"); } TEST(StreamCipherSalsa20Test, cryptWithoutKey) { CryptoppApi::StreamCipherSalsa20 cipher; size_t inputLength = cipher.getBlockSize(); byte input[inputLength]; byte output[inputLength]; EXPECT_THROW_MSG(cipher.encrypt(input, output, inputLength), CryptoppApi::Exception, "a key is required"); EXPECT_THROW_MSG(cipher.decrypt(input, output, inputLength), CryptoppApi::Exception, "a key is required"); } TEST(StreamCipherSalsa20Test, cryptWithoutIv) { CryptoppApi::StreamCipherSalsa20 cipher; std::string key("1234567890123456"); cipher.setKey(reinterpret_cast<const byte*>(key.c_str()), key.length()); size_t inputLength = cipher.getBlockSize(); byte input[inputLength]; byte output[inputLength]; EXPECT_THROW_MSG(cipher.encrypt(input, output, inputLength), CryptoppApi::Exception, "an initialization vector is required"); EXPECT_THROW_MSG(cipher.decrypt(input, output, inputLength), CryptoppApi::Exception, "an initialization vector is required"); } TEST(StreamCipherSalsa20Test, invalidRoundNumber) { CryptoppApi::StreamCipherSalsa20 cipher; EXPECT_THROW_MSG(cipher.setRounds(5), CryptoppApi::Exception, "number of rounds must be one of 8, 12 or 20"); }
31.912621
129
0.709887
[ "vector" ]
780022126e353a065e40147707c6e90622f9cabf
362
cpp
C++
Leetcode/Move_Zeros_to_end.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
1
2019-03-24T12:35:43.000Z
2019-03-24T12:35:43.000Z
Leetcode/Move_Zeros_to_end.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
Leetcode/Move_Zeros_to_end.cpp
anishacharya/Cracking-Coding-Interviews
f94e70c240ad9a76eddf22b8f4d5b4185c611a71
[ "MIT" ]
null
null
null
class Solution { public: void moveZeroes(vector<int>& nums) { int count = 0; // Count of non-zero elements int n=nums.size(); for (int i = 0; i < n; i++) { if (nums[i] != 0) { nums[count] = nums[i]; count++; } } while (count < n) nums[count++] = 0; } };
18.1
38
0.40884
[ "vector" ]
780904425943c993e3fd4b873c514d0ca59a3b3b
2,394
cpp
C++
Coursera/Yandex_CppYellow/Week05_Task05.cpp
zakhars/Education
4d791f6b4559a90ee383039aaeb15c7041138b12
[ "MIT" ]
null
null
null
Coursera/Yandex_CppYellow/Week05_Task05.cpp
zakhars/Education
4d791f6b4559a90ee383039aaeb15c7041138b12
[ "MIT" ]
null
null
null
Coursera/Yandex_CppYellow/Week05_Task05.cpp
zakhars/Education
4d791f6b4559a90ee383039aaeb15c7041138b12
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; // Base people properties class People { protected: const string name_; const string title_; const string fullName() const { return Title() + ": " + Name(); } void doWalk(const string& destination) const { cout << fullName() << " walks to: " << destination << endl; } public: People(const string& name, const string& title) : name_(name) , title_(title) { } const string& Name() const { return name_; } const string& Title() const { return title_; } virtual void Walk(const string& destination) const { doWalk(destination); } }; class Student : public People { public: Student(const string& name, const string& favoriteSong) : People(name, "Student") , favoriteSong_(favoriteSong) { } void Learn() const { cout << fullName() << " learns" << endl; } void Walk(const string& destination) const override { People::Walk(destination); SingSong(); } void SingSong() const { cout << fullName() << " sings a song: " << favoriteSong_ << endl; } protected: // probably not a final class const string favoriteSong_; }; class Teacher : public People { public: Teacher(const string& name, const string& subject) : People(name, "Teacher") , subject_(subject) { } void Teach() const { cout << fullName() << " teaches: " << subject_ << endl; } protected: const string subject_; }; class Policeman : public People { public: Policeman(const string& name) : People(name, "Policeman") { } void Check(const People& t) const { cout << fullName() << " checks " << t.Title() << ". " << t.Title() << "'s name is: " << t.Name() << endl; } }; void VisitPlaces(People& t, const vector<string>& places) { for (const auto& p : places) { t.Walk(p); } } int main_cppy_w05_t05() { Teacher t("Jim", "Math"); Student s("Ann", "We will rock you"); Policeman p("Bob"); Policeman p2("Sherlock"); VisitPlaces(t, { "Moscow", "London" }); VisitPlaces(s, { "Moscow", "London" }); VisitPlaces(p, { "London", "Moscow" }); p.Check(s); p.Check(t); p.Check(p2); s.Learn(); s.SingSong(); t.Teach(); return 0; }
21
79
0.571429
[ "vector" ]
780a8306c58ea8e9d43958c75ad873c0bf68ae09
125,544
cxx
C++
test/math/test.cxx
sstefan/vigra
f8826fa4de4293efb95582367f4bf42cc8ba8c11
[ "MIT" ]
1
2019-04-22T20:43:46.000Z
2019-04-22T20:43:46.000Z
test/math/test.cxx
tikroeger/vigra
981d1ebc3ee85464a0d2ace693ad41606b475e2f
[ "MIT" ]
null
null
null
test/math/test.cxx
tikroeger/vigra
981d1ebc3ee85464a0d2ace693ad41606b475e2f
[ "MIT" ]
null
null
null
/************************************************************************/ /* */ /* Copyright 2004-2011 by Ullrich Koethe */ /* */ /* This file is part of the VIGRA computer vision library. */ /* The VIGRA Website is */ /* http://hci.iwr.uni-heidelberg.de/vigra/ */ /* Please direct questions, bug reports, and contributions to */ /* ullrich.koethe@iwr.uni-heidelberg.de or */ /* vigra@informatik.uni-hamburg.de */ /* */ /* 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(__GNUC__) && __GNUC__ == 2 && __GNUC_MINOR__ == 95 // deactivate broken std::relops # define __SGI_STL_INTERNAL_RELOPS #endif // __GNUC__ #include <typeinfo> #include <iostream> #include <iomanip> #include <algorithm> #include <sstream> #include <cstdlib> #include "unittest.hxx" #include "vigra/mathutil.hxx" #include "vigra/algorithm.hxx" #include "vigra/functorexpression.hxx" #include "vigra/polynomial.hxx" #include "vigra/array_vector.hxx" #include "vigra/splines.hxx" #include "vigra/gaussians.hxx" #include "vigra/rational.hxx" #include "vigra/fixedpoint.hxx" #include "vigra/linear_algebra.hxx" #include "vigra/singular_value_decomposition.hxx" #include "vigra/regression.hxx" #include "vigra/random.hxx" #include "vigra/tinyvector.hxx" #include "vigra/polygon.hxx" #include "vigra/quaternion.hxx" #include "vigra/clebsch-gordan.hxx" #include "vigra/bessel.hxx" #include "vigra/timing.hxx" #include "convex_hull_test.hxx" #define VIGRA_TOLERANCE_MESSAGE "If this test fails, please adjust the tolerance threshold and report\n" \ "your findings (including compiler information etc.) to the VIGRA mailing list:" static double coefficients[][12] = { { 5.0, -416.0, 720.0, -464.0, 136.0, -18.0, 1.0 }, { 8.0, 40320.0, -109584.0, 118124.0, -67284.0, 22449.0, -4536.0, 546.0, -36.0, 1.0}, { 3.0, 1e10, -1e10, -1e-10, 1e-10}, { 3.0, 1e-10, -1e-10, -1e10, 1e10}, { 10.0, 2.88e-8, -1.848e-6, 0.00005204, -0.0008458, 0.008777, -0.06072, 0.2835, -0.882, 1.75, -2.0, 1.0}, { 5.0, 0.3411268890719874, 0.48265610836623374, 0.29941395284477745, 0.13065520631476124, 0.68342489290545338, 0.0017437185812028133 }, { 3.0, -1.0, 1000001000001.0 / 1e6, -1000001000001.0 / 1e6, 1.0}, { 8.0, 36.0, 0.0, 85.0, 0.0, 63.0, 0.0, 15.0, 0.0, 1.0 } }; typedef std::complex<double> C; static C reference[][12] = { { C(1e-12), C(2.0), C(2.0), C(2.0), C(6.0, -4.0), C(6.0, 4.0) }, { C(1e-11), C(1.0), C(2.0), C(3.0), C(4.0), C(5.0), C(6.0), C(7.0), C(8.0) }, { C(1e-12), C(-1e10), C(1.0), C(1e10) }, { C(1e-12), C(-1e-10), C(1e-10), C(1.0) }, { C(1e-5), C(0.1), C(0.1), C(0.1), C(0.1), C(0.2), C(0.2), C(0.2), C(0.3), C(0.3), C(0.4) }, { C(1e-12), C(-391.74516023901123), C(-0.56839260551055271, -0.4046562986541693), C(-0.56839260551055271, 0.4046562986541693), C(0.47331479192572767, -0.89542786425410759), C(0.47331479192572767, 0.89542786425410759) }, { C(1e-12), C(1e-6), C(1.0), C(1e6) }, { C(1e-12), C(0.0, -3.0), C(0.0, -2.0), C(0.0, -1.0), C(0.0, -1.0), C(0.0, 1.0), C(0.0, 1.0), C(0.0, 2.0), C(0.0, 3.0) } }; #if 0 #undef should #define should(v) (std::cerr << #v << ": " << (v) << std::endl) #undef shouldEqual #define shouldEqual(v1, v2) \ (std::cerr << #v1 << " == " << #v2 << ": " << (v1) << " " << (v2) << std::endl) #undef shouldEqualTolerance #define shouldEqualTolerance(v1, v2, e) \ (std::cerr << #v1 << " == " << #v2 << ": " << (v1) << " " << (v2) << " " << (v1 - v2) << std::endl) #endif template <unsigned int N, class POLYNOMIAL> struct PolynomialTest { void testPolynomial() { double epsilon = reference[N][0].real(); unsigned int order = (unsigned int)(coefficients[N][0] + 0.5); POLYNOMIAL p(coefficients[N]+1, order); vigra::ArrayVector<std::complex<double> > roots; should(polynomialRoots(p, roots)); shouldEqual(roots.size(), order); for(unsigned int i = 0; i<roots.size(); ++i) { shouldEqualTolerance(roots[i].real(), reference[N][i+1].real(), epsilon); shouldEqualTolerance(roots[i].imag(), reference[N][i+1].imag(), epsilon); } } void testPolynomialEigenvalueMethod() { double epsilon = 1e-7; unsigned int order = (unsigned int)(coefficients[N][0] + 0.5); POLYNOMIAL p(coefficients[N]+1, order); p.setEpsilon(epsilon); vigra::ArrayVector<std::complex<double> > roots; should(polynomialRootsEigenvalueMethod(p, roots)); shouldEqual(roots.size(), order); for(unsigned int i = 0; i<roots.size(); ++i) { shouldEqualTolerance(roots[i].real(), reference[N][i+1].real(), epsilon); shouldEqualTolerance(roots[i].imag(), reference[N][i+1].imag(), epsilon); } } }; struct HighOrderPolynomialTest { void testPolynomial() { unsigned int order = 80; double epsilon = 1e-12; vigra::ArrayVector<double> coeffs(order+1, 0.0); coeffs[0] = -1.0; coeffs[order] = 1.0; vigra::Polynomial<double> p(coeffs.begin(), order); vigra::ArrayVector<std::complex<double> > roots; should(vigra::polynomialRoots(p, roots)); shouldEqual(roots.size(), order); for(unsigned int i = 0; i<roots.size(); ++i) { shouldEqualTolerance(std::abs(roots[i]), 1.0, epsilon); C r = p(roots[i]); shouldEqualTolerance(r.real(), 0.0, epsilon); shouldEqualTolerance(r.imag(), 0.0, epsilon); } vigra::ArrayVector<double> rroots; should(polynomialRealRoots(p, rroots)); shouldEqual(rroots.size(), 2u); shouldEqualTolerance(rroots[0], -1.0, epsilon); shouldEqualTolerance(rroots[1], 1.0, epsilon); } void testPolynomialEigenvalueMethod() { unsigned int order = 80; double epsilon = 1e-12; vigra::ArrayVector<double> coeffs(order+1, 0.0); coeffs[0] = -1.0; coeffs[order] = 1.0; vigra::Polynomial<double> p(coeffs.begin(), order); vigra::ArrayVector<std::complex<double> > roots; should(vigra::polynomialRootsEigenvalueMethod(p, roots)); shouldEqual(roots.size(), order); for(unsigned int i = 0; i<roots.size(); ++i) { shouldEqualTolerance(std::abs(roots[i]), 1.0, epsilon); C r = p(roots[i]); shouldEqualTolerance(r.real(), 0.0, epsilon); shouldEqualTolerance(r.imag(), 0.0, epsilon); } vigra::ArrayVector<double> rroots; should(polynomialRealRootsEigenvalueMethod(p, rroots)); shouldEqual(rroots.size(), 2u); shouldEqualTolerance(rroots[0], -1.0, epsilon); shouldEqualTolerance(rroots[1], 1.0, epsilon); } }; template <int ORDER> struct SplineTest { typedef vigra::BSpline<ORDER, double> BS; typedef vigra::BSplineBase<ORDER, double> BSB; BS spline; BSB splineBase; void testValues() { double r = spline.radius(); shouldEqual(r, splineBase.radius()); for(int d = 0; d <= ORDER+1; ++d) { for(double x = -r-0.5; x <= r+0.5; x += 0.5) shouldEqualTolerance(spline(x, d), splineBase(x, d), 1e-15); } } void testFixedPointValues() { double r = spline.radius(); shouldEqual(r, splineBase.radius()); for(double x = -r-0.5; x <= r+0.5; x += 0.5) { vigra::FixedPoint<11,20> fpx20(x); vigra::FixedPoint<11,15> fpx15(x); should(vigra::abs(vigra::fixed_point_cast<double>(spline(fpx20)) - spline(x)) < 1e-6); should(vigra::abs(vigra::fixed_point_cast<double>(spline(fpx15)) - spline(x)) < 4e-5); } } void testPrefilterCoefficients() { int n = ORDER / 2; vigra::ArrayVector<double> const & ps = spline.prefilterCoefficients(); vigra::ArrayVector<double> const & psb = splineBase.prefilterCoefficients(); if(n == 0) { shouldEqual(ps.size(), 0u); shouldEqual(psb.size(), 0u); } else { vigra::ArrayVector<double> & psb1 = const_cast<vigra::ArrayVector<double> &>(psb); std::sort(psb1.begin(), psb1.end()); for(int i = 0; i < n; ++i) shouldEqualTolerance(ps[i], psb[i], 1e-14); } } void testWeightMatrix() { int n = ORDER + 1; typename BS::WeightMatrix & ws = BS::weights(); typename BSB::WeightMatrix & wsb = BSB::weights(); for(int d = 0; d < n; ++d) for(int i = 0; i < n; ++i) shouldEqualTolerance(ws[d][i], wsb[d][i], 1e-14); } }; struct FunctionsTest { void testGaussians() { vigra::Gaussian<double> g, g1(2.0, 1), g2(1.0, 2), g3(2.0, 3), g4(2.0, 4), g5(2.0, 5); double epsilon = 1e-15; shouldEqual(g.derivativeOrder(), 0u); shouldEqual(g.sigma(), 1.0); shouldEqualTolerance(g(0.0), 0.3989422804014327, epsilon); shouldEqualTolerance(g(0.5), 0.35206532676429952, epsilon); shouldEqualTolerance(g(1.0), 0.24197072451914337, epsilon); shouldEqualTolerance(g(-1.0), 0.24197072451914337, epsilon); shouldEqual(g1.derivativeOrder(), 1u); shouldEqual(g1.sigma(), 2.0); shouldEqualTolerance(g1(0.0), 0, epsilon); shouldEqualTolerance(g1(0.5), -0.024166757300178077, epsilon); shouldEqualTolerance(g1(1.0), -0.044008165845537441, epsilon); shouldEqualTolerance(g1(-1.0), 0.044008165845537441, epsilon); shouldEqual(g2.derivativeOrder(), 2u); shouldEqual(g2.sigma(), 1.0); shouldEqualTolerance(g2(0.0), -0.3989422804014327, epsilon); shouldEqualTolerance(g2(0.5), -0.26404899507322466, epsilon); shouldEqualTolerance(g2(1.0), 0, epsilon); shouldEqualTolerance(g2(-1.0), 0, epsilon); shouldEqualTolerance(g2(1.5), 0.16189699458236467, epsilon); shouldEqualTolerance(g2(-1.5), 0.16189699458236467, epsilon); shouldEqual(g3.derivativeOrder(), 3u); shouldEqual(g3.sigma(), 2.0); shouldEqualTolerance(g3(0.0), 0, epsilon); shouldEqualTolerance(g3(0.5), 0.017747462392318277, epsilon); shouldEqualTolerance(g3(1.0), 0.030255614018806987, epsilon); shouldEqualTolerance(g3(-1.0), -0.030255614018806987, epsilon); shouldEqualTolerance(g3(2.0*VIGRA_CSTD::sqrt(3.0)), 0, epsilon); shouldEqualTolerance(g3(-2.0*VIGRA_CSTD::sqrt(3.0)), 0, epsilon); shouldEqualTolerance(g4(0.0), 0.037400838787634318, epsilon); shouldEqualTolerance(g4(1.0), 0.017190689783413062, epsilon); shouldEqualTolerance(g4(-1.0), 0.017190689783413062, epsilon); shouldEqualTolerance(g4(1.483927568605452), 0, epsilon); shouldEqualTolerance(g4(4.668828436677955), 0, epsilon); shouldEqualTolerance(g5(0.0), 0, epsilon); shouldEqualTolerance(g5(1.0), -0.034553286464660257, epsilon); shouldEqualTolerance(g5(-1.0), 0.034553286464660257, epsilon); shouldEqualTolerance(g5(2.711252359948531), 0, epsilon); shouldEqualTolerance(g5(5.713940027745611), 0, epsilon); } void testSpecialIntegerFunctions() { for(vigra::Int32 i = 0; i < 1024; ++i) { shouldEqual(vigra::sqrti(i), (vigra::Int32)vigra::floor(vigra::sqrt((double)i))); } shouldEqual(vigra::roundi(0.0), 0); shouldEqual(vigra::roundi(1.0), 1); shouldEqual(vigra::roundi(1.1), 1); shouldEqual(vigra::roundi(1.6), 2); shouldEqual(vigra::roundi(-1.0), -1); shouldEqual(vigra::roundi(-1.1), -1); shouldEqual(vigra::roundi(-1.6), -2); vigra::UInt32 roundPower2[] = {0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 0xffff, 0x7fffffff, 0x80000000, 0x80000001, 0xffffffff}; vigra::UInt32 floorResult[] = {0, 1, 2, 2, 4, 4, 4, 8, 8, 8, 16, 0x8000, 0x40000000, 0x80000000, 0x80000000, 0x80000000}; vigra::UInt32 ceilResult[] = {0, 1, 2, 4, 4, 8, 8, 8, 16, 16, 16, 0x10000, 0x80000000, 0x80000000, 0, 0}; for(unsigned int i = 0; i < sizeof(roundPower2) / sizeof(vigra::UInt32); ++i) { shouldEqual(vigra::floorPower2(roundPower2[i]), floorResult[i]); shouldEqual(vigra::ceilPower2(roundPower2[i]), ceilResult[i]); } for(vigra::Int32 k=0; k<32; ++k) { shouldEqual(vigra::log2i(1 << k), k); shouldEqual(vigra::log2i((1 << k) + 1), k == 0 ? 1 : k); shouldEqual(vigra::log2i((1 << k) - 1), k-1); } should(vigra::even(0)); should(!vigra::odd(0)); should(!vigra::even(1)); should(vigra::odd(1)); should(vigra::even(2)); should(!vigra::odd(2)); should(!vigra::even(-1)); should(vigra::odd(-1)); should(vigra::even(-2)); should(!vigra::odd(-2)); } void testSpecialFunctions() { shouldEqualTolerance(vigra::ellipticIntegralE(M_PI / 2.0, 0.0), M_PI / 2.0, 1e-14); shouldEqualTolerance(vigra::ellipticIntegralF(0.3, 0.3), 0.30039919311549118, 1e-14); shouldEqualTolerance(vigra::ellipticIntegralE(0.3, 0.3), 0.29960175507025716, 1e-14); shouldEqualTolerance(vigra::erf(0.3), 0.32862675945912745, 1e-7); should(vigra::noncentralChi2CDFApprox(200, 0.0, 200.0) > 0.5); should(vigra::noncentralChi2CDFApprox(200, 0.0, 199.0) < 0.5); should(vigra::noncentralChi2CDF(200, 0.0, 200.0) > 0.5); should(vigra::noncentralChi2CDF(200, 0.0, 199.0) < 0.5); shouldEqualTolerance(vigra::noncentralChi2CDF(2, 2.0, 2.0), 0.34574583872316456, 1e-7); shouldEqualTolerance(vigra::noncentralChi2(2, 2.0, 2.0), 0.154254161276835, 1e-7); shouldEqualTolerance(vigra::noncentralChi2CDF(3, 2.0, 2.0), 0.22073308707450343, 1e-7); shouldEqualTolerance(vigra::noncentralChi2(3, 2.0, 2.0), 0.13846402271767755, 1e-7); shouldEqualTolerance(vigra::noncentralChi2CDFApprox(2, 2.0, 2.0), 0.34574583872316456, 1e-1); shouldEqualTolerance(vigra::noncentralChi2CDFApprox(3, 2.0, 2.0), 0.22073308707450343, 1e-1); for(double x = -4.0; x <= 4.0; x += 1.0) { shouldEqual(vigra::sin_pi(x), 0.0); shouldEqual(vigra::cos_pi(x+0.5), 0.0); } for(double x = -4.5; x <= 4.5; x += 2.0) { shouldEqual(vigra::sin_pi(x), -1.0); shouldEqual(vigra::cos_pi(x+0.5), 1.0); } for(double x = -3.5; x <= 4.5; x += 2.0) { shouldEqual(vigra::sin_pi(x), 1.0); shouldEqual(vigra::cos_pi(x+0.5), -1.0); } for(double x = -4.0; x <= 4.0; x += 0.0625) { shouldEqualTolerance(vigra::sin_pi(x), std::sin(M_PI*x), 1e-14); shouldEqualTolerance(vigra::cos_pi(x), std::cos(M_PI*x), 1e-14); } shouldEqual(vigra::gamma(4.0), 6.0); shouldEqualTolerance(vigra::gamma(0.1), 9.5135076986687306, 1e-15); shouldEqualTolerance(vigra::gamma(3.2), 2.4239654799353683, 1e-15); shouldEqualTolerance(vigra::gamma(170.2), 1.1918411166366696e+305, 1e-15); shouldEqualTolerance(vigra::gamma(-0.1), -10.686287021193193, 1e-14); shouldEqualTolerance(vigra::gamma(-3.2), 0.689056412005979, 1e-14); shouldEqualTolerance(vigra::gamma(-170.2), -2.6348340538196879e-307, 1e-14); try { vigra::gamma(0.0); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} try { vigra::gamma(-1.0); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} shouldEqual(vigra::loggamma(1.0), 0.0); shouldEqual(vigra::loggamma(2.0), 0.0); shouldEqualTolerance(vigra::loggamma(4.0e-22), 49.2705776847491144296, 1e-15); shouldEqualTolerance(vigra::loggamma(0.1), 2.2527126517342055401, 1e-15); shouldEqualTolerance(vigra::loggamma(0.3), 1.0957979948180756047, 1e-15); shouldEqualTolerance(vigra::loggamma(0.8), 0.15205967839983755563, 1e-15); shouldEqualTolerance(vigra::loggamma(1.1), -0.049872441259839757344, 1e-15); shouldEqualTolerance(vigra::loggamma(1.3), -0.10817480950786048655, 1e-15); shouldEqualTolerance(vigra::loggamma(1.8), -0.071083872914372153717, 1e-15); shouldEqualTolerance(vigra::loggamma(3.0), 0.69314718055994528623, 1e-15); shouldEqualTolerance(vigra::loggamma(3.1), 0.78737508327386251938, 1e-15); shouldEqualTolerance(vigra::loggamma(4.0), 1.79175946922805500081, 1e-15); shouldEqualTolerance(vigra::loggamma(8.0), 8.5251613610654143002, 1e-15); shouldEqualTolerance(vigra::loggamma(1000.0), 5905.2204232091812118261, 1e-15); shouldEqualTolerance(vigra::loggamma(1000.2), 5906.6018942569799037, 1e-15); shouldEqualTolerance(vigra::loggamma(2.8e+17), 1.096859847946237952e+19, 1e-15); shouldEqualTolerance(vigra::loggamma(2.9e+17), 1.1370510622188449792e+19, 1e-15); shouldEqualTolerance(vigra::loggamma(5.7646075230342349e+17), 2.2998295812288974848e+19, 1e-15); try { vigra::loggamma(0.0); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} try { vigra::loggamma(-1.0); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} double args[5] = {0.0, 1.0, 0.7, -0.7, -1.0}; for(int i=0; i<5; ++i) { double x = args[i], x2 = x*x; shouldEqualTolerance(vigra::legendre(0, x), 1.0, 1e-15); shouldEqualTolerance(vigra::legendre(1, x), x, 1e-15); shouldEqualTolerance(vigra::legendre(2, x), 0.5*(3.0*x2-1.0), 1e-15); shouldEqualTolerance(vigra::legendre(3, x), 0.5*x*(5.0*x2-3.0), 1e-15); shouldEqualTolerance(vigra::legendre(0, 0, x), 1.0, 1e-15); shouldEqualTolerance(vigra::legendre(1, 0, x), x, 1e-15); shouldEqualTolerance(vigra::legendre(1, 1, x), -std::sqrt(1.0-x2), 1e-15); shouldEqualTolerance(vigra::legendre(2, 0, x), 0.5*(3.0*x2-1.0), 1e-15); shouldEqualTolerance(vigra::legendre(2, 1, x), -3.0*x*std::sqrt(1.0-x2), 1e-15); shouldEqualTolerance(vigra::legendre(2, 2, x), 3.0*(1.0-x2), 1e-15); shouldEqualTolerance(vigra::legendre(4, 2, x), 7.5*(7.0*x2-1.0)*(1.0-x2), 1e-15); shouldEqualTolerance(vigra::legendre(1, -1, x), -vigra::legendre(1, 1, x) / 2.0, 1e-15); shouldEqualTolerance(vigra::legendre(2, -1, x), -vigra::legendre(2, 1, x) / 6.0, 1e-15); shouldEqualTolerance(vigra::legendre(2, -2, x), vigra::legendre(2, 2, x) / 24.0, 1e-15); } } void testBessel() { // Reference values computed to 16 digits with Python.mpmath. // Casual comparison showed no difference to Mathematica's results. double x[] = { 1.0, 4.0, 6.0 }; double besseljnref[] = { 7.6519768655796649e-01, -3.9714980986384740e-01, 1.5064525725099692e-01, 5.7672480775687329e-01, -3.2757913759146523e-01, -4.6828234823458334e-03, 4.8609126058589103e-01, -2.4287320996018547e-01, -1.1299172042407525e-01, 4.3017147387562193e-01, -1.6755558799533424e-01, -1.8093519033665686e-01, 3.9123236045864818e-01, -1.0535743487538894e-01, -2.1960268610200856e-01, 3.6208707488717234e-01, -5.5038855669513713e-02, -2.3828585178317879e-01, 3.3919660498317961e-01, -1.4458842084785106e-02, -2.4372476722886663e-01, 3.2058907797982628e-01, 1.8376032647858614e-02, -2.4057094958616052e-01, 3.0506707225300012e-01, 4.5095329080457235e-02, -2.3197310306707983e-01, 2.9185568526512001e-01, 6.6976198673670620e-02, -2.2004622511384700e-01, 2.8042823052537585e-01, 8.5006705446061023e-02, -2.0620569442259729e-01, 2.7041248255096445e-01, 9.9950477050301592e-02, -1.9139539469541733e-01, 2.6153687541034509e-01, 1.1240023492610679e-01, -1.7624117645477547e-01, 2.5359797330294920e-01, 1.2281915265293869e-01, -1.6115376768165826e-01, 2.4643993656993257e-01, 1.3157198580936999e-01, -1.4639794400255970e-01 }; double besselynref[] = { 8.8256964215676956e-02, -1.6940739325064992e-02, -2.8819468398157916e-01, -1.0703243154093754e-01, 1.4786314339122683e-01, -3.0266723702418485e-01, -1.6040039348492374e-01, 2.2985790254811306e-01, -2.6303660482037811e-01, -1.8202211595348500e-01, 2.6808060304231507e-01, -2.0509487811877961e-01, -1.9214228737369318e-01, 2.8294322431117191e-01, -1.4494951186809379e-01, -1.9706088806443733e-01, 2.8511777841103764e-01, -8.9252841434580163e-02, -1.9930679029227036e-01, 2.8035255955745608e-01, -4.0297251103395833e-02, -2.0006390460040860e-01, 2.7184139484930947e-01, 1.5698795407253514e-03, -1.9994686666043449e-01, 2.6140472921203017e-01, 3.6815736940746704e-02, -1.9929926580524435e-01, 2.5009898312668521e-01, 6.6197858895869655e-02, -1.9832403085028555e-01, 2.3854272714494473e-01, 9.0526604143921052e-02, -1.9714613354518651e-01, 2.2709735924007149e-01, 1.1056356972736049e-01, -1.9584504763522584e-01, 2.1597027298252575e-01, 1.2698414345087472e-01, -1.9447256680104227e-01, 2.0527533641239212e-01, 1.4036965442780550e-01, -1.9306306446008192e-01, 1.9506914688206353e-01, 1.5121244335755843e-01 }; for(int n = 0; n < 15; ++n) { if(n == 0) shouldEqual(vigra::besselJ(n, 0.0), 1.0); else shouldEqual(vigra::besselJ(n, 0.0), 0.0); should(vigra::besselY(n, 0.0) == -std::numeric_limits<double>::infinity()); for(int k=0; k<3; ++k) { double f = vigra::odd(n) ? -1.0 : 1.0; double eps = 1e-14; shouldEqualTolerance(vigra::besselJ(n, x[k]+n) - besseljnref[k+3*n], 0.0, eps); shouldEqualTolerance(vigra::besselJ(-n, x[k]+n) - f*besseljnref[k+3*n], 0.0, eps); shouldEqualTolerance(vigra::besselY(n, x[k]+n) - besselynref[k+3*n], 0.0, eps); shouldEqualTolerance(vigra::besselY(-n, x[k]+n) - f*besselynref[k+3*n], 0.0, eps); } } } void closeAtToleranceTest() { double a = 0.0, b = vigra::NumericTraits<double>::epsilon(), c = 1000.0, d = 1000.1; using vigra::closeAtTolerance; should(closeAtTolerance(a, b)); should(closeAtTolerance(c, c + b)); should(closeAtTolerance(c, d, 1.0)); should(closeAtTolerance(-a, -b)); should(closeAtTolerance(-c, -c + b)); should(closeAtTolerance(-c, -d, 1.0)); should(!closeAtTolerance(c, -c)); should(!closeAtTolerance(a, c)); should(!closeAtTolerance(c, d)); should(!closeAtTolerance(-a, -c)); should(!closeAtTolerance(-c, -d)); } void testArgMinMax() { using namespace vigra; using namespace vigra::functor; double data[] = {1.0, 5.0, 3.0, 2.0, -2.0, 4.0}; double *end = data + 6; shouldEqual(argMin(data, end), data+4); shouldEqual(argMax(data, end), data+1); shouldEqual(argMinIf(data, end, Arg1() > Param(0.0)), data); shouldEqual(argMinIf(data, end, Arg1() > Param(5.0)), end); shouldEqual(argMaxIf(data, end, Arg1() < Param(5.0)), data+5); shouldEqual(argMaxIf(data, end, Arg1() < Param(-2.0)), end); } void testAlgorithms() { static const int size = 6; int index[size]; vigra::linearSequence(index, index+size); int indexref[size] = {0, 1, 2, 3, 4, 5}; shouldEqualSequence(index, index+size, indexref); vigra::linearSequence(index, index+size, 5, 5); int indexref2[size] = {5, 10, 15, 20, 25, 30}; shouldEqualSequence(index, index+size, indexref2); double data[size] = {1.0, 5.0, 3.0, 2.0, -2.0, 4.0}; vigra::indexSort(data, data+size, index, std::greater<double>()); int sortref[size] = {1, 5, 2, 3, 0, 4}; shouldEqualSequence(index, index+size, sortref); vigra::indexSort(data, data+size, index); int sortref2[size] = {4, 0, 3, 2, 5, 1}; shouldEqualSequence(index, index+size, sortref2); double res[size]; vigra::applyPermutation(index, index+size, data, res); double ref[size] = {-2.0, 1.0, 2.0, 3.0, 4.0, 5.0 }; shouldEqualSequence(res, res+size, ref); int inverse[size]; vigra::inversePermutation(index, index+size, inverse); int inverseref[size] = {1, 5, 3, 2, 0, 4}; shouldEqualSequence(inverse, inverse+size, inverseref); vigra::applyPermutation(inverse, inverse+size, ref, res); shouldEqualSequence(res, res+size, data); } void testChecksum() { std::string s(""); vigra::UInt32 crc = vigra::checksum(s.c_str(), s.size()); shouldEqual(crc, 0u); s = "hello world"; crc = vigra::checksum(s.c_str(), s.size()); shouldEqual(crc, 222957957u); s = "hallo world"; crc = vigra::checksum(s.c_str(), s.size()); shouldEqual(crc, 77705727u); int split = 5; std::string s1 = s.substr(0, split), s2 = s.substr(split); crc = vigra::checksum(s1.c_str(), s1.size()); crc = vigra::concatenateChecksum(crc, s2.c_str(), s2.size()); shouldEqual(crc, 77705727u); const int size = 446; char t[size+1] = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, " "sed do eiusmod tempor incididunt ut labore et dolore magna " "aliqua. Ut enim ad minim veniam, quis nostrud exercitation " "ullamco laboris nisi ut aliquip ex ea commodo consequat. " "Duis aute irure dolor in reprehenderit in voluptate velit " "esse cillum dolore eu fugiat nulla pariatur. Excepteur " "sint occaecat cupidatat non proident, sunt in culpa qui " "officia deserunt mollit anim id est laborum."; crc = vigra::checksum(t, size); shouldEqual(crc, 2408722991u); for(split = 64; split < 80; ++split) // check alignment { crc = vigra::checksum(t, split); crc = vigra::concatenateChecksum(crc, t+split, size-split); shouldEqual(crc, 2408722991u); } } void testClebschGordan() { using vigra::clebschGordan; shouldEqualTolerance(clebschGordan(0.5, 0.5, 0.5, 0.5, 1.0, 1.0), std::sqrt(1.0), 1e-15); shouldEqualTolerance(clebschGordan(0.5, 0.5, 0.5, -0.5, 1.0, 0.0), std::sqrt(0.5), 1e-15); shouldEqualTolerance(clebschGordan(0.5, -0.5, 0.5, 0.5, 1.0, 0.0), std::sqrt(0.5), 1e-15); shouldEqualTolerance(clebschGordan(0.5, 0.5, 0.5, -0.5, 0.0, 0.0), std::sqrt(0.5), 1e-15); shouldEqualTolerance(clebschGordan(0.5, -0.5, 0.5, 0.5, 0.0, 0.0), -std::sqrt(0.5), 1e-15); shouldEqualTolerance(clebschGordan(2.0, 2.0, 0.5, 0.5, 2.5, 2.5), std::sqrt(1.0), 1e-15); shouldEqualTolerance(clebschGordan(2.0, 2.0, 0.5, -0.5, 2.5, 1.5), std::sqrt(0.2), 1e-15); shouldEqualTolerance(clebschGordan(2.0, 1.0, 0.5, 0.5, 2.5, 1.5), std::sqrt(0.8), 1e-15); shouldEqualTolerance(clebschGordan(2.0, 2.0, 0.5, -0.5, 1.5, 1.5), std::sqrt(0.8), 1e-15); shouldEqualTolerance(clebschGordan(2.0, 1.0, 0.5, 0.5, 1.5, 1.5), -std::sqrt(0.2), 1e-15); } }; struct RationalTest { typedef vigra::Rational<int> R; void testGcdLcm() { shouldEqual(vigra::gcd(24, 18), 6); shouldEqual(vigra::lcm(6, 4), 12); shouldEqual(vigra::gcd(18, 24), 6); shouldEqual(vigra::lcm(4, 6), 12); } void testOStreamShifting() { std::ostringstream out; out << R(1,2); out << "Testing.." << R(42,23) << 3.141592653589793238 << std::endl; } void testOperators() { shouldEqual(R(3,4), R(3,4)); shouldEqual(-R(3,4), R(-3,4)); shouldEqual(R(3,4) + R(12,6), R(11,4)); shouldEqual(R(3,4) - R(12,6), R(-5,4)); shouldEqual(R(3,4) * R(12,6), R(3,2)); shouldEqual(R(3,4) / R(12,6), R(3,8)); shouldEqual(abs(R(-3,4)), R(3,4)); shouldEqual(norm(R(-3,4)), R(3,4)); shouldEqual(squaredNorm(R(-3,4)), R(9,16)); should(R(3,4) == R(9,12)); should(R(3,4) != R(12,6)); should(R(3,4) < R(12,6)); should(R(19,4) > R(12,6)); should(R(3,4) <= R(12,6)); should(R(19,4) >= R(12,6)); shouldEqual(R(3,4) + 2, R(11,4)); shouldEqual(R(3,4) - 2, R(-5,4)); shouldEqual(R(3,4) * 2, R(3,2)); shouldEqual(R(3,4) / 2, R(3,8)); should(!(R(3,4) == 2)); should(R(3,4) != 2); should(R(3,4) < 2); should(R(19,4) > 2); should(R(3,4) <= 2); should(R(19,4) >= 2); shouldEqual(2 + R(3,4), R(11,4)); shouldEqual(2 - R(3,4), R(5,4)); shouldEqual(2 * R(3,4), R(3,2)); shouldEqual(2 / R(3,4), R(8, 3)); should(!(2 == R(3,4))); should(2 != R(3,4)); should(2 > R(3,4)); should(2 < R(19,4)); should(2 >= R(3,4)); should(2 <= R(19,4)); } void testConversion() { shouldEqual(vigra::rational_cast<R>(R(3,2)), R(3,2)); shouldEqual(vigra::rational_cast<int>(R(3,2)), 1); shouldEqual(vigra::rational_cast<double>(R(3,2)), 1.5); shouldEqual(vigra::rational_cast<double>(1.5), 1.5); shouldEqual(R(vigra::Rational<short>((short)-2, (short)-4)), R(1,2)); shouldEqual(R(3.5, 1e-4), R(7,2)); shouldEqual(R(-3.5, 1e-4), R(-7,2)); shouldEqual(R(0.123, 1e-4), R(123,1000)); shouldEqual(R(-0.123, 1e-4), R(-123,1000)); shouldEqual(R(0.123456, 1e-4), R(1235,10000)); shouldEqual(R(0.123432, 1e-4), R(1234,10000)); shouldEqual(R(-0.123456, 1e-4), R(-1235,10000)); shouldEqual(R(-0.123432, 1e-4), R(-1234,10000)); } void testFunctions() { shouldEqual(pow(R(1,2),2), R(1,4)); shouldEqual(pow(R(2),-2), R(1,4)); shouldEqual(pow(R(-1,2),2), R(1,4)); shouldEqual(pow(R(-2),-2), R(1,4)); shouldEqual(pow(R(-1,2),3), R(-1,8)); shouldEqual(pow(R(-2),-3), R(-1,8)); shouldEqual(pow(R(3),0), R(1)); shouldEqual(pow(R(0),3), R(0)); shouldEqual(pow(R(0),0), R(1)); should(pow(R(0),-3).is_pinf()); should(pow(R(1,0, false), 1).is_pinf()); should(pow(R(-1,0, false), 1).is_ninf()); shouldEqual(pow(R(1,0, false), -1), R(0)); shouldEqual(pow(R(-1,0, false), -1), R(0)); try { pow(R(1,0, false), 0); failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { pow(R(-1,0, false), 0); failTest("No exception thrown"); } catch(vigra::bad_rational &) {} shouldEqual(floor(R(2)), R(2)); shouldEqual(floor(R(3,2)), R(1)); shouldEqual(floor(R(1,2)), R(0)); shouldEqual(floor(R(-1,2)), R(-1)); shouldEqual(floor(R(1,-2)), R(-1)); shouldEqual(floor(R(-3,2)), R(-2)); shouldEqual(floor(R(-2)), R(-2)); shouldEqual(floor(R(1,0,false)), R(1,0,false)); shouldEqual(floor(R(-1,0,false)), R(-1,0,false)); shouldEqual(ceil(R(2)), R(2)); shouldEqual(ceil(R(3,2)), R(2)); shouldEqual(ceil(R(1,2)), R(1)); shouldEqual(ceil(R(-1,2)), R(0)); shouldEqual(ceil(R(1,-2)), R(0)); shouldEqual(ceil(R(-3,2)), R(-1)); shouldEqual(ceil(R(-2)), R(-2)); shouldEqual(ceil(R(1,0,false)), R(1,0,false)); shouldEqual(ceil(R(-1,0,false)), R(-1,0,false)); } void testInf() { R inf(2,0); R ninf(-2,0); should(inf.is_inf()); should(inf.is_pinf()); should(!inf.is_ninf()); should(ninf.is_inf()); should(ninf.is_ninf()); should(!ninf.is_pinf()); shouldEqual(inf.numerator(), 1); shouldEqual(ninf.numerator(), -1); should((inf + R(1)).is_pinf()); should((inf + R(0)).is_pinf()); should((inf + R(-1)).is_pinf()); should((ninf + R(1)).is_ninf()); should((ninf + R(0)).is_ninf()); should((ninf + R(-1)).is_ninf()); should((inf + 1).is_pinf()); should((inf + 0).is_pinf()); should((inf + (-1)).is_pinf()); should((ninf + 1).is_ninf()); should((ninf + 0).is_ninf()); should((ninf + (-1)).is_ninf()); should((inf + inf).is_pinf()); should((ninf + ninf).is_ninf()); shouldEqual((inf + R(3)).numerator(), 1); shouldEqual((ninf + R(3)).numerator(), -1); should((inf - R(1)).is_pinf()); should((inf - R(0)).is_pinf()); should((inf - R(-1)).is_pinf()); should((ninf - R(1)).is_ninf()); should((ninf - R(0)).is_ninf()); should((ninf - R(-1)).is_ninf()); should((inf - 1).is_pinf()); should((inf - 0).is_pinf()); should((inf - (-1)).is_pinf()); should((ninf - 1).is_ninf()); should((ninf - 0).is_ninf()); should((ninf - (-1)).is_ninf()); should((inf - ninf).is_pinf()); should((ninf - inf).is_ninf()); shouldEqual((inf - R(3)).numerator(), 1); shouldEqual((ninf - R(3)).numerator(), -1); should((inf * R(1)).is_pinf()); should((inf * R(-1)).is_ninf()); should((ninf * R(1)).is_ninf()); should((ninf * R(-1)).is_pinf()); should((inf * 1).is_pinf()); should((inf * (-1)).is_ninf()); should((ninf * 1).is_ninf()); should((ninf * (-1)).is_pinf()); should((inf * inf).is_pinf()); should((inf * ninf).is_ninf()); should((ninf * inf).is_ninf()); should((ninf * ninf).is_pinf()); shouldEqual((inf * R(3)).numerator(), 1); shouldEqual((ninf * R(3)).numerator(), -1); shouldEqual((inf * R(-3)).numerator(), -1); shouldEqual((ninf * R(-3)).numerator(), 1); should((inf / R(1)).is_pinf()); should((inf / R(0)).is_pinf()); should((inf / R(-1)).is_ninf()); should((ninf / R(1)).is_ninf()); should((ninf / R(0)).is_ninf()); should((ninf / R(-1)).is_pinf()); shouldEqual(R(1) / inf, R(0)); shouldEqual(R(-1) / inf, R(0)); shouldEqual(R(1) / ninf, R(0)); shouldEqual(R(-1) / ninf, R(0)); should((inf / 1).is_pinf()); should((inf / 0).is_pinf()); should((inf / (-1)).is_ninf()); should((ninf / 1).is_ninf()); should((ninf / 0).is_ninf()); should((ninf / (-1)).is_pinf()); shouldEqual(2 / inf, R(0)); shouldEqual((-2) / inf, R(0)); shouldEqual(2 / ninf, R(0)); shouldEqual((-2) / ninf, R(0)); shouldEqual((2 / inf).denominator(), 1); shouldEqual(((-2) / inf).denominator(), 1); shouldEqual((2 / ninf).denominator(), 1); shouldEqual(((-2) / ninf).denominator(), 1); shouldEqual((inf / R(3)).numerator(), 1); shouldEqual((ninf / R(3)).numerator(), -1); shouldEqual((inf / R(-3)).numerator(), -1); shouldEqual((ninf / R(-3)).numerator(), 1); should(inf == inf); should(!(inf != inf)); should(!(inf < inf)); should(inf <= inf); should(!(inf > inf)); should(inf >= inf); should(ninf == ninf); should(!(ninf != ninf)); should(!(ninf < ninf)); should(ninf <= ninf); should(!(ninf > ninf)); should(ninf >= ninf); should(inf != ninf); should(ninf != inf); should(inf > ninf); should(ninf < inf); should(!(inf < ninf)); should(!(ninf > inf)); should(inf != 0); should(ninf != 0); should(inf > 0); should(inf >= 0); should(ninf < 0); should(ninf <= 0); should(!(0 < ninf)); should(!(0 > inf)); should(!(0 <= ninf)); should(!(0 >= inf)); should(inf != R(1)); should(ninf != R(1)); should(inf > R(1)); should(inf >= R(1)); should(ninf < R(1)); should(ninf <= R(1)); should(!(R(1) < ninf)); should(!(R(1) > inf)); should(!(R(1) <= ninf)); should(!(R(1) >= inf)); try { inf + ninf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { ninf + inf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { inf - inf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { ninf - ninf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { inf * R(0); failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { ninf * R(0); failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { R(0) * inf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { R(0) * ninf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { inf * 0; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { ninf * 0; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { 0 * inf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { 0 * ninf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { inf / inf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { inf / ninf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { ninf / inf; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { R(0) / R(0); failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { R(0) / 0; failTest("No exception thrown"); } catch(vigra::bad_rational &) {} try { 0 / R(0); failTest("No exception thrown"); } catch(vigra::bad_rational &) {} } }; struct QuaternionTest { typedef vigra::Quaternion<double> Q; typedef Q::Vector V; void testContents() { Q q(1.0, 2.0, 3.0, 4.0), q0, q1(-1.0), q2(q), q3(q.w(), q.v()); shouldEqual(q.w(), 1.0); shouldEqual(q.v(), V(2.0, 3.0, 4.0)); shouldEqual(q0.w(), 0.0); shouldEqual(q0.v(), V(0.0, 0.0, 0.0)); shouldEqual(q1.w(), -1.0); shouldEqual(q1.v(), V(0.0, 0.0, 0.0)); shouldEqual(q2.w(), 1.0); shouldEqual(q2.v(), V(2.0, 3.0, 4.0)); shouldEqual(q3.w(), 1.0); shouldEqual(q3.v(), V(2.0, 3.0, 4.0)); shouldEqual(q[0], 1.0); shouldEqual(q[1], 2.0); shouldEqual(q[2], 3.0); shouldEqual(q[3], 4.0); shouldEqual(q.x(), 2.0); shouldEqual(q.y(), 3.0); shouldEqual(q.z(), 4.0); should(q == q2); should(q1 != q2); q2 = q1; shouldEqual(q2.w(), -1.0); shouldEqual(q2.v(), V(0.0, 0.0, 0.0)); should(q != q2); should(q1 == q2); q3 = 10.0; shouldEqual(q3.w(), 10.0); shouldEqual(q3.v(), V(0.0, 0.0, 0.0)); q2.setW(-2.0); shouldEqual(q2.w(), -2.0); shouldEqual(q2.v(), V(0.0, 0.0, 0.0)); q2.setV(V(5.0, 6.0, 7.0)); shouldEqual(q2.w(), -2.0); shouldEqual(q2.v(), V(5.0, 6.0, 7.0)); q3.setV(5.0, 6.0, 7.0); shouldEqual(q3.w(), 10.0); shouldEqual(q3.v(), V(5.0, 6.0, 7.0)); q3.setX(2.0); q3.setY(3.0); q3.setZ(4.0); shouldEqual(q3.w(), 10.0); shouldEqual(q3.v(), V(2.0, 3.0, 4.0)); shouldEqual(q.squaredMagnitude(), 30.0); shouldEqual(squaredNorm(q), 30.0); shouldEqualTolerance(q.magnitude(), std::sqrt(30.0), 1e-15); shouldEqualTolerance(norm(q), std::sqrt(30.0), 1e-15); shouldEqual(norm(q), abs(q)); } void testStreamIO() { std::ostringstream out; Q q(1.0, 2.0, 3.0, 4.0); out << q; shouldEqual(out.str(), "1 2 3 4"); std::istringstream in; in.str("10 11 12 13"); in >> q; shouldEqual(q, Q(10.0, 11.0, 12.0, 13.0)); } void testOperators() { Q q(1.0, 2.0, 3.0, 4.0); shouldEqual(+q, q); shouldEqual(-q, Q(-1,-2,-3,-4)); shouldEqual(q+q, Q(2,4,6,8)); shouldEqual(q+2.0, Q(3,2,3,4)); shouldEqual(2.0+q, Q(3,2,3,4)); shouldEqual(Q(2,4,6,8) - q, q); shouldEqual(q-2.0, Q(-1,2,3,4)); shouldEqual(2.0-q, Q(1,-2,-3,-4)); shouldEqual(Q(1,0,0,0)*Q(1,0,0,0), Q(1,0,0,0)); shouldEqual(Q(0,1,0,0)*Q(0,1,0,0), Q(-1,0,0,0)); shouldEqual(Q(0,0,1,0)*Q(0,0,1,0), Q(-1,0,0,0)); shouldEqual(Q(0,0,0,1)*Q(0,0,0,1), Q(-1,0,0,0)); shouldEqual(Q(0,1,0,0)*Q(0,0,1,0), Q(0,0,0,1)); shouldEqual(Q(0,0,1,0)*Q(0,1,0,0), Q(0,0,0,-1)); shouldEqual(Q(0,0,1,0)*Q(0,0,0,1), Q(0,1,0,0)); shouldEqual(Q(0,0,0,1)*Q(0,0,1,0), Q(0,-1,0,0)); shouldEqual(Q(0,0,0,1)*Q(0,1,0,0), Q(0,0,1,0)); shouldEqual(Q(0,1,0,0)*Q(0,0,0,1), Q(0,0,-1,0)); shouldEqual(q*q, Q(-28,4,6,8)); shouldEqual(q*2.0, Q(2,4,6,8)); shouldEqual(2.0*q, Q(2,4,6,8)); Q q1 = q / q; shouldEqualTolerance(q1[0], 1.0, 1e-16); shouldEqualTolerance(q1[1], 0.0, 1e-16); shouldEqualTolerance(q1[2], 0.0, 1e-16); shouldEqualTolerance(q1[3], 0.0, 1e-16); shouldEqual(Q(2,4,6,8)/2.0, q); shouldEqual(60.0/q, Q(2,-4,-6,-8)); shouldEqualTolerance(norm(q / norm(q)), 1.0, 1e-15); } void testRotation() { Q q(1.0, 2.0, 3.0, 4.0); q /= norm(q); double ref[3][3] = {{-2.0/3.0, 0.4/3.0, 2.2/3.0 }, { 2.0/3.0, -1.0/3.0, 2.0/3.0 }, { 1.0/3.0, 2.8/3.0, 0.4/3.0 } }; vigra::Matrix<double> m(3,3), mref(3,3, (double*)ref); q.fillRotationMatrix(m); shouldEqualSequenceTolerance(m.begin(), m.end(), mref.begin(), 1e-15); double res[3][3]; q.fillRotationMatrix(res); shouldEqualSequenceTolerance((double*)res, (double*)res+9, (double*)ref, 1e-15); Q q1 = Q::createRotation(M_PI/2.0, V(1,0,0)); Q q2 = Q::createRotation(M_PI/2.0, V(0,1,0)); Q q3 = Q::createRotation(M_PI/2.0, V(0,0,1)); Q q4 = q3*(-q1)*q2*q1; shouldEqualTolerance(norm(q4), 1.0, 1e-15); shouldEqualTolerance(q4[0], 0.0, 1e-15); } }; struct FixedPointTest { void testConstruction() { shouldEqual(vigra::fixedPoint(3).value, 3); shouldEqual(vigra::fixedPoint(-3).value, -3); shouldEqual(-vigra::fixedPoint(3).value, -3); shouldEqual((vigra::FixedPoint<3,4>(3).value), 3 << 4); shouldEqual((vigra::FixedPoint<3,4>(-3).value), -3 << 4); shouldEqual((-vigra::FixedPoint<3,4>(3).value), -3 << 4); shouldEqual((vigra::FixedPoint<3,4>(3.5).value), 56); shouldEqual((vigra::FixedPoint<3,4>(-3.5).value), -56); shouldEqual((-vigra::FixedPoint<3,4>(3.5).value), -56); try { vigra::FixedPoint<1, 8>(3.75); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} shouldEqual((vigra::NumericTraits<vigra::FixedPoint<1, 8> >::zero()).value, 0); shouldEqual((vigra::NumericTraits<vigra::FixedPoint<1, 8> >::one()).value, 1 << 8); shouldEqual((vigra::NumericTraits<vigra::FixedPoint<1, 8> >::max()).value, (1 << 9) - 1); shouldEqual((vigra::NumericTraits<vigra::FixedPoint<1, 8> >::min()).value, -((1 << 9) - 1)); vigra::FixedPoint<2, 8> v(3.75); shouldEqual((vigra::FixedPoint<2, 8>(v).value), 15 << 6); shouldEqual((vigra::FixedPoint<3, 10>(v).value), 15 << 8); shouldEqual((vigra::FixedPoint<2, 2>(v).value), 15); shouldEqual((vigra::FixedPoint<2, 0>(v).value), 4); shouldEqual((vigra::FixedPoint<2, 8>(-v).value), -15 << 6); shouldEqual((vigra::FixedPoint<3, 10>(-v).value), -15 << 8); shouldEqual((vigra::FixedPoint<2, 2>(-v).value), -15); shouldEqual((vigra::FixedPoint<2, 0>(-v).value), -4); shouldEqual(vigra::fixed_point_cast<double>(v), 3.75); should((frac(v) == vigra::FixedPoint<0, 8>(0.75))); should((dual_frac(v) == vigra::FixedPoint<0, 8>(0.25))); should(vigra::floor(v) == 3); should(vigra::ceil(v) == 4); should(round(v) == 4); should(vigra::abs(v) == v); should((frac(-v) == vigra::FixedPoint<0, 8>(0.25))); should((dual_frac(-v) == vigra::FixedPoint<0, 8>(0.75))); should(vigra::floor(-v) == -4); should(vigra::ceil(-v) == -3); should(round(-v) == -4); should(vigra::abs(-v) == v); should(vigra::norm(-v) == v); should(vigra::squaredNorm(-v) == v*v); vigra::FixedPoint<3, 10> v1; shouldEqual((v1 = v).value, 15 << 8); shouldEqual((v1 = -v).value, -15 << 8); vigra::FixedPoint<2, 0> v2; shouldEqual((v2 = v).value, 4); shouldEqual((v2 = -v).value, -4); } void testComparison() { vigra::FixedPoint<3, 8> v1(3.75), v2(4); vigra::FixedPoint<2, 2> v3(3.75); should(v1 == v1); should(v1 == v3); should(!(v1 != v1)); should(!(v1 != v3)); should(v1 <= v1); should(v1 <= v3); should(!(v1 < v1)); should(!(v1 < v3)); should(v1 >= v1); should(v1 >= v3); should(!(v1 > v1)); should(!(v1 > v3)); should(v2 != v1); should(v2 != v3); should(!(v2 == v1)); should(!(v2 == v3)); should(!(v2 <= v1)); should(!(v2 <= v3)); should(!(v2 < v1)); should(!(v2 < v3)); should(v2 >= v1); should(v2 >= v3); should(v2 > v1); should(v2 > v3); } void testArithmetic() { vigra::FixedPoint<1, 16> t1(0.75), t2(0.25); signed char v1 = 1, v2 = 2, v4 = 4, v8 = 8; should((vigra::FixedPoint<1, 16>(t1) += t1) == (vigra::FixedPoint<1, 16>(1.5))); should((vigra::FixedPoint<1, 16>(t1) -= t1) == (vigra::FixedPoint<1, 16>(0.0))); should((vigra::FixedPoint<2, 16>(t1) *= t1) == (vigra::FixedPoint<1, 16>(9.0 / 16.0))); should(--t1 == (vigra::FixedPoint<1, 16>(-0.25))); should(t1 == (vigra::FixedPoint<1, 16>(-0.25))); should(++t1 == (vigra::FixedPoint<1, 16>(0.75))); should(t1 == (vigra::FixedPoint<1, 16>(0.75))); should(t1++ == (vigra::FixedPoint<1, 16>(0.75))); should(t1 == (vigra::FixedPoint<1, 16>(1.75))); should(t1-- == (vigra::FixedPoint<1, 16>(1.75))); should(t1 == (vigra::FixedPoint<1, 16>(0.75))); shouldEqual((t1 * vigra::fixedPoint(v1)).value, 3 << 14); shouldEqual((t2 * vigra::fixedPoint(v1)).value, 1 << 14); shouldEqual((-t1 * vigra::fixedPoint(v1)).value, -3 << 14); shouldEqual((-t2 * vigra::fixedPoint(v1)).value, -1 << 14); shouldEqual((t1 * -vigra::fixedPoint(v1)).value, -3 << 14); shouldEqual((t2 * -vigra::fixedPoint(v1)).value, -1 << 14); shouldEqual((vigra::FixedPoint<8, 2>(t1 * vigra::fixedPoint(v1))).value, 3); shouldEqual((vigra::FixedPoint<8, 2>(t2 * vigra::fixedPoint(v1))).value, 1); shouldEqual((vigra::FixedPoint<8, 2>(-t1 * vigra::fixedPoint(v1))).value, -3); shouldEqual((vigra::FixedPoint<8, 2>(-t2 * vigra::fixedPoint(v1))).value, -1); shouldEqual(vigra::floor(t1 * vigra::fixedPoint(v1) + t2 * vigra::fixedPoint(v2)), 1); shouldEqual(vigra::ceil(t1 * vigra::fixedPoint(v1) + t2 * vigra::fixedPoint(v2)), 2); shouldEqual(round(t1 * vigra::fixedPoint(v1) + t2 * vigra::fixedPoint(v2)), 1); shouldEqual(vigra::floor(t1 * vigra::fixedPoint(v4) + t2 * vigra::fixedPoint(v8)), 5); shouldEqual(vigra::ceil(t1 * vigra::fixedPoint(v4) + t2 * vigra::fixedPoint(v8)), 5); shouldEqual(round(t1 * vigra::fixedPoint(v4) + t2 * vigra::fixedPoint(v8)), 5); shouldEqual(vigra::floor(t1 * -vigra::fixedPoint(v1) - t2 * vigra::fixedPoint(v2)), -2); shouldEqual(vigra::ceil(t1 * -vigra::fixedPoint(v1) - t2 * vigra::fixedPoint(v2)), -1); shouldEqual(round(t1 * -vigra::fixedPoint(v1) - t2 * vigra::fixedPoint(v2)), -1); shouldEqual(vigra::floor(t1 * -vigra::fixedPoint(v4) - t2 * vigra::fixedPoint(v8)), -5); shouldEqual(vigra::ceil(t1 * -vigra::fixedPoint(v4) - t2 * vigra::fixedPoint(v8)), -5); shouldEqual(round(t1 * -vigra::fixedPoint(v4) - t2 * vigra::fixedPoint(v8)), -5); double d1 = 1.0 / 3.0, d2 = 1.0 / 7.0; vigra::FixedPoint<1, 24> r1(d1), r2(d2); vigra::FixedPoint<2, 24> r3; add(r1, r2, r3); shouldEqual(r3.value, (vigra::FixedPoint<2, 24>(d1 + d2)).value); sub(r1, r2, r3); shouldEqual(r3.value, (vigra::FixedPoint<2, 24>(d1 - d2)).value); mul(r1, r2, r3); shouldEqual(r3.value >> 2, (vigra::FixedPoint<2, 24>(d1 * d2)).value >> 2); for(int i = 0; i < 1024; ++i) { vigra::FixedPoint<4,5> fv1(i, vigra::FPNoShift); vigra::FixedPoint<5,4> fv2(i, vigra::FPNoShift); vigra::FixedPoint<5,5> fv3(i, vigra::FPNoShift); vigra::FixedPoint<6,6> fv4(i, vigra::FPNoShift); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(fv1)), vigra::floor(vigra::sqrt((double)fv1.value)) / 8.0); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(fv2)), vigra::floor(vigra::sqrt((double)fv2.value)) / 4.0); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(fv3)), vigra::floor(vigra::sqrt((double)fv3.value)) / 4.0); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(fv4)), vigra::floor(vigra::sqrt((double)fv4.value)) / 8.0); } } }; struct FixedPoint16Test { void testConstruction() { shouldEqual((vigra::FixedPoint16<3>(3).value), 3 << 12); shouldEqual((vigra::FixedPoint16<3>(-3).value), -3 << 12); shouldEqual((-vigra::FixedPoint16<3>(3).value), -3 << 12); shouldEqual((vigra::FixedPoint16<8>(3).value), 3 << 7); shouldEqual((vigra::FixedPoint16<3>(3.5).value), 7 << 11); shouldEqual((vigra::FixedPoint16<3>(-3.5).value), -(7 << 11)); shouldEqual((-vigra::FixedPoint16<3>(3.5).value), -(7 << 11)); shouldEqual((vigra::NumericTraits<vigra::FixedPoint16<4> >::zero()).value, 0); shouldEqual((vigra::NumericTraits<vigra::FixedPoint16<4> >::one()).value, 1 << 11); shouldEqual((vigra::NumericTraits<vigra::FixedPoint16<4> >::max()).value, (1 << 15) - 1); shouldEqual((vigra::NumericTraits<vigra::FixedPoint16<4> >::min()).value, -(1 << 15)); shouldEqual((vigra::FixedPoint16<1, vigra::FPOverflowSaturate>(3.75).value), (1 << 15)-1); shouldEqual((vigra::FixedPoint16<1, vigra::FPOverflowSaturate>(-3.75).value), -(1 << 15)); try { vigra::FixedPoint16<1, vigra::FPOverflowError>(3.75); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} try { vigra::FixedPoint16<1, vigra::FPOverflowError>(-3.75); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} vigra::FixedPoint16<4> v(3.75); shouldEqual((v.value), 15 << 9); shouldEqual(((-v).value), -15 << 9); shouldEqual((vigra::FixedPoint16<4>(v).value), 15 << 9); shouldEqual((vigra::FixedPoint16<6>(v).value), 15 << 7); shouldEqual((vigra::FixedPoint16<13>(v).value), 15); shouldEqual((vigra::FixedPoint16<15>(v).value), 4); shouldEqual((vigra::FixedPoint16<4>(-v).value), -15 << 9); shouldEqual((vigra::FixedPoint16<6>(-v).value), -15 << 7); shouldEqual((vigra::FixedPoint16<13>(-v).value), -15); shouldEqual((vigra::FixedPoint16<15>(-v).value), -4); shouldEqual(vigra::fixed_point_cast<double>(v), 3.75); shouldEqual(vigra::fixed_point_cast<double>(-v), -3.75); shouldEqual(frac(v), vigra::FixedPoint16<4>(0.75)); shouldEqual(dual_frac(v), vigra::FixedPoint16<4>(0.25)); shouldEqual(frac(-v), vigra::FixedPoint16<4>(0.25)); shouldEqual(dual_frac(-v), vigra::FixedPoint16<4>(0.75)); shouldEqual(vigra::floor(v), 3); shouldEqual(vigra::ceil(v), 4); shouldEqual(vigra::floor(-v), -4); shouldEqual(vigra::ceil(-v), -3); shouldEqual(round(v), 4); shouldEqual(round(-v), -4); shouldEqual(vigra::abs(v), v); shouldEqual(vigra::abs(-v), v); shouldEqual(vigra::norm(-v), v); shouldEqual(vigra::squaredNorm(-v), v*v); vigra::FixedPoint16<2> v1; shouldEqual((v1 = v).value, 15 << 11); shouldEqual((v1 = -v).value, -15 << 11); vigra::FixedPoint16<15> v2; shouldEqual((v2 = v).value, 4); shouldEqual((v2 = -v).value, -4); } void testComparison() { vigra::FixedPoint16<4> v1(3.75), v2(4); vigra::FixedPoint16<2> v3(3.75); should(v1 == v1); should(v1 == v3); should(!(v1 != v1)); should(!(v1 != v3)); should(v1 <= v1); should(v1 <= v3); should(!(v1 < v1)); should(!(v1 < v3)); should(v1 >= v1); should(v1 >= v3); should(!(v1 > v1)); should(!(v1 > v3)); should(v2 != v1); should(v2 != v3); should(!(v2 == v1)); should(!(v2 == v3)); should(!(v2 <= v1)); should(!(v2 <= v3)); should(!(v2 < v1)); should(!(v2 < v3)); should(v2 >= v1); should(v2 >= v3); should(v2 > v1); should(v2 > v3); } void testArithmetic() { typedef vigra::FixedPoint16<1> FP1; typedef vigra::FixedPoint16<2> FP2; typedef vigra::FixedPoint16<7> FP7; typedef vigra::FixedPoint16<8> FP8; typedef vigra::FixedPoint16<13> FP13; typedef vigra::FixedPoint16<15> FP15; FP1 t0(0), t1(0.75), t2(0.25); signed char v1 = 1, v2 = 2, v4 = 4, v8 = 8; shouldEqual(FP1(t1) += t1, FP1(1.5)); shouldEqual(FP1(t1) -= t1, FP1(0.0)); shouldEqual(FP1(t1) -= t2, FP1(0.5)); shouldEqual(FP2(t1) *= t1, FP1(9.0 / 16.0)); shouldEqual(FP2(t1) /= t2, FP2(3)); shouldEqual(FP2(t1) /= t0, vigra::NumericTraits<FP2>::max()); shouldEqual(FP2(-t1) /= t0, vigra::NumericTraits<FP2>::min()); FP2 res; shouldEqual(add(t1, t1, res), FP2(1.5)); shouldEqual(sub(t1, t1, res), FP2(0)); shouldEqual(sub(t1, t2, res), FP2(0.5)); shouldEqual(mul(t1, t1, res), FP2(9.0 / 16.0)); shouldEqual(div(t1, t2, res), FP2(3)); shouldEqual(div(t1, t0, res), vigra::NumericTraits<FP2>::max()); shouldEqual(div(-t1, t0, res), vigra::NumericTraits<FP2>::min()); shouldEqual(--t1, FP1(-0.25)); shouldEqual(t1, FP1(-0.25)); shouldEqual(++t1, FP1(0.75)); shouldEqual(t1, FP1(0.75)); shouldEqual(t1++, FP1(0.75)); shouldEqual(t1, FP1(1.75)); shouldEqual(t1--, FP1(1.75)); shouldEqual(t1, FP1(0.75)); shouldEqual((t1 * FP7(v1)).value, 3 << 6); shouldEqual((t2 * FP7(v1)).value, 1 << 6); shouldEqual((-t1 * FP7(v1)).value, -3 << 6); shouldEqual((-t2 * FP7(v1)).value, -1 << 6); shouldEqual((t1 * -FP7(v1)).value, -3 << 6); shouldEqual((t2 * -FP7(v1)).value, -1 << 6); shouldEqual((vigra::FixedPoint16<2, vigra::FPOverflowSaturate>(t1*FP7(v8)).value), (1 << 15)-1); shouldEqual((vigra::FixedPoint16<2, vigra::FPOverflowSaturate>(t1*FP7(-v8)).value), -(1 << 15)); try { vigra::FixedPoint16<2, vigra::FPOverflowError>(t1*FP7(v8)); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} try { vigra::FixedPoint16<2, vigra::FPOverflowError>(t1*FP7(-v8)); failTest("No exception thrown"); } catch(vigra::PreconditionViolation &) {} shouldEqual((FP13(t1 * FP7(v1))).value, 3); shouldEqual((FP13(t2 * FP7(v1))).value, 1); shouldEqual((FP13(-t1 * FP7(v1))).value, -3); shouldEqual((FP13(-t2 * FP7(v1))).value, -1); shouldEqual((t1 * FP7(v4) + t2 * FP7(v8)).value, 5 << 8); shouldEqual((t1 * FP7(v1) + t2 * FP7(v2)).value, 5 << 6); shouldEqual(FP7(6) / FP7(3), FP7(2)); shouldEqual(FP7(0.75) / FP7(0.25), FP7(3)); shouldEqual(FP7(12) / FP7(48), FP7(0.25)); shouldEqual(FP1(0.25) / FP7(2), FP7(0.125)); shouldEqual(FP7(10) / FP1(0.25), FP7(40)); shouldEqual(FP7(10) / t0, vigra::NumericTraits<FP7>::max()); shouldEqual(FP7(-10) / t0, vigra::NumericTraits<FP7>::min()); shouldEqual(vigra::floor(t1 * FP7(v1) + t2 * FP7(v2)), 1); shouldEqual(vigra::ceil(t1 * FP7(v1) + t2 * FP7(v2)), 2); shouldEqual(round(t1 * FP7(v1) + t2 * FP7(v2)), 1); shouldEqual(vigra::floor(t1 * FP7(v4) + t2 * FP7(v8)), 5); shouldEqual(vigra::ceil(t1 * FP7(v4) + t2 * FP7(v8)), 5); shouldEqual(round(t1 * FP7(v4) + t2 * FP7(v8)), 5); shouldEqual(vigra::floor(t1 * -FP7(v1) - t2 * FP7(v2)), -2); shouldEqual(vigra::ceil(t1 * -FP7(v1) - t2 * FP7(v2)), -1); shouldEqual(round(t1 * -FP7(v1) - t2 * FP7(v2)), -1); shouldEqual(vigra::floor(t1 * -FP7(v4) - t2 * FP7(v8)), -5); shouldEqual(vigra::ceil(t1 * -FP7(v4) - t2 * FP7(v8)), -5); shouldEqual(round(t1 * -FP7(v4) - t2 * FP7(v8)), -5); double d1 = 1.0 / 3.0, d2 = 1.0 / 7.0; FP1 r1(d1), r2(d2); FP2 r3; add(r1, r2, r3); shouldEqual(r3.value, FP2(d1 + d2).value); sub(r1, r2, r3); shouldEqual(r3.value, FP2(d1 - d2).value); mul(r1, r2, r3); shouldEqual(r3.value >> 2, FP2(d1 * d2).value >> 2); shouldEqual(vigra::sqrt(FP7(4)).value, 1 << 12); shouldEqual(vigra::sqrt(FP8(4)).value, 1 << 12); shouldEqual(vigra::hypot(FP8(3), FP8(4)), FP8(5)); shouldEqual(vigra::hypot(FP8(-3), FP8(-4)), FP8(5)); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(FP7(4))), 2.0); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(FP2(2.25))), 1.5); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(FP8(6.25))), 2.5); for(int i = 0; i < 1024; ++i) { vigra::FixedPoint16<11> fv1(i, vigra::FPNoShift); vigra::FixedPoint16<10> fv2(i, vigra::FPNoShift); vigra::FixedPoint16<9> fv3(i, vigra::FPNoShift); vigra::FixedPoint16<8> fv4(i, vigra::FPNoShift); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(fv1)), vigra::floor(vigra::sqrt((double)(i << 14))) / 512.0); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(fv2)), vigra::floor(vigra::sqrt((double)(i << 15))) / 1024.0); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(fv3)), vigra::floor(vigra::sqrt((double)(i << 14))) / 1024.0); shouldEqual(vigra::fixed_point_cast<double>(vigra::sqrt(fv4)), vigra::floor(vigra::sqrt((double)(i << 15))) / 2048.0); } shouldEqual(vigra::atan2(FP1(0), FP1(1)), FP2(0)); shouldEqual(vigra::atan2(FP1(0), FP1(-1)), FP2(M_PI)); shouldEqual(vigra::atan2(FP1(1), FP1(0)), FP2(0.5*M_PI)); shouldEqual(vigra::atan2(FP1(-1), FP1(0)), FP2(-0.5*M_PI)); for(int i = -179; i < 180; ++i) { double angle = M_PI*i/180.0; double c = std::cos(angle), s = std::sin(angle); FP2 a = vigra::atan2(FP1(s), FP1(c)); should(vigra::abs(i-vigra::fixed_point_cast<double>(a)/M_PI*180.0) < 0.3); a = vigra::atan2(FP15(30000.0*s), FP15(30000.0*c)); should(vigra::abs(i-vigra::fixed_point_cast<double>(a)/M_PI*180.0) < 0.3); } } }; struct LinalgTest { typedef vigra::Matrix<double> Matrix; typedef Matrix::difference_type Shape; unsigned int size, iterations; vigra::RandomMT19937 random_; LinalgTest() : size(50), iterations(5), random_(23098349) {} void testOStreamShifting() { Matrix a = random_matrix (size, size); std::ostringstream out; out << a; out << "Testing.." << a << 42 << std::endl; } double random_double () { double ret = 2.0 * random_.uniform53() - 1.0; return ret; } Matrix random_matrix(unsigned int rows, unsigned int cols) { Matrix ret (rows, cols); for (unsigned int i = 0; i < rows; ++i) for (unsigned int j = 0; j < cols; ++j) ret (i, j) = random_double (); return ret; } Matrix random_symmetric_matrix(unsigned int rows) { Matrix ret (rows, rows); for (unsigned int i = 0; i < rows; ++i) for (unsigned int j = i; j < rows; ++j) ret (j, i) = ret (i, j) = random_double (); return ret; } void testMatrix() { double data[] = {1.0, 5.0, 3.0, 2.0, 4.0, 7.0}; double tref[] = {1.0, 3.0, 4.0, 5.0, 2.0, 7.0}; double tref2[] = {1.0, 3.0, 5.0, 2.0}; double idref[] = {1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0}; std::string sref("1.0000 5.0000 \n3.0000 2.0000 \n4.0000 7.0000 \n"); unsigned int r = 3, c = 2; Matrix a(r, c, data), zero(r, c); shouldEqual(a.rowCount(), r); shouldEqual(a.columnCount(), c); shouldEqual(a.elementCount(), r*c); shouldEqual(a.squaredNorm(), 104.0); shouldEqual(a.norm(), std::sqrt(104.0)); shouldEqual(a.squaredNorm(), squaredNorm(a)); shouldEqual(a.norm(), vigra::norm(a)); shouldEqual(rowCount(a), r); shouldEqual(columnCount(a), c); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(zero(i,j), 0.0); Matrix one = zero + Matrix(r,c).init(1.0); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(one(i,j), 1.0); std::stringstream s; s << std::setprecision(4) << a; shouldEqual(s.str(), sref); for(unsigned int i=0, k=0; i<r; ++i) { Matrix::view_type ar = a.rowVector(i); shouldEqual(rowCount(ar), 1); shouldEqual(columnCount(ar), c); Matrix::view_type ar1 = rowVector(a, i); shouldEqual(rowCount(ar1), 1); shouldEqual(columnCount(ar1), c); for(unsigned int j=0; j<c; ++j, ++k) { shouldEqual(a(i,j), data[k]); shouldEqual(ar(0, j), data[k]); shouldEqual(ar1(0, j), data[k]); } } Matrix aa(r, c, tref, vigra::ColumnMajor); shouldEqual(aa.rowCount(), r); shouldEqual(aa.columnCount(), c); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(aa(i,j), a(i,j)); Matrix b = a; shouldEqual(b.rowCount(), r); shouldEqual(b.columnCount(), c); shouldEqualSequence(a.begin(), a.end(), b.begin()); b.init(0.0); should(b == zero); Matrix::iterator ib = b.begin(); b = a; shouldEqual(ib, b.begin()); shouldEqualSequence(a.begin(), a.end(), b.begin()); b = 4.0 + a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), 4.0+data[k]); b = a + 3.0; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k]+3.0); b += 4.0; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), 7.0+data[k]); b += a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), 7.0+2.0*data[k]); b = 4.0 - a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), 4.0-data[k]); b = a - 3.0; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k]-3.0); b -= 4.0; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k]-7.0); b -= a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), -7.0); b = 4.0 * a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), 4.0*data[k]); b = a * 3.0; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k]*3.0); b *= 4.0; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k]*12.0); b *= a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k]*data[k]*12.0); b = 4.0 / a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), 4.0/data[k]); b = a / 3.0; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k] / 3.0); b /= 4.0; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k] / 12.0); b /= a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqualTolerance(b(i,j), 1.0 / 12.0, 1e-12); b = a + a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), 2.0 * data[k]); b = a - a; for(unsigned int i=0; i<r; ++i) for(unsigned int j=0; j<c; ++j) shouldEqual(b(i,j), 0.0); b = -a; for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), -data[k]); b = a * pointWise(a); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k] * data[k]); b = a / pointWise(a); for(unsigned int i=0; i<r; ++i) for(unsigned int j=0; j<c; ++j) shouldEqual(b(i,j), 1.0); b = pow(a, 2); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), data[k] * data[k]); b = sqrt(a); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), sqrt(data[k])); b = sq(a); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), vigra::sq(data[k])); b = sign(a); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(b(i,j), vigra::sign(data[k])); Matrix at = transpose(a); shouldEqual(at.rowCount(), c); shouldEqual(at.columnCount(), r); for(unsigned int i=0, k=0; i<c; ++i) { Matrix::view_type ac = a.columnVector(i); shouldEqual(rowCount(ac), r); shouldEqual(columnCount(ac), 1); Matrix::view_type ac1 = columnVector(a, i); shouldEqual(rowCount(ac1), r); shouldEqual(columnCount(ac1), 1); for(unsigned int j=0; j<r; ++j, ++k) { shouldEqual(at(i,j), tref[k]); shouldEqual(ac(j,0), tref[k]); shouldEqual(ac1(j,0), tref[k]); } shouldEqual(ac, subVector(ac, 0, r)); shouldEqual(a.subarray(Shape(1, i), Shape(r-1, i+1)), subVector(ac, 1, r-1)); } double sn = squaredNorm(columnVector(a, 0)); shouldEqual(sn, 26.0); shouldEqual(sn, dot(columnVector(a, 0), columnVector(a, 0))); shouldEqual(sn, dot(rowVector(at, 0), columnVector(a, 0))); shouldEqual(sn, dot(columnVector(a, 0), rowVector(at, 0))); shouldEqual(sn, dot(rowVector(at, 0), rowVector(at, 0))); shouldEqual(0.0, dot(a.subarray(Shape(0,0), Shape(1,0)), a.subarray(Shape(0,0), Shape(0,1)))); shouldEqual(0.0, dot(a.subarray(Shape(0,0), Shape(0,1)), a.subarray(Shape(0,0), Shape(0,1)))); shouldEqual(0.0, dot(a.subarray(Shape(0,0), Shape(1,0)), a.subarray(Shape(0,0), Shape(1,0)))); shouldEqual(0.0, dot(a.subarray(Shape(0,0), Shape(0,1)), a.subarray(Shape(0,0), Shape(1,0)))); Matrix a2(c, c, data); a2 = a2.transpose(); for(unsigned int i=0, k=0; i<c; ++i) for(unsigned int j=0; j<c; ++j, ++k) shouldEqual(a2(i,j), tref2[k]); shouldEqual(trace(a2), 3.0); Matrix id = vigra::identityMatrix<double>(r); shouldEqual(id.rowCount(), r); shouldEqual(id.columnCount(), r); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<r; ++j, ++k) shouldEqual(id(i,j), idref[k]); shouldEqual(trace(id), 3.0); Matrix d = diagonalMatrix(Matrix(r, 1, data)); shouldEqual(d.rowCount(), r); shouldEqual(d.columnCount(), r); for(unsigned int i=0, k=0; i<r; ++i) for(unsigned int j=0; j<r; ++j, ++k) shouldEqual(d(i,j), idref[k]*data[i]); Matrix e(r*c, 1, data); shouldEqual(dot(transpose(e), e), e.squaredNorm()); double dc1[] = {1.0, 1.0, 1.0}, dc2[] = {1.2, 2.4, 3.6}; Matrix c1(3,1, dc1), c2(3,1, dc2); Matrix cr = cross(c1, c2); shouldEqualTolerance(cr(0,0), 1.2, 1e-12); shouldEqualTolerance(cr(1,0), -2.4, 1e-12); shouldEqualTolerance(cr(2,0), 1.2, 1e-12); Matrix f(1, r*c - 1, tref); Matrix g = outer(e, f); shouldEqual(g.rowCount(), e.rowCount()); shouldEqual(g.columnCount(), f.columnCount()); for(int i=0; i<g.rowCount(); ++i) for(int j=0; j<g.columnCount(); ++j) shouldEqual(g(i,j), data[i]*tref[j]); Matrix h = transpose(a) * a; shouldEqual(h.rowCount(), c); shouldEqual(h.columnCount(), c); for(int i=0; i<(int)c; ++i) for(int j=0; j<(int)c; ++j) shouldEqual(h(i,j), dot(rowVector(at, i), columnVector(a, j))); should(isSymmetric(random_symmetric_matrix(10))); should(!isSymmetric(random_matrix(10, 10))); Matrix tm(2, 2, tref2); vigra::TinyVector<double, 2> tv(1.0, 2.0), tvrref(7.0, 9.0), tvlref(11.0, 7.0); shouldEqual(tm * tv, tvrref); shouldEqual(tv * tm, tvlref); Matrix rep = repeatMatrix(a, 2, 4); shouldEqual(rowCount(rep), 2*r); shouldEqual(columnCount(rep), 4*c); for(unsigned int l=0; l<4; ++l) for(unsigned int k=0; k<2; ++k) for(unsigned int j=0; j<c; ++j) for(unsigned int i=0; i<r; ++i) shouldEqual(rep(k*r+i, l*c+j), a(i,j)); double columnSum[] = {8.0, 14.0}; double rowSum[] = {6.0, 5.0, 11.0}; Matrix matColumnSum = Matrix(1, 2, columnSum); Matrix matRowSum = Matrix(3, 1, rowSum); shouldEqualSequence(matColumnSum.data(), matColumnSum.data()+2, a.sum(0).data()); shouldEqualSequence(matRowSum.data(), matRowSum.data()+3, a.sum(1).data()); double columnMean[] = {8/3.0, 14/3.0}; double rowMean[] = {3.0, 2.5, 5.5}; Matrix matColumnMean = Matrix(1, 2, columnMean); Matrix matRowMean = Matrix(3, 1, rowMean); shouldEqualSequence(matColumnMean.data(), matColumnMean.data()+2, a.mean(0).data()); shouldEqualSequence(matRowMean.data(), matRowMean.data()+3, a.mean(1).data()); } void testArgMinMax() { using namespace vigra::functor; double data[] = {1.0, 5.0, 3.0, 2.0, -2.0, 4.0}; unsigned int r = 3, c = 2; Matrix minmax(r, c, data); shouldEqual(argMin(minmax), 2); shouldEqual(argMax(minmax), 3); shouldEqual(argMinIf(minmax, Arg1() > Param(0.0)), 0); shouldEqual(argMinIf(minmax, Arg1() > Param(5.0)), -1); shouldEqual(argMaxIf(minmax, Arg1() < Param(5.0)), 5); shouldEqual(argMaxIf(minmax, Arg1() < Param(-2.0)), -1); } void testColumnAndRowStatistics() { double epsilon = 1e-11; Matrix rowMean(size, 1), columnMean(1, size); Matrix rowStdDev(size, 1), columnStdDev(1, size); Matrix rowNorm(size, 1), columnNorm(1, size); Matrix rowCovariance(size, size), columnCovariance(size, size); for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_matrix (size, size); rowStatistics(a, rowMean, rowStdDev, rowNorm); columnStatistics(a, columnMean, columnStdDev, columnNorm); for(unsigned int k=0; k<size; ++k) { double rm = 0.0, cm = 0.0, rn = 0.0, cn = 0.0, rs = 0.0, cs = 0.0; for(unsigned int l=0; l<size; ++l) { rm += a(k, l); cm += a(l, k); rn += vigra::sq(a(k, l)); cn += vigra::sq(a(l, k)); } rm /= size; cm /= size; rn = std::sqrt(rn); cn = std::sqrt(cn); shouldEqualTolerance(rm, rowMean(k,0), epsilon); shouldEqualTolerance(cm, columnMean(0,k), epsilon); shouldEqualTolerance(rn, rowNorm(k,0), epsilon); shouldEqualTolerance(cn, columnNorm(0,k), epsilon); for(unsigned int l=0; l<size; ++l) { rs += vigra::sq(a(k, l) - rm); cs += vigra::sq(a(l, k) - cm); } rs = std::sqrt(rs / (size-1)); cs = std::sqrt(cs / (size-1)); shouldEqualTolerance(rs, rowStdDev(k,0), epsilon); shouldEqualTolerance(cs, columnStdDev(0,k), epsilon); } covarianceMatrixOfRows(a, rowCovariance); covarianceMatrixOfColumns(a, columnCovariance); Matrix rowCovarianceRef(size, size), columnCovarianceRef(size, size); for(unsigned int k=0; k<size; ++k) { for(unsigned int l=0; l<size; ++l) { for(unsigned int m=0; m<size; ++m) { rowCovarianceRef(l, m) += (a(l, k) - rowMean(l, 0)) * (a(m, k) - rowMean(m, 0)); columnCovarianceRef(l, m) += (a(k, l) - columnMean(0, l)) * (a(k, m) - columnMean(0, m)); } } } rowCovarianceRef /= (size-1); columnCovarianceRef /= (size-1); shouldEqualSequenceTolerance(rowCovariance.data(), rowCovariance.data()+size*size, rowCovarianceRef.data(), epsilon); shouldEqualSequenceTolerance(columnCovariance.data(), columnCovariance.data()+size*size, columnCovarianceRef.data(), epsilon); } } void testColumnAndRowPreparation() { using vigra::ZeroMean; using vigra::UnitVariance; using vigra::UnitNorm; using vigra::UnitSum; double epsilon = 1e-11; Matrix rowMean(size, 1), columnMean(1, size); Matrix rowStdDev(size, 1), columnStdDev(1, size); Matrix rowNorm(size, 1), columnNorm(1, size); Matrix rowPrepared(size, size), columnPrepared(size, size); Matrix rowMeanPrepared(size, 1), columnMeanPrepared(1, size); Matrix rowStdDevPrepared(size, 1), columnStdDevPrepared(1, size); Matrix rowNormPrepared(size, 1), columnNormPrepared(1, size); Matrix rowOffset(size, 1), columnOffset(1, size); Matrix rowScaling(size, 1), columnScaling(1, size); Matrix zeroRowRef(size,1), zeroColRef(1, size); Matrix oneRowRef(size,1), oneColRef(1, size); oneRowRef.init(1.0); oneColRef.init(1.0); { Matrix a = random_matrix (size, size); columnStatistics(a, columnMean, columnStdDev, columnNorm); prepareColumns(a, columnPrepared, columnOffset, columnScaling, UnitSum); shouldEqualSequence(zeroColRef.data(), zeroColRef.data()+size, columnOffset.data()); columnScaling *= columnMean; columnScaling *= size; shouldEqualSequenceTolerance(oneColRef.data(), oneColRef.data()+size, columnScaling.data(), epsilon); columnStatistics(columnPrepared, columnMeanPrepared, columnStdDevPrepared, columnNormPrepared); columnMeanPrepared *= size; shouldEqualSequenceTolerance(oneColRef.data(), oneColRef.data()+size, columnMeanPrepared.data(), epsilon); prepareColumns(a, columnPrepared, columnOffset, columnScaling, ZeroMean); columnStatistics(columnPrepared, columnMeanPrepared, columnStdDevPrepared, columnNormPrepared); shouldEqualSequenceTolerance(zeroColRef.data(), zeroColRef.data()+size, columnMeanPrepared.data(), epsilon); shouldEqualSequenceTolerance(columnStdDev.data(), columnStdDev.data()+size, columnStdDevPrepared.data(), epsilon); Matrix ap = columnPrepared / pointWise(repeatMatrix(columnScaling, size, 1)) + repeatMatrix(columnOffset, size, 1); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareColumns(a, columnPrepared, columnOffset, columnScaling, UnitNorm); columnStatistics(columnPrepared, columnMeanPrepared, columnStdDevPrepared, columnNormPrepared); shouldEqualSequenceTolerance(oneColRef.data(), oneColRef.data()+size, columnNormPrepared.data(), epsilon); ap = columnPrepared / pointWise(repeatMatrix(columnScaling, size, 1)) + repeatMatrix(columnOffset, size, 1); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareColumns(a, columnPrepared, columnOffset, columnScaling, UnitVariance); columnStatistics(columnPrepared, columnMeanPrepared, columnStdDevPrepared, columnNormPrepared); columnMeanPrepared /= columnScaling; shouldEqualSequenceTolerance(columnMean.data(), columnMean.data()+size, columnMeanPrepared.data(), epsilon); shouldEqualSequenceTolerance(oneColRef.data(), oneColRef.data()+size, columnStdDevPrepared.data(), epsilon); ap = columnPrepared / pointWise(repeatMatrix(columnScaling, size, 1)) + repeatMatrix(columnOffset, size, 1); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareColumns(a, columnPrepared, columnOffset, columnScaling, ZeroMean | UnitVariance); columnStatistics(columnPrepared, columnMeanPrepared, columnStdDevPrepared, columnNormPrepared); shouldEqualSequenceTolerance(zeroColRef.data(), zeroColRef.data()+size, columnMeanPrepared.data(), epsilon); shouldEqualSequenceTolerance(oneColRef.data(), oneColRef.data()+size, columnStdDevPrepared.data(), epsilon); ap = columnPrepared / pointWise(repeatMatrix(columnScaling, size, 1)) + repeatMatrix(columnOffset, size, 1); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareColumns(a, columnPrepared, columnOffset, columnScaling, ZeroMean | UnitNorm); columnStatistics(columnPrepared, columnMeanPrepared, columnStdDevPrepared, columnNormPrepared); shouldEqualSequenceTolerance(zeroColRef.data(), zeroColRef.data()+size, columnMeanPrepared.data(), epsilon); shouldEqualSequenceTolerance(oneColRef.data(), oneColRef.data()+size, columnNormPrepared.data(), epsilon); ap = columnPrepared / pointWise(repeatMatrix(columnScaling, size, 1)) + repeatMatrix(columnOffset, size, 1); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); rowStatistics(a, rowMean, rowStdDev, rowNorm); prepareRows(a, rowPrepared, rowOffset, rowScaling, UnitSum); shouldEqualSequence(zeroRowRef.data(), zeroRowRef.data()+size, rowOffset.data()); rowScaling *= rowMean; rowScaling *= size; shouldEqualSequenceTolerance(oneRowRef.data(), oneRowRef.data()+size, rowScaling.data(), epsilon); rowStatistics(rowPrepared, rowMeanPrepared, rowStdDevPrepared, rowNormPrepared); rowMeanPrepared *= size; shouldEqualSequenceTolerance(oneRowRef.data(), oneRowRef.data()+size, rowMeanPrepared.data(), epsilon); prepareRows(a, rowPrepared, rowOffset, rowScaling, ZeroMean); rowStatistics(rowPrepared, rowMeanPrepared, rowStdDevPrepared, rowNormPrepared); shouldEqualSequenceTolerance(zeroRowRef.data(), zeroRowRef.data()+size, rowMeanPrepared.data(), epsilon); shouldEqualSequenceTolerance(rowStdDev.data(), rowStdDev.data()+size, rowStdDevPrepared.data(), epsilon); ap = rowPrepared / pointWise(repeatMatrix(rowScaling, 1, size)) + repeatMatrix(rowOffset, 1, size); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareRows(a, rowPrepared, rowOffset, rowScaling, UnitNorm); rowStatistics(rowPrepared, rowMeanPrepared, rowStdDevPrepared, rowNormPrepared); shouldEqualSequenceTolerance(oneRowRef.data(), oneRowRef.data()+size, rowNormPrepared.data(), epsilon); ap = rowPrepared / pointWise(repeatMatrix(rowScaling, 1, size)) + repeatMatrix(rowOffset, 1, size); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareRows(a, rowPrepared, rowOffset, rowScaling, UnitVariance); rowStatistics(rowPrepared, rowMeanPrepared, rowStdDevPrepared, rowNormPrepared); rowMeanPrepared /= rowScaling; shouldEqualSequenceTolerance(rowMean.data(), rowMean.data()+size, rowMeanPrepared.data(), epsilon); shouldEqualSequenceTolerance(oneRowRef.data(), oneRowRef.data()+size, rowStdDevPrepared.data(), epsilon); ap = rowPrepared / pointWise(repeatMatrix(rowScaling, 1, size)) + repeatMatrix(rowOffset, 1, size); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareRows(a, rowPrepared, rowOffset, rowScaling, ZeroMean | UnitVariance); rowStatistics(rowPrepared, rowMeanPrepared, rowStdDevPrepared, rowNormPrepared); shouldEqualSequenceTolerance(zeroRowRef.data(), zeroRowRef.data()+size, rowMeanPrepared.data(), epsilon); shouldEqualSequenceTolerance(oneRowRef.data(), oneRowRef.data()+size, rowStdDevPrepared.data(), epsilon); ap = rowPrepared / pointWise(repeatMatrix(rowScaling, 1, size)) + repeatMatrix(rowOffset, 1, size); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareRows(a, rowPrepared, rowOffset, rowScaling, ZeroMean | UnitNorm); rowStatistics(rowPrepared, rowMeanPrepared, rowStdDevPrepared, rowNormPrepared); shouldEqualSequenceTolerance(zeroRowRef.data(), zeroRowRef.data()+size, rowMeanPrepared.data(), epsilon); shouldEqualSequenceTolerance(oneRowRef.data(), oneRowRef.data()+size, rowNormPrepared.data(), epsilon); ap = rowPrepared / pointWise(repeatMatrix(rowScaling, 1, size)) + repeatMatrix(rowOffset, 1, size); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); } { Matrix a(size, size, 2.0), aref(size, size, 1.0/std::sqrt((double)size)); prepareColumns(a, columnPrepared, columnOffset, columnScaling, ZeroMean | UnitVariance); shouldEqualSequence(a.data(), a.data()+size*size, columnPrepared.data()); prepareColumns(a, columnPrepared, columnOffset, columnScaling, ZeroMean | UnitNorm); shouldEqualSequenceTolerance(aref.data(), aref.data()+size*size, columnPrepared.data(), epsilon); Matrix ap = columnPrepared / pointWise(repeatMatrix(columnScaling, size, 1)) + repeatMatrix(columnOffset, size, 1); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); prepareRows(a, rowPrepared, rowOffset, rowScaling, ZeroMean | UnitVariance); shouldEqualSequence(a.data(), a.data()+size*size, rowPrepared.data()); prepareRows(a, rowPrepared, rowOffset, rowScaling, ZeroMean | UnitNorm); shouldEqualSequenceTolerance(aref.data(), aref.data()+size*size, rowPrepared.data(), epsilon); ap = rowPrepared / pointWise(repeatMatrix(rowScaling, 1, size)) + repeatMatrix(rowOffset, 1, size); shouldEqualSequenceTolerance(a.data(), a.data()+size*size, ap.data(), epsilon); } } void testCholesky() { double epsilon = 1e-11; Matrix idref = vigra::identityMatrix<double>(size); for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_matrix (size, size); a = transpose(a) * a; // make a symmetric positive definite matrix Matrix l(size, size); choleskyDecomposition (a, l); Matrix ch = l * transpose(l); shouldEqualSequenceTolerance(ch.data(), ch.data()+size*size, a.data(), epsilon); } } void testQR() { double epsilon = 1e-11; Matrix idref = vigra::identityMatrix<double>(size); for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_matrix (size, size); Matrix r(size, size); Matrix q(size, size); qrDecomposition (a, q, r); Matrix id = transpose(q) * q; shouldEqualSequenceTolerance(id.data(), id.data()+size*size, idref.data(), epsilon); Matrix qr = q * r; shouldEqualSequenceTolerance(qr.data(), qr.data()+size*size, a.data(), epsilon); } } void testLinearSolve() { double epsilon = 1e-11; int size = 50; for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_matrix (size, size); Matrix b = random_matrix (size, 1); Matrix x(size, 1); should(linearSolve (a, b, x, "QR")); Matrix ax = a * x; shouldEqualSequenceTolerance(ax.data(), ax.data()+size, b.data(), epsilon); should(linearSolve(a, b, x, "SVD")); ax = a * x; shouldEqualSequenceTolerance(ax.data(), ax.data()+size, b.data(), epsilon); should(linearSolve(a, b, x, "NE")); ax = a * x; shouldEqualSequenceTolerance(ax.data(), ax.data()+size, b.data(), epsilon); Matrix c = transpose(a) * a; // make a symmetric positive definite matrix Matrix d = transpose(a) * b; should(linearSolve (c, d, x, "Cholesky")); ax = c * x; shouldEqualSequenceTolerance(ax.data(), ax.data()+size, d.data(), epsilon); } } void testUnderdetermined() { // test singular matrix Matrix a = vigra::identityMatrix<Matrix::value_type> (size); a(0,0) = 0; Matrix b = random_matrix (size, 1); Matrix x(size, 1); should(!linearSolve (a, b, x, "Cholesky")); should(!linearSolve (a, b, x, "QR")); should(!linearSolve (a, b, x, "SVD")); { // square, rank-deficient system (compute minimum norm solution) double mdata[] = {1.0, 3.0, 7.0, -1.0, 4.0, 4.0, 1.0, 10.0, 18.0}; double rhsdata[] = { 5.0, 2.0, 12.0}; double refdata[] = { 0.3850, -0.1103, 0.7066 }; Matrix m(3,3,mdata), rhs(3,1,rhsdata), xx(3,1); shouldEqual(linearSolveQR(m, rhs, xx), 2u); shouldEqualSequenceTolerance(refdata, refdata+3, xx.data(), 1e-3); } { // underdetermined, full-rank system (compute minimum norm solution) double mdata[] = {2.0, -3.0, 1.0, -6.0, 4.0, 1.0, 2.0, 9.0, 3.0, 1.0, 1.0, 8.0}; double rhsdata[] = { -7.0, -7.0, -8.0}; double refdata[] = { -3.26666666666667, 3.6, 5.13333333333333, -0.86666666666667 }; Matrix m(3,4,mdata), rhs(3,1,rhsdata), xx(4,1); shouldEqual(linearSolveQR(m, rhs, xx), 3u); shouldEqualSequenceTolerance(refdata, refdata+4, xx.data(), 1e-12); } { // underdetermined, rank-deficient, consistent system (compute minimum norm solution) double mdata[] = {1.0, 3.0, 3.0, 2.0, 2.0, 6.0, 9.0, 5.0, -1.0, -3.0, 3.0, 0.0}; double rhsdata[] = { 1.0, 5.0, 5.0}; double refdata[] = { -0.211009, -0.633027, 0.963303, 0.110092 }; Matrix m(3,4,mdata), rhs(3,1,rhsdata), xx(4,1); shouldEqual(linearSolveQR(m, rhs, xx), 2u); shouldEqualSequenceTolerance(refdata, refdata+4, xx.data(), 1e-5); } { // underdetermined, rank-deficient, inconsistent system (compute minimum norm least squares solution) double mdata[] = {2.0, 1.0, 7.0, -7.0, -3.0, 4.0, -5.0, -6.0, 1.0, 1.0, 4.0, -5.0}; double rhsdata[] = { 2.0, 3.0, 2.0}; double refdata[] = { -0.0627, 0.1561, -0.0321, -0.3427 }; Matrix m(3,4,mdata), rhs(3,1,rhsdata), xx(4,1); shouldEqual(linearSolveQR(m, rhs, xx), 2u); shouldEqualSequenceTolerance(refdata, refdata+4, xx.data(), 1e-3); } } void testOverdetermined() { double epsilon = 1e-11; unsigned int n = 5; unsigned int size = 1000; double noiseStdDev = 0.1; Matrix A(size, n), xs(n,1), xq(n,1), xn(n,1), r(size, 1); for(unsigned int iter=0; iter<iterations; ++iter) { // set up a linear regression problem for a polynomial of degree n Matrix weights = random_matrix (n, 1); Matrix v = random_matrix (size, 1); // init rhs with Gaussian noise with zero mean and noiseStdDev Matrix rhs = 0.5*noiseStdDev*random_matrix (size, 1); for(unsigned int k=1; k<12; ++k) rhs += 0.5*noiseStdDev*random_matrix (size, 1); for(unsigned int k=0; k<size; ++k) { for(unsigned int l=0; l<n; ++l) { A(k,l) = std::pow(v(k,0), double(l)); rhs(k,0) += weights(l,0)*A(k,l); } } shouldEqual(linearSolve(A, rhs, xs, "SVD"), true); // check that solution is indeed a minimum by // testing for zero derivative of the objective Matrix derivative = abs(transpose(A)*(A*xs - rhs)); int absIndex = argMax(derivative); shouldEqualTolerance(derivative(absIndex,0), 0.0, epsilon); shouldEqual(linearSolveQR(A, rhs, xq), n); shouldEqualSequenceTolerance(xs.data(), xs.data()+n, xq.data(), epsilon); shouldEqual(linearSolve(A, rhs, xn, "ne"), true); shouldEqualSequenceTolerance(xs.data(), xs.data()+n, xn.data(), epsilon); } } void testIncrementalLinearSolve() { double epsilon = 1e-11; int size = 50; for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_matrix (size, size); Matrix b = random_matrix (size, 1); Matrix x(size, 1); should(linearSolve(a, b, x, "QR")); { Matrix r(a), qtb(b), px(size,1), xx(size,1); vigra::ArrayVector<unsigned int> permutation(size); for(int k=0; k<size; ++k) { // use Givens steps for a change (Householder steps like // should(vigra::linalg::detail::qrColumnHouseholderStep(k, r, qtb)); // work as well, but are already extensively tested within the QR algorithm) should(vigra::linalg::detail::qrGivensStepImpl(k, r, qtb)); permutation[k] = k; } for(int k=0; k<size; ++k) { int i = random_.uniformInt(size), j = random_.uniformInt(size); if(i==j) continue; vigra::linalg::detail::upperTriangularCyclicShiftColumns(i, j, r, qtb, permutation); } should(vigra::linalg::linearSolveUpperTriangular(r, qtb, px)); vigra::linalg::detail::inverseRowPermutation(px, xx, permutation); shouldEqualSequenceTolerance(x.data(), x.data()+size, xx.data(), epsilon); } { Matrix r(a), qtb(b), px(size,1), xx(size,1); vigra::ArrayVector<unsigned int> permutation(size); for(int k=0; k<size; ++k) { // use Givens steps for a change (Householder steps like // should(vigra::linalg::detail::qrColumnHouseholderStep(k, r, qtb)); // work as well, but are already extensively tested within the QR algorithm) should(vigra::linalg::detail::qrGivensStepImpl(k, r, qtb)); permutation[k] = k; } for(int k=0; k<size; ++k) { int i = random_.uniformInt(size), j = random_.uniformInt(size); vigra::linalg::detail::upperTriangularSwapColumns(i, j, r, qtb, permutation); } should(vigra::linalg::linearSolveUpperTriangular(r, qtb, px)); vigra::linalg::detail::inverseRowPermutation(px, xx, permutation); shouldEqualSequenceTolerance(x.data(), x.data()+size, xx.data(), epsilon); } } } void testInverse() { double epsilon = 1e-11; Matrix idref = vigra::identityMatrix<double>(size); for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_matrix (size, size); Matrix id = a * inverse(a); shouldEqualSequenceTolerance(id.data(), id.data()+size*size, idref.data(), epsilon); id = inverse(a) * a; shouldEqualSequenceTolerance(id.data(), id.data()+size*size, idref.data(), epsilon); id = inverse(idref * a) * a; // test inverse(const TemporaryMatrix<T> &v) shouldEqualSequenceTolerance(id.data(), id.data()+size*size, idref.data(), epsilon); } double data[] = { 1.0, 0.0, 0.0, 0.0 }; Matrix singular(2, 2, data); try { inverse(singular); failTest("inverse(singular) didn't throw an exception."); } catch(vigra::PreconditionViolation & c) { std::string expected("\nPrecondition violation!\ninverse(): matrix is not invertible."); std::string message(c.what()); should(0 == expected.compare(message.substr(0,expected.size()))); } // test pseudo-inverse double data2[] = { 0., 1., 0., 0., 0., 0., 0., 1., 0., 2., 2., 0., 0., 3., 0. }; double refdata[] = { 0.0, 0.0, 0.15384615384615388, 1.0, 0.0, 0.0, 0.0, 0.2, 0.0, 0.0, 0.0, 0.23076923076923081, 0.0, 0.4, 0.0 }; Matrix m(3, 5, data2), piref(5, 3, refdata), pitref(transpose(piref)); Matrix pi = inverse(m); shouldEqual(pi.shape(), Shape(5, 3)); shouldEqualSequenceTolerance(piref.data(), piref.data()+15, pi.data(), 1e-15); Matrix pit = inverse(transpose(m)); shouldEqual(pit.shape(), Shape(3, 5)); shouldEqualSequenceTolerance(pitref.data(), pitref.data()+15, pit.data(), 1e-15); } void testSymmetricEigensystem() { double epsilon = 1e-8; Matrix idref = vigra::identityMatrix<double>(size); for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_symmetric_matrix (size); Matrix ew(size, 1); Matrix ev(size, size); should(symmetricEigensystem(a, ew, ev)); Matrix id = ev * transpose(ev); shouldEqualSequenceTolerance(id.data(), id.data()+size*size, idref.data(), epsilon); Matrix ae = ev * diagonalMatrix(ew) * transpose(ev); shouldEqualSequenceTolerance(ae.data(), ae.data()+size*size, a.data(), epsilon); } } void testSymmetricEigensystemAnalytic() { double epsilon = 1e-8; int size = 2; for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_symmetric_matrix (size); Matrix ew(size, 1), ewref(size, 1); Matrix ev(size, size); symmetricEigensystem(a, ewref, ev); vigra::symmetric2x2Eigenvalues( a(0,0), a(0,1), a(1,1), &ew(0,0), &ew(1,0)); shouldEqualSequenceTolerance(ew.data(), ew.data()+size, ewref.data(), epsilon); } size = 3; for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_symmetric_matrix (size); Matrix ew(size, 1), ewref(size, 1); Matrix ev(size, size); symmetricEigensystem(a, ewref, ev); vigra::symmetric3x3Eigenvalues<double>( a(0,0), a(0,1), a(0,2), a(1,1), a(1,2), a(2,2), &ew(0,0), &ew(1,0), &ew(2,0)); shouldEqualSequenceTolerance(ew.data(), ew.data()+size, ewref.data(), epsilon); } } void testNonsymmetricEigensystem() { double epsilon = 1e-8; Matrix idref = vigra::identityMatrix<double>(size); for(unsigned int i = 0; i < iterations; ++i) { Matrix a = random_matrix (size, size); vigra::Matrix<std::complex<double> > ew(size, 1); Matrix ev(size, size); should(nonsymmetricEigensystem(a, ew, ev)); Matrix ewm(size, size); for(unsigned int k = 0; k < size; k++) { ewm(k, k) = ew(k, 0).real(); if(ew(k, 0).imag() > 0.0) { ewm(k, k+1) = ew(k, 0).imag(); } else if(ew(k, 0).imag() < 0.0) { ewm(k, k-1) = ew(k, 0).imag(); } } Matrix ae = ev * ewm * inverse(ev); shouldEqualSequenceTolerance(ae.data(), ae.data()+size*size, a.data(), epsilon); } } void testDeterminant() { double ds2[] = {1, 2, 2, 1}; double dns2[] = {1, 2, 3, 1}; Matrix ms2(Shape(2,2), ds2); Matrix mns2(Shape(2,2), dns2); double eps = 1e-12; shouldEqualTolerance(determinant(ms2), -3.0, eps); shouldEqualTolerance(determinant(mns2), -5.0, eps); shouldEqualTolerance(logDeterminant(transpose(ms2)*ms2), std::log(9.0), eps); shouldEqualTolerance(logDeterminant(transpose(mns2)*mns2), std::log(25.0), eps); double ds3[] = {1, 2, 3, 2, 3, 1, 3, 1, 2}; double dns3[] = {1, 2, 3, 5, 3, 1, 3, 1, 2}; Matrix ms3(Shape(3,3), ds3); Matrix mns3(Shape(3,3), dns3); shouldEqualTolerance(determinant(ms3), -18.0, eps); shouldEqualTolerance(determinant(mns3), -21.0, eps); shouldEqualTolerance(determinant(transpose(ms3)*ms3, "Cholesky"), 324.0, eps); shouldEqualTolerance(determinant(transpose(mns3)*mns3, "Cholesky"), 441.0, eps); shouldEqualTolerance(logDeterminant(transpose(ms3)*ms3), std::log(324.0), eps); shouldEqualTolerance(logDeterminant(transpose(mns3)*mns3), std::log(441.0), eps); } void testSVD() { unsigned int m = 6, n = 4; Matrix a(m, n); for(unsigned int i1= 0; i1 < m; i1++) for(unsigned int i2= 0; i2 < n; i2++) a(i1, i2)= random_double(); Matrix u(m, n); Matrix v(n, n); Matrix S(n, 1); unsigned int rank = singularValueDecomposition(a, u, S, v); shouldEqual(rank, n); double eps = 1e-11; shouldEqualToleranceMessage(vigra::norm(a-u*diagonalMatrix(S)*transpose(v)), 0.0, eps, VIGRA_TOLERANCE_MESSAGE); shouldEqualToleranceMessage(vigra::norm(vigra::identityMatrix<double>(4) - transpose(u)*u), 0.0, eps, VIGRA_TOLERANCE_MESSAGE); shouldEqualToleranceMessage(vigra::norm(vigra::identityMatrix<double>(4) - transpose(v)*v), 0.0, eps, VIGRA_TOLERANCE_MESSAGE); shouldEqualToleranceMessage(vigra::norm(vigra::identityMatrix<double>(4) - v*transpose(v)), 0.0, eps, VIGRA_TOLERANCE_MESSAGE); } }; struct RandomTest { void testTT800() { const unsigned int n = 50; unsigned int iref[n] = { 3169973338U, 2724982910U, 347012937U, 1735893326U, 2282497071U, 3975116866U, 62755666U, 500522132U, 129776071U, 1978109378U, 4040131704U, 3800592193U, 3057303977U, 1468369496U, 370579849U, 3630178833U, 51910867U, 819270944U, 476180518U, 190380673U, 1370447020U, 1620916304U, 663482756U, 1354889312U, 4000276916U, 868393086U, 1441698743U, 1086138563U, 1899869374U, 3717419747U, 2455034041U, 2617437696U, 1595651084U, 4148285605U, 1860328467U, 928897371U, 263340857U, 4091726170U, 2359987311U, 1669697327U, 1882626857U, 1635656338U, 897501559U, 3233276032U, 373770970U, 2950632840U, 2706386845U, 3294066568U, 3819538748U, 1902519841U }; vigra::RandomTT800 random; for(unsigned int k=0; k<n; ++k) shouldEqual(random(), iref[k]); double fref[n] = { 0.738067, 0.634460, 0.080795, 0.404169, 0.531435, 0.925529, 0.014611, 0.116537, 0.030216, 0.460564, 0.940666, 0.884894, 0.711834, 0.341881, 0.086282, 0.845217, 0.012086, 0.190751, 0.110869, 0.044326, 0.319082, 0.377399, 0.154479, 0.315460, 0.931387, 0.202189, 0.335672, 0.252886, 0.442348, 0.865529, 0.571607, 0.609420, 0.371516, 0.965848, 0.433141, 0.216276, 0.061314, 0.952679, 0.549477, 0.388757, 0.438333, 0.380831, 0.208966, 0.752806, 0.087025, 0.686998, 0.630130, 0.766960, 0.889306, 0.442965 }; vigra::RandomTT800 randomf; for(unsigned int k=0; k<n; ++k) should(vigra::abs(randomf.uniform() - fref[k]) < 2e-6); vigra::RandomTT800 randomr(vigra::RandomSeed); } void testMT19937() { const unsigned int n = 20, skip = 960, ilen = 4; unsigned int first[n] = { 956529277U, 3842322136U, 3319553134U, 1843186657U, 2704993644U, 595827513U, 938518626U, 1676224337U, 3221315650U, 1819026461U, 2401778706U, 2494028885U, 767405145U, 1590064561U, 2766888951U, 3951114980U, 2568046436U, 2550998890U, 2642089177U, 568249289U }; unsigned int last[n] = { 2396869032U, 1982500200U, 2649478910U, 839934727U, 3814542520U, 918389387U, 995030736U, 2017568170U, 2621335422U, 1020082601U, 24244213U, 2575242697U, 3941971804U, 922591409U, 2851763435U, 2055641408U, 3695291669U, 2040276077U, 4118847636U, 3528766079U }; vigra::RandomMT19937 random(0xDEADBEEF); for(unsigned int k=0; k<n; ++k) shouldEqual(random(), first[k]); for(unsigned int k=0; k<skip; ++k) random(); for(unsigned int k=0; k<n; ++k) shouldEqual(random(), last[k]); for(unsigned int k=0; k<skip; ++k) should(random.uniformInt(31) < 31); random.seed(0xDEADBEEF); for(unsigned int k=0; k<n; ++k) shouldEqual(random(), first[k]); for(unsigned int k=0; k<skip; ++k) random(); for(unsigned int k=0; k<n; ++k) shouldEqual(random(), last[k]); unsigned int firsta[n] = { 1067595299U, 955945823U, 477289528U, 4107218783U, 4228976476U, 3344332714U, 3355579695U, 227628506U, 810200273U, 2591290167U, 2560260675U, 3242736208U, 646746669U, 1479517882U, 4245472273U, 1143372638U, 3863670494U, 3221021970U, 1773610557U, 1138697238U }; unsigned int lasta[n] = { 123599888U, 472658308U, 1053598179U, 1012713758U, 3481064843U, 3759461013U, 3981457956U, 3830587662U, 1877191791U, 3650996736U, 988064871U, 3515461600U, 4089077232U, 2225147448U, 1249609188U, 2643151863U, 3896204135U, 2416995901U, 1397735321U, 3460025646U }; unsigned int init[ilen] = {0x123, 0x234, 0x345, 0x456}; vigra::RandomMT19937 randoma(init, ilen); for(unsigned int k=0; k<n; ++k) shouldEqual(randoma(), firsta[k]); for(unsigned int k=0; k<skip; ++k) randoma(); for(unsigned int k=0; k<n; ++k) shouldEqual(randoma(), lasta[k]); double ref53[n] = { 0.76275444, 0.98670464, 0.27933125, 0.94218739, 0.78842173, 0.92179002, 0.54534773, 0.38107717, 0.65286910, 0.22765212, 0.74557914, 0.54708246, 0.42043117, 0.19189126, 0.70259889, 0.77408120, 0.04605807, 0.69398269, 0.61711170, 0.10133577}; for(unsigned int k=0; k<n; ++k) should(vigra::abs(randoma.uniform53()-ref53[k]) < 2e-8); randoma.seed(init, ilen); for(unsigned int k=0; k<n; ++k) shouldEqual(randoma(), firsta[k]); for(unsigned int k=0; k<skip; ++k) randoma(); for(unsigned int k=0; k<n; ++k) shouldEqual(randoma(), lasta[k]); } void testRandomFunctors() { const unsigned int n = 50; unsigned int iref[n] = { 3169973338U, 2724982910U, 347012937U, 1735893326U, 2282497071U, 3975116866U, 62755666U, 500522132U, 129776071U, 1978109378U, 4040131704U, 3800592193U, 3057303977U, 1468369496U, 370579849U, 3630178833U, 51910867U, 819270944U, 476180518U, 190380673U, 1370447020U, 1620916304U, 663482756U, 1354889312U, 4000276916U, 868393086U, 1441698743U, 1086138563U, 1899869374U, 3717419747U, 2455034041U, 2617437696U, 1595651084U, 4148285605U, 1860328467U, 928897371U, 263340857U, 4091726170U, 2359987311U, 1669697327U, 1882626857U, 1635656338U, 897501559U, 3233276032U, 373770970U, 2950632840U, 2706386845U, 3294066568U, 3819538748U, 1902519841U }; double fref[n] = { 0.738067, 0.634460, 0.080795, 0.404169, 0.531435, 0.925529, 0.014611, 0.116537, 0.030216, 0.460564, 0.940666, 0.884894, 0.711834, 0.341881, 0.086282, 0.845217, 0.012086, 0.190751, 0.110869, 0.044326, 0.319082, 0.377399, 0.154479, 0.315460, 0.931387, 0.202189, 0.335672, 0.252886, 0.442348, 0.865529, 0.571607, 0.609420, 0.371516, 0.965848, 0.433141, 0.216276, 0.061314, 0.952679, 0.549477, 0.388757, 0.438333, 0.380831, 0.208966, 0.752806, 0.087025, 0.686998, 0.630130, 0.766960, 0.889306, 0.442965 }; double nref[n] = { 1.35298, 0.764158, -0.757076, -0.173069, 0.0586711, 0.794212, -0.483372, -0.0405762, 1.27956, -0.955101, -1.5062, -1.02069, -0.871562, -0.465495, -0.799888, -1.20286, -0.170944, 1.08383, 1.26832, 1.93807, -0.098183, 0.355986, -0.336965, -1.42996, 0.966012, -2.17195, -1.05422, -2.03724, -0.769992, 0.668851, -0.570259, 0.258217, 0.632492, 1.29755, 0.96869, -0.141918, -0.836236, -0.62337, 0.116509, -0.0314471, 0.402451, -1.20504, -0.140861, -0.0765263, 1.06057, 2.57671, 0.0299117, 0.471425, 1.59464, 1.37346}; vigra::RandomTT800 random1; vigra::UniformRandomFunctor<> f1(random1); for(unsigned int k=0; k<n; ++k) should(vigra::abs(f1() - fref[k]) < 2e-6); vigra::RandomTT800 random2; vigra::UniformIntRandomFunctor<> f2(4, 34, random2, true); for(unsigned int k=0; k<n; ++k) shouldEqual(f2(), iref[k] % 31 + 4); vigra::RandomTT800 random3; vigra::UniformIntRandomFunctor<> f3(random3); for(unsigned int k=0; k<n; ++k) shouldEqual(f3(32), iref[k] % 32); vigra::RandomTT800 random4; vigra::NormalRandomFunctor<> f4(random4); for(unsigned int k=0; k<n; ++k) shouldEqualTolerance(f4(), nref[k], 1e-5); } }; struct PolygonTest { typedef vigra::TinyVector<double, 2> Point; void testConvexHull() { vigra::ArrayVector<Point> points, reference, hull; points.push_back(Point(0.0, 0.0)); points.push_back(Point(2.0, 1.0)); points.push_back(Point(2.0, -1.0)); points.push_back(Point(0.0, 2.0)); points.push_back(Point(-2.0, 1.0)); points.push_back(Point(-2.0, -1.0)); points.push_back(Point(0.0, -2.0)); reference.push_back(Point(-2.0, -1.0)); reference.push_back(Point(0.0, -2.0)); reference.push_back(Point(2.0, -1.0)); reference.push_back(Point(2.0, 1.0)); reference.push_back(Point(0.0, 2.0)); reference.push_back(Point(-2.0, 1.0)); reference.push_back(Point(-2.0, -1.0)); vigra::convexHull(points, hull); shouldEqual(7u, hull.size()); shouldEqualSequence(reference.begin(), reference.end(), hull.begin()); hull.clear(); vigra::convexHull(reference, hull); shouldEqual(7u, hull.size()); shouldEqualSequence(reference.begin(), reference.end(), hull.begin()); typedef Point P; P p[200] = { P(0.0, 0.0), P(42.0, 468.0), P(335.0, 501.0), P(170.0, 725.0), P(479.0, 359.0), P(963.0, 465.0), P(706.0, 146.0), P(282.0, 828.0), P(962.0, 492.0), P(996.0, 943.0), P(828.0, 437.0), P(392.0, 605.0), P(903.0, 154.0), P(293.0, 383.0), P(422.0, 717.0), P(719.0, 896.0), P(448.0, 727.0), P(772.0, 539.0), P(870.0, 913.0), P(668.0, 300.0), P(36.0, 895.0), P(704.0, 812.0), P(323.0, 334.0), P(674.0, 665.0), P(142.0, 712.0), P(254.0, 869.0), P(548.0, 645.0), P(663.0, 758.0), P(38.0, 860.0), P(724.0, 742.0), P(530.0, 779.0), P(317.0, 36.0), P(191.0, 843.0), P(289.0, 107.0), P(41.0, 943.0), P(265.0, 649.0), P(447.0, 806.0), P(891.0, 730.0), P(371.0, 351.0), P(7.0, 102.0), P(394.0, 549.0), P(630.0, 624.0), P(85.0, 955.0), P(757.0, 841.0), P(967.0, 377.0), P(932.0, 309.0), P(945.0, 440.0), P(627.0, 324.0), P(538.0, 539.0), P(119.0, 83.0), P(930.0, 542.0), P(834.0, 116.0), P(640.0, 659.0), P(705.0, 931.0), P(978.0, 307.0), P(674.0, 387.0), P(22.0, 746.0), P(925.0, 73.0), P(271.0, 830.0), P(778.0, 574.0), P(98.0, 513.0), P(987.0, 291.0), P(162.0, 637.0), P(356.0, 768.0), P(656.0, 575.0), P(32.0, 53.0), P(351.0, 151.0), P(942.0, 725.0), P(967.0, 431.0), P(108.0, 192.0), P(8.0, 338.0), P(458.0, 288.0), P(754.0, 384.0), P(946.0, 910.0), P(210.0, 759.0), P(222.0, 589.0), P(423.0, 947.0), P(507.0, 31.0), P(414.0, 169.0), P(901.0, 592.0), P(763.0, 656.0), P(411.0, 360.0), P(625.0, 538.0), P(549.0, 484.0), P(596.0, 42.0), P(603.0, 351.0), P(292.0, 837.0), P(375.0, 21.0), P(597.0, 22.0), P(349.0, 200.0), P(669.0, 485.0), P(282.0, 735.0), P(54.0, 1000.0), P(419.0, 939.0), P(901.0, 789.0), P(128.0, 468.0), P(729.0, 894.0), P(649.0, 484.0), P(808.0, 422.0), P(311.0, 618.0), P(814.0, 515.0), P(310.0, 617.0), P(936.0, 452.0), P(601.0, 250.0), P(520.0, 557.0), P(799.0, 304.0), P(225.0, 9.0), P(845.0, 610.0), P(990.0, 703.0), P(196.0, 486.0), P(94.0, 344.0), P(524.0, 588.0), P(315.0, 504.0), P(449.0, 201.0), P(459.0, 619.0), P(581.0, 797.0), P(799.0, 282.0), P(590.0, 799.0), P(10.0, 158.0), P(473.0, 623.0), P(539.0, 293.0), P(39.0, 180.0), P(191.0, 658.0), P(959.0, 192.0), P(816.0, 889.0), P(157.0, 512.0), P(203.0, 635.0), P(273.0, 56.0), P(329.0, 647.0), P(363.0, 887.0), P(876.0, 434.0), P(870.0, 143.0), P(845.0, 417.0), P(882.0, 999.0), P(323.0, 652.0), P(22.0, 700.0), P(558.0, 477.0), P(893.0, 390.0), P(76.0, 713.0), P(601.0, 511.0), P(4.0, 870.0), P(862.0, 689.0), P(402.0, 790.0), P(256.0, 424.0), P(3.0, 586.0), P(183.0, 286.0), P(89.0, 427.0), P(618.0, 758.0), P(833.0, 933.0), P(170.0, 155.0), P(722.0, 190.0), P(977.0, 330.0), P(369.0, 693.0), P(426.0, 556.0), P(435.0, 550.0), P(442.0, 513.0), P(146.0, 61.0), P(719.0, 754.0), P(140.0, 424.0), P(280.0, 997.0), P(688.0, 530.0), P(550.0, 438.0), P(867.0, 950.0), P(194.0, 196.0), P(298.0, 417.0), P(287.0, 106.0), P(489.0, 283.0), P(456.0, 735.0), P(115.0, 702.0), P(317.0, 672.0), P(787.0, 264.0), P(314.0, 356.0), P(186.0, 54.0), P(913.0, 809.0), P(833.0, 946.0), P(314.0, 757.0), P(322.0, 559.0), P(647.0, 983.0), P(482.0, 145.0), P(197.0, 223.0), P(130.0, 162.0), P(536.0, 451.0), P(174.0, 467.0), P(45.0, 660.0), P(293.0, 440.0), P(254.0, 25.0), P(155.0, 511.0), P(746.0, 650.0), P(187.0, 314.0), P(475.0, 23.0), P(169.0, 19.0), P(788.0, 906.0), P(959.0, 392.0), P(203.0, 626.0), P(478.0, 415.0), P(315.0, 825.0), P(335.0, 875.0), P(373.0, 160.0), P(834.0, 71.0), P(488.0, 298.0) }; P ref[10] = { P(0.0, 0.0), P(597.0, 22.0), P(925.0, 73.0), P(959.0, 192.0), P(987.0, 291.0), P(996.0, 943.0), P(882.0, 999.0), P(54.0, 1000.0), P(4.0, 870.0), P(0.0, 0.0) }; points = vigra::ArrayVector<Point>(p, p+200); hull.clear(); vigra::convexHull(points, hull); shouldEqual(10u, hull.size()); shouldEqualSequence(ref, ref+10, hull.begin()); int size = sizeof(convexHullInputs) / sizeof(Point); points = vigra::ArrayVector<Point>(convexHullInputs, convexHullInputs+size); hull.clear(); vigra::convexHull(points, hull); shouldEqual(17u, hull.size()); shouldEqualSequence(convexHullReference, convexHullReference+17, hull.begin()); } }; struct MathTestSuite : public vigra::test_suite { MathTestSuite() : vigra::test_suite("MathTest") { typedef vigra::Polynomial<double> P1; typedef vigra::StaticPolynomial<10, double> P2; add( testCase((&PolynomialTest<0, P1>::testPolynomial))); add( testCase((&PolynomialTest<1, P1>::testPolynomial))); add( testCase((&PolynomialTest<2, P1>::testPolynomial))); add( testCase((&PolynomialTest<3, P1>::testPolynomial))); add( testCase((&PolynomialTest<4, P1>::testPolynomial))); add( testCase((&PolynomialTest<5, P1>::testPolynomial))); add( testCase((&PolynomialTest<6, P1>::testPolynomial))); add( testCase((&PolynomialTest<7, P1>::testPolynomial))); // test only some polynomials, as the eigenvalue method is less robust add( testCase((&PolynomialTest<1, P1>::testPolynomialEigenvalueMethod))); add( testCase((&PolynomialTest<5, P1>::testPolynomialEigenvalueMethod))); add( testCase((&PolynomialTest<6, P1>::testPolynomialEigenvalueMethod))); add( testCase((&PolynomialTest<7, P1>::testPolynomialEigenvalueMethod))); add( testCase((&PolynomialTest<0, P2>::testPolynomial))); add( testCase((&PolynomialTest<1, P2>::testPolynomial))); add( testCase((&PolynomialTest<2, P2>::testPolynomial))); add( testCase(&HighOrderPolynomialTest::testPolynomial)); add( testCase(&HighOrderPolynomialTest::testPolynomialEigenvalueMethod)); add( testCase(&SplineTest<0>::testValues)); add( testCase(&SplineTest<1>::testValues)); add( testCase(&SplineTest<2>::testValues)); add( testCase(&SplineTest<3>::testValues)); add( testCase(&SplineTest<4>::testValues)); add( testCase(&SplineTest<5>::testValues)); add( testCase(&SplineTest<0>::testFixedPointValues)); add( testCase(&SplineTest<1>::testFixedPointValues)); add( testCase(&SplineTest<2>::testFixedPointValues)); add( testCase(&SplineTest<3>::testFixedPointValues)); add( testCase(&SplineTest<0>::testPrefilterCoefficients)); add( testCase(&SplineTest<1>::testPrefilterCoefficients)); add( testCase(&SplineTest<2>::testPrefilterCoefficients)); add( testCase(&SplineTest<3>::testPrefilterCoefficients)); add( testCase(&SplineTest<4>::testPrefilterCoefficients)); add( testCase(&SplineTest<5>::testPrefilterCoefficients)); add( testCase(&SplineTest<0>::testWeightMatrix)); add( testCase(&SplineTest<1>::testWeightMatrix)); add( testCase(&SplineTest<2>::testWeightMatrix)); add( testCase(&SplineTest<3>::testWeightMatrix)); add( testCase(&SplineTest<4>::testWeightMatrix)); add( testCase(&SplineTest<5>::testWeightMatrix)); add( testCase(&FunctionsTest::testGaussians)); add( testCase(&FunctionsTest::testSpecialIntegerFunctions)); add( testCase(&FunctionsTest::testSpecialFunctions)); add( testCase(&FunctionsTest::testBessel)); add( testCase(&FunctionsTest::closeAtToleranceTest)); add( testCase(&FunctionsTest::testArgMinMax)); add( testCase(&FunctionsTest::testAlgorithms)); add( testCase(&FunctionsTest::testChecksum)); add( testCase(&FunctionsTest::testClebschGordan)); add( testCase(&RationalTest::testGcdLcm)); add( testCase(&RationalTest::testOStreamShifting)); add( testCase(&RationalTest::testOperators)); add( testCase(&RationalTest::testConversion)); add( testCase(&RationalTest::testFunctions)); add( testCase(&RationalTest::testInf)); add( testCase(&QuaternionTest::testContents)); add( testCase(&QuaternionTest::testStreamIO)); add( testCase(&QuaternionTest::testOperators)); add( testCase(&QuaternionTest::testRotation)); add( testCase(&LinalgTest::testOStreamShifting)); add( testCase(&LinalgTest::testMatrix)); add( testCase(&LinalgTest::testArgMinMax)); add( testCase(&LinalgTest::testColumnAndRowStatistics)); add( testCase(&LinalgTest::testColumnAndRowPreparation)); add( testCase(&LinalgTest::testCholesky)); add( testCase(&LinalgTest::testQR)); add( testCase(&LinalgTest::testLinearSolve)); add( testCase(&LinalgTest::testUnderdetermined)); add( testCase(&LinalgTest::testOverdetermined)); add( testCase(&LinalgTest::testIncrementalLinearSolve)); add( testCase(&LinalgTest::testInverse)); add( testCase(&LinalgTest::testSymmetricEigensystem)); add( testCase(&LinalgTest::testNonsymmetricEigensystem)); add( testCase(&LinalgTest::testSymmetricEigensystemAnalytic)); add( testCase(&LinalgTest::testDeterminant)); add( testCase(&LinalgTest::testSVD)); add( testCase(&FixedPointTest::testConstruction)); add( testCase(&FixedPointTest::testComparison)); add( testCase(&FixedPointTest::testArithmetic)); add( testCase(&FixedPoint16Test::testConstruction)); add( testCase(&FixedPoint16Test::testComparison)); add( testCase(&FixedPoint16Test::testArithmetic)); add( testCase(&RandomTest::testTT800)); add( testCase(&RandomTest::testMT19937)); add( testCase(&RandomTest::testRandomFunctors)); add( testCase(&PolygonTest::testConvexHull)); } }; int main(int argc, char ** argv) { try { MathTestSuite test; int failed = test.run(vigra::testsToBeExecuted(argc, argv)); std::cerr << test.report() << std::endl; return (failed != 0); } catch(std::exception & e) { std::cerr << "Unexpected exception: " << e.what() << "\n"; return 1; } }
43.291034
138
0.546964
[ "shape", "vector" ]
780fb2087970912450c83fd2e9be53ed121fd4e0
24,586
cpp
C++
frameworks/compile/mclinker/lib/Target/ARM/ARMLDBackend.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2022-01-07T01:53:19.000Z
2022-01-07T01:53:19.000Z
frameworks/compile/mclinker/lib/Target/ARM/ARMLDBackend.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
null
null
null
frameworks/compile/mclinker/lib/Target/ARM/ARMLDBackend.cpp
touxiong88/92_mediatek
5e96a7bb778fd9d9b335825584664e0c8b5ff2c7
[ "Apache-2.0" ]
1
2020-02-28T02:48:42.000Z
2020-02-28T02:48:42.000Z
//===- ARMLDBackend.cpp ---------------------------------------------------===// // // The MCLinker Project // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "ARM.h" #include "ARMGNUInfo.h" #include "ARMELFAttributeData.h" #include "ARMELFDynamic.h" #include "ARMLDBackend.h" #include "ARMRelocator.h" #include "ARMToARMStub.h" #include "ARMToTHMStub.h" #include "THMToTHMStub.h" #include "THMToARMStub.h" #include <cstring> #include <llvm/ADT/Triple.h> #include <llvm/ADT/Twine.h> #include <llvm/Support/ELF.h> #include <llvm/Support/Casting.h> #include <mcld/IRBuilder.h> #include <mcld/LinkerConfig.h> #include <mcld/Fragment/FillFragment.h> #include <mcld/Fragment/AlignFragment.h> #include <mcld/Fragment/RegionFragment.h> #include <mcld/Fragment/Stub.h> #include <mcld/Fragment/NullFragment.h> #include <mcld/Support/MemoryRegion.h> #include <mcld/Support/MemoryArea.h> #include <mcld/Support/MsgHandling.h> #include <mcld/Support/TargetRegistry.h> #include <mcld/LD/BranchIslandFactory.h> #include <mcld/LD/StubFactory.h> #include <mcld/LD/LDContext.h> #include <mcld/LD/ELFFileFormat.h> #include <mcld/LD/ELFSegmentFactory.h> #include <mcld/LD/ELFSegment.h> #include <mcld/Target/ELFAttribute.h> #include <mcld/Target/GNUInfo.h> #include <mcld/Object/ObjectBuilder.h> using namespace mcld; //===----------------------------------------------------------------------===// // ARMGNULDBackend //===----------------------------------------------------------------------===// ARMGNULDBackend::ARMGNULDBackend(const LinkerConfig& pConfig, GNUInfo* pInfo) : GNULDBackend(pConfig, pInfo), m_pRelocator(NULL), m_pGOT(NULL), m_pPLT(NULL), m_pRelDyn(NULL), m_pRelPLT(NULL), m_pAttrData(NULL), m_pDynamic(NULL), m_pGOTSymbol(NULL), m_pEXIDXStart(NULL), m_pEXIDXEnd(NULL), m_pEXIDX(NULL), m_pEXTAB(NULL), m_pAttributes(NULL) { } ARMGNULDBackend::~ARMGNULDBackend() { delete m_pRelocator; delete m_pGOT; delete m_pPLT; delete m_pRelDyn; delete m_pRelPLT; delete m_pDynamic; delete m_pAttrData; } void ARMGNULDBackend::initTargetSections(Module& pModule, ObjectBuilder& pBuilder) { // FIXME: Currently we set exidx and extab to "Exception" and directly emit // them from input m_pEXIDX = pBuilder.CreateSection(".ARM.exidx", LDFileFormat::Target, llvm::ELF::SHT_ARM_EXIDX, llvm::ELF::SHF_ALLOC | llvm::ELF::SHF_LINK_ORDER, config().targets().bitclass() / 8); m_pEXTAB = pBuilder.CreateSection(".ARM.extab", LDFileFormat::Target, llvm::ELF::SHT_PROGBITS, llvm::ELF::SHF_ALLOC, 0x1); m_pAttributes = pBuilder.CreateSection(".ARM.attributes", LDFileFormat::Target, llvm::ELF::SHT_ARM_ATTRIBUTES, 0x0, 0x1); // initialize "aeabi" attributes subsection m_pAttrData = new ARMELFAttributeData(); attribute().registerAttributeData(*m_pAttrData); if (LinkerConfig::Object != config().codeGenType()) { ELFFileFormat* file_format = getOutputFormat(); // initialize .got LDSection& got = file_format->getGOT(); m_pGOT = new ARMGOT(got); // initialize .plt LDSection& plt = file_format->getPLT(); m_pPLT = new ARMPLT(plt, *m_pGOT); // initialize .rel.plt LDSection& relplt = file_format->getRelPlt(); relplt.setLink(&plt); // create SectionData and ARMRelDynSection m_pRelPLT = new OutputRelocSection(pModule, relplt); // initialize .rel.dyn LDSection& reldyn = file_format->getRelDyn(); m_pRelDyn = new OutputRelocSection(pModule, reldyn); } } void ARMGNULDBackend::initTargetSymbols(IRBuilder& pBuilder, Module& pModule) { // Define the symbol _GLOBAL_OFFSET_TABLE_ if there is a symbol with the // same name in input if (LinkerConfig::Object != config().codeGenType()) { m_pGOTSymbol = pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>( "_GLOBAL_OFFSET_TABLE_", ResolveInfo::Object, ResolveInfo::Define, ResolveInfo::Local, 0x0, // size 0x0, // value FragmentRef::Null(), ResolveInfo::Hidden); } if (NULL != m_pEXIDX && 0x0 != m_pEXIDX->size()) { FragmentRef* exidx_start = FragmentRef::Create(m_pEXIDX->getSectionData()->front(), 0x0); FragmentRef* exidx_end = FragmentRef::Create(m_pEXIDX->getSectionData()->front(), m_pEXIDX->size()); m_pEXIDXStart = pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>( "__exidx_start", ResolveInfo::Object, ResolveInfo::Define, ResolveInfo::Local, 0x0, // size 0x0, // value exidx_start, // FragRef ResolveInfo::Default); m_pEXIDXEnd = pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>( "__exidx_end", ResolveInfo::Object, ResolveInfo::Define, ResolveInfo::Local, 0x0, // size 0x0, // value exidx_end, // FragRef ResolveInfo::Default); // change __exidx_start/_end to local dynamic category if (NULL != m_pEXIDXStart) pModule.getSymbolTable().changeToDynamic(*m_pEXIDXStart); if (NULL != m_pEXIDXEnd) pModule.getSymbolTable().changeToDynamic(*m_pEXIDXEnd); } else { m_pEXIDXStart = pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>( "__exidx_start", ResolveInfo::NoType, ResolveInfo::Define, ResolveInfo::Absolute, 0x0, // size 0x0, // value FragmentRef::Null(), ResolveInfo::Default); m_pEXIDXEnd = pBuilder.AddSymbol<IRBuilder::AsReferred, IRBuilder::Resolve>( "__exidx_end", ResolveInfo::NoType, ResolveInfo::Define, ResolveInfo::Absolute, 0x0, // size 0x0, // value FragmentRef::Null(), ResolveInfo::Default); } } bool ARMGNULDBackend::initRelocator() { if (NULL == m_pRelocator) { m_pRelocator = new ARMRelocator(*this, config()); } return true; } Relocator* ARMGNULDBackend::getRelocator() { assert(NULL != m_pRelocator); return m_pRelocator; } void ARMGNULDBackend::doPreLayout(IRBuilder& pBuilder) { // initialize .dynamic data if (!config().isCodeStatic() && NULL == m_pDynamic) m_pDynamic = new ARMELFDynamic(*this, config()); // set attribute section size m_pAttributes->setSize(attribute().sizeOutput()); // set .got size // when building shared object, the .got section is must if (LinkerConfig::Object != config().codeGenType()) { if (LinkerConfig::DynObj == config().codeGenType() || m_pGOT->hasGOT1() || NULL != m_pGOTSymbol) { m_pGOT->finalizeSectionSize(); defineGOTSymbol(pBuilder); } // set .plt size if (m_pPLT->hasPLT1()) m_pPLT->finalizeSectionSize(); ELFFileFormat* file_format = getOutputFormat(); // set .rel.dyn size if (!m_pRelDyn->empty()) { assert(!config().isCodeStatic() && "static linkage should not result in a dynamic relocation section"); file_format->getRelDyn().setSize( m_pRelDyn->numOfRelocs() * getRelEntrySize()); } // set .rel.plt size if (!m_pRelPLT->empty()) { assert(!config().isCodeStatic() && "static linkage should not result in a dynamic relocation section"); file_format->getRelPlt().setSize( m_pRelPLT->numOfRelocs() * getRelEntrySize()); } } } void ARMGNULDBackend::doPostLayout(Module& pModule, IRBuilder& pBuilder) { const ELFFileFormat *file_format = getOutputFormat(); // apply PLT if (file_format->hasPLT()) { // Since we already have the size of LDSection PLT, m_pPLT should not be // NULL. assert(NULL != m_pPLT); m_pPLT->applyPLT0(); m_pPLT->applyPLT1(); } // apply GOT if (file_format->hasGOT()) { // Since we already have the size of GOT, m_pGOT should not be NULL. assert(NULL != m_pGOT); if (LinkerConfig::DynObj == config().codeGenType()) m_pGOT->applyGOT0(file_format->getDynamic().addr()); else { // executable file and object file? should fill with zero. m_pGOT->applyGOT0(0); } } } /// dynamic - the dynamic section of the target machine. /// Use co-variant return type to return its own dynamic section. ARMELFDynamic& ARMGNULDBackend::dynamic() { assert(NULL != m_pDynamic); return *m_pDynamic; } /// dynamic - the dynamic section of the target machine. /// Use co-variant return type to return its own dynamic section. const ARMELFDynamic& ARMGNULDBackend::dynamic() const { assert(NULL != m_pDynamic); return *m_pDynamic; } void ARMGNULDBackend::defineGOTSymbol(IRBuilder& pBuilder) { // define symbol _GLOBAL_OFFSET_TABLE_ when .got create if (m_pGOTSymbol != NULL) { pBuilder.AddSymbol<IRBuilder::Force, IRBuilder::Unresolve>( "_GLOBAL_OFFSET_TABLE_", ResolveInfo::Object, ResolveInfo::Define, ResolveInfo::Local, 0x0, // size 0x0, // value FragmentRef::Create(*(m_pGOT->begin()), 0x0), ResolveInfo::Hidden); } else { m_pGOTSymbol = pBuilder.AddSymbol<IRBuilder::Force, IRBuilder::Resolve>( "_GLOBAL_OFFSET_TABLE_", ResolveInfo::Object, ResolveInfo::Define, ResolveInfo::Local, 0x0, // size 0x0, // value FragmentRef::Create(*(m_pGOT->begin()), 0x0), ResolveInfo::Hidden); } } uint64_t ARMGNULDBackend::emitSectionData(const LDSection& pSection, MemoryRegion& pRegion) const { assert(pRegion.size() && "Size of MemoryRegion is zero!"); const ELFFileFormat* file_format = getOutputFormat(); if (&pSection == &(file_format->getPLT())) { assert(NULL != m_pPLT && "emitSectionData failed, m_pPLT is NULL!"); uint64_t result = m_pPLT->emit(pRegion); return result; } if (&pSection == &(file_format->getGOT())) { assert(NULL != m_pGOT && "emitSectionData failed, m_pGOT is NULL!"); uint64_t result = m_pGOT->emit(pRegion); return result; } if (&pSection == m_pAttributes) { return attribute().emit(pRegion); } // FIXME: Currently Emitting .ARM.attributes, .ARM.exidx, and .ARM.extab // directly from the input file. const SectionData* sect_data = pSection.getSectionData(); SectionData::const_iterator frag_iter, frag_end = sect_data->end(); uint8_t* out_offset = pRegion.start(); for (frag_iter = sect_data->begin(); frag_iter != frag_end; ++frag_iter) { size_t size = frag_iter->size(); switch(frag_iter->getKind()) { case Fragment::Fillment: { const FillFragment& fill_frag = llvm::cast<FillFragment>(*frag_iter); if (0 == fill_frag.getValueSize()) { // virtual fillment, ignore it. break; } memset(out_offset, fill_frag.getValue(), fill_frag.size()); break; } case Fragment::Region: { const RegionFragment& region_frag = llvm::cast<RegionFragment>(*frag_iter); const uint8_t* start = region_frag.getRegion().start(); memcpy(out_offset, start, size); break; } case Fragment::Alignment: { const AlignFragment& align_frag = llvm::cast<AlignFragment>(*frag_iter); uint64_t count = size / align_frag.getValueSize(); switch (align_frag.getValueSize()) { case 1u: std::memset(out_offset, align_frag.getValue(), count); break; default: llvm::report_fatal_error( "unsupported value size for align fragment emission yet.\n"); break; } // end switch break; } case Fragment::Null: { assert(0x0 == size); break; } default: llvm::report_fatal_error("unsupported fragment type.\n"); break; } // end switch out_offset += size; } // end for return pRegion.size(); } /// finalizeSymbol - finalize the symbol value bool ARMGNULDBackend::finalizeTargetSymbols() { return true; } bool ARMGNULDBackend::mergeSection(Module& pModule, const Input& pInput, LDSection& pSection) { switch (pSection.type()) { case llvm::ELF::SHT_ARM_ATTRIBUTES: { return attribute().merge(pInput, pSection); } default: { ObjectBuilder builder(config(), pModule); builder.MergeSection(pInput, pSection); return true; } } // end of switch return true; } bool ARMGNULDBackend::readSection(Input& pInput, SectionData& pSD) { Fragment* frag = NULL; uint32_t offset = pInput.fileOffset() + pSD.getSection().offset(); uint32_t size = pSD.getSection().size(); MemoryRegion* region = pInput.memArea()->request(offset, size); if (NULL == region) { // If the input section's size is zero, we got a NULL region. // use a virtual fill fragment frag = new FillFragment(0x0, 0, 0); } else { frag = new RegionFragment(*region); } ObjectBuilder::AppendFragment(*frag, pSD); return true; } ARMGOT& ARMGNULDBackend::getGOT() { assert(NULL != m_pGOT && "GOT section not exist"); return *m_pGOT; } const ARMGOT& ARMGNULDBackend::getGOT() const { assert(NULL != m_pGOT && "GOT section not exist"); return *m_pGOT; } ARMPLT& ARMGNULDBackend::getPLT() { assert(NULL != m_pPLT && "PLT section not exist"); return *m_pPLT; } const ARMPLT& ARMGNULDBackend::getPLT() const { assert(NULL != m_pPLT && "PLT section not exist"); return *m_pPLT; } OutputRelocSection& ARMGNULDBackend::getRelDyn() { assert(NULL != m_pRelDyn && ".rel.dyn section not exist"); return *m_pRelDyn; } const OutputRelocSection& ARMGNULDBackend::getRelDyn() const { assert(NULL != m_pRelDyn && ".rel.dyn section not exist"); return *m_pRelDyn; } OutputRelocSection& ARMGNULDBackend::getRelPLT() { assert(NULL != m_pRelPLT && ".rel.plt section not exist"); return *m_pRelPLT; } const OutputRelocSection& ARMGNULDBackend::getRelPLT() const { assert(NULL != m_pRelPLT && ".rel.plt section not exist"); return *m_pRelPLT; } ARMELFAttributeData& ARMGNULDBackend::getAttributeData() { assert(NULL != m_pAttrData && ".ARM.attributes section not exist"); return *m_pAttrData; } const ARMELFAttributeData& ARMGNULDBackend::getAttributeData() const { assert(NULL != m_pAttrData && ".ARM.attributes section not exist"); return *m_pAttrData; } unsigned int ARMGNULDBackend::getTargetSectionOrder(const LDSection& pSectHdr) const { const ELFFileFormat* file_format = getOutputFormat(); if (&pSectHdr == &file_format->getGOT()) { if (config().options().hasNow()) return SHO_RELRO_LAST; return SHO_DATA; } if (&pSectHdr == &file_format->getPLT()) return SHO_PLT; if (&pSectHdr == m_pEXIDX || &pSectHdr == m_pEXTAB) { // put ARM.exidx and ARM.extab in the same order of .eh_frame return SHO_EXCEPTION; } return SHO_UNDEFINED; } /// doRelax bool ARMGNULDBackend::doRelax(Module& pModule, IRBuilder& pBuilder, bool& pFinished) { assert(NULL != getStubFactory() && NULL != getBRIslandFactory()); bool isRelaxed = false; ELFFileFormat* file_format = getOutputFormat(); // check branch relocs and create the related stubs if needed Module::obj_iterator input, inEnd = pModule.obj_end(); for (input = pModule.obj_begin(); input != inEnd; ++input) { LDContext::sect_iterator rs, rsEnd = (*input)->context()->relocSectEnd(); for (rs = (*input)->context()->relocSectBegin(); rs != rsEnd; ++rs) { if (LDFileFormat::Ignore == (*rs)->kind() || !(*rs)->hasRelocData()) continue; RelocData::iterator reloc, rEnd = (*rs)->getRelocData()->end(); for (reloc = (*rs)->getRelocData()->begin(); reloc != rEnd; ++reloc) { Relocation* relocation = llvm::cast<Relocation>(reloc); switch (relocation->type()) { case llvm::ELF::R_ARM_PC24: case llvm::ELF::R_ARM_CALL: case llvm::ELF::R_ARM_JUMP24: case llvm::ELF::R_ARM_PLT32: case llvm::ELF::R_ARM_THM_CALL: case llvm::ELF::R_ARM_THM_XPC22: case llvm::ELF::R_ARM_THM_JUMP24: case llvm::ELF::R_ARM_THM_JUMP19: { // calculate the possible symbol value uint64_t sym_value = 0x0; LDSymbol* symbol = relocation->symInfo()->outSymbol(); if (symbol->hasFragRef()) { uint64_t value = symbol->fragRef()->getOutputOffset(); uint64_t addr = symbol->fragRef()->frag()->getParent()->getSection().addr(); sym_value = addr + value; } if (relocation->symInfo()->isGlobal() && (relocation->symInfo()->reserved() & ARMRelocator::ReservePLT) != 0x0) { // FIXME: we need to find out the address of the specific plt entry assert(file_format->hasPLT()); sym_value = file_format->getPLT().addr(); } Stub* stub = getStubFactory()->create(*relocation, // relocation sym_value, // symbol value pBuilder, *getBRIslandFactory()); if (NULL != stub) { switch (config().options().getStripSymbolMode()) { case GeneralOptions::StripAllSymbols: case GeneralOptions::StripLocals: break; default: { // a stub symbol should be local assert(NULL != stub->symInfo() && stub->symInfo()->isLocal()); LDSection& symtab = file_format->getSymTab(); LDSection& strtab = file_format->getStrTab(); // increase the size of .symtab and .strtab if needed if (config().targets().is32Bits()) symtab.setSize(symtab.size() + sizeof(llvm::ELF::Elf32_Sym)); else symtab.setSize(symtab.size() + sizeof(llvm::ELF::Elf64_Sym)); symtab.setInfo(symtab.getInfo() + 1); strtab.setSize(strtab.size() + stub->symInfo()->nameSize() + 1); } } // end of switch isRelaxed = true; } break; } case llvm::ELF::R_ARM_V4BX: /* FIXME: bypass R_ARM_V4BX relocation now */ break; default: break; } // end of switch } // for all relocations } // for all relocation section } // for all inputs // find the first fragment w/ invalid offset due to stub insertion Fragment* invalid = NULL; pFinished = true; for (BranchIslandFactory::iterator island = getBRIslandFactory()->begin(), island_end = getBRIslandFactory()->end(); island != island_end; ++island) { if ((*island).end() == file_format->getText().getSectionData()->end()) break; Fragment* exit = (*island).end(); if (((*island).offset() + (*island).size()) > exit->getOffset()) { invalid = exit; pFinished = false; break; } } // reset the offset of invalid fragments while (NULL != invalid) { invalid->setOffset(invalid->getPrevNode()->getOffset() + invalid->getPrevNode()->size()); invalid = invalid->getNextNode(); } // reset the size of .text if (isRelaxed) { file_format->getText().setSize( file_format->getText().getSectionData()->back().getOffset() + file_format->getText().getSectionData()->back().size()); } return isRelaxed; } /// initTargetStubs bool ARMGNULDBackend::initTargetStubs() { if (NULL != getStubFactory()) { getStubFactory()->addPrototype(new ARMToARMStub(config().isCodeIndep())); getStubFactory()->addPrototype(new ARMToTHMStub(config().isCodeIndep())); getStubFactory()->addPrototype(new THMToTHMStub(config().isCodeIndep())); getStubFactory()->addPrototype(new THMToARMStub(config().isCodeIndep())); return true; } return false; } /// doCreateProgramHdrs - backend can implement this function to create the /// target-dependent segments void ARMGNULDBackend::doCreateProgramHdrs(Module& pModule) { if (NULL != m_pEXIDX && 0x0 != m_pEXIDX->size()) { // make PT_ARM_EXIDX ELFSegment* exidx_seg = elfSegmentTable().produce(llvm::ELF::PT_ARM_EXIDX, llvm::ELF::PF_R); exidx_seg->append(m_pEXIDX); } } namespace mcld { //===----------------------------------------------------------------------===// /// createARMLDBackend - the help funtion to create corresponding ARMLDBackend /// TargetLDBackend* createARMLDBackend(const LinkerConfig& pConfig) { if (pConfig.targets().triple().isOSDarwin()) { assert(0 && "MachO linker is not supported yet"); /** return new ARMMachOLDBackend(createARMMachOArchiveReader, createARMMachOObjectReader, createARMMachOObjectWriter); **/ } if (pConfig.targets().triple().isOSWindows()) { assert(0 && "COFF linker is not supported yet"); /** return new ARMCOFFLDBackend(createARMCOFFArchiveReader, createARMCOFFObjectReader, createARMCOFFObjectWriter); **/ } return new ARMGNULDBackend(pConfig, new ARMGNUInfo(pConfig.targets().triple())); } } // namespace of mcld //===----------------------------------------------------------------------===// // Force static initialization. //===----------------------------------------------------------------------===// extern "C" void MCLDInitializeARMLDBackend() { // Register the linker backend mcld::TargetRegistry::RegisterTargetLDBackend(TheARMTarget, createARMLDBackend); mcld::TargetRegistry::RegisterTargetLDBackend(TheThumbTarget, createARMLDBackend); }
34.923295
92
0.556455
[ "object" ]
781bfa0f9c889fbdd30cd5091f8a9434f630caa4
939
cpp
C++
Codeforces/cf1582_D.cpp
Tunghohin/Competitive_coding
879238605d5525cda9fd0cfa1155ba67959179a6
[ "MIT" ]
2
2021-09-06T08:34:00.000Z
2021-11-22T14:52:41.000Z
Codeforces/cf1582_D.cpp
Tunghohin/Competitive_coding
879238605d5525cda9fd0cfa1155ba67959179a6
[ "MIT" ]
null
null
null
Codeforces/cf1582_D.cpp
Tunghohin/Competitive_coding
879238605d5525cda9fd0cfa1155ba67959179a6
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <cmath> #include <vector> #include <algorithm> using namespace std; long long a[100010]; long long b[100010]; void solve() { int n; cin >> n; for (int i = 1; i <= n; i++) cin >> a[i]; if (n % 2 == 0) { for (int i = 1; i <= n; i += 2) { b[i] = -a[i + 1]; b[i + 1] = a[i]; } } else { for (int i = 4; i <= n; i += 2) { b[i] = -a[i + 1]; b[i + 1] = a[i]; } long long pos1 = a[1], pos2 = a[2], pos3 = a[3]; if (pos1 + pos2 != 0) { b[1] = pos3, b[2] = pos3, b[3] = -(pos1 + pos2); } else if (pos1 + pos3 != 0) { b[1] = pos2, b[3] = pos2, b[2] = -(pos1 + pos3); } else { b[2] = pos1, b[3] = pos1, b[1] = -(pos2 + pos3); } } for (int i = 1; i <= n; i++) cout << b[i] << ' '; cout << '\n'; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr), cout.tie(nullptr); int T; cin >> T; while (T--) { solve(); } }
14.014925
51
0.452609
[ "vector" ]
781ca4e7f6c77b25e34c8c9490459c3f324375e3
3,114
cpp
C++
uva/uva11214/save.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
uva/uva11214/save.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
uva/uva11214/save.cpp
oklen/my-soluation
56d6c32f0a328332b090f9d633365b75605f4616
[ "MIT" ]
null
null
null
//#include <iostream> //#include <cstring> //#include <vector> //using namespace std; //char bd[9][9],bc[9][9]; //int m,n,cnt,maxd,bccnt; //bool fin; //void inline fill(int ii,int jj) //{ // for(int i = 0;i<n;++i) // if(bd[ii][i]>=1) {if(bd[ii][i]==1)--cnt; // ++bd[ii][i];} // for(int i =0;i<m;++i) // if(i!=ii&&bd[i][jj]>=1) {if(bd[i][jj]==1)--cnt; // ++bd[i][jj];} // for(int i = -min(jj,m-ii);ii-i>=0&&jj+i<n;++i) // if(i!=0&&bd[ii-i][jj+i]>=1) {if(bd[ii-i][jj+i]==1)--cnt; // ++bd[ii-i][jj+i];} // for(int i = -min(jj,ii);ii+i<m&&jj+i<n;++i) // if(i!=0&&bd[ii+i][jj+i]>=1) {if(bd[ii+i][jj+i]==1)--cnt; // ++bd[ii+i][jj+i];} //// if(bd[ii][jj]>=1) //// bd[ii][jj]-=3; //} //void inline revs(int ii,int jj) //{ // for(int i = 0;i<n;++i) // if(bd[ii][i]>=2) {--bd[ii][i]; // if(bd[ii][i]==1)++cnt;} // for(int i =0;i<m;++i) // if(i!=ii&&bd[i][jj]>=2) {--bd[i][jj]; // if(bd[i][jj]==1)++cnt;} // for(int i = -min(jj,m-ii);ii-i>=0&&jj+i<n;++i) // if(i!=0&&bd[ii-i][jj+i]>=2) {--bd[ii-i][jj+i]; // if(bd[ii-i][jj+i]==1)++cnt;} // for(int i = -min(jj,ii);ii+i<m&&jj+i<n;++i) // if(i!=0&&bd[ii+i][jj+i]>=2) {--bd[ii+i][jj+i]; // if(bd[ii+i][jj+i]==1)++cnt;} //// if(bd[ii][jj]>=2) //// bd[ii][jj]+=3; //} //void show() //{ // for(int i = 0;i<m;++i) // { // for(int j = 0;j<n;++j) // cout << (int)bd[i][j]; // cout <<endl; // } //} //void solve(int dep,int ii,int jj) //{ // if(dep==0)return; // int ccnt = cnt; //// char bk[9][9];memcpy(bk,bd,sizeof(char)*9*9); // for(int i = ii;i<m;++i) // { // for(int j = i==ii?jj:0;j<n;++j) // { // fill(i,j); // if(cnt == 0){fin=true;return;} // if(cnt > ccnt-3) // { // revs(i,j);continue; // } // solve(dep-1,ii,jj+1); // revs(i,j); // } // } //} //int main() //{ //// freopen("/media/root/Dstore/LENOVO/Qt_Project/build-uva11214-Desktop_Qt_5_11_1_GCC_64bit-Debug/input", //// "r",stdin); // int glc = 1; // while(scanf("%d",&m)&&m&&scanf("%d",&n)) // { // for(int i = 0;i<m;++i) // scanf("%s",bd[i]); // cnt=0; // for(int i = 0;i<m;++i) // for(int j =0;j<n;++j) // if(bd[i][j]=='X') { // bd[i][j] = 1;++cnt; // } // else bd[i][j]=0;fin=false; // memcpy(bc,bd,sizeof(char)*9*9);bccnt = cnt; //// show();return 0;; // for(maxd=1;;++maxd) // { // solve(maxd,0,0); //// cout << "maxd:"<<maxd << endl; // cnt = bccnt;memcpy(bd,bc,sizeof(char)*9*9); // if(fin) break; // } // memset(bd,0,sizeof(char)*9*9); // printf("Case %d: %d\n",glc++,maxd); // } // return 0; //}
28.833333
110
0.369942
[ "vector" ]
782898781502326b35288607b05a4245d5b40c76
2,063
cpp
C++
Examples/Cpp/source/Exchange_EWS/CaseSensitiveEmailsFilteringUsingEWS.cpp
kashifiqb/Aspose.Email-for-C
96684cb6ed9f4e321a00c74ca219440baaef8ba8
[ "MIT" ]
4
2019-12-01T16:19:12.000Z
2022-03-28T18:51:42.000Z
Examples/Cpp/source/Exchange_EWS/CaseSensitiveEmailsFilteringUsingEWS.cpp
kashifiqb/Aspose.Email-for-C
96684cb6ed9f4e321a00c74ca219440baaef8ba8
[ "MIT" ]
1
2022-02-15T01:02:15.000Z
2022-02-15T01:02:15.000Z
Examples/Cpp/source/Exchange_EWS/CaseSensitiveEmailsFilteringUsingEWS.cpp
kashifiqb/Aspose.Email-for-C
96684cb6ed9f4e321a00c74ca219440baaef8ba8
[ "MIT" ]
5
2017-09-27T14:43:20.000Z
2021-11-16T06:47:11.000Z
#include "Examples.h" #include <Tools/Search/StringComparisonField.h> #include <Tools/Search/MailQuery.h> #include <Tools/Search/DateComparisonField.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/object.h> #include <system/exceptions.h> #include <system/date_time.h> #include <system/console.h> #include <cstdint> #include <Clients/Exchange/WebService/EWSClient/IEWSClient.h> #include <Clients/Exchange/WebService/EWSClient/EWSClient.h> #include <Clients/Exchange/Search/ExchangeQueryBuilder.h> #include <Clients/Exchange/ExchangeMessageInfoCollection.h> #include <Clients/Exchange/ExchangeMailboxInfo.h> using namespace Aspose::Email::Clients::Exchange; using namespace Aspose::Email::Clients::Exchange::WebService; using namespace Aspose::Email::Tools::Search; void CaseSensitiveEmailsFilteringUsingEWS() { // Connect to EWS const System::String mailboxUri = u"https://outlook.office365.com/ews/exchange.asmx"; const System::String username = u"username"; const System::String password = u"password"; const System::String domain = u"domain"; try { System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser()); // Query building by means of ExchangeQueryBuilder class System::SharedPtr<ExchangeQueryBuilder> builder = System::MakeObject<ExchangeQueryBuilder>(); builder->get_Subject()->Contains(u"Newsletter", true); builder->get_InternalDate()->On(System::DateTime::get_Now()); System::SharedPtr<MailQuery> query = builder->GetQuery(); // Get list of messages System::SharedPtr<ExchangeMessageInfoCollection> messages = client->ListMessages(client->get_MailboxInfo()->get_InboxUri(), query, false); System::Console::WriteLine(System::String(u"EWS: ") + messages->get_Count() + u" message(s) found."); // Disconnect from EWS client->Dispose(); } catch (System::Exception& ex) { System::Console::WriteLine(ex->get_Message()); } }
38.203704
146
0.713524
[ "object" ]
7828dd70a1f49ddd44b360640e813d324be483b6
133,816
hpp
C++
source/pixie/vecmath.hpp
rdacomp/pixie
cc2abb5572952ce567f96d19244996f249a423ca
[ "Unlicense" ]
148
2018-01-22T05:32:04.000Z
2022-01-09T22:36:10.000Z
source/pixie/vecmath.hpp
rdacomp/pixie
cc2abb5572952ce567f96d19244996f249a423ca
[ "Unlicense" ]
null
null
null
source/pixie/vecmath.hpp
rdacomp/pixie
cc2abb5572952ce567f96d19244996f249a423ca
[ "Unlicense" ]
3
2018-02-08T12:51:16.000Z
2020-02-01T21:04:38.000Z
/* ------------------------------------------------------------------------------ Licensing information can be found at the end of the file. ------------------------------------------------------------------------------ vecmath.hpp - v0.1 - simple HLSL style vector math library for C++. */ #ifndef vecmath_hpp #define vecmath_hpp #ifdef max #undef max #endif #ifdef min #undef min #endif namespace vecmath { // POD types struct float2_t { float x, y; }; struct float3_t { float x, y, z; }; struct float4_t { float x, y, z, w; }; struct float2x2_t { /* rows */ float2_t x, y; }; struct float2x3_t { /* rows */ float3_t x, y, z; }; struct float3x2_t { /* rows */ float2_t x, y, z; }; struct float3x3_t { /* rows */ float3_t x, y, z; }; struct float2x4_t { /* rows */ float4_t x, y; }; struct float3x4_t { /* rows */ float4_t x, y, z; }; struct float4x2_t { /* rows */ float2_t x, y, z, w; }; struct float4x3_t { /* rows */ float3_t x, y, z, w; }; struct float4x4_t { /* rows */ float4_t x, y, z, w; }; // swizzling helpers struct swizzle2 { inline swizzle2( float& xr, float& yg ) : x( xr ), y( yg ) {} inline swizzle2& operator=( struct float2 const& v ); inline swizzle2& operator=( swizzle2 const& v ); inline swizzle2& operator=( float s ) { x = s; y = s; return *this; } inline float& operator[]( int index ) { return *( (float**) this )[ index ]; } inline operator float2_t() { float2_t r = { x, y }; return r; } float& x; float& y; }; struct swizzle3 { inline swizzle3( float& xr, float& yg, float& zb ) : x( xr ), y( yg ), z( zb ) {} inline swizzle3& operator=( struct float3 const& v ); inline swizzle3& operator=( swizzle3 const& v ); inline swizzle3& operator=( float s ) { x = s; y = s; z = s; return *this; } inline float& operator[]( int index ) { return *( (float**) this )[ index ]; } inline operator float3_t() { float3_t r = { x, y, z }; return r; } float& x; float& y; float& z; }; struct swizzle4 { inline swizzle4( float& xr, float& yg, float& zb, float& wa ) : x( xr ), y( yg ), z( zb ), w( wa ) {} inline swizzle4& operator=( struct float4 const& v ); inline swizzle4& operator=( swizzle4 const& v ); inline swizzle4& operator=( float s ) { x = s; y = s; z = s; w = s; return *this; } inline float& operator[]( int index ) { return *( (float**) this )[ index ]; } inline operator float4_t() { float4_t r = { x, y, z, w }; return r; } float& x; float& y; float& z; float& w; }; // internal math functions namespace internal { float acosf( float ); float asinf( float ); float atanf( float ); float atan2f( float, float ); float ceilf( float ); float cosf( float ); float coshf( float ); float expf( float ); float fabsf( float ); float floorf( float ); float fmodf( float, float ); float ldexpf( float, int ); float logf( float ); float log2f( float ); float log10f( float ); float modff( float, float* ); float powf( float, float ); float roundf( float ); float sqrtf( float ); float sinf( float ); float sinhf( float ); float tanf( float ); float tanhf( float ); float truncf( float ); } /* namespace internal */ // functions inline float abs( float v ) { return float( internal::fabsf( v ) ); } inline float acos( float v ) { return float( internal::acosf( v ) ); } inline bool all( float v ) { return v != 0.0f; } inline bool any( float v ) { return v != 0.0f; } inline float asin( float v ) { return float( internal::asinf( v ) ); } inline float atan( float v ) { return float( internal::atanf( v ) ); } inline float atan2( float y, float x ) { return float( internal::atan2f( y, x ) ); } inline float ceil( float v ) { return float( internal::ceilf( v ) ); } inline float clamp( float v, float min, float max ) { return float( v < min ? min : v > max ? max : v ); } inline float cos( float v ) { return float( internal::cosf( v ) ); } inline float cosh( float v ) { return float( internal::coshf( v ) ); } inline float degrees( float v ) { float const f = 57.295779513082320876846364344191f; return float( v * f ); } inline float distancesq( float a, float b ) { float x = b - a; return x * x; } inline float distance( float a, float b ) { float x = b - a; return internal::sqrtf( x * x ); } inline float dot( float a, float b ) { return a * b; } inline float exp( float v ) { return float( internal::expf( v ) ); } inline float exp2( float v ) { return float( internal::powf( 2.0f, v ) ); } inline float floor( float v ) { return float( internal::floorf( v ) ); } inline float fmod( float a, float b ) { return float( internal::fmodf( a, b ) ); } inline float frac( float v ) { float t; return float( internal::fabsf( internal::modff( v, &t ) ) ); } inline float lengthsq( float v ) { return v * v; } inline float length( float v ) { return internal::sqrtf( v * v ); } inline float lerp( float a, float b, float s ) { return float( a + ( b - a ) * s ); } inline float log( float v ) { return float( internal::logf( v ) ); } inline float log2( float v ) { return float( internal::log2f( v ) ); return v; } inline float log10( float v ) { return float( internal::log10f( v ) ); } inline float mad( float a, float b, float c ) { return a * b + c; } inline float max( float a, float b ) { return float( a > b ? a : b ); } inline float min( float a, float b ) { return float( a < b ? a : b ); } inline float normalize( float v ) { float l = internal::sqrtf( v * v ); return l == 0.0f ? v : float( v / l ); } inline float pow( float a, float b ) { return float( internal::powf( a, b ) ); } inline float radians( float v ) { float const f = 0.01745329251994329576922222222222f; return float( v * f ); } inline float rcp( float v ) { return float( 1.0f / v ); } inline float reflect( float i, float n ) { return i - 2.0f * n * dot( i, n ); } inline float refract( float i, float n, float r ) { float n_i = dot( n, i ); float k = 1.0f - r * r * ( 1.0f - n_i * n_i ); return ( k < 0.0f ) ? float( 0.0f ) : ( r * i - ( r * n_i + internal::sqrtf( k ) ) * n ); } inline float round( float v ) { return float( internal::roundf( v ) ); } inline float rsqrt( float v ) { return float( 1.0f / internal::sqrtf( v ) ); } inline float saturate( float v ) { return float( v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v ); } inline float sign( float v ) { return float( v < 0.0f ? -1.0f : v > 0.0f ? 1.0f : 0.0f ); } inline float sin( float v ) { return float( internal::sinf( v ) ); } inline float sinh( float v ) { return float( internal::sinhf( v ) ); } inline float smoothstep( float min, float max, float v ) { v = ( v - min ) / ( max - min ); v = float( v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v ); return float( v * v * ( 3.0f - 2.0f * v ) ); } inline float smootherstep( float min, float max, float v ) { v = ( v - min ) / ( max - min ); v = float( v < 0.0f ? 0.0f : v > 1.0f ? 1.0f : v ); return float( v * v * v * ( v * ( v * 6.0f - 15.0f ) + 10.0f ) ); } inline float sqrt( float v ) { return float( internal::sqrtf( v ) ); } inline float step( float a, float b ) { return float( b >= a ? 1.0f : 0.0f ); } inline float tan( float v ) { return float( internal::tanf( v ) ); } inline float tanh( float v ) { return float( internal::tanhf( v ) ); } inline float trunc( float v ) { return float( internal::truncf( v ) ); } struct float2 { float x; float y; // constructors inline float2() { } inline float2( float f ) : x( f ), y( f ) { } inline explicit float2( float f[2] ) : x( f[0] ), y( f[1] ) { } inline float2( float xr, float yg ) : x( xr ), y( yg ) { } inline float2( swizzle2 s ) : x( s.x ), y( s.y ) { } // conversions inline float2( float2_t v ) : x( v.x ), y( v.y ) { } inline operator float2_t() const { float2_t v = { x, y }; return v; }; // indexing inline float& operator[]( int index ) { return ( (float*) this )[ index ]; } inline const float& operator[]( int index ) const { return ( (float*) this )[ index ]; } // aliases inline float& r() { return x; } inline float& g() { return y; } // swizzling permutations: v.rg(), v.xwzz() etc. #define S( a, b ) inline swizzle2 a##b() { return swizzle2( a, b ); } S(x,x); S(x,y); S(y,x); S(y,y); #undef S #define S( a, b ) inline swizzle2 a##b() { return swizzle2( a(), b() ); } S(r,r); S(r,g); S(g,r); S(g,g); #undef S #define S( a, b, c ) inline swizzle3 a##b##c() { return swizzle3( a, b, c ); } S(x,x,x); S(x,x,y); S(x,y,x); S(x,y,y); S(y,x,x); S(y,x,y); S(y,y,x); S(y,y,y); #undef S #define S( a, b, c ) inline swizzle3 a##b##c() { return swizzle3( a(), b(), c() ); } S(r,r,r); S(r,r,g); S(r,g,r); S(r,g,g); S(g,r,r); S(g,r,g); S(g,g,r); S(g,g,g); #undef S #define S( a, b, c, d ) inline swizzle4 a##b##c##d() { return swizzle4( a, b, c, d ); } S(x,x,x,x); S(x,x,x,y); S(x,x,y,x); S(x,x,y,y); S(x,y,x,x); S(x,y,x,y); S(x,y,y,x); S(x,y,y,y); S(y,x,x,x); S(y,x,x,y); S(y,x,y,x); S(y,x,y,y); S(y,y,x,x); S(y,y,x,y); S(y,y,y,x); S(y,y,y,y); #undef S #define S( a, b, c, d ) inline swizzle4 a##b##c##d() { return swizzle4( a(), b(), c(), d() ); } S(r,r,r,r); S(r,r,r,g); S(r,r,g,r); S(r,r,g,g); S(r,g,r,r); S(r,g,r,g); S(r,g,g,r); S(r,g,g,g); S(g,r,r,r); S(g,r,r,g); S(g,r,g,r); S(g,r,g,g); S(g,g,r,r); S(g,g,r,g); S(g,g,g,r); S(g,g,g,g); #undef S }; // operators inline float2 operator-( float2 v ) { return float2( -v.x, -v.y ); } inline bool operator==( float2 a, float2 b ) { return a.x == b.x && a.y == b.y; } inline bool operator!=( float2 a, float2 b ) { return a.x != b.x || a.y != b.y; } inline float2& operator+=( float2& a, float2 b ) { a.x += b.x; a.y += b.y; return a; }; inline float2& operator-=( float2& a, float2 b ) { a.x -= b.x; a.y -= b.y; return a; }; inline float2& operator*=( float2& a, float2 b ) { a.x *= b.x; a.y *= b.y; return a; }; inline float2& operator/=( float2& a, float2 b ) { a.x /= b.x; a.y /= b.y; return a; }; inline float2& operator+=( float2& a, float s ) { a.x += s; a.y += s; return a; }; inline float2& operator-=( float2& a, float s ) { a.x -= s; a.y -= s; return a; }; inline float2& operator*=( float2& a, float s ) { a.x *= s; a.y *= s; return a; }; inline float2& operator/=( float2& a, float s ) { a.x /= s; a.y /= s; return a; }; inline float2 operator+( float2 a, float2 b ) { return float2( a.x + b.x, a.y + b.y ); } inline float2 operator-( float2 a, float2 b ) { return float2( a.x - b.x, a.y - b.y ); } inline float2 operator*( float2 a, float2 b ) { return float2( a.x * b.x, a.y * b.y ); } inline float2 operator/( float2 a, float2 b ) { return float2( a.x / b.x, a.y / b.y ); } inline float2 operator+( float2 a, float b ) { return float2( a.x + b, a.y + b ); } inline float2 operator-( float2 a, float b ) { return float2( a.x - b, a.y - b ); } inline float2 operator*( float2 a, float b ) { return float2( a.x * b, a.y * b ); } inline float2 operator/( float2 a, float b ) { return float2( a.x / b, a.y / b ); } inline float2 operator+( float a, float2 b ) { return float2( a + b.x, a + b.y ); } inline float2 operator-( float a, float2 b ) { return float2( a - b.x, a - b.y ); } inline float2 operator*( float a, float2 b ) { return float2( a * b.x, a * b.y ); } inline float2 operator/( float a, float2 b ) { return float2( a / b.x, a / b.y ); } // functions inline float2 abs( float2 v ) { return float2( abs( v.x ), abs( v.y ) ); } inline float2 acos( float2 v ) { return float2( acos( v.x ), acos( v.y ) ); } inline bool all( float2 v ) { return v.x != 0.0f && v.y != 0.0f; } inline bool any( float2 v ) { return v.x != 0.0f || v.y != 0.0f; } inline float2 asin( float2 v ) { return float2( asin( v.x ), asin( v.y ) ); } inline float2 atan( float2 v ) { return float2( atan( v.x ), atan( v.y ) ); } inline float2 atan2( float2 y, float2 x ) { return float2( atan2( y.x, x.x ), atan2( y.y, x.y ) ); } inline float2 ceil( float2 v ) { return float2( ceil( v.x ), ceil( v.y ) ); } inline float2 clamp( float2 v, float2 min, float2 max ) { return float2( clamp( v.x, min.x, max.x ), clamp( v.y, min.y, max.y ) ); } inline float2 cos( float2 v ) { return float2( cos( v.x ), cos( v.y ) ); } inline float2 cosh( float2 v ) { return float2( cosh( v.x ), cosh( v.y ) ); } inline float2 degrees( float2 v ) { return float2( degrees( v.x ), degrees( v.y ) ); } inline float distancesq( float2 a, float2 b ) { float x = b.x - a.x; float y = b.y - a.y; return x * x + y * y; } inline float distance( float2 a, float2 b ) { float x = b.x - a.x; float y = b.y - a.y; return sqrt( x * x + y * y ); } inline float dot( float2 a, float2 b ) { return a.x * b.x + a.y * b.y; } inline float2 exp( float2 v ) { return float2( exp( v.x ), exp( v.y ) ); } inline float2 exp2( float2 v ) { return float2( exp2( v.x ), exp2( v.y ) ); } inline float2 floor( float2 v ) { return float2( floor( v.x ), floor( v.y ) ); } inline float2 fmod( float2 a, float2 b ) { return float2( fmod( a.x, b.x ), fmod( a.y, b.y ) ); } inline float2 frac( float2 v ) { return float2( frac( v.x ), frac( v.y ) ); } inline float lengthsq( float2 v ) { return v.x * v.x + v.y * v.y; } inline float length( float2 v ) { return sqrt( v.x * v.x + v.y * v.y ); } inline float2 lerp( float2 a, float2 b, float s ) { return float2( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ) ); } inline float2 log( float2 v ) { return float2( log( v.x ), log( v.y ) ); } inline float2 log2( float2 v ) { return float2( log2( v.x ), log2( v.y ) ); } inline float2 log10( float2 v ) { return float2( log10( v.x ), log10( v.y ) ); } inline float2 mad( float2 a, float2 b, float2 c ) { return a * b + c; } inline float2 max( float2 a, float2 b ) { return float2( max( a.x, b.x ), max( a.y, b.y ) ); } inline float2 min( float2 a, float2 b ) { return float2( min( a.x, b.x ), min( a.y, b.y ) ); } inline float2 normalize( float2 v ) { float l = sqrt( v.x * v.x + v.y * v.y ); return l == 0.0f ? v : float2( v.x / l, v.y / l ); } inline float2 pow( float2 a, float2 b ) { return float2( pow( a.x, b.x ), pow( a.y, b.y ) ); } inline float2 radians( float2 v ) { return float2( radians( v.x ), radians( v.y ) ); } inline float2 rcp( float2 v ) { return float2( rcp( v.x ), rcp( v.y ) ); } inline float2 reflect( float2 i, float2 n ) { return i - 2.0f * n * dot( i, n ) ; } inline float2 refract( float2 i, float2 n, float r ) { float n_i = dot( n, i ); float k = 1.0f - r * r * ( 1.0f - n_i * n_i ); return ( k < 0.0f ) ? float2( 0.0f, 0.0f ) : ( r * i - ( r * n_i + sqrt( k ) ) * n ); } inline float2 round( float2 v ) { return float2( round( v.x ), round( v.y ) ); } inline float2 rsqrt( float2 v ) { return float2( rcp( sqrt( v.x ) ), rcp( sqrt( v.y ) ) ); } inline float2 saturate( float2 v ) { return float2( saturate( v.x ), saturate( v.y ) ); } inline float2 sign( float2 v ) { return float2( sign( v.x ), sign( v.y ) ); } inline float2 sin( float2 v ) { return float2( sin( v.x ), sin( v.y ) ); } inline float2 sinh( float2 v ) { return float2( sinh( v.x ), sinh( v.y ) ); } inline float2 smoothstep( float2 min, float2 max, float2 v ) { return float2( smoothstep( min.x, max.x, v.x ), smoothstep( min.y, max.y, v.y ) ); } inline float2 smootherstep( float2 min, float2 max, float2 v ) { return float2( smootherstep( min.x, max.x, v.x ), smootherstep( min.y, max.y, v.y ) ); } inline float2 sqrt( float2 v ) { return float2( sqrt( v.x ), sqrt( v.y ) ); } inline float2 step( float2 a, float2 b ) { return float2( step( a.x, b.x ), step( a.y, b.y ) ); } inline float2 tan( float2 v ) { return float2( tan( v.x ), tan( v.y ) ); } inline float2 tanh( float2 v ) { return float2( tanh( v.x ), tanh( v.y ) ); } inline float2 trunc( float2 v ) { return float2( trunc( v.x ), trunc( v.y ) ); } struct float3 { float x; float y; float z; // constructors inline float3() { } inline float3( float f ) : x( f ), y( f ), z( f ) { } inline explicit float3( float f[3] ) : x( f[0] ), y( f[1] ), z( f[2] ) { } inline float3( float xr, float yg, float zb ) : x( xr ), y( yg ), z( zb ) { } inline float3( float a, float2 b ) : x( a ), y( b.x ), z( b.y ) { } inline float3( float2 a, float b ) : x( a.x ), y( a.y ), z( b ) { } inline float3( swizzle3 s ) : x( s.x ), y( s.y ), z( s.z ) { } // conversions inline float3( float3_t v ) : x( v.x ), y( v.y ), z( v.z ) { } inline operator float3_t() const { float3_t v = { x, y, z }; return v; }; // indexing inline float& operator[]( int index ) { return ( (float*) this )[ index ]; } inline const float& operator[]( int index ) const { return ( (float*) this )[ index ]; } // aliases inline float& r() { return x; } inline float& g() { return y; } inline float& b() { return z; } // swizzling permutations: v.rg(), v.xwzz() etc. #define S( a, b ) inline swizzle2 a##b() { return swizzle2( a, b ); } S(x,x); S(x,y); S(x,z); S(y,x); S(y,y); S(y,z); S(z,x); S(z,y); S(z,z); #undef S #define S( a, b ) inline swizzle2 a##b() { return swizzle2( a(), b() ); } S(r,r); S(r,g); S(r,b); S(g,r); S(g,g); S(g,b); S(b,r); S(b,g); S(b,b); #undef S #define S( a, b, c ) inline swizzle3 a##b##c() { return swizzle3( a, b, c ); } S(x,x,x); S(x,x,y); S(x,x,z); S(x,y,x); S(x,y,y); S(x,y,z); S(x,z,x); S(x,z,y); S(x,z,z); S(y,x,x); S(y,x,y); S(y,x,z); S(y,y,x); S(y,y,y); S(y,y,z); S(y,z,x); S(y,z,y); S(y,z,z); S(z,x,x); S(z,x,y); S(z,x,z); S(z,y,x); S(z,y,y); S(z,y,z); S(z,z,x); S(z,z,y); S(z,z,z); #undef S #define S( a, b, c ) inline swizzle3 a##b##c() { return swizzle3( a(), b(), c() ); } S(r,r,r); S(r,r,g); S(r,r,b); S(r,g,r); S(r,g,g); S(r,g,b); S(r,b,r); S(r,b,g); S(r,b,b); S(g,r,r); S(g,r,g); S(g,r,b); S(g,g,r); S(g,g,g); S(g,g,b); S(g,b,r); S(g,b,g); S(g,b,b); S(b,r,r); S(b,r,g); S(b,r,b); S(b,g,r); S(b,g,g); S(b,g,b); S(b,b,r); S(b,b,g); S(b,b,b); #undef S #define S( a, b, c, d ) inline swizzle4 a##b##c##d() { return swizzle4( a, b, c, d ); } S(x,x,x,x); S(x,x,x,y); S(x,x,x,z); S(x,x,y,x); S(x,x,y,y); S(x,x,y,z); S(x,x,z,x); S(x,x,z,y); S(x,x,z,z); S(x,y,x,x); S(x,y,x,y); S(x,y,x,z); S(x,y,y,x); S(x,y,y,y); S(x,y,y,z); S(x,y,z,x); S(x,y,z,y); S(x,y,z,z); S(x,z,x,x); S(x,z,x,y); S(x,z,x,z); S(x,z,y,x); S(x,z,y,y); S(x,z,y,z); S(x,z,z,x); S(x,z,z,y); S(x,z,z,z); S(y,x,x,x); S(y,x,x,y); S(y,x,x,z); S(y,x,y,x); S(y,x,y,y); S(y,x,y,z); S(y,x,z,x); S(y,x,z,y); S(y,x,z,z); S(y,y,x,x); S(y,y,x,y); S(y,y,x,z); S(y,y,y,x); S(y,y,y,y); S(y,y,y,z); S(y,y,z,x); S(y,y,z,y); S(y,y,z,z); S(y,z,x,x); S(y,z,x,y); S(y,z,x,z); S(y,z,y,x); S(y,z,y,y); S(y,z,y,z); S(y,z,z,x); S(y,z,z,y); S(y,z,z,z); S(z,x,x,x); S(z,x,x,y); S(z,x,x,z); S(z,x,y,x); S(z,x,y,y); S(z,x,y,z); S(z,x,z,x); S(z,x,z,y); S(z,x,z,z); S(z,y,x,x); S(z,y,x,y); S(z,y,x,z); S(z,y,y,x); S(z,y,y,y); S(z,y,y,z); S(z,y,z,x); S(z,y,z,y); S(z,y,z,z); S(z,z,x,x); S(z,z,x,y); S(z,z,x,z); S(z,z,y,x); S(z,z,y,y); S(z,z,y,z); S(z,z,z,x); S(z,z,z,y); S(z,z,z,z); #undef S #define S( a, b, c, d ) inline swizzle4 a##b##c##d() { return swizzle4( a(), b(), c(), d() ); } S(r,r,r,r); S(r,r,r,g); S(r,r,r,b); S(r,r,g,r); S(r,r,g,g); S(r,r,g,b); S(r,r,b,r); S(r,r,b,g); S(r,r,b,b); S(r,g,r,r); S(r,g,r,g); S(r,g,r,b); S(r,g,g,r); S(r,g,g,g); S(r,g,g,b); S(r,g,b,r); S(r,g,b,g); S(r,g,b,b); S(r,b,r,r); S(r,b,r,g); S(r,b,r,b); S(r,b,g,r); S(r,b,g,g); S(r,b,g,b); S(r,b,b,r); S(r,b,b,g); S(r,b,b,b); S(g,r,r,r); S(g,r,r,g); S(g,r,r,b); S(g,r,g,r); S(g,r,g,g); S(g,r,g,b); S(g,r,b,r); S(g,r,b,g); S(g,r,b,b); S(g,g,r,r); S(g,g,r,g); S(g,g,r,b); S(g,g,g,r); S(g,g,g,g); S(g,g,g,b); S(g,g,b,r); S(g,g,b,g); S(g,g,b,b); S(g,b,r,r); S(g,b,r,g); S(g,b,r,b); S(g,b,g,r); S(g,b,g,g); S(g,b,g,b); S(g,b,b,r); S(g,b,b,g); S(g,b,b,b); S(b,r,r,r); S(b,r,r,g); S(b,r,r,b); S(b,r,g,r); S(b,r,g,g); S(b,r,g,b); S(b,r,b,r); S(b,r,b,g); S(b,r,b,b); S(b,g,r,r); S(b,g,r,g); S(b,g,r,b); S(b,g,g,r); S(b,g,g,g); S(b,g,g,b); S(b,g,b,r); S(b,g,b,g); S(b,g,b,b); S(b,b,r,r); S(b,b,r,g); S(b,b,r,b); S(b,b,g,r); S(b,b,g,g); S(b,b,g,b); S(b,b,b,r); S(b,b,b,g); S(b,b,b,b); #undef S }; // operators inline float3 operator-( float3 v ) { return float3( -v.x, -v.y, -v.z ); } inline bool operator==( float3 a, float3 b ) { return a.x == b.x && a.y == b.y && a.z == b.z; } inline bool operator!=( float3 a, float3 b ) { return a.x != b.x || a.y != b.y || a.z != b.z; } inline float3& operator+=( float3& a, float3 b ) { a.x += b.x; a.y += b.y; a.z += b.z; return a; }; inline float3& operator-=( float3& a, float3 b ) { a.x -= b.x; a.y -= b.y; a.z -= b.z; return a; }; inline float3& operator*=( float3& a, float3 b ) { a.x *= b.x; a.y *= b.y; a.z *= b.z; return a; }; inline float3& operator/=( float3& a, float3 b ) { a.x /= b.x; a.y /= b.y; a.z /= b.z; return a; }; inline float3& operator+=( float3& a, float s ) { a.x += s; a.y += s; a.z += s; return a; }; inline float3& operator-=( float3& a, float s ) { a.x -= s; a.y -= s; a.z -= s; return a; }; inline float3& operator*=( float3& a, float s ) { a.x *= s; a.y *= s; a.z *= s; return a; }; inline float3& operator/=( float3& a, float s ) { a.x /= s; a.y /= s; a.z /= s; return a; }; inline float3 operator+( float3 a, float3 b ) { return float3( a.x + b.x, a.y + b.y, a.z + b.z ); } inline float3 operator-( float3 a, float3 b ) { return float3( a.x - b.x, a.y - b.y, a.z - b.z ); } inline float3 operator*( float3 a, float3 b ) { return float3( a.x * b.x, a.y * b.y, a.z * b.z ); } inline float3 operator/( float3 a, float3 b ) { return float3( a.x / b.x, a.y / b.y, a.z / b.z ); } inline float3 operator+( float3 a, float b ) { return float3( a.x + b, a.y + b, a.z + b ); } inline float3 operator-( float3 a, float b ) { return float3( a.x - b, a.y - b, a.z - b ); } inline float3 operator*( float3 a, float b ) { return float3( a.x * b, a.y * b, a.z * b ); } inline float3 operator/( float3 a, float b ) { return float3( a.x / b, a.y / b, a.z / b ); } inline float3 operator+( float a, float3 b ) { return float3( a + b.x, a + b.y, a + b.z ); } inline float3 operator-( float a, float3 b ) { return float3( a - b.x, a - b.y, a - b.z ); } inline float3 operator*( float a, float3 b ) { return float3( a * b.x, a * b.y, a * b.z ); } inline float3 operator/( float a, float3 b ) { return float3( a / b.x, a / b.y, a / b.z ); } // functions inline float3 abs( float3 v ) { return float3( abs( v.x ), abs( v.y ), abs( v.z ) ); } inline float3 acos( float3 v ) { return float3( acos( v.x ), acos( v.y ), acos( v.z ) ); } inline bool all( float3 v ) { return v.x != 0.0f && v.y != 0.0f && v.z != 0.0f; } inline bool any( float3 v ) { return v.x != 0.0f || v.y != 0.0f || v.z != 0.0f; } inline float3 asin( float3 v ) { return float3( asin( v.x ), asin( v.y ), asin( v.z ) ); } inline float3 atan( float3 v ) { return float3( atan( v.x ), atan( v.y ), atan( v.z ) ); } inline float3 atan2( float3 y, float3 x ) { return float3( atan2( y.x, x.x ), atan2( y.y, x.y ), atan2( y.z, x.z ) ); } inline float3 ceil( float3 v ) { return float3( ceil( v.x ), ceil( v.y ), ceil( v.z ) ); } inline float3 clamp( float3 v, float3 min, float3 max ) { return float3( clamp( v.x, min.x, max.x ), clamp( v.y, min.y, max.y ), clamp( v.z, min.z, max.z ) ); } inline float3 cos( float3 v ) { return float3( cos( v.x ), cos( v.y ), cos( v.z ) ); } inline float3 cosh( float3 v ) { return float3( cosh( v.x ), cosh( v.y ), cosh( v.z ) ); } inline float3 cross( float3 a, float3 b ) { return float3( a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x ); } inline float3 degrees( float3 v ) { return float3( degrees( v.x ), degrees( v.y ), degrees( v.z ) ); } inline float distancesq( float3 a, float3 b ) { float x = b.x - a.x; float y = b.y - a.y; float z = b.z - a.z; return x * x + y * y + z * z; } inline float distance( float3 a, float3 b ) { float x = b.x - a.x; float y = b.y - a.y; float z = b.z - a.z; return sqrt( x * x + y * y + z * z ); } inline float dot( float3 a, float3 b ) { return a.x * b.x + a.y * b.y + a.z * b.z; } inline float3 exp( float3 v ) { return float3( exp( v.x ), exp( v.y ), exp( v.z ) ); } inline float3 exp2( float3 v ) { return float3( exp2( v.x ), exp2( v.y ), exp2( v.z ) ); } inline float3 floor( float3 v ) { return float3( floor( v.x ), floor( v.y ), floor( v.z ) ); } inline float3 fmod( float3 a, float3 b ) { return float3( fmod( a.x, b.x ), fmod( a.y, b.y ), fmod( a.z, b.z ) ); } inline float3 frac( float3 v ) { return float3( frac( v.x ), frac( v.y ), frac( v.z ) ); } inline float lengthsq( float3 v ) { return v.x * v.x + v.y * v.y + v.z * v.z; } inline float length( float3 v ) { return sqrt( v.x * v.x + v.y * v.y + v.z * v.z ); } inline float3 lerp( float3 a, float3 b, float s ) { return float3( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ), lerp( a.z, b.z, s ) ); } inline float3 log( float3 v ) { return float3( log( v.x ), log( v.y ), log( v.z ) ); } inline float3 log2( float3 v ) { return float3( log2( v.x ), log2( v.y ), log2( v.z ) ); } inline float3 log10( float3 v ) { return float3( log10( v.x ), log10( v.y ), log10( v.z ) ); } inline float3 mad( float3 a, float3 b, float3 c ) { return a * b + c; } inline float3 max( float3 a, float3 b ) { return float3( max( a.x, b.x ), max( a.y, b.y ), max( a.z, b.z ) ); } inline float3 min( float3 a, float3 b ) { return float3( min( a.x, b.x ), min( a.y, b.y ), min( a.z, b.z ) ); } inline float3 normalize( float3 v ) { float l = sqrt( v.x * v.x + v.y * v.y + v.z * v.z ); return l == 0.0f ? v : float3( v.x / l, v.y / l, v.z / l ); } inline float3 pow( float3 a, float3 b ) { return float3( pow( a.x, b.x ), pow( a.y, b.y ), pow( a.z, b.z ) ); } inline float3 radians( float3 v ) { return float3( radians( v.x ), radians( v.y ), radians( v.z ) ); } inline float3 rcp( float3 v ) { return float3( rcp( v.x ), rcp( v.y ), rcp( v.z ) ); } inline float3 reflect( float3 i, float3 n ) { return i - 2.0f * n * dot( i, n ) ; } inline float3 refract( float3 i, float3 n, float r ) { float n_i = dot( n, i ); float k = 1.0f - r * r * ( 1.0f - n_i * n_i ); return ( k < 0.0f ) ? float3( 0.0f, 0.0f, 0.0f ) : ( r * i - ( r * n_i + sqrt( k ) ) * n ); } inline float3 round( float3 v ) { return float3( round( v.x ), round( v.y ), round( v.z ) ); } inline float3 rsqrt( float3 v ) { return float3( rcp( sqrt( v.x ) ), rcp( sqrt( v.y ) ), rcp( sqrt( v.z ) ) ); } inline float3 saturate( float3 v ) { return float3( saturate( v.x ), saturate( v.y ), saturate( v.z ) ); } inline float3 sign( float3 v ) { return float3( sign( v.x ), sign( v.y ), sign( v.z ) ); } inline float3 sin( float3 v ) { return float3( sin( v.x ), sin( v.y ), sin( v.z ) ); } inline float3 sinh( float3 v ) { return float3( sinh( v.x ), sinh( v.y ), sinh( v.z ) ); } inline float3 smoothstep( float3 min, float3 max, float3 v ) { return float3( smoothstep( min.x, max.x, v.x ), smoothstep( min.y, max.y, v.y ), smoothstep( min.z, max.z, v.z ) ); } inline float3 smootherstep( float3 min, float3 max, float3 v ) { return float3( smootherstep( min.x, max.x, v.x ), smootherstep( min.y, max.y, v.y ), smootherstep( min.z, max.z, v.z ) ); } inline float3 sqrt( float3 v ) { return float3( sqrt( v.x ), sqrt( v.y ), sqrt( v.z ) ); } inline float3 step( float3 a, float3 b ) { return float3( step( a.x, b.x ), step( a.y, b.y ), step( a.z, b.z ) ); } inline float3 tan( float3 v ) { return float3( tan( v.x ), tan( v.y ), tan( v.z ) ); } inline float3 tanh( float3 v ) { return float3( tanh( v.x ), tanh( v.y ), tanh( v.z ) ); } inline float3 trunc( float3 v ) { return float3( trunc( v.x ), trunc( v.y ), trunc( v.z ) ); } struct float4 { float x; float y; float z; float w; // constructors inline float4() { } inline float4( float f ) : x( f ), y( f ), z( f ), w( f ) { } inline explicit float4( float f[4] ) : x( f[0] ), y( f[1] ), z( f[2] ), w( f[3] ) { } inline float4( float xr, float yg, float zb, float wa ) : x( xr ), y( yg ), z( zb ), w( wa ) { } inline float4( float2 a, float b, float c ) : x( a.x ), y( a.y ), z( b ), w( c ) { } inline float4( float a, float2 b, float c ) : x( a ), y( b.x ), z( b.y ), w( c ) { } inline float4( float a, float b, float2 c ) : x( a ), y( b ), z( c.x ), w( c.y ) { } inline float4( float2 a, float2 b ) : x( a.x ), y( a.y ), z( b.x ), w( b.y ) { } inline float4( float a, float3 b ) : x( a ), y( b.x ), z( b.y ), w( b.z ) { } inline float4( float3 a, float b ) : x( a.x ), y( a.y ), z( a.z ), w( b ) { } inline float4( swizzle4 s ) : x( s.x ), y( s.y ), z( s.z ), w( s.w ) { } // conversions inline float4( float4_t v ) : x( v.x ), y( v.y ), z( v.z ), w( v.w ) { } inline operator float4_t() const { float4_t v = { x, y, z, w }; return v; }; // indexing inline float& operator[]( int index ) { return ( (float*) this )[ index ]; } inline const float& operator[]( int index ) const { return ( (float*) this )[ index ]; } // aliases inline float& r() { return x; } inline float& g() { return y; } inline float& b() { return z; } inline float& a() { return w; } // swizzling permutations: v.rg(), v.xwzz() etc. #define S( a, b ) inline swizzle2 a##b() { return swizzle2( a, b ); } S(x,x); S(x,y); S(x,z); S(x,w); S(y,x); S(y,y); S(y,z); S(y,w); S(z,x); S(z,y); S(z,z); S(z,w); S(w,x); S(w,y); S(w,z); S(w,w); #undef S #define S( a, b ) inline swizzle2 a##b() { return swizzle2( a(), b() ); } S(r,r); S(r,g); S(r,b); S(r,a); S(g,r); S(g,g); S(g,b); S(g,a); S(b,r); S(b,g); S(b,b); S(b,a); S(a,r); S(a,g); S(a,b); S(a,a); #undef S #define S( a, b, c ) inline swizzle3 a##b##c() { return swizzle3( a, b, c ); } S(x,x,x); S(x,x,y); S(x,x,z); S(x,x,w); S(x,y,x); S(x,y,y); S(x,y,z); S(x,y,w); S(x,z,x); S(x,z,y); S(x,z,z); S(x,z,w); S(x,w,x); S(x,w,y); S(x,w,z); S(x,w,w); S(y,x,x); S(y,x,y); S(y,x,z); S(y,x,w); S(y,y,x); S(y,y,y); S(y,y,z); S(y,y,w); S(y,z,x); S(y,z,y); S(y,z,z); S(y,z,w); S(y,w,x); S(y,w,y); S(y,w,z); S(y,w,w); S(z,x,x); S(z,x,y); S(z,x,z); S(z,x,w); S(z,y,x); S(z,y,y); S(z,y,z); S(z,y,w); S(z,z,x); S(z,z,y); S(z,z,z); S(z,z,w); S(z,w,x); S(z,w,y); S(z,w,z); S(z,w,w); S(w,x,x); S(w,x,y); S(w,x,z); S(w,x,w); S(w,y,x); S(w,y,y); S(w,y,z); S(w,y,w); S(w,z,x); S(w,z,y); S(w,z,z); S(w,z,w); S(w,w,x); S(w,w,y); S(w,w,z); S(w,w,w); #undef S #define S( a, b, c ) inline swizzle3 a##b##c() { return swizzle3( a(), b(), c() ); } S(r,r,r); S(r,r,g); S(r,r,b); S(r,r,a); S(r,g,r); S(r,g,g); S(r,g,b); S(r,g,a); S(r,b,r); S(r,b,g); S(r,b,b); S(r,b,a); S(r,a,r); S(r,a,g); S(r,a,b); S(r,a,a); S(g,r,r); S(g,r,g); S(g,r,b); S(g,r,a); S(g,g,r); S(g,g,g); S(g,g,b); S(g,g,a); S(g,b,r); S(g,b,g); S(g,b,b); S(g,b,a); S(g,a,r); S(g,a,g); S(g,a,b); S(g,a,a); S(b,r,r); S(b,r,g); S(b,r,b); S(b,r,a); S(b,g,r); S(b,g,g); S(b,g,b); S(b,g,a); S(b,b,r); S(b,b,g); S(b,b,b); S(b,b,a); S(b,a,r); S(b,a,g); S(b,a,b); S(b,a,a); S(a,r,r); S(a,r,g); S(a,r,b); S(a,r,a); S(a,g,r); S(a,g,g); S(a,g,b); S(a,g,a); S(a,b,r); S(a,b,g); S(a,b,b); S(a,b,a); S(a,a,r); S(a,a,g); S(a,a,b); S(a,a,a); #undef S #define S( a, b, c, d ) inline swizzle4 a##b##c##d() { return swizzle4( a, b, c, d ); } S(x,x,x,x); S(x,x,x,y); S(x,x,x,z); S(x,x,x,w); S(x,x,y,x); S(x,x,y,y); S(x,x,y,z); S(x,x,y,w); S(x,x,z,x); S(x,x,z,y); S(x,x,z,z); S(x,x,z,w); S(x,x,w,x); S(x,x,w,y); S(x,x,w,z); S(x,x,w,w); S(x,y,x,x); S(x,y,x,y); S(x,y,x,z); S(x,y,x,w); S(x,y,y,x); S(x,y,y,y); S(x,y,y,z); S(x,y,y,w); S(x,y,z,x); S(x,y,z,y); S(x,y,z,z); S(x,y,z,w); S(x,y,w,x); S(x,y,w,y); S(x,y,w,z); S(x,y,w,w); S(x,z,x,x); S(x,z,x,y); S(x,z,x,z); S(x,z,x,w); S(x,z,y,x); S(x,z,y,y); S(x,z,y,z); S(x,z,y,w); S(x,z,z,x); S(x,z,z,y); S(x,z,z,z); S(x,z,z,w); S(x,z,w,x); S(x,z,w,y); S(x,z,w,z); S(x,z,w,w); S(x,w,x,x); S(x,w,x,y); S(x,w,x,z); S(x,w,x,w); S(x,w,y,x); S(x,w,y,y); S(x,w,y,z); S(x,w,y,w); S(x,w,z,x); S(x,w,z,y); S(x,w,z,z); S(x,w,z,w); S(x,w,w,x); S(x,w,w,y); S(x,w,w,z); S(x,w,w,w); S(y,x,x,x); S(y,x,x,y); S(y,x,x,z); S(y,x,x,w); S(y,x,y,x); S(y,x,y,y); S(y,x,y,z); S(y,x,y,w); S(y,x,z,x); S(y,x,z,y); S(y,x,z,z); S(y,x,z,w); S(y,x,w,x); S(y,x,w,y); S(y,x,w,z); S(y,x,w,w); S(y,y,x,x); S(y,y,x,y); S(y,y,x,z); S(y,y,x,w); S(y,y,y,x); S(y,y,y,y); S(y,y,y,z); S(y,y,y,w); S(y,y,z,x); S(y,y,z,y); S(y,y,z,z); S(y,y,z,w); S(y,y,w,x); S(y,y,w,y); S(y,y,w,z); S(y,y,w,w); S(y,z,x,x); S(y,z,x,y); S(y,z,x,z); S(y,z,x,w); S(y,z,y,x); S(y,z,y,y); S(y,z,y,z); S(y,z,y,w); S(y,z,z,x); S(y,z,z,y); S(y,z,z,z); S(y,z,z,w); S(y,z,w,x); S(y,z,w,y); S(y,z,w,z); S(y,z,w,w); S(y,w,x,x); S(y,w,x,y); S(y,w,x,z); S(y,w,x,w); S(y,w,y,x); S(y,w,y,y); S(y,w,y,z); S(y,w,y,w); S(y,w,z,x); S(y,w,z,y); S(y,w,z,z); S(y,w,z,w); S(y,w,w,x); S(y,w,w,y); S(y,w,w,z); S(y,w,w,w); S(z,x,x,x); S(z,x,x,y); S(z,x,x,z); S(z,x,x,w); S(z,x,y,x); S(z,x,y,y); S(z,x,y,z); S(z,x,y,w); S(z,x,z,x); S(z,x,z,y); S(z,x,z,z); S(z,x,z,w); S(z,x,w,x); S(z,x,w,y); S(z,x,w,z); S(z,x,w,w); S(z,y,x,x); S(z,y,x,y); S(z,y,x,z); S(z,y,x,w); S(z,y,y,x); S(z,y,y,y); S(z,y,y,z); S(z,y,y,w); S(z,y,z,x); S(z,y,z,y); S(z,y,z,z); S(z,y,z,w); S(z,y,w,x); S(z,y,w,y); S(z,y,w,z); S(z,y,w,w); S(z,z,x,x); S(z,z,x,y); S(z,z,x,z); S(z,z,x,w); S(z,z,y,x); S(z,z,y,y); S(z,z,y,z); S(z,z,y,w); S(z,z,z,x); S(z,z,z,y); S(z,z,z,z); S(z,z,z,w); S(z,z,w,x); S(z,z,w,y); S(z,z,w,z); S(z,z,w,w); S(z,w,x,x); S(z,w,x,y); S(z,w,x,z); S(z,w,x,w); S(z,w,y,x); S(z,w,y,y); S(z,w,y,z); S(z,w,y,w); S(z,w,z,x); S(z,w,z,y); S(z,w,z,z); S(z,w,z,w); S(z,w,w,x); S(z,w,w,y); S(z,w,w,z); S(z,w,w,w); S(w,x,x,x); S(w,x,x,y); S(w,x,x,z); S(w,x,x,w); S(w,x,y,x); S(w,x,y,y); S(w,x,y,z); S(w,x,y,w); S(w,x,z,x); S(w,x,z,y); S(w,x,z,z); S(w,x,z,w); S(w,x,w,x); S(w,x,w,y); S(w,x,w,z); S(w,x,w,w); S(w,y,x,x); S(w,y,x,y); S(w,y,x,z); S(w,y,x,w); S(w,y,y,x); S(w,y,y,y); S(w,y,y,z); S(w,y,y,w); S(w,y,z,x); S(w,y,z,y); S(w,y,z,z); S(w,y,z,w); S(w,y,w,x); S(w,y,w,y); S(w,y,w,z); S(w,y,w,w); S(w,z,x,x); S(w,z,x,y); S(w,z,x,z); S(w,z,x,w); S(w,z,y,x); S(w,z,y,y); S(w,z,y,z); S(w,z,y,w); S(w,z,z,x); S(w,z,z,y); S(w,z,z,z); S(w,z,z,w); S(w,z,w,x); S(w,z,w,y); S(w,z,w,z); S(w,z,w,w); S(w,w,x,x); S(w,w,x,y); S(w,w,x,z); S(w,w,x,w); S(w,w,y,x); S(w,w,y,y); S(w,w,y,z); S(w,w,y,w); S(w,w,z,x); S(w,w,z,y); S(w,w,z,z); S(w,w,z,w); S(w,w,w,x); S(w,w,w,y); S(w,w,w,z); S(w,w,w,w); #undef S #define S( a, b, c, d ) inline swizzle4 a##b##c##d() { return swizzle4( a(), b(), c(), d() ); } S(r,r,r,r); S(r,r,r,g); S(r,r,r,b); S(r,r,r,a); S(r,r,g,r); S(r,r,g,g); S(r,r,g,b); S(r,r,g,a); S(r,r,b,r); S(r,r,b,g); S(r,r,b,b); S(r,r,b,a); S(r,r,a,r); S(r,r,a,g); S(r,r,a,b); S(r,r,a,a); S(r,g,r,r); S(r,g,r,g); S(r,g,r,b); S(r,g,r,a); S(r,g,g,r); S(r,g,g,g); S(r,g,g,b); S(r,g,g,a); S(r,g,b,r); S(r,g,b,g); S(r,g,b,b); S(r,g,b,a); S(r,g,a,r); S(r,g,a,g); S(r,g,a,b); S(r,g,a,a); S(r,b,r,r); S(r,b,r,g); S(r,b,r,b); S(r,b,r,a); S(r,b,g,r); S(r,b,g,g); S(r,b,g,b); S(r,b,g,a); S(r,b,b,r); S(r,b,b,g); S(r,b,b,b); S(r,b,b,a); S(r,b,a,r); S(r,b,a,g); S(r,b,a,b); S(r,b,a,a); S(r,a,r,r); S(r,a,r,g); S(r,a,r,b); S(r,a,r,a); S(r,a,g,r); S(r,a,g,g); S(r,a,g,b); S(r,a,g,a); S(r,a,b,r); S(r,a,b,g); S(r,a,b,b); S(r,a,b,a); S(r,a,a,r); S(r,a,a,g); S(r,a,a,b); S(r,a,a,a); S(g,r,r,r); S(g,r,r,g); S(g,r,r,b); S(g,r,r,a); S(g,r,g,r); S(g,r,g,g); S(g,r,g,b); S(g,r,g,a); S(g,r,b,r); S(g,r,b,g); S(g,r,b,b); S(g,r,b,a); S(g,r,a,r); S(g,r,a,g); S(g,r,a,b); S(g,r,a,a); S(g,g,r,r); S(g,g,r,g); S(g,g,r,b); S(g,g,r,a); S(g,g,g,r); S(g,g,g,g); S(g,g,g,b); S(g,g,g,a); S(g,g,b,r); S(g,g,b,g); S(g,g,b,b); S(g,g,b,a); S(g,g,a,r); S(g,g,a,g); S(g,g,a,b); S(g,g,a,a); S(g,b,r,r); S(g,b,r,g); S(g,b,r,b); S(g,b,r,a); S(g,b,g,r); S(g,b,g,g); S(g,b,g,b); S(g,b,g,a); S(g,b,b,r); S(g,b,b,g); S(g,b,b,b); S(g,b,b,a); S(g,b,a,r); S(g,b,a,g); S(g,b,a,b); S(g,b,a,a); S(g,a,r,r); S(g,a,r,g); S(g,a,r,b); S(g,a,r,a); S(g,a,g,r); S(g,a,g,g); S(g,a,g,b); S(g,a,g,a); S(g,a,b,r); S(g,a,b,g); S(g,a,b,b); S(g,a,b,a); S(g,a,a,r); S(g,a,a,g); S(g,a,a,b); S(g,a,a,a); S(b,r,r,r); S(b,r,r,g); S(b,r,r,b); S(b,r,r,a); S(b,r,g,r); S(b,r,g,g); S(b,r,g,b); S(b,r,g,a); S(b,r,b,r); S(b,r,b,g); S(b,r,b,b); S(b,r,b,a); S(b,r,a,r); S(b,r,a,g); S(b,r,a,b); S(b,r,a,a); S(b,g,r,r); S(b,g,r,g); S(b,g,r,b); S(b,g,r,a); S(b,g,g,r); S(b,g,g,g); S(b,g,g,b); S(b,g,g,a); S(b,g,b,r); S(b,g,b,g); S(b,g,b,b); S(b,g,b,a); S(b,g,a,r); S(b,g,a,g); S(b,g,a,b); S(b,g,a,a); S(b,b,r,r); S(b,b,r,g); S(b,b,r,b); S(b,b,r,a); S(b,b,g,r); S(b,b,g,g); S(b,b,g,b); S(b,b,g,a); S(b,b,b,r); S(b,b,b,g); S(b,b,b,b); S(b,b,b,a); S(b,b,a,r); S(b,b,a,g); S(b,b,a,b); S(b,b,a,a); S(b,a,r,r); S(b,a,r,g); S(b,a,r,b); S(b,a,r,a); S(b,a,g,r); S(b,a,g,g); S(b,a,g,b); S(b,a,g,a); S(b,a,b,r); S(b,a,b,g); S(b,a,b,b); S(b,a,b,a); S(b,a,a,r); S(b,a,a,g); S(b,a,a,b); S(b,a,a,a); S(a,r,r,r); S(a,r,r,g); S(a,r,r,b); S(a,r,r,a); S(a,r,g,r); S(a,r,g,g); S(a,r,g,b); S(a,r,g,a); S(a,r,b,r); S(a,r,b,g); S(a,r,b,b); S(a,r,b,a); S(a,r,a,r); S(a,r,a,g); S(a,r,a,b); S(a,r,a,a); S(a,g,r,r); S(a,g,r,g); S(a,g,r,b); S(a,g,r,a); S(a,g,g,r); S(a,g,g,g); S(a,g,g,b); S(a,g,g,a); S(a,g,b,r); S(a,g,b,g); S(a,g,b,b); S(a,g,b,a); S(a,g,a,r); S(a,g,a,g); S(a,g,a,b); S(a,g,a,a); S(a,b,r,r); S(a,b,r,g); S(a,b,r,b); S(a,b,r,a); S(a,b,g,r); S(a,b,g,g); S(a,b,g,b); S(a,b,g,a); S(a,b,b,r); S(a,b,b,g); S(a,b,b,b); S(a,b,b,a); S(a,b,a,r); S(a,b,a,g); S(a,b,a,b); S(a,b,a,a); S(a,a,r,r); S(a,a,r,g); S(a,a,r,b); S(a,a,r,a); S(a,a,g,r); S(a,a,g,g); S(a,a,g,b); S(a,a,g,a); S(a,a,b,r); S(a,a,b,g); S(a,a,b,b); S(a,a,b,a); S(a,a,a,r); S(a,a,a,g); S(a,a,a,b); S(a,a,a,a); #undef S }; // operators inline float4 operator-( float4 v ) { return float4( -v.x, -v.y, -v.z, -v.w ); } inline bool operator==( float4 a, float4 b ) { return a.x == b.x && a.y == b.y && a.z == b.z && a.w == b.w; } inline bool operator!=( float4 a, float4 b ) { return a.x != b.x || a.y != b.y || a.z != b.z || a.w != b.w; } inline float4& operator+=( float4& a, float4 b ) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; return a; }; inline float4& operator-=( float4& a, float4 b ) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; return a; }; inline float4& operator*=( float4& a, float4 b ) { a.x *= b.x; a.y *= b.y; a.z *= b.z; a.w *= b.w; return a; }; inline float4& operator/=( float4& a, float4 b ) { a.x /= b.x; a.y /= b.y; a.z /= b.z; a.w /= b.w; return a; }; inline float4& operator+=( float4& a, float s ) { a.x += s; a.y += s; a.z += s; a.w += s; return a; }; inline float4& operator-=( float4& a, float s ) { a.x -= s; a.y -= s; a.z -= s; a.w -= s; return a; }; inline float4& operator*=( float4& a, float s ) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; return a; }; inline float4& operator/=( float4& a, float s ) { a.x /= s; a.y /= s; a.z /= s; a.w /= s; return a; }; inline float4 operator+( float4 a, float4 b ) { return float4( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w ); } inline float4 operator-( float4 a, float4 b ) { return float4( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w ); } inline float4 operator*( float4 a, float4 b ) { return float4( a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w ); } inline float4 operator/( float4 a, float4 b ) { return float4( a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w ); } inline float4 operator+( float4 a, float b ) { return float4( a.x + b, a.y + b, a.z + b, a.w + b ); } inline float4 operator-( float4 a, float b ) { return float4( a.x - b, a.y - b, a.z - b, a.w - b ); } inline float4 operator*( float4 a, float b ) { return float4( a.x * b, a.y * b, a.z * b, a.w * b ); } inline float4 operator/( float4 a, float b ) { return float4( a.x / b, a.y / b, a.z / b, a.w / b ); } inline float4 operator+( float a, float4 b ) { return float4( a + b.x, a + b.y, a + b.z, a + b.w ); } inline float4 operator-( float a, float4 b ) { return float4( a - b.x, a - b.y, a - b.z, a - b.w ); } inline float4 operator*( float a, float4 b ) { return float4( a * b.x, a * b.y, a * b.z, a * b.w ); } inline float4 operator/( float a, float4 b ) { return float4( a / b.x, a / b.y, a / b.z, a / b.w ); } // functions inline float4 abs( float4 v ) { return float4( abs( v.x ), abs( v.y ), abs( v.z ), abs( v.w ) ); } inline float4 acos( float4 v ) { return float4( acos( v.x ), acos( v.y ), acos( v.z ), acos( v.w ) ); } inline bool all( float4 v ) { return v.x != 0.0f && v.y != 0.0f && v.z != 0.0f && v.w != 0.0f; } inline bool any( float4 v ) { return v.x != 0.0f || v.y != 0.0f || v.z != 0.0f || v.w != 0.0f; } inline float4 asin( float4 v ) { return float4( asin( v.x ), asin( v.y ), asin( v.z ), asin( v.w ) ); } inline float4 atan( float4 v ) { return float4( atan( v.x ), atan( v.y ), atan( v.z ), atan( v.w ) ); } inline float4 atan2( float4 y, float4 x ) { return float4( atan2( y.x, x.x ), atan2( y.y, x.y ), atan2( y.z, x.z ), atan2( y.w, x.w ) ); } inline float4 ceil( float4 v ) { return float4( ceil( v.x ), ceil( v.y ), ceil( v.z ), ceil( v.w ) ); } inline float4 clamp( float4 v, float4 min, float4 max ) { return float4( clamp( v.x, min.x, max.x ), clamp( v.y, min.y, max.y ), clamp( v.z, min.z, max.z ), clamp( v.w, min.w, max.w ) ); } inline float4 cos( float4 v ) { return float4( cos( v.x ), cos( v.y ), cos( v.z ), cos( v.w ) ); } inline float4 cosh( float4 v ) { return float4( cosh( v.x ), cosh( v.y ), cosh( v.z ), cosh( v.w ) ); } inline float4 degrees( float4 v ) { return float4( degrees( v.x ), degrees( v.y ), degrees( v.z ), degrees( v.w ) ); } inline float distancesq( float4 a, float4 b ) { float x = b.x - a.x; float y = b.y - a.y; float z = b.z - a.z; float w = b.w - a.w; return x * x + y * y + z * z + w * w; } inline float distance( float4 a, float4 b ) { float x = b.x - a.x; float y = b.y - a.y; float z = b.z - a.z; float w = b.w - a.w; return sqrt( x * x + y * y + z * z + w * w ); } inline float dot( float4 a, float4 b ) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } inline float4 exp( float4 v ) { return float4( exp( v.x ), exp( v.y ), exp( v.z ), exp( v.w ) ); } inline float4 exp2( float4 v ) { return float4( exp2( v.x ), exp2( v.y ), exp2( v.z ), exp2( v.w ) ); } inline float4 floor( float4 v ) { return float4( floor( v.x ), floor( v.y ), floor( v.z ), floor( v.w ) ); } inline float4 fmod( float4 a, float4 b ) { return float4( fmod( a.x, b.x ), fmod( a.y, b.y ), fmod( a.z, b.z ), fmod( a.w, b.w ) ); } inline float4 frac( float4 v ) { return float4( frac( v.x ), frac( v.y ), frac( v.z ), frac( v.w ) ); } inline float lengthsq( float4 v ) { return v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w; } inline float length( float4 v ) { return sqrt( v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w ); } inline float4 lerp( float4 a, float4 b, float s ) { return float4( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ), lerp( a.z, b.z, s ), lerp( a.w, b.w, s ) ); } inline float4 log( float4 v ) { return float4( log( v.x ), log( v.y ), log( v.z ), log( v.w ) ); } inline float4 log2( float4 v ) { return float4( log2( v.x ), log2( v.y ), log2( v.z ), log2( v.w ) ); } inline float4 log10( float4 v ) { return float4( log10( v.x ), log10( v.y ), log10( v.z ), log10( v.w ) ); } inline float4 mad( float4 a, float4 b, float4 c ) { return a * b + c; } inline float4 max( float4 a, float4 b ) { return float4( max( a.x, b.x ), max( a.y, b.y ), max( a.z, b.z ), max( a.w, b.w ) ); } inline float4 min( float4 a, float4 b ) { return float4( min( a.x, b.x ), min( a.y, b.y ), min( a.z, b.z ), min( a.w, b.w ) ); } inline float4 normalize( float4 v ) { float l = sqrt( v.x * v.x + v.y * v.y + v.z * v.z + v.w * v.w ); return l == 0.0f ? v : float4( v.x / l, v.y / l, v.z / l, v.w / l ); } inline float4 pow( float4 a, float4 b ) { return float4( pow( a.x, b.x ), pow( a.y, b.y ), pow( a.z, b.z ), pow( a.w, b.w ) ); } inline float4 radians( float4 v ) { return float4( radians( v.x ), radians( v.y ), radians( v.z ), radians( v.w ) ); } inline float4 rcp( float4 v ) { return float4( rcp( v.x ), rcp( v.y ), rcp( v.z ), rcp( v.w ) ); } inline float4 reflect( float4 i, float4 n ) { return i - 2.0f * n * dot( i, n ) ; } inline float4 refract( float4 i, float4 n, float r ) { float n_i = dot( n, i ); float k = 1.0f - r * r * ( 1.0f - n_i * n_i ); return ( k < 0.0f ) ? float4( 0.0f, 0.0f, 0.0f, 0.0f ) : ( r * i - ( r * n_i + sqrt( k ) ) * n ); } inline float4 round( float4 v ) { return float4( round( v.x ), round( v.y ), round( v.z ), round( v.w ) ); } inline float4 rsqrt( float4 v ) { return float4( rcp( sqrt( v.x ) ), rcp( sqrt( v.y ) ), rcp( sqrt( v.z ) ), rcp( sqrt( v.w ) ) ); } inline float4 saturate( float4 v ) { return float4( saturate( v.x ), saturate( v.y ), saturate( v.z ), saturate( v.w ) ); } inline float4 sign( float4 v ) { return float4( sign( v.x ), sign( v.y ), sign( v.z ), sign( v.w ) ); } inline float4 sin( float4 v ) { return float4( sin( v.x ), sin( v.y ), sin( v.z ), sin( v.w ) ); } inline float4 sinh( float4 v ) { return float4( sinh( v.x ), sinh( v.y ), sinh( v.z ), sinh( v.w ) ); } inline float4 smoothstep( float4 min, float4 max, float4 v ) { return float4( smoothstep( min.x, max.x, v.x ), smoothstep( min.y, max.y, v.y ), smoothstep( min.z, max.z, v.z ), smoothstep( min.w, max.w, v.w ) ); } inline float4 smootherstep( float4 min, float4 max, float4 v ) { return float4( smootherstep( min.x, max.x, v.x ), smootherstep( min.y, max.y, v.y ), smootherstep( min.z, max.z, v.z ), smootherstep( min.w, max.w, v.w ) ); } inline float4 sqrt( float4 v ) { return float4( sqrt( v.x ), sqrt( v.y ), sqrt( v.z ), sqrt( v.w ) ); } inline float4 step( float4 a, float4 b ) { return float4( step( a.x, b.x ), step( a.y, b.y ), step( a.z, b.z ), step( a.w, b.w ) ); } inline float4 tan( float4 v ) { return float4( tan( v.x ), tan( v.y ), tan( v.z ), tan( v.w ) ); } inline float4 tanh( float4 v ) { return float4( tanh( v.x ), tanh( v.y ), tanh( v.z ), tanh( v.w ) ); } inline float4 trunc( float4 v ) { return float4( trunc( v.x ), trunc( v.y ), trunc( v.z ), trunc( v.w ) ); } struct float2x2 { // rows float2 x; float2 y; // constructors inline float2x2() { } inline float2x2( float f ) : x( float2( f ) ), y( float2( f ) ) { } inline explicit float2x2( float m[4] ) : x( m[0], m[1] ), y( m[2], m[3] ) { } inline float2x2( float m00, float m01, float m10, float m11) : x( m00, m01 ), y( m10, m11 ) { } inline float2x2( float2 x_, float2 y_ ) : x( x_ ), y( y_ ) { } // conversions inline float2x2( float2x2_t m ) : x( m.x ), y( m.y ) { } inline operator float2x2_t() const { float2x2_t m = { x, y }; return m; }; // indexing inline float2& operator[]( int row ) { return ( (float2*) this )[ row ]; } // constants static inline float2x2 identity() { return float2x2( float2( 1.0f, 0.0f ), float2( 0.0f, 1.0f ) ); } }; // operators inline float2x2& operator+=( float2x2& a, float2x2 b ) { a.x += b.x; a.y += b.y; return a; }; inline float2x2& operator-=( float2x2& a, float2x2 b ) { a.x -= b.x; a.y -= b.y; return a; }; inline float2x2& operator*=( float2x2& a, float2x2 b ) { a.x *= b.x; a.y *= b.y; return a; }; inline float2x2& operator/=( float2x2& a, float2x2 b ) { a.x /= b.x; a.y /= b.y; return a; }; inline float2x2& operator+=( float2x2& a, float s ) { a.x += s; a.y += s; return a; }; inline float2x2& operator-=( float2x2& a, float s ) { a.x -= s; a.y -= s; return a; }; inline float2x2& operator*=( float2x2& a, float s ) { a.x *= s; a.y *= s; return a; }; inline float2x2& operator/=( float2x2& a, float s ) { a.x /= s; a.y /= s; return a; }; inline float2x2 operator+( float2x2 a, float2x2 b ) { return float2x2( a.x + b.x, a.y + b.y ); } inline float2x2 operator-( float2x2 a, float2x2 b ) { return float2x2( a.x - b.x, a.y - b.y ); } inline float2x2 operator*( float2x2 a, float2x2 b ) { return float2x2( a.x * b.x, a.y * b.y ); } inline float2x2 operator/( float2x2 a, float2x2 b ) { return float2x2( a.x / b.x, a.y / b.y ); } inline float2x2 operator+( float2x2 a, float b ) { return float2x2( a.x + b, a.y + b ); } inline float2x2 operator-( float2x2 a, float b ) { return float2x2( a.x - b, a.y - b ); } inline float2x2 operator*( float2x2 a, float b ) { return float2x2( a.x * b, a.y * b ); } inline float2x2 operator/( float2x2 a, float b ) { return float2x2( a.x / b, a.y / b ); } inline float2x2 operator+( float a, float2x2 b ) { return float2x2( a + b.x, a + b.y ); } inline float2x2 operator-( float a, float2x2 b ) { return float2x2( a - b.x, a - b.y ); } inline float2x2 operator*( float a, float2x2 b ) { return float2x2( a * b.x, a * b.y ); } inline float2x2 operator/( float a, float2x2 b ) { return float2x2( a / b.x, a / b.y ); } // functions inline float2x2 abs( float2x2 m ) { return float2x2( abs( m.x ), abs( m.y ) ); } inline float2x2 acos( float2x2 m ) { return float2x2( acos( m.x ), acos( m.y ) ); } inline bool all( float2x2 m ) { return all( m.x ) && all( m.y ); } inline bool any( float2x2 m ) { return any( m.x ) || any( m.y ); } inline float2x2 asin( float2x2 m ) { return float2x2( asin( m.x ), asin( m.y ) ); } inline float2x2 atan( float2x2 m ) { return float2x2( atan( m.x ), atan( m.y ) ); } inline float2x2 atan2( float2x2 y, float2x2 x ) { return float2x2( atan2( y.x, x.x ), atan2( y.y, x.y ) ); } inline float2x2 ceil( float2x2 m ) { return float2x2( ceil( m.x ), ceil( m.y ) ); } inline float2x2 clamp( float2x2 m, float2x2 min, float2x2 max ) { return float2x2( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ) ); } inline float2x2 cos( float2x2 m ) { return float2x2( cos( m.x ), cos( m.y ) ); } inline float2x2 cosh( float2x2 m ) { return float2x2( cosh( m.x ), cosh( m.y ) ); } inline float2x2 degrees( float2x2 m ) { return float2x2( degrees( m.x ), degrees( m.y ) ); } inline float2x2 exp( float2x2 m ) { return float2x2( exp( m.x ), exp( m.y ) ); } inline float2x2 exp2( float2x2 m ) { return float2x2( exp2( m.x ), exp2( m.y ) ); } inline float2x2 floor( float2x2 m ) { return float2x2( floor( m.x ), floor( m.y ) ); } inline float2x2 fmod( float2x2 a, float2x2 b ) { return float2x2( fmod( a.x, b.x ), fmod( a.y, b.y ) ); } inline float2x2 frac( float2x2 m ) { return float2x2( frac( m.x ), frac( m.y ) ); } inline float2x2 lerp( float2x2 a, float2x2 b, float s ) { return float2x2( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ) ); } inline float2x2 log( float2x2 m ) { return float2x2( log( m.x ), log( m.y ) ); } inline float2x2 log2( float2x2 m ) { return float2x2( log2( m.x ), log2( m.y ) ); } inline float2x2 log10( float2x2 m ) { return float2x2( log10( m.x ), log10( m.y ) ); } inline float2x2 mad( float2x2 a, float2x2 b, float2x2 c ) { return a * b + c; } inline float2x2 max( float2x2 a, float2x2 b ) { return float2x2( max( a.x, b.x ), max( a.y, b.y ) ); } inline float2x2 min( float2x2 a, float2x2 b ) { return float2x2( min( a.x, b.x ), min( a.y, b.y ) ); } inline float2x2 pow( float2x2 a, float2x2 b ) { return float2x2( pow( a.x, b.x ), pow( a.y, b.y ) ); } inline float2x2 radians( float2x2 m ) { return float2x2( radians( m.x ), radians( m.y ) ); } inline float2x2 rcp( float2x2 m ) { return float2x2( rcp( m.x ), rcp( m.y ) ); } inline float2x2 round( float2x2 m ) { return float2x2( round( m.x ), round( m.y ) ); } inline float2x2 rsqrt( float2x2 m ) { return float2x2( rsqrt( m.x ), rsqrt( m.y ) ); } inline float2x2 saturate( float2x2 m ) { return float2x2( saturate( m.x ), saturate( m.y ) ); } inline float2x2 sign( float2x2 m ) { return float2x2( sign( m.x ), sign( m.y ) ); } inline float2x2 sin( float2x2 m ) { return float2x2( sin( m.x ), sin( m.y ) ); } inline float2x2 sinh( float2x2 m ) { return float2x2( sinh( m.x ), sinh( m.y ) ); } inline float2x2 smoothstep( float2x2 min, float2x2 max, float2x2 m ) { return float2x2( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ) ); } inline float2x2 smootherstep( float2x2 min, float2x2 max, float2x2 m ) { return float2x2( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ) ); } inline float2x2 sqrt( float2x2 m ) { return float2x2( sqrt( m.x ), sqrt( m.y ) ); } inline float2x2 step( float2x2 a, float2x2 b ) { return float2x2( step( a.x, b.x ), step( a.y, b.y ) ); } inline float2x2 tan( float2x2 m ) { return float2x2( tan( m.x ), tan( m.y ) ); } inline float2x2 tanh( float2x2 m ) { return float2x2( tanh( m.x ), tanh( m.y ) ); } inline float2x2 trunc( float2x2 m ) { return float2x2( trunc( m.x ), trunc( m.y ) ); } struct float2x3 { // rows float3 x; float3 y; // constructors inline float2x3() { } inline float2x3( float f ) : x( float3( f ) ), y( float3( f ) ) { } inline explicit float2x3( float m[6] ) : x( m[0], m[1], m[2] ), y( m[3], m[4], m[5] ) { } inline float2x3( float m00, float m01, float m02, float m10, float m11, float m12 ) : x( m00, m01, m02 ), y( m10, m11, m12 ) { } inline float2x3( float3 x_, float3 y_ ) : x( x_ ), y( y_ ) { } // conversions inline float2x3( float2x3_t m ) : x( m.x ), y( m.y ) { } inline operator float2x3_t() const { float2x3_t m = { x, y }; return m; }; // indexing inline float3 operator[]( int row ) { return ( (float3*) this )[ row ]; } }; // operators inline float2x3& operator+=( float2x3& a, float2x3 b ) { a.x += b.x; a.y += b.y; return a; }; inline float2x3& operator-=( float2x3& a, float2x3 b ) { a.x -= b.x; a.y -= b.y; return a; }; inline float2x3& operator*=( float2x3& a, float2x3 b ) { a.x *= b.x; a.y *= b.y; return a; }; inline float2x3& operator/=( float2x3& a, float2x3 b ) { a.x /= b.x; a.y /= b.y; return a; }; inline float2x3& operator+=( float2x3& a, float s ) { a.x += s; a.y += s; return a; }; inline float2x3& operator-=( float2x3& a, float s ) { a.x -= s; a.y -= s; return a; }; inline float2x3& operator*=( float2x3& a, float s ) { a.x *= s; a.y *= s; return a; }; inline float2x3& operator/=( float2x3& a, float s ) { a.x /= s; a.y /= s; return a; }; inline float2x3 operator+( float2x3 a, float2x3 b ) { return float2x3( a.x + b.x, a.y + b.y ); } inline float2x3 operator-( float2x3 a, float2x3 b ) { return float2x3( a.x - b.x, a.y - b.y ); } inline float2x3 operator*( float2x3 a, float2x3 b ) { return float2x3( a.x * b.x, a.y * b.y ); } inline float2x3 operator/( float2x3 a, float2x3 b ) { return float2x3( a.x / b.x, a.y / b.y ); } inline float2x3 operator+( float2x3 a, float b ) { return float2x3( a.x + b, a.y + b ); } inline float2x3 operator-( float2x3 a, float b ) { return float2x3( a.x - b, a.y - b ); } inline float2x3 operator*( float2x3 a, float b ) { return float2x3( a.x * b, a.y * b ); } inline float2x3 operator/( float2x3 a, float b ) { return float2x3( a.x / b, a.y / b ); } inline float2x3 operator+( float a, float2x3 b ) { return float2x3( a + b.x, a + b.y ); } inline float2x3 operator-( float a, float2x3 b ) { return float2x3( a - b.x, a - b.y ); } inline float2x3 operator*( float a, float2x3 b ) { return float2x3( a * b.x, a * b.y ); } inline float2x3 operator/( float a, float2x3 b ) { return float2x3( a / b.x, a / b.y ); } // functions inline float2x3 abs( float2x3 m ) { return float2x3( abs( m.x ), abs( m.y ) ); } inline float2x3 acos( float2x3 m ) { return float2x3( acos( m.x ), acos( m.y ) ); } inline bool all( float2x3 m ) { return all( m.x ) && all( m.y ); } inline bool any( float2x3 m ) { return any( m.x ) || any( m.y ); } inline float2x3 asin( float2x3 m ) { return float2x3( asin( m.x ), asin( m.y ) ); } inline float2x3 atan( float2x3 m ) { return float2x3( atan( m.x ), atan( m.y ) ); } inline float2x3 atan2( float2x3 y, float2x3 x ) { return float2x3( atan2( y.x, x.x ), atan2( y.y, x.y ) ); } inline float2x3 ceil( float2x3 m ) { return float2x3( ceil( m.x ), ceil( m.y ) ); } inline float2x3 clamp( float2x3 m, float2x3 min, float2x3 max ) { return float2x3( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ) ); } inline float2x3 cos( float2x3 m ) { return float2x3( cos( m.x ), cos( m.y ) ); } inline float2x3 cosh( float2x3 m ) { return float2x3( cosh( m.x ), cosh( m.y ) ); } inline float2x3 degrees( float2x3 m ) { return float2x3( degrees( m.x ), degrees( m.y ) ); } inline float2x3 exp( float2x3 m ) { return float2x3( exp( m.x ), exp( m.y ) ); } inline float2x3 exp2( float2x3 m ) { return float2x3( exp2( m.x ), exp2( m.y ) ); } inline float2x3 floor( float2x3 m ) { return float2x3( floor( m.x ), floor( m.y ) ); } inline float2x3 fmod( float2x3 a, float2x3 b ) { return float2x3( fmod( a.x, b.x ), fmod( a.y, b.y ) ); } inline float2x3 frac( float2x3 m ) { return float2x3( frac( m.x ), frac( m.y ) ); } inline float2x3 lerp( float2x3 a, float2x3 b, float s ) { return float2x3( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ) ); } inline float2x3 log( float2x3 m ) { return float2x3( log( m.x ), log( m.y ) ); } inline float2x3 log2( float2x3 m ) { return float2x3( log2( m.x ), log2( m.y ) ); } inline float2x3 log10( float2x3 m ) { return float2x3( log10( m.x ), log10( m.y ) ); } inline float2x3 mad( float2x3 a, float2x3 b, float2x3 c ) { return a * b + c; } inline float2x3 max( float2x3 a, float2x3 b ) { return float2x3( max( a.x, b.x ), max( a.y, b.y ) ); } inline float2x3 min( float2x3 a, float2x3 b ) { return float2x3( min( a.x, b.x ), min( a.y, b.y ) ); } inline float2x3 pow( float2x3 a, float2x3 b ) { return float2x3( pow( a.x, b.x ), pow( a.y, b.y ) ); } inline float2x3 radians( float2x3 m ) { return float2x3( radians( m.x ), radians( m.y ) ); } inline float2x3 rcp( float2x3 m ) { return float2x3( rcp( m.x ), rcp( m.y ) ); } inline float2x3 round( float2x3 m ) { return float2x3( round( m.x ), round( m.y ) ); } inline float2x3 rsqrt( float2x3 m ) { return float2x3( rsqrt( m.x ), rsqrt( m.y ) ); } inline float2x3 saturate( float2x3 m ) { return float2x3( saturate( m.x ), saturate( m.y ) ); } inline float2x3 sign( float2x3 m ) { return float2x3( sign( m.x ), sign( m.y ) ); } inline float2x3 sin( float2x3 m ) { return float2x3( sin( m.x ), sin( m.y ) ); } inline float2x3 sinh( float2x3 m ) { return float2x3( sinh( m.x ), sinh( m.y ) ); } inline float2x3 smoothstep( float2x3 min, float2x3 max, float2x3 m ) { return float2x3( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ) ); } inline float2x3 smootherstep( float2x3 min, float2x3 max, float2x3 m ) { return float2x3( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ) ); } inline float2x3 sqrt( float2x3 m ) { return float2x3( sqrt( m.x ), sqrt( m.y ) ); } inline float2x3 step( float2x3 a, float2x3 b ) { return float2x3( step( a.x, b.x ), step( a.y, b.y ) ); } inline float2x3 tan( float2x3 m ) { return float2x3( tan( m.x ), tan( m.y ) ); } inline float2x3 tanh( float2x3 m ) { return float2x3( tanh( m.x ), tanh( m.y ) ); } inline float2x3 trunc( float2x3 m ) { return float2x3( trunc( m.x ), trunc( m.y ) ); } struct float3x2 { // rows float2 x; float2 y; float2 z; // constructors inline float3x2() { } inline float3x2( float f ) : x( float2( f ) ), y( float2( f ) ), z( float2( f ) ) { } inline explicit float3x2( float m[6] ) : x( m[0], m[1] ), y( m[2], m[3] ), z( m[4], m[5] ) { } inline float3x2( float m00, float m01, float m10, float m11, float m20, float m21 ) : x( m00, m01 ), y( m10, m11 ), z( m20, m21 ) { } inline float3x2( float2 x_, float2 y_, float2 z_ ) : x( x_ ), y( y_ ), z( z_ ) { } // conversions inline float3x2( float3x2_t m ) : x( m.x ), y( m.y ), z( m.z ) { } inline operator float3x2_t() const { float3x2_t m = { x, y, z }; return m; }; // indexing inline float2 operator[]( int row ) { return ( (float2*) this )[ row ]; } }; // operators inline float3x2& operator+=( float3x2& a, float3x2 b ) { a.x += b.x; a.y += b.y; a.z += b.z; return a; }; inline float3x2& operator-=( float3x2& a, float3x2 b ) { a.x -= b.x; a.y -= b.y; a.z -= b.z; return a; }; inline float3x2& operator*=( float3x2& a, float3x2 b ) { a.x *= b.x; a.y *= b.y; a.z *= b.z; return a; }; inline float3x2& operator/=( float3x2& a, float3x2 b ) { a.x /= b.x; a.y /= b.y; a.z /= b.z; return a; }; inline float3x2& operator+=( float3x2& a, float s ) { a.x += s; a.y += s; a.z += s; return a; }; inline float3x2& operator-=( float3x2& a, float s ) { a.x -= s; a.y -= s; a.z -= s; return a; }; inline float3x2& operator*=( float3x2& a, float s ) { a.x *= s; a.y *= s; a.z *= s; return a; }; inline float3x2& operator/=( float3x2& a, float s ) { a.x /= s; a.y /= s; a.z /= s; return a; }; inline float3x2 operator+( float3x2 a, float3x2 b ) { return float3x2( a.x + b.x, a.y + b.y, a.z + b.z ); } inline float3x2 operator-( float3x2 a, float3x2 b ) { return float3x2( a.x - b.x, a.y - b.y, a.z - b.z ); } inline float3x2 operator*( float3x2 a, float3x2 b ) { return float3x2( a.x * b.x, a.y * b.y, a.z * b.z ); } inline float3x2 operator/( float3x2 a, float3x2 b ) { return float3x2( a.x / b.x, a.y / b.y, a.z / b.z ); } inline float3x2 operator+( float3x2 a, float b ) { return float3x2( a.x + b, a.y + b, a.z + b ); } inline float3x2 operator-( float3x2 a, float b ) { return float3x2( a.x - b, a.y - b, a.z - b ); } inline float3x2 operator*( float3x2 a, float b ) { return float3x2( a.x * b, a.y * b, a.z * b ); } inline float3x2 operator/( float3x2 a, float b ) { return float3x2( a.x / b, a.y / b, a.z / b ); } inline float3x2 operator+( float a, float3x2 b ) { return float3x2( a + b.x, a + b.y, a + b.z ); } inline float3x2 operator-( float a, float3x2 b ) { return float3x2( a - b.x, a - b.y, a - b.z ); } inline float3x2 operator*( float a, float3x2 b ) { return float3x2( a * b.x, a * b.y, a * b.z ); } inline float3x2 operator/( float a, float3x2 b ) { return float3x2( a / b.x, a / b.y, a / b.z ); } // functions inline float3x2 abs( float3x2 m ) { return float3x2( abs( m.x ), abs( m.y ), abs( m.z ) ); } inline float3x2 acos( float3x2 m ) { return float3x2( acos( m.x ), acos( m.y ), acos( m.z ) ); } inline bool all( float3x2 m ) { return all( m.x ) && all( m.y ) && all( m.z ); } inline bool any( float3x2 m ) { return any( m.x ) || any( m.y ) || any( m.z ); } inline float3x2 asin( float3x2 m ) { return float3x2( asin( m.x ), asin( m.y ), asin( m.z ) ); } inline float3x2 atan( float3x2 m ) { return float3x2( atan( m.x ), atan( m.y ), atan( m.z ) ); } inline float3x2 atan2( float3x2 y, float3x2 x ) { return float3x2( atan2( y.x, x.x ), atan2( y.y, x.y ), atan2( y.z, x.z ) ); } inline float3x2 ceil( float3x2 m ) { return float3x2( ceil( m.x ), ceil( m.y ), ceil( m.z ) ); } inline float3x2 clamp( float3x2 m, float3x2 min, float3x2 max ) { return float3x2( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ), clamp( m.z, min.z, max.z ) ); } inline float3x2 cos( float3x2 m ) { return float3x2( cos( m.x ), cos( m.y ), cos( m.z ) ); } inline float3x2 cosh( float3x2 m ) { return float3x2( cosh( m.x ), cosh( m.y ), cosh( m.z ) ); } inline float3x2 degrees( float3x2 m ) { return float3x2( degrees( m.x ), degrees( m.y ), degrees( m.z ) ); } inline float3x2 exp( float3x2 m ) { return float3x2( exp( m.x ), exp( m.y ), exp( m.z ) ); } inline float3x2 exp2( float3x2 m ) { return float3x2( exp2( m.x ), exp2( m.y ), exp2( m.z ) ); } inline float3x2 floor( float3x2 m ) { return float3x2( floor( m.x ), floor( m.y ), floor( m.z ) ); } inline float3x2 fmod( float3x2 a, float3x2 b ) { return float3x2( fmod( a.x, b.x ), fmod( a.y, b.y ), fmod( a.z, b.z ) ); } inline float3x2 frac( float3x2 m ) { return float3x2( frac( m.x ), frac( m.y ), frac( m.z ) ); } inline float3x2 lerp( float3x2 a, float3x2 b, float s ) { return float3x2( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ), lerp( a.z, b.z, s ) ); } inline float3x2 log( float3x2 m ) { return float3x2( log( m.x ), log( m.y ), log( m.z ) ); } inline float3x2 log2( float3x2 m ) { return float3x2( log2( m.x ), log2( m.y ), log2( m.z ) ); } inline float3x2 log10( float3x2 m ) { return float3x2( log10( m.x ), log10( m.y ), log10( m.z ) ); } inline float3x2 mad( float3x2 a, float3x2 b, float3x2 c ) { return a * b + c; } inline float3x2 max( float3x2 a, float3x2 b ) { return float3x2( max( a.x, b.x ), max( a.y, b.y ), max( a.z, b.z ) ); } inline float3x2 min( float3x2 a, float3x2 b ) { return float3x2( min( a.x, b.x ), min( a.y, b.y ), min( a.z, b.z ) ); } inline float3x2 pow( float3x2 a, float3x2 b ) { return float3x2( pow( a.x, b.x ), pow( a.y, b.y ), pow( a.z, b.z ) ); } inline float3x2 radians( float3x2 m ) { return float3x2( radians( m.x ), radians( m.y ), radians( m.z ) ); } inline float3x2 rcp( float3x2 m ) { return float3x2( rcp( m.x ), rcp( m.y ), rcp( m.z ) ); } inline float3x2 round( float3x2 m ) { return float3x2( round( m.x ), round( m.y ), round( m.z ) ); } inline float3x2 rsqrt( float3x2 m ) { return float3x2( rsqrt( m.x ), rsqrt( m.y ), rsqrt( m.z ) ); } inline float3x2 saturate( float3x2 m ) { return float3x2( saturate( m.x ), saturate( m.y ), saturate( m.z ) ); } inline float3x2 sign( float3x2 m ) { return float3x2( sign( m.x ), sign( m.y ), sign( m.z ) ); } inline float3x2 sin( float3x2 m ) { return float3x2( sin( m.x ), sin( m.y ), sin( m.z ) ); } inline float3x2 sinh( float3x2 m ) { return float3x2( sinh( m.x ), sinh( m.y ), sinh( m.z ) ); } inline float3x2 smoothstep( float3x2 min, float3x2 max, float3x2 m ) { return float3x2( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ), smoothstep( min.z, max.z, m.z ) ); } inline float3x2 smootherstep( float3x2 min, float3x2 max, float3x2 m ) { return float3x2( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ), smootherstep( min.z, max.z, m.z ) ); } inline float3x2 sqrt( float3x2 m ) { return float3x2( sqrt( m.x ), sqrt( m.y ), sqrt( m.z ) ); } inline float3x2 step( float3x2 a, float3x2 b ) { return float3x2( step( a.x, b.x ), step( a.y, b.y ), step( a.z, b.z ) ); } inline float3x2 tan( float3x2 m ) { return float3x2( tan( m.x ), tan( m.y ), tan( m.z ) ); } inline float3x2 tanh( float3x2 m ) { return float3x2( tanh( m.x ), tanh( m.y ), tanh( m.z ) ); } inline float3x2 trunc( float3x2 m ) { return float3x2( trunc( m.x ), trunc( m.y ), trunc( m.z ) ); } struct float3x3 { // rows float3 x; float3 y; float3 z; // constructors inline float3x3() { } inline float3x3( float f ) : x( float3( f ) ), y( float3( f ) ), z( float3( f ) ) { } inline explicit float3x3( float m[9] ) : x( m[0], m[1], m[2] ), y( m[3], m[4], m[5] ), z( m[6], m[7], m[8] ) { } inline float3x3( float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22 ) : x( m00, m01, m02 ), y( m10, m11, m12 ), z( m20, m21, m22 ) { } inline float3x3( float3 x_, float3 y_, float3 z_ ) : x( x_ ), y( y_ ), z( z_ ) { } // conversions inline float3x3( float3x3_t m ) : x( m.x ), y( m.y ), z( m.z ) { } inline operator float3x3_t() const { float3x3_t m = { x, y, z }; return m; }; // indexing inline float3 operator[]( int row ) { return ( (float3*) this )[ row ]; } // constants static inline float3x3 identity() { return float3x3( float3( 1.0f, 0.0f, 0.0f ), float3( 0.0f, 1.0f, 0.0f ), float3( 0.0f, 0.0f, 1.0f ) ); } }; // operators inline float3x3& operator+=( float3x3& a, float3x3 b ) { a.x += b.x; a.y += b.y; a.z += b.z; return a; }; inline float3x3& operator-=( float3x3& a, float3x3 b ) { a.x -= b.x; a.y -= b.y; a.z -= b.z; return a; }; inline float3x3& operator*=( float3x3& a, float3x3 b ) { a.x *= b.x; a.y *= b.y; a.z *= b.z; return a; }; inline float3x3& operator/=( float3x3& a, float3x3 b ) { a.x /= b.x; a.y /= b.y; a.z /= b.z; return a; }; inline float3x3& operator+=( float3x3& a, float s ) { a.x += s; a.y += s; a.z += s; return a; }; inline float3x3& operator-=( float3x3& a, float s ) { a.x -= s; a.y -= s; a.z -= s; return a; }; inline float3x3& operator*=( float3x3& a, float s ) { a.x *= s; a.y *= s; a.z *= s; return a; }; inline float3x3& operator/=( float3x3& a, float s ) { a.x /= s; a.y /= s; a.z /= s; return a; }; inline float3x3 operator+( float3x3 a, float3x3 b ) { return float3x3( a.x + b.x, a.y + b.y, a.z + b.z ); } inline float3x3 operator-( float3x3 a, float3x3 b ) { return float3x3( a.x - b.x, a.y - b.y, a.z - b.z ); } inline float3x3 operator*( float3x3 a, float3x3 b ) { return float3x3( a.x * b.x, a.y * b.y, a.z * b.z ); } inline float3x3 operator/( float3x3 a, float3x3 b ) { return float3x3( a.x / b.x, a.y / b.y, a.z / b.z ); } inline float3x3 operator+( float3x3 a, float b ) { return float3x3( a.x + b, a.y + b, a.z + b ); } inline float3x3 operator-( float3x3 a, float b ) { return float3x3( a.x - b, a.y - b, a.z - b ); } inline float3x3 operator*( float3x3 a, float b ) { return float3x3( a.x * b, a.y * b, a.z * b ); } inline float3x3 operator/( float3x3 a, float b ) { return float3x3( a.x / b, a.y / b, a.z / b ); } inline float3x3 operator+( float a, float3x3 b ) { return float3x3( a + b.x, a + b.y, a + b.z ); } inline float3x3 operator-( float a, float3x3 b ) { return float3x3( a - b.x, a - b.y, a - b.z ); } inline float3x3 operator*( float a, float3x3 b ) { return float3x3( a * b.x, a * b.y, a * b.z ); } inline float3x3 operator/( float a, float3x3 b ) { return float3x3( a / b.x, a / b.y, a / b.z ); } // functions inline float3x3 abs( float3x3 m ) { return float3x3( abs( m.x ), abs( m.y ), abs( m.z ) ); } inline float3x3 acos( float3x3 m ) { return float3x3( acos( m.x ), acos( m.y ), acos( m.z ) ); } inline bool all( float3x3 m ) { return all( m.x ) && all( m.y ) && all( m.z ); } inline bool any( float3x3 m ) { return any( m.x ) || any( m.y ) || any( m.z ); } inline float3x3 asin( float3x3 m ) { return float3x3( asin( m.x ), asin( m.y ), asin( m.z ) ); } inline float3x3 atan( float3x3 m ) { return float3x3( atan( m.x ), atan( m.y ), atan( m.z ) ); } inline float3x3 atan2( float3x3 y, float3x3 x ) { return float3x3( atan2( y.x, x.x ), atan2( y.y, x.y ), atan2( y.z, x.z ) ); } inline float3x3 ceil( float3x3 m ) { return float3x3( ceil( m.x ), ceil( m.y ), ceil( m.z ) ); } inline float3x3 clamp( float3x3 m, float3x3 min, float3x3 max ) { return float3x3( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ), clamp( m.z, min.z, max.z ) ); } inline float3x3 cos( float3x3 m ) { return float3x3( cos( m.x ), cos( m.y ), cos( m.z ) ); } inline float3x3 cosh( float3x3 m ) { return float3x3( cosh( m.x ), cosh( m.y ), cosh( m.z ) ); } inline float3x3 degrees( float3x3 m ) { return float3x3( degrees( m.x ), degrees( m.y ), degrees( m.z ) ); } inline float3x3 exp( float3x3 m ) { return float3x3( exp( m.x ), exp( m.y ), exp( m.z ) ); } inline float3x3 exp2( float3x3 m ) { return float3x3( exp2( m.x ), exp2( m.y ), exp2( m.z ) ); } inline float3x3 floor( float3x3 m ) { return float3x3( floor( m.x ), floor( m.y ), floor( m.z ) ); } inline float3x3 fmod( float3x3 a, float3x3 b ) { return float3x3( fmod( a.x, b.x ), fmod( a.y, b.y ), fmod( a.z, b.z ) ); } inline float3x3 frac( float3x3 m ) { return float3x3( frac( m.x ), frac( m.y ), frac( m.z ) ); } inline float3x3 lerp( float3x3 a, float3x3 b, float s ) { return float3x3( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ), lerp( a.z, b.z, s ) ); } inline float3x3 log( float3x3 m ) { return float3x3( log( m.x ), log( m.y ), log( m.z ) ); } inline float3x3 log2( float3x3 m ) { return float3x3( log2( m.x ), log2( m.y ), log2( m.z ) ); } inline float3x3 log10( float3x3 m ) { return float3x3( log10( m.x ), log10( m.y ), log10( m.z ) ); } inline float3x3 mad( float3x3 a, float3x3 b, float3x3 c ) { return a * b + c; } inline float3x3 max( float3x3 a, float3x3 b ) { return float3x3( max( a.x, b.x ), max( a.y, b.y ), max( a.z, b.z ) ); } inline float3x3 min( float3x3 a, float3x3 b ) { return float3x3( min( a.x, b.x ), min( a.y, b.y ), min( a.z, b.z ) ); } inline float3x3 pow( float3x3 a, float3x3 b ) { return float3x3( pow( a.x, b.x ), pow( a.y, b.y ), pow( a.z, b.z ) ); } inline float3x3 radians( float3x3 m ) { return float3x3( radians( m.x ), radians( m.y ), radians( m.z ) ); } inline float3x3 rcp( float3x3 m ) { return float3x3( rcp( m.x ), rcp( m.y ), rcp( m.z ) ); } inline float3x3 round( float3x3 m ) { return float3x3( round( m.x ), round( m.y ), round( m.z ) ); } inline float3x3 rsqrt( float3x3 m ) { return float3x3( rsqrt( m.x ), rsqrt( m.y ), rsqrt( m.z ) ); } inline float3x3 saturate( float3x3 m ) { return float3x3( saturate( m.x ), saturate( m.y ), saturate( m.z ) ); } inline float3x3 sign( float3x3 m ) { return float3x3( sign( m.x ), sign( m.y ), sign( m.z ) ); } inline float3x3 sin( float3x3 m ) { return float3x3( sin( m.x ), sin( m.y ), sin( m.z ) ); } inline float3x3 sinh( float3x3 m ) { return float3x3( sinh( m.x ), sinh( m.y ), sinh( m.z ) ); } inline float3x3 smoothstep( float3x3 min, float3x3 max, float3x3 m ) { return float3x3( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ), smoothstep( min.z, max.z, m.z ) ); } inline float3x3 smootherstep( float3x3 min, float3x3 max, float3x3 m ) { return float3x3( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ), smootherstep( min.z, max.z, m.z ) ); } inline float3x3 sqrt( float3x3 m ) { return float3x3( sqrt( m.x ), sqrt( m.y ), sqrt( m.z ) ); } inline float3x3 step( float3x3 a, float3x3 b ) { return float3x3( step( a.x, b.x ), step( a.y, b.y ), step( a.z, b.z ) ); } inline float3x3 tan( float3x3 m ) { return float3x3( tan( m.x ), tan( m.y ), tan( m.z ) ); } inline float3x3 tanh( float3x3 m ) { return float3x3( tanh( m.x ), tanh( m.y ), tanh( m.z ) ); } inline float3x3 trunc( float3x3 m ) { return float3x3( trunc( m.x ), trunc( m.y ), trunc( m.z ) ); } struct float2x4 { // rows float4 x; float4 y; // constructors inline float2x4() { } inline float2x4( float f ) : x( float4( f ) ), y( float4( f ) ) { } inline explicit float2x4( float m[8] ) : x( m[0], m[1], m[2], m[3] ), y( m[4], m[5], m[6], m[7] ) { } inline float2x4( float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13 ) : x( m00, m01, m02, m03 ), y( m10, m11, m12, m13 ) { } inline float2x4( float4 x_, float4 y_ ) : x( x_ ), y( y_ ) { } // conversions inline float2x4( float2x4_t m ) : x( m.x ), y( m.y ) { } inline operator float2x4_t() const { float2x4_t m = { x, y }; return m; }; // indexing inline float4 operator[]( int row ) { return ( (float4*) this )[ row ]; } }; // operators inline float2x4& operator+=( float2x4& a, float2x4 b ) { a.x += b.x; a.y += b.y; return a; }; inline float2x4& operator-=( float2x4& a, float2x4 b ) { a.x -= b.x; a.y -= b.y; return a; }; inline float2x4& operator*=( float2x4& a, float2x4 b ) { a.x *= b.x; a.y *= b.y; return a; }; inline float2x4& operator/=( float2x4& a, float2x4 b ) { a.x /= b.x; a.y /= b.y; return a; }; inline float2x4& operator+=( float2x4& a, float s ) { a.x += s; a.y += s; return a; }; inline float2x4& operator-=( float2x4& a, float s ) { a.x -= s; a.y -= s; return a; }; inline float2x4& operator*=( float2x4& a, float s ) { a.x *= s; a.y *= s; return a; }; inline float2x4& operator/=( float2x4& a, float s ) { a.x /= s; a.y /= s; return a; }; inline float2x4 operator+( float2x4 a, float2x4 b ) { return float2x4( a.x + b.x, a.y + b.y ); } inline float2x4 operator-( float2x4 a, float2x4 b ) { return float2x4( a.x - b.x, a.y - b.y ); } inline float2x4 operator*( float2x4 a, float2x4 b ) { return float2x4( a.x * b.x, a.y * b.y ); } inline float2x4 operator/( float2x4 a, float2x4 b ) { return float2x4( a.x / b.x, a.y / b.y ); } inline float2x4 operator+( float2x4 a, float b ) { return float2x4( a.x + b, a.y + b ); } inline float2x4 operator-( float2x4 a, float b ) { return float2x4( a.x - b, a.y - b ); } inline float2x4 operator*( float2x4 a, float b ) { return float2x4( a.x * b, a.y * b ); } inline float2x4 operator/( float2x4 a, float b ) { return float2x4( a.x / b, a.y / b ); } inline float2x4 operator+( float a, float2x4 b ) { return float2x4( a + b.x, a + b.y ); } inline float2x4 operator-( float a, float2x4 b ) { return float2x4( a - b.x, a - b.y ); } inline float2x4 operator*( float a, float2x4 b ) { return float2x4( a * b.x, a * b.y ); } inline float2x4 operator/( float a, float2x4 b ) { return float2x4( a / b.x, a / b.y ); } // functions inline float2x4 abs( float2x4 m ) { return float2x4( abs( m.x ), abs( m.y ) ); } inline float2x4 acos( float2x4 m ) { return float2x4( acos( m.x ), acos( m.y ) ); } inline bool all( float2x4 m ) { return all( m.x ) && all( m.y ); } inline bool any( float2x4 m ) { return any( m.x ) || any( m.y ); } inline float2x4 asin( float2x4 m ) { return float2x4( asin( m.x ), asin( m.y ) ); } inline float2x4 atan( float2x4 m ) { return float2x4( atan( m.x ), atan( m.y ) ); } inline float2x4 atan2( float2x4 y, float2x4 x ) { return float2x4( atan2( y.x, x.x ), atan2( y.y, x.y ) ); } inline float2x4 ceil( float2x4 m ) { return float2x4( ceil( m.x ), ceil( m.y ) ); } inline float2x4 clamp( float2x4 m, float2x4 min, float2x4 max ) { return float2x4( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ) ); } inline float2x4 cos( float2x4 m ) { return float2x4( cos( m.x ), cos( m.y ) ); } inline float2x4 cosh( float2x4 m ) { return float2x4( cosh( m.x ), cosh( m.y ) ); } inline float2x4 degrees( float2x4 m ) { return float2x4( degrees( m.x ), degrees( m.y ) ); } inline float2x4 exp( float2x4 m ) { return float2x4( exp( m.x ), exp( m.y ) ); } inline float2x4 exp2( float2x4 m ) { return float2x4( exp2( m.x ), exp2( m.y ) ); } inline float2x4 floor( float2x4 m ) { return float2x4( floor( m.x ), floor( m.y ) ); } inline float2x4 fmod( float2x4 a, float2x4 b ) { return float2x4( fmod( a.x, b.x ), fmod( a.y, b.y ) ); } inline float2x4 frac( float2x4 m ) { return float2x4( frac( m.x ), frac( m.y ) ); } inline float2x4 lerp( float2x4 a, float2x4 b, float s ) { return float2x4( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ) ); } inline float2x4 log( float2x4 m ) { return float2x4( log( m.x ), log( m.y ) ); } inline float2x4 log2( float2x4 m ) { return float2x4( log2( m.x ), log2( m.y ) ); } inline float2x4 log10( float2x4 m ) { return float2x4( log10( m.x ), log10( m.y ) ); } inline float2x4 mad( float2x4 a, float2x4 b, float2x4 c ) { return a * b + c; } inline float2x4 max( float2x4 a, float2x4 b ) { return float2x4( max( a.x, b.x ), max( a.y, b.y ) ); } inline float2x4 min( float2x4 a, float2x4 b ) { return float2x4( min( a.x, b.x ), min( a.y, b.y ) ); } inline float2x4 pow( float2x4 a, float2x4 b ) { return float2x4( pow( a.x, b.x ), pow( a.y, b.y ) ); } inline float2x4 radians( float2x4 m ) { return float2x4( radians( m.x ), radians( m.y ) ); } inline float2x4 rcp( float2x4 m ) { return float2x4( rcp( m.x ), rcp( m.y ) ); } inline float2x4 round( float2x4 m ) { return float2x4( round( m.x ), round( m.y ) ); } inline float2x4 rsqrt( float2x4 m ) { return float2x4( rsqrt( m.x ), rsqrt( m.y ) ); } inline float2x4 saturate( float2x4 m ) { return float2x4( saturate( m.x ), saturate( m.y ) ); } inline float2x4 sign( float2x4 m ) { return float2x4( sign( m.x ), sign( m.y ) ); } inline float2x4 sin( float2x4 m ) { return float2x4( sin( m.x ), sin( m.y ) ); } inline float2x4 sinh( float2x4 m ) { return float2x4( sinh( m.x ), sinh( m.y ) ); } inline float2x4 smoothstep( float2x4 min, float2x4 max, float2x4 m ) { return float2x4( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ) ); } inline float2x4 smootherstep( float2x4 min, float2x4 max, float2x4 m ) { return float2x4( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ) ); } inline float2x4 sqrt( float2x4 m ) { return float2x4( sqrt( m.x ), sqrt( m.y ) ); } inline float2x4 step( float2x4 a, float2x4 b ) { return float2x4( step( a.x, b.x ), step( a.y, b.y ) ); } inline float2x4 tan( float2x4 m ) { return float2x4( tan( m.x ), tan( m.y ) ); } inline float2x4 tanh( float2x4 m ) { return float2x4( tanh( m.x ), tanh( m.y ) ); } inline float2x4 trunc( float2x4 m ) { return float2x4( trunc( m.x ), trunc( m.y ) ); } struct float3x4 { // rows float4 x; float4 y; float4 z; // constructors inline float3x4() { } inline float3x4( float f ) : x( float4( f ) ), y( float4( f ) ), z( float4( f ) ) { } inline explicit float3x4( float m[12] ) : x( m[0], m[1], m[2], m[3] ), y( m[4], m[5], m[6], m[7] ), z( m[8], m[9], m[10], m[11] ) { } inline float3x4( float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23 ) : x( m00, m01, m02, m03 ), y( m10, m11, m12, m13 ), z( m20, m21, m22, m23 ) { } inline float3x4( float4 x_, float4 y_, float4 z_ ) : x( x_ ), y( y_ ), z( z_ ) { } // conversions inline float3x4( float3x4_t m ) : x( m.x ), y( m.y ), z( m.z ) { } inline operator float3x4_t() const { float3x4_t m = { x, y, z }; return m; }; // indexing inline float4 operator[]( int row ) { return ( (float4*) this )[ row ]; } }; // operators inline float3x4& operator+=( float3x4& a, float3x4 b ) { a.x += b.x; a.y += b.y; a.z += b.z; return a; }; inline float3x4& operator-=( float3x4& a, float3x4 b ) { a.x -= b.x; a.y -= b.y; a.z -= b.z; return a; }; inline float3x4& operator*=( float3x4& a, float3x4 b ) { a.x *= b.x; a.y *= b.y; a.z *= b.z; return a; }; inline float3x4& operator/=( float3x4& a, float3x4 b ) { a.x /= b.x; a.y /= b.y; a.z /= b.z; return a; }; inline float3x4& operator+=( float3x4& a, float s ) { a.x += s; a.y += s; a.z += s; return a; }; inline float3x4& operator-=( float3x4& a, float s ) { a.x -= s; a.y -= s; a.z -= s; return a; }; inline float3x4& operator*=( float3x4& a, float s ) { a.x *= s; a.y *= s; a.z *= s; return a; }; inline float3x4& operator/=( float3x4& a, float s ) { a.x /= s; a.y /= s; a.z /= s; return a; }; inline float3x4 operator+( float3x4 a, float3x4 b ) { return float3x4( a.x + b.x, a.y + b.y, a.z + b.z ); } inline float3x4 operator-( float3x4 a, float3x4 b ) { return float3x4( a.x - b.x, a.y - b.y, a.z - b.z ); } inline float3x4 operator*( float3x4 a, float3x4 b ) { return float3x4( a.x * b.x, a.y * b.y, a.z * b.z ); } inline float3x4 operator/( float3x4 a, float3x4 b ) { return float3x4( a.x / b.x, a.y / b.y, a.z / b.z ); } inline float3x4 operator+( float3x4 a, float b ) { return float3x4( a.x + b, a.y + b, a.z + b ); } inline float3x4 operator-( float3x4 a, float b ) { return float3x4( a.x - b, a.y - b, a.z - b ); } inline float3x4 operator*( float3x4 a, float b ) { return float3x4( a.x * b, a.y * b, a.z * b ); } inline float3x4 operator/( float3x4 a, float b ) { return float3x4( a.x / b, a.y / b, a.z / b ); } inline float3x4 operator+( float a, float3x4 b ) { return float3x4( a + b.x, a + b.y, a + b.z ); } inline float3x4 operator-( float a, float3x4 b ) { return float3x4( a - b.x, a - b.y, a - b.z ); } inline float3x4 operator*( float a, float3x4 b ) { return float3x4( a * b.x, a * b.y, a * b.z ); } inline float3x4 operator/( float a, float3x4 b ) { return float3x4( a / b.x, a / b.y, a / b.z ); } // functions inline float3x4 abs( float3x4 m ) { return float3x4( abs( m.x ), abs( m.y ), abs( m.z ) ); } inline float3x4 acos( float3x4 m ) { return float3x4( acos( m.x ), acos( m.y ), acos( m.z ) ); } inline bool all( float3x4 m ) { return all( m.x ) && all( m.y ) && all( m.z ); } inline bool any( float3x4 m ) { return any( m.x ) || any( m.y ) || any( m.z ); } inline float3x4 asin( float3x4 m ) { return float3x4( asin( m.x ), asin( m.y ), asin( m.z ) ); } inline float3x4 atan( float3x4 m ) { return float3x4( atan( m.x ), atan( m.y ), atan( m.z ) ); } inline float3x4 atan2( float3x4 y, float3x4 x ) { return float3x4( atan2( y.x, x.x ), atan2( y.y, x.y ), atan2( y.z, x.z ) ); } inline float3x4 ceil( float3x4 m ) { return float3x4( ceil( m.x ), ceil( m.y ), ceil( m.z ) ); } inline float3x4 clamp( float3x4 m, float3x4 min, float3x4 max ) { return float3x4( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ), clamp( m.z, min.z, max.z ) ); } inline float3x4 cos( float3x4 m ) { return float3x4( cos( m.x ), cos( m.y ), cos( m.z ) ); } inline float3x4 cosh( float3x4 m ) { return float3x4( cosh( m.x ), cosh( m.y ), cosh( m.z ) ); } inline float3x4 degrees( float3x4 m ) { return float3x4( degrees( m.x ), degrees( m.y ), degrees( m.z ) ); } inline float3x4 exp( float3x4 m ) { return float3x4( exp( m.x ), exp( m.y ), exp( m.z ) ); } inline float3x4 exp2( float3x4 m ) { return float3x4( exp2( m.x ), exp2( m.y ), exp2( m.z ) ); } inline float3x4 floor( float3x4 m ) { return float3x4( floor( m.x ), floor( m.y ), floor( m.z ) ); } inline float3x4 fmod( float3x4 a, float3x4 b ) { return float3x4( fmod( a.x, b.x ), fmod( a.y, b.y ), fmod( a.z, b.z ) ); } inline float3x4 frac( float3x4 m ) { return float3x4( frac( m.x ), frac( m.y ), frac( m.z ) ); } inline float3x4 lerp( float3x4 a, float3x4 b, float s ) { return float3x4( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ), lerp( a.z, b.z, s ) ); } inline float3x4 log( float3x4 m ) { return float3x4( log( m.x ), log( m.y ), log( m.z ) ); } inline float3x4 log2( float3x4 m ) { return float3x4( log2( m.x ), log2( m.y ), log2( m.z ) ); } inline float3x4 log10( float3x4 m ) { return float3x4( log10( m.x ), log10( m.y ), log10( m.z ) ); } inline float3x4 mad( float3x4 a, float3x4 b, float3x4 c ) { return a * b + c; } inline float3x4 max( float3x4 a, float3x4 b ) { return float3x4( max( a.x, b.x ), max( a.y, b.y ), max( a.z, b.z ) ); } inline float3x4 min( float3x4 a, float3x4 b ) { return float3x4( min( a.x, b.x ), min( a.y, b.y ), min( a.z, b.z ) ); } inline float3x4 pow( float3x4 a, float3x4 b ) { return float3x4( pow( a.x, b.x ), pow( a.y, b.y ), pow( a.z, b.z ) ); } inline float3x4 radians( float3x4 m ) { return float3x4( radians( m.x ), radians( m.y ), radians( m.z ) ); } inline float3x4 rcp( float3x4 m ) { return float3x4( rcp( m.x ), rcp( m.y ), rcp( m.z ) ); } inline float3x4 round( float3x4 m ) { return float3x4( round( m.x ), round( m.y ), round( m.z ) ); } inline float3x4 rsqrt( float3x4 m ) { return float3x4( rsqrt( m.x ), rsqrt( m.y ), rsqrt( m.z ) ); } inline float3x4 saturate( float3x4 m ) { return float3x4( saturate( m.x ), saturate( m.y ), saturate( m.z ) ); } inline float3x4 sign( float3x4 m ) { return float3x4( sign( m.x ), sign( m.y ), sign( m.z ) ); } inline float3x4 sin( float3x4 m ) { return float3x4( sin( m.x ), sin( m.y ), sin( m.z ) ); } inline float3x4 sinh( float3x4 m ) { return float3x4( sinh( m.x ), sinh( m.y ), sinh( m.z ) ); } inline float3x4 smoothstep( float3x4 min, float3x4 max, float3x4 m ) { return float3x4( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ), smoothstep( min.z, max.z, m.z ) ); } inline float3x4 smootherstep( float3x4 min, float3x4 max, float3x4 m ) { return float3x4( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ), smootherstep( min.z, max.z, m.z ) ); } inline float3x4 sqrt( float3x4 m ) { return float3x4( sqrt( m.x ), sqrt( m.y ), sqrt( m.z ) ); } inline float3x4 step( float3x4 a, float3x4 b ) { return float3x4( step( a.x, b.x ), step( a.y, b.y ), step( a.z, b.z ) ); } inline float3x4 tan( float3x4 m ) { return float3x4( tan( m.x ), tan( m.y ), tan( m.z ) ); } inline float3x4 tanh( float3x4 m ) { return float3x4( tanh( m.x ), tanh( m.y ), tanh( m.z ) ); } inline float3x4 trunc( float3x4 m ) { return float3x4( trunc( m.x ), trunc( m.y ), trunc( m.z ) ); } struct float4x2 { // rows float2 x; float2 y; float2 z; float2 w; // constructors inline float4x2() { } inline float4x2( float f ) : x( f ), y( f ), z( f ), w( f ) { } inline explicit float4x2( float m[8] ) : x( m[0], m[1] ), y( m[2], m[3] ), z( m[4], m[5] ), w( m[6], m[7] ) { } inline float4x2( float m00, float m01, float m10, float m11, float m20, float m21, float m30, float m31) : x( m00, m01 ), y( m10, m11 ), z( m20, m21 ), w( m30, m31 ) { } inline float4x2( float2 x_, float2 y_, float2 z_, float2 w_ ) : x( x_ ), y( y_ ), z( z_ ), w( w_ ) { } // conversions inline float4x2( float4x2_t m ) : x( m.x ), y( m.y ), z( m.z ), w( m.w ) { } inline operator float4x2_t() const { float4x2_t m = { x, y, z, w }; return m; }; // indexing inline float2 operator[]( int row ) { return ( (float2*) this )[ row ]; } }; // operators inline float4x2& operator+=( float4x2& a, float4x2 b ) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; return a; }; inline float4x2& operator-=( float4x2& a, float4x2 b ) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; return a; }; inline float4x2& operator*=( float4x2& a, float4x2 b ) { a.x *= b.x; a.y *= b.y; a.z *= b.z; a.w *= b.w; return a; }; inline float4x2& operator/=( float4x2& a, float4x2 b ) { a.x /= b.x; a.y /= b.y; a.z /= b.z; a.w /= b.w; return a; }; inline float4x2& operator+=( float4x2& a, float s ) { a.x += s; a.y += s; a.z += s; a.w += s; return a; }; inline float4x2& operator-=( float4x2& a, float s ) { a.x -= s; a.y -= s; a.z -= s; a.w -= s; return a; }; inline float4x2& operator*=( float4x2& a, float s ) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; return a; }; inline float4x2& operator/=( float4x2& a, float s ) { a.x /= s; a.y /= s; a.z /= s; a.w /= s; return a; }; inline float4x2 operator+( float4x2 a, float4x2 b ) { return float4x2( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w ); } inline float4x2 operator-( float4x2 a, float4x2 b ) { return float4x2( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w ); } inline float4x2 operator*( float4x2 a, float4x2 b ) { return float4x2( a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w ); } inline float4x2 operator/( float4x2 a, float4x2 b ) { return float4x2( a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w ); } inline float4x2 operator+( float4x2 a, float b ) { return float4x2( a.x + b, a.y + b, a.z + b, a.w + b ); } inline float4x2 operator-( float4x2 a, float b ) { return float4x2( a.x - b, a.y - b, a.z - b, a.w - b ); } inline float4x2 operator*( float4x2 a, float b ) { return float4x2( a.x * b, a.y * b, a.z * b, a.w * b ); } inline float4x2 operator/( float4x2 a, float b ) { return float4x2( a.x / b, a.y / b, a.z / b, a.w / b ); } inline float4x2 operator+( float a, float4x2 b ) { return float4x2( a + b.x, a + b.y, a + b.z, a + b.w ); } inline float4x2 operator-( float a, float4x2 b ) { return float4x2( a - b.x, a - b.y, a - b.z, a - b.w ); } inline float4x2 operator*( float a, float4x2 b ) { return float4x2( a * b.x, a * b.y, a * b.z, a * b.w ); } inline float4x2 operator/( float a, float4x2 b ) { return float4x2( a / b.x, a / b.y, a / b.z, a / b.w ); } // functions inline float4x2 abs( float4x2 m ) { return float4x2( abs( m.x ), abs( m.y ), abs( m.z ), abs( m.w ) ); } inline float4x2 acos( float4x2 m ) { return float4x2( acos( m.x ), acos( m.y ), acos( m.z ), acos( m.w ) ); } inline bool all( float4x2 m ) { return all( m.x ) && all( m.y ) && all( m.z ) && all( m.w ); } inline bool any( float4x2 m ) { return any( m.x ) || any( m.y ) || any( m.z ) || any( m.w ); } inline float4x2 asin( float4x2 m ) { return float4x2( asin( m.x ), asin( m.y ), asin( m.z ), asin( m.w ) ); } inline float4x2 atan( float4x2 m ) { return float4x2( atan( m.x ), atan( m.y ), atan( m.z ), atan( m.w ) ); } inline float4x2 atan2( float4x2 y, float4x2 x ) { return float4x2( atan2( y.x, x.x ), atan2( y.y, x.y ), atan2( y.z, x.z ), atan2( y.w, x.w ) ); } inline float4x2 ceil( float4x2 m ) { return float4x2( ceil( m.x ), ceil( m.y ), ceil( m.z ), ceil( m.w ) ); } inline float4x2 clamp( float4x2 m, float4x2 min, float4x2 max ) { return float4x2( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ), clamp( m.z, min.z, max.z ), clamp( m.w, min.w, max.w ) ); } inline float4x2 cos( float4x2 m ) { return float4x2( cos( m.x ), cos( m.y ), cos( m.z ), cos( m.w ) ); } inline float4x2 cosh( float4x2 m ) { return float4x2( cosh( m.x ), cosh( m.y ), cosh( m.z ), cosh( m.w ) ); } inline float4x2 degrees( float4x2 m ) { return float4x2( degrees( m.x ), degrees( m.y ), degrees( m.z ), degrees( m.w ) ); } inline float4x2 exp( float4x2 m ) { return float4x2( exp( m.x ), exp( m.y ), exp( m.z ), exp( m.w ) ); } inline float4x2 exp2( float4x2 m ) { return float4x2( exp2( m.x ), exp2( m.y ), exp2( m.z ), exp2( m.w ) ); } inline float4x2 floor( float4x2 m ) { return float4x2( floor( m.x ), floor( m.y ), floor( m.z ), floor( m.w ) ); } inline float4x2 fmod( float4x2 a, float4x2 b ) { return float4x2( fmod( a.x, b.x ), fmod( a.y, b.y ), fmod( a.z, b.z ), fmod( a.w, b.w ) ); } inline float4x2 frac( float4x2 m ) { return float4x2( frac( m.x ), frac( m.y ), frac( m.z ), frac( m.w ) ); } inline float4x2 lerp( float4x2 a, float4x2 b, float s ) { return float4x2( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ), lerp( a.z, b.z, s ), lerp( a.w, b.w, s ) ); } inline float4x2 log( float4x2 m ) { return float4x2( log( m.x ), log( m.y ), log( m.z ), log( m.w ) ); } inline float4x2 log2( float4x2 m ) { return float4x2( log2( m.x ), log2( m.y ), log2( m.z ), log2( m.w ) ); } inline float4x2 log10( float4x2 m ) { return float4x2( log10( m.x ), log10( m.y ), log10( m.z ), log10( m.w ) ); } inline float4x2 mad( float4x2 a, float4x2 b, float4x2 c ) { return a * b + c; } inline float4x2 max( float4x2 a, float4x2 b ) { return float4x2( max( a.x, b.x ), max( a.y, b.y ), max( a.z, b.z ), max( a.w, b.w ) ); } inline float4x2 min( float4x2 a, float4x2 b ) { return float4x2( min( a.x, b.x ), min( a.y, b.y ), min( a.z, b.z ), min( a.w, b.w ) ); } inline float4x2 pow( float4x2 a, float4x2 b ) { return float4x2( pow( a.x, b.x ), pow( a.y, b.y ), pow( a.z, b.z ), pow( a.w, b.w ) ); } inline float4x2 radians( float4x2 m ) { return float4x2( radians( m.x ), radians( m.y ), radians( m.z ), radians( m.w ) ); } inline float4x2 rcp( float4x2 m ) { return float4x2( rcp( m.x ), rcp( m.y ), rcp( m.z ), rcp( m.w ) ); } inline float4x2 round( float4x2 m ) { return float4x2( round( m.x ), round( m.y ), round( m.z ), round( m.w ) ); } inline float4x2 rsqrt( float4x2 m ) { return float4x2( rsqrt( m.x ), rsqrt( m.y ), rsqrt( m.z ), rsqrt( m.w ) ); } inline float4x2 saturate( float4x2 m ) { return float4x2( saturate( m.x ), saturate( m.y ), saturate( m.z ), saturate( m.w ) ); } inline float4x2 sign( float4x2 m ) { return float4x2( sign( m.x ), sign( m.y ), sign( m.z ), sign( m.w ) ); } inline float4x2 sin( float4x2 m ) { return float4x2( sin( m.x ), sin( m.y ), sin( m.z ), sin( m.w ) ); } inline float4x2 sinh( float4x2 m ) { return float4x2( sinh( m.x ), sinh( m.y ), sinh( m.z ), sinh( m.w ) ); } inline float4x2 smoothstep( float4x2 min, float4x2 max, float4x2 m ) { return float4x2( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ), smoothstep( min.z, max.z, m.z ), smoothstep( min.w, max.w, m.w ) ); } inline float4x2 smootherstep( float4x2 min, float4x2 max, float4x2 m ) { return float4x2( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ), smootherstep( min.z, max.z, m.z ), smootherstep( min.w, max.w, m.w ) ); } inline float4x2 sqrt( float4x2 m ) { return float4x2( sqrt( m.x ), sqrt( m.y ), sqrt( m.z ), sqrt( m.w ) ); } inline float4x2 step( float4x2 a, float4x2 b ) { return float4x2( step( a.x, b.x ), step( a.y, b.y ), step( a.z, b.z ), step( a.w, b.w ) ); } inline float4x2 tan( float4x2 m ) { return float4x2( tan( m.x ), tan( m.y ), tan( m.z ), tan( m.w ) ); } inline float4x2 tanh( float4x2 m ) { return float4x2( tanh( m.x ), tanh( m.y ), tanh( m.z ), tanh( m.w ) ); } inline float4x2 trunc( float4x2 m ) { return float4x2( trunc( m.x ), trunc( m.y ), trunc( m.z ), trunc( m.w ) ); } struct float4x3 { // rows float3 x; float3 y; float3 z; float3 w; // constructors inline float4x3() { } inline float4x3( float f ) : x( f ), y( f ), z( f ), w( f ) { } inline explicit float4x3( float m[12] ) : x( m[0], m[1], m[2] ), y( m[3], m[4], m[5] ), z( m[6], m[7], m[8] ), w( m[9], m[10], m[11] ) { } inline float4x3( float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22, float m30, float m31, float m32 ) : x( m00, m01, m02 ), y( m10, m11, m12 ), z( m20, m21, m22 ), w( m30, m31, m32 ) { } inline float4x3( float3 x_, float3 y_, float3 z_, float3 w_ ) : x( x_ ), y( y_ ), z( z_ ), w( w_ ) { } // conversions inline float4x3( float4x3_t m ) : x( m.x ), y( m.y ), z( m.z ), w( m.w ) { } inline operator float4x3_t() const { float4x3_t m = { x, y, z, w }; return m; }; // indexing inline float3 operator[]( int row ) { return ( (float3*) this )[ row ]; } }; // operators inline float4x3& operator+=( float4x3& a, float4x3 b ) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; return a; }; inline float4x3& operator-=( float4x3& a, float4x3 b ) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; return a; }; inline float4x3& operator*=( float4x3& a, float4x3 b ) { a.x *= b.x; a.y *= b.y; a.z *= b.z; a.w *= b.w; return a; }; inline float4x3& operator/=( float4x3& a, float4x3 b ) { a.x /= b.x; a.y /= b.y; a.z /= b.z; a.w /= b.w; return a; }; inline float4x3& operator+=( float4x3& a, float s ) { a.x += s; a.y += s; a.z += s; a.w += s; return a; }; inline float4x3& operator-=( float4x3& a, float s ) { a.x -= s; a.y -= s; a.z -= s; a.w -= s; return a; }; inline float4x3& operator*=( float4x3& a, float s ) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; return a; }; inline float4x3& operator/=( float4x3& a, float s ) { a.x /= s; a.y /= s; a.z /= s; a.w /= s; return a; }; inline float4x3 operator+( float4x3 a, float4x3 b ) { return float4x3( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w ); } inline float4x3 operator-( float4x3 a, float4x3 b ) { return float4x3( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w ); } inline float4x3 operator*( float4x3 a, float4x3 b ) { return float4x3( a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w ); } inline float4x3 operator/( float4x3 a, float4x3 b ) { return float4x3( a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w ); } inline float4x3 operator+( float4x3 a, float b ) { return float4x3( a.x + b, a.y + b, a.z + b, a.w + b ); } inline float4x3 operator-( float4x3 a, float b ) { return float4x3( a.x - b, a.y - b, a.z - b, a.w - b ); } inline float4x3 operator*( float4x3 a, float b ) { return float4x3( a.x * b, a.y * b, a.z * b, a.w * b ); } inline float4x3 operator/( float4x3 a, float b ) { return float4x3( a.x / b, a.y / b, a.z / b, a.w / b ); } inline float4x3 operator+( float a, float4x3 b ) { return float4x3( a + b.x, a + b.y, a + b.z, a + b.w ); } inline float4x3 operator-( float a, float4x3 b ) { return float4x3( a - b.x, a - b.y, a - b.z, a - b.w ); } inline float4x3 operator*( float a, float4x3 b ) { return float4x3( a * b.x, a * b.y, a * b.z, a * b.w ); } inline float4x3 operator/( float a, float4x3 b ) { return float4x3( a / b.x, a / b.y, a / b.z, a / b.w ); } // functions inline float4x3 abs( float4x3 m ) { return float4x3( abs( m.x ), abs( m.y ), abs( m.z ), abs( m.w ) ); } inline float4x3 acos( float4x3 m ) { return float4x3( acos( m.x ), acos( m.y ), acos( m.z ), acos( m.w ) ); } inline bool all( float4x3 m ) { return all( m.x ) && all( m.y ) && all( m.z ) && all( m.w ); } inline bool any( float4x3 m ) { return any( m.x ) || any( m.y ) || any( m.z ) || any( m.w ); } inline float4x3 asin( float4x3 m ) { return float4x3( asin( m.x ), asin( m.y ), asin( m.z ), asin( m.w ) ); } inline float4x3 atan( float4x3 m ) { return float4x3( atan( m.x ), atan( m.y ), atan( m.z ), atan( m.w ) ); } inline float4x3 atan2( float4x3 y, float4x3 x ) { return float4x3( atan2( y.x, x.x ), atan2( y.y, x.y ), atan2( y.z, x.z ), atan2( y.w, x.w ) ); } inline float4x3 ceil( float4x3 m ) { return float4x3( ceil( m.x ), ceil( m.y ), ceil( m.z ), ceil( m.w ) ); } inline float4x3 clamp( float4x3 m, float4x3 min, float4x3 max ) { return float4x3( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ), clamp( m.z, min.z, max.z ), clamp( m.w, min.w, max.w ) ); } inline float4x3 cos( float4x3 m ) { return float4x3( cos( m.x ), cos( m.y ), cos( m.z ), cos( m.w ) ); } inline float4x3 cosh( float4x3 m ) { return float4x3( cosh( m.x ), cosh( m.y ), cosh( m.z ), cosh( m.w ) ); } inline float4x3 degrees( float4x3 m ) { return float4x3( degrees( m.x ), degrees( m.y ), degrees( m.z ), degrees( m.w ) ); } inline float4x3 exp( float4x3 m ) { return float4x3( exp( m.x ), exp( m.y ), exp( m.z ), exp( m.w ) ); } inline float4x3 exp2( float4x3 m ) { return float4x3( exp2( m.x ), exp2( m.y ), exp2( m.z ), exp2( m.w ) ); } inline float4x3 floor( float4x3 m ) { return float4x3( floor( m.x ), floor( m.y ), floor( m.z ), floor( m.w ) ); } inline float4x3 fmod( float4x3 a, float4x3 b ) { return float4x3( fmod( a.x, b.x ), fmod( a.y, b.y ), fmod( a.z, b.z ), fmod( a.w, b.w ) ); } inline float4x3 frac( float4x3 m ) { return float4x3( frac( m.x ), frac( m.y ), frac( m.z ), frac( m.w ) ); } inline float4x3 lerp( float4x3 a, float4x3 b, float s ) { return float4x3( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ), lerp( a.z, b.z, s ), lerp( a.w, b.w, s ) ); } inline float4x3 log( float4x3 m ) { return float4x3( log( m.x ), log( m.y ), log( m.z ), log( m.w ) ); } inline float4x3 log2( float4x3 m ) { return float4x3( log2( m.x ), log2( m.y ), log2( m.z ), log2( m.w ) ); } inline float4x3 log10( float4x3 m ) { return float4x3( log10( m.x ), log10( m.y ), log10( m.z ), log10( m.w ) ); } inline float4x3 mad( float4x3 a, float4x3 b, float4x3 c ) { return a * b + c; } inline float4x3 max( float4x3 a, float4x3 b ) { return float4x3( max( a.x, b.x ), max( a.y, b.y ), max( a.z, b.z ), max( a.w, b.w ) ); } inline float4x3 min( float4x3 a, float4x3 b ) { return float4x3( min( a.x, b.x ), min( a.y, b.y ), min( a.z, b.z ), min( a.w, b.w ) ); } inline float4x3 pow( float4x3 a, float4x3 b ) { return float4x3( pow( a.x, b.x ), pow( a.y, b.y ), pow( a.z, b.z ), pow( a.w, b.w ) ); } inline float4x3 radians( float4x3 m ) { return float4x3( radians( m.x ), radians( m.y ), radians( m.z ), radians( m.w ) ); } inline float4x3 rcp( float4x3 m ) { return float4x3( rcp( m.x ), rcp( m.y ), rcp( m.z ), rcp( m.w ) ); } inline float4x3 round( float4x3 m ) { return float4x3( round( m.x ), round( m.y ), round( m.z ), round( m.w ) ); } inline float4x3 rsqrt( float4x3 m ) { return float4x3( rsqrt( m.x ), rsqrt( m.y ), rsqrt( m.z ), rsqrt( m.w ) ); } inline float4x3 saturate( float4x3 m ) { return float4x3( saturate( m.x ), saturate( m.y ), saturate( m.z ), saturate( m.w ) ); } inline float4x3 sign( float4x3 m ) { return float4x3( sign( m.x ), sign( m.y ), sign( m.z ), sign( m.w ) ); } inline float4x3 sin( float4x3 m ) { return float4x3( sin( m.x ), sin( m.y ), sin( m.z ), sin( m.w ) ); } inline float4x3 sinh( float4x3 m ) { return float4x3( sinh( m.x ), sinh( m.y ), sinh( m.z ), sinh( m.w ) ); } inline float4x3 smoothstep( float4x3 min, float4x3 max, float4x3 m ) { return float4x3( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ), smoothstep( min.z, max.z, m.z ), smoothstep( min.w, max.w, m.w ) ); } inline float4x3 smootherstep( float4x3 min, float4x3 max, float4x3 m ) { return float4x3( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ), smootherstep( min.z, max.z, m.z ), smootherstep( min.w, max.w, m.w ) ); } inline float4x3 sqrt( float4x3 m ) { return float4x3( sqrt( m.x ), sqrt( m.y ), sqrt( m.z ), sqrt( m.w ) ); } inline float4x3 step( float4x3 a, float4x3 b ) { return float4x3( step( a.x, b.x ), step( a.y, b.y ), step( a.z, b.z ), step( a.w, b.w ) ); } inline float4x3 tan( float4x3 m ) { return float4x3( tan( m.x ), tan( m.y ), tan( m.z ), tan( m.w ) ); } inline float4x3 tanh( float4x3 m ) { return float4x3( tanh( m.x ), tanh( m.y ), tanh( m.z ), tanh( m.w ) ); } inline float4x3 trunc( float4x3 m ) { return float4x3( trunc( m.x ), trunc( m.y ), trunc( m.z ), trunc( m.w ) ); } struct float4x4 { // rows float4 x; float4 y; float4 z; float4 w; // constructors inline float4x4() { } inline float4x4( float f ) : x( f ), y( f ), z( f ), w( f ) { } inline explicit float4x4( float m[16] ) : x( m[0], m[1], m[2], m[3] ), y( m[4], m[5], m[6], m[7] ), z( m[8], m[9], m[10], m[11] ), w( m[12], m[13], m[14], m[15] ) { } inline float4x4( float m00, float m01, float m02, float m03, float m10, float m11, float m12, float m13, float m20, float m21, float m22, float m23, float m30, float m31, float m32, float m33 ) : x( m00, m01, m02, m03 ), y( m10, m11, m12, m13 ), z( m20, m21, m22, m23 ), w( m30, m31, m32, m33 ) { } inline float4x4( float4 x_, float4 y_, float4 z_, float4 w_ ) : x( x_ ), y( y_ ), z( z_ ), w( w_ ) { } // conversions inline float4x4( float4x4_t m ) : x( m.x ), y( m.y ), z( m.z ), w( m.w ) { } inline operator float4x4_t() const { float4x4_t m = { x, y, z, w }; return m; }; // indexing inline float4 operator[]( int row ) { return ( (float4*) this )[ row ]; } // constants static inline float4x4 identity() { return float4x4( float4( 1.0f, 0.0f, 0.0f, 0.0f ), float4( 0.0f, 1.0f, 0.0f, 0.0f ), float4( 0.0f, 0.0f, 1.0f, 0.0f ), float4( 0.0f, 0.0f, 0.0f, 1.0f ) ); } }; // operators inline float4x4& operator+=( float4x4& a, float4x4 b ) { a.x += b.x; a.y += b.y; a.z += b.z; a.w += b.w; return a; }; inline float4x4& operator-=( float4x4& a, float4x4 b ) { a.x -= b.x; a.y -= b.y; a.z -= b.z; a.w -= b.w; return a; }; inline float4x4& operator*=( float4x4& a, float4x4 b ) { a.x *= b.x; a.y *= b.y; a.z *= b.z; a.w *= b.w; return a; }; inline float4x4& operator/=( float4x4& a, float4x4 b ) { a.x /= b.x; a.y /= b.y; a.z /= b.z; a.w /= b.w; return a; }; inline float4x4& operator+=( float4x4& a, float s ) { a.x += s; a.y += s; a.z += s; a.w += s; return a; }; inline float4x4& operator-=( float4x4& a, float s ) { a.x -= s; a.y -= s; a.z -= s; a.w -= s; return a; }; inline float4x4& operator*=( float4x4& a, float s ) { a.x *= s; a.y *= s; a.z *= s; a.w *= s; return a; }; inline float4x4& operator/=( float4x4& a, float s ) { a.x /= s; a.y /= s; a.z /= s; a.w /= s; return a; }; inline float4x4 operator+( float4x4 a, float4x4 b ) { return float4x4( a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w ); } inline float4x4 operator-( float4x4 a, float4x4 b ) { return float4x4( a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w ); } inline float4x4 operator*( float4x4 a, float4x4 b ) { return float4x4( a.x * b.x, a.y * b.y, a.z * b.z, a.w * b.w ); } inline float4x4 operator/( float4x4 a, float4x4 b ) { return float4x4( a.x / b.x, a.y / b.y, a.z / b.z, a.w / b.w ); } inline float4x4 operator+( float4x4 a, float b ) { return float4x4( a.x + b, a.y + b, a.z + b, a.w + b ); } inline float4x4 operator-( float4x4 a, float b ) { return float4x4( a.x - b, a.y - b, a.z - b, a.w - b ); } inline float4x4 operator*( float4x4 a, float b ) { return float4x4( a.x * b, a.y * b, a.z * b, a.w * b ); } inline float4x4 operator/( float4x4 a, float b ) { return float4x4( a.x / b, a.y / b, a.z / b, a.w / b ); } inline float4x4 operator+( float a, float4x4 b ) { return float4x4( a + b.x, a + b.y, a + b.z, a + b.w ); } inline float4x4 operator-( float a, float4x4 b ) { return float4x4( a - b.x, a - b.y, a - b.z, a - b.w ); } inline float4x4 operator*( float a, float4x4 b ) { return float4x4( a * b.x, a * b.y, a * b.z, a * b.w ); } inline float4x4 operator/( float a, float4x4 b ) { return float4x4( a / b.x, a / b.y, a / b.z, a / b.w ); } // functions inline float4x4 abs( float4x4 m ) { return float4x4( abs( m.x ), abs( m.y ), abs( m.z ), abs( m.w ) ); } inline float4x4 acos( float4x4 m ) { return float4x4( acos( m.x ), acos( m.y ), acos( m.z ), acos( m.w ) ); } inline bool all( float4x4 m ) { return all( m.x ) && all( m.y ) && all( m.z ) && all( m.w ); } inline bool any( float4x4 m ) { return any( m.x ) || any( m.y ) || any( m.z ) || any( m.w ); } inline float4x4 asin( float4x4 m ) { return float4x4( asin( m.x ), asin( m.y ), asin( m.z ), asin( m.w ) ); } inline float4x4 atan( float4x4 m ) { return float4x4( atan( m.x ), atan( m.y ), atan( m.z ), atan( m.w ) ); } inline float4x4 atan2( float4x4 y, float4x4 x ) { return float4x4( atan2( y.x, x.x ), atan2( y.y, x.y ), atan2( y.z, x.z ), atan2( y.w, x.w ) ); } inline float4x4 ceil( float4x4 m ) { return float4x4( ceil( m.x ), ceil( m.y ), ceil( m.z ), ceil( m.w ) ); } inline float4x4 clamp( float4x4 m, float4x4 min, float4x4 max ) { return float4x4( clamp( m.x, min.x, max.x ), clamp( m.y, min.y, max.y ), clamp( m.z, min.z, max.z ), clamp( m.w, min.w, max.w ) ); } inline float4x4 cos( float4x4 m ) { return float4x4( cos( m.x ), cos( m.y ), cos( m.z ), cos( m.w ) ); } inline float4x4 cosh( float4x4 m ) { return float4x4( cosh( m.x ), cosh( m.y ), cosh( m.z ), cosh( m.w ) ); } inline float4x4 degrees( float4x4 m ) { return float4x4( degrees( m.x ), degrees( m.y ), degrees( m.z ), degrees( m.w ) ); } inline float4x4 exp( float4x4 m ) { return float4x4( exp( m.x ), exp( m.y ), exp( m.z ), exp( m.w ) ); } inline float4x4 exp2( float4x4 m ) { return float4x4( exp2( m.x ), exp2( m.y ), exp2( m.z ), exp2( m.w ) ); } inline float4x4 floor( float4x4 m ) { return float4x4( floor( m.x ), floor( m.y ), floor( m.z ), floor( m.w ) ); } inline float4x4 fmod( float4x4 a, float4x4 b ) { return float4x4( fmod( a.x, b.x ), fmod( a.y, b.y ), fmod( a.z, b.z ), fmod( a.w, b.w ) ); } inline float4x4 frac( float4x4 m ) { return float4x4( frac( m.x ), frac( m.y ), frac( m.z ), frac( m.w ) ); } inline float4x4 lerp( float4x4 a, float4x4 b, float s ) { return float4x4( lerp( a.x, b.x, s ), lerp( a.y, b.y, s ), lerp( a.z, b.z, s ), lerp( a.w, b.w, s ) ); } inline float4x4 log( float4x4 m ) { return float4x4( log( m.x ), log( m.y ), log( m.z ), log( m.w ) ); } inline float4x4 log2( float4x4 m ) { return float4x4( log2( m.x ), log2( m.y ), log2( m.z ), log2( m.w ) ); } inline float4x4 log10( float4x4 m ) { return float4x4( log10( m.x ), log10( m.y ), log10( m.z ), log10( m.w ) ); } inline float4x4 mad( float4x4 a, float4x4 b, float4x4 c ) { return a * b + c; } inline float4x4 max( float4x4 a, float4x4 b ) { return float4x4( max( a.x, b.x ), max( a.y, b.y ), max( a.z, b.z ), max( a.w, b.w ) ); } inline float4x4 min( float4x4 a, float4x4 b ) { return float4x4( min( a.x, b.x ), min( a.y, b.y ), min( a.z, b.z ), min( a.w, b.w ) ); } inline float4x4 pow( float4x4 a, float4x4 b ) { return float4x4( pow( a.x, b.x ), pow( a.y, b.y ), pow( a.z, b.z ), pow( a.w, b.w ) ); } inline float4x4 radians( float4x4 m ) { return float4x4( radians( m.x ), radians( m.y ), radians( m.z ), radians( m.w ) ); } inline float4x4 rcp( float4x4 m ) { return float4x4( rcp( m.x ), rcp( m.y ), rcp( m.z ), rcp( m.w ) ); } inline float4x4 round( float4x4 m ) { return float4x4( round( m.x ), round( m.y ), round( m.z ), round( m.w ) ); } inline float4x4 rsqrt( float4x4 m ) { return float4x4( rsqrt( m.x ), rsqrt( m.y ), rsqrt( m.z ), rsqrt( m.w ) ); } inline float4x4 saturate( float4x4 m ) { return float4x4( saturate( m.x ), saturate( m.y ), saturate( m.z ), saturate( m.w ) ); } inline float4x4 sign( float4x4 m ) { return float4x4( sign( m.x ), sign( m.y ), sign( m.z ), sign( m.w ) ); } inline float4x4 sin( float4x4 m ) { return float4x4( sin( m.x ), sin( m.y ), sin( m.z ), sin( m.w ) ); } inline float4x4 sinh( float4x4 m ) { return float4x4( sinh( m.x ), sinh( m.y ), sinh( m.z ), sinh( m.w ) ); } inline float4x4 smoothstep( float4x4 min, float4x4 max, float4x4 m ) { return float4x4( smoothstep( min.x, max.x, m.x ), smoothstep( min.y, max.y, m.y ), smoothstep( min.z, max.z, m.z ), smoothstep( min.w, max.w, m.w ) ); } inline float4x4 smootherstep( float4x4 min, float4x4 max, float4x4 m ) { return float4x4( smootherstep( min.x, max.x, m.x ), smootherstep( min.y, max.y, m.y ), smootherstep( min.z, max.z, m.z ), smootherstep( min.w, max.w, m.w ) ); } inline float4x4 sqrt( float4x4 m ) { return float4x4( sqrt( m.x ), sqrt( m.y ), sqrt( m.z ), sqrt( m.w ) ); } inline float4x4 step( float4x4 a, float4x4 b ) { return float4x4( step( a.x, b.x ), step( a.y, b.y ), step( a.z, b.z ), step( a.w, b.w ) ); } inline float4x4 tan( float4x4 m ) { return float4x4( tan( m.x ), tan( m.y ), tan( m.z ), tan( m.w ) ); } inline float4x4 tanh( float4x4 m ) { return float4x4( tanh( m.x ), tanh( m.y ), tanh( m.z ), tanh( m.w ) ); } inline float4x4 trunc( float4x4 m ) { return float4x4( trunc( m.x ), trunc( m.y ), trunc( m.z ), trunc( m.w ) ); } // matrix math inline float2x2 transpose( float2x2 m ) { return float2x2( float2( m.x.x, m.y.x ), float2( m.x.y, m.y.y ) ); } inline float3x2 transpose( float2x3 m ) { return float3x2( float2( m.x.x, m.y.x ), float2( m.x.y, m.y.y ), float2( m.x.z, m.y.z ) ); } inline float2x3 transpose( float3x2 m ) { return float2x3( float3( m.x.x, m.y.x, m.z.x ), float3( m.x.y, m.y.y, m.z.y ) ); } inline float3x3 transpose( float3x3 m ) { return float3x3( float3( m.x.x, m.y.x, m.z.x ), float3( m.x.y, m.y.y, m.z.y ), float3( m.x.z, m.y.z, m.z.z ) ); } inline float4x2 transpose( float2x4 m ) { return float4x2( float2( m.x.x, m.y.x ), float2( m.x.y, m.y.y ), float2( m.x.z, m.y.z ), float2( m.x.w, m.y.w ) ); } inline float4x3 transpose( float3x4 m ) { return float4x3( float3( m.x.x, m.y.x, m.z.x ), float3( m.x.y, m.y.y, m.z.y ), float3( m.x.z, m.y.z, m.z.z ), float3( m.x.w, m.y.w, m.z.w ) ); } inline float2x4 transpose( float4x2 m ) { return float2x4( float4( m.x.x, m.y.x, m.z.x, m.w.x ), float4( m.x.y, m.y.y, m.z.y, m.w.y ) ); } inline float3x4 transpose( float4x3 m ) { return float3x4( float4( m.x.x, m.y.x, m.z.x, m.w.x ), float4( m.x.y, m.y.y, m.z.y, m.w.y ), float4( m.x.z, m.y.z, m.z.z, m.w.z ) ); } inline float4x4 transpose( float4x4 m ) { return float4x4( float4( m.x.x, m.y.x, m.z.x, m.w.x ), float4( m.x.y, m.y.y, m.z.y, m.w.y ), float4( m.x.z, m.y.z, m.z.z, m.w.z ), float4( m.x.w, m.y.w, m.z.w, m.w.w ) ); } inline float determinant( float2x2 m) { return m.x.x * m.y.y - m.x.y * m.y.x; } inline float determinant( float3x3 m) { return m.x.x * m.y.y * m.z.z + m.x.y * m.y.z * m.z.x + m.x.z * m.y.x * m.z.y - m.x.x * m.y.z * m.z.y - m.x.y * m.y.x * m.z.z - m.x.z * m.y.y * m.z.x; } inline float determinant( float4x4 m) { return m.x.w * m.y.z * m.z.y * m.w.x - m.x.z * m.y.w * m.z.y * m.w.x - m.x.w * m.y.y * m.z.z * m.w.x + m.x.y * m.y.w * m.z.z * m.w.x + m.x.z * m.y.y * m.z.w * m.w.x - m.x.y * m.y.z * m.z.w * m.w.x - m.x.w * m.y.z * m.z.x * m.w.y + m.x.z * m.y.w * m.z.x * m.w.y + m.x.w * m.y.x * m.z.z * m.w.y - m.x.x * m.y.w * m.z.z * m.w.y - m.x.z * m.y.x * m.z.w * m.w.y + m.x.x * m.y.z * m.z.w * m.w.y + m.x.w * m.y.y * m.z.x * m.w.z - m.x.y * m.y.w * m.z.x * m.w.z - m.x.w * m.y.x * m.z.y * m.w.z + m.x.x * m.y.w * m.z.y * m.w.z + m.x.y * m.y.x * m.z.w * m.w.z - m.x.x * m.y.y * m.z.w * m.w.z - m.x.z * m.y.y * m.z.x * m.w.w + m.x.y * m.y.z * m.z.x * m.w.w + m.x.z * m.y.x * m.z.y * m.w.w - m.x.x * m.y.z * m.z.y * m.w.w - m.x.y * m.y.x * m.z.z * m.w.w + m.x.x * m.y.y * m.z.z * m.w.w; } inline bool is_identity( float2x2 m ) { return m.x.x == 1.0f && m.x.y == 0.0f && m.y.x == 0.0f && m.y.y == 1.0f; } inline bool is_identity( float3x3 m ) { return m.x.x == 1.0f && m.x.y == 0.0f && m.x.z == 0.0f && m.y.x == 0.0f && m.y.y == 1.0f && m.y.z == 0.0f && m.z.x == 0.0f && m.z.y == 0.0f && m.z.z == 1.0f; } inline bool is_identity( float4x4 m ) { return m.x.x == 1.0f && m.x.y == 0.0f && m.x.z == 0.0f && m.x.w == 0.0f && m.y.x == 0.0f && m.y.y == 1.0f && m.y.z == 0.0f && m.y.w == 0.0f && m.z.x == 0.0f && m.z.y == 0.0f && m.z.z == 1.0f && m.z.w == 0.0f && m.w.x == 0.0f && m.w.y == 0.0f && m.w.z == 0.0f && m.w.w == 1.0f; } inline bool inverse( float2x2* out_matrix, float* out_determinant, float2x2 m ) { float d = determinant( m ); if( out_determinant ) *out_determinant = d; if( d != 0.0f && out_matrix ) *out_matrix = float2x2( float2( m.y.y / d, - m.x.y / d), float2( - m.y.x / d, m.x.x / d ) ); return d != 0.0f; } inline bool inverse( float3x3* out_matrix, float* out_determinant, float3x3 m ) { float d = determinant( m ); if( out_determinant ) *out_determinant = d; if( d != 0.0f && out_matrix ) *out_matrix = float3x3( float3( ( m.y.y * m.z.z - m.y.z * m.z.y ) / d, ( m.x.z * m.z.y - m.x.y * m.z.z ) / d, ( m.x.y * m.y.z - m.x.z * m.y.y ) / d ), float3( ( m.y.z * m.z.x - m.y.x * m.z.z ) / d, ( m.x.x * m.z.z - m.x.z * m.z.x ) / d, ( m.x.z * m.y.x - m.x.x * m.y.z ) / d ), float3( ( m.y.x * m.z.y - m.y.y * m.z.x ) / d, ( m.x.y * m.z.x - m.x.x * m.z.y ) / d, ( m.x.x * m.y.y - m.x.y * m.y.x ) / d ) ); return d != 0.0f; } inline bool inverse( float4x4* out_matrix, float* out_determinant, float4x4 m ) { float d = determinant( m ); if( out_determinant ) *out_determinant = d; if( d != 0.0f && out_matrix ) *out_matrix = float4x4( float4( ( m.y.z * m.z.w * m.w.y - m.y.w * m.z.z * m.w.y + m.y.w * m.z.y * m.w.z - m.y.y * m.z.w * m.w.z - m.y.z * m.z.y * m.w.w + m.y.y * m.z.z * m.w.w ) / d, ( m.x.w * m.z.z * m.w.y - m.x.z * m.z.w * m.w.y - m.x.w * m.z.y * m.w.z + m.x.y * m.z.w * m.w.z + m.x.z * m.z.y * m.w.w - m.x.y * m.z.z * m.w.w ) / d, ( m.x.z * m.y.w * m.w.y - m.x.w * m.y.z * m.w.y + m.x.w * m.y.y * m.w.z - m.x.y * m.y.w * m.w.z - m.x.z * m.y.y * m.w.w + m.x.y * m.y.z * m.w.w ) / d, ( m.x.w * m.y.z * m.z.y - m.x.z * m.y.w * m.z.y - m.x.w * m.y.y * m.z.z + m.x.y * m.y.w * m.z.z + m.x.z * m.y.y * m.z.w - m.x.y * m.y.z * m.z.w ) / d ), float4( ( m.y.w * m.z.z * m.w.x - m.y.z * m.z.w * m.w.x - m.y.w * m.z.x * m.w.z + m.y.x * m.z.w * m.w.z + m.y.z * m.z.x * m.w.w - m.y.x * m.z.z * m.w.w ) / d, ( m.x.z * m.z.w * m.w.x - m.x.w * m.z.z * m.w.x + m.x.w * m.z.x * m.w.z - m.x.x * m.z.w * m.w.z - m.x.z * m.z.x * m.w.w + m.x.x * m.z.z * m.w.w ) / d, ( m.x.w * m.y.z * m.w.x - m.x.z * m.y.w * m.w.x - m.x.w * m.y.x * m.w.z + m.x.x * m.y.w * m.w.z + m.x.z * m.y.x * m.w.w - m.x.x * m.y.z * m.w.w ) / d, ( m.x.z * m.y.w * m.z.x - m.x.w * m.y.z * m.z.x + m.x.w * m.y.x * m.z.z - m.x.x * m.y.w * m.z.z - m.x.z * m.y.x * m.z.w + m.x.x * m.y.z * m.z.w ) / d ), float4( ( m.y.y * m.z.w * m.w.x - m.y.w * m.z.y * m.w.x + m.y.w * m.z.x * m.w.y - m.y.x * m.z.w * m.w.y - m.y.y * m.z.x * m.w.w + m.y.x * m.z.y * m.w.w ) / d, ( m.x.w * m.z.y * m.w.x - m.x.y * m.z.w * m.w.x - m.x.w * m.z.x * m.w.y + m.x.x * m.z.w * m.w.y + m.x.y * m.z.x * m.w.w - m.x.x * m.z.y * m.w.w ) / d, ( m.x.y * m.y.w * m.w.x - m.x.w * m.y.y * m.w.x + m.x.w * m.y.x * m.w.y - m.x.x * m.y.w * m.w.y - m.x.y * m.y.x * m.w.w + m.x.x * m.y.y * m.w.w ) / d, ( m.x.w * m.y.y * m.z.x - m.x.y * m.y.w * m.z.x - m.x.w * m.y.x * m.z.y + m.x.x * m.y.w * m.z.y + m.x.y * m.y.x * m.z.w - m.x.x * m.y.y * m.z.w ) / d ), float4( ( m.y.z * m.z.y * m.w.x - m.y.y * m.z.z * m.w.x - m.y.z * m.z.x * m.w.y + m.y.x * m.z.z * m.w.y + m.y.y * m.z.x * m.w.z - m.y.x * m.z.y * m.w.z ) / d, ( m.x.y * m.z.z * m.w.x - m.x.z * m.z.y * m.w.x + m.x.z * m.z.x * m.w.y - m.x.x * m.z.z * m.w.y - m.x.y * m.z.x * m.w.z + m.x.x * m.z.y * m.w.z ) / d, ( m.x.z * m.y.y * m.w.x - m.x.y * m.y.z * m.w.x - m.x.z * m.y.x * m.w.y + m.x.x * m.y.z * m.w.y + m.x.y * m.y.x * m.w.z - m.x.x * m.y.y * m.w.z ) / d, ( m.x.y * m.y.z * m.z.x - m.x.z * m.y.y * m.z.x + m.x.z * m.y.x * m.z.y - m.x.x * m.y.z * m.z.y - m.x.y * m.y.x * m.z.z + m.x.x * m.y.y * m.z.z ) / d ) ); return d != 0.0f; } // matrix multiplications inline float mul( float a, float b ) { return a * b; } inline float2 mul( float a, float2 b ) { return a * b; } inline float3 mul( float a, float3 b ) { return a * b; } inline float4 mul( float a, float4 b ) { return a * b; } inline float2x2 mul( float a, float2x2 b ) { return a * b; } inline float2x3 mul( float a, float2x3 b ) { return a * b; } inline float3x2 mul( float a, float3x2 b ) { return a * b; } inline float3x3 mul( float a, float3x3 b ) { return a * b; } inline float2x4 mul( float a, float2x4 b ) { return a * b; } inline float3x4 mul( float a, float3x4 b ) { return a * b; } inline float4x2 mul( float a, float4x2 b ) { return a * b; } inline float4x3 mul( float a, float4x3 b ) { return a * b; } inline float4x4 mul( float a, float4x4 b ) { return a * b; } inline float2 mul( float2 a, float b ) { return a * b; } inline float3 mul( float3 a, float b ) { return a * b; } inline float4 mul( float4 a, float b ) { return a * b; } inline float mul( float2 a, float2 b ) { return dot( a, b ); } inline float mul( float3 a, float3 b ) { return dot( a, b ); } inline float mul( float4 a, float4 b ) { return dot( a, b ); } inline float2 mul( float2 a, float2x2 b ) { return float2( a.x * b.x.x + a.y * b.y.x, a.x * b.x.y + a.y * b.y.y ); } inline float3 mul( float2 a, float2x3 b ) { return float3( a.x * b.x.x + a.y * b.y.x, a.x * b.x.y + a.y * b.y.y, a.x * b.x.z + a.y * b.y.z ); } inline float2 mul( float3 a, float3x2 b ) { return float2( a.x * b.x.x + a.y * b.y.x + a.z * b.z.x, a.x * b.x.y + a.y * b.y.y + a.z * b.z.y ); } inline float3 mul( float3 a, float3x3 b ) { return float3( a.x * b.x.x + a.y * b.y.x + a.z * b.z.x, a.x * b.x.y + a.y * b.y.y + a.z * b.z.y, a.x * b.x.z + a.y * b.y.z + a.z * b.z.z ); } inline float4 mul( float2 a, float2x4 b ) { return float4( a.x * b.x.x + a.y * b.y.x, a.x * b.x.y + a.y * b.y.y, a.x * b.x.z + a.y * b.y.z, a.x * b.x.w + a.y * b.y.w ); } inline float4 mul( float3 a, float3x4 b ) { return float4( a.x * b.x.x + a.y * b.y.x + a.z * b.z.x, a.x * b.x.y + a.y * b.y.y + a.z * b.z.y, a.x * b.x.z + a.y * b.y.z + a.z * b.z.z, a.x * b.x.w + a.y * b.y.w + a.z * b.z.w ); } inline float2 mul( float4 a, float4x2 b ) { return float2( a.x * b.x.x + a.y * b.y.x + a.z * b.z.x + a.w * b.w.x, a.x * b.x.y + a.y * b.y.y + a.z * b.z.y + a.w * b.w.y ); } inline float3 mul( float4 a, float4x3 b ) { return float3( a.x * b.x.x + a.y * b.y.x + a.z * b.z.x + a.w * b.w.x, a.x * b.x.y + a.y * b.y.y + a.z * b.z.y + a.w * b.w.y, a.x * b.x.z + a.y * b.y.z + a.z * b.z.z + a.w * b.w.z ); } inline float4 mul( float4 a, float4x4 b ) { return float4( a.x * b.x.x + a.y * b.y.x + a.z * b.z.x + a.w * b.w.x, a.x * b.x.y + a.y * b.y.y + a.z * b.z.y + a.w * b.w.y, a.x * b.x.z + a.y * b.y.z + a.z * b.z.z + a.w * b.w.z, a.x * b.x.w + a.y * b.y.w + a.z * b.z.w + a.w * b.w.w ); } inline float2x2 mul( float2x2 a, float b ) { return a * b; } inline float2x3 mul( float2x3 a, float b ) { return a * b; } inline float3x2 mul( float3x2 a, float b ) { return a * b; } inline float3x3 mul( float3x3 a, float b ) { return a * b; } inline float2x4 mul( float2x4 a, float b ) { return a * b; } inline float3x4 mul( float3x4 a, float b ) { return a * b; } inline float4x2 mul( float4x2 a, float b ) { return a * b; } inline float4x3 mul( float4x3 a, float b ) { return a * b; } inline float4x4 mul( float4x4 a, float b ) { return a * b; } inline float2 mul( float2x2 a, float2 b ) { return float2( a.x.x * b.x + a.x.y * b.y, a.y.x * b.x + a.y.y * b.y ); } inline float2 mul( float2x3 a, float3 b ) { return float2( a.x.x * b.x + a.x.y * b.y + a.x.z * b.z, a.y.x * b.x + a.y.y * b.y + a.y.z * b.z ); } inline float3 mul( float3x2 a, float2 b ) { return float3( a.x.x * b.x + a.x.y * b.y, a.y.x * b.x + a.y.y * b.y, a.z.x * b.x + a.z.y * b.y ); } inline float3 mul( float3x3 a, float3 b ) { return float3( a.x.x * b.x + a.x.y * b.y + a.x.z * b.z, a.y.x * b.x + a.y.y * b.y + a.y.z * b.z, a.z.x * b.x + a.z.y * b.y + a.z.z * b.z ); } inline float2 mul( float2x4 a, float4 b ) { return float2( a.x.x * b.x + a.x.y * b.y + a.x.z * b.z + a.x.w * b.w, a.y.x * b.x + a.y.y * b.y + a.y.z * b.z + a.y.w * b.w ); } inline float3 mul( float3x4 a, float4 b ) { return float3( a.x.x * b.x + a.x.y * b.y + a.x.z * b.z + a.x.w * b.w, a.y.x * b.x + a.y.y * b.y + a.y.z * b.z + a.y.w * b.w, a.z.x * b.x + a.z.y * b.y + a.z.z * b.z + a.z.w * b.w ); } inline float4 mul( float4x2 a, float2 b ) { return float4( a.x.x * b.x + a.x.y * b.y, a.y.x * b.x + a.y.y * b.y, a.z.x * b.x + a.z.y * b.y, a.w.x * b.x + a.w.y * b.y ); } inline float4 mul( float4x3 a, float3 b ) { return float4( a.x.x * b.x + a.x.y * b.y + a.x.z * b.z, a.y.x * b.x + a.y.y * b.y + a.y.z * b.z, a.z.x * b.x + a.z.y * b.y + a.z.z * b.z, a.w.x * b.x + a.w.y * b.y + a.w.z * b.z ); } inline float4 mul( float4x4 a, float4 b ) { return float4( a.x.x * b.x + a.x.y * b.y + a.x.z * b.z + a.x.w * b.w, a.y.x * b.x + a.y.y * b.y + a.y.z * b.z + a.y.w * b.w, a.z.x * b.x + a.z.y * b.y + a.z.z * b.z + a.z.w * b.w, a.w.x * b.x + a.w.y * b.y + a.w.z * b.z + a.w.w * b.w ); } inline float2x2 mul( float2x2 a, float2x2 b ) { return float2x2( float2( a.x.x * b.x.x + a.x.y * b.y.x, a.x.x * b.x.y + a.x.y * b.y.y ), float2( a.y.x * b.x.x + a.y.y * b.y.x, a.y.x * b.x.y + a.y.y * b.y.y ) ); } inline float3x3 mul( float3x2 a, float2x3 b ) { return float3x3( float3( a.x.x * b.x.x + a.x.y * b.y.x, a.x.x * b.x.y + a.x.y * b.y.y, a.x.x * b.x.z + a.x.y * b.y.z ), float3( a.y.x * b.x.x + a.y.y * b.y.x, a.y.x * b.x.y + a.y.y * b.y.y, a.y.x * b.x.z + a.y.y * b.y.z ), float3( a.z.x * b.x.x + a.z.y * b.y.x, a.z.x * b.x.y + a.z.y * b.y.y, a.z.x * b.x.z + a.z.y * b.y.z ) ); } inline float2x2 mul( float2x3 a, float3x2 b ) { return float2x2( float2( a.x.x * b.x.x + a.x.y * b.y.x + a.x.z * b.z.x, a.x.x * b.x.y + a.x.y * b.y.y + a.x.z * b.z.y ), float2( a.y.x * b.x.x + a.y.y * b.y.x + a.y.z * b.z.x, a.y.x * b.x.y + a.y.y * b.y.y + a.y.z * b.z.y ) ); } inline float3x3 mul( float3x3 a, float3x3 b ) { return float3x3( float3( a.x.x * b.x.x + a.x.y * b.y.x + a.x.z * b.z.x, a.x.x * b.x.y + a.x.y * b.y.y + a.x.z * b.z.y, a.x.x * b.x.z + a.x.y * b.y.z + a.x.z * b.z.z ), float3( a.y.x * b.x.x + a.y.y * b.y.x + a.y.z * b.z.x, a.y.x * b.x.y + a.y.y * b.y.y + a.y.z * b.z.y, a.y.x * b.x.z + a.y.y * b.y.z + a.y.z * b.z.z ), float3( a.z.x * b.x.x + a.z.y * b.y.x + a.z.z * b.z.x, a.z.x * b.x.y + a.z.y * b.y.y + a.z.z * b.z.y, a.z.x * b.x.z + a.z.y * b.y.z + a.z.z * b.z.z ) ); } inline float4x4 mul( float4x2 a, float2x4 b ) { return float4x4( float4( a.x.x * b.x.x + a.x.y * b.y.x, a.x.x * b.x.y + a.x.y * b.y.y, a.x.x * b.x.z + a.x.y * b.y.z, a.x.x * b.x.w + a.x.y * b.y.w ), float4( a.y.x * b.x.x + a.y.y * b.y.x, a.y.x * b.x.y + a.y.y * b.y.y, a.y.x * b.x.z + a.y.y * b.y.z, a.y.x * b.x.w + a.y.y * b.y.w ), float4( a.z.x * b.x.x + a.z.y * b.y.x, a.z.x * b.x.y + a.z.y * b.y.y, a.z.x * b.x.z + a.z.y * b.y.z, a.z.x * b.x.w + a.z.y * b.y.w ), float4( a.w.x * b.x.x + a.w.y * b.y.x, a.w.x * b.x.y + a.w.y * b.y.y, a.w.x * b.x.z + a.w.y * b.y.z, a.w.x * b.x.w + a.w.y * b.y.w ) ); } inline float4x4 mul( float4x3 a, float3x4 b ) { return float4x4( float4( a.x.x * b.x.x + a.x.y * b.y.x + a.x.z * b.z.x, a.x.x * b.x.y + a.x.y * b.y.y + a.x.z * b.z.y, a.x.x * b.x.z + a.x.y * b.y.z + a.x.z * b.z.z, a.x.x * b.x.w + a.x.y * b.y.w + a.x.z * b.z.w ), float4( a.y.x * b.x.x + a.y.y * b.y.x + a.y.z * b.z.x, a.y.x * b.x.y + a.y.y * b.y.y + a.y.z * b.z.y, a.y.x * b.x.z + a.y.y * b.y.z + a.y.z * b.z.z, a.y.x * b.x.w + a.y.y * b.y.w + a.y.z * b.z.w ), float4( a.z.x * b.x.x + a.z.y * b.y.x + a.z.z * b.z.x, a.z.x * b.x.y + a.z.y * b.y.y + a.z.z * b.z.y, a.z.x * b.x.z + a.z.y * b.y.z + a.z.z * b.z.z, a.z.x * b.x.w + a.z.y * b.y.w + a.z.z * b.z.w ), float4( a.w.x * b.x.x + a.w.y * b.y.x + a.w.z * b.z.x, a.w.x * b.x.y + a.w.y * b.y.y + a.w.z * b.z.y, a.w.x * b.x.z + a.w.y * b.y.z + a.w.z * b.z.z, a.w.x * b.x.w + a.w.y * b.y.w + a.w.z * b.z.w ) ); } inline float2x2 mul( float2x4 a, float4x2 b ) { return float2x2( float2( a.x.x * b.x.x + a.x.y * b.y.x + a.x.z * b.z.x + a.x.w * b.w.x, a.x.x * b.x.y + a.x.y * b.y.y + a.x.z * b.z.y + a.x.w * b.w.y ), float2( a.y.x * b.x.x + a.y.y * b.y.x + a.y.z * b.z.x + a.y.w * b.w.x, a.y.x * b.x.y + a.y.y * b.y.y + a.y.z * b.z.y + a.y.w * b.w.y ) ); } inline float3x3 mul( float3x4 a, float4x3 b ) { return float3x3( float3( a.x.x * b.x.x + a.x.y * b.y.x + a.x.z * b.z.x, a.x.x * b.x.y + a.x.y * b.y.y + a.x.z * b.z.y, a.x.x * b.x.z + a.x.y * b.y.z + a.x.z * b.z.z ), float3( a.y.x * b.x.x + a.y.y * b.y.x + a.y.z * b.z.x, a.y.x * b.x.y + a.y.y * b.y.y + a.y.z * b.z.y, a.y.x * b.x.z + a.y.y * b.y.z + a.y.z * b.z.z ), float3( a.z.x * b.x.x + a.z.y * b.y.x + a.z.z * b.z.x, a.z.x * b.x.y + a.z.y * b.y.y + a.z.z * b.z.y, a.z.x * b.x.z + a.z.y * b.y.z + a.z.z * b.z.z ) ); } inline float4x4 mul( float4x4 a, float4x4 b ) { return float4x4( float4( a.x.x * b.x.x + a.x.y * b.y.x + a.x.z * b.z.x + a.x.w * b.w.x, a.x.x * b.x.y + a.x.y * b.y.y + a.x.z * b.z.y + a.x.w * b.w.y, a.x.x * b.x.z + a.x.y * b.y.z + a.x.z * b.z.z + a.x.w * b.w.z, a.x.x * b.x.w + a.x.y * b.y.w + a.x.z * b.z.w + a.x.w * b.w.w ), float4( a.y.x * b.x.x + a.y.y * b.y.x + a.y.z * b.z.x + a.y.w * b.w.x, a.y.x * b.x.y + a.y.y * b.y.y + a.y.z * b.z.y + a.y.w * b.w.y, a.y.x * b.x.z + a.y.y * b.y.z + a.y.z * b.z.z + a.y.w * b.w.z, a.y.x * b.x.w + a.y.y * b.y.w + a.y.z * b.z.w + a.y.w * b.w.w ), float4( a.z.x * b.x.x + a.z.y * b.y.x + a.z.z * b.z.x + a.z.w * b.w.x, a.z.x * b.x.y + a.z.y * b.y.y + a.z.z * b.z.y + a.z.w * b.w.y, a.z.x * b.x.z + a.z.y * b.y.z + a.z.z * b.z.z + a.z.w * b.w.z, a.z.x * b.x.w + a.z.y * b.y.w + a.z.z * b.z.w + a.z.w * b.w.w ), float4( a.w.x * b.x.x + a.w.y * b.y.x + a.w.z * b.z.x + a.w.w * b.w.x, a.w.x * b.x.y + a.w.y * b.y.y + a.w.z * b.z.y + a.w.w * b.w.y, a.w.x * b.x.z + a.w.y * b.y.z + a.w.z * b.z.z + a.w.w * b.w.z, a.w.x * b.x.w + a.w.y * b.y.w + a.w.z * b.z.w + a.w.w * b.w.w ) ); } } /* namespace vecmath */ #endif /* vecmath_hpp */ /* ---------------------- IMPLEMENTATION ---------------------- */ #ifndef vecmath_impl #define vecmath_impl namespace vecmath { inline swizzle2& swizzle2::operator=( float2 const& v ) { x = v.x; y = v.y; return *this; } inline swizzle3& swizzle3::operator=( float3 const& v ) { x = v.x; y = v.y; z = v.z; return *this; } inline swizzle4& swizzle4::operator=( float4 const& v ) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } inline swizzle2& swizzle2::operator=( swizzle2 const& v ) { float2 t = v; x = t.x; y = t.y; return *this; } inline swizzle3& swizzle3::operator=( swizzle3 const& v ) { float3 t = v; x = t.x; y = t.y; z = t.z; return *this; } inline swizzle4& swizzle4::operator=( swizzle4 const& v ) { float4 t = v; x = t.x; y = t.y; z = t.z; w = t.w; return *this; } } /* namespace vecmath */ #endif /* vecmath_impl */ #ifdef VECMATH_IMPLEMENTATION #undef VECMATH_IMPLEMENTATION // TODO: customizable math funcs #define _CRT_NONSTDC_NO_DEPRECATE #define _CRT_SECURE_NO_WARNINGS #pragma warning( push ) #pragma warning( disable: 4668 ) // 'symbol' is not defined as a preprocessor macro, replacing with '0' for 'directives' #include <math.h> #pragma warning( pop ) float vecmath::internal::acosf( float x ) { return (float)::acos( (double) x ); } float vecmath::internal::asinf( float x ) { return (float)::asin( (double) x ); } float vecmath::internal::atanf( float x ) { return (float)::atan( (double) x ); } float vecmath::internal::atan2f( float x, float y ) { return (float)::atan2( (double) x, (double) y ); } float vecmath::internal::ceilf( float x ) { return (float)::ceil( (double) x ); } float vecmath::internal::cosf( float x ) { return (float)::cos( (double) x ); } float vecmath::internal::coshf( float x ) { return (float)::cosh( (double) x ); } float vecmath::internal::expf( float x ) { return (float)::exp( (double) x ); } float vecmath::internal::fabsf( float x ) { return (float)::fabs( (double) x ); } float vecmath::internal::floorf( float x ) { return (float)::floor( (double) x ); } float vecmath::internal::fmodf( float x, float y ) { return (float)::fmod( (double) x, (double) y ); } float vecmath::internal::logf( float x ) { return (float)::log( (double) x ); } float vecmath::internal::log10f( float x ) { return (float)::log10( (double) x ); } float vecmath::internal::modff( float x, float* y ) { double yy; float r = (float)::modf( (double) x, &yy ); *y = (float) yy; return r; } float vecmath::internal::powf( float x, float y ) { return (float)::pow( (double) x, (double) y ); } float vecmath::internal::sqrtf( float x ) { return (float)::sqrt( (double) x ); } float vecmath::internal::sinf( float x ) { return (float)::sin( (double) x ); } float vecmath::internal::sinhf( float x ) { return (float)::sinh( (double) x ); } float vecmath::internal::tanf( float x ) { return (float)::tan( (double) x ); } float vecmath::internal::tanhf( float x ) { return (float)::tanh( (double) x ); } #if !defined( _MSC_VER ) || _MSC_VER >= 1800 float vecmath::internal::log2f( float x ) { return (float)::log2( (double) x ); } float vecmath::internal::roundf( float x ) { return (float)::round( (double) x ); } float vecmath::internal::truncf( float x ) { return (float)::trunc( (double) x ); } #else float vecmath::internal::log2f( float x ) { return (float)( ::log10( (double) x ) / ::log10( 2.0 ) ); } float vecmath::internal::roundf( float x ) { double i, r; double fraction = modf( (double) x, &i ); modf( 2.0 * fraction, &r ); return (float)( i + r ); } float vecmath::internal::truncf( float x ) { return (float)( x > 0.0f ? ( ::floor( (double) x ) ) : ( ::ceil( (double) x ) ) ); } #endif #endif /* VECMATH_IMPLEMENTATION */ /* ------------------------------------------------------------------------------ This software is available under 2 licenses - you may choose the one you like. ------------------------------------------------------------------------------ ALTERNATIVE A - MIT License Copyright (c) 2015 Mattias Gustavsson 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. ------------------------------------------------------------------------------ ALTERNATIVE B - Public Domain (www.unlicense.org) This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ------------------------------------------------------------------------------ */
82.909542
2,687
0.56435
[ "vector" ]
782a5bd53f2b55649dd915e3cc1cf728158ac043
1,418
cpp
C++
leetcode/problems/easy/1389-create-target-array-in-the-given-order.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/easy/1389-create-target-array-in-the-given-order.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/easy/1389-create-target-array-in-the-given-order.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Create Target Array in the Given Order Given two arrays of integers nums and index. Your task is to create target array under the following rules: Initially target array is empty. From left to right read nums[i] and index[i], insert at index index[i] the value nums[i] in target array. Repeat the previous step until there are no elements to read in nums and index. Return the target array. It is guaranteed that the insertion operations will be valid. Example 1: Input: nums = [0,1,2,3,4], index = [0,1,2,2,1] Output: [0,4,1,3,2] Explanation: nums index target 0 0 [0] 1 1 [0,1] 2 2 [0,1,2] 3 2 [0,1,3,2] 4 1 [0,4,1,3,2] Example 2: Input: nums = [1,2,3,4,0], index = [0,1,2,3,0] Output: [0,1,2,3,4] Explanation: nums index target 1 0 [1] 2 1 [1,2] 3 2 [1,2,3] 4 3 [1,2,3,4] 0 0 [0,1,2,3,4] Example 3: Input: nums = [1], index = [0] Output: [1] */ class Solution { public: vector<int> createTargetArray(vector<int>& nums, vector<int>& index) { vector<int> ans; for(int i=0;i<nums.size();i++) ans.insert(ans.begin()+index[i], nums[i]); return ans; } }; static const auto io_sync_off = []() {std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();
27.269231
119
0.566291
[ "vector" ]
7831e6f44bc424e3780ac8fe51710d93fb647f78
3,015
cpp
C++
Code/GraphMol/MolDraw2D/DrawTextCairo.cpp
NadineSchneider/rdkit
7f6920ff4e53859f1fb54a4177123540fc073093
[ "BSD-3-Clause" ]
null
null
null
Code/GraphMol/MolDraw2D/DrawTextCairo.cpp
NadineSchneider/rdkit
7f6920ff4e53859f1fb54a4177123540fc073093
[ "BSD-3-Clause" ]
2
2020-06-08T08:06:39.000Z
2020-07-03T07:04:42.000Z
Code/GraphMol/MolDraw2D/DrawTextCairo.cpp
NadineSchneider/rdkit
7f6920ff4e53859f1fb54a4177123540fc073093
[ "BSD-3-Clause" ]
1
2020-05-15T12:15:35.000Z
2020-05-15T12:15:35.000Z
// // @@ 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. // // Original author: David Cosgrove (CozChemIx) on 29/04/2020. // #include <GraphMol/MolDraw2D/DrawTextCairo.h> #include <GraphMol/MolDraw2D/MolDraw2D.h> using namespace std; namespace RDKit { // **************************************************************************** DrawTextCairo::DrawTextCairo(double max_fnt_sz, double min_fnt_sz, cairo_t *dp_cr) : DrawText(max_fnt_sz, min_fnt_sz), dp_cr_(dp_cr) { cairo_select_font_face(dp_cr, "sans", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL); cairo_set_font_size(dp_cr, fontSize()); } // **************************************************************************** // draw the char, with the bottom left hand corner at cds void DrawTextCairo::drawChar(char c, const Point2D &cds) { PRECONDITION(dp_cr_, "no draw context"); cairo_set_font_size(dp_cr_, fontSize()); DrawColour col = colour(); cairo_set_source_rgb(dp_cr_, col.r, col.g, col.b); char txt[2]; txt[0] = c; txt[1] = 0; cairo_move_to(dp_cr_, cds.x, cds.y); cairo_show_text(dp_cr_, txt); cairo_stroke(dp_cr_); } // **************************************************************************** void DrawTextCairo::getStringRects(const string &text, vector<shared_ptr<StringRect>> &rects, vector<TextDrawType> &draw_modes, vector<char> &draw_chars) const { TextDrawType draw_mode = TextDrawType::TextDrawNormal; double running_x = 0.0; char char_str[2]; char_str[1] = 0; double max_y = 0.0; double full_fs = fontSize(); for(size_t i = 0; i < text.length(); ++i) { // setStringDrawMode moves i along to the end of any <sub> or <sup> // markup if ('<' == text[i] && setStringDrawMode(text, draw_mode, i)) { continue; } draw_chars.push_back(text[i]); char_str[0] = text[i]; cairo_text_extents_t extents; cairo_set_font_size(dp_cr_, selectScaleFactor(text[i], draw_mode) * full_fs); cairo_text_extents(dp_cr_, char_str, &extents); cairo_set_font_size(dp_cr_, full_fs); double twidth = extents.width; double theight = extents.height; Point2D offset(extents.x_bearing + twidth / 2.0, -extents.y_bearing / 2.0); Point2D g_centre(offset.x, -extents.y_bearing - theight / 2.0); rects.push_back(shared_ptr<StringRect>(new StringRect(offset, g_centre, twidth, theight))); rects.back()->trans_.x = running_x; draw_modes.push_back(draw_mode); running_x += extents.x_advance; max_y = max(max_y, -extents.y_bearing); } for(auto r: rects) { r->g_centre_.y = max_y - r->g_centre_.y; r->offset_.y = max_y / 2.0; } adjustStringRectsForSuperSubScript(draw_modes, rects); } } // namespace RDKit
33.876404
95
0.61194
[ "vector" ]
7839185fd173db8be1f39ee71118dddfeb6edfbd
1,259
cpp
C++
test/snippet/argument_parser/argument_parser_3.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
null
null
null
test/snippet/argument_parser/argument_parser_3.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
null
null
null
test/snippet/argument_parser/argument_parser_3.cpp
Clemapfel/seqan3
7114024ccaa883364d47f9335d6b19525a1fa7a9
[ "BSD-3-Clause" ]
null
null
null
//! [usage] #include <seqan3/argument_parser/all.hpp> int main(int argc, char ** argv) { seqan3::argument_parser myparser("Penguin_Parade", argc, argv); // initialize myparser.info.version = "2.0.0"; myparser.info.date = "12.01.2017"; myparser.info.short_description = "Organize your penguin parade"; myparser.info.description.push_back("First Paragraph."); myparser.info.description.push_back("Second Paragraph."); myparser.info.examples.push_back("./penguin_parade Skipper Kowalski Rico Private -d 10 -m 02 -y 2017"); int d{01}; // day int m{01}; // month int y{2050}; // year myparser.add_option(d, 'd', "day", "Please specify your preferred day."); myparser.add_option(m, 'm', "month", "Please specify your preferred month."); myparser.add_option(y, 'y', "year", "Please specify your preferred year."); std::vector<std::string> penguin_names; myparser.add_positional_option(penguin_names, "Specify the names of the penguins."); try { myparser.parse(); } catch (seqan3::parser_invalid_argument const & ext) // the user did something wrong { std::cerr << ext.what() << "\n"; return -1; } // organize ... return 0; } //! [usage]
29.97619
107
0.646545
[ "vector" ]
78448fbc98cd19c69b7a193730b7953c58d7dd2f
3,297
cpp
C++
sl/Main.cpp
clagv/sl
1e0a76685acdf72085a9c6ee58a7e8926463fb15
[ "Unlicense" ]
null
null
null
sl/Main.cpp
clagv/sl
1e0a76685acdf72085a9c6ee58a7e8926463fb15
[ "Unlicense" ]
null
null
null
sl/Main.cpp
clagv/sl
1e0a76685acdf72085a9c6ee58a7e8926463fb15
[ "Unlicense" ]
null
null
null
#include "SLUtils.h" #include "SLData.h" #include "SLVector.h" #include "SLMap.h" #include "SLSet.h" #include "SLVar.h" #include <iostream> #include <iterator> #include <map> using namespace sl; typedef std::vector<std::string> StrVec; struct Lvl1 { double m_x; std::string m_a; std::string m_b; StrVec m_vec; }; ISerializablePtr makeSerializable(const std::string& key, Lvl1& lvl1) { ISerializableObjPtr wrt = createSerializableObj(key); add(wrt, "x", lvl1.m_x); add(wrt, "a", lvl1.m_a); add(wrt, "b", lvl1.m_b); add(wrt, "vec", lvl1.m_vec); return wrt; } struct Lvl2 { std::string m_c; Lvl1 m_lvl1; std::vector<StrVec> m_vecVec; std::map<std::string, StrVec> m_map; }; ISerializablePtr makeSerializable(const std::string& key, Lvl2& lvl2) { ISerializableObjPtr wrt = createSerializableObj(key); add(wrt, "c", lvl2.m_c); add(wrt, makeSerializable("1", lvl2.m_lvl1)); add(wrt, "vv", lvl2.m_vecVec); add(wrt, makeSerializable("map", lvl2.m_map)); return wrt; } int main() { SLVar var1("Very long string"); SLVar var2("Shrtstr"); var2 = var1; var1 = SLVar(2.3); std::pair<const std::string, std::string> css("abc", "d"); std::pair<std::string, std::string> ss("ef","gh"); std::pair<StrVec, std::string> svs(StrVec(2, "blah"), "ij"); std::multimap<std::string, double> mm; ISerializablePtr serMM = makeSerializable("", mm); mm.insert(std::make_pair("a", 0.5)); mm.insert(std::make_pair("a", 0.2)); IDataPtr dtmm = createEmptyData(); serMM->write(dtmm.get()); dtmm->overwriteVal("a", SLVar(0.1), 1); serMM->read(dtmm.get()); ISerializablePtr serPair; serPair = makeSerializable("", ss); serPair = makeSerializable("", svs); Lvl2 lvl2; ISerializablePtr ser = makeSerializable("", lvl2); lvl2.m_lvl1.m_x = 1.25; lvl2.m_lvl1.m_b = "abc"; lvl2.m_lvl1.m_vec.assign(2, "vec0"); lvl2.m_vecVec.assign(3, StrVec(3, "vv0")); lvl2.m_map["mapKey"] = StrVec(2, "mapVal"); IDataPtr dt = createEmptyData(); ser->write(dt.get()); dt->existingData("1", 0)->overwriteVal("x", SLVar(0.75), 0); dt->existingData("1", 0)->overwriteVal("a", SLVar("blah"), 0); dt->existingData("1", 0)->existingData("vec", 0)->overwriteVal("item", SLVar("vec1"), 1); dt->existingData("vv", 0)->existingData("item", 2)->overwriteVal("item", SLVar("vv22"), 2); dt->existingData("map", 0)->newData("mapKey2")->newVal("item", SLVar("mapVal2")); dt->overwriteVal("c", SLVar("OK"), 0); ser->read(dt.get()); std::cout << lvl2.m_lvl1.m_a << '\n'; std::cout << lvl2.m_c << '\n'; std::copy(lvl2.m_lvl1.m_vec.begin(), lvl2.m_lvl1.m_vec.end(), std::ostream_iterator<std::string>(std::cout, " ")); std::cout << '\n' << lvl2.m_vecVec.at(2).at(2) << '\n'; std::cout << (++lvl2.m_map.begin())->first << '\n'; std::cout << lvl2.m_lvl1.m_x << '\n'; std::set<std::string> strSet; makeSerializable("", strSet); IData* pd = dt->existingData("vv", 0)->existingData("item", 2); pd->begin(); pd->next(); pd->erase("item", 2); if(pd->end()) std::cout << "erase error"; pd->erase("item", 1); if(!pd->end()) std::cout << "erase error"; return 0; }
31.4
118
0.602062
[ "vector" ]
7845354f1d315dd2e25ccf80dcd0d0ed762241d2
8,514
cpp
C++
libakumuli/storage_engine/column_store.cpp
webfolderio/akumuli
e120763ffd3f7bf8094c36358d8b8600cdcccd79
[ "Apache-2.0" ]
1,094
2015-01-03T13:40:12.000Z
2022-03-29T02:28:25.000Z
libakumuli/storage_engine/column_store.cpp
webfolderio/akumuli
e120763ffd3f7bf8094c36358d8b8600cdcccd79
[ "Apache-2.0" ]
193
2015-01-30T09:25:59.000Z
2020-12-02T08:54:35.000Z
libakumuli/storage_engine/column_store.cpp
webfolderio/akumuli
e120763ffd3f7bf8094c36358d8b8600cdcccd79
[ "Apache-2.0" ]
124
2015-02-03T14:57:14.000Z
2022-03-14T14:27:37.000Z
#include "column_store.h" #include "log_iface.h" #include "status_util.h" #include "query_processing/queryplan.h" #include "operators/aggregate.h" #include "operators/scan.h" #include "operators/join.h" #include "operators/merge.h" #include <boost/property_tree/ptree.hpp> namespace Akumuli { namespace StorageEngine { using namespace QP; // ////////////// // // Column-store // // ////////////// // ColumnStore::ColumnStore(std::shared_ptr<BlockStore> bstore) : blockstore_(bstore) { } std::tuple<aku_Status, std::vector<aku_ParamId>> ColumnStore::open_or_restore( std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>> const& mapping, bool force_init) { std::vector<aku_ParamId> ids2recover; for (auto it: mapping) { aku_ParamId id = it.first; std::vector<LogicAddr> const& rescue_points = it.second; if (rescue_points.empty()) { Logger::msg(AKU_LOG_ERROR, "Empty rescue points list found, leaf-node data was lost"); } auto status = NBTreeExtentsList::repair_status(rescue_points); if (status == NBTreeExtentsList::RepairStatus::REPAIR) { Logger::msg(AKU_LOG_ERROR, "Repair needed, id=" + std::to_string(id)); } auto tree = std::make_shared<NBTreeExtentsList>(id, rescue_points, blockstore_); std::lock_guard<std::mutex> tl(table_lock_); if (columns_.count(id)) { Logger::msg(AKU_LOG_ERROR, "Can't open/repair " + std::to_string(id) + " (already exists)"); return std::make_tuple(AKU_EBAD_ARG, std::vector<aku_ParamId>()); } else { columns_[id] = std::move(tree); } if (force_init || status == NBTreeExtentsList::RepairStatus::REPAIR) { // Repair is performed on initialization. We don't want to postprone this process // since it will introduce runtime penalties. columns_[id]->force_init(); if (status == NBTreeExtentsList::RepairStatus::REPAIR) { ids2recover.push_back(id); } if (force_init == false) { // Close the tree until it will be acessed first auto rplist = columns_[id]->close(); rescue_points_[id] = std::move(rplist); } } } return std::make_tuple(AKU_SUCCESS, ids2recover); } std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>> ColumnStore::close() { // TODO: remove size_t c1_mem = 0, c2_mem = 0; for (auto it: columns_) { if (it.second->is_initialized()) { size_t c1, c2; std::tie(c1, c2) = it.second->bytes_used(); c1_mem += c1; c2_mem += c2; } } Logger::msg(AKU_LOG_INFO, "Total memory usage: " + std::to_string(c1_mem + c2_mem)); Logger::msg(AKU_LOG_INFO, "Leaf node memory usage: " + std::to_string(c1_mem)); Logger::msg(AKU_LOG_INFO, "SBlock memory usage: " + std::to_string(c2_mem)); // end TODO remove std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>> result; std::lock_guard<std::mutex> tl(table_lock_); Logger::msg(AKU_LOG_INFO, "Column-store commit called"); for (auto it: columns_) { if (it.second->is_initialized()) { auto addrlist = it.second->close(); result[it.first] = addrlist; } } Logger::msg(AKU_LOG_INFO, "Column-store commit completed"); return result; } std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>> ColumnStore::close(const std::vector<u64>& ids) { std::unordered_map<aku_ParamId, std::vector<StorageEngine::LogicAddr>> result; Logger::msg(AKU_LOG_INFO, "Column-store close specific columns"); for (auto id: ids) { std::lock_guard<std::mutex> tl(table_lock_); auto it = columns_.find(id); if (it == columns_.end()) { continue; } if (it->second->is_initialized()) { auto addrlist = it->second->close(); result[it->first] = addrlist; } } Logger::msg(AKU_LOG_INFO, "Column-store close specific columns, operation completed"); return result; } aku_Status ColumnStore::create_new_column(aku_ParamId id) { std::vector<LogicAddr> empty; auto tree = std::make_shared<NBTreeExtentsList>(id, empty, blockstore_); { std::lock_guard<std::mutex> tl(table_lock_); if (columns_.count(id)) { return AKU_EBAD_ARG; } else { columns_[id] = std::move(tree); columns_[id]->force_init(); return AKU_SUCCESS; } } } size_t ColumnStore::_get_uncommitted_memory() const { std::lock_guard<std::mutex> guard(table_lock_); size_t total_size = 0; for (auto const& p: columns_) { if (p.second->is_initialized()) { total_size += p.second->_get_uncommitted_size(); } } return total_size; } NBTreeAppendResult ColumnStore::write(aku_Sample const& sample, std::vector<LogicAddr>* rescue_points, std::unordered_map<aku_ParamId, std::shared_ptr<NBTreeExtentsList>>* cache_or_null) { std::lock_guard<std::mutex> lock(table_lock_); aku_ParamId id = sample.paramid; auto it = columns_.find(id); if (it != columns_.end()) { auto tree = it->second; NBTreeAppendResult res = NBTreeAppendResult::OK; if (AKU_LIKELY(sample.payload.type == AKU_PAYLOAD_FLOAT)) { res = tree->append(sample.timestamp, sample.payload.float64); } else if (sample.payload.type == AKU_PAYLOAD_EVENT) { u32 sz = sample.payload.size - sizeof(aku_Sample); u8 const* pdata = reinterpret_cast<u8 const*>(sample.payload.data); res = tree->append(sample.timestamp, pdata, sz); } if (res == NBTreeAppendResult::OK_FLUSH_NEEDED) { auto tmp = tree->get_roots(); rescue_points->swap(tmp); } if (cache_or_null != nullptr) { // Tree is guaranteed to be initialized here, so all values in the cache // don't need to be checked. cache_or_null->insert(std::make_pair(id, tree)); } return res; } return NBTreeAppendResult::FAIL_BAD_ID; } NBTreeAppendResult ColumnStore::recovery_write(aku_Sample const& sample, bool allow_duplicates) { std::lock_guard<std::mutex> lock(table_lock_); aku_ParamId id = sample.paramid; auto it = columns_.find(id); if (it != columns_.end()) { auto tree = it->second; return tree->append(sample.timestamp, sample.payload.float64, allow_duplicates); } return NBTreeAppendResult::FAIL_BAD_ID; } // ////////////////////// // // WriteSession // // ////////////////////// // CStoreSession::CStoreSession(std::shared_ptr<ColumnStore> registry) : cstore_(registry) { } NBTreeAppendResult CStoreSession::write(aku_Sample const& sample, std::vector<LogicAddr> *rescue_points) { if (AKU_LIKELY(sample.payload.type == AKU_PAYLOAD_FLOAT)) { // Cache lookup auto it = cache_.find(sample.paramid); if (it != cache_.end()) { auto res = it->second->append(sample.timestamp, sample.payload.float64); if (res == NBTreeAppendResult::OK_FLUSH_NEEDED) { auto tmp = it->second->get_roots(); rescue_points->swap(tmp); } return res; } // Cache miss - access global registry return cstore_->write(sample, rescue_points, &cache_); } else if (sample.payload.type == AKU_PAYLOAD_EVENT) { // Unpack event fields u32 sz = sample.payload.size - sizeof(aku_Sample); u8 const* pdata = reinterpret_cast<u8 const*>(sample.payload.data); // Cache lookup auto it = cache_.find(sample.paramid); if (it != cache_.end()) { auto res = it->second->append(sample.timestamp, pdata, sz); if (res == NBTreeAppendResult::OK_FLUSH_NEEDED) { auto tmp = it->second->get_roots(); rescue_points->swap(tmp); } return res; } return cstore_->write(sample, rescue_points, &cache_); } return NBTreeAppendResult::FAIL_BAD_VALUE; } void CStoreSession::close() { // This method can't be implemented yet, because it will waste space. // Leaf node recovery should be implemented first. } }} // namespace
36.540773
120
0.61299
[ "vector" ]
784bcd6f967aba63d23b757cbc7f681b8fe59ff5
114,523
cpp
C++
MachineLearning/Entity101/opennn/quasi_newton_method.cpp
CJBuchel/Entity101
b868ffff4ca99e240a0bf1248d5c5ebb45019426
[ "MIT" ]
null
null
null
MachineLearning/Entity101/opennn/quasi_newton_method.cpp
CJBuchel/Entity101
b868ffff4ca99e240a0bf1248d5c5ebb45019426
[ "MIT" ]
null
null
null
MachineLearning/Entity101/opennn/quasi_newton_method.cpp
CJBuchel/Entity101
b868ffff4ca99e240a0bf1248d5c5ebb45019426
[ "MIT" ]
null
null
null
/****************************************************************************************************************/ /* */ /* OpenNN: Open Neural Networks Library */ /* www.opennn.net */ /* */ /* Q U A S I - N E W T O N M E T H O D C L A S S */ /* */ /* Roberto Lopez */ /* Artelnics - Making intelligent use of data */ /* robertolopez@artelnics.com */ /* */ /****************************************************************************************************************/ // OpenNN includes #include "quasi_newton_method.h" #ifdef __OPENNN_CUDA__ #include <cuda_runtime.h> #include <cublas_v2.h> void createHandle(cublasHandle_t* handle); void destroyHandle(cublasHandle_t* handle); void initCUDA(); int mallocCUDA(double** A_d, int nBytes); int memcpyCUDA(double* A_d, const double* A_h, int nBytes); void freeCUDA(double* A_d); void dfpInverseHessian( double* old_parameters, double* parameters, double* old_gradient, double* gradient, double* old_inverse_Hessian, double* auxiliar_matrix, double* inverse_Hessian_host, int n); void bfgsInverseHessian( double* old_parameters, double* parameters, double* old_gradient, double* gradient, double* old_inverse_Hessian, double* auxiliar_matrix, double* inverse_Hessian_host, int n); #endif //#include"windows.h" namespace OpenNN { // DEFAULT CONSTRUCTOR /// Default constructor. /// It creates a quasi-Newton method training algorithm not associated to any loss functional. /// It also initializes the class members to their default values. QuasiNewtonMethod::QuasiNewtonMethod(void) : TrainingAlgorithm() { set_default(); } // PERFORMANCE FUNCTIONAL CONSTRUCTOR /// Loss index constructor. /// It creates a quasi-Newton method training algorithm associated to a loss functional. /// It also initializes the class members to their default values. /// @param new_loss_index_pointer Pointer to a loss functional object. QuasiNewtonMethod::QuasiNewtonMethod(LossIndex* new_loss_index_pointer) : TrainingAlgorithm(new_loss_index_pointer) { training_rate_algorithm.set_loss_index_pointer(new_loss_index_pointer); set_default(); } // XML CONSTRUCTOR /// XML constructor. /// It creates a quasi-Newton method training algorithm not associated to any loss functional. /// It also initializes the class members to their default values. QuasiNewtonMethod::QuasiNewtonMethod(const tinyxml2::XMLDocument& document) : TrainingAlgorithm(document) { set_default(); } // DESTRUCTOR /// Destructor. /// It does not delete any object. QuasiNewtonMethod::~QuasiNewtonMethod(void) { } // METHODS // const TrainingRateAlgorithm& get_training_rate_algorithm(void) const method /// Returns a constant reference to the training rate algorithm object inside the quasi-Newton method object. const TrainingRateAlgorithm& QuasiNewtonMethod::get_training_rate_algorithm(void) const { return(training_rate_algorithm); } // TrainingRateAlgorithm* get_training_rate_algorithm_pointer(void) method /// Returns a pointer to the training rate algorithm object inside the quasi-Newton method object. TrainingRateAlgorithm* QuasiNewtonMethod::get_training_rate_algorithm_pointer(void) { return(&training_rate_algorithm); } // const InverseHessianApproximationMethod& get_inverse_Hessian_approximation_method(void) const method /// Returns the method for approximating the inverse Hessian matrix to be used when training. const QuasiNewtonMethod::InverseHessianApproximationMethod& QuasiNewtonMethod::get_inverse_Hessian_approximation_method(void) const { return(inverse_Hessian_approximation_method); } // std::string write_inverse_Hessian_approximation_method(void) const method /// Returns the name of the method for the approximation of the inverse Hessian. std::string QuasiNewtonMethod::write_inverse_Hessian_approximation_method(void) const { switch(inverse_Hessian_approximation_method) { case DFP: { return("DFP"); } break; case BFGS: { return("BFGS"); } break; default: { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "std::string write_inverse_Hessian_approximation_method(void) const method.\n" << "Unknown inverse Hessian approximation method.\n"; throw std::logic_error(buffer.str()); } break; } } // const double& get_warning_parameters_norm(void) const method /// Returns the minimum value for the norm of the parameters vector at wich a warning message is written to the screen. const double& QuasiNewtonMethod::get_warning_parameters_norm(void) const { return(warning_parameters_norm); } // const double& get_warning_gradient_norm(void) const method /// Returns the minimum value for the norm of the gradient vector at wich a warning message is written to the screen. const double& QuasiNewtonMethod::get_warning_gradient_norm(void) const { return(warning_gradient_norm); } // const double& get_warning_training_rate(void) const method /// Returns the training rate value at wich a warning message is written to the screen during line minimization. const double& QuasiNewtonMethod::get_warning_training_rate(void) const { return(warning_training_rate); } // const double& get_error_parameters_norm(void) const method /// Returns the value for the norm of the parameters vector at wich an error message is written to the screen and the program exits. const double& QuasiNewtonMethod::get_error_parameters_norm(void) const { return(error_parameters_norm); } // const double& get_error_gradient_norm(void) const method /// Returns the value for the norm of the gradient vector at wich an error message is written /// to the screen and the program exits. const double& QuasiNewtonMethod::get_error_gradient_norm(void) const { return(error_gradient_norm); } // const double& get_error_training_rate(void) const method /// Returns the training rate value at wich the line minimization algorithm is assumed to fail when /// bracketing a minimum. const double& QuasiNewtonMethod::get_error_training_rate(void) const { return(error_training_rate); } // const double& get_minimum_parameters_increment_norm(void) const method /// Returns the minimum norm of the parameter increment vector used as a stopping criteria when training. const double& QuasiNewtonMethod::get_minimum_parameters_increment_norm(void) const { return(minimum_parameters_increment_norm); } // const double& get_minimum_loss_increase(void) const method /// Returns the minimum loss improvement during training. const double& QuasiNewtonMethod::get_minimum_loss_increase(void) const { return(minimum_loss_increase); } // const double& get_loss_goal(void) const method /// Returns the goal value for the loss. /// This is used as a stopping criterion when training a multilayer perceptron const double& QuasiNewtonMethod::get_loss_goal(void) const { return(loss_goal); } // const double& get_gradient_norm_goal(void) const method /// Returns the goal value for the norm of the objective function gradient. /// This is used as a stopping criterion when training a multilayer perceptron const double& QuasiNewtonMethod::get_gradient_norm_goal(void) const { return(gradient_norm_goal); } // const size_t& get_maximum_selection_loss_decreases(void) const method /// Returns the maximum number of selection failures during the training process. const size_t& QuasiNewtonMethod::get_maximum_selection_loss_decreases(void) const { return(maximum_selection_loss_decreases); } // const size_t& get_maximum_iterations_number(void) const method /// Returns the maximum number of iterations for training. const size_t& QuasiNewtonMethod::get_maximum_iterations_number(void) const { return(maximum_iterations_number); } // const double& get_maximum_time(void) const method /// Returns the maximum training time. const double& QuasiNewtonMethod::get_maximum_time(void) const { return(maximum_time); } // const bool& get_return_minimum_selection_error_neural_network(void) const method /// Returns true if the final model will be the neural network with the minimum selection error, false otherwise. const bool& QuasiNewtonMethod::get_return_minimum_selection_error_neural_network(void) const { return(return_minimum_selection_error_neural_network); } // const bool& get_reserve_parameters_history(void) const method /// Returns true if the parameters history matrix is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_parameters_history(void) const { return(reserve_parameters_history); } // const bool& get_reserve_parameters_norm_history(void) const method /// Returns true if the parameters norm history vector is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_parameters_norm_history(void) const { return(reserve_parameters_norm_history); } // const bool& get_reserve_loss_history(void) const method /// Returns true if the loss history vector is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_loss_history(void) const { return(reserve_loss_history); } // const bool& get_reserve_gradient_history(void) const method /// Returns true if the gradient history vector of vectors is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_gradient_history(void) const { return(reserve_gradient_history); } // const bool& get_reserve_gradient_norm_history(void) const method /// Returns true if the gradient norm history vector is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_gradient_norm_history(void) const { return(reserve_gradient_norm_history); } // const bool& get_reserve_training_direction_history(void) const method /// Returns true if the training direction history matrix is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_training_direction_history(void) const { return(reserve_training_direction_history); } // const bool& get_reserve_training_rate_history(void) const method /// Returns true if the training rate history vector is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_training_rate_history(void) const { return(reserve_training_rate_history); } // const bool& get_reserve_elapsed_time_history(void) const method /// Returns true if the elapsed time history vector is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_elapsed_time_history(void) const { return(reserve_elapsed_time_history); } // const bool& get_reserve_inverse_Hessian_history(void) const method /// Returns true if the inverse Hessian history is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_inverse_Hessian_history(void) const { return(reserve_inverse_Hessian_history); } // const bool& get_reserve_selection_loss_history(void) const method /// Returns true if the selection loss history vector is to be reserved, and false otherwise. const bool& QuasiNewtonMethod::get_reserve_selection_loss_history(void) const { return(reserve_selection_loss_history); } // void set_loss_index_pointer(LossIndex*) method /// Sets a pointer to a loss functional object to be associated to the quasi-Newton method object. /// It also sets that loss functional to the training rate algorithm. /// @param new_loss_index_pointer Pointer to a loss functional object. void QuasiNewtonMethod::set_loss_index_pointer(LossIndex* new_loss_index_pointer) { loss_index_pointer = new_loss_index_pointer; training_rate_algorithm.set_loss_index_pointer(new_loss_index_pointer); } // void set_inverse_Hessian_approximation_method(const InverseHessianApproximationMethod&) method /// Sets a new inverse Hessian approximatation method value. /// @param new_inverse_Hessian_approximation_method Inverse Hessian approximation method value. void QuasiNewtonMethod::set_inverse_Hessian_approximation_method(const QuasiNewtonMethod::InverseHessianApproximationMethod& new_inverse_Hessian_approximation_method) { inverse_Hessian_approximation_method = new_inverse_Hessian_approximation_method; } // void set_inverse_Hessian_approximation_method(const std::string&) method /// Sets a new method for approximating the inverse of the Hessian matrix from a string containing the name. /// Possible values are: /// <ul> /// <li> "DFP" /// <li> "BFGS" /// </ul> /// @param new_inverse_Hessian_approximation_method_name Name of inverse Hessian approximation method. void QuasiNewtonMethod::set_inverse_Hessian_approximation_method(const std::string& new_inverse_Hessian_approximation_method_name) { if(new_inverse_Hessian_approximation_method_name == "DFP") { inverse_Hessian_approximation_method = DFP; } else if(new_inverse_Hessian_approximation_method_name == "BFGS") { inverse_Hessian_approximation_method = BFGS; } else { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_inverse_Hessian_approximation_method(const std::string&) method.\n" << "Unknown inverse Hessian approximation method: " << new_inverse_Hessian_approximation_method_name << ".\n"; throw std::logic_error(buffer.str()); } } // void set_reserve_all_training_history(bool) method /// Makes the training history of all variables to reseved or not in memory. /// @param new_reserve_all_training_history True if the training history of all variables is to be reserved, /// false otherwise. void QuasiNewtonMethod::set_reserve_all_training_history(const bool& new_reserve_all_training_history) { reserve_elapsed_time_history = new_reserve_all_training_history; reserve_parameters_history = new_reserve_all_training_history; reserve_parameters_norm_history = new_reserve_all_training_history; reserve_loss_history = new_reserve_all_training_history; reserve_gradient_history = new_reserve_all_training_history; reserve_gradient_norm_history = new_reserve_all_training_history; reserve_training_direction_history = new_reserve_all_training_history; reserve_training_rate_history = new_reserve_all_training_history; } // void set_default(void) method void QuasiNewtonMethod::set_default(void) { inverse_Hessian_approximation_method = BFGS; training_rate_algorithm.set_default(); // TRAINING PARAMETERS warning_parameters_norm = 1.0e3; warning_gradient_norm = 1.0e3; warning_training_rate = 1.0e3; error_parameters_norm = 1.0e6; error_gradient_norm = 1.0e6; error_training_rate = 1.0e6; // STOPPING CRITERIA minimum_parameters_increment_norm = 0.0; minimum_loss_increase = 0.0; loss_goal = -1.0e99; gradient_norm_goal = 0.0; maximum_selection_loss_decreases = 1000000; maximum_iterations_number = 1000; maximum_time = 1000.0; return_minimum_selection_error_neural_network = false; // TRAINING HISTORY reserve_parameters_history = false; reserve_parameters_norm_history = false; reserve_loss_history = true; reserve_gradient_history = false; reserve_gradient_norm_history = false; reserve_selection_loss_history = false; reserve_inverse_Hessian_history = false; reserve_training_direction_history = false; reserve_training_rate_history = false; reserve_elapsed_time_history = false; // UTILITIES display = true; display_period = 5; } // void set_warning_parameters_norm(const double&) method /// Sets a new value for the parameters vector norm at which a warning message is written to the /// screen. /// @param new_warning_parameters_norm Warning norm of parameters vector value. void QuasiNewtonMethod::set_warning_parameters_norm(const double& new_warning_parameters_norm) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_warning_parameters_norm < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_warning_parameters_norm(const double&) method.\n" << "Warning parameters norm must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set warning parameters norm warning_parameters_norm = new_warning_parameters_norm; } // void set_warning_gradient_norm(const double&) method /// Sets a new value for the gradient vector norm at which /// a warning message is written to the screen. /// @param new_warning_gradient_norm Warning norm of gradient vector value. void QuasiNewtonMethod::set_warning_gradient_norm(const double& new_warning_gradient_norm) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_warning_gradient_norm < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_warning_gradient_norm(const double&) method.\n" << "Warning gradient norm must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set warning gradient norm warning_gradient_norm = new_warning_gradient_norm; } // void set_warning_training_rate(const double&) method /// Sets a new training rate value at wich a warning message is written to the screen during line /// minimization. /// @param new_warning_training_rate Warning training rate value. void QuasiNewtonMethod::set_warning_training_rate(const double& new_warning_training_rate) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_warning_training_rate < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_warning_training_rate(const double&) method.\n" << "Warning training rate must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif warning_training_rate = new_warning_training_rate; } // void set_error_parameters_norm(const double&) method /// Sets a new value for the parameters vector norm at which an error message is written to the /// screen and the program exits. /// @param new_error_parameters_norm Error norm of parameters vector value. void QuasiNewtonMethod::set_error_parameters_norm(const double& new_error_parameters_norm) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_error_parameters_norm < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_error_parameters_norm(const double&) method.\n" << "Error parameters norm must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set error parameters norm error_parameters_norm = new_error_parameters_norm; } // void set_error_gradient_norm(const double&) method /// Sets a new value for the gradient vector norm at which an error message is written to the screen /// and the program exits. /// @param new_error_gradient_norm Error norm of gradient vector value. void QuasiNewtonMethod::set_error_gradient_norm(const double& new_error_gradient_norm) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_error_gradient_norm < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_error_gradient_norm(const double&) method.\n" << "Error gradient norm must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set error gradient norm error_gradient_norm = new_error_gradient_norm; } // void set_error_training_rate(const double&) method /// Sets a new training rate value at wich a the line minimization algorithm is assumed to fail when /// bracketing a minimum. /// @param new_error_training_rate Error training rate value. void QuasiNewtonMethod::set_error_training_rate(const double& new_error_training_rate) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_error_training_rate < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_error_training_rate(const double&) method.\n" << "Error training rate must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set error training rate error_training_rate = new_error_training_rate; } // void set_minimum_parameters_increment_norm(const double&) method /// Sets a new value for the minimum parameters increment norm stopping criterion. /// @param new_minimum_parameters_increment_norm Value of norm of parameters increment norm used to stop training. void QuasiNewtonMethod::set_minimum_parameters_increment_norm(const double& new_minimum_parameters_increment_norm) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_minimum_parameters_increment_norm < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void new_minimum_parameters_increment_norm(const double&) method.\n" << "Minimum parameters increment norm must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set error training rate minimum_parameters_increment_norm = new_minimum_parameters_increment_norm; } // void set_minimum_loss_increase(const double&) method /// Sets a new minimum loss improvement during training. /// @param new_minimum_loss_increase Minimum improvement in the loss between two iterations. void QuasiNewtonMethod::set_minimum_loss_increase(const double& new_minimum_loss_increase) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_minimum_loss_increase < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_minimum_loss_increase(const double&) method.\n" << "Minimum loss improvement must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set minimum loss improvement minimum_loss_increase = new_minimum_loss_increase; } // void set_loss_goal(const double&) method /// Sets a new goal value for the loss. /// This is used as a stopping criterion when training a multilayer perceptron /// @param new_loss_goal Goal value for the loss. void QuasiNewtonMethod::set_loss_goal(const double& new_loss_goal) { loss_goal = new_loss_goal; } // void set_gradient_norm_goal(const double&) method /// Sets a new the goal value for the norm of the objective function gradient. /// This is used as a stopping criterion when training a multilayer perceptron /// @param new_gradient_norm_goal Goal value for the norm of the objective function gradient. void QuasiNewtonMethod::set_gradient_norm_goal(const double& new_gradient_norm_goal) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_gradient_norm_goal < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_gradient_norm_goal(const double&) method.\n" << "Gradient norm goal must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set gradient norm goal gradient_norm_goal = new_gradient_norm_goal; } // void set_maximum_selection_loss_decreases(const size_t&) method /// Sets a new maximum number of selection failures. /// @param new_maximum_selection_loss_decreases Maximum number of iterations in which the selection evalutation decreases. void QuasiNewtonMethod::set_maximum_selection_loss_decreases(const size_t& new_maximum_selection_loss_decreases) { // Set maximum selection performace decrases maximum_selection_loss_decreases = new_maximum_selection_loss_decreases; } // void set_maximum_iterations_number(size_t) method /// Sets a maximum number of iterations for training. /// @param new_maximum_iterations_number Maximum number of iterations for training. void QuasiNewtonMethod::set_maximum_iterations_number(const size_t& new_maximum_iterations_number) { // Set maximum iterations number maximum_iterations_number = new_maximum_iterations_number; } // void set_maximum_time(const double&) method /// Sets a new maximum training time. /// @param new_maximum_time Maximum training time. void QuasiNewtonMethod::set_maximum_time(const double& new_maximum_time) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_maximum_time < 0.0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_maximum_time(const double&) method.\n" << "Maximum time must be equal or greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif // Set maximum time maximum_time = new_maximum_time; } // void set_return_minimum_selection_error_neural_network(const bool&) method /// Makes the minimum selection error neural network of all the iterations to be returned or not. /// @param new_return_minimum_selection_error_neural_network True if the final model will be the neural network with the minimum selection error, false otherwise. void QuasiNewtonMethod::set_return_minimum_selection_error_neural_network(const bool& new_return_minimum_selection_error_neural_network) { return_minimum_selection_error_neural_network = new_return_minimum_selection_error_neural_network; } // void set_reserve_parameters_history(bool) method /// Makes the parameters history vector of vectors to be reseved or not in memory. /// @param new_reserve_parameters_history True if the parameters history vector of vectors is to be reserved, false otherwise. void QuasiNewtonMethod::set_reserve_parameters_history(const bool& new_reserve_parameters_history) { reserve_parameters_history = new_reserve_parameters_history; } // void set_reserve_parameters_norm_history(bool) method /// Makes the parameters norm history vector to be reseved or not in memory. /// @param new_reserve_parameters_norm_history True if the parameters norm history vector is to be reserved, false otherwise. void QuasiNewtonMethod::set_reserve_parameters_norm_history(const bool& new_reserve_parameters_norm_history) { reserve_parameters_norm_history = new_reserve_parameters_norm_history; } // void set_reserve_loss_history(bool) method /// Makes the loss history vector to be reseved or not in memory. /// @param new_reserve_loss_history True if the loss history vector is to be reserved, false otherwise. void QuasiNewtonMethod::set_reserve_loss_history(const bool& new_reserve_loss_history) { reserve_loss_history = new_reserve_loss_history; } // void set_reserve_gradient_history(bool) method /// Makes the gradient history vector of vectors to be reseved or not in memory. /// @param new_reserve_gradient_history True if the gradient history matrix is to be reserved, false otherwise. void QuasiNewtonMethod::set_reserve_gradient_history(const bool& new_reserve_gradient_history) { reserve_gradient_history = new_reserve_gradient_history; } // void set_reserve_gradient_norm_history(bool) method /// Makes the gradient norm history vector to be reseved or not in memory. /// @param new_reserve_gradient_norm_history True if the gradient norm history matrix is to be reserved, false /// otherwise. void QuasiNewtonMethod::set_reserve_gradient_norm_history(const bool& new_reserve_gradient_norm_history) { reserve_gradient_norm_history = new_reserve_gradient_norm_history; } // void set_reserve_inverse_Hessian_history(bool) method /// Sets the history of the inverse of the Hessian matrix to be reserved or not in memory. /// This is a vector of matrices. /// @param new_reserve_inverse_Hessian_history True if the inverse Hessian history is to be reserved, false otherwise. void QuasiNewtonMethod::set_reserve_inverse_Hessian_history(const bool& new_reserve_inverse_Hessian_history) { reserve_inverse_Hessian_history = new_reserve_inverse_Hessian_history; } // void set_reserve_training_direction_history(bool) method /// Makes the training direction history vector of vectors to be reseved or not in memory. /// @param new_reserve_training_direction_history True if the training direction history matrix is to be reserved, /// false otherwise. void QuasiNewtonMethod::set_reserve_training_direction_history(const bool& new_reserve_training_direction_history) { reserve_training_direction_history = new_reserve_training_direction_history; } // void set_reserve_training_rate_history(bool) method /// Makes the training rate history vector to be reseved or not in memory. /// @param new_reserve_training_rate_history True if the training rate history vector is to be reserved, false /// otherwise. void QuasiNewtonMethod::set_reserve_training_rate_history(const bool& new_reserve_training_rate_history) { reserve_training_rate_history = new_reserve_training_rate_history; } // void set_reserve_elapsed_time_history(bool) method /// Makes the elapsed time over the iterations to be reseved or not in memory. This is a vector. /// @param new_reserve_elapsed_time_history True if the elapsed time history vector is to be reserved, false /// otherwise. void QuasiNewtonMethod::set_reserve_elapsed_time_history(const bool& new_reserve_elapsed_time_history) { reserve_elapsed_time_history = new_reserve_elapsed_time_history; } // void set_reserve_selection_loss_history(bool) method /// Makes the selection loss history to be reserved or not in memory. /// This is a vector. /// @param new_reserve_selection_loss_history True if the selection loss history is to be reserved, false otherwise. void QuasiNewtonMethod::set_reserve_selection_loss_history(const bool& new_reserve_selection_loss_history) { reserve_selection_loss_history = new_reserve_selection_loss_history; } // void set_display_period(const size_t&) method /// Sets a new number of iterations between the training showing progress. /// @param new_display_period /// Number of iterations between the training showing progress. void QuasiNewtonMethod::set_display_period(const size_t& new_display_period) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(new_display_period == 0) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void set_display_period(const size_t&) method.\n" << "Display period must be greater than 0.\n"; throw std::logic_error(buffer.str()); } #endif display_period = new_display_period; } // Vector<double> calculate_inverse_Hessian_approximation( // const Vector<double>&, const Vector<double>&, // const Vector<double>&, const Vector<double>&, // const Matrix<double>&) method /// Calculates an approximation of the inverse Hessian, accoring to the method used. /// @param old_parameters Another point of the objective function. /// @param parameters Current point of the objective function /// @param old_gradient Gradient at the other point. /// @param gradient Gradient at the current point. /// @param old_inverse_Hessian Inverse Hessian at the other point of the objective function. Matrix<double> QuasiNewtonMethod::calculate_inverse_Hessian_approximation( const Vector<double>& old_parameters, const Vector<double>& parameters, const Vector<double>& old_gradient, const Vector<double>& gradient, const Matrix<double>& old_inverse_Hessian) const { switch(inverse_Hessian_approximation_method) { case DFP: { return(calculate_DFP_inverse_Hessian(old_parameters, parameters, old_gradient, gradient, old_inverse_Hessian)); } break; case BFGS: { return(calculate_BFGS_inverse_Hessian(old_parameters, parameters, old_gradient, gradient, old_inverse_Hessian)); } break; default: { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Vector<double> calculate_inverse_Hessian_approximation(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Unknown inverse Hessian approximation method.\n"; throw std::logic_error(buffer.str()); } break; } } #ifdef __OPENNN_CUDA__ // Matrix<double> calculate_inverse_Hessian_approximation_CUDA(double*, double*, double*, double*, double*, double*) const method /// Calculates an approximation of the inverse Hessian, accoring to the method used. This method uses CUDA. /// @param old_parameters_d Another point of the objective function. /// @param parameters_d Current point of the objective function /// @param old_gradient_d Gradient at the other point. /// @param gradient_d Gradient at the current point. /// @param old_inverse_Hessian_d Inverse Hessian at the other point of the objective function. /// @param auxiliar_matrix_d Auxiliar empty matrix used in the CUDA computation. Matrix<double> QuasiNewtonMethod::calculate_inverse_Hessian_approximation_CUDA( double* old_parameters_d, double* parameters_d, double* old_gradient_d, double* gradient_d, double* old_inverse_Hessian_d, double* auxiliar_matrix_d) const { switch(inverse_Hessian_approximation_method) { case DFP: { return(calculate_DFP_inverse_Hessian_CUDA(old_parameters_d, parameters_d, old_gradient_d, gradient_d, old_inverse_Hessian_d, auxiliar_matrix_d)); } break; case BFGS: { return(calculate_BFGS_inverse_Hessian_CUDA(old_parameters_d, parameters_d, old_gradient_d, gradient_d, old_inverse_Hessian_d, auxiliar_matrix_d)); } break; default: { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Vector<double> calculate_inverse_Hessian_approximation_CUDA(const double*, const double*, const double*, const double*, const double*) method.\n" << "Unknown inverse Hessian approximation method.\n"; throw std::logic_error(buffer.str()); } break; } } #endif // Vector<double> calculate_training_direction(const Vector<double>&, const Matrix<double>&) const method /// Returns the quasi-Newton method training direction, which has been previously normalized. /// @param gradient Gradient vector. /// @param inverse_Hessian_approximation Inverse Hessian approximation matrix. Vector<double> QuasiNewtonMethod::calculate_training_direction(const Vector<double>& gradient, const Matrix<double>& inverse_Hessian_approximation) const { return((inverse_Hessian_approximation.dot(gradient)*(-1.0)).calculate_normalized()); } // Vector<double> calculate_gradient_descent_training_direction(const Vector<double>&) const method /// Returns the gradient descent training direction, which is the negative of the normalized gradient. /// @param gradient Gradient vector. Vector<double> QuasiNewtonMethod::calculate_gradient_descent_training_direction(const Vector<double>& gradient) const { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ std::ostringstream buffer; if(!loss_index_pointer) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Vector<double> calculate_gradient_descent_training_direction(const Vector<double>&) const method.\n" << "Loss index pointer is NULL.\n"; throw std::logic_error(buffer.str()); } #endif #ifdef __OPENNN_DEBUG__ const NeuralNetwork* neural_network_pointer = loss_index_pointer->get_neural_network_pointer(); const size_t gradient_size = gradient.size(); const size_t parameters_number = neural_network_pointer->count_parameters_number(); if(gradient_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Vector<double> calculate_gradient_descent_training_direction(const Vector<double>&) const method.\n" << "Size of gradient (" << gradient_size << ") is not equal to number of parameters (" << parameters_number << ").\n"; throw std::logic_error(buffer.str()); } #endif return(gradient.calculate_normalized()*(-1.0)); } // Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method /// Returns an approximation of the inverse Hessian matrix according to the Davidon-Fletcher-Powel /// (DFP) algorithm. /// @param old_parameters A previous set of parameters. /// @param old_gradient The gradient of the objective function for that previous set of parameters. /// @param old_inverse_Hessian The Hessian of the objective function for that previous set of parameters. /// @param parameters Actual set of parameters. /// @param gradient The gradient of the objective function for the actual set of parameters. Matrix<double> QuasiNewtonMethod::calculate_DFP_inverse_Hessian( const Vector<double>& old_parameters, const Vector<double>& parameters, const Vector<double>& old_gradient, const Vector<double>& gradient, const Matrix<double>& old_inverse_Hessian) const { std::ostringstream buffer; // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ const NeuralNetwork* neural_network_pointer = loss_index_pointer->get_neural_network_pointer(); const size_t parameters_number = neural_network_pointer->count_parameters_number(); const size_t old_parameters_size = old_parameters.size(); const size_t parameters_size = parameters.size(); if(old_parameters_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Size of old parameters vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } else if(parameters_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Size of parameters vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } const size_t old_gradient_size = old_gradient.size(); const size_t gradient_size = gradient.size(); if(old_gradient_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Size of old gradient vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } else if(gradient_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Size of gradient vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } const size_t rows_number = old_inverse_Hessian.get_rows_number(); const size_t columns_number = old_inverse_Hessian.get_columns_number(); if(rows_number != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Number of rows in old inverse Hessian must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } else if(columns_number != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Number of columns in old inverse Hessian must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } #endif // Parameters difference Vector const Vector<double> parameters_difference = parameters - old_parameters; // Control sentence (if debug) if(parameters_difference.calculate_absolute_value() < 1.0e-99) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Parameters difference vector is zero.\n"; throw std::logic_error(buffer.str()); } // Gradient difference Vector const Vector<double> gradient_difference = gradient - old_gradient; if(gradient_difference.calculate_absolute_value() < 1.0e-50) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Gradient difference vector is zero.\n"; throw std::logic_error(buffer.str()); } if(old_inverse_Hessian.calculate_absolute_value() < 1.0e-50) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Old inverse Hessian matrix is zero.\n"; throw std::logic_error(buffer.str()); } if(fabs(parameters_difference.dot(gradient_difference)) < 1.0e-50) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Denominator of first term is zero.\n"; throw std::logic_error(buffer.str()); } else if(fabs(gradient_difference.dot(old_inverse_Hessian).dot(gradient_difference)) < 1.0e-50) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_DFP_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Denominator of second term is zero.\n"; throw std::logic_error(buffer.str()); } Matrix<double> inverse_Hessian_approximation = old_inverse_Hessian; const Vector<double> Hessian_dot_gradient_difference = old_inverse_Hessian.dot(gradient_difference); inverse_Hessian_approximation += parameters_difference.direct(parameters_difference)/parameters_difference.dot(gradient_difference); inverse_Hessian_approximation -= (Hessian_dot_gradient_difference).direct(Hessian_dot_gradient_difference) /gradient_difference.dot(Hessian_dot_gradient_difference); return(inverse_Hessian_approximation); } // Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Matrix<double>&, const Vector<double>&, const Vector<double>&) method /// Returns an approximation of the inverse Hessian matrix according to the /// Broyden-Fletcher-Goldfarb-Shanno (BGFS) algorithm. /// @param old_parameters A previous set of parameters. /// @param old_gradient The gradient of the objective function for that previous set of parameters. /// @param old_inverse_Hessian The Hessian of the objective function for that previous set of parameters. /// @param parameters Actual set of parameters. /// @param gradient The gradient of the objective function for the actual set of parameters. Matrix<double> QuasiNewtonMethod::calculate_BFGS_inverse_Hessian( const Vector<double>& old_parameters, const Vector<double>& parameters, const Vector<double>& old_gradient, const Vector<double>& gradient, const Matrix<double>& old_inverse_Hessian) const { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ std::ostringstream buffer; const NeuralNetwork* neural_network_pointer = loss_index_pointer->get_neural_network_pointer(); const size_t parameters_number = neural_network_pointer->count_parameters_number(); const size_t old_parameters_size = old_parameters.size(); const size_t parameters_size = parameters.size(); if(old_parameters_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Size of old parameters vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } else if(parameters_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Size of parameters vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } const size_t old_gradient_size = old_gradient.size(); if(old_gradient_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method." << std::endl << "Size of old gradient vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } const size_t gradient_size = gradient.size(); if(gradient_size != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method." << std::endl << "Size of gradient vector must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } const size_t rows_number = old_inverse_Hessian.get_rows_number(); const size_t columns_number = old_inverse_Hessian.get_columns_number(); if(rows_number != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Number of rows in old inverse Hessian must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } if(columns_number != parameters_number) { buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Number of columns in old inverse Hessian must be equal to number of parameters.\n"; throw std::logic_error(buffer.str()); } #endif // Parameters difference Vector const Vector<double> parameters_difference = parameters - old_parameters; if(parameters_difference.calculate_absolute_value() < 1.0e-50) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Parameters difference vector is zero.\n"; throw std::logic_error(buffer.str()); } // Gradient difference Vector const Vector<double> gradient_difference = gradient - old_gradient; if(gradient_difference.calculate_absolute_value() < 1.0e-99) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Gradient difference vector is zero.\n"; throw std::logic_error(buffer.str()); } if(old_inverse_Hessian.calculate_absolute_value() < 1.0e-50) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "Matrix<double> calculate_BFGS_inverse_Hessian(const Vector<double>&, const Vector<double>&, const Vector<double>&, const Vector<double>&, const Matrix<double>&) method.\n" << "Old inverse Hessian matrix is zero.\n"; throw std::logic_error(buffer.str()); } // BGFS Vector const double parameters_dot_gradient = parameters_difference.dot(gradient_difference); const Vector<double> Hessian_dot_gradient = old_inverse_Hessian.dot(gradient_difference); const double gradient_dot_Hessian_dot_gradient = gradient_difference.dot(Hessian_dot_gradient); const Vector<double> BFGS = parameters_difference/parameters_dot_gradient - Hessian_dot_gradient /gradient_dot_Hessian_dot_gradient; // Calculate inverse Hessian approximation Matrix<double> inverse_Hessian_approximation = old_inverse_Hessian; inverse_Hessian_approximation += parameters_difference.direct(parameters_difference)/parameters_dot_gradient; inverse_Hessian_approximation -= (Hessian_dot_gradient).direct(Hessian_dot_gradient) /gradient_dot_Hessian_dot_gradient; inverse_Hessian_approximation += (BFGS.direct(BFGS))*(gradient_dot_Hessian_dot_gradient); return(inverse_Hessian_approximation); } #ifdef __OPENNN_CUDA__ // Matrix<double> calculate_DFP_inverse_Hessian_CUDA(double*, double*, double*, double*, double*, double*) const method /// Returns an approximation of the inverse Hessian matrix according to the Davidon-Fletcher-Powel /// (DFP) algorithm. This method uses CUDA. /// @param old_parameters_d A previous set of parameters. /// @param parameters_d Actual set of parameters. /// @param old_gradient_d The gradient of the objective function for that previous set of parameters. /// @param gradient_d The gradient of the objective function for the actual set of parameters. /// @param old_inverse_Hessian The Hessian of the objective function for that previous set of parameters. /// @param auxiliar_matrix_d Auxiliar empty matrix used in the CUDA computation. Matrix<double> QuasiNewtonMethod::calculate_DFP_inverse_Hessian_CUDA( double* old_parameters_d, double* parameters_d, double* old_gradient_d, double* gradient_d, double* old_inverse_Hessian_d, double* auxiliar_matrix_d) const { const size_t parameters_number = loss_index_pointer->get_neural_network_pointer()->count_parameters_number(); Matrix<double> inverse_Hessian_approximation(parameters_number, parameters_number); double* inverse_Hessian_approximation_data = inverse_Hessian_approximation.data(); dfpInverseHessian(old_parameters_d, parameters_d, old_gradient_d, gradient_d, old_inverse_Hessian_d, auxiliar_matrix_d, inverse_Hessian_approximation_data, (int)parameters_number); return(inverse_Hessian_approximation); } // Matrix<double> calculate_BFGS_inverse_Hessian_CUDA(double*, double*, double*, double*, double*, double*) const method /// Returns an approximation of the inverse Hessian matrix according to the /// Broyden-Fletcher-Goldfarb-Shanno (BGFS) algorithm. This method uses CUDA. /// @param old_parameters_d A previous set of parameters. /// @param parameters_d Actual set of parameters. /// @param old_gradient_d The gradient of the objective function for that previous set of parameters. /// @param gradient_d The gradient of the objective function for the actual set of parameters. /// @param old_inverse_Hessian The Hessian of the objective function for that previous set of parameters. /// @param auxiliar_matrix_d Auxiliar empty matrix used in the CUDA computation. Matrix<double> QuasiNewtonMethod::calculate_BFGS_inverse_Hessian_CUDA( double* old_parameters_d, double* parameters_d, double* old_gradient_d, double* gradient_d, double* old_inverse_Hessian_d, double* auxiliar_matrix_d) const { const size_t parameters_number = loss_index_pointer->get_neural_network_pointer()->count_parameters_number(); Matrix<double> inverse_Hessian_approximation(parameters_number, parameters_number); double* inverse_Hessian_approximation_data = inverse_Hessian_approximation.data(); bfgsInverseHessian(old_parameters_d, parameters_d, old_gradient_d, gradient_d, old_inverse_Hessian_d, auxiliar_matrix_d, inverse_Hessian_approximation_data, (int)parameters_number); return(inverse_Hessian_approximation); } #endif // QuasiNewtonMethod* get_quasi_Newton_method_pointer(void) const method /// Returns the pointer to the quasi-Newton method object required by the corresponding results structure. QuasiNewtonMethod* QuasiNewtonMethod::QuasiNewtonMethodResults::get_quasi_Newton_method_pointer(void) const { return(quasi_Newton_method_pointer); } // void set_quasi_Newton_method_pointer(QuasiNewtonMethod*) method /// Returns the pointer to the quasi-Newton method object required by the corresponding results structure. void QuasiNewtonMethod::QuasiNewtonMethodResults::set_quasi_Newton_method_pointer(QuasiNewtonMethod* new_quasi_Newton_method_pointer) { quasi_Newton_method_pointer = new_quasi_Newton_method_pointer; } // void resize_training_history(const size_t&) method /// Resizes all the training history variables. /// @param new_size Size of training history variables. void QuasiNewtonMethod::QuasiNewtonMethodResults::resize_training_history(const size_t& new_size) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ if(quasi_Newton_method_pointer == NULL) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethodResults structure.\n" << "void resize_training_history(const size_t&) method.\n" << "Quasi-Newton method pointer is NULL.\n"; throw std::logic_error(buffer.str()); } #endif if(quasi_Newton_method_pointer->get_reserve_parameters_history()) { parameters_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_parameters_norm_history()) { parameters_norm_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_loss_history()) { loss_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_selection_loss_history()) { selection_loss_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_gradient_history()) { gradient_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_gradient_norm_history()) { gradient_norm_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_inverse_Hessian_history()) { inverse_Hessian_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_training_direction_history()) { training_direction_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_training_rate_history()) { training_rate_history.resize(new_size); } if(quasi_Newton_method_pointer->get_reserve_elapsed_time_history()) { elapsed_time_history.resize(new_size); } } // std::string to_string(void) const method /// Returns a string representation of the current quasi-Newton method results structure. std::string QuasiNewtonMethod::QuasiNewtonMethodResults::to_string(void) const { std::ostringstream buffer; buffer << "% Quasi-Newton method results\n"; // Parameters history if(!parameters_history.empty()) { if(!parameters_history[0].empty()) { buffer << "% Parameters history:\n" << parameters_history << "\n"; } } // Parameters norm history if(!parameters_norm_history.empty()) { buffer << "% Parameters norm history:\n" << parameters_norm_history << "\n"; } // Performance history if(!loss_history.empty()) { buffer << "% Performance history:\n" << loss_history << "\n"; } // Selection loss history if(!selection_loss_history.empty()) { buffer << "% Selection loss history:\n" << selection_loss_history << "\n"; } // Gradient history if(!gradient_history.empty()) { if(!gradient_history[0].empty()) { buffer << "% Gradient history:\n" << gradient_history << "\n"; } } // Gradient norm history if(!gradient_norm_history.empty()) { buffer << "% Gradient norm history:\n" << gradient_norm_history << "\n"; } // Inverse Hessian history if(!inverse_Hessian_history.empty()) { if(!inverse_Hessian_history[0].empty()) { buffer << "% Inverse Hessian history:\n" << inverse_Hessian_history << "\n"; } } // Training direction history if(!training_direction_history.empty()) { if(!training_direction_history[0].empty()) { buffer << "% Training direction history:\n" << training_direction_history << "\n"; } } // Training rate history if(!training_rate_history.empty()) { buffer << "% Training rate history:\n" << training_rate_history << "\n"; } // Elapsed time history if(!elapsed_time_history.empty()) { buffer << "% Elapsed time history:\n" << elapsed_time_history << "\n"; } return(buffer.str()); } // Matrix<std::string> write_final_results(const size_t& precision) const method Matrix<std::string> QuasiNewtonMethod::QuasiNewtonMethodResults::write_final_results(const size_t& precision) const { std::ostringstream buffer; Vector<std::string> names; Vector<std::string> values; // Final parameters norm names.push_back("Final parameters norm"); buffer.str(""); buffer << std::setprecision(precision) << final_parameters_norm; values.push_back(buffer.str()); // Final loss names.push_back("Final loss"); buffer.str(""); buffer << std::setprecision(precision) << final_loss; values.push_back(buffer.str()); // Final selection loss const LossIndex* loss_index_pointer = quasi_Newton_method_pointer->get_loss_index_pointer(); if(loss_index_pointer->has_selection()) { names.push_back("Final selection loss"); buffer.str(""); buffer << std::setprecision(precision) << final_selection_loss; values.push_back(buffer.str()); } // Final gradient norm names.push_back("Final gradient norm"); buffer.str(""); buffer << std::setprecision(precision) << final_gradient_norm; values.push_back(buffer.str()); // Final training rate // names.push_back("Final training rate"); // buffer.str(""); // buffer << std::setprecision(precision) << final_training_rate; // values.push_back(buffer.str()); // Iterations number names.push_back("Iterations number"); buffer.str(""); buffer << iterations_number; values.push_back(buffer.str()); // Elapsed time names.push_back("Elapsed time"); buffer.str(""); buffer << elapsed_time; values.push_back(buffer.str()); // Stopping criteria names.push_back("Stopping criterion"); values.push_back(write_stopping_condition()); const size_t rows_number = names.size(); const size_t columns_number = 2; Matrix<std::string> final_results(rows_number, columns_number); final_results.set_column(0, names); final_results.set_column(1, values); return(final_results); } // QuasiNewtonMethodResults* perform_training(void) method /// Trains a neural network with an associated loss functional according to the quasi-Newton method. /// Training occurs according to the training operators, training parameters and stopping criteria. QuasiNewtonMethod::QuasiNewtonMethodResults* QuasiNewtonMethod::perform_training(void) { // Control sentence (if debug) #ifdef __OPENNN_DEBUG__ check(); #endif // Start training if(display) { std::cout << "Training with quasi-Newton method...\n"; } QuasiNewtonMethodResults* results_pointer = new QuasiNewtonMethodResults(this); results_pointer->resize_training_history(1+maximum_iterations_number); // Neural network stuff NeuralNetwork* neural_network_pointer = loss_index_pointer->get_neural_network_pointer(); const size_t parameters_number = neural_network_pointer->count_parameters_number(); Vector<double> parameters(parameters_number); Vector<double> old_parameters(parameters_number); double parameters_norm; Vector<double> parameters_increment(parameters_number); double parameters_increment_norm; // Loss index stuff double loss = 0.0; double old_loss = 0.0; double loss_increase = 0.0; Vector<double> gradient(parameters_number); Vector<double> old_gradient(parameters_number); double gradient_norm; Matrix<double> inverse_Hessian(parameters_number, parameters_number); Matrix<double> old_inverse_Hessian(parameters_number, parameters_number); #ifdef __OPENNN_CUDA__ double* parameters_data = parameters.data(); double* old_parameters_data = old_parameters.data(); double* gradient_data = gradient.data(); double* old_gradient_data = old_gradient.data(); double* old_inverse_Hessian_data = old_inverse_Hessian.data(); double* parameters_d; double* old_parameters_d; double* gradient_d; double* old_gradient_d; double* auxiliar_matrix_d; double* old_inverse_Hessian_d; const int num_bytes = (int)parameters_number * sizeof(double); int error; int deviceCount; int gpuDeviceCount = 0; struct cudaDeviceProp properties; cudaError_t cudaResultCode = cudaGetDeviceCount(&deviceCount); if (cudaResultCode != cudaSuccess) { deviceCount = 0; } for (int device = 0; device < deviceCount; ++device) { cudaGetDeviceProperties(&properties, device); if (properties.major != 9999) /* 9999 means emulation only */ { ++gpuDeviceCount; } else if (properties.major > 3) { ++gpuDeviceCount; } else if (properties.major == 3 && properties.minor >= 5) { ++gpuDeviceCount; } } if (gpuDeviceCount > 0) { initCUDA(); //createHandle(&cublas_handle); error = mallocCUDA(&parameters_d, num_bytes); if (error != 0) { gpuDeviceCount = 0; } error = mallocCUDA(&old_parameters_d, num_bytes); if (error != 0) { gpuDeviceCount = 0; } error = mallocCUDA(&gradient_d, num_bytes); if (error != 0) { gpuDeviceCount = 0; } error = mallocCUDA(&old_gradient_d, num_bytes); if (error != 0) { gpuDeviceCount = 0; } error = mallocCUDA(&auxiliar_matrix_d, (int)parameters_number * num_bytes); if (error != 0) { gpuDeviceCount = 0; } error = mallocCUDA(&old_inverse_Hessian_d, (int)parameters_number * num_bytes); if (error != 0) { gpuDeviceCount = 0; } } #endif double selection_loss = 0.0; double old_selection_loss = 0.0; // Training algorithm stuff Vector<double> training_direction(parameters_number); double training_slope; // const double& first_training_rate = training_rate_algorithm.get_first_training_rate(); const double first_training_rate = 0.01; double initial_training_rate = 0.0; double training_rate = 0.0; double old_training_rate = 0.0; Vector<double> directional_point(2); directional_point[0] = 0.0; directional_point[1] = 0.0; Vector<double> minimum_selection_error_parameters; double minimum_selection_error; bool stop_training = false; size_t selection_failures = 0; time_t beginning_time, current_time; time(&beginning_time); double elapsed_time; size_t iteration; // Main loop for(iteration = 0; iteration <= maximum_iterations_number; iteration++) { // Neural network parameters = neural_network_pointer->arrange_parameters(); parameters_norm = parameters.calculate_norm(); if(display && parameters_norm >= warning_parameters_norm) { std::cout << "OpenNN Warning: Parameters norm is " << parameters_norm << ".\n"; } // Loss index stuff if(iteration == 0) { loss = loss_index_pointer->calculate_loss(); loss_increase = 0.0; } else { loss = directional_point[1]; loss_increase = old_loss - loss; } gradient = loss_index_pointer->calculate_gradient(); gradient_norm = gradient.calculate_norm(); if(display && gradient_norm >= warning_gradient_norm) { std::cout << "OpenNN Warning: Gradient norm is " << gradient_norm << ".\n"; } if(iteration == 0 || (old_parameters - parameters).calculate_absolute_value() < 1.0e-99 || (old_gradient - gradient).calculate_absolute_value() < 1.0e-99) { inverse_Hessian.initialize_identity(); } else { #ifdef __OPENNN_CUDA__ if (gpuDeviceCount > 0) { error += memcpyCUDA(old_parameters_d, old_parameters_data, num_bytes); error += memcpyCUDA(parameters_d, parameters_data, num_bytes); error += memcpyCUDA(old_gradient_d, old_gradient_data, num_bytes); error += memcpyCUDA(gradient_d, gradient_data, num_bytes); error += memcpyCUDA(old_inverse_Hessian_d, old_inverse_Hessian_data, (int)parameters_number * num_bytes); if (error != 0) { inverse_Hessian = calculate_inverse_Hessian_approximation(old_parameters, parameters, old_gradient, gradient, old_inverse_Hessian); error = 0; } else { inverse_Hessian = calculate_inverse_Hessian_approximation_CUDA(old_parameters_d, parameters_d, old_gradient_d, gradient_d, old_inverse_Hessian_d, auxiliar_matrix_d); } } else { inverse_Hessian = calculate_inverse_Hessian_approximation(old_parameters, parameters, old_gradient, gradient, old_inverse_Hessian); } #else inverse_Hessian = calculate_inverse_Hessian_approximation(old_parameters, parameters, old_gradient, gradient, old_inverse_Hessian); #endif } selection_loss = loss_index_pointer->calculate_selection_loss(); if(iteration == 0) { minimum_selection_error = selection_loss; minimum_selection_error_parameters = neural_network_pointer->arrange_parameters(); } else if(iteration != 0 && selection_loss > old_selection_loss) { selection_failures++; } else if(selection_loss < minimum_selection_error) { minimum_selection_error = selection_loss; minimum_selection_error_parameters = neural_network_pointer->arrange_parameters(); } // Training algorithm training_direction = calculate_training_direction(gradient, inverse_Hessian); // Calculate loss training slope training_slope = (gradient/gradient_norm).dot(training_direction); // Check for a descent direction if(training_slope >= 0.0) { // Reset training direction training_direction = calculate_gradient_descent_training_direction(gradient); } // Get initial training rate if(iteration == 0) { initial_training_rate = first_training_rate; } else { initial_training_rate = old_training_rate; } directional_point = training_rate_algorithm.calculate_directional_point(loss, training_direction, initial_training_rate); training_rate = directional_point[0]; // Reset training direction when training rate is 0 if(iteration != 0 && training_rate < 1.0e-99) { training_direction = calculate_gradient_descent_training_direction(gradient); directional_point = training_rate_algorithm.calculate_directional_point(loss, training_direction, first_training_rate); training_rate = directional_point[0]; } parameters_increment = training_direction*training_rate; parameters_increment_norm = parameters_increment.calculate_norm(); // Elapsed time time(&current_time); elapsed_time = difftime(current_time, beginning_time); // Training history neural neural network if(reserve_parameters_history) { results_pointer->parameters_history[iteration] = parameters; } if(reserve_parameters_norm_history) { results_pointer->parameters_norm_history[iteration] = parameters_norm; } if(reserve_loss_history) { results_pointer->loss_history[iteration] = loss; } if(reserve_selection_loss_history) { results_pointer->selection_loss_history[iteration] = selection_loss; } if(reserve_gradient_history) { results_pointer->gradient_history[iteration] = gradient; } if(reserve_gradient_norm_history) { results_pointer->gradient_norm_history[iteration] = gradient_norm; } if(reserve_inverse_Hessian_history) { results_pointer->inverse_Hessian_history[iteration] = inverse_Hessian; } // Training history training algorithm if(reserve_training_direction_history) { results_pointer->training_direction_history[iteration] = training_direction; } if(reserve_training_rate_history) { results_pointer->training_rate_history[iteration] = training_rate; } if(reserve_elapsed_time_history) { results_pointer->elapsed_time_history[iteration] = elapsed_time; } // Stopping Criteria if(parameters_increment_norm <= minimum_parameters_increment_norm) { if(display) { std::cout << "Iteration " << iteration << ": Minimum parameters increment norm reached.\n" << "Parameters increment norm: " << parameters_increment_norm << std::endl; } stop_training = true; results_pointer->stopping_condition = MinimumParametersIncrementNorm; } else if(iteration != 0 && loss_increase <= minimum_loss_increase) { if(display) { std::cout << "Iteration " << iteration << ": Minimum loss increase reached.\n" << "Performance increase: " << loss_increase << std::endl; } stop_training = true; results_pointer->stopping_condition = MinimumPerformanceIncrease; } else if(loss <= loss_goal) { if(display) { std::cout << "Iteration " << iteration << ": Performance goal reached.\n"; } stop_training = true; results_pointer->stopping_condition = PerformanceGoal; } else if(gradient_norm <= gradient_norm_goal) { if(display) { std::cout << "Iteration " << iteration << ": Gradient norm goal reached.\n"; } stop_training = true; results_pointer->stopping_condition = GradientNormGoal; } else if(selection_failures >= maximum_selection_loss_decreases) { if(display) { std::cout << "Iteration " << iteration << ": Maximum selection loss increases reached.\n" << "Selection loss increases: "<< selection_failures << std::endl; } stop_training = true; results_pointer->stopping_condition = MaximumSelectionPerformanceDecreases; } else if(iteration == maximum_iterations_number) { if(display) { std::cout << "Iteration " << iteration << ": Maximum number of iterations reached.\n"; } stop_training = true; results_pointer->stopping_condition = MaximumIterationsNumber; } else if(elapsed_time >= maximum_time) { if(display) { std::cout << "Iteration " << iteration << ": Maximum training time reached.\n"; } stop_training = true; results_pointer->stopping_condition = MaximumTime; } if(iteration != 0 && iteration % save_period == 0) { neural_network_pointer->save(neural_network_file_name); } if(stop_training) { results_pointer->final_parameters = parameters; results_pointer->final_parameters_norm = parameters_norm; results_pointer->final_loss = loss; results_pointer->final_selection_loss = selection_loss; results_pointer->final_gradient = gradient; results_pointer->final_gradient_norm = gradient_norm; results_pointer->final_training_direction = training_direction; results_pointer->final_training_rate = training_rate; results_pointer->elapsed_time = elapsed_time; results_pointer->iterations_number = iteration; results_pointer->resize_training_history(iteration+1); if(display) { std::cout << "Parameters norm: " << parameters_norm << "\n" << "Training loss: " << loss << "\n" << "Gradient norm: " << gradient_norm << "\n" << loss_index_pointer->write_information() << "Training rate: " << training_rate << "\n" << "Elapsed time: " << elapsed_time << std::endl; if(selection_loss != 0) { std::cout << "Selection loss: " << selection_loss << std::endl; } } break; } else if(display && iteration % display_period == 0) { std::cout << "Iteration " << iteration << ";\n" << "Parameters norm: " << parameters_norm << "\n" << "Training loss: " << loss << "\n" << "Gradient norm: " << gradient_norm << "\n" << loss_index_pointer->write_information() << "Training rate: " << training_rate << "\n" << "Elapsed time: " << elapsed_time << std::endl; if(selection_loss != 0) { std::cout << "Selection loss: " << selection_loss << std::endl; } } // Update stuff old_parameters = parameters; old_loss = loss; old_gradient = gradient; old_inverse_Hessian = inverse_Hessian; old_selection_loss = selection_loss; old_training_rate = training_rate; // Set new parameters parameters += parameters_increment; neural_network_pointer->set_parameters(parameters); } if(return_minimum_selection_error_neural_network) { parameters = minimum_selection_error_parameters; parameters_norm = parameters.calculate_norm(); neural_network_pointer->set_parameters(parameters); loss = loss_index_pointer->calculate_loss(); selection_loss = minimum_selection_error; } results_pointer->final_parameters = parameters; results_pointer->final_parameters_norm = parameters_norm; results_pointer->final_loss = loss; results_pointer->final_selection_loss = selection_loss; results_pointer->final_gradient = gradient; results_pointer->final_gradient_norm = gradient_norm; results_pointer->final_training_direction = training_direction; results_pointer->final_training_rate = training_rate; results_pointer->elapsed_time = elapsed_time; results_pointer->iterations_number = iteration; results_pointer->resize_training_history(iteration+1); #ifdef __OPENNN_CUDA__ if (gpuDeviceCount > 0) { freeCUDA(parameters_d); freeCUDA(old_parameters_d); freeCUDA(gradient_d); freeCUDA(old_gradient_d); freeCUDA(auxiliar_matrix_d); freeCUDA(old_inverse_Hessian_d); } #endif return(results_pointer); } // std::string write_training_algorithm_type(void) const method std::string QuasiNewtonMethod::write_training_algorithm_type(void) const { return("QUASI_NEWTON_METHOD"); } // tinyxml2::XMLDocument* to_XML(void) const method /// Returns a XML-type string representation of this quasi-Newton method object. /// It contains the training methods and parameters chosen, as well as /// the stopping criteria and other user stuff concerning the quasi-Newton method object. tinyxml2::XMLDocument* QuasiNewtonMethod::to_XML(void) const { std::ostringstream buffer; tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument; // Quasi-Newton method tinyxml2::XMLElement* root_element = document->NewElement("QuasiNewtonMethod"); document->InsertFirstChild(root_element); tinyxml2::XMLElement* element = NULL; tinyxml2::XMLText* text = NULL; // Inverse Hessian approximation method { element = document->NewElement("InverseHessianApproximationMethod"); root_element->LinkEndChild(element); text = document->NewText(write_inverse_Hessian_approximation_method().c_str()); element->LinkEndChild(text); } // Training rate algorithm { tinyxml2::XMLElement* element = document->NewElement("TrainingRateAlgorithm"); root_element->LinkEndChild(element); const tinyxml2::XMLDocument* training_rate_algorithm_document = training_rate_algorithm.to_XML(); const tinyxml2::XMLElement* training_rate_algorithm_element = training_rate_algorithm_document->FirstChildElement("TrainingRateAlgorithm"); DeepClone(element, training_rate_algorithm_element, document, NULL); delete training_rate_algorithm_document; } // Return minimum selection error neural network element = document->NewElement("ReturnMinimumSelectionErrorNN"); root_element->LinkEndChild(element); buffer.str(""); buffer << return_minimum_selection_error_neural_network; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Warning parameters norm // { // element = document->NewElement("WarningParametersNorm"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << warning_parameters_norm; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Warning gradient norm // { // element = document->NewElement("WarningGradientNorm"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << warning_gradient_norm; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Warning training rate // { // element = document->NewElement("WarningTrainingRate"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << warning_training_rate; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Error parameters norm // { // element = document->NewElement("ErrorParametersNorm"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << error_parameters_norm; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Error gradient norm // { // element = document->NewElement("ErrorGradientNorm"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << error_gradient_norm; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Error training rate // { // element = document->NewElement("ErrorTrainingRate"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << error_training_rate; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Minimum parameters increment norm { element = document->NewElement("MinimumParametersIncrementNorm"); root_element->LinkEndChild(element); buffer.str(""); buffer << minimum_parameters_increment_norm; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Minimum loss increase { element = document->NewElement("MinimumPerformanceIncrease"); root_element->LinkEndChild(element); buffer.str(""); buffer << minimum_loss_increase; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Performance goal { element = document->NewElement("PerformanceGoal"); root_element->LinkEndChild(element); buffer.str(""); buffer << loss_goal; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Gradient norm goal { element = document->NewElement("GradientNormGoal"); root_element->LinkEndChild(element); buffer.str(""); buffer << gradient_norm_goal; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Maximum selection loss decreases { element = document->NewElement("MaximumSelectionLossDecreases"); root_element->LinkEndChild(element); buffer.str(""); buffer << maximum_selection_loss_decreases; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Maximum iterations number { element = document->NewElement("MaximumIterationsNumber"); root_element->LinkEndChild(element); buffer.str(""); buffer << maximum_iterations_number; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Maximum time { element = document->NewElement("MaximumTime"); root_element->LinkEndChild(element); buffer.str(""); buffer << maximum_time; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Reserve parameters history // { // element = document->NewElement("ReserveParametersHistory"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << reserve_parameters_history; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Reserve parameters norm history { element = document->NewElement("ReserveParametersNormHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_parameters_norm_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Reserve loss history { element = document->NewElement("ReservePerformanceHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_loss_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Reserve selection loss history { element = document->NewElement("ReserveSelectionLossHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_selection_loss_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Reserve gradient history // { // element = document->NewElement("ReserveGradientHistory"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << reserve_gradient_history; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Reserve gradient norm history { element = document->NewElement("ReserveGradientNormHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_gradient_norm_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); } // Reserve inverse Hessian history // { // element = document->NewElement("ReserveInverseHessianHistory"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << reserve_inverse_Hessian_history; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Reserve training direction history // { // element = document->NewElement("ReserveTrainingDirectionHistory"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << reserve_training_direction_history; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Reserve training rate history // { // element = document->NewElement("ReserveTrainingRateHistory"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << reserve_training_rate_history; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Reserve elapsed time history // { // element = document->NewElement("ReserveElapsedTimeHistory"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << reserve_elapsed_time_history; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Reserve selection loss history // { // element = document->NewElement("ReserveSelectionLossHistory"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << reserve_selection_loss_history; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Display period // { // element = document->NewElement("DisplayPeriod"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << display_period; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Save period // { // element = document->NewElement("SavePeriod"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << save_period; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } // Neural network file name // { // element = document->NewElement("NeuralNetworkFileName"); // root_element->LinkEndChild(element); // text = document->NewText(neural_network_file_name.c_str()); // element->LinkEndChild(text); // } // Display // { // element = document->NewElement("Display"); // root_element->LinkEndChild(element); // buffer.str(""); // buffer << display; // text = document->NewText(buffer.str().c_str()); // element->LinkEndChild(text); // } return(document); } //void write_XML(tinyxml2::XMLPrinter&) const method /// Serializes the quasi Newton method object into a XML document of the TinyXML library without keep the DOM tree in memory. /// See the OpenNN manual for more information about the format of this document. void QuasiNewtonMethod::write_XML(tinyxml2::XMLPrinter& file_stream) const { std::ostringstream buffer; //file_stream.OpenElement("QuasiNewtonMethod"); // Inverse Hessian approximation method file_stream.OpenElement("InverseHessianApproximationMethod"); file_stream.PushText(write_inverse_Hessian_approximation_method().c_str()); file_stream.CloseElement(); // Training rate algorithm training_rate_algorithm.write_XML(file_stream); // Return minimum selection error neural network file_stream.OpenElement("ReturnMinimumSelectionErrorNN"); buffer.str(""); buffer << return_minimum_selection_error_neural_network; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Minimum parameters increment norm file_stream.OpenElement("MinimumParametersIncrementNorm"); buffer.str(""); buffer << minimum_parameters_increment_norm; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Minimum loss increase file_stream.OpenElement("MinimumPerformanceIncrease"); buffer.str(""); buffer << minimum_loss_increase; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Performance goal file_stream.OpenElement("PerformanceGoal"); buffer.str(""); buffer << loss_goal; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Gradient norm goal file_stream.OpenElement("GradientNormGoal"); buffer.str(""); buffer << gradient_norm_goal; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Maximum selection loss decreases file_stream.OpenElement("MaximumSelectionLossDecreases"); buffer.str(""); buffer << maximum_selection_loss_decreases; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Maximum iterations number file_stream.OpenElement("MaximumIterationsNumber"); buffer.str(""); buffer << maximum_iterations_number; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Maximum time file_stream.OpenElement("MaximumTime"); buffer.str(""); buffer << maximum_time; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Reserve parameters norm history file_stream.OpenElement("ReserveParametersNormHistory"); buffer.str(""); buffer << reserve_parameters_norm_history; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Reserve loss history file_stream.OpenElement("ReservePerformanceHistory"); buffer.str(""); buffer << reserve_loss_history; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Reserve selection loss history file_stream.OpenElement("ReserveSelectionLossHistory"); buffer.str(""); buffer << reserve_selection_loss_history; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Reserve gradient norm history file_stream.OpenElement("ReserveGradientNormHistory"); buffer.str(""); buffer << reserve_gradient_norm_history; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); //file_stream.CloseElement(); } // std::string to_string(void) const method std::string QuasiNewtonMethod::to_string(void) const { std::ostringstream buffer; buffer << "Quasi-Newton method\n"; return(buffer.str()); } // Matrix<std::string> to_string_matrix(void) const method /// Writes as matrix of strings the most representative atributes. Matrix<std::string> QuasiNewtonMethod::to_string_matrix(void) const { std::ostringstream buffer; Vector<std::string> labels; Vector<std::string> values; // Inverse Hessian approximation method labels.push_back("Inverse Hessian approximation method"); const std::string inverse_Hessian_approximation_method_string = write_inverse_Hessian_approximation_method(); values.push_back(inverse_Hessian_approximation_method_string); // Training rate method labels.push_back("Training rate method"); const std::string training_rate_method = training_rate_algorithm.write_training_rate_method(); values.push_back(training_rate_method); // Training rate tolerance labels.push_back("Training rate tolerance"); buffer.str(""); buffer << training_rate_algorithm.get_training_rate_tolerance(); values.push_back(buffer.str()); // Minimum parameters increment norm labels.push_back("Minimum parameters increment norm"); buffer.str(""); buffer << minimum_parameters_increment_norm; values.push_back(buffer.str()); // Minimum loss increase labels.push_back("Minimum loss increase"); buffer.str(""); buffer << minimum_loss_increase; values.push_back(buffer.str()); // Performance goal labels.push_back("Performance goal"); buffer.str(""); buffer << loss_goal; values.push_back(buffer.str()); // Gradient norm goal labels.push_back("Gradient norm goal"); buffer.str(""); buffer << gradient_norm_goal; values.push_back(buffer.str()); // Maximum selection loss decreases labels.push_back("Maximum selection loss increases"); buffer.str(""); buffer << maximum_selection_loss_decreases; values.push_back(buffer.str()); // Maximum iterations number labels.push_back("Maximum iterations number"); buffer.str(""); buffer << maximum_iterations_number; values.push_back(buffer.str()); // Maximum time labels.push_back("Maximum time"); buffer.str(""); buffer << maximum_time; values.push_back(buffer.str()); // Reserve parameters norm history labels.push_back("Reserve parameters norm history"); buffer.str(""); if(reserve_parameters_norm_history) { buffer << "true"; } else { buffer << "false"; } values.push_back(buffer.str()); // Reserve loss history labels.push_back("Reserve loss history"); buffer.str(""); if(reserve_loss_history) { buffer << "true"; } else { buffer << "false"; } values.push_back(buffer.str()); // Reserve selection loss history labels.push_back("Reserve selection loss history"); buffer.str(""); if(reserve_selection_loss_history) { buffer << "true"; } else { buffer << "false"; } values.push_back(buffer.str()); // Reserve gradient norm history labels.push_back("Reserve gradient norm history"); buffer.str(""); if(reserve_gradient_norm_history) { buffer << "true"; } else { buffer << "false"; } values.push_back(buffer.str()); // Reserve training direction norm history // labels.push_back(""); // buffer.str(""); // buffer << reserve_training_direction_norm_history; // Reserve training rate history // labels.push_back(""); // buffer.str(""); // buffer << reserve_training_rate_history; // values.push_back(buffer.str()); // Reserve elapsed time history // labels.push_back("Reserve elapsed time history"); // buffer.str(""); // buffer << reserve_elapsed_time_history; // values.push_back(buffer.str()); const size_t rows_number = labels.size(); const size_t columns_number = 2; Matrix<std::string> string_matrix(rows_number, columns_number); string_matrix.set_column(0, labels); string_matrix.set_column(1, values); return(string_matrix); } // void from_XML(const tinyxml2::XMLDocument&) const method void QuasiNewtonMethod::from_XML(const tinyxml2::XMLDocument& document) { const tinyxml2::XMLElement* root_element = document.FirstChildElement("QuasiNewtonMethod"); if(!root_element) { std::ostringstream buffer; buffer << "OpenNN Exception: QuasiNewtonMethod class.\n" << "void from_XML(const tinyxml2::XMLDocument&) method.\n" << "Quasi-Newton method element is NULL.\n"; throw std::logic_error(buffer.str()); } // Inverse Hessian approximation method { const tinyxml2::XMLElement* element = root_element->FirstChildElement("InverseHessianApproximationMethod"); if(element) { const std::string new_inverse_Hessian_approximation_method = element->GetText(); try { set_inverse_Hessian_approximation_method(new_inverse_Hessian_approximation_method); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Inverse Hessian approximation method { const tinyxml2::XMLElement* element = root_element->FirstChildElement("InverseHessianApproximationMethod"); if(element) { const std::string new_inverse_Hessian_approximation_method = element->GetText(); try { set_inverse_Hessian_approximation_method(new_inverse_Hessian_approximation_method); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Training rate algorithm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("TrainingRateAlgorithm"); if(element) { tinyxml2::XMLDocument training_rate_algorithm_document; tinyxml2::XMLElement* element_clone = training_rate_algorithm_document.NewElement("TrainingRateAlgorithm"); training_rate_algorithm_document.InsertFirstChild(element_clone); DeepClone(element_clone, element, &training_rate_algorithm_document, NULL); training_rate_algorithm.from_XML(training_rate_algorithm_document); } } // Warning parameters norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("WarningParametersNorm"); if(element) { const double new_warning_parameters_norm = atof(element->GetText()); try { set_warning_parameters_norm(new_warning_parameters_norm); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Warning gradient norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("WarningGradientNorm"); if(element) { const double new_warning_gradient_norm = atof(element->GetText()); try { set_warning_gradient_norm(new_warning_gradient_norm); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Warning training rate { const tinyxml2::XMLElement* element = root_element->FirstChildElement("WarningTrainingRate"); if(element) { const double new_warning_training_rate = atof(element->GetText()); try { set_warning_training_rate(new_warning_training_rate); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Error parameters norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ErrorParametersNorm"); if(element) { const double new_error_parameters_norm = atof(element->GetText()); try { set_error_parameters_norm(new_error_parameters_norm); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Error gradient norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ErrorGradientNorm"); if(element) { const double new_error_gradient_norm = atof(element->GetText()); try { set_error_gradient_norm(new_error_gradient_norm); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Error training rate { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ErrorTrainingRate"); if(element) { const double new_error_training_rate = atof(element->GetText()); try { set_error_training_rate(new_error_training_rate); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Return minimum selection error neural network const tinyxml2::XMLElement* return_minimum_selection_error_neural_network_element = root_element->FirstChildElement("ReturnMinimumSelectionErrorNN"); if(return_minimum_selection_error_neural_network_element) { std::string new_return_minimum_selection_error_neural_network = return_minimum_selection_error_neural_network_element->GetText(); try { set_return_minimum_selection_error_neural_network(new_return_minimum_selection_error_neural_network != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } // Minimum parameters increment norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MinimumParametersIncrementNorm"); if(element) { const double new_minimum_parameters_increment_norm = atof(element->GetText()); try { set_minimum_parameters_increment_norm(new_minimum_parameters_increment_norm); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Minimum loss increase { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MinimumPerformanceIncrease"); if(element) { const double new_minimum_loss_increase = atof(element->GetText()); try { set_minimum_loss_increase(new_minimum_loss_increase); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Performance goal { const tinyxml2::XMLElement* element = root_element->FirstChildElement("PerformanceGoal"); if(element) { const double new_loss_goal = atof(element->GetText()); try { set_loss_goal(new_loss_goal); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Gradient norm goal { const tinyxml2::XMLElement* element = root_element->FirstChildElement("GradientNormGoal"); if(element) { const double new_gradient_norm_goal = atof(element->GetText()); try { set_gradient_norm_goal(new_gradient_norm_goal); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Maximum selection loss decreases { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumSelectionLossDecreases"); if(element) { const size_t new_maximum_selection_loss_decreases = atoi(element->GetText()); try { set_maximum_selection_loss_decreases(new_maximum_selection_loss_decreases); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Maximum iterations number { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumIterationsNumber"); if(element) { const size_t new_maximum_iterations_number = atoi(element->GetText()); try { set_maximum_iterations_number(new_maximum_iterations_number); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Maximum time { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumTime"); if(element) { const double new_maximum_time = atof(element->GetText()); try { set_maximum_time(new_maximum_time); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve parameters history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveParametersHistory"); if(element) { const std::string new_reserve_parameters_history = element->GetText(); try { set_reserve_parameters_history(new_reserve_parameters_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve parameters norm history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveParametersNormHistory"); if(element) { const std::string new_reserve_parameters_norm_history = element->GetText(); try { set_reserve_parameters_norm_history(new_reserve_parameters_norm_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve loss history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReservePerformanceHistory"); if(element) { const std::string new_reserve_loss_history = element->GetText(); try { set_reserve_loss_history(new_reserve_loss_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve selection loss history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveSelectionLossHistory"); if(element) { const std::string new_reserve_selection_loss_history = element->GetText(); try { set_reserve_selection_loss_history(new_reserve_selection_loss_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve gradient history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveGradientHistory"); if(element) { const std::string new_reserve_gradient_history = element->GetText(); try { set_reserve_gradient_history(new_reserve_gradient_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve gradient norm history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveGradientNormHistory"); if(element) { const std::string new_reserve_gradient_norm_history = element->GetText(); try { set_reserve_gradient_norm_history(new_reserve_gradient_norm_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve inverse Hessian history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveInverseHessianHistory"); if(element) { const std::string new_reserve_inverse_Hessian_history = element->GetText(); try { set_reserve_inverse_Hessian_history(new_reserve_inverse_Hessian_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve training direction history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveTrainingDirectionHistory"); if(element) { const std::string new_reserve_training_direction_history = element->GetText(); try { set_reserve_training_direction_history(new_reserve_training_direction_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve training rate history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveTrainingRateHistory"); if(element) { const std::string new_reserve_training_rate_history = element->GetText(); try { set_reserve_training_rate_history(new_reserve_training_rate_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve elapsed time history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveElapsedTimeHistory"); if(element) { const std::string new_reserve_elapsed_time_history = element->GetText(); try { set_reserve_elapsed_time_history(new_reserve_elapsed_time_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Reserve selection loss history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveSelectionLossHistory"); if(element) { const std::string new_reserve_selection_loss_history = element->GetText(); try { set_reserve_selection_loss_history(new_reserve_selection_loss_history != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Display period { const tinyxml2::XMLElement* element = root_element->FirstChildElement("DisplayPeriod"); if(element) { const size_t new_display_period = atoi(element->GetText()); try { set_display_period(new_display_period); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Save period { const tinyxml2::XMLElement* element = root_element->FirstChildElement("SavePeriod"); if(element) { const size_t new_save_period = atoi(element->GetText()); try { set_save_period(new_save_period); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Neural network file name { const tinyxml2::XMLElement* element = root_element->FirstChildElement("NeuralNetworkFileName"); if(element) { const std::string new_neural_network_file_name = element->GetText(); try { set_neural_network_file_name(new_neural_network_file_name); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } // Display { const tinyxml2::XMLElement* element = root_element->FirstChildElement("Display"); if(element) { const std::string new_display = element->GetText(); try { set_display(new_display != "0"); } catch(const std::logic_error& e) { std::cout << e.what() << std::endl; } } } } } // OpenNN: Open Neural Networks Library. // Copyright (c) 2005-2016 Roberto Lopez. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
29.463082
200
0.682937
[ "object", "vector", "model" ]
784f90ec0b2094bbd3c7e4c182421f438e43024f
14,271
cpp
C++
Algorithm/arcsim/adaptiveCloth/simulation.cpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
32
2016-12-13T05:49:12.000Z
2022-02-04T06:15:47.000Z
Algorithm/arcsim/adaptiveCloth/simulation.cpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
2
2019-07-30T02:01:16.000Z
2020-03-12T15:06:51.000Z
Algorithm/arcsim/adaptiveCloth/simulation.cpp
dolphin-li/ClothDesigner
82b186d6db320b645ac67a4d32d7746cc9bdd391
[ "MIT" ]
18
2017-11-16T13:37:06.000Z
2022-03-11T08:13:46.000Z
/* Copyright ©2013 The Regents of the University of California (Regents). All Rights Reserved. Permission to use, copy, modify, and distribute this software and its documentation for educational, research, and not-for-profit purposes, without fee and without a signed licensing agreement, is hereby granted, provided that the above copyright notice, this paragraph and the following two paragraphs appear in all copies, modifications, and distributions. Contact The Office of Technology Licensing, UC Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620, (510) 643-7201, for commercial licensing opportunities. IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include "simulation.hpp" #include "collision.hpp" #include "dynamicremesh.hpp" #include "geometry.hpp" #include "magic.hpp" #include "nearobs.hpp" #include "physics.hpp" #include "plasticity.hpp" #include "popfilter.hpp" #include "proximity.hpp" #include "separate.hpp" #include "strainlimiting.hpp" #include <iostream> #include <fstream> using namespace std; namespace arcsim { static const bool verbose = false; static const int proximity = Simulation::Proximity, physics = Simulation::Physics, strainlimiting = Simulation::StrainLimiting, collision = Simulation::Collision, remeshing = Simulation::Remeshing, separation = Simulation::Separation, popfilter = Simulation::PopFilter, plasticity = Simulation::Plasticity; void physics_step(Simulation &sim, const vector<Constraint*> &cons); void plasticity_step(Simulation &sim); void strainlimiting_step(Simulation &sim, const vector<Constraint*> &cons); void strainzeroing_step(Simulation &sim); void equilibration_step(Simulation &sim); void collision_step(Simulation &sim); void remeshing_step(Simulation &sim, bool initializing = false); void validate_handles(const Simulation &sim); void prepare(Simulation &sim) { sim.cloth_meshes.resize(sim.cloths.size()); for (int c = 0; c < sim.cloths.size(); c++) { compute_masses(sim.cloths[c]); sim.cloth_meshes[c] = &sim.cloths[c].mesh; update_x0(*sim.cloth_meshes[c]); } sim.obstacle_meshes.resize(sim.obstacles.size()); for (int o = 0; o < sim.obstacles.size(); o++) { sim.obstacle_meshes[o] = &sim.obstacles[o].get_mesh(); update_x0(*sim.obstacle_meshes[o]); sim.obstacles[o].base_acc_noccd.reset(new AccelStruct(*sim.obstacle_meshes[o], false)); } } void relax_initial_state(Simulation &sim) { validate_handles(sim); if (arcsim::magic.preserve_creases) { for (int c = 0; c < sim.cloths.size(); c++) reset_plasticity(sim.cloths[c]); } bool equilibrate = true; if (equilibrate) { equilibration_step(sim); remeshing_step(sim, true); equilibration_step(sim); } else { remeshing_step(sim, true); strainzeroing_step(sim); remeshing_step(sim, true); strainzeroing_step(sim); } if (arcsim::magic.preserve_creases) { for (int c = 0; c < sim.cloths.size(); c++) reset_plasticity(sim.cloths[c]); } arcsim::magic.preserve_creases = false; if (arcsim::magic.fixed_high_res_mesh) sim.enabled[remeshing] = false; } void validate_handles(const Simulation &sim) { for (int h = 0; h < sim.handles.size(); h++) { vector<Node*> nodes = sim.handles[h]->get_nodes(); for (int n = 0; n < nodes.size(); n++) { if (!nodes[n]->preserve) { cout << "Constrained node " << nodes[n]->index << " will not be preserved by remeshing" << endl; abort(); } } } } vector<Constraint*> get_constraints(Simulation &sim, bool include_proximity); void delete_constraints(const vector<Constraint*> &cons); void update_obstacles(Simulation &sim, bool update_positions = true); void advance_step(Simulation &sim); void advance_frame(Simulation &sim) { for (int s = 0; s < sim.frame_steps; s++) advance_step(sim); } void advance_step(Simulation &sim) { sim.time += sim.step_time; sim.step++; // ldp: update obstacles only if they have motions if (sim.motions.size() > 1) update_obstacles(sim, false); // collect constraints vector<Constraint*> cons;// = get_constraints(sim, true); if (1)//sim.enabled[collision]) cons = get_constraints(sim, true); // physical simulation physics_step(sim, cons); plasticity_step(sim); strainlimiting_step(sim, cons); collision_step(sim); // go to next step if (sim.step % sim.frame_steps == 0) { remeshing_step(sim); sim.frame++; } delete_constraints(cons); } vector<Constraint*> get_constraints(Simulation &sim, bool include_proximity) { vector<Constraint*> cons; for (int h = 0; h < sim.handles.size(); h++) append(cons, sim.handles[h]->get_constraints(sim.time)); if (include_proximity && sim.enabled[proximity]) { sim.timers[proximity].tick(); // ldp: if have motions, we re-create obs accs each frame // else we reuse the base obs accs if (sim.motions.size() > 1) append(cons, proximity_constraints(sim.cloth_meshes, sim.obstacle_meshes, sim.friction, sim.obs_friction)); else { std::vector<AccelStruct*> obs_accs(sim.obstacles.size()); for (size_t i = 0; i < obs_accs.size(); i++) obs_accs[i] = sim.obstacles[i].base_acc_noccd.get(); append(cons, proximity_constraints(sim.cloth_meshes, obs_accs,sim.friction, sim.obs_friction)); } sim.timers[proximity].tock(); } return cons; } void delete_constraints(const vector<Constraint*> &cons) { for (int c = 0; c < cons.size(); c++) delete cons[c]; } // Steps void update_velocities(vector<Mesh*> &meshes, vector<Vec3> &xold, double dt); void step_mesh(Mesh &mesh, double dt); void physics_step(Simulation &sim, const vector<Constraint*> &cons) { if (!sim.enabled[physics]) return; sim.timers[physics].tick(); for (int c = 0; c < sim.cloths.size(); c++) { int nn = sim.cloths[c].mesh.nodes.size(); vector<Vec3> fext(nn, Vec3(0)); vector<Mat3x3> Jext(nn, Mat3x3(0)); add_external_forces(sim.cloths[c], sim.gravity, sim.wind, fext, Jext); for (int m = 0; m < sim.morphs.size(); m++) if (sim.morphs[m].mesh == &sim.cloths[c].mesh) add_morph_forces(sim.cloths[c], sim.morphs[m], sim.time, sim.step_time, fext, Jext); implicit_update(sim.cloths[c], fext, Jext, cons, sim.step_time, false); } for (int c = 0; c < sim.cloth_meshes.size(); c++) step_mesh(*sim.cloth_meshes[c], sim.step_time); for (int o = 0; o < sim.obstacle_meshes.size(); o++) step_mesh(*sim.obstacle_meshes[o], sim.step_time); sim.timers[physics].tock(); } void step_mesh(Mesh &mesh, double dt) { for (int n = 0; n < mesh.nodes.size(); n++) mesh.nodes[n]->x += mesh.nodes[n]->v*dt; } void plasticity_step(Simulation &sim) { if (!sim.enabled[plasticity]) return; sim.timers[plasticity].tick(); for (int c = 0; c < sim.cloths.size(); c++) { plastic_update(sim.cloths[c]); optimize_plastic_embedding(sim.cloths[c]); } sim.timers[plasticity].tock(); } void strainlimiting_step(Simulation &sim, const vector<Constraint*> &cons) { if (!sim.enabled[strainlimiting]) return; sim.timers[strainlimiting].tick(); vector<Vec3> xold = node_positions(sim.cloth_meshes); strain_limiting(sim.cloth_meshes, get_strain_limits(sim.cloths), cons); update_velocities(sim.cloth_meshes, xold, sim.step_time); sim.timers[strainlimiting].tock(); } void equilibration_step(Simulation &sim) { sim.timers[remeshing].tick(); vector<Constraint*> cons;// = get_constraints(sim, true); // double stiff = 1; // swap(stiff, ::magic.handle_stiffness); for (int c = 0; c < sim.cloths.size(); c++) { Mesh &mesh = sim.cloths[c].mesh; for (int n = 0; n < mesh.nodes.size(); n++) mesh.nodes[n]->acceleration = Vec3(0); apply_pop_filter(sim.cloths[c], cons, 1); } // swap(stiff, ::magic.handle_stiffness); sim.timers[remeshing].tock(); delete_constraints(cons); cons = get_constraints(sim, false); if (sim.enabled[collision]) { sim.timers[collision].tick(); collision_response(sim.cloth_meshes, cons, sim.obstacle_meshes); sim.timers[collision].tock(); } delete_constraints(cons); } void strainzeroing_step(Simulation &sim) { sim.timers[strainlimiting].tick(); vector<Vec2> strain_limits(size<Face>(sim.cloth_meshes), Vec2(1, 1)); vector<Constraint*> cons = proximity_constraints(sim.cloth_meshes, sim.obstacle_meshes, sim.friction, sim.obs_friction); strain_limiting(sim.cloth_meshes, strain_limits, cons); delete_constraints(cons); sim.timers[strainlimiting].tock(); if (sim.enabled[collision]) { sim.timers[collision].tock(); collision_response(sim.cloth_meshes, vector<Constraint*>(), sim.obstacle_meshes); sim.timers[collision].tock(); } } void collision_step(Simulation &sim) { if (!sim.enabled[collision]) return; sim.timers[collision].tick(); vector<Vec3> xold = node_positions(sim.cloth_meshes); vector<Constraint*> cons = get_constraints(sim, false); collision_response(sim.cloth_meshes, cons, sim.obstacle_meshes); delete_constraints(cons); update_velocities(sim.cloth_meshes, xold, sim.step_time); sim.timers[collision].tock(); } void remeshing_step(Simulation &sim, bool initializing) { if (!sim.enabled[remeshing]) return; // copy old meshes vector<Mesh> old_meshes(sim.cloths.size()); vector<Mesh*> old_meshes_p(sim.cloths.size()); // for symmetry in separate() for (int c = 0; c < sim.cloths.size(); c++) { old_meshes[c] = deep_copy(sim.cloths[c].mesh); old_meshes_p[c] = &old_meshes[c]; } // back up residuals typedef vector<Residual> MeshResidual; vector<MeshResidual> res; if (sim.enabled[plasticity] && !initializing) { sim.timers[plasticity].tick(); res.resize(sim.cloths.size()); for (int c = 0; c < sim.cloths.size(); c++) res[c] = back_up_residuals(sim.cloths[c].mesh); sim.timers[plasticity].tock(); } // remesh sim.timers[remeshing].tick(); for (int c = 0; c < sim.cloths.size(); c++) { if (arcsim::magic.fixed_high_res_mesh) static_remesh(sim.cloths[c]); else { vector<Plane> planes = nearest_obstacle_planes(sim.cloths[c].mesh, sim.obstacle_meshes); dynamic_remesh(sim.cloths[c], planes, sim.enabled[plasticity]); } } sim.timers[remeshing].tock(); // restore residuals if (sim.enabled[plasticity] && !initializing) { sim.timers[plasticity].tick(); for (int c = 0; c < sim.cloths.size(); c++) restore_residuals(sim.cloths[c].mesh, old_meshes[c], res[c]); sim.timers[plasticity].tock(); } // separate if (sim.enabled[separation]) { sim.timers[separation].tick(); separate(sim.cloth_meshes, old_meshes_p, sim.obstacle_meshes); sim.timers[separation].tock(); } // apply pop filter if (sim.enabled[popfilter] && !initializing) { sim.timers[popfilter].tick(); vector<Constraint*> cons = get_constraints(sim, true); for (int c = 0; c < sim.cloths.size(); c++) apply_pop_filter(sim.cloths[c], cons); delete_constraints(cons); sim.timers[popfilter].tock(); } // delete old meshes for (int c = 0; c < sim.cloths.size(); c++) delete_mesh(old_meshes[c]); } void update_velocities(vector<Mesh*> &meshes, vector<Vec3> &xold, double dt) { double inv_dt = 1 / dt; #pragma omp parallel for for (int n = 0; n < xold.size(); n++) { Node *node = get<Node>(n, meshes); node->v += (node->x - xold[n])*inv_dt; } } void update_obstacles(Simulation &sim, bool update_positions) { double decay_time = 0.1, blend = sim.step_time / decay_time; blend = blend / (1 + blend); for (int o = 0; o < sim.obstacles.size(); o++) { sim.obstacles[o].get_mesh(sim.time); sim.obstacles[o].blend_with_previous(sim.time, sim.step_time, blend); if (!update_positions) { // put positions back where they were Mesh &mesh = sim.obstacles[o].get_mesh(); for (int n = 0; n < mesh.nodes.size(); n++) { Node *node = mesh.nodes[n]; node->v = (node->x - node->x0) / sim.step_time; node->x = node->x0; } } } } // Helper functions template <typename Prim> int size(const vector<Mesh*> &meshes) { int np = 0; for (int m = 0; m < meshes.size(); m++) np += get<Prim>(*meshes[m]).size(); return np; } template int size<Vert>(const vector<Mesh*>&); template int size<Node>(const vector<Mesh*>&); template int size<Edge>(const vector<Mesh*>&); template int size<Face>(const vector<Mesh*>&); template <typename Prim> int get_index(const Prim *p, const vector<Mesh*> &meshes) { int i = 0; for (int m = 0; m < meshes.size(); m++) { const vector<Prim*> &ps = get<Prim>(*meshes[m]); if (p->index < ps.size() && p == ps[p->index]) return i + p->index; else i += ps.size(); } return -1; } template int get_index(const Vert*, const vector<Mesh*>&); template int get_index(const Node*, const vector<Mesh*>&); template int get_index(const Edge*, const vector<Mesh*>&); template int get_index(const Face*, const vector<Mesh*>&); template <typename Prim> Prim *get(int i, const vector<Mesh*> &meshes) { for (int m = 0; m < meshes.size(); m++) { const vector<Prim*> &ps = get<Prim>(*meshes[m]); if (i < ps.size()) return ps[i]; else i -= ps.size(); } return NULL; } template Vert *get(int, const vector<Mesh*>&); template Node *get(int, const vector<Mesh*>&); template Edge *get(int, const vector<Mesh*>&); template Face *get(int, const vector<Mesh*>&); vector<Vec3> node_positions(const vector<Mesh*> &meshes) { vector<Vec3> xs(size<Node>(meshes)); for (int n = 0; n < xs.size(); n++) xs[n] = get<Node>(n, meshes)->x; return xs; } }
29.424742
101
0.677598
[ "mesh", "geometry", "vector" ]