hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
0fa912fc4ff4cff150a2eace2e7d4ab77d2c860b
16,793
cc
C++
o3d/core/cross/param_object_test.cc
zachlatta/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
1
2021-09-24T22:49:10.000Z
2021-09-24T22:49:10.000Z
o3d/core/cross/param_object_test.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
o3d/core/cross/param_object_test.cc
changbai1980/chromium
c4625eefca763df86471d798ee5a4a054b4716ae
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // Tests functionality of the ParamObject class #include <algorithm> #include "core/cross/param_object.h" #include "core/cross/client.h" #include "tests/common/win/testing_common.h" #include "core/cross/error.h" namespace o3d { // Test fixture for ParamObject testing. Creates a Client object // and a ParamObject before each test and deletes it after class ParamObjectTest : public testing::Test { protected: ParamObjectTest() : object_manager_(g_service_locator) {} virtual void SetUp(); virtual void TearDown(); Pack* pack() { return pack_; } ParamObject* param_obj() { return param_obj_; } ServiceDependency<ObjectManager> object_manager_; private: Pack* pack_; ParamObject* param_obj_; }; void ParamObjectTest::SetUp() { pack_ = object_manager_->CreatePack(); param_obj_ = pack()->Create<Transform>(); } void ParamObjectTest::TearDown() { pack_->Destroy(); } namespace { class FakeParam : public Param { public: explicit FakeParam(ServiceLocator* service_locator) : Param(service_locator, false, false) { } virtual void CopyDataFromParam(Param* source_param) { // Do nothing. We are fake. } }; class FakeDivModParamOperation : public ParamObject { public: typedef SmartPointer<FakeDivModParamOperation> Ref; static const char* kInput1Name; static const char* kInput2Name; static const char* kOutput1Name; static const char* kOutput2Name; explicit FakeDivModParamOperation(ServiceLocator* service_locator); void UpdateOutputs(); int input1() const { return input1_param_->value(); } void set_input1(int value) { input1_param_->set_value(value); } int input2() const { return input2_param_->value(); } void set_input2(int value) { input2_param_->set_value(value); } int output1() const { return output1_param_->value(); } int output2() const { return output2_param_->value(); } unsigned NumberOfCallsToUpdateOutputs() const { return update_outputs_call_count_; } protected: // Overridden from ParamObject // For the given Param, returns all the inputs that affect that param through // this ParamObject. virtual void ConcreteGetInputsForParam(const Param* param, ParamVector* inputs) const; // Overridden from ParamObject // For the given Param, returns all the outputs that the given param will // affect through this ParamObject. virtual void ConcreteGetOutputsForParam(const Param* param, ParamVector* outputs) const; private: typedef SlaveParam<ParamInteger, FakeDivModParamOperation> SlaveParamInteger; ParamInteger::Ref input1_param_; ParamInteger::Ref input2_param_; SlaveParamInteger::Ref output1_param_; SlaveParamInteger::Ref output2_param_; unsigned update_outputs_call_count_; O3D_DECL_CLASS(FakeDivModParamOperation, ParamObject); DISALLOW_COPY_AND_ASSIGN(FakeDivModParamOperation); }; O3D_DEFN_CLASS(FakeDivModParamOperation, ParamObject); const char* FakeDivModParamOperation::kInput1Name = "input1"; const char* FakeDivModParamOperation::kInput2Name = "input2"; const char* FakeDivModParamOperation::kOutput1Name = "output1"; const char* FakeDivModParamOperation::kOutput2Name = "output2"; FakeDivModParamOperation::FakeDivModParamOperation( ServiceLocator* service_locator) : ParamObject(service_locator), update_outputs_call_count_(0) { RegisterParamRef(kInput1Name, &input1_param_); RegisterParamRef(kInput2Name, &input2_param_); SlaveParamInteger::RegisterParamRef(kOutput1Name, &output1_param_, this); SlaveParamInteger::RegisterParamRef(kOutput2Name, &output2_param_, this); } void FakeDivModParamOperation::ConcreteGetInputsForParam( const Param* param, ParamVector* inputs) const { if ((param == output1_param_ && output1_param_->input_connection() == NULL) || (param == output2_param_ && output2_param_->input_connection() == NULL)) { inputs->push_back(input1_param_); inputs->push_back(input2_param_); } } void FakeDivModParamOperation::ConcreteGetOutputsForParam( const Param* param, ParamVector* outputs) const { if (param == input1_param_ || param == input2_param_) { if (output1_param_->input_connection() == NULL) { outputs->push_back(output1_param_); } if (output2_param_->input_connection() == NULL) { outputs->push_back(output2_param_); } } } void FakeDivModParamOperation::UpdateOutputs() { ++update_outputs_call_count_; int input1 = input1_param_->value(); int input2 = input2_param_->value(); if (input2 != 0) { output1_param_->set_dynamic_value(input1 / input2); output2_param_->set_dynamic_value(input1 % input2); } else { O3D_ERROR(g_service_locator) << "divide by zero in '" << name() << "'"; } } // Check if a param is in the given param array // Parameters: // param: param to search for. // params: ParamVector to search. // Returns: // true if param is in params. bool ParamInParams(Param* param, const ParamVector& params) { return std::find(params.begin(), params.end(), param) != params.end(); } } // anonymous namespace // Test ParamObject::AddParam(). TEST_F(ParamObjectTest, AddParam) { using o3d::NamedParamRefMap; Param* param = new FakeParam(g_service_locator); Param* param2 = new FakeParam(g_service_locator); param_obj()->AddParam("param", param); // Make sure the param ends up in the Param obj's Param Map. const NamedParamRefMap& param_map = param_obj()->params(); NamedParamRefMap::const_iterator pos = param_map.find("param"); EXPECT_TRUE(pos != param_map.end()); // Make sure the param ends up in the client as well. EXPECT_TRUE(object_manager_->GetById<Param>(param->id()) == param); // Make sure if we add another of the same name it fails. EXPECT_FALSE(param_obj()->AddParam("param", param2)); // Make sure the old param was uneffected. pos = param_map.find("param"); EXPECT_TRUE(pos != param_map.end()); EXPECT_EQ(param, param_obj()->GetUntypedParam("param")); // Note: Param is owned by the ParamObject now so we don't delete it here. } // Test ParamObject::RemoveParam(). TEST_F(ParamObjectTest, RemoveParam) { Param::Ref param(param_obj()->CreateParam<ParamFloat>("param")); ASSERT_FALSE(param.IsNull()); // Should be able to remove it EXPECT_TRUE(param_obj()->RemoveParam(param)); // Should not be able to remove it twice. EXPECT_FALSE(param_obj()->RemoveParam(param)); } // Test ParamObject::CreateParam(). TEST_F(ParamObjectTest, CreateParam) { using o3d::NamedParamRefMap; Param *param = param_obj()->CreateParam<ParamFloat>("param"); // Make sure the param ends up in the Param obj's Param Map. NamedParamRefMap param_map = param_obj()->params(); NamedParamRefMap::const_iterator pos = param_map.find("param"); EXPECT_TRUE(pos != param_map.end()); // Make sure the param ends up in the client as well. EXPECT_TRUE(object_manager_->GetById<Param>(param->id()) == param); // Note: Param is owned by the ParamObject now so we don't delete it here. } // Test ParamObject::CreateParam(). TEST_F(ParamObjectTest, GetOrCreateParam) { using o3d::NamedParamRefMap; Param *param = param_obj()->GetOrCreateParam<ParamMatrix4>("param1"); EXPECT_TRUE(param != NULL); EXPECT_EQ(ParamMatrix4::GetApparentClass(), param->GetClass()); EXPECT_EQ("param1", param->name()); size_t size = param_obj()->params().size(); // Create an already-existing param, check that it returns the same one and // doesn't add anything else to the node. Param *param2 = param_obj()->GetOrCreateParam<ParamMatrix4>("param1"); EXPECT_EQ(param, param2); EXPECT_EQ(size, param_obj()->params().size()); EXPECT_EQ(param2, param_obj()->GetUntypedParam("param1")); // Note: Param is owned by the ParamObject now so we don't delete it here. } // Tests GetInputsForParam and GetOutputsForParam TEST_F(ParamObjectTest, GetInputsForParamGetOutputsForParam) { FakeDivModParamOperation::Ref operation = FakeDivModParamOperation::Ref( new FakeDivModParamOperation(g_service_locator)); ASSERT_FALSE(operation.IsNull()); // Verify that FakeDivModParamOperationWorks. operation->set_input1(19); operation->set_input2(5); EXPECT_EQ(operation->NumberOfCallsToUpdateOutputs(), 0); EXPECT_EQ(operation->output1(), 3); EXPECT_EQ(operation->NumberOfCallsToUpdateOutputs(), 1); EXPECT_EQ(operation->output2(), 4); // This should be 1 because calling operation->output1() should // have updated output2(). EXPECT_EQ(operation->NumberOfCallsToUpdateOutputs(), 1); // Now check GetInputs Param* input1 = operation->GetUntypedParam( FakeDivModParamOperation::kInput1Name); Param* input2 = operation->GetUntypedParam( FakeDivModParamOperation::kInput2Name); Param* output1 = operation->GetUntypedParam( FakeDivModParamOperation::kOutput1Name); Param* output2 = operation->GetUntypedParam( FakeDivModParamOperation::kOutput2Name); ASSERT_TRUE(input1 != NULL); ASSERT_TRUE(input2 != NULL); ASSERT_TRUE(output1 != NULL); ASSERT_TRUE(output2 != NULL); ParamVector params; // There should be no params on the params operation->GetInputsForParam(input1, &params); EXPECT_EQ(params.size(), 0); operation->GetInputsForParam(input2, &params); EXPECT_EQ(params.size(), 0); // There should be two params for each output. operation->GetInputsForParam(output1, &params); EXPECT_EQ(params.size(), 2); EXPECT_TRUE(ParamInParams(input1, params)); EXPECT_TRUE(ParamInParams(input2, params)); params.clear(); // make sure we are not just getting the same result. operation->GetInputsForParam(output2, &params); EXPECT_EQ(params.size(), 2); EXPECT_TRUE(ParamInParams(input1, params)); EXPECT_TRUE(ParamInParams(input2, params)); // Make sure we don't just add more params. operation->GetInputsForParam(output2, &params); EXPECT_EQ(params.size(), 2); // Check GetOutputs operation->GetOutputsForParam(input1, &params); EXPECT_EQ(params.size(), 2); EXPECT_TRUE(ParamInParams(output1, params)); EXPECT_TRUE(ParamInParams(output2, params)); operation->GetOutputsForParam(input2, &params); EXPECT_EQ(params.size(), 2); EXPECT_TRUE(ParamInParams(output1, params)); EXPECT_TRUE(ParamInParams(output2, params)); operation->GetOutputsForParam(output1, &params); EXPECT_EQ(params.size(), 0); operation->GetOutputsForParam(output2, &params); EXPECT_EQ(params.size(), 0); // If we bind the output we should not get it as an input or an output. Param* other = operation->CreateParam<ParamInteger>("other"); ASSERT_TRUE(other != NULL); ASSERT_TRUE(output2->Bind(other)); // There should be two inputs for output1 but none for output2 since it is // bound. operation->GetInputsForParam(output1, &params); EXPECT_EQ(params.size(), 2); operation->GetInputsForParam(output2, &params); EXPECT_EQ(params.size(), 0); // There should only be 1 output for each of the inputs since output2 is // no longer effected by the inputs. operation->GetOutputsForParam(input1, &params); EXPECT_EQ(params.size(), 1); EXPECT_TRUE(ParamInParams(output1, params)); operation->GetOutputsForParam(input2, &params); EXPECT_EQ(params.size(), 1); EXPECT_TRUE(ParamInParams(output1, params)); } // Tests Implicit Cycles TEST_F(ParamObjectTest, ImplicitCycles) { FakeDivModParamOperation::Ref operation_a = FakeDivModParamOperation::Ref( new FakeDivModParamOperation(g_service_locator)); FakeDivModParamOperation::Ref operation_b = FakeDivModParamOperation::Ref( new FakeDivModParamOperation(g_service_locator)); ASSERT_FALSE(operation_a.IsNull()); ASSERT_FALSE(operation_b.IsNull()); // Now check GetInputs Param* input_a_1 = operation_a->GetUntypedParam( FakeDivModParamOperation::kInput1Name); Param* input_a_2 = operation_a->GetUntypedParam( FakeDivModParamOperation::kInput2Name); Param* output_a_1 = operation_a->GetUntypedParam( FakeDivModParamOperation::kOutput1Name); Param* output_a_2 = operation_a->GetUntypedParam( FakeDivModParamOperation::kOutput2Name); Param* input_b_1 = operation_b->GetUntypedParam( FakeDivModParamOperation::kInput1Name); Param* input_b_2 = operation_b->GetUntypedParam( FakeDivModParamOperation::kInput2Name); Param* output_b_1 = operation_b->GetUntypedParam( FakeDivModParamOperation::kOutput1Name); Param* output_b_2 = operation_b->GetUntypedParam( FakeDivModParamOperation::kOutput2Name); ASSERT_TRUE(input_a_1 != NULL); ASSERT_TRUE(input_a_2 != NULL); ASSERT_TRUE(output_a_1 != NULL); ASSERT_TRUE(output_a_2 != NULL); ASSERT_TRUE(input_b_1 != NULL); ASSERT_TRUE(input_b_2 != NULL); ASSERT_TRUE(output_b_1 != NULL); ASSERT_TRUE(output_b_2 != NULL); ParamVector params; // Test with cycle in operation 2 EXPECT_TRUE(input_b_1->Bind(output_a_1)); EXPECT_TRUE(input_b_2->Bind(output_b_1)); // IA1 OA1--->IB1 OB1--+ // [OPA] [OPB] | // IA2 OA2 +->IB2 OB2 | // | | // +-------------+ input_a_1->GetOutputs(&params); EXPECT_EQ(params.size(), 6); EXPECT_TRUE(ParamInParams(output_a_1, params)); EXPECT_TRUE(ParamInParams(output_a_2, params)); EXPECT_TRUE(ParamInParams(output_b_1, params)); EXPECT_TRUE(ParamInParams(output_b_2, params)); EXPECT_TRUE(ParamInParams(input_b_1, params)); EXPECT_TRUE(ParamInParams(input_b_2, params)); // Test with cycle in operation 1 output_b_1->UnbindInput(); input_a_1->Bind(output_a_1); // +------------+ // | | // +->IA1 OA1-+->IB1 OB1 // [OPA] [OPB] // IA2 OA2 IB2 OB2 output_b_1->GetInputs(&params); EXPECT_EQ(params.size(), 5); EXPECT_TRUE(ParamInParams(input_a_1, params)); EXPECT_TRUE(ParamInParams(input_a_2, params)); EXPECT_TRUE(ParamInParams(input_b_1, params)); EXPECT_TRUE(ParamInParams(input_b_2, params)); EXPECT_TRUE(ParamInParams(output_a_1, params)); } TEST_F(ParamObjectTest, ParametersRegisteredAtConstructionTimeAreNotRegardedAsAdded) { FakeDivModParamOperation::Ref operation = FakeDivModParamOperation::Ref( new FakeDivModParamOperation(g_service_locator)); Param* input1 = operation->GetUntypedParam( FakeDivModParamOperation::kInput1Name); EXPECT_FALSE(operation->IsAddedParam(input1)); } TEST_F(ParamObjectTest, ParametersAfterConstructionTimeAreRegardedAsAdded) { FakeDivModParamOperation::Ref operation = FakeDivModParamOperation::Ref( new FakeDivModParamOperation(g_service_locator)); ParamFloat* param = operation->CreateParam<ParamFloat>("param"); EXPECT_TRUE(operation->IsAddedParam(param)); } TEST_F(ParamObjectTest, ParametersOwnedByOtherObjectsAreNotRegardedAsAdded) { FakeDivModParamOperation::Ref operation1 = FakeDivModParamOperation::Ref( new FakeDivModParamOperation(g_service_locator)); ParamFloat* param = operation1->CreateParam<ParamFloat>("param"); FakeDivModParamOperation::Ref operation2 = FakeDivModParamOperation::Ref( new FakeDivModParamOperation(g_service_locator)); EXPECT_FALSE(operation2->IsAddedParam(param)); } } // namespace o3d
34.411885
79
0.73346
zachlatta
0faa1d597a62c211f319bb778d6c4785a7fd52f4
669
hpp
C++
PyMieSim/includes/LMT/includes/Definitions.hpp
MartinPdS/PyMieSim
2560c7f4009df5d05bcb0ce8e929aa7baa7be8de
[ "MIT" ]
6
2021-02-11T17:53:40.000Z
2021-12-11T20:20:01.000Z
PyMieSim/includes/LMT/includes/Definitions.hpp
MartinPdS/PyMieSim
2560c7f4009df5d05bcb0ce8e929aa7baa7be8de
[ "MIT" ]
6
2021-05-12T04:33:26.000Z
2021-11-14T05:25:19.000Z
PyMieSim/includes/LMT/includes/Definitions.hpp
MartinPdS/PyMieSim
2560c7f4009df5d05bcb0ce8e929aa7baa7be8de
[ "MIT" ]
3
2021-05-10T19:46:42.000Z
2021-06-01T19:52:14.000Z
#ifndef DEF_H #define DEF_H #include "pybind11.hpp" typedef unsigned int uint; typedef std::complex<double> complex128; typedef std::vector<double> DVector; typedef std::vector<complex128> CVector; typedef pybind11::array_t<double> ndarray; typedef pybind11::array_t<complex128> Cndarray; typedef std::vector<std::vector<double>> Matrix3; typedef pybind11::array_t<size_t> Indarray; typedef pybind11::buffer_info info; #define J complex128(0.0,1.0) #define PI (double)3.14159265358979323846264338 double EPSILON0 = 8.854187817620389e-12; double C = 299792458.0 ; #endif
25.730769
52
0.67713
MartinPdS
0fac56086f3cd6a06d615db843a6fbb93c6f304b
522
hxx
C++
odb-tests-2.4.0/libcommon/common/config.hxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/libcommon/common/config.hxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
odb-tests-2.4.0/libcommon/common/config.hxx
edidada/odb
78ed750a9dde65a627fc33078225410306c2e78b
[ "MIT" ]
null
null
null
// file : libcommon/common/config.hxx // copyright : Copyright (c) 2005-2015 Code Synthesis Tools CC // license : GNU GPL v2; see accompanying LICENSE file #ifndef LIBCOMMON_COMMON_CONFIG_HXX #define LIBCOMMON_COMMON_CONFIG_HXX #ifdef HAVE_CONFIG_VC_H # include <common/config-vc.h> #else # include <common/config.h> // GCC supports strongly typed enums from 4.4 (forward -- 4.6), // Clang -- 2.9 (3.1). // # ifdef HAVE_CXX11 # define HAVE_CXX11_ENUM # endif #endif #endif // LIBCOMMON_COMMON_CONFIG_HXX
23.727273
63
0.727969
edidada
0fb00e19083d80d78fe062637ed1ce2d727605b0
3,499
cc
C++
ortools/linear_solver/samples/assignment_mip.cc
sreesubbash/or-tools
701496e45d54fa9938afeedec43089314d93ec11
[ "Apache-2.0" ]
1
2021-03-30T21:10:27.000Z
2021-03-30T21:10:27.000Z
ortools/linear_solver/samples/assignment_mip.cc
sreesubbash/or-tools
701496e45d54fa9938afeedec43089314d93ec11
[ "Apache-2.0" ]
null
null
null
ortools/linear_solver/samples/assignment_mip.cc
sreesubbash/or-tools
701496e45d54fa9938afeedec43089314d93ec11
[ "Apache-2.0" ]
null
null
null
// Copyright 2010-2018 Google LLC // 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. // [START program] // [START import] #include <vector> #include "ortools/base/logging.h" #include "ortools/linear_solver/linear_solver.h" // [END import] namespace operations_research { void AssignmentMip() { // Data // [START data_model] const std::vector<std::vector<double>> costs{ {90, 80, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 95}, {45, 110, 95, 115}, {50, 100, 90, 100}, }; const int num_workers = costs.size(); const int num_tasks = costs[0].size(); // [END data_model] // Solver // [START solver] // Create the mip solver with the SCIP backend. MPSolver solver("assignment_mip", MPSolver::SCIP_MIXED_INTEGER_PROGRAMMING); // [END solver] // Variables // [START variables] // x[i][j] is an array of 0-1 variables, which will be 1 // if worker i is assigned to task j. std::vector<std::vector<const MPVariable*>> x( num_workers, std::vector<const MPVariable*>(num_tasks)); for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { x[i][j] = solver.MakeIntVar(0, 1, ""); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int i = 0; i < num_workers; ++i) { LinearExpr worker_sum; for (int j = 0; j < num_tasks; ++j) { worker_sum += x[i][j]; } solver.MakeRowConstraint(worker_sum <= 1.0); } // Each task is assigned to exactly one worker. for (int j = 0; j < num_tasks; ++j) { LinearExpr task_sum; for (int i = 0; i < num_workers; ++i) { task_sum += x[i][j]; } solver.MakeRowConstraint(task_sum == 1.0); } // [END constraints] // Objective. // [START objective] MPObjective* const objective = solver.MutableObjective(); for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { objective->SetCoefficient(x[i][j], costs[i][j]); } } objective->SetMinimization(); // [END objective] // Solve // [START solve] const MPSolver::ResultStatus result_status = solver.Solve(); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (result_status != MPSolver::OPTIMAL & result_status != MPSolver::FEASIBLE) { LOG(FATAL) << "No solution found."; } LOG(INFO) << "Total cost = " << objective->Value() << "\n\n"; for (int i = 0; i < num_workers; ++i) { for (int j = 0; j < num_tasks; ++j) { // Test if x[i][j] is 0 or 1 (with tolerance for floating point // arithmetic). if (x[i][j]->solution_value() > 0.5) { LOG(INFO) << "Worker " << i << " assigned to task " << j << ". Cost = " << costs[i][j]; } } } // [END print_solution] } } // namespace operations_research int main(int argc, char** argv) { operations_research::AssignmentMip(); return EXIT_SUCCESS; } // [END program]
29.652542
78
0.620177
sreesubbash
0fb02bebc89e077559a8771bf8a33cb5817f763a
9,544
cpp
C++
LevelEditor/Edit/EShape.cpp
MlssingTexture/xray-sdk
648de11d78fcc8088e802572da6187ee9b198f9f
[ "CC0-1.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
LevelEditor/Edit/EShape.cpp
MlssingTexture/xray-sdk
648de11d78fcc8088e802572da6187ee9b198f9f
[ "CC0-1.0" ]
null
null
null
LevelEditor/Edit/EShape.cpp
MlssingTexture/xray-sdk
648de11d78fcc8088e802572da6187ee9b198f9f
[ "CC0-1.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
//--------------------------------------------------------------------------- #include "stdafx.h" #pragma hdrstop #include "EShape.h" #include "D3DUtils.h" #include "du_box.h" #include "Scene.h" #define SHAPE_COLOR_TRANSP 0x1800FF00 #define SHAPE_COLOR_EDGE 0xFF202020 //--------------------------------------------------------------------------- #define SHAPE_CURRENT_VERSION 0x0001 //--------------------------------------------------------------------------- #define SHAPE_CHUNK_VERSION 0x0000 #define SHAPE_CHUNK_SHAPES 0x0001 //--------------------------------------------------------------------------- CEditShape::CEditShape(LPVOID data, LPCSTR name):CCustomObject(data,name) { Construct(data); } CEditShape::~CEditShape() { } void CEditShape::Construct(LPVOID data) { ClassID = OBJCLASS_SHAPE; m_DrawTranspColor = SHAPE_COLOR_TRANSP; m_DrawEdgeColor = SHAPE_COLOR_EDGE; m_Box.invalidate(); } void CEditShape::OnUpdateTransform() { inherited::OnUpdateTransform(); } void CEditShape::ComputeBounds() { m_Box.invalidate (); for (ShapeIt it=shapes.begin(); it!=shapes.end(); it++){ switch (it->type){ case cfSphere:{ Fsphere& T = it->data.sphere; Fvector P; P.set (T.P); P.sub(T.R); m_Box.modify(P); P.set (T.P); P.add(T.R); m_Box.modify(P); }break; case cfBox:{ Fvector P; Fmatrix& T = it->data.box; // Build points Fvector p; for (int i=0; i<DU_BOX_NUMVERTEX; i++){ T.transform_tiny (P,du_box_vertices[i]); m_Box.modify (P); } }break; } } m_Box.getsphere(m_Sphere.P,m_Sphere.R); } void CEditShape::SetScale(const Fvector& val) { if (shapes.size()==1){ switch (shapes[0].type){ case cfSphere:{ FScale.set(val.x,val.x,val.x); }break; case cfBox: FScale.set(val.x,val.y,val.z); break; default: THROW; } }else{ FScale.set(val.x,val.x,val.x); } ComputeBounds (); UpdateTransform (); } void CEditShape::ApplyScale() { for (ShapeIt it=shapes.begin(); it!=shapes.end(); it++){ switch (it->type){ case cfSphere:{ Fsphere& T = it->data.sphere; FTransformS.transform_tiny(T.P); T.R *= PScale.x; }break; case cfBox:{ Fmatrix& B = it->data.box; B.mulA_43 (FTransformS); }break; } } FScale.set (1.f,1.f,1.f); UpdateTransform (true); ComputeBounds (); } void CEditShape::add_sphere(const Fsphere& S) { shapes.push_back(shape_def()); shapes.back().type = cfSphere; shapes.back().data.sphere.set(S); ComputeBounds(); } void CEditShape::add_box(const Fmatrix& B) { shapes.push_back(shape_def()); shapes.back().type = cfBox; shapes.back().data.box.set(B); ComputeBounds(); } void CEditShape::Attach(CEditShape* from) { ApplyScale (); // transfer data from->ApplyScale (); Fmatrix M = from->_Transform(); M.mulA_43 (_ITransform()); for (ShapeIt it=from->shapes.begin(); it!=from->shapes.end(); it++){ switch (it->type){ case cfSphere:{ Fsphere& T = it->data.sphere; M.transform_tiny(T.P); add_sphere (T); }break; case cfBox:{ Fmatrix B = it->data.box; B.mulA_43 (M); add_box (B); }break; default: THROW; } } // common Scene->RemoveObject (from,true); xr_delete (from); ComputeBounds (); } void CEditShape::Detach() { if (shapes.size()>1){ Select (true); ApplyScale (); // create scene shapes const Fmatrix& M = _Transform(); ShapeIt it=shapes.begin(); it++; for (; it!=shapes.end(); it++){ string256 namebuffer; Scene->GenObjectName (OBJCLASS_SHAPE, namebuffer, Name); CEditShape* shape = (CEditShape*)Scene->GetOTools(ClassID)->CreateObject(0, namebuffer); switch (it->type){ case cfSphere:{ Fsphere T = it->data.sphere; M.transform_tiny(T.P); shape->PPosition= T.P; T.P.set (0,0,0); shape->add_sphere(T); }break; case cfBox:{ Fmatrix B = it->data.box; B.mulA_43 (M); shape->PPosition= B.c; B.c.set (0,0,0); shape->add_box (B); }break; default: THROW; } Scene->AppendObject (shape,false); shape->Select (true); } // erase shapes in base object it=shapes.begin(); it++; shapes.erase(it,shapes.end()); ComputeBounds(); Scene->UndoSave(); } } bool CEditShape::RayPick(float& distance, const Fvector& start, const Fvector& direction, SRayPickInfo* pinf) { float dist = distance; for (ShapeIt it=shapes.begin(); it!=shapes.end(); it++){ switch (it->type){ case cfSphere:{ Fvector S,D; Fmatrix M; M.invert (FTransformR); M.transform_dir (D,direction); FITransform.transform_tiny(S,start); Fsphere& T = it->data.sphere; T.intersect (S,D,dist); if (dist<=0.f) dist = distance; }break; case cfBox:{ Fbox box; box.identity (); Fmatrix BI; BI.invert (it->data.box); Fvector S,D,S1,D1,P; FITransform.transform_tiny (S,start); FITransform.transform_dir (D,direction); BI.transform_tiny (S1,S); BI.transform_dir (D1,D); Fbox::ERP_Result rp_res = box.Pick2(S1,D1,P); if (rp_res==Fbox::rpOriginOutside){ it->data.box.transform_tiny (P); FTransform.transform_tiny (P); P.sub (start); dist = P.magnitude(); } }break; } } if (dist<distance){ distance = dist; return true; } return false; } bool CEditShape::FrustumPick(const CFrustum& frustum) { const Fmatrix& M = _Transform(); for (ShapeIt it=shapes.begin(); it!=shapes.end(); it++){ switch (it->type){ case cfSphere:{ Fvector C; Fsphere& T = it->data.sphere; M.transform_tiny(C,T.P); if (frustum.testSphere_dirty(C,T.R*FScale.x)) return true; }break; case cfBox:{ Fbox box; box.identity (); Fmatrix B = it->data.box; B.mulA_43 (_Transform()); box.xform (B); u32 mask = 0xff; if (frustum.testAABB(box.data(),mask)) return true; }break; } } return false; } bool CEditShape::GetBox(Fbox& box) { if (m_Box.is_valid()){ box.xform(m_Box,FTransform); return true; } return false; } bool CEditShape::Load(IReader& F) { R_ASSERT(F.find_chunk(SHAPE_CHUNK_VERSION)); u16 vers = F.r_u16(); if (SHAPE_CURRENT_VERSION!=vers){ ELog.DlgMsg( mtError, "CEditShape: unsupported version. Object can't load."); return false; } inherited::Load (F); R_ASSERT(F.find_chunk(SHAPE_CHUNK_SHAPES)); shapes.resize (F.r_u32()); F.r (shapes.begin(),shapes.size()*sizeof(shape_def)); ComputeBounds(); return true; } void CEditShape::Save(IWriter& F) { inherited::Save (F); F.open_chunk (SHAPE_CHUNK_VERSION); F.w_u16 (SHAPE_CURRENT_VERSION); F.close_chunk (); F.open_chunk (SHAPE_CHUNK_SHAPES); F.w_u32 (shapes.size()); F.w (shapes.begin(),shapes.size()*sizeof(shape_def)); F.close_chunk (); } void CEditShape::FillProp(LPCSTR pref, PropItemVec& values) { inherited::FillProp(pref,values); } void CEditShape::Render(int priority, bool strictB2F) { inherited::Render(priority, strictB2F); if (1==priority){ if (strictB2F){ Device.SetShader (Device.m_WireShader); Device.SetRS (D3DRS_CULLMODE,D3DCULL_NONE); u32 clr = Selected()?subst_alpha(m_DrawTranspColor, color_get_A(m_DrawTranspColor)*2):m_DrawTranspColor; Fvector zero ={0.f,0.f,0.f}; for (ShapeIt it=shapes.begin(); it!=shapes.end(); it++){ switch(it->type){ case cfSphere:{ Fsphere& S = it->data.sphere; Fmatrix B; B.scale (S.R,S.R,S.R); B.translate_over (S.P); B.mulA_43 (_Transform()); RCache.set_xform_world(B); Device.SetShader (Device.m_WireShader); DU.DrawCross (zero,1.f,m_DrawEdgeColor,false); DU.DrawIdentSphere (true,true,clr,m_DrawEdgeColor); }break; case cfBox: Fmatrix B = it->data.box; B.mulA_43 (_Transform()); RCache.set_xform_world(B); DU.DrawIdentBox (true,true,clr,m_DrawEdgeColor); break; } } Device.SetRS(D3DRS_CULLMODE,D3DCULL_CCW); }else{ if( Selected()&&m_Box.is_valid() ){ Device.SetShader (Device.m_SelectionShader); RCache.set_xform_world (_Transform()); u32 clr = Locked()?0xFFFF0000:0xFFFFFFFF; Device.SetShader (Device.m_WireShader); DU.DrawSelectionBox (m_Box,&clr); } } } } void CEditShape::OnFrame() { inherited::OnFrame(); } void CEditShape::OnShowHint(AStringVec& dest) { }
26.292011
121
0.538977
MlssingTexture
0fb271150037c157633a72bd0ce5156b7569951d
3,387
cpp
C++
lib/Runtime/Base/LeaveScriptObject.cpp
Taritsyn/ChakraCore
b6042191545a823fcf9d53df2b09d160d5808f51
[ "MIT" ]
8,664
2016-01-13T17:33:19.000Z
2019-05-06T19:55:36.000Z
lib/Runtime/Base/LeaveScriptObject.cpp
Taritsyn/ChakraCore
b6042191545a823fcf9d53df2b09d160d5808f51
[ "MIT" ]
5,058
2016-01-13T17:57:02.000Z
2019-05-04T15:41:54.000Z
lib/Runtime/Base/LeaveScriptObject.cpp
Taritsyn/ChakraCore
b6042191545a823fcf9d53df2b09d160d5808f51
[ "MIT" ]
1,367
2016-01-13T17:54:57.000Z
2019-04-29T18:16:27.000Z
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeBasePch.h" namespace Js { EnterScriptObject::EnterScriptObject(ScriptContext* scriptContext, ScriptEntryExitRecord* entryExitRecord, void * returnAddress, void * addrOfReturnAddress, bool doCleanup, bool isCallRoot, bool hasCaller) { Assert(scriptContext); #ifdef PROFILE_EXEC scriptContext->ProfileBegin(Js::RunPhase); #endif if (scriptContext->GetThreadContext() && scriptContext->GetThreadContext()->IsNoScriptScope()) { FromDOM_NoScriptScope_unrecoverable_error(); } // Keep a copy locally so the optimizer can just copy prop it to the dtor this->scriptContext = scriptContext; this->entryExitRecord = entryExitRecord; this->doCleanup = doCleanup; this->isCallRoot = isCallRoot; this->hr = NOERROR; this->hasForcedEnter = #ifdef ENABLE_SCRIPT_DEBUGGING scriptContext->GetDebugContext() != nullptr ? scriptContext->GetDebugContext()->GetProbeContainer()->isForcedToEnterScriptStart : #endif false; // Initialize the entry exit record entryExitRecord->returnAddrOfScriptEntryFunction = returnAddress; entryExitRecord->addrOfReturnAddrOfScriptEntryFunction = addrOfReturnAddress; entryExitRecord->hasCaller = hasCaller; entryExitRecord->scriptContext = scriptContext; #ifdef EXCEPTION_CHECK entryExitRecord->handledExceptionType = ExceptionCheck::ClearHandledExceptionType(); #endif #if DBG_DUMP entryExitRecord->isCallRoot = isCallRoot; #endif if (!scriptContext->IsClosed()) { library = scriptContext->GetLibrary(); } try { AUTO_NESTED_HANDLED_EXCEPTION_TYPE(ExceptionType_OutOfMemory); scriptContext->GetThreadContext()->PushHostScriptContext(scriptContext->GetHostScriptContext()); } catch (Js::OutOfMemoryException) { this->hr = E_OUTOFMEMORY; } BEGIN_NO_EXCEPTION { // We can not have any exception in the constructor, otherwise the destructor will // not run and we might be in an inconsistent state // Put any code that may raise an exception in OnScriptStart scriptContext->GetThreadContext()->EnterScriptStart(entryExitRecord, doCleanup); } END_NO_EXCEPTION } void EnterScriptObject::VerifyEnterScript() { if (FAILED(hr)) { Assert(hr == E_OUTOFMEMORY); throw Js::OutOfMemoryException(); } } EnterScriptObject::~EnterScriptObject() { scriptContext->OnScriptEnd(isCallRoot, hasForcedEnter); if (SUCCEEDED(hr)) { scriptContext->GetThreadContext()->PopHostScriptContext(); } scriptContext->GetThreadContext()->EnterScriptEnd(entryExitRecord, doCleanup); #ifdef PROFILE_EXEC scriptContext->ProfileEnd(Js::RunPhase); #endif } };
36.031915
110
0.621494
Taritsyn
0fb2b454ad764f7497dca7878910bee3ca701238
13,698
cc
C++
base/timer/timer_unittest.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
231
2015-01-08T09:04:44.000Z
2021-12-30T03:03:10.000Z
base/timer/timer_unittest.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-02-09T06:38:05.000Z
2016-09-30T00:47:01.000Z
base/timer/timer_unittest.cc
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
268
2015-01-21T05:53:28.000Z
2022-03-25T22:09:01.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/memory/scoped_ptr.h" #include "base/message_loop/message_loop.h" #include "base/timer/timer.h" #include "testing/gtest/include/gtest/gtest.h" using base::TimeDelta; namespace { // The message loops on which each timer should be tested. const base::MessageLoop::Type testing_message_loops[] = { base::MessageLoop::TYPE_DEFAULT, base::MessageLoop::TYPE_IO, #if !defined(OS_IOS) // iOS does not allow direct running of the UI loop. base::MessageLoop::TYPE_UI, #endif }; const int kNumTestingMessageLoops = arraysize(testing_message_loops); class OneShotTimerTester { public: explicit OneShotTimerTester(bool* did_run, unsigned milliseconds = 10) : did_run_(did_run), delay_ms_(milliseconds) { } void Start() { timer_.Start(FROM_HERE, TimeDelta::FromMilliseconds(delay_ms_), this, &OneShotTimerTester::Run); } private: void Run() { *did_run_ = true; base::MessageLoop::current()->QuitWhenIdle(); } bool* did_run_; base::OneShotTimer<OneShotTimerTester> timer_; const unsigned delay_ms_; }; class OneShotSelfDeletingTimerTester { public: explicit OneShotSelfDeletingTimerTester(bool* did_run) : did_run_(did_run), timer_(new base::OneShotTimer<OneShotSelfDeletingTimerTester>()) { } void Start() { timer_->Start(FROM_HERE, TimeDelta::FromMilliseconds(10), this, &OneShotSelfDeletingTimerTester::Run); } private: void Run() { *did_run_ = true; timer_.reset(); base::MessageLoop::current()->QuitWhenIdle(); } bool* did_run_; scoped_ptr<base::OneShotTimer<OneShotSelfDeletingTimerTester> > timer_; }; class RepeatingTimerTester { public: explicit RepeatingTimerTester(bool* did_run, const TimeDelta& delay) : did_run_(did_run), counter_(10), delay_(delay) { } void Start() { timer_.Start(FROM_HERE, delay_, this, &RepeatingTimerTester::Run); } private: void Run() { if (--counter_ == 0) { *did_run_ = true; timer_.Stop(); base::MessageLoop::current()->QuitWhenIdle(); } } bool* did_run_; int counter_; TimeDelta delay_; base::RepeatingTimer<RepeatingTimerTester> timer_; }; void RunTest_OneShotTimer(base::MessageLoop::Type message_loop_type) { base::MessageLoop loop(message_loop_type); bool did_run = false; OneShotTimerTester f(&did_run); f.Start(); base::MessageLoop::current()->Run(); EXPECT_TRUE(did_run); } void RunTest_OneShotTimer_Cancel(base::MessageLoop::Type message_loop_type) { base::MessageLoop loop(message_loop_type); bool did_run_a = false; OneShotTimerTester* a = new OneShotTimerTester(&did_run_a); // This should run before the timer expires. base::MessageLoop::current()->DeleteSoon(FROM_HERE, a); // Now start the timer. a->Start(); bool did_run_b = false; OneShotTimerTester b(&did_run_b); b.Start(); base::MessageLoop::current()->Run(); EXPECT_FALSE(did_run_a); EXPECT_TRUE(did_run_b); } void RunTest_OneShotSelfDeletingTimer( base::MessageLoop::Type message_loop_type) { base::MessageLoop loop(message_loop_type); bool did_run = false; OneShotSelfDeletingTimerTester f(&did_run); f.Start(); base::MessageLoop::current()->Run(); EXPECT_TRUE(did_run); } void RunTest_RepeatingTimer(base::MessageLoop::Type message_loop_type, const TimeDelta& delay) { base::MessageLoop loop(message_loop_type); bool did_run = false; RepeatingTimerTester f(&did_run, delay); f.Start(); base::MessageLoop::current()->Run(); EXPECT_TRUE(did_run); } void RunTest_RepeatingTimer_Cancel(base::MessageLoop::Type message_loop_type, const TimeDelta& delay) { base::MessageLoop loop(message_loop_type); bool did_run_a = false; RepeatingTimerTester* a = new RepeatingTimerTester(&did_run_a, delay); // This should run before the timer expires. base::MessageLoop::current()->DeleteSoon(FROM_HERE, a); // Now start the timer. a->Start(); bool did_run_b = false; RepeatingTimerTester b(&did_run_b, delay); b.Start(); base::MessageLoop::current()->Run(); EXPECT_FALSE(did_run_a); EXPECT_TRUE(did_run_b); } class DelayTimerTarget { public: DelayTimerTarget() : signaled_(false) { } bool signaled() const { return signaled_; } void Signal() { ASSERT_FALSE(signaled_); signaled_ = true; } private: bool signaled_; }; void RunTest_DelayTimer_NoCall(base::MessageLoop::Type message_loop_type) { base::MessageLoop loop(message_loop_type); // If Delay is never called, the timer shouldn't go off. DelayTimerTarget target; base::DelayTimer<DelayTimerTarget> timer(FROM_HERE, TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal); bool did_run = false; OneShotTimerTester tester(&did_run); tester.Start(); base::MessageLoop::current()->Run(); ASSERT_FALSE(target.signaled()); } void RunTest_DelayTimer_OneCall(base::MessageLoop::Type message_loop_type) { base::MessageLoop loop(message_loop_type); DelayTimerTarget target; base::DelayTimer<DelayTimerTarget> timer(FROM_HERE, TimeDelta::FromMilliseconds(1), &target, &DelayTimerTarget::Signal); timer.Reset(); bool did_run = false; OneShotTimerTester tester(&did_run, 100 /* milliseconds */); tester.Start(); base::MessageLoop::current()->Run(); ASSERT_TRUE(target.signaled()); } struct ResetHelper { ResetHelper(base::DelayTimer<DelayTimerTarget>* timer, DelayTimerTarget* target) : timer_(timer), target_(target) { } void Reset() { ASSERT_FALSE(target_->signaled()); timer_->Reset(); } private: base::DelayTimer<DelayTimerTarget> *const timer_; DelayTimerTarget *const target_; }; void RunTest_DelayTimer_Reset(base::MessageLoop::Type message_loop_type) { base::MessageLoop loop(message_loop_type); // If Delay is never called, the timer shouldn't go off. DelayTimerTarget target; base::DelayTimer<DelayTimerTarget> timer(FROM_HERE, TimeDelta::FromMilliseconds(50), &target, &DelayTimerTarget::Signal); timer.Reset(); ResetHelper reset_helper(&timer, &target); base::OneShotTimer<ResetHelper> timers[20]; for (size_t i = 0; i < arraysize(timers); ++i) { timers[i].Start(FROM_HERE, TimeDelta::FromMilliseconds(i * 10), &reset_helper, &ResetHelper::Reset); } bool did_run = false; OneShotTimerTester tester(&did_run, 300); tester.Start(); base::MessageLoop::current()->Run(); ASSERT_TRUE(target.signaled()); } class DelayTimerFatalTarget { public: void Signal() { ASSERT_TRUE(false); } }; void RunTest_DelayTimer_Deleted(base::MessageLoop::Type message_loop_type) { base::MessageLoop loop(message_loop_type); DelayTimerFatalTarget target; { base::DelayTimer<DelayTimerFatalTarget> timer( FROM_HERE, TimeDelta::FromMilliseconds(50), &target, &DelayTimerFatalTarget::Signal); timer.Reset(); } // When the timer is deleted, the DelayTimerFatalTarget should never be // called. base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(100)); } } // namespace //----------------------------------------------------------------------------- // Each test is run against each type of MessageLoop. That way we are sure // that timers work properly in all configurations. TEST(TimerTest, OneShotTimer) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_OneShotTimer(testing_message_loops[i]); } } TEST(TimerTest, OneShotTimer_Cancel) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_OneShotTimer_Cancel(testing_message_loops[i]); } } // If underline timer does not handle properly, we will crash or fail // in full page heap environment. TEST(TimerTest, OneShotSelfDeletingTimer) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_OneShotSelfDeletingTimer(testing_message_loops[i]); } } TEST(TimerTest, RepeatingTimer) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_RepeatingTimer(testing_message_loops[i], TimeDelta::FromMilliseconds(10)); } } TEST(TimerTest, RepeatingTimer_Cancel) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_RepeatingTimer_Cancel(testing_message_loops[i], TimeDelta::FromMilliseconds(10)); } } TEST(TimerTest, RepeatingTimerZeroDelay) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_RepeatingTimer(testing_message_loops[i], TimeDelta::FromMilliseconds(0)); } } TEST(TimerTest, RepeatingTimerZeroDelay_Cancel) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_RepeatingTimer_Cancel(testing_message_loops[i], TimeDelta::FromMilliseconds(0)); } } TEST(TimerTest, DelayTimer_NoCall) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_DelayTimer_NoCall(testing_message_loops[i]); } } TEST(TimerTest, DelayTimer_OneCall) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_DelayTimer_OneCall(testing_message_loops[i]); } } // It's flaky on the buildbot, http://crbug.com/25038. TEST(TimerTest, DISABLED_DelayTimer_Reset) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_DelayTimer_Reset(testing_message_loops[i]); } } TEST(TimerTest, DelayTimer_Deleted) { for (int i = 0; i < kNumTestingMessageLoops; i++) { RunTest_DelayTimer_Deleted(testing_message_loops[i]); } } TEST(TimerTest, MessageLoopShutdown) { // This test is designed to verify that shutdown of the // message loop does not cause crashes if there were pending // timers not yet fired. It may only trigger exceptions // if debug heap checking is enabled. bool did_run = false; { OneShotTimerTester a(&did_run); OneShotTimerTester b(&did_run); OneShotTimerTester c(&did_run); OneShotTimerTester d(&did_run); { base::MessageLoop loop; a.Start(); b.Start(); } // MessageLoop destructs by falling out of scope. } // OneShotTimers destruct. SHOULD NOT CRASH, of course. EXPECT_FALSE(did_run); } void TimerTestCallback() { } TEST(TimerTest, NonRepeatIsRunning) { { base::MessageLoop loop; base::Timer timer(false, false); EXPECT_FALSE(timer.IsRunning()); timer.Start(FROM_HERE, TimeDelta::FromDays(1), base::Bind(&TimerTestCallback)); EXPECT_TRUE(timer.IsRunning()); timer.Stop(); EXPECT_FALSE(timer.IsRunning()); EXPECT_TRUE(timer.user_task().is_null()); } { base::Timer timer(true, false); base::MessageLoop loop; EXPECT_FALSE(timer.IsRunning()); timer.Start(FROM_HERE, TimeDelta::FromDays(1), base::Bind(&TimerTestCallback)); EXPECT_TRUE(timer.IsRunning()); timer.Stop(); EXPECT_FALSE(timer.IsRunning()); ASSERT_FALSE(timer.user_task().is_null()); timer.Reset(); EXPECT_TRUE(timer.IsRunning()); } } TEST(TimerTest, NonRepeatMessageLoopDeath) { base::Timer timer(false, false); { base::MessageLoop loop; EXPECT_FALSE(timer.IsRunning()); timer.Start(FROM_HERE, TimeDelta::FromDays(1), base::Bind(&TimerTestCallback)); EXPECT_TRUE(timer.IsRunning()); } EXPECT_FALSE(timer.IsRunning()); EXPECT_TRUE(timer.user_task().is_null()); } TEST(TimerTest, RetainRepeatIsRunning) { base::MessageLoop loop; base::Timer timer(FROM_HERE, TimeDelta::FromDays(1), base::Bind(&TimerTestCallback), true); EXPECT_FALSE(timer.IsRunning()); timer.Reset(); EXPECT_TRUE(timer.IsRunning()); timer.Stop(); EXPECT_FALSE(timer.IsRunning()); timer.Reset(); EXPECT_TRUE(timer.IsRunning()); } TEST(TimerTest, RetainNonRepeatIsRunning) { base::MessageLoop loop; base::Timer timer(FROM_HERE, TimeDelta::FromDays(1), base::Bind(&TimerTestCallback), false); EXPECT_FALSE(timer.IsRunning()); timer.Reset(); EXPECT_TRUE(timer.IsRunning()); timer.Stop(); EXPECT_FALSE(timer.IsRunning()); timer.Reset(); EXPECT_TRUE(timer.IsRunning()); } namespace { bool g_callback_happened1 = false; bool g_callback_happened2 = false; void ClearAllCallbackHappened() { g_callback_happened1 = false; g_callback_happened2 = false; } void SetCallbackHappened1() { g_callback_happened1 = true; base::MessageLoop::current()->QuitWhenIdle(); } void SetCallbackHappened2() { g_callback_happened2 = true; base::MessageLoop::current()->QuitWhenIdle(); } TEST(TimerTest, ContinuationStopStart) { { ClearAllCallbackHappened(); base::MessageLoop loop; base::Timer timer(false, false); timer.Start(FROM_HERE, TimeDelta::FromMilliseconds(10), base::Bind(&SetCallbackHappened1)); timer.Stop(); timer.Start(FROM_HERE, TimeDelta::FromMilliseconds(40), base::Bind(&SetCallbackHappened2)); base::MessageLoop::current()->Run(); EXPECT_FALSE(g_callback_happened1); EXPECT_TRUE(g_callback_happened2); } } TEST(TimerTest, ContinuationReset) { { ClearAllCallbackHappened(); base::MessageLoop loop; base::Timer timer(false, false); timer.Start(FROM_HERE, TimeDelta::FromMilliseconds(10), base::Bind(&SetCallbackHappened1)); timer.Reset(); // Since Reset happened before task ran, the user_task must not be cleared: ASSERT_FALSE(timer.user_task().is_null()); base::MessageLoop::current()->Run(); EXPECT_TRUE(g_callback_happened1); } } } // namespace
26.911591
79
0.692291
Fusion-Rom
0fb37ddb3511f8d7dc230cecf93992477b3f74ec
1,985
cc
C++
src/developer/forensics/exceptions/handler_manager.cc
EnderNightLord-ChromeBook/zircon-rpi
b09b1eb3aa7a127c65568229fe10edd251869283
[ "BSD-2-Clause" ]
14
2020-10-25T05:48:36.000Z
2021-09-20T02:46:20.000Z
src/developer/forensics/exceptions/handler_manager.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
null
null
null
src/developer/forensics/exceptions/handler_manager.cc
DamieFC/fuchsia
f78a4a1326f4a4bb5834500918756173c01bab4f
[ "BSD-2-Clause" ]
2
2022-02-25T12:22:49.000Z
2022-03-12T03:20:10.000Z
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. #include "src/developer/forensics/exceptions/handler_manager.h" namespace forensics { namespace exceptions { HandlerManager::HandlerManager(async_dispatcher_t* dispatcher, size_t max_num_handlers, zx::duration exception_ttl) : dispatcher_(dispatcher), exception_ttl_(exception_ttl) { handlers_.reserve(max_num_handlers); for (size_t i = 0; i < max_num_handlers; ++i) { handlers_.emplace_back(dispatcher_, /*on_available=*/[i, this] { // Push to the front so already initialized handlers are used first. available_handlers_.push_front(i); HandleNextPendingException(); }); available_handlers_.emplace_back(i); } } void HandlerManager::Handle(zx::exception exception) { pending_exceptions_.emplace_back(dispatcher_, exception_ttl_, std::move(exception)); HandleNextPendingException(); } void HandlerManager::HandleNextPendingException() { if (pending_exceptions_.empty() || available_handlers_.empty()) { return; } // We must reserve all state needed to handle the exception (the handler and the exception) and // remove it from the queues prior to actually handling the exception. This is done to prevent // that state from being erroneously being reused when ProcessHandler::Handle ends up calling // HandleNextPendingException on a failure. const size_t handler_idx = available_handlers_.front(); available_handlers_.pop_front(); zx::exception exception = pending_exceptions_.front().TakeException(); zx::process process = pending_exceptions_.front().TakeProcess(); zx::thread thread = pending_exceptions_.front().TakeThread(); pending_exceptions_.pop_front(); handlers_[handler_idx].Handle(std::move(exception), std::move(process), std::move(thread)); } } // namespace exceptions } // namespace forensics
38.921569
100
0.748111
EnderNightLord-ChromeBook
0fb39d8862baeda7c568b8029e112bf159f96684
978
cpp
C++
10487/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
10487/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
10487/src.cpp
sabingoyek/uva-online-judge
78be271d440ff3b9b1b038fb83343ba46ea60843
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { // your code goes here int n, test_case = 0; while(true){ scanf("%d", &n); if(n == 0){ break; } else{ test_case++; vector<int> numbers; int tmp, m; for(int i = 0; i < n; i++){ scanf("%d", &tmp); numbers.push_back(tmp); } /*for(int i = 0; i < n; i++) printf("%d ", numbers[i]); printf("\n");*/ vector<int>sum; for(int i = 0; i < n; i++){ for(int j = i+1; j < n; j++){ sum.push_back(numbers[i] + numbers[j]); } } /* for(int i = 0; i < sum.size(); i++) printf("%d ", sum[i]); printf("\n");*/ scanf("%d", &m); int q; printf("Case %d:\n", test_case); for(int i = 0; i < m; i++){ scanf("%d", &q); int ans = sum[0]; for(int i = 1; i < sum.size(); i++){ if(abs(sum[i] - q) < abs(ans - q)){ ans = sum[i]; } } printf("Closest sum to %d is %d.\n", q, ans); } } } return 0; }
16.862069
49
0.445808
sabingoyek
0fb7dba0d35ba3341831e928733118eeeb60c1bb
1,040
cpp
C++
p1130.cpp
ThinkiNOriginal/PTA-Advanced
55cae28f76102964d0f6fd728dd62d6eba980c49
[ "MIT" ]
null
null
null
p1130.cpp
ThinkiNOriginal/PTA-Advanced
55cae28f76102964d0f6fd728dd62d6eba980c49
[ "MIT" ]
null
null
null
p1130.cpp
ThinkiNOriginal/PTA-Advanced
55cae28f76102964d0f6fd728dd62d6eba980c49
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <vector> #include <algorithm> #include <cstring> using namespace std; struct Node { string val; Node* left; Node* right; }; string infix(Node* tree) { static string res; if (tree) { if (tree -> left or tree -> right) res += '('; infix(tree -> left); res += tree -> val; infix(tree -> right); if (tree -> right or tree -> left) res += ')'; } return res; } int main() { int N; scanf("%d", &N); vector<Node> tree(N + 1); vector<bool> root(N + 1, true); for (int i = 1; i <= N; i++) { string val; int l, r; cin >> val >> l >> r; tree[i].val = val; if (l != -1) { tree[i].left = &tree[l]; root[l] = false; } if (r != -1) { tree[i].right = &tree[r]; root[r]= false; } } int rootP = -1; for (int i = 1; i <= N; i++) { if (root[i]) { rootP = i; break; } } auto res = infix(&tree[rootP]); int len = res.size(); if (res[0] == '(') { res.erase(len - 1, 1); res.erase(0, 1); } cout << res << endl; return 0; }
14.246575
36
0.511538
ThinkiNOriginal
0fb849a6834497762b912d4b63ba262c1e1710d9
13,486
cpp
C++
client/publishdialog.cpp
vorushin/moodbox_aka_risovaska
5943452e4c7fc9e3c828f62f565cd2da9a040e92
[ "MIT" ]
1
2015-08-23T11:03:58.000Z
2015-08-23T11:03:58.000Z
client/publishdialog.cpp
vorushin/moodbox_aka_risovaska
5943452e4c7fc9e3c828f62f565cd2da9a040e92
[ "MIT" ]
null
null
null
client/publishdialog.cpp
vorushin/moodbox_aka_risovaska
5943452e4c7fc9e3c828f62f565cd2da9a040e92
[ "MIT" ]
3
2016-12-05T02:43:52.000Z
2021-06-30T21:35:46.000Z
#include "publishdialog.h" #include <QClipboard> #include <QDateTime> #include <QMessageBox> #include <QUrl> #include <QDesktopServices> #include "messagemanager.h" #include "logondataprovider.h" #include "blogtools.h" #include "testtools.h" namespace MoodBox { PublishDialog::PublishDialog(QWidget *parent) : MoodBoxDialog(parent), publishRequestId(0), publishRecipientId(-1), loginsLoaded(false) { TimeMeasure t("PublishDialog"); setupUi(this); t.showTimePassedAfterSetupUi(); UiTools::moveWindowToScreenCenter(this); typeCombo->addItem(tr(PUBLISHING_TYPE_LIVEJOURNAL_TEXT)); #ifdef RUSSIAN_VERSION typeCombo->addItem(tr(PUBLISHING_TYPE_LIVEINTERNET_TEXT)); typeCombo->addItem(tr(PUBLISHING_TYPE_DAIRY_TEXT)); #endif restorePublishParameters(); // Control signals connect(closeToolButton, SIGNAL(clicked()), this, SLOT(reject())); connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject())); connect(cancelPublishingButton, SIGNAL(clicked()), this, SLOT(reject())); connect(closeButton, SIGNAL(clicked()), this, SLOT(accept())); connect(moodstripNameEdit, SIGNAL(textChanged(const QString &)), this, SLOT(publishEnabled())); connect(typeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(loadPublishingParameters(int))); // Publishing signals connect(MESSAGEMANAGER, SIGNAL(publishing(qint32, qint32)), this, SLOT(onPublishProgress(qint32, qint32))); connect(MESSAGEMANAGER, SIGNAL(publishCompleted(qint32, qint32, const QList<PublishingWay> &)), this, SLOT(onPublishCompleted(qint32, qint32, const QList<PublishingWay> &))); connect(MESSAGEMANAGER, SIGNAL(publishError(qint32)), this, SLOT(onPublishError(qint32))); // Update values on_blogCheckBox_stateChanged(blogCheckBox->checkState()); openOptionsPage(); } void PublishDialog::showEvent(QShowEvent * event) { hiddenCheckBox->setChecked(false); moodstripNameEdit->clear(); moodstripNameEdit->setFocus(); postText->clear(); QWidget::showEvent(event); } void PublishDialog::setMessages(const QList<PublishMessageInfo> &messages) { this->messages = messages; } void PublishDialog::cleanup() { loginCombo->clear(); passwordEdit->clear(); } void PublishDialog::accept() { MoodBoxDialog::accept(); openOptionsPage(); } void PublishDialog::reject() { if (publishRequestId) { MESSAGEMANAGER->cancelPublish(publishRequestId); publishRequestId = 0; } MoodBoxDialog::reject(); openOptionsPage(); } void PublishDialog::setPage(int pageNum) { stackedWidget->setCurrentIndex(pageNum); } void PublishDialog::openOptionsPage() { setPage(Options); publishRequestId = 0; } void PublishDialog::openProgressPage() { setPage(Progress); setPublishingProgress(0); } void PublishDialog::openResultPage() { setPage(Result); show(); raise(); activateWindow(); } void PublishDialog::setPublishingProgress(int progress) { publishingProgressBar->setValue(progress); } void PublishDialog::copyToClipboard(QString text) { QApplication::clipboard()->setText(text); } void PublishDialog::startPublishing() { publishRequestId = QDateTime::currentDateTime().toTime_t(); MESSAGEMANAGER->publishMoodstrip(publishRequestId, moodstripNameEdit->text(), messages, hiddenCheckBox->isChecked(), publishRecipientId); } void PublishDialog::startBlogLoginCheck() { switch (typeCombo->currentIndex()) { case LIVEJOURNAL_TYPE_INDEX: ljPoster->checkLoginAndPassword(loginCombo->lineEdit()->text(), passwordEdit->text()); break; case LIVEINTERNET_TYPE_INDEX: liPoster->checkLoginAndPassword(loginCombo->lineEdit()->text(), passwordEdit->text()); break; case DIARY_TYPE_INDEX: diaryPoster->checkLoginAndPassword(loginCombo->lineEdit()->text(), passwordEdit->text()); break; } } void PublishDialog::postToBlog() { QString text; switch (typeCombo->currentIndex()) { case LIVEJOURNAL_TYPE_INDEX: case DIARY_TYPE_INDEX: switch (methodCombo->currentIndex()) { case 0: text = embedEdit->text(); break; case 1: text = embedMoodstripEdit->text(); break; case 2: text = embedMoodstripCutEdit->text(); break; }; break; case LIVEINTERNET_TYPE_INDEX: text = embedMoodstripEdit->text(); break; } switch (typeCombo->currentIndex()) { case LIVEJOURNAL_TYPE_INDEX: text = BlogPoster::getEscapedString(postText->toPlainText() + "\n" + text); break; case DIARY_TYPE_INDEX: text = BlogPoster::getHtmlString(postText->toPlainText() + "\n" + text); break; case LIVEINTERNET_TYPE_INDEX: text = postText->toPlainText() + "\n" + text; break; } switch (typeCombo->currentIndex()) { case LIVEJOURNAL_TYPE_INDEX: ljPoster->post(loginCombo->lineEdit()->text(), passwordEdit->text(), moodstripNameEdit->text(), text, true); break; case LIVEINTERNET_TYPE_INDEX: liPoster->post(loginCombo->lineEdit()->text(), passwordEdit->text(), moodstripNameEdit->text(), text, true); break; case DIARY_TYPE_INDEX: diaryPoster->post(loginCombo->lineEdit()->text(), passwordEdit->text(), moodstripNameEdit->text(), text, true); break; } } void PublishDialog::restorePublishParameters() { QSettings settings; settings.beginGroup(SERVICELOGONPROVIDER->getMainSubgroup()); settings.beginGroup(SERVICELOGONPROVIDER->getSettingsSubgroup()); int m = settings.value(PUBLISHING_TYPE_OPTION, 1).toInt(); if (m < 0) m = 1; else if (m >= typeCombo->count()) m = typeCombo->count() - 1; typeCombo->setCurrentIndex(m); m = settings.value(PUBLISHING_METHOD_OPTION, 1).toInt(); if (m < 0) m = 1; else if (m >= methodCombo->count()) m = methodCombo->count() - 1; methodCombo->setCurrentIndex(m); blogCheckBox->setChecked(settings.value(PUBLISHING_TO_BLOG_OPTION, false).toBool()); loadPublishingParameters(typeCombo->currentIndex()); settings.endGroup(); settings.endGroup(); } void PublishDialog::savePublishParameters() { QSettings settings; settings.beginGroup(SERVICELOGONPROVIDER->getMainSubgroup()); settings.beginGroup(SERVICELOGONPROVIDER->getSettingsSubgroup()); settings.setValue(PUBLISHING_METHOD_OPTION, methodCombo->currentIndex()); settings.setValue(PUBLISHING_TYPE_OPTION, typeCombo->currentIndex()); settings.setValue(PUBLISHING_TO_BLOG_OPTION, blogCheckBox->isChecked()); settings.endGroup(); settings.endGroup(); } void PublishDialog::on_publishingButton_clicked() { if (moodstripNameEdit->text().isEmpty()) { moodstripNameEdit->setFocus(); return; } if (publishRequestId) return; // Protection against double click // Check Blog if (blogCheckBox->isChecked()) { if (loginCombo->lineEdit()->text().isEmpty()) { loginCombo->lineEdit()->setFocus(); return; } if (passwordEdit->text().isEmpty()) { passwordEdit->setFocus(); return; } SERVICELOGONPROVIDER->setCurrent(loginCombo->lineEdit()->text(), passwordEdit->text()); } savePublishParameters(); openProgressPage(); switch (typeCombo->currentIndex()) { case LIVEJOURNAL_TYPE_INDEX: ljPoster = new LJPoster(this); connect(ljPoster, SIGNAL(loginChecked(bool, const QString &)), this, SLOT(onBlogLoginChecked(bool, const QString &))); connect(ljPoster, SIGNAL(postCompleted(bool, const QString &)), this, SLOT(onBlogPostCompleted(bool, const QString &))); break; case LIVEINTERNET_TYPE_INDEX: liPoster = new LIPoster(this); connect(liPoster, SIGNAL(loginChecked(bool, const QString &)), this, SLOT(onBlogLoginChecked(bool, const QString &))); connect(liPoster, SIGNAL(postCompleted(bool, const QString &)), this, SLOT(onBlogPostCompleted(bool, const QString &))); break; case DIARY_TYPE_INDEX: diaryPoster = new DiaryPoster(this); connect(diaryPoster, SIGNAL(loginChecked(bool, const QString &)), this, SLOT(onBlogLoginChecked(bool, const QString &))); connect(diaryPoster, SIGNAL(postCompleted(bool, const QString &)), this, SLOT(onBlogPostCompleted(bool, const QString &))); break; } if (blogCheckBox->isChecked()) startBlogLoginCheck(); else startPublishing(); } void PublishDialog::on_blogCheckBox_stateChanged(int state) { const bool visible = state != 0; ljControlsWidget->setVisible(visible); ljUrlLabel->setVisible(visible); ljUrlEdit->setVisible(visible); blogUrlButton->setVisible(visible); ljMoodstripCutLabel->setVisible(visible); embedMoodstripCutEdit->setVisible(visible); publishedFrame->layout()->activate(); } void PublishDialog::on_savePasswordCheck_stateChanged(int state) { bool value = (state == Qt::Checked); SERVICELOGONPROVIDER->setIsPasswordSavingEnabled(value); } void PublishDialog::on_loginCombo_currentIndexChanged(const QString& text) { if (text.isEmpty()) passwordEdit->clear(); else passwordEdit->setText(SERVICELOGONPROVIDER->getPassword(text)); } void PublishDialog::onPublishProgress(qint32 id, qint32 percentDone) { if (id != publishRequestId) return; Q_ASSERT_X(percentDone >= 0 && percentDone <= 100, "PublishDialog::onPublishProgress", "Invalid percent"); setPublishingProgress(percentDone); } void PublishDialog::onPublishCompleted(qint32 id, qint32 moodstripId, const QList<PublishingWay> &urls) { Q_UNUSED(moodstripId); if (id != publishRequestId) return; if (urls.isEmpty()) onPublishError(id); else { Q_ASSERT_X(moodstripId > 0 && !urls.isEmpty(), "PublishDialog::onPublishCompleted", "Empty parameter"); this->urls = urls; foreach(PublishingWay url, urls) { switch (url.getCode()) { case UrlCode::SimpleUrl: urlEdit->setText(url.getUrl()); urlEdit->setCursorPosition(0); break; case UrlCode::EmbeddedFlash: embedEdit->setText(url.getUrl()); embedEdit->setCursorPosition(0); break; case UrlCode::Lj: embedMoodstripEdit->setText(url.getUrl()); embedMoodstripEdit->setCursorPosition(0); break; case UrlCode::LjCut: embedMoodstripCutEdit->setText(url.getUrl()); embedMoodstripCutEdit->setCursorPosition(0); break; } } publishedLabel->setText(tr(PUBLISHING_COMPLETED_TEXT)); if (blogCheckBox->isChecked()) postToBlog(); else openResultPage(); } } void PublishDialog::onPublishError(qint32 id) { if (id != publishRequestId) return; QMessageBox::warning(this, tr(PUBLISHING_ERROR_TITLE), tr(PUBLISHING_ERROR_TEXT)); openOptionsPage(); } void PublishDialog::onBlogLoginChecked(bool success, const QString &errorMessage) { if (!success) { QMessageBox::warning(this, tr(POST_LJ_LOGIN_ERROR_TITLE), tr(POST_LJ_LOGIN_ERROR_TEXT).arg(errorMessage)); openOptionsPage(); } else { SERVICELOGONPROVIDER->saveLogonDataIfAllowed(); startPublishing(); } } void PublishDialog::onBlogPostCompleted(bool success, const QString &info) { if (!success) { QMessageBox::warning(this, tr(POST_LJ_ERROR_TITLE), tr(POST_LJ_ERROR_TEXT).arg(info)); ljUrlEdit->clear(); } else { publishedLabel->setText(tr(PUBLISHINGLJ_COMPLETED_TEXT)); ljUrlEdit->setText(info); ljUrlEdit->setCursorPosition(0); } openResultPage(); } void PublishDialog::publishEnabled() { } void PublishDialog::loadPublishingParameters(int PublishingType) { // load logins switch (PublishingType) { case LIVEJOURNAL_TYPE_INDEX: SERVICELOGONPROVIDER->setCurrentService(SERVICE_LJ_NAME); break; case LIVEINTERNET_TYPE_INDEX: SERVICELOGONPROVIDER->setCurrentService(SERVICE_LI_NAME); break; case DIARY_TYPE_INDEX: SERVICELOGONPROVIDER->setCurrentService(SERVICE_DIARY_NAME); break; } SERVICELOGONPROVIDER->reload(); savePasswordCheck->setChecked(SERVICELOGONPROVIDER->getIsPasswordSavingEnabled()); QString oldLogin = loginCombo->lineEdit()->text(); QString oldPassword = passwordEdit->text(); loginCombo->clear(); loginCombo->addItem(QString()); QStringList logins = SERVICELOGONPROVIDER->getSavedLogins(); QString login; foreach(login, logins) loginCombo->addItem(login); if (!loginsLoaded) { login = SERVICELOGONPROVIDER->getLastLoggedOnLogin(); if (!login.isEmpty()) { loginCombo->lineEdit()->setText(login); loginCombo->lineEdit()->selectAll(); passwordEdit->setText(SERVICELOGONPROVIDER->getPassword(login)); } loginsLoaded = true; } else { loginCombo->lineEdit()->setText(oldLogin); passwordEdit->setText(oldPassword); } oldPassword.clear(); // load publishing methods methodCombo->clear(); if (PublishingType == LIVEJOURNAL_TYPE_INDEX || PublishingType == DIARY_TYPE_INDEX) // LiveJournal and Dairy.ru methodCombo->addItem(embedLabel->text().replace('\n',' ')); methodCombo->addItem(moodstripLabel->text().replace('\n',' ')); if (PublishingType == LIVEJOURNAL_TYPE_INDEX) // only for LiveJournal methodCombo->addItem(ljMoodstripCutLabel->text().replace('\n',' ')); } void PublishDialog::on_urlButton_clicked() { QUrl url = QUrl(urlEdit->text()); QDesktopServices::openUrl(url); } void PublishDialog::on_blogUrlButton_clicked() { if (ljUrlEdit->text().isEmpty()) return; QUrl url = QUrl(ljUrlEdit->text()); QDesktopServices::openUrl(url); } }
25.207477
139
0.707178
vorushin
0fbd172e36f976bebca2e21cc1e1dea9caf32a7e
1,442
cpp
C++
ext/stub/javax/imageio/ImageIO_ContainsFilter-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/javax/imageio/ImageIO_ContainsFilter-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
ext/stub/javax/imageio/ImageIO_ContainsFilter-stub.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #include <javax/imageio/ImageIO_ContainsFilter.hpp> extern void unimplemented_(const char16_t* name); javax::imageio::ImageIO_ContainsFilter::ImageIO_ContainsFilter(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } javax::imageio::ImageIO_ContainsFilter::ImageIO_ContainsFilter(::java::lang::reflect::Method* method, ::java::lang::String* name) : ImageIO_ContainsFilter(*static_cast< ::default_init_tag* >(0)) { ctor(method, name); } void ::javax::imageio::ImageIO_ContainsFilter::ctor(::java::lang::reflect::Method* method, ::java::lang::String* name) { /* stub */ /* super::ctor(); */ unimplemented_(u"void ::javax::imageio::ImageIO_ContainsFilter::ctor(::java::lang::reflect::Method* method, ::java::lang::String* name)"); } bool javax::imageio::ImageIO_ContainsFilter::filter(::java::lang::Object* elt) { /* stub */ unimplemented_(u"bool javax::imageio::ImageIO_ContainsFilter::filter(::java::lang::Object* elt)"); return 0; } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* javax::imageio::ImageIO_ContainsFilter::class_() { static ::java::lang::Class* c = ::class_(u"javax.imageio.ImageIO.ContainsFilter", 36); return c; } java::lang::Class* javax::imageio::ImageIO_ContainsFilter::getClass0() { return class_(); }
33.534884
142
0.712899
pebble2015
0fbd343c82f39328aa0cfe80a3dc9f33d6327680
10,276
hpp
C++
include/nodamushi/svd/normalized/Register.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
include/nodamushi/svd/normalized/Register.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
include/nodamushi/svd/normalized/Register.hpp
nodamushi/nsvd-reader
cf3a840aaac78d5791df1cf045596ec20dc03257
[ "CC0-1.0" ]
null
null
null
/*! @brief normalized register @file nodamushi/svd/normalized/Register.hpp */ /* * These codes are licensed under CC0. * http://creativecommons.org/publicdomain/zero/1.0/ */ #ifndef NODAMUSHI_SVD_NORMALIZED_REGISTER_HPP #define NODAMUSHI_SVD_NORMALIZED_REGISTER_HPP # include <sstream> # include "nodamushi/svd/normalized/node_container.hpp" # include "nodamushi/svd/normalized/WriteConstraint.hpp" namespace nodamushi{ namespace svd{ namespace normalized{ /* * Normalized register class. * if STRREF is string_view or something like it, * the reference source of string is the value of nodamushi::svd::Register instance member. * * @see http://www.keil.com/pack/doc/CMSIS/SVD/html/elem_registers.html#elem_register */ template<typename STRREF>struct Register { using Field = ::nodamushi::svd::normalized::Field<STRREF>; using Cluster= ::nodamushi::svd::normalized::Cluster<STRREF>; using Peripheral= ::nodamushi::svd::normalized::Peripheral<STRREF>; using this_t = Register<STRREF>; using p_ptr = parent_ptr<Peripheral>; using p2_ptr = parent_ptr<Cluster>; private: p_ptr parent; //!< perihperal parent pointer p2_ptr parent2; //!< cluster parent pointer public: //! @brief derivedFrom attribute path<STRREF> derivedFrom; /** * @brief &lt;name&gt; of this register without peripheral.prependToName and peripheral.appendToName * @see get_name_with_appendix() */ std::string name; //! @brief &lt;displayName&gt; std::string displayName; //! @brief dimemsion information object. dim_info dim; //! @brief &lt;description&gt; STRREF description; //! @brief &lt;alternateGroup&gt; STRREF alternateGroup; //! @brief &lt;alternateRegister&gt; STRREF alternateRegister; /** @brief &lt;addressOffset&gt; @par If you nead an absolute address, call the get_address() method. If you nead a relative address from the baseAddress of peripheral,call the get_address_offset() method. @see get_address() @see get_address_offset() */ uint64_t addressOffset; /** @brief &lt;size&gt; @see get_size() */ nullable<uint32_t> size; /** @brief &lt;access&gt; @see get_access() */ nullable<Access> access; /** @brief &lt;protection&gt; @see get_protection() */ nullable<Protection> protection; /** @brief &lt;resetValue&gt; @see get_resetValue() */ nullable<uint64_t> resetValue; /** @brief &lt;resetMask&gt; @see get_resetMask() */ nullable<uint64_t> resetMask; /** @brief &lt;dataType&gt; @see get_dataType() */ nullable<DataType> dataType; //! @brief &lt;modifiedWriteValues&gt; ModifiedWriteValues modifiedWriteValues; //! @brief &lt;readAction&gt; ReadAction readAction; //! @brief &lt;writeConstraint&gt; WriteConstraint writeConstraint; /*! @brief &lt;field&gt; elements list. This list is sorted by lsb of field. Field class does not prohibit copying, but basically it should be treated with a reference. @code auto& f = reg.fields[x]; @endcode */ list<Field> fields; //----------------------------------------------------------- /** * @brief get name with peripheral.prependToName and peripheral.appendToName */ std::string get_name_with_appendix()const noexcept{ auto p = get_peripheral(); if(p && p->has_register_name_appendix()){ std::stringstream s; if(! p->prependToName.empty()) s << p->prependToName; if(p->appendToName.empty()) s << name; else{ bool arr=dim.is_array() && name.length() > 3; if(arr){ size_t l = name.length()-3; while(l != 1){ if(name[l] == '[')break; l--; } if(name[l] == '['){ s.write(name.data(),l); }else{ s << name; arr = false; } }else s << name; s << p->appendToName; if(arr) s <<'['<<dim.index << ']'; } return s.str(); } return name; } /** @brief get parent cluster pointer @return parent peripheral pointer or nullptr. @see get_parent2() */ node_ptr<Peripheral> get_parent() noexcept{return parent.lock();} //! @return parent peripheral pointer or nullptr. node_ptr<Peripheral const> get_parent()const noexcept{return parent.lock();} /** @brief get parent cluster pointer @return parent cluster pointer or nullptr. @see get_parent() */ node_ptr<Cluster> get_parent2() noexcept{return parent2.lock();} //! @brief parent cluster pointer or nullptr. node_ptr<Cluster const> get_parent2()const noexcept{return parent2.lock();} //! @brief find the Peripheral to which this register belongs. node_ptr<Peripheral const> get_peripheral()const noexcept{return find_parent_peripheral(*this);} //! @brief find the Peripheral to which this register belongs. node_ptr<Peripheral> get_peripheral()noexcept{return find_parent_peripheral(*this);} //! @brief calculate an absolute address uint64_t get_address()const{ return calc_address(*this);} //! @brief a relative address from the baseAddress of the peripheral uint64_t get_address_offset()const{ return calc_offset(*this);} //! @brief get path ::nodamushi::svd::path<> get_path()const { ::nodamushi::svd::path<> p; path_helper(*this,p); return p; } /** @brief resolve the dataType. The default type is determined by the size.(size=8 : uint8_t,size=32: uint32_t) */ DataType get_dataType()const{ return dataType.get<this_t,get_default_dataType<this_t>>(this); } //! @brief resolve the value of size and return it. uint32_t get_size()const{ return size.get<this_t,get_default_size<this_t>>(this); } //! @brief resolve the value of resetValue and return it. uint64_t get_resetValue()const{ return resetValue.get<this_t,get_default_resetValue<this_t>>(this); } //! @brief resolve the value of resetMask and return it. uint64_t get_resetMask()const{ return resetMask.get<this_t,get_default_resetMask<this_t>>(this); } //! @brief resolve the value of access and return it. Access get_access()const{ return access.get<this_t,get_default_access<this_t>>(this); } //! @brief resolve the value of protection and return it. Protection get_protection()const{ return protection.get<this_t,get_default_protection<this_t>>(this); } //! @brief resolve the value of modifiedWriteValues and return it. ModifiedWriteValues get_modifiedWriteValues()const{return modifiedWriteValues;} ReadAction get_readAction()const{return readAction;} //------------------------------------------- /** * @brief find path element * @param p path * @param pindex the first index of serach path. default is 0. * @return element pointer */ template<typename STR> node_ptr<void> find(const ::nodamushi::svd::path<STR>& p,size_t pindex=0) { const size_t ps = p.size(); if(ps > pindex){ string_ref n = p[pindex]; if(auto c = __find_helper(fields,n)){ if(ps == pindex + 1)return c; else return c->find(p,pindex+1); } } return {}; } /** * @brief find field element * @param p path * @param pindex the first index of serach path. default is 0. * @return element pointer */ template<typename STR> node_ptr<Field> find_field(::nodamushi::svd::path<STR>& p,size_t pindex=0) { const size_t ps = p.size(); if(ps == pindex+1){ string_ref n = p[pindex]; return __find_helper(fields,n); } return {}; } //------------------------------------------- template<typename T> Register(const T& n)://don't change name parent(), parent2(), derivedFrom(), name(n.name), displayName(make_dim_displayName_helper(n.svd)(n.dim.index)), dim(n.dim), __NORMALIZED_DERIVED_FROM(description), __NORMALIZED_DERIVED_FROM(alternateGroup), __NORMALIZED_DERIVED_FROM(alternateRegister), __NORMALIZED_DERIVED_FROM(addressOffset), __NORMALIZED_DERIVED_FROM(size), __NORMALIZED_DERIVED_FROM(access), __NORMALIZED_DERIVED_FROM(protection), __NORMALIZED_DERIVED_FROM(resetValue), __NORMALIZED_DERIVED_FROM(resetMask), __NORMALIZED_DERIVED_FROM(dataType), __NORMALIZED_DERIVED_FROM(modifiedWriteValues), __NORMALIZED_DERIVED_FROM(readAction), __NORMALIZED_DERIVED_FROM_MEMBER(writeConstraint), fields(n.fields.size()) { if(n.svd.derivedFrom) derivedFrom = n.svd.derivedFrom.get(); // add dim offset if(n.dim && n.dim.index!=0){ __NORMALIZED_DERIVED_FROM_HELPER(dimIncrement); size_t inc = 1; if(dimIncrement) inc = *dimIncrement; addressOffset += inc * n.dim.index; } for(const auto& f:n.fields) fields.emplace_back(f); // sort by lsb fields.sort([](const Field& a,const Field& b)->bool {return a.lsb() < b.lsb();}); } void update_parent(p_ptr& new_parent,node_ptr<this_t>& me) { parent = new_parent; parent2= {}; update_parent_of_children(fields,me); } void update_parent(p2_ptr& new_parent,node_ptr<this_t>& me) { parent2= new_parent; parent = {}; update_parent_of_children(fields,me); } /** * @brief sort field by lsb, and call Field.sort */ void sort() { std::sort(fields.ptr_begin(),fields.ptr_end(), [](auto x,auto y){ const auto lsbx = x->lsb(); const auto lsby = y->lsb(); return lsbx < lsby; }); for(auto& f:fields) f.sort(); } }; //---------- Visitor -------------------- __NX_NORM_HANDLE_VISIT(Register) { namespace nv = ::nodamushi::visitor; using r = nv::result; r ret; // visit register / cluster ret = CONTROLLER::apply(t.fields,v); if(ret == r::BREAK)return ret; if(ret == r::SKIP)return r::CONTINUE; return r::CONTINUE; }}; //-------------------------------------------- }}} // end namespace svd #endif // NODAMUSHI_SVD_NORMALIZED_REGISTER_HPP
29.613833
107
0.635072
nodamushi
0fc0a177cad09bce23bf64f9ef768e147b5e5d42
1,909
cpp
C++
ndk-basic/src/main/cpp/sample-lib.cpp
syusikoku/NDKDemo
92322273b16366ae30e0c239df6bfaaf2a6ab958
[ "W3C", "OLDAP-2.3" ]
null
null
null
ndk-basic/src/main/cpp/sample-lib.cpp
syusikoku/NDKDemo
92322273b16366ae30e0c239df6bfaaf2a6ab958
[ "W3C", "OLDAP-2.3" ]
null
null
null
ndk-basic/src/main/cpp/sample-lib.cpp
syusikoku/NDKDemo
92322273b16366ae30e0c239df6bfaaf2a6ab958
[ "W3C", "OLDAP-2.3" ]
null
null
null
#include <jni.h> #include <string> #include <android/log.h> #include <sys/inotify.h> #define LOG_TAG "zy" #include <unistd.h> #include <malloc.h> #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) #define LOGF(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) extern "C" JNIEXPORT jint JNICALL Java_com_example_nd_JNI_plus(JNIEnv *env, jobject obj, jint a, jint b) { LOGD(LOG_TAG, "call Java_com_example_nd_JNI_plus"); return a + b; } extern "C" JNIEXPORT void JNICALL Java_com_example_nd_JNI_callUnInstallListener(JNIEnv *env, jobject obj, jint versionSdk, jstring path) { /* fork()子进程 创建监听文件 初始化inotify实例 注册监听事件 调用read函数开始监听 卸载反馈统计 */ LOGD("------------------------"); LOGF("------------------------"); const char *path_str = env->GetStringUTFChars(path, 0); pid_t pid = fork(); if (pid < 0) { LOGD("克隆失败"); } else if (pid > 0) { LOGD("父进程"); } else { LOGD("子进程!"); //*******************在这里进程操作***************** LOGD("你好,终端研发部"); int fuileDescript = inotify_init(); int watch = inotify_add_watch(fuileDescript, path_str, IN_DELETE_SELF); void *p = malloc(sizeof(struct inotify_event)); read(fuileDescript, p, sizeof(struct inotify_event)); inotify_rm_watch(fuileDescript, watch); LOGD(LOG_TAG, "接下来进行操作,来条状网页!!!"); if (versionSdk < 17) { //am start -a android.intent.action.VIEW -d execlp("am", "am", "start", "-a", "android.intent.action.VIEW", "-d", "https://github.com/syusikoku", NULL); } else { execlp("am", "am", "start", "--user", "0", "-a", "android.intent.action.VIEW", "-d", "https://github.com/syusikoku", NULL); } } env->ReleaseStringUTFChars(path, path_str); }
31.295082
96
0.577266
syusikoku
0fc143ee7694b39857b3bc1e985a6c3a7ad0177e
48,745
cpp
C++
src/rpggame/rpgio.cpp
Hirato/lamiae
c8a94794035d313420ea56b2bf9dd603fe06f520
[ "Zlib" ]
68
2015-01-26T14:03:42.000Z
2022-02-28T06:08:24.000Z
src/rpggame/rpgio.cpp
Hirato/lamiae
c8a94794035d313420ea56b2bf9dd603fe06f520
[ "Zlib" ]
13
2015-01-09T21:57:27.000Z
2022-02-20T11:25:39.000Z
src/rpggame/rpgio.cpp
Hirato/lamiae
c8a94794035d313420ea56b2bf9dd603fe06f520
[ "Zlib" ]
18
2015-01-08T14:15:21.000Z
2021-12-27T16:14:07.000Z
#include "rpggame.h" extern bool reloadtexture(const char *name); //texture.cpp namespace rpgio { #define SAVE_VERSION 49 #define COMPAT_VERSION 49 #define SAVE_MAGIC "RPGS" /** SAVING STUFF STRINGS - use writestring(stream *, char *) HASHES - see strings VECTORS - write an int corresponding to the number of elements, then write the elements POINTERS - convert to reference, if this is not possible don't save it VEC - use writevec macro, you need to write all 3 coordinates independantly LOADING STUFF STRINGS - use readstring(stream *) HASHES - use READHASH macros and if needed, NOTNULL and VERIFYHASH macros VECTORS - read the next int, and use that as the basis of knowing how many elements to load POINTERS - read the reference and convert it back to a pointer of the intended object. If this can't be done reliably don't save it VEC - use readvec macro, you need to read all 3 coordinates independantly REMINDERS HOW MANY - don't forget to indicate how many times you need to repeat the loop; there should be a amcro that helps with this ORDER - you must read and write items in the same order LITTLE ENDIAN - pullil add getlil for single values and lilswap for arrays and objects are going to be your bestest friends POINTERS - they change each run, remember that, for convention, use -1 for players ARGUMENTS - as a argument to a function, ORDER IS NOT RESPECTED, use with extreme care TIME - the difference of lastmillis is taken and applied on save and load - use countdown timers instead if possible. ORDER they are to coincide with the order of the item structs, and before the map functions, the order in which crap is stored there */ #define readvec(v) \ v.x = f->getlil<float>(); \ v.y = f->getlil<float>(); \ v.z = f->getlil<float>(); \ if(DEBUG_IO) \ DEBUGF("Read vec (%f, %f, %f) from file", v.x, v.y, v.z); #define writevec(v) \ f->putlil(v.x); \ f->putlil(v.y); \ f->putlil(v.z); \ if(DEBUG_IO) \ DEBUGF("Wrote vec (%f, %f, %f) to file", v.x, v.y, v.z); #define CHECKEOF(f, val) \ if((f).end()) \ { \ abort = true; \ ERRORF("Unexpected EoF at " __FILE__ ":%i; aborting - You should report this.", __LINE__); \ return val; \ } #define NOTNULL(f, val) \ if(!f) \ { \ abort = true; \ ERRORF("Encountered unexpected NULL value for " #f " at " __FILE__ ":%i; aborting.", __LINE__); \ return val; \ } #define READHASH(val) \ do { \ const char *_str = readstring(f); \ if(_str) val = game::queryhashpool(_str); \ else val = NULL; \ delete[] _str; \ } while(0); #define READHASHEXTENDED(val, ht) \ do { \ const char *_str = readstring(f); \ if(_str) val = ht.access(_str); \ else val = NULL; \ delete[] _str; \ } while(0); struct saveheader { char magic[4]; int sversion; //save int gversion; //game }; bool abort = false; mapinfo *lastmap = NULL; rpgent *entfromnum(int num) { if(num == -2) return NULL; if(num == -1) return game::player1; else if(num >= lastmap->objs.length()) { WARNINGF("invalid entity num (%i), possible corruption", num); return NULL; } return lastmap->objs[num]; } int enttonum(rpgent *ent) { if(ent == NULL) return -2; if(ent == game::player1) return -1; int i = lastmap->objs.find(game::player1); if(i != -1) { int num = lastmap->objs.find(ent); if(num > i) num--; return num; } else return lastmap->objs.find(ent); } struct reference { int ind; mapinfo *map; rpgent *&ref; reference(int i, mapinfo *m, rpgent *&r) : ind(i), map(m), ref(r) {} ~reference() {} }; vector<reference> updates; const char *readstring(stream *f) { int len = f->getlil<int>(); char *s = NULL; if(len) { int fsize = f->size() - f->tell(); if(len < 0 || len > fsize) { ERRORF("Cannot read %i characters from file, there are %i bytes remaining, aborting", len, fsize); abort = true; return NULL; } s = new char[len]; f->read(s, len); if(DEBUG_IO) DEBUGF("Read \"%s\" from file (%i)", s, len); } return s; } void writestring(stream *f, const char *s) { int len = s ? strlen(s) + 1 : 0; f->putlil(len); if(!len) return; f->write(s, len); if(DEBUG_IO) DEBUGF("Wrote \"%s\" to file (%i)", s, len); } void readfaction(stream *f, faction *fact) { int num = f->getlil<int>(); if(DEBUG_IO) DEBUGF("reading %i relations", num); loopi(num) { CHECKEOF(*f, ) const char *fac = readstring(f); int val = f->getlil<short>(); if(fact && game::factions.access(fac)) fact->setrelation(game::queryhashpool(fac), val); else WARNINGF("Faction %s does not exist, ignoring relation of %i", fac, val); delete[] fac; } } void writefaction(stream *f, faction *fact) { f->putlil(fact->relations.length()); if(DEBUG_IO) DEBUGF("saving %i relations", fact->relations.length()); enumeratekt(fact->relations, const char *, fac, short, relation, if(DEBUG_IO) DEBUGF("writing: factions[%s]->relations[%s] (%i)", fact->key, fac, relation); writestring(f, fac); f->putlil(relation); ) } void readrecipe(stream *f, recipe *rec) { int flags = f->getlil<int>(); if(rec) rec->flags |= flags; } void writerecipe(stream *f, recipe *rec) { f->putlil( rec->flags & recipe::SAVE); } void readmerchant(stream *f, merchant *mer) { int credit = f->getlil<int>(); if(mer) mer->credit = credit; } void writemerchant(stream *f, merchant *mer) { f->putlil(mer->credit); } item *readitem(stream *f, item *it = NULL) { if(!it) it = new item(); delete[] it->name; delete[] it->icon; delete[] it->description; delete[] it->mdl; it->name = readstring(f); it->icon = readstring(f); it->description = readstring(f); it->mdl = readstring(f); NOTNULL(it->mdl, it); preloadmodel(it->mdl); READHASHEXTENDED(it->script, game::scripts); READHASH(it->base); NOTNULL(it->script, it) NOTNULL(it->base, it); readvec(it->colour) it->quantity = f->getlil<int>(); it->category = f->getlil<int>(); it->flags = f->getlil<int>(); it->value = f->getlil<int>(); it->maxdurability = f->getlil<int>(); it->charges = f->getlil<int>(); it->scale = f->getlil<float>(); it->weight = f->getlil<float>(); it->durability = f->getlil<float>(); it->recovery = f->getlil<float>(); rpgscript::keeplocal((it->locals = f->getlil<int>())); int uses = f->getlil<int>(); loopi(uses) { CHECKEOF(*f,it) int type = f->getlil<int>(); use *u = NULL; switch(type) { case USE_WEAPON: { if(!u) u = it->uses.add(new use_weapon(NULL)); use_weapon *wp = (use_weapon *) u; READHASHEXTENDED(wp->projeffect, game::effects) READHASHEXTENDED(wp->traileffect, game::effects) READHASHEXTENDED(wp->deatheffect, game::effects) READHASHEXTENDED(wp->ammo, game::ammotypes) NOTNULL(wp->ammo, it); wp->range = f->getlil<int>(); wp->angle = f->getlil<int>(); wp->lifetime = f->getlil<int>(); wp->gravity = f->getlil<int>(); wp->cost = f->getlil<int>(); wp->pflags = f->getlil<int>(); wp->target = f->getlil<int>(); wp->radius = f->getlil<int>(); wp->kickback = f->getlil<int>(); wp->recoil = f->getlil<int>(); wp->charge = f->getlil<int>(); wp->basecharge = f->getlil<float>(); wp->mincharge = f->getlil<float>(); wp->maxcharge = f->getlil<float>(); wp->elasticity = f->getlil<float>(); wp->speed = f->getlil<float>(); } [[fallthrough]]; case USE_ARMOUR: { if(!u) u = it->uses.add(new use_armour(NULL)); use_armour *ar = (use_armour *) u; delete[] ar->vwepmdl; delete[] ar->hudmdl; ar->vwepmdl = readstring(f); ar->hudmdl = readstring(f); if(ar->vwepmdl) preloadmodel(ar->vwepmdl); if(ar->hudmdl) preloadmodel(ar->hudmdl); READHASHEXTENDED(ar->idlefx, game::effects); ar->slots = f->getlil<int>(); ar->skill = f->getlil<int>(); loopj(STAT_MAX) ar->reqs.attrs[j] = f->getlil<short>(); loopj(SKILL_MAX) ar->reqs.skills[j] = f->getlil<short>(); } [[fallthrough]]; case USE_CONSUME: { if(!u) u = it->uses.add(new use(NULL)); delete[] u->name; delete[] u->description; delete[] u->icon; u->name = readstring(f); u->description = readstring(f); u->icon = readstring(f); READHASHEXTENDED(u->script, game::scripts); NOTNULL(u->script, it); u->cooldown = f->getlil<int>(); u->chargeflags = f->getlil<int>(); int efx = f->getlil<int>(); loopj(efx) { CHECKEOF(*f, it) statusgroup *status = NULL; READHASHEXTENDED(status, game::statuses); NOTNULL(status, it); int e = f->getlil<int>(); float m = f->getlil<float>(); u->effects.add(new inflict(status, e, m)); } break; } } } return it; } void writeitem(stream *f, item *it) { writestring(f, it->name); writestring(f, it->icon); writestring(f, it->description); writestring(f, it->mdl); writestring(f, it->script->key); writestring(f, it->base); writevec(it->colour) f->putlil(it->quantity); f->putlil(it->category); f->putlil(it->flags); f->putlil(it->value); f->putlil(it->maxdurability); f->putlil(it->charges); f->putlil(it->scale); f->putlil(it->weight); f->putlil(it->durability); f->putlil(it->recovery); f->putlil(it->locals); f->putlil(it->uses.length()); loopv(it->uses) { f->putlil(it->uses[i]->type); switch(it->uses[i]->type) { case USE_WEAPON: { use_weapon *wp = (use_weapon *) it->uses[i]; writestring(f, wp->projeffect ? wp->projeffect->key : NULL); writestring(f, wp->traileffect ? wp->traileffect->key : NULL); writestring(f, wp->deatheffect ? wp->deatheffect->key : NULL); writestring(f, wp->ammo->key); f->putlil(wp->range); f->putlil(wp->angle); f->putlil(wp->lifetime); f->putlil(wp->gravity); f->putlil(wp->cost); f->putlil(wp->pflags); f->putlil(wp->target); f->putlil(wp->radius); f->putlil(wp->kickback); f->putlil(wp->recoil); f->putlil(wp->charge); f->putlil(wp->basecharge); f->putlil(wp->mincharge); f->putlil(wp->maxcharge); f->putlil(wp->elasticity); f->putlil(wp->speed); } [[fallthrough]]; case USE_ARMOUR: { use_armour *ar = (use_armour *) it->uses[i]; writestring(f, ar->vwepmdl); writestring(f, ar->hudmdl); writestring(f, ar->idlefx ? ar->idlefx->key : NULL); f->putlil(ar->slots); f->putlil(ar->skill); loopj(STAT_MAX) f->putlil<short>(ar->reqs.attrs[j]); loopj(SKILL_MAX) f->putlil<short>(ar->reqs.skills[j]); } [[fallthrough]]; case USE_CONSUME: { use *u = it->uses[i]; writestring(f, u->name); writestring(f, u->description); writestring(f, u->icon); writestring(f, u->script->key); f->putlil(u->cooldown); f->putlil(u->chargeflags); f->putlil(u->effects.length()); loopvj(u->effects) { writestring(f, u->effects[j]->status->key); f->putlil(u->effects[j]->element); f->putlil(u->effects[j]->mul); } break; } } } } vector<rpgchar *> characters; rpgent *readent(stream *f, rpgent *ent = NULL) { int type = f->getlil<int>(); if(ent) type = ent->type(); switch(type) { case ENT_CHAR: { if(!ent) ent = new rpgchar(); rpgchar *loading = (rpgchar *) ent; characters.add(loading); delete[] loading->name; delete[] loading->mdl; delete[] loading->portrait; loading->name = readstring(f); loading->mdl = readstring(f); loading->portrait = readstring(f); readvec(loading->colour); NOTNULL(loading->mdl, ent); preloadmodel(loading->mdl); #define x(var, type) loading->base.var = f->getlil<type>(); loopi(STAT_MAX) x(baseattrs[i], short) loopi(SKILL_MAX) x(baseskills[i], short) loopi(STAT_MAX) x(deltaattrs[i], short) loopi(SKILL_MAX) x(deltaskills[i], short) loopi(ATTACK_MAX) x(bonusthresh[i], short) loopi(ATTACK_MAX) x(bonusresist[i], short) x(bonushealth, int) x(bonusmana, int) x(bonusmovespeed, int) x(bonusjumpvel, int) x(bonuscarry, int) x(bonuscrit, int) x(bonushregen, float) x(bonusmregen, float) loopi(ATTACK_MAX) x(deltathresh[i], short) loopi(ATTACK_MAX) x(deltaresist[i], short) x(deltahealth, int) x(deltamana, int) x(deltamovespeed, int) x(deltajumpvel, int) x(deltacarry, int) x(deltacrit, int) x(deltahregen, float) x(deltamregen, float) #undef x READHASHEXTENDED(loading->script, game::scripts) READHASHEXTENDED(loading->faction, game::factions) READHASHEXTENDED(loading->merchant, game::merchants) NOTNULL(loading->script, ent) NOTNULL(loading->faction, ent) if(loading->merchant) NOTNULL(loading->merchant, ent) loading->health = f->getlil<float>(); loading->mana = f->getlil<float>(); loading->scale = f->getlil<float>(); loading->lastaction = f->getlil<int>() + lastmillis; vector<item *> items; int num = f->getlil<int>(); loopi(num) { CHECKEOF(*f, ent) item *it = items.add(readitem(f)); if(abort) {delete it; return ent;} loading->inventory.access(it->base, vector<item *>()).add(it); } int equiplen = f->getlil<int>(); loopi(equiplen) { CHECKEOF(*f, ent) int idx = f->getlil<int>(); int use = f->getlil<int>(); //validate equipment items[idx]->quantity++; loading->equip(items[idx], use); } break; } case ENT_ITEM: { if(!ent) ent = new rpgitem(); rpgitem *loading = (rpgitem *) ent; readitem(f, loading); if(abort) return ent; break; } case ENT_OBSTACLE: { if(!ent) ent = new rpgobstacle(); rpgobstacle *loading = (rpgobstacle *) ent; delete loading->mdl; loading->mdl = readstring(f); NOTNULL(loading->mdl, ent); preloadmodel(loading->mdl); READHASHEXTENDED(loading->script, game::scripts); NOTNULL(loading->script, ent); readvec(loading->colour); loading->weight = f->getlil<int>(); loading->flags = f->getlil<int>(); loading->scale = f->getlil<float>(); break; } case ENT_CONTAINER: { if(!ent) ent = new rpgcontainer(); rpgcontainer *loading = (rpgcontainer *) ent; delete[] loading->mdl; delete[] loading->name; loading->mdl = readstring(f); loading->name = readstring(f); NOTNULL(loading->mdl, ent); preloadmodel(loading->mdl); READHASHEXTENDED(loading->faction, game::factions) READHASHEXTENDED(loading->merchant, game::merchants) READHASHEXTENDED(loading->script, game::scripts) if(loading->faction) NOTNULL(loading->faction, ent); if(loading->merchant) NOTNULL(loading->merchant, ent); NOTNULL(loading->script, ent) readvec(loading->colour); loading->capacity = f->getlil<int>(); loading->lock = f->getlil<int>(); loading->magelock = f->getlil<int>(); loading->scale = f->getlil<float>(); int items = f->getlil<int>(); loopi(items) { CHECKEOF(*f, ent) item *it = readitem(f); if(abort) { delete it; return ent; } loading->inventory.access(it->base, vector<item *>()).add(it); } break; } case ENT_PLATFORM: { if(!ent) ent = new rpgplatform(); rpgplatform *loading = (rpgplatform *) ent; delete[] loading->mdl; loading->mdl = readstring(f); NOTNULL(loading->mdl, ent); preloadmodel(loading->mdl); READHASHEXTENDED(loading->script, game::scripts) NOTNULL(loading->script, ent) readvec(loading->colour); loading->speed = f->getlil<int>(); loading->flags = f->getlil<int>(); loading->scale = f->getlil<float>(); int steps = f->getlil<int>(); loopi(steps) { CHECKEOF(*f, ent) vector<int> &detours = loading->routes.access(f->getlil<int>(), vector<int>()); int routes = f->getlil<int>(); loopj(routes) detours.add(f->getlil<int>()); } loading->target = f->getlil<int>(); break; } case ENT_TRIGGER: { if(!ent) ent = new rpgtrigger(); rpgtrigger *loading = (rpgtrigger *) ent; delete[] loading->mdl; delete[] loading->name; loading->mdl = readstring(f); NOTNULL(loading->mdl, ent); preloadmodel(loading->mdl); loading->name = readstring(f); READHASHEXTENDED(loading->script, game::scripts) NOTNULL(loading->script, ent) readvec(loading->colour); loading->flags = f->getlil<int>(); loading->lasttrigger = f->getlil<int>() + lastmillis; loading->scale = f->getlil<float>(); break; } default: ERRORF("unknown entity type %i", type); abort = true; return NULL; } rpgscript::keeplocal((ent->locals = f->getlil<int>())); int numeffs = f->getlil<int>(); loopi(numeffs) { CHECKEOF(*f, ent) victimeffect *eff = new victimeffect(); ent->seffects.add(eff); updates.add(reference(f->getlil<int>(), lastmap, eff->owner)); READHASHEXTENDED(eff->group, game::statuses); NOTNULL(eff->group, ent); eff->elem = f->getlil<int>(); int numstat = f->getlil<int>(); loopj(numstat) { CHECKEOF(*f, ent) int type = f->getlil<int>(); status *st = NULL; switch(type) { case STATUS_POLYMORPH: { st = eff->effects.add(new status_polymorph()); status_polymorph *poly = (status_polymorph *) st; poly->mdl = readstring(f); break; } case STATUS_LIGHT: { st = eff->effects.add(new status_light()); status_light *light = (status_light *) st; readvec(light->colour); break; } case STATUS_SCRIPT: { st = eff->effects.add(new status_script()); status_script *scr = (status_script *) st; scr->script = readstring(f); break; } case STATUS_SIGNAL: { st = eff->effects.add(new status_signal()); status_signal *sig = (status_signal *) st; sig->signal = readstring(f); break; } default: st = eff->effects.add(new status_generic()); break; } st->type = type; st->duration = f->getlil<int>(); st->remain = f->getlil<int>(); st->strength = f->getlil<int>(); st->variance = f->getlil<float>(); eff->effects.add(st); } } ent->maxheight = f->getlil<float>(); ent->eyeheight = f->getlil<float>(); readvec(ent->o); ent->newpos = ent->o; readvec(ent->vel); readvec(ent->falling); ent->yaw = f->getlil<float>(); ent->pitch = f->getlil<float>(); ent->roll = f->getlil<float>(); ent->timeinair = f->getlil<int>(); ent->state = f->getchar(); ent->editstate = f->getchar(); return ent; } void writeent(stream *f, rpgent *d) { f->putlil(d->type()); switch(d->type()) { case ENT_CHAR: { rpgchar *saving = (rpgchar *) d; writestring(f, saving->name); writestring(f, saving->mdl); writestring(f, saving->portrait); writevec(saving->colour) #define x(var) f->putlil(saving->base.var); loopi(STAT_MAX) x(baseattrs[i]) loopi(SKILL_MAX) x(baseskills[i]) loopi(STAT_MAX) x(deltaattrs[i]) loopi(SKILL_MAX) x(deltaskills[i]) loopi(ATTACK_MAX) x(bonusthresh[i]) loopi(ATTACK_MAX) x(bonusresist[i]) x(bonushealth) x(bonusmana) x(bonusmovespeed) x(bonusjumpvel) x(bonuscarry) x(bonuscrit) x(bonushregen) x(bonusmregen) loopi(ATTACK_MAX) x(deltathresh[i]) loopi(ATTACK_MAX) x(deltaresist[i]) x(deltahealth) x(deltamana) x(deltamovespeed) x(deltajumpvel) x(deltacarry) x(deltacrit) x(deltahregen) x(deltamregen) #undef x writestring(f, saving->script->key); writestring(f, saving->faction->key); writestring(f, saving->merchant ? saving->merchant->key : NULL); f->putlil(saving->health); f->putlil(saving->mana); f->putlil(saving->scale); f->putlil(saving->lastaction - lastmillis); vector<item *> items; enumerate(saving->inventory, vector<item *>, stack, loopvj(stack) items.add(stack[j]); ) f->putlil(items.length()); loopv(items) writeitem(f, items[i]); f->putlil(saving->equipped.length()); loopv(saving->equipped) { f->putlil(items.find(saving->equipped[i]->it)); f->putlil(saving->equipped[i]->use); } break; } case ENT_ITEM: { rpgitem *saving = (rpgitem *) d; writeitem(f, saving); break; } case ENT_OBSTACLE: { rpgobstacle *saving = (rpgobstacle *) d; writestring(f, saving->mdl); writestring(f, saving->script->key); writevec(saving->colour) f->putlil(saving->weight); f->putlil(saving->flags); f->putlil(saving->scale); break; } case ENT_CONTAINER: { rpgcontainer *saving = (rpgcontainer *) d; writestring(f, saving->mdl); writestring(f, saving->name); writestring(f, saving->faction ? saving->faction->key : NULL); writestring(f, saving->merchant ? saving->merchant->key : NULL); writestring(f, saving->script->key ); writevec(saving->colour) f->putlil(saving->capacity); f->putlil(saving->lock); f->putlil(saving->magelock); f->putlil(saving->scale); vector<item *> items; enumerate(saving->inventory, vector<item *>, stack, loopvj(stack) items.add(stack[j]); ) f->putlil(items.length()); loopv(items) writeitem(f, items[i]); break; } case ENT_PLATFORM: { rpgplatform *saving = (rpgplatform *) d; writestring(f, saving->mdl); writestring(f, saving->script->key); writevec(saving->colour) f->putlil(saving->speed); f->putlil(saving->flags); f->putlil(saving->scale); f->putlil(saving->routes.length()); enumeratekt(saving->routes, int, stop, vector<int>, routes, f->putlil(stop); f->putlil(routes.length()); loopvj(routes) f->putlil(routes[j]); ); f->putlil(saving->target); break; } case ENT_TRIGGER: { rpgtrigger *saving = (rpgtrigger *) d; writestring(f, saving->mdl); writestring(f, saving->name); writestring(f, saving->script->key); writevec(saving->colour) f->putlil(saving->flags); f->putlil(saving->lasttrigger - lastmillis); f->putlil(saving->scale); break; } default: ERRORF("unsupported ent type %i, aborting", d->type()); return; } f->putlil(d->locals); f->putlil(d->seffects.length()); loopv(d->seffects) { f->putlil(enttonum(d->seffects[i]->owner)); writestring(f, d->seffects[i]->group->key); f->putlil(d->seffects[i]->elem); f->putlil(d->seffects[i]->effects.length()); loopvj(d->seffects[i]->effects) { status *st = d->seffects[i]->effects[j]; f->putlil(st->type); switch(st->type) { case STATUS_POLYMORPH: { status_polymorph *poly = (status_polymorph *) st; writestring(f, poly->mdl); break; } case STATUS_LIGHT: { status_light *light = (status_light *) st; writevec(light->colour); break; } case STATUS_SCRIPT: { status_script *scr = (status_script *) st; writestring(f, scr->script); break; } case STATUS_SIGNAL: { status_signal *sig = (status_signal *) st; writestring(f, sig->signal); break; } } f->putlil(st->duration); f->putlil(st->remain); f->putlil(st->strength); f->putlil(st->variance); } } f->putlil(d->maxheight); f->putlil(d->eyeheight); writevec(d->o); writevec(d->vel); writevec(d->falling); f->putlil(d->yaw); f->putlil(d->pitch); f->putlil(d->roll); f->putlil(d->timeinair); f->putchar(d->state); f->putchar(d->editstate); } mapinfo *readmap(stream *f) { const char *name = readstring(f); mapinfo *loading = game::accessmap(name); lastmap = loading; loading->name = name; READHASHEXTENDED(loading->script, game::mapscripts); NOTNULL(loading->script, loading); loading->flags = f->getlil<int>(); loading->loaded = f->getchar(); int numobjs = f->getlil<int>(), numactions = f->getlil<int>(), numprojs = f->getlil<int>(), numaeffects = f->getlil<int>(), numblips = f->getlil<int>(); rpgscript::keeplocal((loading->locals = f->getlil<int>())); loopi(numobjs) { CHECKEOF(*f, loading) loading->objs.add(readent(f)); } loopvrev(updates) { CHECKEOF(*f, loading) if(updates[i].map == lastmap) updates[i].ref = entfromnum(updates[i].ind); } loopi(numactions) { CHECKEOF(*f, loading) action *act = NULL; int type = f->getlil<int>(); switch(type) { case ACTION_TELEPORT: { int ent = f->getlil<int>(); if(!entfromnum(ent)) {//how'd that happen? WARNINGF("loaded teleport loadaction for invalid ent? ignoring"); f->getlil<int>(); f->getlil<int>(); continue; } int d = f->getlil<int>(); int t = f->getlil<int>(); act = new action_teleport(entfromnum(ent), d, t); break; } case ACTION_SPAWN: { const char *id = NULL; READHASH(id) NOTNULL(id, loading) int tag = f->getlil<int>(), ent = f->getlil<int>(), amount = f->getlil<int>(), qty = f->getlil<int>(); act = new action_spawn(tag, ent, id, amount, qty); break; } case ACTION_SCRIPT: { act = new action_script(readstring(f)); break; } } loading->loadactions.add(act); } loopk(numprojs) { CHECKEOF(*f, loading) projectile *p = loading->projs.add(new projectile()); p->owner = (rpgchar *) entfromnum(f->getlil<int>()); if(p->owner && p->owner->type() != ENT_CHAR) p->owner = NULL; int wep = f->getlil<int>(); int ammo = f->getlil<int>(); int use = f->getlil<int>(); int ause = f->getlil<int>(); if(p->owner) { enumerate(p->owner->inventory, vector<item *>, stack, if(stack.inrange(wep)) p->item = equipment(stack[wep], use); if(stack.inrange(ammo)) p->ammo = equipment(stack[ammo], ause); wep -= stack.length(); ammo -= stack.length(); ) } readvec(p->o); readvec(p->dir); readvec(p->emitpos); p->lastemit = 0; //should emit immediately p->gravity = f->getlil<int>(); p->deleted = f->getchar(); p->pflags = f->getlil<int>(); p->time = f->getlil<int>(); p->dist = f->getlil<int>(); READHASHEXTENDED(p->projfx, game::effects) READHASHEXTENDED(p->trailfx, game::effects) READHASHEXTENDED(p->deathfx, game::effects) p->radius = f->getlil<int>(); p->elasticity = f->getlil<float>(); p->charge = f->getlil<float>(); p->chargeflags = f->getlil<int>(); } loopi(numaeffects) { CHECKEOF(*f, loading) areaeffect *aeff = loading->aeffects.add(new areaeffect()); aeff->owner = entfromnum(f->getlil<int>()); readvec(aeff->o); aeff->lastemit = 0; //should emit immediately READHASHEXTENDED(aeff->group, game::statuses) NOTNULL(aeff->group, loading); READHASHEXTENDED(aeff->fx, game::effects) if(aeff->fx) NOTNULL(aeff->fx, loading); aeff->elem = f->getlil<int>(); aeff->radius = f->getlil<int>(); int numstat = f->getlil<int>(); loopj(numstat) { CHECKEOF(*f, loading) int type = f->getlil<int>(); status *st = NULL; switch(type) { case STATUS_POLYMORPH: { status_polymorph *poly = new status_polymorph(); st = aeff->effects.add(poly); poly->mdl = readstring(f); NOTNULL(poly->mdl, loading); preloadmodel(poly->mdl); break; } case STATUS_LIGHT: { status_light *light = new status_light(); st = aeff->effects.add(light); readvec(light->colour); break; } case STATUS_SCRIPT: { status_script *scr = new status_script(); st = aeff->effects.add(scr); scr->script = readstring(f); break; } case STATUS_SIGNAL: { status_signal *sig = new status_signal(); st = aeff->effects.add(sig); sig->signal = readstring(f); break; } default: st = aeff->effects.add(new status_generic()); break; } st->type = type; st->duration = f->getlil<int>(); st->remain = f->getlil<int>(); st->strength = f->getlil<int>(); st->variance = f->getlil<float>(); } } loopi(numblips) { ///FIXME finalize blip structure and write me } lastmap = NULL; return loading; } void writemap(stream *f, mapinfo *saving) { lastmap = saving; writestring(f, saving->name); writestring(f, saving->script->key); f->putlil(saving->flags); f->putchar(saving->loaded); f->putlil(saving->objs.length()); f->putlil(saving->loadactions.length()); f->putlil(saving->projs.length()); f->putlil(saving->aeffects.length()); f->putlil(saving->blips.length()); f->putlil(saving->locals); loopv(saving->objs) { writeent(f, saving->objs[i]); } loopv(saving->loadactions) { f->putlil(saving->loadactions[i]->type()); switch(saving->loadactions[i]->type()) { case ACTION_TELEPORT: { action_teleport *act = (action_teleport *) saving->loadactions[i]; f->putlil(enttonum(act->ent)); f->putlil(act->dest); f->putlil(act->etype); break; } case ACTION_SPAWN: { action_spawn *spw = (action_spawn *) saving->loadactions[i]; writestring(f, spw->id); f->putlil(spw->tag); f->putlil(spw->ent); f->putlil(spw->amount); f->putlil(spw->qty); break; } case ACTION_SCRIPT: writestring(f, ((action_script *) saving->loadactions[i])->script); break; } } loopv(saving->projs) { projectile *p = saving->projs[i]; f->putlil(enttonum(p->owner)); int offset = 0; int wep = -1; int ammo = -1; if(p->owner) { enumerate(p->owner->inventory, vector<item *>, stack, if(stack.find(p->item.it) >= 0) wep = stack.find(p->item.it) + offset; if(stack.find(p->ammo.it) >= 0) ammo = stack.find(p->ammo.it) + offset; offset += stack.length(); ) } f->putlil(wep); f->putlil(ammo); f->putlil(p->item.use); f->putlil(p->ammo.use); writevec(p->o); writevec(p->dir); writevec(p->emitpos); //f->putlil(p->lastemit); f->putlil(p->gravity); f->putchar(p->deleted); f->putlil(p->pflags); f->putlil(p->time); f->putlil(p->dist); writestring(f, p->projfx ? p->projfx->key : NULL); writestring(f, p->trailfx ? p->trailfx->key : NULL); writestring(f, p->deathfx ? p->deathfx->key : NULL); f->putlil(p->radius); f->putlil(p->elasticity); f->putlil(p->charge); f->putlil(p->chargeflags); } loopv(saving->aeffects) { areaeffect *aeff = saving->aeffects[i]; f->putlil(enttonum(aeff->owner)); writevec(aeff->o); writestring(f, aeff->group ? aeff->group->key : NULL); writestring(f, aeff->fx ? aeff->fx->key : NULL); f->putlil(aeff->elem); f->putlil(aeff->radius); f->putlil(aeff->effects.length()); loopvj(aeff->effects) { status *st = aeff->effects[i]; f->putlil(st->type); switch(st->type) { case STATUS_POLYMORPH: { status_polymorph *poly = (status_polymorph *) st; writestring(f, poly->mdl); break; } case STATUS_LIGHT: { status_light *light = (status_light *) st; writevec(light->colour); break; } case STATUS_SCRIPT: { status_script *scr = (status_script *) st; writestring(f, scr->script); break; } case STATUS_SIGNAL: { status_signal *sig = (status_signal *) st; writestring(f, sig->signal); break; } } f->putlil(st->duration); f->putlil(st->remain); f->putlil(st->strength); f->putlil(st->variance); } } loopv(saving->blips) { ///FIXME finalize blip structure and write me } lastmap = NULL; } //don't mind the ::blah, just a namespace collision with rpgio:: when we want it from the global scope void writereferences(stream *f, const vector<mapinfo *> &maps, hashnameset< ::reference> &stack) { f->putlil(stack.length()); enumerate(stack, ::reference, saving, writestring(f, saving.name); f->putchar(saving.immutable); f->putlil(saving.list.length()); loopvj(saving.list) { ::reference::ref &sav = saving.list[j]; char type = sav.type; if(sav.ptr == NULL) { if(DEBUG_IO) DEBUGF("reference %s:%i of type %i is null, saving as T_INVALID", saving.name, j, type); type = ::reference::T_INVALID; } switch(type) { case ::reference::T_CHAR: case ::reference::T_ITEM: case ::reference::T_OBSTACLE: case ::reference::T_CONTAINER: case ::reference::T_PLATFORM: case ::reference::T_TRIGGER: { int map = -1; int ent = -1; if(sav.ptr == game::player1) { map = ent = -1; } else loopvj(maps) { ent = maps[j]->objs.find(sav.ptr); if(ent >= 0) {map = j; break;} } if(map < 0 && ent < 0 && sav.ptr != game::player1) { WARNINGF("char/item/object reference \"%s\" points to non-player entity that does not exist", saving.name); f->putchar(::reference::T_INVALID); continue; } if(DEBUG_IO) DEBUGF("writing reference %s as rpgent reference: %i %i", saving.name, map, ent); f->putchar(type); f->putlil(map); f->putlil(ent); break; } case ::reference::T_MAP: { f->putchar(type); int map = maps.find(sav.ptr); f->putlil(map); if(DEBUG_IO) DEBUGF("writing reference %s:%i as map reference: %i", saving.name, j, map); break; } case ::reference::T_INV: { int map = -1; int ent = -1; const char *base = saving.getinv(j)->base; int offset = -1; { vector <item *> *stack = game::player1->inventory.access(base); if(stack) offset = stack->find(sav.ptr); } if(offset < 0) loopv(maps) { loopvj(maps[i]->objs) { vector<item *> *stack = NULL; if(maps[i]->objs[j]->type() == ENT_CHAR) stack = ((rpgchar *) maps[i]->objs[j])->inventory.access(base); else if(maps[i]->objs[j]->type() == ENT_CONTAINER) stack = ((rpgcontainer *) maps[i]->objs[j])->inventory.access(base); if(stack) offset = stack->find(sav.ptr); if(offset >= 0) { ent = j; break; } } if(offset >= 0) { map = i; break; } } if(offset < 0) { WARNINGF("inv reference \"%s:%i\" points to an item that does not exist", saving.name, j); f->putchar(::reference::T_INVALID); continue; } if(DEBUG_IO) DEBUGF("writing reference \"%s:%i\" as type T_INV with indices: %i %i %s %i", saving.name, j, map, ent, base, offset); f->putchar(type); f->putlil(map); f->putlil(ent); writestring(f, base); f->putlil(offset); break; } // default: ERRORF("unsupported reference type %i for reference %s:%i, saving as T_INVALID", sav.type, saving.name, j); // Temporary reference types below this line... [[fallthrough]]; case ::reference::T_EQUIP: case ::reference::T_VEFFECT: case ::reference::T_AEFFECT: type = ::reference::T_INVALID; [[fallthrough]]; case ::reference::T_INVALID: if(DEBUG_IO) DEBUGF("writing null reference %s:%i", saving.name, j); f->putchar(type); break; } } ) } void readreferences(stream *f, const vector<mapinfo *> &maps, hashnameset< ::reference> &stack) { int num = f->getlil<int>(); loopi(num) { CHECKEOF(*f, ) const char *name = NULL; READHASH(name); NOTNULL(name, ) ::reference *loading = stack.access(name); if(loading) { WARNINGF("reference \"%s\" appears to have already been loaded", name); loading->dump(); } else { if(DEBUG_IO) DEBUGF("Creating reference \"%s\"", name); loading = &stack[name]; loading->name = name; } loading->immutable = f->getchar(); int len = f->getlil<int>(); loopj(len) { char type = f->getchar(); switch(type) { case ::reference::T_CHAR: case ::reference::T_ITEM: case ::reference::T_OBSTACLE: case ::reference::T_CONTAINER: case ::reference::T_PLATFORM: case ::reference::T_TRIGGER: { int map = f->getlil<int>(); int ent = f->getlil<int>(); if(map == -1 && ent == -1) { if(DEBUG_IO) DEBUGF("reading player char reference %s:%i", loading->name, j); loading->pushref(game::player1, true); } else if(maps.inrange(map) && maps[map]->objs.inrange(ent)) { if(DEBUG_IO) DEBUGF("reading valid rpgent reference %s:%i -> %i %i", loading->name, j, map, ent); loading->pushref(maps[map]->objs[ent], true); } else WARNINGF("rpgent reference %s:%i -> %i %i - indices out of range", loading->name, j, map, ent); break; } case ::reference::T_MAP: { int map = f->getlil<int>(); if(DEBUG_IO) DEBUGF("reading map reference %s:%i -> %i", loading->name, j, map); if(maps.inrange(map)) loading->pushref(maps[map], true); break; } case ::reference::T_INV: { int map = f->getlil<int>(); int ent = f->getlil<int>(); const char *base = NULL; READHASH(base); NOTNULL(base, ) int offset = f->getlil<int>(); if(DEBUG_IO) DEBUGF("reading T_INV reference %s:%i with values %i %i %s %i...", loading->name, j, map, ent, base, offset); vector <item *> *stack = NULL; if(map == -1 && ent == -1) stack = game::player1->inventory.access(base); else if (maps.inrange(map) && maps[map]->objs.inrange(ent)) { if(maps[map]->objs[ent]->type() == ENT_CHAR) stack = ((rpgchar *) maps[map]->objs[ent])->inventory.access(base); else if(maps[map]->objs[ent]->type() == ENT_CONTAINER) stack = ((rpgcontainer *) maps[map]->objs[ent])->inventory.access(base); } if(stack && stack->inrange(offset)) { if(DEBUG_IO) DEBUGF("Loading T_INV reference to %p successfully", (*stack)[offset]); loading->pushref((*stack)[offset], true); } else WARNINGF("T_INV reference %s:%i has out of range values: %i %i %s %i, loading failed", loading->name, j, map, ent, base, offset); break; } //Temporary types below this line case ::reference::T_EQUIP: case ::reference::T_VEFFECT: case ::reference::T_AEFFECT: WARNINGF("volatile reference type found for reference %s:%i, assuming invalid", loading->name, j); [[fallthrough]]; case ::reference::T_INVALID: if(DEBUG_IO) DEBUGF("reading now null reference %s:%i", loading->name, j); loading->pushref(NULL, true); break; default: ERRORF("unsupported reference type %i for reference %s:%i, this will cause issues; aborting", type, loading->name, j); abort = true; return; } } } } void writedelayscript(stream *f, const vector<mapinfo *> &maps, delayscript *saving) { writereferences(f, maps, saving->refs); writestring(f, saving->script); f->putlil(saving->remaining); } void readdelayscript(stream *f, const vector<mapinfo *> &maps, delayscript *loading) { readreferences(f, maps, loading->refs); loading->script = readstring(f); loading->remaining = f->getlil<int>(); } void writejournal(stream *f, journal *saving) { writestring(f, saving->name); f->putlil(saving->status); f->putlil(saving->entries.length()); loopv(saving->entries) writestring(f, saving->entries[i]); } void readjournal(stream *f) { const char *name = NULL; READHASH(name); NOTNULL(name, ) journal *journ = &game::journals[name]; if(journ->name) WARNINGF("additional instance of journal %s exists, merging", name); journ->name = name; journ->status = f->getlil<int>(); int entries = f->getlil<int>(); loopi(entries) journ->entries.add(readstring(f)); } void writelocal(stream *f, localinst *saving) { f->putchar(saving ? saving->shared : 0); int n = 0; if(saving) n = saving->variables.length(); f->putlil(n); if(saving) enumerate(saving->variables, rpgvar, var, writestring(f, var.name); writestring(f, var.value); ) } void readlocal(stream *f, int i) { if(!rpgscript::locals.inrange(i)) rpgscript::alloclocal(false); localinst *loading = rpgscript::locals[i]; loading->refs = 0; loading->shared = f->getchar(); int n = f->getlil<int>(); loopj(n) { CHECKEOF(*f, ) const char *name = NULL; READHASH(name); NOTNULL(name, ); const char *value = readstring(f); rpgvar &var = loading->variables[name]; if(var.value) delete[] var.value; var.name = name; var.value = value; } } void writetimer(stream *f, vector<mapinfo *> &maps, timer *saving) { writestring(f, saving->name); writestring(f, saving->cond); writestring(f, saving->script); f->putlil(saving->delay); f->putlil(saving->remaining); } void readtimer(stream *f, vector<mapinfo *> &maps) { const char *name; READHASH(name); NOTNULL(name, ); bool del = false; timer *loading; if(rpgscript::timers.access(name)) { if(DEBUG_IO) DEBUGF("Timer %s already exists, restoring countdown only", name); del = true; loading = new timer(); } else loading = &rpgscript::timers[name]; loading->name = name; loading->cond = readstring(f); loading->script = readstring(f); loading->delay = f->getlil<int>(); loading->remaining = f->getlil<int>(); if(del) { rpgscript::timers[name].remaining = loading->remaining; delete loading; } } void loadgame(const char *name) { defformatstring(file, "%s/%s.sgz", game::datapath("saves"), name); stream *f = opengzfile(file, "rb"); if(!f) { ERRORF("unable to read file: %s", file); return; } saveheader hdr; f->read(&hdr, sizeof(saveheader)); lilswap(&hdr.sversion, 2); if(hdr.sversion < COMPAT_VERSION || hdr.sversion > SAVE_VERSION || strncmp(hdr.magic, SAVE_MAGIC, 4)) { ERRORF("Unsupported version or corrupt save: %i (%i) - %4.4s (%s)", hdr.sversion, SAVE_VERSION, hdr.magic, SAVE_MAGIC); delete f; return; } if(DEBUG_IO) DEBUGF("supported save: %i %4.4s", hdr.sversion, hdr.magic); vector<mapinfo *> maps; const char *data = readstring(f); const char *curmap = readstring(f); const char *cpmap = readstring(f); int cpnum = f->getlil<int>(); abort = !game::newgame(data, true); if(cpmap) game::setcheckpoint(cpmap, cpnum); delete[] data; delete[] cpmap; if(game::compatversion > hdr.gversion) { ERRORF("saved game is of game version %i, last compatible version is %i; aborting", hdr.gversion, game::compatversion); abort = true; goto cleanup; } if(!curmap || abort) { ERRORF("No map in progress?"); abort = true; goto cleanup; } lastmap = game::accessmap(curmap); int num; #define READ(m, b) \ num = f->getlil<int>(); \ loopi(num) \ { \ if(abort) goto cleanup; \ if(f->end()) \ { \ ERRORF("unexpected EoF, aborting"); \ abort = true; goto cleanup; \ } \ if(DEBUG_IO) \ DEBUGF("reading " #m " %i of %i", i + 1, num); \ b; \ } ///TODO redo hotkeys // READ(hotkey, // int b = f->getlil<int>(); // int u = f->getlil<int>(); // game::hotkeys.add(equipment(b, u)); // ) READ(faction, const char *key = NULL; READHASH(key); faction *fac = game::factions.access(key); if(!fac) WARNINGF("reading faction %s as a dummy", key); readfaction(f, fac); ); READ(recipe, const char *key = NULL; READHASH(key); recipe *r = game::recipes.access(key); if(!r) WARNINGF("reading recipe %s as a dummy", key); readrecipe(f, r); ); READ(merchant, const char *key = NULL; READHASH(key); merchant *m = game::merchants.access(key); if(!m) WARNINGF("reading merchant %s as a dummy", key); readmerchant(f, m); ); READ(variable, const char *name = NULL; READHASH(name); const char *v = readstring(f); if(!rpgscript::setglobal(name, v, false)) WARNINGF("reloading the game added variable \"%s\"", name); ) READ(locals stack, readlocal(f, i); ) readent(f, game::player1); READ(mapinfo, maps.add(readmap(f))); READ(reference stack, if(!rpgscript::stack.inrange(i)) rpgscript::pushstack(); readreferences(f, maps, *rpgscript::stack[i]); ) READ(delayscript stack, rpgscript::delaystack.add(new delayscript()); readdelayscript(f, maps, rpgscript::delaystack[i]); ) READ(global timers, readtimer(f, maps); ) READ(journal bucket, readjournal(f); ) #undef READ if(!abort) loopv(characters) characters[i]->compactinventory(NULL); cleanup: delete f; characters.shrink(0); updates.shrink(0); rpgscript::cleanlocals(); if(abort) { ERRORF("aborted - something went seriously wrong"); localdisconnect(); delete[] curmap; return; } game::transfer = true; game::openworld(curmap); delete[] curmap; //the game is compatible but is an older version //this is to update things to a newer version if such changes are required for(int v = hdr.gversion; v < game::gameversion; v++) { defformatstring(signal, "import %i", v); if(DEBUG_IO) DEBUGF("the game is outdated, currently version %i - sending \"%s\" to do any needed changes", v, signal); enumerate(game::mapdata, mapinfo, map, map.getsignal(signal, true, NULL); ) } } COMMAND(loadgame, "s"); void savegame(const char *name) { if(!game::connected || !game::curmap) { ERRORF("No game in progress, can't save"); return; } else if(!game::cansave()) { conoutf("You may not save at this time"); return; } defformatstring(file, "%s/%s.sgz.tmp", game::datapath("saves"), name); stream *f = opengzfile(path(file), "wb"); if(!f) { ERRORF("failed to create savegame"); return; } saveheader hdr; hdr.sversion = SAVE_VERSION; hdr.gversion = game::gameversion; memcpy(hdr.magic, SAVE_MAGIC, 4); lilswap(&hdr.sversion, 2); f->write(&hdr, sizeof(saveheader)); writestring(f, game::data); writestring(f, game::curmap->name); writestring(f, game::cpmap); f->putlil(game::cpnum); #define WRITE(m, v, b) \ f->putlil(v.length()); \ loopv(v) \ { \ if(DEBUG_IO) \ DEBUGF("Writing " #m " %i of %i", i + 1, v.length()); \ b; \ } #define WRITEHT(m, ht, t, b) \ if(DEBUG_IO) DEBUGF("Writing %i " #m "(s)", (ht).length()); \ f->putlil((ht).length()); \ enumerate(ht, t, entry, \ writestring(f, entry.key); \ if(DEBUG_IO) \ DEBUGF("Writing " #m " %s to file...", entry.key); \ b; \ ) ///TODO redo hotkeys // WRITE(hotkey, game::hotkeys, // f->putlil(game::hotkeys[i].base); // f->putlil(game::hotkeys[i].use); // ) WRITEHT(faction, game::factions, faction, writefaction(f, &entry); ) WRITEHT(recipe, game::recipes, recipe, writerecipe(f, &entry); ) WRITEHT(merchant, game::merchants, merchant, writemerchant(f, &entry); ) vector<rpgvar *> vars; enumerate(game::variables, rpgvar, var, vars.add(&var)); WRITE(variable, vars, writestring(f, vars[i]->name); writestring(f, vars[i]->value); ) WRITE(locals stack, rpgscript::locals, writelocal(f, rpgscript::locals[i]); ) writeent(f, game::player1); game::curmap->objs.removeobj(game::player1); vector<mapinfo *> maps; enumerate(game::mapdata, mapinfo, map, maps.add(&map);); WRITE(map, maps, writemap(f, maps[i])); WRITE(reference stack, rpgscript::stack, writereferences(f, maps, *rpgscript::stack[i]); ) WRITE(delayscript stack, rpgscript::delaystack, writedelayscript(f, maps, rpgscript::delaystack[i]); ) vector<timer *> timers; enumerate(rpgscript::timers, timer, t, timers.add(&t)); WRITE(global timer, timers, writetimer(f, maps, timers[i]); ) vector<journal *> journ; enumerate(game::journals, journal, bucket, journ.add(&bucket); ) WRITE(journal bucket, journ, writejournal(f, journ[i]); ) game::curmap->objs.add(game::player1); DELETEP(f); string final; copystring(final, file, strlen(file) - 3); backup(file, final); conoutf("Game saved successfully to %s", final); copystring(file + strlen(file) - 8, ".png", 5); scaledscreenshot(file, 2, 256, 256); reloadtexture(file); } COMMAND(savegame, "s"); }
24.119248
137
0.598851
Hirato
0fc1bff6c52ccfb50269b5d37ebb75bc57cc4103
1,266
cc
C++
src/ppl/nn/engines/riscv/utils/fp16fp32_cvt.cc
tangyanf/ppl.nn
744ac02e7d6e363522dc629b35db8a5eca2e7c3c
[ "Apache-2.0" ]
1
2022-03-27T07:55:37.000Z
2022-03-27T07:55:37.000Z
src/ppl/nn/engines/riscv/utils/fp16fp32_cvt.cc
tangyanf/ppl.nn
744ac02e7d6e363522dc629b35db8a5eca2e7c3c
[ "Apache-2.0" ]
null
null
null
src/ppl/nn/engines/riscv/utils/fp16fp32_cvt.cc
tangyanf/ppl.nn
744ac02e7d6e363522dc629b35db8a5eca2e7c3c
[ "Apache-2.0" ]
null
null
null
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "ppl/common/log.h" void CvtFp32ToFp16(int64_t counts, void const* src, void* dst) { auto src_ptr = (float*)src; auto dst_ptr = (__fp16*)dst; for (int64_t i = 0; i < counts; i += 1) { dst_ptr[i] = src_ptr[i]; } } void CvtFp16ToFp32(int64_t counts, void const* src, void* dst) { auto src_ptr = (__fp16*)src; auto dst_ptr = (float*)dst; for (int64_t i = 0; i < counts; i += 1) { dst_ptr[i] = src_ptr[i]; } }
36.171429
64
0.692733
tangyanf
0fc1f37a38b5d513e821111d5f5c2192eb9bc554
140
hpp
C++
Iridium/Utility/Allocator.hpp
lordharambae/Iridium
40997d7082f7f80e38338af358fdca2a5ac3af63
[ "BSD-3-Clause" ]
null
null
null
Iridium/Utility/Allocator.hpp
lordharambae/Iridium
40997d7082f7f80e38338af358fdca2a5ac3af63
[ "BSD-3-Clause" ]
null
null
null
Iridium/Utility/Allocator.hpp
lordharambae/Iridium
40997d7082f7f80e38338af358fdca2a5ac3af63
[ "BSD-3-Clause" ]
null
null
null
#pragma once #ifndef ALLOCATOR_HPP #define ALLOCATOR_HPP namespace Iridium { namespace Utility { class Allocator {}; } } #endif
8.75
21
0.707143
lordharambae
0fc3c2656736fc3dfc22fc80f6cf8a7294d5090a
2,039
cc
C++
mindspore/core/ir/func_graph_base.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
1
2022-03-05T02:59:21.000Z
2022-03-05T02:59:21.000Z
mindspore/core/ir/func_graph_base.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
mindspore/core/ir/func_graph_base.cc
zhz44/mindspore
6044d34074c8505dd4b02c0a05419cbc32a43f86
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2019-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 "ir/func_graph_base.h" #include <list> #include <algorithm> #include "ir/func_graph.h" namespace mindspore { FuncGraphLoopBreaker::~FuncGraphLoopBreaker() { std::lock_guard<std::mutex> lock_set(func_mutex_); for (auto fg : func_set_) { fg->reg_flg = false; } } FuncGraphLoopBreaker &FuncGraphLoopBreaker::Inst() { static FuncGraphLoopBreaker mgr; return mgr; } void FuncGraphLoopBreaker::BreakLoop() { MS_LOG(INFO) << "Size of not recycled graph before break loop is:" << func_set_.size(); std::list<FuncGraphBasePtr> func_list; // Generate shared_ptr for every graph, to avoid func_set_ changes while BreakLoop (void)std::transform(func_set_.begin(), func_set_.end(), std::back_inserter(func_list), [](FuncGraphBase *fun) -> FuncGraphBasePtr { return fun->shared_from_base<FuncGraphBase>(); }); for (auto &item : func_list) { item->DoBreakLoop(); } func_list.clear(); int func_graph_cnt = 0; for (auto item : func_set_) { if (item->isa<FuncGraph>()) { MS_LOG(ERROR) << "Unfree graph info:" << item->ToString(); func_graph_cnt++; } } if (func_graph_cnt > 0) { MS_LOG(EXCEPTION) << "Size of not recycled graph after break loop should be 0, but got:" << func_set_.size() << "\n" << "Please check the usage of clear_compile_cache or contact to the maintenance engineers."; } } } // namespace mindspore
34.559322
120
0.695439
zhz44
0fc50082be9f2214956188bcdd64b61b03cf7624
8,882
cc
C++
code/bess-v1/core/utils/cuckoo_map_test.cc
Lossless-Virtual-Switching/Backdraft
99e8f7acf833d1755a109898eb397c3412fff159
[ "MIT" ]
1
2020-06-22T13:21:43.000Z
2020-06-22T13:21:43.000Z
code/bess-v1/core/utils/cuckoo_map_test.cc
Lossless-Virtual-Switching/Backdraft
99e8f7acf833d1755a109898eb397c3412fff159
[ "MIT" ]
null
null
null
code/bess-v1/core/utils/cuckoo_map_test.cc
Lossless-Virtual-Switching/Backdraft
99e8f7acf833d1755a109898eb397c3412fff159
[ "MIT" ]
null
null
null
// Copyright (c) 2016-2017, Nefeli Networks, Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the names of the copyright holders nor the names of their // 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 "cuckoo_map.h" #include <map> #include <unordered_map> #include <vector> #include <gtest/gtest.h> #include "random.h" struct CopyConstructorOnly { // FIXME: CuckooMap should work without this default constructor CopyConstructorOnly() = default; CopyConstructorOnly(CopyConstructorOnly &&other) = delete; CopyConstructorOnly(int aa, int bb): a(aa), b(bb) {} CopyConstructorOnly(const CopyConstructorOnly &other) : a(other.a), b(other.b) {} int a; int b; }; struct MoveConstructorOnly { // FIXME: CuckooMap should work without this default constructor MoveConstructorOnly() = default; MoveConstructorOnly(const MoveConstructorOnly &other) = delete; MoveConstructorOnly(int aa, int bb): a(aa), b(bb) {} MoveConstructorOnly(MoveConstructorOnly &&other) noexcept : a(other.a), b(other.b) { other.a = 0; other.b = 0; } int a; int b; }; // C++ has no clean way to specialize templates for derived typess... // so we just define a hash functor for each. template <> struct std::hash<CopyConstructorOnly> { std::size_t operator()(const CopyConstructorOnly &t) const noexcept { return std::hash<int>()(t.a + t.b); // doesn't need to be a good one... } }; template <> struct std::hash<MoveConstructorOnly> { std::size_t operator()(const MoveConstructorOnly &t) const noexcept { return std::hash<int>()(t.a * t.b); // doesn't need to be a good one... } }; namespace { using bess::utils::CuckooMap; // Test Insert function TEST(CuckooMapTest, Insert) { CuckooMap<uint32_t, uint16_t> cuckoo; EXPECT_EQ(cuckoo.Insert(1, 99)->second, 99); EXPECT_EQ(cuckoo.Insert(2, 98)->second, 98); EXPECT_EQ(cuckoo.Insert(1, 1)->second, 1); } template<typename T> void CompileTimeInstantiation() { std::map<int, T> m1; std::map<T, int> m2; std::map<T, T> m3; std::unordered_map<int, T> u1; std::unordered_map<T, int> u2; std::unordered_map<T, T> u3; std::vector<T> v1; // FIXME: currently, CuckooMap does not support types without a default // constructor. The following will fail with the current code. // CuckooMap<int, T> c1; // CuckooMap<T, int> c2; // CuckooMap<T, T> c3; } TEST(CuckooMap, TypeSupport) { // Standard containers, such as std::map and std::vector, should be able to // contain types with various constructor and assignment restrictions. // The below will check this ability at compile time. CompileTimeInstantiation<CopyConstructorOnly>(); CompileTimeInstantiation<MoveConstructorOnly>(); } // Test insertion with copy TEST(CuckooMapTest, CopyInsert) { CuckooMap<uint32_t, CopyConstructorOnly> cuckoo; auto expected = CopyConstructorOnly(1, 2); auto *entry = cuckoo.Insert(10, expected); ASSERT_NE(nullptr, entry); const auto &x = entry->second; EXPECT_EQ(1, x.a); EXPECT_EQ(2, x.b); } // Test insertion with move TEST(CuckooMapTest, MoveInsert) { CuckooMap<uint32_t, MoveConstructorOnly> cuckoo; auto expected = MoveConstructorOnly(3, 4); auto *entry = cuckoo.Insert(11, std::move(expected)); ASSERT_NE(nullptr, entry); const auto &x = entry->second; EXPECT_EQ(3, x.a); EXPECT_EQ(4, x.b); } // Test Emplace function TEST(CuckooMapTest, Emplace) { CuckooMap<uint32_t, CopyConstructorOnly> cuckoo; auto *entry = cuckoo.Emplace(12, 5, 6); ASSERT_NE(nullptr, entry); const auto &x = entry->second; EXPECT_EQ(5, x.a); EXPECT_EQ(6, x.b); } // Test Find function TEST(CuckooMapTest, Find) { CuckooMap<uint32_t, uint16_t> cuckoo; cuckoo.Insert(1, 99); cuckoo.Insert(2, 99); EXPECT_EQ(cuckoo.Find(1)->second, 99); EXPECT_EQ(cuckoo.Find(2)->second, 99); cuckoo.Insert(1, 2); EXPECT_EQ(cuckoo.Find(1)->second, 2); EXPECT_EQ(cuckoo.Find(3), nullptr); EXPECT_EQ(cuckoo.Find(4), nullptr); } // Test Remove function TEST(CuckooMapTest, Remove) { CuckooMap<uint32_t, uint16_t> cuckoo; cuckoo.Insert(1, 99); cuckoo.Insert(2, 99); EXPECT_EQ(cuckoo.Find(1)->second, 99); EXPECT_EQ(cuckoo.Find(2)->second, 99); EXPECT_TRUE(cuckoo.Remove(1)); EXPECT_TRUE(cuckoo.Remove(2)); EXPECT_EQ(cuckoo.Find(1), nullptr); EXPECT_EQ(cuckoo.Find(2), nullptr); } // Test Count function TEST(CuckooMapTest, Count) { CuckooMap<uint32_t, uint16_t> cuckoo; EXPECT_EQ(cuckoo.Count(), 0); cuckoo.Insert(1, 99); cuckoo.Insert(2, 99); EXPECT_EQ(cuckoo.Count(), 2); cuckoo.Insert(1, 2); EXPECT_EQ(cuckoo.Count(), 2); EXPECT_TRUE(cuckoo.Remove(1)); EXPECT_TRUE(cuckoo.Remove(2)); EXPECT_EQ(cuckoo.Count(), 0); } // Test Clear function TEST(CuckooMapTest, Clear) { CuckooMap<uint32_t, uint16_t> cuckoo; EXPECT_EQ(cuckoo.Count(), 0); cuckoo.Insert(1, 99); cuckoo.Insert(2, 99); EXPECT_EQ(cuckoo.Count(), 2); cuckoo.Clear(); EXPECT_EQ(cuckoo.Count(), 0); EXPECT_FALSE(cuckoo.Remove(1)); EXPECT_FALSE(cuckoo.Remove(2)); } // Test iterators TEST(CuckooMapTest, Iterator) { CuckooMap<uint32_t, uint16_t> cuckoo; EXPECT_EQ(cuckoo.begin(), cuckoo.end()); cuckoo.Insert(1, 99); cuckoo.Insert(2, 99); auto it = cuckoo.begin(); EXPECT_EQ(it->first, 1); EXPECT_EQ(it->second, 99); ++it; EXPECT_EQ(it->first, 2); EXPECT_EQ(it->second, 99); it++; EXPECT_EQ(it, cuckoo.end()); } // Test different keys with the same hash value TEST(CuckooMapTest, CollisionTest) { class BrokenHash { public: bess::utils::HashResult operator()(const uint32_t) const { return 9999999; } }; CuckooMap<int, int, BrokenHash> cuckoo; // Up to 8 (2 * slots/bucket) hash collision should be acceptable const int n = 8; for (int i = 0; i < n; i++) { EXPECT_TRUE(cuckoo.Insert(i, i + 100)); } EXPECT_EQ(nullptr, cuckoo.Insert(n, n + 100)); for (int i = 0; i < n; i++) { auto *ret = cuckoo.Find(i); CHECK_NOTNULL(ret); EXPECT_EQ(i + 100, ret->second); } } // RandomTest TEST(CuckooMapTest, RandomTest) { typedef uint32_t key_t; typedef uint64_t value_t; const size_t iterations = 10000000; const size_t array_size = 100000; value_t truth[array_size] = {0}; // 0 means empty Random rd; CuckooMap<key_t, value_t> cuckoo; // populate with 50% occupancy for (size_t i = 0; i < array_size / 2; i++) { key_t idx = rd.GetRange(array_size); value_t val = static_cast<value_t>(rd.Get()) + 1; truth[idx] = val; cuckoo.Insert(idx, val); } // check if the initial population succeeded for (size_t i = 0; i < array_size; i++) { auto ret = cuckoo.Find(i); if (truth[i] == 0) { EXPECT_EQ(nullptr, ret); } else { CHECK_NOTNULL(ret); EXPECT_EQ(truth[i], ret->second); } } for (size_t i = 0; i < iterations; i++) { uint32_t odd = rd.GetRange(10); key_t idx = rd.GetRange(array_size); if (odd == 0) { // 10% insert value_t val = static_cast<value_t>(rd.Get()) + 1; auto ret = cuckoo.Insert(idx, val); EXPECT_NE(nullptr, ret); truth[idx] = val; } else if (odd == 1) { // 10% delete bool ret = cuckoo.Remove(idx); EXPECT_EQ(truth[idx] != 0, ret); truth[idx] = 0; } else { // 80% lookup auto ret = cuckoo.Find(idx); if (truth[idx] == 0) { EXPECT_EQ(nullptr, ret); } else { CHECK_NOTNULL(ret); EXPECT_EQ(truth[idx], ret->second); } } } } } // namespace
27.16208
80
0.681491
Lossless-Virtual-Switching
0fc5fb72f3fe232b80609e6d7e9af660a71996e1
5,788
cpp
C++
extension/app/handler.cpp
vvalceanu/mozilla-vpn-client
bd682c5b7b12bb49e1b1c555f1ca973484b8ce5a
[ "MIT" ]
222
2020-11-21T05:55:56.000Z
2022-03-29T16:20:03.000Z
extension/app/handler.cpp
vvalceanu/mozilla-vpn-client
bd682c5b7b12bb49e1b1c555f1ca973484b8ce5a
[ "MIT" ]
1,893
2020-11-16T19:31:50.000Z
2022-03-31T21:51:31.000Z
extension/app/handler.cpp
vvalceanu/mozilla-vpn-client
bd682c5b7b12bb49e1b1c555f1ca973484b8ce5a
[ "MIT" ]
68
2020-11-19T19:08:16.000Z
2022-03-25T20:07:59.000Z
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "handler.h" #include "constants.h" #include "logger.h" #include <iostream> #ifndef MVPN_WINDOWS # include <sys/select.h> #else # include <fcntl.h> # include <io.h> #endif using namespace nlohmann; using namespace std; #ifdef MVPN_WINDOWS static bool setBinaryMode(FILE* file) { if (_setmode(_fileno(file), _O_BINARY) == -1) { Logger::log("Failed to set BINARY mode"); return false; } if (setvbuf(file, NULL, _IONBF, 0) != 0) { Logger::log("Failed to set no-buffering mode"); return false; } return true; } #endif int Handler::run() { #ifdef MVPN_WINDOWS if (!setBinaryMode(stdin)) { Logger::log("Failed to set STDIN in binary mode"); return 1; } if (!setBinaryMode(stdout)) { Logger::log("Failed to set STDOUT in binary mode"); return 1; } #endif while (true) { // Let's see if we need to connect to the VPN client before reading any // message. We don't care about the result of this operation because we can // start reading from STDIN and retry the connection later on. maybeConnect(); bool readStdin = false; bool readVpnConnection = false; #ifdef MVPN_WINDOWS HANDLE handles[3]; handles[0] = GetStdHandle(STD_INPUT_HANDLE); handles[1] = INVALID_HANDLE_VALUE; handles[2] = INVALID_HANDLE_VALUE; int count = 1; if (m_vpnConnection.connected()) { handles[1] = WSACreateEvent(); if (handles[1] == WSA_INVALID_EVENT) { Logger::log("Failed to create a WSA event"); return 1; } if (WSAEventSelect(m_vpnConnection.socket(), handles[1], FD_READ) == SOCKET_ERROR) { Logger::log("Failed to associate the event with the socket"); return 1; } ++count; } // We use the following call only to "wait". WaitForMultipleObjectsEx(count, handles, FALSE, INFINITE, FALSE); readStdin = (WaitForSingleObjectEx(handles[0], 0, FALSE) == WAIT_OBJECT_0); readVpnConnection = (m_vpnConnection.connected() && WaitForSingleObjectEx(handles[1], 0, FALSE) == WAIT_OBJECT_0); #else // POSIX fd_set rfds; int nfds = 0; // the STDIN FD_ZERO(&rfds); FD_SET(0, &rfds); if (m_vpnConnection.connected()) { FD_SET(m_vpnConnection.socket(), &rfds); nfds = m_vpnConnection.socket(); } int rv = select(nfds + 1, &rfds, NULL, NULL, NULL); if (rv == -1) { return 1; } if (!rv) { continue; } readStdin = FD_ISSET(0, &rfds); readVpnConnection = m_vpnConnection.connected() && FD_ISSET(m_vpnConnection.socket(), &rfds); #endif // Something to read from STDIN if (readStdin) { Logger::log("STDIN message received"); json message; if (!readMessage(message)) { return 1; } // This is mainly for testing. if (message == "bridge_ping") { if (!writeMessage("bridge_pong")) { return 1; } continue; } // Maybe we are not connected yet. We need to be connected to send the // message to the VPN client. if (!maybeConnect()) { Logger::log("VPN Client not connected"); if (!writeVpnNotConnected()) { return 1; } continue; } // The VPN can be terminated at any time. Let's treat it as a non-fatal // error. if (!m_vpnConnection.writeMessage(message)) { assert(!m_vpnConnection.connected()); if (!writeVpnNotConnected()) { return 1; } continue; } } // Something to read from the VPN client if (m_vpnConnection.connected() && readVpnConnection) { json message; if (!m_vpnConnection.readMessage(message)) { assert(!m_vpnConnection.connected()); continue; } if (!writeMessage(message)) { return 1; } } } return 0; } bool Handler::maybeConnect() { if (m_vpnConnection.connected()) { return true; } return m_vpnConnection.connect(); } // Retrieve a message from the STDIN. // static bool Handler::readMessage(json& output) { char rawLength[sizeof(uint32_t)]; if (fread(rawLength, sizeof(char), sizeof(uint32_t), stdin) != sizeof(uint32_t)) { Logger::log("Failed to read from STDIN"); return false; } uint32_t length = *reinterpret_cast<uint32_t*>(rawLength); if (!length || length > Constants::MAX_MSG_SIZE) { Logger::log("Failed to read from STDIN"); return false; } char* message = (char*)malloc(length); if (!message) { Logger::log("Failed to allocate the message buffer"); return false; } if (fread(message, sizeof(char), length, stdin) != length) { Logger::log("Failed to read from STDIN"); free(message); return false; } string m(message, message + length); output = json::parse(m); free(message); return true; } // Serialize a message to STDOUT // static bool Handler::writeMessage(const json& body) { string message = body.dump(); uint32_t length = (uint32_t)message.length(); char* rawLength = reinterpret_cast<char*>(&length); if (fwrite(rawLength, sizeof(char), sizeof(uint32_t), stdout) != sizeof(uint32_t)) { Logger::log("Failed to write to STDOUT"); return false; } if (fwrite(message.c_str(), sizeof(char), length, stdout) != length) { Logger::log("Failed to write to STDOUT"); return false; } fflush(stdout); return true; } // static bool Handler::writeVpnNotConnected() { return writeMessage({{"error", "vpn-client-down"}}); }
23.62449
79
0.620767
vvalceanu
0fc6df27917ae4f535ef158327091c558b4b8e56
221
hh
C++
firmware/src/MightyBoard/Motherboard/Compat.hh
46cv8/Sailfish-MightyBoardFirmware
4d8456e54c537dd32775095ed2715d41f5961e6c
[ "AAL" ]
79
2015-01-13T21:00:15.000Z
2022-03-22T14:40:41.000Z
firmware/src/MightyBoard/Motherboard/Compat.hh
46cv8/Sailfish-MightyBoardFirmware
4d8456e54c537dd32775095ed2715d41f5961e6c
[ "AAL" ]
79
2015-04-23T18:25:49.000Z
2021-10-03T14:42:07.000Z
firmware/src/MightyBoard/Motherboard/Compat.hh
46cv8/Sailfish-MightyBoardFirmware
4d8456e54c537dd32775095ed2715d41f5961e6c
[ "AAL" ]
66
2015-01-05T04:05:09.000Z
2022-02-16T17:31:02.000Z
#ifndef __COMPAT_HH__ #define __COMPAT_HH__ #ifndef SIMULATOR #include <avr/version.h> #if __AVR_LIBC_VERSION__ >= 10800UL #define __DELAY_BACKWARD_COMPATIBLE__ 1 #define __PROG_TYPES_COMPAT__ 1 #endif #endif #endif
13.8125
39
0.809955
46cv8
0fc8e8193b6099b0121e2f8b7ff42a03a7569383
10,776
hpp
C++
include/mango/simd/avx512_float128.hpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
3
2021-02-27T10:29:37.000Z
2022-02-16T16:31:26.000Z
include/mango/simd/avx512_float128.hpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
null
null
null
include/mango/simd/avx512_float128.hpp
ufoym/mango
9732fc528f66439f50a3a7cb72d4ba42a59a3d54
[ "Zlib" ]
5
2021-03-22T11:06:00.000Z
2022-02-22T02:53:19.000Z
/* MANGO Multimedia Development Platform Copyright (C) 2012-2021 Twilight Finland 3D Oy Ltd. All rights reserved. */ #pragma once #include <mango/simd/simd.hpp> namespace mango::simd { // ----------------------------------------------------------------- // f32x4 // ----------------------------------------------------------------- // shuffle template <u32 x, u32 y, u32 z, u32 w> static inline f32x4 shuffle(f32x4 a, f32x4 b) { static_assert(x < 4 && y < 4 && z < 4 && w < 4, "Index out of range."); return _mm_shuffle_ps(a, b, _MM_SHUFFLE(w, z, y, x)); } template <u32 x, u32 y, u32 z, u32 w> static inline f32x4 shuffle(f32x4 v) { static_assert(x < 4 && y < 4 && z < 4 && w < 4, "Index out of range."); return _mm_shuffle_ps(v, v, _MM_SHUFFLE(w, z, y, x)); } template <> inline f32x4 shuffle<0, 1, 2, 3>(f32x4 v) { // .xyzw return v; } // indexed access template <unsigned int Index> static inline f32x4 set_component(f32x4 a, f32 s) { static_assert(Index < 4, "Index out of range."); return _mm_insert_ps(a, _mm_set_ss(s), Index * 0x10); } template <int Index> static inline f32 get_component(f32x4 a); template <> inline f32 get_component<0>(f32x4 a) { return _mm_cvtss_f32(a); } template <> inline f32 get_component<1>(f32x4 a) { return _mm_cvtss_f32(shuffle<1, 1, 1, 1>(a)); } template <> inline f32 get_component<2>(f32x4 a) { return _mm_cvtss_f32(shuffle<2, 2, 2, 2>(a)); } template <> inline f32 get_component<3>(f32x4 a) { return _mm_cvtss_f32(shuffle<3, 3, 3, 3>(a)); } static inline f32x4 f32x4_zero() { return _mm_setzero_ps(); } static inline f32x4 f32x4_set(f32 s) { return _mm_set1_ps(s); } static inline f32x4 f32x4_set(f32 x, f32 y, f32 z, f32 w) { return _mm_setr_ps(x, y, z, w); } static inline f32x4 f32x4_uload(const f32* source) { return _mm_loadu_ps(source); } static inline void f32x4_ustore(f32* dest, f32x4 a) { _mm_storeu_ps(dest, a); } static inline f32x4 movelh(f32x4 a, f32x4 b) { return _mm_movelh_ps(a, b); } static inline f32x4 movehl(f32x4 a, f32x4 b) { return _mm_movehl_ps(a, b); } static inline f32x4 unpackhi(f32x4 a, f32x4 b) { return _mm_unpackhi_ps(a, b); } static inline f32x4 unpacklo(f32x4 a, f32x4 b) { return _mm_unpacklo_ps(a, b); } // bitwise static inline f32x4 bitwise_nand(f32x4 a, f32x4 b) { return _mm_andnot_ps(a, b); } static inline f32x4 bitwise_and(f32x4 a, f32x4 b) { return _mm_and_ps(a, b); } static inline f32x4 bitwise_or(f32x4 a, f32x4 b) { return _mm_or_ps(a, b); } static inline f32x4 bitwise_xor(f32x4 a, f32x4 b) { return _mm_xor_ps(a, b); } static inline f32x4 bitwise_not(f32x4 a) { const __m128i s = _mm_castps_si128(a); return _mm_castsi128_ps(_mm_ternarylogic_epi32(s, s, s, 0x01)); } static inline f32x4 min(f32x4 a, f32x4 b) { return _mm_min_ps(a, b); } static inline f32x4 min(f32x4 a, f32x4 b, mask32x4 mask) { return _mm_maskz_min_ps(mask, a, b); } static inline f32x4 min(f32x4 a, f32x4 b, mask32x4 mask, f32x4 value) { return _mm_mask_min_ps(value, mask, a, b); } static inline f32x4 max(f32x4 a, f32x4 b) { return _mm_max_ps(a, b); } static inline f32x4 max(f32x4 a, f32x4 b, mask32x4 mask) { return _mm_maskz_max_ps(mask, a, b); } static inline f32x4 max(f32x4 a, f32x4 b, mask32x4 mask, f32x4 value) { return _mm_mask_max_ps(value, mask, a, b); } static inline f32x4 hmin(f32x4 a) { __m128 temp = _mm_min_ps(a, _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 3, 0, 1))); return _mm_min_ps(temp, _mm_shuffle_ps(temp, temp, _MM_SHUFFLE(1, 0, 3, 2))); } static inline f32x4 hmax(f32x4 a) { __m128 temp = _mm_max_ps(a, _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 3, 0, 1))); return _mm_max_ps(temp, _mm_shuffle_ps(temp, temp, _MM_SHUFFLE(1, 0, 3, 2))); } static inline f32x4 abs(f32x4 a) { return _mm_max_ps(a, _mm_sub_ps(_mm_setzero_ps(), a)); } static inline f32x4 neg(f32x4 a) { return _mm_sub_ps(_mm_setzero_ps(), a); } static inline f32x4 sign(f32x4 a) { __m128 sign_mask = _mm_set1_ps(-0.0f); __m128 value_mask = _mm_cmpneq_ps(a, _mm_setzero_ps()); __m128 sign_bits = _mm_and_ps(a, sign_mask); __m128 value_bits = _mm_and_ps(_mm_set1_ps(1.0f), value_mask); return _mm_or_ps(value_bits, sign_bits); } static inline f32x4 add(f32x4 a, f32x4 b) { return _mm_add_ps(a, b); } static inline f32x4 add(f32x4 a, f32x4 b, mask32x4 mask) { return _mm_maskz_add_ps(mask, a, b); } static inline f32x4 add(f32x4 a, f32x4 b, mask32x4 mask, f32x4 value) { return _mm_mask_add_ps(value, mask, a, b); } static inline f32x4 sub(f32x4 a, f32x4 b) { return _mm_sub_ps(a, b); } static inline f32x4 sub(f32x4 a, f32x4 b, mask32x4 mask) { return _mm_maskz_sub_ps(mask, a, b); } static inline f32x4 sub(f32x4 a, f32x4 b, mask32x4 mask, f32x4 value) { return _mm_mask_sub_ps(value, mask, a, b); } static inline f32x4 mul(f32x4 a, f32x4 b) { return _mm_mul_ps(a, b); } static inline f32x4 mul(f32x4 a, f32x4 b, mask32x4 mask) { return _mm_maskz_mul_ps(mask, a, b); } static inline f32x4 mul(f32x4 a, f32x4 b, mask32x4 mask, f32x4 value) { return _mm_mask_mul_ps(value, mask, a, b); } static inline f32x4 div(f32x4 a, f32x4 b) { return _mm_div_ps(a, b); } static inline f32x4 div(f32x4 a, f32x4 b, mask32x4 mask) { return _mm_maskz_div_ps(mask, a, b); } static inline f32x4 div(f32x4 a, f32x4 b, mask32x4 mask, f32x4 value) { return _mm_mask_div_ps(value, mask, a, b); } static inline f32x4 div(f32x4 a, f32 b) { return _mm_div_ps(a, _mm_set1_ps(b)); } static inline f32x4 hadd(f32x4 a, f32x4 b) { return _mm_hadd_ps(a, b); } static inline f32x4 hsub(f32x4 a, f32x4 b) { return _mm_hsub_ps(a, b); } #if defined(MANGO_ENABLE_FMA3) static inline f32x4 madd(f32x4 a, f32x4 b, f32x4 c) { // a + b * c return _mm_fmadd_ps(b, c, a); } static inline f32x4 msub(f32x4 a, f32x4 b, f32x4 c) { // b * c - a return _mm_fmsub_ps(b, c, a); } static inline f32x4 nmadd(f32x4 a, f32x4 b, f32x4 c) { // a - b * c return _mm_fnmadd_ps(b, c, a); } static inline f32x4 nmsub(f32x4 a, f32x4 b, f32x4 c) { // -(a + b * c) return _mm_fnmsub_ps(b, c, a); } #else static inline f32x4 madd(f32x4 a, f32x4 b, f32x4 c) { return _mm_add_ps(a, _mm_mul_ps(b, c)); } static inline f32x4 msub(f32x4 a, f32x4 b, f32x4 c) { return _mm_sub_ps(_mm_mul_ps(b, c), a); } static inline f32x4 nmadd(f32x4 a, f32x4 b, f32x4 c) { return _mm_sub_ps(a, _mm_mul_ps(b, c)); } static inline f32x4 nmsub(f32x4 a, f32x4 b, f32x4 c) { return _mm_sub_ps(_mm_setzero_ps(), _mm_add_ps(a, _mm_mul_ps(b, c))); } #endif static inline f32x4 lerp(f32x4 a, f32x4 b, f32x4 s) { // a * (1.0 - s) + b * s // (a - a * s) + (b * s) return madd(nmadd(a, a, s), b, s); } #if defined(MANGO_FAST_MATH) static inline f32x4 rcp(f32x4 a) { return _mm_rcp14_ps(a); } static inline f32x4 rsqrt(f32x4 a) { return _mm_maskz_rsqrt14_ps(_mm_cmp_ps_mask(a, a, _CMP_EQ_OQ), a); } #else static inline f32x4 rcp(f32x4 a) { f32x4 n = _mm_rcp_ps(a); f32x4 m = _mm_mul_ps(_mm_mul_ps(n, n), a); return _mm_sub_ps(_mm_add_ps(n, n), m); } static inline f32x4 rsqrt(f32x4 a) { f32x4 n = _mm_rsqrt_ps(a); f32x4 e = _mm_mul_ps(_mm_mul_ps(n, n), a); n = _mm_mul_ps(_mm_set_ps1(0.5f), n); e = _mm_sub_ps(_mm_set_ps1(3.0f), e); return _mm_mul_ps(n, e); } #endif static inline f32x4 sqrt(f32x4 a) { return _mm_sqrt_ps(a); } static inline f32 dot3(f32x4 a, f32x4 b) { f32x4 s = _mm_dp_ps(a, b, 0x7f); return get_component<0>(s); } static inline f32 dot4(f32x4 a, f32x4 b) { f32x4 s = _mm_dp_ps(a, b, 0xff); return get_component<0>(s); } static inline f32x4 cross3(f32x4 a, f32x4 b) { f32x4 c = _mm_sub_ps(_mm_mul_ps(a, shuffle<1, 2, 0, 3>(b)), _mm_mul_ps(b, shuffle<1, 2, 0, 3>(a))); return shuffle<1, 2, 0, 3>(c); } // compare static inline mask32x4 compare_neq(f32x4 a, f32x4 b) { return _mm_cmp_ps_mask(a, b, _CMP_NEQ_UQ); } static inline mask32x4 compare_eq(f32x4 a, f32x4 b) { return _mm_cmp_ps_mask(a, b, _CMP_EQ_OQ); } static inline mask32x4 compare_lt(f32x4 a, f32x4 b) { return _mm_cmp_ps_mask(a, b, _CMP_LT_OS); } static inline mask32x4 compare_le(f32x4 a, f32x4 b) { return _mm_cmp_ps_mask(a, b, _CMP_LE_OS); } static inline mask32x4 compare_gt(f32x4 a, f32x4 b) { return _mm_cmp_ps_mask(b, a, _CMP_LT_OS); } static inline mask32x4 compare_ge(f32x4 a, f32x4 b) { return _mm_cmp_ps_mask(b, a, _CMP_LE_OS); } static inline f32x4 select(mask32x4 mask, f32x4 a, f32x4 b) { return _mm_mask_blend_ps(mask, b, a); } // rounding static inline f32x4 round(f32x4 s) { return _mm_round_ps(s, _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC); } static inline f32x4 trunc(f32x4 s) { //return _mm_roundscale_ps(s, 0x13); return _mm_round_ps(s, _MM_FROUND_TO_ZERO | _MM_FROUND_NO_EXC); } static inline f32x4 floor(f32x4 s) { //return _mm_roundscale_ps(s, 0x11); return _mm_round_ps(s, _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC); } static inline f32x4 ceil(f32x4 s) { //return _mm_roundscale_ps(s, 0x12); return _mm_round_ps(s, _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC); } static inline f32x4 fract(f32x4 s) { return sub(s, floor(s)); } } // namespace mango::simd
23.174194
85
0.577394
ufoym
0fcadda78fd2ffbccebab730c1285236f67058b6
2,328
cc
C++
zircon/system/utest/core/handle-dup/handle-dup.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
zircon/system/utest/core/handle-dup/handle-dup.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2022-03-01T01:12:04.000Z
2022-03-01T01:17:26.000Z
zircon/system/utest/core/handle-dup/handle-dup.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/zx/event.h> #include <zircon/syscalls.h> #include <zircon/syscalls/object.h> #include <fbl/vector.h> #include <zxtest/zxtest.h> namespace { constexpr uint32_t kEventOption = 0u; TEST(HandleDup, ReplaceSuccessOrigInvalid) { zx::event orig_event; ASSERT_OK(zx::event::create(kEventOption, &orig_event)); zx::event replaced_event; ASSERT_OK(orig_event.replace(ZX_RIGHTS_BASIC, &replaced_event)); EXPECT_FALSE(orig_event.is_valid()); EXPECT_TRUE(replaced_event.is_valid()); } TEST(HandleDup, ReplaceFailureBothInvalid) { zx::event orig_event; ASSERT_OK(zx::event::create(kEventOption, &orig_event)); zx::event failed_event; EXPECT_EQ(orig_event.replace(ZX_RIGHT_EXECUTE, &failed_event), ZX_ERR_INVALID_ARGS); // Even on failure, a replaced object is now invalid. EXPECT_FALSE(orig_event.is_valid()); EXPECT_FALSE(failed_event.is_valid()); } // UBSan triggers on nullptrs passed as an argument, but these tests are meant // to test the kernel's handling of an invalid argument, which we want. So we // just disable UBSan for these two tests. #ifdef __clang__ [[clang::no_sanitize("undefined")]] #endif void TestReplace() { // Call handle_replace with an invalid destination slot. This will cause the handle to get // duplicated in the kernel, but then have to get deleted at the point the copy-out happens. zx::event event; ASSERT_OK(zx::event::create(kEventOption, &event)); // This should fail and not cause the kernel to panic. The event handle is invalidated. ASSERT_STATUS(ZX_ERR_INVALID_ARGS, zx_handle_replace(event.release(), 0, nullptr)); } TEST(HandleDup, Replace) { ASSERT_NO_FATAL_FAILURE(TestReplace()); } #ifdef __clang__ [[clang::no_sanitize("undefined")]] #endif void TestDuplicate() { // Same as above, but using the handle_duplicate to cause the dup to happen in the kernel. zx::event event; ASSERT_OK(zx::event::create(kEventOption, &event)); // This should fail and not cause the kernel to panic. ASSERT_STATUS(ZX_ERR_INVALID_ARGS, zx_handle_duplicate(event.get(), 0, nullptr)); } TEST(HandleDup, Duplicate) { ASSERT_NO_FATAL_FAILURE(TestDuplicate()); } } // namespace
32.333333
94
0.753436
allansrc
0fcb0d654cd2ffa142d1cbe73dbeec0d082a43a2
34,154
cpp
C++
iRODS/server/api/src/rsServerReport.cpp
cyverse/irods
4ea33f5f0e220b6e5d257a49b45e10d07ec02d75
[ "BSD-3-Clause" ]
null
null
null
iRODS/server/api/src/rsServerReport.cpp
cyverse/irods
4ea33f5f0e220b6e5d257a49b45e10d07ec02d75
[ "BSD-3-Clause" ]
7
2019-12-02T17:55:49.000Z
2019-12-02T17:55:59.000Z
iRODS/server/api/src/rsServerReport.cpp
benlazarine/irods
83f3c4a6f8f7fc6422a1e73a297b97796a961322
[ "BSD-3-Clause" ]
1
2019-12-02T05:44:10.000Z
2019-12-02T05:44:10.000Z
#include "rsGlobalExtern.hpp" #include "rodsErrorTable.h" #include "miscServerFunct.hpp" #include "reIn2p3SysRule.hpp" #include "irods_lookup_table.hpp" #include "irods_log.hpp" #include "irods_plugin_name_generator.hpp" #include "irods_home_directory.hpp" #include "irods_plugin_home_directory.hpp" #include "irods_resource_manager.hpp" #include "irods_get_full_path_for_config_file.hpp" #include "server_report.h" #include "readServerConfig.hpp" #include "irods_server_properties.hpp" #include "irods_environment_properties.hpp" #include "irods_load_plugin.hpp" #include "jansson.h" #include <fstream> #include <boost/algorithm/string.hpp> #include <boost/filesystem.hpp> #include <boost/lexical_cast.hpp> #include <boost/archive/iterators/base64_from_binary.hpp> #include <boost/archive/iterators/insert_linebreaks.hpp> #include <boost/archive/iterators/transform_width.hpp> #include <boost/archive/iterators/ostream_iterator.hpp> namespace fs = boost::filesystem; #include <sys/utsname.h> int _rsServerReport( rsComm_t* _comm, bytesBuf_t** _bbuf ); int rsServerReport( rsComm_t* _comm, bytesBuf_t** _bbuf ) { // always execute this locally int status = _rsServerReport( _comm, _bbuf ); if ( status < 0 ) { rodsLog( LOG_ERROR, "rsServerReport: rcServerReport failed, status = %d", status ); } return status; } // rsServerReport irods::error make_file_set( const std::string& _files, json_t*& _object ) { if ( _files.empty() ) { return SUCCESS(); } if ( _object ) { return ERROR( SYS_INVALID_INPUT_PARAM, "json object is not null" ); } std::vector<std::string> file_set; boost::split( file_set, _files, boost::is_any_of( "," ) ); _object = json_array(); if ( !_object ) { return ERROR( SYS_MALLOC_ERR, "allocation of json object failed" ); } for ( size_t i = 0; i < file_set.size(); ++i ) { json_t* obj = json_object(); if ( !obj ) { return ERROR( SYS_MALLOC_ERR, "failed to allocate object" ); } json_object_set( obj, "filename", json_string( file_set[ i ].c_str() ) ); json_array_append( _object, obj ); } // for i return SUCCESS(); } // make_file_set irods::error make_federation_set( const std::vector< std::string >& _feds, json_t*& _object ) { if ( _feds.empty() ) { return SUCCESS(); } if ( _object ) { return ERROR( SYS_INVALID_INPUT_PARAM, "json object is not null" ); } _object = json_array(); if ( !_object ) { return ERROR( SYS_MALLOC_ERR, "allocation of json object failed" ); } for ( size_t i = 0; i < _feds.size(); ++i ) { std::vector<std::string> zone_sid_vals; boost::split( zone_sid_vals, _feds[ i ], boost::is_any_of( "-" ) ); if ( zone_sid_vals.size() > 2 ) { rodsLog( LOG_ERROR, "multiple hyphens found in RemoteZoneSID [%s]", _feds[ i ].c_str() ); continue; } json_t* fed_obj = json_object(); json_object_set( fed_obj, "zone_name", json_string( zone_sid_vals[ 0 ].c_str() ) ); json_object_set( fed_obj, "zone_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); json_object_set( fed_obj, "negotiation_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); json_array_append( _object, fed_obj ); } // for i return SUCCESS(); } // make_federation_set irods::error sanitize_server_config_keys( json_t* _svr_cfg ) { if ( !_svr_cfg ) { return ERROR( SYS_INVALID_INPUT_PARAM, "null json object" ); } // sanitize the top level keys json_object_set( _svr_cfg, "zone_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); json_object_set( _svr_cfg, "negotiation_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); json_object_set( _svr_cfg, "server_control_plane_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); // get the federation object json_t* fed_obj = json_object_get( _svr_cfg, "federation" ); if ( !fed_obj ) { return SUCCESS(); } // sanitize all federation keys size_t idx = 0; json_t* obj = 0; json_array_foreach( fed_obj, idx, obj ) { json_object_set( obj, "negotiation_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); json_object_set( obj, "zone_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); } return SUCCESS(); } // sanitize_server_config_keys irods::error convert_server_config( json_t*& _svr_cfg ) { // =-=-=-=-=-=-=- // if json file exists, simply load that std::string svr_cfg; irods::error ret = irods::get_full_path_for_config_file( "server_config.json", svr_cfg ); if ( ret.ok() && fs::exists( svr_cfg ) ) { json_error_t error; _svr_cfg = json_load_file( svr_cfg.c_str(), 0, &error ); if ( !_svr_cfg ) { std::string msg( "failed to load file [" ); msg += svr_cfg; msg += "] json error ["; msg += error.text; msg += "]"; return ERROR( -1, msg ); } else { return sanitize_server_config_keys( _svr_cfg ); } } // =-=-=-=-=-=-=- // otherwise, convert the old properties irods::server_properties& props = irods::server_properties::getInstance(); props.capture_if_needed(); _svr_cfg = json_object(); if ( !_svr_cfg ) { return ERROR( SYS_MALLOC_ERR, "json_object() failed" ); } std::string s_val; ret = props.get_property< std::string >( "icatHost", s_val ); if ( ret.ok() ) { json_object_set( _svr_cfg, "icat_host", json_string( s_val.c_str() ) ); } ret = props.get_property< std::string >( "KerberosName", s_val ); if ( ret.ok() ) { json_object_set( _svr_cfg, "kerberos_name", json_string( s_val.c_str() ) ); } bool b_val = false; ret = props.get_property< bool >( "pam_no_extend", b_val ); if ( ret.ok() ) { if ( b_val ) { json_object_set( _svr_cfg, "pam_no_extend", json_string( "true" ) ); } else { json_object_set( _svr_cfg, "pam_no_extend", json_string( "false" ) ); } } ret = props.get_property< std::string >( "pam_password_min_time", s_val ); if ( ret.ok() ) { int min_time = boost::lexical_cast< int >( s_val ); json_object_set( _svr_cfg, "pam_password_min_time", json_integer( min_time ) ); } ret = props.get_property< std::string >( "pam_password_max_time", s_val ); if ( ret.ok() ) { int max_time = boost::lexical_cast< int >( s_val ); json_object_set( _svr_cfg, "pam_password_max_time", json_integer( max_time ) ); } size_t st_val = 0; ret = props.get_property< size_t>( "pam_password_length", st_val ); if ( ret.ok() ) { json_object_set( _svr_cfg, "pam_password_length", json_integer( st_val ) ); } int i_val = 0; ret = props.get_property< int >( "default_dir_mode", i_val ); if ( ret.ok() ) { std::string mode = boost::lexical_cast< std::string >( i_val ); json_object_set( _svr_cfg, "default_dir_mode", json_string( mode.c_str() ) ); } ret = props.get_property< int >( "default_file_mode", i_val ); if ( ret.ok() ) { std::string mode = boost::lexical_cast< std::string >( i_val ); json_object_set( _svr_cfg, "default_file_mode", json_string( mode.c_str() ) ); } ret = props.get_property< std::string >( "default_hash_scheme", s_val ); if ( ret.ok() ) { json_object_set( _svr_cfg, "default_hash_scheme", json_string( s_val.c_str() ) ); } ret = props.get_property< std::string >( "LocalZoneSID", s_val ); if ( ret.ok() ) { json_object_set( _svr_cfg, "zone_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); } ret = props.get_property< std::string >( "agent_key", s_val ); if ( ret.ok() ) { json_object_set( _svr_cfg, "negotiation_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); } ret = props.get_property< std::string >( "match_hash_policy", s_val ); if ( ret.ok() ) { json_object_set( _svr_cfg, "match_hash_policy", json_string( s_val.c_str() ) ); } else { json_object_set( _svr_cfg, "match_hash_policy", json_string( "" ) ); } ret = props.get_property< std::string >( "reRuleSet", s_val ); if ( ret.ok() ) { json_t* arr = 0; ret = make_file_set( s_val, arr ); if ( ret.ok() ) { json_object_set( _svr_cfg, "re_rulebase_set", arr ); } } ret = props.get_property< std::string >( "reFuncMapSet", s_val ); if ( ret.ok() ) { json_t* arr = 0; ret = make_file_set( s_val, arr ); if ( ret.ok() ) { json_object_set( _svr_cfg, "re_function_name_mapping_set", arr ); } } ret = props.get_property< std::string >( "reVariableMapSet", s_val ); if ( ret.ok() ) { json_t* arr = 0; ret = make_file_set( s_val, arr ); if ( ret.ok() ) { json_object_set( _svr_cfg, "re_data_variable_mapping_set", arr ); } } std::vector< std::string > rem_sids; ret = props.get_property< std::vector< std::string > >( "RemoteZoneSID", rem_sids ); if ( ret.ok() ) { json_t* arr = 0; ret = make_federation_set( rem_sids, arr ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( _svr_cfg, "federation", arr ); } else { // may not be federated, but it is required by the spec json_t* arr = json_array(); json_object_set( _svr_cfg, "federation", arr ); } return SUCCESS(); } // convert_server_config irods::error convert_host_access_control( json_t*& _host_ctrl ) { std::string cfg_file; irods::error ret = irods::get_full_path_for_config_file( HOST_ACCESS_CONTROL_FILE, cfg_file ); if ( !ret.ok() ) { return PASS( ret ); } json_error_t error; _host_ctrl = json_load_file( cfg_file.c_str(), 0, &error ); if ( !_host_ctrl ) { std::string msg( "failed to load file [" ); msg += cfg_file; msg += "] json error ["; msg += error.text; msg += "]"; return ERROR( -1, msg ); } return SUCCESS(); } // convert_host_access_control irods::error convert_irods_host( json_t*& _irods_host ) { std::string cfg_file; irods::error ret = irods::get_full_path_for_config_file( HOST_CONFIG_FILE, cfg_file ); if ( !ret.ok() ) { return PASS( ret ); } json_error_t error; _irods_host = json_load_file( cfg_file.c_str(), 0, &error ); if ( !_irods_host ) { std::string msg( "failed to load file [" ); msg += cfg_file; msg += "] json error ["; msg += error.text; msg += "]"; return ERROR( -1, msg ); } return SUCCESS(); } // convert_irods_host irods::error convert_service_account( json_t*& _svc_acct ) { // =-=-=-=-=-=-=- // if json file exists, simply load that std::string env_file( irods::IRODS_HOME_DIRECTORY ); env_file += irods::environment_properties::JSON_ENV_FILE; if ( fs::exists( env_file ) ) { json_error_t error; _svc_acct = json_load_file( env_file.c_str(), 0, &error ); if ( !_svc_acct ) { std::string msg( "failed to load file [" ); msg += env_file; msg += "] json error ["; msg += error.text; msg += "]"; return ERROR( -1, msg ); } else { // sanitize the keys json_object_set( _svc_acct, "irods_server_control_plane_key", json_string( "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" ) ); return SUCCESS(); } } // =-=-=-=-=-=-=- // otherwise, convert the old properties _svc_acct = json_object(); if ( !_svc_acct ) { return ERROR( SYS_MALLOC_ERR, "json_object() failed" ); } rodsEnv my_env; int status = getRodsEnv( &my_env ); if ( status < 0 ) { return ERROR( status, "failed in getRodsEnv" ); } json_object_set( _svc_acct, "irods_host", json_string( my_env.rodsHost ) ); json_object_set( _svc_acct, "irods_port", json_integer( my_env.rodsPort ) ); json_object_set( _svc_acct, "irods_default_resource", json_string( my_env.rodsDefResource ) ); if ( my_env.rodsServerDn ) { json_object_set( _svc_acct, "irods_server_dn", json_string( my_env.rodsServerDn ) ); } else { json_object_set( _svc_acct, "irods_server_dn", json_string( "" ) ); } json_object_set( _svc_acct, "irods_log_level", json_integer( my_env.rodsPort ) ); json_object_set( _svc_acct, "irods_authentication_file", json_string( my_env.rodsAuthFile ) ); json_object_set( _svc_acct, "irods_debug", json_string( my_env.rodsDebug ) ); json_object_set( _svc_acct, "irods_home", json_string( my_env.rodsHome ) ); json_object_set( _svc_acct, "irods_cwd", json_string( my_env.rodsCwd ) ); json_object_set( _svc_acct, "irods_authentication_scheme", json_string( my_env.rodsAuthScheme ) ); json_object_set( _svc_acct, "irods_user_name", json_string( my_env.rodsUserName ) ); json_object_set( _svc_acct, "irods_zone_name", json_string( my_env.rodsZone ) ); json_object_set( _svc_acct, "irods_client_server_negotiation", json_string( my_env.rodsClientServerNegotiation ) ); json_object_set( _svc_acct, "irods_client_server_policy", json_string( my_env.rodsClientServerPolicy ) ); json_object_set( _svc_acct, "irods_encryption_key_size", json_integer( my_env.rodsEncryptionKeySize ) ); json_object_set( _svc_acct, "irods_encryption_salt_size", json_integer( my_env.rodsEncryptionSaltSize ) ); json_object_set( _svc_acct, "irods_encryption_num_hash_rounds", json_integer( my_env.rodsEncryptionNumHashRounds ) ); json_object_set( _svc_acct, "irods_encryption_algorithm", json_string( my_env.rodsEncryptionAlgorithm ) ); json_object_set( _svc_acct, "irods_default_hash_scheme", json_string( my_env.rodsDefaultHashScheme ) ); json_object_set( _svc_acct, "irods_match_hash_policy", json_string( my_env.rodsMatchHashPolicy ) ); return SUCCESS(); } // convert_service_account irods::error add_plugin_type_to_json_array( const std::string& _plugin_type, const char* _type_name, json_t*& _json_array ) { std::string plugin_home; irods::error ret = irods::resolve_plugin_path( _plugin_type, plugin_home ); if ( !ret.ok() ) { return PASS( ret ); } irods::plugin_name_generator name_gen; irods::plugin_name_generator::plugin_list_t plugin_list; ret = name_gen.list_plugins( plugin_home, plugin_list ); if ( !ret.ok() ) { return PASS( ret ); } for ( irods::plugin_name_generator::plugin_list_t::iterator itr = plugin_list.begin(); itr != plugin_list.end(); ++itr ) { json_t* plug = json_object(); json_object_set( plug, "name", json_string( itr->c_str() ) ); json_object_set( plug, "type", json_string( _type_name ) ); json_object_set( plug, "version", json_string( "" ) ); json_object_set( plug, "checksum_sha256", json_string( "" ) ); json_array_append( _json_array, plug ); } return SUCCESS(); } irods::error get_plugin_array( json_t*& _plugins ) { _plugins = json_array(); if ( !_plugins ) { return ERROR( SYS_MALLOC_ERR, "json_object() failed" ); } irods::error ret = add_plugin_type_to_json_array( irods::PLUGIN_TYPE_RESOURCE, "resource", _plugins ); if ( !ret.ok() ) { return PASS( ret ); } #ifdef RODS_CAT ret = add_plugin_type_to_json_array( irods::PLUGIN_TYPE_DATABASE, "database", _plugins ); if ( !ret.ok() ) { return PASS( ret ); } #endif // RODS_CAT ret = add_plugin_type_to_json_array( irods::PLUGIN_TYPE_AUTHENTICATION, "authentication", _plugins ); if ( !ret.ok() ) { return PASS( ret ); } ret = add_plugin_type_to_json_array( irods::PLUGIN_TYPE_NETWORK, "network", _plugins ); if ( !ret.ok() ) { return PASS( ret ); } ret = add_plugin_type_to_json_array( irods::PLUGIN_TYPE_API, "api", _plugins ); if ( !ret.ok() ) { return PASS( ret ); } ret = add_plugin_type_to_json_array( irods::PLUGIN_TYPE_MICROSERVICE, "microservice", _plugins ); if ( !ret.ok() ) { return PASS( ret ); } return SUCCESS(); } // get_plugin_array irods::error get_uname_string( std::string& _str ) { struct utsname os_name; memset( &os_name, 0, sizeof( os_name ) ); const int status = uname( &os_name ); if ( status != 0 ) { return ERROR( status, "uname failed" ); } _str.clear(); _str += "SYS_NAME=" ; _str += os_name.sysname; _str += ";NODE_NAME="; _str += os_name.nodename; _str += ";RELEASE="; _str += os_name.release; _str += ";VERSION="; _str += os_name.version; _str += ";MACHINE="; _str += os_name.machine; return SUCCESS(); } // get_uname_string irods::error get_host_system_information( json_t*& _host_system_information ) { _host_system_information = json_object(); if ( !_host_system_information ) { return ERROR( SYS_MALLOC_ERR, "json_object() failed" ); } std::string uname_string; irods::error ret = get_uname_string( uname_string ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( _host_system_information, "uname", json_string( uname_string.c_str() ) ); std::vector<std::string> args; args.push_back( "os_distribution_name" ); std::string os_distribution_name; ret = get_script_output_single_line( "python", "system_identification.py", args, os_distribution_name ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( _host_system_information, "os_distribution_name", json_string( os_distribution_name.c_str() ) ); args.clear(); args.push_back( "os_distribution_version" ); std::string os_distribution_version; ret = get_script_output_single_line( "python", "system_identification.py", args, os_distribution_version ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( _host_system_information, "os_distribution_version", json_string( os_distribution_version.c_str() ) ); return SUCCESS(); } // get_host_system_information irods::error get_resource_array( json_t*& _resources ) { _resources = json_array(); if ( !_resources ) { return ERROR( SYS_MALLOC_ERR, "json_array() failed" ); } rodsEnv my_env; int status = getRodsEnv( &my_env ); if ( status < 0 ) { return ERROR( status, "failed in getRodsEnv" ); } const std::string local_host_name = my_env.rodsHost; for ( irods::resource_manager::iterator itr = resc_mgr.begin(); itr != resc_mgr.end(); ++itr ) { irods::resource_ptr resc = itr->second; rodsServerHost_t* tmp_host = 0; irods::error ret = resc->get_property< rodsServerHost_t* >( irods::RESOURCE_HOST, tmp_host ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } if ( !tmp_host ) { rodsLog( LOG_ERROR, "null tmp_host in get_resource_array" ); continue; } if ( LOCAL_HOST != tmp_host->localFlag ) { continue; } std::string host_name; ret = resc->get_property< std::string >( irods::RESOURCE_LOCATION, host_name ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } std::string name; ret = resc->get_property< std::string >( irods::RESOURCE_NAME, name ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } if ( host_name != irods::EMPTY_RESC_HOST && std::string::npos == host_name.find( local_host_name ) && std::string::npos == local_host_name.find( host_name ) ) { rodsLog( LOG_DEBUG, "get_resource_array - skipping non-local resource [%s] on [%s]", name.c_str(), host_name.c_str() ); continue; } std::string type; ret = resc->get_property< std::string >( irods::RESOURCE_TYPE, type ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } std::string vault; ret = resc->get_property< std::string >( irods::RESOURCE_PATH, vault ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } std::string context; ret = resc->get_property< std::string >( irods::RESOURCE_CONTEXT, context ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } std::string parent; ret = resc->get_property< std::string >( irods::RESOURCE_PARENT, parent ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } std::string children; ret = resc->get_property< std::string >( irods::RESOURCE_CHILDREN, children ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } std::string object_count; ret = resc->get_property< std::string >( irods::RESOURCE_OBJCOUNT, object_count ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } long freespace = 0; ret = resc->get_property< long >( irods::RESOURCE_FREESPACE, freespace ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } int status = 0; ret = resc->get_property< int >( irods::RESOURCE_STATUS, status ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } json_t* entry = json_object(); if ( !entry ) { return ERROR( SYS_MALLOC_ERR, "failed to alloc entry" ); } json_object_set( entry, "name", json_string( name.c_str() ) ); json_object_set( entry, "type", json_string( type.c_str() ) ); json_object_set( entry, "host", json_string( host_name.c_str() ) ); json_object_set( entry, "vault_path", json_string( vault.c_str() ) ); json_object_set( entry, "context_string", json_string( context.c_str() ) ); json_object_set( entry, "parent_resource", json_string( parent.c_str() ) ); int count = boost::lexical_cast< int >( object_count ); json_object_set( entry, "object_count", json_integer( count ) ); std::stringstream fs; fs << freespace; json_object_set( entry, "free_space", json_string( fs.str().c_str() ) ); if ( status != INT_RESC_STATUS_DOWN ) { json_object_set( entry, "status", json_string( "up" ) ); } else { json_object_set( entry, "status", json_string( "down" ) ); } json_array_append( _resources, entry ); } // for itr return SUCCESS(); } // get_resource_array irods::error get_file_contents( const std::string& _fn, std::string& _cont ) { std::ifstream f( _fn.c_str() ); std::stringstream ss; ss << f.rdbuf(); f.close(); std::string in_s = ss.str(); namespace bitr = boost::archive::iterators; std::stringstream o_str; typedef bitr::base64_from_binary < // convert binary values to base64 characters bitr::transform_width < // retrieve 6 bit integers from a sequence of 8 bit bytes const char *, 6, 8 > > base64_text; // compose all the above operations in to a new iterator std::copy( base64_text( in_s.c_str() ), base64_text( in_s.c_str() + in_s.size() ), bitr::ostream_iterator<char>( o_str ) ); _cont = o_str.str(); size_t pad = in_s.size() % 3; _cont.insert( _cont.size(), ( 3 - pad ) % 3, '=' ); return SUCCESS(); } // get_file_contents irods::error get_config_dir( json_t*& _cfg_dir ) { namespace fs = boost::filesystem; _cfg_dir = json_object(); if ( !_cfg_dir ) { return ERROR( SYS_MALLOC_ERR, "json_object() failed" ); } json_t* file_arr = json_array(); if ( !file_arr ) { return ERROR( SYS_MALLOC_ERR, "json_array() failed" ); } std::string cfg_file; irods::error ret = irods::get_full_path_for_config_file( SERVER_CONFIG_FILE, cfg_file ); if ( !ret.ok() ) { irods::error ret = irods::get_full_path_for_config_file( LEGACY_SERVER_CONFIG_FILE, cfg_file ); if ( !ret.ok() ) { return PASS( ret ); } } fs::path p( cfg_file ); std::string config_dir = p.parent_path().string(); json_object_set( _cfg_dir, "path", json_string( config_dir.c_str() ) ); for ( fs::directory_iterator itr( config_dir ); itr != fs::directory_iterator(); ++itr ) { if ( fs::is_regular_file( itr->path() ) ) { const fs::path& p = itr->path(); const std::string& name = p.string(); if ( std::string::npos != name.find( SERVER_CONFIG_FILE ) || std::string::npos != name.find( LEGACY_SERVER_CONFIG_FILE ) || std::string::npos != name.find( HOST_CONFIG_FILE ) || std::string::npos != name.find( HOST_ACCESS_CONTROL_FILE ) || std::string::npos != name.find( "irods.config" ) ) { continue; } json_t* f_obj = json_object(); if ( !f_obj ) { return ERROR( SYS_MALLOC_ERR, "failed to allocate f_obj" ); } json_object_set( f_obj, "name", json_string( name.c_str() ) ); std::string contents; ret = get_file_contents( name, contents ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); continue; } json_object_set( f_obj, "contents", json_string( contents.c_str() ) ); json_array_append( file_arr, f_obj ); } } // for itr json_object_set( _cfg_dir, "files", file_arr ); return SUCCESS(); } // get_config_dir irods::error load_version_file( json_t*& _version ) { // =-=-=-=-=-=-=- // if json file exists, simply load that std::string version_file( irods::IRODS_HOME_DIRECTORY ); version_file += "VERSION.json"; if ( fs::exists( version_file ) ) { json_error_t error; _version = json_load_file( version_file.c_str(), 0, &error ); if ( !_version ) { std::string msg( "failed to load file [" ); msg += version_file; msg += "] json error ["; msg += error.text; msg += "]"; return ERROR( -1, msg ); } else { return SUCCESS(); } } return SUCCESS(); } // load_version_file #ifdef RODS_CAT irods::error get_database_config( json_t*& _db_cfg ) { // =-=-=-=-=-=-=- // if json file exists, simply load that std::string db_cfg; irods::error ret = irods::get_full_path_for_config_file( "database_config.json", db_cfg ); if ( ret.ok() && fs::exists( db_cfg ) ) { json_error_t error; _db_cfg = json_load_file( db_cfg.c_str(), 0, &error ); if ( !_db_cfg ) { std::string msg( "failed to load file [" ); msg += db_cfg; msg += "] json error ["; msg += error.text; msg += "]"; return ERROR( -1, msg ); } else { // sanitize passwords json_object_set( _db_cfg, "db_password", json_string( "XXXXX" ) ); return SUCCESS(); } } irods::server_properties& props = irods::server_properties::getInstance(); props.capture_if_needed(); _db_cfg = json_object(); if ( !_db_cfg ) { return ERROR( SYS_MALLOC_ERR, "allocation of json_object failed" ); } std::string s_val; ret = props.get_property< std::string >( "catalog_database_type", s_val ); if ( ret.ok() ) { json_object_set( _db_cfg, "catalog_database_type", json_string( s_val.c_str() ) ); } ret = props.get_property< std::string >( "DBUsername", s_val ); if ( ret.ok() ) { json_object_set( _db_cfg, "db_username", json_string( s_val.c_str() ) ); } json_object_set( _db_cfg, "db_password", json_string( "XXXXX" ) ); return SUCCESS(); } // get_database_config #endif int _rsServerReport( rsComm_t* _comm, bytesBuf_t** _bbuf ) { if ( !_comm || !_bbuf ) { rodsLog( LOG_ERROR, "_rsServerReport: null comm or bbuf" ); return SYS_INVALID_INPUT_PARAM; } ( *_bbuf ) = ( bytesBuf_t* ) malloc( sizeof( **_bbuf ) ); if ( !( *_bbuf ) ) { rodsLog( LOG_ERROR, "_rsServerReport: failed to allocate _bbuf" ); return SYS_MALLOC_ERR; } json_t* resc_svr = json_object(); if ( !resc_svr ) { rodsLog( LOG_ERROR, "_rsServerReport: failed to allocate resc_svr" ); return SYS_MALLOC_ERR; } json_t* version = 0; irods::error ret = load_version_file( version ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "version", version ); json_t* host_system_information = 0; ret = get_host_system_information( host_system_information ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "host_system_information", host_system_information ); json_t* svr_cfg = 0; ret = convert_server_config( svr_cfg ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "server_config", svr_cfg ); json_t* host_ctrl = 0; ret = convert_host_access_control( host_ctrl ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "host_access_control_config", host_ctrl ); json_t* irods_host = 0; ret = convert_irods_host( irods_host ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "hosts_config", irods_host ); json_t* svc_acct = 0; ret = convert_service_account( svc_acct ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "service_account_environment", svc_acct ); json_t* plugins = 0; ret = get_plugin_array( plugins ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "plugins", plugins ); json_t* resources = 0; ret = get_resource_array( resources ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "resources", resources ); json_t* cfg_dir = 0; ret = get_config_dir( cfg_dir ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "configuration_directory", cfg_dir ); #ifdef RODS_CAT json_t* db_cfg = 0; ret = get_database_config( db_cfg ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } json_object_set( resc_svr, "database_config", db_cfg ); #endif char* tmp_buf = json_dumps( resc_svr, JSON_INDENT( 4 ) ); // *SHOULD* free All The Things... json_decref( resc_svr ); ( *_bbuf )->buf = tmp_buf; ( *_bbuf )->len = strlen( tmp_buf ); return 0; } // _rsServerReport
28.580753
123
0.555367
cyverse
0fcbcbedfe04f771ca8d82785d69dfdf334805ca
6,091
cpp
C++
tools/clang/lib/ARCMigrate/TransProtectedScope.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
1,192
2017-01-23T23:27:01.000Z
2019-05-05T14:08:40.000Z
tools/clang/lib/ARCMigrate/TransProtectedScope.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
2,214
2019-05-06T22:22:53.000Z
2022-03-31T19:38:50.000Z
tools/clang/lib/ARCMigrate/TransProtectedScope.cpp
clayne/DirectXShaderCompiler
0ef9b702890b1d45f0bec5fa75481290323e14dc
[ "NCSA" ]
269
2019-05-07T11:59:04.000Z
2022-03-30T08:41:50.000Z
//===--- TransProtectedScope.cpp - Transformations to ARC mode ------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Adds brackets in case statements that "contain" initialization of retaining // variable, thus emitting the "switch case is in protected scope" error. // //===----------------------------------------------------------------------===// #include "Transforms.h" #include "Internals.h" #include "clang/AST/ASTContext.h" #include "clang/Sema/SemaDiagnostic.h" using namespace clang; using namespace arcmt; using namespace trans; namespace { class LocalRefsCollector : public RecursiveASTVisitor<LocalRefsCollector> { SmallVectorImpl<DeclRefExpr *> &Refs; public: LocalRefsCollector(SmallVectorImpl<DeclRefExpr *> &refs) : Refs(refs) { } bool VisitDeclRefExpr(DeclRefExpr *E) { if (ValueDecl *D = E->getDecl()) if (D->getDeclContext()->getRedeclContext()->isFunctionOrMethod()) Refs.push_back(E); return true; } }; struct CaseInfo { SwitchCase *SC; SourceRange Range; enum { St_Unchecked, St_CannotFix, St_Fixed } State; CaseInfo() : SC(nullptr), State(St_Unchecked) {} CaseInfo(SwitchCase *S, SourceRange Range) : SC(S), Range(Range), State(St_Unchecked) {} }; class CaseCollector : public RecursiveASTVisitor<CaseCollector> { ParentMap &PMap; SmallVectorImpl<CaseInfo> &Cases; public: CaseCollector(ParentMap &PMap, SmallVectorImpl<CaseInfo> &Cases) : PMap(PMap), Cases(Cases) { } bool VisitSwitchStmt(SwitchStmt *S) { SwitchCase *Curr = S->getSwitchCaseList(); if (!Curr) return true; Stmt *Parent = getCaseParent(Curr); Curr = Curr->getNextSwitchCase(); // Make sure all case statements are in the same scope. while (Curr) { if (getCaseParent(Curr) != Parent) return true; Curr = Curr->getNextSwitchCase(); } SourceLocation NextLoc = S->getLocEnd(); Curr = S->getSwitchCaseList(); // We iterate over case statements in reverse source-order. while (Curr) { Cases.push_back(CaseInfo(Curr,SourceRange(Curr->getLocStart(), NextLoc))); NextLoc = Curr->getLocStart(); Curr = Curr->getNextSwitchCase(); } return true; } Stmt *getCaseParent(SwitchCase *S) { Stmt *Parent = PMap.getParent(S); while (Parent && (isa<SwitchCase>(Parent) || isa<LabelStmt>(Parent))) Parent = PMap.getParent(Parent); return Parent; } }; class ProtectedScopeFixer { MigrationPass &Pass; SourceManager &SM; SmallVector<CaseInfo, 16> Cases; SmallVector<DeclRefExpr *, 16> LocalRefs; public: ProtectedScopeFixer(BodyContext &BodyCtx) : Pass(BodyCtx.getMigrationContext().Pass), SM(Pass.Ctx.getSourceManager()) { CaseCollector(BodyCtx.getParentMap(), Cases) .TraverseStmt(BodyCtx.getTopStmt()); LocalRefsCollector(LocalRefs).TraverseStmt(BodyCtx.getTopStmt()); SourceRange BodyRange = BodyCtx.getTopStmt()->getSourceRange(); const CapturedDiagList &DiagList = Pass.getDiags(); // Copy the diagnostics so we don't have to worry about invaliding iterators // from the diagnostic list. SmallVector<StoredDiagnostic, 16> StoredDiags; StoredDiags.append(DiagList.begin(), DiagList.end()); SmallVectorImpl<StoredDiagnostic>::iterator I = StoredDiags.begin(), E = StoredDiags.end(); while (I != E) { if (I->getID() == diag::err_switch_into_protected_scope && isInRange(I->getLocation(), BodyRange)) { handleProtectedScopeError(I, E); continue; } ++I; } } void handleProtectedScopeError( SmallVectorImpl<StoredDiagnostic>::iterator &DiagI, SmallVectorImpl<StoredDiagnostic>::iterator DiagE){ Transaction Trans(Pass.TA); assert(DiagI->getID() == diag::err_switch_into_protected_scope); SourceLocation ErrLoc = DiagI->getLocation(); bool handledAllNotes = true; ++DiagI; for (; DiagI != DiagE && DiagI->getLevel() == DiagnosticsEngine::Note; ++DiagI) { if (!handleProtectedNote(*DiagI)) handledAllNotes = false; } if (handledAllNotes) Pass.TA.clearDiagnostic(diag::err_switch_into_protected_scope, ErrLoc); } bool handleProtectedNote(const StoredDiagnostic &Diag) { assert(Diag.getLevel() == DiagnosticsEngine::Note); for (unsigned i = 0; i != Cases.size(); i++) { CaseInfo &info = Cases[i]; if (isInRange(Diag.getLocation(), info.Range)) { if (info.State == CaseInfo::St_Unchecked) tryFixing(info); assert(info.State != CaseInfo::St_Unchecked); if (info.State == CaseInfo::St_Fixed) { Pass.TA.clearDiagnostic(Diag.getID(), Diag.getLocation()); return true; } return false; } } return false; } void tryFixing(CaseInfo &info) { assert(info.State == CaseInfo::St_Unchecked); if (hasVarReferencedOutside(info)) { info.State = CaseInfo::St_CannotFix; return; } Pass.TA.insertAfterToken(info.SC->getColonLoc(), " {"); Pass.TA.insert(info.Range.getEnd(), "}\n"); info.State = CaseInfo::St_Fixed; } bool hasVarReferencedOutside(CaseInfo &info) { for (unsigned i = 0, e = LocalRefs.size(); i != e; ++i) { DeclRefExpr *DRE = LocalRefs[i]; if (isInRange(DRE->getDecl()->getLocation(), info.Range) && !isInRange(DRE->getLocation(), info.Range)) return true; } return false; } bool isInRange(SourceLocation Loc, SourceRange R) { if (Loc.isInvalid()) return false; return !SM.isBeforeInTranslationUnit(Loc, R.getBegin()) && SM.isBeforeInTranslationUnit(Loc, R.getEnd()); } }; } // anonymous namespace void ProtectedScopeTraverser::traverseBody(BodyContext &BodyCtx) { ProtectedScopeFixer Fix(BodyCtx); }
30.004926
80
0.640617
clayne
0fcd8dbef9f0d095c79da808e706a6a1ededd8a1
989
cxx
C++
pandatool/src/xfile/xFileParseData.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
pandatool/src/xfile/xFileParseData.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
pandatool/src/xfile/xFileParseData.cxx
cmarshall108/panda3d-python3
8bea2c0c120b03ec1c9fd179701fdeb7510bb97b
[ "PHP-3.0", "PHP-3.01" ]
null
null
null
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file xFileParseData.cxx * @author drose * @date 2004-10-07 */ #include "xFileParseData.h" #include "xLexerDefs.h" /** * */ XFileParseData:: XFileParseData() : _parse_flags(0) { // Save the line number, column number, and line text in case we detect an // error later and want to report a meaningful message to the user. _line_number = x_line_number; _col_number = x_col_number; _current_line = x_current_line; } /** * Reports a parsing error message to the user, showing the line and column * from which this object was originally parsed. */ void XFileParseData:: yyerror(const std::string &message) const { xyyerror(message, _line_number, _col_number, _current_line); }
24.725
76
0.722952
cmarshall108
0fceac63b54e5119d25099ae36b7ea7bb0b325e2
11,450
cxx
C++
main/vcl/workben/svptest.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/vcl/workben/svptest.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/vcl/workben/svptest.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. * *************************************************************/ #include <sal/main.h> #include <tools/extendapplicationenvironment.hxx> #include <com/sun/star/lang/XMultiServiceFactory.hpp> #include <vcl/event.hxx> #include <vcl/svapp.hxx> #include <vcl/wrkwin.hxx> #include <vcl/gradient.hxx> #include <vcl/lineinfo.hxx> #include <vcl/bitmap.hxx> #include <vcl/bmpacc.hxx> #include <vcl/metric.hxx> #include <rtl/ustrbuf.hxx> #include <math.h> #include <comphelper/processfactory.hxx> #include <cppuhelper/servicefactory.hxx> #include <cppuhelper/bootstrap.hxx> using namespace rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; // ----------------------------------------------------------------------- // Forward declaration void Main(); // ----------------------------------------------------------------------- SAL_IMPLEMENT_MAIN() { tools::extendApplicationEnvironment(); Reference< XMultiServiceFactory > xMS; xMS = cppu::createRegistryServiceFactory( rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "types.rdb" ) ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "applicat.rdb" ) ), sal_True ); InitVCL( xMS ); ::Main(); DeInitVCL(); return 0; } // ----------------------------------------------------------------------- class MyWin : public WorkWindow { Bitmap m_aBitmap; public: MyWin( Window* pParent, WinBits nWinStyle ); void MouseMove( const MouseEvent& rMEvt ); void MouseButtonDown( const MouseEvent& rMEvt ); void MouseButtonUp( const MouseEvent& rMEvt ); void KeyInput( const KeyEvent& rKEvt ); void KeyUp( const KeyEvent& rKEvt ); void Paint( const Rectangle& rRect ); void Resize(); }; // ----------------------------------------------------------------------- void Main() { MyWin aMainWin( NULL, WB_APP | WB_STDWORK ); aMainWin.SetText( XubString( RTL_CONSTASCII_USTRINGPARAM( "VCL - Workbench" ) ) ); aMainWin.Show(); Application::Execute(); } // ----------------------------------------------------------------------- MyWin::MyWin( Window* pParent, WinBits nWinStyle ) : WorkWindow( pParent, nWinStyle ), m_aBitmap( Size( 256, 256 ), 32 ) { // prepare an alpha mask BitmapWriteAccess* pAcc = m_aBitmap.AcquireWriteAccess(); for( int nX = 0; nX < 256; nX++ ) { for( int nY = 0; nY < 256; nY++ ) { double fRed = 255.0-1.5*sqrt((double)(nX*nX+nY*nY)); if( fRed < 0.0 ) fRed = 0.0; double fGreen = 255.0-1.5*sqrt((double)(((255-nX)*(255-nX)+nY*nY))); if( fGreen < 0.0 ) fGreen = 0.0; double fBlue = 255.0-1.5*sqrt((double)((128-nX)*(128-nX)+(255-nY)*(255-nY))); if( fBlue < 0.0 ) fBlue = 0.0; pAcc->SetPixel( nX, nY, BitmapColor( sal_uInt8(fRed), sal_uInt8(fGreen), sal_uInt8(fBlue) ) ); } } m_aBitmap.ReleaseAccess( pAcc ); } // ----------------------------------------------------------------------- void MyWin::MouseMove( const MouseEvent& rMEvt ) { WorkWindow::MouseMove( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::MouseButtonDown( const MouseEvent& rMEvt ) { WorkWindow::MouseButtonDown( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::MouseButtonUp( const MouseEvent& rMEvt ) { WorkWindow::MouseButtonUp( rMEvt ); } // ----------------------------------------------------------------------- void MyWin::KeyInput( const KeyEvent& rKEvt ) { WorkWindow::KeyInput( rKEvt ); } // ----------------------------------------------------------------------- void MyWin::KeyUp( const KeyEvent& rKEvt ) { WorkWindow::KeyUp( rKEvt ); } // ----------------------------------------------------------------------- static Point project( const Point& rPoint ) { const double angle_x = M_PI / 6.0; const double angle_z = M_PI / 6.0; // transform planar coordinates to 3d double x = rPoint.X(); double y = rPoint.Y(); //double z = 0; // rotate around X axis double x1 = x; double y1 = y * cos( angle_x ); double z1 = y * sin( angle_x ); // rotate around Z axis double x2 = x1 * cos( angle_z ) + y1 * sin( angle_z ); //double y2 = y1 * cos( angle_z ) - x1 * sin( angle_z ); double z2 = z1; return Point( (sal_Int32)x2, (sal_Int32)z2 ); } static Color approachColor( const Color& rFrom, const Color& rTo ) { Color aColor; sal_uInt8 nDiff; // approach red if( rFrom.GetRed() < rTo.GetRed() ) { nDiff = rTo.GetRed() - rFrom.GetRed(); aColor.SetRed( rFrom.GetRed() + ( nDiff < 10 ? nDiff : 10 ) ); } else if( rFrom.GetRed() > rTo.GetRed() ) { nDiff = rFrom.GetRed() - rTo.GetRed(); aColor.SetRed( rFrom.GetRed() - ( nDiff < 10 ? nDiff : 10 ) ); } else aColor.SetRed( rFrom.GetRed() ); // approach Green if( rFrom.GetGreen() < rTo.GetGreen() ) { nDiff = rTo.GetGreen() - rFrom.GetGreen(); aColor.SetGreen( rFrom.GetGreen() + ( nDiff < 10 ? nDiff : 10 ) ); } else if( rFrom.GetGreen() > rTo.GetGreen() ) { nDiff = rFrom.GetGreen() - rTo.GetGreen(); aColor.SetGreen( rFrom.GetGreen() - ( nDiff < 10 ? nDiff : 10 ) ); } else aColor.SetGreen( rFrom.GetGreen() ); // approach blue if( rFrom.GetBlue() < rTo.GetBlue() ) { nDiff = rTo.GetBlue() - rFrom.GetBlue(); aColor.SetBlue( rFrom.GetBlue() + ( nDiff < 10 ? nDiff : 10 ) ); } else if( rFrom.GetBlue() > rTo.GetBlue() ) { nDiff = rFrom.GetBlue() - rTo.GetBlue(); aColor.SetBlue( rFrom.GetBlue() - ( nDiff < 10 ? nDiff : 10 ) ); } else aColor.SetBlue( rFrom.GetBlue() ); return aColor; } #define DELTA 5.0 void MyWin::Paint( const Rectangle& rRect ) { WorkWindow::Paint( rRect ); Push( PUSH_ALL ); MapMode aMapMode( MAP_100TH_MM ); SetMapMode( aMapMode ); Size aPaperSize = GetOutputSize(); Point aCenter( aPaperSize.Width()/2-300, (aPaperSize.Height() - 8400)/2 + 8400 ); Point aP1( aPaperSize.Width()/48, 0), aP2( aPaperSize.Width()/40, 0 ), aPoint; DrawRect( Rectangle( Point( 0,0 ), aPaperSize ) ); DrawRect( Rectangle( Point( 100,100 ), Size( aPaperSize.Width()-200, aPaperSize.Height()-200 ) ) ); DrawRect( Rectangle( Point( 200,200 ), Size( aPaperSize.Width()-400, aPaperSize.Height()-400 ) ) ); DrawRect( Rectangle( Point( 300,300 ), Size( aPaperSize.Width()-600, aPaperSize.Height()-600 ) ) ); // AllSettings aSettings( Application::GetSettings() ); const int nFontCount = GetDevFontCount(); const int nFontSamples = (nFontCount<15) ? nFontCount : 15; for( int i = 0; i < nFontSamples; ++i ) { #if 0 Font aFont( GetFont() ); aFont.SetName( String( RTL_CONSTASCII_USTRINGPARAM( "Courier" ) ) ); aFont.SetWeight( WEIGHT_NORMAL ); aFont.SetItalic( ITALIC_NONE ); #else FontInfo aFont = GetDevFont( (i*nFontCount) / nFontSamples ); aFont.SetHeight( 400 + (i%7) * 100 ); aFont.SetOrientation( i * (3600 / nFontSamples) ); #endif SetFont( aFont ); sal_uInt8 nRed = (i << 6) & 0xC0; sal_uInt8 nGreen = (i << 4) & 0xC0; sal_uInt8 nBlue = (i << 2) & 0xC0; SetTextColor( Color( nRed, nGreen, nBlue ) ); OUStringBuffer aPrintText(1024); long nMaxWidth = 0; aPrintText.appendAscii( "SVP test program" ); DrawText( Rectangle( Point( (aPaperSize.Width() - 4000) / 2, 2000 ), Size( aPaperSize.Width() - 2100 - nMaxWidth, aPaperSize.Height() - 4000 ) ), aPrintText.makeStringAndClear(), TEXT_DRAW_MULTILINE ); } SetFillColor(); DrawRect( Rectangle( Point( aPaperSize.Width() - 4000, 1000 ), Size( 3000,3000 ) ) ); DrawBitmap( Point( aPaperSize.Width() - 4000, 1000 ), Size( 3000,3000 ), m_aBitmap ); Color aWhite( 0xff, 0xff, 0xff ); Color aBlack( 0, 0, 0 ); Color aLightRed( 0xff, 0, 0 ); Color aDarkRed( 0x40, 0, 0 ); Color aLightBlue( 0, 0, 0xff ); Color aDarkBlue( 0,0,0x40 ); Color aLightGreen( 0, 0xff, 0 ); Color aDarkGreen( 0, 0x40, 0 ); Gradient aGradient( GRADIENT_LINEAR, aBlack, aWhite ); aGradient.SetAngle( 900 ); DrawGradient( Rectangle( Point( 1000, 4500 ), Size( aPaperSize.Width() - 2000, 500 ) ), aGradient ); aGradient.SetStartColor( aDarkRed ); aGradient.SetEndColor( aLightBlue ); DrawGradient( Rectangle( Point( 1000, 5300 ), Size( aPaperSize.Width() - 2000, 500 ) ), aGradient ); aGradient.SetStartColor( aDarkBlue ); aGradient.SetEndColor( aLightGreen ); DrawGradient( Rectangle( Point( 1000, 6100 ), Size( aPaperSize.Width() - 2000, 500 ) ), aGradient ); aGradient.SetStartColor( aDarkGreen ); aGradient.SetEndColor( aLightRed ); DrawGradient( Rectangle( Point( 1000, 6900 ), Size( aPaperSize.Width() - 2000, 500 ) ), aGradient ); LineInfo aLineInfo( LINE_SOLID, 200 ); double sind = sin( DELTA*M_PI/180.0 ); double cosd = cos( DELTA*M_PI/180.0 ); double factor = 1 + (DELTA/1000.0); int n=0; Color aLineColor( 0, 0, 0 ); Color aApproachColor( 0, 0, 200 ); while ( aP2.X() < aCenter.X() && n++ < 680 ) { aLineInfo.SetWidth( n/3 ); aLineColor = approachColor( aLineColor, aApproachColor ); SetLineColor( aLineColor ); // switch aproach color if( aApproachColor.IsRGBEqual( aLineColor ) ) { if( aApproachColor.GetRed() ) aApproachColor = Color( 0, 0, 200 ); else if( aApproachColor.GetGreen() ) aApproachColor = Color( 200, 0, 0 ); else aApproachColor = Color( 0, 200, 0 ); } DrawLine( project( aP1 ) + aCenter, project( aP2 ) + aCenter, aLineInfo ); aPoint.X() = (int)((((double)aP1.X())*cosd - ((double)aP1.Y())*sind)*factor); aPoint.Y() = (int)((((double)aP1.Y())*cosd + ((double)aP1.X())*sind)*factor); aP1 = aPoint; aPoint.X() = (int)((((double)aP2.X())*cosd - ((double)aP2.Y())*sind)*factor); aPoint.Y() = (int)((((double)aP2.Y())*cosd + ((double)aP2.X())*sind)*factor); aP2 = aPoint; } Pop(); } // ----------------------------------------------------------------------- void MyWin::Resize() { WorkWindow::Resize(); }
30.452128
182
0.555459
Grosskopf
0fd162b1d401dc6b0bc04884786a5a17eed4b3e0
10,578
cpp
C++
plugins/render/ogreRender/3rdParty/ogre/Dependencies/src/FreeImage/Source/FreeImage/PluginSGI.cpp
wterkaj/ApertusVR
424ec5515ae08780542f33cc4841a8f9a96337b3
[ "MIT" ]
158
2016-11-17T19:37:51.000Z
2022-03-21T19:57:55.000Z
plugins/render/ogreRender/3rdParty/ogre/Dependencies/src/FreeImage/Source/FreeImage/PluginSGI.cpp
wterkaj/ApertusVR
424ec5515ae08780542f33cc4841a8f9a96337b3
[ "MIT" ]
94
2016-11-18T09:55:57.000Z
2021-01-14T08:50:40.000Z
plugins/render/ogreRender/3rdParty/ogre/Dependencies/src/FreeImage/Source/FreeImage/PluginSGI.cpp
wterkaj/ApertusVR
424ec5515ae08780542f33cc4841a8f9a96337b3
[ "MIT" ]
51
2017-05-24T10:20:25.000Z
2022-03-17T15:07:02.000Z
// ========================================================== // SGI Loader // // Design and implementation by // - Sherman Wilcox // - Noam Gat // // References : // ------------ // - The SGI Image File Format, Version 1.0 // http://astronomy.swin.edu.au/~pbourke/dataformats/sgirgb/sgiversion.html // - SGI RGB Image Format // http://astronomy.swin.edu.au/~pbourke/dataformats/sgirgb/ // // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== #include "FreeImage.h" #include "Utilities.h" // ---------------------------------------------------------- // Constants + headers // ---------------------------------------------------------- #ifdef _WIN32 #pragma pack(push, 1) #else #pragma pack(1) #endif typedef struct tagSGIHeader { /** IRIS image file magic number. This should be decimal 474. */ WORD magic; /** Storage format: 0 for uncompressed, 1 for RLE compression. */ BYTE storage; /** Number of bytes per pixel channel. Legally 1 or 2. */ BYTE bpc; /** Number of dimensions. Legally 1, 2, or 3. 1 means a single row, XSIZE long 2 means a single 2D image 3 means multiple 2D images */ WORD dimension; /** X size in pixels */ WORD xsize; /** Y size in pixels */ WORD ysize; /** Number of channels. 1 indicates greyscale 3 indicates RGB 4 indicates RGB and Alpha */ WORD zsize; /** Minimum pixel value. This is the lowest pixel value in the image.*/ LONG pixmin; /** Maximum pixel value. This is the highest pixel value in the image.*/ LONG pixmax; /** Ignored. Normally set to 0. */ char dummy[4]; /** Image name. Must be null terminated, therefore at most 79 bytes. */ char imagename[80]; /** Colormap ID. 0 - normal mode 1 - dithered, 3 mits for red and green, 2 for blue, obsolete 2 - index colour, obsolete 3 - not an image but a colourmap */ LONG colormap; /** Ignored. Should be set to 0, makes the header 512 bytes. */ char reserved[404]; } SGIHeader; typedef struct tagRLEStatus { int cnt; int val; } RLEStatus; #ifdef _WIN32 #pragma pack(pop) #else #pragma pack() #endif static const char *SGI_LESS_THAN_HEADER_LENGTH = "Incorrect header size"; static const char *SGI_16_BIT_COMPONENTS_NOT_SUPPORTED = "No 16 bit support"; static const char *SGI_COLORMAPS_NOT_SUPPORTED = "No colormap support"; static const char *SGI_EOF_IN_RLE_INDEX = "EOF in run length encoding"; static const char *SGI_EOF_IN_IMAGE_DATA = "EOF in image data"; static const char *SGI_INVALID_CHANNEL_COUNT = "Invalid channel count"; // ========================================================== // Plugin Interface // ========================================================== static int s_format_id; // ========================================================== // Plugin Implementation // ========================================================== #ifndef FREEIMAGE_BIGENDIAN static void SwapHeader(SGIHeader *header) { SwapShort(&header->magic); SwapShort(&header->dimension); SwapShort(&header->xsize); SwapShort(&header->ysize); SwapShort(&header->zsize); SwapLong((DWORD*)&header->pixmin); SwapLong((DWORD*)&header->pixmax); SwapLong((DWORD*)&header->colormap); } #endif static int get_rlechar(FreeImageIO *io, fi_handle handle, RLEStatus *pstatus) { if (!pstatus->cnt) { int cnt = 0; while (0 == cnt) { BYTE packed = 0; if(io->read_proc(&packed, sizeof(BYTE), 1, handle) < 1) { return EOF; } cnt = packed; } if (cnt == EOF) { return EOF; } pstatus->cnt = cnt & 0x7F; if (cnt & 0x80) { pstatus->val = -1; } else { BYTE packed = 0; if(io->read_proc(&packed, sizeof(BYTE), 1, handle) < 1) { return EOF; } pstatus->val = packed; } } pstatus->cnt--; if (pstatus->val == -1) { BYTE packed = 0; if(io->read_proc(&packed, sizeof(BYTE), 1, handle) < 1) { return EOF; } return packed; } else { return pstatus->val; } } static const char * DLL_CALLCONV Format() { return "SGI"; } static const char * DLL_CALLCONV Description() { return "SGI Image Format"; } static const char * DLL_CALLCONV Extension() { return "sgi"; } static const char * DLL_CALLCONV RegExpr() { return NULL; } static const char * DLL_CALLCONV MimeType() { return "image/x-sgi"; } static BOOL DLL_CALLCONV Validate(FreeImageIO *io, fi_handle handle) { BYTE sgi_signature[2] = { 0x01, 0xDA }; BYTE signature[2] = { 0, 0 }; io->read_proc(signature, 1, sizeof(sgi_signature), handle); return (memcmp(sgi_signature, signature, sizeof(sgi_signature)) == 0); } static BOOL DLL_CALLCONV SupportsExportDepth(int depth) { return FALSE; } static BOOL DLL_CALLCONV SupportsExportType(FREE_IMAGE_TYPE type) { return FALSE; } static FIBITMAP * DLL_CALLCONV Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) { int width = 0, height = 0, zsize = 0; int i, dim; int bitcount; SGIHeader sgiHeader; RLEStatus my_rle_status; FIBITMAP *dib = NULL; LONG *pRowIndex = NULL; try { // read the header memset(&sgiHeader, 0, sizeof(SGIHeader)); if(io->read_proc(&sgiHeader, 1, sizeof(SGIHeader), handle) < sizeof(SGIHeader)) { throw SGI_LESS_THAN_HEADER_LENGTH; } #ifndef FREEIMAGE_BIGENDIAN SwapHeader(&sgiHeader); #endif if(sgiHeader.magic != 474) { throw FI_MSG_ERROR_MAGIC_NUMBER; } BOOL bIsRLE = (sgiHeader.storage == 1) ? TRUE : FALSE; // check for unsupported image types if (sgiHeader.bpc != 1) { // Expected one byte per color component throw SGI_16_BIT_COMPONENTS_NOT_SUPPORTED; } if (sgiHeader.colormap != 0) { // Indexed or dithered images not supported throw SGI_COLORMAPS_NOT_SUPPORTED; } // get the width & height dim = sgiHeader.dimension; width = sgiHeader.xsize; if (dim < 3) { zsize = 1; } else { zsize = sgiHeader.zsize; } if (dim < 2) { height = 1; } else { height = sgiHeader.ysize; } if(bIsRLE) { // read the Offset Tables int index_len = height * zsize; pRowIndex = (LONG*)malloc(index_len * sizeof(LONG)); if(!pRowIndex) { throw FI_MSG_ERROR_MEMORY; } if ((unsigned)index_len != io->read_proc(pRowIndex, sizeof(LONG), index_len, handle)) { throw SGI_EOF_IN_RLE_INDEX; } #ifndef FREEIMAGE_BIGENDIAN // Fix byte order in index for (i = 0; i < index_len; i++) { SwapLong((DWORD*)&pRowIndex[i]); } #endif // Discard row size index for (i = 0; i < (int)(index_len * sizeof(LONG)); i++) { BYTE packed = 0; if( io->read_proc(&packed, sizeof(BYTE), 1, handle) < 1 ) { throw SGI_EOF_IN_RLE_INDEX; } } } switch(zsize) { case 1: bitcount = 8; break; case 2: //Grayscale+Alpha. Need to fake RGBA bitcount = 32; break; case 3: bitcount = 24; break; case 4: bitcount = 32; break; default: throw SGI_INVALID_CHANNEL_COUNT; } dib = FreeImage_Allocate(width, height, bitcount); if(!dib) { throw FI_MSG_ERROR_DIB_MEMORY; } if (bitcount == 8) { // 8-bit SGI files are grayscale images, so we'll generate // a grayscale palette. RGBQUAD *pclrs = FreeImage_GetPalette(dib); for (i = 0; i < 256; i++) { pclrs[i].rgbRed = (BYTE)i; pclrs[i].rgbGreen = (BYTE)i; pclrs[i].rgbBlue = (BYTE)i; pclrs[i].rgbReserved = 0; } } // decode the image memset(&my_rle_status, 0, sizeof(RLEStatus)); int ns = FreeImage_GetPitch(dib); BYTE *pStartRow = FreeImage_GetScanLine(dib, 0); int offset_table[] = { 2, 1, 0, 3 }; int numChannels = zsize; if (zsize < 3) { offset_table[0] = 0; } if (zsize == 2) { //This is how faked grayscale+alpha works. //First channel goes into first //second channel goes into alpha (4th channel) //Two channels are left empty and will be copied later offset_table[1] = 3; numChannels = 4; } LONG *pri = pRowIndex; for (i = 0; i < zsize; i++) { BYTE *pRow = pStartRow + offset_table[i]; for (int j = 0; j < height; j++, pRow += ns, pri++) { BYTE *p = pRow; if (bIsRLE) { my_rle_status.cnt = 0; io->seek_proc(handle, *pri, SEEK_SET); } for (int k = 0; k < width; k++, p += numChannels) { int ch; BYTE packed = 0; if (bIsRLE) { ch = get_rlechar(io, handle, &my_rle_status); packed = (BYTE)ch; } else { ch = io->read_proc(&packed, sizeof(BYTE), 1, handle); } if (ch == EOF) { throw SGI_EOF_IN_IMAGE_DATA; } *p = packed; } } } if (zsize == 2) { BYTE *pRow = pStartRow; //If faking RGBA from grayscale + alpha, copy first channel to second and third for (int i=0; i<height; i++, pRow += ns) { BYTE *pPixel = pRow; for (int j=0; j<width; j++) { pPixel[2] = pPixel[1] = pPixel[0]; pPixel += 4; } } } if(pRowIndex) free(pRowIndex); return dib; } catch(const char *text) { if(pRowIndex) free(pRowIndex); if(dib) FreeImage_Unload(dib); FreeImage_OutputMessageProc(s_format_id, text); return NULL; } } // ========================================================== // Init // ========================================================== void DLL_CALLCONV InitSGI(Plugin *plugin, int format_id) { s_format_id = format_id; plugin->format_proc = Format; plugin->description_proc = Description; plugin->extension_proc = Extension; plugin->regexpr_proc = RegExpr; plugin->open_proc = NULL; plugin->close_proc = NULL; plugin->pagecount_proc = NULL; plugin->pagecapability_proc = NULL; plugin->load_proc = Load; plugin->save_proc = NULL; plugin->validate_proc = Validate; plugin->mime_proc = MimeType; plugin->supports_export_bpp_proc = SupportsExportDepth; plugin->supports_export_type_proc = SupportsExportType; plugin->supports_icc_profiles_proc = NULL; }
24.830986
90
0.620533
wterkaj
0fd1d219863da4e3213b2ddcd489f4a45379e0f4
11,370
cpp
C++
OpenSees/SRC/renderer/X11Device.cpp
kuanshi/ductile-fracture
ccb350564df54f5c5ec3a079100effe261b46650
[ "MIT" ]
8
2019-03-05T16:25:10.000Z
2020-04-17T14:12:03.000Z
SRC/renderer/X11Device.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
null
null
null
SRC/renderer/X11Device.cpp
steva44/OpenSees
417c3be117992a108c6bbbcf5c9b63806b9362ab
[ "TCL" ]
3
2019-09-21T03:11:11.000Z
2020-01-19T07:29:37.000Z
/* ****************************************************************** ** ** OpenSees - Open System for Earthquake Engineering Simulation ** ** Pacific Earthquake Engineering Research Center ** ** ** ** ** ** (C) Copyright 1999, The Regents of the University of California ** ** All Rights Reserved. ** ** ** ** Commercial use of this program without express permission of the ** ** University of California, Berkeley, is strictly prohibited. See ** ** file 'COPYRIGHT' in main directory for information on usage and ** ** redistribution, and for a DISCLAIMER OF ALL WARRANTIES. ** ** ** ** Developed by: ** ** Frank McKenna (fmckenna@ce.berkeley.edu) ** ** Gregory L. Fenves (fenves@ce.berkeley.edu) ** ** Filip C. Filippou (filippou@ce.berkeley.edu) ** ** ** ** ****************************************************************** */ // $Revision: 1.4 $ // $Date: 2003-02-18 23:38:04 $ // $Source: /usr/local/cvs/OpenSees/SRC/renderer/X11Device.cpp,v $ #include "X11Device.h" #include <OPS_Globals.h> #include <stdlib.h> int X11Device::numX11Device(0); Display *X11Device::theDisplay; Colormap X11Device::cmap; int X11Device::theScreen; unsigned long X11Device::pixels[X11_MAX_COLORS]; XColor X11Device::colors[X11_MAX_COLORS]; int X11Device::colorFlag; X11Device::X11Device() :winOpen(1) { hints.x = 50; hints.y = 50; hints.width = 0; hints.height = 0; drawingPolygon = 0; numPoints = 0; // call the initX11 method if this is the first object if (numX11Device == 0) { this->initX11(); numX11Device++; } } X11Device::~X11Device() { numX11Device--; if (winOpen == 0) { // we must close the old window XFreeGC(theDisplay, theGC); XDestroyWindow(theDisplay, theWindow); } if (numX11Device == 0) { if (colorFlag == 0) XFreeColors(theDisplay, cmap, pixels, 256, 0); else if (colorFlag == 1) XFreeColors(theDisplay, cmap, pixels, 192, 0); else if (colorFlag == 2) XFreeColors(theDisplay, cmap, pixels, 64, 0); XFreeColormap(theDisplay, cmap); XCloseDisplay(theDisplay); } } void X11Device::WINOPEN(int _width, int _height) { if (winOpen == 0) { // we must close the old window XFreeGC(theDisplay, theGC); XDestroyWindow(theDisplay, theWindow); } // define the position and size of the window - only hints hints.x = 50; hints.y = 50; hints.width = _width; hints.height = _height; height = _height; // now open a window theWindow = XCreateSimpleWindow(theDisplay,RootWindow(theDisplay,0), hints.x, hints.y, hints.width,hints.height,4, foreground, background); if (theWindow == 0) { opserr << "X11Device::WINOPEN() - could not open a window\n"; exit(-1); } XSetStandardProperties(theDisplay, theWindow, "g3", "g3", None, 0, 0, &hints); // create a graphical context theGC = XCreateGC(theDisplay, theWindow, 0, 0); XSetBackground(theDisplay, theGC, background); XSetForeground(theDisplay, theGC, foreground); if (colorFlag == 3) { cmap = XCreateColormap(theDisplay,theWindow, DefaultVisual(theDisplay,0),AllocAll); if (cmap == 0) { opserr << "X11Device::initX11() - could not get a new color table\n"; exit(-1); } // we are going to try to allocate 256 new colors -- need 8 planes for this int depth = DefaultDepth(theDisplay, theScreen); if (depth < 8) { opserr << "X11Device::initX11() - needed at least 8 planes\n"; exit(-1); } int cnt = 0; for (int red = 0; red < 8; red++) { for (int green = 0; green < 8; green++) { for (int blue = 0; blue < 4; blue++) { colors[cnt].pixel = pixels[32*red + 4*green + blue]; colors[cnt].red = (65536/7)*red; colors[cnt].green = (65536/7)*green; colors[cnt].blue = (65536/3)*blue; colors[cnt].flags = DoRed | DoGreen | DoBlue; cnt++; } } } XStoreColors(theDisplay, cmap, colors, cnt); XSetWindowColormap(theDisplay, theWindow, cmap); } XMapWindow(theDisplay,theWindow); XClearWindow(theDisplay, theWindow); XFlush(theDisplay); winOpen = 0; } void X11Device::CLEAR() { XSetBackground(theDisplay, theGC, background); XClearWindow(theDisplay, theWindow); XFlush(theDisplay); } void X11Device::C3F(float r, float g, float b) { int index, val; // check range of rgb values if (r<0 || r>1.0 || g<0 || g>1.0 || b<0 || b>1.0) { opserr << "X11Device::X11Device::C3F() rgb val out of range "; opserr << r << " " << g << " " << b << endln; return; } if (colorFlag == 0 || colorFlag == 3) { val = (((int)((r * 7.0)+.5))*32 + ((int)((g * 7.0)+.5))*4 + ((int)((b * 3.0)+.5))); } else if (colorFlag == 1) { val = (((int)((r * 7.0)+.5))*24 + ((int)((g * 5.0)+.5))*4 + ((int)((b * 3.0)+.5))); } else if (colorFlag == 2) { val = ((int)((r * 3.0)+.5))*16 + ((int)((g * 3.0)+.5))*4 + ((int)((b * 3.0)+.5)); } else val = 0; // should never be called index = pixels[val]; XSetForeground(theDisplay, theGC, index); } void X11Device::V2F(float x, float y) { // Flip the Y-Coordinate because X goes from 0->height as we // go top->bottom while GL goes from height->0 as we go top->bottom. y = height-y; if (drawingPolygon) { if (numPoints == MAX_NUM_POINTS_FOR_POLYGON) { opserr << "ERROR: Maximum number of points has been exceeded" << endln; return; } polygonPointArray[numPoints].x = (int)x; polygonPointArray[numPoints].y = (int)y; numPoints++; } else { XDrawPoint(theDisplay, theWindow, theGC, (int) x, (int) y); } } void X11Device::ENDIMAGE() { // Copy the image from our internal // buffer (theImage) onto the display. XFlush(theDisplay); // Update the XServer } void X11Device::STARTIMAGE() { // Copy the image from our internal // buffer (theImage) onto the display. XFlush(theDisplay); // Update the XServer } void X11Device::BGNPOLYGON() { numPoints = 0; drawingPolygon = 1; } void X11Device::ENDPOLYGON() { drawingPolygon = 0; // Draw the polygon with the GCs color opserr << " NUMPOINTS: "<< numPoints << endln; XFillPolygon(theDisplay, theWindow, theGC, polygonPointArray, numPoints, Complex, CoordModeOrigin); } void X11Device::BGNCLOSEDLINE() { numPoints = 0; drawingPolygon = 1; } void X11Device::ENDCLOSEDLINE() { drawingPolygon = 0; // Draw the polygon with the GCs color polygonPointArray[numPoints] = polygonPointArray[0]; // Close the loop XDrawLines(theDisplay, theWindow, theGC, polygonPointArray, numPoints+1, CoordModeOrigin); } void X11Device::BGNPOINT() { } void X11Device::ENDPOINT() { } void X11Device::drawText(float x, float y, char *text, int length) { y = height-y; XDrawString(theDisplay, theWindow, theGC, (int) x, (int) y, text, length); } int X11Device::GetWidth() { int x,y; unsigned int width, h, borderWidth, depth; XGetGeometry(theDisplay, theWindow, &RootWindow(theDisplay,0), &x, &y, &width, &h, &borderWidth, &depth); hints.width = width; hints.height = h; height = h; return width; } int X11Device::GetHeight() { int x,y; unsigned int width, h, borderWidth, depth; XGetGeometry(theDisplay, theWindow, &RootWindow(theDisplay,0), &x, &y, &width, &h, &borderWidth, &depth); hints.width = width; hints.height = h; height = h; return height; } void X11Device::initX11(void) { // set the display and screen variables theDisplay = XOpenDisplay(""); // init a display connection if (theDisplay == 0) { // and check we got one opserr << "X11Device::initX11() - could not connect to display\n"; exit(-1); } theScreen = DefaultScreen(theDisplay); // set the defualt foreground and background colors foreground = BlackPixel(theDisplay, theScreen); background = WhitePixel(theDisplay, theScreen); // lets try using the default colormap cmap = DefaultColormap(theDisplay, theScreen); XVisualInfo vinfo; if (XMatchVisualInfo(theDisplay, theScreen, 8, PseudoColor, &vinfo) == false) opserr << "X11Device::initX11 - could not get info\n"; // we now try to allocate some color cells from the colormap // we start by tring to obtain 256 colors, then 192, finally 64 // if we can't get these (and as a last resort) we create a new color map if (XAllocColorCells(theDisplay, cmap, false, NULL, 0, pixels, 256) != 0) { // we were able to allocate 256 colors from the table for our use colorFlag = 0; int cnt = 0; for (int red =0; red <8; red++) { for (int green = 0; green<8; green++) { for (int blue =0; blue<4; blue++) { colors[cnt].pixel = pixels[32*red + 4*green + blue]; colors[cnt].red = (65536/7)*red; colors[cnt].green = (65536/7)*green; colors[cnt].blue = (65536/3)*blue; colors[cnt].flags = DoRed | DoGreen | DoBlue; cnt++; } } } XStoreColors(theDisplay, cmap, colors, cnt); } else if (XAllocColorCells(theDisplay, cmap, false, NULL, 0, pixels, 192) != 0) { // we were able to allocate 192 colors from the table for our use colorFlag = 1; int cnt = 0; for (int red =0; red <8; red++) { for (int green = 0; green<6; green++) { for (int blue =0; blue<4; blue++) { colors[cnt].pixel = pixels[24*red + 4*green + blue]; colors[cnt].red = (65536/7)*red; colors[cnt].green = (65536/5)*green; colors[cnt].blue = (65536/3)*blue; colors[cnt].flags = DoRed | DoGreen | DoBlue; cnt++; } } } XStoreColors(theDisplay, cmap, colors, cnt); } else if (XAllocColorCells(theDisplay, cmap, false, NULL, 0, pixels, 64) != 0) { colorFlag = 2; int cnt = 0; for (int red =0; red <4; red++) { for (int green = 0; green<4; green++) { for (int blue =0; blue<4; blue++) { colors[cnt].pixel = pixels[16*red + 4*green + blue]; colors[cnt].red = (65536/3)*red; colors[cnt].green = (65536/3)*green; colors[cnt].blue = (65536/3)*blue; colors[cnt].flags = DoRed | DoGreen | DoBlue; cnt++; } } } XStoreColors(theDisplay, cmap, colors, cnt); } else { colorFlag = 3; // lets create our own color table - // problem with this is that screen colors change as we enter opserr << "X11Device::initX11() - could not any colors from the default\n"; opserr << "colormap - have to create our own for the app - windows will\n"; opserr << "windows will change color as move mouse from one window to another\n\n"; } }
27.597087
86
0.574318
kuanshi
0fd3dfb2b29d04d9e65156adb43d220e322ea57a
12,964
cc
C++
common/formatting/state_node.cc
snsokolov/verible
7c59a17b975c9e87fb5d675540dc788d389edac9
[ "Apache-2.0" ]
null
null
null
common/formatting/state_node.cc
snsokolov/verible
7c59a17b975c9e87fb5d675540dc788d389edac9
[ "Apache-2.0" ]
null
null
null
common/formatting/state_node.cc
snsokolov/verible
7c59a17b975c9e87fb5d675540dc788d389edac9
[ "Apache-2.0" ]
null
null
null
// Copyright 2017-2019 The Verible Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "common/formatting/state_node.h" #include <cstddef> #include <iterator> #include <memory> #include <stack> #include <vector> #include "absl/strings/string_view.h" #include "common/formatting/basic_format_style.h" #include "common/formatting/format_token.h" #include "common/formatting/unwrapped_line.h" #include "common/strings/position.h" #include "common/strings/range.h" #include "common/text/token_info.h" #include "common/util/iterator_adaptors.h" #include "common/util/iterator_range.h" #include "common/util/logging.h" namespace verible { StateNode::StateNode(const UnwrappedLine& uwline, const BasicFormatStyle& style) : prev_state(nullptr), undecided_path(uwline.TokensRange().begin(), uwline.TokensRange().end()), spacing_choice( SpacingDecision::Append), // Treat first token as appended. // Kludge: This leaks into the resulting FormattedExcerpt, which means // additional logic is needed to handle preservation of (vertical) spacing // between formatted token partitions. current_column(uwline.IndentationSpaces()), wrap_column_positions() { // The starting column is relative to the current indentation level. VLOG(4) << "initial column position: " << current_column; wrap_column_positions.push(current_column + style.wrap_spaces); if (!uwline.TokensRange().empty()) { VLOG(4) << "token.text: \'" << undecided_path.front().token->text << '\''; // Point undecided_path past the first token. undecided_path.pop_front(); // Place first token on unwrapped line. _UpdateColumnPosition(); CHECK_EQ(cumulative_cost, 0); _OpenGroupBalance(style); } VLOG(4) << "root: " << *this; } StateNode::StateNode(const std::shared_ptr<const StateNode>& parent, const BasicFormatStyle& style, SpacingDecision spacing_choice) : prev_state(ABSL_DIE_IF_NULL(parent)), undecided_path(prev_state->undecided_path.begin() + 1, // pop_front() prev_state->undecided_path.end()), spacing_choice(spacing_choice), // current_column to be computed, depending on spacing_choice cumulative_cost(prev_state->cumulative_cost), // will be adjusted below wrap_column_positions(prev_state->wrap_column_positions) { CHECK(!prev_state->Done()); const PreFormatToken& current_format_token(GetCurrentToken()); VLOG(4) << "token.text: \'" << current_format_token.token->text << '\''; bool called_open_group_balance = false; bool called_close_group_balance = false; if (spacing_choice == SpacingDecision::Wrap) { // When wrapping and closing a balance group, adjust wrap column stack // first. if (current_format_token.balancing == GroupBalancing::Close) { _CloseGroupBalance(); called_close_group_balance = true; } // When wrapping after opening a balance group, adjust wrap column stack // first. if (prev_state->spacing_choice == SpacingDecision::Wrap) { _OpenGroupBalance(style); called_open_group_balance = true; } } // Update column position and add penalty to the cumulative cost. _UpdateColumnPosition(); _UpdateCumulativeCost(style); // Adjusting for open-group is done after updating current column position, // and is based on the *previous* open-group token, and the // spacing_choice for *this* token. if (!called_open_group_balance) { _OpenGroupBalance(style); } // When appending and closing a balance group, adjust wrap column stack last. if (!called_close_group_balance && (current_format_token.balancing == GroupBalancing::Close)) { _CloseGroupBalance(); } VLOG(4) << "new state_node: " << *this; } const PreFormatToken& StateNode::_GetPreviousToken() const { CHECK(!ABSL_DIE_IF_NULL(prev_state)->Done()); return prev_state->GetCurrentToken(); } void StateNode::_UpdateColumnPosition() { VLOG(4) << __FUNCTION__; const PreFormatToken& current_format_token(GetCurrentToken()); const int token_length = current_format_token.Length(); switch (spacing_choice) { case SpacingDecision::Wrap: // If wrapping, new column position is based on the wrap_column_positions // top-of-stack. current_column = wrap_column_positions.top() + token_length; VLOG(4) << "current wrap_position = " << wrap_column_positions.top(); VLOG(4) << "wrapping, current_column is now " << current_column; break; case SpacingDecision::Append: // If appending, new column position is added to previous state's column // position. if (!IsRootState()) { VLOG(4) << " previous column position: " << prev_state->current_column; current_column = prev_state->current_column + current_format_token.before.spaces_required + token_length; } else { VLOG(4) << " old column position: " << current_column; // current_column was already initialized, so just add token length. current_column += token_length; } break; case SpacingDecision::Preserve: { const absl::string_view original_spacing_text = current_format_token.OriginalLeadingSpaces(); current_column = AdvancingTextNewColumnPosition( prev_state->current_column, original_spacing_text); current_column += token_length; VLOG(4) << " new column position (preserved): " << current_column; break; } } } void StateNode::_UpdateCumulativeCost(const BasicFormatStyle& style) { // This must be called after _UpdateColumnPosition() to account for // the updated current_column. if (!IsRootState()) { CHECK_EQ(cumulative_cost, prev_state->cumulative_cost); } const PreFormatToken& current_format_token(GetCurrentToken()); if (spacing_choice == SpacingDecision::Wrap) { // Only incur the penalty for breaking before this token. // Newly wrapped, so don't bother checking line length and suppress // penalty if the first token on a line happens to exceed column limit. cumulative_cost += current_format_token.before.break_penalty; } else if (spacing_choice == SpacingDecision::Append) { // Check for line length violation of current_column, and penalize more // for each column over the limit. if (current_column > style.column_limit) { cumulative_cost += style.over_column_limit_penalty + current_column - style.column_limit; } } // no additional cost if Spacing::Preserve } void StateNode::_OpenGroupBalance(const BasicFormatStyle& style) { VLOG(4) << __FUNCTION__; // The adjustment to the wrap_column_positions stack based on a token's // balance type is delayed until we see the token *after*. // If previous token was an open-group, then update indentation of // subsequent tokens to line up with the column of the open-group operator. // Otherwise, it should wrap to the previous state's column position. // // Illustrated: // // [append-open-group, wrap-next-token] // ...... ( // ^--- next wrap should line up here // // [append-open-group, append-next-token] // ...... ( ...something... // ^--- next wrap should line up here // // [wrap-open-group, wrap-next-token] // ...... // ( // ^--- next wrap should line up here // // [wrap-open-group, append-next-token] // ...... // ( ...something... // ^--- next wrap should line up here // // TODO(fangism): what if previous token is open, and new token is close? // Suppress? CHECK(!wrap_column_positions.empty()); if (!IsRootState()) { const PreFormatToken& prev_format_token(_GetPreviousToken()); if (prev_format_token.balancing == GroupBalancing::Open) { VLOG(4) << "previous token is open-group"; switch (spacing_choice) { case SpacingDecision::Wrap: VLOG(4) << "current token is wrapped"; wrap_column_positions.push(prev_state->wrap_column_positions.top() + style.wrap_spaces); break; case SpacingDecision::Append: VLOG(4) << "current token is appended"; wrap_column_positions.push(prev_state->current_column); break; case SpacingDecision::Preserve: // TODO(b/134711965): calculate column position using original spaces break; } } } // TODO(fangism): what if first token on unwrapped line is open-group? } void StateNode::_CloseGroupBalance() { if (wrap_column_positions.size() > 1) { // Always maintain at least one element on column position stack. wrap_column_positions.pop(); } // TODO(fangism): Align with the corresponding open-group operator, // assuming its string length is 1, but only when the open-group operator // has text that follows on the same line. // This will appear like: // ... (... // ... // ) <-- aligned with ( } std::shared_ptr<const StateNode> StateNode::AppendIfItFits( const std::shared_ptr<const StateNode>& current_state, const verible::BasicFormatStyle& style) { if (current_state->Done()) return current_state; const auto& token = current_state->GetNextToken(); // It seems little wasteful to always create both states when only one is // returned, but compiler optimization should be able to leverage this. // In any case, this is not a critical path operation, so we're not going to // worry about it. const auto wrapped = std::make_shared<StateNode>(current_state, style, SpacingDecision::Wrap); const auto appended = std::make_shared<StateNode>(current_state, style, SpacingDecision::Append); if (token.before.break_decision == SpacingOptions::MustWrap || appended->current_column > style.column_limit) { return wrapped; } else { return appended; } } std::shared_ptr<const StateNode> StateNode::QuickFinish( const std::shared_ptr<const StateNode>& current_state, const verible::BasicFormatStyle& style) { std::shared_ptr<const StateNode> latest(current_state); // Construct a chain of reference-counted states where the returned pointer // "holds on" to all of its ancestors like a singly-linked-list. while (!latest->Done()) { latest = AppendIfItFits(latest, style); } return latest; } void StateNode::ReconstructFormatDecisions(FormattedExcerpt* result) const { // Find all wrap decisions from the greatest ancestor state to this state. // This is allowed to work on any intermediate state in the search process, // so the depth can be less than the number of format tokens in the // UnwrappedLine. const size_t depth = Depth(); CHECK_LE(depth, result->Tokens().size()); const StateNode* reverse_iter = this; auto& format_tokens = result->MutableTokens(); const auto format_tokens_slice = make_range(format_tokens.begin(), format_tokens.begin() + depth); for (auto& format_token : reversed_view(format_tokens_slice)) { VLOG(3) << "reconstructing: " << format_token.token->text; // Apply decision at reverse_iter to (formatted) FormatToken. format_token.before.action = ABSL_DIE_IF_NULL(reverse_iter)->spacing_choice; if (reverse_iter->spacing_choice == SpacingDecision::Wrap) { // Mark as inserting a line break. // Immediately after a line break, print out the amount of spaces // required to honor the indentation and wrapping. format_token.before.spaces = reverse_iter->current_column - format_token.token->text.length(); VLOG(3) << " wrapped, with " << format_token.before.spaces << " leading spaces."; CHECK_GE(format_token.before.spaces, 0); } // else: no need to calculate before.spaces. reverse_iter = reverse_iter->next(); } } std::ostream& operator<<(std::ostream& stream, const StateNode& state) { // Omit information about remaining decisions and parent state. CHECK(!state.wrap_column_positions.empty()); return stream << "spacing:" << state.spacing_choice << // noformat ", col@" << state.current_column << // noformat ", cost=" << state.cumulative_cost << // noformat ", [..." << state.wrap_column_positions.top() << ']'; } } // namespace verible
39.889231
80
0.683662
snsokolov
0fd49e65f71f076c3657a1f89b191f394be91c4c
4,981
cpp
C++
Source/FactorySkyline/Operators/FSConveyorBeltOperator.cpp
RozeDoyanawa/FactorySkyline
381d983d8c8fcac7fa9ce3c386d52bd68d2248b6
[ "MIT" ]
3
2021-07-09T06:20:11.000Z
2022-01-23T09:29:21.000Z
Source/FactorySkyline/Operators/FSConveyorBeltOperator.cpp
The1NdNly/FactorySkyline
e9ee8750ed6417fc8e12328b0adb44a9e3baa739
[ "MIT" ]
null
null
null
Source/FactorySkyline/Operators/FSConveyorBeltOperator.cpp
The1NdNly/FactorySkyline
e9ee8750ed6417fc8e12328b0adb44a9e3baa739
[ "MIT" ]
6
2021-07-11T15:10:12.000Z
2022-02-27T02:16:15.000Z
// ILikeBanas #include "FSConveyorBeltOperator.h" #include "Buildables/FGBuildable.h" #include "Buildables/FGBuildableConveyorBelt.h" //#include "FGInstancedSplineMesh.h" #include "FGInstancedSplineMeshComponent.h" #include "FactorySkyline/FSkyline.h" AFGHologram* UFSConveyorBeltOperator::HologramCopy(FTransform& RelativeTransform) { RelativeTransform = Source->GetTransform(); AFGHologram* Hologram = CreateHologram(); if (!Hologram) return nullptr; AFGConveyorBeltHologram* ConveyorBeltHologram = Cast<AFGConveyorBeltHologram>(Hologram); if (!ConveyorBeltHologram) return Hologram; AFGBuildableConveyorBelt* SourceBelt = Cast<AFGBuildableConveyorBelt>(Source); FHitResult Hit; Hit.Actor = nullptr; Hit.Time = 0.006946; Hit.Location = FVector(-11720.067f, 248538.719f, -10141.936f); Hit.ImpactPoint = FVector(-11720.066f, 248538.719f, -10141.936f); Hit.Normal = FVector(1.0f, 0.0f, 0.0f); Hit.ImpactNormal = FVector(1.0f, 0.0f, 0.0f); Hit.TraceStart = FVector(-11025.803f, 248538.188f, -10162.381f); Hit.TraceEnd = FVector(-110982.445f, 248615.406f, -12781.198f); Hit.PenetrationDepth = 0.0f; Hit.Item = -1; Hit.FaceIndex = -1; Hologram->SetHologramLocationAndRotation(Hit); Hologram->SetPlacementMaterial(true); UFGInstancedSplineMeshComponent* SourceComponent = Cast<UFGInstancedSplineMeshComponent>(SourceBelt->GetComponentByClass(UFGInstancedSplineMeshComponent::StaticClass())); USplineMeshComponent* SplineMeshComponent = nullptr; TSet<UActorComponent*> Set = Hologram->GetComponents(); for (UActorComponent* Component : Set) { Log("%s", *Component->GetName()); auto c = Cast<USplineMeshComponent>(Component); if(c) { SplineMeshComponent = Cast<USplineMeshComponent>(Component); break; } } bool NeedNew = false; for (FInstancedSplineInstanceData& Data : SourceComponent->PerInstanceSplineData) { if (NeedNew) { USplineMeshComponent* Component = NewObject<USplineMeshComponent>(Hologram); Component->SetStaticMesh(SplineMeshComponent->GetStaticMesh()); Component->BodyInstance = SplineMeshComponent->BodyInstance; Component->SetForwardAxis(SplineMeshComponent->ForwardAxis); Component->SetMobility(SplineMeshComponent->Mobility); for (int i = 0; i < SplineMeshComponent->GetNumMaterials(); i++) { Component->SetMaterial(i, SplineMeshComponent->GetMaterial(i)); } Component->SetStartAndEnd(Data.StartPos, Data.StartTangent, Data.EndPos, Data.EndTangent); Component->AttachTo(Hologram->GetRootComponent()); Component->RegisterComponent(); } else { SplineMeshComponent->SetStartAndEnd(Data.StartPos, Data.StartTangent, Data.EndPos, Data.EndTangent); } NeedNew = true; } return Hologram; } AFGBuildable* UFSConveyorBeltOperator::CreateCopy(const FSTransformOperator& TransformOperator) { AFSkyline* FSkyline = AFSkyline::Get(this); FVector RelativeVector = TransformOperator.SourceTransform.InverseTransformPositionNoScale(Source->GetTransform().GetLocation()); FQuat RelativeRotation = TransformOperator.SourceTransform.InverseTransformRotation(Source->GetTransform().GetRotation()); FQuat Rotation = TransformOperator.TargetTransform.TransformRotation(RelativeRotation); FTransform Transform = FTransform(FRotator::ZeroRotator, TransformOperator.TargetTransform.TransformPositionNoScale(RelativeVector), Source->GetTransform().GetScale3D()); AFGBuildableConveyorBelt* SourceConveyorBelt = Cast<AFGBuildableConveyorBelt>(Source); AFGBuildable* Buildable = BuildableSubsystem->BeginSpawnBuildable(Source->GetClass(), Transform); AFGBuildableConveyorBelt* TargetConveyorBelt = Cast<AFGBuildableConveyorBelt>(Buildable); TSubclassOf<UFGRecipe> Recipe = SplineHologramFactory->GetRecipeFromClass(Source->GetClass()); if (!Recipe) Recipe = Source->GetBuiltWithRecipe(); if (!Recipe) return nullptr; Buildable->SetBuiltWithRecipe(Recipe); //Buildable->SetBuildingID(Source->GetBuildingID()); //TArray< FSplinePointData >* SourceData = &SourceConveyorBelt->mSplineData; TArray< FSplinePointData >* SourceData = FSkyline->AdaptiveUtil->GetConveyorBeltSplineData(SourceConveyorBelt); //TArray< FSplinePointData >* SourceData = &TargetConveyorBelt->mSplineData; TArray< FSplinePointData >* TargetData = FSkyline->AdaptiveUtil->GetConveyorBeltSplineData(TargetConveyorBelt); for (const FSplinePointData& PointData : *SourceData) { FSplinePointData NewPointData; NewPointData.Location = Rotation.RotateVector(PointData.Location); NewPointData.ArriveTangent = Rotation.RotateVector(PointData.ArriveTangent); NewPointData.LeaveTangent = Rotation.RotateVector(PointData.LeaveTangent); TargetData->Add(NewPointData); } Buildable->SetColorSlot_Implementation(Source->GetColorSlot_Implementation()); Buildable->FinishSpawning(Transform); this->BuildableSubsystem->RemoveConveyorFromBucket(TargetConveyorBelt); return Buildable; }
42.211864
172
0.773539
RozeDoyanawa
0fd63208c236712add2719a7f4d14c7c1c660fb7
592
hpp
C++
Utility/VLArray/Entry/a_Body.hpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
2
2020-09-13T07:31:22.000Z
2022-03-26T08:37:32.000Z
Utility/VLArray/Entry/a_Body.hpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
null
null
null
Utility/VLArray/Entry/a_Body.hpp
p-adic/cpp
9404a08f26c55a19c53ab0a11edb70f3ed6a8e3c
[ "MIT" ]
null
null
null
// c:/Users/user/Documents/Programming/Utility/VLArray/Entry/a_Body.hpp #pragma once #include "a.hpp" template <typename T> inline EntryOfVLArray<T>::EntryOfVLArray() : m_t() , m_prev( this ) , m_next( this ) {} template <typename T> template <typename Arg> inline EntryOfVLArray<T>::EntryOfVLArray( const Arg& t ) : m_t( t ) , m_prev( this ) , m_next( this ) {} template <typename T> template <typename Arg> inline EntryOfVLArray<T>::EntryOfVLArray( const Arg& t , EntryOfVLArray<T>* const& prev , EntryOfVLArray<T>* const& next ) : m_t( t ) , m_prev( prev ) , m_next( next ) {}
59.2
217
0.692568
p-adic
0fd6df511852dea8122fbf77f74909535ee0c34f
5,180
cpp
C++
bin/docker/CH_HCNetSDK_V5.3.5.2_build20171124_Linux64/QtDemo/src/OtherFunc/Deployment/deploy.cpp
escoffier/newmedia
f15aedae56a5b5c22c6451fa45b58ce108a58b9e
[ "Apache-2.0" ]
null
null
null
bin/docker/CH_HCNetSDK_V5.3.5.2_build20171124_Linux64/QtDemo/src/OtherFunc/Deployment/deploy.cpp
escoffier/newmedia
f15aedae56a5b5c22c6451fa45b58ce108a58b9e
[ "Apache-2.0" ]
null
null
null
bin/docker/CH_HCNetSDK_V5.3.5.2_build20171124_Linux64/QtDemo/src/OtherFunc/Deployment/deploy.cpp
escoffier/newmedia
f15aedae56a5b5c22c6451fa45b58ce108a58b9e
[ "Apache-2.0" ]
null
null
null
/************************************************************************ * Copyright 2009-2011 Hikvision Digital Technology Co., Ltd. * FileName : deploy.cpp * Description : deploy * Modification History : none * Version : V1.0 * Time : 2009-11,12 * Author : wanggongpu * Descrp : *************************************************************************/ #include "deploy.h" #include <QMessageBox> #include <QString> /************************************************************************ * Function : Deploy * Description : instructor * Input : none * Output : none * Return : none *************************************************************************/ Deploy::Deploy(QList<DeviceData> * tree, QDialog *parent) : QDialog(parent) { ui.setupUi(this); m_qlistdevicetree =tree; QList<DeviceData>::iterator it; int i=0; for ( it = (*m_qlistdevicetree).begin(); it != (*m_qlistdevicetree).end(); ++it) { if ((*it).getUsrID()>=0) { items.append(new QTreeWidgetItem((QTreeWidget*)0, QStringList((*it).getDeviceName()))); } } ui.treeWidget->insertTopLevelItems(0, items); connect(ui.treeWidget,SIGNAL(itemClicked(QTreeWidgetItem *, int)),this,SLOT(deployDevice(QTreeWidgetItem *, int))); m_dphandle =-1; } /************************************************************************ * Function : ~Deploy * Description : none * Input : none * Output : none * Return : none *************************************************************************/ Deploy::~Deploy() { items.clear(); ui.treeWidget->clear(); } /************************************************************************ * Function : deployDevice * Description : deploy a device * Input : QTreeWidgetItem * item, int column * Output : none * Return : none *************************************************************************/ void Deploy::deployDevice(QTreeWidgetItem * item, int column) { QList<DeviceData>::iterator it; int i=0; for ( it = (*m_qlistdevicetree).begin(),i=0; i<256,it != (*m_qlistdevicetree).end(); ++it) { if ((*it).getDeviceName()==item->text(column)) { //QMessageBox::information(this,tr("NET_DVR_SetupAlarmChan_V30 SUCCESS"), //tr("(*it).getDeployState()=%1").arg((*it).getDeployState())); m_useridtmp = (*it).getUsrID(); break; } if ((*it).getUsrID()>=0) { i++; } } } /************************************************************************ * Function : on_pushButton_deployornot_clicked * Description : deloy or not * Input : none * Output : none * Return : none *************************************************************************/ void Deploy::on_pushButton_deployornot_clicked() { QList<DeviceData>::iterator it; int i=0; for ( it = (*m_qlistdevicetree).begin(),i=0; i<256,it != (*m_qlistdevicetree).end(); ++it) { if ((*it).getUsrID()==m_useridtmp ) { break; } } if ((*it).getDeployState()==-1) { m_dphandle= NET_DVR_SetupAlarmChan_V30(m_useridtmp); if (-1 == m_dphandle) { QMessageBox::information(this,tr("NET_DVR_SetupAlarmChan_V30 failed"), \ tr("SDK_Last_Error =%1 ").arg(NET_DVR_GetLastError())); return ; } QMessageBox::information(this,tr("NET_DVR_SetupAlarmChan_V30 SUCCESS"), tr("NET_DVR_SetupAlarmChan_V30 SUCCESS")); (*it).setDeployState(m_dphandle); } else { int i=(*it).getDeployState(); if (!NET_DVR_CloseAlarmChan_V30(i)) { QMessageBox::information(this,tr("NET_DVR_CloseAlarmChan_V30 failed"), \ tr("SDK_Last_Error =%1 ").arg(NET_DVR_GetLastError())); return ; } QMessageBox::information(this,tr("NET_DVR_CloseAlarmChan_V30 SUCCESS"), tr("NET_DVR_CloseAlarmChan_V30 SUCCESS")); (*it).setDeployState(-1); } } /************************************************************************ * Function : on_pushButton_exit_clicked * Description : exit * Input : none * Output : none * Return : none *************************************************************************/ void Deploy::on_pushButton_exit_clicked() { close(); }
34.078947
90
0.405212
escoffier
0fd6e07d340533199a882e38a014d19127240ae9
16,928
cpp
C++
src_legacy/2017/pixelgateway.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
src_legacy/2017/pixelgateway.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
75
2017-05-28T23:39:33.000Z
2019-05-09T06:18:44.000Z
src_legacy/2017/pixelgateway.cpp
gmoehler/ledpoi
d1294b172b7069f62119c310399d80500402d882
[ "MIT" ]
null
null
null
#include <Arduino.h> #include <ws2812.h> #include <WiFi.h> #include "WiFiCredentials.h" #include "ledpoi.h" #include "PoiActionRunner.h" #include "PoiTimer.h" #include "OneButton.h" enum PoiState { POI_INIT, // 0 POI_IP_CONFIG_OPTION, // 1 POI_IP_CONFIG, // 2 POI_NETWORK_SEARCH, // 3 POI_CLIENT_CONNECTING, // 4 POI_RECEIVING_DATA, // 5 POI_AWAIT_PROGRAM_SYNC, // 6 POI_PLAY_PROGRAM, // 7 NUM_POI_STATES}; // only used for enum size LogLevel logLevel = QUIET; // CHATTY, QUIET or MUTE const int DATA_PIN = 23; // was 18 Avoid using any of the strapping pins on the ESP32 const int LED_PIN = 2; const int BUTTON_PIN = 0; OneButton button1(BUTTON_PIN, true); const int connTimeout=10; // client connection timeout in secs const int maxLEDLevel = 200; // restrict max LED brightness due to protocol const uint8_t aliveTickModulo = 10; uint8_t aliveTickCnt = 0; // WiFi credentials (as defined in WiFiCredentials.h) extern const char* WIFI_SSID[]; extern const char* WIFI_PASS[]; WiFiServer server(1110); WiFiClient client; IPAddress clientIP; uint32_t connectionLostTime = 0; uint8_t baseIpAdress[4] = {192, 168, 1, 127}; uint8_t ipIncrement = 0; // increment to base ip for different pois uint8_t currentNetworkConfig = 0; // which one of the configs defined in WiFiCredentials.h PoiState poiState = POI_INIT; PoiState nextPoiState = poiState; PoiTimer ptimer(logLevel, true); PoiActionRunner runner(ptimer, logLevel); PoiFlashMemory _flashMemory; uint32_t lastSignalTime = 0; // time when last wifi signal was received, for timeout unsigned char cmd [7]; // command read from server int cmdIndex=0; // index into command read from server char c; bool loadingImgData = false; // tag to suppress log during image loading uint32_t poi_network_display_entered = 0; uint32_t currentTime = 0; void blink(int m){ for (int n=0;n<m;n++){ digitalWrite(LED_PIN,HIGH); delay(50); digitalWrite(LED_PIN,LOW); delay(50); } } // Interrupt at interval determined by program void IRAM_ATTR ptimer_intr() { // printf cannot be used within interrupt //Serial.print("Interrupt at "); //Serial.println(millis()); runner.onInterrupt(); } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); } void wifi_disconnect(){ client.stop(); server.end(); WiFi.disconnect(); printf("WIFI disconnected."); } // synchronous method connecting to wifi void wifi_connect(){ uint8_t ip4 = baseIpAdress[3] + ipIncrement; printf("My address: %d.%d.%d.%d\n", baseIpAdress[0],baseIpAdress[1],baseIpAdress[2],ip4); IPAddress myIP(baseIpAdress[0],baseIpAdress[1],baseIpAdress[2],ip4); IPAddress gateway(192, 168, 1, 1); IPAddress subnet(255, 255, 255, 0); if (logLevel != MUTE){ Serial.println(); Serial.print("Connecting to "); Serial.println(WIFI_SSID[currentNetworkConfig]); } // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); if (WiFi.status() == WL_CONNECTED){ WiFi.disconnect(); delay(100); } bool connectedToWifi=false; WiFi.config(myIP,gateway,subnet); while (!connectedToWifi){ WiFi.begin(WIFI_SSID[currentNetworkConfig], WIFI_PASS[currentNetworkConfig]); if (logLevel != MUTE) Serial.print("Connecting..."); while (WiFi.status() != WL_CONNECTED) { // Check to see if connecting failed. // This is due to incorrect credentials delay(500); if (logLevel != MUTE) Serial.print("."); } if (WiFi.status() == WL_CONNECT_FAILED) { if (logLevel != MUTE) Serial.println("Connection Failed. Retrying..."); blink(1); } else { blink(10); connectedToWifi=true; if (logLevel != MUTE) { Serial.println("Connected."); printWifiStatus(); } } } // printWifiStatus(); digitalWrite(LED_PIN, LOW); // Turn off LED server.begin(); // important nextPoiState = POI_CLIENT_CONNECTING; } void wifi_connect_async_init(){ uint8_t ip4 = baseIpAdress[3] + ipIncrement; printf("My address: %d.%d.%d.%d\n", baseIpAdress[0],baseIpAdress[1],baseIpAdress[2],ip4); IPAddress myIP(baseIpAdress[0],baseIpAdress[1],baseIpAdress[2],ip4); IPAddress gateway(192, 168, 1, 1); IPAddress subnet(255, 255, 255, 0); if (logLevel != MUTE){ Serial.println(); Serial.printf("Connecting to SSID %s...\n", WIFI_SSID[currentNetworkConfig]); } // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); if (WiFi.status() == WL_CONNECTED){ WiFi.disconnect(); delay(100); } WiFi.config(myIP,gateway,subnet); WiFi.begin(WIFI_SSID[currentNetworkConfig], WIFI_PASS[currentNetworkConfig]); if (logLevel != MUTE) Serial.print("Connecting..."); } void wifi_connect_async(){ wl_status_t wifiStatus = WiFi.status(); if (wifiStatus == WL_CONNECTED) { Serial.println("Connected."); printWifiStatus(); nextPoiState = POI_CLIENT_CONNECTING; return; } // first few cycles after connection is lost if (wifiStatus == WL_CONNECTION_LOST) { connectionLostTime = millis(); } // all other errors (connection failed, ssid not found...) else if (millis() - connectionLostTime > 5000){ printf("Re-initializing connection process...\n"); currentNetworkConfig++; if (currentNetworkConfig > NUM_WIFI_CONFIG -1){ currentNetworkConfig = 0; } wifi_connect_async_init(); connectionLostTime = millis(); } if (!runner.isProgramActive()){ delay(500); if (logLevel != MUTE) Serial.print("."); } //printf("***Connection status: %d\n", WiFi.status()); } void resetTimeout(){ lastSignalTime = millis(); } bool reachedTimeout(){ return (millis() - lastSignalTime > connTimeout * 1000); } // connect to a client if available void client_connect(){ //printf("****client_connect status: %d", WiFi.status()); if (WiFi.status() != WL_CONNECTED) { printf("***CONNECTION LOST\n"); nextPoiState = POI_NETWORK_SEARCH; return; } server.begin(); // if server has been started it simply returns client = server.available(); if (client.connected()){ if (logLevel != MUTE) printf("Client connected.\n" ); resetTimeout(); nextPoiState = POI_RECEIVING_DATA; } else if (!runner.isProgramActive()) { // slow down a bit delay(100); } } void client_disconnect(){ client.stop(); if (logLevel != MUTE) Serial.println("Connection closed."); } // defined below void longPressStart1(); void click1(); void setup() { // pinMode(BUTTON_PIN, INPUT_PULLUP); pinMode(LED_PIN, OUTPUT); // blink(5); delay(500); Serial.begin(115200); if (logLevel != MUTE) { Serial.println(); Serial.println("Starting..."); } button1.attachLongPressStart(longPressStart1); button1.attachClick(click1); // init runner runner.setup(); ipIncrement = runner.getIpIncrement(); // init LEDs if(ws2812_init(DATA_PIN, LED_WS2812B)){ Serial.println("LED Pixel init error."); } #if DEBUG_WS2812_DRIVER dumpDebugBuffer(-2, ws2812_debugBuffer); #endif runner.displayOff(); #if DEBUG_WS2812_DRIVER dumpDebugBuffer(-1, ws2812_debugBuffer); #endif if (logLevel != MUTE) Serial.println("Init LEDs complete"); blink(2); // init timer ptimer.init(ptimer_intr); } void print_cmd(){ printf("CMD: %d %d %d %d %d %d\n", cmd[0], cmd[1], cmd[2], cmd[3], cmd[4], cmd[5]); } void realize_cmd(){ switch(cmd[0]){ case 254: switch (cmd[1]){ // setAction case 0: runner.saveScene(cmd[2]); break; case 1: runner.showStaticFrame(cmd[2], cmd[3], cmd[4], cmd[5]); break; case 2: // (fade to) black runner.fadeToBlack(cmd[2], cmd[3]); break; case 3: runner.startProg(); break; case 4: runner.pauseProg(); break; case 5: runner.continueProg(); break; case 6: runner.jumptoSync(cmd[2]); break; case 7: //setIP(cmd[2],cmd[3],cmd[4],cmd[5]); break; case 8: //setGW(cmd[2],cmd[3],cmd[4],cmd[5]); break; case 9: if (logLevel != MUTE) Serial.println("Completely erasing and initializing flash."); runner.initializeFlash(); case 10: if (logLevel != MUTE) Serial.println("Connection close command received."); client_disconnect(); nextPoiState = POI_CLIENT_CONNECTING; break; case11: if (cmd[2] < NUM_WIFI_CONFIG){ currentNetworkConfig = cmd[2]; nextPoiState = POI_NETWORK_SEARCH; if (logLevel != MUTE) Serial.printf("Changed network configuration to SSID: %s\n", WIFI_SSID[currentNetworkConfig]); } default: if (logLevel != MUTE) { printf("Protocoll Error: Unknown command received: " ); print_cmd(); } break; }; // end setAction break; case 253: // define programs runner.addCmdToProgram(cmd); break; case 252: // directly play scene runner.playScene(cmd[1],cmd[2],cmd[3],cmd[4],cmd[5]); break; // 0...200 default: runner.setPixel(cmd[1], cmd[2], cmd[0], cmd[3], cmd[4], cmd[5]); break; } } bool protocol_is_data(){ return (cmd[0] < 200); } bool protocol_is_sendalive(){ return (cmd[0] == 254 && cmd[1] == 11); } void protocoll_clean_cmd(){ cmdIndex=0; for (int ix=0;ix<6;ix++) cmd[ix]=0; } bool protocoll_cmd_complete(){ return (cmdIndex >= 6); } // wait for data and handle incomming data void protocoll_receive_data(){ // data available if (client.available()){ char c = client.read(); //printf("READ: %d\n", c); // start byte detected if (c== 255) { aliveTickCnt++; if (logLevel != MUTE && !loadingImgData && (aliveTickCnt % aliveTickModulo) == 0) { Serial.print("*"); aliveTickCnt = 0; } protocoll_clean_cmd(); resetTimeout(); } else if (cmdIndex > 5){ Serial.println("Protocol Error. More than 6 bytes transmitted."); } // command else { cmd[cmdIndex++]=(unsigned char)c; } } // no data - disconnect after timeout else if (reachedTimeout()){ client_disconnect(); nextPoiState = POI_CLIENT_CONNECTING; } // no longer connected else if (!client.connected()){ client_disconnect(); // required? nextPoiState = POI_CLIENT_CONNECTING; } } // =============================================== // ==== BUTTONS ==================================== // =============================================== // long click void longPressStart1() { printf("Long press1\n"); if (poiState == POI_IP_CONFIG_OPTION) { nextPoiState = POI_IP_CONFIG; } else if (poiState == POI_IP_CONFIG) { runner.saveIpIncrement(ipIncrement); nextPoiState = POI_NETWORK_SEARCH; } else { // like a reset nextPoiState = POI_INIT; } } // single short click void click1() { if (poiState == POI_IP_CONFIG_OPTION){ nextPoiState = POI_AWAIT_PROGRAM_SYNC; } else if (poiState == POI_IP_CONFIG){ // set back the ip led to black ipIncrement++; if (ipIncrement + 1 > N_POIS){ ipIncrement = 0; // cyclic } printf("IP Increment: %d\n", ipIncrement); // display colored led (first one less bright for each) runner.displayIp(ipIncrement, false); } else if (poiState == POI_NETWORK_SEARCH || poiState == POI_CLIENT_CONNECTING){ if (runner.isProgramActive()){ runner.jumptoSync(); } else { runner.startProg(); } } else if (poiState == POI_AWAIT_PROGRAM_SYNC){ nextPoiState = POI_PLAY_PROGRAM; } } // =============================================== // ==== LOOP ==================================== // =============================================== // state machine with entry actions, state actions and exit actions void loop() { button1.tick(); // read button data bool state_changed = nextPoiState != poiState; // exit actions if (state_changed){ if (logLevel != MUTE) printf("Poi State changed: %d -> %d\n", (poiState), (nextPoiState)); switch(poiState){ case POI_INIT: break; case POI_IP_CONFIG_OPTION: // switch off ip display //runner.displayOff(); break; case POI_IP_CONFIG: runner.playWorm(RAINBOW, N_POIS, 1); break; case POI_NETWORK_SEARCH: break; case POI_CLIENT_CONNECTING: if (nextPoiState == POI_RECEIVING_DATA && !runner.isProgramActive()){ runner.playWummer(GREEN, 3, 4); } break; case POI_RECEIVING_DATA: // switch off led if we leave this state digitalWrite(LED_PIN,LOW); break; case POI_AWAIT_PROGRAM_SYNC: break; case POI_PLAY_PROGRAM: // on exit stop the program runner.pauseProg(); runner.displayOff(); break; default: break; } } // update state // need to do this *here* since following functions may set nextPoiState poiState = nextPoiState; // entry and state actions of state machine switch (poiState){ case POI_INIT: if (state_changed){ // cleanup action runner.finishAction(); } runner.playWorm(RAINBOW, N_PIXELS, 1); // proceed to next state nextPoiState = POI_IP_CONFIG_OPTION; break; case POI_IP_CONFIG_OPTION: // display pale white for 2 seconds // user needs to long press to set ip if (state_changed){ poi_network_display_entered = millis(); // show ip with pale white background runner.displayIp(ipIncrement, true); } currentTime = millis(); if (currentTime-poi_network_display_entered > 5000){ runner.playWorm(RAINBOW, N_POIS, 1); nextPoiState = POI_AWAIT_PROGRAM_SYNC; } break; case POI_IP_CONFIG: if (state_changed){ runner.playWorm(RAINBOW, N_POIS, 1); delay (100); // otherwise the worm may overtake the displayIp runner.displayIp(ipIncrement, false); } // operation is done thru click1 break; case POI_NETWORK_SEARCH: if (state_changed){ digitalWrite(LED_PIN,LOW); wifi_connect_async_init(); if (!runner.isProgramActive()){ runner.playWummer(RED, 2, 0); } } //wifi_connect(); wifi_connect_async(); break; case POI_CLIENT_CONNECTING: if (state_changed){ resetTimeout(); // not when connection is lost during program if (!runner.isProgramActive()){ runner.playWummer(YELLOW, 2, 0); } if (logLevel != MUTE) printf("Waiting for client...\n"); } client_connect(); break; case POI_RECEIVING_DATA: if (state_changed){ digitalWrite(LED_PIN,HIGH); } protocoll_receive_data(); if (protocoll_cmd_complete()){ if (logLevel != MUTE){ if (logLevel == CHATTY || ( !protocol_is_data() && !protocol_is_sendalive() )){ print_cmd(); } } if (protocol_is_data()){ // image data // only print once if (logLevel != MUTE && !loadingImgData){ printf("Reading image data... \n"); // runner.playWorm(PALE_WHITE, N_POIS, 0, false); // async forever // currently required since we write directly into image memory // TODO: add start command for image loading (with scene id) // which will remove current image from memory // TODO: then remove this line again - it does not work anyway ;-) runner.clearImageMap(); } loadingImgData = true; } else { // runner.pauseAction(); // finish worm loadingImgData = false; } // carry out and clean command realize_cmd(); protocoll_clean_cmd(); } break; case POI_AWAIT_PROGRAM_SYNC: if (state_changed){ runner.displayOff(); if (WiFi.status() == WL_CONNECTED){ WiFi.disconnect(); } } // just wait for click to start program break; case POI_PLAY_PROGRAM: if (state_changed){ printf(" Starting program...\n" ); runner.startProg(); } else if (!runner.isProgramActive()){ printf("Program finished\n" ); nextPoiState = POI_AWAIT_PROGRAM_SYNC; } break; default: break; } runner.loop(); }
25.190476
124
0.619861
gmoehler
0fd7f3c25f5a73f90516fe51472759d2046b5be6
3,029
cpp
C++
codes/compiler/llvm/frontend/clang/generate-IR/project.cpp
zhoujiagen/learning-algorithms
de3c17a68319499afc72acea1be92b1c92ea30cd
[ "MIT" ]
null
null
null
codes/compiler/llvm/frontend/clang/generate-IR/project.cpp
zhoujiagen/learning-algorithms
de3c17a68319499afc72acea1be92b1c92ea30cd
[ "MIT" ]
null
null
null
codes/compiler/llvm/frontend/clang/generate-IR/project.cpp
zhoujiagen/learning-algorithms
de3c17a68319499afc72acea1be92b1c92ea30cd
[ "MIT" ]
null
null
null
// $ make // $ ./project ../../data/test.c // // int main() { // char *msg = "Hello, world!\n"; // write(1, msg, 14); // return 0; // } // *** AST Context Stats: // 72 types total. // 2 ConstantArray types, 56 each (112 bytes) // 58 Builtin types, 24 each (1392 bytes) // 4 Complex types, 40 each (160 bytes) // 1 FunctionNoProto types, 40 each (40 bytes) // 5 Pointer types, 40 each (200 bytes) // 2 Record types, 32 each (64 bytes) // Total bytes = 1968 // 0/0 implicit default constructors created // 0/0 implicit copy constructors created // 0/0 implicit copy assignment operators created // 0/0 implicit destructors created // Number of memory regions: 2 // Bytes used: 4698 // Bytes allocated: 8192 // Bytes wasted: 3494 (includes alignment, etc) #include "llvm/Support/CommandLine.h" #include "llvm/Support/Host.h" #include "clang/AST/ASTContext.h" #include "clang/AST/ASTConsumer.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/DiagnosticOptions.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Frontend/ASTConsumers.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/TextDiagnosticPrinter.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/PreprocessorOptions.h" #include "clang/Parse/Parser.h" #include "clang/Parse/ParseAST.h" #include <iostream> using namespace llvm; using namespace clang; static cl::opt<std::string> FileName(cl::Positional, cl::desc("Input file"), cl::Required); int main(int argc, char **argv) { cl::ParseCommandLineOptions(argc, argv, "My simple driver\n"); CompilerInstance CI; DiagnosticOptions diagnosticOptions; CI.createDiagnostics(); //std::shared_ptr<TargetOptions> PTO(new TargetOptions()); std::shared_ptr<clang::TargetOptions> PTO(new clang::TargetOptions()); PTO->Triple = sys::getDefaultTargetTriple(); TargetInfo *PTI = TargetInfo::CreateTargetInfo(CI.getDiagnostics(), PTO); CI.setTarget(PTI); CI.createFileManager(); CI.createSourceManager(CI.getFileManager()); CI.createPreprocessor(TU_Complete); CI.getPreprocessorOpts().UsePredefines = false; //ASTConsumer *astConsumer = CreateASTPrinter(NULL, ""); //CI.setASTConsumer(astConsumer); CI.setASTConsumer(CreateASTPrinter(NULL, "")); CI.createASTContext(); CI.createSema(TU_Complete, NULL); const FileEntry *pFile = CI.getFileManager().getFile(FileName).get(); if (!pFile) { std::cerr << "File not found: " << FileName << std::endl; return 1; } CI.getSourceManager().setMainFileID(CI.getSourceManager().createFileID(pFile, SourceLocation(), SrcMgr::C_User)); CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0); ParseAST(CI.getSema()); CI.getASTContext().PrintStats(); CI.getDiagnosticClient().EndSourceFile(); return 0; }
30.908163
117
0.69726
zhoujiagen
0fdcdc3f8809d90f853ab899ef4f70091d6662d2
1,650
cpp
C++
library/dht11.cpp
Patatje19/IPASS
3a4c8ecc74d043f9d7e3284209bb1760adf56e3e
[ "BSL-1.0" ]
null
null
null
library/dht11.cpp
Patatje19/IPASS
3a4c8ecc74d043f9d7e3284209bb1760adf56e3e
[ "BSL-1.0" ]
null
null
null
library/dht11.cpp
Patatje19/IPASS
3a4c8ecc74d043f9d7e3284209bb1760adf56e3e
[ "BSL-1.0" ]
null
null
null
#include "dht11.hpp" /******************************************************************************/ void dht11::wait_us( const int & time ) { hwlib::wait_us( time ); } void dht11::wait_ms( const int & time ) { hwlib::wait_ms( time ); } /******************************************************************************/ void dht11::data_pin_start() { data_pin.direction_set_output(); data_pin.direction_flush(); data_pin.write(0); data_pin.flush(); wait_ms(18); data_pin.write(1); data_pin.flush(); data_pin.direction_set_input(); data_pin.direction_flush(); wait_us(40); } void dht11::acknowledge_signal() { while( data_pin.read() == 0 ) {}; while( data_pin.read() == 1 ) {}; while( data_pin.read() == 0 ) {}; } void dht11::reading_40bits() { int bit_counter = 0; for( int byte_index = 0; byte_index < 5; byte_index++ ) { for( int byte = 0; byte < 7; byte++ ) { wait_us(50); if( data_pin.read() == 0 ) { bit_counter <<= 1; } else { bit_counter++; bit_counter <<= 1; while( data_pin.read() == 1 ) {}; } while( data_pin.read() == 0 ) {}; } wait_us(50); if( data_pin.read() == 1 ) { bit_counter += 1; while( data_pin.read() == 1 ) {}; } while( data_pin.read() == 0 ) {}; bits[byte_index] = bit_counter; } } /******************************************************************************/ void dht11::read_sensor() { data_pin_start(); acknowledge_signal(); reading_40bits(); } int dht11::get_humidity() { int humidity = bits[0]; return humidity; } int dht11::get_temperature() { int temperature = bits[2]; return temperature; }
14.732143
80
0.513333
Patatje19
0fde18e1640c0e06981c0aaa2d3c8acd534799c8
27,135
cpp
C++
src/files/CFileXML.cpp
RoboticsDesignLab/chai3d
66927fb9c81a173b988e1fc81cf6bfd57d69dcd7
[ "BSD-3-Clause" ]
75
2016-12-22T14:53:01.000Z
2022-03-31T08:04:19.000Z
src/files/CFileXML.cpp
RoboticsDesignLab/chai3d
66927fb9c81a173b988e1fc81cf6bfd57d69dcd7
[ "BSD-3-Clause" ]
6
2017-04-03T21:27:16.000Z
2019-08-28T17:05:23.000Z
src/files/CFileXML.cpp
RoboticsDesignLab/chai3d
66927fb9c81a173b988e1fc81cf6bfd57d69dcd7
[ "BSD-3-Clause" ]
53
2017-03-16T16:38:34.000Z
2022-02-25T14:31:01.000Z
//============================================================================== /* Software License Agreement (BSD License) Copyright (c) 2003-2016, CHAI3D. (www.chai3d.org) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of CHAI3D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \author <http://www.chai3d.org> \author Sebastien Grange \version 3.2.0 $Rev: 2173 $ */ //============================================================================== //------------------------------------------------------------------------------ #include "files/CFileXML.h" //------------------------------------------------------------------------------ #include "pugixml.hpp" using namespace pugi; //------------------------------------------------------------------------------ #include <string> #include <sstream> using namespace std; //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ namespace chai3d { //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #ifndef DOXYGEN_SHOULD_SKIP_THIS //------------------------------------------------------------------------------ struct XML { xml_node m_rootNode; xml_node m_currentNode; xml_document m_document; std::string m_filename; XML() { m_filename = ""; m_currentNode = m_document; } }; //------------------------------------------------------------------------------ #endif // DOXYGEN_SHOULD_SKIP_THIS //------------------------------------------------------------------------------ //============================================================================== /*! This function converts a __string__ into a __long int__. \param a_str Input __string__ to convert. \return The converted __long int__ value if the string is valid, 0 otherwise. */ //============================================================================== static inline long int strToInt(const std::string& a_str) { std::istringstream i(a_str); int x = 0; if (!(i >> x)) return 0; else return x; } //============================================================================== /*! This function converts a __string__ into a __double__. \param a_str Input __string__ to convert. \return The converted __double__ value if the string is valid, 0.0 otherwise. */ //============================================================================== static inline double strToDouble(const std::string& a_str) { std::istringstream i(a_str); double x = 0.0; if (!(i >> x)) return 0.0; else return x; } //============================================================================== /*! Constructor of cFileXML. */ //============================================================================== cFileXML::cFileXML() { m_xml = (void*)(new XML); } //============================================================================== /*! Constructor of cFileXML for loading a specific file. \param a_filename XML file to load. */ //============================================================================== cFileXML::cFileXML(const string& a_filename) { m_xml = (void*)(new XML); loadFromFile(a_filename); } //============================================================================== /*! cFileXML destructor. \note The destructor does not save the XML data back into the file loaded using \ref loadFromFile(). Remember to call \ref saveToFile() as required. */ //============================================================================== cFileXML::~cFileXML() { delete (XML*)(m_xml); } //============================================================================== /*! Load XML data from a given file. The XML data is stored internally, and a pointer to the current XML node is kept internally. The XML data can be navigated using \ref gotoChild(), \ref gotoParent() and other related methods. If the file does not exist, it will be created and written to disk when calling \ref saveToFile(). \param a_filename Name of the XML file to load. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::loadFromFile(const string& a_filename) { // store filename for use by the save() method ((XML*)(m_xml))->m_filename = a_filename; // load XML content (even if file is empty with no document elements) xml_parse_result res = ((XML*)(m_xml))->m_document.load_file(a_filename.c_str()); if (res.status == status_ok || res.status == status_no_document_element) { // make sure the current node pointer is set to the root of the XML data gotoRoot(); // success return true; } // if file loading failed, return failure else { return false; } } //============================================================================== /*! Save the current XML data using the filename saved from the call to \ref loadFromFile(). If the XML data was not loaded from a file, the method fails. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::saveToFile() { // save XML data using the current filename return saveToFile(((XML*)(m_xml))->m_filename); } //============================================================================== /*! Save the current XML data to a given file. If the XML data is empty, or the filename invalid, the method fails. \param a_filename The name of the file to save the XML data to. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::saveToFile(const string& a_filename) { // check that filename is valid if (((XML*)(m_xml))->m_filename == "") { return false; } // save the file if (((XML*)(m_xml))->m_document.save_file(a_filename.c_str())) { return true; } else { return false; } } //============================================================================== /*! Remove all XML data. */ //============================================================================== void cFileXML::clear() { // remove all XML data ((XML*)(m_xml))->m_document.reset(); return gotoRoot(); } //============================================================================== /*! Set the current node pointer to the XML data root. */ //============================================================================== void cFileXML::gotoRoot() { // point to the document root ((XML*)(m_xml))->m_currentNode = ((XML*)(m_xml))->m_document; } //============================================================================== /*! Set the current node pointer to a given child of the current node. Optionally, create the child node if it does not exist. \param a_name Name of the child node to navigate to. \param a_index Index of the child, used when several children have the same name. \param a_create Node creation flag: if the specified child node does not exist and __a_create__ is set to __true__, the node will be created. \return Return 0 if child node existed and operation succeeded, 1 if the child node did not exist and node creation succeded, -1 otherwise. */ //============================================================================== int cFileXML::gotoChild(const string& a_name, int a_index, bool a_create) { // navigate to first child with matching name xml_node node = ((XML*)(m_xml))->m_currentNode.child(a_name.c_str()); // navigate to the matching child at the desired index for (int index=0; index<a_index; index++) { node = node.next_sibling(a_name.c_str()); } // if desired node exists, set current node to it and return 0 if (!node.empty()) { ((XML*)(m_xml))->m_currentNode = node; return 0; } // if desired node does not exist else { // if we are not supposed to create it, return error if (!a_create) { return -1; } // otherwise, create node and return 1 else { ((XML*)(m_xml))->m_currentNode = ((XML*)(m_xml))->m_currentNode.append_child(a_name.c_str()); return 1; } } } //============================================================================== /*! Remove a specific child node from the current node. \param a_name Name of the child node to navigate to. \param a_index Index of the child, used when several children have the same name. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::removeChild(const string& a_name, int a_index) { // navigate to first child with matching name xml_node node = ((XML*)(m_xml))->m_currentNode.child(a_name.c_str()); // navigate to the matching child at the desired index for (int index=0; index<a_index; index++) { node = node.next_sibling(a_name.c_str()); } // if desired node exists, remove it and return success if (!node.empty ()) { ((XML*)(m_xml))->m_currentNode.remove_child(node); return true; } // otherwise, return failure else { return false; } } //============================================================================== /*! Set the current node pointer to the parent of the current node. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::gotoParent() { // set current pointer to parent node ((XML*)(m_xml))->m_currentNode = ((XML*)(m_xml))->m_currentNode.parent(); return true; } //============================================================================== /*! Set the current node pointer to the first child of the current node. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::gotoFirstChild() { // set current pointer to first child xml_node node = ((XML*)(m_xml))->m_currentNode.first_child(); // if child exists, return success if (!node.empty()) { ((XML*)(m_xml))->m_currentNode = node; return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Set the current node pointer to the next sibling of the current node. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::gotoNextSibling() { // set current pointer to next sibling xml_node node = ((XML*)(m_xml))->m_currentNode.next_sibling(); // if node exists, return success if (!node.empty()) { ((XML*)(m_xml))->m_currentNode = node; return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Get the name of the current node. \param a_name Holds the name of the current node on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getName(string& a_name) const { // check that we are not trying to get the root node name if (((XML*)(m_xml))->m_currentNode == ((XML*)(m_xml))->m_document) { return false; } // retrieve current node name a_name = ((XML*)(m_xml))->m_currentNode.name (); return true; } //============================================================================== /*! Set the name of the current node. \param a_name Name to assign to the current node. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setName(const string& a_name) { // check that we are not trying to rename the root node if (((XML*)(m_xml))->m_currentNode == ((XML*)(m_xml))->m_document) { return false; } // otherwise, assign name to current node else { ((XML*)(m_xml))->m_currentNode.set_value(a_name.c_str()); return true; } } //============================================================================== /*! Get the value of the current node. \param a_val Holds the value of the current node on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getValue(bool& a_val) const { string tmp; // retrieve current node value as a string if (getValue(tmp)) { // convert string to bool if (tmp == "1") { a_val = true; } else { a_val = false; } // success return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Get the value of the current node. \param a_val Holds the value of the current node on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getValue(long int& a_val) const { string tmp; // retrieve current node value as a string if (getValue(tmp)) { // convert string to __long int__ a_val = strToInt(tmp); // success return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Get the value of the current node. \param a_val Holds the value of the current node on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getValue(double& a_val) const { string tmp; // retrieve current node value as a string if (getValue(tmp)) { // convert string to __double__ a_val = strToDouble(tmp); // success return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Get the value of the current node. \param a_val Holds the value of the current node on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getValue(string& a_val) const { // check that we are not trying to get the root node value if (((XML*)(m_xml))->m_currentNode == ((XML*)(m_xml))->m_document) { return false; } // retrieve current node value as string a_val = string(((XML*)(m_xml))->m_currentNode.child_value()); // if string is non null, return success if (a_val.length() > 0) { return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Set current node value. \param a_val Node value to assign to current node. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setValue(const bool a_val) { ostringstream o; // create string from value if (a_val) { o << "1"; } else { o << "0"; } // write to current node return setValue(o.str()); } //============================================================================== /*! Set current node value. \param a_val Node value to assign to current node. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setValue(const long int a_val) { ostringstream o; // create string from value o << a_val; // write to current node return setValue(o.str()); } //============================================================================== /*! Set current node value. \param a_val Node value to assign to current node. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setValue(const double a_val) { ostringstream o; // create string from value o << a_val; // write to current node return setValue(o.str()); } //============================================================================== /*! Set current node value. \param a_val Node value to assign to current node. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setValue(const string a_val) { // check that we are not trying to set the value of the root node if (((XML*)(m_xml))->m_currentNode == ((XML*)(m_xml))->m_document) { return false; } // write string to current node value if (((XML*)(m_xml))->m_currentNode.append_child(node_pcdata).set_value (a_val.c_str())) { return true; } else { return false; } } //============================================================================== /*! Get the value of a specific attribute of the current node. \param a_attribute String holding the name of the attribute. \param a_val Holds the value of the requested attribute on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getAttribute(const string& a_attribute, bool& a_val) const { string tmp; // retrieve attribute value as a string if(getAttribute(a_attribute, tmp)) { // convert to __bool__ if (tmp == "1") { a_val = true; } else { a_val = false; } // success return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Get the value of a specific attribute of the current node. \param a_attribute String holding the name of the attribute. \param a_val Holds the value of the requested attribute on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getAttribute(const string& a_attribute, long int& a_val) const { string tmp; // retrieve attribute value as a string if(getAttribute(a_attribute, tmp)) { // convert to __long int__ a_val = strToInt(tmp); // success return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Get the value of a specific attribute of the current node. \param a_attribute String holding the name of the attribute. \param a_val Holds the value of the requested attribute on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getAttribute(const string& a_attribute, double& a_val) const { string tmp; // retrieve attribute value as a string if (getAttribute(a_attribute, tmp)) { // convert to __double__ a_val = strToDouble(tmp); // success return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Get the value of a specific attribute of the current node. \param a_attribute String holding the name of the attribute. \param a_val Holds the value of the requested attribute on success. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::getAttribute(const string& a_attribute, string& a_val) const { // retrieve attribute value a_val = string(((XML*)(m_xml))->m_currentNode.attribute(a_attribute.c_str()).as_string()); // if string is non null, return success if (a_val.length() > 0) { return true; } // otherwise return failure else { return false; } } //============================================================================== /*! Set an attribute value for the current node. \param a_attribute String holding the name of the attribute to set. \param a_val Attribute value to assign to current node attribute. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setAttribute(const string& a_attribute, const bool a_val) { ostringstream o; // convert __string__ if (a_val) { o << "1"; } else { o << "0"; } // write string to attribute return setAttribute(a_attribute, o.str()); } //============================================================================== /*! Set an attribute value for the current node. \param a_attribute String holding the name of the attribute to set. \param a_val Attribute value to assign to current node attribute. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setAttribute(const string& a_attribute, const long int a_val) { ostringstream o; // convert to __string__ o << a_val; // write string to attribute return setAttribute(a_attribute, o.str()); } //============================================================================== /*! Set an attribute value for the current node. \param a_attribute String holding the name of the attribute to set. \param a_val Attribute value to assign to current node attribute. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setAttribute(const string& a_attribute, const double a_val) { ostringstream o; // convert to __string__ o << a_val; // write string to attribute return setAttribute(a_attribute, o.str()); } //============================================================================== /*! Set an attribute value for the current node. \param a_attribute String holding the name of the attribute to set. \param a_val Attribute value to assign to current node attribute. \return __true__ if in case of success, __false__ otherwise. */ //============================================================================== bool cFileXML::setAttribute(const string& a_attribute, const string a_val) { // set attribute value ((XML*)(m_xml))->m_currentNode.append_attribute(a_attribute.c_str()) = a_val.c_str(); // success return true; } //------------------------------------------------------------------------------ } // namespace chai3d //------------------------------------------------------------------------------
28.653643
106
0.462834
RoboticsDesignLab
0fde9557c4e6855f93307aec25137540cf169837
3,543
cpp
C++
core/storage/trie/impl/persistent_trie_batch_impl.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
core/storage/trie/impl/persistent_trie_batch_impl.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
core/storage/trie/impl/persistent_trie_batch_impl.cpp
FlorianFranzen/kagome
27ee11c78767e72f0ecd2c515c77bebc2ff5758d
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "storage/trie/impl/persistent_trie_batch_impl.hpp" #include "scale/scale.hpp" #include "storage/trie/impl/topper_trie_batch_impl.hpp" #include "storage/trie/polkadot_trie/polkadot_trie_cursor.hpp" #include "storage/trie/polkadot_trie/trie_error.hpp" namespace kagome::storage::trie { const common::Buffer EXTRINSIC_INDEX_KEY = common::Buffer{}.put(":extrinsic_index"); // sometimes there is no extrinsic index for a runtime call const common::Buffer NO_EXTRINSIC_INDEX_VALUE{ scale::encode(0xffffffff).value()}; PersistentTrieBatchImpl::PersistentTrieBatchImpl( std::shared_ptr<Codec> codec, std::shared_ptr<TrieSerializer> serializer, boost::optional<std::shared_ptr<changes_trie::ChangesTracker>> changes, std::unique_ptr<PolkadotTrie> trie, RootChangedEventHandler &&handler) : codec_{std::move(codec)}, serializer_{std::move(serializer)}, changes_{std::move(changes)}, trie_{std::move(trie)}, root_changed_handler_{std::move(handler)} { BOOST_ASSERT(codec_ != nullptr); BOOST_ASSERT(serializer_ != nullptr); BOOST_ASSERT((changes_.has_value() && changes_.value() != nullptr) or not changes_.has_value()); BOOST_ASSERT(trie_ != nullptr); if (changes_) { changes_.value()->setExtrinsicIdxGetter( [this]() -> outcome::result<Buffer> { auto res = trie_->get(EXTRINSIC_INDEX_KEY); if (res.has_error() and res.error() == TrieError::NO_VALUE) { return NO_EXTRINSIC_INDEX_VALUE; } return res; }); } } outcome::result<Buffer> PersistentTrieBatchImpl::commit() { OUTCOME_TRY(root, serializer_->storeTrie(*trie_)); root_changed_handler_(root); return std::move(root); } std::unique_ptr<TopperTrieBatch> PersistentTrieBatchImpl::batchOnTop() { return std::make_unique<TopperTrieBatchImpl>(shared_from_this()); } outcome::result<Buffer> PersistentTrieBatchImpl::get( const Buffer &key) const { return trie_->get(key); } std::unique_ptr<BufferMapCursor> PersistentTrieBatchImpl::cursor() { return std::make_unique<PolkadotTrieCursor>(*trie_); } bool PersistentTrieBatchImpl::contains(const Buffer &key) const { return trie_->contains(key); } bool PersistentTrieBatchImpl::empty() const { return trie_->empty(); } outcome::result<void> PersistentTrieBatchImpl::clearPrefix( const Buffer &prefix) { // TODO(Harrm): notify changes tracker return trie_->clearPrefix(prefix); } outcome::result<void> PersistentTrieBatchImpl::put(const Buffer &key, const Buffer &value) { return put(key, Buffer{value}); // would have to copy anyway } outcome::result<void> PersistentTrieBatchImpl::put(const Buffer &key, Buffer &&value) { bool is_new_entry = not trie_->contains(key); auto res = trie_->put(key, value); if (res and changes_.has_value()) { OUTCOME_TRY(changes_.value()->onPut(key, value, is_new_entry)); } return res; } outcome::result<void> PersistentTrieBatchImpl::remove(const Buffer &key) { auto res = trie_->remove(key); if (res and changes_.has_value()) { OUTCOME_TRY(changes_.value()->onRemove(key)); } return res; } } // namespace kagome::storage::trie
33.11215
77
0.662997
FlorianFranzen
0fe1364b9c7335ff265f45a56f0d3014b80576b3
11,438
cpp
C++
src/ramen/core/vma.cpp
helixd2s/Ramen
5b1ebcfdc796b2276b607e71e09c5842d0c52933
[ "MIT" ]
4
2021-05-13T21:12:09.000Z
2022-01-26T18:24:30.000Z
src/ramen/core/vma.cpp
helixd2s/Ramen
5b1ebcfdc796b2276b607e71e09c5842d0c52933
[ "MIT" ]
null
null
null
src/ramen/core/vma.cpp
helixd2s/Ramen
5b1ebcfdc796b2276b607e71e09c5842d0c52933
[ "MIT" ]
null
null
null
#pragma once // // #include <ramen/core/core.hpp> #include <ramen/core/instance.hpp> #include <ramen/core/device.hpp> #include <ramen/core/memoryAllocator.hpp> #include <ramen/core/memory.hpp> #include <ramen/core/consumer.hpp> // //#define VMA_IMPLEMENTATION #include <vk_mem_alloc.h> // namespace rmc { // Handle& MemoryAllocatorObjectVma::constructor() { // auto& device = (vk::Device&)(this->base); auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base); auto& physicalDevice = this->getPhysicalDevice(); auto allocatorObj = std::dynamic_pointer_cast<MemoryAllocatorObject>(shared_from_this()); auto& instance = (vk::Instance&)(deviceObj->base); auto instanceObj = InstanceObject::context->get<InstanceObject>(deviceObj->base); auto& instanceDispatch = deviceObj->dispatch; auto& deviceDispatch = instanceObj->dispatch; // redirect Vulkan API functions VmaVulkanFunctions func = {}; func.vkAllocateMemory = deviceDispatch.vkAllocateMemory; func.vkBindBufferMemory = deviceDispatch.vkBindBufferMemory; func.vkBindBufferMemory2KHR = deviceDispatch.vkBindBufferMemory2; func.vkBindImageMemory = deviceDispatch.vkBindImageMemory; func.vkBindImageMemory2KHR = deviceDispatch.vkBindImageMemory2; func.vkCmdCopyBuffer = deviceDispatch.vkCmdCopyBuffer; func.vkCreateBuffer = deviceDispatch.vkCreateBuffer; func.vkCreateImage = deviceDispatch.vkCreateImage; func.vkDestroyBuffer = deviceDispatch.vkDestroyBuffer; func.vkDestroyImage = deviceDispatch.vkDestroyImage; func.vkFlushMappedMemoryRanges = deviceDispatch.vkFlushMappedMemoryRanges; func.vkFreeMemory = deviceDispatch.vkFreeMemory; func.vkGetBufferMemoryRequirements = deviceDispatch.vkGetBufferMemoryRequirements; func.vkGetBufferMemoryRequirements2KHR = deviceDispatch.vkGetBufferMemoryRequirements2; func.vkGetImageMemoryRequirements = deviceDispatch.vkGetImageMemoryRequirements; func.vkGetImageMemoryRequirements2KHR = deviceDispatch.vkGetImageMemoryRequirements2; func.vkGetPhysicalDeviceMemoryProperties = instanceDispatch.vkGetPhysicalDeviceMemoryProperties; func.vkGetPhysicalDeviceMemoryProperties2KHR = instanceDispatch.vkGetPhysicalDeviceMemoryProperties2; func.vkGetPhysicalDeviceProperties = instanceDispatch.vkGetPhysicalDeviceProperties; func.vkInvalidateMappedMemoryRanges = deviceDispatch.vkInvalidateMappedMemoryRanges; func.vkMapMemory = deviceDispatch.vkMapMemory; func.vkUnmapMemory = deviceDispatch.vkUnmapMemory; // VmaAllocatorCreateInfo vmaInfo = {}; vmaInfo.pVulkanFunctions = &func; vmaInfo.device = device; vmaInfo.instance = instance; vmaInfo.flags = VMA_ALLOCATOR_CREATE_BUFFER_DEVICE_ADDRESS_BIT; vmaInfo.physicalDevice = physicalDevice; // auto result = vk::Result(vmaCreateAllocator(&vmaInfo, &(VmaAllocator&)this->handle)); if (result != vk::Result::eSuccess) { vk::throwResultException(result, "Failed to create VMA allocator..."); }; // return this->handle; }; // MemoryAllocation MemoryAllocatorObjectVma::allocateMemory( MemoryAllocationInfo const& memAllocInfo) { VmaAllocationInfo allocInfo = {}; VmaAllocationCreateInfo allocCreateInfo = { .usage = reinterpret_cast<const VmaMemoryUsage&>(memAllocInfo.memoryUsage) }; if (allocCreateInfo.usage != VMA_MEMORY_USAGE_GPU_ONLY) { allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; }; // auto& device = (vk::Device&)(this->base); auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base); auto allocatorObj = std::dynamic_pointer_cast<MemoryAllocatorObject>(shared_from_this()); std::shared_ptr<BufferObject> bufferObj = {}; std::shared_ptr<ImageObject> imageObj = {}; // auto requirements = memAllocInfo.requirements ? memAllocInfo.requirements.value() : vk::MemoryRequirements2{}; // VmaAllocation allocation_ptr = nullptr; auto result = vk::Result::eSuccess; if (memAllocInfo.dedicated && memAllocInfo.dedicated->buffer && bufferObj) { bufferObj = deviceObj->getRaw<BufferObject>(memAllocInfo.dedicated->buffer); requirements = device.getBufferMemoryRequirements2(vk::BufferMemoryRequirementsInfo2{ .buffer = bufferObj->handle }); result = vk::Result(vmaAllocateMemoryForBuffer((const VmaAllocator&)this->handle, bufferObj->handle, &allocCreateInfo, &allocation_ptr, &allocInfo)); } else if (memAllocInfo.dedicated && memAllocInfo.dedicated->image && imageObj) { imageObj = deviceObj->getRaw<ImageObject>(memAllocInfo.dedicated->image); requirements = device.getImageMemoryRequirements2(vk::ImageMemoryRequirementsInfo2{ .image = imageObj->handle }); result = vk::Result(vmaAllocateMemoryForImage((const VmaAllocator&)this->handle, bufferObj->handle, &allocCreateInfo, &allocation_ptr, &allocInfo)); } else if (memAllocInfo.requirements) { result = vk::Result(vmaAllocateMemory((const VmaAllocator&)this->handle, (VkMemoryRequirements*)&requirements.memoryRequirements, &allocCreateInfo, &allocation_ptr, &allocInfo)); }; // vk::throwResultException(result, "VMA memory allocation failed..."); // auto deviceMemoryObj = this->getRaw<DeviceMemoryObject>(allocInfo.deviceMemory); //deviceMemoryObj->allocation = allocation_ptr; deviceMemoryObj->mapped = shift(allocInfo.pMappedData, -allocInfo.offset); deviceMemoryObj->makeAllocation(allocInfo.offset, allocInfo.size); // auto memoryAllocation = MemoryAllocation{ allocInfo.deviceMemory, allocInfo.offset, allocInfo.size, uintptr_t(allocation_ptr) }; if (imageObj) { imageObj->bindMemory(memoryAllocation); imageObj->destructor = [device, image = imageObj->handle, allocator = (const VmaAllocator&)this->handle, allocation = allocation_ptr](Handle const& base, Handle const& handle) { device.destroyImage(image); vmaFreeMemory(allocator, allocation); }; }; if (bufferObj) { bufferObj->bindMemory(memoryAllocation); bufferObj->destructor = [device, buffer = bufferObj->handle, allocator = (const VmaAllocator&)this->handle, allocation = allocation_ptr](Handle const& base, Handle const& handle) { device.destroyBuffer(buffer); vmaFreeMemory(allocator, allocation); }; }; return memoryAllocation; }; // vk::Buffer& MemoryAllocatorObjectVma::allocateAndCreateBuffer( std::shared_ptr<vkh::BufferCreateHelper> const& info_) { MemoryAllocationInfo& memAllocInfo = info_->allocInfo.value(); VmaAllocationInfo allocInfo = {}; VmaAllocationCreateInfo allocCreateInfo = { .usage = reinterpret_cast<const VmaMemoryUsage&>(memAllocInfo.memoryUsage) }; if (allocCreateInfo.usage != VMA_MEMORY_USAGE_GPU_ONLY) { allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; }; // auto& device = (vk::Device&)(this->base); auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base); auto allocatorObj = std::dynamic_pointer_cast<MemoryAllocatorObject>(shared_from_this()); // auto& info = info_->value(); info.usage |= vk::BufferUsageFlagBits::eAccelerationStructureStorageKHR | vk::BufferUsageFlagBits::eStorageBuffer; if (allocCreateInfo.usage == VMA_MEMORY_USAGE_GPU_ONLY) { info.usage |= vk::BufferUsageFlagBits::eShaderDeviceAddress; }; // auto bufferObj = std::make_shared<BufferObject>(this->base, info_); // manually, no sense //memAllocInfo.buffer = buffer->buffer; // VmaAllocation allocation_ptr = nullptr; auto result = vk::Result(vmaCreateBuffer((const VmaAllocator&)this->handle, (const VkBufferCreateInfo*)&(info), &allocCreateInfo, (VkBuffer*)&bufferObj->handle, &allocation_ptr, nullptr)); if (result != vk::Result::eSuccess) { vk::throwResultException(result, "VMA buffer allocation failed..."); }; vmaGetAllocationInfo((const VmaAllocator&)this->handle, allocation_ptr, &allocInfo); // auto deviceMemoryObj = this->getRaw<DeviceMemoryObject>(allocInfo.deviceMemory); deviceMemoryObj->makeAllocation(allocInfo.offset, allocInfo.size); deviceMemoryObj->mapped = shift(allocInfo.pMappedData, -allocInfo.offset); // deviceObj->setMap(bufferObj); bufferObj->bindMemory(MemoryAllocation{ allocInfo.deviceMemory, allocInfo.offset, allocInfo.size }, false); bufferObj->destructor = [allocator = (const VmaAllocator&)this->handle, allocation = allocation_ptr, buffer = bufferObj->handle](Handle const& base, Handle const& handle){ vmaDestroyBuffer(allocator,buffer,allocation); }; // return bufferObj->handle; }; // vk::Image& MemoryAllocatorObjectVma::allocateAndCreateImage( std::shared_ptr<vkh::ImageCreateHelper> const& info_) { MemoryAllocationInfo& memAllocInfo = info_->allocInfo.value(); VmaAllocationInfo allocInfo = {}; VmaAllocationCreateInfo allocCreateInfo = { .usage = reinterpret_cast<const VmaMemoryUsage&>(memAllocInfo.memoryUsage) }; if (allocCreateInfo.usage != VMA_MEMORY_USAGE_GPU_ONLY) { allocCreateInfo.flags = VMA_ALLOCATION_CREATE_MAPPED_BIT; }; // auto& device = (vk::Device&)(this->base); auto deviceObj = InstanceObject::context->get<DeviceObject>(this->base); auto allocatorObj = std::dynamic_pointer_cast<MemoryAllocatorObject>(shared_from_this()); // auto& info = info_->value(); // currently only textures supported info.usage |= vk::ImageUsageFlagBits::eSampled; // auto imageObj = std::make_shared<ImageObject>(this->base, info_); // manually, no sense //memAllocInfo.image = image->image; // VmaAllocation allocation_ptr = nullptr; auto result = vk::Result(vmaCreateImage((const VmaAllocator&)this->handle, (const VkImageCreateInfo*)&(info), &allocCreateInfo, (VkImage*)&imageObj->handle, &allocation_ptr, nullptr)); if (result != vk::Result::eSuccess) { vk::throwResultException(result, "VMA image allocation failed..."); }; vmaGetAllocationInfo((const VmaAllocator&)this->handle, allocation_ptr, &allocInfo); // auto deviceMemoryObj = this->getRaw<DeviceMemoryObject>(allocInfo.deviceMemory); deviceMemoryObj->makeAllocation(allocInfo.offset, allocInfo.size); deviceMemoryObj->mapped = shift(allocInfo.pMappedData, -allocInfo.offset); // deviceObj->setMap(imageObj); imageObj->bindMemory(MemoryAllocation{ allocInfo.deviceMemory, allocInfo.offset, allocInfo.size }, false); imageObj->destructor = [allocator = (const VmaAllocator&)this->handle, allocation = allocation_ptr, image = imageObj->handle](Handle const& base, Handle const& handle){ vmaDestroyImage(allocator,image,allocation); }; // return imageObj->handle; }; };
50.610619
320
0.698811
helixd2s
0fe1a0b3be2149ccd89af9f431b4c3e8d2865a05
1,918
hpp
C++
include/xtr/detail/commands/regex_matcher.hpp
uilianries/xtr
b1dccc51b024369e6c1a2f6d3fcf5f405735289b
[ "MIT" ]
null
null
null
include/xtr/detail/commands/regex_matcher.hpp
uilianries/xtr
b1dccc51b024369e6c1a2f6d3fcf5f405735289b
[ "MIT" ]
null
null
null
include/xtr/detail/commands/regex_matcher.hpp
uilianries/xtr
b1dccc51b024369e6c1a2f6d3fcf5f405735289b
[ "MIT" ]
null
null
null
// Copyright 2021 Chris E. Holloway // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #ifndef XTR_DETAIL_COMMANDS_REGEX_MATCHER_HPP #define XTR_DETAIL_COMMANDS_REGEX_MATCHER_HPP #include "matcher.hpp" #include <regex.h> namespace xtr::detail { class regex_matcher; } class xtr::detail::regex_matcher : public matcher { public: regex_matcher(const char* pattern, bool ignore_case, bool extended); ~regex_matcher(); regex_matcher(const regex_matcher&) = delete; regex_matcher& operator=(const regex_matcher&) = delete; bool valid() const override; void error_reason(char* buf, std::size_t bufsz) const override; bool operator()(const char* str) const override; private: // std::regex isn't used because it isn't possible to use it without // exceptions (it throws if an expression is invalid). ::regex_t regex_; int errnum_; }; #endif
33.649123
81
0.749739
uilianries
0fe2f89c514b08bccb5aff081cde3d12f09a7797
833
hpp
C++
libs/core/include/fcppt/metal/set/make.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/metal/set/make.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/metal/set/make.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_METAL_SET_MAKE_HPP_INCLUDED #define FCPPT_METAL_SET_MAKE_HPP_INCLUDED #include <fcppt/metal/set/empty.hpp> #include <fcppt/metal/set/insert.hpp> #include <fcppt/config/external_begin.hpp> #include <metal/lambda/lambda.hpp> #include <metal/list/accumulate.hpp> #include <metal/list/list.hpp> #include <metal/map/map.hpp> #include <fcppt/config/external_end.hpp> namespace fcppt { namespace metal { namespace set { template< typename... Types > using make = ::metal::accumulate< ::metal::lambda< fcppt::metal::set::insert >, ::metal::map<>, ::metal::list< Types... > >; } } } #endif
17.354167
61
0.713085
pmiddend
0fe35f33be4684aa233a03f76cc01a766a96d263
722
hpp
C++
pythran/pythonic/include/numpy/sort.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/sort.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/numpy/sort.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_NUMPY_SORT_HPP #define PYTHONIC_INCLUDE_NUMPY_SORT_HPP #include <algorithm> #include "pythonic/utils/proxy.hpp" #include "pythonic/types/numexpr_to_ndarray.hpp" #include "pythonic/types/ndarray.hpp" namespace pythonic { namespace numpy { template <class T> bool _comp(T const &i, T const &j); template <class T> bool _comp(std::complex<T> const &i, std::complex<T> const &j); template <class T, size_t N> void _sort(types::ndarray<T, N> &out, long axis); template <class T, size_t N> types::ndarray<T, N> sort(types::ndarray<T, N> const &expr, long axis = -1); NUMPY_EXPR_TO_NDARRAY0_DECL(sort); PROXY_DECL(pythonic::numpy, sort); } } #endif
21.878788
80
0.696676
artas360
0fe4df0e9e941947aeb6d9ce46c3ddf4b52bed92
5,126
cpp
C++
src/libs/ml_models/src/support_vector_machine.cpp
boazsade/machine_learinig_models
eb1f9eda0e4e25a6d028b25682dfb20628a20624
[ "MIT" ]
null
null
null
src/libs/ml_models/src/support_vector_machine.cpp
boazsade/machine_learinig_models
eb1f9eda0e4e25a6d028b25682dfb20628a20624
[ "MIT" ]
null
null
null
src/libs/ml_models/src/support_vector_machine.cpp
boazsade/machine_learinig_models
eb1f9eda0e4e25a6d028b25682dfb20628a20624
[ "MIT" ]
null
null
null
#include "libs/ml_models/support_vector_machine.h" #include "svm_impl/svm_model.h" #include "svm_impl/classifiers_generator.h" #include "svm_impl/regressions_generator.h" //#include "shared_operations.hpp" #include "utils/missing_values.hpp" #include <opencv2/core.hpp> #include <opencv/ml.h> #include <iostream> #include <boost/assign.hpp> #include <map> //#define _PRINT_MODEL_PARAMS #ifdef _PRINT_MODEL_PARAMS #include <boost/range/algorithm/copy.hpp> #include <iterator> #endif // _PRINT_MODEL_PARAMS namespace mlmodels { namespace { support_vector_machine::model_type generate_reg_model(const training_data& data, const class_data& classes, const regression_svm::args& a) { if (a.type != svm::type_t::NU_SVR) { return support_vector_machine::model_type{}; } switch (a.kernel) { case svm::kernel_type::LINEAR: return svm::regression::create_model( svm::regression::nu_linear_train{}, data, classes ); case svm::kernel_type::POLY: return svm::regression::create_model( svm::regression::nu_poly_train{}, data, classes ); case svm::kernel_type::RBF: return svm::regression::create_model( svm::regression::nu_rbf_train{}, data, classes ); case svm::kernel_type::SIGMOID: return svm::regression::create_model( svm::regression::nu_sig_train{}, data, classes ); default: return support_vector_machine::model_type{}; } } support_vector_machine::model_type generate_class_model(const training_data& data, const class_data& classes, const classifier_svm::args& a) { if (a.type != svm::type_t::C_SVC) { return support_vector_machine::model_type{}; } switch (a.kernel) { case svm::kernel_type::LINEAR: return svm::classifier::create_model( svm::classifier::c_linear_train{}, data, classes ); case svm::kernel_type::POLY: return svm::classifier::create_model( svm::classifier::c_poly_train{}, data, classes ); case svm::kernel_type::RBF: return svm::classifier::create_model( svm::classifier::c_rbf_train{}, data, classes ); case svm::kernel_type::SIGMOID: return svm::classifier::create_model( svm::classifier::c_sig_train{}, data, classes ); default: return support_vector_machine::model_type{}; } } } // end of local namespce svm::kernel_type support_vector_machine::string2kernel(const std::string& from) { return svm::str2kernel(from); } svm::type_t support_vector_machine::string2type(const std::string& from) { return svm::str2type(from); } classifier_svm::model_type classifier_svm::train(const training_data& data, const class_data& classes, const args& a) const { return generate_class_model(data, classes, a); } support_vector_machine::_args::_args(svm::kernel_type k, svm::type_t t) : kernel(k), type(t) { } support_vector_machine::model_type support_vector_machine::load(const char* from) { return svm::load(from); } value_type support_vector_machine::predict(model_type model, const class_data& samples) const { if (model) { return svm::predict(model, samples); } return missing_value<value_type>(); } bool support_vector_machine::predict(model_type model, const testing_data& data, testing_result& predications) const { if (model) { predications = svm::predict(model, data); return not predications.empty(); } else { return false; } } support_vector_machine::row_output support_vector_machine::test(model_type model, const testing_data& data, int ) const { if (model) { return svm::test(model, data); } else { return row_output{}; } } void save_model(support_vector_machine::model_type model, const char* path) { if (model) { svm::save(model, path); } } classifier_svm::args::args() : base_t{} { type = svm::C_SVC; } classifier_svm::args::args(svm::kernel_type k) : base_t{k, svm::C_SVC} { } classifier_svm::row_output classifier_svm::test(model_type model, const testing_data& data, int classes) const { return base_t::test(model, data, classes); } regression_svm::args::args() : base_t{} { type = svm::NU_SVR; } regression_svm::args::args(svm::kernel_type k) : base_t{k, svm::NU_SVR} { } regression_svm::model_type regression_svm::train(const training_data& data, const class_data& classes, const args& a) const { return generate_reg_model(data, classes, a); } regression_svm::row_output regression_svm::test(model_type model, const testing_data& data, int ) const { return base_t::test(model, data, -1); } } // end of namespace mlmodels
27.265957
103
0.635193
boazsade
0fe61f620caab81f329ce22f1c247e32c1282610
1,178
cc
C++
ui/events/test/keyboard_layout.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
ui/events/test/keyboard_layout.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
ui/events/test/keyboard_layout.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// 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 "ui/events/test/keyboard_layout.h" #include "base/check_op.h" #include "base/notreached.h" #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" // nogncheck #include "ui/events/ozone/layout/stub/stub_keyboard_layout_engine.h" // nogncheck #endif namespace ui { ScopedKeyboardLayout::ScopedKeyboardLayout(KeyboardLayout layout) { #if defined(USE_OZONE) if (features::IsUsingOzonePlatform()) { CHECK_EQ(layout, KEYBOARD_LAYOUT_ENGLISH_US); auto keyboard_layout_engine = std::make_unique<StubKeyboardLayoutEngine>(); scoped_keyboard_layout_engine_ = std::make_unique<ScopedKeyboardLayoutEngine>( std::move(keyboard_layout_engine)); } #elif defined(OS_WIN) || defined(OS_MAC) original_layout_ = GetActiveLayout(); ActivateLayout(GetPlatformKeyboardLayout(layout)); #else NOTIMPLEMENTED(); #endif } ScopedKeyboardLayout::~ScopedKeyboardLayout() { #if defined(OS_WIN) || defined(OS_MAC) ActivateLayout(original_layout_); #endif } } // namespace ui
28.731707
82
0.760611
mghgroup
0fe6bbacbd82c8334b4fba0b8a558f66374027fd
2,851
cc
C++
agent/php5/openrasp_ini.cc
rosag49/openrasp
793bb33721abcb926bead77b32bee608a951268a
[ "Apache-2.0" ]
1
2020-12-18T01:04:20.000Z
2020-12-18T01:04:20.000Z
agent/php5/openrasp_ini.cc
threedr3am/openrasp
c9febf767174608314793607bcc503c9090f3bac
[ "Apache-2.0" ]
null
null
null
agent/php5/openrasp_ini.cc
threedr3am/openrasp
c9febf767174608314793607bcc503c9090f3bac
[ "Apache-2.0" ]
1
2020-09-28T06:21:03.000Z
2020-09-28T06:21:03.000Z
/* * Copyright 2017-2019 Baidu Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "openrasp_ini.h" #include <limits> #include "utils/string.h" #include "utils/regex.h" Openrasp_ini openrasp_ini; static const int MIN_HEARTBEAT_INTERVAL = 10; const char *Openrasp_ini::APPID_REGEX = "^[0-9a-fA-F]{40}$"; const char *Openrasp_ini::APPSECRET_REGEX = "^[0-9a-zA-Z_-]{43,45}$"; const char *Openrasp_ini::RASPID_REGEX = "^[0-9a-zA-Z]{16,512}$"; bool Openrasp_ini::verify_remote_management_ini(std::string &error) { if (openrasp::empty(backend_url)) { error = std::string(_("openrasp.backend_url is required when remote management is enabled.")); return false; } if (openrasp::empty(app_id)) { error = std::string(_("openrasp.app_id is required when remote management is enabled.")); return false; } else { if (!openrasp::regex_match(app_id, Openrasp_ini::APPID_REGEX)) { error = std::string(_("openrasp.app_id must be exactly 40 characters long.")); return false; } } if (openrasp::empty(app_secret)) { error = std::string(_("openrasp.app_secret is required when remote management is enabled.")); return false; } else { if (!openrasp::regex_match(app_secret, Openrasp_ini::APPSECRET_REGEX)) { error = std::string(_("openrasp.app_secret configuration format is incorrect.")); return false; } } return true; } bool Openrasp_ini::verify_rasp_id() { if (!openrasp::empty(rasp_id)) { return openrasp::regex_match(rasp_id, Openrasp_ini::RASPID_REGEX); } return true; } ZEND_INI_MH(OnUpdateOpenraspCString) { *reinterpret_cast<char **>(mh_arg1) = new_value_length ? new_value : nullptr; return SUCCESS; } ZEND_INI_MH(OnUpdateOpenraspBool) { bool *tmp = reinterpret_cast<bool *>(mh_arg1); *tmp = strtobool(new_value, new_value_length); return SUCCESS; } ZEND_INI_MH(OnUpdateOpenraspHeartbeatInterval) { long tmp = zend_atol(new_value, new_value_length); if (tmp < MIN_HEARTBEAT_INTERVAL || tmp > 1800) { return FAILURE; } *reinterpret_cast<int *>(mh_arg1) = tmp; return SUCCESS; } bool strtobool(const char *str, int len) { return atoi(str); }
28.227723
102
0.668537
rosag49
0fe7686d64c3f0af29b4768d00d71acddbc4595f
3,869
cpp
C++
VC/ResourceManager.cpp
UnknownArkish/MyGraphicsFramework-SZU-
15bcb916712eabd4586464423af4668bc5704d20
[ "MIT" ]
7
2019-08-03T18:35:05.000Z
2022-02-24T11:04:19.000Z
VC/ResourceManager.cpp
UnknownArkish/MyGraphicsFramework-SZU-
15bcb916712eabd4586464423af4668bc5704d20
[ "MIT" ]
null
null
null
VC/ResourceManager.cpp
UnknownArkish/MyGraphicsFramework-SZU-
15bcb916712eabd4586464423af4668bc5704d20
[ "MIT" ]
2
2019-09-06T04:59:43.000Z
2020-12-30T12:08:44.000Z
/******************************************************************* ** This code is part of Breakout. ** ** Breakout is free software: you can redistribute it and/or modify ** it under the terms of the CC BY 4.0 license as published by ** Creative Commons, either version 4 of the License, or (at your ** option) any later version. ******************************************************************/ #include"include\ResourceManager.h" #include <iostream> #include <sstream> #include <fstream> #include<stb_image.h> #include<iostream> // Instantiate static variables std::map<std::string, Texture2D> ResourceManager::Textures; std::map<std::string, Shader> ResourceManager::Shaders; Shader ResourceManager::LoadShader(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile, std::string name) { Shaders[name] = loadShaderFromFile(vShaderFile, fShaderFile, gShaderFile); return Shaders[name]; } Shader ResourceManager::GetShader(std::string name) { return Shaders[name]; } Texture2D ResourceManager::LoadTexture(const GLchar *file, GLboolean alpha, std::string name) { Textures[name] = loadTextureFromFile(file, alpha); return Textures[name]; } Texture2D ResourceManager::GetTexture(std::string name) { return Textures[name]; } void ResourceManager::Clear() { // (Properly) delete all shaders for (auto iter : Shaders) glDeleteProgram(iter.second.ID); // (Properly) delete all textures for (auto iter : Textures) glDeleteTextures(1, &iter.second.ID); } Shader ResourceManager::loadShaderFromFile(const GLchar *vShaderFile, const GLchar *fShaderFile, const GLchar *gShaderFile) { // 1. Retrieve the vertex/fragment source code from filePath std::string vertexCode; std::string fragmentCode; std::string geometryCode; try { // Open files std::ifstream vertexShaderFile(vShaderFile); std::ifstream fragmentShaderFile(fShaderFile); std::stringstream vShaderStream, fShaderStream; // Read file's buffer contents into streams vShaderStream << vertexShaderFile.rdbuf(); fShaderStream << fragmentShaderFile.rdbuf(); // close file handlers vertexShaderFile.close(); fragmentShaderFile.close(); // Convert stream into string vertexCode = vShaderStream.str(); fragmentCode = fShaderStream.str(); // If geometry shader path is present, also load a geometry shader if (gShaderFile != nullptr) { std::ifstream geometryShaderFile(gShaderFile); std::stringstream gShaderStream; gShaderStream << geometryShaderFile.rdbuf(); geometryShaderFile.close(); geometryCode = gShaderStream.str(); } } catch (std::exception e) { std::cout << "ERROR::SHADER: Failed to read shader files" << std::endl; } const GLchar *vShaderCode = vertexCode.c_str(); const GLchar *fShaderCode = fragmentCode.c_str(); const GLchar *gShaderCode = geometryCode.c_str(); // 2. Now create shader object from source code Shader shader; shader.Compile(vShaderCode, fShaderCode, gShaderFile != nullptr ? gShaderCode : nullptr); return shader; } Texture2D ResourceManager::loadTextureFromFile(const GLchar *file, GLboolean alpha) { // Create Texture object Texture2D texture; if (alpha) { texture.Internal_Format = GL_RGBA; texture.Image_Format = GL_RGBA; } // Load image int width, height, nrChannels; unsigned char *data = stbi_load(file, &width, &height, &nrChannels, 0); if (data) { // Now generate texture texture.Generate(width, height, data); // And finally free image data stbi_image_free(data); } else { std::cout << "Can't not open Texture!!!" << std::endl; } return texture; }
31.713115
133
0.65986
UnknownArkish
0fe8f273dda4d822b5b137501a0ac8db590eaf0a
370
hpp
C++
extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.hpp
rh101/engine-x
17ad9829dd410c689857760b6ece89d99e877a95
[ "MIT" ]
244
2018-05-24T07:17:29.000Z
2022-03-31T15:51:43.000Z
extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.hpp
rh101/engine-x
17ad9829dd410c689857760b6ece89d99e877a95
[ "MIT" ]
172
2020-02-21T08:56:42.000Z
2021-05-12T03:18:40.000Z
extensions/scripting/lua-bindings/auto/lua_cocos2dx_navmesh_auto.hpp
rh101/engine-x
17ad9829dd410c689857760b6ece89d99e877a95
[ "MIT" ]
98
2019-02-20T01:14:46.000Z
2022-03-22T16:20:51.000Z
#include "base/ccConfig.h" #if CC_USE_NAVMESH #ifndef __cocos2dx_navmesh_h__ #define __cocos2dx_navmesh_h__ #ifdef __cplusplus extern "C" { #endif #include "tolua++.h" #ifdef __cplusplus } #endif int register_all_cocos2dx_navmesh(lua_State* tolua_S); #endif // __cocos2dx_navmesh_h__ #endif //#if CC_USE_NAVMESH
5.068493
54
0.675676
rh101
0fea4341956b1bb8901b48c3d053226e782b29ee
4,332
cpp
C++
dev/Gems/Vegetation/Code/Source/StaticVegetationSystemComponent.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
8
2019-10-07T16:33:47.000Z
2020-12-07T03:59:58.000Z
dev/Gems/Vegetation/Code/Source/StaticVegetationSystemComponent.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
null
null
null
dev/Gems/Vegetation/Code/Source/StaticVegetationSystemComponent.cpp
jeikabu/lumberyard
07228c605ce16cbf5aaa209a94a3cb9d6c1a4115
[ "AML" ]
4
2019-08-05T07:25:46.000Z
2020-12-07T05:12:55.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include "Vegetation_precompiled.h" #include <StaticVegetationSystemComponent.h> #include <MathConversion.h> #include <IEntityRenderState.h> #include <AzCore/Serialization/SerializeContext.h> #include <AzCore/Serialization/EditContext.h> namespace Vegetation { void StaticVegetationSystemComponent::GetProvidedServices(AZ::ComponentDescriptor::DependencyArrayType& services) { } void StaticVegetationSystemComponent::GetIncompatibleServices(AZ::ComponentDescriptor::DependencyArrayType& services) { } void StaticVegetationSystemComponent::GetRequiredServices(AZ::ComponentDescriptor::DependencyArrayType& services) { } void StaticVegetationSystemComponent::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serialize = azrtti_cast<AZ::SerializeContext*>(context); if (serialize) { serialize->Class<StaticVegetationSystemComponent, AZ::Component>() ->Version(0) ; if (AZ::EditContext* editContext = serialize->GetEditContext()) { editContext->Class<StaticVegetationSystemComponent>("Static Vegetation System", "Manages interactions between the legacy and dynamic vegetation systems and instances") ->ClassElement(AZ::Edit::ClassElements::EditorData, "") ->Attribute(AZ::Edit::Attributes::Category, "Vegetation") ->Attribute(AZ::Edit::Attributes::AppearsInAddComponentMenu, AZ_CRC("System", 0xc94d118b)) ->Attribute(AZ::Edit::Attributes::AutoExpand, true) ; } } } void StaticVegetationSystemComponent::Init() { } void StaticVegetationSystemComponent::Activate() { StaticVegetationNotificationBus::Handler::BusConnect(); StaticVegetationRequestBus::Handler::BusConnect(); } void StaticVegetationSystemComponent::Deactivate() { StaticVegetationNotificationBus::Handler::BusDisconnect(); StaticVegetationRequestBus::Handler::BusDisconnect(); } void StaticVegetationSystemComponent::InstanceAdded(UniqueVegetationInstancePtr vegetationInstance, AZ::Aabb aabb) { AZStd::unique_lock<decltype(m_mapMutex)> mapScopeLock(m_mapMutex); ++m_vegetationUpdateCount; m_vegetation[vegetationInstance] = { aabb.GetCenter(), aabb }; } void StaticVegetationSystemComponent::InstanceRemoved(UniqueVegetationInstancePtr vegetationInstance, AZ::Aabb aabb) { AZStd::unique_lock<decltype(m_mapMutex)> mapScopeLock(m_mapMutex); ++m_vegetationUpdateCount; m_vegetation.erase(vegetationInstance); } void StaticVegetationSystemComponent::VegetationCleared() { AZStd::unique_lock<decltype(m_mapMutex)> mapScopeLock(m_mapMutex); ++m_vegetationUpdateCount; m_vegetation.clear(); } MapHandle StaticVegetationSystemComponent::GetStaticVegetation() { if (m_vegetationUpdateCount != m_vegetationCopyUpdateCount) { AZStd::unique_lock<decltype(m_mapMutex)> mapScopeLock(m_mapMutex); AZStd::unique_lock<decltype(m_mapCopyReadMutex)> mapCopyScopeLock(m_mapCopyReadMutex); if (m_vegetationUpdateCount != m_vegetationCopyUpdateCount) // check again after lock in case we waited for another thread to finish updating. { m_vegetationReturnCopy = m_vegetation; m_vegetationCopyUpdateCount = m_vegetationUpdateCount; } } return MapHandle{ &m_vegetationReturnCopy, m_vegetationCopyUpdateCount, &m_mapCopyReadMutex }; // need to do this outside the read scope lock above as the MapHandle locks the ReadMutex on construction } }
37.344828
208
0.701062
jeikabu
0feb626eee51bf8499ad74c26240428b4391c59f
6,724
cc
C++
rgbReconstruction/rgbReconstruct.cc
TracyHuang/lightfield_SFFT
9e5742ae597cd80938601b895fc62b9c06edbab9
[ "MIT" ]
2
2016-12-11T08:21:35.000Z
2019-03-16T04:07:21.000Z
rgbReconstruction/rgbReconstruct.cc
TracyHuang/lightfield_SFFT
9e5742ae597cd80938601b895fc62b9c06edbab9
[ "MIT" ]
null
null
null
rgbReconstruction/rgbReconstruct.cc
TracyHuang/lightfield_SFFT
9e5742ae597cd80938601b895fc62b9c06edbab9
[ "MIT" ]
1
2017-04-11T17:14:47.000Z
2017-04-11T17:14:47.000Z
#include <iostream> #include <stdio.h> #include <string> #include <cstring> #include <errno.h> #include <vector> #include <sys/types.h> #include <dirent.h> #include <sys/stat.h> #include <unistd.h> #include <sstream> #include <cv.h> #include <climits> #include <highgui.h> #include "opencv2/core/core_c.h" #include "opencv2/core/core.hpp" #include "opencv2/flann/miniflann.hpp" #include "opencv2/imgproc/imgproc_c.h" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/video/video.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/objdetect/objdetect.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/ml/ml.hpp" #include "opencv2/highgui/highgui_c.h" #include "opencv2/highgui/highgui.hpp" #include "opencv2/contrib/contrib.hpp" using namespace std; using namespace cv; #define MAX_DIRECTORY_NAME_LENGTH 100 namespace patch { template < typename T > std::string to_string( const T& n ) { std::ostringstream stm ; stm << n ; return stm.str() ; } } int isFile(const char *path) { struct stat buf; stat(path, &buf); return S_ISREG(buf.st_mode); } int getFileList(string dir, vector<string> &files) { DIR *dp; struct dirent *dirp; if((dp = opendir(dir.c_str())) == NULL) { cout << "Error(" << errno << ") opening " << dir << endl; return errno; } string filePath; while ((dirp = readdir(dp)) != NULL) { filePath = dir + string(dirp->d_name); if (isFile(filePath.c_str())) { files.push_back(filePath); } } sort( files.begin(), files.end() ); closedir(dp); return 0; } unsigned char double2uchar(double a) { //cout << a << '\t'; if (a < 0) { //cout << 0 << endl; return 0; } if (a > UCHAR_MAX * 1.0) { //cout << UCHAR_MAX; return UCHAR_MAX; } //cout << (int) ((unsigned char) a) << endl; return (unsigned char) a; } int main(int argc, char *argv[]) { if (argc != 8) { cerr << "Error usage, the correct way should be ./rgbReconstruct <Y_directory> <U_directory> <V_directory> <n1> >n2> <n3> <n4>" << endl; exit(-1); } char y_dir[MAX_DIRECTORY_NAME_LENGTH]; char u_dir[MAX_DIRECTORY_NAME_LENGTH]; char v_dir[MAX_DIRECTORY_NAME_LENGTH]; int n1, n2, n3, n4; strcpy(y_dir, argv[1]); strcpy(u_dir, argv[2]); strcpy(v_dir, argv[3]); n1 = atoi(argv[4]); n2 = atoi(argv[5]); n3 = atoi(argv[6]); n4 = atoi(argv[7]); vector<string> y_files = vector<string>(); vector<string> u_files = vector<string>(); vector<string> v_files = vector<string>(); getFileList(y_dir, y_files); getFileList(u_dir, u_files); getFileList(v_dir, v_files); // note that the desired output storage order is BGR // The conversion formula is as below // R = 1.164 * ( Y - 16 ) + 1.596 * ( V - 128 ) // G = 1.164 * ( Y - 16 ) - 0.813 * ( V - 128 ) - 0.391 * ( U - 128 ) // B = 1.164 * ( Y - 16 ) + 2.018 * ( U - 128 ) //Mat y_image, u_image, v_image; // we need 3 2D arrays to store the information double ** y = (double **) malloc(sizeof(double *) * n3); for (int i = 0; i < n3; i ++) { y[i] = (double *) malloc(sizeof(double) * n4); for (int j = 0; j < n4; j ++) { y[i][j] = 0.0; } } double ** u = (double **) malloc(sizeof(double *) * n3); for (int i = 0; i < n3; i ++) { u[i] = (double *) malloc(sizeof(double) * n4); for (int j = 0; j < n4; j ++) { u[i][j] = 0.0; } } double ** v = (double **) malloc(sizeof(double *) * n3); for (int i = 0; i < n3; i ++) { v[i] = (double *) malloc(sizeof(double) * n4); for (int j = 0; j < n4; j ++) { v[i][j] = 0.0; } } Mat img = Mat::zeros(n3, n4, CV_8UC3); Vec3b color; string outFilePrefix = "result_"; string outFileName; FILE * input_file; int x_index, y_index; for (int i = 0; i < y_files.size(); i ++) { //y_image = imread(y_files[i].c_str(), 0); // 0 means read it into grayscale //u_image = imread(u_files[i].c_str(), 0); //v_image = imread(v_files[i].c_str(), 0); // read files // read y input_file = fopen(y_files[i].c_str(), "rb"); if (input_file == NULL) { cerr << "File error " << y_files[i] << " is empty" << endl; exit(-1); } for (int j = 0; j < n3; j ++) { for (int k = 0; k < n4; k ++) { fread(&(y[j][k]), sizeof(double), 1, input_file); } } fclose(input_file); // read u input_file = fopen(u_files[i].c_str(), "rb"); if (input_file == NULL) { cerr << "File error " << u_files[i] << " is empty" << endl; exit(-1); } for (int j = 0; j < n3; j ++) { for (int k = 0; k < n4; k ++) { fread(&(u[j][k]), sizeof(double), 1, input_file); } } fclose(input_file); // read v input_file = fopen(v_files[i].c_str(), "rb"); if (input_file == NULL) { cerr << "File error " << v_files[i] << " is empty" << endl; exit(-1); } for (int j = 0; j < n3; j ++) { for (int k = 0; k < n4; k ++) { fread(&(v[j][k]), sizeof(double), 1, input_file); } } fclose(input_file); //int a; //cin >> a; for (int j = 0; j < n3; j ++) { // rows for (int k = 0; k < n4; k ++) { // columns //y = y_image.at<double>(j, k); //u = u_image.at<double>(j, k); //v = v_image.at<double>(j, k); color = img.at<Vec3b>(j, k); // storage is in order of BGR //color.val[0] = double2uchar(y[j][k] + 2.03211 * u[j][k]); //color.val[1] = double2uchar(y[j][k] - 0.39465 * u[j][k] - 0.58060 * v[j][k]); //color.val[2] = double2uchar(y[j][k] + 1.13983 * v[j][k]); color.val[0] = double2uchar(1.164 * (y[j][k] - 16.0) + 2.018 * (u[j][k] - 128.0)); color.val[1] = double2uchar(1.164 * (y[j][k] - 16.0) - 0.813 * (v[j][k] - 128.0) - 0.391 * (u[j][k] - 128.0)); color.val[2] = double2uchar(1.164 * (y[j][k] - 16.0) + 1.596 * (v[j][k] - 128.0)); // store the color back img.at<Vec3b>(j, k) = color; } } x_index = i / n2; y_index = i % n2; if (x_index < 10) { if (y_index < 10) { outFileName = outFilePrefix + "0" + patch::to_string(x_index) + "_0" + patch::to_string(y_index) + ".png"; } else { outFileName = outFilePrefix + "0" + patch::to_string(x_index) + "_" + patch::to_string(y_index) + ".png"; } } else { if (y_index < 10) { outFileName = outFilePrefix + patch::to_string(x_index) + "_0" + patch::to_string(y_index) + ".png"; } else { outFileName = outFilePrefix + patch::to_string(x_index) + "_" + patch::to_string(y_index) + ".png"; } } imwrite(outFileName, img); } cout << " finish generating rgb images" << endl; return 0; }
25.56654
138
0.55235
TracyHuang
0febac4b05539901fe97e97451bbc343e0acbda4
20,343
cpp
C++
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/apps/ecparam.cpp
Sirokujira/MicroFrameworkPK_v4_3
a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e
[ "Apache-2.0" ]
4
2019-01-21T11:47:53.000Z
2020-06-09T02:14:15.000Z
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/apps/ecparam.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
null
null
null
DeviceCode/pal/OpenSSL/OpenSSL_1_0_0/apps/ecparam.cpp
yisea123/NetmfSTM32
62ddb8aa0362b83d2e73f3621a56593988e3620f
[ "Apache-2.0" ]
6
2017-11-09T11:48:10.000Z
2020-05-24T09:43:07.000Z
/* apps/ecparam.c */ /* * Written by Nils Larsch for the OpenSSL project. */ /* ==================================================================== * Copyright (c) 1998-2005 The OpenSSL Project. 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. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED 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 OpenSSL PROJECT OR * ITS 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. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * * Portions of the attached software ("Contribution") are developed by * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project. * * The Contribution is licensed pursuant to the OpenSSL open source * license provided above. * * The elliptic curve binary polynomial software is originally written by * Sheueling Chang Shantz and Douglas Stebila of Sun Microsystems Laboratories. * */ #include "e_os.h" #ifndef OPENSSL_NO_EC #ifdef OPENSSL_SYS_WINDOWS #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #endif #include "apps.h" #include <openssl/bio.h> #include <openssl/err.h> #include <openssl/bn.h> #include <openssl/ec.h> #include <openssl/x509.h> #include <openssl/pem.h> #undef PROG #define PROG ecparam_main /* -inform arg - input format - default PEM (DER or PEM) * -outform arg - output format - default PEM * -in arg - input file - default stdin * -out arg - output file - default stdout * -noout - do not print the ec parameter * -text - print the ec parameters in text form * -check - validate the ec parameters * -C - print a 'C' function creating the parameters * -name arg - use the ec parameters with 'short name' name * -list_curves - prints a list of all currently available curve 'short names' * -conv_form arg - specifies the point conversion form * - possible values: compressed * uncompressed (default) * hybrid * -param_enc arg - specifies the way the ec parameters are encoded * in the asn1 der encoding * possible values: named_curve (default) * explicit * -no_seed - if 'explicit' parameters are choosen do not use the seed * -genkey - generate ec key * -rand file - files to use for random number input * -engine e - use engine e, possibly a hardware device */ static int ecparam_print_var(BIO *,BIGNUM *,const char *,int,unsigned char *); extern "C" int MAIN(int, char **); int MAIN(int argc, char **argv) { EC_GROUP *group = NULL; point_conversion_form_t form = POINT_CONVERSION_UNCOMPRESSED; int new_form = 0; int asn1_flag = OPENSSL_EC_NAMED_CURVE; int new_asn1_flag = 0; char *curve_name = NULL, *inrand = NULL; int list_curves = 0, no_seed = 0, check = 0, badops = 0, text = 0, i, need_rand = 0, genkey = 0; char *infile = NULL, *outfile = NULL, *prog; BIO *in = NULL, *out = NULL; int informat, outformat, noout = 0, C = 0, ret = 1; char *engine = NULL; BIGNUM *ec_p = NULL, *ec_a = NULL, *ec_b = NULL, *ec_gen = NULL, *ec_order = NULL, *ec_cofactor = NULL; unsigned char *buffer = NULL; apps_startup(); if (bio_err == NULL) if ((bio_err=BIO_new(BIO_s_file())) != NULL) BIO_set_fp(bio_err,OPENSSL_TYPE__FILE_STDERR,BIO_NOCLOSE|BIO_FP_TEXT); if (!load_config(bio_err, NULL)) goto end; informat=FORMAT_PEM; outformat=FORMAT_PEM; prog=argv[0]; argc--; argv++; while (argc >= 1) { if (TINYCLR_SSL_STRCMP(*argv,"-inform") == 0) { if (--argc < 1) goto bad; informat=str2fmt(*(++argv)); } else if (TINYCLR_SSL_STRCMP(*argv,"-outform") == 0) { if (--argc < 1) goto bad; outformat=str2fmt(*(++argv)); } else if (TINYCLR_SSL_STRCMP(*argv,"-in") == 0) { if (--argc < 1) goto bad; infile= *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0) { if (--argc < 1) goto bad; outfile= *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv,"-text") == 0) text = 1; else if (TINYCLR_SSL_STRCMP(*argv,"-C") == 0) C = 1; else if (TINYCLR_SSL_STRCMP(*argv,"-check") == 0) check = 1; else if (TINYCLR_SSL_STRCMP (*argv, "-name") == 0) { if (--argc < 1) goto bad; curve_name = *(++argv); } else if (TINYCLR_SSL_STRCMP(*argv, "-list_curves") == 0) list_curves = 1; else if (TINYCLR_SSL_STRCMP(*argv, "-conv_form") == 0) { if (--argc < 1) goto bad; ++argv; new_form = 1; if (TINYCLR_SSL_STRCMP(*argv, "compressed") == 0) form = POINT_CONVERSION_COMPRESSED; else if (TINYCLR_SSL_STRCMP(*argv, "uncompressed") == 0) form = POINT_CONVERSION_UNCOMPRESSED; else if (TINYCLR_SSL_STRCMP(*argv, "hybrid") == 0) form = POINT_CONVERSION_HYBRID; else goto bad; } else if (TINYCLR_SSL_STRCMP(*argv, "-param_enc") == 0) { if (--argc < 1) goto bad; ++argv; new_asn1_flag = 1; if (TINYCLR_SSL_STRCMP(*argv, "named_curve") == 0) asn1_flag = OPENSSL_EC_NAMED_CURVE; else if (TINYCLR_SSL_STRCMP(*argv, "explicit") == 0) asn1_flag = 0; else goto bad; } else if (TINYCLR_SSL_STRCMP(*argv, "-no_seed") == 0) no_seed = 1; else if (TINYCLR_SSL_STRCMP(*argv, "-noout") == 0) noout=1; else if (TINYCLR_SSL_STRCMP(*argv,"-genkey") == 0) { genkey=1; need_rand=1; } else if (TINYCLR_SSL_STRCMP(*argv, "-rand") == 0) { if (--argc < 1) goto bad; inrand= *(++argv); need_rand=1; } else if(TINYCLR_SSL_STRCMP(*argv, "-engine") == 0) { if (--argc < 1) goto bad; engine = *(++argv); } else { BIO_printf(bio_err,"unknown option %s\n",*argv); badops=1; break; } argc--; argv++; } if (badops) { bad: BIO_printf(bio_err, "%s [options] <infile >outfile\n",prog); BIO_printf(bio_err, "where options are\n"); BIO_printf(bio_err, " -inform arg input format - " "default PEM (DER or PEM)\n"); BIO_printf(bio_err, " -outform arg output format - " "default PEM\n"); BIO_printf(bio_err, " -in arg input file - " "default stdin\n"); BIO_printf(bio_err, " -out arg output file - " "default stdout\n"); BIO_printf(bio_err, " -noout do not print the " "ec parameter\n"); BIO_printf(bio_err, " -text print the ec " "parameters in text form\n"); BIO_printf(bio_err, " -check validate the ec " "parameters\n"); BIO_printf(bio_err, " -C print a 'C' " "function creating the parameters\n"); BIO_printf(bio_err, " -name arg use the " "ec parameters with 'short name' name\n"); BIO_printf(bio_err, " -list_curves prints a list of " "all currently available curve 'short names'\n"); BIO_printf(bio_err, " -conv_form arg specifies the " "point conversion form \n"); BIO_printf(bio_err, " possible values:" " compressed\n"); BIO_printf(bio_err, " " " uncompressed (default)\n"); BIO_printf(bio_err, " " " hybrid\n"); BIO_printf(bio_err, " -param_enc arg specifies the way" " the ec parameters are encoded\n"); BIO_printf(bio_err, " in the asn1 der " "encoding\n"); BIO_printf(bio_err, " possible values:" " named_curve (default)\n"); BIO_printf(bio_err, " " " explicit\n"); BIO_printf(bio_err, " -no_seed if 'explicit'" " parameters are choosen do not" " use the seed\n"); BIO_printf(bio_err, " -genkey generate ec" " key\n"); BIO_printf(bio_err, " -rand file files to use for" " random number input\n"); BIO_printf(bio_err, " -engine e use engine e, " "possibly a hardware device\n"); goto end; } ERR_load_crypto_strings(); in=BIO_new(BIO_s_file()); out=BIO_new(BIO_s_file()); if ((in == NULL) || (out == NULL)) { ERR_print_errors(bio_err); goto end; } if (infile == NULL) BIO_set_fp(in,OPENSSL_TYPE__FILE_STDIN,BIO_NOCLOSE); else { if (BIO_read_filename(in,infile) <= 0) { TINYCLR_SSL_PERROR(infile); goto end; } } if (outfile == NULL) { BIO_set_fp(out,OPENSSL_TYPE__FILE_STDOUT,BIO_NOCLOSE); #ifdef OPENSSL_SYS_VMS { BIO *tmpbio = BIO_new(BIO_f_linebuffer()); out = BIO_push(tmpbio, out); } #endif } else { if (BIO_write_filename(out,outfile) <= 0) { TINYCLR_SSL_PERROR(outfile); goto end; } } #ifndef OPENSSL_NO_ENGINE setup_engine(bio_err, engine, 0); #endif if (list_curves) { EC_builtin_curve *curves = NULL; size_t crv_len = 0; size_t n = 0; crv_len = EC_get_builtin_curves(NULL, 0); curves = (EC_builtin_curve*)OPENSSL_malloc((int)(sizeof(EC_builtin_curve) * crv_len)); if (curves == NULL) goto end; if (!EC_get_builtin_curves(curves, crv_len)) { OPENSSL_free(curves); goto end; } for (n = 0; n < crv_len; n++) { const char *comment; const char *sname; comment = curves[n].comment; sname = OBJ_nid2sn(curves[n].nid); if (comment == NULL) comment = "CURVE DESCRIPTION NOT AVAILABLE"; if (sname == NULL) sname = ""; BIO_printf(out, " %-10s: ", sname); BIO_printf(out, "%s\n", comment); } OPENSSL_free(curves); ret = 0; goto end; } if (curve_name != NULL) { int nid; /* workaround for the SECG curve names secp192r1 * and secp256r1 (which are the same as the curves * prime192v1 and prime256v1 defined in X9.62) */ if (!TINYCLR_SSL_STRCMP(curve_name, "secp192r1")) { BIO_printf(bio_err, "using curve name prime192v1 " "instead of secp192r1\n"); nid = NID_X9_62_prime192v1; } else if (!TINYCLR_SSL_STRCMP(curve_name, "secp256r1")) { BIO_printf(bio_err, "using curve name prime256v1 " "instead of secp256r1\n"); nid = NID_X9_62_prime256v1; } else nid = OBJ_sn2nid(curve_name); if (nid == 0) { BIO_printf(bio_err, "unknown curve name (%s)\n", curve_name); goto end; } group = EC_GROUP_new_by_curve_name(nid); if (group == NULL) { BIO_printf(bio_err, "unable to create curve (%s)\n", curve_name); goto end; } EC_GROUP_set_asn1_flag(group, asn1_flag); EC_GROUP_set_point_conversion_form(group, form); } else if (informat == FORMAT_ASN1) { group = d2i_ECPKParameters_bio(in, NULL); } else if (informat == FORMAT_PEM) { group = PEM_read_bio_ECPKParameters(in,NULL,NULL,NULL); } else { BIO_printf(bio_err, "bad input format specified\n"); goto end; } if (group == NULL) { BIO_printf(bio_err, "unable to load elliptic curve parameters\n"); ERR_print_errors(bio_err); goto end; } if (new_form) EC_GROUP_set_point_conversion_form(group, form); if (new_asn1_flag) EC_GROUP_set_asn1_flag(group, asn1_flag); if (no_seed) { EC_GROUP_set_seed(group, NULL, 0); } if (text) { if (!ECPKParameters_print(out, group, 0)) goto end; } if (check) { if (group == NULL) BIO_printf(bio_err, "no elliptic curve parameters\n"); BIO_printf(bio_err, "checking elliptic curve parameters: "); if (!EC_GROUP_check(group, NULL)) { BIO_printf(bio_err, "failed\n"); ERR_print_errors(bio_err); } else BIO_printf(bio_err, "ok\n"); } if (C) { size_t buf_len = 0, tmp_len = 0; const EC_POINT *point; int is_prime, len = 0; const EC_METHOD *meth = EC_GROUP_method_of(group); if ((ec_p = BN_new()) == NULL || (ec_a = BN_new()) == NULL || (ec_b = BN_new()) == NULL || (ec_gen = BN_new()) == NULL || (ec_order = BN_new()) == NULL || (ec_cofactor = BN_new()) == NULL ) { TINYCLR_SSL_PERROR("OPENSSL_malloc"); goto end; } is_prime = (EC_METHOD_get_field_type(meth) == NID_X9_62_prime_field); if (is_prime) { if (!EC_GROUP_get_curve_GFp(group, ec_p, ec_a, ec_b, NULL)) goto end; } else { /* TODO */ goto end; } if ((point = EC_GROUP_get0_generator(group)) == NULL) goto end; if (!EC_POINT_point2bn(group, point, EC_GROUP_get_point_conversion_form(group), ec_gen, NULL)) goto end; if (!EC_GROUP_get_order(group, ec_order, NULL)) goto end; if (!EC_GROUP_get_cofactor(group, ec_cofactor, NULL)) goto end; if (!ec_p || !ec_a || !ec_b || !ec_gen || !ec_order || !ec_cofactor) goto end; len = BN_num_bits(ec_order); if ((tmp_len = (size_t)BN_num_bytes(ec_p)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t)BN_num_bytes(ec_a)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t)BN_num_bytes(ec_b)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t)BN_num_bytes(ec_gen)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t)BN_num_bytes(ec_order)) > buf_len) buf_len = tmp_len; if ((tmp_len = (size_t)BN_num_bytes(ec_cofactor)) > buf_len) buf_len = tmp_len; buffer = (unsigned char *)OPENSSL_malloc(buf_len); if (buffer == NULL) { TINYCLR_SSL_PERROR("OPENSSL_malloc"); goto end; } ecparam_print_var(out, ec_p, "ec_p", len, buffer); ecparam_print_var(out, ec_a, "ec_a", len, buffer); ecparam_print_var(out, ec_b, "ec_b", len, buffer); ecparam_print_var(out, ec_gen, "ec_gen", len, buffer); ecparam_print_var(out, ec_order, "ec_order", len, buffer); ecparam_print_var(out, ec_cofactor, "ec_cofactor", len, buffer); BIO_printf(out, "\n\n"); BIO_printf(out, "EC_GROUP *get_ec_group_%d(void)\n\t{\n", len); BIO_printf(out, "\tint ok=0;\n"); BIO_printf(out, "\tEC_GROUP *group = NULL;\n"); BIO_printf(out, "\tEC_POINT *point = NULL;\n"); BIO_printf(out, "\tBIGNUM *tmp_1 = NULL, *tmp_2 = NULL, " "*tmp_3 = NULL;\n\n"); BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_p_%d, " "sizeof(ec_p_%d), NULL)) == NULL)\n\t\t" "goto err;\n", len, len); BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_a_%d, " "sizeof(ec_a_%d), NULL)) == NULL)\n\t\t" "goto err;\n", len, len); BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_b_%d, " "sizeof(ec_b_%d), NULL)) == NULL)\n\t\t" "goto err;\n", len, len); if (is_prime) { BIO_printf(out, "\tif ((group = EC_GROUP_new_curve_" "GFp(tmp_1, tmp_2, tmp_3, NULL)) == NULL)" "\n\t\tgoto err;\n\n"); } else { /* TODO */ goto end; } BIO_printf(out, "\t/* build generator */\n"); BIO_printf(out, "\tif ((tmp_1 = BN_bin2bn(ec_gen_%d, " "sizeof(ec_gen_%d), tmp_1)) == NULL)" "\n\t\tgoto err;\n", len, len); BIO_printf(out, "\tpoint = EC_POINT_bn2point(group, tmp_1, " "NULL, NULL);\n"); BIO_printf(out, "\tif (point == NULL)\n\t\tgoto err;\n"); BIO_printf(out, "\tif ((tmp_2 = BN_bin2bn(ec_order_%d, " "sizeof(ec_order_%d), tmp_2)) == NULL)" "\n\t\tgoto err;\n", len, len); BIO_printf(out, "\tif ((tmp_3 = BN_bin2bn(ec_cofactor_%d, " "sizeof(ec_cofactor_%d), tmp_3)) == NULL)" "\n\t\tgoto err;\n", len, len); BIO_printf(out, "\tif (!EC_GROUP_set_generator(group, point," " tmp_2, tmp_3))\n\t\tgoto err;\n"); BIO_printf(out, "\n\tok=1;\n"); BIO_printf(out, "err:\n"); BIO_printf(out, "\tif (tmp_1)\n\t\tBN_free(tmp_1);\n"); BIO_printf(out, "\tif (tmp_2)\n\t\tBN_free(tmp_2);\n"); BIO_printf(out, "\tif (tmp_3)\n\t\tBN_free(tmp_3);\n"); BIO_printf(out, "\tif (point)\n\t\tEC_POINT_free(point);\n"); BIO_printf(out, "\tif (!ok)\n"); BIO_printf(out, "\t\t{\n"); BIO_printf(out, "\t\tEC_GROUP_free(group);\n"); BIO_printf(out, "\t\tgroup = NULL;\n"); BIO_printf(out, "\t\t}\n"); BIO_printf(out, "\treturn(group);\n\t}\n"); } if (!noout) { if (outformat == FORMAT_ASN1) i = i2d_ECPKParameters_bio(out, group); else if (outformat == FORMAT_PEM) i = PEM_write_bio_ECPKParameters(out, group); else { BIO_printf(bio_err,"bad output format specified for" " outfile\n"); goto end; } if (!i) { BIO_printf(bio_err, "unable to write elliptic " "curve parameters\n"); ERR_print_errors(bio_err); goto end; } } if (need_rand) { app_RAND_load_file(NULL, bio_err, (inrand != NULL)); if (inrand != NULL) BIO_printf(bio_err,"%ld semi-random bytes loaded\n", app_RAND_load_files(inrand)); } if (genkey) { EC_KEY *eckey = EC_KEY_new(); if (eckey == NULL) goto end; TINYCLR_SSL_ASSERT(need_rand); if (EC_KEY_set_group(eckey, group) == 0) goto end; if (!EC_KEY_generate_key(eckey)) { EC_KEY_free(eckey); goto end; } if (outformat == FORMAT_ASN1) i = i2d_ECPrivateKey_bio(out, eckey); else if (outformat == FORMAT_PEM) i = PEM_write_bio_ECPrivateKey(out, eckey, NULL, NULL, 0, NULL, NULL); else { BIO_printf(bio_err, "bad output format specified " "for outfile\n"); EC_KEY_free(eckey); goto end; } EC_KEY_free(eckey); } if (need_rand) app_RAND_write_file(NULL, bio_err); ret=0; end: if (ec_p) BN_free(ec_p); if (ec_a) BN_free(ec_a); if (ec_b) BN_free(ec_b); if (ec_gen) BN_free(ec_gen); if (ec_order) BN_free(ec_order); if (ec_cofactor) BN_free(ec_cofactor); if (buffer) OPENSSL_free(buffer); if (in != NULL) BIO_free(in); if (out != NULL) BIO_free_all(out); if (group != NULL) EC_GROUP_free(group); apps_shutdown(); OPENSSL_EXIT(ret); } static int ecparam_print_var(BIO *out, BIGNUM *in, const char *var, int len, unsigned char *buffer) { BIO_printf(out, "static unsigned char %s_%d[] = {", var, len); if (BN_is_zero(in)) BIO_printf(out, "\n\t0x00"); else { int i, l; l = BN_bn2bin(in, buffer); for (i=0; i<l-1; i++) { if ((i%12) == 0) BIO_printf(out, "\n\t"); BIO_printf(out, "0x%02X,", buffer[i]); } if ((i%12) == 0) BIO_printf(out, "\n\t"); BIO_printf(out, "0x%02X", buffer[i]); } BIO_printf(out, "\n\t};\n\n"); return 1; } #else /* !OPENSSL_NO_EC */ # if PEDANTIC static void *dummy=&dummy; # endif #endif
27.715259
88
0.627046
Sirokujira
0fed217cfc72aefa2b234af4626cc54c1b1ce430
4,307
cpp
C++
iotivity-1.0.1/examples/OICMiddle/OICMiddle.cpp
gerald-yang/ubuntu-iotivity-demo
17e799e209442bbefb2df846e329c802ee5255f7
[ "Apache-2.0" ]
1,433
2015-04-30T09:26:53.000Z
2022-03-26T12:44:12.000Z
AllJoyn/Samples/OICAdapter/iotivity-1.0.0/examples/OICMiddle/OICMiddle.cpp
buocnhay/samples-1
ddd614bb5ae595f03811e3dfa15a5d107005d0fc
[ "MIT" ]
530
2015-05-02T09:12:48.000Z
2018-01-03T17:52:01.000Z
AllJoyn/Samples/OICAdapter/iotivity-1.0.0/examples/OICMiddle/OICMiddle.cpp
buocnhay/samples-1
ddd614bb5ae595f03811e3dfa15a5d107005d0fc
[ "MIT" ]
1,878
2015-04-30T04:18:57.000Z
2022-03-15T16:51:17.000Z
//****************************************************************** // // Copyright 2014 Intel Corporation. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // OICMiddle.cpp : OIC demo application for Minnowboard // #include <unistd.h> #include "OICMiddle.h" #include "WrapResource.h" #include "Client.h" #include "Server.h" #include "LineInput.h" #include "RestInput.h" class Middle middle; // one and only Middle::Middle() : m_appType(AT_None), m_useLineInput(false), m_useRestInput(false), m_client(nullptr), m_server(nullptr), m_lineInput(nullptr), m_restInput(nullptr) { } Middle::~Middle() { delete m_client; delete m_server; delete m_lineInput; delete m_restInput; } void Middle::init() { } void Middle::run(int argc, char* argv[]) { parseCommandLineOptions(argc, argv); startPlatform(); if (m_appType & AT_Client) { m_client = new MiddleClient(); m_client->init(); } m_lineInput = new LineInput(m_client); if (m_appType & AT_Server) { m_server = new MiddleServer(); m_server->init(); } if (m_useRestInput) { if (!m_server) { m_server = new MiddleServer(); m_server->init(); } m_restInput = new RestInput(m_lineInput); m_restInput->init(); } if (m_useLineInput) { if (m_server) { m_lineInput->setServer(m_server); } m_lineInput->run(); } else { while (true) sleep(1); } } void Middle::startPlatform() { uint16_t port = 0; //std::string ipaddr = INADDR_ANY; std::string ipaddr = "0.0.0.0"; PlatformConfig cfg { ServiceType::InProc, ModeType::Both, ipaddr, port, QualityOfService::LowQos}; OC::OCPlatform::Configure(cfg); } void Middle::provideHelp() { static const char usage[] = "\nUsage: IOCMiddle args\n" " where args may include any of these:\n" "\t-client Run OIC client\n" "\t-server Run OIC server\n" "\t-both Run OIC client and server\n" "\t-console Run console line interpreter\n" "\t-rest Run ReST server\n" "\t-hue addr Enable Hue resources on bridge at addr\n" "\t-help Show Usage again\n" "Any combination of the above is okay.\n\n"; cout << usage; } bool Middle::parseCommandLineOptions(int argc, char *argv[]) { bool any = false; for (int i = 1; i < argc; i++) { if (argv[i] == string("-server")) { middle.m_appType = AT_Server; any = true; } else if (argv[i] == string("-client")) { middle.m_appType = AT_Client; any = true; } else if (argv[i] == string("-both")) { middle.m_appType = AT_Both; any = true; } else if (argv[i] == string("-console")) { middle.m_useLineInput = true; any = true; } else if (argv[i] == string("-rest")) { middle.m_useRestInput = true; any = true; } else if (argv[i] == string("-hue")) { if (i + 1 < argc && argv[i + 1][0] != '-') { m_hueAddr = argv[++i]; any = true; } } else if (argv[i] == string("-help")) { any = false; break; } else { std::cerr << "Not enough or invalid arguments, please try again.\n"; exit(1); } } if (!any) provideHelp(); return true; } int main(int argc, char* argv[]) { middle.run(argc, argv); return 0; }
26.751553
80
0.536104
gerald-yang
0fed62a9c8896a5a35b86a140922a1774fdebd2b
2,827
cpp
C++
lib/params/SliceParams.cpp
sgpearse/VAPOR
12d4ed2e914ff3f6b59989a33a88d7399f45c41b
[ "BSD-3-Clause" ]
1
2021-05-18T20:12:31.000Z
2021-05-18T20:12:31.000Z
lib/params/SliceParams.cpp
sgpearse/VAPOR
12d4ed2e914ff3f6b59989a33a88d7399f45c41b
[ "BSD-3-Clause" ]
null
null
null
lib/params/SliceParams.cpp
sgpearse/VAPOR
12d4ed2e914ff3f6b59989a33a88d7399f45c41b
[ "BSD-3-Clause" ]
null
null
null
#include <string> #include <vapor/RenderParams.h> #include <vapor/SliceParams.h> using namespace Wasp; using namespace VAPoR; #define THREED 3 #define X 0 #define Y 1 #define Z 2 #define XY 0 #define XZ 1 #define YZ 2 #define MIN_DEFAULT_SAMPLERATE 200 const string SliceParams::_sampleRateTag = "SampleRate"; const string SliceParams::SampleLocationTag = "SampleLocationTag"; // // Register class with object factory!!! // static RenParamsRegistrar<SliceParams> registrar(SliceParams::GetClassType()); SliceParams::SliceParams(DataMgr *dataMgr, ParamsBase::StateSave *ssave) : RenderParams(dataMgr, ssave, SliceParams::GetClassType(), THREED) { SetDiagMsg("SliceParams::SliceParams() this=%p", this); _cachedValues.clear(); _init(); } SliceParams::SliceParams(DataMgr *dataMgr, ParamsBase::StateSave *ssave, XmlNode *node) : RenderParams(dataMgr, ssave, node, THREED) { _initialized = true; } SliceParams::~SliceParams() { SetDiagMsg("SliceParams::~SliceParams() this=%p", this); } void SliceParams::SetRefinementLevel(int level) { BeginGroup("SliceParams: Change refinement level and sample rate"); RenderParams::SetRefinementLevel(level); SetSampleRate(GetDefaultSampleRate()); EndGroup(); } void SliceParams::_init() { SetDiagMsg("SliceParams::_init()"); SetFieldVariableNames(vector<string>()); SetSampleRate(MIN_DEFAULT_SAMPLERATE); } int SliceParams::Initialize() { int rc = RenderParams::Initialize(); if (rc < 0) return (rc); if (_initialized) return 0; _initialized = true; Box *box = GetBox(); box->SetOrientation(XY); std::vector<double> minExt, maxExt; box->GetExtents(minExt, maxExt); std::vector<double> sampleLocation(3); for (int i = 0; i < 3; i++) sampleLocation[i] = (minExt[i] + maxExt[i]) / 2.0; SetValueDoubleVec(SampleLocationTag, "", sampleLocation); SetSampleRate(MIN_DEFAULT_SAMPLERATE); return (0); } int SliceParams::GetDefaultSampleRate() const { string varName = GetVariableName(); int refLevel = GetRefinementLevel(); vector<size_t> dimsAtLevel; _dataMgr->GetDimLensAtLevel(varName, refLevel, dimsAtLevel); int sampleRate = *max_element(dimsAtLevel.begin(), dimsAtLevel.end()); if (sampleRate < MIN_DEFAULT_SAMPLERATE) sampleRate = MIN_DEFAULT_SAMPLERATE; return sampleRate; } int SliceParams::GetSampleRate() const { int rate = (int)GetValueDouble(_sampleRateTag, MIN_DEFAULT_SAMPLERATE); return rate; } void SliceParams::SetSampleRate(int rate) { SetValueDouble(_sampleRateTag, "Set sample rate", (double)rate); } void SliceParams::SetCachedValues(std::vector<double> values) { _cachedValues.clear(); _cachedValues = values; } std::vector<double> SliceParams::GetCachedValues() const { return _cachedValues; }
26.175926
157
0.719137
sgpearse
0fee19d9f96d45bb52f518b34ddc1a3a80ba71e8
2,979
cpp
C++
src/server/scripts/EasternKingdoms/BlackrockSpire/boss_drakkisath.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
src/server/scripts/EasternKingdoms/BlackrockSpire/boss_drakkisath.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
src/server/scripts/EasternKingdoms/BlackrockSpire/boss_drakkisath.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/> * * Copyright (C) 2010 - 2012 ProjectSkyfire <http://www.projectskyfire.org/> * * Copyright (C) 2011 - 2012 ArkCORE <http://www.arkania.net/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License 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 */ /* ScriptData SDName: Boss_Drakkisath SD%Complete: 100 SDComment: SDCategory: Blackrock Spire EndScriptData */ #include "ScriptPCH.h" #define SPELL_FIRENOVA 23462 #define SPELL_CLEAVE 20691 #define SPELL_CONFLIGURATION 16805 #define SPELL_THUNDERCLAP 15548 //Not sure if right ID. 23931 would be a harder possibility. class boss_drakkisath: public CreatureScript { public: boss_drakkisath() : CreatureScript("boss_drakkisath") { } CreatureAI* GetAI(Creature* pCreature) const { return new boss_drakkisathAI(pCreature); } struct boss_drakkisathAI: public ScriptedAI { boss_drakkisathAI(Creature *c) : ScriptedAI(c) { } uint32 FireNova_Timer; uint32 Cleave_Timer; uint32 Confliguration_Timer; uint32 Thunderclap_Timer; void Reset() { FireNova_Timer = 6000; Cleave_Timer = 8000; Confliguration_Timer = 15000; Thunderclap_Timer = 17000; } void EnterCombat(Unit * /*who*/) { } void UpdateAI(const uint32 diff) { //Return since we have no target if (!UpdateVictim()) return; //FireNova_Timer if (FireNova_Timer <= diff) { DoCast(me->getVictim(), SPELL_FIRENOVA); FireNova_Timer = 10000; } else FireNova_Timer -= diff; //Cleave_Timer if (Cleave_Timer <= diff) { DoCast(me->getVictim(), SPELL_CLEAVE); Cleave_Timer = 8000; } else Cleave_Timer -= diff; //Confliguration_Timer if (Confliguration_Timer <= diff) { DoCast(me->getVictim(), SPELL_CONFLIGURATION); Confliguration_Timer = 18000; } else Confliguration_Timer -= diff; //Thunderclap_Timer if (Thunderclap_Timer <= diff) { DoCast(me->getVictim(), SPELL_THUNDERCLAP); Thunderclap_Timer = 20000; } else Thunderclap_Timer -= diff; DoMeleeAttackIfReady(); } }; }; void AddSC_boss_drakkisath() { new boss_drakkisath(); }
26.837838
120
0.692514
forgottenlands
0fee2d8d0fe9158d3ae9fa1e25e1c4fed7579527
2,905
cpp
C++
DX12VertexBuffer.cpp
TheBearProject/beardirectx
1fdeaeea37d7669361972f6a59d9a1ddc7c29429
[ "MIT" ]
null
null
null
DX12VertexBuffer.cpp
TheBearProject/beardirectx
1fdeaeea37d7669361972f6a59d9a1ddc7c29429
[ "MIT" ]
null
null
null
DX12VertexBuffer.cpp
TheBearProject/beardirectx
1fdeaeea37d7669361972f6a59d9a1ddc7c29429
[ "MIT" ]
null
null
null
#include "DX12PCH.h" bsize VertexBufferCounter = 0; DX12VertexBuffer::DX12VertexBuffer() :m_Dynamic(false) { VertexBufferView.SizeInBytes = 0; VertexBufferCounter++; } void DX12VertexBuffer::Create(bsize stride, bsize count, bool dynamic, void* data) { Clear(); m_Dynamic = dynamic; { auto Properties = CD3DX12_HEAP_PROPERTIES (dynamic ? D3D12_HEAP_TYPE_UPLOAD : D3D12_HEAP_TYPE_DEFAULT); auto ResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(static_cast<uint64>(stride * count)); R_CHK(Factory->Device->CreateCommittedResource(&Properties,D3D12_HEAP_FLAG_NONE,&ResourceDesc,dynamic ? D3D12_RESOURCE_STATE_GENERIC_READ : D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER,nullptr,IID_PPV_ARGS(&VertexBuffer))); } VertexBufferView.SizeInBytes = static_cast<UINT>(stride * count); VertexBufferView.StrideInBytes = static_cast<UINT>(stride); VertexBufferView.BufferLocation = VertexBuffer->GetGPUVirtualAddress(); if (data && !m_Dynamic) { ComPtr<ID3D12Resource> TempBuffer; auto Properties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD); auto ResourceDesc = CD3DX12_RESOURCE_DESC::Buffer(static_cast<uint64>(stride * count)); R_CHK(Factory->Device->CreateCommittedResource(&Properties,D3D12_HEAP_FLAG_NONE,&ResourceDesc,D3D12_RESOURCE_STATE_GENERIC_READ,nullptr,IID_PPV_ARGS(&TempBuffer))); { void* Pointer; CD3DX12_RANGE ReadRange(0, 0); R_CHK(TempBuffer->Map(0, &ReadRange, reinterpret_cast<void**>(&Pointer))); bear_copy(Pointer, data, count * stride); TempBuffer->Unmap(0, nullptr); } Factory->LockCommandList(); auto ResourceBarrier1 = CD3DX12_RESOURCE_BARRIER::Transition(VertexBuffer.Get(), D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER, D3D12_RESOURCE_STATE_COPY_DEST); Factory->CommandList->ResourceBarrier(1, &ResourceBarrier1); Factory->CommandList->CopyBufferRegion(VertexBuffer.Get(), 0, TempBuffer.Get(), 0, count * stride); auto ResourceBarrier2 = CD3DX12_RESOURCE_BARRIER::Transition(VertexBuffer.Get(), D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); Factory->CommandList->ResourceBarrier(1, &ResourceBarrier2); Factory->UnlockCommandList(); } else if (data) { bear_copy(Lock(), data, count * stride); Unlock(); } } DX12VertexBuffer::~DX12VertexBuffer() { VertexBufferCounter--; Clear(); } void* DX12VertexBuffer::Lock() { BEAR_CHECK(m_Dynamic); if (VertexBuffer.Get() == 0)return 0; void* Pointer; CD3DX12_RANGE ReadRange(0, 0); R_CHK(VertexBuffer->Map(0, &ReadRange, reinterpret_cast<void**>(&Pointer))); return Pointer; } void DX12VertexBuffer::Unlock() { VertexBuffer->Unmap(0, nullptr); } void DX12VertexBuffer::Clear() { VertexBufferView.SizeInBytes = 0; VertexBuffer.Reset(); m_Dynamic = false; } bsize DX12VertexBuffer::GetCount() { if (VertexBufferView.StrideInBytes == 0)return 0; return VertexBufferView.SizeInBytes / VertexBufferView.StrideInBytes; }
33.011364
228
0.778313
TheBearProject
0fee6ba3ef58dbc33fb7c68088c75090d01215fd
10,314
cpp
C++
Kamek/src/bossKoopaThrow.cpp
Treeki/NewerSMBW
3ef0ff1849ed6be7b555a6debe37d72a8e5d09ba
[ "MIT" ]
44
2015-04-21T09:29:19.000Z
2020-11-06T14:16:16.000Z
Kamek/src/bossKoopaThrow.cpp
aboood40091/NewerSMBW
468b88d614ff2543225ba260ce77381c59247576
[ "MIT" ]
1
2018-09-19T00:00:37.000Z
2020-05-12T14:15:01.000Z
Kamek/src/bossKoopaThrow.cpp
Treeki/NewerSMBW
3ef0ff1849ed6be7b555a6debe37d72a8e5d09ba
[ "MIT" ]
24
2016-01-12T03:28:47.000Z
2020-11-11T18:27:32.000Z
#include <common.h> #include <game.h> #include <g3dhax.h> #include <sfx.h> #include "boss.h" struct TypeInfo { const char *arcName; const char *brresName; const char *modelName; const char *deathEffect; int launchSound; int breakSound; int flySound; float size; float scale; u16 xrot; u16 yrot; u16 zrot; }; static const TypeInfo types[6] = { {"choropoo", "g3d/choropoo.brres", "spanner", "Wm_en_hit", 0, SE_BOSS_JR_FLOOR_BREAK, 0, 8.0f, 2.0f, 0, 0, 0x1000}, {"choropoo", "g3d/choropoo.brres", "spanner", "Wm_en_burst_s", 0, SE_BOSS_JR_BOMB_BURST, 0, 12.0f, 2.0f, 0, 0, 0x1000}, {"koopa_clown_bomb", "g3d/koopa_clown_bomb.brres", "koopa_clown_bomb", "Wm_en_burst_s", SE_EMY_ELCJ_THROW, SE_BOSS_JR_BOMB_BURST, 0, 16.0f, 0.8f, 0x200, 0x800, 0x1000}, {"bros", "g3d/t00.brres", "bros_hammer", "Wm_en_hit", 0, SE_OBJ_HAMMER_HIT_BOTH, 0, 16.0f, 2.0f, 0, 0, 0x1000}, {"dossun", "g3d/t02.brres", "dossun", "Wm_en_hit", SE_EMY_DOSSUN, SE_EMY_DOSSUN_DEAD, 0, 14.0f, 1.0f, 0, 0, 0}, {"KoopaShip", "g3d/present.brres", "PresentBox_penguin", "Wm_dm_presentopen",SE_DEMO_OP_PRESENT_THROW_2400f, SE_DEMO_OP_PRESENT_BOX_BURST, 0, 20.0f, 1.0f, 0x20, 0x40, 0x200} }; const char* KPTarcNameList [] = { "choropoo", "koopa_clown_bomb", "dossun", "KoopaShip", NULL }; class daKoopaThrow : public dEn_c { int onCreate(); int onExecute(); int onDelete(); int onDraw(); mHeapAllocator_c allocator; m3d::mdl_c bodyModel; int timer; char Type; char direction; char front; float ymod; int lifespan; u32 cmgr_returnValue; bool playsAnim; m3d::anmChr_c chrAnim; nw4r::snd::SoundHandle hammerSound; const TypeInfo *currentInfo; static daKoopaThrow *build(); void updateModelMatrices(); void playerCollision(ActivePhysics *apThis, ActivePhysics *apOther); void spriteCollision(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat1_Fireball_E_Explosion(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat2_IceBall_15_YoshiIce(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat9_RollingObject(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat13_Hammer(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat14_YoshiFire(ActivePhysics *apThis, ActivePhysics *apOther); bool collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther); USING_STATES(daKoopaThrow); DECLARE_STATE(Straight); }; CREATE_STATE(daKoopaThrow, Straight); // Types: // // 0 - Wrench // 1 - Exploding Wrench // 2 - Bomb // 3 - Hammer // 4 - Thwomp // 5 - Present // extern "C" void *PlayWrenchSound(dEn_c *); extern "C" void *dAcPy_c__ChangePowerupWithAnimation(void * Player, int powerup); extern "C" int CheckExistingPowerup(void * Player); void daKoopaThrow::playerCollision(ActivePhysics *apThis, ActivePhysics *apOther) { if (Type == 5) { PlaySoundAsync(this, currentInfo->breakSound); SpawnEffect(currentInfo->deathEffect, 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){3.0, 3.0, 3.0}); // dStageActor_c *spawned = CreateActor(EN_ITEM, 0x20000063, this->pos, 0, 0); // spawned->pos.x = this->pos.x; // spawned->pos.y = this->pos.y; int p = CheckExistingPowerup(apOther->owner); if (p == 0 || p == 3) { // Powerups - 0 = small; 1 = big; 2 = fire; 3 = mini; 4 = prop; 5 = peng; 6 = ice; 7 = hammer dAcPy_c__ChangePowerupWithAnimation(apOther->owner, 1); } this->Delete(1); return; } DamagePlayer(this, apThis, apOther); if (Type == 1 || Type == 2) { PlaySoundAsync(this, SE_BOSS_JR_BOMB_BURST); SpawnEffect("Wm_en_burst_s", 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){0.75, 0.75, 0.75}); SpawnEffect("Wm_mr_wirehit", 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){1.25, 1.25, 1.25}); this->Delete(1); } } void daKoopaThrow::spriteCollision(ActivePhysics *apThis, ActivePhysics *apOther) {} bool daKoopaThrow::collisionCat1_Fireball_E_Explosion(ActivePhysics *apThis, ActivePhysics *apOther) { return true; } bool daKoopaThrow::collisionCat2_IceBall_15_YoshiIce(ActivePhysics *apThis, ActivePhysics *apOther) { return false; } bool daKoopaThrow::collisionCat9_RollingObject(ActivePhysics *apThis, ActivePhysics *apOther) { return true; } bool daKoopaThrow::collisionCat13_Hammer(ActivePhysics *apThis, ActivePhysics *apOther) { if (Type == 1 || Type == 2) { SpawnEffect("Wm_en_burst_s", 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){0.75, 0.75, 0.75}); SpawnEffect("Wm_mr_wirehit", 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){1.25, 1.25, 1.25}); } else { SpawnEffect("Wm_ob_cmnboxgrain", 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){0.5, 0.5, 0.5}); } PlaySoundAsync(this, currentInfo->breakSound); this->Delete(1); return true; } bool daKoopaThrow::collisionCat14_YoshiFire(ActivePhysics *apThis, ActivePhysics *apOther) { return true; } bool daKoopaThrow::collisionCat7_GroundPound(ActivePhysics *apThis, ActivePhysics *apOther) { DamagePlayer(this, apThis, apOther); if (Type == 1 || Type == 2) { PlaySoundAsync(this, SE_BOSS_JR_BOMB_BURST); SpawnEffect("Wm_en_burst_s", 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){0.75, 0.75, 0.75}); SpawnEffect("Wm_mr_wirehit", 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){1.25, 1.25, 1.25}); this->Delete(1); } return true; } daKoopaThrow *daKoopaThrow::build() { void *buffer = AllocFromGameHeap1(sizeof(daKoopaThrow)); return new(buffer) daKoopaThrow; } int daKoopaThrow::onCreate() { this->direction = this->settings & 0xF; this->Type = (this->settings >> 4) & 0xF; this->front = (this->settings >> 8) & 0xF; currentInfo = &types[Type]; allocator.link(-1, GameHeaps[0], 0, 0x20); nw4r::g3d::ResFile rf(getResource(currentInfo->arcName, currentInfo->brresName)); nw4r::g3d::ResMdl resMdl = rf.GetResMdl(currentInfo->modelName); bodyModel.setup(resMdl, &allocator, (Type == 4 ? 0x224 : 0), 1, 0); SetupTextures_Enemy(&bodyModel, 0); if (Type == 4) { // Thwomp playsAnim = true; nw4r::g3d::ResAnmChr anmChr = rf.GetResAnmChr("boss_throw"); chrAnim.setup(resMdl, anmChr, &allocator, 0); chrAnim.bind(&bodyModel, anmChr, 1); bodyModel.bindAnim(&chrAnim, 0.0); chrAnim.setUpdateRate(1.0); } allocator.unlink(); ActivePhysics::Info KoopaJunk; KoopaJunk.xDistToCenter = 0.0f; KoopaJunk.yDistToCenter = (Type == 4) ? currentInfo->size : 0.0; KoopaJunk.xDistToEdge = currentInfo->size; KoopaJunk.yDistToEdge = currentInfo->size; this->scale.x = currentInfo->scale; this->scale.y = currentInfo->scale; this->scale.z = currentInfo->scale; KoopaJunk.category1 = 0x3; KoopaJunk.category2 = 0x0; KoopaJunk.bitfield1 = 0x47; KoopaJunk.bitfield2 = 0xFFFFFFFF; KoopaJunk.unkShort1C = 0; KoopaJunk.callback = &dEn_c::collisionCallback; this->aPhysics.initWithStruct(this, &KoopaJunk); this->aPhysics.addToList(); spriteSomeRectX = currentInfo->size; spriteSomeRectY = currentInfo->size; _320 = 0.0f; _324 = currentInfo->size; // These structs tell stupid collider what to collide with - these are from koopa troopa static const lineSensor_s below(12<<12, 4<<12, 0<<12); static const pointSensor_s above(0<<12, 12<<12); static const lineSensor_s adjacent(6<<12, 9<<12, 6<<12); collMgr.init(this, &below, &above, &adjacent); collMgr.calculateBelowCollisionWithSmokeEffect(); cmgr_returnValue = collMgr.isOnTopOfTile(); if (this->direction == 0) { // Ground Facing Left this->pos.x -= 0.0; // -32 to +32 this->pos.y += 36.0; // this->rot.z = 0x2000; } else if (this->direction == 1) { // Ground Facing Right this->pos.x += 0.0; // +32 to -32 this->pos.y += 36.0; // this->rot.z = 0xE000; } if (this->front == 1) { this->pos.z = -1804.0; } else { this->pos.z = 3300.0; } if (currentInfo->launchSound != 0) { PlaySound(this, currentInfo->launchSound); } if (Type == 3) { PlaySoundWithFunctionB4(SoundRelatedClass, &hammerSound, SE_EMY_MEGA_BROS_HAMMER, 1); } doStateChange(&StateID_Straight); this->onExecute(); return true; } int daKoopaThrow::onDelete() { if (hammerSound.Exists()) hammerSound.Stop(10); return true; } int daKoopaThrow::onDraw() { bodyModel.scheduleForDrawing(); return true; } void daKoopaThrow::updateModelMatrices() { matrix.translation(pos.x, pos.y, pos.z); matrix.applyRotationYXZ(&rot.x, &rot.y, &rot.z); bodyModel.setDrawMatrix(matrix); bodyModel.setScale(&scale); bodyModel.calcWorld(false); } int daKoopaThrow::onExecute() { acState.execute(); updateModelMatrices(); if (playsAnim) { if (chrAnim.isAnimationDone()) chrAnim.setCurrentFrame(0.0f); bodyModel._vf1C(); } float rect[] = {this->_320, this->_324, this->spriteSomeRectX, this->spriteSomeRectY}; int ret = this->outOfZone(this->pos, (float*)&rect, this->currentZoneID); if(ret) { this->Delete(1); } return true; } void daKoopaThrow::beginState_Straight() { float rand = (float)GenerateRandomNumber(10) * 0.4; if (this->direction == 0) { // directions 1 spins clockwise, fly rightwards speed.x = 1.5 + rand; } else { // directions 0 spins anti-clockwise, fly leftwards speed.x = -1.5 - rand; } speed.y = 9.0; } void daKoopaThrow::executeState_Straight() { speed.y = speed.y - 0.01875; HandleXSpeed(); HandleYSpeed(); doSpriteMovement(); // cmgr_returnValue = collMgr.isOnTopOfTile(); // collMgr.calculateBelowCollisionWithSmokeEffect(); // if (collMgr.isOnTopOfTile() || (collMgr.outputMaybe & (0x15 << direction))) { // // hit the ground or wall // PlaySoundAsync(this, currentInfo->breakSound); // SpawnEffect(currentInfo->deathEffect, 0, &this->pos, &(S16Vec){0,0,0}, &(Vec){0.75, 0.75, 0.75}); // this->Delete(1); // } if (this->direction == 1) { // directions 1 spins clockwise, fly rightwards this->rot.x -= currentInfo->xrot; this->rot.y -= currentInfo->yrot; this->rot.z -= currentInfo->zrot; } else { // directions 0 spins anti-clockwise, fly leftwards this->rot.x -= currentInfo->xrot; this->rot.y -= currentInfo->yrot; this->rot.z += currentInfo->zrot; } if (Type < 2) { PlayWrenchSound(this); } else if (currentInfo->flySound == 0) { return; } else { PlaySound(this, currentInfo->flySound); } } void daKoopaThrow::endState_Straight() { }
27.35809
187
0.683343
Treeki
0fefd954c91d07b472bf2869f201dcf895211199
5,430
cc
C++
chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/printing/cloud_print/gcd_api_flow_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/cloud_print/gcd_api_flow.h" #include <memory> #include <set> #include <utility> #include "base/bind.h" #include "base/containers/contains.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/printing/cloud_print/gcd_api_flow_impl.h" #include "components/signin/public/identity_manager/identity_test_environment.h" #include "content/public/test/browser_task_environment.h" #include "google_apis/gaia/google_service_auth_error.h" #include "net/base/host_port_pair.h" #include "net/base/net_errors.h" #include "net/http/http_request_headers.h" #include "services/network/public/cpp/weak_wrapper_shared_url_loader_factory.h" #include "services/network/test/test_url_loader_factory.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::Invoke; using testing::Return; using testing::WithArgs; namespace cloud_print { namespace { const char kConfirmRequest[] = "https://www.google.com/cloudprint/confirm?token=SomeToken"; const char kSampleConfirmResponse[] = "{}"; const char kFailedConfirmResponseBadJson[] = "[]"; const char kAccountId[] = "account_id@gmail.com"; class MockDelegate : public CloudPrintApiFlowRequest { public: MOCK_METHOD1(OnGCDApiFlowError, void(GCDApiFlow::Status)); MOCK_METHOD1(OnGCDApiFlowComplete, void(const base::DictionaryValue&)); MOCK_METHOD0(GetURL, GURL()); MOCK_METHOD0(GetNetworkTrafficAnnotationType, GCDApiFlow::Request::NetworkTrafficAnnotation()); }; class GCDApiFlowTest : public testing::Test { public: GCDApiFlowTest() : test_shared_url_loader_factory_( base::MakeRefCounted<network::WeakWrapperSharedURLLoaderFactory>( &test_url_loader_factory_)) {} ~GCDApiFlowTest() override {} protected: void SetUp() override { identity_test_environment_.MakePrimaryAccountAvailable(kAccountId); std::unique_ptr<MockDelegate> delegate = std::make_unique<MockDelegate>(); mock_delegate_ = delegate.get(); EXPECT_CALL(*mock_delegate_, GetURL()) .WillRepeatedly(Return( GURL("https://www.google.com/cloudprint/confirm?token=SomeToken"))); gcd_flow_ = std::make_unique<GCDApiFlowImpl>( test_shared_url_loader_factory_.get(), identity_test_environment_.identity_manager()); gcd_flow_->Start(std::move(delegate)); } network::TestURLLoaderFactory test_url_loader_factory_; std::unique_ptr<GCDApiFlowImpl> gcd_flow_; MockDelegate* mock_delegate_; private: content::BrowserTaskEnvironment task_environment_; signin::IdentityTestEnvironment identity_test_environment_; scoped_refptr<network::WeakWrapperSharedURLLoaderFactory> test_shared_url_loader_factory_; }; TEST_F(GCDApiFlowTest, SuccessOAuth2) { std::set<GURL> requested_urls; test_url_loader_factory_.SetInterceptor( base::BindLambdaForTesting([&](const network::ResourceRequest& request) { requested_urls.insert(request.url); std::string oauth_header; EXPECT_TRUE(request.headers.GetHeader("Authorization", &oauth_header)); EXPECT_EQ("Bearer SomeToken", oauth_header); std::string proxy; EXPECT_TRUE(request.headers.GetHeader("X-Cloudprint-Proxy", &proxy)); EXPECT_EQ("Chrome", proxy); })); gcd_flow_->OnAccessTokenFetchComplete( GoogleServiceAuthError::AuthErrorNone(), signin::AccessTokenInfo( "SomeToken", base::Time::Now() + base::TimeDelta::FromHours(1), std::string() /* No extra information needed for this test */)); EXPECT_TRUE(base::Contains(requested_urls, GURL(kConfirmRequest))); test_url_loader_factory_.AddResponse(kConfirmRequest, kSampleConfirmResponse); base::RunLoop run_loop; EXPECT_CALL(*mock_delegate_, OnGCDApiFlowComplete(_)) .WillOnce(testing::InvokeWithoutArgs([&]() { run_loop.Quit(); })); run_loop.Run(); } TEST_F(GCDApiFlowTest, BadToken) { EXPECT_CALL(*mock_delegate_, OnGCDApiFlowError(GCDApiFlow::ERROR_TOKEN)); gcd_flow_->OnAccessTokenFetchComplete( GoogleServiceAuthError(GoogleServiceAuthError::USER_NOT_SIGNED_UP), signin::AccessTokenInfo()); } TEST_F(GCDApiFlowTest, BadJson) { std::set<GURL> requested_urls; test_url_loader_factory_.SetInterceptor( base::BindLambdaForTesting([&](const network::ResourceRequest& request) { requested_urls.insert(request.url); })); gcd_flow_->OnAccessTokenFetchComplete( GoogleServiceAuthError::AuthErrorNone(), signin::AccessTokenInfo( "SomeToken", base::Time::Now() + base::TimeDelta::FromHours(1), std::string() /* No extra information needed for this test */)); EXPECT_TRUE(base::Contains(requested_urls, GURL(kConfirmRequest))); test_url_loader_factory_.AddResponse(kConfirmRequest, kFailedConfirmResponseBadJson); base::RunLoop run_loop; EXPECT_CALL(*mock_delegate_, OnGCDApiFlowError(GCDApiFlow::ERROR_MALFORMED_RESPONSE)) .WillOnce(testing::InvokeWithoutArgs([&]() { run_loop.Quit(); })); run_loop.Run(); } } // namespace } // namespace cloud_print
35.25974
80
0.7407
Ron423c
0ff0c0a25dad2852b176d711f08a26f7b791c99d
4,351
cpp
C++
ipmi/manualcmds.cpp
openbmc/phosphor-pid-control
457993f836338aa0c13a32af803fcbc5227c81f3
[ "Apache-2.0" ]
9
2018-09-19T10:26:53.000Z
2020-11-09T23:02:16.000Z
ipmi/manualcmds.cpp
openbmc/phosphor-pid-control
457993f836338aa0c13a32af803fcbc5227c81f3
[ "Apache-2.0" ]
17
2018-08-13T10:34:26.000Z
2022-02-08T02:24:12.000Z
ipmi/manualcmds.cpp
openbmc/phosphor-pid-control
457993f836338aa0c13a32af803fcbc5227c81f3
[ "Apache-2.0" ]
9
2019-03-23T03:08:32.000Z
2021-04-25T03:39:34.000Z
/** * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "manualcmds.hpp" #include "control.hpp" #include "dbus_mode.hpp" #include "manual_messages.hpp" #include <ipmid/api.h> #include <sdbusplus/bus.hpp> #include <sdbusplus/message.hpp> #include <map> #include <memory> #include <string> #include <tuple> #include <variant> namespace pid_control { namespace ipmi { static constexpr auto manualProperty = "Manual"; static constexpr auto failsafeProperty = "FailSafe"; ipmi_ret_t ZoneControlIpmiHandler::getFailsafeModeState(const uint8_t* reqBuf, uint8_t* replyBuf, size_t* dataLen) { bool current; if (*dataLen < sizeof(struct FanCtrlRequest)) { return IPMI_CC_INVALID; } const auto request = reinterpret_cast<const struct FanCtrlRequest*>(&reqBuf[0]); ipmi_ret_t rc = _control->getFanCtrlProperty(request->zone, &current, failsafeProperty); if (rc) { return rc; } *replyBuf = (uint8_t)current; *dataLen = sizeof(uint8_t); return IPMI_CC_OK; } /* * <method name="GetAll"> * <arg name="interface" direction="in" type="s"/> * <arg name="properties" direction="out" type="a{sv}"/> * </method> */ ipmi_ret_t ZoneControlIpmiHandler::getManualModeState(const uint8_t* reqBuf, uint8_t* replyBuf, size_t* dataLen) { bool current; if (*dataLen < sizeof(struct FanCtrlRequest)) { return IPMI_CC_INVALID; } const auto request = reinterpret_cast<const struct FanCtrlRequest*>(&reqBuf[0]); ipmi_ret_t rc = _control->getFanCtrlProperty(request->zone, &current, manualProperty); if (rc) { return rc; } *replyBuf = (uint8_t)current; *dataLen = sizeof(uint8_t); return IPMI_CC_OK; } /* * <method name="Set"> * <arg name="interface" direction="in" type="s"/> * <arg name="property" direction="in" type="s"/> * <arg name="value" direction="in" type="v"/> * </method> */ ipmi_ret_t ZoneControlIpmiHandler::setManualModeState(const uint8_t* reqBuf, uint8_t* replyBuf, size_t* dataLen) { if (*dataLen < sizeof(struct FanCtrlRequestSet)) { return IPMI_CC_INVALID; } const auto request = reinterpret_cast<const struct FanCtrlRequestSet*>(&reqBuf[0]); /* 0 is false, 1 is true */ ipmi_ret_t rc = _control->setFanCtrlProperty( request->zone, static_cast<bool>(request->value), manualProperty); return rc; } /* Three command packages: get, set true, set false */ ipmi_ret_t manualModeControl(ZoneControlIpmiHandler* handler, ipmi_cmd_t cmd, const uint8_t* reqBuf, uint8_t* replyCmdBuf, size_t* dataLen) { // FanCtrlRequest is the smaller of the requests, so it's at a minimum. if (*dataLen < sizeof(struct FanCtrlRequest)) { return IPMI_CC_INVALID; } const auto request = reinterpret_cast<const struct FanCtrlRequest*>(&reqBuf[0]); ipmi_ret_t rc = IPMI_CC_OK; switch (request->command) { case getControlState: return handler->getManualModeState(reqBuf, replyCmdBuf, dataLen); case setControlState: return handler->setManualModeState(reqBuf, replyCmdBuf, dataLen); case getFailsafeState: return handler->getFailsafeModeState(reqBuf, replyCmdBuf, dataLen); default: rc = IPMI_CC_INVALID; } return rc; } } // namespace ipmi } // namespace pid_control
27.537975
80
0.619398
openbmc
0ff2fd1be1e9c93ae51c8d754e78325447436975
30,022
cpp
C++
data_reader/stage_0/src/data_reader_stage_0.cpp
shtroizel/matchmaker
457521bd677f6e06e9f2b6552b1ff661f52788d3
[ "BSD-3-Clause" ]
null
null
null
data_reader/stage_0/src/data_reader_stage_0.cpp
shtroizel/matchmaker
457521bd677f6e06e9f2b6552b1ff661f52788d3
[ "BSD-3-Clause" ]
null
null
null
data_reader/stage_0/src/data_reader_stage_0.cpp
shtroizel/matchmaker
457521bd677f6e06e9f2b6552b1ff661f52788d3
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2020, Eric Hyer 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 <cstring> #include <iostream> #include <matchable/matchable.h> #include <matchable/matchable_fwd.h> #include <matchable/MatchableMaker.h> #include <matchmaker/parts_of_speech.h> int const MAX_WORD_LENGTH{44}; MATCHABLE( word_attribute, invisible_ascii, matchable_symbols, unmatchable_symbols, name, male_name, female_name, place, compound, acronym ) void print_usage(); bool has_responsibility(char letter, char prefix_element); bool passes_prefix_filter( std::string const & word, std::string const & l0, // first letter std::string const & l1, // second letter std::string const & l2, // third letter std::string const & l3, // fourth letter std::string const & l4, // fifth letter std::string const & l5 // sixth letter ); bool passes_status_filter(word_attribute::Flags const & status); bool passes_filter( std::string const & word, word_attribute::Flags const & status, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5 ); void read_3201_default( FILE * input_file, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5, std::string const & prefix, word_attribute::Flags const & base_attributes, matchable::MatchableMaker & mm ); void read_3202( FILE * input_file, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5, std::string const & prefix, matchable::MatchableMaker & mm ); void read_3203_mobypos( FILE * input_file, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5, std::string const & prefix, matchable::MatchableMaker & mm ); void update_word_attribute(word_attribute::Flags & flags, int & ch); bool read_3201_default_line(FILE * f, std::string & word, word_attribute::Flags & status); bool read_3203_mobypos_line( FILE * f, std::string & word, word_attribute::Flags & status, parts_of_speech::Flags & pos ); void add_word( std::string const & word, std::string const & prefix, word_attribute::Flags const & wsf, matchable::MatchableMaker & mm ); void add_word( std::string const & word, std::string const & prefix, word_attribute::Flags const & wsf, parts_of_speech::Flags const & pos_flags, matchable::MatchableMaker & mm ); // allow Q to build quickly by eliminating quasi-words // * q u a s i A is very large because of all these words with symbols // // optional last argv can set this to true making Q quick again bool symbols_off = false; int main(int argc, char ** argv) { if (argc < 9) { print_usage(); return 2; } std::string const DATA_DIR{argv[1]}; std::string const OUTPUT_DIR{argv[2]}; std::string l0{argv[3]}; if (l0.size() != 1) { print_usage(); return 2; } if (l0[0] < 'A' || (l0[0] > 'Z' && l0[0] < 'a') || l0[0] > 'z') { print_usage(); return 2; } std::string l1{argv[4]}; if (l1.size() != 1 && l1 != "nil") { print_usage(); return 2; } if (l1[0] < 'A' || (l1[0] > 'Z' && l1[0] < 'a') || l1[0] > 'z') { print_usage(); return 2; } std::string l2{argv[5]}; if (l2.size() != 1 && l2 != "nil") { print_usage(); return 2; } if (l2[0] < 'A' || (l2[0] > 'Z' && l2[0] < 'a') || l2[0] > 'z') { print_usage(); return 2; } std::string l3{argv[6]}; if (l3.size() != 1 && l3 != "nil") { print_usage(); return 2; } if (l3[0] < 'A' || (l3[0] > 'Z' && l3[0] < 'a') || l3[0] > 'z') { print_usage(); return 2; } std::string l4{argv[7]}; if (l4.size() != 1 && l4 != "nil") { print_usage(); return 2; } if (l4[0] < 'A' || (l4[0] > 'Z' && l4[0] < 'a') || l4[0] > 'z') { print_usage(); return 2; } std::string l5{argv[8]}; if (l5.size() != 1 && l5 != "nil") { print_usage(); return 2; } if (l5[0] < 'A' || (l5[0] > 'Z' && l5[0] < 'a') || l5[0] > 'z') { print_usage(); return 2; } if (argc == 10 && strcmp(argv[9], "symbols_off") == 0) symbols_off = true; std::string prefix{"_" + l0}; if (l1 != "nil") { prefix += "_" + l1; if (l2 != "nil") { prefix += "_" + l2; if (l3 != "nil") { prefix += "_" + l3; if (l4 != "nil") { prefix += "_" + l4; if (l5 != "nil") { prefix += "_" + l5; } } } } } matchable::MatchableMaker mm; mm.grab("word" + prefix)->add_property("int8_t", "pos"); mm.grab("word" + prefix)->add_property("int", "syn"); mm.grab("word" + prefix)->add_property("int", "ant"); mm.grab("word" + prefix)->add_property("int", "by_longest_index"); mm.grab("word" + prefix)->add_property("int", "ordinal_summation"); // "word_attribute" properties { auto add_att_prop = [&](word_attribute::Type att) { std::string const prop_name = "is_" + att.as_string(); mm.grab("word" + prefix)->add_property("int8_t", prop_name); }; add_att_prop(word_attribute::name::grab()); add_att_prop(word_attribute::male_name::grab()); add_att_prop(word_attribute::female_name::grab()); add_att_prop(word_attribute::place::grab()); add_att_prop(word_attribute::compound::grab()); add_att_prop(word_attribute::acronym::grab()); } { std::string const FN_3201_SINGLE{DATA_DIR + "/3201/files/SINGLE.TXT"}; FILE * single_file = fopen(FN_3201_SINGLE.c_str(), "r"); if (single_file == 0) { perror(FN_3201_SINGLE.c_str()); exit(1); } word_attribute::Flags base_attributes; read_3201_default(single_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(single_file); } { std::string const FN_3201_COMPOUND{DATA_DIR + "/3201/files/COMPOUND.TXT"}; FILE * compound_file = fopen(FN_3201_COMPOUND.c_str(), "r"); if (compound_file == 0) { perror(FN_3201_COMPOUND.c_str()); exit(1); } word_attribute::Flags base_attributes{word_attribute::compound::grab()}; read_3201_default(compound_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(compound_file); } { std::string const FN_3201_COMMON{DATA_DIR + "/3201/files/COMMON.TXT"}; FILE * common_file = fopen(FN_3201_COMMON.c_str(), "r"); if (common_file == 0) { perror(FN_3201_COMMON.c_str()); exit(1); } word_attribute::Flags base_attributes; read_3201_default(common_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(common_file); } { std::string const FN_3201_NAMES{DATA_DIR + "/3201/files/NAMES.TXT"}; FILE * names_file = fopen(FN_3201_NAMES.c_str(), "r"); if (names_file == 0) { perror(FN_3201_NAMES.c_str()); exit(1); } word_attribute::Flags base_attributes{word_attribute::name::grab()}; read_3201_default(names_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(names_file); } { std::string const FN_3201_NAMES_F{DATA_DIR + "/3201/files/NAMES-F.TXT"}; FILE * names_f_file = fopen(FN_3201_NAMES_F.c_str(), "r"); if (names_f_file == 0) { perror(FN_3201_NAMES_F.c_str()); exit(1); } word_attribute::Flags base_attributes{ word_attribute::name::grab(), word_attribute::female_name::grab() }; read_3201_default(names_f_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(names_f_file); } { std::string const FN_3201_NAMES_M{DATA_DIR + "/3201/files/NAMES-M.TXT"}; FILE * names_m_file = fopen(FN_3201_NAMES_M.c_str(), "r"); if (names_m_file == 0) { perror(FN_3201_NAMES_M.c_str()); exit(1); } word_attribute::Flags base_attributes{ word_attribute::name::grab(), word_attribute::male_name::grab() }; read_3201_default(names_m_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(names_m_file); } { std::string const FN_3201_PLACES{DATA_DIR + "/3201/files/PLACES.TXT"}; FILE * places_file = fopen(FN_3201_PLACES.c_str(), "r"); if (places_file == 0) { perror(FN_3201_PLACES.c_str()); exit(1); } word_attribute::Flags base_attributes{word_attribute::place::grab()}; read_3201_default(places_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(places_file); } { std::string const FN_3201_CROSSWD{DATA_DIR + "/3201/files/CROSSWD.TXT"}; FILE * crosswd_file = fopen(FN_3201_CROSSWD.c_str(), "r"); if (crosswd_file == 0) { perror(FN_3201_CROSSWD.c_str()); exit(1); } word_attribute::Flags base_attributes; read_3201_default(crosswd_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(crosswd_file); } { std::string const FN_3201_CRSWD_D{DATA_DIR + "/3201/files/CRSWD-D.TXT"}; FILE * crswd_d_file = fopen(FN_3201_CRSWD_D.c_str(), "r"); if (crswd_d_file == 0) { perror(FN_3201_CRSWD_D.c_str()); exit(1); } word_attribute::Flags base_attributes; read_3201_default(crswd_d_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(crswd_d_file); } { std::string const FN_3201_ACRONYMS{DATA_DIR + "/3201/files/ACRONYMS.TXT"}; FILE * acronyms_file = fopen(FN_3201_ACRONYMS.c_str(), "r"); if (acronyms_file == 0) { perror(FN_3201_ACRONYMS.c_str()); exit(1); } word_attribute::Flags base_attributes{word_attribute::acronym::grab()}; read_3201_default(acronyms_file, l0, l1, l2, l3, l4, l5, prefix, base_attributes, mm); fclose(acronyms_file); } { std::string const FN_3202{DATA_DIR + "/3202/files/mthesaur.txt"}; FILE * input_file = fopen(FN_3202.c_str(), "r"); if (input_file == 0) { perror(FN_3202.c_str()); exit(1); } read_3202(input_file, l0, l1, l2, l3, l4, l5, prefix, mm); fclose(input_file); } { std::string const FN_3203_MOBYPOS{DATA_DIR + "/3203/files/mobypos.txt"}; FILE * mobypos_file = fopen(FN_3203_MOBYPOS.c_str(), "r"); if (mobypos_file == 0) { perror(FN_3203_MOBYPOS.c_str()); exit(1); } read_3203_mobypos(mobypos_file, l0, l1, l2, l3, l4, l5, prefix, mm); fclose(mobypos_file); } // remove leading underscore prefix.erase(0, 1); { auto sa_status = mm.save_as( OUTPUT_DIR + "/" + prefix + ".h", {matchable::save_as__content::matchables::grab()}, matchable::save_as__spread_mode::wrap::grab() ); std::cout << "generating stage 0 matchables: " << l0 << " "; if (l1 == "nil") std::cout << "--"; else std::cout << l1 << " "; if (l2 == "nil") std::cout << "--"; else std::cout << l2 << " "; if (l3 == "nil") std::cout << "--"; else std::cout << l3 << " "; if (l4 == "nil") std::cout << "--"; else std::cout << l4 << " "; if (l5 == "nil") std::cout << "--"; else std::cout << l5 << " "; std::cout << "---------> " << sa_status << std::endl; if (sa_status != matchable::save_as__status::success::grab()) return 1; } return 0; } void print_usage() { std::cout << "program expects 8 arguments:\n" << " [1] data directory\n" << " [2] output directory\n" << "\n" << " * letter arguments form an inclusive prefix filter\n" << " * letters are case sensitive\n" << "\n" << " [3] first letter\n" << " - include words starting with <first letter>\n" << " - single letter word of 'first letter' is included when second letter is 'a'\n" << " and 'third letter' is either 'a' or 'nil'\n" << " [4] second letter\n" << " - include words seconding with <second letter>\n" << " - two letter word of 'first letter' + 'second letter' is included when \n" << " 'third letter' is either 'a' or 'nil'\n" << " - can be disabled for single letter prefix by setting to 'nil'\n" << " [5] third letter\n" << " - include words thirding with <third letter>\n" << " - can be disabled for two letter prefix by setting to 'nil'\n" << " - ignored when second letter is 'nil'\n" << " [6] fourth letter\n" << " - include words fourthing with <fourth letter>\n" << " - can be disabled for three letter prefix by setting to 'nil'\n" << " - ignored when <second letter> or <third letter> is 'nil'\n" << " [7] fifth letter\n" << " - include words fifthing with <fifth letter>\n" << " - can be disabled for four letter prefix by setting to 'nil'\n" << " - ignored when <second letter> or <third letter> or <fourth letter> is 'nil'\n" << " [8] sixth letter\n" << " - include words sixthing with <sixth letter>\n" << " - can be disabled for five letter prefix by setting to 'nil'\n" << " - ignored when <second letter> or <third letter> or <fourth letter>\n" << " or <fifth letter> is 'nil'\n" << std::flush; } bool has_responsibility(char letter, char prefix_element) { if (letter == prefix_element) return true; // support symbols supported by MATCHABLE // store them all under the left most leaf if (prefix_element == 'A') { for (auto const & [code, symbol] : matchable::escapable::code_symbol_pairs()) if (symbol.length() > 0 && symbol[0] == letter) return true; } return false; } bool passes_prefix_filter( std::string const & word, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5 ) { if (word.size() == 0) return false; // if word does not start with l0 then fail if (!has_responsibility(word[0], l0[0])) return false; if (l1 != "nil") { if (word.size() > 1) { // if word does not second with l1 then fail if (!has_responsibility(word[1], l1[0])) return false; if (l2 != "nil") { if (word.size() > 2) { // if 3+ letter word does not third with l2 then fail if (!has_responsibility(word[2], l2[0])) return false; if (l3 != "nil") { if (word.size() > 3) { // if 4+ letter word does not fourth with l3 then fail if (!has_responsibility(word[3], l3[0])) return false; if (l4 != "nil") { if (word.size() > 4) { // if 5+ letter word does not fifth with l4 then fail if (!has_responsibility(word[4], l4[0])) return false; if (l5 != "nil") { if (word.size() > 5) { // if 6+ letter word does not sixth with l5 then fail if (!has_responsibility(word[5], l5[0])) return false; } else { // fail five letter word unless left leaf bool left_leaf = (l5[0] == 'A'); if (!left_leaf) return false; } } } else { // fail four letter word unless left leaf bool left_leaf = (l4[0] == 'A' && l5[0] == 'A') || (l4[0] == 'A' && l5 == "nil"); if (!left_leaf) return false; } } } else { // fail three letter word unless left leaf bool left_leaf = (l3[0] == 'A' && l4[0] == 'A' && l5[0] == 'A') || (l3[0] == 'A' && l4[0] == 'A' && l5 == "nil") || (l3[0] == 'A' && l4 == "nil"); if (!left_leaf) return false; } } } else { // fail two letter word unless left leaf bool left_leaf = (l2[0] == 'A' && l3[0] == 'A' && l4[0] == 'A' && l5[0] == 'A') || (l2[0] == 'A' && l3[0] == 'A' && l4[0] == 'A' && l5 == "nil") || (l2[0] == 'A' && l3[0] == 'A' && l4 == "nil") || (l2[0] == 'A' && l3 == "nil"); if (!left_leaf) return false; } } } else { // fail one letter word unless left leaf bool left_leaf = (l1[0] == 'A' && l2[0] == 'A' && l3[0] == 'A' && l4[0] == 'A' && l5[0] == 'A') || (l1[0] == 'A' && l2[0] == 'A' && l3[0] == 'A' && l4[0] == 'A' && l5 == "nil") || (l1[0] == 'A' && l2[0] == 'A' && l3[0] == 'A' && l4 == "nil") || (l1[0] == 'A' && l2[0] == 'A' && l3 == "nil") || (l1[0] == 'A' && l2 == "nil"); if (!left_leaf) return false; } } return true; } bool passes_status_filter(word_attribute::Flags const & status) { if (status.is_set(word_attribute::invisible_ascii::grab())) return false; if (status.is_set(word_attribute::unmatchable_symbols::grab())) return false; if (symbols_off && status.is_set(word_attribute::matchable_symbols::grab())) return false; return true; } bool passes_filter( std::string const & word, word_attribute::Flags const & status, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5 ) { if (word.size() < 1) return false; if (word.size() > MAX_WORD_LENGTH) return false; if (!passes_prefix_filter(word, l0, l1, l2, l3, l4, l5)) return false; if (!passes_status_filter(status)) return false; return true; } void read_3201_default( FILE * input_file, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5, std::string const & prefix, word_attribute::Flags const & base_attributes, matchable::MatchableMaker & mm ) { std::string word; word_attribute::Flags attributes; while (true) { attributes = base_attributes; if (!read_3201_default_line(input_file, word, attributes)) break; if (word.size() == 0) continue; if (!passes_filter(word, attributes, l0, l1, l2, l3, l4, l5)) continue; if (attributes.is_set(word_attribute::compound::grab()) && word.find('-') == std::string::npos && word.find(' ') == std::string::npos) attributes.unset(word_attribute::compound::grab()); add_word(word, prefix, attributes, mm); } } void read_3202( FILE * input_file, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5, std::string const & prefix, matchable::MatchableMaker & mm ) { std::string word; parts_of_speech::Flags pos_flags; word_attribute::Flags attributes; int ch = 0; while (true) { word.clear(); while (true) { ch = fgetc(input_file); if (ch == EOF || ch == 10 || ch == 13 || ch == ',') break; word += (char) ch; } if (passes_filter(word, attributes, l0, l1, l2, l3, l4, l5) && word.size() > 0) add_word(word, prefix, attributes, pos_flags, mm); if (ch == EOF) break; } } void read_3203_mobypos( FILE * input_file, std::string const & l0, std::string const & l1, std::string const & l2, std::string const & l3, std::string const & l4, std::string const & l5, std::string const & prefix, matchable::MatchableMaker & mm ) { std::string word; parts_of_speech::Flags pos_flags; word_attribute::Flags attributes; while (true) { if (!read_3203_mobypos_line(input_file, word, attributes, pos_flags)) break; if (word.size() == 0) continue; if (!passes_filter(word, attributes, l0, l1, l2, l3, l4, l5)) continue; add_word(word, prefix, attributes, pos_flags, mm); } } void update_word_attribute(word_attribute::Flags & flags, int & ch) { if (ch < 32 || ch > 126) { flags.set(word_attribute::invisible_ascii::grab()); ch = '?'; } else { if (ch < 'A' || (ch > 'Z' && ch < 'a') || ch > 'z') { bool found{false}; for (auto const & [code, symbol] : matchable::escapable::code_symbol_pairs()) { if (symbol.length() > 0 && symbol[0] == ch) { found = true; break; } } if (found) flags.set(word_attribute::matchable_symbols::grab()); else flags.set(word_attribute::unmatchable_symbols::grab()); } } } bool read_3201_default_line( FILE * f, std::string & word, word_attribute::Flags & attributes ) { word.clear(); int ch; while (true) { ch = fgetc(f); if (ch == EOF) return false; if (ch == 10 || ch == 13) { while (true) { ch = fgetc(f); if (ch == EOF) return false; if (ch != 10 && ch != 13) { ungetc(ch, f); break; } } break; } update_word_attribute(attributes, ch); word += (char) ch; } return true; } bool read_3203_mobypos_line( FILE * f, std::string & word, word_attribute::Flags & attributes, parts_of_speech::Flags & pos_flags ) { word.clear(); attributes.clear(); pos_flags.clear(); int ch; while (true) { ch = fgetc(f); if (ch == EOF) return false; if (ch == 10 || ch == 13) continue; if (ch == (int) '\\') break; update_word_attribute(attributes, ch); word += (char) ch; } while (true) { ch = fgetc(f); if (ch == EOF) return false; if (ch == 10 || ch == 13) break; if (ch < 32 || ch > 126) attributes.set(word_attribute::invisible_ascii::grab()); if (ch == (int) '!') ch = (int) 'n'; auto ch_str = std::string(1, (char) ch); auto pos_flag = parts_of_speech::from_string(ch_str); if (!pos_flag.is_nil()) pos_flags.set(pos_flag); } return true; } void add_word( std::string const & word, std::string const & prefix, word_attribute::Flags const & wsf, matchable::MatchableMaker & mm ) { static parts_of_speech::Flags const empty_pos_flags; add_word(word, prefix, wsf, empty_pos_flags, mm); } void add_word( std::string const & word, std::string const & prefix, word_attribute::Flags const & wsf, parts_of_speech::Flags const & pos_flags, matchable::MatchableMaker & mm ) { // create new variant std::string const escaped = "esc_" + matchable::escapable::escape_all(word); mm.grab("word" + prefix)->add_variant(escaped); // property for parts of speech std::vector<std::string> property_values; for (auto p : parts_of_speech::variants_by_string()) { if (pos_flags.is_set(p)) property_values.push_back("1"); else property_values.push_back("0"); } mm.grab("word" + prefix)->set_propertyvect(escaped, "pos", property_values); // property for ordinal sum { int ordinal_sum = 0; int letter = 0; for (int letter_index = 0; letter_index < (int) word.size(); ++letter_index) { letter = (int) word[letter_index]; if (letter > 96) letter -= 96; else if (letter > 64) letter -= 64; if (letter >= 1 && letter <= 26) ordinal_sum += letter; } mm.grab("word" + prefix)->set_property(escaped, "ordinal_summation", std::to_string(ordinal_sum)); } // properties from word attributes { auto set_prop = [&](word_attribute::Type att) { if (wsf.is_set(att)) { std::string const prop_name = std::string("is_") + att.as_string(); mm.grab("word" + prefix)->set_property(escaped, prop_name, "1"); } }; set_prop(word_attribute::name::grab()); set_prop(word_attribute::male_name::grab()); set_prop(word_attribute::female_name::grab()); set_prop(word_attribute::place::grab()); set_prop(word_attribute::compound::grab()); set_prop(word_attribute::acronym::grab()); } }
29.175899
106
0.4996
shtroizel
0ff32d66ecfa9c4791ae69e092e4236fd829e9de
5,605
cpp
C++
sandbox/src/sandbox_layer.cpp
christopher-besch/lynton
5af1f84fcb39db5717074b5bbc5fe4097d67c1ea
[ "MIT" ]
7
2021-01-04T15:16:48.000Z
2021-12-01T21:43:42.000Z
sandbox/src/sandbox_layer.cpp
christopher-besch/lynton
5af1f84fcb39db5717074b5bbc5fe4097d67c1ea
[ "MIT" ]
3
2021-08-12T21:28:54.000Z
2021-09-02T13:20:18.000Z
sandbox/src/sandbox_layer.cpp
christopher-besch/lynton
5af1f84fcb39db5717074b5bbc5fe4097d67c1ea
[ "MIT" ]
1
2021-07-26T10:41:56.000Z
2021-07-26T10:41:56.000Z
#include "sandbox_layer.h" #include <iostream> #include <stdio.h> SandboxLayer::~SandboxLayer() { delete m_smiley; delete m_dot1; delete m_dot2; delete m_dot3; delete m_dot4; delete m_dot5; } void SandboxLayer::setup() { m_font = new Lynton::Font("res/iosevka-extendedbold.ttf", 50); // image unsigned short img_id = m_tex_lib->load_from_file("res/awesomeface.png"); m_tex_lib->lock(img_id); uint32_t* pixels = static_cast<uint32_t*>(m_tex_lib->get_pixels(img_id)); for(int x = 0; x < m_tex_lib->get_height(img_id); ++x) for(int y = 0; y < m_tex_lib->get_width(img_id); ++y) if(x % 2 && y % 2) pixels[x + y * m_tex_lib->get_width(img_id)] = m_renderer->get_color(0x10, 0x50, 0xff, 0xff); m_tex_lib->unlock(img_id); // text // unsigned short text_id = m_tex_lib->load_from_text("Hello World!", {0xff, 0x20, 0x20, 0xff}, m_font); unsigned short dot_id1 = m_tex_lib->create_blank(5, 5); m_tex_lib->lock(dot_id1); pixels = static_cast<uint32_t*>(m_tex_lib->get_pixels(dot_id1)); for(int i = 0; i < m_tex_lib->get_pixel_count(dot_id1); ++i) { pixels[i] = m_renderer->get_color(0x00, 0x00, 0xff, 0xff); } m_tex_lib->unlock(dot_id1); unsigned short dot_id2 = m_tex_lib->create_blank(5, 5); m_tex_lib->lock(dot_id2); pixels = static_cast<uint32_t*>(m_tex_lib->get_pixels(dot_id2)); for(int i = 0; i < m_tex_lib->get_pixel_count(dot_id2); ++i) { pixels[i] = m_renderer->get_color(0xff, 0x00, 0x00, 0xff); } m_tex_lib->unlock(dot_id2); unsigned short dot_id3 = m_tex_lib->create_blank(5, 5); m_tex_lib->lock(dot_id3); pixels = static_cast<uint32_t*>(m_tex_lib->get_pixels(dot_id3)); for(int i = 0; i < m_tex_lib->get_pixel_count(dot_id3); ++i) { pixels[i] = m_renderer->get_color(0x00, 0xff, 0x00, 0xff); } m_tex_lib->unlock(dot_id3); m_smiley = new Lynton::TexQuad(m_renderer, m_camera, {0, 0, 1}, 50, 50); m_smiley->set_texture_id(img_id); m_dot1 = new Lynton::TexQuad(m_renderer, m_camera, {0, 0, 1}, m_tex_lib->get_width(dot_id1), m_tex_lib->get_height(dot_id1)); m_dot1->set_texture_id(dot_id1); m_dot2 = new Lynton::TexQuad(m_renderer, m_camera, {100, 0, 1}, m_tex_lib->get_width(dot_id2), m_tex_lib->get_height(dot_id2)); m_dot2->set_texture_id(dot_id2); m_dot3 = new Lynton::TexQuad(m_renderer, m_camera, {0, 100, 1}, m_tex_lib->get_width(dot_id3), m_tex_lib->get_height(dot_id3)); m_dot3->set_texture_id(dot_id3); m_dot4 = new Lynton::TexQuad(m_renderer, m_camera, {100, 100, 1}, m_tex_lib->get_width(dot_id1), m_tex_lib->get_height(dot_id1)); m_dot4->set_texture_id(dot_id1); m_dot5 = new Lynton::TexQuad(m_renderer, m_camera, {50, 50, 1}, m_tex_lib->get_width(dot_id2), m_tex_lib->get_height(dot_id2)); m_dot5->set_texture_id(dot_id1); } void SandboxLayer::update(double frame_time) { // translate objects m_v_right += 200 * frame_time * (m_a_right - m_a_left); m_v_down += 200 * frame_time * (m_a_down - m_a_up); m_camera->translate_local_global_scale(200 * (m_a_right - m_a_left) * frame_time, 200 * (m_a_down - m_a_up) * frame_time); // scale Lynton::scalar scale_factor = 1 / (1 + 3 * frame_time * (m_scale_up - m_scale_down)); // m_camera->scale(1, scale_factor); m_smiley->scale_at(scale_factor, m_smiley->get_middle()); // rotate m_smiley->rotate_at(90 * (m_rotate_right - m_rotate_left) * frame_time, m_smiley->get_middle()); } void SandboxLayer::render() { m_smiley->render(); m_dot1->render(); m_dot2->render(); m_dot3->render(); m_dot4->render(); m_dot5->render(); } bool SandboxLayer::handle_event(SDL_Event e) { // todo: filter out repetitions if(e.type == SDL_KEYDOWN) { switch(e.key.keysym.sym) { // translation case SDLK_w: m_a_up = true; return true; case SDLK_s: m_a_down = true; return true; case SDLK_a: m_a_left = true; return true; case SDLK_d: m_a_right = true; return true; // scaling case SDLK_q: m_scale_up = true; return true; case SDLK_e: m_scale_down = true; return true; // flipping case SDLK_r: // m_camera->flip_hor_at(m_camera->get_middle()); return true; case SDLK_f: // m_camera->flip_ver_at(m_camera->get_middle()); return true; // rotation case SDLK_t: m_rotate_left = true; return true; case SDLK_g: m_rotate_right = true; return true; } } else if(e.type == SDL_KEYUP) { switch(e.key.keysym.sym) { // translation case SDLK_w: m_a_up = false; return true; case SDLK_s: m_a_down = false; return true; case SDLK_a: m_a_left = false; return true; case SDLK_d: m_a_right = false; return true; // scaling case SDLK_q: m_scale_up = false; return true; case SDLK_e: m_scale_down = false; return true; // rotation case SDLK_t: m_rotate_left = false; return true; case SDLK_g: m_rotate_right = false; return true; } } return false; }
31.312849
133
0.598394
christopher-besch
0ff45fc3c2861ee6bd6ddd916c7e9b0e4c50417f
347
cpp
C++
BAC/exercises/warmup/UVa10300.cpp
Anyrainel/aoapc-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
3
2017-08-15T06:00:01.000Z
2018-12-10T09:05:53.000Z
BAC/exercises/warmup/UVa10300.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
null
null
null
BAC/exercises/warmup/UVa10300.cpp
Anyrainel/aoapc-related-code
e787a01380698fb9236d933462052f97b20e6132
[ "Apache-2.0" ]
2
2017-09-16T18:46:27.000Z
2018-05-22T05:42:03.000Z
// UVa10300 Ecological Premium // Rujia Liu // 题意:输入n个三元组(a,b,c),计算a*c之和 // 注意事项:观察题目中的数值范围可以发现结果需要用long long保存 #include<iostream> using namespace std; int main() { int T; cin >> T; while(T--) { long long n, a, b, c, sum = 0; cin >> n; while(n--) { cin >> a >> b >> c; sum += a * c; } cout << sum << "\n"; } return 0; }
18.263158
52
0.544669
Anyrainel
0ff4695ec24edf2c83f4172a52b1d353974a2a5b
2,956
hpp
C++
src/grovevdiv/grovevdiv.hpp
engagementlab/upm
9be920dbcd4ff9f333bce27e937a6e72e46899d6
[ "MIT" ]
1
2018-11-08T03:59:01.000Z
2018-11-08T03:59:01.000Z
src/grovevdiv/grovevdiv.hpp
engagementlab/upm
9be920dbcd4ff9f333bce27e937a6e72e46899d6
[ "MIT" ]
null
null
null
src/grovevdiv/grovevdiv.hpp
engagementlab/upm
9be920dbcd4ff9f333bce27e937a6e72e46899d6
[ "MIT" ]
1
2018-11-08T03:59:04.000Z
2018-11-08T03:59:04.000Z
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2014 Intel Corporation. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <string> #include <iostream> #include <stdint.h> #include <mraa/aio.h> // reference voltage in millivolts #define GROVEVDIV_VREF 4980 // default ADC resolution #define GROVEVDIV_ADC_RES 1024 namespace upm { /** * @deprecated This library is being replaced by libupm-vdiv * @brief Grove Voltage Divider Sensor library * @defgroup grovevdiv libupm-grovevdiv * @ingroup seeed analog electric robok */ /** * @library grovevdiv * @sensor grovevdiv * @comname Grove Voltage Divider * @type electric * @man seeed * @con analog * @kit robok * @deprecated This class is being replaced by VDiv * * @brief API for the Grove Voltage Divider Sensor * * UPM module for the Grove Voltage Divider sensor * * @image html grovevdiv.jpg * @snippet grovevdiv.cxx Interesting */ class GroveVDiv { public: /** * Grove Voltage Divider sensor constructor * * @param pin Analog pin to use */ GroveVDiv(int pin); /** * Grove Voltage Divider destructor */ ~GroveVDiv(); /** * Gets the conversion value from the sensor * * @param samples Specifies how many samples to average over * @return Average ADC conversion value */ unsigned int value(unsigned int samples); /** * Computes the measured voltage * * @param gain Gain switch, either 3 or 10 for Grove * @param val Measured voltage (from value()) * @param vref Reference voltage in millivolts * @param res ADC resolution * * @return Measured voltage */ float computedValue(uint8_t gain, unsigned int val, int vref=GROVEVDIV_VREF, int res=GROVEVDIV_ADC_RES); private: mraa_aio_context m_aio; }; }
29.267327
80
0.691813
engagementlab
0ff515c7aa82fdf70250d722c2e31b6707010cf3
1,675
cpp
C++
Sorting_algorithms/Insertion_sort.cpp
codewithsatyam/Data_Structures_n_Algorithms_in_CPP-
59f6d63c7f996aa0693a530dd3cfe32a80d91bf9
[ "MIT" ]
null
null
null
Sorting_algorithms/Insertion_sort.cpp
codewithsatyam/Data_Structures_n_Algorithms_in_CPP-
59f6d63c7f996aa0693a530dd3cfe32a80d91bf9
[ "MIT" ]
null
null
null
Sorting_algorithms/Insertion_sort.cpp
codewithsatyam/Data_Structures_n_Algorithms_in_CPP-
59f6d63c7f996aa0693a530dd3cfe32a80d91bf9
[ "MIT" ]
null
null
null
//Program to sort a sequence using insertion sort #include <iostream> using namespace std; void in_sort(int[], int); ////////////////////////////////////////////////////////////////////////////////////// int main() { int arr[50], n; cout << "*************INSERTION_SORT*************" << endl; cout << "How many elements do you want to create with...(max50):" << endl; cin >> n; cout << "Enter the elements of array:" << endl; for (int i = 0; i < n; i++) cin >> arr[i]; in_sort(arr, n); cout << "The sorted array is given below:" << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; cout << endl; return 0; } ////////////////////////////////////////////////////////////////////////////////////// void in_sort(int AR[], int size) { int key = 0, j = 0; for (int i = 1; i < size; i++) { key = AR[i]; j = i - 1; while (j >= 0 && key < AR[j]) { AR[j + 1] = AR[j]; j -= 1; } AR[j + 1] = key; cout << "Array after pass-" << i << "-is : "; for (int k = 0; k < size; k++) cout << AR[k] << " "; cout << endl; } } /****************** output: *************INSERTION_SORT************* How many elements do you want to create with...(max50): 7 Enter the elements of array: 9 4 3 2 34 1 6 Array after pass-1-is : 4 9 3 2 34 1 6 Array after pass-2-is : 3 4 9 2 34 1 6 Array after pass-3-is : 2 3 4 9 34 1 6 Array after pass-4-is : 2 3 4 9 34 1 6 Array after pass-5-is : 1 2 3 4 9 34 6 Array after pass-6-is : 1 2 3 4 6 9 34 The sorted array is given below: 1 2 3 4 6 9 34 *******************/
26.171875
86
0.429254
codewithsatyam
0ff65ce6dcc20a5c7e249c3136ee14ac3e98129c
5,008
hpp
C++
src/uTensor/ops/Dsp.hpp
koson/uTensor
d486d0be89ee98762d4e84b7614a30902413fdb5
[ "Apache-2.0" ]
1,047
2017-12-30T06:46:01.000Z
2022-03-30T05:03:20.000Z
src/uTensor/ops/Dsp.hpp
koson/uTensor
d486d0be89ee98762d4e84b7614a30902413fdb5
[ "Apache-2.0" ]
115
2018-01-15T12:55:36.000Z
2021-11-20T19:33:20.000Z
src/uTensor/ops/Dsp.hpp
koson/uTensor
d486d0be89ee98762d4e84b7614a30902413fdb5
[ "Apache-2.0" ]
171
2017-12-30T17:14:17.000Z
2022-03-23T12:45:32.000Z
#ifndef UTENSOR_DSP_OPS_H #define UTENSOR_DSP_OPS_H #include "uTensor/core/operatorBase.hpp" // Based on MFCC op from // https://github.com/ARM-software/ML-KWS-for-MCU/blob/master/Deployment/Source/MFCC/mfcc.h namespace uTensor { namespace ReferenceOperators { #define SAMP_FREQ 16000 #define NUM_FBANK_BINS 40 #define MEL_LOW_FREQ 20 #define MEL_HIGH_FREQ 4000 #define M_2PI 6.283185307179586476925286766559005 template <typename T> void convolution_kernel() {} // This MFCC operator allocates all the tensors required for use on // construction, then releases on destruction. template <typename Tin, typename Tout> class FixedMfccOperator : public OperatorInterface<1, 1> { public: enum names_in : uint8_t { in }; enum names_out : uint8_t { out }; FixedMfccOperator(int frame_len, int num_mfcc_features, int mfcc_dec_bits); ~FixedMfccOperator(); private: float** create_mel_fbank(); void populate_dct_matrix(int32_t input_length, int32_t coefficient_count); static inline float InverseMelScale(float mel_freq) { return 700.0f * (expf(mel_freq / 1127.0f) - 1.0f); } static inline float MelScale(float freq) { return 1127.0f * logf(1.0f + freq / 700.0f); } protected: virtual void compute() {} private: int frame_len; int num_mfcc_features; int frame_len_padded; int mfcc_dec_bits; Tensor frame; // float Tensor buffer; // float Tensor mel_energies; // float Tensor window_func; // float Tensor fbank_filter_first; // int 32 Tensor fbank_filter_last; // int 32 float** mel_fbank; Tensor dct_matrix; }; template <typename Tin, typename Tout> FixedMfccOperator<Tin, Tout>::FixedMfccOperator(int frame_len, int num_mfcc_features, int mfcc_dec_bits) : frame_len(frame_len), num_mfcc_features(num_mfcc_features), frame_len_padded(pow(2, ceil((log(frame_len) / log(2))))), mfcc_dec_bits(mfcc_dec_bits), frame(new RamTensor({frame_len_padded}, flt)), buffer(new RamTensor({frame_len_padded}, flt)), // mel_energies(new RamTensor({NUM_FBANK_BINS}, flt)), window_func(new RamTensor({frame_len}, flt)), fbank_filter_first(new RamTensor({NUM_FBANK_BINS}, i32)), fbank_filter_last(new RamTensor({NUM_FBANK_BINS}, i32)), dct_matrix(new RamTensor({NUM_FBANK_BINS * num_mfcc_features}, flt)) { for (int i = 0; i < frame_len; i++) window_func(i) = 0.5 - 0.5 * cos(M_2PI * ((float)i) / (frame_len)); mel_fbank = create_mel_fbank(); populate_dct_matrix(NUM_FBANK_BINS, num_mfcc_features); } template <typename Tin, typename Tout> FixedMfccOperator<Tin, Tout>::~FixedMfccOperator() { for (int i = 0; i < NUM_FBANK_BINS; i++) delete mel_fbank[i]; delete mel_fbank; } template <typename Tin, typename Tout> float** FixedMfccOperator<Tin, Tout>::create_mel_fbank() { int32_t bin, i; int32_t num_fft_bins = frame_len_padded / 2; float fft_bin_width = ((float)SAMP_FREQ) / frame_len_padded; float mel_low_freq = MelScale(MEL_LOW_FREQ); float mel_high_freq = MelScale(MEL_HIGH_FREQ); float mel_freq_delta = (mel_high_freq - mel_low_freq) / (NUM_FBANK_BINS + 1); float* this_bin = new float[num_fft_bins]; float** mel_fbank = new float*[NUM_FBANK_BINS]; for (bin = 0; bin < NUM_FBANK_BINS; bin++) { float left_mel = mel_low_freq + bin * mel_freq_delta; float center_mel = mel_low_freq + (bin + 1) * mel_freq_delta; float right_mel = mel_low_freq + (bin + 2) * mel_freq_delta; int32_t first_index = -1, last_index = -1; for (i = 0; i < num_fft_bins; i++) { float freq = (fft_bin_width * i); // center freq of this fft bin. float mel = MelScale(freq); this_bin[i] = 0.0; if (mel > left_mel && mel < right_mel) { float weight; if (mel <= center_mel) { weight = (mel - left_mel) / (center_mel - left_mel); } else { weight = (right_mel - mel) / (right_mel - center_mel); } this_bin[i] = weight; if (first_index == -1) first_index = i; last_index = i; } } fbank_filter_first(bin) = first_index; fbank_filter_last(bin) = last_index; mel_fbank[bin] = new float[last_index - first_index + 1]; int32_t j = 0; // copy the part we care about for (i = first_index; i <= last_index; i++) { mel_fbank[bin][j++] = this_bin[i]; } } delete[] this_bin; return mel_fbank; } template <typename Tin, typename Tout> void FixedMfccOperator<Tin, Tout>::populate_dct_matrix( int32_t input_length, int32_t coefficient_count) { int32_t k, n; float normalizer; arm_sqrt_f32(2.0 / (float)input_length, &normalizer); for (k = 0; k < coefficient_count; k++) { for (n = 0; n < input_length; n++) { dct_matrix(k * input_length + n) = normalizer * cos(((double)M_PI) / input_length * (n + 0.5) * k); } } } } } // namespace uTensor #endif
31.496855
91
0.666534
koson
0ff6f77d2eb90376cbfd389b0f045f3d7221385d
997
cpp
C++
2504/main2.cpp
leesk0502/BOJ_Solving
fa4c7fe7e9b9a7bf464531ade6705f8c6c1ae3ce
[ "Apache-2.0" ]
null
null
null
2504/main2.cpp
leesk0502/BOJ_Solving
fa4c7fe7e9b9a7bf464531ade6705f8c6c1ae3ce
[ "Apache-2.0" ]
null
null
null
2504/main2.cpp
leesk0502/BOJ_Solving
fa4c7fe7e9b9a7bf464531ade6705f8c6c1ae3ce
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <stdlib.h> #include <string> #include <iostream> #include <vector> using namespace std; int get(string s){ if( s.compare("()") == 0 ) return 2; if( s.compare("[]") == 0 ) return 3; if( s.length() == 0 ) return 1; if( s.length() == 1 ){ printf("0"); exit(1); } // (()[]) // ()(), ()[], [](), [][], (), [] int sum = 0; vector<char> v; string re = ""; for(int i=0; i<s.length(); i++){ char c = s.at(i); re += c; if( c == '(' || c == '[' ){ v.push_back(c); } else if( c == ')' ){ if( v.back() == '(' ) v.pop_back(); if( v.size() == 0 ) { sum += 2 * get(re.substr(1, re.length() - 2)); re = ""; } } else if( c == ']' ){ if( v.back() == '[' ) v.pop_back(); if( v.size() == 0 ) { sum += 3 * get(re.substr(1, re.length() - 2)); re = ""; } } } return sum; } int main(){ string s; cin >> s; printf("%d", get(s)); return 0; }
18.462963
54
0.405216
leesk0502
0ff7943593e469e420472718be4d923fb14ccc8c
35,536
cxx
C++
extern/FBXSDK/samples/ViewScene/DrawScene.cxx
maxortner01/ansel
cf9930c921ca439968daa29b242a1b532030088a
[ "BSD-2-Clause" ]
2
2019-04-04T07:26:54.000Z
2019-07-07T20:48:30.000Z
extern/FBXSDK/samples/ViewScene/DrawScene.cxx
maxortner01/ansel
cf9930c921ca439968daa29b242a1b532030088a
[ "BSD-2-Clause" ]
null
null
null
extern/FBXSDK/samples/ViewScene/DrawScene.cxx
maxortner01/ansel
cf9930c921ca439968daa29b242a1b532030088a
[ "BSD-2-Clause" ]
null
null
null
/**************************************************************************************** Copyright (C) 2015 Autodesk, Inc. All rights reserved. Use of this software is subject to the terms of the Autodesk license agreement provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. ****************************************************************************************/ #include "DrawScene.h" #include "SceneCache.h" #include "GetPosition.h" void DrawNode(FbxNode* pNode, FbxTime& lTime, FbxAnimLayer * pAnimLayer, FbxAMatrix& pParentGlobalPosition, FbxAMatrix& pGlobalPosition, FbxPose* pPose, ShadingMode pShadingMode); void DrawMarker(FbxAMatrix& pGlobalPosition); void DrawSkeleton(FbxNode* pNode, FbxAMatrix& pParentGlobalPosition, FbxAMatrix& pGlobalPosition); void DrawMesh(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer, FbxAMatrix& pGlobalPosition, FbxPose* pPose, ShadingMode pShadingMode); void ComputeShapeDeformation(FbxMesh* pMesh, FbxTime& pTime, FbxAnimLayer * pAnimLayer, FbxVector4* pVertexArray); void ComputeClusterDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxCluster* pCluster, FbxAMatrix& pVertexTransformMatrix, FbxTime pTime, FbxPose* pPose); void ComputeLinearDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray, FbxPose* pPose); void ComputeDualQuaternionDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray, FbxPose* pPose); void ComputeSkinDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray, FbxPose* pPose); void ReadVertexCacheData(FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray); void DrawCamera(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer, FbxAMatrix& pGlobalPosition); void DrawLight(const FbxNode* pNode, const FbxTime& pTime, const FbxAMatrix& pGlobalPosition); void DrawNull(FbxAMatrix& pGlobalPosition); void MatrixScale(FbxAMatrix& pMatrix, double pValue); void MatrixAddToDiagonal(FbxAMatrix& pMatrix, double pValue); void MatrixAdd(FbxAMatrix& pDstMatrix, FbxAMatrix& pSrcMatrix); void InitializeLights(const FbxScene* pScene, const FbxTime & pTime, FbxPose* pPose) { // Set ambient light. Turn on light0 and set its attributes to default (white directional light in Z axis). // If the scene contains at least one light, the attributes of light0 will be overridden. LightCache::IntializeEnvironment(pScene->GetGlobalSettings().GetAmbientColor()); // Setting the lights before drawing the whole scene const int lLightCount = pScene->GetSrcObjectCount<FbxLight>(); for (int lLightIndex = 0; lLightIndex < lLightCount; ++lLightIndex) { FbxLight * lLight = pScene->GetSrcObject<FbxLight>(lLightIndex); FbxNode * lNode = lLight->GetNode(); if (lNode) { FbxAMatrix lGlobalPosition = GetGlobalPosition(lNode, pTime, pPose); FbxAMatrix lGeometryOffset = GetGeometry(lNode); FbxAMatrix lGlobalOffPosition = lGlobalPosition * lGeometryOffset; DrawLight(lNode, pTime, lGlobalOffPosition); } } } // Draw recursively each node of the scene. To avoid recomputing // uselessly the global positions, the global position of each // node is passed to it's children while browsing the node tree. // If the node is part of the given pose for the current scene, // it will be drawn at the position specified in the pose, Otherwise // it will be drawn at the given time. void DrawNodeRecursive(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer, FbxAMatrix& pParentGlobalPosition, FbxPose* pPose, ShadingMode pShadingMode) { FbxAMatrix lGlobalPosition = GetGlobalPosition(pNode, pTime, pPose, &pParentGlobalPosition); if (pNode->GetNodeAttribute()) { // Geometry offset. // it is not inherited by the children. FbxAMatrix lGeometryOffset = GetGeometry(pNode); FbxAMatrix lGlobalOffPosition = lGlobalPosition * lGeometryOffset; DrawNode(pNode, pTime, pAnimLayer, pParentGlobalPosition, lGlobalOffPosition, pPose, pShadingMode); } const int lChildCount = pNode->GetChildCount(); for (int lChildIndex = 0; lChildIndex < lChildCount; ++lChildIndex) { DrawNodeRecursive(pNode->GetChild(lChildIndex), pTime, pAnimLayer, lGlobalPosition, pPose, pShadingMode); } } // Draw the node following the content of it's node attribute. void DrawNode(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer, FbxAMatrix& pParentGlobalPosition, FbxAMatrix& pGlobalPosition, FbxPose* pPose, ShadingMode pShadingMode) { FbxNodeAttribute* lNodeAttribute = pNode->GetNodeAttribute(); if (lNodeAttribute) { // All lights has been processed before the whole scene because they influence every geometry. if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eMarker) { DrawMarker(pGlobalPosition); } else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eSkeleton) { DrawSkeleton(pNode, pParentGlobalPosition, pGlobalPosition); } // NURBS and patch have been converted into triangluation meshes. else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eMesh) { DrawMesh(pNode, pTime, pAnimLayer, pGlobalPosition, pPose, pShadingMode); } else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eCamera) { DrawCamera(pNode, pTime, pAnimLayer, pGlobalPosition); } else if (lNodeAttribute->GetAttributeType() == FbxNodeAttribute::eNull) { DrawNull(pGlobalPosition); } } else { // Draw a Null for nodes without attribute. DrawNull(pGlobalPosition); } } // Draw a small box where the node is located. void DrawMarker(FbxAMatrix& pGlobalPosition) { GlDrawMarker(pGlobalPosition); } // Draw a limb between the node and its parent. void DrawSkeleton(FbxNode* pNode, FbxAMatrix& pParentGlobalPosition, FbxAMatrix& pGlobalPosition) { FbxSkeleton* lSkeleton = (FbxSkeleton*) pNode->GetNodeAttribute(); // Only draw the skeleton if it's a limb node and if // the parent also has an attribute of type skeleton. if (lSkeleton->GetSkeletonType() == FbxSkeleton::eLimbNode && pNode->GetParent() && pNode->GetParent()->GetNodeAttribute() && pNode->GetParent()->GetNodeAttribute()->GetAttributeType() == FbxNodeAttribute::eSkeleton) { GlDrawLimbNode(pParentGlobalPosition, pGlobalPosition); } } // Draw the vertices of a mesh. void DrawMesh(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer, FbxAMatrix& pGlobalPosition, FbxPose* pPose, ShadingMode pShadingMode) { FbxMesh* lMesh = pNode->GetMesh(); const int lVertexCount = lMesh->GetControlPointsCount(); // No vertex to draw. if (lVertexCount == 0) { return; } const VBOMesh * lMeshCache = static_cast<const VBOMesh *>(lMesh->GetUserDataPtr()); // If it has some defomer connection, update the vertices position const bool lHasVertexCache = lMesh->GetDeformerCount(FbxDeformer::eVertexCache) && (static_cast<FbxVertexCacheDeformer*>(lMesh->GetDeformer(0, FbxDeformer::eVertexCache)))->Active.Get(); const bool lHasShape = lMesh->GetShapeCount() > 0; const bool lHasSkin = lMesh->GetDeformerCount(FbxDeformer::eSkin) > 0; const bool lHasDeformation = lHasVertexCache || lHasShape || lHasSkin; FbxVector4* lVertexArray = NULL; if (!lMeshCache || lHasDeformation) { lVertexArray = new FbxVector4[lVertexCount]; memcpy(lVertexArray, lMesh->GetControlPoints(), lVertexCount * sizeof(FbxVector4)); } if (lHasDeformation) { // Active vertex cache deformer will overwrite any other deformer if (lHasVertexCache) { ReadVertexCacheData(lMesh, pTime, lVertexArray); } else { if (lHasShape) { // Deform the vertex array with the shapes. ComputeShapeDeformation(lMesh, pTime, pAnimLayer, lVertexArray); } //we need to get the number of clusters const int lSkinCount = lMesh->GetDeformerCount(FbxDeformer::eSkin); int lClusterCount = 0; for (int lSkinIndex = 0; lSkinIndex < lSkinCount; ++lSkinIndex) { lClusterCount += ((FbxSkin *)(lMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin)))->GetClusterCount(); } if (lClusterCount) { // Deform the vertex array with the skin deformer. ComputeSkinDeformation(pGlobalPosition, lMesh, pTime, lVertexArray, pPose); } } if (lMeshCache) lMeshCache->UpdateVertexPosition(lMesh, lVertexArray); } glPushMatrix(); glMultMatrixd((const double*)pGlobalPosition); if (lMeshCache) { lMeshCache->BeginDraw(pShadingMode); const int lSubMeshCount = lMeshCache->GetSubMeshCount(); for (int lIndex = 0; lIndex < lSubMeshCount; ++lIndex) { if (pShadingMode == SHADING_MODE_SHADED) { const FbxSurfaceMaterial * lMaterial = pNode->GetMaterial(lIndex); if (lMaterial) { const MaterialCache * lMaterialCache = static_cast<const MaterialCache *>(lMaterial->GetUserDataPtr()); if (lMaterialCache) { lMaterialCache->SetCurrentMaterial(); } } else { // Draw green for faces without material MaterialCache::SetDefaultMaterial(); } } lMeshCache->Draw(lIndex, pShadingMode); } lMeshCache->EndDraw(); } else { // OpenGL driver is too lower and use Immediate Mode glColor4f(0.5f, 0.5f, 0.5f, 1.0f); const int lPolygonCount = lMesh->GetPolygonCount(); for (int lPolygonIndex = 0; lPolygonIndex < lPolygonCount; lPolygonIndex++) { const int lVerticeCount = lMesh->GetPolygonSize(lPolygonIndex); glBegin(GL_LINE_LOOP); for (int lVerticeIndex = 0; lVerticeIndex < lVerticeCount; lVerticeIndex++) { glVertex3dv((GLdouble *)lVertexArray[lMesh->GetPolygonVertex(lPolygonIndex, lVerticeIndex)]); } glEnd(); } } glPopMatrix(); delete [] lVertexArray; } // Deform the vertex array with the shapes contained in the mesh. void ComputeShapeDeformation(FbxMesh* pMesh, FbxTime& pTime, FbxAnimLayer * pAnimLayer, FbxVector4* pVertexArray) { int lVertexCount = pMesh->GetControlPointsCount(); FbxVector4* lSrcVertexArray = pVertexArray; FbxVector4* lDstVertexArray = new FbxVector4[lVertexCount]; memcpy(lDstVertexArray, pVertexArray, lVertexCount * sizeof(FbxVector4)); int lBlendShapeDeformerCount = pMesh->GetDeformerCount(FbxDeformer::eBlendShape); for(int lBlendShapeIndex = 0; lBlendShapeIndex<lBlendShapeDeformerCount; ++lBlendShapeIndex) { FbxBlendShape* lBlendShape = (FbxBlendShape*)pMesh->GetDeformer(lBlendShapeIndex, FbxDeformer::eBlendShape); int lBlendShapeChannelCount = lBlendShape->GetBlendShapeChannelCount(); for(int lChannelIndex = 0; lChannelIndex<lBlendShapeChannelCount; ++lChannelIndex) { FbxBlendShapeChannel* lChannel = lBlendShape->GetBlendShapeChannel(lChannelIndex); if(lChannel) { // Get the percentage of influence on this channel. FbxAnimCurve* lFCurve = pMesh->GetShapeChannel(lBlendShapeIndex, lChannelIndex, pAnimLayer); if (!lFCurve) continue; double lWeight = lFCurve->Evaluate(pTime); /* If there is only one targetShape on this channel, the influence is easy to calculate: influence = (targetShape - baseGeometry) * weight * 0.01 dstGeometry = baseGeometry + influence But if there are more than one targetShapes on this channel, this is an in-between blendshape, also called progressive morph. The calculation of influence is different. For example, given two in-between targets, the full weight percentage of first target is 50, and the full weight percentage of the second target is 100. When the weight percentage reach 50, the base geometry is already be fully morphed to the first target shape. When the weight go over 50, it begin to morph from the first target shape to the second target shape. To calculate influence when the weight percentage is 25: 1. 25 falls in the scope of 0 and 50, the morphing is from base geometry to the first target. 2. And since 25 is already half way between 0 and 50, so the real weight percentage change to the first target is 50. influence = (firstTargetShape - baseGeometry) * (25-0)/(50-0) * 100 dstGeometry = baseGeometry + influence To calculate influence when the weight percentage is 75: 1. 75 falls in the scope of 50 and 100, the morphing is from the first target to the second. 2. And since 75 is already half way between 50 and 100, so the real weight percentage change to the second target is 50. influence = (secondTargetShape - firstTargetShape) * (75-50)/(100-50) * 100 dstGeometry = firstTargetShape + influence */ // Find the two shape indices for influence calculation according to the weight. // Consider index of base geometry as -1. int lShapeCount = lChannel->GetTargetShapeCount(); double* lFullWeights = lChannel->GetTargetShapeFullWeights(); // Find out which scope the lWeight falls in. int lStartIndex = -1; int lEndIndex = -1; for(int lShapeIndex = 0; lShapeIndex<lShapeCount; ++lShapeIndex) { if(lWeight > 0 && lWeight <= lFullWeights[0]) { lEndIndex = 0; break; } if(lWeight > lFullWeights[lShapeIndex] && lWeight < lFullWeights[lShapeIndex+1]) { lStartIndex = lShapeIndex; lEndIndex = lShapeIndex + 1; break; } } FbxShape* lStartShape = NULL; FbxShape* lEndShape = NULL; if(lStartIndex > -1) { lStartShape = lChannel->GetTargetShape(lStartIndex); } if(lEndIndex > -1) { lEndShape = lChannel->GetTargetShape(lEndIndex); } //The weight percentage falls between base geometry and the first target shape. if(lStartIndex == -1 && lEndShape) { double lEndWeight = lFullWeights[0]; // Calculate the real weight. lWeight = (lWeight/lEndWeight) * 100; // Initialize the lDstVertexArray with vertex of base geometry. memcpy(lDstVertexArray, lSrcVertexArray, lVertexCount * sizeof(FbxVector4)); for (int j = 0; j < lVertexCount; j++) { // Add the influence of the shape vertex to the mesh vertex. FbxVector4 lInfluence = (lEndShape->GetControlPoints()[j] - lSrcVertexArray[j]) * lWeight * 0.01; lDstVertexArray[j] += lInfluence; } } //The weight percentage falls between two target shapes. else if(lStartShape && lEndShape) { double lStartWeight = lFullWeights[lStartIndex]; double lEndWeight = lFullWeights[lEndIndex]; // Calculate the real weight. lWeight = ((lWeight-lStartWeight)/(lEndWeight-lStartWeight)) * 100; // Initialize the lDstVertexArray with vertex of the previous target shape geometry. memcpy(lDstVertexArray, lStartShape->GetControlPoints(), lVertexCount * sizeof(FbxVector4)); for (int j = 0; j < lVertexCount; j++) { // Add the influence of the shape vertex to the previous shape vertex. FbxVector4 lInfluence = (lEndShape->GetControlPoints()[j] - lStartShape->GetControlPoints()[j]) * lWeight * 0.01; lDstVertexArray[j] += lInfluence; } } }//If lChannel is valid }//For each blend shape channel }//For each blend shape deformer memcpy(pVertexArray, lDstVertexArray, lVertexCount * sizeof(FbxVector4)); delete [] lDstVertexArray; } //Compute the transform matrix that the cluster will transform the vertex. void ComputeClusterDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxCluster* pCluster, FbxAMatrix& pVertexTransformMatrix, FbxTime pTime, FbxPose* pPose) { FbxCluster::ELinkMode lClusterMode = pCluster->GetLinkMode(); FbxAMatrix lReferenceGlobalInitPosition; FbxAMatrix lReferenceGlobalCurrentPosition; FbxAMatrix lAssociateGlobalInitPosition; FbxAMatrix lAssociateGlobalCurrentPosition; FbxAMatrix lClusterGlobalInitPosition; FbxAMatrix lClusterGlobalCurrentPosition; FbxAMatrix lReferenceGeometry; FbxAMatrix lAssociateGeometry; FbxAMatrix lClusterGeometry; FbxAMatrix lClusterRelativeInitPosition; FbxAMatrix lClusterRelativeCurrentPositionInverse; if (lClusterMode == FbxCluster::eAdditive && pCluster->GetAssociateModel()) { pCluster->GetTransformAssociateModelMatrix(lAssociateGlobalInitPosition); // Geometric transform of the model lAssociateGeometry = GetGeometry(pCluster->GetAssociateModel()); lAssociateGlobalInitPosition *= lAssociateGeometry; lAssociateGlobalCurrentPosition = GetGlobalPosition(pCluster->GetAssociateModel(), pTime, pPose); pCluster->GetTransformMatrix(lReferenceGlobalInitPosition); // Multiply lReferenceGlobalInitPosition by Geometric Transformation lReferenceGeometry = GetGeometry(pMesh->GetNode()); lReferenceGlobalInitPosition *= lReferenceGeometry; lReferenceGlobalCurrentPosition = pGlobalPosition; // Get the link initial global position and the link current global position. pCluster->GetTransformLinkMatrix(lClusterGlobalInitPosition); // Multiply lClusterGlobalInitPosition by Geometric Transformation lClusterGeometry = GetGeometry(pCluster->GetLink()); lClusterGlobalInitPosition *= lClusterGeometry; lClusterGlobalCurrentPosition = GetGlobalPosition(pCluster->GetLink(), pTime, pPose); // Compute the shift of the link relative to the reference. //ModelM-1 * AssoM * AssoGX-1 * LinkGX * LinkM-1*ModelM pVertexTransformMatrix = lReferenceGlobalInitPosition.Inverse() * lAssociateGlobalInitPosition * lAssociateGlobalCurrentPosition.Inverse() * lClusterGlobalCurrentPosition * lClusterGlobalInitPosition.Inverse() * lReferenceGlobalInitPosition; } else { pCluster->GetTransformMatrix(lReferenceGlobalInitPosition); lReferenceGlobalCurrentPosition = pGlobalPosition; // Multiply lReferenceGlobalInitPosition by Geometric Transformation lReferenceGeometry = GetGeometry(pMesh->GetNode()); lReferenceGlobalInitPosition *= lReferenceGeometry; // Get the link initial global position and the link current global position. pCluster->GetTransformLinkMatrix(lClusterGlobalInitPosition); lClusterGlobalCurrentPosition = GetGlobalPosition(pCluster->GetLink(), pTime, pPose); // Compute the initial position of the link relative to the reference. lClusterRelativeInitPosition = lClusterGlobalInitPosition.Inverse() * lReferenceGlobalInitPosition; // Compute the current position of the link relative to the reference. lClusterRelativeCurrentPositionInverse = lReferenceGlobalCurrentPosition.Inverse() * lClusterGlobalCurrentPosition; // Compute the shift of the link relative to the reference. pVertexTransformMatrix = lClusterRelativeCurrentPositionInverse * lClusterRelativeInitPosition; } } // Deform the vertex array in classic linear way. void ComputeLinearDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray, FbxPose* pPose) { // All the links must have the same link mode. FbxCluster::ELinkMode lClusterMode = ((FbxSkin*)pMesh->GetDeformer(0, FbxDeformer::eSkin))->GetCluster(0)->GetLinkMode(); int lVertexCount = pMesh->GetControlPointsCount(); FbxAMatrix* lClusterDeformation = new FbxAMatrix[lVertexCount]; memset(lClusterDeformation, 0, lVertexCount * sizeof(FbxAMatrix)); double* lClusterWeight = new double[lVertexCount]; memset(lClusterWeight, 0, lVertexCount * sizeof(double)); if (lClusterMode == FbxCluster::eAdditive) { for (int i = 0; i < lVertexCount; ++i) { lClusterDeformation[i].SetIdentity(); } } // For all skins and all clusters, accumulate their deformation and weight // on each vertices and store them in lClusterDeformation and lClusterWeight. int lSkinCount = pMesh->GetDeformerCount(FbxDeformer::eSkin); for ( int lSkinIndex=0; lSkinIndex<lSkinCount; ++lSkinIndex) { FbxSkin * lSkinDeformer = (FbxSkin *)pMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin); int lClusterCount = lSkinDeformer->GetClusterCount(); for ( int lClusterIndex=0; lClusterIndex<lClusterCount; ++lClusterIndex) { FbxCluster* lCluster = lSkinDeformer->GetCluster(lClusterIndex); if (!lCluster->GetLink()) continue; FbxAMatrix lVertexTransformMatrix; ComputeClusterDeformation(pGlobalPosition, pMesh, lCluster, lVertexTransformMatrix, pTime, pPose); int lVertexIndexCount = lCluster->GetControlPointIndicesCount(); for (int k = 0; k < lVertexIndexCount; ++k) { int lIndex = lCluster->GetControlPointIndices()[k]; // Sometimes, the mesh can have less points than at the time of the skinning // because a smooth operator was active when skinning but has been deactivated during export. if (lIndex >= lVertexCount) continue; double lWeight = lCluster->GetControlPointWeights()[k]; if (lWeight == 0.0) { continue; } // Compute the influence of the link on the vertex. FbxAMatrix lInfluence = lVertexTransformMatrix; MatrixScale(lInfluence, lWeight); if (lClusterMode == FbxCluster::eAdditive) { // Multiply with the product of the deformations on the vertex. MatrixAddToDiagonal(lInfluence, 1.0 - lWeight); lClusterDeformation[lIndex] = lInfluence * lClusterDeformation[lIndex]; // Set the link to 1.0 just to know this vertex is influenced by a link. lClusterWeight[lIndex] = 1.0; } else // lLinkMode == FbxCluster::eNormalize || lLinkMode == FbxCluster::eTotalOne { // Add to the sum of the deformations on the vertex. MatrixAdd(lClusterDeformation[lIndex], lInfluence); // Add to the sum of weights to either normalize or complete the vertex. lClusterWeight[lIndex] += lWeight; } }//For each vertex }//lClusterCount } //Actually deform each vertices here by information stored in lClusterDeformation and lClusterWeight for (int i = 0; i < lVertexCount; i++) { FbxVector4 lSrcVertex = pVertexArray[i]; FbxVector4& lDstVertex = pVertexArray[i]; double lWeight = lClusterWeight[i]; // Deform the vertex if there was at least a link with an influence on the vertex, if (lWeight != 0.0) { lDstVertex = lClusterDeformation[i].MultT(lSrcVertex); if (lClusterMode == FbxCluster::eNormalize) { // In the normalized link mode, a vertex is always totally influenced by the links. lDstVertex /= lWeight; } else if (lClusterMode == FbxCluster::eTotalOne) { // In the total 1 link mode, a vertex can be partially influenced by the links. lSrcVertex *= (1.0 - lWeight); lDstVertex += lSrcVertex; } } } delete [] lClusterDeformation; delete [] lClusterWeight; } // Deform the vertex array in Dual Quaternion Skinning way. void ComputeDualQuaternionDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray, FbxPose* pPose) { // All the links must have the same link mode. FbxCluster::ELinkMode lClusterMode = ((FbxSkin*)pMesh->GetDeformer(0, FbxDeformer::eSkin))->GetCluster(0)->GetLinkMode(); int lVertexCount = pMesh->GetControlPointsCount(); int lSkinCount = pMesh->GetDeformerCount(FbxDeformer::eSkin); FbxDualQuaternion* lDQClusterDeformation = new FbxDualQuaternion[lVertexCount]; memset(lDQClusterDeformation, 0, lVertexCount * sizeof(FbxDualQuaternion)); double* lClusterWeight = new double[lVertexCount]; memset(lClusterWeight, 0, lVertexCount * sizeof(double)); // For all skins and all clusters, accumulate their deformation and weight // on each vertices and store them in lClusterDeformation and lClusterWeight. for ( int lSkinIndex=0; lSkinIndex<lSkinCount; ++lSkinIndex) { FbxSkin * lSkinDeformer = (FbxSkin *)pMesh->GetDeformer(lSkinIndex, FbxDeformer::eSkin); int lClusterCount = lSkinDeformer->GetClusterCount(); for ( int lClusterIndex=0; lClusterIndex<lClusterCount; ++lClusterIndex) { FbxCluster* lCluster = lSkinDeformer->GetCluster(lClusterIndex); if (!lCluster->GetLink()) continue; FbxAMatrix lVertexTransformMatrix; ComputeClusterDeformation(pGlobalPosition, pMesh, lCluster, lVertexTransformMatrix, pTime, pPose); FbxQuaternion lQ = lVertexTransformMatrix.GetQ(); FbxVector4 lT = lVertexTransformMatrix.GetT(); FbxDualQuaternion lDualQuaternion(lQ, lT); int lVertexIndexCount = lCluster->GetControlPointIndicesCount(); for (int k = 0; k < lVertexIndexCount; ++k) { int lIndex = lCluster->GetControlPointIndices()[k]; // Sometimes, the mesh can have less points than at the time of the skinning // because a smooth operator was active when skinning but has been deactivated during export. if (lIndex >= lVertexCount) continue; double lWeight = lCluster->GetControlPointWeights()[k]; if (lWeight == 0.0) continue; // Compute the influence of the link on the vertex. FbxDualQuaternion lInfluence = lDualQuaternion * lWeight; if (lClusterMode == FbxCluster::eAdditive) { // Simply influenced by the dual quaternion. lDQClusterDeformation[lIndex] = lInfluence; // Set the link to 1.0 just to know this vertex is influenced by a link. lClusterWeight[lIndex] = 1.0; } else // lLinkMode == FbxCluster::eNormalize || lLinkMode == FbxCluster::eTotalOne { if(lClusterIndex == 0) { lDQClusterDeformation[lIndex] = lInfluence; } else { // Add to the sum of the deformations on the vertex. // Make sure the deformation is accumulated in the same rotation direction. // Use dot product to judge the sign. double lSign = lDQClusterDeformation[lIndex].GetFirstQuaternion().DotProduct(lDualQuaternion.GetFirstQuaternion()); if( lSign >= 0.0 ) { lDQClusterDeformation[lIndex] += lInfluence; } else { lDQClusterDeformation[lIndex] -= lInfluence; } } // Add to the sum of weights to either normalize or complete the vertex. lClusterWeight[lIndex] += lWeight; } }//For each vertex }//lClusterCount } //Actually deform each vertices here by information stored in lClusterDeformation and lClusterWeight for (int i = 0; i < lVertexCount; i++) { FbxVector4 lSrcVertex = pVertexArray[i]; FbxVector4& lDstVertex = pVertexArray[i]; double lWeightSum = lClusterWeight[i]; // Deform the vertex if there was at least a link with an influence on the vertex, if (lWeightSum != 0.0) { lDQClusterDeformation[i].Normalize(); lDstVertex = lDQClusterDeformation[i].Deform(lDstVertex); if (lClusterMode == FbxCluster::eNormalize) { // In the normalized link mode, a vertex is always totally influenced by the links. lDstVertex /= lWeightSum; } else if (lClusterMode == FbxCluster::eTotalOne) { // In the total 1 link mode, a vertex can be partially influenced by the links. lSrcVertex *= (1.0 - lWeightSum); lDstVertex += lSrcVertex; } } } delete [] lDQClusterDeformation; delete [] lClusterWeight; } // Deform the vertex array according to the links contained in the mesh and the skinning type. void ComputeSkinDeformation(FbxAMatrix& pGlobalPosition, FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray, FbxPose* pPose) { FbxSkin * lSkinDeformer = (FbxSkin *)pMesh->GetDeformer(0, FbxDeformer::eSkin); FbxSkin::EType lSkinningType = lSkinDeformer->GetSkinningType(); if(lSkinningType == FbxSkin::eLinear || lSkinningType == FbxSkin::eRigid) { ComputeLinearDeformation(pGlobalPosition, pMesh, pTime, pVertexArray, pPose); } else if(lSkinningType == FbxSkin::eDualQuaternion) { ComputeDualQuaternionDeformation(pGlobalPosition, pMesh, pTime, pVertexArray, pPose); } else if(lSkinningType == FbxSkin::eBlend) { int lVertexCount = pMesh->GetControlPointsCount(); FbxVector4* lVertexArrayLinear = new FbxVector4[lVertexCount]; memcpy(lVertexArrayLinear, pMesh->GetControlPoints(), lVertexCount * sizeof(FbxVector4)); FbxVector4* lVertexArrayDQ = new FbxVector4[lVertexCount]; memcpy(lVertexArrayDQ, pMesh->GetControlPoints(), lVertexCount * sizeof(FbxVector4)); ComputeLinearDeformation(pGlobalPosition, pMesh, pTime, lVertexArrayLinear, pPose); ComputeDualQuaternionDeformation(pGlobalPosition, pMesh, pTime, lVertexArrayDQ, pPose); // To blend the skinning according to the blend weights // Final vertex = DQSVertex * blend weight + LinearVertex * (1- blend weight) // DQSVertex: vertex that is deformed by dual quaternion skinning method; // LinearVertex: vertex that is deformed by classic linear skinning method; int lBlendWeightsCount = lSkinDeformer->GetControlPointIndicesCount(); for(int lBWIndex = 0; lBWIndex<lBlendWeightsCount; ++lBWIndex) { double lBlendWeight = lSkinDeformer->GetControlPointBlendWeights()[lBWIndex]; pVertexArray[lBWIndex] = lVertexArrayDQ[lBWIndex] * lBlendWeight + lVertexArrayLinear[lBWIndex] * (1 - lBlendWeight); } } } void ReadVertexCacheData(FbxMesh* pMesh, FbxTime& pTime, FbxVector4* pVertexArray) { FbxVertexCacheDeformer* lDeformer = static_cast<FbxVertexCacheDeformer*>(pMesh->GetDeformer(0, FbxDeformer::eVertexCache)); FbxCache* lCache = lDeformer->GetCache(); int lChannelIndex = lCache->GetChannelIndex(lDeformer->Channel.Get()); unsigned int lVertexCount = (unsigned int)pMesh->GetControlPointsCount(); bool lReadSucceed = false; float* lReadBuf = NULL; unsigned int BufferSize = 0; if (lDeformer->Type.Get() != FbxVertexCacheDeformer::ePositions) // only process positions return; unsigned int Length = 0; lCache->Read(NULL, Length, FBXSDK_TIME_ZERO, lChannelIndex); if (Length != lVertexCount*3) // the content of the cache is by vertex not by control points (we don't support it here) return; lReadSucceed = lCache->Read(&lReadBuf, BufferSize, pTime, lChannelIndex); if (lReadSucceed) { unsigned int lReadBufIndex = 0; while (lReadBufIndex < 3*lVertexCount) { // In statements like "pVertexArray[lReadBufIndex/3].SetAt(2, lReadBuf[lReadBufIndex++])", // on Mac platform, "lReadBufIndex++" is evaluated before "lReadBufIndex/3". // So separate them. pVertexArray[lReadBufIndex/3].mData[0] = lReadBuf[lReadBufIndex]; lReadBufIndex++; pVertexArray[lReadBufIndex/3].mData[1] = lReadBuf[lReadBufIndex]; lReadBufIndex++; pVertexArray[lReadBufIndex/3].mData[2] = lReadBuf[lReadBufIndex]; lReadBufIndex++; } } } // Draw an oriented camera box where the node is located. void DrawCamera(FbxNode* pNode, FbxTime& pTime, FbxAnimLayer* pAnimLayer, FbxAMatrix& pGlobalPosition) { FbxAMatrix lCameraGlobalPosition; FbxVector4 lCameraPosition, lCameraDefaultDirection, lCameraInterestPosition; lCameraPosition = pGlobalPosition.GetT(); // By default, FBX cameras point towards the X positive axis. FbxVector4 lXPositiveAxis(1.0, 0.0, 0.0); lCameraDefaultDirection = lCameraPosition + lXPositiveAxis; lCameraGlobalPosition = pGlobalPosition; // If the camera is linked to an interest, get the interest position. if (pNode->GetTarget()) { lCameraInterestPosition = GetGlobalPosition(pNode->GetTarget(), pTime).GetT(); // Compute the required rotation to make the camera point to it's interest. FbxVector4 lCameraDirection; FbxVector4::AxisAlignmentInEulerAngle(lCameraPosition, lCameraDefaultDirection, lCameraInterestPosition, lCameraDirection); // Must override the camera rotation // to make it point to it's interest. lCameraGlobalPosition.SetR(lCameraDirection); } // Get the camera roll. FbxCamera* cam = pNode->GetCamera(); double lRoll = 0; if (cam) { lRoll = cam->Roll.Get(); FbxAnimCurve* fc = cam->Roll.GetCurve(pAnimLayer); if (fc) fc->Evaluate(pTime); } GlDrawCamera(lCameraGlobalPosition, lRoll); } // Draw a colored sphere or cone where the node is located. void DrawLight(const FbxNode* pNode, const FbxTime& pTime, const FbxAMatrix& pGlobalPosition) { const FbxLight* lLight = pNode->GetLight(); if (!lLight) return; // Must rotate the light's global position because // FBX lights point towards the Y negative axis. FbxAMatrix lLightRotation; const FbxVector4 lYNegativeAxis(-90.0, 0.0, 0.0); lLightRotation.SetR(lYNegativeAxis); const FbxAMatrix lLightGlobalPosition = pGlobalPosition * lLightRotation; glPushMatrix(); glMultMatrixd((const double*)lLightGlobalPosition); const LightCache * lLightCache = static_cast<const LightCache *>(lLight->GetUserDataPtr()); if (lLightCache) { lLightCache->SetLight(pTime); } glPopMatrix(); } // Draw a cross hair where the node is located. void DrawNull(FbxAMatrix& pGlobalPosition) { GlDrawCrossHair(pGlobalPosition); } // Scale all the elements of a matrix. void MatrixScale(FbxAMatrix& pMatrix, double pValue) { int i,j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { pMatrix[i][j] *= pValue; } } } // Add a value to all the elements in the diagonal of the matrix. void MatrixAddToDiagonal(FbxAMatrix& pMatrix, double pValue) { pMatrix[0][0] += pValue; pMatrix[1][1] += pValue; pMatrix[2][2] += pValue; pMatrix[3][3] += pValue; } // Sum two matrices element by element. void MatrixAdd(FbxAMatrix& pDstMatrix, FbxAMatrix& pSrcMatrix) { int i,j; for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { pDstMatrix[i][j] += pSrcMatrix[i][j]; } } }
37.683987
142
0.684208
maxortner01
0ff90cb2cfd637013eb559a2847f61f42b00ffc6
30,425
cpp
C++
src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/GDIExporter/FontInfo.cpp
reyqn/wpf
6858a87af432aae629e28970a14c3560bef4f349
[ "MIT" ]
1
2020-01-11T12:53:52.000Z
2020-01-11T12:53:52.000Z
src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/GDIExporter/FontInfo.cpp
reyqn/wpf
6858a87af432aae629e28970a14c3560bef4f349
[ "MIT" ]
null
null
null
src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/GDIExporter/FontInfo.cpp
reyqn/wpf
6858a87af432aae629e28970a14c3560bef4f349
[ "MIT" ]
1
2021-05-05T12:05:28.000Z
2021-05-05T12:05:28.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /************************************************************************** * * * Abstract: * * GDI font installation information and management. * * **************************************************************************/ // FontStreamContext FontStreamContext::FontStreamContext(GlyphTypeface^ source) { Debug::Assert(source != nullptr); _sourceTypeface = source; } FontStreamContext::FontStreamContext(Uri^ source, int streamLength) { Debug::Assert(source != nullptr); _sourceUri = source; _streamLength = streamLength; } void FontStreamContext::Close() { if (_stream != nullptr) { _stream->Close(); } } const int c_FontBufferSize = 32 * 1024; Stream^ CopyToMemoryStream(Stream ^ source) { MemoryStream^ dest = gcnew MemoryStream(); array<Byte>^ buffer= gcnew array<Byte>(c_FontBufferSize); int bytesRead = source->Read(buffer, 0, c_FontBufferSize); while (bytesRead > 0) { dest->Write(buffer, 0, bytesRead); bytesRead = source->Read(buffer, 0, c_FontBufferSize); } return dest; } Stream^ FontStreamContext::GetStream() { if (_stream == nullptr) { if (_sourceUri != nullptr && _sourceUri->IsFile) { _stream = File::OpenRead(_sourceUri->LocalPath); } else if (_sourceTypeface != nullptr) { // avalon returns new stream on every GetFontStream() call _stream = _sourceTypeface->GetFontStream(); if (! _stream->CanSeek) { Stream^ newstream = CopyToMemoryStream(_stream); _stream->Close(); _stream = newstream; } } } else { // ensure stream is at zero _stream->Position = 0; } return _stream; } void FontStreamContext::UpdateStreamLength() { if (_streamLength == 0) { Stream^ stream = GetStream(); if (stream == nullptr || stream->Length >= MaximumStreamLength) { _streamLength = MaximumStreamLength; } else { _streamLength = (int)stream->Length; } } } bool FontStreamContext::Equals(FontStreamContext% otherContext) { // make sure stream lengths are valid for comparison UpdateStreamLength(); otherContext.UpdateStreamLength(); if (_streamLength != otherContext._streamLength) { // streams have different lengths; definitely not the same font return false; } // otherwise compare first CompareLength bytes of both streams Stream^ thisStream = GetStream(); if (thisStream != nullptr) { Stream^ otherStream = otherContext.GetStream(); if (otherStream != nullptr) { Debug::Assert(thisStream->Length == otherStream->Length); // // Compare both streams CompareLength bytes at a time. // array<Byte>^ thisData = gcnew array<Byte>(CompareLength); array<Byte>^ otherData = gcnew array<Byte>(CompareLength); int eof = 0; // number of streams reaching eof while (eof == 0) { // Read CompareLength amount of data from both streams, or less only if eof. int thisRead = 0, otherRead = 0; while (thisRead < CompareLength) { int read = thisStream->Read(thisData, thisRead, CompareLength - thisRead); if (read == 0) { eof++; break; } thisRead += read; } while (otherRead < CompareLength) { int read = otherStream->Read(otherData, otherRead, CompareLength - otherRead); if (read == 0) { eof++; break; } otherRead += read; } if (thisRead != otherRead || eof == 1) { // One of the streams EOF'd early despite being same length. Assume both fonts aren't equal. return false; } // Compare data byte-by-byte. for (int index = 0; index < thisRead; index++) { if (thisData[index] != otherData[index]) { // byte mismatch; not the same font return false; } } } Debug::Assert(eof == 2); } } return true; } // FontInstallInfo FontInstallInfo::FontInstallInfo(Uri^ uri) { Debug::Assert(uri != nullptr); _uri = uri; } bool FontInstallInfo::Equals(FontStreamContext% context, FontInstallInfo^ otherFont) { Debug::Assert(otherFont != nullptr); if (_uri->Equals(otherFont->_uri)) { // Fonts come from same location, therefore same. return true; } // Construct stream context with other font's URI as source, // and compare the two contexts for stream sameness. FontStreamContext otherContext(otherFont->_uri, otherFont->_streamLength); try { return context.Equals(otherContext); } finally { // The comparison process may've updated stream information for otherFont. // Cache it to otherFont. otherFont->UpdateFromContext(otherContext); otherContext.Close(); } } // Class for handling TrueType font name change // fyuan, 07/28/2006 // // BUG 1772833: When installing fonts with the same name as existing fonts, GDI would not pick them. // So we need to modify TrueType font to make the names 'unique'. // // Truetype name table: http://www.microsoft.com/typography/otspec/name.htm value class TrueTypeFont { //constants for fields in Truetype name table #define NAME_FAMILY 1 #define NAME_FULLNAME 4 #define MS_PLATFORM 3 #define MS_SYMBOL_ENCODING 0 #define MS_UNICODEBMP_ENCODING 1 #define MS_LANG_EN_US 0x409 #define MAC_PLATFORM 1 #define MAC_ROMAN_ENCODING 0 #define MAC_LANG_ENGLISH 0 array<Byte>^ m_fontdata; // Complete font data unsigned m_faceIndex; // Truetype font collection index unsigned m_size; // font data size static Random ^ s_random = gcnew Random(); static int s_order = 0; public: TrueTypeFont(array<Byte>^ fontdata, unsigned faceIndex) { m_fontdata = fontdata; m_faceIndex = faceIndex; m_size = (unsigned)fontdata->Length; } // Replace font family name with new randomly generated 'unique' name // Return new family name String ^ ReplaceFontName() { unsigned base = 0; if (read32(0) == 0x74746366) // ttcf: TrueType font collection { unsigned nfonts = read32(8); if (m_faceIndex >= nfonts) { return nullptr; } base = read32(12 + m_faceIndex * 4); } unsigned version = read32(base); // TableDirectory (void)version; int ntables = read16(base + 4); for (int i = 0; i < ntables; i ++) { unsigned pos = base + 12 + i * 16; // TableEntry unsigned tag = read32(pos); if (tag == 0x6E616D65) // 'name' { return ProcessNameTable(pos); } } return nullptr; } private: // Replace font family name in name table String ^ ProcessNameTable(unsigned pos) { // TableEntry // ULONG tag // ULONG checksum // ULONG offset // ULONG length unsigned crc = read32(pos + 4); // check sum unsigned len = read32(pos + 12); unsigned nametablepos = read32(pos + 8); // offset to name table unsigned sum = CheckSum(nametablepos, len); if (sum != crc) { return nullptr; } array<Char>^ familyName; array<Char>^ newFamilyName; GenerateFamilyNameFromNametable(nametablepos, familyName, newFamilyName); if(newFamilyName == nullptr) { return nullptr; } int count = ReplaceAll(nametablepos, familyName, newFamilyName); if (count == 0) { return nullptr; } sum = CheckSum(nametablepos, len); write32(pos + 4, sum); // update checksum String^ newName = gcnew String(newFamilyName); #ifdef Testing if(newName != nullptr) { FileStream^ dest = gcnew FileStream(String::Concat("c:\\", String::Concat(newName, ".ttf")), FileMode::Create, FileAccess::Write); dest->Write(m_fontdata, 0, m_size); dest->Close(); } #endif return newName; } // Fix: Windows OS Bugs 1925144: // Extending font family name lookup to use MS <OSLANG> Unicode, MS <OSLANG> Symbol and Mac English Roman family names // (where <OSLANG> denotes the OS language). // The previous implementation was unable to rename some embedded fonts because it only checked for MS English Unicode family names // Search for the Microsoft <OSLANG> or the Macintosh English family names and generate a random alternate // When the function returns // familyName will be set to the MS <OSLANG> Unicode family name if one was found // newFamilyName will be set to the generated name (which can still happen even if an MS <OSLANG> Unicode family name was not found) void GenerateFamilyNameFromNametable(unsigned nametablepos, array<Char>^ % familyName, array<Char>^ % newFamilyName) { // NameHeader // USHORT formatSelector; // USHORT numNameRecords; // USHORT offsetToStringStorage; // from start of table array<Char>^ fallbackFamilyName = nullptr; familyName = nullptr; newFamilyName = nullptr; unsigned formatSelector = read16(nametablepos); (void)formatSelector; unsigned numNames = read16(nametablepos + 2); unsigned stringOffset = read16(nametablepos + 4); unsigned osLanguageID = (unsigned)CultureInfo::InstalledUICulture->LCID; for (unsigned i = 0; i < numNames; i++) { unsigned p = nametablepos + 6 + i * 12; unsigned nameID = read16(p + 6); if(nameID == NAME_FAMILY) { unsigned platformID = read16(p); unsigned encodingID = read16(p + 2); unsigned languageID = read16(p + 4); if(platformID == MS_PLATFORM && (encodingID == MS_UNICODEBMP_ENCODING || encodingID == MS_SYMBOL_ENCODING) && languageID == osLanguageID) { unsigned length = read16(p + 8); unsigned offset = read16(p + 10); unsigned namepos = nametablepos + stringOffset + offset; if(encodingID == MS_UNICODEBMP_ENCODING) { //The MS Unicode family name is GDI's prefered family name, dont look for any alternate names readString(namepos, length, familyName, System::Text::Encoding::BigEndianUnicode); break; } else { //Use the MS Symbol family name as a fallback in the absence of a MS Unicode name readString(namepos, length, fallbackFamilyName, System::Text::Encoding::BigEndianUnicode); } } else if(platformID == MAC_PLATFORM && encodingID == MAC_ROMAN_ENCODING && languageID == MAC_LANG_ENGLISH) { unsigned length = read16(p + 8); unsigned offset = read16(p + 10); unsigned namepos = nametablepos + stringOffset + offset; //Use the MS Symbol family name as a fallback in the absence of a MS Unicode name readString(namepos, length, fallbackFamilyName, System::Text::Encoding::ASCII); } } } if(familyName != nullptr) { newFamilyName = GenerateRandomName(familyName->Length); } else if(fallbackFamilyName != nullptr) { newFamilyName = GenerateRandomName(fallbackFamilyName->Length); } } // Replace all matches of font family name in TrueType font name table int ReplaceAll(unsigned nametablepos, array<Char>^ baseEnglishFamilyName, array<Char>^ newFamilyName) { /* Fix: Windows OS Bugs 1925144: Ported font rename logic from TTEmbed code. The previous implementation did not follow some subtle font rename conventions and created fonts that could not be located using newFamilyname Replace all Family Names, Full Family Names and Unique Names with newFamilyName given the following constraints Only replace the prefix of an MS Full Family Name that matches An existing Family Name of the same platform and language or The MS <OSLANG> Unicode Family Name Only replace the prefix of a MAC Full Family Name that matches An existing Family Name of the same platform using the following algorithm Given an EnglishBaseFamilyName //Obtained by scanning the name table for the first <OSLANG> MS Unicode Family Name //note it is possible for such a record to not exist //also note that it's not necessarily English (despite the variable's name) While scanning the name table a second time For any Family Name (MS Unicode, MS Symbol or Mac Roman) Let CurrentBaseFamily=the entry (its value, platform and language) Replace the entry's value with newFamilyName For any Full Family Name (MS Unicode, MS Symbol) If there is a CurrentBaseFamily and the entry has the same platform and language as the CurrentBaseFamily let familyNamePrefix = CurrentBaseFamily's value Else let familyNamePrefix = EnglishBaseFamilyName If a familyNamePrefix was set If the entry's value starts with familyNamePrefix Replace familyNamePrefix in the entry with newFamilyName For any Full Family Name (Mac Roman) If there is a CurrentBaseFamily and the entry has the same platform as the CurrentBaseFamily let familyNamePrefix = CurrentBaseFamily's value If the entry's value starts with familyNamePrefix Replace familyNamePrefix in the entry with newFamilyName */ int count = 0; array<Char>^ baseFamilyName = nullptr; unsigned numNames = read16(nametablepos + 2); unsigned stringOffset = read16(nametablepos + 4); unsigned basePlatformID = 0; unsigned baseEncodingID = 0; unsigned baseLanguageID = 0; for (unsigned i = 0; i < numNames; i ++) { unsigned p = nametablepos + 6 + i * 12; unsigned platformID = read16(p); unsigned encodingID = read16(p + 2); unsigned languageID = read16(p + 4); unsigned nameID = read16(p + 6); unsigned length = read16(p + 8); unsigned offset = read16(p + 10); unsigned namepos = nametablepos + stringOffset + offset; switch(nameID) { case NAME_FAMILY: { if((platformID == MS_PLATFORM) && (encodingID == MS_UNICODEBMP_ENCODING || encodingID == MS_SYMBOL_ENCODING)) { readString(namepos, length, baseFamilyName, System::Text::Encoding::BigEndianUnicode); basePlatformID = platformID; baseEncodingID = encodingID; baseLanguageID = languageID; if(ReplaceFamilyName(namepos, length, newFamilyName, System::Text::Encoding::BigEndianUnicode)) { count++; } } else if((platformID == MAC_PLATFORM) && (encodingID == MAC_ROMAN_ENCODING)) { readString(namepos, length, baseFamilyName, System::Text::Encoding::ASCII); basePlatformID = platformID; baseEncodingID = encodingID; baseLanguageID = languageID; if(ReplaceFamilyName(namepos, length, newFamilyName, System::Text::Encoding::ASCII)) { count++; } } break; } case NAME_FULLNAME: { if((platformID == MS_PLATFORM) && (encodingID == MS_UNICODEBMP_ENCODING || encodingID == MS_SYMBOL_ENCODING)) { array<Char>^ familyName = nullptr; if(baseFamilyName != nullptr && basePlatformID == platformID && baseLanguageID == languageID) { familyName = baseFamilyName; } else { familyName = baseEnglishFamilyName; } if(familyName != nullptr) { if(ReplaceFullFamilyName(namepos, length, familyName, newFamilyName, System::Text::Encoding::BigEndianUnicode)) { count++; } } } else if((platformID == MAC_PLATFORM) && (encodingID == MAC_ROMAN_ENCODING)) { if(baseFamilyName != nullptr && basePlatformID == platformID) { if(ReplaceFullFamilyName(namepos, length, baseFamilyName, newFamilyName, System::Text::Encoding::ASCII)) { count++; } } } break; } } //end switch } //end for return count; } //Replaces a Family Name entry //newFamilyName must be the same byte length as length when encoded bool ReplaceFamilyName(unsigned namepos, unsigned length, array<Char>^ newFamilyName, System::Text::Encoding^ encoding) { if(length == (unsigned)encoding->GetByteCount(newFamilyName)) { writeString(namepos, length, newFamilyName, encoding); return true; } return false; } //Replaces the Family Name prefix of a Full Family Name //if the entry starts with familyName then familyName is replaced with newFamilyName //familyName and newFamilyName must have the same length bool ReplaceFullFamilyName(unsigned namepos, unsigned length, array<Char>^ familyName, array<Char>^ newFamilyName, System::Text::Encoding^ encoding) { array<Char>^ fullName = nullptr; readString(namepos, length, fullName, encoding); if(newFamilyName->Length <= familyName->Length) { if(AreCharsEqual(familyName, fullName, newFamilyName->Length)) { writeString(namepos, encoding->GetByteCount(newFamilyName), newFamilyName, encoding); return true; } } return false; } array<Char>^ GenerateRandomName(unsigned length) { array<Char>^ newName = gcnew array<Char>(length); unsigned start = 2; if(newName->Length < 2) { start = 0; } else { newName[0] = (Char)('0' + ((s_order / 10) % 10)); newName[1] = (Char)('0' + (s_order % 10)); } for (unsigned i = start; i < (unsigned)newName->Length; i++) { newName[i] = (Char)('a' + s_random->Next(26)); // random low-case character } s_order ++; return newName; } //Returns true if // a and b have up to length characters // and // a and b's first length characters are identical bool AreCharsEqual(array<Char>^ a, array<Char>^ b, unsigned length) { unsigned i = 0; if(((unsigned)a->Length < length || ((unsigned)b->Length) < length)) { return false; } for(i = 0; i < length; i++) { if(a[i] != b[i]) { return false; } } return true; } // Truetype font table checksum unsigned CheckSum(unsigned pos, unsigned len) { len = (len + 3) / 4; // Always DWORD aligned unsigned sum = 0; for (unsigned i = 0; i < len; i ++) { sum += read32(pos); pos += 4; } return sum; } // Read two bytes and reverse byte order unsigned short read16(unsigned offset) { return (m_fontdata[offset] << 8) | m_fontdata[offset + 1]; } // Read four bytes and reverse byte order unsigned read32(unsigned offset) { return (m_fontdata[offset] << 24) | (m_fontdata[offset + 1] << 16) | (m_fontdata[offset + 2] << 8) + m_fontdata[offset + 3]; } // Write two bytes in reverse byte order void write16(unsigned offset, unsigned short value) { m_fontdata[offset + 1] = (Byte) (value); value >>= 8; m_fontdata[offset ] = (Byte) (value); } // Write four bytes in reverse byte order void write32(unsigned offset, unsigned value) { m_fontdata[offset + 3] = (Byte) (value); value >>= 8; m_fontdata[offset + 2] = (Byte) (value); value >>= 8; m_fontdata[offset + 1] = (Byte) (value); value >>= 8; m_fontdata[offset ] = (Byte) (value); } //write a string with a given encoding //only System::Text::Encoding::ASCII and System::Text::Encoding::BigEndianUnicode are safe to use) //returns false if the bytes written exceeds byteLength bool writeString(unsigned offset, unsigned byteLength, String^ value, System::Text::Encoding^ encoding) { unsigned charCount = (encoding->IsSingleByte) ? byteLength : (byteLength / 2); return byteLength >= (unsigned)encoding->GetBytes(value, 0, charCount, m_fontdata, offset); } //write a string with a given encoding //only System::Text::Encoding::ASCII and System::Text::Encoding::BigEndianUnicode are safe to use) void writeString(unsigned offset, unsigned byteLength, array<Char>^ value, System::Text::Encoding^ encoding) { unsigned charCount = (encoding->IsSingleByte) ? byteLength : (byteLength / 2); encoding->GetBytes(value, 0, charCount, m_fontdata, offset); } //reads a string with a given encoding //value is resize to be exactly big enough to accept the string //only System::Text::Encoding::ASCII and System::Text::Encoding::BigEndianUnicode are safe to use) void readString(unsigned offset, unsigned byteLength, array<Char>^ % value, System::Text::Encoding^ encoding) { unsigned charCount = (encoding->IsSingleByte) ? byteLength : (byteLength / 2); if(value == nullptr || (unsigned)value->Length != charCount) { value = gcnew array<Char>(charCount); } encoding->GetChars(m_fontdata, offset, byteLength, value, 0); } }; Object^ FontInstallInfo::Install(FontStreamContext% context, String^ % newFamilyName, unsigned faceIndex) { // cache font stream length and hash if provided in context UpdateFromContext(context); Object^ installHandle = nullptr; // Comment out AddFontResourceEx path. We need to modify font name table before installation. // So we can't use original file content. /* if (_uri->IsFile) { // install font from file int numberAdded = CNativeMethods::AddFontResourceEx(_uri->LocalPath, FR_PRIVATE | FR_NOT_ENUM, nullptr); if (numberAdded > 0) { installHandle = _uri->LocalPath; } } */ if (installHandle == nullptr) { // read stream and install from memory context.UpdateStreamLength(); int size = context.StreamLength; if (size > 0 && size < FontStreamContext::MaximumStreamLength) { Stream^ stream = context.GetStream(); if (stream != nullptr) { array<Byte>^ data = gcnew array<Byte>(size); // ensure we read entire font file for GDI install if (stream->Read(data, 0, size) == size) { TrueTypeFont font(data, faceIndex); newFamilyName = font.ReplaceFontName(); DWORD nFonts = 0; installHandle = CNativeMethods::AddFontMemResourceEx(data, size, NULL, &nFonts); } } } } return installHandle; } void FontInstallInfo::Uninstall(Object^ installHandle) { Debug::Assert(installHandle != nullptr); String^ filename = dynamic_cast<String^>(installHandle); if (filename != nullptr) { // uninstall local file int errCode = CNativeMethods::RemoveFontResourceEx(filename, FR_PRIVATE | FR_NOT_ENUM, NULL); Debug::Assert(errCode != 0, "RemoveFontResourceEx failed"); } else { GdiFontResourceSafeHandle^ hfont = dynamic_cast<GdiFontResourceSafeHandle^>(installHandle); if (hfont != nullptr) { // We can't unstall the font from memory now, because it could be still needed by printer driver // in local EMF spooling print job. Move such handles into OldPrivateFonts CGDIDevice::OldPrivateFonts->Add(hfont); // hfont->Close(); uninstall from memory } } } void FontInstallInfo::UpdateFromContext(FontStreamContext% context) { // save font stream length to avoid reopening the stream in the future // when comparing lengths if (_streamLength == 0) { _streamLength = context.StreamLength; } } // FontInfo FontInfo::FontInfo() { } FontInfo::FontInfo(Uri^ systemUri) { Debug::Assert(systemUri != nullptr, "System font URI can't be null"); _systemInstall = gcnew FontInstallInfo(systemUri); } bool FontInfo::UsePrivate(GlyphTypeface^ typeface) { // // Prepare GDI to render text using GlyphTypeface. First see if GlyphTypeface is already // installed as private or system font, in which case we simply use one of those. // Otherwise install the GlyphTypeface font into GDI. // Debug::Assert(typeface != nullptr); FontStreamContext installContext(typeface); try { FontInstallInfo^ install = gcnew FontInstallInfo(Microsoft::Internal::AlphaFlattener::Utility::GetFontUri(typeface)); if (_privateInstall != nullptr) { // We have a private font installed with this name. If requested typeface // matches this private font, use it, otherwise uninstall it. if (install->Equals(installContext, _privateInstall)) { return true; } else { UninstallPrivate(); } } Debug::Assert(_privateInstall == nullptr, "Private font should not be installed at this point"); if (_systemInstall != nullptr && install->Equals(installContext, _systemInstall)) { // Requested typeface matches the system-installed font; use that one. return true; } // Otherwise we need to install a new private font. _privateInstallHandle = install->Install(installContext, _newFamilyName, typeface->FaceIndex); if (_privateInstallHandle == nullptr) { return false; } else { _privateInstall = install; return true; } } finally { installContext.Close(); } } void FontInfo::UninstallPrivate() { if (_privateInstall != nullptr) { Debug::Assert(_privateInstallHandle != nullptr); _privateInstall->Uninstall(_privateInstallHandle); _privateInstall = nullptr; _privateInstallHandle = nullptr; _newFamilyName = nullptr; } }
33.215066
154
0.542679
reyqn
0ffa0e41e122a5cc406baabe97d2bdb7973355d9
8,371
cc
C++
chrome/browser/policy/configuration_policy_provider_test.cc
robclark/chromium
f097b6ea775c27e5352c94ddddd264dd2af21479
[ "BSD-3-Clause" ]
1
2019-07-22T23:03:26.000Z
2019-07-22T23:03:26.000Z
chrome/browser/policy/configuration_policy_provider_test.cc
robclark/chromium
f097b6ea775c27e5352c94ddddd264dd2af21479
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/policy/configuration_policy_provider_test.cc
robclark/chromium
f097b6ea775c27e5352c94ddddd264dd2af21479
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/policy/configuration_policy_provider_test.h" #include "base/bind.h" #include "base/values.h" #include "chrome/browser/policy/asynchronous_policy_loader.h" #include "chrome/browser/policy/asynchronous_policy_provider.h" #include "chrome/browser/policy/configuration_policy_provider.h" #include "chrome/browser/policy/mock_configuration_policy_provider.h" #include "chrome/browser/policy/policy_map.h" #include "policy/policy_constants.h" #include "testing/gmock/include/gmock/gmock.h" using ::testing::Mock; using ::testing::_; namespace policy { namespace test_policy_definitions { const char kKeyString[] = "StringPolicy"; const char kKeyBoolean[] = "BooleanPolicy"; const char kKeyInteger[] = "IntegerPolicy"; const char kKeyStringList[] = "StringListPolicy"; const char kKeyDictionary[] = "DictionaryPolicy"; static const PolicyDefinitionList::Entry kEntries[] = { { kKeyString, base::Value::TYPE_STRING }, { kKeyBoolean, base::Value::TYPE_BOOLEAN }, { kKeyInteger, base::Value::TYPE_INTEGER }, { kKeyStringList, base::Value::TYPE_LIST }, { kKeyDictionary, base::Value::TYPE_DICTIONARY }, }; const PolicyDefinitionList kList = { kEntries, kEntries + arraysize(kEntries) }; } // namespace test_policy_definitions PolicyProviderTestHarness::PolicyProviderTestHarness() {} PolicyProviderTestHarness::~PolicyProviderTestHarness() {} ConfigurationPolicyProviderTest::ConfigurationPolicyProviderTest() {} ConfigurationPolicyProviderTest::~ConfigurationPolicyProviderTest() {} void ConfigurationPolicyProviderTest::SetUp() { AsynchronousPolicyTestBase::SetUp(); test_harness_.reset((*GetParam())()); test_harness_->SetUp(); provider_.reset( test_harness_->CreateProvider(&test_policy_definitions::kList)); // Some providers do a reload on init. Make sure any notifications generated // are fired now. loop_.RunAllPending(); PolicyMap policy_map; EXPECT_TRUE(provider_->Provide(&policy_map)); EXPECT_TRUE(policy_map.empty()); } void ConfigurationPolicyProviderTest::TearDown() { // Give providers the chance to clean up after themselves on the file thread. provider_.reset(); AsynchronousPolicyTestBase::TearDown(); } void ConfigurationPolicyProviderTest::CheckValue( const char* policy_name, const base::Value& expected_value, base::Closure install_value) { // Install the value, reload policy and check the provider for the value. install_value.Run(); provider_->RefreshPolicies(); loop_.RunAllPending(); PolicyMap policy_map; EXPECT_TRUE(provider_->Provide(&policy_map)); EXPECT_EQ(1U, policy_map.size()); EXPECT_TRUE(base::Value::Equals(&expected_value, policy_map.GetValue(policy_name))); } TEST_P(ConfigurationPolicyProviderTest, Empty) { provider_->RefreshPolicies(); loop_.RunAllPending(); PolicyMap policy_map; EXPECT_TRUE(provider_->Provide(&policy_map)); EXPECT_TRUE(policy_map.empty()); } TEST_P(ConfigurationPolicyProviderTest, StringValue) { const char kTestString[] = "string_value"; base::StringValue expected_value(kTestString); CheckValue(test_policy_definitions::kKeyString, expected_value, base::Bind(&PolicyProviderTestHarness::InstallStringPolicy, base::Unretained(test_harness_.get()), test_policy_definitions::kKeyString, kTestString)); } TEST_P(ConfigurationPolicyProviderTest, BooleanValue) { base::FundamentalValue expected_value(true); CheckValue(test_policy_definitions::kKeyBoolean, expected_value, base::Bind(&PolicyProviderTestHarness::InstallBooleanPolicy, base::Unretained(test_harness_.get()), test_policy_definitions::kKeyBoolean, true)); } TEST_P(ConfigurationPolicyProviderTest, IntegerValue) { base::FundamentalValue expected_value(42); CheckValue(test_policy_definitions::kKeyInteger, expected_value, base::Bind(&PolicyProviderTestHarness::InstallIntegerPolicy, base::Unretained(test_harness_.get()), test_policy_definitions::kKeyInteger, 42)); } TEST_P(ConfigurationPolicyProviderTest, StringListValue) { base::ListValue expected_value; expected_value.Set(0U, base::Value::CreateStringValue("first")); expected_value.Set(1U, base::Value::CreateStringValue("second")); CheckValue(test_policy_definitions::kKeyStringList, expected_value, base::Bind(&PolicyProviderTestHarness::InstallStringListPolicy, base::Unretained(test_harness_.get()), test_policy_definitions::kKeyStringList, &expected_value)); } TEST_P(ConfigurationPolicyProviderTest, DictionaryValue) { base::DictionaryValue expected_value; expected_value.SetBoolean("bool", true); expected_value.SetInteger("int", 123); expected_value.SetString("str", "omg"); base::ListValue* list = new base::ListValue(); list->Set(0U, base::Value::CreateStringValue("first")); list->Set(1U, base::Value::CreateStringValue("second")); expected_value.Set("list", list); base::DictionaryValue* dict = new base::DictionaryValue(); dict->SetString("sub", "value"); list = new base::ListValue(); base::DictionaryValue* sub = new base::DictionaryValue(); sub->SetInteger("aaa", 111); sub->SetInteger("bbb", 222); list->Append(sub); sub = new base::DictionaryValue(); sub->SetString("ccc", "333"); sub->SetString("ddd", "444"); list->Append(sub); dict->Set("sublist", list); expected_value.Set("dict", dict); CheckValue(test_policy_definitions::kKeyDictionary, expected_value, base::Bind(&PolicyProviderTestHarness::InstallDictionaryPolicy, base::Unretained(test_harness_.get()), test_policy_definitions::kKeyDictionary, &expected_value)); } TEST_P(ConfigurationPolicyProviderTest, RefreshPolicies) { PolicyMap policy_map; EXPECT_TRUE(provider_->Provide(&policy_map)); EXPECT_EQ(0U, policy_map.size()); // OnUpdatePolicy is called even when there are no changes. MockConfigurationPolicyObserver observer; ConfigurationPolicyObserverRegistrar registrar; registrar.Init(provider_.get(), &observer); EXPECT_CALL(observer, OnUpdatePolicy(provider_.get())).Times(1); provider_->RefreshPolicies(); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); EXPECT_TRUE(provider_->Provide(&policy_map)); EXPECT_EQ(0U, policy_map.size()); // OnUpdatePolicy is called when there are changes. test_harness_->InstallStringPolicy(test_policy_definitions::kKeyString, "value"); EXPECT_CALL(observer, OnUpdatePolicy(provider_.get())).Times(1); provider_->RefreshPolicies(); loop_.RunAllPending(); Mock::VerifyAndClearExpectations(&observer); policy_map.Clear(); EXPECT_TRUE(provider_->Provide(&policy_map)); EXPECT_EQ(1U, policy_map.size()); } TEST(ConfigurationPolicyProviderTest, FixDeprecatedPolicies) { PolicyMap policy_map; policy_map.Set(key::kProxyServerMode, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER, base::Value::CreateIntegerValue(3)); // Both these policies should be ignored, since there's a higher priority // policy available. policy_map.Set(key::kProxyMode, POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, base::Value::CreateStringValue("pac_script")); policy_map.Set(key::kProxyPacUrl, POLICY_LEVEL_RECOMMENDED, POLICY_SCOPE_USER, base::Value::CreateStringValue("http://example.com/wpad.dat")); ConfigurationPolicyProvider::FixDeprecatedPolicies(&policy_map); base::DictionaryValue expected; expected.SetInteger(key::kProxyServerMode, 3); EXPECT_EQ(1U, policy_map.size()); EXPECT_TRUE(base::Value::Equals(&expected, policy_map.GetValue(key::kProxySettings))); } } // namespace policy
36.081897
80
0.706128
robclark
0ffa7e47e1591fcb57c40fc1015c4c1f06a52ea9
5,474
hpp
C++
include/System/Threading/ThreadPoolWorkQueue.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Threading/ThreadPoolWorkQueue.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/System/Threading/ThreadPoolWorkQueue.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Threading namespace System::Threading { // Forward declaring type: ThreadPoolWorkQueueThreadLocals class ThreadPoolWorkQueueThreadLocals; // Forward declaring type: IThreadPoolWorkItem class IThreadPoolWorkItem; } // Completed forward declares // Type namespace: System.Threading namespace System::Threading { // Size: 0x24 #pragma pack(push, 1) // Autogenerated type: System.Threading.ThreadPoolWorkQueue class ThreadPoolWorkQueue : public ::Il2CppObject { public: // Nested type: System::Threading::ThreadPoolWorkQueue::SparseArray_1<T> template<typename T> class SparseArray_1; // Nested type: System::Threading::ThreadPoolWorkQueue::WorkStealingQueue class WorkStealingQueue; // Nested type: System::Threading::ThreadPoolWorkQueue::QueueSegment class QueueSegment; // System.Threading.ThreadPoolWorkQueue/QueueSegment queueHead // Size: 0x8 // Offset: 0x10 System::Threading::ThreadPoolWorkQueue::QueueSegment* queueHead; // Field size check static_assert(sizeof(System::Threading::ThreadPoolWorkQueue::QueueSegment*) == 0x8); // System.Threading.ThreadPoolWorkQueue/QueueSegment queueTail // Size: 0x8 // Offset: 0x18 System::Threading::ThreadPoolWorkQueue::QueueSegment* queueTail; // Field size check static_assert(sizeof(System::Threading::ThreadPoolWorkQueue::QueueSegment*) == 0x8); // private System.Int32 numOutstandingThreadRequests // Size: 0x4 // Offset: 0x20 int numOutstandingThreadRequests; // Field size check static_assert(sizeof(int) == 0x4); // Creating value type constructor for type: ThreadPoolWorkQueue ThreadPoolWorkQueue(System::Threading::ThreadPoolWorkQueue::QueueSegment* queueHead_ = {}, System::Threading::ThreadPoolWorkQueue::QueueSegment* queueTail_ = {}, int numOutstandingThreadRequests_ = {}) noexcept : queueHead{queueHead_}, queueTail{queueTail_}, numOutstandingThreadRequests{numOutstandingThreadRequests_} {} // Get static field: static System.Threading.ThreadPoolWorkQueue/SparseArray`1<System.Threading.ThreadPoolWorkQueue/WorkStealingQueue> allThreadQueues static System::Threading::ThreadPoolWorkQueue::SparseArray_1<System::Threading::ThreadPoolWorkQueue::WorkStealingQueue*>* _get_allThreadQueues(); // Set static field: static System.Threading.ThreadPoolWorkQueue/SparseArray`1<System.Threading.ThreadPoolWorkQueue/WorkStealingQueue> allThreadQueues static void _set_allThreadQueues(System::Threading::ThreadPoolWorkQueue::SparseArray_1<System::Threading::ThreadPoolWorkQueue::WorkStealingQueue*>* value); // public System.Threading.ThreadPoolWorkQueueThreadLocals EnsureCurrentThreadHasQueue() // Offset: 0x187A8B0 System::Threading::ThreadPoolWorkQueueThreadLocals* EnsureCurrentThreadHasQueue(); // System.Void EnsureThreadRequested() // Offset: 0x187AA30 void EnsureThreadRequested(); // System.Void MarkThreadRequestSatisfied() // Offset: 0x187AAE8 void MarkThreadRequestSatisfied(); // public System.Void Enqueue(System.Threading.IThreadPoolWorkItem callback, System.Boolean forceGlobal) // Offset: 0x187A578 void Enqueue(System::Threading::IThreadPoolWorkItem* callback, bool forceGlobal); // System.Boolean LocalFindAndPop(System.Threading.IThreadPoolWorkItem callback) // Offset: 0x187A6A4 bool LocalFindAndPop(System::Threading::IThreadPoolWorkItem* callback); // public System.Void Dequeue(System.Threading.ThreadPoolWorkQueueThreadLocals tl, out System.Threading.IThreadPoolWorkItem callback, out System.Boolean missedSteal) // Offset: 0x187B30C void Dequeue(System::Threading::ThreadPoolWorkQueueThreadLocals* tl, System::Threading::IThreadPoolWorkItem*& callback, bool& missedSteal); // static System.Boolean Dispatch() // Offset: 0x187B8D0 static bool Dispatch(); // static private System.Void .cctor() // Offset: 0x187BE5C static void _cctor(); // public System.Void .ctor() // Offset: 0x187A7D8 // Implemented from: System.Object // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ThreadPoolWorkQueue* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("System::Threading::ThreadPoolWorkQueue::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ThreadPoolWorkQueue*, creationType>())); } }; // System.Threading.ThreadPoolWorkQueue #pragma pack(pop) static check_size<sizeof(ThreadPoolWorkQueue), 32 + sizeof(int)> __System_Threading_ThreadPoolWorkQueueSizeCheck; static_assert(sizeof(ThreadPoolWorkQueue) == 0x24); } DEFINE_IL2CPP_ARG_TYPE(System::Threading::ThreadPoolWorkQueue*, "System.Threading", "ThreadPoolWorkQueue");
55.857143
326
0.746438
darknight1050
0ffdcd3c8e55dd1186267a285283993dab0bad59
8,980
hpp
C++
include/multiqueue/multiqueue.hpp
marvinwilliams/multiqueue_experimental
97d0d6005075166ba445609996ab3c0b9fd79096
[ "MIT" ]
null
null
null
include/multiqueue/multiqueue.hpp
marvinwilliams/multiqueue_experimental
97d0d6005075166ba445609996ab3c0b9fd79096
[ "MIT" ]
null
null
null
include/multiqueue/multiqueue.hpp
marvinwilliams/multiqueue_experimental
97d0d6005075166ba445609996ab3c0b9fd79096
[ "MIT" ]
null
null
null
/** ****************************************************************************** * @file: multiqueue.hpp * * @author: Marvin Williams * @date: 2021/03/29 17:19 * @brief: ******************************************************************************* **/ #pragma once #ifndef MULTIQUEUE_HPP_INCLUDED #define MULTIQUEUE_HPP_INCLUDED #ifndef L1_CACHE_LINESIZE #define L1_CACHE_LINESIZE 64 #endif #ifndef PAGESIZE #define PAGESIZE 4096 #endif #include "multiqueue/external/xoroshiro256starstar.hpp" #include "multiqueue/guarded_pq.hpp" #include "multiqueue/selection_strategy/sticky.hpp" #include <cassert> #include <cstddef> #include <cstdlib> #include <functional> #include <memory> #include <sstream> #include <stdexcept> #include <string> #include <type_traits> #ifdef MQ_ELEMENT_DISTRIBUTION #include <algorithm> #include <utility> #include <vector> #endif namespace multiqueue { template <typename... Configs> struct MultiqueueParameters : Configs::Parameters... { std::uint64_t seed = 1; std::size_t c = 4; }; template <typename Key, typename T, typename Compare, template <typename, typename> typename PriorityQueue, typename StrategyType = selection_strategy::sticky, bool ImplicitLock = false, typename Allocator = std::allocator<Key>> class Multiqueue { private: using pq_type = GuardedPQ<Key, T, Compare, PriorityQueue, ImplicitLock>; public: using key_type = typename pq_type::key_type; using value_type = typename pq_type::value_type; using key_compare = typename pq_type::key_compare; using reference = typename pq_type::reference; using const_reference = typename pq_type::const_reference; using size_type = typename pq_type::size_type; using allocator_type = Allocator; using param_type = MultiqueueParameters<StrategyType>; private: using Strategy = typename StrategyType::template Strategy<Multiqueue>; friend Strategy; public: class alignas(2 * L1_CACHE_LINESIZE) Handle { friend Multiqueue; using data_t = typename Strategy::handle_data_t; std::reference_wrapper<Multiqueue> mq_; xoroshiro256starstar rng_; data_t data_; public: Handle(Handle const &) = delete; Handle &operator=(Handle const &) = delete; Handle(Handle &&) = default; private: explicit Handle(Multiqueue &mq, unsigned int id, std::uint64_t seed) noexcept : mq_{mq}, rng_{seed}, data_{id} { } public: bool try_extract_top(reference retval) noexcept { auto pq = mq_.get().strategy_.lock_delete_pq(data_, rng_); if (!pq) { return false; } pq->extract_top(retval); pq->unlock(); return true; } void push(const_reference value) noexcept { auto pq = mq_.get().strategy_.lock_push_pq(data_, rng_); assert(pq); pq->push(value); pq->unlock(); } void push(value_type &&value) noexcept { auto pq = mq_.get().strategy_.lock_push_pq(data_, rng_); assert(pq); pq->push(std::move(value)); pq->unlock(); } bool try_extract_from(size_type pos, value_type &retval) noexcept { assert(pos < mq_.get().num_pqs()); auto &pq = mq_.get().pq_list_[pos]; if (pq.try_lock()) { if (!pq.empty()) { pq.extract_top(retval); pq.unlock(); return true; } pq.unlock(); } return false; } }; private: using pq_alloc_type = typename std::allocator_traits<allocator_type>::template rebind_alloc<pq_type>; using pq_alloc_traits = typename std::allocator_traits<pq_alloc_type>; struct Deleter { size_type num_pqs; [[no_unique_address]] pq_alloc_type alloc; Deleter(allocator_type a) : num_pqs{0}, alloc{a} { } Deleter(size_type n, allocator_type a) : num_pqs{n}, alloc{a} { } void operator()(pq_type *pq_list) noexcept { for (pq_type *s = pq_list; s != pq_list + num_pqs; ++s) { pq_alloc_traits::destroy(alloc, s); } pq_alloc_traits::deallocate(alloc, pq_list, num_pqs); } }; private: // False sharing is avoided by class alignment, but the members do not need to reside in individual cache lines, as // they are not written concurrently std::unique_ptr<pq_type[], Deleter> pq_list_; key_type sentinel_; [[no_unique_address]] key_compare comp_; std::unique_ptr<std::uint64_t[]> handle_seeds_; std::atomic_uint handle_index_ = 0; // strategy data in separate cache line, as it might be written to [[no_unique_address]] alignas(2 * L1_CACHE_LINESIZE) Strategy strategy_; void abort_on_data_misalignment() { for (pq_type *s = pq_list_.get(); s != pq_list_.get() + num_pqs(); ++s) { if (reinterpret_cast<std::uintptr_t>(s) % (2 * L1_CACHE_LINESIZE) != 0) { std::abort(); } } } public: explicit Multiqueue(unsigned int num_threads, param_type const &param, key_compare const &comp = key_compare(), key_type sentinel = pq_type::max_key, allocator_type const &alloc = allocator_type()) : pq_list_(nullptr, Deleter(num_threads * param.c, alloc)), sentinel_{sentinel}, comp_{comp}, strategy_(*this, param) { assert(num_threads > 0); assert(param.c > 0); size_type const num_pqs = num_threads * param.c; pq_type *pq_list = pq_alloc_traits::allocate(pq_list_.get_deleter().alloc, num_pqs); for (pq_type *s = pq_list; s != pq_list + num_pqs; ++s) { pq_alloc_traits::construct(pq_list_.get_deleter().alloc, s, sentinel, comp_); } pq_list_.get_deleter().num_pqs = 0; pq_list_.reset(pq_list); pq_list_.get_deleter().num_pqs = num_pqs; #ifdef MQ_ABORT_MISALIGNMENT abort_on_data_misalignment(); #endif handle_seeds_ = std::make_unique<std::uint64_t[]>(num_threads); std::generate(handle_seeds_.get(), handle_seeds_.get() + num_threads, xoroshiro256starstar{param.seed}); } explicit Multiqueue(unsigned int num_threads, MultiqueueParameters<StrategyType> const &param, key_compare const &comp, allocator_type const &alloc) : Multiqueue(num_threads, param, comp, pq_type::max_key, alloc) { } Handle get_handle() noexcept { unsigned int index = handle_index_.fetch_add(1, std::memory_order_relaxed); return Handle(*this, index, handle_seeds_[index]); } constexpr key_type const &get_sentinel() noexcept { return sentinel_; } void reserve(size_type cap) { std::size_t const cap_per_pq = (2 * cap) / num_pqs(); for (auto &pq : pq_list_) { pq.reserve(cap_per_pq); }; } #ifdef MQ_ELEMENT_DISTRIBUTION std::vector<std::size_t> get_distribution() const { std::vector<std::size_t> distribution(num_pqs()); std::transform(pq_list_.get(), pq_list_.get() + num_pqs(), distribution.begin(), [](auto const &pq) { return pq.unsafe_size(); }); return distribution; } std::vector<std::size_t> get_top_distribution(std::size_t k) { std::vector<std::pair<value_type, std::size_t>> removed_elements; removed_elements.reserve(k); std::vector<std::size_t> distribution(num_pqs(), 0); for (std::size_t i = 0; i < k; ++i) { auto min = std::min_element(pq_list_.get(), pq_list_.get() + num_pqs(), [](auto const &lhs, auto const &rhs) { return lhs.top_key() < rhs.top_key(); }); if (min->min_key() == sentinel) { break; } assert(!min->empty()); std::pair<value_type, std::size_t> result; min->extract_top(result.first); result.second = static_cast<std::size_t>(min - std::begin(pq_list_)); removed_elements.push_back(result); ++distribution[result.second]; } for (auto [val, index] : removed_elements) { pq_list_[index].push(std::move(val)); } return distribution; } #endif constexpr size_type num_pqs() const noexcept { return pq_list_.get_deleter().num_pqs; } std::string description() const { std::stringstream ss; ss << "multiqueue\n\t"; ss << "PQs: " << num_pqs() << "\n\t"; ss << "Sentinel: " << sentinel_ << "\n\t"; ss << "Selection strategy: " << strategy_.description() << "\n\t"; ss << pq_type::description(); return ss.str(); } }; } // namespace multiqueue #endif //! MULTIQUEUE_HPP_INCLUDED
34.144487
120
0.602339
marvinwilliams
0ffe0e9e9dbd3f76d12b83299c1553c31af754e3
143
hpp
C++
storm/Queue.hpp
whoahq/storm
8a90f867ae1f600e1c82427749bbdaaac107b608
[ "Unlicense" ]
2
2020-09-07T20:05:50.000Z
2020-09-17T17:43:47.000Z
storm/Queue.hpp
whoahq/storm
8a90f867ae1f600e1c82427749bbdaaac107b608
[ "Unlicense" ]
null
null
null
storm/Queue.hpp
whoahq/storm
8a90f867ae1f600e1c82427749bbdaaac107b608
[ "Unlicense" ]
null
null
null
#ifndef STORM_QUEUE_HPP #define STORM_QUEUE_HPP #include "storm/queue/TSPriorityQueue.hpp" #include "storm/queue/TSTimerPriority.hpp" #endif
17.875
42
0.818182
whoahq
0ffe4ef15ab3edbaddaa0642221d438b35dde972
1,559
cpp
C++
src/Utility.cpp
Gregofi/metrics
a8da292a98b66a36329f1e5c9423ec01d86c07a1
[ "MIT" ]
null
null
null
src/Utility.cpp
Gregofi/metrics
a8da292a98b66a36329f1e5c9423ec01d86c07a1
[ "MIT" ]
1
2022-02-05T09:52:40.000Z
2022-02-05T09:52:40.000Z
src/Utility.cpp
Gregofi/metrics
a8da292a98b66a36329f1e5c9423ec01d86c07a1
[ "MIT" ]
null
null
null
#include "include/Utility.hpp" std::string EscapeXML(const std::string &text) { std::string result; for(char c: text) { if(c == '&') result += "&amp;"; else if(c == '<') result += "&lt;"; else if(c == '>') result += "&gt;"; else if(c == '"') result += "&quot;"; else if(c == '\'') result += "&apos;"; else result += c; } return result; } std::string GetFunctionHead(const clang::FunctionDecl *decl) { std::string res = decl->getQualifiedNameAsString() + "("; for(size_t i = 0; i < decl->getNumParams(); ++ i) { res += decl->getParamDecl(i)->getType().getAsString(); if(i + 1 != decl->getNumParams()) res += ", "; } res += ")"; /* Handle ref qualifiers such as 'int a() const &&' * Only methods can have those, so we cast it first. */ if(auto method = llvm::dyn_cast_or_null<clang::CXXMethodDecl>(decl); method) { res += " "; if(method->isConst()) { res += "const "; } switch(method->getRefQualifier()) { case clang::RefQualifierKind::RQ_LValue: res += "&"; break; case clang::RefQualifierKind::RQ_RValue: res += "&&"; break; case clang::RefQualifierKind::RQ_None: break; } if(res[res.length() - 1] == ' ') res.pop_back(); } return res; }
25.557377
80
0.45542
Gregofi
0fff3586bd93df4600a3ed78d96bc87032988b64
1,778
cpp
C++
falcon/regex_dfa/scan_intervals.cpp
jonathanpoelen/falcon.regex-dfa
cce9603d2a4b9269036c7888c1b8cf706c1548c4
[ "MIT" ]
null
null
null
falcon/regex_dfa/scan_intervals.cpp
jonathanpoelen/falcon.regex-dfa
cce9603d2a4b9269036c7888c1b8cf706c1548c4
[ "MIT" ]
null
null
null
falcon/regex_dfa/scan_intervals.cpp
jonathanpoelen/falcon.regex-dfa
cce9603d2a4b9269036c7888c1b8cf706c1548c4
[ "MIT" ]
null
null
null
#include "scan_intervals.hpp" #include "reverse_transitions.hpp" #include "redfa.hpp" #include <stdexcept> #include <algorithm> void falcon::regex_dfa::scan_intervals( utf8_consumer& consumer, Transitions& ts, unsigned int next_ts, Transition::State state ) { char_int c = consumer.bumpc(); bool const reverse = [&]() -> bool { if (c == '^') { c = consumer.bumpc(); return true; } return false; }(); if (c == '-') { ts.push_back({{c, c}, next_ts, state}); c = consumer.bumpc(); } while (c && c != ']') { if (c == '-') { if (!(c = consumer.bumpc())) { throw std::runtime_error("missing terminating ]"); } if (c == ']') { ts.push_back({{'-', '-'}, next_ts, state}); } else { Event & e = ts.back().e; if (e.l != e.r) { ts.push_back({{'-', '-'}, next_ts, state}); } else if (!( (('0' <= e.l && e.l <= '9' && '0' <= c && c <= '9') || ('a' <= e.l && e.l <= 'z' && 'a' <= c && c <= 'z') || ('A' <= e.l && e.l <= 'Z' && 'A' <= c && c <= 'Z') ) && e.l <= c )) { throw std::runtime_error("range out of order in character class"); } else { e.r = c; c = consumer.bumpc(); } } } else { if (c == '\\') { if (!(c = consumer.bumpc())) { throw std::runtime_error("missing terminating ]"); } } ts.push_back({{c, c}, next_ts, state}); c = consumer.bumpc(); } } if (!c) { throw std::runtime_error("missing terminating ]"); } if (ts.empty()) { throw std::runtime_error("error end of range"); } if (reverse) { reverse_transitions(ts, next_ts, state); } }
23.090909
89
0.453318
jonathanpoelen
ba01e8caff380677a43f14017bd3b2b3b5dbfd20
538
cpp
C++
Test/UnitTests/dllmain.cpp
Colorfingers/QuantumGate
e183e02464859f4ca486999182c4c41221f3261a
[ "MIT" ]
87
2018-09-01T05:29:22.000Z
2022-03-13T17:44:00.000Z
Test/UnitTests/dllmain.cpp
Colorfingers/QuantumGate
e183e02464859f4ca486999182c4c41221f3261a
[ "MIT" ]
6
2019-01-30T14:48:17.000Z
2022-03-14T21:10:56.000Z
Test/UnitTests/dllmain.cpp
Colorfingers/QuantumGate
e183e02464859f4ca486999182c4c41221f3261a
[ "MIT" ]
16
2018-11-25T23:09:47.000Z
2022-02-01T22:14:11.000Z
// This file is part of the QuantumGate project. For copyright and // licensing information refer to the license file(s) in the project root. #include "pch.h" BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) noexcept { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: QuantumGate::InitQuantumGateModule(); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: QuantumGate::DeinitQuantumGateModule(); break; } return TRUE; }
22.416667
92
0.756506
Colorfingers
ba05aa023aa3dfa99bfb10cc11adf2d5f9ccd695
10,264
cpp
C++
tests/cv/src/aoptflowlk.cpp
sunbuny/ReadOpenCV1.0Code
4d6593aa0a06d2c89a4a97209b1b2944a961b0b3
[ "MIT", "BSD-3-Clause" ]
6
2019-03-04T11:32:46.000Z
2020-03-31T06:54:16.000Z
tests/cv/src/aoptflowlk.cpp
anoopmenon/opencv-perl
b52785caee9f8967a4f2ead9c7b436056ffa830c
[ "BSD-3-Clause" ]
14
2016-11-24T10:46:39.000Z
2016-12-10T07:24:15.000Z
to/lang/OpenCV-2.2.0/tests/cv/src/aoptflowlk.cpp
eirTony/INDI1
42642d8c632da53f60f2610b056547137793021b
[ "MIT" ]
2
2021-04-20T08:12:49.000Z
2021-08-09T10:10:45.000Z
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // Intel License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of Intel Corporation may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "cvtest.h" #if 0 /* Testing parameters */ static char FuncName[] = "cvCalcOpticalFlowLK"; static char TestName[] = "Optical flow (Lucas & Kanade)"; static char TestClass[] = "Algorithm"; static long lImageWidth; static long lImageHeight; static long lWinWidth; static long lWinHeight; #define EPSILON 0.00001f static int fmaCalcOpticalFlowLK( void ) { /* Some Variables */ int* WH = NULL; int* WV = NULL; int W3[3] = { 1, 2, 1 }; int W5[5] = { 1, 4, 6, 4, 1 }; int W7[7] = { 1, 6, 15, 20, 15, 6, 1 }; int W9[9] = { 1, 8, 28, 56, 70, 56, 28, 8, 1 }; int W11[11] = {1, 10, 45, 120, 210, 252, 210, 120, 45, 10, 1 }; int i,j,m,k; uchar* roiA; uchar* roiB; float* VelocityX; float* VelocityY; float* DerivativeX; float* DerivativeY; float* DerivativeT; long lErrors = 0; CvSize winSize; int HRad; int VRad; float A1, A2, B1, B2, C1, C2; static int read_param = 0; /* Initialization global parameters */ if( !read_param ) { read_param = 1; /* Reading test-parameters */ trslRead( &lImageHeight, "563", "Image height" ); trslRead( &lImageWidth, "345", "Image width" ); trslRead( &lWinHeight, "7", "win height 3/5/7/9/11 " ); trslRead( &lWinWidth, "9", "win width 3/5/7/9/11 " ); } /* Checking all sizes of source histogram in ranges */ IplImage* imgA = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_8U, 1 ); IplImage* imgB = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_8U, 1 ); IplImage* testVelocityX = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_32F, 1 ); IplImage* testVelocityY = cvCreateImage( cvSize(lImageWidth,lImageHeight), IPL_DEPTH_32F, 1 ); VelocityX = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); VelocityY = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); DerivativeX = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); DerivativeY = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); DerivativeT = (float*)cvAlloc( lImageWidth * lImageHeight * sizeof(float) ); winSize.height = lWinHeight; winSize.width = lWinWidth; switch (lWinHeight) { case 3: WV = W3; break; case 5: WV = W5; break; case 7: WV = W7; break; case 9: WV = W9; break; case 11: WV = W11; break; } switch (lWinWidth) { case 3: WH = W3; break; case 5: WH = W5; break; case 7: WH = W7; break; case 9: WH = W9; break; case 11: WH = W11; break; } HRad = (winSize.width - 1)/2; VRad = (winSize.height - 1)/2; /* Filling images */ ats1bInitRandom( 0, 255, (uchar*)imgA->imageData, lImageHeight * imgA->widthStep ); ats1bInitRandom( 0, 255, (uchar*)imgB->imageData, imgA->widthStep * lImageHeight ); /* Run CVL function */ cvCalcOpticalFlowLK( imgA , imgB, winSize, testVelocityX, testVelocityY ); /* Calc by other way */ roiA = (uchar*)imgA->imageData; roiB = (uchar*)imgB->imageData; /* Calculate derivatives */ for (i=0; i<imgA->height; i++) { for(j=0; j<imgA->width; j++) { int jr,jl,it,ib; if ( j==imgA->width-1 ) jr = imgA->width-1; else jr = j + 1; if ( j==0 ) jl = 0; else jl = j - 1; if ( i==(imgA->height - 1) ) ib = imgA->height - 1; else ib = i + 1; if ( i==0 ) it = 0; else it = i - 1; DerivativeX[ i*lImageWidth + j ] = (float) (roiA[ (it)*imgA->widthStep + jr ] - roiA[ (it)*imgA->widthStep + jl ] + 2*roiA[ (i)*imgA->widthStep + jr ] - 2*roiA[ (i)*imgA->widthStep + jl ] + roiA[ (ib)*imgA->widthStep + jr ] - roiA[ (ib)*imgA->widthStep + jl ]) ; DerivativeY[ i*lImageWidth + j ] = (float) ( roiA[ (ib)*imgA->widthStep + jl ] + 2*roiA[ (ib)*imgA->widthStep + j ] + roiA[ (ib)*imgA->widthStep + jr ] - roiA[ (it)*imgA->widthStep + jl ] - 2*roiA[ (it)*imgA->widthStep + j ] - roiA[ (it)*imgA->widthStep + jr ]) ; DerivativeT[ i*lImageWidth + j ] = (float) (roiB[i*imgB->widthStep + j] - roiA[i*imgA->widthStep + j])*8; } } for( i = 0; i < lImageHeight; i++) { for(j = 0; j< lImageWidth; j++) { A1 =0; A2 =0; B1 =0; B2 =0; C1= 0; C2= 0; for( k = -VRad ; k <= VRad ; k++ ) { for( m = - HRad; m <= HRad ; m++ ) { int coord = (i+k)*lImageWidth + (j+m); if ( (j+m<0) || (j+m >lImageWidth-1) || ( (k+i)<0 ) || ( (k+i)>lImageHeight-1) ) {continue;} A1+=WV[k+VRad]*WH[m+HRad]* DerivativeX[coord]*DerivativeY[coord]; A2+=WV[k+VRad]*WH[m+HRad]* DerivativeX[coord]*DerivativeX[coord]; B1+=WV[k+VRad]*WH[m+HRad]* DerivativeY[coord]*DerivativeY[coord]; B2+=WV[k+VRad]*WH[m+HRad]* DerivativeX[coord]*DerivativeY[coord]; C1+=WV[k+VRad]*WH[m+HRad]* DerivativeY[coord]*DerivativeT[coord]; C2+=WV[k+VRad]*WH[m+HRad]* DerivativeX[coord]*DerivativeT[coord]; } } if (A1*B2 - A2*B1) { VelocityX[i*lImageWidth + j] = - (C1*B2 - C2*B1)/(A1*B2 - A2*B1); VelocityY[i*lImageWidth + j] = - (A1*C2 - A2*C1)/(A1*B2 - A2*B1); } else if ( (A1+A2)*(A1+A2) + (B1+B2)*(B1+B2) ) { /* Calculate Normal flow */ VelocityX[i*lImageWidth + j] = -(A1+A2)*(C1+C2)/((A1+A2)*(A1+A2)+(B1+B2)*(B1+B2)); VelocityY[i*lImageWidth + j] = -(B1+B2)*(C1+C2)/((A1+A2)*(A1+A2)+(B1+B2)*(B1+B2)); } else { VelocityX[i*lImageWidth + j] = 0; VelocityY[i*lImageWidth + j] = 0; } } } for( i = 0; i < lImageHeight; i++) { for(j = 0; j< lImageWidth; j++) { float tvx = ((float*)(testVelocityX->imageData + i*testVelocityX->widthStep))[j]; float tvy = ((float*)(testVelocityY->imageData + i*testVelocityY->widthStep))[j]; if (( fabs(tvx - VelocityX[i*lImageWidth + j])>EPSILON )|| ( fabs(tvy - VelocityY[i*lImageWidth + j])>EPSILON ) ) { //trsWrite( ATS_LST | ATS_CON, " ValueX %f \n", tvx ); //trsWrite( ATS_LST | ATS_CON, " mustX %f \n", VelocityX[i*lImageWidth + j] ); //trsWrite( ATS_LST | ATS_CON, " ValueY %f \n", tvy ); //trsWrite( ATS_LST | ATS_CON, " mustY %f \n", VelocityY[i*lImageWidth + j] ); //trsWrite( ATS_LST | ATS_CON, " Coordinates %d %d\n", i, j ); lErrors++; } } } cvFree( &VelocityX ); cvFree( &VelocityY ); cvFree( &DerivativeX ); cvFree( &DerivativeY ); cvFree( &DerivativeT ); cvReleaseImage( &imgA ); cvReleaseImage( &imgB ); cvReleaseImage( &testVelocityX ); cvReleaseImage( &testVelocityY ); if( lErrors == 0 ) return trsResult( TRS_OK, "No errors fixed for this text" ); else return trsResult( TRS_FAIL, "Total fixed %d errors", lErrors ); } /*fmaCalcOpticalFlowLK*/ void InitACalcOpticalFlowLK( void ) { /* Registering test function */ trsReg( FuncName, TestName, TestClass, fmaCalcOpticalFlowLK ); } /* InitAACalcOpticalFlowLK */ #endif /* End of file. */
33.652459
98
0.538094
sunbuny
6135c1fff7daa4e921581b7e454c27334123dad4
8,682
cpp
C++
client/OAIUser_ResponseCompound.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
client/OAIUser_ResponseCompound.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
client/OAIUser_ResponseCompound.cpp
ezmaxinc/eZmax-SDK-cpp-qt5-client
70cc5ea2bccba1a7c192f88b15bee8225dbb3d01
[ "MIT" ]
null
null
null
/** * eZmax API Definition (Full) * This API expose all the functionnalities for the eZmax and eZsign applications. * * The version of the OpenAPI document: 1.1.7 * Contact: support-api@ezmax.ca * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ #include "OAIUser_ResponseCompound.h" #include <QDebug> #include <QJsonArray> #include <QJsonDocument> #include <QObject> #include "OAIHelpers.h" namespace OpenAPI { OAIUser_ResponseCompound::OAIUser_ResponseCompound(QString json) { this->initializeModel(); this->fromJson(json); } OAIUser_ResponseCompound::OAIUser_ResponseCompound() { this->initializeModel(); } OAIUser_ResponseCompound::~OAIUser_ResponseCompound() {} void OAIUser_ResponseCompound::initializeModel() { m_pki_user_id_isSet = false; m_pki_user_id_isValid = false; m_fki_language_id_isSet = false; m_fki_language_id_isValid = false; m_e_user_type_isSet = false; m_e_user_type_isValid = false; m_s_user_firstname_isSet = false; m_s_user_firstname_isValid = false; m_s_user_lastname_isSet = false; m_s_user_lastname_isValid = false; m_s_user_loginname_isSet = false; m_s_user_loginname_isValid = false; m_obj_audit_isSet = false; m_obj_audit_isValid = false; } void OAIUser_ResponseCompound::fromJson(QString jsonString) { QByteArray array(jsonString.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); } void OAIUser_ResponseCompound::fromJsonObject(QJsonObject json) { m_pki_user_id_isValid = ::OpenAPI::fromJsonValue(pki_user_id, json[QString("pkiUserID")]); m_pki_user_id_isSet = !json[QString("pkiUserID")].isNull() && m_pki_user_id_isValid; m_fki_language_id_isValid = ::OpenAPI::fromJsonValue(fki_language_id, json[QString("fkiLanguageID")]); m_fki_language_id_isSet = !json[QString("fkiLanguageID")].isNull() && m_fki_language_id_isValid; m_e_user_type_isValid = ::OpenAPI::fromJsonValue(e_user_type, json[QString("eUserType")]); m_e_user_type_isSet = !json[QString("eUserType")].isNull() && m_e_user_type_isValid; m_s_user_firstname_isValid = ::OpenAPI::fromJsonValue(s_user_firstname, json[QString("sUserFirstname")]); m_s_user_firstname_isSet = !json[QString("sUserFirstname")].isNull() && m_s_user_firstname_isValid; m_s_user_lastname_isValid = ::OpenAPI::fromJsonValue(s_user_lastname, json[QString("sUserLastname")]); m_s_user_lastname_isSet = !json[QString("sUserLastname")].isNull() && m_s_user_lastname_isValid; m_s_user_loginname_isValid = ::OpenAPI::fromJsonValue(s_user_loginname, json[QString("sUserLoginname")]); m_s_user_loginname_isSet = !json[QString("sUserLoginname")].isNull() && m_s_user_loginname_isValid; m_obj_audit_isValid = ::OpenAPI::fromJsonValue(obj_audit, json[QString("objAudit")]); m_obj_audit_isSet = !json[QString("objAudit")].isNull() && m_obj_audit_isValid; } QString OAIUser_ResponseCompound::asJson() const { QJsonObject obj = this->asJsonObject(); QJsonDocument doc(obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject OAIUser_ResponseCompound::asJsonObject() const { QJsonObject obj; if (m_pki_user_id_isSet) { obj.insert(QString("pkiUserID"), ::OpenAPI::toJsonValue(pki_user_id)); } if (m_fki_language_id_isSet) { obj.insert(QString("fkiLanguageID"), ::OpenAPI::toJsonValue(fki_language_id)); } if (e_user_type.isSet()) { obj.insert(QString("eUserType"), ::OpenAPI::toJsonValue(e_user_type)); } if (m_s_user_firstname_isSet) { obj.insert(QString("sUserFirstname"), ::OpenAPI::toJsonValue(s_user_firstname)); } if (m_s_user_lastname_isSet) { obj.insert(QString("sUserLastname"), ::OpenAPI::toJsonValue(s_user_lastname)); } if (m_s_user_loginname_isSet) { obj.insert(QString("sUserLoginname"), ::OpenAPI::toJsonValue(s_user_loginname)); } if (obj_audit.isSet()) { obj.insert(QString("objAudit"), ::OpenAPI::toJsonValue(obj_audit)); } return obj; } qint32 OAIUser_ResponseCompound::getPkiUserId() const { return pki_user_id; } void OAIUser_ResponseCompound::setPkiUserId(const qint32 &pki_user_id) { this->pki_user_id = pki_user_id; this->m_pki_user_id_isSet = true; } bool OAIUser_ResponseCompound::is_pki_user_id_Set() const{ return m_pki_user_id_isSet; } bool OAIUser_ResponseCompound::is_pki_user_id_Valid() const{ return m_pki_user_id_isValid; } qint32 OAIUser_ResponseCompound::getFkiLanguageId() const { return fki_language_id; } void OAIUser_ResponseCompound::setFkiLanguageId(const qint32 &fki_language_id) { this->fki_language_id = fki_language_id; this->m_fki_language_id_isSet = true; } bool OAIUser_ResponseCompound::is_fki_language_id_Set() const{ return m_fki_language_id_isSet; } bool OAIUser_ResponseCompound::is_fki_language_id_Valid() const{ return m_fki_language_id_isValid; } OAIField_eUserType OAIUser_ResponseCompound::getEUserType() const { return e_user_type; } void OAIUser_ResponseCompound::setEUserType(const OAIField_eUserType &e_user_type) { this->e_user_type = e_user_type; this->m_e_user_type_isSet = true; } bool OAIUser_ResponseCompound::is_e_user_type_Set() const{ return m_e_user_type_isSet; } bool OAIUser_ResponseCompound::is_e_user_type_Valid() const{ return m_e_user_type_isValid; } QString OAIUser_ResponseCompound::getSUserFirstname() const { return s_user_firstname; } void OAIUser_ResponseCompound::setSUserFirstname(const QString &s_user_firstname) { this->s_user_firstname = s_user_firstname; this->m_s_user_firstname_isSet = true; } bool OAIUser_ResponseCompound::is_s_user_firstname_Set() const{ return m_s_user_firstname_isSet; } bool OAIUser_ResponseCompound::is_s_user_firstname_Valid() const{ return m_s_user_firstname_isValid; } QString OAIUser_ResponseCompound::getSUserLastname() const { return s_user_lastname; } void OAIUser_ResponseCompound::setSUserLastname(const QString &s_user_lastname) { this->s_user_lastname = s_user_lastname; this->m_s_user_lastname_isSet = true; } bool OAIUser_ResponseCompound::is_s_user_lastname_Set() const{ return m_s_user_lastname_isSet; } bool OAIUser_ResponseCompound::is_s_user_lastname_Valid() const{ return m_s_user_lastname_isValid; } QString OAIUser_ResponseCompound::getSUserLoginname() const { return s_user_loginname; } void OAIUser_ResponseCompound::setSUserLoginname(const QString &s_user_loginname) { this->s_user_loginname = s_user_loginname; this->m_s_user_loginname_isSet = true; } bool OAIUser_ResponseCompound::is_s_user_loginname_Set() const{ return m_s_user_loginname_isSet; } bool OAIUser_ResponseCompound::is_s_user_loginname_Valid() const{ return m_s_user_loginname_isValid; } OAICommon_Audit OAIUser_ResponseCompound::getObjAudit() const { return obj_audit; } void OAIUser_ResponseCompound::setObjAudit(const OAICommon_Audit &obj_audit) { this->obj_audit = obj_audit; this->m_obj_audit_isSet = true; } bool OAIUser_ResponseCompound::is_obj_audit_Set() const{ return m_obj_audit_isSet; } bool OAIUser_ResponseCompound::is_obj_audit_Valid() const{ return m_obj_audit_isValid; } bool OAIUser_ResponseCompound::isSet() const { bool isObjectUpdated = false; do { if (m_pki_user_id_isSet) { isObjectUpdated = true; break; } if (m_fki_language_id_isSet) { isObjectUpdated = true; break; } if (e_user_type.isSet()) { isObjectUpdated = true; break; } if (m_s_user_firstname_isSet) { isObjectUpdated = true; break; } if (m_s_user_lastname_isSet) { isObjectUpdated = true; break; } if (m_s_user_loginname_isSet) { isObjectUpdated = true; break; } if (obj_audit.isSet()) { isObjectUpdated = true; break; } } while (false); return isObjectUpdated; } bool OAIUser_ResponseCompound::isValid() const { // only required properties are required for the object to be considered valid return m_pki_user_id_isValid && m_fki_language_id_isValid && m_e_user_type_isValid && m_s_user_firstname_isValid && m_s_user_lastname_isValid && m_s_user_loginname_isValid && m_obj_audit_isValid && true; } } // namespace OpenAPI
30.787234
207
0.737848
ezmaxinc
61372ef9d7e36dcf1820e8f8adfeb2e8ebed66b2
10,120
cpp
C++
Code/ChiCheCanvas.cpp
spencerparkin/ChineseCheckers
0d6a1b22637805ac8ac19bf4a55a3547312f7cb5
[ "MIT" ]
1
2016-10-12T14:34:23.000Z
2016-10-12T14:34:23.000Z
Code/ChiCheCanvas.cpp
spencerparkin/ChineseCheckers
0d6a1b22637805ac8ac19bf4a55a3547312f7cb5
[ "MIT" ]
null
null
null
Code/ChiCheCanvas.cpp
spencerparkin/ChineseCheckers
0d6a1b22637805ac8ac19bf4a55a3547312f7cb5
[ "MIT" ]
null
null
null
// ChiCheCanvas.cpp #include "ChiCheCanvas.h" #include "ChiCheClient.h" #include "ChiCheApp.h" #include "ChiCheSound.h" #include <GL/gl.h> #include <GL/glu.h> #include <wx/time.h> using namespace ChiChe; int Canvas::attributeList[] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER, WX_GL_DEPTH_SIZE, 16, 0 }; // TODO: It might be nice to swap out the lines for a nice 3D polygon-mesh. // TODO: It might be fun to give a first-person view of the marble as it jumps around the board. //===================================================================================== Canvas::Canvas( wxWindow* parent ) : wxGLCanvas( parent, wxID_ANY, attributeList ) { context = 0; mousePos.x = 0; mousePos.y = 0; hitBuffer = 0; hitBufferSize = 0; lastFrameTime = -1; frameRate = 60.0; Bind( wxEVT_PAINT, &Canvas::OnPaint, this ); Bind( wxEVT_SIZE, &Canvas::OnSize, this ); Bind( wxEVT_MOUSEWHEEL, &Canvas::OnMouseWheel, this ); Bind( wxEVT_LEFT_DOWN, &Canvas::OnMouseLeftDown, this ); Bind( wxEVT_RIGHT_DOWN, &Canvas::OnMouseRightDown, this ); Bind( wxEVT_MOTION, &Canvas::OnMouseMotion, this ); } //===================================================================================== /*virtual*/ Canvas::~Canvas( void ) { delete context; } //===================================================================================== void Canvas::BindContext( bool actuallyBind ) { if( !context ) context = new wxGLContext( this ); if( context && actuallyBind ) SetCurrent( *context ); } //===================================================================================== double Canvas::FrameRate( void ) { return frameRate; } //===================================================================================== void Canvas::OnPaint( wxPaintEvent& event ) { PreRender( GL_RENDER ); Client* client = wxGetApp().GetClient(); if( client ) { // Approximate the frame-rate this frame as the frame-rate last frame. wxLongLong thisFrameTime = wxGetLocalTimeMillis(); if( lastFrameTime != -1 ) { wxLongLong deltaTime = thisFrameTime - lastFrameTime; double frameTime = deltaTime.ToDouble() / 1000.0; frameRate = 1.0 / frameTime; } lastFrameTime = thisFrameTime; // Ask the client to render for us. client->Render( GL_RENDER ); } PostRender( GL_RENDER ); } //===================================================================================== void Canvas::PreRender( GLenum renderMode ) { BindContext( true ); glClearColor( 0.f, 0.f, 0.f, 1.f ); glEnable( GL_DEPTH_TEST ); glEnable( GL_LINE_SMOOTH ); glEnable( GL_BLEND ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glHint( GL_LINE_SMOOTH_HINT, GL_DONT_CARE ); glShadeModel( GL_SMOOTH ); if( renderMode == GL_SELECT ) { hitBufferSize = 512; hitBuffer = new unsigned int[ hitBufferSize ]; glSelectBuffer( hitBufferSize, hitBuffer ); glRenderMode( GL_SELECT ); glInitNames(); } glClear( GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT ); wxPoint* pickingPoint = 0; if( renderMode == GL_SELECT ) pickingPoint = &mousePos; camera.LoadViewingMatrices( pickingPoint ); } //===================================================================================== void Canvas::PostRender( GLenum renderMode ) { glFlush(); if( renderMode == GL_SELECT ) { int hitCount = glRenderMode( GL_RENDER ); Client* client = wxGetApp().GetClient(); if( client ) client->ProcessHitList( hitBuffer, hitBufferSize, hitCount ); delete[] hitBuffer; hitBuffer = 0; hitBufferSize = 0; } else if( renderMode == GL_RENDER ) { SwapBuffers(); } } //===================================================================================== void Canvas::OnSize( wxSizeEvent& event ) { #ifdef __LINUX__ // TODO: Why can't or shouldn't we bind the context in the on-size event for Linux? OpenGL must be bound before issuing gl-commands. BindContext( false ); #else //__LINUX__ BindContext( true ); #endif //__LINUX__ wxSize size = event.GetSize(); glViewport( 0, 0, size.GetWidth(), size.GetHeight() ); double aspectRatio = double( size.GetWidth() ) / double( size.GetHeight() ); camera.SetAspectRatio( aspectRatio ); Refresh(); } //===================================================================================== void Canvas::OnMouseWheel( wxMouseEvent& event ) { double wheelDelta = event.GetWheelDelta(); double wheelRotation = event.GetWheelRotation(); double wheelIncrements = wheelRotation / wheelDelta; double zoomPercentagePerIncrement = 0.1; double zoomPercentage = 1.0 + wheelIncrements * zoomPercentagePerIncrement; double minimumFocalLength = 5.0; double maximumFocalLength = 100.0; camera.Zoom( zoomPercentage, minimumFocalLength, maximumFocalLength ); Refresh(); } //===================================================================================== void Canvas::OnMouseLeftDown( wxMouseEvent& event ) { SetFocus(); mousePos = event.GetPosition(); if( event.ShiftDown() && event.AltDown() ) wxGetApp().GetSound()->PlayWave( "Fart1" ); } //===================================================================================== void Canvas::OnMouseRightDown( wxMouseEvent& event ) { mousePos = event.GetPosition(); Client* client = wxGetApp().GetClient(); if( client ) { PreRender( GL_SELECT ); client->Render( GL_SELECT ); PostRender( GL_SELECT ); } } //===================================================================================== void Canvas::OnMouseMotion( wxMouseEvent& event ) { if( event.LeftIsDown() ) { wxPoint mouseDelta = event.GetPosition() - mousePos; mousePos = event.GetPosition(); c3ga::vectorE3GA eye = camera.GetEye(); c3ga::vectorE3GA xAxis, yAxis, zAxis; camera.CalcPanFrame( xAxis, yAxis, zAxis ); double unitsPerPixel = 0.2; c3ga::vectorE3GA delta; delta.set( c3ga::vectorE3GA::coord_e1_e2_e3, unitsPerPixel * -double( mouseDelta.x ), unitsPerPixel * double( mouseDelta.y ), 0.0 ); delta = c3ga::gp( xAxis, delta.get_e1() ) + c3ga::gp( yAxis, delta.get_e2() ) + c3ga::gp( zAxis, delta.get_e3() ); camera.Move( delta, true ); c3ga::vectorE3GA lookVec = c3ga::unit( camera.GetFocus() - camera.GetEye() ); double angle = acos( lookVec.get_e2() ); if( angle < M_PI / 2.0 || angle > M_PI * 0.95 ) camera.SetEye( eye ); else Refresh(); } } //===================================================================================== Canvas::Camera::Camera( void ) { focus.set( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, 0.0 ); eye.set( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 20.0, -50.0 ); up.set( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 1.0, 0.0 ); foviAngle = 60.0; aspectRatio = 1.0; } //===================================================================================== Canvas::Camera::~Camera( void ) { } //===================================================================================== void Canvas::Camera::Zoom( double zoomPercentage, double minimumFocalLength, double maximumFocalLength ) { c3ga::vectorE3GA originalEye = eye; c3ga::vectorE3GA lookVec = focus - eye; lookVec = c3ga::gp( lookVec, zoomPercentage ); eye = focus - lookVec; double focalLength = FocalLength(); if( focalLength < minimumFocalLength || focalLength > maximumFocalLength ) eye = originalEye; } //===================================================================================== double Canvas::Camera::FocalLength( void ) { c3ga::vectorE3GA lookVec = focus - eye; return c3ga::norm( lookVec ); } //===================================================================================== void Canvas::Camera::Move( const c3ga::vectorE3GA& delta, bool maintainFocalLength /*= true*/ ) { double oldFocalLength = FocalLength(); eye = eye + delta; if( maintainFocalLength ) { double newFocalLength = FocalLength(); double zoomPercentage = oldFocalLength / newFocalLength; Zoom( zoomPercentage, 0.0, 1000.0 ); } } //===================================================================================== void Canvas::Camera::CalcPanFrame( c3ga::vectorE3GA& xAxis, c3ga::vectorE3GA& yAxis, c3ga::vectorE3GA& zAxis ) { // This should create a right-handed system. c3ga::vectorE3GA lookVec = focus - eye; zAxis = c3ga::unit( c3ga::negate( lookVec ) ); yAxis = c3ga::unit( c3ga::lc( lookVec, c3ga::op( lookVec, up ) ) ); xAxis = c3ga::gp( c3ga::op( zAxis, yAxis ), c3ga::I3 ); } //===================================================================================== void Canvas::Camera::LoadViewingMatrices( wxPoint* pickingPoint /*= 0*/ ) { glMatrixMode( GL_PROJECTION ); glLoadIdentity(); if( pickingPoint ) { GLint viewport[4]; glGetIntegerv( GL_VIEWPORT, viewport ); GLdouble x = pickingPoint->x; GLdouble y = GLdouble( viewport[3] ) - GLdouble( pickingPoint->y ); GLdouble w = 2.0; GLdouble h = 2.0; gluPickMatrix( x, y, w, h, viewport ); } gluPerspective( foviAngle, aspectRatio, 1.0, 1000.0 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( eye.get_e1(), eye.get_e2(), eye.get_e3(), focus.get_e1(), focus.get_e2(), focus.get_e3(), up.get_e1(), up.get_e2(), up.get_e3() ); } //===================================================================================== void Canvas::Camera::SetAspectRatio( double aspectRatio ) { this->aspectRatio = aspectRatio; } //===================================================================================== double Canvas::Camera::GetAspectRatio( void ) { return aspectRatio; } //===================================================================================== const c3ga::vectorE3GA& Canvas::Camera::GetEye( void ) { return eye; } //===================================================================================== void Canvas::Camera::SetEye( const c3ga::vectorE3GA& eye ) { this->eye = eye; } //===================================================================================== const c3ga::vectorE3GA& Canvas::Camera::GetFocus( void ) { return focus; } //===================================================================================== void Canvas::Camera::SetFocus( const c3ga::vectorE3GA& focus ) { this->focus = focus; } // ChiCheCanvas.cpp
29.418605
134
0.547233
spencerparkin
613b500d712809bf61975255cd2b990298250b2b
1,077
hpp
C++
tests/token_equality.hpp
Je06jm/Matrin-Language
2aa440873f926c7fcd70e331b3619bbef5bdf5d9
[ "MIT" ]
null
null
null
tests/token_equality.hpp
Je06jm/Matrin-Language
2aa440873f926c7fcd70e331b3619bbef5bdf5d9
[ "MIT" ]
null
null
null
tests/token_equality.hpp
Je06jm/Matrin-Language
2aa440873f926c7fcd70e331b3619bbef5bdf5d9
[ "MIT" ]
null
null
null
#ifndef MARTIN_TEST_TOKEN_EQUALITY #define MARTIN_TEST_TOKEN_EQUALITY #include "testing.hpp" #include <generators/equality.hpp> #include "helpers/validatetree.hpp" #include "helpers/tokennode.hpp" #include "helpers/parseerror.hpp" #include "helpers/subtests.hpp" namespace Martin { class Test_token_equality : public Test { public: std::string GetName() const override { return "Token(Equality)"; } bool RunTest() override { auto tree = TokenizerSingleton.TokenizeString("== != < > <= >="); const std::vector<TokenType::Type> types = { TokenType::Type::SYM_Equals, TokenType::Type::SYM_NotEquals, TokenType::Type::SYM_LessThan, TokenType::Type::SYM_GreaterThan, TokenType::Type::SYM_LessThanEquals, TokenType::Type::SYM_GreaterThanEquals }; if (!ValidateTokenList(tree, error)) return false; return ValidateExpectedTokenList(tree, types, error); } }; } #endif
29.916667
77
0.618384
Je06jm
613c3f841039d91d1be2fab00721218c337f0d0c
1,175
cxx
C++
Cpp SOURCE CODE/Cpp basics/Casts/casts.cxx
DevJeffersonL/OPEN-SOURCE-
8e650337ebab7608a4bdb5106df74e17b0e0e995
[ "MIT" ]
1
2022-03-30T06:19:22.000Z
2022-03-30T06:19:22.000Z
Cpp SOURCE CODE/Cpp basics/Casts/casts.cxx
DevJeffersonL/OPEN-SOURCE-CODE
8e650337ebab7608a4bdb5106df74e17b0e0e995
[ "MIT" ]
null
null
null
Cpp SOURCE CODE/Cpp basics/Casts/casts.cxx
DevJeffersonL/OPEN-SOURCE-CODE
8e650337ebab7608a4bdb5106df74e17b0e0e995
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Base { virtual void dummy() { // Required to make class polymorphic } // Some base class }; class Derived : public Base { // Some derived class }; int main() { Base *base = new Base; Base *derived = new Derived; Derived *tmp; tmp = dynamic_cast<Derived *>(base); if (tmp) cout << "Base* has been successfully casted to Derived* using dynamic_cast" << endl; else cout << "dynamic_cast prevented Base* cast to Derived* from happening" << endl; tmp = dynamic_cast<Derived *>(derived); if (tmp) cout << "Derived* has been successfully casted to Derived* using " "dynamic_cast" << endl; else cout << "dynamic_cast prevented Derived* cast to Derived* from happening" << endl; tmp = static_cast<Derived *>(base); if (tmp) cout << "Base* has been successfully casted to Derived* using static_cast" << endl; else cout << "This actually never happens" << endl; tmp = static_cast<Derived *>(derived); if (tmp) cout << "Derived* has been successfully casted to Derived* using static_cast" << endl; else cout << "This actually never happens" << endl; return 0; }
19.915254
77
0.666383
DevJeffersonL
61417e9866f46e9b75fafc63c54dfb5b952d25b1
4,209
cpp
C++
ace/examples/C++NPv1/Logging_Client.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
46
2015-12-04T17:12:58.000Z
2022-03-11T04:30:49.000Z
ace/examples/C++NPv1/Logging_Client.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
null
null
null
ace/examples/C++NPv1/Logging_Client.cpp
tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective
1b0172cdb78757fd17898503aaf6ce03d940ef28
[ "Apache-1.1" ]
23
2016-10-24T09:18:14.000Z
2022-02-25T02:11:35.000Z
/* ** Logging_Client.cpp,v 1.4 2001/10/03 01:54:28 shuston Exp ** ** Copyright 2001 Addison Wesley. All Rights Reserved. */ #include "ace/OS.h" #include "ace/CDR_Stream.h" #include "ace/INET_Addr.h" #include "ace/SOCK_Connector.h" #include "ace/SOCK_Stream.h" #include "ace/Log_Record.h" #include "ace/streams.h" #include <string> int operator<< (ACE_OutputCDR &cdr, const ACE_Log_Record &log_record) { size_t msglen = log_record.msg_data_len (); // The ACE_Log_Record::msg_data () function is non-const, since it // returns a non-const pointer to internal class members. Since we // know that no members are modified here, we can safely const_cast // the log_record parameter without violating the interface // contract. ACE_Log_Record &nonconst_record = (ACE_const_cast (ACE_Log_Record&, log_record)); // Insert each field from <log_record> into the output CDR stream. cdr << ACE_CDR::Long (log_record.type ()); cdr << ACE_CDR::Long (log_record.pid ()); cdr << ACE_CDR::Long (log_record.time_stamp ().sec ()); cdr << ACE_CDR::Long (log_record.time_stamp ().usec ()); cdr << ACE_CDR::ULong (msglen); cdr.write_char_array (nonconst_record.msg_data (), msglen); return cdr.good_bit (); } class Logging_Client { private: ACE_SOCK_Stream logging_peer_; public: ACE_SOCK_Stream &peer () { return logging_peer_; } int send (const ACE_Log_Record &log_record) { // Serialize the log record using a CDR stream, allocate // enough space for the complete <ACE_Log_Record>. const size_t max_payload_size = 4 // type() + 8 // timestamp + 4 // process id + 4 // data length + ACE_Log_Record::MAXLOGMSGLEN // data + ACE_CDR::MAX_ALIGNMENT; // padding; // Insert contents of <log_record> into payload stream. ACE_OutputCDR payload (max_payload_size); payload << log_record; // Get the number of bytes used by the CDR stream. ACE_CDR::ULong length = payload.total_length (); // Send a header so the receiver can determine the byte // order and size of the incoming CDR stream. ACE_OutputCDR header (ACE_CDR::MAX_ALIGNMENT + 8); header << ACE_OutputCDR::from_boolean (ACE_CDR_BYTE_ORDER); // Store the size of the payload that follows header << ACE_CDR::ULong (length); // Use an iovec to send both buffer and payload simultaneously. iovec iov[2]; iov[0].iov_base = header.begin ()->rd_ptr (); iov[0].iov_len = 8; iov[1].iov_base = payload.begin ()->rd_ptr (); iov[1].iov_len = length; // Send header and payload efficiently using "gather-write". return logging_peer_.sendv_n (iov, 2); } ~Logging_Client () { logging_peer_.close (); } }; int main (int argc, char *argv[]) { u_short logger_port = argc > 1 ? atoi (argv[1]) : 0; const char *logger_host = argc > 2 ? argv[2] : ACE_DEFAULT_SERVER_HOST; int result; ACE_INET_Addr server_addr; if (logger_port != 0) result = server_addr.set (logger_port, logger_host); else result = server_addr.set ("ace_logger", logger_host); if (result == -1) ACE_ERROR_RETURN ((LM_ERROR, "lookup %s, %p\n", logger_port == 0 ? "ace_logger" : argv[1], logger_host), 1); ACE_SOCK_Connector connector; Logging_Client logging_client; if (connector.connect (logging_client.peer (), server_addr) < 0) ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "connect()"), 1); // Limit the number of characters read on each record cin.width (ACE_Log_Record::MAXLOGMSGLEN); for (;;) { std::string user_input; std::getline (cin, user_input, '\n'); if (!cin || cin.eof ()) break; ACE_Time_Value now (ACE_OS::gettimeofday ()); ACE_Log_Record log_record (LM_INFO, now, ACE_OS::getpid ()); log_record.msg_data (user_input.c_str ()); if (logging_client.send (log_record) == -1) ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "logging_client.send()"), 1); } return 0; // Logging_Client destructor closes TCP connection. }
32.882813
70
0.642195
tharindusathis
6145049908bbb51a6249826d3f307ced63a614ba
3,093
hpp
C++
include/codegen/include/Zenject/MemoryPool_6.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/Zenject/MemoryPool_6.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/Zenject/MemoryPool_6.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:44 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: Zenject.MemoryPoolBase`1 #include "Zenject/MemoryPoolBase_1.hpp" // Including type: Zenject.IMemoryPool`6 #include "Zenject/IMemoryPool_6.hpp" // Including type: Zenject.IFactory`6 #include "Zenject/IFactory_6.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Completed forward declares // Type namespace: Zenject namespace Zenject { // Autogenerated type: Zenject.MemoryPool`6 template<typename TValue, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5> class MemoryPool_6 : public Zenject::MemoryPoolBase_1<TValue>, public Zenject::IMemoryPool_6<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>, public Zenject::IDespawnableMemoryPool_1<TValue>, public Zenject::IMemoryPool, public Zenject::IFactory_6<TParam1, TParam2, TParam3, TParam4, TParam5, TValue>, public Zenject::IFactory { public: // public TValue Spawn(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5) // Offset: 0x15CD334 TValue Spawn(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5) { return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Spawn", param1, param2, param3, param4, param5)); } // protected System.Void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TValue item) // Offset: 0x15CD3F4 void Reinitialize(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TValue item) { CRASH_UNLESS(il2cpp_utils::RunMethod(this, "Reinitialize", p1, p2, p3, p4, p5, item)); } // private TValue Zenject.IFactory<TParam1,TParam2,TParam3,TParam4,TParam5,TValue>.Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5) // Offset: 0x15CD3F8 // Implemented from: Zenject.IFactory`6 // Base method: TValue IFactory`6::Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5) TValue Zenject_IFactory_6_Create(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5) { return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Zenject.IFactory<TParam1,TParam2,TParam3,TParam4,TParam5,TValue>.Create", p1, p2, p3, p4, p5)); } // public System.Void .ctor() // Offset: 0x15CD41C // Implemented from: Zenject.MemoryPoolBase`1 // Base method: System.Void MemoryPoolBase`1::.ctor() // Base method: System.Void Object::.ctor() static MemoryPool_6<TValue, TParam1, TParam2, TParam3, TParam4, TParam5>* New_ctor() { return (MemoryPool_6<TValue, TParam1, TParam2, TParam3, TParam4, TParam5>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<MemoryPool_6<TValue, TParam1, TParam2, TParam3, TParam4, TParam5>*>::get())); } }; // Zenject.MemoryPool`6 } DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::MemoryPool_6, "Zenject", "MemoryPool`6"); #pragma pack(pop)
59.480769
335
0.728096
Futuremappermydud
6146a9aa27279fd69965de2441efe7899de9c710
4,313
cpp
C++
dancex11/handler/instance/interceptor_handler_impl.cpp
mcorino/dancex11
297cb17066873ad7f30e88b0e8d64cd0e6ed2f68
[ "MIT" ]
4
2016-04-12T15:09:28.000Z
2020-01-16T10:42:55.000Z
dancex11/handler/instance/interceptor_handler_impl.cpp
mcorino/dancex11
297cb17066873ad7f30e88b0e8d64cd0e6ed2f68
[ "MIT" ]
null
null
null
dancex11/handler/instance/interceptor_handler_impl.cpp
mcorino/dancex11
297cb17066873ad7f30e88b0e8d64cd0e6ed2f68
[ "MIT" ]
4
2016-04-12T18:40:25.000Z
2019-11-16T14:41:45.000Z
// -*- C++ -*- /** * @file interceptor_handler_impl.cpp * @author Johnny Willemsen, Martin Corino * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "interceptor_handler_impl.h" #include "dancex11/core/dancex11_propertiesC.h" #include "ace/DLL.h" namespace DAnCEX11 { Interceptor_Handler_Impl::Interceptor_Handler_Impl ( Plugin_Manager& plugins) : plugins_ (plugins) { } Interceptor_Handler_Impl::~Interceptor_Handler_Impl () { } CORBA::StringSeq Interceptor_Handler_Impl::dependencies () { CORBA::StringSeq retval; return retval; } void Interceptor_Handler_Impl::close () { } std::string Interceptor_Handler_Impl::instance_type () { DANCEX11_LOG_TRACE ("Interceptor_Handler_Impl::instance_type"); return DAnCEX11::DANCE_DEPLOYMENTINTERCEPTOR; } void Interceptor_Handler_Impl::install_instance (const Deployment::DeploymentPlan & plan, uint32_t instanceRef, CORBA::Any&) { DANCEX11_LOG_TRACE ("Interceptor_Handler_Impl::install_instance - Called"); if (plan.instance ().size () <= instanceRef) { DANCEX11_LOG_ERROR ("Interceptor_Handler_Impl::install_instance - " << "Invalid instance reference " << instanceRef << " provided " << "to install_instance"); throw ::Deployment::PlanError (plan.UUID (), "Invalid instance reference"); } Deployment::InstanceDeploymentDescription const &idd = plan.instance ()[instanceRef]; if (plan.implementation ().size () <= idd.implementationRef ()) { DANCEX11_LOG_ERROR ("Interceptor_Handler_Impl::install_instance - " << "Invalid implementation reference " << idd.implementationRef () << " provided " << "to install_instance"); throw Deployment::PlanError (plan.UUID (), "Invalid Implementation reference"); } Deployment::MonolithicDeploymentDescription const &mdd = plan.implementation ()[idd.implementationRef ()]; DANCEX11_LOG_DEBUG ("Interceptor_Handler_Impl::install_instance - " << "Starting installation of instance <" << idd.name () << ">"); std::string entrypt; if (!DAnCEX11::Utility::get_property_value (DAnCEX11::DANCE_PLUGIN_FACTORY, mdd.execParameter (), entrypt)) { DANCEX11_LOG_ERROR ("Interceptor_Handler_Impl::install_instance - " << "No entrypoint found for plug-in initialization"); throw ::Deployment::StartError (idd.name (), "No entrypoint found for plug-in initialization\n"); } std::string artifact; if (!DAnCEX11::Utility::get_property_value (DAnCEX11::DANCE_PLUGIN_ARTIFACT, mdd.execParameter (), artifact)) { DANCEX11_LOG_ERROR ("Interceptor_Handler_Impl::install_instance - " << "No artifact found for plug-in initialization"); throw ::Deployment::StartError (idd.name (), "No artifact found for plug-in initialization\n"); } uint32_t open_mode = ACE_DEFAULT_SHLIB_MODE; if (!DAnCEX11::Utility::get_property_value (DAnCEX11::DANCE_PLUGIN_OPENMODE, mdd.execParameter (), open_mode)) { DANCEX11_LOG_INFO ("Interceptor_Handler_Impl::install_instance - " << "No open mode found for plug-in initialization"); } Utility::PROPERTY_MAP config; Utility::build_property_map (config, idd.configProperty ()); Utility::build_property_map (config, mdd.execParameter ()); this->plugins_.register_interceptor ( ACE_TEXT_CHAR_TO_TCHAR (artifact.c_str ()), ACE_TEXT_CHAR_TO_TCHAR (entrypt.c_str ()), open_mode, config); } void Interceptor_Handler_Impl::remove_instance (const Deployment::DeploymentPlan &, uint32_t, const CORBA::Any &) { } void Interceptor_Handler_Impl::connect_instance (const Deployment::DeploymentPlan &, uint32_t, const CORBA::Any &) { throw CORBA::NO_IMPLEMENT (); } void Interceptor_Handler_Impl::disconnect_instance (const Deployment::DeploymentPlan &, uint32_t) { throw CORBA::NO_IMPLEMENT (); } void Interceptor_Handler_Impl::configure (const ::Deployment::Properties &) { } }
29.541096
108
0.658474
mcorino
6147bbe1c58ebecda601d0fbd3d935d3e2815544
338
cpp
C++
src/ast/ast_value.cpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
4
2017-10-31T14:01:58.000Z
2019-07-16T04:53:32.000Z
src/ast/ast_value.cpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
null
null
null
src/ast/ast_value.cpp
traplol/malang
3c02f4f483b7580a557841c31a65bf190fd1228f
[ "MIT" ]
2
2018-01-23T12:59:07.000Z
2019-07-16T04:53:39.000Z
#include "ast_value.hpp" Type_Info *Ast_Value::get_type() { return nullptr; } bool Ast_LValue::can_lvalue() const { return true; } bool Ast_LValue::can_rvalue() const { return true; } bool Ast_RValue::can_lvalue() const { return false; } bool Ast_RValue::can_rvalue() const { return true; }
13.52
36
0.636095
traplol
61492c702f3cc5bdaa3701a58600a7c87f31f4fd
2,543
cpp
C++
boost/libs/bimap/test/test_bimap_extra.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
3
2015-01-03T23:52:29.000Z
2021-02-22T17:41:27.000Z
boost/libs/bimap/test/test_bimap_extra.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
1
2018-01-17T10:11:43.000Z
2018-01-17T10:11:43.000Z
boost/libs/bimap/test/test_bimap_extra.cpp
randolphwong/mcsema
eb5b376736e7f57ff0a61f7e4e5a436bbb874720
[ "BSD-3-Clause" ]
3
2016-11-08T01:56:40.000Z
2021-11-21T09:02:49.000Z
// Boost.Bimap // // Copyright (c) 2006-2007 Matias Capeletto // // 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) // VC++ 8.0 warns on usage of certain Standard Library and API functions that // can be cause buffer overruns or other possible security issues if misused. // See http://msdn.microsoft.com/msdnmag/issues/05/05/SafeCandC/default.aspx // But the wording of the warning is misleading and unsettling, there are no // portable alternative functions, and VC++ 8.0's own libraries use the // functions in question. So turn off the warnings. #define _CRT_SECURE_NO_DEPRECATE #define _SCL_SECURE_NO_DEPRECATE #include <boost/config.hpp> // Boost.Test #include <boost/test/minimal.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/is_same.hpp> // Boost.Bimap #include <boost/bimap/support/lambda.hpp> #include <boost/bimap/bimap.hpp> #include <boost/bimap/list_of.hpp> // Support metafunctions #include <boost/bimap/support/data_type_by.hpp> #include <boost/bimap/support/key_type_by.hpp> #include <boost/bimap/support/map_type_by.hpp> #include <boost/bimap/support/value_type_by.hpp> #include <boost/bimap/support/iterator_type_by.hpp> using namespace boost::bimaps; using namespace boost::bimaps::support; typedef bimap<int, unconstrained_set_of<double> > bm_type; namespace support_metafunctions_test { typedef boost::is_same < data_type_by< member_at::left , bm_type >::type, key_type_by < member_at::right, bm_type >::type >::type test_metafunction_1; BOOST_STATIC_ASSERT(test_metafunction_1::value); typedef boost::is_same < data_type_by< member_at::right, bm_type >::type, key_type_by < member_at::left , bm_type >::type >::type test_metafunction_2; BOOST_STATIC_ASSERT(test_metafunction_2::value); typedef boost::is_same < map_type_by < member_at::left , bm_type >::type::value_type, value_type_by< member_at::left , bm_type >::type >::type test_metafunction_3; BOOST_STATIC_ASSERT(test_metafunction_3::value); } // namespace support_metafunctions_test void test_bimap_extra() { // extra tests // --------------------------------------------------------------- // This section test small things... when a group of this checks // can be related it is moved to a separate unit test file. } int test_main( int, char* [] ) { test_bimap_extra(); return 0; }
28.255556
78
0.709792
randolphwong
6149af574debad2461d5f05b65117c50f7ec6098
3,545
cpp
C++
engine/formats/texture/TextureLoad.cpp
KenzieMac130/CitrusToolbox
b679ffbf7c98aebeb4ed1f3a4f46102b96466af8
[ "Apache-2.0" ]
8
2021-03-29T17:21:08.000Z
2022-01-31T09:54:56.000Z
engine/formats/texture/TextureLoad.cpp
KenzieMac130/CitrusToolbox
b679ffbf7c98aebeb4ed1f3a4f46102b96466af8
[ "Apache-2.0" ]
12
2021-02-16T22:28:15.000Z
2022-01-28T18:12:53.000Z
engine/formats/texture/TextureLoad.cpp
KenzieMac130/CitrusToolbox
b679ffbf7c98aebeb4ed1f3a4f46102b96466af8
[ "Apache-2.0" ]
1
2021-06-25T00:24:20.000Z
2021-06-25T00:24:20.000Z
/* Copyright 2021 MacKenzie Strand 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 "TextureLoad.h" #define STBI_ASSERT(x) ctAssert(x) #define STBI_MALLOC(sz) ctMalloc(sz) #define STBI_REALLOC(p, newsz) ctRealloc(p, newsz) #define STBI_FREE(p) ctFree(p) #define STB_IMAGE_IMPLEMENTATION #include "stb/stb_image.h" #include "tiny_imageFormat/tinyimageformat.h" #define TINYKTX_IMPLEMENTATION #define TINYDDS_IMPLEMENTATION #include "tiny_ktx/tinyktx.h" #include "tiny_dds/tinydds.h" struct tinyUserData { ctFile* pFile; }; void* ctTinyAlloc(void* user, size_t size) { return ctMalloc(size); } void ctTinyFree(void* user, void* memory) { ctFree(memory); } size_t ctTinyRead(void* user, void* buffer, size_t byteCount) { tinyUserData* pCtx = (tinyUserData*)user; return pCtx->pFile->ReadRaw(buffer, byteCount, 1); } bool ctTinySeek(void* user, int64_t offset) { tinyUserData* pCtx = (tinyUserData*)user; return pCtx->pFile->Seek(offset, CT_FILE_SEEK_SET) == CT_SUCCESS; } int64_t ctTinyTell(void* user) { tinyUserData* pCtx = (tinyUserData*)user; return pCtx->pFile->Tell(); } void ctTinyError(void* user, char const* msg) { ctDebugError(msg); } TinyKtx_Callbacks tinyKtxCbs = { ctTinyError, ctTinyAlloc, ctTinyFree, ctTinyRead, ctTinySeek, ctTinyTell}; TinyDDS_Callbacks tinyDdsCbs = { ctTinyError, ctTinyAlloc, ctTinyFree, ctTinyRead, ctTinySeek, ctTinyTell}; struct stbUserData { ctFile* pFile; }; int ctStbRead(void* user, char* data, int size) { stbUserData* pCtx = (stbUserData*)user; return (int)pCtx->pFile->ReadRaw(data, size, 1); } void ctStbSkip(void* user, int n) { stbUserData* pCtx = (stbUserData*)user; pCtx->pFile->Seek(n, CT_FILE_SEEK_CUR); } int ctStbEof(void* user) { stbUserData* pCtx = (stbUserData*)user; return pCtx->pFile->isEndOfFile(); } stbi_io_callbacks stbCallbacks = {ctStbRead, ctStbSkip, ctStbEof}; ctResults ctLoadTextureFromFile(const char* path, ctTextureLoadCtx* ctx) { ctFile file = ctFile(path, CT_FILE_OPEN_READ); if (!file.isOpen()) { return CT_FAILURE_INACCESSIBLE; } ctStringUtf8 ext = path; ext.FilePathGetExtension(); if (ext == ".ktx") { /* Load Tiny KTX */ tinyUserData ud = {&file}; TinyKtx_ContextHandle tinyKtx = TinyKtx_CreateContext(&tinyKtxCbs, &ud); if (!TinyKtx_ReadHeader(tinyKtx)) { TinyKtx_DestroyContext(tinyKtx); return CT_FAILURE_CORRUPTED_CONTENTS; } } else if (ext == ".dds") { /* Load Tiny DDS */ } else { /* Attempt to Load STB */ int channels = 0; stbUserData ud = {&file}; ctx->memory.data = stbi_load_from_callbacks( &stbCallbacks, &ud, &ctx->memory.width, &ctx->memory.height, &channels, 4); ctx->memory.format = TinyImageFormat_R8G8B8A8_UNORM; if (!ctx->memory.data) { return CT_FAILURE_CORRUPTED_CONTENTS; } } return CT_SUCCESS; } void ctTextureLoadCtxRelease(ctTextureLoadCtx* pCtx) { if (!pCtx) { return; } ctFree(pCtx->memory.data); }
31.096491
83
0.705501
KenzieMac130
614d8694ff056eb8efd01ca5b78a168f29a0ce0e
327
cpp
C++
CourseContent/data-members/main.cpp
ejrach/course-cplusplus
bc646ea3a2294d1d0b897d214845925fca848002
[ "MIT" ]
null
null
null
CourseContent/data-members/main.cpp
ejrach/course-cplusplus
bc646ea3a2294d1d0b897d214845925fca848002
[ "MIT" ]
null
null
null
CourseContent/data-members/main.cpp
ejrach/course-cplusplus
bc646ea3a2294d1d0b897d214845925fca848002
[ "MIT" ]
null
null
null
// // main.cpp // data-members // // Created by Eric on 7/9/19. // Copyright © 2019 Eric. All rights reserved. // #include <iostream> #include "Cat.h" using namespace std; int main(){ Cat jim; Cat bob; jim.makeHappy(); jim.speak(); bob.makeSad(); bob.speak(); return 0; }
12.111111
47
0.544343
ejrach
6153151bc64efbf7ec41bf76c8e2907ce39bf2e3
1,180
hpp
C++
3rdparty/range-v3/include/range/v3/action.hpp
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
2
2018-01-28T14:30:10.000Z
2019-03-27T09:21:58.000Z
3rdparty/range-v3/include/range/v3/action.hpp
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
1
2020-05-01T11:52:59.000Z
2020-05-01T11:52:59.000Z
include/3rd-party/ericniebler/range-v3/include/range/v3/action.hpp
dda119141/mp3tags
c75818e4fd6341f2c0c0b482f5c6eb1809b382aa
[ "MIT" ]
2
2020-03-27T22:08:35.000Z
2020-04-01T22:14:56.000Z
/// \file // Range v3 library // // Copyright Eric Niebler 2014-present // // Use, modification and distribution is subject to the // Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Project home: https://github.com/ericniebler/range-v3 // #ifndef RANGES_V3_ACTION_HPP #define RANGES_V3_ACTION_HPP #include <range/v3/action/concepts.hpp> #include <range/v3/action/drop.hpp> #include <range/v3/action/drop_while.hpp> #include <range/v3/action/erase.hpp> #include <range/v3/action/insert.hpp> #include <range/v3/action/join.hpp> #include <range/v3/action/push_back.hpp> #include <range/v3/action/push_front.hpp> #include <range/v3/action/remove_if.hpp> #include <range/v3/action/reverse.hpp> #include <range/v3/action/shuffle.hpp> #include <range/v3/action/slice.hpp> #include <range/v3/action/sort.hpp> #include <range/v3/action/split.hpp> #include <range/v3/action/stable_sort.hpp> #include <range/v3/action/stride.hpp> #include <range/v3/action/take.hpp> #include <range/v3/action/take_while.hpp> #include <range/v3/action/transform.hpp> #include <range/v3/action/unique.hpp> #endif
30.25641
58
0.755085
WoodoLee
6153203947123856a28443e6368df7c3c63eb699
1,998
hpp
C++
systems/opengl/shaders/ShadowMapShader.hpp
phisko/kengine
c30f98cc8e79cce6574b5f61088b511f29bbe8eb
[ "MIT" ]
259
2018-11-01T05:12:37.000Z
2022-03-28T11:15:27.000Z
systems/opengl/shaders/ShadowMapShader.hpp
raptoravis/kengine
619151c20e9db86584faf04937bed3d084e3bc21
[ "MIT" ]
2
2018-11-30T13:58:44.000Z
2018-12-17T11:58:42.000Z
systems/opengl/shaders/ShadowMapShader.hpp
raptoravis/kengine
619151c20e9db86584faf04937bed3d084e3bc21
[ "MIT" ]
16
2018-12-01T13:38:18.000Z
2021-12-04T21:31:55.000Z
#pragma once #include <glm/glm.hpp> #include "Point.hpp" #include "opengl/Program.hpp" #include "DepthCubeSrc.hpp" namespace kengine { class Entity; struct DirLightComponent; struct SpotLightComponent; struct PointLightComponent; } namespace kengine::Shaders { class ShadowMapShader : public putils::gl::Program { public: ShadowMapShader(bool usesGBuffer = false, const char * name = "") : Program(usesGBuffer, name) {} virtual ~ShadowMapShader() {} virtual void drawToTexture(GLuint texture, const glm::mat4 & lightSpaceMatrix) {} void run(const Parameters & params) override {} virtual void run(Entity & e, DirLightComponent & light, const Parameters & params); virtual void run(Entity & e, SpotLightComponent & light, const putils::Point3f & pos, const Parameters & params); private: template<typename T, typename Func> void runImpl(T & depthMap, Func && draw, const Parameters & params); }; class ShadowCubeShader : public putils::gl::Program, public Shaders::src::DepthCube::Geom::Uniforms, public Shaders::src::DepthCube::Frag::Uniforms { public: ShadowCubeShader(bool usesGBuffer = false, const char * name = "") : Program(usesGBuffer, name) {} virtual ~ShadowCubeShader() {} void run(const Parameters & params) override {} virtual void run(Entity & e, PointLightComponent & light, const putils::Point3f & pos, float radius, const Parameters & params); virtual void drawObjects() {} protected: putils::gl::Uniform<glm::mat4> _proj; putils::gl::Uniform<glm::mat4> _view; putils::gl::Uniform<glm::mat4> _model; public: putils_reflection_attributes( putils_reflection_attribute_private(&ShadowCubeShader::_proj), putils_reflection_attribute_private(&ShadowCubeShader::_view), putils_reflection_attribute_private(&ShadowCubeShader::_model) ); putils_reflection_parents( putils_reflection_parent(Shaders::src::DepthCube::Geom::Uniforms), putils_reflection_parent(Shaders::src::DepthCube::Frag::Uniforms) ); }; }
32.225806
130
0.742743
phisko
6158085c4eea83ed8841d0362254223735dd3f47
86,513
cpp
C++
Source/HoudiniEngineEditor/Private/HoudiniPDGDetails.cpp
Filoppi/HoudiniEngineForUnreal
7927f4fe7c6bd92e6d4b0f356f58d7eda20964e6
[ "BSD-3-Clause" ]
null
null
null
Source/HoudiniEngineEditor/Private/HoudiniPDGDetails.cpp
Filoppi/HoudiniEngineForUnreal
7927f4fe7c6bd92e6d4b0f356f58d7eda20964e6
[ "BSD-3-Clause" ]
null
null
null
Source/HoudiniEngineEditor/Private/HoudiniPDGDetails.cpp
Filoppi/HoudiniEngineForUnreal
7927f4fe7c6bd92e6d4b0f356f58d7eda20964e6
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) <2021> Side Effects Software Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. The name of Side Effects Software may not be used to endorse or * promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY SIDE EFFECTS SOFTWARE "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 SIDE EFFECTS SOFTWARE 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 "HoudiniPDGDetails.h" #include "HoudiniEngineEditorPrivatePCH.h" #include "HoudiniPDGAssetLink.h" #include "HoudiniPDGManager.h" #include "HoudiniEngineUtils.h" #include "HoudiniEngineRuntimePrivatePCH.h" #include "HoudiniAssetActor.h" #include "HoudiniEngine.h" #include "HoudiniEngineBakeUtils.h" #include "HoudiniEngineCommands.h" #include "HoudiniEngineDetails.h" #include "HoudiniEngineEditor.h" #include "HoudiniEngineEditorUtils.h" #include "DetailCategoryBuilder.h" #include "DetailLayoutBuilder.h" #include "IDetailGroup.h" #include "IDetailCustomization.h" #include "PropertyCustomizationHelpers.h" #include "DetailWidgetRow.h" #include "ScopedTransaction.h" #include "Widgets/Input/SButton.h" #include "Widgets/Input/SCheckBox.h" #include "Widgets/Input/SComboBox.h" #include "Widgets/Input/SEditableTextBox.h" #include "Widgets/Images/SImage.h" #include "Widgets/SBoxPanel.h" #include "Widgets/Layout/SSpacer.h" #include "Framework/SlateDelegates.h" #include "Templates/SharedPointer.h" #include "Internationalization/Internationalization.h" #define LOCTEXT_NAMESPACE HOUDINI_LOCTEXT_NAMESPACE #define HOUDINI_ENGINE_UI_SECTION_PDG_BAKE 2 void FHoudiniPDGDetails::CreateWidget( IDetailCategoryBuilder& HouPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>&& InPDGAssetLink) { if (!IsValidWeakPointer(InPDGAssetLink)) return; // PDG ASSET FHoudiniPDGDetails::AddPDGAssetWidget(HouPDGCategory, InPDGAssetLink); // TOP NETWORKS FHoudiniPDGDetails::AddTOPNetworkWidget(HouPDGCategory, InPDGAssetLink); // PDG EVENT MESSAGES } void FHoudiniPDGDetails::AddPDGAssetWidget( IDetailCategoryBuilder& InPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink) { // PDG STATUS ROW AddPDGAssetStatus(InPDGCategory, InPDGAssetLink); // Commandlet Status row AddPDGCommandletStatus(InPDGCategory, FHoudiniEngine::Get().GetPDGCommandletStatus()); // REFRESH / RESET Buttons { TSharedRef<SHorizontalBox> RefreshHBox = SNew(SHorizontalBox); TSharedPtr<SHorizontalBox> ResetHBox = SNew(SHorizontalBox); FDetailWidgetRow& PDGRefreshResetRow = InPDGCategory.AddCustomRow(FText::GetEmpty()) .WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ SNew(SBox) .WidthOverride(200.0f) [ SNew(SButton) //.Text(LOCTEXT("Refresh", "Refresh")) .ToolTipText(LOCTEXT("RefreshTooltip", "Refreshes infos displayed by the the PDG Asset Link")) .ContentPadding(FMargin(5.0f, 5.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .OnClicked_Lambda([InPDGAssetLink]() { FHoudiniPDGDetails::RefreshPDGAssetLink(InPDGAssetLink); return FReply::Handled(); }) .Content() [ SAssignNew(RefreshHBox, SHorizontalBox) ] ] ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(200.0f) [ SNew(SButton) //.Text(LOCTEXT("Reset", "Reset")) .ToolTipText(LOCTEXT("ResetTooltip", "Resets the PDG Asset Link")) .ContentPadding(FMargin(5.0f, 5.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .OnClicked_Lambda([InPDGAssetLink]() { // TODO: RESET USELESS? FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); return FReply::Handled(); }) .Content() [ SAssignNew(ResetHBox, SHorizontalBox) ] ] ] ]; TSharedPtr<FSlateDynamicImageBrush> RefreshIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGRefreshIconBrush(); if (RefreshIconBrush.IsValid()) { TSharedPtr<SImage> RefreshImage; RefreshHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(RefreshImage, SImage) ] ]; RefreshImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([RefreshIconBrush]() { return RefreshIconBrush.Get(); }))); } RefreshHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(LOCTEXT("Refresh", "Refresh")) ]; TSharedPtr<FSlateDynamicImageBrush> ResetIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGResetIconBrush(); if (ResetIconBrush.IsValid()) { TSharedPtr<SImage> ResetImage; ResetHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(ResetImage, SImage) ] ]; ResetImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([ResetIconBrush]() { return ResetIconBrush.Get(); }))); } ResetHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(LOCTEXT("Reset", "Reset")) ]; } // TOP NODE FILTER { FText Tooltip = FText::FromString(TEXT("When enabled, the TOP Node Filter will only display the TOP Nodes found in the current network that start with the filter prefix. Disabling the Filter will display all of the TOP Network's TOP Nodes.")); // Lambda for changing the filter value auto ChangeTOPNodeFilter = [InPDGAssetLink](const FString& NewValue) { if (!IsValidWeakPointer(InPDGAssetLink)) return; if (InPDGAssetLink->TOPNodeFilter.Equals(NewValue)) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->TOPNodeFilter = NewValue; // Notify that we have changed the property FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, TOPNodeFilter), InPDGAssetLink.Get()); }; FDetailWidgetRow& PDGFilterRow = InPDGCategory.AddCustomRow(FText::GetEmpty()); // Disable if PDG is not linked DisableIfPDGNotLinked(PDGFilterRow, InPDGAssetLink); PDGFilterRow.NameWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ // Checkbox enable filter SNew(SCheckBox) .IsChecked_Lambda([InPDGAssetLink]() { return InPDGAssetLink->bUseTOPNodeFilter ? ECheckBoxState::Checked : ECheckBoxState::Unchecked;; }) .OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState) { if (!IsValidWeakPointer(InPDGAssetLink)) return; const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false; if (InPDGAssetLink->bUseTOPNodeFilter == bNewState) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->bUseTOPNodeFilter = bNewState; // Notify that we have changed the property FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bUseTOPNodeFilter), InPDGAssetLink.Get()); }) .ToolTipText(Tooltip) ] + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ SNew(STextBlock) .Text(FText::FromString(TEXT("TOP Node Filter"))) .ToolTipText(Tooltip) ]; PDGFilterRow.ValueWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot().FillWidth(1.0f) [ SNew(SEditableTextBox) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) .ToolTipText(Tooltip) .Text_Lambda([InPDGAssetLink]() { if (!IsValidWeakPointer(InPDGAssetLink)) return FText(); return FText::FromString(InPDGAssetLink->TOPNodeFilter); }) .OnTextCommitted_Lambda([ChangeTOPNodeFilter](const FText& Val, ETextCommit::Type TextCommitType) { ChangeTOPNodeFilter(Val.ToString()); }) ] + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) .VAlign(VAlign_Center) [ SNew(SButton) .ToolTipText(LOCTEXT("RevertToDefault", "Revert to default")) .ButtonStyle(FEditorStyle::Get(), "NoBorder") .ContentPadding(0) .Visibility(EVisibility::Visible) .OnClicked_Lambda([=]() { FString DefaultFilter = TEXT(HAPI_UNREAL_PDG_DEFAULT_TOP_FILTER); ChangeTOPNodeFilter(DefaultFilter); return FReply::Handled(); }) [ SNew(SImage) .Image(FEditorStyle::GetBrush("PropertyWindow.DiffersFromDefault")) ] ]; } // TOP OUTPUT FILTER { // Lambda for changing the filter value FText Tooltip = FText::FromString(TEXT("When enabled, the Work Item Output Files created for the TOP Nodes found in the current network that start with the filter prefix will be automatically loaded int the world after being cooked.")); auto ChangeTOPOutputFilter = [InPDGAssetLink](const FString& NewValue) { if (IsValidWeakPointer(InPDGAssetLink)) return; if (InPDGAssetLink->TOPOutputFilter.Equals(NewValue)) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->TOPOutputFilter = NewValue; // Notify that we have changed the property FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, TOPOutputFilter), InPDGAssetLink.Get()); }; FDetailWidgetRow& PDGOutputFilterRow = InPDGCategory.AddCustomRow(FText::GetEmpty()); // Disable if PDG is not linked DisableIfPDGNotLinked(PDGOutputFilterRow, InPDGAssetLink); PDGOutputFilterRow.NameWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ // Checkbox enable filter SNew(SCheckBox) .IsChecked_Lambda([InPDGAssetLink]() { return InPDGAssetLink->bUseTOPOutputFilter ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }) .OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState) { if (IsValidWeakPointer(InPDGAssetLink)) return; const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false; if (InPDGAssetLink->bUseTOPOutputFilter == bNewState) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->bUseTOPOutputFilter = bNewState; // Notify that we have changed the property FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bUseTOPOutputFilter), InPDGAssetLink.Get()); }) .ToolTipText(Tooltip) ] + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ SNew(STextBlock) .Text(FText::FromString(TEXT("TOP Output Filter"))) .ToolTipText(Tooltip) ]; PDGOutputFilterRow.ValueWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot().FillWidth(1.0f) [ SNew(SEditableTextBox) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) .Text_Lambda([InPDGAssetLink]() { if (!IsValidWeakPointer(InPDGAssetLink)) return FText(); return FText::FromString(InPDGAssetLink->TOPOutputFilter); }) .OnTextCommitted_Lambda([ChangeTOPOutputFilter](const FText& Val, ETextCommit::Type TextCommitType) { ChangeTOPOutputFilter(Val.ToString()); }) .ToolTipText(Tooltip) ] + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) .VAlign(VAlign_Center) [ SNew(SButton) .ToolTipText(LOCTEXT("RevertToDefault", "Revert to default")) .ButtonStyle(FEditorStyle::Get(), "NoBorder") .ContentPadding(0) .Visibility(EVisibility::Visible) .OnClicked_Lambda([ChangeTOPOutputFilter]() { FString DefaultFilter = TEXT(HAPI_UNREAL_PDG_DEFAULT_TOP_OUTPUT_FILTER); ChangeTOPOutputFilter(DefaultFilter); return FReply::Handled(); }) [ SNew(SImage) .Image(FEditorStyle::GetBrush("PropertyWindow.DiffersFromDefault")) ] ]; } // Checkbox: Autocook { FText Tooltip = FText::FromString(TEXT("When enabled, the selected TOP Network's output will automatically cook after succesfully cooking the PDG Asset Link HDA.")); FDetailWidgetRow& PDGAutocookRow = InPDGCategory.AddCustomRow(FText::GetEmpty()); // Disable if PDG is not linked DisableIfPDGNotLinked(PDGAutocookRow, InPDGAssetLink); PDGAutocookRow.NameWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ SNew(STextBlock) .Text(FText::FromString(TEXT("Auto-cook"))) .ToolTipText(Tooltip) ]; TSharedPtr<SCheckBox> AutoCookCheckBox; PDGAutocookRow.ValueWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ // Checkbox SAssignNew(AutoCookCheckBox, SCheckBox) .IsChecked_Lambda([InPDGAssetLink]() { return InPDGAssetLink->bAutoCook ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }) .OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState) { const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false; if (!IsValidWeakPointer(InPDGAssetLink) || InPDGAssetLink->bAutoCook == bNewState) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->bAutoCook = bNewState; FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bAutoCook), InPDGAssetLink.Get()); }) .ToolTipText(Tooltip) ]; } // Output parent actor selector { IDetailPropertyRow* PDGOutputParentActorRow = InPDGCategory.AddExternalObjectProperty({ InPDGAssetLink.Get() }, "OutputParentActor"); if (PDGOutputParentActorRow) { TAttribute<bool> PDGOutputParentActorRowEnabled; BindDisableIfPDGNotLinked(PDGOutputParentActorRowEnabled, InPDGAssetLink); PDGOutputParentActorRow->IsEnabled(PDGOutputParentActorRowEnabled); TSharedPtr<SWidget> NameWidget; TSharedPtr<SWidget> ValueWidget; PDGOutputParentActorRow->GetDefaultWidgets(NameWidget, ValueWidget); PDGOutputParentActorRow->DisplayName(FText::FromString(TEXT("Output Parent Actor"))); PDGOutputParentActorRow->ToolTip(FText::FromString( TEXT("The PDG Output Actors will be created under this parent actor. If not set, then the PDG Output Actors will be created under a new folder."))); } } // Add bake widgets for PDG output CreatePDGBakeWidgets(InPDGCategory, InPDGAssetLink); // TODO: move this to a better place: the baking code is in HoudiniEngineEditor, the PDG manager (that knows about // when work object results are loaded is in HoudiniEngine and the PDGAssetLink is in HoudiniEngineRuntime). So // we bind an auto-bake helper function here. Maybe the baking code can move to HoudiniEngine? if (InPDGAssetLink->AutoBakeDelegateHandle.IsValid()) InPDGAssetLink->OnWorkResultObjectLoaded.Remove(InPDGAssetLink->AutoBakeDelegateHandle); InPDGAssetLink->AutoBakeDelegateHandle = InPDGAssetLink->OnWorkResultObjectLoaded.AddStatic(FHoudiniEngineBakeUtils::CheckPDGAutoBakeAfterResultObjectLoaded); // WORK ITEM STATUS { FDetailWidgetRow& PDGStatusRow = InPDGCategory.AddCustomRow(FText::GetEmpty()); // Disable if PDG is not linked DisableIfPDGNotLinked(PDGStatusRow, InPDGAssetLink); FHoudiniPDGDetails::AddWorkItemStatusWidget( PDGStatusRow, TEXT("Asset Work Item Status"), InPDGAssetLink, false); } } bool FHoudiniPDGDetails::GetPDGStatusAndColor( const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink, FString& OutPDGStatusString, FLinearColor& OutPDGStatusColor) { OutPDGStatusString = FString(); OutPDGStatusColor = FLinearColor::White; if (!IsValidWeakPointer(InPDGAssetLink)) return false; switch (InPDGAssetLink->LinkState) { case EPDGLinkState::Linked: OutPDGStatusString = TEXT("PDG is READY"); OutPDGStatusColor = FLinearColor::Green; break; case EPDGLinkState::Linking: OutPDGStatusString = TEXT("PDG is Linking"); OutPDGStatusColor = FLinearColor::Yellow; break; case EPDGLinkState::Error_Not_Linked: OutPDGStatusString = TEXT("PDG is ERRORED"); OutPDGStatusColor = FLinearColor::Red; break; case EPDGLinkState::Inactive: OutPDGStatusString = TEXT("PDG is INACTIVE"); OutPDGStatusColor = FLinearColor::White; break; default: return false; } return true; } void FHoudiniPDGDetails::AddPDGAssetStatus( IDetailCategoryBuilder& InPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink) { FDetailWidgetRow& PDGStatusRow = InPDGCategory.AddCustomRow(FText::GetEmpty()) .WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .FillWidth(1.0f) .Padding(2.0f, 0.0f) .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ SNew(STextBlock) .Text_Lambda([InPDGAssetLink]() { FString PDGStatusString; FLinearColor PDGStatusColor; GetPDGStatusAndColor(InPDGAssetLink, PDGStatusString, PDGStatusColor); return FText::FromString(PDGStatusString); }) .ColorAndOpacity_Lambda([InPDGAssetLink]() { FString PDGStatusString; FLinearColor PDGStatusColor; GetPDGStatusAndColor(InPDGAssetLink, PDGStatusString, PDGStatusColor); return FSlateColor(PDGStatusColor); }) ] ]; } void FHoudiniPDGDetails::GetPDGCommandletStatus(FString& OutStatusString, FLinearColor& OutStatusColor) { OutStatusString = FString(); OutStatusColor = FLinearColor::White; switch (FHoudiniEngine::Get().GetPDGCommandletStatus()) { case EHoudiniBGEOCommandletStatus::Connected: OutStatusString = TEXT("Async importer is CONNECTED"); OutStatusColor = FLinearColor::Green; break; case EHoudiniBGEOCommandletStatus::Running: OutStatusString = TEXT("Async importer is Running"); OutStatusColor = FLinearColor::Yellow; break; case EHoudiniBGEOCommandletStatus::Crashed: OutStatusString = TEXT("Async importer has CRASHED"); OutStatusColor = FLinearColor::Red; break; case EHoudiniBGEOCommandletStatus::NotStarted: OutStatusString = TEXT("Async importer is NOT STARTED"); OutStatusColor = FLinearColor::White; break; } } void FHoudiniPDGDetails::AddPDGCommandletStatus( IDetailCategoryBuilder& InPDGCategory, const EHoudiniBGEOCommandletStatus& InCommandletStatus) { FDetailWidgetRow& PDGStatusRow = InPDGCategory.AddCustomRow(FText::GetEmpty()) .WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .FillWidth(1.0f) .Padding(2.0f, 0.0f) .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ SNew(STextBlock) .Visibility_Lambda([]() { const UHoudiniRuntimeSettings* Settings = GetDefault<UHoudiniRuntimeSettings>(); if (IsValid(Settings)) { return FHoudiniEngineCommands::IsPDGCommandletEnabled() ? EVisibility::Visible : EVisibility::Collapsed; } return EVisibility::Visible; }) .Text_Lambda([]() { FString StatusString; FLinearColor StatusColor; GetPDGCommandletStatus(StatusString, StatusColor); return FText::FromString(StatusString); }) .ColorAndOpacity_Lambda([]() { FString StatusString; FLinearColor StatusColor; GetPDGCommandletStatus(StatusString, StatusColor); return FSlateColor(StatusColor); }) ] ]; } bool FHoudiniPDGDetails::GetWorkItemTallyValueAndColor( const TWeakObjectPtr<UHoudiniPDGAssetLink>& InAssetLink, bool bInForSelectedNode, const FString& InTallyItemString, int32& OutValue, FLinearColor& OutColor) { OutValue = 0; OutColor = FLinearColor::White; if (!IsValidWeakPointer(InAssetLink)) return false; bool bFound = false; const FWorkItemTallyBase* TallyPtr = nullptr; if (bInForSelectedNode) { UTOPNode* const TOPNode = InAssetLink->GetSelectedTOPNode(); if (TOPNode && !TOPNode->bHidden) TallyPtr = &(TOPNode->GetWorkItemTally()); } else TallyPtr = &(InAssetLink->WorkItemTally); if (TallyPtr) { if (InTallyItemString == TEXT("WAITING")) { // For now we add waiting and scheduled together, since there is no separate column for scheduled on the UI OutValue = TallyPtr->NumWaitingWorkItems() + TallyPtr->NumScheduledWorkItems(); OutColor = OutValue > 0 ? FLinearColor(0.0f, 1.0f, 1.0f) : FLinearColor::White; bFound = true; } else if (InTallyItemString == TEXT("COOKING")) { OutValue = TallyPtr->NumCookingWorkItems(); OutColor = OutValue > 0 ? FLinearColor::Yellow : FLinearColor::White; bFound = true; } else if (InTallyItemString == TEXT("COOKED")) { OutValue = TallyPtr->NumCookedWorkItems(); OutColor = OutValue > 0 ? FLinearColor::Green : FLinearColor::White; bFound = true; } else if (InTallyItemString == TEXT("FAILED")) { OutValue = TallyPtr->NumErroredWorkItems(); OutColor = OutValue > 0 ? FLinearColor::Red : FLinearColor::White; bFound = true; } } return bFound; } void FHoudiniPDGDetails::AddWorkItemStatusWidget( FDetailWidgetRow& InRow, const FString& InTitleString, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InAssetLink, bool bInForSelectedNode) { auto AddGridBox = [InAssetLink, bInForSelectedNode](const FString& Title) -> SHorizontalBox::FSlot& { return SHorizontalBox::Slot() .MaxWidth(500.0f) .Padding(0.0f, 0.0f, 2.0f, 0.0f) .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ SNew(SVerticalBox) + SVerticalBox::Slot() .VAlign(VAlign_Center) .HAlign(HAlign_Center) .AutoHeight() .Padding(FMargin(1.0f, 2.0f)) [ SNew(SBorder) .IsEnabled_Lambda([InAssetLink]() { return IsPDGLinked(InAssetLink); }) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) .BorderBackgroundColor(FSlateColor(FLinearColor(0.6, 0.6, 0.6))) .Padding(FMargin(1.0f, 5.0f)) [ SNew(SBox) .WidthOverride(95.0f) .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ SNew(STextBlock) .Text(FText::FromString(Title)) .ColorAndOpacity_Lambda([InAssetLink, bInForSelectedNode, Title]() { int32 Value; FLinearColor Color; GetWorkItemTallyValueAndColor(InAssetLink, bInForSelectedNode, Title, Value, Color); return FSlateColor(Color); }) ] ] ] + SVerticalBox::Slot() .VAlign(VAlign_Center) .HAlign(HAlign_Center) .AutoHeight() .Padding(FMargin(1.0f, 2.0f)) [ SNew(SBorder) .IsEnabled_Lambda([InAssetLink]() { return IsPDGLinked(InAssetLink); }) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) .BorderBackgroundColor(FSlateColor(FLinearColor(0.8, 0.8, 0.8))) .Padding(FMargin(1.0f, 5.0f)) [ SNew(SBox) .WidthOverride(95.0f) .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ SNew(STextBlock) .Text_Lambda([InAssetLink, bInForSelectedNode, Title]() { int32 Value; FLinearColor Color; GetWorkItemTallyValueAndColor(InAssetLink, bInForSelectedNode, Title, Value, Color); return FText::AsNumber(Value); }) .ColorAndOpacity_Lambda([InAssetLink, bInForSelectedNode, Title]() { int32 Value; FLinearColor Color; GetWorkItemTallyValueAndColor(InAssetLink, bInForSelectedNode, Title, Value, Color); return FSlateColor(Color); }) ] ] ] ]; }; InRow.WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .Padding(0.0f, 0.0f) .AutoWidth() [ SNew(SVerticalBox) +SVerticalBox::Slot() [ SNew(SSpacer) ] + SVerticalBox::Slot() .AutoHeight() .VAlign(VAlign_Center) .HAlign(HAlign_Center) .Padding(FMargin(0.0f, 2.0f)) [ SNew(STextBlock) .IsEnabled_Lambda([InAssetLink]() { return IsPDGLinked(InAssetLink); }) .Text(FText::FromString(InTitleString)) ] + SVerticalBox::Slot() .AutoHeight() .VAlign(VAlign_Center) .HAlign(HAlign_Center) .Padding(FMargin(0.0f, 2.0f)) [ SNew(SHorizontalBox) + AddGridBox(TEXT("WAITING")) + AddGridBox(TEXT("COOKING")) + AddGridBox(TEXT("COOKED")) + AddGridBox(TEXT("FAILED")) ] + SVerticalBox::Slot() [ SNew(SSpacer) ] ] ]; } void FHoudiniPDGDetails::AddTOPNetworkWidget( IDetailCategoryBuilder& InPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink ) { auto DirtyAll = [this](const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink) { if (IsValidWeakPointer(InPDGAssetLink)) { UTOPNetwork* const TOPNetwork = InPDGAssetLink->GetSelectedTOPNetwork(); if (IsValid(TOPNetwork)) { if (IsPDGLinked(InPDGAssetLink)) { FHoudiniPDGManager::DirtyAll(TOPNetwork); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); } else { UHoudiniPDGAssetLink::ClearTOPNetworkWorkItemResults(TOPNetwork); } } } }; if (!InPDGAssetLink->GetSelectedTOPNetwork()) return; if (InPDGAssetLink->AllTOPNetworks.Num() <= 0) return; TOPNetworksPtr.Reset(); FString GroupLabel = TEXT("TOP Networks"); IDetailGroup& TOPNetWorkGrp = InPDGCategory.AddGroup(FName(*GroupLabel), FText::FromString(GroupLabel), false, true); // Combobox: TOP Network { FDetailWidgetRow& PDGTOPNetRow = TOPNetWorkGrp.AddWidgetRow(); // DisableIfPDGNotLinked(PDGTOPNetRow, InPDGAssetLink); PDGTOPNetRow.NameWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() [ SNew(STextBlock) .Text(FText::FromString(TEXT("TOP Network"))) ]; // Fill the TOP Networks SharedString array TOPNetworksPtr.SetNum(InPDGAssetLink->AllTOPNetworks.Num()); for(int32 Idx = 0; Idx < InPDGAssetLink->AllTOPNetworks.Num(); Idx++) { const UTOPNetwork* Network = InPDGAssetLink->AllTOPNetworks[Idx]; if (!IsValid(Network)) { TOPNetworksPtr[Idx] = MakeShareable(new FTextAndTooltip( Idx, TEXT("Invalid"), TEXT("Invalid") )); } else { TOPNetworksPtr[Idx] = MakeShareable(new FTextAndTooltip( Idx, FHoudiniEngineEditorUtils::GetNodeNamePaddedByPathDepth(Network->NodeName, Network->NodePath), Network->NodePath )); } } if(TOPNetworksPtr.Num() <= 0) TOPNetworksPtr.Add(MakeShareable(new FTextAndTooltip(INDEX_NONE, "----"))); // Lambda for selecting another TOPNet auto OnTOPNetChanged = [InPDGAssetLink](TSharedPtr<FTextAndTooltip> InNewChoice) { if (!InNewChoice.IsValid() || !IsValidWeakPointer(InPDGAssetLink)) return; const int32 NewChoice = InNewChoice->Value; int32 NewSelectedIndex = -1; if (InPDGAssetLink->AllTOPNetworks.IsValidIndex(NewChoice)) NewSelectedIndex = NewChoice; if (InPDGAssetLink->SelectedTOPNetworkIndex == NewSelectedIndex) return; if (NewSelectedIndex < 0) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->SelectedTOPNetworkIndex = NewSelectedIndex; FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, SelectedTOPNetworkIndex), InPDGAssetLink.Get()); }; TSharedPtr<SHorizontalBox, ESPMode::NotThreadSafe> HorizontalBoxTOPNet; TSharedPtr<SComboBox<TSharedPtr<FTextAndTooltip>>> ComboBoxTOPNet; int32 SelectedIndex = TOPNetworksPtr.IndexOfByPredicate([InPDGAssetLink](const TSharedPtr<FTextAndTooltip>& InEntry) { return InEntry.IsValid() && InEntry->Value == InPDGAssetLink->SelectedTOPNetworkIndex; }); if (SelectedIndex < 0) SelectedIndex = 0; PDGTOPNetRow.ValueWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .Padding(2, 2, 5, 2) .FillWidth(300.f) .MaxWidth(300.f) [ SAssignNew(ComboBoxTOPNet, SComboBox<TSharedPtr<FTextAndTooltip>>) .OptionsSource(&TOPNetworksPtr) .InitiallySelectedItem(TOPNetworksPtr[SelectedIndex]) .OnGenerateWidget_Lambda([](TSharedPtr<FTextAndTooltip> ChoiceEntry) { const FText ChoiceEntryText = FText::FromString(ChoiceEntry->Text); const FText ChoiceEntryToolTip = FText::FromString(ChoiceEntry->ToolTip); return SNew(STextBlock) .Text(ChoiceEntryText) .ToolTipText(ChoiceEntryToolTip) .Margin(2.0f) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))); }) .OnSelectionChanged_Lambda([OnTOPNetChanged](TSharedPtr<FTextAndTooltip> NewChoice, ESelectInfo::Type SelectType) { return OnTOPNetChanged(NewChoice); }) [ SNew(STextBlock) .Text_Lambda([InPDGAssetLink]() { return FText::FromString(InPDGAssetLink->GetSelectedTOPNetworkName()); }) .ToolTipText_Lambda([InPDGAssetLink]() { UTOPNetwork const * const Network = InPDGAssetLink->GetSelectedTOPNetwork(); if (IsValid(Network)) { if (!Network->NodePath.IsEmpty()) return FText::FromString(Network->NodePath); else return FText::FromString(Network->NodeName); } else { return FText(); } }) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) ] ]; } // Buttons: DIRTY ALL / COOK OUTPUT { TSharedRef<SHorizontalBox> DirtyAllHBox = SNew(SHorizontalBox); TSharedPtr<SHorizontalBox> CookOutHBox = SNew(SHorizontalBox); FDetailWidgetRow& PDGDirtyCookRow = TOPNetWorkGrp.AddWidgetRow() .WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .VAlign(VAlign_Center) .HAlign(HAlign_Center) [ SNew(SBox) .WidthOverride(200.0f) [ SNew(SButton) //.Text(LOCTEXT("DirtyAll", "Dirty All")) .ToolTipText(LOCTEXT("DirtyAllTooltip", "Dirty all TOP nodes in the selected TOP network and clears all of its work item results.")) .ContentPadding(FMargin(5.0f, 5.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink) || (IsValidWeakPointer(InPDGAssetLink) && InPDGAssetLink->GetSelectedTOPNetwork()); }) .OnClicked_Lambda([InPDGAssetLink]() { if (IsValidWeakPointer(InPDGAssetLink)) { UTOPNetwork* const TOPNetwork = InPDGAssetLink->GetSelectedTOPNetwork(); if (IsValid(TOPNetwork)) { if (IsPDGLinked(InPDGAssetLink)) { FHoudiniPDGManager::DirtyAll(TOPNetwork); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); } else { UHoudiniPDGAssetLink::ClearTOPNetworkWorkItemResults(TOPNetwork); } } } return FReply::Handled(); }) .Content() [ SAssignNew(DirtyAllHBox, SHorizontalBox) ] ] ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(200.0f) [ SNew(SButton) //.Text(LOCTEXT("CookOut", "Cook Output")) .ToolTipText(LOCTEXT("CookOutTooltip", "Cooks the output nodes of the selected TOP network")) .ContentPadding(FMargin(5.0f, 5.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { if (!IsPDGLinked(InPDGAssetLink)) return false; const UTOPNetwork* const SelectedTOPNet = InPDGAssetLink->GetSelectedTOPNetwork(); if (!IsValid(SelectedTOPNet)) return false; // Disable if there any nodes in the network that are already cooking return !SelectedTOPNet->AnyWorkItemsPending(); }) .OnClicked_Lambda([InPDGAssetLink]() { if (IsValid(InPDGAssetLink->GetSelectedTOPNetwork())) { //InPDGAssetLink->WorkItemTally.ZeroAll(); FHoudiniPDGManager::CookOutput(InPDGAssetLink->GetSelectedTOPNetwork()); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); } return FReply::Handled(); }) .Content() [ SAssignNew(CookOutHBox, SHorizontalBox) ] ] ] ]; TSharedPtr<FSlateDynamicImageBrush> DirtyAllIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGDirtyAllIconBrush(); if (DirtyAllIconBrush.IsValid()) { TSharedPtr<SImage> DirtyAllImage; DirtyAllHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(DirtyAllImage, SImage) ] ]; DirtyAllImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([DirtyAllIconBrush]() { return DirtyAllIconBrush.Get(); }))); } DirtyAllHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(LOCTEXT("DirtyAll", "Dirty All")) ]; TSharedPtr<FSlateDynamicImageBrush> CookOutIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIRecookIconBrush(); if (CookOutIconBrush.IsValid()) { TSharedPtr<SImage> CookOutImage; CookOutHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(CookOutImage, SImage) ] ]; CookOutImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([CookOutIconBrush]() { return CookOutIconBrush.Get(); }))); } CookOutHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(LOCTEXT("CookOut", "Cook Output")) ]; DisableIfPDGNotLinked(PDGDirtyCookRow, InPDGAssetLink); } // Buttons: PAUSE COOK / CANCEL COOK { TSharedRef<SHorizontalBox> PauseHBox = SNew(SHorizontalBox); TSharedPtr<SHorizontalBox> CancelHBox = SNew(SHorizontalBox); FDetailWidgetRow& PDGDirtyCookRow = TOPNetWorkGrp.AddWidgetRow() .WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(200.0f) [ SNew(SButton) //.Text(LOCTEXT("Pause", "Pause Cook")) .ToolTipText(LOCTEXT("PauseTooltip", "Pauses cooking for the selected TOP Network")) .ContentPadding(FMargin(5.0f, 2.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .OnClicked_Lambda([InPDGAssetLink]() { if (IsValid(InPDGAssetLink->GetSelectedTOPNetwork())) { //InPDGAssetLink->WorkItemTally.ZeroAll(); FHoudiniPDGManager::PauseCook(InPDGAssetLink->GetSelectedTOPNetwork()); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); } return FReply::Handled(); }) .Content() [ SAssignNew(PauseHBox, SHorizontalBox) ] ] ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(200.0f) [ SNew(SButton) //.Text(LOCTEXT("Cancel", "Cancel Cook")) .ToolTipText(LOCTEXT("CancelTooltip", "Cancels cooking the selected TOP network")) .ContentPadding(FMargin(5.0f, 2.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .OnClicked_Lambda([InPDGAssetLink]() { if (IsValid(InPDGAssetLink->GetSelectedTOPNetwork())) { //InPDGAssetLink->WorkItemTally.ZeroAll(); FHoudiniPDGManager::CancelCook(InPDGAssetLink->GetSelectedTOPNetwork()); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); } return FReply::Handled(); }) .Content() [ SAssignNew(CancelHBox, SHorizontalBox) ] ] ] ]; TSharedPtr<FSlateDynamicImageBrush> PauseIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGPauseIconBrush(); if (PauseIconBrush.IsValid()) { TSharedPtr<SImage> PauseImage; PauseHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(PauseImage, SImage) ] ]; PauseImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([PauseIconBrush]() { return PauseIconBrush.Get(); }))); } PauseHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(LOCTEXT("Pause", "Pause Cook")) ]; TSharedPtr<FSlateDynamicImageBrush> CancelIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGCancelIconBrush(); if (CancelIconBrush.IsValid()) { TSharedPtr<SImage> CancelImage; CancelHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(CancelImage, SImage) ] ]; CancelImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([CancelIconBrush]() { return CancelIconBrush.Get(); }))); } CancelHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(LOCTEXT("Cancel", "Cancel Cook")) ]; DisableIfPDGNotLinked(PDGDirtyCookRow, InPDGAssetLink); } // Buttons: Unload Work Item Objects { FDetailWidgetRow& PDGUnloadLoadWorkItemsRow = TOPNetWorkGrp.AddWidgetRow() .WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsValidWeakPointer(InPDGAssetLink) && InPDGAssetLink->GetSelectedTOPNetwork(); }) .WidthOverride(200.0f) [ SNew(SButton) .Text(LOCTEXT("UnloadWorkItemsForNetwork", "Unload All Work Item Objects")) .ToolTipText(LOCTEXT("UnloadWorkItemsForNetworkTooltip", "Unloads / removes loaded work item results from level for all nodes in this network. Not undoable: use the \"Load Work Item Objects\" button on the individual TOP nodes to reload work item results.")) .ContentPadding(FMargin(5.0f, 2.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { if (!IsValidWeakPointer(InPDGAssetLink)) return false; UTOPNetwork* const SelectedNet = InPDGAssetLink->GetSelectedTOPNetwork(); if (!IsValid(SelectedNet) || INDEX_NONE == SelectedNet->AllTOPNodes.IndexOfByPredicate([](const UTOPNode* InNode) { return IsValid(InNode) && InNode->bCachedHaveLoadedWorkResults; })) return false; return true; }) .OnClicked_Lambda([InPDGAssetLink]() { if (IsValidWeakPointer(InPDGAssetLink)) { UTOPNetwork* const TOPNet = InPDGAssetLink->GetSelectedTOPNetwork(); if (IsValid(TOPNet)) { if (IsPDGLinked(InPDGAssetLink)) { // Set the state to ToDelete, PDGManager will delete it when processing work items TOPNet->SetLoadedWorkResultsToDelete(); } else { // Delete and unload the result objects and actors now TOPNet->DeleteAllWorkResultObjectOutputs(); } } } return FReply::Handled(); }) ] ] ]; } // TOP NODE WIDGETS FHoudiniPDGDetails::AddTOPNodeWidget(TOPNetWorkGrp, InPDGAssetLink); } bool FHoudiniPDGDetails::GetSelectedTOPNodeStatusAndColor(const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink, FString& OutTOPNodeStatus, FLinearColor &OutTOPNodeStatusColor) { OutTOPNodeStatus = FString(); OutTOPNodeStatusColor = FLinearColor::White; if (IsValidWeakPointer(InPDGAssetLink)) { UTOPNode* const TOPNode = InPDGAssetLink->GetSelectedTOPNode(); if (IsValid(TOPNode) && !TOPNode->bHidden) { OutTOPNodeStatus = UHoudiniPDGAssetLink::GetTOPNodeStatus(TOPNode); OutTOPNodeStatusColor = UHoudiniPDGAssetLink::GetTOPNodeStatusColor(TOPNode); return true; } } return false; } void FHoudiniPDGDetails::AddTOPNodeWidget( IDetailGroup& InGroup, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink ) { if (!InPDGAssetLink->GetSelectedTOPNetwork()) return; FString GroupLabel = TEXT("TOP Nodes"); IDetailGroup& TOPNodesGrp = InGroup.AddGroup(FName(*GroupLabel), FText::FromString(GroupLabel), true); // Combobox: TOP Node { FDetailWidgetRow& PDGTOPNodeRow = TOPNodesGrp.AddWidgetRow(); // DisableIfPDGNotLinked(PDGTOPNodeRow, InPDGAssetLink); PDGTOPNodeRow.NameWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() [ SNew(STextBlock) .Text(FText::FromString(TEXT("TOP Node"))) ]; // Update the TOP Node SharedString TOPNodesPtr.Reset(); TOPNodesPtr.Add(MakeShareable(new FTextAndTooltip(INDEX_NONE, LOCTEXT("ComboBoxEntryNoSelectedTOPNode", "- Select -").ToString()))); const UTOPNetwork* const SelectedTOPNet = InPDGAssetLink->GetSelectedTOPNetwork(); if (IsValid(SelectedTOPNet)) { const int32 NumTOPNodes = SelectedTOPNet->AllTOPNodes.Num(); for (int32 Idx = 0; Idx < NumTOPNodes; Idx++) { const UTOPNode* const Node = SelectedTOPNet->AllTOPNodes[Idx]; if (!IsValid(Node) || Node->bHidden) continue; TOPNodesPtr.Add(MakeShareable(new FTextAndTooltip( Idx, FHoudiniEngineEditorUtils::GetNodeNamePaddedByPathDepth(Node->NodeName, Node->NodePath), Node->NodePath ))); } } FString NodeErrorText = FString(); FString NodeErrorTooltip = FString(); FLinearColor NodeErrorColor = FLinearColor::White; if (!IsValid(SelectedTOPNet) || SelectedTOPNet->AllTOPNodes.Num() <= 0) { NodeErrorText = TEXT("No valid TOP Node found!"); NodeErrorTooltip = TEXT("There is no valid TOP Node found in the selected TOP Network!"); NodeErrorColor = FLinearColor::Red; } else if(TOPNodesPtr.Num() <= 0) { NodeErrorText = TEXT("No visible TOP Node found!"); NodeErrorTooltip = TEXT("No visible TOP Node found, all nodes in this network are hidden. Please update your TOP Node Filter."); NodeErrorColor = FLinearColor::Yellow; } // Lambda for selecting a TOPNode auto OnTOPNodeChanged = [InPDGAssetLink](TSharedPtr<FTextAndTooltip> InNewChoice) { UTOPNetwork* const TOPNetwork = InPDGAssetLink->GetSelectedTOPNetwork(); if (!InNewChoice.IsValid() || !IsValid(TOPNetwork)) return; const int32 NewChoice = InNewChoice->Value; int32 NewSelectedIndex = INDEX_NONE; if (TOPNetwork->AllTOPNodes.IsValidIndex(NewChoice)) NewSelectedIndex = NewChoice; if (TOPNetwork->SelectedTOPIndex != NewSelectedIndex) { // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), TOPNetwork); TOPNetwork->Modify(); TOPNetwork->SelectedTOPIndex = NewSelectedIndex; FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UTOPNetwork, SelectedTOPIndex), TOPNetwork); } }; TSharedPtr<SHorizontalBox, ESPMode::NotThreadSafe> HorizontalBoxTOPNode; TSharedPtr<SComboBox<TSharedPtr<FTextAndTooltip>>> ComboBoxTOPNode; int32 SelectedIndex = 0; UTOPNetwork* const SelectedTOPNetwork = InPDGAssetLink->GetSelectedTOPNetwork(); if (IsValid(SelectedTOPNetwork) && SelectedTOPNetwork->SelectedTOPIndex >= 0) { //SelectedIndex = InPDGAssetLink->GetSelectedTOPNetwork()->SelectedTOPIndex; // We need to match the selection by the index in the AllTopNodes array // Because of the nodefilter, it is possible that the selected index does not match the index in TOPNodesPtr const int32 SelectedTOPNodeIndex = SelectedTOPNetwork->SelectedTOPIndex; // Find the matching UI index for (int32 UIIndex = 0; UIIndex < TOPNodesPtr.Num(); UIIndex++) { if (TOPNodesPtr[UIIndex] && TOPNodesPtr[UIIndex]->Value == SelectedTOPNodeIndex) { // We found the UI Index that matches the current TOP Node! SelectedIndex = UIIndex; break; } } } TSharedPtr<STextBlock> ErrorText; PDGTOPNodeRow.ValueWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .Padding(2, 2, 5, 2) .FillWidth(300.f) .MaxWidth(300.f) [ SAssignNew(ComboBoxTOPNode, SComboBox<TSharedPtr<FTextAndTooltip>>) .OptionsSource(&TOPNodesPtr) .InitiallySelectedItem(TOPNodesPtr[SelectedIndex]) .OnGenerateWidget_Lambda([](TSharedPtr<FTextAndTooltip> ChoiceEntry) { const FText ChoiceEntryText = FText::FromString(ChoiceEntry->Text); const FText ChoiceEntryToolTip = FText::FromString(ChoiceEntry->ToolTip); return SNew(STextBlock) .Text(ChoiceEntryText) .ToolTipText(ChoiceEntryToolTip) .Margin(2.0f) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))); }) .OnSelectionChanged_Lambda([OnTOPNodeChanged](TSharedPtr<FTextAndTooltip> NewChoice, ESelectInfo::Type SelectType) { return OnTOPNodeChanged(NewChoice); }) [ SNew(STextBlock) .Text_Lambda([InPDGAssetLink, ComboBoxTOPNode, Options = TOPNodesPtr]() { if (IsValidWeakPointer(InPDGAssetLink)) return FText::FromString(InPDGAssetLink->GetSelectedTOPNodeName()); else return FText(); }) .ToolTipText_Lambda([InPDGAssetLink]() { UTOPNode const * const TOPNode = InPDGAssetLink->GetSelectedTOPNode(); if (IsValid(TOPNode)) { if (!TOPNode->NodePath.IsEmpty()) return FText::FromString(TOPNode->NodePath); else return FText::FromString(TOPNode->NodeName); } else { return FText(); } }) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) ] ] + SHorizontalBox::Slot() .Padding(2, 2, 5, 2) .AutoWidth() [ SAssignNew(ErrorText, STextBlock) .Text(FText::FromString(NodeErrorText)) .ToolTipText(FText::FromString(NodeErrorText)) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) .ColorAndOpacity(FLinearColor::Red) //.ShadowColorAndOpacity(FLinearColor::Black) ]; // Update the error text if needed ErrorText->SetText(FText::FromString(NodeErrorText)); ErrorText->SetToolTipText(FText::FromString(NodeErrorTooltip)); ErrorText->SetColorAndOpacity(NodeErrorColor); // Hide the combobox if we have an error ComboBoxTOPNode->SetVisibility(NodeErrorText.IsEmpty() ? EVisibility::Visible : EVisibility::Hidden); } // TOP Node State { FDetailWidgetRow& PDGNodeStateResultRow = TOPNodesGrp.AddWidgetRow(); DisableIfPDGNotLinked(PDGNodeStateResultRow, InPDGAssetLink); PDGNodeStateResultRow.NameWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ SNew(STextBlock) .Text(FText::FromString(TEXT("TOP Node State"))) ]; PDGNodeStateResultRow.ValueWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ SNew(STextBlock) .Text_Lambda([InPDGAssetLink]() { FString TOPNodeStatus = FString(); FLinearColor TOPNodeStatusColor = FLinearColor::White; GetSelectedTOPNodeStatusAndColor(InPDGAssetLink, TOPNodeStatus, TOPNodeStatusColor); return FText::FromString(TOPNodeStatus); }) .ColorAndOpacity_Lambda([InPDGAssetLink]() { FString TOPNodeStatus = FString(); FLinearColor TOPNodeStatusColor = FLinearColor::White; GetSelectedTOPNodeStatusAndColor(InPDGAssetLink, TOPNodeStatus, TOPNodeStatusColor); return FSlateColor(TOPNodeStatusColor); }) ]; } // Checkbox: Load Work Item Output Files { auto ToolTipLambda = [InPDGAssetLink]() { bool bDisabled = false; if (IsValidWeakPointer(InPDGAssetLink) && InPDGAssetLink->GetSelectedTOPNode()) { bDisabled = InPDGAssetLink->GetSelectedTOPNode()->bHasChildNodes; } return bDisabled ? FText::FromString(TEXT("This node has child nodes, the auto-load setting must be set on the child nodes individually.")) : FText::FromString(TEXT("When enabled, Output files produced by this TOP Node's Work Items will automatically be loaded when cooked.")); }; FDetailWidgetRow& PDGNodeAutoLoadRow = TOPNodesGrp.AddWidgetRow(); DisableIfPDGNotLinked(PDGNodeAutoLoadRow, InPDGAssetLink); PDGNodeAutoLoadRow.IsEnabledAttr.Bind(TAttribute<bool>::FGetter::CreateLambda([InPDGAssetLink]() { if (!IsPDGLinked(InPDGAssetLink)) return false; UTOPNode* const Node = InPDGAssetLink->GetSelectedTOPNode(); if (IsValid(Node) && !Node->bHidden && !Node->bHasChildNodes) return true; return false; })); PDGNodeAutoLoadRow.NameWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ SNew(STextBlock) .Text(FText::FromString(TEXT("Auto-Load Work Item Output Files"))) .ToolTipText_Lambda(ToolTipLambda) ]; TSharedPtr<SCheckBox> AutoLoadCheckBox; PDGNodeAutoLoadRow.ValueWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ // Checkbox SAssignNew(AutoLoadCheckBox, SCheckBox) .IsChecked_Lambda([InPDGAssetLink]() { return InPDGAssetLink->GetSelectedTOPNode() ? (InPDGAssetLink->GetSelectedTOPNode()->bAutoLoad ? ECheckBoxState::Checked : ECheckBoxState::Unchecked) : ECheckBoxState::Unchecked; }) .OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState) { const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false; UTOPNode* TOPNode = InPDGAssetLink->GetSelectedTOPNode(); if (!IsValid(TOPNode) || TOPNode->bAutoLoad == bNewState) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), TOPNode); TOPNode->Modify(); TOPNode->bAutoLoad = bNewState; FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UTOPNode, bAutoLoad), TOPNode); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); }) .ToolTipText_Lambda(ToolTipLambda) ]; } // Checkbox: Work Item Output Files Visible { auto ToolTipLambda = [InPDGAssetLink]() { bool bDisabled = false; if (IsValidWeakPointer(InPDGAssetLink) && InPDGAssetLink->GetSelectedTOPNode()) { bDisabled = InPDGAssetLink->GetSelectedTOPNode()->bHasChildNodes; } return bDisabled ? FText::FromString(TEXT("This node has child nodes, visibility of work item outputs must be set on the child nodes individually.")) : FText::FromString(TEXT("Toggles the visibility of the actors created from this TOP Node's Work Item File Outputs.")); }; FDetailWidgetRow& PDGNodeShowResultRow = TOPNodesGrp.AddWidgetRow(); // DisableIfPDGNotLinked(PDGNodeShowResultRow, InPDGAssetLink); PDGNodeShowResultRow.IsEnabledAttr.Bind(TAttribute<bool>::FGetter::CreateLambda([InPDGAssetLink]() { if (!IsValidWeakPointer(InPDGAssetLink)) return false; UTOPNode* const Node = InPDGAssetLink->GetSelectedTOPNode(); if (IsValid(Node) && !Node->bHidden && !Node->bHasChildNodes) return true; return false; })); PDGNodeShowResultRow.NameWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ SNew(STextBlock) .Text(FText::FromString(TEXT("Work Item Output Files Visible"))) .ToolTipText_Lambda(ToolTipLambda) ]; TSharedPtr<SCheckBox> ShowResCheckBox; PDGNodeShowResultRow.ValueWidget.Widget = SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f) [ // Checkbox SAssignNew(ShowResCheckBox, SCheckBox) .IsChecked_Lambda([InPDGAssetLink]() { return InPDGAssetLink->GetSelectedTOPNode() ? (InPDGAssetLink->GetSelectedTOPNode()->IsVisibleInLevel() ? ECheckBoxState::Checked : ECheckBoxState::Unchecked) : ECheckBoxState::Unchecked; }) .OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState) { const bool bNewState = (NewState == ECheckBoxState::Checked) ? true : false; UTOPNode* const TOPNode = InPDGAssetLink->GetSelectedTOPNode(); if (!IsValid(TOPNode) || TOPNode->IsVisibleInLevel() == bNewState) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), TOPNode); TOPNode->Modify(); TOPNode->SetVisibleInLevel(bNewState); FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty(TEXT("bShow"), TOPNode); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); }) .ToolTipText_Lambda(ToolTipLambda) ]; } // Buttons: DIRTY NODE / COOK NODE { TSharedRef<SHorizontalBox> DirtyHBox = SNew(SHorizontalBox); TSharedPtr<SHorizontalBox> CookHBox = SNew(SHorizontalBox); TSharedPtr<SButton> DirtyButton; TSharedPtr<SButton> CookButton; FDetailWidgetRow& PDGDirtyCookRow = TOPNodesGrp.AddWidgetRow() .WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink) || (IsValidWeakPointer(InPDGAssetLink) && IsValid(InPDGAssetLink->GetSelectedTOPNode())); }) .WidthOverride(200.0f) [ SAssignNew(DirtyButton, SButton) //.Text(LOCTEXT("DirtyNode", "Dirty Node")) .ToolTipText(LOCTEXT("DirtyNodeTooltip", "Dirties the selected TOP node and clears its work item results.")) .ContentPadding(FMargin(5.0f, 2.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink) || (IsValidWeakPointer(InPDGAssetLink) && IsValid(InPDGAssetLink->GetSelectedTOPNode())); }) .OnClicked_Lambda([InPDGAssetLink]() { if (IsValidWeakPointer(InPDGAssetLink)) { UTOPNode* const TOPNode = InPDGAssetLink->GetSelectedTOPNode(); if (IsValid(TOPNode)) { if (IsPDGLinked(InPDGAssetLink)) { FHoudiniPDGManager::DirtyTOPNode(TOPNode); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); } else { UHoudiniPDGAssetLink::ClearTOPNodeWorkItemResults(TOPNode); } } } return FReply::Handled(); }) .IsEnabled_Lambda([InPDGAssetLink]() { if (IsValid(InPDGAssetLink->GetSelectedTOPNode()) && !InPDGAssetLink->GetSelectedTOPNode()->bHidden) return true; return false; }) .Content() [ SAssignNew(DirtyHBox, SHorizontalBox) ] ] ] // + SHorizontalBox::Slot() // .AutoWidth() // [ // SNew(SBox) // .WidthOverride(200.0f) // [ // SAssignNew(DirtyButton, SButton) // .Text(LOCTEXT("DirtyAllTasks", "Dirty All Tasks")) // .ToolTipText(LOCTEXT("DirtyAllTasksTooltip", "Dirties all tasks/work items on the selected TOP node.")) // .ContentPadding(FMargin(5.0f, 2.0f)) // .VAlign(VAlign_Center) // .HAlign(HAlign_Center) // .OnClicked_Lambda([InPDGAssetLink]() // { // if(InPDGAssetLink->GetSelectedTOPNode()) // { // FHoudiniPDGManager::DirtyAllTasksOfTOPNode(*(InPDGAssetLink->GetSelectedTOPNode())); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); // } // // return FReply::Handled(); // }) // ] // ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .WidthOverride(200.0f) [ SAssignNew(CookButton, SButton) //.Text(LOCTEXT("CookNode", "Cook Node")) .ToolTipText(LOCTEXT("CookNodeTooltip", "Cooks the selected TOP Node.")) .ContentPadding(FMargin(5.0f, 2.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { if (!IsPDGLinked(InPDGAssetLink)) return false; UTOPNode* const SelectedNode = InPDGAssetLink->GetSelectedTOPNode(); if (!IsValid(SelectedNode)) return false; // Disable Cook Node button if the node is already cooking return !SelectedNode->bHidden && SelectedNode->NodeState != EPDGNodeState::Cooking && !SelectedNode->AnyWorkItemsPending(); }) .OnClicked_Lambda([InPDGAssetLink]() { UTOPNode* const Node = InPDGAssetLink->GetSelectedTOPNode(); if (IsValid(Node)) { FHoudiniPDGManager::CookTOPNode(Node); // FHoudiniPDGDetails::RefreshUI(InPDGAssetLink); } return FReply::Handled(); }) .Content() [ SAssignNew(CookHBox, SHorizontalBox) ] ] ] ]; TSharedPtr<FSlateDynamicImageBrush> DirtyIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIPDGDirtyNodeIconBrush(); if (DirtyIconBrush.IsValid()) { TSharedPtr<SImage> DirtyImage; DirtyHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(DirtyImage, SImage) ] ]; DirtyImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([DirtyIconBrush]() { return DirtyIconBrush.Get(); }))); } DirtyHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(LOCTEXT("DirtyNode", "Dirty Node")) ]; TSharedPtr<FSlateDynamicImageBrush> CookIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIRecookIconBrush(); if (CookIconBrush.IsValid()) { TSharedPtr<SImage> CookImage; CookHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(CookImage, SImage) ] ]; CookImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([CookIconBrush]() { return CookIconBrush.Get(); }))); } CookHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(LOCTEXT("CookNode", "Cook Node")) ]; DisableIfPDGNotLinked(PDGDirtyCookRow, InPDGAssetLink); } // Buttons: Load Work Item Objects / Unload Work Item Objects { TSharedPtr<SButton> UnloadWorkItemsButton; TSharedPtr<SButton> LoadWorkItemsButton; FDetailWidgetRow& PDGUnloadLoadWorkItemsRow = TOPNodesGrp.AddWidgetRow() .WholeRowContent() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsValidWeakPointer(InPDGAssetLink) && IsValid(InPDGAssetLink->GetSelectedTOPNode()); }) .WidthOverride(200.0f) [ SAssignNew(UnloadWorkItemsButton, SButton) .Text(LOCTEXT("UnloadWorkItemsForNode", "Unload Work Item Objects")) .ToolTipText(LOCTEXT("UnloadWorkItemsForNodeTooltip", "Unloads / removes loaded work item results from level. Not undoable: use the \"Load Work Item Objects\" button to reload the results.")) .ContentPadding(FMargin(5.0f, 2.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { if (!IsValidWeakPointer(InPDGAssetLink)) return false; UTOPNode* const SelectedNode = InPDGAssetLink->GetSelectedTOPNode(); if (!IsValid(SelectedNode) || SelectedNode->bHidden || !SelectedNode->bCachedHaveLoadedWorkResults) return false; return true; }) .OnClicked_Lambda([InPDGAssetLink]() { if (IsValidWeakPointer(InPDGAssetLink)) { UTOPNode* const TOPNode = InPDGAssetLink->GetSelectedTOPNode(); if (IsValid(TOPNode)) { if (IsPDGLinked(InPDGAssetLink)) { // Set the state to ToDelete, PDGManager will delete it when processing work items TOPNode->SetLoadedWorkResultsToDelete(); } else { // Delete and unload the result objects and actors now TOPNode->DeleteAllWorkResultObjectOutputs(); } } } return FReply::Handled(); }) ] ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .WidthOverride(200.0f) [ SAssignNew(LoadWorkItemsButton, SButton) .Text(LOCTEXT("LoadWorkItems", "Load Work Item Objects")) .ToolTipText(LOCTEXT("LoadWorkItemsForNodeTooltip", "Loads any available but not loaded work items objects (this could include items from a previous cook). Creates output actors. Not undoable: use the \"Unload Work Item Objects\" button to unload/remove loaded work item results.")) .ContentPadding(FMargin(5.0f, 2.0f)) .VAlign(VAlign_Center) .HAlign(HAlign_Center) .IsEnabled_Lambda([InPDGAssetLink]() { if (!IsValidWeakPointer(InPDGAssetLink)) return false; UTOPNode* const SelectedNode = InPDGAssetLink->GetSelectedTOPNode(); if (!IsValid(SelectedNode) || SelectedNode->bHidden || !SelectedNode->bCachedHaveNotLoadedWorkResults) return false; return true; }) .OnClicked_Lambda([InPDGAssetLink]() { if (IsValidWeakPointer(InPDGAssetLink)) { UTOPNode* const SelectedNode = InPDGAssetLink->GetSelectedTOPNode(); if (IsValid(SelectedNode)) { SelectedNode->SetNotLoadedWorkResultsToLoad(true); } } return FReply::Handled(); }) ] ] ]; } // TOP Node WorkItem Status { if (InPDGAssetLink->GetSelectedTOPNode()) { FDetailWidgetRow& PDGNodeWorkItemStatsRow = TOPNodesGrp.AddWidgetRow(); DisableIfPDGNotLinked(PDGNodeWorkItemStatsRow, InPDGAssetLink); FHoudiniPDGDetails::AddWorkItemStatusWidget( PDGNodeWorkItemStatsRow, TEXT("TOP Node Work Item Status"), InPDGAssetLink, true); } } } void FHoudiniPDGDetails::RefreshPDGAssetLink(const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink) { // Repopulate the network and nodes for the assetlink if (!IsValidWeakPointer(InPDGAssetLink) || !FHoudiniPDGManager::UpdatePDGAssetLink(InPDGAssetLink.Get())) return; FHoudiniPDGDetails::RefreshUI(InPDGAssetLink, true); } void FHoudiniPDGDetails::RefreshUI(const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink, const bool& InFullUpdate) { if (!IsValidWeakPointer(InPDGAssetLink)) return; // Update the workitem stats InPDGAssetLink->UpdateWorkItemTally(); // Update the editor properties FHoudiniEngineUtils::UpdateEditorProperties(InPDGAssetLink.Get(), InFullUpdate); } void FHoudiniPDGDetails::CreatePDGBakeWidgets(IDetailCategoryBuilder& InPDGCategory, const TWeakObjectPtr<UHoudiniPDGAssetLink>& InPDGAssetLink) { if (!IsValidWeakPointer(InPDGAssetLink)) return; FHoudiniEngineDetails::AddHeaderRowForHoudiniPDGAssetLink(InPDGCategory, InPDGAssetLink, HOUDINI_ENGINE_UI_SECTION_PDG_BAKE); if (!InPDGAssetLink->bBakeMenuExpanded) return; auto OnBakeButtonClickedLambda = [InPDGAssetLink]() { switch (InPDGAssetLink->HoudiniEngineBakeOption) { case EHoudiniEngineBakeOption::ToActor: { // if (InPDGAssetLink->bIsReplace) // FHoudiniEngineBakeUtils::ReplaceHoudiniActorWithActors(InPDGAssetLink); // else FHoudiniEngineBakeUtils::BakePDGAssetLinkOutputsKeepActors(InPDGAssetLink.Get(), InPDGAssetLink->PDGBakeSelectionOption, InPDGAssetLink->PDGBakePackageReplaceMode, InPDGAssetLink->bRecenterBakedActors); } break; case EHoudiniEngineBakeOption::ToBlueprint: { // if (InPDGAssetLink->bIsReplace) // FHoudiniEngineBakeUtils::ReplaceWithBlueprint(InPDGAssetLink); // else FHoudiniEngineBakeUtils::BakePDGAssetLinkBlueprints(InPDGAssetLink.Get(), InPDGAssetLink->PDGBakeSelectionOption, InPDGAssetLink->PDGBakePackageReplaceMode, InPDGAssetLink->bRecenterBakedActors); } break; // // case EHoudiniEngineBakeOption::ToFoliage: // { // if (InPDGAssetLink->bIsReplace) // FHoudiniEngineBakeUtils::ReplaceHoudiniActorWithFoliage(InPDGAssetLink); // else // FHoudiniEngineBakeUtils::BakeHoudiniActorToFoliage(InPDGAssetLink); // } // break; // // case EHoudiniEngineBakeOption::ToWorldOutliner: // { // if (InPDGAssetLink->bIsReplace) // { // // Todo // } // else // { // //Todo // } // } // break; } return FReply::Handled(); }; auto OnBakeFolderTextCommittedLambda = [InPDGAssetLink](const FText& Val, ETextCommit::Type TextCommitType) { if (!IsValidWeakPointer(InPDGAssetLink)) return; FString NewPathStr = Val.ToString(); if (NewPathStr.IsEmpty()) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); //Todo? Check if the new Bake folder path is valid InPDGAssetLink->Modify(); InPDGAssetLink->BakeFolder.Path = NewPathStr; FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, BakeFolder), InPDGAssetLink.Get()); }; // Button Row FDetailWidgetRow & ButtonRow = InPDGCategory.AddCustomRow(FText::GetEmpty()); DisableIfPDGNotLinked(ButtonRow, InPDGAssetLink); TSharedRef<SHorizontalBox> ButtonRowHorizontalBox = SNew(SHorizontalBox); // Bake Button TSharedRef<SHorizontalBox> BakeHBox = SNew(SHorizontalBox); TSharedPtr<SButton> BakeButton; ButtonRowHorizontalBox->AddSlot() /*.AutoWidth()*/ .Padding(15.f, 0.0f, 0.0f, 0.0f) .MaxWidth(75.0f) [ SNew(SBox) .WidthOverride(75.0f) [ SAssignNew(BakeButton, SButton) //.Text(FText::FromString("Bake")) .VAlign(VAlign_Center) .HAlign(HAlign_Center) //.ToolTipText(LOCTEXT("HoudiniPDGDetailsBakeButton", "Bake the Houdini PDG TOP Node(s)")) .ToolTipText_Lambda([InPDGAssetLink]() { switch (InPDGAssetLink->HoudiniEngineBakeOption) { case EHoudiniEngineBakeOption::ToActor: { return LOCTEXT( "HoudiniEnginePDGBakeButtonBakeToActorToolTip", "Bake this Houdini PDG Asset's output assets and seperate the output actors from the PDG asset link."); } break; case EHoudiniEngineBakeOption::ToBlueprint: { return LOCTEXT( "HoudiniEnginePDGBakeButtonBakeToBlueprintToolTip", "Bake this Houdini PDG Asset's output assets to blueprints and remove temporary output actors that no " "longer has output components from the PDG asset link."); } break; default: { return FText(); } } }) .Visibility(EVisibility::Visible) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .OnClicked_Lambda(OnBakeButtonClickedLambda) .Content() [ SAssignNew(BakeHBox, SHorizontalBox) ] ] ]; TSharedPtr<FSlateDynamicImageBrush> BakeIconBrush = FHoudiniEngineEditor::Get().GetHoudiniEngineUIBakeIconBrush(); if (BakeIconBrush.IsValid()) { TSharedPtr<SImage> BakeImage; BakeHBox->AddSlot() .MaxWidth(16.0f) [ SNew(SBox) .WidthOverride(16.0f) .HeightOverride(16.0f) [ SAssignNew(BakeImage, SImage) ] ]; BakeImage->SetImage( TAttribute<const FSlateBrush*>::Create( TAttribute<const FSlateBrush*>::FGetter::CreateLambda([BakeIconBrush]() { return BakeIconBrush.Get(); }))); } BakeHBox->AddSlot() .Padding(5.0, 0.0, 0.0, 0.0) .VAlign(VAlign_Center) .AutoWidth() [ SNew(STextBlock) .Text(FText::FromString("Bake")) ]; // bake Type ComboBox TSharedPtr<SComboBox<TSharedPtr<FString>>> TypeComboBox; TArray<TSharedPtr<FString>>* OptionSource = FHoudiniEngineEditor::Get().GetHoudiniEnginePDGBakeTypeOptionsLabels(); TSharedPtr<FString> IntialSelec; if (OptionSource) { // IntialSelec = (*OptionSource)[(int)InPDGAssetLink->HoudiniEngineBakeOption]; const FString DefaultStr = FHoudiniEngineEditor::Get().GetStringFromHoudiniEngineBakeOption(InPDGAssetLink->HoudiniEngineBakeOption); const TSharedPtr<FString>* DefaultOption = OptionSource->FindByPredicate( [DefaultStr](TSharedPtr<FString> InStringPtr) { return InStringPtr.IsValid() && *InStringPtr == DefaultStr; } ); if (DefaultOption) IntialSelec = *DefaultOption; } ButtonRowHorizontalBox->AddSlot() /*.AutoWidth()*/ .Padding(3.0, 0.0, 4.0f, 0.0f) .MaxWidth(93.f) [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .WidthOverride(93.f) [ SAssignNew(TypeComboBox, SComboBox<TSharedPtr<FString>>) .OptionsSource(OptionSource) .InitiallySelectedItem(IntialSelec) .OnGenerateWidget_Lambda( [](TSharedPtr< FString > InItem) { FText ChoiceEntryText = FText::FromString(*InItem); return SNew(STextBlock) .Text(ChoiceEntryText) .ToolTipText(ChoiceEntryText) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))); }) .OnSelectionChanged_Lambda( [InPDGAssetLink](TSharedPtr< FString > NewChoice, ESelectInfo::Type SelectType) { if (IsValidWeakPointer(InPDGAssetLink)) return; if (!NewChoice.IsValid() || SelectType == ESelectInfo::Type::Direct) return; const EHoudiniEngineBakeOption NewOption = FHoudiniEngineEditor::Get().StringToHoudiniEngineBakeOption(*NewChoice.Get()); if (NewOption != InPDGAssetLink->HoudiniEngineBakeOption) { // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->HoudiniEngineBakeOption = NewOption; FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, HoudiniEngineBakeOption), InPDGAssetLink.Get()); } }) [ SNew(STextBlock) .Text_Lambda([InPDGAssetLink, TypeComboBox, OptionSource]() { return FText::FromString(FHoudiniEngineEditor::Get().GetStringFromHoudiniEngineBakeOption(InPDGAssetLink->HoudiniEngineBakeOption)); }) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) ] ] ]; // bake selection ComboBox TSharedPtr<SComboBox<TSharedPtr<FString>>> BakeSelectionComboBox; TArray<TSharedPtr<FString>>* PDGBakeSelectionOptionSource = FHoudiniEngineEditor::Get().GetHoudiniEnginePDGBakeSelectionOptionsLabels(); TSharedPtr<FString> PDGBakeSelectionIntialSelec; if (PDGBakeSelectionOptionSource) { PDGBakeSelectionIntialSelec = (*PDGBakeSelectionOptionSource)[(int)InPDGAssetLink->PDGBakeSelectionOption]; } ButtonRowHorizontalBox->AddSlot() /*.AutoWidth()*/ .Padding(3.0, 0.0, 4.0f, 0.0f) .MaxWidth(163.f) [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .WidthOverride(163.f) [ SAssignNew(TypeComboBox, SComboBox<TSharedPtr<FString>>) .OptionsSource(PDGBakeSelectionOptionSource) .InitiallySelectedItem(PDGBakeSelectionIntialSelec) .OnGenerateWidget_Lambda( [](TSharedPtr< FString > InItem) { FText ChoiceEntryText = FText::FromString(*InItem); return SNew(STextBlock) .Text(ChoiceEntryText) .ToolTipText(ChoiceEntryText) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))); }) .OnSelectionChanged_Lambda( [InPDGAssetLink](TSharedPtr< FString > NewChoice, ESelectInfo::Type SelectType) { if (!IsValidWeakPointer(InPDGAssetLink) || !NewChoice.IsValid()) return; const EPDGBakeSelectionOption NewOption = FHoudiniEngineEditor::Get().StringToPDGBakeSelectionOption(*NewChoice.Get()); if (NewOption != InPDGAssetLink->PDGBakeSelectionOption) { // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->PDGBakeSelectionOption = NewOption; FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, PDGBakeSelectionOption), InPDGAssetLink.Get()); } }) [ SNew(STextBlock) .Text_Lambda([InPDGAssetLink]() { return FText::FromString( FHoudiniEngineEditor::Get().GetStringFromPDGBakeTargetOption(InPDGAssetLink->PDGBakeSelectionOption)); }) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) ] ] ]; ButtonRow.WholeRowWidget.Widget = ButtonRowHorizontalBox; // Bake package replacement mode row FDetailWidgetRow & BakePackageReplaceRow = InPDGCategory.AddCustomRow(FText::GetEmpty()); DisableIfPDGNotLinked(BakePackageReplaceRow, InPDGAssetLink); TSharedRef<SHorizontalBox> BakePackageReplaceRowHorizontalBox = SNew(SHorizontalBox); BakePackageReplaceRowHorizontalBox->AddSlot() /*.AutoWidth()*/ .Padding(30.0f, 0.0f, 6.0f, 0.0f) .MaxWidth(155.0f) [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .WidthOverride(155.0f) [ SNew(STextBlock) .Text(LOCTEXT("HoudiniEnginePDGBakePackageReplacementModeLabel", "Replace Mode")) .ToolTipText( LOCTEXT("HoudiniEnginePDGBakePackageReplacementModeTooltip", "Replacement mode " "during baking. Create new assets, using numerical suffixes in package names when necessary, or " "replace existing assets with matching names. Also replaces the previous bake's output actors in " "replacement mode vs creating incremental ones.")) ] ]; // bake package replace mode ComboBox TSharedPtr<SComboBox<TSharedPtr<FString>>> BakePackageReplaceModeComboBox; TArray<TSharedPtr<FString>>* PDGBakePackageReplaceModeOptionSource = FHoudiniEngineEditor::Get().GetHoudiniEnginePDGBakePackageReplaceModeOptionsLabels(); TSharedPtr<FString> PDGBakePackageReplaceModeInitialSelec; if (PDGBakePackageReplaceModeOptionSource) { const FString DefaultStr = FHoudiniEngineEditor::Get().GetStringFromPDGBakePackageReplaceModeOption(InPDGAssetLink->PDGBakePackageReplaceMode); const TSharedPtr<FString>* DefaultOption = PDGBakePackageReplaceModeOptionSource->FindByPredicate( [DefaultStr](TSharedPtr<FString> InStringPtr) { return InStringPtr.IsValid() && *InStringPtr == DefaultStr; } ); if (DefaultOption) PDGBakePackageReplaceModeInitialSelec = *DefaultOption; } BakePackageReplaceRowHorizontalBox->AddSlot() /*.AutoWidth()*/ .Padding(3.0, 0.0, 4.0f, 0.0f) .MaxWidth(163.f) [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .WidthOverride(163.f) [ SAssignNew(TypeComboBox, SComboBox<TSharedPtr<FString>>) .OptionsSource(PDGBakePackageReplaceModeOptionSource) .InitiallySelectedItem(PDGBakePackageReplaceModeInitialSelec) .OnGenerateWidget_Lambda( [](TSharedPtr< FString > InItem) { const FText ChoiceEntryText = FText::FromString(*InItem); return SNew(STextBlock) .Text(ChoiceEntryText) .ToolTipText(ChoiceEntryText) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))); }) .OnSelectionChanged_Lambda( [InPDGAssetLink](TSharedPtr< FString > NewChoice, ESelectInfo::Type SelectType) { if (!IsValidWeakPointer(InPDGAssetLink) || !NewChoice.IsValid()) return; const EPDGBakePackageReplaceModeOption NewOption = FHoudiniEngineEditor::Get().StringToPDGBakePackageReplaceModeOption(*NewChoice.Get()); if (NewOption != InPDGAssetLink->PDGBakePackageReplaceMode) { // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->PDGBakePackageReplaceMode = NewOption; FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, PDGBakePackageReplaceMode), InPDGAssetLink.Get()); } }) [ SNew(STextBlock) .Text_Lambda([InPDGAssetLink]() { return FText::FromString( FHoudiniEngineEditor::Get().GetStringFromPDGBakePackageReplaceModeOption(InPDGAssetLink->PDGBakePackageReplaceMode)); }) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) ] ] ]; BakePackageReplaceRow.WholeRowWidget.Widget = BakePackageReplaceRowHorizontalBox; // Bake Folder Row FDetailWidgetRow & BakeFolderRow = InPDGCategory.AddCustomRow(FText::GetEmpty()); DisableIfPDGNotLinked(BakeFolderRow, InPDGAssetLink); TSharedRef<SHorizontalBox> BakeFolderRowHorizontalBox = SNew(SHorizontalBox); BakeFolderRowHorizontalBox->AddSlot() /*.AutoWidth()*/ .Padding(30.0f, 0.0f, 6.0f, 0.0f) .MaxWidth(155.0f) [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .WidthOverride(155.0f) [ SNew(STextBlock) .Text(LOCTEXT("HoudiniEngineBakeFolderLabel", "Bake Folder")) .ToolTipText(LOCTEXT( "HoudiniEnginePDGBakeFolderTooltip", "The folder used to store the objects that are generated by this Houdini PDG Asset when baking, if the " "unreal_bake_folder attribute is not set on the geometry. If this value is blank, the default from the " "plugin settings is used.")) ] ]; BakeFolderRowHorizontalBox->AddSlot() /*.AutoWidth()*/ .MaxWidth(235.0) [ SNew(SBox) .IsEnabled_Lambda([InPDGAssetLink]() { return IsPDGLinked(InPDGAssetLink); }) .WidthOverride(235.0f) [ SNew(SEditableTextBox) .MinDesiredWidth(HAPI_UNREAL_DESIRED_ROW_VALUE_WIDGET_WIDTH) .ToolTipText(LOCTEXT( "HoudiniEnginePDGBakeFolderTooltip", "The folder used to store the objects that are generated by this Houdini PDG Asset when baking, if the " "unreal_bake_folder attribute is not set on the geometry. If this value is blank, the default from the " "plugin settings is used.")) .HintText(LOCTEXT("HoudiniEngineBakeFolderHintText", "Input to set bake folder")) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) .Text_Lambda([InPDGAssetLink](){ return FText::FromString(InPDGAssetLink->BakeFolder.Path); }) .OnTextCommitted_Lambda(OnBakeFolderTextCommittedLambda) ] ]; BakeFolderRow.WholeRowWidget.Widget = BakeFolderRowHorizontalBox; // Add additional bake options FDetailWidgetRow & AdditionalBakeSettingsRow = InPDGCategory.AddCustomRow(FText::GetEmpty()); TSharedRef<SHorizontalBox> AdditionalBakeSettingsRowHorizontalBox = SNew(SHorizontalBox); TSharedPtr<SCheckBox> CheckBoxAutoBake; TSharedPtr<SCheckBox> CheckBoxRecenterBakedActors; TSharedPtr<SVerticalBox> LeftColumnVerticalBox; TSharedPtr<SVerticalBox> RightColumnVerticalBox; AdditionalBakeSettingsRowHorizontalBox->AddSlot() .Padding(30.0f, 5.0f, 0.0f, 0.0f) .MaxWidth(200.f) [ SNew(SBox) .WidthOverride(200.f) [ SAssignNew(LeftColumnVerticalBox, SVerticalBox) ] ]; AdditionalBakeSettingsRowHorizontalBox->AddSlot() .Padding(20.0f, 5.0f, 0.0f, 0.0f) .MaxWidth(200.f) [ SNew(SBox) [ SAssignNew(RightColumnVerticalBox, SVerticalBox) ] ]; LeftColumnVerticalBox->AddSlot() .AutoHeight() .Padding(0.0f, 0.0f, 0.0f, 3.5f) [ SNew(SBox) .WidthOverride(160.f) [ SAssignNew(CheckBoxRecenterBakedActors, SCheckBox) .Content() [ SNew(STextBlock).Text(LOCTEXT("HoudiniEngineUIRecenterBakedActorsCheckBox", "Recenter Baked Actors")) .ToolTipText(LOCTEXT("HoudiniEngineUIRecenterBakedActorsCheckBoxToolTip", "After baking recenter the baked actors to their bounding box center.")) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) ] .IsChecked_Lambda([InPDGAssetLink]() { return InPDGAssetLink->bRecenterBakedActors ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }) .OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState) { if (!IsValidWeakPointer(InPDGAssetLink)) return; const bool bNewState = (NewState == ECheckBoxState::Checked); // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->bRecenterBakedActors = bNewState; // Notify that we have changed the property FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bRecenterBakedActors), InPDGAssetLink.Get()); }) ] ]; RightColumnVerticalBox->AddSlot() .AutoHeight() .Padding(0.0f, 0.0f, 0.0f, 3.5f) [ SNew(SBox) .WidthOverride(160.f) [ SAssignNew(CheckBoxAutoBake, SCheckBox) .Content() [ SNew(STextBlock).Text(LOCTEXT("HoudiniEngineUIAutoBakeCheckBox", "Auto Bake")) .ToolTipText(LOCTEXT("HoudiniEngineUIAutoBakeCheckBoxToolTip", "Automatically bake work result object as they are loaded.")) .Font(FEditorStyle::GetFontStyle(TEXT("PropertyWindow.NormalFont"))) ] .IsChecked_Lambda([InPDGAssetLink]() { return InPDGAssetLink->bBakeAfterAllWorkResultObjectsLoaded ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; }) .OnCheckStateChanged_Lambda([InPDGAssetLink](ECheckBoxState NewState) { const bool bNewState = (NewState == ECheckBoxState::Checked); if (!IsValidWeakPointer(InPDGAssetLink)) return; // Record a transaction for undo/redo FScopedTransaction Transaction( TEXT(HOUDINI_MODULE_RUNTIME), LOCTEXT("HoudiniPDGAssetLinkParameterChange", "Houdini PDG Asset Link Parameter: Changing a value"), InPDGAssetLink.Get()); InPDGAssetLink->Modify(); InPDGAssetLink->bBakeAfterAllWorkResultObjectsLoaded = bNewState; // Notify that we have changed the property FHoudiniEngineEditorUtils::NotifyPostEditChangeProperty( GET_MEMBER_NAME_STRING_CHECKED(UHoudiniPDGAssetLink, bBakeAfterAllWorkResultObjectsLoaded), InPDGAssetLink.Get()); }) ] ]; AdditionalBakeSettingsRow.WholeRowWidget.Widget = AdditionalBakeSettingsRowHorizontalBox; } FTextAndTooltip::FTextAndTooltip(int32 InValue, const FString& InText) : Text(InText) , Value(InValue) { } FTextAndTooltip::FTextAndTooltip(int32 InValue, const FString& InText, const FString &InToolTip) : Text(InText) , ToolTip(InToolTip) , Value(InValue) { } FTextAndTooltip::FTextAndTooltip(int32 InValue, FString&& InText) : Text(InText) , Value(InValue) { } FTextAndTooltip::FTextAndTooltip(int32 InValue, FString&& InText, FString&& InToolTip) : Text(InText) , ToolTip(InToolTip) , Value(InValue) { } #undef LOCTEXT_NAMESPACE
32.305078
287
0.699583
Filoppi
61592f14d6ce7b37e4c8b06047e5b04e53b5d1d0
1,362
cpp
C++
0 - 1 Knapsack Problem - GFG/0-1-knapsack-problem.cpp
champmaniac/LeetCode
65810e0123e0ceaefb76d0a223436d1525dac0d4
[ "MIT" ]
1
2022-02-27T09:01:07.000Z
2022-02-27T09:01:07.000Z
0 - 1 Knapsack Problem - GFG/0-1-knapsack-problem.cpp
champmaniac/LeetCode
65810e0123e0ceaefb76d0a223436d1525dac0d4
[ "MIT" ]
null
null
null
0 - 1 Knapsack Problem - GFG/0-1-knapsack-problem.cpp
champmaniac/LeetCode
65810e0123e0ceaefb76d0a223436d1525dac0d4
[ "MIT" ]
null
null
null
// { Driver Code Starts #include<bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution { public: //Function to return max value that can be put in knapsack of capacity W. int knapSack(int W, int wt[], int val[], int n) { // Your code here int dp[n+1][W+1]; for(int i=0;i<n+1;i++){ for(int j=0;j<W+1;j++){ if(i==0 || j==0) dp[i][j]=0; } } for(int i=1;i<n+1;i++){ for(int j=1;j<W+1;j++){ if(wt[i-1]<=j){ dp[i][j]= max(val[i-1]+dp[i-1][j-wt[i-1]],dp[i-1][j]); } else{ dp[i][j]=dp[i-1][j]; } } } return dp[n][W]; } }; // { Driver Code Starts. int main() { //taking total testcases int t; cin>>t; while(t--) { //reading number of elements and weight int n, w; cin>>n>>w; int val[n]; int wt[n]; //inserting the values for(int i=0;i<n;i++) cin>>val[i]; //inserting the weights for(int i=0;i<n;i++) cin>>wt[i]; Solution ob; //calling method knapSack() cout<<ob.knapSack(w, wt, val, n)<<endl; } return 0; } // } Driver Code Ends
21.28125
77
0.415565
champmaniac
6159356959861c5fa854bed62fa552d3ec5cdd5e
408
cpp
C++
problem_009.cpp
wurfkeks/project-euler
782c459546ae0d98ce20ce0bbcde3fed3adaab06
[ "Unlicense" ]
null
null
null
problem_009.cpp
wurfkeks/project-euler
782c459546ae0d98ce20ce0bbcde3fed3adaab06
[ "Unlicense" ]
null
null
null
problem_009.cpp
wurfkeks/project-euler
782c459546ae0d98ce20ce0bbcde3fed3adaab06
[ "Unlicense" ]
null
null
null
// Problem 9: Special Pythagorean triplet #include <iostream> int main(void) { int x = 0; for (int a=1; a<500; ++a) { for (int b=a; b < 1000; ++b) { int c = 1000 - a - b; if (c*c == a*a + b*b) { std::cout << (a*b*c) << std::endl; return 0; } } } std::cout << "no solution" << std::endl; return 0; }
18.545455
50
0.401961
wurfkeks
61593bfa80863d76b84412f5e468234da2e3ed87
4,879
cc
C++
CalibTracker/SiStripESProducers/plugins/fake/SiStripApvGainBuilderFromTag.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
CalibTracker/SiStripESProducers/plugins/fake/SiStripApvGainBuilderFromTag.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
CalibTracker/SiStripESProducers/plugins/fake/SiStripApvGainBuilderFromTag.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "CalibTracker/SiStripESProducers/plugins/fake/SiStripApvGainBuilderFromTag.h" #include "CalibTracker/SiStripCommon/interface/SiStripDetInfoFileReader.h" #include "CondFormats/DataRecord/interface/SiStripCondDataRecords.h" #include "DataFormats/TrackerCommon/interface/TrackerTopology.h" #include "Geometry/Records/interface/IdealGeometryRecord.h" #include "FWCore/Framework/interface/EventSetup.h" #include <iostream> #include <fstream> #include <vector> #include <algorithm> #include "SiStripFakeAPVParameters.h" SiStripApvGainBuilderFromTag::SiStripApvGainBuilderFromTag( const edm::ParameterSet& iConfig ): printdebug_(iConfig.getUntrackedParameter<uint32_t>("printDebug",1)), pset_(iConfig) {} void SiStripApvGainBuilderFromTag::analyze(const edm::Event& evt, const edm::EventSetup& iSetup) { //Retrieve tracker topology from geometry edm::ESHandle<TrackerTopology> tTopoHandle; iSetup.get<IdealGeometryRecord>().get(tTopoHandle); const TrackerTopology* const tTopo = tTopoHandle.product(); // unsigned int run=evt.id().run(); std::string genMode = pset_.getParameter<std::string>("genMode"); bool applyTuning = pset_.getParameter<bool>("applyTuning"); double meanGain_=pset_.getParameter<double>("MeanGain"); double sigmaGain_=pset_.getParameter<double>("SigmaGain"); double minimumPosValue_=pset_.getParameter<double>("MinPositiveGain"); uint32_t printdebug_ = pset_.getUntrackedParameter<uint32_t>("printDebug", 5); //parameters for layer/disk level correction; not used if applyTuning=false SiStripFakeAPVParameters correct{pset_, "correct"}; // Read the gain from the given tag edm::ESHandle<SiStripApvGain> inputApvGain; iSetup.get<SiStripApvGainRcd>().get( inputApvGain ); std::vector<uint32_t> inputDetIds; inputApvGain->getDetIds(inputDetIds); // Prepare the new object SiStripApvGain* obj = new SiStripApvGain(); const edm::Service<SiStripDetInfoFileReader> reader; uint32_t count = 0; const std::map<uint32_t, SiStripDetInfoFileReader::DetInfo >& DetInfos = reader->getAllData(); for(std::map<uint32_t, SiStripDetInfoFileReader::DetInfo >::const_iterator it = DetInfos.begin(); it != DetInfos.end(); it++) { // Find if this DetId is in the input tag and if so how many are the Apvs for which it contains information SiStripApvGain::Range inputRange; size_t inputRangeSize = 0; if( find( inputDetIds.begin(), inputDetIds.end(), it->first ) != inputDetIds.end() ) { inputRange = inputApvGain->getRange(it->first); inputRangeSize = distance(inputRange.first, inputRange.second); } std::vector<float> theSiStripVector; for(unsigned short j=0; j<it->second.nApvs; j++){ double gainValue = meanGain_; if( j < inputRangeSize ) { gainValue = inputApvGain->getApvGain(j, inputRange); // cout << "Gain = " << gainValue <<" from input tag for DetId = " << it->first << " and apv = " << j << endl; } // else { // cout << "No gain in input tag for DetId = " << it->first << " and apv = " << j << " using value from cfg = " << gainValue << endl; // } // corrections at layer/disk level: uint32_t detId = it->first; SiStripFakeAPVParameters::index sl = SiStripFakeAPVParameters::getIndex(tTopo, detId); //unsigned short nApvs = it->second.nApvs; if (applyTuning) { double correction = correct.get(sl); gainValue *= correction; } // smearing: if (genMode == "gaussian") { gainValue = CLHEP::RandGauss::shoot(gainValue, sigmaGain_); if(gainValue<=minimumPosValue_) gainValue=minimumPosValue_; } else if( genMode != "default" ) { LogDebug("SiStripApvGain") << "ERROR: wrong genMode specifier : " << genMode << ", please select one of \"default\" or \"gaussian\"" << std::endl; exit(1); } if (count<printdebug_) { edm::LogInfo("SiStripApvGainGeneratorFromTag") << "detid: " << it->first << " Apv: " << j << " gain: " << gainValue << std::endl; } theSiStripVector.push_back(gainValue); } count++; SiStripApvGain::Range range(theSiStripVector.begin(),theSiStripVector.end()); if ( ! obj->put(it->first,range) ) edm::LogError("SiStripApvGainGeneratorFromTag")<<" detid already exists"<<std::endl; } //End now write data in DB edm::Service<cond::service::PoolDBOutputService> mydbservice; if( mydbservice.isAvailable() ){ if( mydbservice->isNewTagRequest("SiStripApvGainRcd2") ){ mydbservice->createNewIOV<SiStripApvGain>(obj,mydbservice->beginOfTime(),mydbservice->endOfTime(),"SiStripApvGainRcd2"); } else { mydbservice->appendSinceTime<SiStripApvGain>(obj,mydbservice->currentTime(),"SiStripApvGainRcd2"); } } else { edm::LogError("SiStripApvGainBuilderFromTag")<<"Service is unavailable"<<std::endl; } }
40.322314
154
0.699324
nistefan
61595dadf3a04d46595e15df0f2fc93471d4bdbf
5,868
cxx
C++
appkit/sw/librnr_appkit/ut/utRegEx.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
appkit/sw/librnr_appkit/ut/utRegEx.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
appkit/sw/librnr_appkit/ut/utRegEx.cxx
roadnarrows-robotics/rnr-sdk
aee20c65b49fb3eedf924c5c2ec9f19f4f1a1b29
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Package: appkit // // Program: utRegEx // // File: utRegEx.cxx // /*! \file * * \brief Unit test RegEx class. * * \author Robin Knight (robin.knight@roadnarrows.com) * * \par Copyright * \h_copy 2017-2017. RoadNarrows LLC.\n * http://www.roadnarrows.com\n * All Rights Reserved */ /* * @EulaBegin@ * @EulaEnd@ */ //////////////////////////////////////////////////////////////////////////////// #include <unistd.h> #include <termios.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdarg.h> #include <iostream> #include <fstream> #include <string> #include "rnr/rnrconfig.h" #include "rnr/log.h" #include "rnr/opts.h" #include "rnr/pkg.h" #include "rnr/appkit/RegEx.h" #include "version.h" using namespace std; using namespace rnr; /*! * \ingroup apps * \defgroup unittest utRegEx * \{ */ #define APP_EC_OK 0 ///< success exit code #define APP_EC_ARGS 2 ///< command-line options/arguments error exit code #define APP_EC_EXEC 4 ///< execution exit code static char *Argv0; ///< the command static double OptsHz = 2; ///< thread hertz rate /*! * \brief Program information. */ static OptsPgmInfo_T PgmInfo = { // usage_args NULL, // synopsis "Unit test librnr_appkit RegEx class.", // long_desc = "The %P command unit tests the librnr_appkit RegEx class operation.", // diagnostics NULL }; /*! * \brief Command line options information. */ static OptsInfo_T OptsInfo[] = { {NULL, } }; /*! * \brief Globally constructed, pre-compiled re's. */ const RegEx re0; const RegEx re1("^[a-z]*$", RegEx::ReFlagICase); RegEx re2 = re1; const RegEx re3("['\"]{1,2}([0-9]+)(hello)(^)"); const RegEx re4("^[a-z]*$"); RegEx reGo = "([cC]at)|([dD]og)"; static string getline(istream &is) { char buf[256]; char *s; is.getline(buf, sizeof(buf)); for(s = buf; *s && isspace(*s); ++s); return string(s); } /*! * \brief Print RegEx data. * * \param re RegEx object. */ static void utPr(ostream &os, const string name, const RegEx &re) { os << " ... RE " << name << endl; os << "getRegEx() " << re.getRegEx() << endl; os << "isValid() " << re.isValid() << endl; os << "getFlags() " << re.getFlags() << endl; os << "getReturnCode() " << re.getReturnCode() << endl; os << "getErrorStr() " << re.getErrorStr() << endl; os << "operator<<() " << re << endl; } /*! * \brief Print RegEx data. * * \param re RegEx object. */ static void utConstRe(ostream &os, const RegEx &re) { const char *testinputs[] = { "abcd", "ABCD", "wXyZ", "12", "jkl mno", NULL }; os << " Test Constant RegEx:" << endl; utPr(os, "sut", re); for(size_t i = 0; testinputs[i] != NULL; ++i) { string input(testinputs[i]); os << input << " --> "; if( re.match(input) ) { os << "match"; } else { os << "no match"; } os << endl; } } /*! * \brief Test RegEx operations. */ static void utRun(ostream &os) { string cmd, arg; RegEx::ReMatchVec matches; os << " Test Run-Time Operations:" << endl; os << "q - Quit." << endl; os << "n <re> - Specify new re." << endl; os << "m <input> - Match input to re." << endl; os << "a <input> - Match all input substrings to re." << endl; os << "p - Print re." << endl; os << endl; while( true ) { if( cin.fail() ) { cin.clear(); cin.ignore(INT_MAX, '\n'); // awkward flush } os << "cmd> "; cin >> cmd; if( cmd == "q" ) { return; } else if( cmd == "n" ) { cin >> reGo; if( cin.fail() ) { os << "bad input" << endl; } else if( !reGo.isValid() ) { os << "bad re: " << reGo.getErrorStr() << endl; } else { os << "new valid re" << endl; } } else if( cmd == "m" ) { arg = getline(cin); os << "try match on '" << arg << "' --> "; if( reGo.match(arg) ) { os << "match" << endl; } else { os << "no match" << endl; } } else if( cmd == "a" ) { arg = getline(cin); os << "try match all on '" << arg << "'" << endl; reGo.match(arg, matches); for(size_t i = 0; i < matches.size(); ++i) { os << i << ". (" << matches[i].m_uStart << "," << matches[i].m_uEnd << ") '" << matches[i].m_strMatch << "'" << endl; } } else if( cmd == "p" ) { utPr(os, "Go", reGo); } else { os << "'" << cmd << "': Bad command. One of: a m n p q" << endl; } } } /*! * \brief Main initialization. * * \param argc Command-line argument count. * \param argv Command-line argument list. * * \par Exits: * Program terminates on conversion error. */ static void mainInit(int argc, char *argv[]) { // name of this process Argv0 = basename(argv[0]); // parse input options argv = OptsGet(Argv0, &PkgInfo, &PgmInfo, OptsInfo, true, &argc, argv); } /*! * \brief Main. * * \param argc Command-line argument count. * \param argv Command-line argument list. * * \return Returns 0 on succes, non-zero on failure. */ int main(int argc, char* argv[]) { mainInit(argc, argv); // // Test pre-compiled constructors // cout << " Test Pre-Compiled:" << endl; utPr(cout, "0", re0); utPr(cout, "1", re1); utPr(cout, "copy of 1", re2); utPr(cout, "3", re3); utPr(cout, "4", re4); utPr(cout, "Go", reGo); cout << endl; // Constant regex match utConstRe(cout, re1); utConstRe(cout, re4); cout << endl; // // Test run-time // utRun(cout); return APP_EC_OK; } /*! * \} */
18.807692
80
0.510736
roadnarrows-robotics
6159ba06674c4454dca8360fc181c8635ad2ff91
11,758
cpp
C++
deps/src/boost_1_65_1/libs/geometry/test/algorithms/relational_operations/disjoint/disjoint_coverage_l_l.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
deps/src/boost_1_65_1/libs/geometry/test/algorithms/relational_operations/disjoint/disjoint_coverage_l_l.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
deps/src/boost_1_65_1/libs/geometry/test/algorithms/relational_operations/disjoint/disjoint_coverage_l_l.cpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2014-2015, Oracle and/or its affiliates. // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html // Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle #ifndef BOOST_TEST_MODULE #define BOOST_TEST_MODULE test_disjoint_coverage #endif // unit test to test disjoint for all geometry combinations #include <iostream> #include <boost/test/included/unit_test.hpp> #include <boost/geometry/core/tag.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/strategies/strategies.hpp> #include <boost/geometry/io/wkt/wkt.hpp> #include <boost/geometry/io/dsv/write.hpp> #include <boost/geometry/geometries/geometries.hpp> #include <boost/geometry/algorithms/disjoint.hpp> #include <from_wkt.hpp> #ifdef HAVE_TTMATH #include <boost/geometry/extensions/contrib/ttmath_stub.hpp> #endif namespace bg = ::boost::geometry; //============================================================================ struct test_disjoint { template <typename Geometry1, typename Geometry2> static inline void apply(std::string const& case_id, Geometry1 const& geometry1, Geometry2 const& geometry2, bool expected_result) { bool result = bg::disjoint(geometry1, geometry2); BOOST_CHECK_MESSAGE(result == expected_result, "case ID: " << case_id << ", G1: " << bg::wkt(geometry1) << ", G2: " << bg::wkt(geometry2) << " -> Expected: " << expected_result << ", detected: " << result); result = bg::disjoint(geometry2, geometry1); BOOST_CHECK_MESSAGE(result == expected_result, "case ID: " << case_id << ", G1: " << bg::wkt(geometry2) << ", G2: " << bg::wkt(geometry1) << " -> Expected: " << expected_result << ", detected: " << result); #ifdef BOOST_GEOMETRY_TEST_DEBUG std::cout << "case ID: " << case_id << "; G1 - G2: "; std::cout << bg::wkt(geometry1) << " - "; std::cout << bg::wkt(geometry2) << std::endl; std::cout << std::boolalpha; std::cout << "expected/computed result: " << expected_result << " / " << result << std::endl; std::cout << std::endl; std::cout << std::noboolalpha; #endif } }; //============================================================================ // linear-linear geometries template <typename P> inline void test_segment_segment() { typedef bg::model::segment<P> S; typedef test_disjoint tester; tester::apply("s-s-01", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<S>("SEGMENT(0 0,0 2)"), false); tester::apply("s-s-02", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<S>("SEGMENT(2 0,3 0)"), false); tester::apply("s-s-03", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<S>("SEGMENT(1 0,3 0)"), false); tester::apply("s-s-04", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<S>("SEGMENT(1 0,1 1)"), false); tester::apply("s-s-05", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<S>("SEGMENT(1 1,2 2)"), true); tester::apply("s-s-06", from_wkt<S>("SEGMENT(0 0,1 1)"), from_wkt<S>("SEGMENT(1 1,1 1)"), false); tester::apply("s-s-07", from_wkt<S>("SEGMENT(0 0,1 1)"), from_wkt<S>("SEGMENT(2 2,2 2)"), true); tester::apply("s-s-08", from_wkt<S>("SEGMENT(0 0,1 1)"), from_wkt<S>("SEGMENT(2 2,3 3)"), true); } template <typename P> inline void test_linestring_segment() { typedef bg::model::segment<P> S; typedef bg::model::linestring<P> L; typedef test_disjoint tester; tester::apply("l-s-01", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(0 0,0 2)"), false); tester::apply("l-s-02", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(2 0,3 0)"), false); tester::apply("l-s-03", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(1 0,3 0)"), false); tester::apply("l-s-04", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(1 0,1 1)"), false); tester::apply("l-s-05", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(1 1,2 2)"), true); tester::apply("l-s-06", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(1 1,1 1,2 2)"), true); tester::apply("l-s-07", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(1 0,1 0,1 1,2 2)"), false); tester::apply("l-s-08", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(1 0,1 0,3 0)"), false); tester::apply("l-s-09", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(3 0,3 0,4 0)"), true); tester::apply("l-s-10", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(3 0,3 0)"), true); tester::apply("l-s-11", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(-1 0,-1 0)"), true); tester::apply("l-s-12", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(1 0,1 0)"), false); tester::apply("l-s-13", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<L>("LINESTRING(1 1,1 1)"), true); } template <typename P> inline void test_multilinestring_segment() { typedef bg::model::segment<P> S; typedef bg::model::linestring<P> L; typedef bg::model::multi_linestring<L> ML; typedef test_disjoint tester; tester::apply("s-ml-01", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((0 0,0 2))"), false); tester::apply("s-ml-02", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((2 0,3 0))"), false); tester::apply("s-ml-03", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 0,3 0))"), false); tester::apply("s-ml-04", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 0,1 1))"), false); tester::apply("s-ml-05", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 1,2 2))"), true); tester::apply("s-ml-06", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 1,2 2),(3 3,3 3))"), true); tester::apply("s-ml-07", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 1,2 2),(1 0,1 0))"), false); tester::apply("s-ml-08", from_wkt<S>("SEGMENT(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 1,2 2),(3 0,3 0))"), true); } template <typename P> inline void test_linestring_linestring() { typedef bg::model::linestring<P> L; typedef test_disjoint tester; tester::apply("l-l-01", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<L>("LINESTRING(0 0,0 2)"), false); tester::apply("l-l-02", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<L>("LINESTRING(2 0,3 0)"), false); tester::apply("l-l-03", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<L>("LINESTRING(1 0,3 0)"), false); tester::apply("l-l-04", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<L>("LINESTRING(1 0,1 1)"), false); tester::apply("l-l-05", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<L>("LINESTRING(1 1,2 2)"), true); } template <typename P> inline void test_linestring_multilinestring() { typedef bg::model::linestring<P> L; typedef bg::model::multi_linestring<L> ML; typedef test_disjoint tester; tester::apply("l-ml-01", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((0 0,0 2))"), false); tester::apply("l-ml-02", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((2 0,3 0))"), false); tester::apply("l-ml-03", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 0,3 0))"), false); tester::apply("l-ml-04", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 0,1 1))"), false); tester::apply("l-ml-05", from_wkt<L>("LINESTRING(0 0,2 0)"), from_wkt<ML>("MULTILINESTRING((1 1,2 2))"), true); } template <typename P> inline void test_multilinestring_multilinestring() { typedef bg::model::linestring<P> L; typedef bg::model::multi_linestring<L> ML; typedef test_disjoint tester; tester::apply("ml-ml-01", from_wkt<ML>("MULTILINESTRING((0 0,2 0))"), from_wkt<ML>("MULTILINESTRING((0 0,0 2))"), false); tester::apply("ml-ml-02", from_wkt<ML>("MULTILINESTRING((0 0,2 0))"), from_wkt<ML>("MULTILINESTRING((2 0,3 0))"), false); tester::apply("ml-ml-03", from_wkt<ML>("MULTILINESTRING((0 0,2 0))"), from_wkt<ML>("MULTILINESTRING((1 0,3 0))"), false); tester::apply("ml-ml-04", from_wkt<ML>("MULTILINESTRING((0 0,2 0))"), from_wkt<ML>("MULTILINESTRING((1 0,1 1))"), false); tester::apply("ml-ml-05", from_wkt<ML>("MULTILINESTRING((0 0,2 0))"), from_wkt<ML>("MULTILINESTRING((1 1,2 2))"), true); } //============================================================================ template <typename CoordinateType> inline void test_linear_linear() { typedef bg::model::point<CoordinateType, 2, bg::cs::cartesian> point_type; test_linestring_linestring<point_type>(); test_linestring_multilinestring<point_type>(); test_linestring_segment<point_type>(); test_multilinestring_multilinestring<point_type>(); test_multilinestring_segment<point_type>(); test_segment_segment<point_type>(); } //============================================================================ BOOST_AUTO_TEST_CASE( test_linear_linear_all ) { test_linear_linear<double>(); test_linear_linear<int>(); #ifdef HAVE_TTMATH test_linear_linear<ttmath_big>(); #endif }
30.942105
78
0.489284
shreyasvj25
615b54b45d5b6a9f224f5e4114a42be55ac3213c
874
cpp
C++
samples/search-delete.cpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
1
2015-09-22T10:32:36.000Z
2015-09-22T10:32:36.000Z
samples/search-delete.cpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
null
null
null
samples/search-delete.cpp
clusterpoint/cpp-client-api
605825f0d46678c1ebdabb006bc0c138e4b0b7f3
[ "MIT" ]
null
null
null
#include "cps/CPS_API.hpp" #include <iostream> #include <string> #include <vector> #include <map> int main() { try { CPS::Connection *conn = new CPS::Connection("tcp://127.0.0.1:5550", "storage", "user", "password"); // deletes all documents with an "expired" tag that contains a 1 CPS::SearchDeleteRequest sdelete_req("<expired>1</expired>"); CPS::SearchDeleteResponse *sdelete_resp = conn->sendRequest<CPS::SearchDeleteResponse>(sdelete_req); // Print out deleted ids std::cout << "Total documents deleted: " << sdelete_resp->getHits() << std::endl; // Clean Up delete sdelete_resp; delete conn; } catch (CPS::Exception& e) { std::cerr << e.what() << endl; std::cerr << boost::diagnostic_information(e); } return 0; }
27.3125
109
0.583524
clusterpoint
615facdb099b50f2f3a57603f7e1717193118239
649
cpp
C++
computerVision/NetFrameworks/INeurNetFramework.cpp
MattLigocki/DNNAssist
97801013ac948c6fdd84fa622888c519eed3bc85
[ "MIT" ]
null
null
null
computerVision/NetFrameworks/INeurNetFramework.cpp
MattLigocki/DNNAssist
97801013ac948c6fdd84fa622888c519eed3bc85
[ "MIT" ]
null
null
null
computerVision/NetFrameworks/INeurNetFramework.cpp
MattLigocki/DNNAssist
97801013ac948c6fdd84fa622888c519eed3bc85
[ "MIT" ]
null
null
null
#include "INeurNetFramework.h" void INeurNetFramework::processImage(QImage image) { if(detectionParameters()->usedFramework=="OpenCv"){ processImageByOpenCv(image); }else if(detectionParameters()->usedFramework=="Darknet"){ processImageByDarknet(image); }else if(detectionParameters()->usedFramework=="OpenMp"){ processImageByOpenMp(image); }else{ qDebug()<<"Invalid framework: "<<detectionParameters()->usedFramework; } } detectionParameters_t* INeurNetFramework::detectionParameters() { return m_detectionParameters; } QCvDetectFilter* INeurNetFramework::filter() { return m_filter; }
27.041667
78
0.721109
MattLigocki
6162f255d2249a1f487c9cd959172c9e655cf68f
8,849
hpp
C++
include/algebra/matrix/matrix_scr.hpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
include/algebra/matrix/matrix_scr.hpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
include/algebra/matrix/matrix_scr.hpp
hyperpower/Nablla
5a9be9f3b064a235572a1a2c9c5c2c19118697c5
[ "MIT" ]
null
null
null
/************************ // \file MatrixSCR.h // \brief // // \author zhou // \date 25 avr. 2014 ***********************/ #ifndef MATRIXSPARCOMPROW_H_ #define MATRIXSPARCOMPROW_H_ #include "algebra/algebra_define.hpp" #include "algebra/array/array_list.hpp" #include "matrix.hpp" namespace carpio { template<class VALUE> class MatrixSCO_; template<class VALUE> class MatrixSCC_; /* * Example: * row_ptr() 0 3 6 9 10 12 * val() 1 2 3, 4 5 6, 7 8 9, 10, 11 12, * col_ind() 0 1 4 0 1 2 1 2 4 3 0 4 */ template<class VALUE> class MatrixSCR_ { public: typedef VALUE Vt; private: ArrayListV_<Vt> val_; // data values (nz_ elements) ArrayListV_<St> rowptr_; // row_ptr (dim_[0]+1 elements) ArrayListV_<St> colind_; // col_ind (nz_ elements) St nz_; // number of nonzeros St dim_[2]; // number of rows, cols public: MatrixSCR_(void) : val_(0), rowptr_(0), colind_(0), nz_(0) { dim_[0] = 0; dim_[1] = 0; } //MatrixSCC(const Matrix &M); MatrixSCR_(const MatrixSCR_<Vt> &S) : val_(S.val_), rowptr_(S.rowptr_), colind_(S.colind_), nz_(S.nz_) { dim_[0] = S.dim_[0]; dim_[1] = S.dim_[1]; } MatrixSCR_(const MatrixSCC_<Vt> &C) : val_(C.NumNonzeros()), // rowptr_(C.iLen() + 1), // colind_(C.NumNonzeros()), // nz_(C.NumNonzeros()) // { dim_[0] = C.getiLen(); dim_[1] = C.getjLen(); St i, j; ArrayListV_<St> tally(C.iLen() + 1, 0); // First pass through nonzeros. Tally entries in each row. // And calculate rowptr array. for (i = 0; i < nz_; i++) { tally[C.row_ind(i)]++; } rowptr_[0] = 0; for (j = 0; j < dim_[0]; j++) rowptr_(j + 1) = rowptr_(j) + tally(j); // Make copy of rowptr for use in second pass. tally = rowptr_; // Second pass through nonzeros. Fill in index and value entries. St count = 0; for (i = 1; i <= dim_[1]; i++) { for (j = count; j < C.col_ptr(i); j++) { val_[tally(C.row_ind(j))] = C.val(j); colind_[tally(C.row_ind(j))] = i - 1; tally[C.row_ind(count)]++; count++; } } } MatrixSCR_(const MatrixSCO_<Vt> &CO) : val_(CO.non_zeros()), rowptr_(CO.size_i() + 1), colind_( CO.non_zeros()), nz_(CO.non_zeros()) { dim_[0] = CO.size_i(); dim_[1] = CO.size_j(); St i; ArrayListV_<St> tally(CO.size_i() + 1, 0); // First pass through nonzeros. Tally entries in each row. // And calculate rowptr array. for (i = 0; i < nz_; i++) { tally[CO.row_ind(i)]++; } rowptr_(0) = 0; for (i = 0; i < dim_[0]; i++) { rowptr_(i + 1) = rowptr_(i) + tally(i); } // Make copy of rowptr for use in second pass. tally = rowptr_; // Second pass through nonzeros. Fill in index and value entries. for (i = 0; i < nz_; i++) { val_[tally(CO.row_ind(i))] = CO.val(i); colind_[tally(CO.row_ind(i))] = CO.col_ind(i); tally[CO.row_ind(i)]++; } } MatrixSCR_(const MatrixV_<Vt> &m) : nz_(0), rowptr_(m.size_i() + 1){ dim_[0] = m.size_i(); dim_[1] = m.size_j(); // count non-zero for(St row = 0; row < m.size_i(); row++){ for(St col = 0; col < m.size_j(); col++){ if(m[row][col] != 0.0){ nz_++; } } } val_.reconstruct(nz_); colind_.reconstruct(nz_); St n = 0; rowptr_[0] = 0; for (St row = 0; row < m.size_i(); row++) { for (St col = 0; col < m.size_j(); col++) { if (m[row][col] != 0.0) { val_[n] = m[row][col]; colind_[n] = col; n++; } } rowptr_[row + 1] = n; } } MatrixSCR_(St M, St N, St nz, Vt *val, St *r, St *c) : val_(val, nz), rowptr_(*r, M + 1), colind_(*c, nz), nz_(nz) { dim_[0] = M; dim_[1] = N; } MatrixSCR_(St M, St N, St nz, const ArrayListV_<Vt> &val, const ArrayListV_<St> &r, const ArrayListV_<St> &c) : val_(val), rowptr_(r), colind_(c), nz_(nz) { dim_[0] = M; dim_[1] = N; } Vt* get_nz_pointer() { return this->val_.getPointer(); } Vt& val(St i) { return val_(i); } St& col_ind(St i) { return colind_(i); } St& row_ptr(St i) { return rowptr_(i); } const Vt& val(St i) const { return val_(i); } const St& col_ind(St i) const { return colind_(i); } const St& row_ptr(St i) const { return rowptr_(i); } St size() const { return dim_[0] * dim_[1]; } St size_i() const { return dim_[0]; } St size_j() const { return dim_[1]; } /* * make it looks like ublas */ St size1() const { return dim_[0]; } St size2() const { return dim_[1]; } St non_zeros() const { return nz_; } Vt max() const { return val_.findMax(); } Vt min() const { return val_.findMin(); } Vt sum() const { return val_.sum(); } /* * returns the sum along dimension dim. * For example, if A is a matrix, * then sum_row() is a column vector * containing the sum of each row. */ ArrayListV_<Vt> sum_row() const { ArrayListV_<Vt> res(this->size_i()); for (St i = 0; i < this->size_i(); ++i) { res[i] = 0; for (St j = this->row_ptr(i); j < this->row_ptr(i + 1); ++j) { res[i] += this->val(j); } } return res; } MatrixSCR_<Vt>& operator=(const MatrixSCR_<Vt> &R) { dim_[0] = R.dim_[0]; dim_[1] = R.dim_[1]; nz_ = R.nz_; val_ = R.val_; rowptr_ = R.rowptr_; colind_ = R.colind_; return *this; } MatrixSCR_<Vt>& newsize(St M, St N, St nz) { dim_[0] = M; dim_[1] = N; nz_ = nz; val_.reconstruct(nz); rowptr_.reconstruct(M + 1); colind_.reconstruct(nz); return *this; } Vt operator()(St i, St j) const { ASSERT(i >= 0 && i < dim_[0]); ASSERT(j >= 0 && j < dim_[1]); for (St t = rowptr_(i); t < rowptr_(i + 1); t++) { if (colind_(t) == j) return val_(t); } return 0.0; } ArrayListV_<Vt> operator*(const ArrayListV_<Vt> &x) const { St M = dim_[0]; St N = dim_[1]; // Check for compatible dimensions: ASSERT(x.size() == N); ArrayListV_<Vt> res(M); #pragma omp parallel for for (St i = 0; i < M; ++i) { for (St j = rowptr_[i]; j < rowptr_[i + 1]; ++j) { res[i] += x[colind_[j]] * val_[j]; } } return res; } ArrayListV_<Vt> trans_mult(const ArrayListV_<Vt> &x) const { St Mt = dim_[1]; St Nt = dim_[0]; // Check for compatible dimensions: ASSERT(x.size() == Nt); ArrayListV_<Vt> res(Mt); for (St i = 0; i < Mt; ++i) { for (St j = rowptr_[i]; j < rowptr_[i + 1]; ++j) { res[i] += x[colind_[j]] * val_[j]; } } return res; } void trans() { MatrixSCC_<Vt> C(dim_[1], dim_[0], nz_, val_, colind_, rowptr_); dim_[0] = C.getiLen(); dim_[1] = C.getjLen(); St i, j; ArrayListV_<St> tally(C.getiLen() + 1, 0); // First pass through nonzeros. Tally entries in each row. // And calculate rowptr array. for (i = 0; i < nz_; i++) { tally[C.row_ind(i)]++; } rowptr_[0] = 0; for (j = 0; j < dim_[0]; j++) rowptr_(j + 1) = rowptr_(j) + tally(j); // Make copy of rowptr for use in second pass. tally = rowptr_; // Second pass through nonzeros. Fill in index and vt entries. St count = 0; for (i = 1; i <= dim_[1]; i++) { for (j = count; j < C.col_ptr(i); j++) { val_[tally(C.row_ind(j))] = C.val(j); colind_[tally(C.row_ind(j))] = i - 1; tally[C.row_ind(count)]++; count++; } } } /* * get a new matrix. It is the Transpose of this matrix * Expensive function */ MatrixSCR_<Vt> get_trans() const { MatrixSCR_ res(dim_[0], dim_[1], nz_, val_, rowptr_, colind_); res.trans(); return res; } /* * check this is a diagonally dominant matrix or not */ bool is_diagonally_dominant() const { St Mt = dim_[1]; // Check for compatible dimensions: for (St i = 0; i < Mt; ++i) { Vt sum_ = 0; Vt vdiag = 0; for (St j = rowptr_[i]; j < rowptr_[i + 1]; ++j) { St col_idx = this->colind_(j); if (i == col_idx) { vdiag = std::abs(this->val_[j]); } else { sum_ += std::abs(this->val_[j]); } } if (sum_ > vdiag) { return false; } } return true; } void show(St a) const { if (a == 0) { std::cout << "RowPtr " << "ColInd " << "vt " << std::endl; for (St i = 0; i < dim_[0]; i++) { for (St ii = rowptr_[i]; ii < rowptr_[i + 1]; ii++) { std::cout << std::scientific << i << " "; std::cout << std::scientific << colind_[ii] << " "; std::cout << std::scientific << val_[ii] << "\n"; } } } else { for (St i = 0; i < dim_[0]; i++) { for (St j = 0; j < dim_[1]; j++) { bool flag = 0; for (St ii = rowptr_[i]; ii < rowptr_[i + 1]; ii++) { if (colind_[ii] == j) { std::cout << std::scientific << val_[ii] << " "; flag = 1; } } if (flag == 0) { std::cout << std::scientific << 0.0 << " "; } } std::cout << std::endl; } } } }; } // This is the end of namespace #endif /* MATRIXSPARCOMPROW_H_ */
22.865633
74
0.539835
hyperpower
616591cf8f309009bce94998640cfad5840de176
2,459
cpp
C++
LiveArchive/PastiPas.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
LiveArchive/PastiPas.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
LiveArchive/PastiPas.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
//Accepted #include <bits/stdc++.h> template<typename T> T gcd(T a, T b) { if(!b) return a; return gcd(b, a % b); } template<typename T> T lcm(T a, T b) { return a * b / gcd(a, b); } template<typename T> void chmin(T& a, T b) { a = (a > b) ? b : a; } template<typename T> void chmax(T& a, T b) { a = (a < b) ? b : a; } int in() { int x; scanf("%d", &x); return x; } using namespace std; typedef long long Int; typedef unsigned uint; typedef unsigned long long uInt; const int MAXN = 50001; const uInt MOD = 1000000007ULL; const uInt BASE = 29ULL; int T, N; char S[MAXN]; uInt hA[MAXN], pA[MAXN], invA[MAXN]; void fix(uInt& value, uInt mod) { if (value < 0LL) value += mod; value %= mod; } uInt modPow(uInt a, uInt n, uInt mod) { uInt res = 1ULL; while (n > 0ULL) { if (n & 1) { res = (res * a) % mod; } a = (a * a) % mod; n >>= 1; } return res; } uInt inv(uInt x, uInt mod) { return modPow(x, mod - 2, mod); } void hash(string s) { hA[0] = 0UL; for (int i = 0; i < N; i++) { int val = S[i] - 'A' + 1; if (i == 0) { hA[i] = (hA[i] + (pA[i] * val)) % MOD; } else { hA[i] = (hA[i - 1] + (pA[i] * val)) % MOD; } } } uInt hashL(int l, int r) { uInt ans_a = hA[r]; if (l > 0) { ans_a -= hA[l - 1]; } ans_a = (ans_a + MOD) % MOD; if (l > 0) { ans_a = (ans_a * invA[l]) % MOD; } return ans_a; } void gen(void) { freopen("i.in", "w", stdout); int t = 100; cout << t << endl; srand(time(NULL)); for (int x = 0; x < t; x++) { int len = 50000; for (int j = 0; j < len; j++) { cout << char('A' + (rand() % 2)); } cout << endl; } } int main(void) { scanf("%d", &T); pA[0] = 1LL; for (int i = 0; i < MAXN; i++) { if (i > 0) { pA[i] = (pA[i - 1] * BASE) % MOD; } invA[i] = inv(pA[i], MOD) % MOD; } for (int t = 1; t <= T; t++) { scanf("%s", S); N = strlen(S); hash(S); int ans = 0; int L = 0, R = N - 1; int pL = 0, pR = N - 1; bool reach = false; for ( ; L < R; ) { //cout << S.substr(pL, L - pL + 1) << " " << hashL(pL, L) << " " << S.substr(R, pR - R + 1) << " " << hashL(R, pR) << "\n"; uInt ha = hashL(pL, L); uInt hb = hashL(R, pR); if (ha == hb) { ans += 2; pL = L + 1; pR = R - 1; if (L + 1 == R) { reach = true; } } L += 1; R -= 1; } if (!reach) ans += 1; printf("Case #%d: %d\n", t, ans); //cout << "Case #" << t << ": " << ans << endl; } return 0; }
16.727891
126
0.464823
aajjbb
616628622b73c0a2221cbba1b9d19eaf44138f1f
921
hpp
C++
include/xtensor-fftw/basic_option.hpp
michaelbacci/xtensor-fftw
0c463ab759d7664a9b25c4382987138151ad74c3
[ "BSD-3-Clause" ]
13
2019-12-13T08:38:55.000Z
2021-06-18T09:01:23.000Z
include/xtensor-fftw/basic_option.hpp
michaelbacci/xtensor-fftw
0c463ab759d7664a9b25c4382987138151ad74c3
[ "BSD-3-Clause" ]
13
2019-11-07T12:15:38.000Z
2022-02-23T14:33:00.000Z
include/xtensor-fftw/basic_option.hpp
michaelbacci/xtensor-fftw
0c463ab759d7664a9b25c4382987138151ad74c3
[ "BSD-3-Clause" ]
5
2019-11-07T11:57:36.000Z
2021-05-15T22:38:37.000Z
/* * xtensor-fftw * Copyright (c) 2017, Patrick Bos * * Distributed under the terms of the BSD 3-Clause License. * * The full license is in the file LICENSE, distributed with this software. * * basic_option.hpp: * Include xtensor-fftw functionalities with explicit defined precision types. * */ #ifndef XTENSOR_FFTW_BASIC_OPTION_HPP #define XTENSOR_FFTW_BASIC_OPTION_HPP #if !defined(XTENSOR_FFTW_USE_FLOAT) \ && !defined(XTENSOR_FFTW_USE_DOUBLE) \ && !defined(XTENSOR_FFTW_USE_LONG_DOUBLE) #error Missing definition of FFTW type library. Please #define at least once before include xtensor-fftw library. #endif #ifdef XTENSOR_FFTW_USE_FLOAT #include "xtensor-fftw/basic_float.hpp" #endif #ifdef XTENSOR_FFTW_USE_DOUBLE #include "xtensor-fftw/basic_double.hpp" #endif #ifdef XTENSOR_FFTW_USE_LONG_DOUBLE #include "xtensor-fftw/basic_long_double.hpp" #endif #endif //XTENSOR_FFTW_BASIC_OPTION_HPP
25.583333
113
0.787188
michaelbacci
61664984721c92412d230192a5f1716f246d08eb
3,467
hpp
C++
src/vector.hpp
fdekruijff/Tesseract-LED-Cube
70a9ce4d44517714966b2a62e8fb6c4a950f8407
[ "BSL-1.0" ]
null
null
null
src/vector.hpp
fdekruijff/Tesseract-LED-Cube
70a9ce4d44517714966b2a62e8fb6c4a950f8407
[ "BSL-1.0" ]
null
null
null
src/vector.hpp
fdekruijff/Tesseract-LED-Cube
70a9ce4d44517714966b2a62e8fb6c4a950f8407
[ "BSL-1.0" ]
null
null
null
/// Copyright Floris de Kruijff 2018. /// Distributed under the Boost Software License, Version 1.0. /// (See accompanying file LICENSE.txt or copy at /// https://www.boost.org/LICENSE.txt) /// @file #ifndef VECTOR_HPP #define VECTOR_HPP /// @class vector /// @author Floris de Kruijff /// @date 25-06-2018 /// @file vector.hpp /// @brief vector ADT /// @details /// Custom vector ADT to define coordinates cube. class vector { public: /// @brief specifies the x-coordinate of the vector as an integer. int x; /// @brief specifies the y-coordinate of the vector as an integer. int y; /// @brief specifies the z-coordinate of the vector as an integer. int z; /// \brief /// Construct a vector from x y z values. /// \details /// This constructor initializes a vector from an x and y value. /// The z value is optional and initiated as 0 if leaved blanc. vector(int x, int y, int z = 0): x( x ), y( y ), z( z ) {} /// \brief /// Compare two vector values /// \details /// This operator tests for equality. It returns true /// if and only if the x, y and z value of both vectors match. bool operator==( const vector &rhs ) const { return ((x == rhs.x) && (y == rhs.y) && (z == rhs.z)); } /// \brief /// Add two vectors together. /// \details /// This operator+ adds a vector value with another vector. vector operator+( const vector &rhs ) const { vector temp = *this; temp += rhs; return temp; } /// \brief /// Add a vector to this object. /// \details /// Add vector values to this object and return this object. vector &operator+=( const vector &rhs ) { x += rhs.x; y += rhs.y; z += rhs.z; return *this; } /// \brief /// Subtract two vectors. /// \details /// This operator- subtracts a vector value with another vector. vector operator-( const vector &rhs ) const { vector temp = *this; temp -= rhs; return temp; } /// \brief /// Subtract a vector from this object. /// \details /// Subtract vector values from this object and return this object. vector &operator-=( const vector &rhs ) { x -= rhs.x; y -= rhs.y; z -= rhs.z; return *this; } /// \brief /// Multiply two vectors together. /// \details /// Multiply two vectors and return the result as vector. vector operator*( const vector &rhs ) const { vector temp = *this; temp *= rhs; return temp; } /// \brief /// Multiply a vector with this object. /// \details /// Multiply a vector with this object and return this object. vector &operator*=( const vector &rhs ) { x *= rhs.x; y *= rhs.y; z *= rhs.z; return *this; } /// \brief /// Add one to this vector. /// \details /// Adds 1 to the (x,y,z) of this object. vector &operator++() { x++; y++; z++; return *this; } /// \brief /// Subtract one from this vector. /// \details /// Subtract 1 from the (x,y,z) of this object. vector &operator--() { x--; y--; z--; return *this; } }; #endif //VECTOR_HPP
27.085938
72
0.533026
fdekruijff
6169b3ea5fd580c864b4dc6ca2f884910d9ad484
40,296
cpp
C++
Source.cpp
kenjinote/Toot
19d75b03eed981f6aed8d041b3c6ba6f3f0ef316
[ "MIT" ]
19
2017-04-19T06:51:59.000Z
2021-12-15T02:55:44.000Z
Source.cpp
kenjinote/Toot
19d75b03eed981f6aed8d041b3c6ba6f3f0ef316
[ "MIT" ]
null
null
null
Source.cpp
kenjinote/Toot
19d75b03eed981f6aed8d041b3c6ba6f3f0ef316
[ "MIT" ]
1
2022-03-05T03:57:49.000Z
2022-03-05T03:57:49.000Z
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") #pragma comment(lib, "wininet") #pragma comment(lib, "gdiplus") #pragma comment(lib, "shlwapi") #pragma comment(lib, "dwmapi") #include <windows.h> #include <windowsx.h> #include <dwmapi.h> #include <gdiplus.h> #include <shlwapi.h> #include <shlobj.h> #include <wininet.h> #include <string> #include <list> #include <vector> #include "json11.hpp" #include "resource.h" #define ID_POST 1000 Gdiplus::Bitmap* LoadBitmapFromResource(int nID, LPCWSTR lpszType) { Gdiplus::Bitmap* pBitmap = 0; const HINSTANCE hInstance = GetModuleHandle(0); const HRSRC hResource = FindResourceW(hInstance, MAKEINTRESOURCE(nID), lpszType); if (!hResource) return 0; const DWORD dwImageSize = SizeofResource(hInstance, hResource); if (!dwImageSize) return 0; const void* pResourceData = LockResource(LoadResource(hInstance, hResource)); if (!pResourceData) return 0; const HGLOBAL hBuffer = GlobalAlloc(GMEM_MOVEABLE, dwImageSize); if (hBuffer) { void* pBuffer = GlobalLock(hBuffer); if (pBuffer) { CopyMemory(pBuffer, pResourceData, dwImageSize); IStream* pStream = NULL; if (CreateStreamOnHGlobal(hBuffer, TRUE, &pStream) == S_OK) { pBitmap = Gdiplus::Bitmap::FromStream(pStream); if (pBitmap) { if (pBitmap->GetLastStatus() != Gdiplus::Ok) { delete pBitmap; pBitmap = NULL; } } pStream->Release(); } GlobalUnlock(hBuffer); } } return pBitmap; } int UrlEncode(LPCWSTR lpszSrc, LPWSTR lpszDst) { DWORD iDst = 0; const DWORD dwTextLengthA = WideCharToMultiByte(CP_UTF8, 0, lpszSrc, -1, 0, 0, 0, 0); LPSTR szUTF8TextA = (LPSTR)GlobalAlloc(GMEM_FIXED, dwTextLengthA); // NULL を含んだ文字列バッファを確保 if (szUTF8TextA) { if (WideCharToMultiByte(CP_UTF8, 0, lpszSrc, -1, szUTF8TextA, dwTextLengthA, 0, 0)) { for (DWORD iSrc = 0; iSrc < dwTextLengthA && szUTF8TextA[iSrc] != '\0'; ++iSrc) { LPCSTR lpszUnreservedCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"; if (StrChrA(lpszUnreservedCharacters, szUTF8TextA[iSrc])) { if (lpszDst) lpszDst[iDst] = (WCHAR)szUTF8TextA[iSrc]; ++iDst; } else if (szUTF8TextA[iSrc] == ' ') { if (lpszDst) lpszDst[iDst] = L'+'; ++iDst; } else { if (lpszDst) wsprintfW(&lpszDst[iDst], L"%%%02X", szUTF8TextA[iSrc] & 0xFF); iDst += 3; } } if (lpszDst) lpszDst[iDst] = L'\0'; ++iDst; } GlobalFree(szUTF8TextA); } return iDst; // NULL 文字を含む } class Mastodon { LPWSTR m_lpszServer; WCHAR m_szClientID[65]; WCHAR m_szSecret[65]; static BOOL GetStringFromJSON(LPCSTR lpszJson, LPCSTR lpszKey, LPSTR lpszValue) { std::string src(lpszJson); std::string err; json11::Json v = json11::Json::parse(src, err); if (err.size()) return FALSE; lpszValue[0] = 0; lstrcpyA(lpszValue, v[lpszKey].string_value().c_str()); return lstrlenA(lpszValue) > 0; } static BOOL GetIntegerFromJSON(LPCSTR lpszJson, LPCSTR lpszKey, LPINT lpInt) { std::string src(lpszJson); std::string err; json11::Json v = json11::Json::parse(src, err); if (err.size()) return FALSE; *lpInt = 0; *lpInt = v[lpszKey].int_value(); return *lpInt > 0; } static BOOL GetLongIntegerFromJSON(LPCSTR lpszJson, LPCSTR lpszKey, PLONGLONG lpLongInt) { std::string src(lpszJson); std::string err; json11::Json v = json11::Json::parse(src, err); if (err.size()) return FALSE; *lpLongInt = 0; *lpLongInt = atoll(v[lpszKey].string_value().c_str()); return *lpLongInt > 0; } public: WCHAR m_szAccessToken[65]; Mastodon() : m_lpszServer(0) { m_szAccessToken[0] = 0; m_szClientID[0] = 0; m_szSecret[0] = 0; }; ~Mastodon() { GlobalFree(m_lpszServer); } void SetServer(LPCWSTR lpszServer) { GlobalFree(m_lpszServer); m_lpszServer = (LPWSTR)GlobalAlloc(0, sizeof(WCHAR) * (lstrlenW(lpszServer) + 1)); lstrcpyW(m_lpszServer, lpszServer); } LPSTR Post(LPCWSTR lpszPath, LPCWSTR lpszHeader, LPBYTE lpbyData, int nSize) const { LPSTR lpszReturn = 0; if (!m_lpszServer || !m_lpszServer[0]) goto END1; const HINTERNET hInternet = InternetOpenW(L"WinInet Toot Program", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (!hInternet) goto END1; const HINTERNET hHttpSession = InternetConnectW(hInternet, m_lpszServer, INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0); if (!hHttpSession) goto END2; const HINTERNET hHttpRequest = HttpOpenRequestW(hHttpSession, L"POST", lpszPath, NULL, 0, NULL, INTERNET_FLAG_SECURE | INTERNET_FLAG_RELOAD, 0); if (!hHttpRequest) goto END3; if (HttpSendRequestW(hHttpRequest, lpszHeader, lstrlenW(lpszHeader), lpbyData, nSize) == FALSE) goto END4; { LPBYTE lpszByte = (LPBYTE)GlobalAlloc(GPTR, 1); DWORD dwRead, dwSize = 0; static BYTE szBuffer[1024 * 4]; for (;;) { if (!InternetReadFile(hHttpRequest, szBuffer, (DWORD)sizeof(szBuffer), &dwRead) || !dwRead) break; LPBYTE lpTemp = (LPBYTE)GlobalReAlloc(lpszByte, (SIZE_T)(dwSize + dwRead + 1), GMEM_MOVEABLE); if (lpTemp == NULL) break; lpszByte = lpTemp; CopyMemory(lpszByte + dwSize, szBuffer, dwRead); dwSize += dwRead; } lpszByte[dwSize] = 0; lpszReturn = (LPSTR)lpszByte; } END4: InternetCloseHandle(hHttpRequest); END3: InternetCloseHandle(hHttpSession); END2: InternetCloseHandle(hInternet); END1: return lpszReturn; } BOOL GetClientIDAndClientSecret() { BOOL bReturnValue = FALSE; CHAR szData[128]; lstrcpyA(szData, "client_name=TootApp&redirect_uris=urn:ietf:wg:oauth:2.0:oob&scopes=write"); LPSTR lpszReturn = Post(L"/api/v1/apps", L"Content-Type: application/x-www-form-urlencoded", (LPBYTE)szData, lstrlenA(szData)); if (lpszReturn) { CHAR szClientID[65]; CHAR szSecret[65]; bReturnValue = GetStringFromJSON(lpszReturn, "client_id", szClientID) & GetStringFromJSON(lpszReturn, "client_secret", szSecret); if (bReturnValue){ MultiByteToWideChar(CP_UTF8, 0, szClientID, -1, m_szClientID, _countof(m_szClientID)); MultiByteToWideChar(CP_UTF8, 0, szSecret, -1, m_szSecret, _countof(m_szSecret)); } GlobalFree(lpszReturn); } return bReturnValue; } BOOL GetAccessToken(LPCWSTR lpszUserName, LPCWSTR lpszPassword) { BOOL bReturnValue = FALSE; if (!m_szClientID[0]) return bReturnValue; if (!m_szSecret[0]) return bReturnValue; WCHAR szData[512]; wsprintfW(szData, L"scope=write&client_id=%s&client_secret=%s&grant_type=password&username=%s&password=%s", m_szClientID, m_szSecret, lpszUserName, lpszPassword); DWORD dwTextLen = WideCharToMultiByte(CP_UTF8, 0, szData, -1, 0, 0, 0, 0); LPSTR lpszDataA = (LPSTR)GlobalAlloc(GPTR, dwTextLen); WideCharToMultiByte(CP_UTF8, 0, szData, -1, lpszDataA, dwTextLen, 0, 0); LPSTR lpszReturn = Post(L"/oauth/token", L"Content-Type: application/x-www-form-urlencoded", (LPBYTE)lpszDataA, dwTextLen - 1); GlobalFree(lpszDataA); if (lpszReturn) { CHAR szAccessToken[65]; bReturnValue = GetStringFromJSON(lpszReturn, "access_token", szAccessToken); if (bReturnValue) { MultiByteToWideChar(CP_UTF8, 0, szAccessToken, -1, m_szAccessToken, _countof(m_szAccessToken)); } GlobalFree(lpszReturn); } return bReturnValue; } BOOL Toot(LPCWSTR lpszMessage, LPCWSTR lpszVisibility, LPWSTR lpszCreatedAt, const std::vector<LONGLONG> &mediaIds, BOOL bCheckNsfw) const { BOOL bReturnValue = FALSE; if (!m_szAccessToken[0]) return bReturnValue; WCHAR szData[1024*4]; const int nMessageSize = UrlEncode(lpszMessage, 0); LPWSTR lpszUrlEncodedMessage = (LPWSTR)GlobalAlloc(0, nMessageSize * sizeof(WCHAR)); UrlEncode(lpszMessage, lpszUrlEncodedMessage); swprintf(szData, L"access_token=%s&status=%s&visibility=%s", m_szAccessToken, lpszUrlEncodedMessage, lpszVisibility); GlobalFree(lpszUrlEncodedMessage); if (mediaIds.size()) { for (auto id : mediaIds) { WCHAR szID[32]; wsprintfW(szID, L"&media_ids[]=%I64d", id); lstrcatW(szData, szID); } if (bCheckNsfw) lstrcatW(szData, L"&sensitive=true"); } DWORD dwTextLen = WideCharToMultiByte(CP_UTF8, 0, szData, -1, 0, 0, 0, 0); LPSTR lpszDataA = (LPSTR)GlobalAlloc(GPTR, dwTextLen); WideCharToMultiByte(CP_UTF8, 0, szData, -1, lpszDataA, dwTextLen, 0, 0); LPSTR lpszReturn = Post(L"/api/v1/statuses", L"Content-Type: application/x-www-form-urlencoded", (LPBYTE)lpszDataA, dwTextLen); GlobalFree(lpszDataA); if (lpszReturn) { CHAR szCreatedAt[32]; bReturnValue = GetStringFromJSON(lpszReturn, "created_at", szCreatedAt); if (bReturnValue) { MultiByteToWideChar(CP_UTF8, 0, szCreatedAt, -1, lpszCreatedAt, 32); } GlobalFree(lpszReturn); } return bReturnValue; } VOID MakeBoundary(LPWSTR lpszBoundary) const { lstrcpyW(lpszBoundary, L"----Boundary"); lstrcatW(lpszBoundary, L"kQcRxxn2b2BGpt9a"); } BOOL MediaUpload(LPCWSTR lpszMediaType, LPBYTE lpbyImageData, int nDataLength, LPWSTR lpszTextURL, PLONGLONG pMediaID) const { BOOL bReturnValue = FALSE; if (!m_szAccessToken[0]) return bReturnValue; WCHAR szBoundary[32]; MakeBoundary(szBoundary); WCHAR szHeader[256]; wsprintfW(szHeader, L"Authorization: Bearer %s\r\nContent-Type: multipart/form-data; boundary=%s", m_szAccessToken, szBoundary); CHAR szMediaTypeA[16]; WideCharToMultiByte(CP_UTF8, 0, lpszMediaType, -1, szMediaTypeA, _countof(szMediaTypeA), 0, 0); CHAR szFileNameA[16]; lstrcpyA(szFileNameA, szMediaTypeA); for (int i = 0; i < lstrlenA(szFileNameA); ++i) { if (szFileNameA[i] == '/') { szFileNameA[i] = '.'; break; } } CHAR szBoundaryA[32]; WideCharToMultiByte(CP_UTF8, 0, szBoundary, -1, szBoundaryA, _countof(szBoundaryA), 0, 0); CHAR szDataBeforeA[256]; int nSizeBefore = wsprintfA(szDataBeforeA, "--%s\r\nContent-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\nContent-Type: %s\r\n\r\n", szBoundaryA, szFileNameA, szMediaTypeA); CHAR szDataAfterA[64]; int nSizeAfter = wsprintfA(szDataAfterA, "--%s--\r\n", szBoundaryA); int nTotalSize = nSizeBefore + nDataLength + nSizeAfter; LPBYTE lpbyData = (LPBYTE)GlobalAlloc(0, nTotalSize); CopyMemory(lpbyData, szDataBeforeA, nSizeBefore); CopyMemory(lpbyData + nSizeBefore, lpbyImageData, nDataLength); CopyMemory(lpbyData + nSizeBefore + nDataLength, szDataAfterA, nSizeAfter); LPSTR lpszReturn = Post(L"/api/v1/media", szHeader, lpbyData, nTotalSize); GlobalFree(lpbyData); if (lpszReturn) { CHAR szTextURL[256]; bReturnValue = GetStringFromJSON(lpszReturn, "url", szTextURL) && !strstr(szTextURL, "/missing."); if (bReturnValue) { bReturnValue = GetLongIntegerFromJSON(lpszReturn, "id", pMediaID); } GlobalFree(lpszReturn); } return bReturnValue; } }; class EditBox { WNDPROC fnEditWndProc; LPWSTR m_lpszPlaceholder; int m_nLimit; static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { EditBox* _this = (EditBox*)GetWindowLongPtr(hWnd, GWLP_USERDATA); if (_this) { if (msg == WM_PAINT) { const LRESULT lResult = CallWindowProc(_this->fnEditWndProc, hWnd, msg, wParam, lParam); const int nTextLength = GetWindowTextLengthW(hWnd); if ((_this->m_lpszPlaceholder && !nTextLength) || _this->m_nLimit) { const HDC hdc = GetDC(hWnd); const COLORREF OldTextColor = SetTextColor(hdc, RGB(180, 180, 180)); const COLORREF OldBkColor = SetBkColor(hdc, RGB(255, 255, 255)); const HFONT hOldFont = (HFONT)SelectObject(hdc, (HFONT)SendMessageW(hWnd, WM_GETFONT, 0, 0)); const int nLeft = LOWORD(SendMessageW(hWnd, EM_GETMARGINS, 0, 0)); if (_this->m_lpszPlaceholder && !nTextLength) { TextOutW(hdc, nLeft + 4, 2, _this->m_lpszPlaceholder, lstrlenW(_this->m_lpszPlaceholder)); } if (_this->m_nLimit) { RECT rect; GetClientRect(hWnd, &rect); --rect.right; --rect.bottom; WCHAR szText[16]; wsprintfW(szText, L"%5d", _this->m_nLimit - nTextLength); DrawTextW(hdc, szText, -1, &rect, DT_RIGHT | DT_SINGLELINE | DT_BOTTOM); } SelectObject(hdc, hOldFont); SetBkColor(hdc, OldBkColor); SetTextColor(hdc, OldTextColor); ReleaseDC(hWnd, hdc); } return lResult; } else if (msg == WM_CHAR && wParam == 1) { SendMessageW(hWnd, EM_SETSEL, 0, -1); return 0; } return CallWindowProc(_this->fnEditWndProc, hWnd, msg, wParam, lParam); } return 0; } public: HWND m_hWnd; EditBox(LPCWSTR lpszDefaultText, DWORD dwStyle, int x, int y, int width, int height, HWND hParent, HMENU hMenu, LPCWSTR lpszPlaceholder) : m_hWnd(0), m_nLimit(0), fnEditWndProc(0), m_lpszPlaceholder(0) { if (lpszPlaceholder && !m_lpszPlaceholder) { m_lpszPlaceholder = (LPWSTR)GlobalAlloc(0, sizeof(WCHAR) * (lstrlenW(lpszPlaceholder) + 1)); lstrcpyW(m_lpszPlaceholder, lpszPlaceholder); } m_hWnd = CreateWindowW(L"EDIT", lpszDefaultText, dwStyle, x, y, width, height, hParent, hMenu, GetModuleHandle(0), 0); SetWindowLongPtr(m_hWnd, GWLP_USERDATA, (LONG_PTR)this); fnEditWndProc = (WNDPROC)SetWindowLongPtr(m_hWnd, GWLP_WNDPROC, (LONG_PTR)WndProc); } ~EditBox() { DestroyWindow(m_hWnd); GlobalFree(m_lpszPlaceholder); } void SetLimit(int nLimit) { SendMessageW(m_hWnd, EM_LIMITTEXT, nLimit, 0); m_nLimit = nLimit; } }; class BitmapEx : public Gdiplus::Bitmap { public: LPBYTE m_lpByte; DWORD m_nSize; BitmapEx(IN HBITMAP hbm) : Gdiplus::Bitmap::Bitmap(hbm, 0) , m_lpByte(0), m_nSize(0) { Gdiplus::Status OldlastResult = GetLastStatus(); if (OldlastResult == Gdiplus::Ok) { GUID guid; if (GetRawFormat(&guid) == Gdiplus::Ok) { } } else { lastResult = OldlastResult; } } BitmapEx(const WCHAR *filename) : Gdiplus::Bitmap::Bitmap(filename) , m_lpByte(0), m_nSize(0) { if (GetLastStatus() == Gdiplus::Ok) { GUID guid; if (GetRawFormat(&guid) == Gdiplus::Ok) { if (guid == Gdiplus::ImageFormatGIF) { UINT count = GetFrameDimensionsCount(); GUID* pDimensionIDs = new GUID[count]; GetFrameDimensionsList(pDimensionIDs, count); int nFrameCount = GetFrameCount(&pDimensionIDs[0]); delete[]pDimensionIDs; if (nFrameCount > 1) { HANDLE hFile = CreateFileW(filename, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (hFile != INVALID_HANDLE_VALUE) { DWORD dwReadSize; m_nSize = GetFileSize(hFile, 0); m_lpByte = (LPBYTE)GlobalAlloc(0, m_nSize); ReadFile(hFile, m_lpByte, m_nSize, &dwReadSize, 0); CloseHandle(hFile); } } } } } else { lastResult = Gdiplus::UnknownImageFormat; } } virtual ~BitmapEx() { GlobalFree(m_lpByte); m_lpByte = 0; } }; BitmapEx* WindowCapture(HWND hWnd) { BitmapEx * pBitmap = 0; RECT rect1; GetWindowRect(hWnd, &rect1); RECT rect2; if (DwmGetWindowAttribute(hWnd, DWMWA_EXTENDED_FRAME_BOUNDS, &rect2, sizeof(rect2)) != S_OK) rect2 = rect1; HDC hdc = GetDC(0); HDC hMem = CreateCompatibleDC(hdc); HBITMAP hBitmap = CreateCompatibleBitmap(hdc, rect2.right - rect2.left, rect2.bottom - rect2.top); if (hBitmap) { HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMem, hBitmap); SetForegroundWindow(hWnd); InvalidateRect(hWnd, 0, 1); UpdateWindow(hWnd); BitBlt(hMem, 0, 0, rect2.right - rect2.left, rect2.bottom - rect2.top, hdc, rect2.left, rect2.top, SRCCOPY); pBitmap = new BitmapEx(hBitmap); SelectObject(hMem, hOldBitmap); DeleteObject(hBitmap); } DeleteDC(hMem); ReleaseDC(0, hdc); return pBitmap; } BitmapEx* ScreenCapture(LPRECT lpRect) { BitmapEx * pBitmap = 0; HDC hdc = GetDC(0); HDC hMem = CreateCompatibleDC(hdc); HBITMAP hBitmap = CreateCompatibleBitmap(hdc, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top); if (hBitmap) { HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMem, hBitmap); BitBlt(hMem, 0, 0, lpRect->right - lpRect->left, lpRect->bottom - lpRect->top, hdc, lpRect->left, lpRect->top, SRCCOPY); pBitmap = new BitmapEx(hBitmap); SelectObject(hMem, hOldBitmap); DeleteObject(hBitmap); } DeleteDC(hMem); ReleaseDC(0, hdc); return pBitmap; } LRESULT CALLBACK LayerWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static HWND hParentWnd; static BOOL bDrag; static BOOL bDown; static POINT posStart; static RECT OldRect; switch (msg) { case WM_CREATE: hParentWnd = (HWND)((LPCREATESTRUCT)lParam)->lpCreateParams; break; case WM_KEYDOWN: case WM_RBUTTONDOWN: SendMessage(hWnd, WM_CLOSE, 0, 0); break; case WM_LBUTTONDOWN: { int xPos = GET_X_LPARAM(lParam); int yPos = GET_Y_LPARAM(lParam); POINT point = { xPos, yPos }; ClientToScreen(hWnd, &point); posStart = point; SetCapture(hWnd); } break; case WM_MOUSEMOVE: if (GetCapture() == hWnd) { int xPos = GET_X_LPARAM(lParam); int yPos = GET_Y_LPARAM(lParam); POINT point = { xPos, yPos }; ClientToScreen(hWnd, &point); if (!bDrag) { if (abs(xPos - posStart.x) > GetSystemMetrics(SM_CXDRAG) && abs(yPos - posStart.y) > GetSystemMetrics(SM_CYDRAG)) { bDrag = TRUE; } } else { HDC hdc = GetDC(hWnd); RECT rect = { min(point.x, posStart.x), min(point.y, posStart.y), max(point.x, posStart.x), max(point.y, posStart.y) }; OffsetRect(&rect, -GetSystemMetrics(SM_XVIRTUALSCREEN), -GetSystemMetrics(SM_YVIRTUALSCREEN)); HBRUSH hBrush = CreateSolidBrush(RGB(255, 0, 0)); HRGN hRgn1 = CreateRectRgn(OldRect.left, OldRect.top, OldRect.right, OldRect.bottom); HRGN hRgn2 = CreateRectRgn(rect.left, rect.top, rect.right, rect.bottom); CombineRgn(hRgn1, hRgn1, hRgn2, RGN_DIFF); FillRgn(hdc, hRgn1, (HBRUSH)GetStockObject(BLACK_BRUSH)); FillRect(hdc, &rect, hBrush); OldRect = rect; DeleteObject(hBrush); DeleteObject(hRgn1); DeleteObject(hRgn2); ReleaseDC(hWnd, hdc); } } break; case WM_LBUTTONUP: if (GetCapture() == hWnd) { ReleaseCapture(); Gdiplus::Bitmap * pBitmap = 0; if (bDrag) { bDrag = FALSE; int xPos = GET_X_LPARAM(lParam); int yPos = GET_Y_LPARAM(lParam); POINT point = { xPos, yPos }; ClientToScreen(hWnd, &point); RECT rect = { min(point.x, posStart.x), min(point.y, posStart.y), max(point.x, posStart.x), max(point.y, posStart.y) }; ShowWindow(hWnd, SW_HIDE); pBitmap = ScreenCapture(&rect); } else { ShowWindow(hWnd, SW_HIDE); HWND hTargetWnd = WindowFromPoint(posStart); hTargetWnd = GetAncestor(hTargetWnd, GA_ROOT); if (hTargetWnd) { pBitmap = WindowCapture(hTargetWnd); } } SendMessage(hParentWnd, WM_APP, 0, (LPARAM)pBitmap); } break; default: return DefWindowProc(hWnd, msg, wParam, lParam); } return 0; } class ImageListPanel { BOOL m_bDrag; int m_nDragIndex; int m_nSplitPrevIndex; int m_nSplitPrevPosY; int m_nMargin; int m_nImageMaxCount; HFONT m_hFont; std::list<BitmapEx*> m_listBitmap; WNDPROC fnWndProc; Gdiplus::Bitmap *m_pCameraIcon; BOOL MoveImage(int nIndexFrom, int nIndexTo) { if (nIndexFrom < 0) nIndexFrom = 0; if (nIndexTo < 0) nIndexTo = 0; if (nIndexFrom == nIndexTo) return FALSE; std::list<BitmapEx*>::iterator itFrom = m_listBitmap.begin(); std::list<BitmapEx*>::iterator itTo = m_listBitmap.begin(); std::advance(itFrom, nIndexFrom); std::advance(itTo, nIndexTo); m_listBitmap.splice(itTo, m_listBitmap, itFrom); return TRUE; } static LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (msg == WM_NCCREATE) { SetWindowLongPtr(hWnd, GWLP_USERDATA, (LONG_PTR)((LPCREATESTRUCT)lParam)->lpCreateParams); return TRUE; } ImageListPanel* _this = (ImageListPanel*)GetWindowLongPtr(hWnd, GWLP_USERDATA); if (_this) { switch (msg) { case WM_DROPFILES: { HDROP hDrop = (HDROP)wParam; WCHAR szFileName[MAX_PATH]; UINT iFile, nFiles; nFiles = DragQueryFile((HDROP)hDrop, 0xFFFFFFFF, NULL, 0); BOOL bUpdate = FALSE; for (iFile = 0; iFile < nFiles; ++iFile) { if ((int)_this->m_listBitmap.size() >= _this->m_nImageMaxCount) break; DragQueryFileW(hDrop, iFile, szFileName, _countof(szFileName)); BitmapEx* pBitmap = new BitmapEx(szFileName); if (pBitmap) { if (pBitmap->GetLastStatus() == Gdiplus::Ok) { _this->m_listBitmap.push_back(pBitmap); bUpdate = TRUE; } else { delete pBitmap; } } } DragFinish(hDrop); if (bUpdate) InvalidateRect(hWnd, 0, 1); } return 0; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); { RECT rect; GetClientRect(hWnd, &rect); INT nTop = _this->m_nMargin; Gdiplus::Graphics g(hdc); int nWidth = rect.right - 2 * _this->m_nMargin; Gdiplus::StringFormat f; f.SetAlignment(Gdiplus::StringAlignmentCenter); f.SetLineAlignment(Gdiplus::StringAlignmentCenter); if (_this->m_listBitmap.size() == 0) { Gdiplus::Font font(hdc, _this->m_hFont); Gdiplus::RectF rectf((Gdiplus::REAL)0, (Gdiplus::REAL)0, (Gdiplus::REAL)rect.right, (Gdiplus::REAL)rect.bottom); g.DrawString(L"画像をドロップ\r\n\r\nまたは\r\n\r\nクリックして画像を選択", -1, &font, rectf, &f, &Gdiplus::SolidBrush(Gdiplus::Color::MakeARGB(128, 0, 0, 0))); } else { Gdiplus::Font font(&Gdiplus::FontFamily(L"Marlett"), 11, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel); for (auto bitmap : _this->m_listBitmap) { int nHeight = bitmap->GetHeight() * nWidth / bitmap->GetWidth(); g.DrawImage(bitmap, _this->m_nMargin, nTop, nWidth, nHeight); Gdiplus::RectF rectf((Gdiplus::REAL)(nWidth + _this->m_nMargin - 16), (Gdiplus::REAL)nTop, (Gdiplus::REAL)16, (Gdiplus::REAL)16); g.FillRectangle(&Gdiplus::SolidBrush(Gdiplus::Color::MakeARGB(192, 255, 255, 255)), rectf); g.DrawString(L"r", 1, &font, rectf, &f, &Gdiplus::SolidBrush(Gdiplus::Color::MakeARGB(192, 0, 0, 0))); nTop += nHeight + _this->m_nMargin; } } int nCameraIconWidth = _this->m_pCameraIcon->GetWidth(); int nCameraIconHeigth = _this->m_pCameraIcon->GetHeight(); g.DrawImage(_this->m_pCameraIcon, rect.right - nCameraIconWidth - 2, rect.bottom - nCameraIconHeigth - 2, nCameraIconWidth, nCameraIconHeigth); } EndPaint(hWnd, &ps); } return 0; case WM_APP: { BitmapEx* pBitmap = (BitmapEx*)lParam; BOOL bPushed = FALSE; if ((int)_this->m_listBitmap.size() < _this->m_nImageMaxCount) { if (pBitmap) { _this->m_listBitmap.push_back(pBitmap); InvalidateRect(hWnd, 0, 1); bPushed = TRUE; } } if (!bPushed) delete pBitmap; SetForegroundWindow(hWnd); } break; case WM_LBUTTONDOWN: { RECT rect; GetClientRect(hWnd, &rect); POINT point = { LOWORD(lParam), HIWORD(lParam) }; int nCameraIconWidth = _this->m_pCameraIcon->GetWidth(); int nCameraIconHeigth = _this->m_pCameraIcon->GetHeight(); RECT rectCameraIcon = { rect.right - nCameraIconWidth - 2, rect.bottom - nCameraIconHeigth - 2, rect.right, rect.bottom }; if (PtInRect(&rectCameraIcon, point)) { HWND hLayerWnd = CreateWindowExW(WS_EX_LAYERED | WS_EX_TOPMOST, L"LayerWindow", 0, WS_POPUP, 0, 0, 0, 0, 0, 0, GetModuleHandle(0), (LPVOID)hWnd); SetLayeredWindowAttributes(hLayerWnd, RGB(255, 0, 0), 64, LWA_ALPHA | LWA_COLORKEY); SetWindowPos(hLayerWnd, HWND_TOPMOST, GetSystemMetrics(SM_XVIRTUALSCREEN), GetSystemMetrics(SM_YVIRTUALSCREEN), GetSystemMetrics(SM_CXVIRTUALSCREEN), GetSystemMetrics(SM_CYVIRTUALSCREEN), SWP_NOSENDCHANGING); ShowWindow(hLayerWnd, SW_NORMAL); UpdateWindow(hLayerWnd); return 0; } INT nTop = _this->m_nMargin; int nWidth = rect.right - 2 * _this->m_nMargin; for (auto it = _this->m_listBitmap.begin(); it != _this->m_listBitmap.end(); ++it) { int nHeight = (*it)->GetHeight() * nWidth / (*it)->GetWidth(); RECT rectCloseButton = { nWidth + _this->m_nMargin - 16, nTop, nWidth + _this->m_nMargin, nTop + 16 }; if (PtInRect(&rectCloseButton, point)) { delete *it; *it = 0; _this->m_listBitmap.erase(it); InvalidateRect(hWnd, 0, 1); return 0; } nTop += nHeight + _this->m_nMargin; } nTop = _this->m_nMargin; int nIndex = 0; for (auto it = _this->m_listBitmap.begin(); it != _this->m_listBitmap.end(); ++it) { int nHeight = (*it)->GetHeight() * nWidth / (*it)->GetWidth(); RECT rectImage = { _this->m_nMargin, nTop, _this->m_nMargin + nWidth, nTop + nHeight }; if (PtInRect(&rectImage, point)) { _this->m_bDrag = TRUE; SetCapture(hWnd); _this->m_nDragIndex = nIndex; return 0; } nTop += nHeight + _this->m_nMargin; ++nIndex; } if ((int)_this->m_listBitmap.size() < _this->m_nImageMaxCount) { WCHAR szFileName[MAX_PATH] = { 0 }; OPENFILENAMEW of = { sizeof(OPENFILENAME) }; WCHAR szMyDocumentFolder[MAX_PATH]; SHGetFolderPathW(NULL, CSIDL_MYPICTURES, NULL, NULL, szMyDocumentFolder);// PathAddBackslashW(szMyDocumentFolder); of.hwndOwner = hWnd; of.lpstrFilter = L"画像ファイル\0*.png;*.gif;*.jpg;*.jpeg;*.bmp;*.tif;*.ico;*.emf;*.wmf;\0すべてのファイル(*.*)\0*.*\0\0"; of.lpstrFile = szFileName; of.nMaxFile = MAX_PATH; of.Flags = OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; of.lpstrTitle = L"画像ファイルを開く"; of.lpstrInitialDir = szMyDocumentFolder; if (GetOpenFileNameW(&of)) { BitmapEx* pBitmap = new BitmapEx(szFileName); if (pBitmap) { if (pBitmap->GetLastStatus() == Gdiplus::Ok) { _this->m_listBitmap.push_back(pBitmap); InvalidateRect(hWnd, 0, 1); } else { delete pBitmap; } } } } } return 0; case WM_MOUSEMOVE: if (_this->m_bDrag) { RECT rect; GetClientRect(hWnd, &rect); INT nCursorY = HIWORD(lParam); INT nTop = 0; int nWidth = rect.right - 2 * _this->m_nMargin; int nIndex = 0; for (auto it = _this->m_listBitmap.begin(); it != _this->m_listBitmap.end(); ++it) { int nHeight = (*it)->GetHeight() * nWidth / (*it)->GetWidth(); RECT rectImage = { 0, nTop, rect.right, nTop + nHeight + _this->m_nMargin }; if (nCursorY >= nTop && (nIndex + 1 == _this->m_listBitmap.size() || nCursorY < nTop + nHeight + _this->m_nMargin)) { int nCurrentIndex; int nCurrentPosY; if (nCursorY < nTop + nHeight / 2 + _this->m_nMargin) { nCurrentIndex = nIndex; nCurrentPosY = nTop; } else { nCurrentIndex = nIndex + 1; nCurrentPosY = nTop + nHeight + _this->m_nMargin; } if (nCurrentIndex != _this->m_nSplitPrevIndex) { HDC hdc = GetDC(hWnd); if (_this->m_nSplitPrevIndex != -1) PatBlt(hdc, 0, _this->m_nSplitPrevPosY, rect.right, _this->m_nMargin, PATINVERT); PatBlt(hdc, 0, nCurrentPosY, rect.right, _this->m_nMargin, PATINVERT); ReleaseDC(hWnd, hdc); _this->m_nSplitPrevIndex = nCurrentIndex; _this->m_nSplitPrevPosY = nCurrentPosY; } return 0; } nTop += nHeight + _this->m_nMargin; ++nIndex; } } return 0; case WM_LBUTTONUP: if (_this->m_bDrag) { ReleaseCapture(); _this->m_bDrag = FALSE; if (_this->m_nSplitPrevIndex != -1) { RECT rect; GetClientRect(hWnd, &rect); HDC hdc = GetDC(hWnd); PatBlt(hdc, 0, _this->m_nSplitPrevPosY, rect.right, _this->m_nMargin, PATINVERT); ReleaseDC(hWnd, hdc); if (_this->MoveImage(_this->m_nDragIndex, _this->m_nSplitPrevIndex)) { InvalidateRect(hWnd, 0, 1); } _this->m_nSplitPrevIndex = -1; } } return 0; } } return DefWindowProc(hWnd, msg, wParam, lParam); } void RemoveAllImage() { for (auto &bitmap : m_listBitmap) { delete bitmap; bitmap = 0; } m_listBitmap.clear(); } public: HWND m_hWnd; ImageListPanel(int nImageMaxCount, DWORD dwStyle, int x, int y, int width, int height, HWND hParent, HFONT hFont) : m_nImageMaxCount(nImageMaxCount) , m_hWnd(0) , fnWndProc(0) , m_nMargin(4) , m_bDrag(0) , m_nSplitPrevIndex(-1) , m_nSplitPrevPosY(0) , m_hFont(hFont) , m_pCameraIcon(0) { m_pCameraIcon = LoadBitmapFromResource(IDB_PNG1, L"PNG"); WNDCLASSW wndclass1 = { 0,LayerWndProc,0,0,GetModuleHandle(0),0,LoadCursor(0,IDC_CROSS),(HBRUSH)GetStockObject(BLACK_BRUSH),0,L"LayerWindow" }; RegisterClassW(&wndclass1); WNDCLASSW wndclass2 = { CS_HREDRAW | CS_VREDRAW,WndProc,0,0,GetModuleHandle(0),0,LoadCursor(0,IDC_ARROW),(HBRUSH)(COLOR_WINDOW + 1),0,__FUNCTIONW__ }; RegisterClassW(&wndclass2); m_hWnd = CreateWindowW(__FUNCTIONW__, 0, dwStyle, x, y, width, height, hParent, 0, GetModuleHandle(0), this); } ~ImageListPanel() { RemoveAllImage(); delete m_pCameraIcon; } int GetImageCount() { return (int)m_listBitmap.size(); } BitmapEx * GetImage(int nIndex) { std::list<BitmapEx*>::iterator it = m_listBitmap.begin(); std::advance(it, nIndex); return *it; } void ResetContent() { RemoveAllImage(); InvalidateRect(m_hWnd, 0, 1); } }; HHOOK g_hHook; LRESULT CALLBACK CBTProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode == HCBT_ACTIVATE) { UnhookWindowsHookEx(g_hHook); RECT rectMessageBox, rectParentWnd; GetWindowRect((HWND)wParam, &rectMessageBox); GetWindowRect(GetParent((HWND)wParam), &rectParentWnd); SetWindowPos((HWND)wParam, 0, (rectParentWnd.right + rectParentWnd.left - rectMessageBox.right + rectMessageBox.left) >> 1, (rectParentWnd.bottom + rectParentWnd.top - rectMessageBox.bottom + rectMessageBox.top) >> 1, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); } return 0; } BOOL GetEncoderClsid(LPCWSTR format, CLSID* pClsid) { UINT num = 0, size = 0; Gdiplus::GetImageEncodersSize(&num, &size); if (size == 0) return FALSE; Gdiplus::ImageCodecInfo* pImageCodecInfo = (Gdiplus::ImageCodecInfo*)(GlobalAlloc(0, size)); if (pImageCodecInfo == NULL) return FALSE; GetImageEncoders(num, size, pImageCodecInfo); for (UINT i = 0; i < num; ++i) { if (wcscmp(pImageCodecInfo[i].MimeType, format) == 0) { *pClsid = pImageCodecInfo[i].Clsid; GlobalFree(pImageCodecInfo); return TRUE; } } GlobalFree(pImageCodecInfo); return FALSE; } LPWSTR GetText(HWND hWnd) { const int nSize = GetWindowTextLengthW(hWnd); LPWSTR lpszText = (LPWSTR)GlobalAlloc(0, sizeof(WCHAR)*(nSize + 1)); GetWindowTextW(hWnd, lpszText, nSize + 1); return lpszText; } LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { static EditBox *pEdit1, *pEdit2, *pEdit3, *pEdit4; static ImageListPanel *pImageListPanel; static HWND hCombo, hButton, hCheckNsfw; static HFONT hFont; static BOOL bModified; static Mastodon* pMastodon; switch (msg) { case WM_CREATE: hFont = CreateFontW(22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, L"Yu Gothic UI"); pEdit1 = new EditBox(0, WS_VISIBLE | WS_CHILD | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, L"サーバー名"); SendMessageW(pEdit1->m_hWnd, WM_SETFONT, (WPARAM)hFont, 0); pEdit2 = new EditBox(0, WS_VISIBLE | WS_CHILD | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, L"メールアドレス"); SendMessageW(pEdit2->m_hWnd, WM_SETFONT, (WPARAM)hFont, 0); pEdit3 = new EditBox(0, WS_VISIBLE | WS_CHILD | WS_BORDER | WS_TABSTOP | ES_AUTOHSCROLL | ES_PASSWORD, 0, 0, 0, 0, hWnd, 0, L"パスワード"); SendMessageW(pEdit3->m_hWnd, WM_SETFONT, (WPARAM)hFont, 0); pEdit4 = new EditBox(0, WS_VISIBLE | WS_CHILD | WS_BORDER | WS_TABSTOP | ES_AUTOVSCROLL | ES_MULTILINE | ES_WANTRETURN, 0, 0, 0, 0, hWnd, 0, L"今何してる?"); SendMessageW(pEdit4->m_hWnd, WM_SETFONT, (WPARAM)hFont, 0); pEdit4->SetLimit(500); pImageListPanel = new ImageListPanel(4, WS_VISIBLE | WS_CHILD | WS_BORDER, 0, 0, 0, 0, hWnd, hFont); hCheckNsfw = CreateWindowW(L"BUTTON", L"NSFWチェック", WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_AUTOCHECKBOX, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0); SendMessageW(hCheckNsfw, WM_SETFONT, (WPARAM)hFont, 0); hCombo = CreateWindowW(L"COMBOBOX", 0, WS_VISIBLE | WS_CHILD | WS_TABSTOP | CBS_DROPDOWNLIST, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0); SendMessageW(hCombo, WM_SETFONT, (WPARAM)hFont, 0); SendMessageW(hCombo, CB_SETITEMDATA, SendMessageW(hCombo, CB_ADDSTRING, 0, (LPARAM)L"全体に公開"), (LPARAM)L"public"); SendMessageW(hCombo, CB_SETITEMDATA, SendMessageW(hCombo, CB_ADDSTRING, 0, (LPARAM)L"自分のタイムラインに公開(公開タイムラインには表示しない)"), (LPARAM)L"unlisted"); SendMessageW(hCombo, CB_SETITEMDATA, SendMessageW(hCombo, CB_ADDSTRING, 0, (LPARAM)L"自分のフォロワーに公開"), (LPARAM)L"private"); SendMessageW(hCombo, CB_SETITEMDATA, SendMessageW(hCombo, CB_ADDSTRING, 0, (LPARAM)L"非公開・ダイレクトメッセージ(自分と@ユーザーのみ閲覧可)"), (LPARAM)L"direct"); SendMessageW(hCombo, CB_SETCURSEL, 0, 0); hButton = CreateWindowW(L"BUTTON", L"トゥート! (Ctrl + Enter)", WS_VISIBLE | WS_CHILD | WS_TABSTOP | BS_DEFPUSHBUTTON, 0, 0, 0, 0, hWnd, (HMENU)ID_POST, ((LPCREATESTRUCT)lParam)->hInstance, 0); SendMessageW(hButton, WM_SETFONT, (WPARAM)hFont, 0); pMastodon = new Mastodon; DragAcceptFiles(hWnd, TRUE); break; case WM_DROPFILES: if (pImageListPanel) { SendMessageW(pImageListPanel->m_hWnd, msg, wParam, lParam); } break; case WM_GETMINMAXINFO: ((MINMAXINFO*)lParam)->ptMinTrackSize.x = 300; ((MINMAXINFO*)lParam)->ptMinTrackSize.y = 555; break; case WM_SIZE: MoveWindow(pEdit1->m_hWnd, 10, 10, LOWORD(lParam) - 20, 32, TRUE); MoveWindow(pEdit2->m_hWnd, 10, 50, LOWORD(lParam) - 20, 32, TRUE); MoveWindow(pEdit3->m_hWnd, 10, 90, LOWORD(lParam) - 20, 32, TRUE); MoveWindow(pEdit4->m_hWnd, 10, 130, LOWORD(lParam) - 158, HIWORD(lParam) - 324 + 90, TRUE); MoveWindow(pImageListPanel->m_hWnd, LOWORD(lParam) - 138, 130, 128, HIWORD(lParam) - 356 + 90, TRUE); MoveWindow(hCheckNsfw, LOWORD(lParam) - 10 - 128, HIWORD(lParam) - 226 + 90, 128, 32, TRUE); MoveWindow(hCombo, 10, HIWORD(lParam) - 184 + 90, LOWORD(lParam) - 20, 256, TRUE); MoveWindow(hButton, 10, HIWORD(lParam) - 142 + 90, LOWORD(lParam) - 20, 32, TRUE); break; case WM_COMMAND: if (HIWORD(wParam) == EN_CHANGE) { InvalidateRect((HWND)lParam, 0, 0); if ((pEdit1 && pEdit1->m_hWnd == (HWND)lParam) || (pEdit2 && pEdit2->m_hWnd == (HWND)lParam)) bModified = TRUE; } else if (LOWORD(wParam) == ID_POST) { std::vector<LONGLONG> mediaIds; LPWSTR lpszServer = 0; LPWSTR lpszUserName = 0; LPWSTR lpszPassword = 0; LPWSTR lpszMessage = 0; if (bModified || !lstrlenW(pMastodon->m_szAccessToken)) { InternetSetOption(0, INTERNET_OPTION_END_BROWSER_SESSION, 0, 0); lpszServer = GetText(pEdit1->m_hWnd); URL_COMPONENTSW uc = { sizeof(uc) }; uc.dwHostNameLength = (DWORD)GlobalSize(lpszServer); uc.lpszHostName = (LPWSTR)GlobalAlloc(0, uc.dwHostNameLength); if (InternetCrackUrlW(lpszServer, 0, 0, &uc)) { lstrcpyW(lpszServer, uc.lpszHostName); } GlobalFree(uc.lpszHostName); pMastodon->SetServer(lpszServer); if (!pMastodon->GetClientIDAndClientSecret()) goto END; lpszUserName = GetText(pEdit2->m_hWnd); lpszPassword = GetText(pEdit3->m_hWnd); if (!pMastodon->GetAccessToken(lpszUserName, lpszPassword)) goto END; bModified = FALSE; } int nImageCount = pImageListPanel->GetImageCount(); for (int i = 0; i < nImageCount; ++i) { BitmapEx*pImage = pImageListPanel->GetImage(i); GUID guid1; LPWSTR lpszMediaType; if (pImage->GetRawFormat(&guid1) != Gdiplus::Ok) continue; if (guid1 == Gdiplus::ImageFormatGIF && pImage->m_lpByte) { lpszMediaType = L"image/gif"; } else if (guid1 == Gdiplus::ImageFormatJPEG || guid1 == Gdiplus::ImageFormatEXIF) { lpszMediaType = L"image/jpeg"; } else { lpszMediaType = L"image/png"; } GUID guid2; GetEncoderClsid(lpszMediaType, &guid2); LONGLONG nMediaID = 0; if (pImage->m_lpByte) { WCHAR szURL[256]; pMastodon->MediaUpload(lpszMediaType, pImage->m_lpByte, (int)pImage->m_nSize, szURL, &nMediaID); } else { IStream *pStream = NULL; if (CreateStreamOnHGlobal(NULL, TRUE, &pStream) == S_OK) { if (pImage->Save(pStream, &guid2) == S_OK) { ULARGE_INTEGER ulnSize; LARGE_INTEGER lnOffset; lnOffset.QuadPart = 0; if (pStream->Seek(lnOffset, STREAM_SEEK_END, &ulnSize) == S_OK) { if (pStream->Seek(lnOffset, STREAM_SEEK_SET, NULL) == S_OK) { LPBYTE baPicture = (LPBYTE)GlobalAlloc(0, (SIZE_T)ulnSize.QuadPart); ULONG ulBytesRead; pStream->Read(baPicture, (ULONG)ulnSize.QuadPart, &ulBytesRead); WCHAR szURL[256]; pMastodon->MediaUpload(lpszMediaType, baPicture, (int)ulnSize.QuadPart, szURL, &nMediaID); GlobalFree(baPicture); } } } pStream->Release(); } } if (nMediaID) { mediaIds.push_back(nMediaID); } else { WCHAR szText[512]; wsprintf(szText, TEXT("トゥートの投稿に失敗しました。\r\n%d 番目の添付メディアのアップロードに失敗しました。"), i + 1); g_hHook = SetWindowsHookEx(WH_CBT, CBTProc, 0, GetCurrentThreadId()); MessageBoxW(hWnd, szText, L"確認", MB_ICONHAND); goto END; } } lpszMessage = GetText(pEdit4->m_hWnd); const int nVisibility = (int)SendMessageW(hCombo, CB_GETCURSEL, 0, 0); LPCWSTR lpszVisibility = (LPCWSTR)SendMessageW(hCombo, CB_GETITEMDATA, nVisibility, 0); WCHAR szCreatedAt[32]; if (!pMastodon->Toot(lpszMessage, lpszVisibility, szCreatedAt, mediaIds, (BOOL)SendMessageW(hCheckNsfw, BM_GETCHECK, 0, 0))) goto END; WCHAR szResult[1024]; wsprintfW(szResult, L"投稿されました。\n投稿日時 = %s", szCreatedAt); g_hHook = SetWindowsHookEx(WH_CBT, CBTProc, 0, GetCurrentThreadId()); MessageBoxW(hWnd, szResult, L"確認", 0); pImageListPanel->ResetContent(); SendMessageW(hCheckNsfw, BM_SETCHECK, 0, 0); SetWindowTextW(pEdit4->m_hWnd, 0); SetFocus(pEdit4->m_hWnd); END: GlobalFree(lpszServer); GlobalFree(lpszUserName); GlobalFree(lpszPassword); GlobalFree(lpszMessage); } break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: delete pMastodon; delete pEdit1; delete pEdit2; delete pEdit3; delete pEdit4; delete pImageListPanel; DeleteObject(hFont); PostQuitMessage(0); break; default: return DefDlgProc(hWnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int) { Gdiplus::GdiplusStartupInput gdiplusStartupInput; ULONG_PTR gdiplusToken; GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, 0); LPCWSTR lpszClassName = L"TootWindow"; MSG msg = { 0 }; const WNDCLASSW wndclass = { 0,WndProc,0,DLGWINDOWEXTRA,hInstance,LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)),LoadCursor(0,IDC_ARROW),0,0,lpszClassName }; RegisterClassW(&wndclass); const HWND hWnd = CreateWindowW(lpszClassName, L"トゥートする", WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN, CW_USEDEFAULT, 0, 512, 800, 0, 0, hInstance, 0); ShowWindow(hWnd, SW_SHOWDEFAULT); UpdateWindow(hWnd); ACCEL Accel[] = { { FVIRTKEY | FCONTROL,VK_RETURN,ID_POST } }; HACCEL hAccel = CreateAcceleratorTable(Accel, _countof(Accel)); while (GetMessage(&msg, 0, 0, 0)) { if (!TranslateAccelerator(hWnd, hAccel, &msg) && !IsDialogMessage(hWnd, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } Gdiplus::GdiplusShutdown(gdiplusToken); return (int)msg.wParam; }
38.450382
271
0.66818
kenjinote