hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
5a164e16ee45920f15896b25587d36628b2362a5
877
cpp
C++
Gates/LogicalGates/XorGate.cpp
clement-gresh/M1-portes_logiques
e034219ac1377602e33aaf1341dd79721bd67317
[ "MIT" ]
null
null
null
Gates/LogicalGates/XorGate.cpp
clement-gresh/M1-portes_logiques
e034219ac1377602e33aaf1341dd79721bd67317
[ "MIT" ]
null
null
null
Gates/LogicalGates/XorGate.cpp
clement-gresh/M1-portes_logiques
e034219ac1377602e33aaf1341dd79721bd67317
[ "MIT" ]
null
null
null
#include "XorGate.hpp" // CONSTRUCTORS // private XorGate::XorGate() : LogicalGate{ std::vector<Gate*>{} } {} //public XorGate::XorGate(Gate* const a, Gate* const b) : LogicalGate{ {a, b} } {} XorGate::XorGate(const XorGate& clone) : XorGate{ clone.getGates().at(0), clone.getGates().at(1) } {} XorGate::XorGate(const XorGate* clone) : XorGate{ clone->getGates().at(0), clone->getGates().at(1) } {} // METHODS void XorGate::updateGate() { // Updating the logical function corresponding to this gate std::string function = this->logicalFunction("xor"); this->setLogicalFunction(function); // Updating the value of the gate this->setValue( (this->getGates().at(0)->getValue() && !this->getGates().at(1)->getValue()) || (!this->getGates().at(0)->getValue() && this->getGates().at(1)->getValue()) ); } void XorGate::drawGate(Drawing& d) { this->draw(d, "XOR", 1); }
33.730769
103
0.663626
[ "vector" ]
5a1765d752946e470ca80ce9067567248ff935ce
2,765
cpp
C++
leetcode/binary_tree/balanced_binary_tree.cpp
chachaxw/data-structure-and-algorithm
343a72f9bd4d78aa69305bf5c58f4aab74979705
[ "MIT" ]
91
2018-11-21T15:29:56.000Z
2022-01-29T12:24:56.000Z
leetcode/binary_tree/balanced_binary_tree.cpp
chachaxw/data-structure-and-algorithm
343a72f9bd4d78aa69305bf5c58f4aab74979705
[ "MIT" ]
null
null
null
leetcode/binary_tree/balanced_binary_tree.cpp
chachaxw/data-structure-and-algorithm
343a72f9bd4d78aa69305bf5c58f4aab74979705
[ "MIT" ]
22
2018-12-08T01:51:59.000Z
2021-03-15T10:07:37.000Z
/** * @Author: Chacha * @Date: 2019-01-03 17:07:54 * @Last Modified by: Chacha * @Last Modified time: 2021-03-30 15:47:16 */ #include <iostream> #include <vector> using namespace std; /** * 题目: * 给定一个二叉树,判断它是否是高度平衡的二叉树 * * 平衡二叉树的定义:一个二叉树每个节点的左右两个子树的高度差的绝对值不超过1。 * * 来源: https://leetcode-cn.com/problems/balanced-binary-tree * * 示例: * 给定二叉树 A={3,9,20,#,#,15,7}, B={3,#,20,15,7} * * A) 3 B) 3 * / \ \ * 9 20 20 * / \ / \ * 15 7 15 7 * * 二叉树 A 是一个高度平衡的二叉树, 但 B 不是. * */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; /** * 方法一:自顶向下的递归 * * 题解: * 定义函数 height,用于计算二叉树中的任意一个节点 p 的高度: * * height(p)={ 0 p 是空节点 * max(height(p.left),height(p.right))+1 p 是非空节点 * * 自顶向下递归类似于前序遍历,对于当前遍历到的节点,首先计算左右子树的高度,如果左右子树的高度差不超过1, * 再分别遍历左右子节点,并判断左子树和右子树是否平衡。 * * 来源:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/ * * 复杂度: * 时间复杂度:O(n^2),其中 n 是二叉树中的节点个数。 * 空间复杂度:O(n),其中 n 是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过 n * */ class Solution { private: /* data */ public: bool isBalanced(TreeNode *root) { if (root == NULL) { return root; } else { return abs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right); } } int height(TreeNode *root) { if (root == NULL) { return 0; } else { return max(height(root->left), height(root->right)) + 1; } } }; /** * 方法二:自底向上的递归 * * 题解: * * 来源:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/ * * 自底向上递归类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。如果一棵子树是 * 平衡的,则返回其高度(高度一定是非负整数),否则返回 -1.如果存在一棵子树不平衡,则整个二叉树一定不平衡。 * * 复杂度: * 时间复杂度:O(n),其中 n 是二叉树中的节点个数。使用自底向上的递归,每个节点的计算高度和判断是否平衡都只需要处理一次, * 最坏情况下需要遍历二叉树中的所有节点,因此时间复杂度是 O(n)。 * 空间复杂度:O(n),其中 n 是二叉树中的节点个数。空间复杂度主要取决于递归调用的层数,递归调用的层数不会超过 n * */ class Solution1 { public: bool isBalanced(TreeNode *root) { return maxDepth(root) >= 0; } private: int maxDepth(TreeNode *root) { if (root == NULL) return 0; int leftDepth = maxDepth(root->left); int rightDepth = maxDepth(root->right); if (leftDepth == -1 || rightDepth == -1 || abs(leftDepth - rightDepth) > 1) { return -1; } return max(leftDepth, rightDepth) + 1; } }; int main() { return 0; }
20.036232
123
0.55226
[ "vector" ]
5a2228a51dbee3ba98c7e349862fae2f91a79416
828
cpp
C++
viterbi_decoder_712/main.cpp
Andrew-Montgomery/viterbi_decoder_712
09200c98fab5eda84460abfc11127982dc9042fb
[ "MIT" ]
1
2022-03-03T20:24:55.000Z
2022-03-03T20:24:55.000Z
viterbi_decoder_712/main.cpp
Andrew-Montgomery/viterbi_decoder_712
09200c98fab5eda84460abfc11127982dc9042fb
[ "MIT" ]
null
null
null
viterbi_decoder_712/main.cpp
Andrew-Montgomery/viterbi_decoder_712
09200c98fab5eda84460abfc11127982dc9042fb
[ "MIT" ]
null
null
null
#include <iostream> #include <random> #include "src/viterbi_decoder_712.h" int main() { BitVector input, encoded, decoded; // Create encoder and decoder. Match puncture patterns. ConvolutionalEncoder712 encoder; encoder.SetPuncturePattern(PuncturePattern712_56); ViterbiDecoder712H decoder; decoder.SetPuncturePattern(PuncturePattern712_56); decoder.SetTracebackDepth(Traceback712_56); // Create input bit vector int inputBits = 260 - 8; for(int i = 0; i < inputBits; i++) { input.PushBack(rand() & 0x1); } // Force final state to zero for(int i = 0; i < 8; i++) { input.PushBack(0); } // Encode and decode data encoded = encoder.Encode(input); decoded = decoder.DecodeTerminated(encoded); assert(input == decoded); return 0; }
23
59
0.664251
[ "vector" ]
5a3414a2614aaafa4d69df5f5abe19cd539ed3ad
1,221
cpp
C++
1094.cpp
ispobock/PAT_code
1426a80ff4a8b0ddba97d9014e10b50a9cff16d6
[ "MIT" ]
1
2020-08-29T03:49:57.000Z
2020-08-29T03:49:57.000Z
1094.cpp
ispobock/PAT_code
1426a80ff4a8b0ddba97d9014e10b50a9cff16d6
[ "MIT" ]
null
null
null
1094.cpp
ispobock/PAT_code
1426a80ff4a8b0ddba97d9014e10b50a9cff16d6
[ "MIT" ]
null
null
null
#include <cstdio> #include <queue> #include <vector> using namespace std; int n, m; struct node{ int generation; vector<int> child; }Node[105]; int generation[105]; int highest = 0; void BFS(int root){ queue<int> q; q.push(root); while(!q.empty()){ int top = q.front(); q.pop(); if(highest < Node[top].generation){ highest = Node[top].generation; } generation[Node[top].generation]++; for(int i = 0; i < Node[top].child.size(); i++){ Node[Node[top].child[i]].generation = Node[top].generation + 1; q.push(Node[top].child[i]); } } } int main(){ scanf("%d %d", &n, &m); for(int i = 0; i < m; i++){ int id, k; scanf("%d %d", &id, &k); for(int j = 0; j < k; j++){ int temp; scanf("%d", &temp); Node[id].child.push_back(temp); } } Node[1].generation = 1; BFS(1); int longest = 0, longest_gen = 0; for(int i = 1; i <= highest; i++){ if(generation[i] > longest){ longest = generation[i]; longest_gen = i; } } printf("%d %d", longest, longest_gen); return 0; }
22.2
75
0.486486
[ "vector" ]
5a35aacf2ef14663bb159d1f5c86180c4f372ca5
5,520
cpp
C++
docs/api/4.1/api/axoverlay/example/opengles_objectloader/loaders.cpp
mattias-kindborg-at-work/acap-documentation
2826b4c493a1813827fc116beebce21dd06bfbd0
[ "FSFAP" ]
4
2021-09-30T10:03:16.000Z
2021-11-17T13:58:08.000Z
docs/api/4.1/api/axoverlay/example/opengles_objectloader/loaders.cpp
mattias-kindborg-at-work/acap-documentation
2826b4c493a1813827fc116beebce21dd06bfbd0
[ "FSFAP" ]
16
2021-11-17T09:30:19.000Z
2022-03-30T15:22:51.000Z
docs/api/4.1/api/axoverlay/example/opengles_objectloader/loaders.cpp
mattias-kindborg-at-work/acap-documentation
2826b4c493a1813827fc116beebce21dd06bfbd0
[ "FSFAP" ]
2
2021-11-17T09:09:06.000Z
2022-02-28T12:56:35.000Z
/* * Copyright (c) 2018 Axis Communications AB. */ #include <stdio.h> #include <string> #include <cmath> #include <stdlib.h> #include <libgen.h> #include "loaders.h" #define TINYOBJLOADER_IMPLEMENTATION #include <tiny_obj_loader.h> #include <syslog.h> #include "gl_example_errors.h" #include <glm/gtx/normal.hpp> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define D(x) if (0) { x; } static std::map<std::string, GLuint> textures; static glm::vec3 fetch(const std::vector<float> &values, int index, int components, const glm::vec3 &fallback) { if (index < 0) { index = values.size()/components + index; } if ((unsigned int)index > values.size()/components) { return fallback; } float data[3] = {0.0f, 0.0f, 0.0f}; int offset = index*components; for (int i = 0; i<components; ++i) { data[i] = values[offset + i]; } return (glm::vec3(data[0], data[1], data[2])); } static GLuint loadTexture(std::vector<tinyobj::material_t> materials, const char *filename) { GError *error = NULL; GLuint texture_id = 0; /* Append `default` material */ materials.push_back(tinyobj::material_t()); for (size_t i = 0; i < materials.size(); i++) { D(printf("material[%d].diffuse_texname = %s\n", int(i), materials[i].diffuse_texname.c_str())); } /* Load diffuse textures */ { for (size_t m = 0; m < materials.size(); m++) { tinyobj::material_t* mp = &materials[m]; if (mp->diffuse_texname.length() > 0) { // Only load the texture if it is not already loaded if (textures.find(mp->diffuse_texname) == textures.end()) { int w, h; int comp; char texture_name[100]; std::string texture_filename = mp->diffuse_texname; memset(texture_name, 0, 100); strcpy(texture_name, "/tmp/"); strcat(texture_name, texture_filename.c_str()); unsigned char* image = stbi_load(texture_name, &w, &h, &comp, STBI_rgb); if (!image) { D(printf("Unable to load texture: %s\n", texture_filename.c_str())); exit(1); } D(printf("Load texture %s w = %d h = %d comp = %d\n", texture_name, w, h, comp)); // Convert BMP from BGR to RGB format (opengles2 supports only RGB) for (int i = 0; i < w * h; i++) { char r = image[i * 3]; image[i * 3] = image[i * 3 + 2]; image[i * 3 + 2] = r; } glActiveTexture(GL_TEXTURE1); glGenTextures(1, &texture_id); check_gl_error(&error); glBindTexture(GL_TEXTURE_2D, texture_id); check_gl_error(&error); if (comp == 3) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, image); } else if (comp == 4) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, w, h, 0, GL_RGB, GL_UNSIGNED_BYTE, image); } else { assert(0); } check_gl_error(&error); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); check_gl_error(&error); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); check_gl_error(&error); stbi_image_free(image); textures.insert(std::make_pair(mp->diffuse_texname, texture_id)); } } } } return texture_id; } int loadOBJ(const char *path, std::vector<glm::vec3> &out_vertices, std::vector<glm::vec3> &out_uvs, std::vector<glm::vec3> &out_normals, GLuint *texture_param) { tinyobj::attrib_t attrib; std::vector<tinyobj::shape_t> shapes; std::vector<tinyobj::material_t> materials; std::string err; std::string warn; glm::vec3 temp_vertices; bool ret = tinyobj::LoadObj(&attrib, &shapes, &materials, &warn, &err, path); if (!ret) { fprintf(stderr, "Failed to load %s: %s\n", path, err.c_str()); return 0; } if (shapes.size() != 1) { fprintf(stderr, "Expected %s to contain exactly one shape, but was %zu\n", path, shapes.size()); return 0; } out_vertices.clear(); out_uvs.clear(); out_normals.clear(); size_t index_offset = 0; /* For each face */ for (size_t f = 0; f < shapes[0].mesh.num_face_vertices.size(); f++) { size_t fnum = shapes[0].mesh.num_face_vertices[f]; if (fnum != 3) { fprintf(stderr, "Expected all faces to be triangles but face %zu has %zu vertices\n", f, fnum); return 0; } for (size_t v = 0; v < fnum; v++) { temp_vertices = fetch(attrib.vertices, shapes[0].mesh.indices[index_offset + v].vertex_index, 3, (glm::vec3){0,0,0}); out_vertices.push_back(temp_vertices); } for (size_t v = 0; v < fnum; v++) { out_uvs.push_back(fetch(attrib.texcoords, shapes[0].mesh.indices[index_offset + v].texcoord_index, 2, (glm::vec3){0,0,0})); } glm::vec3 triangleNormal = glm::triangleNormal(out_vertices[out_vertices.size()-3], out_vertices[out_vertices.size()-2], out_vertices[out_vertices.size()-1]); for (size_t v = 0; v < fnum; v++) { out_normals.push_back(fetch(attrib.normals, shapes[0].mesh.indices[index_offset + v].normal_index, 3, triangleNormal)); } index_offset += fnum; } size_t n = out_vertices.size() / 3; D(printf("Number of triangles: %zu\n", n)); *texture_param = loadTexture(materials, path); return n; }
27.738693
129
0.595471
[ "mesh", "shape", "vector" ]
5a3d216a68b6611bcab0f2248554546f6d204ab7
4,818
cpp
C++
CppP4rhSln/16/overcomp.cpp
blacop/CppPR
a76574ee83000d898d989aab96eac4ac746244fa
[ "MIT" ]
1
2017-04-01T06:57:30.000Z
2017-04-01T06:57:30.000Z
gnu_files/16/overcomp.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
gnu_files/16/overcomp.cc
hongmi/cpp-primer-4-exercises
98ddb98b41d457a1caa525d246dfb7453be0c8d2
[ "MIT" ]
null
null
null
/* * This file contains code from "C++ Primer, Fourth Edition", by Stanley B. * Lippman, Jose Lajoie, and Barbara E. Moo, and is covered under the * copyright and warranty notices given in that book: * * "Copyright (c) 2005 by Objectwrite, Inc., Jose Lajoie, and Barbara E. Moo." * * * "The authors and publisher have taken care in the preparation of this book, * but make no expressed or implied warranty of any kind and assume no * responsibility for errors or omissions. No liability is assumed for * incidental or consequential damages in connection with or arising out of the * use of the information or programs contained herein." * * Permission is granted for this code to be used for educational purposes in * association with the book, given proper citation if and when posted or * reproduced.Any commercial use of this code requires the explicit written * permission of the publisher, Addison-Wesley Professional, a division of * Pearson Education, Inc. Send your request for permission, stating clearly * what code you would like to use, and in what specific way, to the following * address: * * Pearson Education, Inc. * Rights and Contracts Department * 75 Arlington Street, Suite 300 * Boston, MA 02216 * Fax: (617) 848-7047 */ #include <vector> using std:: vector; #include <iostream> using std::cout; using std::endl; #include <string> using std::string; // implement strcmp-like generic compare function template <typename T> int compare2(T, T); template <typename T> int compare2(T v1, T v2) { // as before cout << "compare2(T, T)" << endl; if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; } // plain functions to handle C-style character strings int compare2(const char* v1, const char* v2) { cout << "compare2(const char*, const char*)" << endl; return strcmp(v1, v2); } // compares two objects template <typename T> int compare(const T&, const T&); // compares elements in two sequences template <class U, class V> int compare(U, U, V); // plain functions to handle C-style character strings int compare(const char*, const char*); // compares two objects template <typename T> int compare(const T &v1, const T &v2) { cout << "compare(const T&, const T&)" << endl; if (v1 < v2) return -1; if (v2 < v1) return 1; return 0; } // compares elements in two sequences template <class U, class V> int compare(U beg1, U end1, V beg2) { cout << "compare(U, U, V)" << endl; while (beg1 != end1) { if (*beg1 < *beg2) return -1; if (*beg2 < *beg1) return 1; ++beg1; ++beg2; } return 0; // if we got here, the two sequences are equal } // plain functions to handle C-style character strings int compare(const char* v1, const char* v2) { cout << "compare(const char*, const char*)" << endl; return strcmp(v1, v2); } int main() { cout << "calling compare(1, 0);" << endl; // calls compare(const T&, const T&) with T bound to int compare(1, 0); cout << "\ncalling compare(vector iters);" << endl; // calls compare(U, U, V), with U and V bound to vector<int>::iterator vector<int> ivec1(10), ivec2(20); compare(ivec1.begin(), ivec1.end(), ivec2.begin()); int ia1[] = {0,1,2,3,4,5,6,7,8,9}; // calls compare(U, U, V) with U bound to int* // and V bound to vector<int>::iterator compare(ia1, ia1 + 10, ivec1.begin()); cout << "\ncalling compare(const_arr1, const_arr2);" << endl; // calls the ordinary function taking const char* parameters const char const_arr1[] = "world", const_arr2[] = "hi"; compare(const_arr1, const_arr2); cout << "\ncalling compare(s1, s2);" << endl; // calls compare(const T&,const T&) with T bound to string string s1 = "hi", s2 = "world"; compare(s1, s2); cout << "\ncalling compare(ch_arr1, ch_arr2);" << endl; // calls the ordinary function taking const char* parameters char ch_arr1[] = "world", ch_arr2[] = "hi"; compare(ch_arr1, ch_arr2); cout << "\ncalling compare(p1, p2);" << endl; char *p1 = ch_arr1, *p2 = ch_arr2; compare(p1, p2); cout << "\ncalling compare(ch_arr1, const_arr1);" << endl; cout << "calling compare(ch_arr2, const_arr1);" << endl; cout << "calling compare(0, 0);" << endl; compare(ch_arr1, const_arr1); compare(ch_arr2, const_arr2); compare(0, 0); cout << "\ncalling compare2(ch_arr1, ch_arr2);" << endl; cout << "calling compare2(p1, p2);" << endl; cout << "calling compare(const_arr1, const_arr2);" << endl; cout << "calling compare(cp1, cp2);" << endl; // calls compare2(T, T) with T bound to char* compare2(ch_arr1, ch_arr2); // calls compare2(T, T) with T bound to char* compare2(p1, p2); // calls the ordinary function taking const char* parameters compare2(const_arr1, const_arr2); const char *cp1 = const_arr1, *cp2 = const_arr2; // calls the ordinary function taking const char* parameters compare2(cp1, cp2); return 0; }
29.558282
79
0.684101
[ "vector" ]
5a3e5b5885e3869890aaa16b3b191f7885a06c25
10,185
cpp
C++
tensorflow_graphics/projects/point_convolutions/custom_ops/tfg_custom_ops/sampling/cc/ops/sampling_ops.cpp
schellmi42/graphics
2e705622c2a6b0007347d2db154ccdf5a0eb73d4
[ "Apache-2.0" ]
3
2020-07-10T12:07:02.000Z
2022-03-21T09:28:55.000Z
custom_ops/tfg_custom_ops/sampling/cc/ops/sampling_ops.cpp
schellmi42/tensorflow_graphics_point_clouds
c8e2dc2963c3eecfb27542449603f81d78494783
[ "Apache-2.0" ]
null
null
null
custom_ops/tfg_custom_ops/sampling/cc/ops/sampling_ops.cpp
schellmi42/tensorflow_graphics_point_clouds
c8e2dc2963c3eecfb27542449603f81d78494783
[ "Apache-2.0" ]
1
2021-10-11T08:27:44.000Z
2021-10-11T08:27:44.000Z
///////////////////////////////////////////////////////////////////////////// /// Copyright 2020 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 /// /// https://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. ///////////////////////////////////////////////////////////////////////////// /// \brief C++ operations definition to perform a sample operation in a point /// cloud. ///////////////////////////////////////////////////////////////////////////// #include "tfg_custom_ops/shared/cc/kernels/defines.hpp" #include "tfg_custom_ops/shared/cc/kernels/tf_utils.hpp" #include "tfg_custom_ops/shared/cc/kernels/tf_gpu_device.hpp" #include "tfg_custom_ops/sampling/cc/kernels/count_unique_keys.h" #include "tfg_custom_ops/sampling/cc/kernels/store_unique_keys.h" #include "tfg_custom_ops/sampling/cc/kernels/sampling_avg.h" #include "tfg_custom_ops/sampling/cc/kernels/count_sampling_pd.h" #include "tfg_custom_ops/sampling/cc/kernels/store_sampled_pts.h" /** * Declaration of the tensorflow operation. */ REGISTER_OP("Sampling") .Input("points: float32") .Input("batch_ids: int32") .Input("point_keys: int64") .Input("num_cells: int32") .Input("neighbors: int32") .Input("sample_neigh_indices: int32") .Output("sample_pts: float32") .Output("sample_batch_ids: int32") .Output("sample_indices: int32") .Attr("mode: int") .SetShapeFn([](shape_inference::InferenceContext* pIC) { shape_inference::ShapeHandle outputDims1 = pIC->MakeShape({-1, pIC->Dim(pIC->input(0), 1)}); shape_inference::ShapeHandle outputDims2 = pIC->MakeShape({-1}); pIC->set_output(0, outputDims1); pIC->set_output(1, outputDims2); pIC->set_output(2, outputDims2); return Status::OK(); }); namespace mccnn{ /** * Operation to perform a sampling operation on a regular grid. */ class SamplingOp: public OpKernel{ public: /** * Constructor. * @param pContext Constructor context of the operation. */ explicit SamplingOp( OpKernelConstruction* pContext) :OpKernel(pContext){ OP_REQUIRES_OK(pContext, pContext->GetAttr("mode", &mode_)); OP_REQUIRES(pContext, mode_ >= 0 && mode_ < 2, errors::InvalidArgument("SamplingOp requires a valid sampling mode.")); } /** * Method to compute the operation. * @param pContext Context of the operation. */ void Compute(OpKernelContext * pContext) override{ //Get the input tensors. const Tensor& inPts = pContext->input(0); const Tensor& inBatchIds = pContext->input(1); const Tensor& inPtKeys = pContext->input(2); const Tensor& inNumCells = pContext->input(3); const Tensor& inNeighbors = pContext->input(4); const Tensor& inStartNeighIds = pContext->input(5); //Get variables from tensors. unsigned int numPts = inPts.shape().dim_size(0); unsigned int numDimensions = inPts.shape().dim_size(1); unsigned int numNeighbors = inNeighbors.shape().dim_size(0); //Get the pointers to GPU data from the tensors. const float* ptsGPUPtr = mccnn::tensorflow_utils::get_const_tensor_pointer<float>(inPts); const int* batchIdsGPUPtr = mccnn::tensorflow_utils::get_const_tensor_pointer<int>(inBatchIds); const mccnn::int64_m* ptKeysGPUPtr = mccnn::tensorflow_utils:: get_const_tensor_pointer<mccnn::int64_m>(inPtKeys); const int* numCellsGPUPtr = mccnn::tensorflow_utils::get_const_tensor_pointer<int>(inNumCells); const int* inNeighborsGPUPtr = mccnn::tensorflow_utils::get_const_tensor_pointer<int>(inNeighbors); const int* inStartNeighIdsGPUPtr = mccnn::tensorflow_utils::get_const_tensor_pointer<int>(inStartNeighIds); //Check for the correctness of the input. OP_REQUIRES(pContext, numDimensions >= MIN_DIMENSIONS && numDimensions <= MAX_DIMENSIONS, errors::InvalidArgument("SamplingOp expects a valid number of dimension")); OP_REQUIRES(pContext, inBatchIds.shape().dim_size(0) == numPts, errors::InvalidArgument("SamplingOp expects the same number of keys" " as number of points.")); OP_REQUIRES(pContext, inPtKeys.shape().dim_size(0) == numPts, errors::InvalidArgument("SamplingOp expects the same number of keys" " as number of points.")); OP_REQUIRES(pContext, inNumCells.shape().dim_size(0) == numDimensions, errors::InvalidArgument("SamplingOp expects a number of dimensions in" " inNumCells equal to the number of dimensions in the input points")); OP_REQUIRES(pContext, inNeighbors.dims() == 2 && inNeighbors.shape().dim_size(1) == 2, errors::InvalidArgument("SamplingOp expects a neighbor tensor with 2 dimensions " "and 2 indices per neighbor.")); OP_REQUIRES(pContext, inStartNeighIds.shape().dim_size(0) == numPts, errors::InvalidArgument("SamplingOp expects the same number of points " "in inStartNeighIds as in the points tensor.")); //Get the gpu device. std::unique_ptr<mccnn::IGPUDevice> gpuDevice = make_unique<mccnn::TFGPUDevice>(pContext); //Count the number of unique keys. unsigned int numKeys = mccnn::count_unique_keys_gpu(gpuDevice, numPts, ptKeysGPUPtr); //Declare the temporal buffers. int* tmpGPUPtr1 = gpuDevice->getIntTmpGPUBuffer(numKeys); //Store the first indices of each key. mccnn::store_unique_keys_gpu(gpuDevice, numPts, ptKeysGPUPtr, tmpGPUPtr1); //Poisson disk sampling. if(mode_ == 0){ //Declare temporal buffers. int* tmpGPUPtr2 = gpuDevice->getIntTmpGPUBuffer(numPts); //Count the number of sampleed points. int numSampledPts; DIMENSION_SWITCH_CALL(numDimensions, mccnn::count_sampling_pd_gpu, gpuDevice, numPts, numKeys, tmpGPUPtr1, ptKeysGPUPtr, ptsGPUPtr, inNeighborsGPUPtr, inStartNeighIdsGPUPtr, numCellsGPUPtr, numSampledPts, tmpGPUPtr2); //Create the output tensors. float* outPtsGPUPtr = nullptr; int* outBatchIdsGPUPtr = nullptr; int* outIndicesGPUPtr = nullptr; TensorShape outShape1 = TensorShape{numSampledPts, numDimensions}; TensorShape outShape2 = TensorShape{numSampledPts}; TensorShape outShape3 = TensorShape{numSampledPts}; OP_REQUIRES_OK(pContext, mccnn::tensorflow_utils::allocate_output_tensor<float> (0, pContext, outShape1, &outPtsGPUPtr)); OP_REQUIRES_OK(pContext, mccnn::tensorflow_utils::allocate_output_tensor<int> (1, pContext, outShape2, &outBatchIdsGPUPtr)); OP_REQUIRES_OK(pContext, mccnn::tensorflow_utils::allocate_output_tensor<int> (2, pContext, outShape3, &outIndicesGPUPtr)); //Store the sampled points. DIMENSION_SWITCH_CALL(numDimensions, mccnn::store_sampled_pts_gpu, gpuDevice, numPts, numSampledPts, ptsGPUPtr, batchIdsGPUPtr, tmpGPUPtr2, outPtsGPUPtr, outBatchIdsGPUPtr, outIndicesGPUPtr); //Cell average. }else{ //Create the output tensors. float* outPtsGPUPtr = nullptr; int* outBatchIdsGPUPtr = nullptr; int* outIndicesGPUPtr = nullptr; TensorShape outShape1 = TensorShape{numKeys, numDimensions}; TensorShape outShape2 = TensorShape{numKeys}; TensorShape outShape3 = TensorShape{1}; OP_REQUIRES_OK(pContext, mccnn::tensorflow_utils::allocate_output_tensor<float> (0, pContext, outShape1, &outPtsGPUPtr)); OP_REQUIRES_OK(pContext, mccnn::tensorflow_utils::allocate_output_tensor<int> (1, pContext, outShape2, &outBatchIdsGPUPtr)); OP_REQUIRES_OK(pContext, mccnn::tensorflow_utils::allocate_output_tensor<int> (2, pContext, outShape3, &outIndicesGPUPtr)); //Select the new point. DIMENSION_SWITCH_CALL(numDimensions, mccnn::sampling_avg_gpu, gpuDevice, numPts, numKeys, ptKeysGPUPtr, ptsGPUPtr, numCellsGPUPtr, tmpGPUPtr1, outPtsGPUPtr, outBatchIdsGPUPtr); } } private: /**Mode used to sample points.*/ int mode_; }; } REGISTER_KERNEL_BUILDER(Name("Sampling").Device(DEVICE_GPU), mccnn::SamplingOp);
49.926471
123
0.580265
[ "shape" ]
5a3e8f5bcd053ad9f07507ea2a12e90cb57836f3
1,227
hpp
C++
bofrak.hpp
supudo/bofrak
0a94a2cffea24bf84193fd6ba039cff0cc17b7fb
[ "Unlicense" ]
null
null
null
bofrak.hpp
supudo/bofrak
0a94a2cffea24bf84193fd6ba039cff0cc17b7fb
[ "Unlicense" ]
null
null
null
bofrak.hpp
supudo/bofrak
0a94a2cffea24bf84193fd6ba039cff0cc17b7fb
[ "Unlicense" ]
null
null
null
#ifndef Bofrak_hpp #define Bofrak_hpp #include <thread> #include <glm/glm.hpp> #include "utilities/gl/glincludes.hpp" #include "utilities/input/controls.hpp" #include "settings/settings.hpp" #include "objects/camera.hpp" #include "ui/uimanager.hpp" #include "objects/fractal.hpp" class Bofrak { public: Bofrak(); ~Bofrak(); int run(); private: bool init(); void onEvent(SDL_Event* ev); void doLog(std::string const& logMessage); void initFolders(); void renderScene(); void guiQuit(); // Screen dimension constants const char *WINDOW_TITLE = "Bofrak"; const unsigned int WINDOW_POSITION_X = SDL_WINDOWPOS_CENTERED; const unsigned int WINDOW_POSITION_Y = SDL_WINDOWPOS_CENTERED; // SDLs SDL_Window *sdlWindow = NULL; SDL_GLContext glContext; // Variables bool appIsRunning = false; // Customs std::unique_ptr<Controls> managerControls; std::unique_ptr<UIManager> managerUI; // 3d float Setting_FOV = 45.0; float Setting_RatioWidth = 4.0f, Setting_RatioHeight = 3.0f; float Setting_PlaneClose = 0.1f, Setting_PlaneFar = 100.0f; glm::mat4 matrixProjection; // objects std::unique_ptr<Camera> oCamera; std::unique_ptr<Fractal> oFractal; }; #endif /* Bofrak_hpp */
22.309091
64
0.727791
[ "3d" ]
5a44d9b3edce364c1f09dbafcf228478197dc996
11,732
hpp
C++
pennylane_lightning_gpu/src/simulator/StateVectorCudaBase.hpp
PennyLaneAI/pennylane-lightning-gpu
1b2a361f68c8580457e61cc706d644c4cbfe04ad
[ "Apache-2.0" ]
9
2022-03-14T15:18:08.000Z
2022-03-30T03:05:36.000Z
pennylane_lightning_gpu/src/simulator/StateVectorCudaBase.hpp
PennyLaneAI/pennylane-lightning-gpu
1b2a361f68c8580457e61cc706d644c4cbfe04ad
[ "Apache-2.0" ]
6
2022-03-18T13:44:10.000Z
2022-03-31T22:07:25.000Z
pennylane_lightning_gpu/src/simulator/StateVectorCudaBase.hpp
PennyLaneAI/pennylane-lightning-gpu
1b2a361f68c8580457e61cc706d644c4cbfe04ad
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 Xanadu Quantum Technologies Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file StateVectorCudaBase.hpp */ #pragma once #include "cuda.h" #include <cuda_runtime_api.h> // cudaMalloc, cudaMemcpy, etc. #include <type_traits> #include <unordered_map> #include <unordered_set> #include "Error.hpp" #include "StateVectorBase.hpp" #include "StateVectorManagedCPU.hpp" #include "cuda_helpers.hpp" /// @cond DEV namespace { namespace cuUtil = Pennylane::CUDA::Util; } // namespace /// @endcond namespace Pennylane { /** * @brief CRTP-enabled base class for CUDA-capable state-vector simulators. * * @tparam Precision Floating point precision. * @tparam Derived Derived class to instantiate using CRTP. */ template <class Precision, class Derived> class StateVectorCudaBase : public StateVectorBase<Precision, Derived> { private: using BaseType = StateVectorBase<Precision, Derived>; public: /// Alias for accessing the class templated precision type using scalar_type_t = Precision; /// Alias for complex floating point datatype supported by class using CFP_t = decltype(cuUtil::getCudaType(Precision{})); /** * @brief Return a pointer to the GPU data. * * @return const CFP_t* Complex device pointer. */ [[nodiscard]] auto getData() const -> CFP_t * { return data_; } /** * @brief Return a pointer to the GPU data. * * @return CFP_t* Complex device pointer. */ [[nodiscard]] auto getData() -> CFP_t * { return data_; } /** * @brief Get the CUDA stream for the given object. * * @return cudaStream_t& */ inline auto getStream() -> cudaStream_t & { return stream_; } /** * @brief Get the CUDA stream for the given object. * * @return const cudaStream_t& */ inline auto getStream() const -> const cudaStream_t & { return stream_; } void setStream(const cudaStream_t &s) { stream_ = s; } /** * @brief Explicitly copy data from host memory to GPU device. * * @param sv StateVector host data class. */ inline void CopyHostDataToGpu(const StateVectorManagedCPU<Precision> &sv, bool async = false) { PL_ABORT_IF_NOT(BaseType::getNumQubits() == sv.getNumQubits(), "Sizes do not match for Host and GPU data"); CopyHostDataToGpu(sv.getData(), sv.getLength(), async); } /** * @brief Explicitly copy data from host memory to GPU device. * * @param sv StateVector host data class. */ inline void CopyHostDataToGpu(const std::vector<std::complex<Precision>> &sv, bool async = false) { PL_ABORT_IF_NOT(BaseType::getLength() == sv.size(), "Sizes do not match for Host and GPU data"); CopyHostDataToGpu(sv.data(), sv.size(), async); } /** * @brief Explicitly copy data from host memory to GPU device. * * @param host_sv Complex data pointer to array. * @param length Number of complex elements. */ inline void CopyGpuDataToGpuIn(const CFP_t *gpu_sv, std::size_t length, bool async = false) { PL_ABORT_IF_NOT(BaseType::getLength() == length, "Sizes do not match for Host and GPU data"); if (!async) { PL_CUDA_IS_SUCCESS(cudaMemcpy(data_, gpu_sv, sizeof(CFP_t) * BaseType::getLength(), cudaMemcpyDefault)); } else { PL_CUDA_IS_SUCCESS(cudaMemcpyAsync( data_, gpu_sv, sizeof(CFP_t) * BaseType::getLength(), cudaMemcpyDeviceToDevice, stream_)); } } /** * @brief Explicitly copy data from host memory to GPU device. * * @param host_sv Complex data pointer to array. * @param length Number of complex elements. */ inline void CopyHostDataToGpu(const std::complex<Precision> *host_sv, std::size_t length, bool async = false) { PL_ABORT_IF_NOT(BaseType::getLength() == length, "Sizes do not match for Host and GPU data"); if (!async) { PL_CUDA_IS_SUCCESS(cudaMemcpy( data_, reinterpret_cast<const CFP_t *>(host_sv), sizeof(CFP_t) * BaseType::getLength(), cudaMemcpyDefault)); } else { PL_CUDA_IS_SUCCESS( cudaMemcpyAsync(data_, reinterpret_cast<const CFP_t *>(host_sv), sizeof(CFP_t) * BaseType::getLength(), cudaMemcpyHostToDevice, stream_)); } } /** * @brief Explicitly copy data from GPU device to host memory. * * @param sv StateVector to receive data from device. */ inline void CopyGpuDataToHost(StateVectorManagedCPU<Precision> &sv, bool async = false) const { PL_ABORT_IF_NOT(BaseType::getNumQubits() == sv.getNumQubits(), "Sizes do not match for Host and GPU data"); if (!async) { PL_CUDA_IS_SUCCESS(cudaMemcpy(sv.getData(), data_, sizeof(CFP_t) * sv.getLength(), cudaMemcpyDefault)); } else { PL_CUDA_IS_SUCCESS(cudaMemcpyAsync( sv.getData(), data_, sizeof(CFP_t) * sv.getLength(), cudaMemcpyDeviceToHost, stream_)); } } /** * @brief Explicitly copy data from GPU device to host memory. * * @param sv Complex data pointer to receive data from device. */ inline void CopyGpuDataToHost(std::complex<Precision> *host_sv, size_t length, bool async = false) const { PL_ABORT_IF_NOT(BaseType::getLength() == length, "Sizes do not match for Host and GPU data"); if (!async) { PL_CUDA_IS_SUCCESS(cudaMemcpy(host_sv, data_, sizeof(CFP_t) * length, cudaMemcpyDeviceToHost)); } else { PL_CUDA_IS_SUCCESS( cudaMemcpyAsync(host_sv, data_, sizeof(CFP_t) * length, cudaMemcpyDeviceToHost, getStream())); } } /** * @brief Explicitly copy data from this GPU device to another GPU device * memory block. * * @param sv LightningGPU object to receive data. */ inline void CopyGpuDataToGpuOut(Derived &sv, bool async = false) { PL_ABORT_IF_NOT(BaseType::getNumQubits() == sv.getNumQubits(), "Sizes do not match for Host and GPU data"); if (!async) { PL_CUDA_IS_SUCCESS(cudaMemcpy(sv.getData(), data_, sizeof(CFP_t) * sv.getLength(), cudaMemcpyDeviceToDevice)); } else { PL_CUDA_IS_SUCCESS(cudaMemcpyAsync( sv.getData(), data_, sizeof(CFP_t) * sv.getLength(), cudaMemcpyDeviceToDevice, getStream())); } } /** * @brief Explicitly copy data from antoher GPU device memory block to this * GPU device. * * @param sv LightningGPU object to send data. */ inline void CopyGpuDataToGpuIn(const Derived &sv, bool async = false) { PL_ABORT_IF_NOT(BaseType::getNumQubits() == sv.getNumQubits(), "Sizes do not match for Host and GPU data"); PL_ABORT_IF_NOT(typeid(data_) == typeid(sv.getData()), "Data types are incompatible for GPU-GPU transfer"); if (!async) { PL_CUDA_IS_SUCCESS(cudaMemcpy(data_, sv.getData(), sizeof(CFP_t) * sv.getLength(), cudaMemcpyDeviceToDevice)); } else { PL_CUDA_IS_SUCCESS(cudaMemcpyAsync( data_, sv.getData(), sizeof(CFP_t) * sv.getLength(), cudaMemcpyDeviceToDevice, getStream())); } } /** * @brief Update GPU device data from given derived object. * * @param other Source data to copy from. * @param async Use asynchronous copies. */ void updateData(const Derived &other, bool async = false) { CopyGpuDataToGpuIn(other, async); } /** * @brief Initialize the statevector data to the |0...0> state * */ void initSV(bool async = false) { std::vector<std::complex<Precision>> data(BaseType::getLength(), {0, 0}); data[0] = {1, 0}; CopyHostDataToGpu(data.data(), data.size(), async); } protected: using ParFunc = std::function<void(const std::vector<size_t> &, bool, const std::vector<Precision> &)>; using FMap = std::unordered_map<std::string, ParFunc>; StateVectorCudaBase(size_t num_qubits, cudaStream_t stream, bool device_alloc = true) : StateVectorBase<Precision, Derived>(num_qubits), stream_{stream} { if (device_alloc && num_qubits > 0) { PL_CUDA_IS_SUCCESS( cudaMalloc(reinterpret_cast<void **>(&data_), sizeof(CFP_t) * Util::exp2(num_qubits))); } } StateVectorCudaBase(size_t num_qubits) : StateVectorCudaBase(num_qubits, 0, true) {} StateVectorCudaBase() = delete; virtual ~StateVectorCudaBase() { PL_CUDA_IS_SUCCESS(cudaFree(data_)); }; /** * @brief Return the mapping of named gates to amount of control wires they * have. * * @return const std::unordered_map<std::string, std::size_t>& */ auto getCtrlMap() -> const std::unordered_map<std::string, std::size_t> & { return ctrl_map_; } /** * @brief Utility method to get the mappings from gate to supported wires. * * @return const std::unordered_map<std::string, std::size_t>& */ auto getParametricGatesMap() -> const std::unordered_map<std::string, std::size_t> & { return ctrl_map_; } private: cudaStream_t stream_; int device_id_; CFP_t *data_; const std::unordered_set<std::string> const_gates_{ "Identity", "PauliX", "PauliY", "PauliZ", "Hadamard", "T", "S", "CNOT", "SWAP", "CZ", "CSWAP", "Toffoli"}; const std::unordered_map<std::string, std::size_t> ctrl_map_{ // Add mapping from function name to required wires. {"Identity", 0}, {"PauliX", 0}, {"PauliY", 0}, {"PauliZ", 0}, {"Hadamard", 0}, {"T", 0}, {"S", 0}, {"RX", 0}, {"RY", 0}, {"RZ", 0}, {"Rot", 0}, {"PhaseShift", 0}, {"ControlledPhaseShift", 1}, {"CNOT", 1}, {"SWAP", 0}, {"CZ", 1}, {"CRX", 1}, {"CRY", 1}, {"CRZ", 1}, {"CRot", 1}, {"CSWAP", 1}, {"Toffoli", 2}}; }; } // namespace Pennylane
36.098462
80
0.568701
[ "object", "vector" ]
5a4f306f2e9be3fd9e1e261b6c3c47b605b6b303
18,360
cpp
C++
source/guise/font.cpp
jimmiebergmann/Guise
b6b16de961f4299e2384980db11a0a811f01eaf4
[ "MIT" ]
1
2020-09-06T10:35:58.000Z
2020-09-06T10:35:58.000Z
source/guise/font.cpp
jimmiebergmann/Guise
b6b16de961f4299e2384980db11a0a811f01eaf4
[ "MIT" ]
null
null
null
source/guise/font.cpp
jimmiebergmann/Guise
b6b16de961f4299e2384980db11a0a811f01eaf4
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019 Jimmie Bergmann * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files(the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions : * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include "guise/font.hpp" #include <map> #include <unordered_map> #include <vector> #include <fstream> #include <limits> #include <algorithm> #include <iostream> #include "freetype/FreeTypeAmalgam.h" namespace Guise { static inline uint64_t getGlyphIndex(const wchar_t character, const uint32_t height) { return static_cast<uint64_t>(character) | (static_cast<uint64_t>(height) << 32); } static inline wchar_t getCharacterFromGlypthIndex(const uint64_t index) { return static_cast<wchar_t>(index & uint64_t(0xFFFFFFFFUL)); } static inline uint32_t getHeightFromGlypthIndex(const uint64_t index) { return static_cast<uint32_t>((index >> 32) & uint64_t(0xFFFFFFFFUL)); } struct Glyph { Glyph(const FT_UInt index, FT_BitmapGlyph bitmapGlyph, const FT_Pos baseline, const FT_Pos horiAdvance, const FT_Pos horiBearingX, const FT_Pos horiBearingY) : index(index), bitmapGlyph(bitmapGlyph), baseline(baseline), horiAdvance(horiAdvance), horiBearingX(horiBearingX), horiBearingY(horiBearingY) { } ~Glyph() { FT_Done_Glyph(reinterpret_cast<FT_Glyph>(bitmapGlyph)); } FT_UInt index; FT_BitmapGlyph bitmapGlyph; FT_Pos baseline; FT_Pos horiAdvance; FT_Pos horiBearingX; FT_Pos horiBearingY; }; // Font implementations. struct Font::Impl { Impl() : dataSize(0), library(nullptr), face(nullptr), currentFontSize(0) { } ~Impl() { if (library) { glyphs.clear(); FT_Done_FreeType(library); } } Glyph * getGlypth(const wchar_t character, const uint32_t height) { auto mapIndex = getGlyphIndex(character, height); auto it = glyphs.find(mapIndex); if (it != glyphs.end()) { return it->second.get(); } FT_Error error = 0; FT_UInt index = 0; if ((index = FT_Get_Char_Index(face, static_cast<FT_ULong>(character))) == 0) { // "Can not get the character index" return nullptr; } if ((error = FT_Load_Glyph(face, index, FT_LOAD_RENDER)) != 0) { // "Can not load the character" return nullptr; } auto & metrics = face->glyph->metrics; FT_GlyphSlot slot = face->glyph; FT_Glyph glyph; if ((error = FT_Get_Glyph(slot, &glyph)) != 0) { // "Can not get the glyph" return nullptr; } FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1); auto bitmapGlyph = reinterpret_cast<FT_BitmapGlyph>(glyph); const FT_Pos baseline = (metrics.height >> 6) - (metrics.horiBearingY >> 6); auto newIt = glyphs.insert({ mapIndex, std::make_unique<Glyph>(index, bitmapGlyph, baseline, metrics.horiAdvance >> 6, metrics.horiBearingX >> 6, metrics.horiBearingY >> 6) }); return newIt.first->second.get(); } std::unique_ptr<uint8_t[]> data; size_t dataSize; FT_Library library; FT_Face face; std::map<uint64_t, std::unique_ptr<Glyph> > glyphs; uint32_t currentFontSize; }; std::shared_ptr<Font> Font::create(const std::string & font) { return std::shared_ptr<Font>(new Font(font)); } Font::~Font() { } bool Font::isValid() const { return m_isValid; } float Font::getVerticalMax() const { return m_verticalMax; } float Font::getVerticalMin() const { return m_verticalMin; } Font::Font(const std::string & font) : m_isValid(false), m_verticalMax(0.0f), m_verticalMin(0.0f), m_impl(std::make_shared<Impl>()) { // Try to open font as path. if (!readFile(font, m_impl->data, m_impl->dataSize)) { // Try to open file as font family. std::string systemFontPath = getFontPath(font); if (!systemFontPath.size() || !readFile(systemFontPath, m_impl->data, m_impl->dataSize)) { return; } } FT_Error error = 0; if ((error = FT_Init_FreeType(&(m_impl->library))) != 0) { // "Failed to initialize the FreeType library, error code: %i\n", FTError); return; } // Load face from memory. if ((error = FT_New_Memory_Face(m_impl->library, reinterpret_cast<FT_Byte *>(m_impl->data.get()), m_impl->dataSize, 0, &(m_impl->face))) != 0) { // "Failed to load font: %s, FreeType error: %i\n", p_pFileName, FTError); return; } // Select the unicode character map if ((error = FT_Select_Charmap(m_impl->face, FT_ENCODING_UNICODE)) != 0) { // "Can not select the unicode character map, FreeType error: %i\n", FTError); return; } const auto & bbox = m_impl->face->bbox; const float unitsPerEm = static_cast<float>(m_impl->face->units_per_EM); m_verticalMax = static_cast<float>(bbox.yMax) / unitsPerEm; m_verticalMin = static_cast<float>(bbox.yMin) / unitsPerEm; m_isValid = true; } bool Font::readFile(const std::string & path, std::unique_ptr<uint8_t[]> & data, size_t & dataSize) const { std::ifstream file(path, std::ifstream::binary); if (!file.is_open()) { return false; } file.seekg(0, std::fstream::end); dataSize = static_cast<size_t>(file.tellg()); if (!dataSize) { return false; } file.seekg(0, std::fstream::beg); data = std::make_unique<uint8_t[]>(dataSize); file.read(reinterpret_cast<char*>(data.get()), dataSize); return true; } std::string Font::getFontPath(const std::string & font) const { #if defined(GUISE_PLATFORM_WINDOWS) char * charPath = nullptr; size_t len = 0; errno_t err = _dupenv_s(&charPath, &len, "windir"); if (err || !charPath) { return ""; } std::string path = std::string(charPath) + "\\Fonts\\" + font + ".ttf"; free(charPath); return path; #elif defined(GUISE_PLATFORM_LINUX) return ""; #endif } // Glyph sequence implementations. struct FontSequence::Impl { Impl() : size(0, 0) { } Impl(std::shared_ptr<Font> & font) : font(font), size(0, 0), baseline(0) { } struct GlyphData { Bounds1i32 bounds; Glyph * glyph; }; std::shared_ptr<Font> font; std::vector<GlyphData> sequence; Vector2<size_t> size; Vector2<FT_Pos> lowDim; Vector2<FT_Pos> highDim; int32_t baseline; }; FontSequence::FontSequence() { } FontSequence::FontSequence(std::shared_ptr<Font> & font) : m_impl(std::make_shared<Impl>(font)) { } float FontSequence::calcVerticalPosition(const float height) const { const float vMax = m_impl->font->getVerticalMax(); const float vMin = m_impl->font->getVerticalMin(); const float vNorm = 1.0f - ((-vMin) / (vMax - vMin)); return (height * vNorm) - static_cast<float>(m_impl->size.y) + static_cast<float>(m_impl->baseline); } bool FontSequence::createSequence(const std::wstring & text, const uint32_t height, const uint32_t dpi) { m_impl->sequence.clear(); m_impl->size = {0, 0}; m_impl->lowDim = { std::numeric_limits<FT_Pos>::max(), std::numeric_limits<FT_Pos>::max() }; m_impl->highDim = { std::numeric_limits<FT_Pos>::min(), std::numeric_limits<FT_Pos>::min() }; m_impl->baseline = 0; const uint32_t fontSize = height * dpi / GUISE_DEFAULT_DPI; if (!text.size() || !fontSize || !m_impl->font || !m_impl->font->isValid()) { return false; } const auto fontImpl = m_impl->font->m_impl; FT_Error error = 0; if (fontSize != fontImpl->currentFontSize) { if ((error = FT_Set_Char_Size(fontImpl->face, 0, height * 64, dpi, dpi)) != 0) { // "Can not setup the font size, FreeType error: %i\n", FTError); return false; } fontImpl->currentFontSize = fontSize; } FT_Pos penPos = 0; FT_Pos prevPenPos = 0; const bool hasKerning = FT_HAS_KERNING(fontImpl->face); FT_UInt prevIndex = 0; // Calcualte text bounding box and pen start position. for (size_t i = 0; i < text.size(); i++) { auto glyph = fontImpl->getGlypth(text[i], fontSize); if (!glyph) { glyph = fontImpl->getGlypth(L' ', fontSize); } if (glyph) { //glyphs.push_back(glyph); auto & bitmap = glyph->bitmapGlyph->bitmap; // Move pen if font has kerning. if (hasKerning && prevIndex) { FT_Vector delta; FT_Get_Kerning(fontImpl->face, prevIndex, glyph->index, FT_KERNING_DEFAULT, &delta); prevPenPos += delta.x >> 6; penPos = prevPenPos; } prevIndex = glyph->index; // Calc X dimensions. FT_Pos lowX = penPos + glyph->horiBearingX; if (lowX < m_impl->lowDim.x) { m_impl->lowDim.x = lowX; } FT_Pos highX = penPos + glyph->horiBearingX + bitmap.width; if (highX > m_impl->highDim.x) { m_impl->highDim.x = highX; } // Calc Y dimensions. FT_Pos lowY = glyph->horiBearingY - bitmap.rows; if (lowY < m_impl->lowDim.y) { m_impl->lowDim.y = lowY; } FT_Pos highY = glyph->horiBearingY; if (highY > m_impl->highDim.y) { m_impl->highDim.y = highY; } penPos += glyph->horiAdvance; m_impl->sequence.push_back({ { static_cast<int32_t>(prevPenPos), static_cast<int32_t>(penPos - prevPenPos) }, glyph }); prevPenPos = penPos; } else { m_impl->sequence.push_back({ { static_cast<int32_t>(prevPenPos), static_cast<int32_t>(prevPenPos) }, nullptr }); } } if (m_impl->lowDim.x > m_impl->highDim.x || m_impl->lowDim.y > m_impl->highDim.y) { m_impl->sequence.clear(); return false; } m_impl->baseline = -m_impl->lowDim.y; m_impl->size.x = static_cast<size_t>(m_impl->highDim.x - m_impl->lowDim.x); m_impl->size.y = static_cast<size_t>(m_impl->highDim.y - m_impl->lowDim.y); return true; } bool FontSequence::createBitmapaAlpha(std::unique_ptr<uint8_t[]> & buffer, Vector2<size_t> & dimensions, const size_t from, const size_t to) { const auto fontImpl = m_impl->font->m_impl; const size_t bufferSize = m_impl->size.x * m_impl->size.y; if (!bufferSize) { return false; } dimensions = m_impl->size; buffer = std::make_unique<uint8_t[]>(bufferSize); uint8_t * glyphBuffer = buffer.get(); memset(glyphBuffer, 0, bufferSize); // Render glyphs. const size_t newTo = to < m_impl->sequence.size() ? to : m_impl->sequence.size(); for (size_t i = from; i < newTo; i++) { auto & currSeq = m_impl->sequence[i]; auto glyph = currSeq.glyph; if (!glyph) { continue; } auto & bitmap = glyph->bitmapGlyph->bitmap; auto bitmapBuffer = bitmap.buffer; auto penPos = currSeq.bounds.position - m_impl->lowDim.x; for (int y = 0; y < bitmap.rows; y++) { int intY = bitmap.rows - 1 - y; for (int x = 0; x < bitmap.width; x++) { const int glyphIndex = ((y - glyph->baseline + m_impl->lowDim.y) * m_impl->size.x) + (x + penPos + glyph->horiBearingX); const int bitmapIndex = (intY * bitmap.width) + x; glyphBuffer[glyphIndex] = std::max(bitmapBuffer[bitmapIndex], glyphBuffer[glyphIndex]); } } } return true; } bool FontSequence::createBitmapRgba(std::unique_ptr<uint8_t[]> & buffer, Vector2<size_t> & dimensions, const size_t from, const size_t to) { const auto fontImpl = m_impl->font->m_impl; const size_t bufferSize = m_impl->size.x * m_impl->size.y * 4; if (!bufferSize) { return false; } dimensions = m_impl->size; buffer = std::make_unique<uint8_t[]>(bufferSize); uint8_t * glyphBuffer = buffer.get(); memset(glyphBuffer, 0, bufferSize); // Render glyphs. const size_t newTo = to < m_impl->sequence.size() ? to : m_impl->sequence.size(); for(size_t i = from; i < newTo; i++) { auto & currSeq = m_impl->sequence[i]; auto glyph = currSeq.glyph; if (!glyph) { continue; } auto & bitmap = glyph->bitmapGlyph->bitmap; auto bitmapBuffer = bitmap.buffer; auto penPos = currSeq.bounds.position - m_impl->lowDim.x; for (int y = 0; y < bitmap.rows; y++) { int intY = bitmap.rows - 1 - y; for (int x = 0; x < bitmap.width; x++) { const int glyphIndex = ((y - (glyph->baseline + m_impl->lowDim.y)) * m_impl->size.x * 4) + ((x + penPos + glyph->horiBearingX) * 4); const int bitmapIndex = (intY * bitmap.width) + x; glyphBuffer[glyphIndex] = 255; glyphBuffer[glyphIndex + 1] = 255; glyphBuffer[glyphIndex + 2] = 255; glyphBuffer[glyphIndex + 3] = std::max(bitmapBuffer[bitmapIndex], glyphBuffer[glyphIndex + 3]); } } } return true; } bool FontSequence::findIndex(const int32_t width, const size_t from, size_t & to) const { if (from >= m_impl->sequence.size()) { return false; } if (!width) { to = from; return true; } size_t left = from; size_t right = m_impl->sequence.size(); size_t mid = left; while (left <= right) { mid = left + (right - 1) / 2; auto glyphEnd = m_impl->sequence[mid].bounds.position + m_impl->sequence[mid].bounds.size; if (glyphEnd == width) { break; } else if (glyphEnd < width) // Ignore left half. { left = mid + 1; } else // Ignore right half. { right = mid - 1; } } to = mid; return true; } size_t FontSequence::getBaseline() const { return m_impl->baseline; } Bounds1i32 FontSequence::getHorizontalBounds(const size_t index) const { return m_impl->sequence[index].bounds; } size_t FontSequence::getCount() const { return m_impl->sequence.size(); } size_t FontSequence::intersect(const Vector2f & /*point*/) const { return 0; } // Font library implementations. static std::unordered_map<std::string, std::shared_ptr<Font>> g_fontLibrary; std::shared_ptr<Font> FontLibrary::get(const std::string & font) { auto it = g_fontLibrary.find(font); if (it == g_fontLibrary.end()) { auto newFont = Font::create(font); if (!newFont->isValid()) { return nullptr; } g_fontLibrary.insert({font, newFont}); return newFont; } return it->second; } }
30.347107
188
0.527015
[ "render", "vector" ]
9900d235fe22596f1e7a4e5753e19f3c23b8c404
21,683
cpp
C++
Embarcadero/OpenGL/MD2 ray picking/Main.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
1
2022-03-22T14:41:15.000Z
2022-03-22T14:41:15.000Z
Embarcadero/OpenGL/MD2 ray picking/Main.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
Embarcadero/OpenGL/MD2 ray picking/Main.cpp
Jeanmilost/Demos
2b71f6edc85948540660d290183530fd846262ad
[ "MIT" ]
null
null
null
/****************************************************************************** * ==> Main ------------------------------------------------------------------* ****************************************************************************** * Description : MD2 demo main form * * Developer : Jean-Milost Reymond * ******************************************************************************/ #include <vcl.h> #pragma hdrstop #include "Main.h" // qr engine #include "QR_STDTools.h" #include "QR_GeometryHelper.h" // resources #include "Resources.rh" #pragma package(smart_init) #pragma link "glewSL.lib" #pragma resource "*.dfm" //------------------------------------------------------------------------------ // TMainForm //------------------------------------------------------------------------------ TMainForm* MainForm; //------------------------------------------------------------------------------ __fastcall TMainForm::TMainForm(TComponent* pOwner) : TForm(pOwner), m_pMemoryDir(NULL), m_PreviousTime(::GetTickCount()) { m_pMemoryDir = new QR_MemoryDir(true); } //------------------------------------------------------------------------------ __fastcall TMainForm::~TMainForm() { // delete model if (m_pMD2) { delete m_pMD2; m_pMD2 = NULL; } // delete memory dir if (m_pMemoryDir) delete m_pMemoryDir; // shutdown OpenGL m_Renderer.DisableOpenGL(Handle); } //------------------------------------------------------------------------------ void __fastcall TMainForm::FormCreate(TObject* pSender) { // initialize OpenGL if (!m_Renderer.EnableOpenGL(Handle)) { MessageDlg("OpenGL could not be initialized.\r\n\r\nApplication will close.", mtError, TMsgDlgButtons() << mbOK, 0);; Application->Terminate(); return; } ConfigOpenGL(); // calculate aspect ratio const float aspect = float(ClientWidth) / float(ClientHeight); // calculate the projection matrix m_Projection = m_Renderer.GetPerspective(45.0f, aspect, 0.1f, 100.0f); m_Renderer.CreateViewport(ClientWidth, ClientHeight); // load resources std::auto_ptr<TResourceStream> pModelStream(new TResourceStream((int)HInstance, ID_MD2_MODEL, L"DATA")); std::auto_ptr<TResourceStream> pTextureStream(new TResourceStream((int)HInstance, ID_MD2_TEXTURE, L"DATA")); std::auto_ptr<TResourceStream> pConfigStream(new TResourceStream((int)HInstance, ID_MD2_CONFIGURATION, L"DATA")); std::auto_ptr<TResourceStream> pNTStream(new TResourceStream((int)HInstance, ID_MD2_NORMALS_TABLE, L"DATA")); // convert model stream to memory file std::auto_ptr<QR_MemoryBuffer> pModelBuffer(new QR_MemoryBuffer()); pModelStream->Seek(0, 0); pModelBuffer->Write(pModelStream->Memory, pModelStream->Size); // convert texture stream to memory file std::auto_ptr<QR_MemoryBuffer> pTextureBuffer(new QR_MemoryBuffer()); pTextureStream->Seek(0, 0); pTextureBuffer->Write(pTextureStream->Memory, pTextureStream->Size); // convert configuration stream to memory file std::auto_ptr<QR_MemoryBuffer> pConfigBuffer(new QR_MemoryBuffer()); pConfigStream->Seek(0, 0); pConfigBuffer->Write(pConfigStream->Memory, pConfigStream->Size); // convert normals table stream to memory file std::auto_ptr<QR_MemoryBuffer> pNTBuffer(new QR_MemoryBuffer()); pNTStream->Seek(0, 0); pNTBuffer->Write(pNTStream->Memory, pNTStream->Size); // add model file to memory dir m_pMemoryDir->AddFile(L"marvin.md2", pModelBuffer.get(), false); pModelBuffer.release(); // add texture file to memory dir m_pMemoryDir->AddFile(L"marvin.bmp", pTextureBuffer.get(), false); pTextureBuffer.release(); // add configuration file to memory dir m_pMemoryDir->AddFile(L"marvin.cfg", pConfigBuffer.get(), false); pConfigBuffer.release(); // add normals table file to memory dir m_pMemoryDir->AddFile(L"normals.bin", pNTBuffer.get(), false); pNTBuffer.release(); // create and populate model info QR_MD2Group::IInfo md2Info; md2Info.m_ModelFileName = L"marvin.md2"; md2Info.m_TextureFileName = L"marvin.bmp"; md2Info.m_ConfigFileName = L"marvin.cfg"; md2Info.m_NormalsFileName = L"normals.bin"; // create and load model std::auto_ptr<QR_MD2Group> pMD2(new QR_MD2Group(&m_Renderer, &m_Resources)); pMD2->Load(*m_pMemoryDir, md2Info); pMD2->SetTranslation(QR_Vector3DF(0.0f, 0.0f, -10.0f)); pMD2->SetRotationX(-M_PI / 2.0f); pMD2->SetRotationY(-M_PI / 4.0f); pMD2->SetScaling(QR_Vector3DF(0.125f, 0.125f, 0.125f)); pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Stand); QR_DirectionalLight light; light.m_Color = QR_Color(255, 255, 255, 255); light.m_Ambient = QR_Color(32, 32, 32, 255); light.m_Direction = QR_Vector3DP(0.5f, 0.0f, 0.5f); light.m_Enabled = false; pMD2->SetLight(light); pMD2->SetVertexFormat(QR_Vertex::IEFormat(QR_Vertex::IE_VF_Normals | QR_Vertex::IE_VF_Colors | QR_Vertex::IE_VF_TexCoords)); m_pMD2 = pMD2.release(); m_pMD2->Set_OnDetectCollision(OnDetectCollision); // from now, OpenGL will draw scene every time the thread do nothing else Application->OnIdle = IdleLoop; } //------------------------------------------------------------------------------ void __fastcall TMainForm::FormResize(TObject* pSender) { // calculate aspect ratio const float aspect = float(ClientWidth) / float(ClientHeight); // calculate the projection matrix m_Projection = m_Renderer.GetPerspective(45.0f, aspect, 0.1f, 100.0f); m_Renderer.CreateViewport(ClientWidth, ClientHeight); } //------------------------------------------------------------------------------ void __fastcall TMainForm::FormPaint(TObject* pSender) { RenderGLScene(); } //------------------------------------------------------------------------------ void __fastcall TMainForm::miLightingClick(TObject* pSender) { // check or uncheck menu item miLighting->Checked = !miLighting->Checked; // switch between color or precalculated light mode m_pMD2->EnableLight(miLighting->Checked); } //------------------------------------------------------------------------------ void __fastcall TMainForm::miPrevAnimClick(TObject* pSender) { // get current running animation const QR_MD2CfgFile::IEGesture gesture = m_pMD2->GetGesture(); // select prev animation if (gesture == QR_MD2CfgFile::IE_AG_Stand) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRDeath4); else if (gesture == QR_MD2CfgFile::IE_AG_Run) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Stand); else if (gesture == QR_MD2CfgFile::IE_AG_Attack) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Run); else if (gesture == QR_MD2CfgFile::IE_AG_Pain1) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Attack); else if (gesture == QR_MD2CfgFile::IE_AG_Pain2) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Pain1); else if (gesture == QR_MD2CfgFile::IE_AG_Pain3) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Pain2); else if (gesture == QR_MD2CfgFile::IE_AG_Jump) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Pain3); else if (gesture == QR_MD2CfgFile::IE_AG_Flip) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Jump); else if (gesture == QR_MD2CfgFile::IE_AG_Salute) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Flip); else if (gesture == QR_MD2CfgFile::IE_AG_Taunt) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Salute); else if (gesture == QR_MD2CfgFile::IE_AG_Wave) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Taunt); else if (gesture == QR_MD2CfgFile::IE_AG_Point) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Wave); else if (gesture == QR_MD2CfgFile::IE_AG_CRStand) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Point); else if (gesture == QR_MD2CfgFile::IE_AG_CRWalk) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRStand); else if (gesture == QR_MD2CfgFile::IE_AG_CRAttack) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRWalk); else if (gesture == QR_MD2CfgFile::IE_AG_CRPain) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRAttack); else if (gesture == QR_MD2CfgFile::IE_AG_CRDeath) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRPain); else if (gesture == QR_MD2CfgFile::IE_AG_CRDeath2) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRDeath); else if (gesture == QR_MD2CfgFile::IE_AG_CRDeath3) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRDeath2); else if (gesture == QR_MD2CfgFile::IE_AG_CRDeath4) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRDeath3); } //------------------------------------------------------------------------------ void __fastcall TMainForm::miNextAnimClick(TObject* pSender) { // get current running animation const QR_MD2CfgFile::IEGesture gesture = m_pMD2->GetGesture(); // select next animation if (gesture == QR_MD2CfgFile::IE_AG_Stand) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Run); else if (gesture == QR_MD2CfgFile::IE_AG_Run) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Attack); else if (gesture == QR_MD2CfgFile::IE_AG_Attack) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Pain1); else if (gesture == QR_MD2CfgFile::IE_AG_Pain1) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Pain2); else if (gesture == QR_MD2CfgFile::IE_AG_Pain2) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Pain3); else if (gesture == QR_MD2CfgFile::IE_AG_Pain3) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Jump); else if (gesture == QR_MD2CfgFile::IE_AG_Jump) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Flip); else if (gesture == QR_MD2CfgFile::IE_AG_Flip) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Salute); else if (gesture == QR_MD2CfgFile::IE_AG_Salute) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Taunt); else if (gesture == QR_MD2CfgFile::IE_AG_Taunt) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Wave); else if (gesture == QR_MD2CfgFile::IE_AG_Wave) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Point); else if (gesture == QR_MD2CfgFile::IE_AG_Point) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRStand); else if (gesture == QR_MD2CfgFile::IE_AG_CRStand) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRWalk); else if (gesture == QR_MD2CfgFile::IE_AG_CRWalk) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRAttack); else if (gesture == QR_MD2CfgFile::IE_AG_CRAttack) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRPain); else if (gesture == QR_MD2CfgFile::IE_AG_CRPain) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRDeath); else if (gesture == QR_MD2CfgFile::IE_AG_CRDeath) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRDeath2); else if (gesture == QR_MD2CfgFile::IE_AG_CRDeath2) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRDeath3); else if (gesture == QR_MD2CfgFile::IE_AG_CRDeath3) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_CRDeath4); else if (gesture == QR_MD2CfgFile::IE_AG_CRDeath4) m_pMD2->SetAnimation(QR_MD2CfgFile::IE_AG_Stand); } //------------------------------------------------------------------------------ void __fastcall TMainForm::IdleLoop(TObject* pSender, bool& done) { done = false; RenderGLScene(); } //------------------------------------------------------------------------------ void __fastcall TMainForm::RenderGLScene() { // calculate time interval const std::time_t now = ::GetTickCount(); const double elapsedTime = (now - m_PreviousTime); m_PreviousTime = now; // begin the scene m_Renderer.BeginScene(m_Color, QR_Renderer::IESceneFlags(QR_Renderer::IE_SF_ClearColor | QR_Renderer::IE_SF_ClearDepth)); // load the projection and view matrices m_Renderer.SetProjectionMatrix(m_Projection); m_Renderer.SetViewMatrix(m_View); if (m_pMD2) m_pMD2->Draw(elapsedTime); // end the scene m_Renderer.EndScene(); } //-------------------------------------------------------------------------------------------------- void TMainForm::DrawPolygons(const QR_PolygonsP& polygons, const QR_Matrix16P& matrix) const { const QR_SizeT polygonCount = polygons.size(); // polygons to draw? if (!polygonCount) return; QR_Mesh mesh; mesh.resize(1); try { // create a vertex buffer and populate it with polygons in collisions mesh[0] = new QR_Vertex(); mesh[0]->m_Type = QR_Vertex::IE_VT_Triangles; mesh[0]->m_CoordType = QR_Vertex::IE_VC_XYZ; mesh[0]->m_Stride = 7; mesh[0]->m_Format = QR_Vertex::IE_VF_Colors; mesh[0]->m_Buffer.resize(polygonCount * (mesh[0]->m_Stride * 3)); QR_SizeT offset = 0; // iterate through polygons to draw for (QR_PolygonsP::const_iterator it = polygons.begin(); it != polygons.end(); ++it) { // build polygon to show mesh[0]->m_Buffer[offset] = (*it)->GetVertex1().m_X; mesh[0]->m_Buffer[offset + 1] = (*it)->GetVertex1().m_Y; mesh[0]->m_Buffer[offset + 2] = (*it)->GetVertex1().m_Z; mesh[0]->m_Buffer[offset + 3] = 1.0f; mesh[0]->m_Buffer[offset + 4] = 0.0f; mesh[0]->m_Buffer[offset + 5] = 0.0f; mesh[0]->m_Buffer[offset + 6] = 1.0f; mesh[0]->m_Buffer[offset + 7] = (*it)->GetVertex2().m_X; mesh[0]->m_Buffer[offset + 8] = (*it)->GetVertex2().m_Y; mesh[0]->m_Buffer[offset + 9] = (*it)->GetVertex2().m_Z; mesh[0]->m_Buffer[offset + 10] = 0.8f; mesh[0]->m_Buffer[offset + 11] = 0.0f; mesh[0]->m_Buffer[offset + 12] = 0.2f; mesh[0]->m_Buffer[offset + 13] = 1.0f; mesh[0]->m_Buffer[offset + 14] = (*it)->GetVertex3().m_X; mesh[0]->m_Buffer[offset + 15] = (*it)->GetVertex3().m_Y; mesh[0]->m_Buffer[offset + 16] = (*it)->GetVertex3().m_Z; mesh[0]->m_Buffer[offset + 17] = 1.0f; mesh[0]->m_Buffer[offset + 18] = 0.12f; mesh[0]->m_Buffer[offset + 19] = 0.2f; mesh[0]->m_Buffer[offset + 20] = 1.0f; // go to next polygon offset += (mesh[0]->m_Stride * 3); } // configure OpenGL to draw polygons in collision glDisable(GL_TEXTURE_2D); glCullFace(GL_NONE); glDisable(GL_DEPTH_TEST); #ifdef USE_SHADER // prepare shader to draw the model m_Renderer.ConnectProjectionMatrixToShader(m_pMouseColDetShader, *m_pScene->GetProjectionMatrix()); m_Renderer.ConnectViewMatrixToShader(m_pMouseColDetShader, *m_pScene->GetViewMatrix()); QR_ModelTextures textures; // draw polygons in collision with mouse pointer m_Renderer.Draw(mesh, matrix, textures, m_pMouseColDetShader); #else glMatrixMode(GL_MODELVIEW); glPushMatrix(); // place triangles into 3D world glLoadMatrixf(const_cast<QR_Matrix16P&>(matrix).GetPtr()); QR_ModelTextures textures; // draw polygons in collision with mouse pointer m_Renderer.Draw(mesh, matrix, textures); glPopMatrix(); #endif // restore previous OpenGL parameters glEnable(GL_DEPTH_TEST); glCullFace(GL_FRONT); glEnable(GL_TEXTURE_2D); glFlush(); } catch (...) { if (mesh.size() && mesh[0]) delete mesh[0]; throw; } if (mesh.size() && mesh[0]) delete mesh[0]; } //-------------------------------------------------------------------------------------------------- void TMainForm::OnDetectCollision(const QR_ModelGroup* pSender, const QR_Mesh* pMesh, const QR_Matrix16P& modelMatrix, const QR_AABBTree* pAABBTree) { if (!pAABBTree) return; // calculate client rect in OpenGL coordinates QR_RectP rect(-1.0f, 1.0f, 1.0f, 3.0f); int width = ClientWidth; int height = ClientHeight; float zNear = 0.1f; float zFar = 100.0f; TPoint mousePos = Mouse->CursorPos; if (!::ScreenToClient(Handle, &mousePos)) return; // convert mouse position to viewport, that will be used as ray start pos QR_Vector3DP rayPos = QR_Renderer::MousePosToViewportPos(QR_PointI(mousePos.X, mousePos.Y), QR_RectI(0, 0, width, height), rect); // create ray dir #ifdef COLLISION_DETECTION_FIRST_SHOOTER_MODE QR_Vector3DP rayDir(0.0f, 0.0f, -1.0f); #else QR_Vector3DP rayDir(rayPos.m_X, rayPos.m_Y, -1.0f); #endif // unproject the ray to make it inside the 3d world coordinates QR_Renderer::Unproject(m_Projection, m_View, rayPos, rayDir); #ifdef COLLISION_DETECTION_DRAW_DEBUG_RAY const QR_Vector3DF farRayPos(rayPos.m_X + (rayDir.m_X * 100.0f), rayPos.m_Y + (rayDir.m_Y * 100.0f), rayPos.m_Z + (rayDir.m_Z * 100.0f)); glDisable(GL_TEXTURE_2D); glLineWidth(2.5f); glBegin(GL_LINES); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(rayPos.m_X, rayPos.m_Y, rayPos.m_Z); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(farRayPos.m_X, farRayPos.m_Y, farRayPos.m_Z); glEnd(); glEnable(GL_TEXTURE_2D); #endif float determinant; // now transform the ray to match with the model position const QR_Matrix16P invertModel = const_cast<QR_Matrix16P&>(modelMatrix).Inverse(determinant); rayPos = invertModel.Transform(rayPos); rayDir = invertModel.TransformNormal(rayDir); rayDir = rayDir.Normalize(); #ifdef USE_DETECTION_COLLISION_DEBUG_TOOLS #ifdef OS_WIN #ifdef CP_EMBARCADERO m_pCollisionToolbox->vmProjection->Show(L"Projection matrix", projectionMatrix); m_pCollisionToolbox->vmView->Show(L"View matrix", viewMatrix); m_pCollisionToolbox->vmModel->Show(L"Model matrix", modelMatrix); m_pCollisionToolbox->vvRayPos->Show(L"Ray pos", rayPos); m_pCollisionToolbox->vvRayDir->Show(L"Ray dir", rayDir); QR_BoxP* pBBox = pAABBTree->GetBoundingBox(); if (pBBox) { m_pCollisionToolbox->vvBoxMin->Show(L"Bounding box min", pBBox->m_Min); m_pCollisionToolbox->vvBoxMax->Show(L"Bounding box max", pBBox->m_Max); } #endif #endif #endif // create and populate ray from mouse position std::auto_ptr<QR_RayP> pRay(new QR_RayP()); pRay->SetPos(rayPos); pRay->SetDir(rayDir); QR_PolygonsP polygons; try { // get polygons to check for collision by resolving AABB tree pAABBTree->Resolve(pRay.get(), polygons); QR_PolygonsP pickedPolygons; QR_SizeT polygonCount = polygons.size(); // iterate through polygons to check if (polygonCount > 0) for (QR_PolygonsP::const_iterator it = polygons.begin(); it != polygons.end(); ++it) // is polygon intersecting ray? if (QR_GeometryHelper::RayIntersectsPolygon(*(pRay.get()), *(*it))) // add polygon in collision to resulting list pickedPolygons.push_back(*it); // found collision? if (pickedPolygons.size()) // draw polygons in collision if required DrawPolygons(pickedPolygons, modelMatrix); } catch (...) { QR_STDTools::DelAndClear(polygons); throw; } QR_STDTools::DelAndClear(polygons); } //------------------------------------------------------------------------------ void TMainForm::ConfigOpenGL() { // configure OpenGL glEnable(GL_DEPTH_TEST); glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); // enable blender (not required but add a nice ghosted effect) glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_SRC_COLOR); glEnable(GL_TEXTURE_2D); } //------------------------------------------------------------------------------
37.320138
100
0.569248
[ "mesh", "model", "transform", "3d" ]
990a0769ffb1c701aba96bf2c74344ee9bcab961
93,755
cpp
C++
inetsrv/iis/svcs/smtp/aqueue/cat/src/ccatrecip.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
inetsrv/iis/svcs/smtp/aqueue/cat/src/ccatrecip.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
inetsrv/iis/svcs/smtp/aqueue/cat/src/ccatrecip.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------ // // Copyright (C) 1998, Microsoft Corporation // // File: ccatrecip.cpp // // Contents: Implementation of classes: // // Classes: // CIMsgRecipListAddr // CCatRecip // // Functions: // CIMsgRecipListAddr::CIMsgRecipListAddr // CIMsgRecipListAddr::~CIMsgRecipListAddr // CIMsgRecipListAddr::GetSpecificOrigAddress // CIMsgRecipListAddr::CreateNewCatAddr // CIMsgRecipListAddr::HrAddAddresses // CIMsgRecipListAddr::SetUnresolved // CIMsgRecipListAddr::SetDontDeliver // CIMsgRecipListAddr::SetMailMsgCatStatus // // CCatRecip::CCatRecip // CCatRecip::AddDLMember // CCatRecip::AddForward // CCatRecip::HrCompletion // CCatRecip::HandleFailure // // History: // jstamerj 980325 15:32:17: Created. // //------------------------------------------------------------- #include "precomp.h" // // class CIMsgRecipListAddr // //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::CIMsgRecipListAddr // // Synopsis: Initializes member data // // Arguments: // pStore: EmailIDStore to use // pIRC: per IMsg resolve list context to use // prlc: store context to use // hLocalDomainContext: local domain context to use // pBifMgr: bifurcation manager to use for getting other // IMailMsgRecipientsAdd interaces // pRecipsAdd: IMailMsgRecipientsAdd of the original recipient to // resolve // dwRecipIndex: Index in pRecipsAdd of the original recipient to // resolve // fPrimary: TRUE means original recipient was added as primary // FALSE means original recipient was added as secondary // // Returns: NOTHING // // History: // jstamerj 980325 12:54:02: Created. // //------------------------------------------------------------- CIMsgRecipListAddr::CIMsgRecipListAddr( CICategorizerListResolveIMP *pCICatListResolve) : CCatAddr(pCICatListResolve) { CatFunctEnterEx((LPARAM)this, "CIMsgRecipListAddr::CIMsgRecipListAddr"); CatFunctLeave(); } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::~CIMsgRecipListAddr // // Synopsis: Releases the IMailMsgRecipientsAdd reference // // Arguments: NONE // // Returns: NOTHING // // History: // jstamerj 980325 12:59:50: Created. // //------------------------------------------------------------- CIMsgRecipListAddr::~CIMsgRecipListAddr() { CatFunctEnterEx((LPARAM)this, "CImsgRecipListAddr::~CIMsgRecipListAddr"); CatFunctLeave(); } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::GetSpecificOrigAddress // // Synopsis: Attempts to retrieve a specified original address // // Arguments: // CAType: Address type to retrieve // psz: Buffer to receive address string // dwcc: Size of that buffer // // Returns: // S_OK: Success // CAT_IMSG_E_PROPNOTFOUND: this recipient does not have that address // or other error from mailmsg // // History: // jstamerj 1998/07/30 20:20:22: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::GetSpecificOrigAddress( CAT_ADDRESS_TYPE CAType, LPSTR psz, DWORD dwcc) { HRESULT hr; IMailMsgRecipientsAdd *pRecipsAdd; DWORD dwRecipIndex; CatFunctEnterEx((LPARAM)this, "CIMsgRecipListAddr::GetSpecificOrigAddress"); hr = GetIMsgRecipInfo(&pRecipsAdd, &dwRecipIndex, NULL, NULL); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "GetIMsgRecipInfo"); CatFunctLeaveEx((LPARAM)this); return hr; } hr = pRecipsAdd->GetStringA( dwRecipIndex, PropIdFromCAType(CAType), dwcc, psz); pRecipsAdd->Release(); DebugTrace((LPARAM)this, "Item/GetStringA returned hr %08lx", hr); if(psz[0] == '\0') hr = CAT_IMSG_E_PROPNOTFOUND; if(FAILED(hr) && (hr != CAT_IMSG_E_PROPNOTFOUND)) { ERROR_LOG_ADDR(this, "pRecipsAdd->GetStringA"); } CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::CreateNewCatAddr // // Synopsis: CCatRecip methods call this function when they need to // create a new CCatRecip object and a corresponding recipient // in the member m_pRecipsAdd with one address only. On // success, the CCatAddr is returned with a refcount of // one. // // Arguments: // CAType: Address type of new CCatRecip object // pszAddress: Address string. If NULL, a new CCatRecip object is // created with properties set to point to the current // mailmsg recipient (AddPrimary/AddSecondary is not // called) // ppCCatAddr: Pointer to pointer to CCatAddr object that is set to // the newly allocated CCatRecip // fPrimary: if TRUE, add via AddPrimary // if FALSE, add via AddSecondary // // Returns: // S_OK: Success // E_OUTOFMEMORY: duh // CAT_E_PROP_NOT_FOUND: a required ICategorizerItem prop was not set // or Error from IMsg // // History: // jstamerj 980325 14:15:50: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::CreateNewCatAddr( CAT_ADDRESS_TYPE CAType, LPTSTR pszAddress, CCatAddr **ppCCatAddr, BOOL fPrimary) { CatFunctEnterEx((LPARAM)this, "CIMsgRecipListAddr::CreateNewCatAddr"); DWORD dwNewRecipIndex = 0; HRESULT hr = S_OK; LPCTSTR psz = pszAddress; DWORD dwPropId = 0; IMailMsgRecipientsAdd *pRecipsAdd = NULL; IMailMsgProperties *pIMailMsgProps = NULL; DWORD dwOrigIndex = 0; DWORD dwLevel = 0; ICategorizerItem *pICatItemNew = NULL; DebugTrace((LPARAM)this, "CAType = %d", CAType); if(pszAddress) { DebugTrace((LPARAM)this, "pszAddress = %s", pszAddress); } else { DebugTrace((LPARAM)this, "pszAddress = NULL"); } DebugTrace((LPARAM)this, "fPrimary = %d", fPrimary); // Retrieve IMsg interface/recip index hr = GetIMsgRecipInfo(&pRecipsAdd, &dwOrigIndex, NULL, &pIMailMsgProps); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "GetIMsgRecipInfo"); pRecipsAdd = NULL; pIMailMsgProps = NULL; goto CLEANUP; } // // Get the recipient level // dwLevel = DWLevel() + 1; // // Unknown dwLevel is -1, so -1 + 1 = 0 // If dwLevel is unknown, new value will be zero. // if(pszAddress == NULL) { // // Create new CCatAddr pointing to the CURRENT recipient // dwNewRecipIndex = dwOrigIndex; } else { // // Get the equivilant mailmsg propID // dwPropId = PropIdFromCAType(CAType); if(fPrimary) { hr = pRecipsAdd->AddPrimary( 1, &psz, &dwPropId, &dwNewRecipIndex, pRecipsAdd, dwOrigIndex); _ASSERT(hr != CAT_IMSG_E_DUPLICATE); } else { hr = pRecipsAdd->AddSecondary( 1, &psz, &dwPropId, &dwNewRecipIndex, pRecipsAdd, dwOrigIndex); } DebugTrace((LPARAM)this, "AddPrimary/AddSecondary returned hr %08lx", hr); } if(hr == CAT_IMSG_E_DUPLICATE) { INCREMENT_COUNTER(MailmsgDuplicateCollisions); goto CLEANUP; } else if(FAILED(hr)) { ERROR_LOG_ADDR(this, "AddPrimary / AddSecondary"); goto CLEANUP; } // // Alloc an ICategorizerItem so that it can set all the necessary properties // hr = m_pCICatListResolve->AllocICategorizerItem( SOURCE_RECIPIENT, &pICatItemNew); ERROR_CLEANUP_LOG_ADDR(this, "m_pCICatListResolve->AllocICategorizerItem"); // // Set important ICategorizerItem props on the newborn // hr = PutIMsgRecipInfo( &pRecipsAdd, &dwNewRecipIndex, &fPrimary, &pIMailMsgProps, // Only set dwLevel if the old value is known (dwLevel == 0) ? NULL : &dwLevel, pICatItemNew); // This should never fail _ASSERT(SUCCEEDED(hr)); // // Get the CCatAddr object // This should never fail as no sinks have had the chance // to muck with properties yet. // hr = m_pCICatListResolve->GetCCatAddrFromICategorizerItem( pICatItemNew, ppCCatAddr); _ASSERT(SUCCEEDED(hr)); // // Reset the display name // hr = ((CIMsgRecipListAddr *) *ppCCatAddr)->HrSetDisplayNameProp(NULL); ERROR_CLEANUP_LOG_ADDR(this, "HrSetDisplayNameProp"); CLEANUP: if(FAILED(hr)) { *ppCCatAddr = NULL; if(pICatItemNew) pICatItemNew->Release(); } if(pRecipsAdd) pRecipsAdd->Release(); if(pIMailMsgProps) pIMailMsgProps->Release(); CatFunctLeave(); return hr; } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::HrAddAddresses // // Synopsis: Add the addresses contained in the arrays to the IMsg // recipient we contain // // Arguments: // dwNumAddresses: Number of new addresses // rgCAType: Array of address types // rgpsz: Array of pointers to address strings // // Returns: // S_OK: Success // CAT_E_FORWARD_LOOP: One or more of the new addresses is a // duplicate of a recipient in the parent chain // CAT_E_NO_SMTP_ADDRESS: Did not add the new addresses because there // is no SMTP address // // History: // jstamerj 980325 14:21:56: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::HrAddAddresses( DWORD dwNumAddresses, CAT_ADDRESS_TYPE *rgCAType, LPTSTR *rgpsz) { CatFunctEnterEx((LPARAM)this, "CIMsgRecipListAddr::AddAddresses"); HRESULT hr, hrDupCheck; IMailMsgRecipientsAdd *pRecipsAdd; DWORD dwOrigIndex; BOOL fPrimary; DWORD dwCount; DWORD dwNewIndex; DWORD dwPropIds[CAT_MAX_ADDRESS_TYPES]; BOOL fSMTPAddress; DWORD dwSMTPAddressIdx = 0; _ASSERT(dwNumAddresses > 0); _ASSERT(dwNumAddresses <= CAT_MAX_ADDRESS_TYPES); // Retrieve IMsg interface/recip index hr = GetIMsgRecipInfo(&pRecipsAdd, &dwOrigIndex, &fPrimary, NULL); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "GetIMsgRecipInfo"); return hr; } // // Initialize the array of address types // fSMTPAddress = FALSE; for(dwCount = 0; dwCount < dwNumAddresses; dwCount++) { dwPropIds[dwCount] = PropIdFromCAType(rgCAType[dwCount]); if(rgCAType[dwCount] == CAT_SMTP) { fSMTPAddress = TRUE; dwSMTPAddressIdx = dwCount; } } if(fSMTPAddress == FALSE) { ErrorTrace((LPARAM)this, "Not delivering to recipient without an SMTP address"); hr = CAT_E_NO_SMTP_ADDRESS; goto CLEANUP; } // // Validate the SMTP address // hr = HrValidateAddress( rgCAType[dwSMTPAddressIdx], rgpsz[dwSMTPAddressIdx]); if(FAILED(hr)) { ErrorTrace((LPARAM)this, "Default SMTP address is invalid: %s", rgpsz[dwSMTPAddressIdx]); ERROR_LOG_ADDR(this, "HrValidateAddress"); hr = HrHandleInvalidAddress(); goto CLEANUP; } // // Call IMsg add with new addresses // If we're primary, we remain primary. // if(fPrimary) { // // We need to check for a loop here too since there could be a // loop where some other recipient is forwarding to one of our // non-default proxy addresses (bug #70220) // hr = CheckForLoop( dwNumAddresses, rgCAType, rgpsz, FALSE); // No need to check ourself for a duplicate if(FAILED(hr)) { ERROR_LOG_ADDR(this, "CheckForLoop"); } else { hr = pRecipsAdd->AddPrimary( dwNumAddresses, (LPCSTR *)rgpsz, dwPropIds, &dwNewIndex, pRecipsAdd, dwOrigIndex); _ASSERT(hr != CAT_IMSG_E_DUPLICATE); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "pRecipsAdd->AddPrimary"); } } } else { hr = pRecipsAdd->AddSecondary( dwNumAddresses, (LPCSTR *)rgpsz, dwPropIds, &dwNewIndex, pRecipsAdd, dwOrigIndex); if(hr == CAT_IMSG_E_DUPLICATE) { INCREMENT_COUNTER(MailmsgDuplicateCollisions); // // The duplicate might be us (the recipient in the mailmsg // before resolution) // hrDupCheck = CheckForDuplicateCCatAddr( dwNumAddresses, rgCAType, rgpsz); if(hrDupCheck == CAT_IMSG_E_DUPLICATE) { // // So we do collide with our parent. // Remove if from duplicate detection and try again. // hr = RemoveFromDuplicateRejectionScheme(TRUE); if(SUCCEEDED(hr)) { hr = pRecipsAdd->AddSecondary( dwNumAddresses, (LPCSTR *)rgpsz, dwPropIds, &dwNewIndex, pRecipsAdd, dwOrigIndex); if(hr == CAT_IMSG_E_DUPLICATE) INCREMENT_COUNTER(MailmsgDuplicateCollisions); } } else if(FAILED(hrDupCheck)) { ERROR_LOG_ADDR(this, "pRecipsAdd->AddSecondary"); // // Return the error // hr = hrDupCheck; ERROR_LOG_ADDR(this, "CheckForDuplicateCCatAddr"); } else { ERROR_LOG_ADDR(this, "pRecipsAdd->AddSecondary"); } if(hr == CAT_IMSG_E_DUPLICATE) { // // If hr is STILL Duplicate, check to see if it's a loop // we've encountered // hrDupCheck = CheckForLoop( dwNumAddresses, rgCAType, rgpsz, FALSE); // No need to check ourself for a // duplicate if(FAILED(hrDupCheck)) { // // Return the error -- this could be // CAT_E_FORWARD_LOOP // hr = hrDupCheck; ERROR_LOG_ADDR(this, "CheckForLoop"); } } } } DebugTrace((LPARAM)this, "AddPrimary/AddSecondary returned hr %08lx", hr); if(SUCCEEDED(hr)) { // Since we were just adding addresses for the same recipient, // always mark the old recipient as "Don't deliver" hr = SetDontDeliver(TRUE); if(SUCCEEDED(hr)) { // // Relase old Recipient, update this to point to the new // recipient // IMailMsgRecipients and fPrimary always remain the same // for default processing // hr = PutIMailMsgRecipientsAddIndex(dwNewIndex, this); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "PutIMailMsgRecipientsAddIndex"); } } else { ERROR_LOG_ADDR(this, "SetDontDeliver"); } } CLEANUP: pRecipsAdd->Release(); CatFunctLeave(); return hr; } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::SetUnresolved // // Synopsis: Sets recipient property on IMsg indicating this recipient // could not be resolved -- this will cause NDR generation for the // recipient // // Arguments: // HrReason: Reason why address is unresolved // // Returns: // S_OK: Success // Or error from IMsg // // History: // jstamerj 980325 14:29:45: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::SetUnresolved( HRESULT HrStatus) { CatFunctEnterEx((LPARAM)this, "CIMsgRecipListAddr::SetUnresolved"); HRESULT hr; IMailMsgRecipientsAdd *pRecipsAdd; IMailMsgProperties *pIMailMsgProps; DWORD dwRecipIndex; DWORD dwFlags = 0; LogNDREvent(HrStatus); INCREMENT_COUNTER(NDRdRecipients); switch(HrStatus) { case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND): INCREMENT_COUNTER(UnresolvedRecipients); break; case CAT_E_MULTIPLE_MATCHES: INCREMENT_COUNTER(AmbiguousRecipients); break; case CAT_E_ILLEGAL_ADDRESS: INCREMENT_COUNTER(IllegalRecipients); break; case CAT_E_FORWARD_LOOP: INCREMENT_COUNTER(LoopRecipients); break; default: INCREMENT_COUNTER(GenericFailureRecipients); break; } // Retrieve IMsg interface/recip index hr = GetIMsgRecipInfo(&pRecipsAdd, &dwRecipIndex, NULL, &pIMailMsgProps); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "GetIMsgRecipInfo"); return hr; } hr = pRecipsAdd->GetDWORD(dwRecipIndex, IMMPID_RP_RECIPIENT_FLAGS, &dwFlags); if(SUCCEEDED(hr) || (hr == CAT_IMSG_E_PROPNOTFOUND)) { dwFlags |= (RP_ERROR_CONTEXT_CAT | RP_UNRESOLVED); hr = pRecipsAdd->PutDWORD(dwRecipIndex, IMMPID_RP_RECIPIENT_FLAGS, dwFlags); if(SUCCEEDED(hr)) { hr = pRecipsAdd->PutDWORD( dwRecipIndex, IMMPID_RP_ERROR_CODE, HrStatus); if(SUCCEEDED(hr)) { hr = SetMailMsgCatStatus( pIMailMsgProps, CAT_W_SOME_UNDELIVERABLE_MSGS); } else { ERROR_LOG_ADDR(this, "SetMailMsgCatStatus"); } } else { ERROR_LOG_ADDR(this, "pRecipsAdd->PutDWORD"); } } else { ERROR_LOG_ADDR(this, "pRecipsAdd->GetDWORD(IMMPID_RP_RECIPIENT_FLAGS)"); } pRecipsAdd->Release(); pIMailMsgProps->Release(); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::SetDontDeliver // // Synopsis: Sets the IMsg property on a recipient that indicates this // recipient should be removed upon a call to WriteList // // Arguments: // fDontDeliver: TRUE means remove recipient on a WriteList // FALSE means clear DontDeliver property, don't // remove on a WriteList // // Returns: // S_OK: Success // // History: // jstamerj 980325 14:34:44: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::SetDontDeliver(BOOL fDontDeliver) { CatFunctEnterEx((LPARAM)this, "CIMsgRecipListAddr::SetDontDeliver"); IMailMsgRecipientsAdd *pRecipsAdd; DWORD dwRecipIndex; HRESULT hr; // Retrieve IMsg interface/recip index hr = GetIMsgRecipInfo(&pRecipsAdd, &dwRecipIndex, NULL, NULL); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "GetIMsgRecipInfo"); return hr; } hr = pRecipsAdd->PutBool(dwRecipIndex, IMMPID_RPV_DONT_DELIVER, fDontDeliver); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "pRecipsAdd->PutBool"); } pRecipsAdd->Release(); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::RemoveFromDuplicateRejectionScheme // // Synopsis: Sets the IMsg property to indicate this recipient's names // should be ignored for duplicate detection // // Arguments: // fRemove: TRUE means remove recipient for dup detection // FALSE means clear property, don't remove recip for dup detection. // // Returns: // S_OK: Success // // History: // jstamerj 980325 14:34:44: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::RemoveFromDuplicateRejectionScheme(BOOL fRemove) { CatFunctEnterEx((LPARAM)this, "CIMsgRecipListAddr::SetDontDeliver"); IMailMsgRecipientsAdd *pRecipsAdd; DWORD dwRecipIndex; HRESULT hr; // Retrieve IMsg interface/recip index hr = GetIMsgRecipInfo(&pRecipsAdd, &dwRecipIndex, NULL, NULL); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "GetIMsgRecipInfo"); return hr; } hr = pRecipsAdd->PutBool(dwRecipIndex, IMMPID_RPV_NO_NAME_COLLISIONS, fRemove); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "pRecipsAdd->PutBool"); } pRecipsAdd->Release(); CatFunctLeave(); return hr; } // // class CCatRecip // //+------------------------------------------------------------ // // Function: CCatRecip::CCatRecip // // Synopsis: initialize member data // // Arguments: // See CIMsgRecipListAddr::CIMsgRecipListAddr // // Returns: NOTHING // // History: // jstamerj 980325 14:36:30: Created. // //------------------------------------------------------------- CCatRecip::CCatRecip( CICategorizerListResolveIMP *pCICatListResolve) : CCatExpandableRecip(pCICatListResolve) { CatFunctEnterEx((LPARAM)this, "CCatRecip::CCatRecip"); INCREMENT_COUNTER(RecipsInMemory); CatFunctLeave(); } //+------------------------------------------------------------ // // Function: CCatRecip::~CCatRecip // // Synopsis: Decrement count of recips in memory // // Arguments: NONE // // Returns: NOTHING // // History: // jstamerj 1999/02/24 19:26:01: Created. // //------------------------------------------------------------- CCatRecip::~CCatRecip() { DECREMENT_COUNTER(RecipsInMemory); } //+------------------------------------------------------------ // // Function: CCatRecip::AddDLMember // // Synopsis: EmailIDStore calls this function once for every DL Member // when setting properties on a DL. It is called before // CCatRecip::HrCompletion // // Arguments: // CAType: Known address type of the DL Member // pszAddress: pointer to the address string // // Returns: // S_OK: Success, issued a pending LDAP search // S_FALSE: Success, did not issue a search // Or, error from IMsg // // History: // jstamerj 980325 14:39:20: Created. // //------------------------------------------------------------- HRESULT CCatRecip::AddDLMember(CAT_ADDRESS_TYPE CAType, LPTSTR pszAddress) { HRESULT hr; CCatAddr *pMember = NULL; CatFunctEnterEx((LPARAM)this, "CCatRecip::AddDLMember"); DebugTrace((LPARAM)this, "CAType: %d", CAType); DebugTrace((LPARAM)this, "pszAddress: %s", pszAddress); hr = GetListResolveStatus(); if(FAILED(hr)) { ErrorTrace((LPARAM)this, "Not adding DL member since list resolve failed"); ERROR_LOG_ADDR(this, "GetListResolveStatus") // Signal to ldapstor to stop resolution goto CLEANUP; } // // Validate the new address first // hr = HrValidateAddress(CAType, pszAddress); if(FAILED(hr)) { ErrorTrace((LPARAM)this, "Invalid member address"); ERROR_LOG_ADDR(this, "HrValidateAddress"); hr = HrHandleInvalidAddress(); goto CLEANUP; } // Create a new CCatAddr to handle resolution of this DL Member hr = CreateNewCatAddr( CAType, pszAddress, &pMember, FALSE); if(hr == CAT_IMSG_E_DUPLICATE) { DebugTrace((LPARAM)this, "Resolution failed with e_duplicate"); // Fine, DL member was a duplicate so we won't be // re-resolving it. Let it be. } else if(SUCCEEDED(hr)) { // Great....dispatch the query to the store hr = pMember->HrResolveIfNecessary(); pMember->Release(); } else { ERROR_LOG_ADDR(this, "CreateNewCatAddr"); } CLEANUP: if(hr == CAT_IMSG_E_DUPLICATE) hr = S_FALSE; DebugTrace((LPARAM)this, "returning hr %08lx", hr); CatFunctLeave(); return hr; } //+------------------------------------------------------------ // // Function: CCatRecip::AddDynamicDlMember // // Synopsis: Add a DL member that has already been looked up in the DS // // Arguments: // pICatItemAttr: the attributes of the DL member // // Returns: // S_OK: Success // MAILTRANSPORT_S_PENDING: doing an async operation, will call your // completion routine when I am finished // // History: // jstamerj 1998/09/29 21:30:26: Created. // //------------------------------------------------------------- HRESULT CCatRecip::AddDynamicDLMember( ICategorizerItemAttributes *pICatItemAttr) { HRESULT hr; CCatAddr *pMember = NULL; ATTRIBUTE_ENUMERATOR enumerator_dn; BOOL fEnumeratingDN = FALSE; LPSTR pszDistinguishedNameAttr = NULL; LPSTR pszDistinguishedName = NULL; ICategorizerUTF8Attributes *pIUTF8Attr = NULL; CatFunctEnterEx((LPARAM)this, "CCatRecip::AddDynamicDlMember"); _ASSERT(pICatItemAttr); hr = GetListResolveStatus(); if(FAILED(hr)) { ErrorTrace((LPARAM)this, "Not adding DL member since list resolve failed"); ERROR_LOG_ADDR(this, "GetListResolveStatus"); // Signal to ldapstor to stop resolution goto CLEANUP; } hr = GetICatParams()->GetDSParameterA( DSPARAMETER_ATTRIBUTE_DEFAULT_DN, &pszDistinguishedNameAttr); if(FAILED(hr)) { // // Fail entire message categorization // ErrorTrace((LPARAM)this, "Failing entire message categorization because we couldn\'t fetch the DN attribute name"); ERROR_LOG_ADDR(this, "GetDSParameterA(DSPARAMETER_ATTRIBUTE_DEFAULT_DN)"); hr = SetListResolveStatus(hr); _ASSERT(SUCCEEDED(hr)); goto CLEANUP; } hr = pICatItemAttr->QueryInterface( IID_ICategorizerUTF8Attributes, (void **)&pIUTF8Attr); if (FAILED(hr)) { ERROR_LOG_ADDR(this, "pICatItemAttr->QueryInterface(IID_ICategorizerUTF8Attributes"); hr = S_OK; goto CLEANUP; } hr = pIUTF8Attr->BeginUTF8AttributeEnumeration( pszDistinguishedNameAttr, &enumerator_dn); if (hr == CAT_E_PROPNOTFOUND) { // // Silently skip this recip // ErrorTrace((LPARAM)this, "DN attribute \'%s\' not present in results; skipping recip", pszDistinguishedNameAttr); ERROR_LOG_ADDR(this, "pIUTF8Attr->BeginUTF8AttributeEnumeration(dn)"); hr = S_OK; goto CLEANUP; } else if (FAILED(hr)) { // // Enumeration failed for some other reason. // Fail entire message categorization. // ErrorTrace((LPARAM)this, "Failing entire message categorization because enumeration of attribute \'%s\' failed with %08lx", pszDistinguishedNameAttr, hr); ERROR_LOG_ADDR(this, "pIUTF8Attr->BeginUTF8AttributeEnumeration(dn)"); hr = SetListResolveStatus(hr); _ASSERT(SUCCEEDED(hr)); goto CLEANUP; } fEnumeratingDN = TRUE; hr = pIUTF8Attr->GetNextUTF8AttributeValue( &enumerator_dn, &pszDistinguishedName); if (hr == HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS)) { // // silently skip this recip // ErrorTrace((LPARAM)this, "attribute \'%s\' present but with no values; skipping recip", pszDistinguishedNameAttr); ERROR_LOG_ADDR(this, "pIUTF8Attr->GetNextUTF8AttributeValue"); hr = S_OK; goto CLEANUP; } else if (FAILED(hr)) { // // fail entire message categorization // ErrorTrace((LPARAM)this, "Failed to enumerate DN attribute \'%s\' with hr %08lx", pszDistinguishedNameAttr, hr); ERROR_LOG_ADDR(this, "pIUTF8Attr->GetNextUTF8AttributeValue"); hr = SetListResolveStatus(hr); _ASSERT(SUCCEEDED(hr)); goto CLEANUP; } // // Create a new CCatAddr for this member // hr = CreateNewCatAddr( CAT_DN, pszDistinguishedName, &pMember, FALSE); if (hr == CAT_IMSG_E_DUPLICATE) { // // silently skip this recip // ErrorTrace((LPARAM)this, "duplicate address detected; skipping recip"); hr = S_OK; goto CLEANUP; } else if (FAILED(hr)) { ERROR_LOG_ADDR(this, "CreateNewCatAddr"); goto CLEANUP; } // // Since we've already looked up the attributes, just set the // ICatItemAttr property of the new guy and trigger // ProcessItem/ExpandItem/CompleteItem // hr = pMember->PutHRESULT( ICATEGORIZERITEM_HRSTATUS, S_OK); ERROR_CLEANUP_LOG_ADDR(this, "pMember->PutHRESULT"); hr = pMember->PutICategorizerItemAttributes( ICATEGORIZERITEM_ICATEGORIZERITEMATTRIBUTES, pICatItemAttr); ERROR_CLEANUP_LOG_ADDR(this, "pMember->PutICategorizerItemAttributes"); // // Simulate DS completion // IncPendingLookups(); pMember->LookupCompletion(); hr = S_OK; CLEANUP: if(pMember) pMember->Release(); if (fEnumeratingDN) { pIUTF8Attr->EndUTF8AttributeEnumeration( &enumerator_dn); } if (pIUTF8Attr) pIUTF8Attr->Release(); DebugTrace((LPARAM)this, "returning hr %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CCatRecip::AddForward // // Synopsis: EMailIDStore calls this function once for every // forwarding address the recipient has. It is called before // CCatRecip::HrCompletion. On any unhandleable errors, // this function sets a list resolve error (instead of // returning an error) // // Arguments: // CAType: Known address type of the forwarding address // szForwardingAddres: The forwarding address // // Returns: // S_OK: Success // // History: // jstamerj 980325 14:48:49: Created. // //------------------------------------------------------------- HRESULT CCatRecip::AddForward( CAT_ADDRESS_TYPE CAType, LPTSTR szForwardingAddress) { CatFunctEnterEx((LPARAM)this, "CCatRecip::AddForward"); DebugTrace((LPARAM)this, "CAType: %d", CAType); DebugTrace((LPARAM)this, "szForwardingAddress: %s", szForwardingAddress); HRESULT hr; CCatAddr *pCCatAddr; BOOL fPrimary; // // Is the forwarding address valid? // hr = HrValidateAddress(CAType, szForwardingAddress); if(FAILED(hr)) { ErrorTrace((LPARAM)this, "Forwarding address string is invalid"); ERROR_LOG_ADDR(this, "HrValidateAddress"); hr = HrHandleInvalidAddress(); goto CLEANUP; } hr = GetFPrimary(&fPrimary); ERROR_CLEANUP_LOG_ADDR(this, "GetFPrimary"); // // jstamerj 1998/07/31 19:58:53: // If we're in the primary chain, we MUST check to see if we're // in a forwarding loop before we call AddPrimary // This is the place to do it // if(fPrimary) { // // Check for a loop before adding the forwarding address // hr = CheckForLoop( CAType, szForwardingAddress, TRUE); // Check this object too (you could forward to yourself) ERROR_CLEANUP_LOG_ADDR(this, "CheckForLoop"); } // Create the new address object with the address we know about hr = CreateNewCatAddr(CAType, szForwardingAddress, &pCCatAddr, fPrimary); if(hr == CAT_IMSG_E_DUPLICATE) { _ASSERT(fPrimary == FALSE); DebugTrace((LPARAM)this, "Duplicate from CreateNewCatAddr, checking for a loop"); // // Did we hit duplicate because we're in a loop? // hr = CheckForLoop( CAType, szForwardingAddress, TRUE); // CHeck this object too if(FAILED(hr)) { ERROR_LOG_ADDR(this, "CheckForLoop"); } } else if(SUCCEEDED(hr)) { // // Since this is forwarding, we need to set the parent // ICatItem pointer (to be able to do loop detection) // hr = PutICategorizerItemParent( this, pCCatAddr); _ASSERT(SUCCEEDED(hr)); // // Resolve the new address // hr = pCCatAddr->HrResolveIfNecessary(); if(FAILED(hr)) { ErrorTrace((LPARAM)this, "Unable to dispatch query for forwarding address"); ERROR_LOG_ADDR(this, "pCCatAddr->HrResolveIfNecessary"); } pCCatAddr->Release(); } else { ERROR_LOG_ADDR(this, "CreateNewCatAddr"); } CLEANUP: if(FAILED(hr) && (hr != CAT_E_FORWARD_LOOP)) { ErrorTrace((LPARAM)this, "Setting the list resolve error:%08lx", hr); _VERIFY(SUCCEEDED(SetListResolveStatus(hr))); } CatFunctLeaveEx((LPARAM)this); return S_OK; } //+------------------------------------------------------------ // // Function: CCatRecip::HrCompleteItem_Default // // Synopsis: Handle the CompleteItem call; finally make decisions // about what to do concerning HrStatus failures. // // Arguments: NONE // // Returns: // S_OK: Success // // History: // jstamerj 1998/07/31 18:50:01: Created. // //------------------------------------------------------------- HRESULT CCatRecip::HrCompleteItem_Default() { HRESULT hr; CatFunctEnterEx((LPARAM)this, "CCatRecip::HrCompleteItem_Default"); hr = GetItemStatus(); // // Try to handle failures // if(FAILED(hr)) { hr = HandleFailure(hr); // // If we couldn't handle the recipient failure, fail the whole message // categorization // if(FAILED(hr)) { _VERIFY(SUCCEEDED(SetListResolveStatus(hr))); } } CatFunctLeaveEx((LPARAM)this); return S_OK; } //+------------------------------------------------------------ // // Function: CCatRecip::HandleFailure // // Synopsis: When a completion happens with a failure status, this is // the helper routine to handle the failure. If the failure can be // handeled, S_OK is returned. If not, the failure itself is returned // // Arguments: // HrFailure: the failure error code // // Returns: // S_OK: Success // or error from Mailmsg // // History: // jstamerj 1998/07/21 18:00:47: Created. // //------------------------------------------------------------- HRESULT CCatRecip::HandleFailure( HRESULT HrFailure) { HRESULT hr; CatFunctEnterEx((LPARAM)this, "CCatRecip::HandleFailure"); _ASSERT(FAILED(HrFailure)); switch(HrFailure) { case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND): { // // Address was not found but it is not a local address anyway // DebugTrace((LPARAM)this, "Remote address not found in DS"); hr = S_OK; } case CAT_E_FORWARD_LOOP: case CAT_IMSG_E_DUPLICATE: case CAT_E_NO_SMTP_ADDRESS: { // // This guy was either a failed resolve where it turns out we // already resolved the recipient (in another place in the // recip list) or a recipient in a detected loop. Don't do // anything here, DSN flags were/will be set in HandleLoopHead // hr = S_OK; break; } case CAT_E_BAD_RECIPIENT: { // // A generic recipient error code that indicates this // recipient should be NDR'd. An optional reason can be set // in the ICATEGORIZERITEM_HRNDR property // HRESULT hrReason; hr = GetHRESULT( ICATEGORIZERITEM_HRNDRREASON, &hrReason); if(FAILED(hr)) { // // Use the generic error code for the NDR reason also // hrReason = CAT_E_BAD_RECIPIENT; } ErrorTrace((LPARAM)this, "NDRing recipient with error code %08lx", hrReason); hr = SetUnresolved(hrReason); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "SetUnresolved"); } break; } case CAT_E_DELETE_RECIPIENT: { // // Don't deliver to this recipient // hr = SetDontDeliver(TRUE); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "SetDontDeliver"); } break; } default: { // // EmailIDStore is informing us of an unrecoverable error // There's nothing we can do to handle this error except // return it (HrCompletion will then SetListResolveStatus) // ErrorTrace((LPARAM)this, "Unrecoverable error returned from EmailIDStore: hr %08lx", HrFailure); hr = HrFailure; ERROR_LOG_ADDR(this, "--unhandeled recip error--"); break; } } CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::CheckForLoop // // Synopsis: Helper routine to check for a loop in our ancestors // // Arguments: // dwNumAddresses: Number of addresses to check // rgCAType: array of address types // rgpsz: array of string pointers // fCheckSelf: Check for a dupicate with this CCatAddr? // // Returns: // S_OK: Success, no loops // CAT_E_FORWARD_LOOP: Detected a loop and called HandleLoopHead // successfully // or error from CheckAncestorsForDuplicate/HandleLoopHead // // History: // jstamerj 1998/08/01 16:05:51: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::CheckForLoop( DWORD dwNumAddresses, CAT_ADDRESS_TYPE *rgCAType, LPSTR *rgpsz, BOOL fCheckSelf) { HRESULT hr; CCatAddr *pCCatAddrDup; CatFunctEnterEx((LPARAM)this, "CCatRecip::CheckForLoop"); hr = CheckAncestorsForDuplicate( dwNumAddresses, rgCAType, rgpsz, fCheckSelf, &pCCatAddrDup); if (hr == CAT_IMSG_E_DUPLICATE) { // // We've got a loop! // ErrorTrace((LPARAM)this, "Loop detected!"); ERROR_LOG_ADDR(this, "CheckAncestorsForDuplicate"); // // Generate the DSN on the CCatAddr at the top of the loop // hr = pCCatAddrDup->HandleLoopHead(); if(SUCCEEDED(hr)) { // // Return error to caller // hr = CAT_E_FORWARD_LOOP; } else { ERROR_LOG_ADDR(this, "pCCatAddrDup->HandleLoopHead"); } pCCatAddrDup->Release(); } DebugTrace((LPARAM)this, "Returning hr %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::CheckForLoop // // Synopsis: Same as above with different style parameters // // Arguments: // CAType: Addres type of pszAddress // pszAddress: Address string // fCheckSelf: Check this CCatAddr for a duplicate as well? // // Returns: // S_OK: Success // CAT_E_FORWARD_LOOP: Detected a loop and called HandleLoopHead // successfully // or error from CheckAncestorsForDuplicate/HandleLoopHead // // History: // jstamerj 1998/08/01 16:10:28: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::CheckForLoop( CAT_ADDRESS_TYPE CAType, LPTSTR pszAddress, BOOL fCheckSelf) { HRESULT hr; CatFunctEnterEx((LPARAM)this, "CCatRecip::CheckForLoop"); hr = CheckForLoop( 1, // Number of addresses &CAType, // TYpe array &pszAddress, // String ptr array fCheckSelf); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::HrSetDisplayNameProp // // Synopsis: Sets the mailmsg recipient display name property. // // Arguments: // pwszDisplayName: Display name value. If NULL, function will set // display name to "". // // Returns: // S_OK: Success // error from mailmsg // // History: // jstamerj 2001/04/03 17:21:17: Created. // //------------------------------------------------------------- HRESULT CIMsgRecipListAddr::HrSetDisplayNameProp( IN LPWSTR pwszDisplayName) { HRESULT hr = S_OK; DWORD dwRecipIdx = 0; IMailMsgRecipientsAdd *pRecipsAdd = NULL; CatFunctEnterEx((LPARAM)this, "CIMsgRecipListAddr::HrSetDisplayNameProp"); hr = GetIMsgRecipInfo(&pRecipsAdd, &dwRecipIdx, NULL, NULL); ERROR_CLEANUP_LOG_ADDR(this, "GetIMsgRecipInfo"); hr = pRecipsAdd->PutStringW( dwRecipIdx, IMMPID_RP_DISPLAY_NAME, pwszDisplayName ? pwszDisplayName : L""); ERROR_CLEANUP_LOG_ADDR(this, "pRecipsAdd->PutStringW"); hr = S_OK; CLEANUP: if(pRecipsAdd) pRecipsAdd->Release(); DebugTrace((LPARAM)this, "returning %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } // CIMsgRecipListAddr::HrSetDisplayNameProp //+------------------------------------------------------------ // // Function: CIMsgRecipListAddr::LogNDREvent // // Synopsis: Log an NDR event // // Arguments: // hrNDRReason: Reason for NDR // // Returns: Nothing // // History: // jstamerj 2001/12/12 23:39:20: Created. // //------------------------------------------------------------- VOID CIMsgRecipListAddr::LogNDREvent( IN HRESULT hrNDRReason) { HRESULT hr = S_OK; LPCSTR rgSubStrings[4]; CHAR szErr[16]; CHAR szAddress[CAT_MAX_INTERNAL_FULL_EMAIL]; CHAR szAddressType[CAT_MAX_ADDRESS_TYPE_STRING]; CatFunctEnter("CIMstRecipListAddr::LogNDREvent"); // // Get the address // hr = HrGetAddressStringFromICatItem( this, sizeof(szAddressType) / sizeof(szAddressType[0]), szAddressType, sizeof(szAddress) / sizeof(szAddress[0]), szAddress); if(FAILED(hr)) { // // Still log an event, but use "unknown" for address type/string // lstrcpyn(szAddressType, "unknown", sizeof(szAddressType) / sizeof(szAddressType[0])); lstrcpyn(szAddress, "unknown", sizeof(szAddress) / sizeof(szAddress[0])); hr = S_OK; } rgSubStrings[0] = szAddressType; rgSubStrings[1] = szAddress; _snprintf(szErr, sizeof(szErr), "0x%08lx", hrNDRReason); rgSubStrings[2] = szErr; rgSubStrings[3] = NULL; // // Can we log an event? // if(GetISMTPServerEx() == NULL) { FatalTrace((LPARAM)0, "Unable to log func NDR event; NULL pISMTPServerEx"); for(DWORD dwIdx = 0; dwIdx < 4; dwIdx++) { if( rgSubStrings[dwIdx] != NULL ) { FatalTrace((LPARAM)0, "Event String %d: %s", dwIdx, rgSubStrings[dwIdx]); } } } else { CatLogEvent( GetISMTPServerEx(), CAT_EVENT_NDR_RECIPIENT, 4, rgSubStrings, hrNDRReason, szErr, LOGEVENT_FLAG_ALWAYS, LOGEVENT_LEVEL_MAXIMUM, 3 ); } } //+------------------------------------------------------------ // // Function: CCatRecip::HandleLoopHead // // Synopsis: This is called when it is determined that this CCatAddr // is the first in a loop chain. It ensures an NDR will be generated // for this recipient // // Arguments: NONE // // Returns: // S_OK: Success // or error from MailMsg // // History: // jstamerj 1998/08/01 16:41:44: Created. // //------------------------------------------------------------- HRESULT CCatRecip::HandleLoopHead() { HRESULT hr = CAT_E_FORWARD_LOOP; CatFunctEnterEx((LPARAM)this, "CCatRecip::HandleLoopHead"); ERROR_LOG_ADDR(this, "--Handle Loop Head--"); // // Set the status on this recipient to loop error, and UNSET Don't // Deliver so an NDR gets generated // hr = SetRecipientStatus( CAT_E_BAD_RECIPIENT); if(SUCCEEDED(hr)) { // // Set the reason // hr = SetRecipientNDRCode( CAT_E_FORWARD_LOOP); if(SUCCEEDED(hr)) { // // Set DSN flags // hr = SetUnresolved(CAT_E_FORWARD_LOOP); if(SUCCEEDED(hr)) { // // Make sure DSN will be generated even if we previously // wern't planning to deliver to this recipient // hr = SetDontDeliver(FALSE); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "SetDontDeliver"); } } else { ERROR_LOG_ADDR(this, "SetUnresolved"); } } else { ERROR_LOG_ADDR(this, "SetRecipientNDRCode"); } } else { ERROR_LOG_ADDR(this, "SetRecipientStatus"); } DebugTrace((LPARAM)this, "Returning hr %08lx", hr); return hr; } //+------------------------------------------------------------ // // Function: CCatRecip::HrHandleInvalidAddress // // Synopsis: Do what needs to be done when an invalid address is // detected (either forwarding to an invalid address or a DL member // with an invalid address or a new address that is invalid) // // Arguments: NONE // // Returns: // S_OK: Success // // History: // jstamerj 1998/08/18 18:53:45: Created. // //------------------------------------------------------------- HRESULT CCatRecip::HrHandleInvalidAddress() { HRESULT hr = CAT_E_ILLEGAL_ADDRESS; CatFunctEnterEx((LPARAM)this, "CCatRecip::HandleInvalidAddress"); ERROR_LOG_ADDR(this, "--Handle Invalid Address--"); // // Set the status on this recipient to casue an NDR // hr = SetRecipientStatus( CAT_E_BAD_RECIPIENT); // // That should never fail // _ASSERT(SUCCEEDED(hr)); // // Set the status on this recipient to invalid address error // hr = SetRecipientNDRCode( CAT_E_ILLEGAL_ADDRESS); // // That should never fail // _ASSERT(SUCCEEDED(hr)); CatFunctLeaveEx((LPARAM)this); return S_OK; } //+------------------------------------------------------------ // // Function: CCatRecip::LookupCompletion // // Synopsis: Lookup completion routine for a recipient. Implement // defer logic so that RecipLookupCompletion is called after the // sender is resolved. // // Arguments: NONE // // Returns: NOTHING // // History: // jstamerj 1999/03/18 10:10:47: Created. // //------------------------------------------------------------- VOID CCatRecip::LookupCompletion() { CatFunctEnterEx((LPARAM)this, "CCatRecip::LookupCompletion"); INCREMENT_COUNTER(AddressLookupCompletions); m_pCICatListResolve->ResolveRecipientAfterSender(this); CatFunctLeaveEx((LPARAM)this); } // CCatRecip::LookupCompletion //+------------------------------------------------------------ // // Function: CCatRecip::RecipLookupCompletion // // Synopsis: Handle lookup completion from the emailidstore // // Arguments: // // Returns: NOTHING // // History: // jstamerj 1998/12/01 14:36:08: Created. // jstamerj 1999/03/18 10:08:26: Removed return value, removed async // completion to asyncctx. Renamed to // RecipLookupCompletion and removed // defer logic // //------------------------------------------------------------- VOID CCatRecip::RecipLookupCompletion() { HRESULT hr = S_OK; CatFunctEnterEx((LPARAM)this, "CCatRecip::RecipLookupCompletion"); hr = GetItemStatus(); if(FAILED(hr)) { // // Recipient status indicates failure -- decide now if we // should NDR // switch(hr) { case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND): { // // Address was not found. Determine if the original // address we looked up looks local mailbox or not. // INCREMENT_COUNTER(AddressLookupsNotFound); DebugTrace((LPARAM)this, "Address was not found in DS. Checking locality"); BOOL fNDR; hr = HrNdrUnresolvedRecip(&fNDR); if(SUCCEEDED(hr) && fNDR) { // // It's local and we need to NDR this recip // ErrorTrace((LPARAM)this, "Address appears to be local but was not found in DS. Setting unresolved property."); // // Set NDR Status and the reason // hr = SetRecipientStatus(CAT_E_BAD_RECIPIENT); if(SUCCEEDED(hr)) { hr = SetRecipientNDRCode(HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "SetRecipientNDRCode"); } } else { ERROR_LOG_ADDR(this, "SetRecipientStatus"); } } else if(FAILED(hr)) { ERROR_LOG_ADDR(this, "HrNdrUnresolvedRecip"); } break; } case CAT_E_MULTIPLE_MATCHES: case CAT_E_ILLEGAL_ADDRESS: case CAT_E_NO_FILTER: { // // Multiple entries for this guy exist in the DS or this guy // has an illegal address/forwards to an illegal address // ErrorTrace((LPARAM)this, "NDRing recipient, reason%08lx", hr); hr = SetRecipientNDRCode(hr); if(SUCCEEDED(hr)) { hr = SetRecipientStatus(CAT_E_BAD_RECIPIENT); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "SetRecipientStatus"); } } else { ERROR_LOG_ADDR(this, "SetRecipientNDRCode"); } break; } case CAT_E_BAD_RECIPIENT: { // // We processed this recipient earlier and returned defer // hr = S_OK; break; } default: { // // EmailIDStore is informing us of an unrecoverable error // There's nothing we can do to handle this error except // fail the entire message categorization // ErrorTrace((LPARAM)this, "Unrecoverable error returned from EmailIDStore: hr %08lx", hr); break; } } if(FAILED(hr)) goto CLEANUP; } // // Set this recipient's display name before triggering events // hr = HrSetDisplayName(); ERROR_CLEANUP_LOG_ADDR(this, "HrSetDisplayName"); // // If we handeled the error, go ahead and trigger events. // Otherwise, we're failing the message categorization so forget // it. // CCatAddr::LookupCompletion(); CLEANUP: if(FAILED(hr)) { ErrorTrace((LPARAM)this, "failing msg categorization hr %08lx", hr); _VERIFY(SUCCEEDED(SetListResolveStatus(hr))); } DecrPendingLookups(); // Matches IncPendingLookups() in CCatAdddr::HrDispatchQuery CatFunctLeaveEx((LPARAM)this); } //+------------------------------------------------------------ // // Function: CCatRecip::HrProcessItem_Default // // Synopsis: The default sink code for the ProcessItem event. // Override CCatAddr's implementation so that we can catch // and handle errors from AddAddresses // // Arguments: NONE // // Returns: // S_OK: Success // jstamerj 1998/12/01 14:47:15: // // History: // jstamerj 980325 14:57:05: Created. // //------------------------------------------------------------- HRESULT CCatRecip::HrProcessItem_Default() { HRESULT hr = S_OK; HRESULT hrItemStatus = S_OK; BOOL fPrimary = FALSE; CatFunctEnterEx((LPARAM)this, "CCatRecip::HrProcessItem_Default"); hr = GetFPrimary(&fPrimary); ERROR_CLEANUP_LOG_ADDR(this, "GetFPrimary"); // // CHeck the recipient status // hrItemStatus = GetItemStatus(); if(SUCCEEDED(hrItemStatus)) { // // Add all known addresses to the new address list // hr = HrAddNewAddressesFromICatItemAttr(); switch(hr) { case CAT_E_NO_SMTP_ADDRESS: // // If this is a primary recipient, NDR // Otherwise, fall through and delete this recipient // if(fPrimary) { DebugTrace((LPARAM)this, "NDRing primary recipient without SMTP address"); // NDR hr = SetRecipientNDRCode( CAT_E_NO_SMTP_ADDRESS); if(SUCCEEDED(hr)) hr = SetRecipientStatus( CAT_E_BAD_RECIPIENT); break; } else { // // Log event when we are deleting recip // ERROR_LOG_ADDR(this, "HrAddNewAddressesFromiCatItemAttr");; } // // Fall through for secondary recipients // case CAT_IMSG_E_DUPLICATE: case CAT_E_FORWARD_LOOP: case CAT_E_DELETE_RECIPIENT: DebugTrace((LPARAM)this, "AddAddresses failed, removing recip, hr %08lx", hr); // // Set the recip status to an error so we don't do // anything stupid later (like spinning off a resolve for // an alternate recipient later) // hr = SetRecipientStatus(hr); if(SUCCEEDED(hr)) { // // Don't deliver to this partialy resolved recipient // hr = SetDontDeliver(TRUE); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "SetDontDeliver"); } } else { ERROR_LOG_ADDR(this, "SetRecipientStatus"); } break; default: // Do nothing break; } } CLEANUP: // // Fail the categorization if the above calls failed // if(FAILED(hr)) { ErrorTrace((LPARAM)this, "Setting list resolve error %08lx", hr); hr = SetListResolveStatus(hr); _ASSERT(SUCCEEDED(hr)); } CatFunctLeaveEx((LPARAM)this); return S_OK; } //+------------------------------------------------------------ // // Function: CCatRecip::HrExpandItem_Default // // Synopsis: Handle the ExpandItem event // // Arguments: // pfnCompletion: Async completion routine // pContext: Context to pass to async completion // // Returns: // S_OK: Success, will NOT call async completion // MAILTRANSPORT_S_PENDING: Will call async completion // // History: // jstamerj 1998/07/31 18:29:57: Created. // //------------------------------------------------------------- HRESULT CCatRecip::HrExpandItem_Default( PFN_EXPANDITEMCOMPLETION pfnCompletion, PVOID pContext) { HRESULT hr; HRESULT hrRet = S_OK; CatFunctEnterEx((LPARAM)this, "CCatRecip::HrExpandItem_Default"); // // CHeck the recipient status // hr = GetItemStatus(); if(SUCCEEDED(hr)) { // // Call AddDlMember/AddForward once per DL member or // forwarding address // hr = HrAddDlMembersAndForwardingAddresses( pfnCompletion, pContext); DebugTrace((LPARAM)this, "HrAddDlMembersAndForwardingAddresses returned hr %08lx", hr); // // if hr is a failure value, something must have failed; so we fail // the whole message categorization // if(FAILED(hr)) { ERROR_LOG_ADDR(this, "HrAddDlMembersAndForwardingAddresses"); _VERIFY(SUCCEEDED(SetListResolveStatus(hr))); } else { // // Return the status returned from HrAddDlMembers... // It could be S_OK or S_PENDING // hrRet = hr; } } CatFunctLeaveEx((LPARAM)this); return hrRet; } //+------------------------------------------------------------ // // Function: CCatRecipient::HrNeedsResolving // // Synopsis: Determines if this recipient should be resolved or not // // Arguments: NONE // // Returns: // S_OK: Success, it needs resolving // S_FALSE: Success, it doesn't need to be resolved // // History: // jstamerj 1998/10/27 15:45:22: Created. // //------------------------------------------------------------- HRESULT CCatRecip::HrNeedsResolveing() { DWORD dwFlags; HRESULT hr; CatFunctEnterEx((LPARAM)this, "CCatRecip::HrNeedsResolveing"); dwFlags = GetCatFlags(); // // Do we resolve recipients at all? // if(! (dwFlags & SMTPDSFLAG_RESOLVERECIPIENTS)) return S_FALSE; #define ISTRUE( x ) ( (x) != 0 ? TRUE : FALSE ) // // Do we need to check if the address is local or not? // if( ISTRUE(dwFlags & SMTPDSFLAG_RESOLVELOCAL) != ISTRUE(dwFlags & SMTPDSFLAG_RESOLVEREMOTE)) { // // We're resolving either local or remote (not both) // BOOL fLocal; hr = HrIsOrigAddressLocal(&fLocal); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "HrIsOrigAddressLocal"); return hr; } // // Resolve if it's local and we're resolving local addrs // if( (dwFlags & SMTPDSFLAG_RESOLVELOCAL) && (fLocal)) return S_OK; // // Resolve if it's remote and we're resolving remote addrs // if( (dwFlags & SMTPDSFLAG_RESOLVEREMOTE) && (!fLocal)) return S_OK; // // else Don't resolve // return S_FALSE; } // // 2 possabilities -- local and remote bits are on OR local and // remote bits are off // _ASSERT( ISTRUE(dwFlags & SMTPDSFLAG_RESOLVELOCAL) == ISTRUE(dwFlags & SMTPDSFLAG_RESOLVEREMOTE)); if(dwFlags & SMTPDSFLAG_RESOLVELOCAL) { // // Both bits are on; Resolve // _ASSERT(dwFlags & SMTPDSFLAG_RESOLVEREMOTE); return S_OK; } else { // // local and remote are disabled; don't resolve // return S_FALSE; } } //+------------------------------------------------------------ // // Function: CCatRecip::HrSetDisplayName // // Synopsis: Set this recipients IMMPID_RP_DISPLAY_NAME property. // Normally, this is set to the "displayName" attribute. Hello, if // that attribute is not available, IMMPID_RP_DISPLAY_NAME will bet // set to L"". // // Arguments: NONE // // Returns: // S_OK: Success // E_OUTOFMEMORY // // History: // jstamerj 2001/04/03 16:25:27: Created. // //------------------------------------------------------------- HRESULT CCatRecip::HrSetDisplayName() { HRESULT hr = S_OK; ICategorizerParameters *pICatParams = NULL; ICategorizerItemAttributes *pICatItemAttr = NULL; ICategorizerItemRawAttributes *pIRaw = NULL; LPSTR pszDisplayNameAttr = NULL; DWORD dwcbDisplayName = 0; LPVOID pvDisplayName = NULL; LPWSTR pwszDisplayName = NULL; BOOL fEnumerating = FALSE; ATTRIBUTE_ENUMERATOR enumerator; CatFunctEnterEx((LPARAM)this, "CCatRecip::HrSetDisplayName"); pICatParams = GetICatParams(); _ASSERT(pICatParams); hr = pICatParams->GetDSParameterA( PHAT_DSPARAMETER_ATTRIBUTE_DISPLAYNAME, &pszDisplayNameAttr); if(FAILED(hr) || (pszDisplayNameAttr == NULL)) { hr = S_OK; goto CLEANUP; } hr = GetICategorizerItemAttributes( ICATEGORIZERITEM_ICATEGORIZERITEMATTRIBUTES, &pICatItemAttr); if(FAILED(hr) || (pICatItemAttr == NULL)) { pICatItemAttr = NULL; hr = S_OK; goto CLEANUP; } hr = pICatItemAttr->QueryInterface( IID_ICategorizerItemRawAttributes, (LPVOID *)&pIRaw); ERROR_CLEANUP_LOG_ADDR(this, "pICatItemAttr->QueryInterface(IID_ICategorizerItemRawAttributes)"); hr = pIRaw->BeginRawAttributeEnumeration( pszDisplayNameAttr, &enumerator); if(FAILED(hr)) { // // No display name // hr = S_OK; goto CLEANUP; } fEnumerating = TRUE; hr = pIRaw->GetNextRawAttributeValue( &enumerator, &dwcbDisplayName, &pvDisplayName); if(FAILED(hr)) { // // No display name // hr = S_OK; goto CLEANUP; } hr = HrConvertToUnicodeWithAlloc( CP_UTF8, dwcbDisplayName, (LPSTR) pvDisplayName, &pwszDisplayName); ERROR_CLEANUP_LOG_ADDR(this, "HrConvertToUnicodeWithAlloc"); hr = HrSetDisplayNameProp(pwszDisplayName); ERROR_CLEANUP_LOG_ADDR(this, "HrSetDisplayNameProp"); CLEANUP: if(pwszDisplayName) CodePageConvertFree(pwszDisplayName); if(fEnumerating) pIRaw->EndRawAttributeEnumeration( &enumerator); if(pIRaw) pIRaw->Release(); if(pICatItemAttr) pICatItemAttr->Release(); DebugTrace((LPARAM)this, "returning %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } // CCatRecip::HrSetDisplayName // // class CCatExpandableRecip // //+------------------------------------------------------------ // // Function: CCatExpandableRecip::HrAddDlMembersAndForwardingAddresses // // Synopsis: Dig through the ICatItemAttr and figure out wether to // call HrAddDlMembers or HrAddForwardingAddresses // // Arguments: // PFN_EXPANDITEMCOMPLETION pfnCompletion: Async completion routine // PVOID pContext: completion routine context // // Returns: // S_OK: Success, will not call completion routine // MAILTRANSPORT_S_PENDING: Will call completion routine // or error from mailmsg/icatitem/HrAddDlMembers/HrAddForwardingAddresses // // History: // jstamerj 1998/09/29 11:28:54: Created. // //------------------------------------------------------------- HRESULT CCatExpandableRecip::HrAddDlMembersAndForwardingAddresses( PFN_EXPANDITEMCOMPLETION pfnCompletion, PVOID pContext) { HRESULT hr; ICategorizerItemAttributes *pICatItemAttr = NULL; ICategorizerParameters *pICatParams; LPSTR pszX500DL = NULL; LPSTR pszSMTPDL = NULL; LPSTR pszDynamicDL = NULL; LPSTR pszObjectClassAttribute; LPSTR pszObjectClass; DLOBJTYPE dlt; ATTRIBUTE_ENUMERATOR enumerator; CatFunctEnterEx((LPARAM)this, "CCatExpandableRecip::HrAddDlMembersAndForwardingAddresses"); pICatParams = GetICatParams(); _ASSERT(pICatParams); hr = GetICategorizerItemAttributes( ICATEGORIZERITEM_ICATEGORIZERITEMATTRIBUTES, &pICatItemAttr); if(FAILED(hr)) { pICatItemAttr = NULL; goto CLEANUP; } // // Fetch DL objectclasses from IDSParams // On failure, the LPSTR will remain pointed to NULL // pICatParams->GetDSParameterA( DSPARAMETER_OBJECTCLASS_DL_X500, &pszX500DL); pICatParams->GetDSParameterA( DSPARAMETER_OBJECTCLASS_DL_SMTP, &pszSMTPDL); pICatParams->GetDSParameterA( DSPARAMETER_OBJECTCLASS_DL_DYNAMIC, &pszDynamicDL); // // Fetch objectclass attribute string from IDSParams // hr = pICatParams->GetDSParameterA( DSPARAMETER_ATTRIBUTE_OBJECTCLASS, &pszObjectClassAttribute); if(FAILED(hr)) goto CLEANUP; // // Now, try to match a DL objectClass with something in // pICatItemAttr // hr = pICatItemAttr->BeginAttributeEnumeration( pszObjectClassAttribute, &enumerator); ERROR_CLEANUP_LOG_ADDR(this, "pICatItemAttr->BeginAttributeEnumeartion(objectClass)"); hr = pICatItemAttr->GetNextAttributeValue( &enumerator, &pszObjectClass); for (dlt = DLT_NONE; SUCCEEDED(hr) && (dlt == DLT_NONE);) { if (pszX500DL && (lstrcmpi(pszObjectClass, pszX500DL) == 0)) { dlt = DLT_X500; } else if (pszSMTPDL && (lstrcmpi(pszObjectClass, pszSMTPDL) == 0)) { dlt = DLT_SMTP; } else if (pszDynamicDL && (lstrcmpi(pszObjectClass, pszDynamicDL) == 0)) { dlt = DLT_DYNAMIC; } hr = pICatItemAttr->GetNextAttributeValue( &enumerator, &pszObjectClass); } pICatItemAttr->EndAttributeEnumeration( &enumerator); // // Call the appropriate routine // if(dlt == DLT_NONE) { hr = HrAddForwardingAddresses(); _ASSERT(hr != MAILTRANSPORT_S_PENDING); ERROR_CLEANUP_LOG_ADDR(this, "HrAddForwardingAddresses"); } else { hr = HrAddDlMembers( dlt, pfnCompletion, pContext); ERROR_CLEANUP_LOG_ADDR(this, "HrAddDlMembers"); } CLEANUP: if(pICatItemAttr) pICatItemAttr->Release(); DebugTrace((LPARAM)this, "Returning hr %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CCatExpandableRecip::HrAddForwardingAddresses // // Synopsis: Call AddForward once for every forwarding address found // in ICatItemAttr // // Arguments: NONE // // Returns: // S_OK: Success // // History: // jstamerj 1998/09/29 13:56:37: Created. // //------------------------------------------------------------- HRESULT CCatExpandableRecip::HrAddForwardingAddresses() { HRESULT hr; ICategorizerParameters *pICatParams; ICategorizerItemAttributes *pICatItemAttr = NULL; ATTRIBUTE_ENUMERATOR enumerator; LPSTR pszForwardingSMTPAttribute; LPSTR pszForwardingSMTPAddress; BOOL fForwarding = FALSE; CatFunctEnterEx((LPARAM)this, "CCatExpandableRecip::HrAddForwardingAddresses"); pICatParams = GetICatParams(); _ASSERT(pICatParams); hr = GetICategorizerItemAttributes( ICATEGORIZERITEM_ICATEGORIZERITEMATTRIBUTES, &pICatItemAttr); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "GetICategorizerItemAttributes"); pICatItemAttr = NULL; goto CLEANUP; } // // Get the Forwarding address(es) // hr = pICatParams->GetDSParameterA( DSPARAMETER_ATTRIBUTE_FORWARD_SMTP, &pszForwardingSMTPAttribute); if(SUCCEEDED(hr)) { hr = pICatItemAttr->BeginAttributeEnumeration( pszForwardingSMTPAttribute, &enumerator); if(SUCCEEDED(hr)) { hr = pICatItemAttr->GetNextAttributeValue( &enumerator, &pszForwardingSMTPAddress); while(SUCCEEDED(hr)) { // // jstamerj 980317 15:53:34: Adding support for multiple // forwarding addresses -- send to all of them. // _VERIFY(SUCCEEDED( AddForward( CAT_SMTP, pszForwardingSMTPAddress ))); // // Remember that we're forwarding to at least one address // fForwarding = TRUE; hr = pICatItemAttr->GetNextAttributeValue( &enumerator, &pszForwardingSMTPAddress); } pICatItemAttr->EndAttributeEnumeration(&enumerator); } } // // Check our recipient status -- if it's a failure, that means // we're NDRing this recipient due to an invalid address, // forward loop, etc. In this case, we don't want to mark // "Don't Deliver" // if(fForwarding && SUCCEEDED(GetItemStatus())) { // // Don't deliver to the original recipient when we're // forwarding // hr = SetDontDeliver(TRUE); ERROR_CLEANUP_LOG_ADDR(this, "SetDontDeliver"); } else { // // Don't return errors from attribute enumeration calls // hr = S_OK; } CLEANUP: if(pICatItemAttr) pICatItemAttr->Release(); DebugTrace((LPARAM)this, "Returning hr %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CCatExpandableRecip::HrAddDlMembers // // Synopsis: Call AddDlMember (or AddDynamicDlMember) once for every // DlMember // // Arguments: // dlt: The type of the DL we're expanding // PFN_EXPANDITEMCOMPLETION pfnCompletion: Async completion routine // PVOID pContext: completion routine context // // Returns: // S_OK: Success, will not call completion routine // MAILTRANSPORT_S_PENDING: Will call completion routine // or error from mailmsg/icatitem // // History: // jstamerj 1998/09/29 14:09:56: Created. // //------------------------------------------------------------- HRESULT CCatExpandableRecip::HrAddDlMembers( DLOBJTYPE dlt, PFN_EXPANDITEMCOMPLETION pfnCompletion, PVOID pContext) { HRESULT hr; DWORD dwNumMembers = 0; PDLCOMPLETIONCONTEXT pDLContext = NULL; CatFunctEnterEx((LPARAM)this, "CCatExpandableRecip::HrAddDlMembers"); // // Since we're a DL, don't deliver to the DL object // hr = SetDontDeliver(TRUE); ERROR_CLEANUP_LOG_ADDR(this, "SetDontDeliver"); switch(dlt) { case DLT_X500: case DLT_SMTP: { LPSTR pszMemberAttribute; ICategorizerParameters *pICatParams; pICatParams = GetICatParams(); _ASSERT(pICatParams); hr = pICatParams->GetDSParameterA( DSPARAMETER_ATTRIBUTE_DL_MEMBERS, &pszMemberAttribute); if(SUCCEEDED(hr)) { hr = HrExpandAttribute( NULL, (dlt == DLT_X500) ? CAT_DN : CAT_SMTP, pszMemberAttribute, &dwNumMembers); if(SUCCEEDED(hr) && (dwNumMembers == 0)) { // // This might be a paged DL // Since paged DLs require additional special LDAP // lookups, use a store function to expand it -- it will // return S_PENDING and call AddDLMember once per member // pDLContext = AllocDlCompletionContext(this, pfnCompletion, pContext); if(pDLContext == NULL) { hr = E_OUTOFMEMORY; ERROR_LOG_ADDR(this, "AllocDlCompletionContext"); } else { hr = GetCCategorizer()->GetEmailIDStore()->HrExpandPagedDlMembers( this, GetResolveListContext(), (dlt == DLT_X500) ? CAT_DN : CAT_SMTP, DlExpansionCompletion, pDLContext); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "HrExpandPagedDlMembers"); } } } else if(FAILED(hr)) { ERROR_LOG_ADDR(this, "HrExpandAttribute"); } } else { ERROR_LOG_ADDR(this, "pICatParams->GetDSParameterA(members)"); } break; } case DLT_DYNAMIC: // // Since dynamic DLs require additional special LDAP lookups, // use a store function to expand them. It will return // S_PENDING and call AddDynamicDLMember once per member // pDLContext = AllocDlCompletionContext(this, pfnCompletion, pContext); if(pDLContext == NULL) { hr = E_OUTOFMEMORY; ERROR_LOG_ADDR(this, "AllocDlCompletionContext"); } else { hr = GetCCategorizer()->GetEmailIDStore()->HrExpandDynamicDlMembers( this, GetResolveListContext(), DlExpansionCompletion, pDLContext); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "HrExpandDynamicDlMembers"); } } } CLEANUP: if((hr != MAILTRANSPORT_S_PENDING) && (pDLContext != NULL)) delete pDLContext; DebugTrace((LPARAM)this, "returning hr %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CCatExpandableRecip::DlExpansionCompletion // // Synopsis: Handle completion of the expansion of a paged/dynamic DL // // Arguments: // hrStatus: Status of the expansion // pContext: Our context // // Returns: // S_OK: Success // // History: // jstamerj 1999/01/29 21:17:46: Created. // //------------------------------------------------------------- VOID CCatExpandableRecip::DlExpansionCompletion( HRESULT hrStatus, PVOID pContext) { PDLCOMPLETIONCONTEXT pDLContext; CatFunctEnterEx((LPARAM)pContext, "CCatExpandableRecip::DlExpansionCompletion"); pDLContext = (PDLCOMPLETIONCONTEXT)pContext; _ASSERT(pDLContext); DebugTrace((LPARAM)pContext, "hrStatus %08lx", hrStatus); if(FAILED(hrStatus)) { HRESULT hr = hrStatus; ErrorTrace((LPARAM)pContext, "DlExpansion failed hr %08lx", hrStatus); ERROR_LOG_ADDR_STATIC( pDLContext->pCCatAddr, "async", pDLContext->pCCatAddr, pDLContext->pCCatAddr->GetISMTPServerEx()); _VERIFY(SUCCEEDED(pDLContext->pCCatAddr->SetListResolveStatus(hrStatus))); } // // Notify that the expanditem event is complete // pDLContext->pfnCompletion(pDLContext->pContext); delete pDLContext; CatFunctLeaveEx((LPARAM)pContext); } //+------------------------------------------------------------ // // Function: CCatExpandableRecip::HrExpandAttribute // // Synopsis: Call AddDlMember(CAType, *) for every attribute value // // Arguments: // pICatItemAttr: Optional ICategorizerItemAttribute to use (if NULL, // will attempt retrieval from ICatItem) // CAType: The address type of the DL. // pszAttributeName: Attribute name to use // pdwNumberMembers: optional pointer to a DWORD to increment once // per member added (not initialized here) // // Returns: // S_OK: Success // or error from ICatItemAttr // // History: // jstamerj 1998/09/23 17:54:57: Created. // //------------------------------------------------------------- HRESULT CCatExpandableRecip::HrExpandAttribute( ICategorizerItemAttributes *pICatItemAttrIN, CAT_ADDRESS_TYPE CAType, LPSTR pszAttributeName, PDWORD pdwNumberMembers) { HRESULT hr; CMembersInsertionRequest *pCInsertionRequest = NULL; ICategorizerItemAttributes *pICatItemAttr = NULL; ICategorizerUTF8Attributes *pIUTF8 = NULL; ATTRIBUTE_ENUMERATOR enumerator; DWORD dwcMembers; BOOL fEndEnumeration = FALSE; CatFunctEnterEx((LPARAM)this, "CCatExpandableRecip::HrExpandAttribute"); _ASSERT(pszAttributeName); if(pICatItemAttrIN) { // // Use specified attributes interface // pICatItemAttr = pICatItemAttrIN; pICatItemAttr->AddRef(); } else { // // Use default attribute interface // hr = GetICategorizerItemAttributes( ICATEGORIZERITEM_ICATEGORIZERITEMATTRIBUTES, &pICatItemAttr); if(FAILED(hr)) { pICatItemAttr = NULL; ERROR_LOG_ADDR(this, "GetICategorizerItemAttributes"); goto CLEANUP; } } hr = pICatItemAttr->QueryInterface( IID_ICategorizerUTF8Attributes, (LPVOID *) &pIUTF8); ERROR_CLEANUP_LOG_ADDR(this, "pICatItemAttr->QueryInterface(utf8)"); DebugTrace((LPARAM)this, "Attribute name: %s", pszAttributeName); hr = pIUTF8->BeginUTF8AttributeEnumeration( pszAttributeName, &enumerator); ERROR_CLEANUP_LOG_ADDR(this, "pIUTF8->BeginUTF8AttributeEnumeration"); fEndEnumeration = TRUE; // // Get the count of values (members) // hr = pIUTF8->CountUTF8AttributeValues( &enumerator, &dwcMembers); ERROR_CLEANUP_LOG_ADDR(this, "pIUTF8->CountUTF8AttributeValues"); if(pdwNumberMembers) (*pdwNumberMembers) += dwcMembers; if(dwcMembers > 0) { pCInsertionRequest = new CMembersInsertionRequest( this, pIUTF8, &enumerator, CAType); if(pCInsertionRequest == NULL) { hr = E_OUTOFMEMORY; ERROR_LOG_ADDR(this, "new CMembersInsertionRequest"); goto CLEANUP; } // // The destructor of CMembersInseritonRequest will now end the // attribute enumeration // fEndEnumeration = FALSE; hr = HrInsertInsertionRequest( pCInsertionRequest); ERROR_CLEANUP_LOG_ADDR(this, "HrInsertInsertionRequest"); } CLEANUP: // // Don't return prop not found errors // if((hr == CAT_E_PROPNOTFOUND) || (hr == HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS))) hr = S_OK; if(fEndEnumeration) pIUTF8->EndUTF8AttributeEnumeration(&enumerator); if(pIUTF8) pIUTF8->Release(); if(pICatItemAttr) pICatItemAttr->Release(); if(pCInsertionRequest) pCInsertionRequest->Release(); DebugTrace((LPARAM)this, "Returning hr %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CCatDLRecip::CCatDLRecip // // Synopsis: Construct the DL recipient // // Arguments: // pIListResolve: the list resolve object to handle expanding this DL // // Returns: NOTHING // // History: // jstamerj 1998/12/05 16:15:20: Created. // //------------------------------------------------------------- CCatDLRecip::CCatDLRecip( CICategorizerDLListResolveIMP *pIListResolve) : CCatRecip(pIListResolve) { _ASSERT(pIListResolve); m_pIListResolve = pIListResolve; m_pIListResolve->AddRef(); } //+------------------------------------------------------------ // // Function: CCatDLRecip::~CCatDLRecip // // Synopsis: release references held by this object // // Arguments: NONE // // Returns: NOTHING // // History: // jstamerj 1998/12/05 16:19:47: Created. // //------------------------------------------------------------- CCatDLRecip::~CCatDLRecip() { if(m_pIListResolve) m_pIListResolve->Release(); } //+------------------------------------------------------------ // // Function: CCatDLRecip::LookupCompletion // // Synopsis: Handle the DS lookup completion of a recipient we're only expanding for // // Arguments: NONE // // Returns: NOTHING // // History: // jstamerj 1998/12/05 15:51:13: Created. // jstamerj 1999/03/18 10:14:35: Removed return value; removed async // completion to asyncctx // //------------------------------------------------------------- VOID CCatDLRecip::LookupCompletion() { HRESULT hr; CatFunctEnterEx((LPARAM)this, "CCatDLRecip::HrLookupCompletion"); hr = GetItemStatus(); if(FAILED(hr)) { switch(hr) { case HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND): // // This object was not in the DS. We do nothing // hr = S_OK; break; case CAT_E_MULTIPLE_MATCHES: case CAT_E_ILLEGAL_ADDRESS: // // These are caused by DS misconfiguration. Instead of // failing the entire expand, we'll just ignore the // recipients that have these problems. // hr = S_OK; break; default: // // We have no choice but to fail the list resolve for any // other error // ErrorTrace((LPARAM)this, "Unrecoverable error returned from EmailIDStore: hr %08lx", hr); ERROR_LOG_ADDR(this, "--emailIDStore--"); break; } } else { // // Original recipient status was SUCCESS // // Call HrAddNewAddressesFromICatItemAttr -- it will dig out all // the addresses from ICatItemAttr and call // CCatDLRecip::HrAddAddresses -- here we will notify the // DLListResolve of the new addresses // hr = HrAddNewAddressesFromICatItemAttr(); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "HrAddNewAddressesFromICatItemAttr"); } if(SUCCEEDED(hr) || (hr == CAT_E_NO_SMTP_ADDRESS)) { // // Should we keep resolving? // hr = m_pIListResolve->HrContinueResolve(); if(hr == S_OK) { // // Assume async operation // IncPendingLookups(); // // Go ahead and expand this if it's a DL // hr = HrAddDlMembersAndForwardingAddresses( ExpansionCompletion, this); if(hr != MAILTRANSPORT_S_PENDING) DecrPendingLookups(); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "HrAddDlMembersAndForwardingAddresses"); } // // MUST preserve return code: MAILTRANSPORT_S_PENDING // } else if(hr == S_FALSE) { hr = S_OK; } else { ERROR_LOG_ADDR(this, "HrContinueResolve"); } } if((hr == CAT_IMSG_E_DUPLICATE) || (hr == CAT_E_FORWARD_LOOP)) { DebugTrace((LPARAM)this, "Duplicate collision on AddAddresses hr %08lx", hr); // // We're just trying to expand DL -- we don't care about // loops and such. However, let's not leave a partially // resolved recipient in the recip list // hr = SetDontDeliver(TRUE); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "SetDontDeliver"); } } } // // Fail the DL expansion if any of the above fails // if(FAILED(hr)) { ErrorTrace((LPARAM)this, "Setting list resolve error %08lx", hr); hr = SetListResolveStatus(hr); _ASSERT(SUCCEEDED(hr)); } DecrPendingLookups(); // Matches IncPendingLookups() in CCatAdddr::HrDispatchQuery CatFunctLeaveEx((LPARAM)this); } //+------------------------------------------------------------ // // Function: CCatDLRecip::HrAddAddresses // // Synopsis: Catch the default AddAddresses and notify m_pIListResolve // // Arguments: // dwNumAddresses: the number of addresses found // rgCAType: array of address types // rgpsz: array of address strings // // Returns: // S_OK: Success // return value from CIMsgRecipListAddr::HrAddAddresses // // History: // jstamerj 1998/12/05 16:42:12: Created. // //------------------------------------------------------------- HRESULT CCatDLRecip::HrAddAddresses( DWORD dwNumAddresses, CAT_ADDRESS_TYPE *rgCAType, LPTSTR *rgpsz) { HRESULT hr; CatFunctEnterEx((LPARAM)this, "CCatDLRecip::HrAddAddresses"); hr = m_pIListResolve->HrNotifyAddress( dwNumAddresses, rgCAType, rgpsz); if(SUCCEEDED(hr)) { // // Add addresses to mailmsg // hr = CIMsgRecipListAddr::HrAddAddresses( dwNumAddresses, rgCAType, rgpsz); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "CIMsgRecipListAddr::HrAddAddresses"); } } else { ERROR_LOG_ADDR(this, "m_pIListResolve->HrNotifyAddress"); } DebugTrace((LPARAM)this, "returning hr %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CCatDLRecip::AddForward // // Synopsis: Catch the AddForward call. Since we do not care about // forwarding addresses, do nothing // // Arguments: // CAType: addresses type of the forwarding address // pszForwardingAddress: the address string // // Returns: // S_OK: Success // // History: // jstamerj 1998/12/05 16:52:58: Created. // //------------------------------------------------------------- HRESULT CCatDLRecip::AddForward( CAT_ADDRESS_TYPE CAType, LPSTR pszForwardingAddress) { return S_OK; } //+------------------------------------------------------------ // // Function: CCatDLRecip::AddDLMember // // Synopsis: Kick off a resolve after we discover this object is a DL // // Arguments: // CAType: address type we have for this DL member // pszAddress: address we have for this DL member // // Returns: // S_OK: Success // // History: // jstamerj 1998/12/05 16:54:47: Created. // //------------------------------------------------------------- HRESULT CCatDLRecip::AddDLMember( CAT_ADDRESS_TYPE CAType, LPSTR pszAddress) { HRESULT hr; CatFunctEnterEx((LPARAM)this, "CCatDLRecip:AddDlMember"); // // Notify the DLListResolve about the new address // hr = m_pIListResolve->HrNotifyAddress( 1, &CAType, &pszAddress); // // Do we keep resolving? // if(hr == S_OK) { // // kick off async resolve // hr = CCatRecip::AddDLMember( CAType, pszAddress); if(FAILED(hr)) { ERROR_LOG_ADDR(this, "CCatRecip::AddDLMember"); } } else if(SUCCEEDED(hr)) { // // Remove S_FALSE // hr = S_OK; } else { ERROR_LOG_ADDR(this, "m_pIListResolve->HrNotifyAddress"); } DebugTrace((LPARAM)this, "returning hr %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } //+------------------------------------------------------------ // // Function: CCatDLRecip::ExpansionCompletion // // Synopsis: Handle async DL expansion completion // // Arguments: // pContext: a CCatDLRecip in disguise // // Returns: NOTHING // // History: // jstamerj 1999/03/18 13:26:20: Created. // //------------------------------------------------------------- VOID CCatDLRecip::ExpansionCompletion( PVOID pContext) { CCatDLRecip *pRecip; CatFunctEnterEx((LPARAM)pContext, "CCatDLRecip::ExpansionCompletion"); pRecip = (CCatDLRecip *)pContext; pRecip->DecrPendingLookups(); CatFunctLeaveEx((LPARAM)pContext); } // CCatDLRecip::ExpansionCompletion //+------------------------------------------------------------ // // Function: CMembersInsertionRequest::HrInsertSearches // // Synopsis: Insert LDAP searches for the next few DL members // // Arguments: // dwcSearches: Number of searches we may insert // // Returns: // S_OK: Success // error: Stop calling HrInsertSearches // // History: // jstamerj 1999/03/25 13:56:46: Created. // //------------------------------------------------------------- HRESULT CMembersInsertionRequest::HrInsertSearches( DWORD dwcSearches) { HRESULT hr = S_OK; LPSTR pszMember = NULL; DWORD dwc; CatFunctEnterEx((LPARAM)this, "CMembersInsertionRequest::HrInsertSearches"); dwc = 0; while(SUCCEEDED(hr) && (dwc < dwcSearches)) { hr = m_pUTF8Attributes->GetNextUTF8AttributeValue( &m_enumerator, &pszMember); // // GetNextUTF8AttributeValue will return HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS) // when we are at the end of the enumeration. // if(SUCCEEDED(hr)) { hr = m_pDLRecipAddr->AddDLMember(m_CAType, pszMember); if(hr == S_OK) dwc++; else if(FAILED(hr)) { ERROR_LOG_ADDR(m_pDLRecipAddr, "m_pDLRecipAddr->AddDLMember"); _VERIFY(SUCCEEDED(m_pDLRecipAddr->SetListResolveStatus(hr))); } } } if(FAILED(hr)) m_hr = hr; DebugTrace((LPARAM)this, "returning %08lx", hr); CatFunctLeaveEx((LPARAM)this); return hr; } // CMembersInsertionRequest::HrInsertSearches //+------------------------------------------------------------ // // Function: CMemberInsertionRequest::NotifyDeQueue // // Synopsis: Callback to notify us that our request is being removed // from the store's queue // // Arguments: NONE // // Returns: NOTHING // // History: // jstamerj 1999/03/25 14:11:12: Created. // //------------------------------------------------------------- VOID CMembersInsertionRequest::NotifyDeQueue( HRESULT hrReason) { HRESULT hr; CatFunctEnterEx((LPARAM)this, "CMemberInsertionRequest::NotifyDeQueue"); // // If we still have things left to resolve, reinsert this // insertion request // hr = hrReason; if(SUCCEEDED(m_hr)) { if( (hr == CAT_E_DBCONNECTION) || (hr == HRESULT_FROM_WIN32(ERROR_CANCELLED))) { hr = m_pDLRecipAddr->HrInsertInsertionRequest( this); } if(FAILED(hr)) { ERROR_LOG_ADDR(m_pDLRecipAddr, "m_pDLRecipAddr->HrInsertInsertionRequest"); _VERIFY(SUCCEEDED(m_pDLRecipAddr->SetListResolveStatus(hr))); } } CatFunctLeaveEx((LPARAM)this); } // CMemberInsertionRequest::NotifyDeQueue
28.264998
129
0.544024
[ "object" ]
99118ac9b1152659576efe40ad791ed406ba0829
4,577
cpp
C++
Engine/ac/roomobject.cpp
proteanblank/ags
025640c60dbf77d84d213d3994ebcc6600979476
[ "Artistic-2.0" ]
null
null
null
Engine/ac/roomobject.cpp
proteanblank/ags
025640c60dbf77d84d213d3994ebcc6600979476
[ "Artistic-2.0" ]
null
null
null
Engine/ac/roomobject.cpp
proteanblank/ags
025640c60dbf77d84d213d3994ebcc6600979476
[ "Artistic-2.0" ]
null
null
null
//============================================================================= // // Adventure Game Studio (AGS) // // Copyright (C) 1999-2011 Chris Jones and 2011-20xx others // The full list of copyright holders can be found in the Copyright.txt // file, which is part of this source code distribution. // // The AGS source code is provided under the Artistic License 2.0. // A copy of this license can be found in the file License.txt and at // http://www.opensource.org/licenses/artistic-license-2.0.php // //============================================================================= #include "ac/roomobject.h" #include "ac/common.h" #include "ac/common_defines.h" #include "ac/gamesetupstruct.h" #include "ac/gamestate.h" #include "ac/object.h" #include "ac/runtime_defines.h" #include "ac/viewframe.h" #include "debug/debug_log.h" #include "main/update.h" #include "util/stream.h" #include "util/string_utils.h" using namespace AGS::Common; extern std::vector<ViewStruct> views; extern GameState play; extern GameSetupStruct game; RoomObject::RoomObject() { x = y = 0; transparent = 0; tint_r = tint_g = 0; tint_b = tint_level = 0; tint_light = 0; zoom = 0; last_width = last_height = 0; num = 0; baseline = 0; view = loop = frame = 0; wait = moving = 0; cycling = 0; overall_speed = 0; on = 0; flags = 0; blocking_width = blocking_height = 0; } int RoomObject::get_width() { if (last_width == 0) return game.SpriteInfos[num].Width; return last_width; } int RoomObject::get_height() { if (last_height == 0) return game.SpriteInfos[num].Height; return last_height; } int RoomObject::get_baseline() { if (baseline < 1) return y; return baseline; } void RoomObject::UpdateCyclingView(int ref_id) { if (on != 1) return; if (moving>0) { do_movelist_move(&moving,&x,&y); } if (cycling==0) return; if (view == RoomObject::NoView) return; if (wait>0) { wait--; return; } if (!CycleViewAnim(view, loop, frame, cycling < ANIM_BACKWARDS, cycling % ANIM_BACKWARDS)) cycling = 0; // finished animating ViewFrame*vfptr=&views[view].loops[loop].frames[frame]; if (vfptr->pic > UINT16_MAX) debug_script_warn("Warning: object's (id %d) sprite %d is outside of internal range (%d), reset to 0", ref_id, vfptr->pic, UINT16_MAX); num = Math::InRangeOrDef<uint16_t>(vfptr->pic, 0); if (cycling == 0) return; wait=vfptr->speed+overall_speed; CheckViewFrame(view, loop, frame, anim_volume); } void RoomObject::ReadFromSavegame(Stream *in, int save_ver) { x = in->ReadInt32(); y = in->ReadInt32(); transparent = in->ReadInt32(); tint_r = in->ReadInt16(); tint_g = in->ReadInt16(); tint_b = in->ReadInt16(); tint_level = in->ReadInt16(); tint_light = in->ReadInt16(); zoom = in->ReadInt16(); last_width = in->ReadInt16(); last_height = in->ReadInt16(); num = in->ReadInt16(); baseline = in->ReadInt16(); view = in->ReadInt16(); loop = in->ReadInt16(); frame = in->ReadInt16(); wait = in->ReadInt16(); moving = in->ReadInt16(); cycling = in->ReadInt8(); overall_speed = in->ReadInt8(); on = in->ReadInt8(); flags = in->ReadInt8(); blocking_width = in->ReadInt16(); blocking_height = in->ReadInt16(); if (save_ver >= 1) { name = StrUtil::ReadString(in); } if (save_ver >= 2) { anim_volume = in->ReadInt8(); in->ReadInt8(); // reserved to fill int32 in->ReadInt8(); in->ReadInt8(); } } void RoomObject::WriteToSavegame(Stream *out) const { out->WriteInt32(x); out->WriteInt32(y); out->WriteInt32(transparent); out->WriteInt16(tint_r); out->WriteInt16(tint_g); out->WriteInt16(tint_b); out->WriteInt16(tint_level); out->WriteInt16(tint_light); out->WriteInt16(zoom); out->WriteInt16(last_width); out->WriteInt16(last_height); out->WriteInt16(num); out->WriteInt16(baseline); out->WriteInt16(view); out->WriteInt16(loop); out->WriteInt16(frame); out->WriteInt16(wait); out->WriteInt16(moving); out->WriteInt8(cycling); out->WriteInt8(overall_speed); out->WriteInt8(on); out->WriteInt8(flags); out->WriteInt16(blocking_width); out->WriteInt16(blocking_height); StrUtil::WriteString(name, out); out->WriteInt8(anim_volume); out->WriteInt8(0); // reserved to fill int32 out->WriteInt8(0); out->WriteInt8(0); }
27.572289
110
0.614813
[ "object", "vector" ]
9912a9b4bb694f220a363321b77d95abdf098636
979
cpp
C++
Graph/allpathfromsourcetotarget.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
null
null
null
Graph/allpathfromsourcetotarget.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
null
null
null
Graph/allpathfromsourcetotarget.cpp
thisisnitish/cp-dsa-
9ae94930b65f8dc293d088e9148960939b9f6fa4
[ "MIT" ]
null
null
null
/* Leetcode Question 797. All Paths From Source to Target https://leetcode.com/problems/all-paths-from-source-to-target/ */ class Solution { public: // Time: O(2^n), Space: O(n) vector<vector<int> > result; vector<vector<int> > allPathsSourceTarget(vector<vector<int> > &graph) { int source = 0; int size = graph.size() - 1; vector<int> path; dfs(graph, source, size, path); return result; } void dfs(vector<vector<int> > &graph, int source, int size, vector<int> &path) { // add the node to the path path.push_back(source); // base case if (source == size) { result.push_back(path); return; } for (auto v : graph[source]) { dfs(graph, v, size, path); /*pop here because you need to start from another edge in order to reach target*/ path.pop_back(); } } };
23.309524
82
0.539326
[ "vector" ]
99208c1c41bc99d9239c9c6bbfd2a85e30c38559
881
cpp
C++
main.cpp
beckylum0216/testMNIST
366574af2a8213e890eaa20576f4579ffea04584
[ "MIT" ]
null
null
null
main.cpp
beckylum0216/testMNIST
366574af2a8213e890eaa20576f4579ffea04584
[ "MIT" ]
null
null
null
main.cpp
beckylum0216/testMNIST
366574af2a8213e890eaa20576f4579ffea04584
[ "MIT" ]
null
null
null
#include <iostream> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include "UtilityFunctions.h" void DisplayImage() { std::string imgFile = "../mnist/train-images.idx3-ubyte"; std::string lblFile = "../mnist/train-labels.idx1-ubyte"; ImageHeader imgHdr; LabelHeader lblHdr; UtilityFunctions uf; std::cout << "Running Display Image..." << std::endl; imgHdr = uf.ReadImageHeader(imgFile); lblHdr = uf.ReadLabelHeader(lblFile); std::vector<cv::Mat> imageMatrix; imageMatrix = uf.ReadImageFile(imgFile, imgHdr); cv::namedWindow("Test OpenCV", cv::WINDOW_AUTOSIZE); for(int ii = 0; ii < imgHdr.maxImages; ii += 1) { cv::imshow("Test OpenCV", imageMatrix[ii]); } cv::waitKey(0); } int main() { std::cout << "Running main..." << std::endl; DisplayImage(); return 0; }
20.022727
61
0.639047
[ "vector" ]
99272d7b51f05f1c23750323861214008d0369f6
270
cpp
C++
cpp/main.cpp
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
1
2019-10-17T08:34:55.000Z
2019-10-17T08:34:55.000Z
cpp/main.cpp
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
1
2020-05-24T08:32:13.000Z
2020-05-24T08:32:13.000Z
cpp/main.cpp
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdlib> #include "select.h" #include <vector> int main (int argc, char *argv[]) { int question_number = atoi(argv[argc-1]); run(question_number); std::cout << "Congratulations, you pass the examination!" << std::endl; return 0; }
24.545455
74
0.681481
[ "vector" ]
99360c2ded4fbe6c1b92b8a0141a2ce6d7f95d52
1,171
cpp
C++
tree/postorder(ilterative)IMP.cpp
ishan0805/gfg_must_do
10af0a6d37d0ac338c7bd235e7aa6190abc9d750
[ "MIT" ]
null
null
null
tree/postorder(ilterative)IMP.cpp
ishan0805/gfg_must_do
10af0a6d37d0ac338c7bd235e7aa6190abc9d750
[ "MIT" ]
null
null
null
tree/postorder(ilterative)IMP.cpp
ishan0805/gfg_must_do
10af0a6d37d0ac338c7bd235e7aa6190abc9d750
[ "MIT" ]
null
null
null
class Solution { public: vector<int> postOrder(Node *root) { stack<Node *> st; vector<int> ans; while (root != NULL || (!st.empty())) { while (root != nullptr) { st.push(root); root = root->left; } root = st.top(); if (root->right == nullptr) { st.pop(); ans.push_back(root->data); auto temp = st.top(); // Imp check if current is the right child of the elemnt in the stack // if so then you should remove the stack element while (!st.empty() && root == temp->right) { ans.push_back(temp->data); root = temp; st.pop(); if (!st.empty()) temp = st.top(); else temp->right = NULL; } root = temp->right; } else { root = root->right; } } return ans; } };
26.613636
85
0.353544
[ "vector" ]
993b3ebad5b0186adbe18a8467b74170b3a0108a
1,889
cpp
C++
UVa Online Judge/v1/154.cpp
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
1
2021-12-08T08:58:43.000Z
2021-12-08T08:58:43.000Z
UVa Online Judge/v1/154.cpp
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
UVa Online Judge/v1/154.cpp
mjenrungrot/algorithm
e0e8174eb133ba20931c2c7f5c67732e4cb2b703
[ "MIT" ]
null
null
null
/*============================================================================= # Author: Teerapat Jenrungrot - https://github.com/mjenrungrot/ # FileName: 154.cpp # Description: UVa Online Judge - 154 =============================================================================*/ #include <cstdio> #include <cstring> #include <vector> using namespace std; char str[100]; vector<char> V[10000]; vector<char> parse() { vector<char> ans; for (int k = 1; k <= 5; k++) { for (int i = 1; i <= 5 and (int) ans.size() < k; i++) { int pos1 = 0 + (i - 1) * 4; int pos2 = 2 + (i - 1) * 4; if (k == 1 and str[pos2] == 'P') ans.push_back(str[pos1]); if (k == 2 and str[pos2] == 'G') ans.push_back(str[pos1]); if (k == 3 and str[pos2] == 'A') ans.push_back(str[pos1]); if (k == 4 and str[pos2] == 'S') ans.push_back(str[pos1]); if (k == 5 and str[pos2] == 'N') ans.push_back(str[pos1]); } } return ans; } int change(vector<char> cc, vector<char> original) { int ans = 0; for (int i = 0; i < 5; i++) if (cc[i] != original[i]) ans++; return ans; } int main() { // freopen("in","r",stdin); while (true) { int counter = 0; while (scanf("%s", str) == 1) { if (str[0] == '#') goto end; if (str[0] == 'e') break; V[++counter] = parse(); } int min_change = 1e9, minidx = 1; for (int i = 1; i <= counter; i++) { int tmp = 0; for (int j = 1; j <= counter; j++) { if (j == i) continue; tmp += change(V[j], V[i]); } if (tmp < min_change) { min_change = tmp; minidx = i; } } printf("%d\n", minidx); } end: return 0; }
29.515625
79
0.404976
[ "vector" ]
993c06b548875ee4e973ac9ed4901a8d38d3f15e
804
hpp
C++
include/pieces/queen.hpp
Creris/chess
e668ae29697df6a4674d9be3c8f57d9b965030a4
[ "MIT" ]
null
null
null
include/pieces/queen.hpp
Creris/chess
e668ae29697df6a4674d9be3c8f57d9b965030a4
[ "MIT" ]
7
2019-05-28T21:53:11.000Z
2019-06-06T23:48:44.000Z
include/pieces/queen.hpp
Creris/chess
e668ae29697df6a4674d9be3c8f57d9b965030a4
[ "MIT" ]
null
null
null
#pragma once #ifndef PIECE_QUEEN_HEADER_H_ #define PIECE_QUEEN_HEADER_H_ /* This file contains: - Definition of PieceQueen which derives from a generic piece. */ #include "generic.hpp" class PieceQueen : public PieceGeneric { public: PieceQueen(Color c) : PieceGeneric(c) {} ~PieceQueen() = default; PieceQueen(const PieceQueen&) = default; PieceQueen(PieceQueen&&) noexcept = default; PieceQueen& operator=(const PieceQueen&) = default; PieceQueen& operator=(PieceQueen&&) noexcept = default; // Inherited via PieceGeneric bool canMove(Position fromPos, Position toPos, const BoardState& state) const override; PieceType getType() const override; std::vector<Position> getAllAvailableMoves(Position fromPos, const BoardState& state) const override; }; #endif // PIECE_QUEEN_HEADER_H_
27.724138
102
0.7699
[ "vector" ]
993da4d4f714320c12db7c88057850817c1dd893
16,130
cpp
C++
GP/PPieces.cpp
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
4
2020-06-22T16:59:51.000Z
2020-06-28T19:35:23.000Z
GP/PPieces.cpp
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
59
2020-09-12T23:54:16.000Z
2022-03-24T18:51:43.000Z
GP/PPieces.cpp
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
4
2020-06-22T13:37:40.000Z
2021-01-29T12:42:54.000Z
// PPieces.cpp // // Copyright (c) 1994-2020 By Dale L. Larson, All Rights Reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #include <stdafx.h> #include "WinExt.h" #include "Gp.h" #include "GamDoc.h" #include "GMisc.h" #include "Trays.h" #include "DrawObj.h" #include "PBoard.h" #include "PPieces.h" #include "CDib.h" #include "MapFace.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #ifdef _DEBUG #define new DEBUG_NEW #endif /////////////////////////////////////////////////////////////////////// CPieceTable::CPieceTable() { m_wReserved1 = 0; m_wReserved2 = 0; m_wReserved3 = 0; m_wReserved4 = 0; // ------ // m_pPMgr = NULL; } /////////////////////////////////////////////////////////////////////// // Loads array with piece ID's that aren't already marked as // is in use and are part of a particular piece set. void CPieceTable::LoadUnusedPieceList(std::vector<PieceID>& pPTbl, size_t nPieceSet, BOOL bClear) { ASSERT(m_pPMgr != NULL); CPieceSet& pPSet = m_pPMgr->GetPieceSet(nPieceSet); LoadUnusedPieceList(pPTbl, pPSet, bClear); } void CPieceTable::LoadUnusedPieceList(std::vector<PieceID>& pPTbl, const CPieceSet& pPceSet, BOOL bClear) { if (bClear) pPTbl.clear(); const std::vector<PieceID>& pPidTbl = pPceSet.GetPieceIDTable(); for (size_t i = 0; i < pPidTbl.size(); i++) { PieceID pid = pPidTbl.at(i); if (!GetPiece(pid).IsUsed()) pPTbl.push_back(pid); } } /////////////////////////////////////////////////////////////////////// // Marks all piece ID's corresponding to the input array's entries // as unused. void CPieceTable::SetPieceListAsUnused(const std::vector<PieceID>& pPTbl) { for (size_t i = 0; i < pPTbl.size(); i++) { PieceID pid = pPTbl.at(i); GetPiece(pid).SetUnused(); } } void CPieceTable::SetPieceListAsFrontUp(const std::vector<PieceID>& pPTbl) { for (size_t i = 0; i < pPTbl.size(); i++) { PieceID pid = pPTbl.at(i); GetPiece(pid).SetSide(0); // Front is up } } /////////////////////////////////////////////////////////////////////// // Remove all pieces that are now undefined. Called from document // code during deserialize. void CPieceTable::PurgeUndefinedPieceIDs() { ASSERT(m_pPMgr != NULL); ASSERT(m_pDoc != NULL); CTrayManager* pYMgr = m_pDoc->GetTrayManager(); ASSERT(pYMgr != NULL); CPBoardManager* pPBMgr = m_pDoc->GetPBoardManager(); ASSERT(pPBMgr != NULL); size_t nPiecesDeleted = 0; for (size_t i = 0; i < m_pPieceTbl.GetSize(); i++) { Piece* pPce; const PieceDef* pDef; GetPieceDefinitionPair(static_cast<PieceID>(i), pPce, pDef); if (pDef->IsEmpty()) { if (pPce->IsUsed()) { TRACE1("ERROR: Piece %zu was defined but had no Tile Images. " "Piece removed from game!\n", i); pYMgr->RemovePieceIDFromTraySets(static_cast<PieceID>(i)); CDrawObj* pObj = pPBMgr->RemoveObjectID(static_cast<ObjectID>(static_cast<PieceID>(i))); if (pObj != NULL) delete pObj; pPce->SetUnused(); // Render it gone! nPiecesDeleted++; } } } if (nPiecesDeleted > 0) { // Post a message that will be displayed after the game has // been fully loaded. CString strMsg; strMsg.LoadString(IDS_WARN_PIECESDELETED); CString* pStr = new CString; pStr->Format(strMsg, nPiecesDeleted); GetApp()->GetMainWnd()->PostMessage(WM_MESSAGEBOX, (WPARAM)WMB_PTR_CSTRING, (LPARAM)pStr); } } /////////////////////////////////////////////////////////////////////// // Creates an empty playing piece table that is the same size as the // the GameBoxes' Piece table. void CPieceTable::CreatePlayingPieceTable() { ASSERT(m_pPMgr != NULL); Clear(); size_t nPieces = m_pPMgr->GetPieceTableSize(); ASSERT(nPieces < decltype(m_pPieceTbl)::maxSize); if (nPieces == size_t(0)) return; m_pPieceTbl.ResizeTable(nPieces, &Piece::SetUnused); } /////////////////////////////////////////////////////////////////////// void CPieceTable::SetPieceFacing(PieceID pid, int nFacingDegCW) { GetPiece(pid).SetFacing(nFacingDegCW); } int CPieceTable::GetPieceFacing(PieceID pid) { return GetPiece(pid).GetFacing(); } /////////////////////////////////////////////////////////////////////// void CPieceTable::FlipPieceOver(PieceID pid) { ASSERT(Is2Sided(pid)); GetPiece(pid).InvertSide(); } void CPieceTable::SetPieceUnused(PieceID pid) { GetPiece(pid).SetUnused(); } BOOL CPieceTable::IsPieceUsed(PieceID pid) { return GetPiece(pid).IsUsed(); } BOOL CPieceTable::IsFrontUp(PieceID pid) { return GetPiece(pid).IsFrontUp(); } BOOL CPieceTable::Is2Sided(PieceID pid) const { const Piece* pPce; const PieceDef* pDef; GetPieceDefinitionPair(pid, pPce, pDef); return pDef->Is2Sided(); } /////////////////////////////////////////////////////////////////////// void CPieceTable::ClearAllOwnership() { for (size_t i = 0; i < m_pPieceTbl.GetSize(); i++) m_pPieceTbl[static_cast<PieceID>(i)].SetOwnerMask(0); } BOOL CPieceTable::IsPieceOwned(PieceID pid) const { return GetPiece(pid).IsOwned(); } BOOL CPieceTable::IsPieceOwnedBy(PieceID pid, DWORD dwOwnerMask) const { return GetPiece(pid).IsOwnedBy(dwOwnerMask); } BOOL CPieceTable::IsOwnedButNotByCurrentPlayer(PieceID pid, CGamDoc* pDoc) const { return IsPieceOwned(pid) && !IsPieceOwnedBy(pid, pDoc->GetCurrentPlayerMask()); } DWORD CPieceTable::GetOwnerMask(PieceID pid) const { return GetPiece(pid).GetOwnerMask(); } void CPieceTable::SetOwnerMask(PieceID pid, DWORD dwMask) { GetPiece(pid).SetOwnerMask(dwMask); } /////////////////////////////////////////////////////////////////////// void CPieceTable::SetPiece(PieceID pid, int nSide, int nFacing) { Piece& pPce = GetPiece(pid); pPce.SetSide(nSide); pPce.SetFacing(nFacing); } /////////////////////////////////////////////////////////////////////// CSize CPieceTable::GetPieceSize(PieceID pid, BOOL bWithFacing) { ASSERT(m_pDoc != NULL); CTile tile; m_pDoc->GetTileManager()->GetTile(GetActiveTileID(pid, bWithFacing), &tile); return tile.GetSize(); } CSize CPieceTable::GetStackedSize(const std::vector<PieceID>& pTbl, int xDelta, int yDelta, BOOL bWithFacing) { CRect rctFull; rctFull.SetRectEmpty(); CPoint pntCtr(0, 0); for (size_t i = 0; i < pTbl.size(); i++) { CSize sz = GetPieceSize(pTbl.at(i), bWithFacing); // First create rect centered on zero CRect rct(CPoint(-sz.cx/2, -sz.cy/2), sz); // Offset by staggered point rct += pntCtr; // Combine with master rect. if (i == 0) rctFull = rct; else rctFull |= rct; // Move stagger point along pntCtr += CSize(xDelta, yDelta); } return rctFull.Size(); } /////////////////////////////////////////////////////////////////////// TileID CPieceTable::GetFrontTileID(PieceID pid, BOOL bWithFacing) { const Piece* pPce; const PieceDef* pDef; GetPieceDefinitionPair(pid, pPce, pDef); TileID tidBase = pDef->m_tidFront; if (!bWithFacing || pPce->GetFacing() == 0) return tidBase; // Handle rotated pieces... return GetFacedTileID(pid, tidBase, pPce->GetFacing(), 0); } TileID CPieceTable::GetBackTileID(PieceID pid, BOOL bWithFacing) { const Piece* pPce; const PieceDef* pDef; GetPieceDefinitionPair(pid, pPce, pDef); TileID tidBase = pDef->m_tidFront; if (!bWithFacing || pPce->GetFacing() == 0) return tidBase; // Handle rotated pieces... return GetFacedTileID(pid, tidBase, pPce->GetFacing(), 0); } /////////////////////////////////////////////////////////////////////// BOOL CPieceTable::IsPieceInvisible(PieceID pid) { TileID tid = GetActiveTileID(pid, FALSE); CTile tile; m_pDoc->GetTileManager()->GetTile(tid, &tile, smallScale); return tile.GetTransparent() == tile.GetSmallColor(); } /////////////////////////////////////////////////////////////////////// TileID CPieceTable::GetActiveTileID(PieceID pid, BOOL bWithFacing) { const Piece* pPce; const PieceDef* pDef; GetPieceDefinitionPair(pid, pPce, pDef); TileID tidBase = pPce->IsFrontUp() ? pDef->GetFrontTID() : pDef->GetBackTID(); if (!bWithFacing || pPce->GetFacing() == 0) return tidBase; // Handle rotated pieces... return GetFacedTileID(pid, tidBase, pPce->GetFacing(), pPce->GetSide()); } TileID CPieceTable::GetInactiveTileID(PieceID pid, BOOL bWithFacing) { const Piece* pPce; const PieceDef* pDef; GetPieceDefinitionPair(pid, pPce, pDef); TileID tidBase = pPce->IsFrontUp() ? pDef->GetBackTID() : pDef->GetFrontTID(); if (!bWithFacing || pPce->GetFacing() == 0) return tidBase; // Handle rotated pieces... return GetFacedTileID(pid, tidBase, pPce->GetFacing(), pPce->GetSide()); } /////////////////////////////////////////////////////////////////////// TileID CPieceTable::GetFacedTileID(PieceID pid, TileID tidBase, int nFacing, int nSide) const { // Handle rotated pieces... ElementState state = MakePieceState(pid, nFacing, nSide); CTileFacingMap* pMapFacing = m_pDoc->GetFacingMap(); TileID tidFacing = pMapFacing->GetFacingTileID(state); if (tidFacing != nullTid) return tidFacing; tidFacing = pMapFacing->CreateFacingTileID(state, tidBase); return tidFacing; } /////////////////////////////////////////////////////////////////////// void CPieceTable::Clear() { m_pPieceTbl.Clear(); } /////////////////////////////////////////////////////////////////////// const Piece& CPieceTable::GetPiece(PieceID pid) const { ASSERT(m_pPieceTbl != NULL); ASSERT(m_pPieceTbl.Valid(pid)); return m_pPieceTbl[pid]; } const PieceDef& CPieceTable::GetPieceDef(PieceID pid) const { ASSERT(m_pPMgr != NULL); return m_pPMgr->GetPiece(pid); } void CPieceTable::GetPieceDefinitionPair(PieceID pid, const Piece*& pPce, const PieceDef*& pDef) const { pPce = &GetPiece(pid); ASSERT(m_pPMgr != NULL); pDef = &m_pPMgr->GetPiece(pid); } /////////////////////////////////////////////////////////////////////// CPieceTable* CPieceTable::Clone(CGamDoc *pDoc) const { CPieceTable* pTbl = new CPieceTable; pTbl->m_pPieceTbl = m_pPieceTbl; return pTbl; } void CPieceTable::Restore(CGamDoc *pDoc, const CPieceTable& pTbl) { Clear(); m_pPieceTbl = pTbl.m_pPieceTbl; } BOOL CPieceTable::Compare(const CPieceTable& pTbl) const { if (m_pPieceTbl.GetSize() != pTbl.m_pPieceTbl.GetSize()) return FALSE; for (size_t i = 0; i < m_pPieceTbl.GetSize(); i++) { if (m_pPieceTbl[static_cast<PieceID>(i)] != pTbl.m_pPieceTbl[static_cast<PieceID>(i)]) return FALSE; } return TRUE; } /////////////////////////////////////////////////////////////////////// void CPieceTable::Serialize(CArchive& ar) { if (ar.IsStoring()) { ar << m_wReserved1; ar << m_wReserved2; ar << m_wReserved3; ar << m_wReserved4; ar << m_pPieceTbl; } else { Clear(); m_pDoc = (CGamDoc*)ar.m_pDocument; m_pPMgr = m_pDoc->GetPieceManager(); ar >> m_wReserved1; ar >> m_wReserved2; ar >> m_wReserved3; ar >> m_wReserved4; ar >> m_pPieceTbl; // Check for consistancy with game box piece table. ASSERT(m_pPMgr != NULL); size_t nDefSize = m_pPMgr->GetPieceTableSize(); if (m_pPieceTbl.GetSize() < nDefSize) { // Need to increase the size of the playing piece table. m_pPieceTbl.ResizeTable(nDefSize, &Piece::SetUnused); } else if (m_pPieceTbl.GetSize() > nDefSize) { // Piece table in Game box was truncated. Probably // bad news. if (AfxMessageBox(IDS_ERR_PIECETBLSIZE, MB_OKCANCEL | MB_ICONEXCLAMATION) != IDOK) AfxThrowArchiveException(CArchiveException::genericException); // Need to decrease the size of the playing piece table. size_t nOldTblSize = m_pPieceTbl.GetSize(); m_pPieceTbl.ResizeTable(nDefSize, nullptr); // Purge pieces in use that don't exist anymore CTrayManager* pYMgr = m_pDoc->GetTrayManager(); CPBoardManager* pPBMgr = m_pDoc->GetPBoardManager(); for (size_t i = m_pPieceTbl.GetSize(); i < nOldTblSize; i++) { pYMgr->RemovePieceIDFromTraySets(static_cast<PieceID>(i)); CDrawObj* pObj = pPBMgr->RemoveObjectID(static_cast<ObjectID>(static_cast<PieceID>(i))); if (pObj != NULL) delete pObj; } } } } /////////////////////////////////////////////////////////////////////// void Piece::Serialize(CArchive& ar) { if (ar.IsStoring()) { ar << m_nSide; ar << m_nFacing; ar << m_dwOwnerMask; } else { ar >> m_nSide; if (CGamDoc::GetLoadingVersion() < NumVersion(2, 90)) // (support degrees) { // Convert pre 2.90 single byte (5 degree resolution) facings to degrees BYTE chVal; ar >> chVal; m_nFacing = chVal; m_nFacing *= 5; // Convert to new degree format } else ar >> m_nFacing; if (CGamDoc::GetLoadingVersion() < NumVersion(2, 0)) m_dwOwnerMask = 0; else if (CGamDoc::GetLoadingVersion() < NumVersion(3, 10)) { WORD wTmp; ar >> wTmp; m_dwOwnerMask = UPGRADE_OWNER_MASK(wTmp); } else ar >> m_dwOwnerMask; } } /////////////////////////////////////////////////////////////////////// #ifdef _DEBUG void CPieceTable::DumpToTextFile(CFile& file) { static char szHead[] = "\r\nPiece Table\r\n-----------\r\n"; file.Write(szHead, lstrlen(szHead)); char szBfr[256]; for (size_t i = 0; i < m_pPieceTbl.GetSize(); i++) { const Piece* pPce; const PieceDef* pDef; GetPieceDefinitionPair(static_cast<PieceID>(i), pPce, pDef); wsprintf(szBfr, "PieceID %5.5d: m_nSide=%02X, m_nFacing=%3u, " "m_tidFront=%5u, m_tidBack=%5u\r\n", i, (UINT)pPce->m_nSide, (UINT)pPce->m_nFacing, (UINT)static_cast<TileID::UNDERLYING_TYPE>(pDef->m_tidFront), (UINT)static_cast<TileID::UNDERLYING_TYPE>(pDef->m_tidBack)); file.Write(szBfr, lstrlen(szBfr)); } } #endif /////////////////////////////////////////////////////////////////////// // NOT INLINED SO WE CAN SET BREAK POINTS void Piece::SetUnused() { m_nSide = 0xFF; m_nFacing = 0; }
28.701068
104
0.577309
[ "render", "vector" ]
9947a50c69ee901f7c7bbfddbc708d3d2d84be76
1,262
cpp
C++
CODECHEF/codechef345.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-04T14:39:02.000Z
2021-10-04T14:39:02.000Z
CODECHEF/codechef345.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-06T04:41:55.000Z
2021-10-06T04:41:55.000Z
CODECHEF/codechef345.cpp
IUC4801/HactoberFest21
ad52dee669deba54630584435b77a6ab07dc67b2
[ "Unlicense" ]
1
2021-10-08T12:31:04.000Z
2021-10-08T12:31:04.000Z
#include <iostream> #include <cstdio> #include <cstdlib> #include <algorithm> #include <cmath> #include <vector> #include <set> #include <map> #include <unordered_set> #include <unordered_map> #include <queue> #include <ctime> #include <cassert> #include <complex> #include <string> #include <cstring> #include <chrono> #include <random> #include <bitset> #define mod 1000000007 const int N=1e7+5; using namespace std ; #define SIZE 26 long long int a[N],c[N]; int arra(long long int n) { long long int temp=c[0]; for(int i=0;i<n-1;i++) c[i]=c[i+1]; c[n-1]=temp; return 0; } long long int testcase () { long long int n; cin>>n; for(int i=0;i<n;i++) { cin>>a[i]; } for(int i=0;i<n;i++) { cin>>c[i]; } long long int ans=999999; for(int i=0;i<n-1;i++) { long long int ans1=0; for(int i=0;i<n;i++) { ans1+=ans1*10+(a[i]+c[i])%n); } if(ans1<ans) ans=ans1; arra(n); } string s1=to_string(ans); for(int i=0;i<n;i++) cout<<s1[i]<<" "; } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); long long int t; cin>>t; for(int i=0;i<t;i++) { testcase(); cout<<"\n"; } }
13.145833
35
0.542789
[ "vector" ]
994a963fb5c94941e7f3b6405cb386b92944203e
10,046
cpp
C++
src/pool/PoolSwitcher.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
4
2019-07-24T03:24:08.000Z
2022-03-04T07:41:08.000Z
src/pool/PoolSwitcher.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
3
2019-07-30T22:10:39.000Z
2020-06-15T15:57:08.000Z
src/pool/PoolSwitcher.cpp
DavHau/Riner
f9e9815b713572f03497f0e4e66c3f82a0241b66
[ "MIT" ]
6
2019-07-30T21:33:07.000Z
2022-03-21T20:53:11.000Z
// // #include "PoolSwitcher.h" #include "WorkQueue.h" #include <src/common/Assert.h> #include <src/algorithm/Algorithm.h> namespace riner { PoolSwitcher::PoolSwitcher(std::string powType, clock::duration checkInterval, clock::duration durUntilDeclaredDead) : Pool(PoolConstructionArgs{}) , checkInterval(checkInterval) , durUntilDeclaredDead(durUntilDeclaredDead) { RNR_EXPECTS(!powType.empty()); _powType = powType; _poolImplName = powType + "-PoolSwitcher"; onStateChange = std::make_shared<std::condition_variable>(); periodicAliveCheckTask = std::async(std::launch::async, [this, powType] () { SetThreadNameStream{} << "poolswitcher " << powType; VLOG(6) << "alive-check thread started"; periodicAliveCheck(); }); } PoolSwitcher::~PoolSwitcher() { { std::lock_guard<std::mutex> lock(mut); shutdown = true; } VLOG(6) << "shutting down poolswitcher " << _powType << " thread"; onStateChange->notify_all(); periodicAliveCheckTask.wait(); VLOG(6) << "sucessfully shut down poolswitcher " << _powType << " thread"; } void PoolSwitcher::periodicAliveCheck() { size_t activePoolIndex = std::numeric_limits<size_t>::max(); //if greater than pools.readLock()->size(), no pool is active while (!shutdown) { bool was_active = false; auto _poolUid = poolUid; //copy shared_ptr to active pool and access pool through copy //because the active pool might change at any time if (auto pool = active_pool.get()) { was_active = pool->isConnected() && !pool->isDisabled(); _poolUid = pool->poolUid; } activePoolIndex = aliveCheckAndMaybeSwitch(activePoolIndex); //if pool switcher selects new pool, then the new pool should be active if (auto pool = active_pool.get()) { was_active |= _poolUid != pool->poolUid; } //notification for waiting tryGetWorkImpl() calls onStateChange->notify_all(); //use condition vairable to wait, so the wait can be interrupted on shutdown std::unique_lock<std::mutex> lock(mut); onStateChange->wait_for(lock, checkInterval, [this, was_active] { bool wakeup = shutdown; if (wakeup) { return true; } auto pool = active_pool.get(); if (was_active && pool && !pools_changed) { wakeup = pool->isDisabled() || !pool->isConnected(); } else { auto pools_lock_guard = _pools.readLock(); for (const auto pool : *pools_lock_guard) { if ((wakeup = pool->isConnected() && !pool->isDisabled())) { break; } } } return wakeup; }); pools_changed = false; } } size_t PoolSwitcher::aliveCheckAndMaybeSwitch(size_t activePoolIndex) { using namespace std::chrono; auto pools_lock_guard = _pools.readLock(); const auto &pools = *pools_lock_guard; auto flt_sec = duration<float>(checkInterval).count(); if (pools.empty()) { VLOG(2) << "no pools in poolswitcher, sleeping for " << flt_sec << "s"; return activePoolIndex; } VLOG(2) << "periodic pool connection status check (every " << flt_sec << "s)"; auto now = clock::now(); auto durUntilDeclaredDeadSecs = duration_cast<seconds>(durUntilDeclaredDead).count(); auto prev_pool = active_pool.get(); auto new_pool = prev_pool; auto pool_switched = false; //first lets write down the relevant info in this struct //so the logic below is better readable struct Info { size_t index = 0; //index in pools std::remove_const_t<decltype(poolUid)> uid; //pool UID bool was_dead{}; //pool was dead during last check bool now_dead{}; //pool is now dead in this check bool disabled{}; bool connected{}; }; std::vector<Info> poolInfos{pools.size()}; //fill the structs for (size_t i = 0; i < pools.size(); ++i) { poolInfos[i].index = i; poolInfos[i].uid = pools[i]->poolUid; poolInfos[i].was_dead = pools[i]->isDead(); poolInfos[i].now_dead = now - pools[i]->getLastKnownAliveTime() > durUntilDeclaredDead; poolInfos[i].disabled = pools[i]->isDisabled(); poolInfos[i].connected = pools[i]->isConnected(); } //decide new active pool for (const Info &p : poolInfos) { if (p.connected && !p.now_dead && !p.disabled) { bool is_another_pool = prev_pool && prev_pool->poolUid != p.uid; pool_switched = is_another_pool || !prev_pool; new_pool = pools[p.index]; activePoolIndex = p.index; active_pool.set(new_pool); if (is_another_pool) { prev_pool->expireJobs(); } break; //first one that is not dead is chosen } } //declare/undeclare pools as dead, close connections of disabled pools for (const Info &p : poolInfos) { pools[p.index]->setDead(p.now_dead); if (p.disabled && p.connected) { LOG(INFO) << "pool '" << pools[p.index]->getName() << "' disabled. kill connection."; pools[p.index]->onDeclaredDead(); } } {//write descriptive logs (collapse this scope if needed) bool there_was_no_active_pool = !prev_pool; bool theres_no_active_pool = !new_pool; if (theres_no_active_pool && there_was_no_active_pool) { VLOG(0) << "still no backup pools available. Waiting for pools to become available again."; } if (pool_switched) { LOG(INFO) << "Pool #" << activePoolIndex << " (" << new_pool->getName() << ") chosen as new active pool"; } for (const Info &p : poolInfos) { auto &pool = pools[p.index]; if (!p.was_dead && p.now_dead) { //if just died if (prev_pool && prev_pool->poolUid == p.uid) { //pool that just died was the active pool if (theres_no_active_pool) { //we now have no more backup LOG(WARNING) << "no more backup pools available for PowType '" << _powType << "'. Waiting for pools to become available again."; if (pools.size() == 1) { LOG(INFO) << "note: you can put multiple pools per PowType into the config file. additional pools will be used as backup."; } } else { //we have a working backup pool LOG(INFO) << "active pool #" << p.index << "(" << pool->getName() << ") was inactive for " << durUntilDeclaredDeadSecs << " seconds, switching to next backup pool"; } } else if (p.connected) { //pool that just died was not the active pool LOG(INFO) << "currently unused backup pool #" << p.index << " (" << pool->getName() << ") was inactive for " << durUntilDeclaredDeadSecs << "s"; } } } } //end of log scope return activePoolIndex; } unique_ptr<Work> PoolSwitcher::tryGetWorkImpl() { //copy shared_ptr to active pool and access pool through copy //because the active pool might change at any time if (auto pool = active_pool.get()) { return pool->tryGetWorkImpl(); //thread-safe method } VLOG(2) << "PoolSwitcher cannot provide work since there is no active pool"; //wait for event to prevent busy waiting in the algorithms' loops std::unique_lock<std::mutex> lock(mut); onStateChange->wait(lock, [this] () { return shutdown || active_pool.get(); }); return nullptr; } void PoolSwitcher::submitSolutionImpl(unique_ptr<WorkSolution> solution) { std::shared_ptr<const PoolJob> job = solution->tryGetJob(); //thread-safe method if (!job) { LOG(INFO) << "work solution is not submitted because its job is stale"; return; } std::shared_ptr<Pool> pool = job->pool.lock(); if (!pool) { LOG(INFO) << "work solution cannot be submitted because its pool does not exist anymore"; return; } auto solutionPoolUid = pool->poolUid; auto activePoolUid = poolUid; bool sameUid = true; if (pool->isConnected()) { if (auto _active_pool = active_pool.get()) { activePoolUid = _active_pool->poolUid; } sameUid = activePoolUid == solutionPoolUid; if (!sameUid) { LOG(INFO) << "solution will be submitted to non-active pool (uid " << solutionPoolUid << ") and not to current pool (uid " << activePoolUid << ")"; } pool->submitSolutionImpl(std::move(solution)); //thread-safe method } else { LOG(INFO) << "solution could not be submitted to pool because it is not connected"; } } size_t PoolSwitcher::poolCount() const { return _pools.readLock()->size(); } }
40.672065
163
0.536631
[ "vector" ]
994b87ce34a608165b56b8fc91d8821b46b3c00a
2,370
hpp
C++
libs/core/include/fcppt/math/matrix/vector.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
libs/core/include/fcppt/math/matrix/vector.hpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
libs/core/include/fcppt/math/matrix/vector.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_MATH_MATRIX_VECTOR_HPP_INCLUDED #define FCPPT_MATH_MATRIX_VECTOR_HPP_INCLUDED #include <fcppt/literal.hpp> #include <fcppt/tag.hpp> #include <fcppt/algorithm/fold.hpp> #include <fcppt/math/int_range_count.hpp> #include <fcppt/math/size_constant.hpp> #include <fcppt/math/size_type.hpp> #include <fcppt/math/detail/binary_type.hpp> #include <fcppt/math/matrix/at_r_c.hpp> #include <fcppt/math/matrix/object_impl.hpp> #include <fcppt/math/vector/at.hpp> #include <fcppt/math/vector/init.hpp> #include <fcppt/math/vector/object_impl.hpp> #include <fcppt/math/vector/static.hpp> #include <fcppt/preprocessor/disable_gcc_warning.hpp> #include <fcppt/preprocessor/pop_warning.hpp> #include <fcppt/preprocessor/push_warning.hpp> #include <fcppt/type_traits/value_type.hpp> namespace fcppt::math::matrix { /** \brief Multiplies a matrix by a vector \ingroup fcpptmathmatrix */ template < typename Left, typename Right, fcppt::math::size_type R, fcppt::math::size_type C, typename S1, typename S2> fcppt::math::vector::static_<FCPPT_MATH_DETAIL_BINARY_TYPE(Left, *, Right), R> operator*( fcppt::math::matrix::object<Left, R, C, S1> const &_left, fcppt::math::vector::object<Right, C, S2> const &_right) { using result_type = fcppt::math::vector::static_<FCPPT_MATH_DETAIL_BINARY_TYPE(Left, *, Right), R>; return fcppt::math::vector::init<result_type>( [&_left, &_right]<fcppt::math::size_type Row>(fcppt::math::size_constant<Row>) { using value_type = fcppt::type_traits::value_type<result_type>; FCPPT_PP_PUSH_WARNING FCPPT_PP_DISABLE_GCC_WARNING(-Wattributes) return fcppt::algorithm::fold( fcppt::math::int_range_count<C>{}, fcppt::literal<value_type>(0), [&_left, &_right]<fcppt::math::size_type Col>( fcppt::tag<fcppt::math::size_constant<Col>>, value_type const _sum) { return _sum + fcppt::math::matrix::at_r_c<Row, Col>(_left) * fcppt::math::vector::at<Col>(_right); }); FCPPT_PP_POP_WARNING }); } } #endif
33.380282
89
0.687342
[ "object", "vector" ]
995a5083ff2aae93c608d7c95ddacb708237c2db
1,325
cc
C++
src/catkin_ws/src/failsafe_nodelets/initialisation/src/initialisation.cc
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
src/catkin_ws/src/failsafe_nodelets/initialisation/src/initialisation.cc
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
src/catkin_ws/src/failsafe_nodelets/initialisation/src/initialisation.cc
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
// -*- lsst-c++ -*/ /** * @file initialisation.cc * @brief Main function for sending the init signal to online verification. * @version 0.1 * @copyright MIT License. Please see package.xml for further detail. */ #include <string> #include <chrono> #include <thread> #include <ros/ros.h> #include <std_msgs/Empty.h> #include "modrob_workstation/RobotConfigMeasured.h" #include "modrob_workstation/RobotStateCommanded.h" /** * @brief Main function that waits for `startup_time` seconds and then sends an init signal. * * The init signal is only read by the online verification object to start the motion planning and verification. */ int main(int argc, char **argv){ ros::init(argc, argv, "initialization"); ros::NodeHandle nh; ROS_INFO("Initialisation"); ros::Publisher start_pub = nh.advertise<std_msgs::Empty>("/initialisation", 1000); double sleep_duration = 0.5; if (ros::param::has("/startup_time")) { ros::param::get("/startup_time", sleep_duration); } ROS_INFO_STREAM("Waiting for " << sleep_duration << "s to initialize the online verification."); int sleep_ms = (int)floor(sleep_duration*1000); std::this_thread::sleep_for(std::chrono::milliseconds(sleep_ms)); std_msgs::Empty start_msg; start_pub.publish(start_msg); ROS_INFO("Sent initialization msg."); return 0; }
30.113636
112
0.720755
[ "object" ]
995ae4ccba10577ed769b13d39eed595c50d0847
2,448
cpp
C++
c++/day_17/day_17.cpp
gbroll/AoC-2021
862d89b3f3eeed732d4bfd2854cb805327445345
[ "MIT" ]
1
2022-01-07T09:38:15.000Z
2022-01-07T09:38:15.000Z
c++/day_17/day_17.cpp
gbroll/AoC-2021
862d89b3f3eeed732d4bfd2854cb805327445345
[ "MIT" ]
null
null
null
c++/day_17/day_17.cpp
gbroll/AoC-2021
862d89b3f3eeed732d4bfd2854cb805327445345
[ "MIT" ]
null
null
null
#include <regex> #include <math.h> #include "../utils/file_reader.cpp" #include "../utils/result_printer.cpp" struct area { int xmin,xmax,ymin,ymax; }; area parse(vector<string> str_data) { area target; string regex_str = "x=(-?[0-9]+)..(-?[0-9]+), y=(-?[0-9]+)..(-?[0-9]+)$"; regex regex_obj(regex_str); smatch matches; regex_search(str_data[0], matches, regex_obj); target.xmin = stoi(matches.str(1)); target.xmax = stoi(matches.str(2)); target.ymin = stoi(matches.str(3));; target.ymax = stoi(matches.str(4)); return target; } int solve_part1(area t) { int v0_ymax = abs(t.ymin)-1; //the maximum y velocity still hitting y_min int y_max = v0_ymax * (v0_ymax+1)/2; //integrate to velocity zero (arithmetic series sum) return y_max; } int solve_part2(area t) { int v0x_min = int( -.5+sqrt((2.0d*double(t.xmin)+0.25d))); int v0x_max = t.xmax; int v0y_min = t.ymin; int v0y_max = abs(t.ymin) -1 ; int x,y,vx,vy,i; int n = 0; for (int v0x = v0x_min; v0x <= v0x_max; v0x++) { for (int v0y = v0y_min; v0y <= v0y_max; v0y++) { vy = v0y; vx = v0x; x = y = 0; while (true) { x += (vx > 0) * vx; y += vy; if (x > t.xmax || y < t.ymin) { //this is a miss break; } else if (x >= t.xmin && x <= t.xmax) { if (y >= t.ymin && y <= t.ymax) { n++; break; } } vx--; vy--; } } } return n; } int main() { int day = 17; auto start = chrono::high_resolution_clock::now(); string filename = "../../input/day_" + to_string(day) + ".txt"; vector<string> string_data = read_file<string>(filename,false); area target = parse(string_data); auto parsed = chrono::high_resolution_clock::now(); int part_1 = solve_part1(target); int part_2 = solve_part2(target); auto solved = chrono::high_resolution_clock::now(); vector<chrono::high_resolution_clock::time_point> time_stamps{start , parsed, solved}; print_results<int>(day, part_1, part_2, time_stamps); return 0; }
22.878505
93
0.496732
[ "vector" ]
995fab6cbe6c08654a6ad9ef8fb27528da36a236
7,247
cpp
C++
src/org/apache/poi/util/HexRead.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/util/HexRead.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/util/HexRead.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/util/HexRead.java #include <org/apache/poi/util/HexRead.hpp> #include <java/io/ByteArrayInputStream.hpp> #include <java/io/File.hpp> #include <java/io/FileInputStream.hpp> #include <java/io/IOException.hpp> #include <java/io/InputStream.hpp> #include <java/io/Serializable.hpp> #include <java/lang/ArrayStoreException.hpp> #include <java/lang/Byte.hpp> #include <java/lang/ClassCastException.hpp> #include <java/lang/Comparable.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/Number.hpp> #include <java/lang/Object.hpp> #include <java/lang/RuntimeException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> #include <java/lang/StringBuilder.hpp> #include <java/lang/Throwable.hpp> #include <java/util/ArrayList.hpp> #include <java/util/List.hpp> #include <org/apache/poi/util/StringUtil.hpp> #include <Array.hpp> #include <SubArray.hpp> #include <ObjectArray.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } // io namespace lang { typedef ::SubArray< ::java::lang::Number, ObjectArray, ::java::io::SerializableArray > NumberArray; typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray; typedef ::SubArray< ::java::lang::Byte, NumberArray, ComparableArray > ByteArray; } // lang } // java template<typename T, typename U> static T java_cast(U* u) { if(!u) return static_cast<T>(nullptr); auto t = dynamic_cast<T>(u); if(!t) throw new ::java::lang::ClassCastException(); return t; } template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } namespace { template<typename F> struct finally_ { finally_(F f) : f(f), moved(false) { } finally_(finally_ &&x) : f(x.f), moved(false) { x.moved = true; } ~finally_() { if(!moved) f(); } private: finally_(const finally_&); finally_& operator=(const finally_&); F f; bool moved; }; template<typename F> finally_<F> finally(F f) { return finally_<F>(f); } } poi::util::HexRead::HexRead(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::util::HexRead::HexRead() : HexRead(*static_cast< ::default_init_tag* >(0)) { ctor(); } int8_tArray* poi::util::HexRead::readData(::java::lang::String* filename) /* throws(IOException) */ { clinit(); auto file = new ::java::io::File(filename); ::java::io::InputStream* stream = new ::java::io::FileInputStream(file); { auto finally0 = finally([&] { npc(stream)->close(); }); { return readData(stream, -int32_t(1)); } } } int8_tArray* poi::util::HexRead::readData(::java::io::InputStream* stream, ::java::lang::String* section) /* throws(IOException) */ { clinit(); { auto finally1 = finally([&] { npc(stream)->close(); }); { auto sectionText = new ::java::lang::StringBuffer(); auto inSection = false; auto c = npc(stream)->read(); while (c != -int32_t(1)) { switch (c) { case u'[': inSection = true; break; case u'\u000a': case u'\u000d': inSection = false; sectionText = new ::java::lang::StringBuffer(); break; case u']': inSection = false; if(npc(npc(sectionText)->toString())->equals(static_cast< ::java::lang::Object* >(section))) return readData(stream, static_cast< int32_t >(u'[')); sectionText = new ::java::lang::StringBuffer(); break; default: if(inSection) npc(sectionText)->append(static_cast< char16_t >(c)); } c = npc(stream)->read(); } } } throw new ::java::io::IOException(::java::lang::StringBuilder().append(u"Section '"_j)->append(section) ->append(u"' not found"_j)->toString()); } int8_tArray* poi::util::HexRead::readData(::java::lang::String* filename, ::java::lang::String* section) /* throws(IOException) */ { clinit(); return readData(static_cast< ::java::io::InputStream* >(new ::java::io::FileInputStream(filename)), section); } int8_tArray* poi::util::HexRead::readData(::java::io::InputStream* stream, int32_t eofChar) /* throws(IOException) */ { clinit(); auto characterCount = int32_t(0); auto b = static_cast< int8_t >(int32_t(0)); ::java::util::List* bytes = new ::java::util::ArrayList(); char16_t const a = u'a' - int32_t(10); char16_t const A = u'A' - int32_t(10); while (true) { auto count = npc(stream)->read(); auto digitValue = -int32_t(1); if(u'0' <= count && count <= u'9') { digitValue = count - u'0'; } else if(u'A' <= count && count <= u'F') { digitValue = count - A; } else if(u'a' <= count && count <= u'f') { digitValue = count - a; } else if(u'#' == count) { readToEOL(stream); } else if(-int32_t(1) == count || eofChar == count) { break; } if(digitValue != -int32_t(1)) { b <<= 4; b += static_cast< int8_t >(digitValue); characterCount++; if(characterCount == 2) { npc(bytes)->add(static_cast< ::java::lang::Object* >(::java::lang::Byte::valueOf(b))); characterCount = 0; b = static_cast< int8_t >(int32_t(0)); } } } auto polished = java_cast< ::java::lang::ByteArray* >(npc(bytes)->toArray_(static_cast< ::java::lang::ObjectArray* >(new ::java::lang::ByteArray(npc(bytes)->size())))); auto rval = new ::int8_tArray(npc(polished)->length); for (auto j = int32_t(0); j < npc(polished)->length; j++) { (*rval)[j] = npc((*polished)[j])->byteValue(); } return rval; } int8_tArray* poi::util::HexRead::readFromString(::java::lang::String* data) { clinit(); try { return readData(static_cast< ::java::io::InputStream* >(new ::java::io::ByteArrayInputStream(npc(data)->getBytes(StringUtil::UTF8()))), -int32_t(1)); } catch (::java::io::IOException* e) { throw new ::java::lang::RuntimeException(static_cast< ::java::lang::Throwable* >(e)); } } void poi::util::HexRead::readToEOL(::java::io::InputStream* stream) /* throws(IOException) */ { clinit(); auto c = npc(stream)->read(); while (c != -int32_t(1) && c != u'\u000a' && c != u'\u000d') { c = npc(stream)->read(); } } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::util::HexRead::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.util.HexRead", 27); return c; } java::lang::Class* poi::util::HexRead::getClass0() { return class_(); }
31.92511
172
0.57817
[ "object" ]
99610d5dac7fc1e782cc2823d7c808e005bf6f14
806
hpp
C++
module/src/torrent_status.hpp
JoyStream/libtorrent-node
95966c620a8b41f491db77b2ba4dd89ed13f480f
[ "MIT" ]
1
2018-07-04T07:45:06.000Z
2018-07-04T07:45:06.000Z
module/src/torrent_status.hpp
JoystreamClassic/libtorrent-node
95966c620a8b41f491db77b2ba4dd89ed13f480f
[ "MIT" ]
1
2017-11-28T08:58:12.000Z
2017-11-28T08:58:12.000Z
module/src/torrent_status.hpp
JoystreamClassic/libtorrent-node
95966c620a8b41f491db77b2ba4dd89ed13f480f
[ "MIT" ]
3
2017-11-10T14:50:45.000Z
2018-08-24T07:41:02.000Z
/** * Copyright (C) JoyStream - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Proprietary and confidential * Written by Bedeho Mender <bedeho.mender@gmail.com>, Januar 16 2017 */ #ifndef LIBTORRENT_NODE_TORRENT_STATUS_HPP #define LIBTORRENT_NODE_TORRENT_STATUS_HPP #include <nan.h> #include <libtorrent/torrent_status.hpp> namespace libtorrent { struct torrent_status; namespace node { namespace torrent_status { // Something about symbols? ...export state_t.... /** * Status is encoded as * { * info_hash : { see info_hash for format }, * state : { Number }, * progress : { Number } * } */ v8::Local<v8::Object> encode(const libtorrent::torrent_status & s); } } } #endif // LIBTORRENT_NODE_TORRENT_STATUS_HPP
21.210526
75
0.709677
[ "object" ]
9966d6987788e70044172bce5acec6eb26c8c0db
546
hpp
C++
wrtstat/aggregator/api/types.hpp
mambaru/wrtstat
d97bf5376c14181974d6eb4632053710bb75cca8
[ "MIT" ]
1
2018-03-16T21:21:23.000Z
2018-03-16T21:21:23.000Z
wrtstat/aggregator/api/types.hpp
mambaru/wrtstat
d97bf5376c14181974d6eb4632053710bb75cca8
[ "MIT" ]
10
2019-12-04T20:44:19.000Z
2021-04-20T21:51:50.000Z
wrtstat/aggregator/api/types.hpp
mambaru/wrtstat
d97bf5376c14181974d6eb4632053710bb75cca8
[ "MIT" ]
null
null
null
#pragma once #include <cstddef> #include <vector> #include <memory> #include <ctime> namespace wrtstat { typedef std::size_t size_type; typedef std::time_t time_type; typedef std::time_t value_type; typedef std::size_t id_t; typedef std::vector<value_type> data_type; typedef std::unique_ptr<data_type> data_ptr; constexpr id_t bad_id = static_cast<id_t>(-1); constexpr id_t get_bad_id() { return bad_id; } enum class resolutions { none = 0, seconds = 1, milliseconds = 1000, microseconds = 1000000, nanoseconds = 1000000000 }; }
18.827586
46
0.741758
[ "vector" ]
996801fff2057bd68a13c540cac61aae306e97c9
8,780
hpp
C++
gtracr/lib/include/uTrajectoryTracer.hpp
kwat0308/gtracr
c7a4967f8e127daa732fd6515b61f13a4fb2b900
[ "BSD-3-Clause" ]
3
2020-08-30T19:47:26.000Z
2022-03-15T01:52:58.000Z
gtracr/lib/include/uTrajectoryTracer.hpp
kwat0308/gtracr
c7a4967f8e127daa732fd6515b61f13a4fb2b900
[ "BSD-3-Clause" ]
3
2020-09-02T00:05:05.000Z
2021-02-04T22:16:39.000Z
gtracr/lib/include/uTrajectoryTracer.hpp
kwat0308/gtracr
c7a4967f8e127daa732fd6515b61f13a4fb2b900
[ "BSD-3-Clause" ]
null
null
null
// header file for Runge Kutta Integrator #ifndef __UTRAJECTORYTRACER_HPP_ #define __UTRAJECTORYTRACER_HPP_ #include <algorithm> #include <array> #include <cmath> #include <functional> #include <iostream> #include <map> #include <string> #include <utility> #include <vector> #include "MagneticField.hpp" #include "constants.hpp" #include "igrf.hpp" /* Class that traces / tracks the trajectory of a single particle within Earth's magnetic field. This is different from the similar class TrajectoryTracer in that the integration algorithm is performed individually instead of in vector form (i.e. evaluates each ODE as its own rather as evaluating the ODE as a vector). Class Members -------- - bfield_ (MagneticField instance): The MagneticField object that contains the information pertaining the Earth's magnetic field model (default is dipole model). - charge_ (double) : The charge of the particle in units of Coulombs (default 1.602e-19 C, i.e. 1e). - mass_ (double) : The (rest) mass of the particle in units of kilograms (default 1.672e-27 kg, i.e. proton mass). - escape_radius_ (double) : The radial distance relative to Earth's center in which the particle is set to have "escaped" Earth, i.e. a valid cosmic ray coming from some astrophysical source. Units are in kilometers (default 10*Earth's radius) - stepsize_ (double) : The stepsize for the integration process (default 1e-5) - max_iter_ (int) : The maximum number of iterations performed for the integration process (default 10000) - particle_escaped_ (bool) : True if particle has effectively "escaped" from Earth (i.e. when the radial component of the trajectory > escape_radius_) (default false). */ class uTrajectoryTracer { private: MagneticField bfield_; // the magnetic field double charge_; // charge of the particle in coulumbs double mass_; // mass of the particle in kg double start_altitude_; // starting altitude of particle double escape_radius_; // radius in which we set for particle to escape double stepsize_; // step size int max_iter_; // maximum step size // binary value to store if particle has escaped or not bool particle_escaped_; double final_time_; // the final time of the trajectory std::array<double, 6> final_sixvector_; // the final six-vector of the trajectory // container for trajectory data throughout integration struct { double t; double r; double theta; double phi; double pr; double ptheta; double pphi; } traj_vector_; /* velocity in the radial component */ inline double dr_dt(double pr); /* velocity in the polar component */ inline double dtheta_dt(double r, double ptheta); /* velocity in the azimuthal component */ inline double dphi_dt(double r, double theta, double pphi); /* acceleration in r component (time derivative of pr) from Lorentz force */ inline double dpr_dt(double r, double theta, double phi, double pr, double ptheta, double pphi); /* acceleration in theta component (time derivative of ptheta) from Lorentz * force */ inline double dptheta_dt(double r, double theta, double phi, double pr, double ptheta, double pphi); /* acceleration in phi component (time derivative of pphi) from Lorentz force */ inline double dpphi_dt(double r, double theta, double phi, double pr, double ptheta, double pphi); /* the Lorentz factor, computed from spherical components */ inline double gamma(double pr, double ptheta, double pphi); /* evaluate / perform one step of the Runge-Kutta algorithm takes the 7-vector consisting of the following format: [t, r, theta, phi, pr, ptheta, pphi] and returns the modified 7-vector in that same format */ void perform_rkstep(); public: /* Default Constructor for TrajectoryTracer class Creates an instance of the TrajectoryTracer, that is, the object that keeps track of a single particle trajectory in Earth's magnetic field. The default constructor initializes the object with the default values provided for the members. Parameters ------------ None */ uTrajectoryTracer(); /* Constructor for TrajectoryTracer class Creates an instance of the TrajectoryTracer, that is, the object that keeps track of a single particle trajectory in Earth's magnetic field. This constructor requires 2 parameters, and the rest may be optional. Required Parameters ------------------- - charge (int) : The charge of the particle in units of electrons. - mass (double) : The mass of the particle in units of GeV. Optional Parameters ------------------- - start_altitude (double) : The starting altitude of the particle, i.e. the altitude in which the cosmic ray has collided with the atmosphere (default 100km) - escape_radius (double) : The radius in which the particle has "escaped" relative to Earth's center in units of km (default 10*RE) - stepsize (double) : The step size of the integration (default 1e-5) - max_iter (int) : The maximum number of iterations performed in the integration process (default 10000) - bfield_type (char) : The type of Magnetic Field to evaluate the trajectory with. Only types 'd' (for dipole model) or 'i' (IGRF model) are allowed (default 'd'). - igrf_params (std::pair<std::string, double>) : Parameters required for instantiating the IGRF model. The first entry contains the path of the directory in which the .COF data file is stored (default to the author's path to the directory). The second entry contains the date in which the evaluation of the trajectory is requested in decimal date (default 2020.). */ uTrajectoryTracer(double charge, double mass, double start_altitude = 100. * (1e3), double escape_radius = 10. * constants::RE, double stepsize = 1e-5, int max_iter = 10000, const char bfield_type = 'i', const std::pair<std::string, double> &igrf_params = { "/home/keito/devel/gtracr/data", 2020.}); // return the charge of the particle associated with the Runge-Kutta // integrator const double &charge() { return charge_; } // return the mass of the particle associated with the Runge-Kutta integrator const double &mass() { return mass_; } // starting altitude of the particle const double &start_altitude() { return start_altitude_; } // return the escape radius of the tracer const double &escape_radius() { return escape_radius_; } // return the step size of the Runge-Kutta integrator const double &stepsize() { return stepsize_; } // return the maximum number of steps of the integrator int max_iter() { return max_iter_; } // return the boolean if particle has escaped or not bool particle_escaped() { return particle_escaped_; } // the final time of the trajectory const double &final_time() { return final_time_; } // the final sixvector of the trajectory const std::array<double, 6> &final_sixvector() { return final_sixvector_; } /* Evaluates the trajectory of the particle using a 4th-order Runge Kutta algorithm. Parameters ----------- - t0 (double) : the initial time in seconds - vec0 (std::array<double, 6>) : the initial six-vector (r0, theta0, phi0, pr0, ptheta0, pphi0) at time t0 Returns -------- None */ void evaluate(double t0, std::array<double, 6> vec0); /* Evaluates the trajectory of the particle using a 4th-order Runge Kutta algorithm and return a map that contains the information of the particle trajectory. This will most often be used for debugging purposes to see the actual trajectory. Parameters ----------- - t0 (double) : the initial time in seconds - vec0 (std::array<double, 6>) : the initial six-vector (r0, theta0, phi0, pr0, ptheta0, pphi0) at time t0 Returns -------- - trajectory_data (std::map<std::string, std::vector<double> >) : the trajectory information, that is, the time array of the trajectory and the six-vector of the trajectory in std::vectors. Notes: - keys are ["t", "r", "theta", "phi", "pr", "ptheta", "pphi"] - the final point of the trajectory is also contained in the map - std::vectors (dynamic arrays) are used since the length of each trajectory is not known at compile time. */ std::map<std::string, std::vector<double>> evaluate_and_get_trajectory( double t0, std::array<double, 6> vec0); }; // end class uTrajectoryTracer #endif //__UTRAJECTORYTRACER_HPP_
39.022222
83
0.692141
[ "object", "vector", "model" ]
996aea2245afee3bef1ec88361a7605daa421847
64,704
cxx
C++
panda/src/physx/physxActor.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/physx/physxActor.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/physx/physxActor.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: physxActor.cxx // Created by: enn0x (14Sep09) // //////////////////////////////////////////////////////////////////// // // 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." // //////////////////////////////////////////////////////////////////// #include "physxActor.h" #include "physxActorDesc.h" #include "physxBodyDesc.h" #include "physxShapeDesc.h" #include "physxManager.h" TypeHandle PhysxActor::_type_handle; //////////////////////////////////////////////////////////////////// // Function: PhysxActor::link // Access: Public // Description: //////////////////////////////////////////////////////////////////// void PhysxActor:: link(NxActor *actorPtr) { // Link self _ptr = actorPtr; _ptr->userData = this; _error_type = ET_ok; set_name(actorPtr->getName()); PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; scene->_actors.add(this); // Link shapes NxShape * const *shapes = _ptr->getShapes(); NxU32 nShapes = _ptr->getNbShapes(); for (NxU32 i=0; i < nShapes; i++) { PhysxShape *shape = PhysxShape::factory(shapes[i]->getType()); shape->link(shapes[i]); } } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::unlink // Access: Public // Description: //////////////////////////////////////////////////////////////////// void PhysxActor:: unlink() { // Unlink shapes NxShape * const *shapes = _ptr->getShapes(); NxU32 nShapes = _ptr->getNbShapes(); for (NxU32 i=0; i < nShapes; i++) { PhysxShape *shape = (PhysxShape *)shapes[i]->userData; shape->unlink(); } // Unlink self _ptr->userData = NULL; _error_type = ET_released; PhysxScene *scene = (PhysxScene *)_ptr->getScene().userData; scene->_actors.remove(this); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::release // Access: Published // Description: //////////////////////////////////////////////////////////////////// void PhysxActor:: release() { nassertv(_error_type == ET_ok); unlink(); _ptr->getScene().releaseActor(*_ptr); _ptr = NULL; } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::link_controller // Access: Public // Description: //////////////////////////////////////////////////////////////////// void PhysxActor:: link_controller(PhysxController *controller) { _controller = controller; } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::save_body_to_desc // Access: Published // Description: Saves the body information of a dynamic actor to // the passed body descriptor. //////////////////////////////////////////////////////////////////// bool PhysxActor:: save_body_to_desc(PhysxBodyDesc &bodyDesc) const { nassertr(_error_type == ET_ok, false); return _ptr->saveBodyToDesc(bodyDesc._desc); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::save_to_desc // Access: Published // Description: Saves the state of the actor to the passed // descriptor. //////////////////////////////////////////////////////////////////// void PhysxActor:: save_to_desc(PhysxActorDesc &actorDesc) const { nassertv(_error_type == ET_ok); _ptr->saveToDesc(actorDesc._desc); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_name // Access: Published // Description: Sets a name string for the object that can be // retrieved with get_name(). // This is for debugging and is not used by the // engine. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_name(const char *name) { nassertv(_error_type == ET_ok); _name = name ? name : ""; _ptr->setName(_name.c_str()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_name // Access: Published // Description: Retrieves the name string. //////////////////////////////////////////////////////////////////// const char *PhysxActor:: get_name() const { nassertr(_error_type == ET_ok, ""); return _ptr->getName(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::update_transform // Access: Public // Description: Updates the transform of an assigned NodePath. If // the actor has been created by a PhysxController // then this method will update the NodePath's // transform from the controller's transform. //////////////////////////////////////////////////////////////////// void PhysxActor:: update_transform(const LMatrix4f &m) { // Active transforms are update AFTER scene.fetchResults() has // been called, and thus can contain removed objects. So either // update transforms after scene.fetchResults() - which means // poor performance - or check if an actor has been removed here // in this method. if (_error_type != ET_ok) return; if (_np.is_empty()) return; if (_controller) { LVector3f hpr(_controller->get_h(), 0.0f, 0.0f); LPoint3f pos = _controller->get_pos(); _np.set_transform(_np.get_top(), TransformState::make_pos_hpr(pos, hpr)); } else { _np.set_transform(_np.get_top(), TransformState::make_mat(m)); } } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_global_pos // Access: Published // Description: Retrieves the actors world space position. //////////////////////////////////////////////////////////////////// LPoint3f PhysxActor:: get_global_pos() const { nassertr(_error_type == ET_ok, LPoint3f::zero()); return PhysxManager::nxVec3_to_point3(_ptr->getGlobalPosition()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_global_mat // Access: Published // Description: Retrieves the actors world space transform. //////////////////////////////////////////////////////////////////// LMatrix4f PhysxActor:: get_global_mat() const { nassertr(_error_type == ET_ok, LMatrix4f::zeros_mat()); return PhysxManager::nxMat34_to_mat4(_ptr->getGlobalPose()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_global_quat // Access: Published // Description: Retrieves the actors world space orientation. //////////////////////////////////////////////////////////////////// LQuaternionf PhysxActor:: get_global_quat() const { nassertr(_error_type == ET_ok, LQuaternionf::zero()); return PhysxManager::nxQuat_to_quat(_ptr->getGlobalOrientation()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_global_pos // Access: Published // Description: Method for setting a dynamic actor's position in // the world. Please see set_global_mat for some // caveats. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_global_pos(const LPoint3f &pos) { nassertv(_error_type == ET_ok); nassertv_always(!pos.is_nan()); _ptr->setGlobalPosition(PhysxManager::point3_to_nxVec3(pos)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_global_mat // Access: Published // Description: Method for setting a dynamic actor's transform // matrix in the world. // // This method instantaneously changes the actor space // to world space transformation. // // One should exercise restraint in making use of // these methods. // // Static actors should not be moved at all. There are // various internal data structures for static actors // which may need to be recomputed when one moves. // Also, moving static actors will not interact // correctly with dynamic actors or joints. If you // would like to directly control an actor's position // and would like to have it correctly interact with // dynamic bodies and joints, you should create a // dynamic body with the BF_kinematic flag, and then // use the move_global_*() commands to move it along // a path! // // When briefly moving dynamic actors, one should not: // - Move actors into other actors, thus causing // interpenetration (an invalid physical state). // - Move an actor that is connected by a joint to // another away from the other (thus causing joint // error). // - When moving jointed actors the joints' cached // transform information is destroyed and recreated // next frame; thus this call is expensive for // jointed actors. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_global_mat(const LMatrix4f &mat) { nassertv(_error_type == ET_ok); nassertv_always(!mat.is_nan()); _ptr->setGlobalPose(PhysxManager::mat4_to_nxMat34(mat)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_global_hpr // Access: Published // Description: Method for setting a dynamic actor's orientation in // the world. Please see set_global_mat for some // caveats. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_global_hpr(float h, float p, float r) { nassertv(_error_type == ET_ok); LQuaternionf q; q.set_hpr(LVector3f(h, p, r)); _ptr->setGlobalOrientationQuat(PhysxManager::quat_to_nxQuat(q)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::move_global_pos // Access: Published // Description: The move_global_* calls serve to move kinematically // controlled dynamic actors through the game world. // // See move_global_mat() for more information. // // This call wakes the actor if it is sleeping. //////////////////////////////////////////////////////////////////// void PhysxActor:: move_global_pos(const LPoint3f &pos) { nassertv(_error_type == ET_ok); nassertv_always(!pos.is_nan()); _ptr->moveGlobalPosition(PhysxManager::point3_to_nxVec3(pos)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::move_global_mat // Access: Published // Description: The move_global_* calls serve to move // kinematically controlled dynamic actors through // the game world. // // You set a dynamic actor to be kinematic using the // BF_KINEMATIC body flag, used either in the // PhysBodyDesc or with set_body_flag(). // // The move command will result in a velocity that, // when successfully carried out (i.e. the motion is // not blocked due to joints or collisions) inside // run*(), will move the body into the desired pose. // After the move is carried out during a single time // step, the velocity is returned to zero. Thus, you // must continuously call this in every time step for // kinematic actors so that they move along a path. // // These functions simply store the move destination // until run*() is called, so consecutive calls will // simply overwrite the stored target variable. // // This call wakes the actor if it is sleeping. //////////////////////////////////////////////////////////////////// void PhysxActor:: move_global_mat(const LMatrix4f &mat) { nassertv(_error_type == ET_ok); nassertv_always(!mat.is_nan()); _ptr->moveGlobalPose(PhysxManager::mat4_to_nxMat34(mat)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::move_global_hpr // Access: Published // Description: The move_global_* calls serve to move kinematically // controlled dynamic actors through the game world. // // See move_global_mat() for more information. // // This call wakes the actor if it is sleeping. //////////////////////////////////////////////////////////////////// void PhysxActor:: move_global_hpr(float h, float p, float r) { nassertv(_error_type == ET_ok); LQuaternionf q; q.set_hpr(LVector3f(h, p, r)); _ptr->moveGlobalOrientationQuat(PhysxManager::quat_to_nxQuat(q)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::attach_node_path // Access: Published // Description: Attaches a node path to this actor. The node // path's transform will be updated automatically if // the actor's transform changes (and only then). // // Note: any non-uniform scale or shear set on the // NodePath's transform will be overwritten at the // time of the first update. //////////////////////////////////////////////////////////////////// void PhysxActor:: attach_node_path(const NodePath &np) { nassertv(_error_type == ET_ok); nassertv_always(!np.is_empty()); _np = NodePath(np); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::detach_node_path // Access: Published // Description: Detaches a previously assigned NodePath from this // actor. The NodePath's transform will no longer // be updated from the actor's transform. //////////////////////////////////////////////////////////////////// void PhysxActor:: detach_node_path() { nassertv(_error_type == ET_ok); _np = NodePath(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_node_path // Access: Published // Description: Retrieves a previously attached NodePath. An empty // NodePath will be returned if no NodePath has been // attached to this actor. //////////////////////////////////////////////////////////////////// NodePath PhysxActor:: get_node_path() const { nassertr(_error_type == ET_ok, NodePath::fail()); return _np; } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_scene // Access: Published // Description: Retrieves the scene which this actor belongs to. //////////////////////////////////////////////////////////////////// PhysxScene *PhysxActor:: get_scene() const { nassertr(_error_type == ET_ok, NULL); NxScene *scenePtr = &(_ptr->getScene()); PhysxScene *scene = (PhysxScene *)(scenePtr->userData); return scene; } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_num_shapes // Access: Published // Description: Returns the number of shapes assigned to the // actor. //////////////////////////////////////////////////////////////////// unsigned int PhysxActor:: get_num_shapes() const { nassertr(_error_type == ET_ok, -1); return _ptr->getNbShapes(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::create_shape // Access: Published // Description: Creates a new shape and adds it to the list of // shapes of this actor. // // Mass properties of dynamic actors will not // automatically be recomputed to reflect the new mass // distribution implied by the shape. Follow this call // with a call to update_mass_from_shapes() to do // that. //////////////////////////////////////////////////////////////////// PhysxShape *PhysxActor:: create_shape(PhysxShapeDesc &desc) { nassertr(_error_type == ET_ok, NULL); nassertr(desc.is_valid(),NULL); PhysxShape *shape = PhysxShape::factory(desc.ptr()->getType()); nassertr(shape, NULL); NxShape *shapePtr = _ptr->createShape(*desc.ptr()); nassertr(shapePtr, NULL); shape->link(shapePtr); return shape; } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_shape // Access: Published // Description: Retrieves an individual shape from the actor's // array of shapes. Index must be in the range from // zero to (number-of-shapes minus 1). //////////////////////////////////////////////////////////////////// PhysxShape *PhysxActor:: get_shape(unsigned int idx) const { nassertr(_error_type == ET_ok, NULL); nassertr_always(idx < _ptr->getNbShapes(), NULL); NxShape * const *shapes = _ptr->getShapes(); NxShape *shapePtr = shapes[idx]; PhysxShape *shape = (PhysxShape *)(shapePtr->userData); return shape; } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_shape_by_name // Access: Published // Description: Retrieves an individual shape from the actor's // array of shapes. The first shape for which the // shape's name matches the specified name is // returned, or NULL if no shape has a matching name. //////////////////////////////////////////////////////////////////// PhysxShape *PhysxActor:: get_shape_by_name(const char *name) const { nassertr(_error_type == ET_ok, NULL); NxShape * const *shapes = _ptr->getShapes(); NxShape *shapePtr = NULL; NxU32 nShapes = _ptr->getNbShapes(); for (NxU32 i=0; i < nShapes; i++) { shapePtr = shapes[i]; if (strcmp(shapePtr->getName(), name) == 0) { return (PhysxShape *) shapePtr->userData; } } return NULL; } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::add_force // Access: Published // Description: Applies a force (or impulse) defined in the global // coordinate frame to the actor. // // This will not induce a torque. // // Mode determines if the torque is to be conventional // or impulsive. // // The actor must be dynamic. // This call wakes the actor if it is sleeping and the // wakeup parameter is true (default). //////////////////////////////////////////////////////////////////// void PhysxActor:: add_force(const LVector3f force, PhysxForceMode mode, bool wakeup) { nassertv(_error_type == ET_ok); nassertv_always(!force.is_nan()); _ptr->addForce(PhysxManager::vec3_to_nxVec3(force), (NxForceMode)mode, wakeup); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::add_force_at_pos // Access: Published // Description: Applies a force (or impulse) defined in the global // coordinate frame, acting at a particular point in // global coordinates, to the actor. // // Note that if the force does not act along the // center of mass of the actor, this will also add the // corresponding torque. Because forces are reset at // the end of every timestep, you can maintain a total // external force on an object by calling this once // every frame. // // Mode determines if the torque is to be conventional // or impulsive. // // The actor must be dynamic. // This call wakes the actor if it is sleeping and the // wakeup parameter is true (default). //////////////////////////////////////////////////////////////////// void PhysxActor:: add_force_at_pos(const LVector3f force, const LPoint3f &pos, PhysxForceMode mode, bool wakeup) { nassertv(_error_type == ET_ok); nassertv_always(!force.is_nan()); nassertv_always(!pos.is_nan()); _ptr->addForceAtPos(PhysxManager::vec3_to_nxVec3(force), PhysxManager::point3_to_nxVec3(pos), (NxForceMode)mode, wakeup); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::add_force_at_local_pos // Access: Published // Description: Applies a force (or impulse) defined in the global // coordinate frame, acting at a particular point in // local coordinates, to the actor. // // Note that if the force does not act along the // center of mass of the actor, this will also add // the corresponding torque. Because forces are reset // at the end of every timestep, you can maintain a // total external force on an object by calling this // once every frame. // // Mode determines if the torque is to be conventional // or impulsive. // // The actor must be dynamic. // This call wakes the actor if it is sleeping and the // wakeup parameter is true (default). //////////////////////////////////////////////////////////////////// void PhysxActor:: add_force_at_local_pos(const LVector3f force, const LPoint3f &pos, PhysxForceMode mode, bool wakeup) { nassertv(_error_type == ET_ok); nassertv_always(!force.is_nan()); nassertv_always(!pos.is_nan()); _ptr->addForceAtLocalPos(PhysxManager::vec3_to_nxVec3(force), PhysxManager::point3_to_nxVec3(pos), (NxForceMode)mode, wakeup); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::add_torque // Access: Published // Description: Applies an impulsive torque defined in the global // coordinate frame to the actor. // // Mode determines if the torque is to be conventional // or impulsive. // // The actor must be dynamic. // This call wakes the actor if it is sleeping and the // wakeup parameter is true (default). //////////////////////////////////////////////////////////////////// void PhysxActor:: add_torque(const LVector3f torque, PhysxForceMode mode, bool wakeup) { nassertv(_error_type == ET_ok); nassertv_always(!torque.is_nan()); _ptr->addTorque(PhysxManager::vec3_to_nxVec3(torque), (NxForceMode)mode, wakeup); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::add_local_force // Access: Published // Description: Applies a force (or impulse) defined in the actor // local coordinate frame to the actor. // This will not induce a torque. // // Mode determines if the torque is to be conventional // or impulsive. // // The actor must be dynamic. // This call wakes the actor if it is sleeping and the // wakeup parameter is true (default). //////////////////////////////////////////////////////////////////// void PhysxActor:: add_local_force(const LVector3f force, PhysxForceMode mode, bool wakeup) { nassertv(_error_type == ET_ok); nassertv_always(!force.is_nan()); _ptr->addLocalForce(PhysxManager::vec3_to_nxVec3(force), (NxForceMode)mode, wakeup); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::add_local_force_at_pos // Access: Published // Description: Applies a force (or impulse) defined in the actor // local coordinate frame, acting at a particular // point in global coordinates, to the actor. // // Note that if the force does not act along the // center of mass of the actor, this will also add // the corresponding torque. Because forces are reset // at the end of every timestep, you can maintain a // total external force on an object by calling this // once every frame. // // Mode determines if the torque is to be conventional // or impulsive. // // The actor must be dynamic. // This call wakes the actor if it is sleeping and the // wakeup parameter is true (default). //////////////////////////////////////////////////////////////////// void PhysxActor:: add_local_force_at_pos(const LVector3f force, const LPoint3f &pos, PhysxForceMode mode, bool wakeup) { nassertv(_error_type == ET_ok); nassertv_always(!force.is_nan()); nassertv_always(!pos.is_nan()); _ptr->addLocalForceAtPos(PhysxManager::vec3_to_nxVec3(force), PhysxManager::point3_to_nxVec3(pos), (NxForceMode)mode, wakeup); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::add_local_force_at_local_pos // Access: Published // Description: Applies a force (or impulse) defined in the actor // local coordinate frame, acting at a particular // point in local coordinates, to the actor. // // Note that if the force does not act along the // center of mass of the actor, this will also add the // corresponding torque. Because forces are reset at // the end of every timestep, you can maintain a total // external force on an object by calling this once // every frame. // // Mode determines if the torque is to be conventional // or impulsive. // // The actor must be dynamic. // This call wakes the actor if it is sleeping and the // wakeup parameter is true (default). //////////////////////////////////////////////////////////////////// void PhysxActor:: add_local_force_at_local_pos(const LVector3f force, const LPoint3f &pos, PhysxForceMode mode, bool wakeup) { nassertv(_error_type == ET_ok); nassertv_always(!force.is_nan()); nassertv_always(!pos.is_nan()); _ptr->addLocalForceAtLocalPos(PhysxManager::vec3_to_nxVec3(force), PhysxManager::point3_to_nxVec3(pos), (NxForceMode)mode, wakeup); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::add_local_torque // Access: Published // Description: Applies an impulsive torque defined in the actor // local coordinate frame to the actor. // // Mode determines if the torque is to be conventional // or impulsive. // // The actor must be dynamic. // This call wakes the actor if it is sleeping and the // wakeup parameter is true (default). //////////////////////////////////////////////////////////////////// void PhysxActor:: add_local_torque(const LVector3f torque, PhysxForceMode mode, bool wakeup) { nassertv(_error_type == ET_ok); nassertv_always(!torque.is_nan()); _ptr->addLocalTorque(PhysxManager::vec3_to_nxVec3(torque), (NxForceMode)mode, wakeup); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::update_mass_from_shapes // Access: Published // Description: Recomputes a dynamic actor's mass properties from // its shapes. // // Given a constant density or total mass, the actors // mass properties can be recomputed using the shapes // attached to the actor. If the actor has no shapes, // then only the totalMass parameter can be used. If // all shapes in the actor are trigger shapes // (non-physical), the call will fail. // // The mass of each shape is either the shape's local // density (as specified in the PhysxShapeDesc; // default 1.0) multiplied by the shape's volume or a // directly specified shape mass. // // The inertia tensor, mass frame and center of mass // will always be recomputed. If there are no shapes // in the actor, the mass will be totalMass, and the // mass frame will be set to the center of the actor. // // If you supply a non-zero total mass, the actor's // mass and inertia will first be computed as above // and then scaled to fit this total mass. // // If you supply a non-zero density, the actor's mass // and inertia will first be computed as above and // then scaled by this factor. // // Either totalMass or density must be non-zero. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// bool PhysxActor:: update_mass_from_shapes(float density, float totalMass) { nassertr(_error_type == ET_ok, false); return _ptr->updateMassFromShapes(density, totalMass); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::compute_kinetic_energy // Access: Published // Description: Computes the total kinetic (rotational and // translational) energy of the object. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// float PhysxActor:: compute_kinetic_energy() const { nassertr(_error_type == ET_ok, 0.0f); return _ptr->computeKineticEnergy(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::is_dynamic // Access: Published // Description: Returns true if the actor is dynamic. //////////////////////////////////////////////////////////////////// bool PhysxActor:: is_dynamic() const { nassertr(_error_type == ET_ok, false); return _ptr->isDynamic(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_shape_group // Access: Published // Description: Sets the collision group for all shapes of this // actor. See PhysxShape.setGroup(). //////////////////////////////////////////////////////////////////// void PhysxActor:: set_shape_group(unsigned int group) { nassertv(_error_type == ET_ok); nassertv(group >= 0 && group < 32); NxShape * const *shapes = _ptr->getShapes(); NxU32 nShapes = _ptr->getNbShapes(); for (NxU32 i=0; i < nShapes; i++) { shapes[i]->setGroup( group ); } } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_body_flag // Access: Published // Description: Raise or lower individual BodyFlag flags. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_body_flag(PhysxBodyFlag flag, bool value) { if (value == true) { _ptr->raiseBodyFlag((NxBodyFlag)flag); } else { _ptr->clearBodyFlag((NxBodyFlag)flag); } } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_body_flag // Access: Published // Description: Return the specified BodyFlag flag. //////////////////////////////////////////////////////////////////// bool PhysxActor:: get_body_flag(PhysxBodyFlag flag) const { nassertr(_error_type == ET_ok, false); return ptr()->readBodyFlag((NxBodyFlag)flag); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_actor_flag // Access: Published // Description: Raise or lower individual ActorFlag flags. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_actor_flag(PhysxActorFlag flag, bool value) { if (value == true) { _ptr->raiseActorFlag((NxActorFlag)flag); } else { _ptr->clearActorFlag((NxActorFlag)flag); } } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_actor_flag // Access: Published // Description: Return the specified ActorFlag flag. //////////////////////////////////////////////////////////////////// bool PhysxActor:: get_actor_flag(PhysxActorFlag flag) const { nassertr(_error_type == ET_ok, false); return ptr()->readActorFlag((NxActorFlag)flag); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_contact_report_flag // Access: Published // Description: Sets the actor's contact report flags. // // These flags are used to determine the kind of // report that is generated for interactions with // other actors. // // Please note: If the actor is part of an interacting // pair for which the contact report generation is // controlled already through any other mechanism // (for example by use of // PhysxScene::set_actor_pair_flags) // then the union of all the specified contact report // flags will be used to generate the report. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_contact_report_flag(PhysxContactPairFlag flag, bool value) { nassertv(_error_type == ET_ok); NxU32 flags = _ptr->getContactReportFlags(); if (value == true) { flags |= flag; } else { flags &= ~(flag); } _ptr->setContactReportFlags(flags); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_contact_report_threshold // Access: Published // Description: Sets the force threshold for contact reports. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_contact_report_threshold(float threshold) { nassertv(_error_type == ET_ok); nassertv(threshold >= 0.0f); _ptr->setContactReportThreshold(threshold); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_group // Access: Published // Description: Assigns the actor to a user defined group of // actors. The actor group must be an integer in // between 0 and 0x7fff (32767). // // This is similar to NxShape groups, except those are // only five bits and serve a different purpose. // // The PhysxScene::set_actor_group_pair_flags() lets // you set certain behaviors for pairs of actor // groups. // // By default every actor is created in group 0. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_group(unsigned int group) { nassertv(_error_type == ET_ok); nassertv(group >= 0 && group < 0x8000); ptr()->setGroup(group); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_group // Access: Published // Description: Retrieves the actor group this actor is assigned // to. //////////////////////////////////////////////////////////////////// unsigned int PhysxActor:: get_group() const { nassertr(_error_type == ET_ok, 0); return ptr()->getGroup(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_dominance_group // Access: Published // Description: Assigns dynamic actors a dominance group // identifier. Dominance groups are integere in the // range from 0 to 31. // // This is similar to shape groups, except those serve // a different purpose. // // The PhysxScene::set_dominance_group_pair() lets you // set certain behaviors for pairs of dominance // groups. // // By default every actor is created in group 0. // Static actors must stay in group 0; thus you can // only call this on dynamic actors. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_dominance_group(unsigned int group) { nassertv(_error_type == ET_ok); nassertv(group >= 0 && group < 32); nassertv(is_dynamic() == true); _ptr->setDominanceGroup(group); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_dominance_group // Access: Published // Description: Retrieves the dominance group of this actor. //////////////////////////////////////////////////////////////////// unsigned int PhysxActor:: get_dominance_group() const { nassertr(_error_type == ET_ok, 0); return ptr()->getDominanceGroup(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_angular_damping // Access: Published // Description: Sets the angular damping coefficient. Zero // represents no damping. The angular damping // coefficient must be nonnegative. The actor must be // dynamic. // Default: 0.05 //////////////////////////////////////////////////////////////////// void PhysxActor:: set_angular_damping(float angDamp) { nassertv(_error_type == ET_ok); nassertv(angDamp >= 0.0f); _ptr->setAngularDamping(angDamp); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_angular_damping // Access: Published // Description: Returns the angular damping coefficient. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// float PhysxActor:: get_angular_damping() const { nassertr(_error_type == ET_ok, 0.0f); return _ptr->getAngularDamping(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_linear_damping // Access: Published // Description: Sets the linear damping coefficient. Zero // represents no damping. The damping coefficient must // be nonnegative. The actor must be dynamic. // Default: 0 //////////////////////////////////////////////////////////////////// void PhysxActor:: set_linear_damping(float linDamp) { nassertv(_error_type == ET_ok); nassertv(linDamp >= 0.0f); _ptr->setLinearDamping(linDamp); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_linear_damping // Access: Published // Description: Retrieves the linear damping coefficient. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// float PhysxActor:: get_linear_damping() const { nassertr(_error_type == ET_ok, 0.0f); return _ptr->getLinearDamping(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_linear_velocity // Access: Published // Description: Sets the linear velocity of the actor. // // Note that if you continuously set the velocity of // an actor yourself, forces such as gravity or // friction will not be able to manifest themselves, // because forces directly influence only the // velocity/momentum of an actor. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_linear_velocity(const LVector3f &linVel) { nassertv(_error_type == ET_ok); nassertv(_ptr->isDynamic()); _ptr->setLinearVelocity(PhysxManager::vec3_to_nxVec3(linVel)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_angular_velocity // Access: Published // Description: Sets the angular velocity of the actor. // // Note that if you continuously set the angular // velocity of an actor yourself, forces such as // friction will not be able to rotate the actor, // because forces directly influence only the // velocity/momentum. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_angular_velocity(const LVector3f &angVel) { nassertv(_error_type == ET_ok); nassertv(_ptr->isDynamic()); _ptr->setAngularVelocity(PhysxManager::vec3_to_nxVec3(angVel)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_max_angular_velocity // Access: Published // Description: Lets you set the maximum angular velocity permitted // for this actor. // // Because for various internal computations, very // quickly rotating actors introduce error into the // simulation, which leads to undesired results. // // With PhysxManager::set_parameter(PP_max_angular_velocity) // you can set the default maximum velocity for actors // created after the call. Bodies' high angular // velocities are clamped to this value. // // However, because some actors, such as car wheels, // should be able to rotate quickly, you can override // the default setting on a per-actor basis with the // below call. Note that objects such as wheels which // are approximated with spherical or other smooth // collision primitives can be simulated with // stability at a much higher angular velocity than, // say, a box that has corners. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_max_angular_velocity(float maxAngVel) { nassertv(_error_type == ET_ok); nassertv(_ptr->isDynamic()); _ptr->setMaxAngularVelocity(maxAngVel); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_linear_velocity // Access: Published // Description: Returns the linear velocity of an actor. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// LVector3f PhysxActor:: get_linear_velocity() const { nassertr(_error_type == ET_ok, LVector3f::zero()); return PhysxManager::nxVec3_to_vec3(_ptr->getLinearVelocity()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_angular_velocity // Access: Published // Description: Returns the angular velocity of the actor. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// LVector3f PhysxActor:: get_angular_velocity() const { nassertr(_error_type == ET_ok, LVector3f::zero()); return PhysxManager::nxVec3_to_vec3(_ptr->getAngularVelocity()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_max_angular_velocity // Access: Published // Description: Returns the maximum angular velocity permitted // for this actor. //////////////////////////////////////////////////////////////////// float PhysxActor:: get_max_angular_velocity() const { nassertr(_error_type == ET_ok, 0.0f); return _ptr->getMaxAngularVelocity(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_point_velocity // Access: Published // Description: Computes the velocity of a point given in world // coordinates if it were attached to the actor and // moving with it. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// LVector3f PhysxActor:: get_point_velocity(const LPoint3f &point) const { nassertr(_error_type == ET_ok, LVector3f::zero()); nassertr_always(!point.is_nan(), LVector3f::zero()); NxVec3 nPoint = PhysxManager::point3_to_nxVec3(point); return PhysxManager::nxVec3_to_vec3(_ptr->getPointVelocity(nPoint)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_local_point_velocity // Access: Published // Description: Computes the velocity of a point given in body // local coordinates as if it were attached to the // actor and moving with it. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// LVector3f PhysxActor:: get_local_point_velocity(const LPoint3f &point) const { nassertr(_error_type == ET_ok, LVector3f::zero()); nassertr_always(!point.is_nan(), LVector3f::zero()); NxVec3 nPoint = PhysxManager::point3_to_nxVec3(point); return PhysxManager::nxVec3_to_vec3(_ptr->getLocalPointVelocity(nPoint)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_linear_momentum // Access: Published // Description: Sets the linear momentum of the actor. // Note that if you continuously set the linear // momentum of an actor yourself, forces such as // gravity or friction will not be able to manifest // themselves, because forces directly influence only // the velocity/momentum of a actor. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_linear_momentum(const LVector3f &momentum) { nassertv(_error_type == ET_ok); _ptr->setLinearMomentum(PhysxManager::vec3_to_nxVec3(momentum)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_angular_momentum // Access: Published // Description: Sets the angular momentum of the actor. // Note that if you continuously set the angular // velocity of an actor yourself, forces such as // friction will not be able to rotate the actor, // because forces directly influence only the velocity // of actor. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_angular_momentum(const LVector3f &momentum) { nassertv(_error_type == ET_ok); _ptr->setAngularMomentum(PhysxManager::vec3_to_nxVec3(momentum)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_linear_momentum // Access: Published // Description: Retrieves the linear momentum of an actor. // The momentum is equal to the velocity times the // mass. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// LVector3f PhysxActor:: get_linear_momentum() const { nassertr(_error_type == ET_ok, LVector3f::zero()); return PhysxManager::nxVec3_to_vec3(_ptr->getLinearMomentum()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_angular_momentum // Access: Published // Description: Retrieves the angular momentum of an actor. // The angular momentum is equal to the angular // velocity times the global space inertia tensor. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// LVector3f PhysxActor:: get_angular_momentum() const { nassertr(_error_type == ET_ok, LVector3f::zero()); return PhysxManager::nxVec3_to_vec3(_ptr->getAngularMomentum()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_sleep_linear_velocity // Access: Published // Description: Sets the linear velocity below which an actor may // go to sleep. Actors whose linear velocity is above // this threshold will not be put to sleep. // // Setting the sleep angular/linear velocity only // makes sense when the BF_energy_sleep_test is not // set. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_sleep_linear_velocity(float threshold) { nassertv(_error_type == ET_ok); _ptr->setSleepLinearVelocity(threshold); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_sleep_angular_velocity // Access: Published // Description: Sets the angular velocity below which an actor may // go to sleep. Actors whose angular velocity is // above this threshold will not be put to sleep. // // Setting the sleep angular/linear velocity only // makes sense when the BF_energy_sleep_test is not // set. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_sleep_angular_velocity(float threshold) { nassertv(_error_type == ET_ok); _ptr->setSleepAngularVelocity(threshold); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_sleep_energy_threshold // Access: Published // Description: Sets the energy threshold below which an actor may // go to sleep. Actors whose kinematic energy is above // this threshold will not be put to sleep. // // Setting the sleep energy threshold only makes sense // when the BF_energy_sleep_test is set. There are // also other types of sleeping that uses the linear // and angular velocities directly instead of the // energy. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_sleep_energy_threshold(float threshold) { nassertv(_error_type == ET_ok); _ptr->setSleepEnergyThreshold(threshold); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_sleep_linear_velocity // Access: Published // Description: Returns the linear velocity below which an actor // may go to sleep. Actors whose linear velocity is // above this threshold will not be put to sleep. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// float PhysxActor:: get_sleep_linear_velocity() const { nassertr(_error_type == ET_ok, 0.0f); return _ptr->getSleepLinearVelocity(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_sleep_angular_velocity // Access: Published // Description: Returns the angular velocity below which an actor // may go to sleep. Actors whose angular velocity is // above this threshold will not be put to sleep. // The actor must be dynamic. //////////////////////////////////////////////////////////////////// float PhysxActor:: get_sleep_angular_velocity() const { nassertr(_error_type == ET_ok, 0.0f); return _ptr->getSleepAngularVelocity(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_sleep_energy_threshold // Access: Published // Description: Returns the energy below which an actor may go to // sleep. Actors whose energy is above this threshold // will not be put to sleep. The actor must be dynamic. //////////////////////////////////////////////////////////////////// float PhysxActor:: get_sleep_energy_threshold() const { nassertr(_error_type == ET_ok, 0.0f); return _ptr->getSleepEnergyThreshold(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::is_sleeping // Access: Published // Description: Returns true if this body is sleeping. // // When an actor does not move for a period of time, // it is no longer simulated in order to save time. // This state is called sleeping. However, because the // object automatically wakes up when it is either // touched by an awake object, or one of its // properties is changed by the user, the entire sleep // mechanism should be transparent to the user. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// bool PhysxActor:: is_sleeping() const { nassertr(_error_type == ET_ok, false); return _ptr->isSleeping(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::wake_up // Access: Published // Description: Wakes up the actor if it is sleeping. // // The wakeCounterValue determines how long until the // body is put to sleep, a value of zero means that // the body is sleeping. wake_up(0) is equivalent to // PhysxActor::put_to_sleep(). // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: wake_up(float wakeCounterValue) { nassertv(_error_type == ET_ok); _ptr->wakeUp(wakeCounterValue); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::put_to_sleep // Access: Published // Description: Forces the actor to sleep. // // The actor will stay asleep until the next call to // simulate, and will not wake up until then even when // otherwise it would (for example a force is applied // to it). It can however wake up during the next // do_physics call. // // The actor must be dynamic. //////////////////////////////////////////////////////////////////// void PhysxActor:: put_to_sleep() { nassertv(_error_type == ET_ok); _ptr->putToSleep(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_mass // Access: Published // Description: Sets the mass of a dynamic actor. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_mass(float mass) { nassertv(_error_type == ET_ok); _ptr->setMass(mass); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_mass // Access: Published // Description: Returns the mass of the actor. //////////////////////////////////////////////////////////////////// float PhysxActor:: get_mass() const { nassertr(_error_type == ET_ok, 0.0f); return _ptr->getMass(); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_offset_local_mat // Access: Published // Description: Sets the matrix of the center of mass relative // to the actor. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_offset_local_mat(const LMatrix4f &mat) { nassertv(_error_type == ET_ok); _ptr->setCMassOffsetLocalPose(PhysxManager::mat4_to_nxMat34(mat)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_offset_local_pos // Access: Published // Description: Sets the position of the center of mass relative // to the actor. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_offset_local_pos(const LPoint3f &pos) { nassertv(_error_type == ET_ok); _ptr->setCMassOffsetLocalPosition(PhysxManager::point3_to_nxVec3(pos)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_offset_local_orientation // Access: Published // Description: Sets the orientation of the center of mass relative // to the actor. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_offset_local_orientation(const LMatrix3f &mat) { nassertv(_error_type == ET_ok); _ptr->setCMassOffsetLocalOrientation(PhysxManager::mat3_to_nxMat33(mat)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_offset_global_mat // Access: Published // Description: Sets the matrix of the center of mass relative // to world space. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_offset_global_mat(const LMatrix4f &mat) { nassertv(_error_type == ET_ok); _ptr->setCMassOffsetGlobalPose(PhysxManager::mat4_to_nxMat34(mat)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_offset_global_pos // Access: Published // Description: Sets the position of the center of mass relative // to world space. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_offset_global_pos(const LPoint3f &pos) { nassertv(_error_type == ET_ok); _ptr->setCMassOffsetGlobalPosition(PhysxManager::point3_to_nxVec3(pos)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_offset_global_orientation // Access: Published // Description: Sets the orientation of the center of mass relative // to world space. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_offset_global_orientation(const LMatrix3f &mat) { nassertv(_error_type == ET_ok); _ptr->setCMassOffsetGlobalOrientation(PhysxManager::mat3_to_nxMat33(mat)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_global_mat // Access: Published // Description: Moves the actor by setting the transform of the // center of mass. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_global_mat(const LMatrix4f &mat) { nassertv(_error_type == ET_ok); _ptr->setCMassGlobalPose(PhysxManager::mat4_to_nxMat34(mat)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_global_pos // Access: Published // Description: Moves the actor by setting the position of the // center of mass. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_global_pos(const LPoint3f &pos) { nassertv(_error_type == ET_ok); _ptr->setCMassGlobalPosition(PhysxManager::point3_to_nxVec3(pos)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_c_mass_global_orientation // Access: Published // Description: Moves the actor by setting the orientation of the // center of mass. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_c_mass_global_orientation(const LMatrix3f &mat) { nassertv(_error_type == ET_ok); _ptr->setCMassGlobalOrientation(PhysxManager::mat3_to_nxMat33(mat)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::set_mass_space_inertia_tensor // Access: Published // Description: Sets the inertia tensor, using a parameter // specified in mass space coordinates. //////////////////////////////////////////////////////////////////// void PhysxActor:: set_mass_space_inertia_tensor(const LVector3f &m) { nassertv(_error_type == ET_ok); _ptr->setMassSpaceInertiaTensor(PhysxManager::vec3_to_nxVec3(m)); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_c_mass_global_mat // Access: Published // Description: Returns the center of mass transform in world // space. //////////////////////////////////////////////////////////////////// LMatrix4f PhysxActor:: get_c_mass_global_mat() const { nassertr(_error_type == ET_ok, LMatrix4f::zeros_mat()); return PhysxManager::nxMat34_to_mat4(_ptr->getCMassGlobalPose()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_c_mass_global_pos // Access: Published // Description: Returns the center of mass position in world // space. //////////////////////////////////////////////////////////////////// LPoint3f PhysxActor:: get_c_mass_global_pos() const { nassertr(_error_type == ET_ok, LPoint3f::zero()); return PhysxManager::nxVec3_to_point3(_ptr->getCMassGlobalPosition()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_c_mass_global_orientation // Access: Published // Description: Returns the center of mass orientation in world // space. //////////////////////////////////////////////////////////////////// LMatrix3f PhysxActor:: get_c_mass_global_orientation() const { nassertr(_error_type == ET_ok, LMatrix3f::ident_mat()); return PhysxManager::nxMat33_to_mat3(_ptr->getCMassGlobalOrientation()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_c_mass_local_mat // Access: Published // Description: Returns the center of mass transform relative // to the actor. //////////////////////////////////////////////////////////////////// LMatrix4f PhysxActor:: get_c_mass_local_mat() const { nassertr(_error_type == ET_ok, LMatrix4f::zeros_mat()); return PhysxManager::nxMat34_to_mat4(_ptr->getCMassLocalPose()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_c_mass_local_pos // Access: Published // Description: Returns the center of mass position relative to // the actor. //////////////////////////////////////////////////////////////////// LPoint3f PhysxActor:: get_c_mass_local_pos() const { nassertr(_error_type == ET_ok, LPoint3f::zero()); return PhysxManager::nxVec3_to_point3(_ptr->getCMassLocalPosition()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_c_mass_local_orientation // Access: Published // Description: Returns the center of mass orientation relative to // the actor. //////////////////////////////////////////////////////////////////// LMatrix3f PhysxActor:: get_c_mass_local_orientation() const { nassertr(_error_type == ET_ok, LMatrix3f::ident_mat()); return PhysxManager::nxMat33_to_mat3(_ptr->getCMassLocalOrientation()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_mass_space_inertia_tensor // Access: Published // Description: Returns the diagonal inertia tensor of the actor // relative to the mass coordinate frame. //////////////////////////////////////////////////////////////////// LVector3f PhysxActor:: get_mass_space_inertia_tensor() const { nassertr(_error_type == ET_ok, LVector3f::zero()); return PhysxManager::nxVec3_to_vec3(_ptr->getMassSpaceInertiaTensor()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_global_inertia_tensor // Access: Published // Description: Returns the inertia tensor of the actor relative // to the world coordinate frame. //////////////////////////////////////////////////////////////////// LMatrix3f PhysxActor:: get_global_inertia_tensor() const { nassertr(_error_type == ET_ok, LMatrix3f::ident_mat()); return PhysxManager::nxMat33_to_mat3(_ptr->getGlobalInertiaTensor()); } //////////////////////////////////////////////////////////////////// // Function: PhysxActor::get_global_inertia_tensor_inverse // Access: Published // Description: Returns the inverse of the inertia tensor of the // actor relative to the world coordinate frame. //////////////////////////////////////////////////////////////////// LMatrix3f PhysxActor:: get_global_inertia_tensor_inverse() const { nassertr(_error_type == ET_ok, LMatrix3f::ident_mat()); return PhysxManager::nxMat33_to_mat3(_ptr->getGlobalInertiaTensorInverse()); }
37.186207
133
0.526923
[ "object", "shape", "transform", "3d" ]
5f5a1f9226e707c1437e09c01cb7398f020dda35
10,711
cpp
C++
Tudat/Mathematics/GeometricShapes/sphereSegment.cpp
JPelamatti/ThesisTUDAT
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
[ "BSD-3-Clause" ]
null
null
null
Tudat/Mathematics/GeometricShapes/sphereSegment.cpp
JPelamatti/ThesisTUDAT
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
[ "BSD-3-Clause" ]
null
null
null
Tudat/Mathematics/GeometricShapes/sphereSegment.cpp
JPelamatti/ThesisTUDAT
b94ce35fb7c8fa44ae83238e296a979dfa3adfe8
[ "BSD-3-Clause" ]
1
2019-05-30T03:42:22.000Z
2019-05-30T03:42:22.000Z
/* Copyright (c) 2010-2015, Delft University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * - Neither the name of the Delft University of Technology 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. * * Changelog * YYMMDD Author Comment * 100910 D. Dirkx First version of file. * 100915 D. Dirkx Modified to correct comments, 80-lines * rule, etc. * 100928 D. Dirkx Modifications following first checking * iteration. * 100929 D. Dirkx Creation of separate file for class. * 101125 D. Dirkx Update of class, better get and set * functions. * 110208 K. Kumar Updated file header; Doxygen comments * corrected; minor changes to functions. * 110209 D. Dirkx Minor changes. * 110209 K. Kumar Minor changes. * 110905 S. Billemont Reorganized includes. * Moved (con/de)structors and getter/setters to header. * 120323 D. Dirkx Removed set functions; moved functionality to constructor. * * References * * Notes * */ #include <cmath> #include "Tudat/Astrodynamics/BasicAstrodynamics/unitConversions.h" #include "Tudat/Mathematics/BasicMathematics/coordinateConversions.h" #include "Tudat/Mathematics/GeometricShapes/sphereSegment.h" namespace tudat { namespace geometric_shapes { // Using declarations. using std::cerr; using std::endl; using std::cos; using std::sin; using unit_conversions::convertRadiansToDegrees; SphereSegment::SphereSegment( const double radius, const double minimumAzimuthAngle, const double maximumAzimuthAngle, const double minimumZenithAngle, const double maximumZenithAngle ) { radius_ = radius; setMinimumIndependentVariable( 1, minimumAzimuthAngle ); setMaximumIndependentVariable( 1, maximumAzimuthAngle ); setMinimumIndependentVariable( 2, minimumZenithAngle ); setMaximumIndependentVariable( 2, maximumZenithAngle ); } //! Get surface point on sphere segment. Eigen::VectorXd SphereSegment::getSurfacePoint( const double azimuthAngle, const double zenithAngle ) { Eigen::Vector3d sphericalPositionVector = Eigen::Vector3d( radius_, zenithAngle, azimuthAngle ); // Gets surface point on sphere, unrotated and centered at origin. cartesianPositionVector_ = coordinate_conversions::convertSphericalToCartesian( sphericalPositionVector ); // Translate point. transformPoint( cartesianPositionVector_ ); // Return Cartesian position vector. return cartesianPositionVector_; } //! Get surface derivative on sphere segment. Eigen::VectorXd SphereSegment::getSurfaceDerivative( const double azimuthAngle, const double zenithAngle, const int powerOfAzimuthAngleDerivative, const int powerOfZenithAngleDerivative ) { // Declare and set size of derivative vector. Eigen::VectorXd derivative_ = Eigen::VectorXd( 3 ); // Go through the different possibilities for the values of the power // of the derivative. if ( powerOfAzimuthAngleDerivative < 0 || powerOfZenithAngleDerivative < 0 ) { derivative_( 0 ) = 0.0; derivative_( 1 ) = 0.0; derivative_( 2 ) = 0.0; cerr << "No negative power of derivatives allowed, returning 0,0,0" << endl; } // When requesting the zeroth derivative with respect to the two // independent variables, the surface point is returned. Note that this // does include the offset. else if ( powerOfAzimuthAngleDerivative == 0 && powerOfZenithAngleDerivative == 0 ) { derivative_ = getSurfacePoint( azimuthAngle, zenithAngle ); } // The contributions of the two parameterizing variables are determined // and then multiplied component-wise. else { // Declare and set sizes contribution vectors. Eigen::VectorXd derivative1Contribution_ = Eigen::VectorXd( 3 ); Eigen::VectorXd derivative2Contribution_ = Eigen::VectorXd( 3 ); // Since this derivative is "cyclical", as it is // only dependent on sines and cosines, only the "modulo 4"th // derivatives need to be determined. Derivatives are determined // from the form of the spherical coordinates, see // basic_mathematics::coordinateConversions::convertSphericalToCartesian from // Tudat Core. switch( powerOfAzimuthAngleDerivative % 4 ) { case( 0 ): derivative1Contribution_( 0 ) = cos( azimuthAngle ); derivative1Contribution_( 1 ) = sin( azimuthAngle ); derivative1Contribution_( 2 ) = 0.0; break; case( 1 ): derivative1Contribution_( 0 ) = -sin( azimuthAngle ); derivative1Contribution_( 1 ) = cos( azimuthAngle ); derivative1Contribution_( 2 ) = 0.0; break; case( 2 ): derivative1Contribution_( 0 ) = -cos( azimuthAngle ); derivative1Contribution_( 1 ) = -sin( azimuthAngle ); derivative1Contribution_( 2 ) = 0.0; break; case( 3 ): derivative1Contribution_( 0 ) = sin( azimuthAngle ); derivative1Contribution_( 1 ) = -cos( azimuthAngle ); derivative1Contribution_( 2 ) = 0.0; break; default: cerr << " Bad value for powerOfAzimuthAngleDerivative" << " ( mod 4 ) of value is not 0, 1, 2 or 3 " << endl; } // This derivative is "cyclical" in the same manner as the derivative // with respect to the 1st independent variable. switch( powerOfZenithAngleDerivative %4 ) { case( 0 ): derivative2Contribution_( 0 ) = sin( zenithAngle ); derivative2Contribution_( 1 ) = sin( zenithAngle ); derivative2Contribution_( 2 ) = cos( zenithAngle ); break; case( 1 ): derivative2Contribution_( 0 ) = cos( zenithAngle ); derivative2Contribution_( 1 ) = cos( zenithAngle ); derivative2Contribution_( 2 ) = -sin( zenithAngle ); break; case( 2 ): derivative2Contribution_( 0 ) = -sin( zenithAngle ); derivative2Contribution_( 1 ) = -sin( zenithAngle ); derivative2Contribution_( 2 ) = -cos( zenithAngle ); break; case( 3 ): derivative2Contribution_( 0 ) = -cos( zenithAngle ); derivative2Contribution_( 1 ) = -cos( zenithAngle ); derivative2Contribution_( 2 ) = sin( zenithAngle ); break; default: cerr << " Bad value for powerOfZenithAngleDerivative" << " ( mod 4 ) of value is not 0, 1, 2 or 3 " << endl; } // Construct the full derivative. derivative_( 0 ) = derivative1Contribution_( 0 ) * derivative2Contribution_( 0 ); derivative_( 1 ) = derivative1Contribution_( 1 ) * derivative2Contribution_( 1 ); derivative_( 2 ) = derivative1Contribution_( 2 ) * derivative2Contribution_( 2 ); // Scale vector by radius. derivative_ = derivative_ * radius_; // Rotate derivatives to take into account rotation of sphere. derivative_ = rotationMatrix_ * scalingMatrix_ * derivative_; } return derivative_; } //! Get parameter of sphere segment. double SphereSegment::getParameter( const int index ) { // Check if parameter is radius. if ( index == 0 ) { parameter_ = radius_; } // Else return cerr statement. else { parameter_ = -0.0; // Cerr statement. cerr << "Parameter does not exist" << endl; } // Return parameter. return parameter_; } //! Overload ostream to print class information. std::ostream& operator<<( std::ostream& stream, SphereSegment& sphereSegment ) { stream << "This is a sphere segment geometry." << endl; stream << "The range of the independent variables are: " << endl; stream << "Azimuth angle: " << convertRadiansToDegrees( sphereSegment.getMinimumIndependentVariable( 1 ) ) << " degrees to " << convertRadiansToDegrees( sphereSegment.getMaximumIndependentVariable( 1 ) ) << " degrees" << endl; stream << "Zenith angle: " << convertRadiansToDegrees( sphereSegment.getMinimumIndependentVariable( 2 ) ) << " degrees to " << convertRadiansToDegrees( sphereSegment.getMaximumIndependentVariable( 2 ) ) << " degrees" << endl; stream << "The radius is: " << sphereSegment.getRadius( ) << " meter." << endl; // Return stream. return stream; } } // namespace geometric_shapes } // namespace tudat
38.949091
100
0.624592
[ "geometry", "vector" ]
5f64b79456e20b6ead43249c6749f217945605b0
6,527
cpp
C++
NeuralCells/Mouth.cpp
CrishNate/NeuralCells
b55c8396a73cadfbf0b02192c07a62cdc752a399
[ "MIT" ]
null
null
null
NeuralCells/Mouth.cpp
CrishNate/NeuralCells
b55c8396a73cadfbf0b02192c07a62cdc752a399
[ "MIT" ]
null
null
null
NeuralCells/Mouth.cpp
CrishNate/NeuralCells
b55c8396a73cadfbf0b02192c07a62cdc752a399
[ "MIT" ]
null
null
null
#include "Mouth.h" #include "Plant.h" #include "CellCreature.h" #include "World.h" void Mouth::Draw(RGBColor color, float angle, const Camera& camera) { angle += m_AngleOffset - M_PI / 2; if (m_ConsumeCooldown > clock()) { m_Chum += 0.25; if (m_Chum > M_2PI) m_Chum -= M_2PI; } else { m_Chum = 0; } if (m_ConsumeType == FoodType::FT_Meat) { Vector2D left = Vector2D(-1, 0) * m_Scale; Vector2D right = Vector2D(1, 0) * m_Scale; Vector2D forward = Vector2D(0, 1) * m_Scale; Vector2D leftd = (left + forward).GetRotated(angle) + m_Position; Vector2D rightd = (right + forward).GetRotated(angle) + m_Position; left = left * abs(cos(m_Chum)) * 1.5 + Vector2D(0, -1) * m_Scale; right = right * abs(cos(m_Chum)) * 1.5 + Vector2D(0, -1) * m_Scale; Vector2D leftt = left.GetRotated(angle) + m_Position; Vector2D rightt = right.GetRotated(angle) + m_Position; forward.GetRotated(angle); DrawTriangle(m_Position.x + forward.x / 10.0f, m_Position.y + forward.y / 10.0f, leftd.x, leftd.y, leftt.x, leftt.y, color, camera); DrawTriangle(m_Position.x + forward.x / 10.0f, m_Position.y + forward.y / 10.0f, rightd.x, rightd.y, rightt.x, rightt.y, color, camera); } else if (m_ConsumeType == FoodType::FT_Plant) { float anim = cos(m_Chum); float anim2 = sin(m_Chum); Vector2D leftN = Vector2D(-1 + anim2 / 6.0f, -1).GetNormalize(); Vector2D rightN = Vector2D(1 - anim2 / 6.0f, -1).GetNormalize(); Vector2D forwardN = Vector2D(anim / 6.0f, -1).GetNormalize(); Vector2D leftf = (leftN * m_Scale * 2).GetRotated(angle) + m_Position; Vector2D rightf = (rightN * m_Scale * 2).GetRotated(angle) + m_Position; Vector2D forward = (forwardN * m_Scale * 2).GetRotated(angle) + m_Position; DrawLineThinkT(m_Position.x, m_Position.y, leftf.x, leftf.y, m_Scale / 8, m_Scale / 32, color, camera); DrawLineThinkT(m_Position.x, m_Position.y, rightf.x, rightf.y, m_Scale / 8, m_Scale / 32, color, camera); DrawLineThinkT(m_Position.x, m_Position.y, forward.x, forward.y, m_Scale / 8, m_Scale / 32, color, camera); } } void Mouth::ConsumeFood(Meat* pMeat, World* pWorld) { m_ConsumeCooldown = clock() + CONSUME_COOLDOWN; pWorld->Remove(pMeat); } void Mouth::ConsumeFood(Plant* pPlant, World* pWorld) { m_ConsumeCooldown = clock() + CONSUME_COOLDOWN; pWorld->Remove(pPlant); } void Mouth::ConsumeFood(CellCreature* pCCreature, World* pWorld) { m_ConsumeCooldown = clock() + CONSUME_COOLDOWN; } PhysObj* Mouth::CanConsumeFood(CellCreature* pCellCreature, const std::vector<Meat*>& meats, const std::vector<CellCreature*>& cellCreaturs) { if (m_ConsumeCooldown > clock()) return NULL; float distM = -1; PhysObj* pFood = NULL; // Finding Closest Meat for (Meat* pM : meats) { float dist = pM->GetPosition().Distance(m_Position); if (dist >= 0 && (distM == -1 || distM > dist)) { distM = dist; pFood = pM; } } // Finding Closest Cell Creature for (CellCreature* pC : cellCreaturs) { if (pC == pCellCreature) continue; float dist = pC->GetPosition().Distance(m_Position); if (dist >= 0 && (distM == -1 || distM > dist)) { distM = dist; pFood = pC; } } if (pFood->GetPosition().Distance(m_Position) > (pFood->GetRadius() + m_Scale)) return NULL; return pFood; } PhysObj* Mouth::CanConsumeFood(const std::vector<Plant*>& plants) { if (m_ConsumeCooldown > clock()) return NULL; float distP = -1; PhysObj* pFood = NULL; // Finding Closest Plant for (Plant* pP : plants) { float dist = pP->GetPosition().Distance(m_Position); if (dist >= 0 && (distP == -1 || distP > dist)) { distP = dist; pFood = pP; } } if (!pFood) return NULL; if (pFood->GetPosition().Distance(m_Position) > (pFood->GetRadius() / 2.0f + m_Scale)) return NULL; return pFood; } void Mouth::GetMouthData(const std::vector<Plant*>& plants, const std::vector<Meat*>& meats, const std::vector<CellCreature*>& cellCreaturs , CellCreature* pCellIgnore, float angle, float viewRadius, int& side) { switch (m_ConsumeType) { case FT_Meat: GetClosestMeat(meats, cellCreaturs, pCellIgnore, angle, viewRadius, side); break; case FT_Plant: GetClosestPlant(plants, angle, viewRadius, side); break; default: break; } } bool Mouth::GetClosestMeat(const std::vector<Meat*>& meats, const std::vector<CellCreature*>& cellcreatures, CellCreature* pCellIgnore, float angle, float viewRadius, int& side) { float distM = -1; PhysObj* pMeat = NULL; for (Meat* pM : meats) { // Plant float dist = pM->GetPosition().Distance(m_Position); if (dist >= 0 && (distM == -1 || distM > dist)) { distM = dist; pMeat = pM; } } for (CellCreature* pC : cellcreatures) { if (pC == pCellIgnore) continue; // Plant float dist = pC->GetPosition().Distance(m_Position); if (dist >= 0 && (distM == -1 || distM > dist)) { distM = dist; pMeat = pC; } } if (!pMeat) return false; Vector2D offset = m_Offset.GetNormalize(); Vector2D dirF = offset.GetRotated(angle); Vector2D dir = (pMeat->GetPosition() - m_Position); float ang1 = atan2(dirF.y, dirF.x); float ang = ang1 - atan2(dir.y, dir.x); if (distM < viewRadius && ang > -M_PI * 0.5f && ang < M_PI * 0.5f) { if (ang > 0) { DrawLineThink(m_Position.x, m_Position.y, m_Position.x + dir.x, m_Position.y + dir.y, 1, RGBColor(0, 0, 255), g_Camera); side = 1; } else { DrawLineThink(m_Position.x, m_Position.y, m_Position.x + dir.x, m_Position.y + dir.y, 1, RGBColor(255, 0, 0), g_Camera); side = -1; } } return true; } bool Mouth::GetClosestPlant(const std::vector<Plant*>& plants, float angle, float viewRadius, int& side) { float distP = -1; Plant* pPlant = NULL; for (Plant* pP : plants) { // Plant float dist = pP->GetPosition().Distance(m_Position); if (dist >= 0 && (distP == -1 || distP > dist)) { distP = dist; pPlant = pP; } } if (!pPlant) return false; Vector2D offset = m_Offset.GetNormalize(); Vector2D dirF = offset.GetRotated(angle); Vector2D dir = (pPlant->GetPosition() - m_Position); float ang1 = atan2(dirF.y, dirF.x); float ang = ang1 - atan2(dir.y, dir.x); if (distP < viewRadius && ang > -M_PI * 0.5f && ang < M_PI * 0.5f) { if (ang > 0) { DrawLineThink(m_Position.x, m_Position.y, m_Position.x + dir.x, m_Position.y + dir.y, 1, RGBColor(0, 0, 255), g_Camera); side = 1; } else { DrawLineThink(m_Position.x, m_Position.y, m_Position.x + dir.x, m_Position.y + dir.y, 1, RGBColor(255, 0, 0), g_Camera); side = -1; } } return true; }
25.496094
177
0.656504
[ "vector" ]
5f755fafd56ac07a661208b400cafb91c7eacf1d
15,313
cpp
C++
Source/DX11/Objects/DX11GameObject.cpp
AlexScapillati/RenderingEngine
a0315ca054db555b56ca4ff84bc2ae42d16440c6
[ "MIT" ]
1
2022-03-11T18:12:09.000Z
2022-03-11T18:12:09.000Z
Source/DX11/Objects/DX11GameObject.cpp
AlexScapillati/RenderingEngine
a0315ca054db555b56ca4ff84bc2ae42d16440c6
[ "MIT" ]
null
null
null
Source/DX11/Objects/DX11GameObject.cpp
AlexScapillati/RenderingEngine
a0315ca054db555b56ca4ff84bc2ae42d16440c6
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------------------- // Class encapsulating a model //-------------------------------------------------------------------------------------- // Holds a pointer to a mesh as well as position, rotation and scaling, which are converted to a world matrix when required // This is more of a convenience class, the Mesh class does most of the difficult work. #include "DX11GameObject.h" #include "../DX11Engine.h" #include "../DX11Scene.h" #include "../GraphicsHelpers.h" #include "../../Utility/HelperFunctions.h" #include "../../Common/CGameObjectManager.h" namespace DX11 { //copy constructor CDX11GameObject::CDX11GameObject(CDX11GameObject& obj) { mEngine = obj.mEngine; //initialize ambient map variables mAmbientMap.size = obj.AmbientMap()->size; mAmbientMap.enabled = obj.AmbientMap()->enabled; mAmbientMap.Init(mEngine); } CDX11GameObject::CDX11GameObject(CDX11Engine* engine, const std::string& mesh, const std::string& name, const std::string& diffuseMap, CVector3 position, CVector3 rotation , float scale) { mEngine = engine; mAmbientMap.enabled = false; mAmbientMap.size = 4; mAmbientMap.Init(mEngine); mParallaxDepth = 0.f; mRoughness = 0.5f; mMetalness = 0.0f; mEnabled = true; if (mesh.empty()) throw std::exception("Error Loading Object"); mName = name; // Import material try { std::vector maps = { diffuseMap }; mMaterial = std::make_unique<CDX11Material>(maps, mEngine); } catch (const std::exception& e) { throw std::runtime_error(e.what()); } //default model //not PBR //that could be light models or cube maps try { mMesh = std::make_unique<CDX11Mesh>(mEngine, mesh, mMaterial->HasNormals()); mMeshFiles.push_back(mesh); // Set default matrices from mesh mWorldMatrices.resize(mMesh->NumberNodes()); for (auto i = 0; i < mWorldMatrices.size(); ++i) mWorldMatrices[i] = mMesh->GetNodeDefaultMatrix(i); } catch (const std::exception& e) { throw std::runtime_error(e.what()); } //geometry loaded, set its position... SetPosition(position); CGameObject::SetRotation(rotation); SetScale(scale); } CDX11GameObject::CDX11GameObject(CDX11Engine* engine, const std::string& dirPath, std::string name, CVector3 position /*= { 0,0,0 }*/, CVector3 rotation /*= { 0,0,0 }*/, float scale /*= 1*/): CGameObject() { mEngine = engine; //initialize member variables mName = std::move(name); //initialize ambient map variables mAmbientMap.size = 4; mAmbientMap.enabled = false; mAmbientMap.Init(mEngine); mEnabled = true; mParallaxDepth = 0.f; mRoughness = 0.5f; mMetalness = 0.0f; //search for files with the same id std::vector<std::string> files; std::string id = dirPath; auto folder = engine->GetMediaFolder() + dirPath; // If the id has a dot, this means it has an extention, so we are dealing with a file if (id.find_last_of('.') == std::string::npos) { // Get every file in that folder // If the id did not have a dot means that we are dealing with a folder GetFilesInFolder(mEngine, folder, files); } else { // Get the position of the last underscore auto nPos = id.find_last_of('_'); //Get folder auto slashPos = id.find_last_of('/'); if (slashPos != std::string::npos) { // Get the id auto subFolder = id.substr(0, slashPos); folder = engine->GetMediaFolder() + subFolder + '/'; //get every file that is beginning with that id GetFilesInFolder(mEngine, folder, files); } else { // Get the ID id = id.substr(0, id.find_first_of('_')); GetFilesWithID(engine->GetMediaFolder(), files, id); } } //create the material mMaterial = std::make_unique<CDX11Material>(files, mEngine); //find meshes trough the files for (auto st : files) { //set the meshes in the vector if (st.find(".fbx") != std::string::npos) { mMeshFiles.push_back(st); } else if (st.find(".x") != std::string::npos) { mMeshFiles.push_back(st); } } if (mMeshFiles.empty()) { throw std::runtime_error("No mesh found in " + name); } // If the meshes vector has more than one fileName if (mMeshFiles.size() > 1) { // Extract the lods and variations int counter = 0; int nVariations = 0; std::vector<std::string> vec; for (auto mesh : mMeshFiles) { // Prepare file to find // It changes depending on the counter std::string currFind = "LOD"; currFind += (counter + '0'); // If found if (mesh.find(currFind) != std::string::npos) { // Push it in the variations vector vec.push_back(mesh); } else { // If not found we finished the variations for this LOD // So push the variations vector in the LODs vector and clear the variations vector mLODs.push_back(move(vec)); // Push the current variation iin the variation vec vec.push_back(mesh); // Increment the LOD counter counter++; } } } else { // If the meshes vector has only one fileName // Push it on the lod mLODs.push_back(mMeshFiles); } try { //load the most detailed mesh with tangents required if the model has normals mMesh = std::make_unique<CDX11Mesh>(mEngine, mMeshFiles.front(), mMaterial->HasNormals()); // Set default matrices from mesh mWorldMatrices.resize(mMesh->NumberNodes()); for (auto i = 0; i < mWorldMatrices.size(); ++i) mWorldMatrices[i] = mMesh->GetNodeDefaultMatrix(i); } catch (std::exception& e) { throw std::runtime_error(e.what()); } // geometry loaded, set its position... SetPosition(position); SetRotation(rotation); SetScale(scale); } // The render function simply passes this model's matrices over to Mesh:Render. // All other per-frame constants must have been set already along with shaders, textures, samplers, states etc. void CDX11GameObject::Render(bool basicGeometry) { //if the model is not enable do not render it if (!mEnabled) return; // Set the parallax depth to the constant buffer gPerModelConstants.parallaxDepth = mParallaxDepth; // Set the material roughness to the constant buffer gPerModelConstants.roughness = mRoughness; gPerModelConstants.metalness = mMetalness; if (!basicGeometry) { if (mAmbientMap.enabled) { mEngine->GetContext()->PSSetShaderResources(6, 1, mAmbientMap.mapSRV.GetAddressOf()); } /*else if (dynamic_cast<CSky*>(GOM->GetSky())->HasCubeMap()); { auto environmentMap = GOM->GetSky()->TextureSRV(); gD3DContext->PSSetShaderResources(6, 1, &environmentMap); }*/ } // Render the material mMaterial->RenderMaterial(basicGeometry); // Render the mesh mMesh->Render(mWorldMatrices); // Unbind the ambient map from the shader ID3D11ShaderResourceView* nullView = nullptr; mEngine->GetContext()->PSSetShaderResources(6, 1, &nullView); } void CDX11GameObject::RenderToAmbientMap() { // if the ambient map is disabled, nothing to do here if (!mAmbientMap.enabled) return; // Store current RS state ID3D11RasterizerState* prevRS = nullptr; mEngine->GetContext()->RSGetState(&prevRS); // Set the cullback state mEngine->GetContext()->RSSetState(mEngine->mCullBackState.Get()); // Store current RTV(render target) and DSV(depth stencil) ID3D11RenderTargetView* prevRTV = nullptr; ID3D11DepthStencilView* prevDSV = nullptr; mEngine->GetContext()->OMGetRenderTargets(1, &prevRTV, &prevDSV); //create the viewport D3D11_VIEWPORT vp; vp.Width = static_cast<FLOAT>(mAmbientMap.size); vp.Height = static_cast<FLOAT>(mAmbientMap.size); vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = 0; vp.TopLeftY = 0; mEngine->GetContext()->RSSetViewports(1, &vp); float mSides[6][3] = { // Starting from facing down the +ve Z direction, left handed rotations {0.0f, 0.5f, 0.0f}, // +ve X direction (values multiplied by PI) {0.0f, -0.5f, 0.0f}, // -ve X direction {-0.5f, 0.0f, 0.0f}, // +ve Y direction {0.5f, 0.0f, 0.0f}, // -ve Y direction {0.0f, 0.0f, 0.0f}, // +ve Z direction {0.0f, 1.0f, 0.0f} // -ve Z direction }; const auto& originalRotation = Rotation(); // for all six faces of the cubemap for (int i = 0; i < 6; ++i) { // change rotation SetRotation(CVector3(mSides[i]) * PI); mEngine->GetContext()->ClearDepthStencilView(mAmbientMap.depthStencilView.Get(), D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); mEngine->GetContext()->OMSetRenderTargets(1, mAmbientMap.RTV[i].GetAddressOf(), mAmbientMap.depthStencilView.Get()); // Update Frame buffer gPerFrameConstants.viewMatrix = InverseAffine(WorldMatrix()); gPerFrameConstants.projectionMatrix = MakeProjectionMatrix(1.0f, ToRadians(90.0f)); gPerFrameConstants.viewProjectionMatrix = gPerFrameConstants.viewMatrix * gPerFrameConstants.projectionMatrix; // Update Constant buffer mEngine->UpdateFrameConstantBuffer(gPerFrameConstantBuffer.Get(), gPerFrameConstants); // Set it to the GPU mEngine->GetContext()->PSSetConstantBuffers(1, 1, gPerFrameConstantBuffer.GetAddressOf()); mEngine->GetContext()->VSSetConstantBuffers(1, 1, gPerFrameConstantBuffer.GetAddressOf()); mEngine->GetObjManager()->mSky->Render(); //render just the objects that can cast shadows for (const auto& it : mEngine->GetObjManager()->mObjects) { // Do not render this object if (it != this) // Render all the objects // Performance improvements: Could render only the closest objects // Could render only the face that the user is looking at (kinda like cull back state) it->Render(); } } //restore render target, otherwise the ambient map will not be sent to the shader because it is still bound as a render target mEngine->GetContext()->OMSetRenderTargets(1, &prevRTV, prevDSV); if (prevRTV) prevRTV->Release(); if (prevDSV) prevDSV->Release(); // Restore previous RS state mEngine->GetContext()->RSSetState(prevRS); // Release that if (prevRS) prevRS->Release(); //restore original rotation SetRotation(originalRotation); //generate mipMaps for the cube map mEngine->GetContext()->GenerateMips(mAmbientMap.mapSRV.Get()); } void CDX11GameObject::sAmbientMap::Init(CDX11Engine* engine) { mEngine = engine; //http://richardssoftware.net/Home/Post/26 //initialize the texture map cube D3D11_TEXTURE2D_DESC textureDesc = {}; textureDesc.Width = size; textureDesc.Height = size; textureDesc.MipLevels = 0; textureDesc.ArraySize = 6; //6 faces textureDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; textureDesc.SampleDesc.Count = 1; textureDesc.SampleDesc.Quality = 0; textureDesc.Usage = D3D11_USAGE_DEFAULT; textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; //use it to passit to the shader and use it as a render target textureDesc.CPUAccessFlags = 0; textureDesc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS | D3D11_RESOURCE_MISC_TEXTURECUBE; //create it auto hr = mEngine->GetDevice()->CreateTexture2D(&textureDesc, nullptr, map.GetAddressOf()); if (FAILED(hr)) { throw std::runtime_error("Error creating cube texture"); } //create render target views D3D11_RENDER_TARGET_VIEW_DESC viewDesc = {}; viewDesc.Format = textureDesc.Format; viewDesc.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2DARRAY; viewDesc.Texture2DArray.FirstArraySlice = 0; viewDesc.Texture2DArray.ArraySize = 1; viewDesc.Texture2DArray.MipSlice = 0; //create 6 of them for (int i = 0; i < 6; ++i) { viewDesc.Texture2DArray.FirstArraySlice = i; hr = mEngine->GetDevice()->CreateRenderTargetView(map.Get(), &viewDesc, RTV[i].GetAddressOf()); if (FAILED(hr)) { throw std::runtime_error("Error creating render target view"); } } D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc = {}; srvDesc.Format = textureDesc.Format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; srvDesc.TextureCube.MostDetailedMip = 0; srvDesc.TextureCube.MipLevels = -1; hr = mEngine->GetDevice()->CreateShaderResourceView(map.Get(), &srvDesc, mapSRV.GetAddressOf()); if (FAILED(hr)) { throw std::runtime_error("Error creating cube map SRV"); } //now can release the texture map->Release(); //create depth stencil D3D11_TEXTURE2D_DESC dsDesc = {}; dsDesc.Width = size; dsDesc.Height = size; dsDesc.MipLevels = 1; dsDesc.ArraySize = 1; dsDesc.Format = DXGI_FORMAT_R32_TYPELESS; dsDesc.SampleDesc.Count = 1; dsDesc.SampleDesc.Quality = 0; dsDesc.Usage = D3D11_USAGE_DEFAULT; dsDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL; dsDesc.CPUAccessFlags = 0; dsDesc.MiscFlags = 0; //create it if (FAILED(mEngine->GetDevice()->CreateTexture2D(&dsDesc, NULL, depthStencilMap.GetAddressOf()))) { throw std::runtime_error("Error creating depth stencil"); } //create depth stencil view D3D11_DEPTH_STENCIL_VIEW_DESC dsvDesc = {}; dsvDesc.Format = DXGI_FORMAT_D32_FLOAT; dsvDesc.Flags = 0; dsvDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; dsvDesc.Texture2D.MipSlice = 0; if (FAILED(mEngine->GetDevice()->CreateDepthStencilView(depthStencilMap.Get(), &dsvDesc, depthStencilView.GetAddressOf()))) { throw std::runtime_error("Error creating depth stencil view "); } //release the depth stencil texture since we are done with it depthStencilMap->Release(); } void CDX11GameObject::LoadNewMesh(std::string newMesh) { try { mMesh = std::make_unique<CDX11Mesh>(mEngine, newMesh, mMaterial->HasNormals()); auto prevPos = Position(); auto prevScale = Scale(); auto prevRotation = Rotation(); // Recalculate matrix based on mesh mWorldMatrices.resize(mMesh->NumberNodes()); for (auto i = 0; i < mWorldMatrices.size(); ++i) mWorldMatrices[i] = mMesh->GetNodeDefaultMatrix(i); SetPosition(prevPos); SetScale(prevScale); SetRotation(prevRotation); } catch (const std::exception& e) { throw std::exception(e.what()); } } ID3D11ShaderResourceView* CDX11GameObject::TextureSRV() const { return mMaterial->TextureSRV(); } CDX11GameObject::sAmbientMap* CDX11GameObject::AmbientMap() { return &mAmbientMap; } ID3D11ShaderResourceView* CDX11GameObject::AmbientMapSRV() const { return mAmbientMap.mapSRV.Get(); } UINT CDX11GameObject::sAmbientMap::Size() const { return size; } CDX11Mesh* CDX11GameObject::Mesh() const { return mMesh.get(); } CDX11Material* CDX11GameObject::Material() const { return mMaterial.get(); } bool& CDX11GameObject::AmbientMapEnabled() { return mAmbientMap.enabled; } void CDX11GameObject::sAmbientMap::SetSize(UINT s) { // Set the size size = s; // Re initialize all the maps to the new size Init(mEngine); } }
33.073434
193
0.665905
[ "mesh", "geometry", "render", "object", "vector", "model" ]
5f7b6ec24ecb523cd87f2110d7146e43471d5976
2,707
cpp
C++
Exercise7/4/main.cpp
jtrillos/LabBasicGraphicsSol
5487e568a332d8ee37ad064da0dd5ceddf35f5eb
[ "Apache-2.0" ]
2
2018-01-15T13:39:56.000Z
2018-04-25T14:27:31.000Z
Exercise7/4/main.cpp
jtrillos/LabBasicGraphicsSol
5487e568a332d8ee37ad064da0dd5ceddf35f5eb
[ "Apache-2.0" ]
null
null
null
Exercise7/4/main.cpp
jtrillos/LabBasicGraphicsSol
5487e568a332d8ee37ad064da0dd5ceddf35f5eb
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> #include <math.h> using namespace std; void print_vec(vector<double> vec){ for (int i = 0; i < vec.size(); i++) { cout << vec[i] << " "; } cout << endl; } double getMin(vector<double> vec){ double min = vec[0]; for (int i = 1; i < vec.size(); i++) { if (min > vec[i]) { min = vec[i]; } } return min; } double getMax(vector<double> vec){ double max = vec[0]; for (int i = 1; i < vec.size(); i++) { if (max < vec[i]) { max = vec[i]; } } return max; } double getMean(vector<double> vec){ double sum = 0; int size = vec.size(); for (int i = 0; i < size; i++) { sum += vec[i]; } double mean = sum / size; return mean; } double getDeviation(vector<double> vec){ double m = getMean(vec); int size = vec.size(); double temp = 0; for(int i = 0; i < size; i++) { temp += (vec[i] - m) * (vec[i] - m) ; } return sqrt(temp / size); } int smaller(vector<double> vec, int val){ int count = 0; for (int i = 0; i < vec.size(); i++) { if (val > vec[i]) { count++; } } return count; } int main() { const double data[] = { -1.37, 2.04, 4.98, 5.36, 8.88e-1, 2.47, -1.19e-1, -5.57e-1, 2.83, 5.38e-1, 4.69, 7.37, 3.78, 5.29, 6.30, 2.62, 2.60, 4.35, 5.31, 3.53, 7.64, 4.41e-1, 1.61, 4.71 }; const int dataCount = sizeof( data ) / sizeof( data[0] ); //filling the vector with the values vector<double> data_vec; for (int i = 0; i < dataCount; ++i){ data_vec.push_back(data[i]); } cout << "The vector is:" << endl; print_vec(data_vec); //erase the 2nd element double pos2 = data_vec[1]; cout << endl << "After erasing and inserting:" << endl; data_vec.erase(data_vec.begin() + 1); data_vec.insert(data_vec.begin() + 6, pos2); print_vec(data_vec); //calculations: double min = getMin(data_vec); double max = getMax(data_vec); double mean = getMean(data_vec); double dev = getDeviation(data_vec); cout << endl << "min: " << min << endl; cout << "max: " << max << endl; cout << "mean: " << mean << endl; cout << "standard deviation: " << dev << endl; int s2 = smaller(data_vec, 2); int s4 = smaller(data_vec, 4); int s6 = smaller(data_vec, 6); cout << endl << "# of smaller than 2: " << s2 << endl; cout << "# of smaller than 4: " << s4 << endl; cout << "# of smaller than 6: " << s6 << endl; return 0; }
25.064815
68
0.493535
[ "vector" ]
5f80ff5ee6c2dfb95478d6a1fa7835765c1d41e3
6,852
cc
C++
src/bin/compare-int-vector.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
116
2016-10-25T06:04:49.000Z
2022-03-13T02:30:52.000Z
src/bin/compare-int-vector.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
38
2018-04-03T14:25:35.000Z
2022-02-19T21:03:11.000Z
src/bin/compare-int-vector.cc
shuipi100/kaldi
8e30fddb300a87e7c79ef2c0b9c731a8a9fd23f0
[ "Apache-2.0" ]
52
2016-04-21T13:38:21.000Z
2022-02-16T08:33:13.000Z
// bin/compare-int-vector.cc // Copyright 2018 Johns Hopkins University (Author: Daniel Povey) // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "matrix/kaldi-vector.h" #include "transform/transform-common.h" #include <iomanip> namespace kaldi { void AddToCount(int32 location_to_add, double value_to_add, std::vector<double> *counts) { if (location_to_add < 0) KALDI_ERR << "Contents of vectors cannot be " "negative if --write-tot-counts or --write-diff-counts " "options are provided."; if (counts->size() <= static_cast<size_t>(location_to_add)) counts->resize(location_to_add + 1, 0.0); (*counts)[location_to_add] += value_to_add; } void AddToConfusionMatrix(int32 phone1, int32 phone2, Matrix<double> *counts) { if (phone1 < 0 || phone2 < 0) KALDI_ERR << "Contents of vectors cannot be " "negative if --write-confusion-matrix option is " "provided."; int32 max_size = std::max<int32>(phone1, phone2) + 1; if (counts->NumRows() < max_size) counts->Resize(max_size, max_size, kCopyData); (*counts)(phone1, phone2) += 1.0; } void WriteAsKaldiVector(const std::vector<double> &counts, std::string &wxfilename, bool binary) { Vector<BaseFloat> counts_vec(counts.size()); for (size_t i = 0; i < counts.size(); i++) counts_vec(i) = counts[i]; WriteKaldiObject(counts_vec, wxfilename, binary); } } // namespace kaldi int main(int argc, char *argv[]) { try { using namespace kaldi; const char *usage = "Compare vectors of integers (e.g. phone alignments)\n" "Prints to stdout fields of the form:\n" "<utterance-id> <num-frames-in-utterance> <num-frames-that-differ>\n" "\n" "e.g.:\n" " SWB1_A_31410_32892 420 36\n" "\n" "Usage:\n" "compare-int-vector [options] <vector1-rspecifier> <vector2-rspecifier>\n" "\n" "e.g. compare-int-vector scp:foo.scp scp:bar.scp > comparison\n" "E.g. the inputs might come from ali-to-phones.\n" "Warnings are printed if the vector lengths differ for a given utterance-id,\n" "and in those cases, the number of frames printed will be the smaller of the\n" "\n" "See also: ali-to-phones, copy-int-vector\n"; ParseOptions po(usage); std::string tot_wxfilename, diff_wxfilename, confusion_matrix_wxfilename; bool binary = true; po.Register("binary", &binary, "If true, write in binary mode (only applies " "if --write-tot-counts or --write-diff-counts options are supplied)."); po.Register("write-tot-counts", &tot_wxfilename, "Filename to write " "vector of total counts. These may be summed with 'vector-sum'."); po.Register("write-diff-counts", &diff_wxfilename, "Filename to write " "vector of counts of phones (or whatever is in the inputs) " "that differ from one vector to the other. Each time a pair differs, " "0.5 will be added to each one's location."); po.Register("write-confusion-matrix", &confusion_matrix_wxfilename, "Filename to write confusion matrix, indexed by [phone1][phone2]." "These may be summed by 'matrix-sum'."); po.Read(argc, argv); if (po.NumArgs() != 2) { po.PrintUsage(); exit(1); } std::string vector1_rspecifier = po.GetArg(1), vector2_rspecifier = po.GetArg(2); int64 num_done = 0, num_not_found = 0, num_mismatched_lengths = 0, tot_frames = 0, tot_difference = 0; std::vector<double> diff_counts; std::vector<double> tot_counts; Matrix<double> confusion_matrix; SequentialInt32VectorReader reader1(vector1_rspecifier); RandomAccessInt32VectorReader reader2(vector2_rspecifier); for (; !reader1.Done(); reader1.Next(), num_done++) { const std::string &key = reader1.Key(); if (!reader2.HasKey(key)) { KALDI_WARN << "No key " << key << " found in second input."; num_not_found++; continue; } const std::vector<int32> &value1 = reader1.Value(), &value2 = reader2.Value(key); size_t len1 = value1.size(), len2 = value2.size(); if (len1 != len2) { KALDI_WARN << "For utterance " << key << ", lengths differ " << len1 << " vs. " << len2; num_mismatched_lengths++; } size_t len = std::min(len1, len2), difference = 0; for (size_t i = 0; i < len; i++) { int32 phone1 = value1[i], phone2 = value2[i]; if (phone1 != phone2) { difference++; if (!diff_wxfilename.empty()) { AddToCount(phone1, 0.5, &diff_counts); AddToCount(phone2, 0.5, &diff_counts); } } if (!tot_wxfilename.empty()) AddToCount(phone1, 1.0, &tot_counts); if (!confusion_matrix_wxfilename.empty()) AddToConfusionMatrix(phone1, phone2, &confusion_matrix); } num_done++; std::cout << key << " " << len << " " << difference << "\n"; tot_frames += len; tot_difference += difference; } BaseFloat difference_percent = tot_difference * 100.0 / tot_frames; KALDI_LOG << "Computed difference for " << num_done << " utterances, of which " << num_mismatched_lengths << " had mismatched lengths; corresponding " "utterance not found for " << num_not_found; KALDI_LOG << "Average p(different) is " << std::setprecision(4) << difference_percent << "%, over " << tot_frames << " frames."; if (!tot_wxfilename.empty()) WriteAsKaldiVector(tot_counts, tot_wxfilename, binary); if (!diff_wxfilename.empty()) WriteAsKaldiVector(diff_counts, diff_wxfilename, binary); if (!confusion_matrix_wxfilename.empty()) WriteKaldiObject(confusion_matrix, confusion_matrix_wxfilename, binary); return (num_done != 0 ? 0 : 1); } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
37.037838
89
0.624051
[ "vector", "transform" ]
5f92477dca87eac37d266428e7a32d0849829189
9,074
cpp
C++
src/metadata/async-io-metadata2.cpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
13
2017-01-07T07:48:54.000Z
2021-09-29T05:33:38.000Z
src/metadata/async-io-metadata2.cpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
27
2016-11-24T11:35:22.000Z
2022-02-14T14:38:09.000Z
src/metadata/async-io-metadata2.cpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
3
2017-10-19T10:12:11.000Z
2019-10-11T16:21:09.000Z
#include "metadata2.hpp" namespace flac_bindings { using namespace Napi; using namespace std::placeholders; AsyncFlacIOWork::AsyncFlacIOWork( std::function<bool(FLAC__IOHandle, FLAC__IOCallbacks)> f, const char* name, const Object& obj, std::function<void(const Napi::Env&, bool)> checkStatus): AsyncBackgroundTask<bool, FlacIOWorkRequest>( obj.Env(), [this, f](auto c) { this->ptr1 = std::make_tuple(&this->cbk1, &c); auto ret = f(&this->ptr1, this->cbk1.generateIOCallbacks()); c.resolve(ret); }, std::bind(&AsyncFlacIOWork::doAsyncWork, this, _1, _2, _3), name, [checkStatus](auto env, auto value) { checkStatus(env, value); return env.Undefined(); }), cbk1(obj), cbk2() {} AsyncFlacIOWork::AsyncFlacIOWork( std::function<bool(FLAC__IOHandle, FLAC__IOCallbacks, FLAC__IOHandle, FLAC__IOCallbacks)> f, const char* name, const Object& obj1, const Object& obj2, std::function<void(const Napi::Env&, bool)> checkStatus): AsyncBackgroundTask<bool, FlacIOWorkRequest>( obj1.Env(), [this, f](auto c) { this->ptr1 = std::make_tuple(&this->cbk1, &c); this->ptr2 = std::make_tuple(&this->cbk2, &c); auto ret = f(&this->ptr1, this->cbk1.generateIOCallbacks(), &this->ptr2, this->cbk2.generateIOCallbacks()); c.resolve(ret); }, std::bind(&AsyncFlacIOWork::doAsyncWork, this, _1, _2, _3), name, [checkStatus](auto env, auto value) { checkStatus(env, value); return env.Undefined(); }), cbk1(obj1), cbk2(obj2) {} template<typename Type> static std::function<void(const Napi::Value& result)> generateProcessResult(const std::function<void(Type)>& setter) { return [setter](auto result) { auto returnValue = maybeNumberFromJs<Type>(result).value_or(booleanFromJs<Type>(result)); setter(returnValue); }; } void AsyncFlacIOWork::doAsyncWork( const Napi::Env& env, AsyncFlacIOWork::ExecutionProgress& prog, const std::shared_ptr<FlacIOWorkRequest>& work) { auto async = nullptr; Napi::Value result = env.Null(); std::function<void(const Napi::Value& result)> processResult; auto io = (AsyncFlacIOWork::IOCallbacks*) work->cbks; switch (work->type) { case FlacIOWorkRequest::Read: { sharedBufferRef.setFromWrap(env, (uint8_t*) work->ptr, *work->bytes); result = io->readCallback.MakeCallback( env.Global(), { sharedBufferRef.value(), numberToJs(env, work->sizeOfItem), numberToJs(env, work->nitems), }, async); processResult = generateProcessResult<size_t>([work](auto v) { *work->bytes = v; }); break; } case FlacIOWorkRequest::Write: { sharedBufferRef.setFromWrap(env, (uint8_t*) work->ptr, *work->bytes); result = io->writeCallback.MakeCallback( env.Global(), { sharedBufferRef.value(), numberToJs(env, work->sizeOfItem), numberToJs(env, work->nitems), }, async); processResult = generateProcessResult<size_t>([work](auto v) { *work->bytes = v; }); break; } case FlacIOWorkRequest::Seek: { String direction; switch (*work->genericReturn) { case SEEK_SET: direction = String::New(env, "set"); break; case SEEK_CUR: direction = String::New(env, "cur"); break; case SEEK_END: direction = String::New(env, "end"); break; default: direction = String::New(env, "set"); } result = io->seekCallback.MakeCallback( env.Global(), { numberToJs(env, *work->offset), direction, }, async); processResult = generateProcessResult<int>([work](auto v) { *work->genericReturn = v; }); break; } case FlacIOWorkRequest::Tell: { result = io->tellCallback.MakeCallback(env.Global(), {}, async); processResult = generateProcessResult<int64_t>([work](auto v) { *work->offset = v; }); break; } case FlacIOWorkRequest::Eof: { result = io->eofCallback.MakeCallback(env.Global(), {}, async); processResult = generateProcessResult<bool>([work](auto v) { *work->genericReturn = v; }); break; } case FlacIOWorkRequest::Close: { result = io->closeCallback.MakeCallback(env.Global(), {}, async); processResult = generateProcessResult<int>([work](auto v) { *work->genericReturn = v; }); break; } } if (result.IsPromise()) { prog.defer(result.As<Promise>(), [processResult](auto&, auto& info, auto) { if (processResult) { processResult(info[0]); } }); } else { if (processResult) { processResult(result); } } } AsyncFlacIOWork::IOCallbacks::IOCallbacks() {} AsyncFlacIOWork::IOCallbacks::IOCallbacks(const Object& obj) { maybeFunctionIntoRef(this->readCallback, obj["read"]); maybeFunctionIntoRef(this->writeCallback, obj["write"]); maybeFunctionIntoRef(this->seekCallback, obj["seek"]); maybeFunctionIntoRef(this->tellCallback, obj["tell"]); maybeFunctionIntoRef(this->eofCallback, obj["eof"]); maybeFunctionIntoRef(this->closeCallback, obj["close"]); } AsyncFlacIOWork::IOCallbacks::~IOCallbacks() { if (!readCallback.IsEmpty()) readCallback.Unref(); if (!writeCallback.IsEmpty()) writeCallback.Unref(); if (!seekCallback.IsEmpty()) seekCallback.Unref(); if (!tellCallback.IsEmpty()) tellCallback.Unref(); if (!eofCallback.IsEmpty()) eofCallback.Unref(); if (!closeCallback.IsEmpty()) closeCallback.Unref(); } typedef std::tuple<void*, AsyncFlacIOWork::ExecutionProgress*> FlacIOArg; static size_t flacIORead(void* ptr, size_t size, size_t numberOfMembers, void* c) { FlacIOArg& ctx = *(FlacIOArg*) c; auto* ec = std::get<1>(ctx); auto req = std::make_shared<FlacIOWorkRequest>(FlacIOWorkRequest::Read); size_t bytes = size * numberOfMembers; req->cbks = std::get<0>(ctx); req->ptr = ptr; req->bytes = &bytes; req->nitems = numberOfMembers; req->sizeOfItem = size; ec->sendProgressAndWait(req); return bytes / size; } static size_t flacIOWrite(const void* ptr, size_t size, size_t numberOfMembers, void* c) { FlacIOArg& ctx = *(FlacIOArg*) c; auto* ec = std::get<1>(ctx); auto req = std::make_shared<FlacIOWorkRequest>(FlacIOWorkRequest::Write); size_t bytes = size * numberOfMembers; if (size * numberOfMembers == 0) { // Sometimes, the callback is called with 0 bytes to write // Discard the call completely :) return 0; } req->cbks = std::get<0>(ctx); req->ptr = (void*) ptr; req->bytes = &bytes; req->nitems = numberOfMembers; req->sizeOfItem = size; ec->sendProgressAndWait(req); return bytes / size; } static int flacIOSeek(void* c, int64_t offset, int whence) { FlacIOArg& ctx = *(FlacIOArg*) c; auto* ec = std::get<1>(ctx); auto req = std::make_shared<FlacIOWorkRequest>(FlacIOWorkRequest::Seek); int ret = whence; req->cbks = std::get<0>(ctx); req->offset = &offset; req->genericReturn = &ret; ec->sendProgressAndWait(req); return ret; } static int64_t flacIOTell(void* c) { FlacIOArg& ctx = *(FlacIOArg*) c; auto* ec = std::get<1>(ctx); auto req = std::make_shared<FlacIOWorkRequest>(FlacIOWorkRequest::Tell); int64_t offset = -1; req->cbks = std::get<0>(ctx); req->offset = &offset; ec->sendProgressAndWait(req); return offset; } static int flacIOEof(void* c) { FlacIOArg& ctx = *(FlacIOArg*) c; auto* ec = std::get<1>(ctx); auto req = std::make_shared<FlacIOWorkRequest>(FlacIOWorkRequest::Eof); int ret = 0; req->cbks = std::get<0>(ctx); req->genericReturn = &ret; ec->sendProgressAndWait(req); return ret; } static int flacIOClose(void* c) { FlacIOArg& ctx = *(FlacIOArg*) c; auto* ec = std::get<1>(ctx); auto req = std::make_shared<FlacIOWorkRequest>(FlacIOWorkRequest::Close); int ret = 0; req->cbks = std::get<0>(ctx); req->genericReturn = &ret; ec->sendProgressAndWait(req); return ret; } FLAC__IOCallbacks AsyncFlacIOWork::IOCallbacks::generateIOCallbacks() { return { !readCallback.IsEmpty() ? flacIORead : nullptr, !writeCallback.IsEmpty() ? flacIOWrite : nullptr, !seekCallback.IsEmpty() ? flacIOSeek : nullptr, !tellCallback.IsEmpty() ? flacIOTell : nullptr, !eofCallback.IsEmpty() ? flacIOEof : nullptr, !closeCallback.IsEmpty() ? flacIOClose : nullptr, }; } }
30.655405
98
0.603593
[ "object" ]
5faa5d37d500a41c6bba63fc7264afcfd08acea2
10,851
cpp
C++
ultra96/ROOT_FS/app/fad/src/fad/StateEstimator/ParticleFilter/ParticleFilter.cpp
rits-drsl/ZybotR2-96-fpt19
bed374a70fc6bad637770532244b20002f8e8a28
[ "MIT" ]
14
2019-12-25T10:17:11.000Z
2022-01-18T09:35:05.000Z
ultra96/ROOT_FS/app/fad/src/fad/StateEstimator/ParticleFilter/ParticleFilter.cpp
rits-drsl/ZybotR2-96-fpt19
bed374a70fc6bad637770532244b20002f8e8a28
[ "MIT" ]
null
null
null
ultra96/ROOT_FS/app/fad/src/fad/StateEstimator/ParticleFilter/ParticleFilter.cpp
rits-drsl/ZybotR2-96-fpt19
bed374a70fc6bad637770532244b20002f8e8a28
[ "MIT" ]
2
2020-02-02T03:12:37.000Z
2020-09-02T00:25:21.000Z
/** * ParticleFilter: パーティクルフィルタを用いて * 現状態を推定するクラス * * Copyright (C) 2019 Yuya Kudo. * Copyright (C) 2019 Atsushi Takada. * Authors: * Yuya Kudo <ri0049ee@ed.ritsumei.ac.jp> * Atsushi Takada <ri0051rr@ed.ritsumei.ac.jp> * */ #include "ParticleFilter.h" namespace fad { ParticleFilter::ParticleFilter() : rand_(std::mt19937(std::random_device()())) { if(std::getenv("FAD_ROOT") == nullptr) { throw std::logic_error("[" + std::string(__PRETTY_FUNCTION__) + "] " + "Please set environment value : $ export FAD_ROOT=<path of project root> "); } const auto root_path = std::getenv("FAD_ROOT"); // パーティクルフィルタのパラメータを読み込む core::YAMLHelper::readStruct(root_path + PARTICLE_FILTER_PARAM_YAML_PATH, pf_param_, "param"); init_weight_ = 1.0/ pf_param_.max_num_particle; reset_thr_ = pf_param_.max_num_particle * pf_param_.reset_ratio_thr; if(!(0.0 <= pf_param_.reset_ratio_thr && pf_param_.reset_ratio_thr <= 1.0)){ throw std::invalid_argument("invalid reset_ratio_thr"); } if(!(0.0 <= pf_param_.vo_ratio_when_calc_disparity && pf_param_.vo_ratio_when_calc_disparity <= 1.0)){ throw std::invalid_argument("invalid vo_ratio_when_calc_disparity"); } dist_uni_real_position_ = std::uniform_real_distribution<double>(-pf_param_.reset_position_sigma, pf_param_.reset_position_sigma); dist_uni_real_theta_ = std::uniform_real_distribution<double>(-pf_param_.reset_theta_sigma, pf_param_.reset_theta_sigma); } ParticleFilter::~ParticleFilter() { } void ParticleFilter::init(const core::VehicleState& init_state) { state_ = init_state; particles_ = std::vector<core::ParticleState>(pf_param_.max_num_particle, core::ParticleState(init_state.x, init_state.y, init_state.t, init_state.v, init_weight_)); } void ParticleFilter::estimate(const core::WheelOdometry& wo, const core::VisualOdometry& vo, const core::InertialOdometry& io, const double& wo_ps_sigma, const double& wo_t_sigma) { updateParticles(wo, vo, io, wo_ps_sigma, wo_t_sigma); // 全粒子の加重平均により次状態の代表を決定する // NOTE: Thetaの加重平均を取る際は境界を考慮する必要があります struct WeightedTheta { core::Theta t; double w; WeightedTheta(const core::Theta& _t, const double& _w) : t(_t), w(_w) { } }; std::vector<WeightedTheta> wt_v; auto x_sum = 0.0; auto y_sum = 0.0; for(size_t i = 1; i < particles_.size(); i++){ x_sum += particles_[i].x * particles_[i].w; y_sum += particles_[i].y * particles_[i].w; wt_v.emplace_back(particles_[i].t, particles_[i].w); } const auto calc_wt_ave = [&](const WeightedTheta& a, const WeightedTheta& b) -> core::Theta { if(std::abs(a.t.get() - b.t.get()) <= core::PI) { return core::Theta((a.t.get() * a.w + b.t.get() * b.w) / (a.w + b.w)); } else { const auto pi = core::Theta(core::PI); return core::Theta(((a.t + pi).get() * a.w + (b.t + pi).get() * b.w) / (a.w + b.w)) - pi; } }; const auto calc_all_wt_ave = [&](auto&& f, std::vector<WeightedTheta>& wt_v, size_t wt_v_index) -> core::Theta { if(wt_v.size() <= 1) { throw std::runtime_error("[" + std::string(__PRETTY_FUNCTION__) + "] " + "The number of particle is few"); } else if(wt_v_index == 2) { return calc_wt_ave(wt_v[0], wt_v[1]); } else { if(wt_v_index % 2 == 1) wt_v_index--; for(size_t i = 0; i < wt_v_index; i += 2) { wt_v[i / 2].t = calc_wt_ave(wt_v[i], wt_v[i + 1]); wt_v[i / 2].w = wt_v[i].w + wt_v[i + 1].w; } return f(f, wt_v, wt_v_index / 2); } }; auto new_state = core::VehicleState(x_sum / weight_sum_, y_sum / weight_sum_, calc_all_wt_ave(calc_all_wt_ave, wt_v, wt_v.size())); const auto current_time = std::chrono::system_clock::now(); const auto interval = std::chrono::duration_cast<std::chrono::microseconds>(current_time - prev_time_).count() / 1e6; new_state.v = new_state.distanceFrom(state_) / interval; const auto dir = core::Theta(std::atan2(new_state.y - state_.y, new_state.x - state_.x)); if(90 <= new_state.t.disparityWith(dir).getDegree()) { new_state.v *= -1; } state_ = new_state; prev_time_ = current_time; if(weight_sum_ < reset_thr_) { resetExpansionary(); } else { resampling(); } } const core::VehicleState& ParticleFilter::getState() const { return state_; } const std::vector<core::ParticleState> & ParticleFilter::getParticles() const { return particles_; } const double& ParticleFilter::getParticlesWeightSum() const { return weight_sum_; } void ParticleFilter::resetExpansionary() { for(auto &particle : particles_) { particle.x += dist_uni_real_position_(rand_); particle.y += dist_uni_real_position_(rand_); particle.t += core::Theta(dist_uni_real_theta_(rand_)); particle.w = 1.0 / particles_.size(); } } void ParticleFilter::updateParticles(const core::WheelOdometry& wo, const core::VisualOdometry& vo, const core::InertialOdometry& io, const double& wo_ps_sigma, const double& wo_t_sigma) { weight_sum_ = 0; auto calc_gauss = [](const double& m, const double& s, const double& v) -> double { return (1 / (std::sqrt(2 * core::PI) * s)) * std::exp(- std::pow(v - m, 2) / (2 * std::pow(s, 2))); }; auto calc_trans_with_gauss = [&](const core::base::StateBase& state, const core::base::StateBase& odometry, const double& ps_sigma = 1.0, const double& t_sigma = 1.0) -> core::ParticleState { auto dist_normal_position = std::normal_distribution<>(0, ps_sigma); auto dist_normal_theta = std::normal_distribution<>(0, t_sigma); return core::ParticleState(state.x + odometry.x + dist_normal_position(rand_), state.y + odometry.y + dist_normal_position(rand_), state.t + odometry.t + core::Theta(dist_normal_theta(rand_))); }; const auto obs_by_vo = calc_trans_with_gauss(state_, vo, pf_param_.vo_ps_sigma, pf_param_.vo_t_sigma); const auto obs_by_io = calc_trans_with_gauss(state_, io, pf_param_.io_ps_sigma, pf_param_.io_t_sigma); for(auto& particle : particles_) { // 状態遷移モデルに基づいて位置・向きを導出 auto new_particle = calc_trans_with_gauss(particle, wo, wo_ps_sigma, wo_t_sigma); // 尤度を計算 const auto vo_ps_disparity = new_particle.distanceFrom(obs_by_vo); const auto vo_t_disparity = new_particle.t.disparityWith(obs_by_vo.t).raw; const auto io_ps_disparity = new_particle.distanceFrom(obs_by_io); const auto io_t_disparity = new_particle.t.disparityWith(obs_by_io.t).raw; new_particle.w = particle.w * pf_param_.vo_ratio_when_calc_disparity * ( (calc_gauss(0, pf_param_.likelifood_position_sigma, vo_ps_disparity) * calc_gauss(0, pf_param_.likelifood_theta_sigma, vo_t_disparity)) + (1 - pf_param_.vo_ratio_when_calc_disparity) * (calc_gauss(0, pf_param_.likelifood_position_sigma, io_ps_disparity) * calc_gauss(0, pf_param_.likelifood_theta_sigma, io_t_disparity))); // パーティクルを更新 particle = new_particle; weight_sum_ += new_particle.w; } if(weight_sum_ == 0) { throw std::runtime_error("[" + std::string(__PRETTY_FUNCTION__) + "] " + "All particles are dead"); } } void ParticleFilter::resampling() { std::vector<core::ParticleState> prev; double sum_weight = 0.0; for(auto &p : particles_) { p.w += sum_weight; sum_weight = p.w; prev.push_back(p); } std::vector<int> choice(particles_.size()); std::uniform_real_distribution<double> rnd(0.0, 1.0); auto accum = rnd(rand_) / particles_.size(); auto step = sum_weight / particles_.size(); size_t j = 0; for(auto &c : choice) { while(prev[j].w <= accum && j < particles_.size() - 1) j++; c = j; accum += step; } for(size_t i = 0; i < particles_.size(); i++) { particles_[i] = prev[choice[i]]; particles_[i].w = 1.0 / particles_.size(); } } }
48.013274
138
0.487236
[ "vector" ]
5fad94745a0771835cbc109af54b3ee3dcd0daaf
928
cpp
C++
modules/task_1/kolesin_a_radix_sort/main.cpp
stasyurin/pp_2021_spring_informatics
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/kolesin_a_radix_sort/main.cpp
stasyurin/pp_2021_spring_informatics
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
[ "BSD-3-Clause" ]
null
null
null
modules/task_1/kolesin_a_radix_sort/main.cpp
stasyurin/pp_2021_spring_informatics
dd9136c28cca4c538c5ecc82512fd78ad1fa7bd3
[ "BSD-3-Clause" ]
1
2021-12-02T22:38:53.000Z
2021-12-02T22:38:53.000Z
// Copyright 2021 Kolesin Andrey #include <gtest/gtest.h> #include <iostream> #include <vector> #include <algorithm> #include "./radix.h" TEST(RadixSort, 321) { std::vector<int> a = {3, 2, 1}; radixSort(&a[0], a.size()); ASSERT_EQ(a, std::vector<int>({1, 2, 3})); } TEST(RadixSort, 1) { std::vector<int> a = {1}; radixSort(&a[0], a.size()); ASSERT_EQ(a, std::vector<int>({1})); } TEST(RadixSort, negative) { std::vector<int> a = {-1, -2, -3}; radixSort(&a[0], a.size()); ASSERT_EQ(a, std::vector<int>({-3, -2, -1})); } TEST(RadixSort, mixed) { std::vector<int> a = {-1, -2, -3, 3, 1, 2, 0}; radixSort(&a[0], a.size()); ASSERT_EQ(a, std::vector<int>({-3, -2, -1, 0, 1, 2, 3})); } TEST(RadixSort, random) { std::vector<int> a = getRandomVector(); // printVec(a); std::vector<int> b = a; radixSort(&a[0], a.size()); std::sort(std::begin(b), std::end(b)); // printVec(a); ASSERT_EQ(a, b); }
23.794872
59
0.572198
[ "vector" ]
5fb42b3b53b6c50eb76d924593fcc166a4d0e8b7
11,339
cpp
C++
src/vlVolume/RaycastVolume.cpp
zpc930/visualizationlibrary
c81fa75c720a3d04d295b977a1f5dc4624428b53
[ "BSD-2-Clause" ]
null
null
null
src/vlVolume/RaycastVolume.cpp
zpc930/visualizationlibrary
c81fa75c720a3d04d295b977a1f5dc4624428b53
[ "BSD-2-Clause" ]
null
null
null
src/vlVolume/RaycastVolume.cpp
zpc930/visualizationlibrary
c81fa75c720a3d04d295b977a1f5dc4624428b53
[ "BSD-2-Clause" ]
null
null
null
/**************************************************************************************/ /* */ /* Visualization Library */ /* http://www.visualizationlibrary.org */ /* */ /* Copyright (c) 2005-2010, Michele Bosi */ /* 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. */ /* */ /* 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 <vlVolume/RaycastVolume.hpp> #include <vlGraphics/GLSL.hpp> #include <vlGraphics/Light.hpp> #include <vlGraphics/Camera.hpp> using namespace vl; /** \class vl::RaycastVolume * A ActorEventCallback used to render a volume using GPU raycasting. * * Pictures from: \ref pagGuideRaycastVolume tutorial. * * <center> * <table border=0 cellspacing=0 cellpadding=5> * <tr> * <td> <img src="pics/pagGuideRaycastVolume_1.jpg"> </td> * <td> <img src="pics/pagGuideRaycastVolume_2.jpg"> </td> * <td> <img src="pics/pagGuideRaycastVolume_3.jpg"> </td> * </tr> * <tr> * <td> <img src="pics/pagGuideRaycastVolume_4.jpg"> </td> * <td> <img src="pics/pagGuideRaycastVolume_5.jpg"> </td> * <td> <img src="pics/pagGuideRaycastVolume_6.jpg"> </td> * </tr> * </table> * </center> * * \sa * - \ref pagGuideRaycastVolume * - \ref pagGuideSlicedVolume * - SlicedVolume * */ RaycastVolume::RaycastVolume() { VL_DEBUG_SET_OBJECT_NAME() // box geometry mGeometry = new Geometry; // install vertex coords array mVertCoord = new ArrayFloat3; mVertCoord->resize( 8 ); mGeometry->setVertexArray( mVertCoord.get() ); // install texture coords array mTexCoord = new ArrayFloat3; mTexCoord->resize( 8 ); mGeometry->setTexCoordArray( 0, mTexCoord.get() ); // install index array ref<DrawElementsUInt> de = new DrawElementsUInt( PT_QUADS ); mGeometry->drawCalls()->push_back( de.get() ); unsigned int de_indices[] = { 0,1,2,3, 1,5,6,2, 5,4,7,6, 4,0,3,7, 3,2,6,7, 4,5,1,0 }; de->indexBuffer()->resize( 4*6 ); memcpy( de->indexBuffer()->ptr(), de_indices, sizeof( de_indices ) ); // generate default texture coordinates fvec3 texc[] = { fvec3( 0,0,0 ), fvec3( 1,0,0 ), fvec3( 1,1,0 ), fvec3( 0,1,0 ), fvec3( 0,0,1 ), fvec3( 1,0,1 ), fvec3( 1,1,1 ), fvec3( 0,1,1 ) }; memcpy( mTexCoord->ptr(), texc, sizeof( texc ) ); // default box dimensions and geometry setBox( AABB( vec3( 0,0,0 ), vec3( 1,1,1 ) ) ); } //----------------------------------------------------------------------------- /** Reimplement this method to update the uniform variables of your GLSL program before the volume is rendered. * - By default updateUniforms() updates the position of up to 4 lights in object space. Such positions are stored in the * \p "uniform vec3 light_position[4]" variable. The updateUniforms() method also fills the * \p "uniform bool light_enable[4]" variable with a flag marking if the Nth light is active or not. * These light values are computed based on the lights bound to the current Shader. * - The \p "uniform vec3 eye_position" variable contains the camera position in object space, useful to compute * specular highlights, raycast direction etc. * - The \p "uniform vec3 eye_look" variable contains the camera look vector in object space. */ void RaycastVolume::updateUniforms( vl::Actor*actor, vl::real, const vl::Camera* camera, vl::Renderable*, const vl::Shader* shader ) { const GLSLProgram* glsl = shader->getGLSLProgram(); VL_CHECK( glsl ); // used later fmat4 inv_mat; if (actor->transform()) inv_mat = ( fmat4 )actor->transform()->worldMatrix().getInverse(); if ( glsl->getUniformLocation( "light_position" ) != -1 && glsl->getUniformLocation( "light_enable" ) != -1 ) { // computes up to 4 light positions ( in object space ) and enables int light_enable[4] = { 0,0,0,0 }; fvec3 light_position[4]; for( int i=0; i<4; ++i ) { const vl::Light* light = shader->getLight( i ); light_enable[i] = light != NULL; if ( light ) { // light position following transform if ( light->boundTransform() ) light_position[i] = ( fmat4 )light->boundTransform()->worldMatrix() * light->position().xyz(); // light position following camera else light_position[i] = ( ( fmat4 )camera->modelingMatrix() * light->position() ).xyz(); // light position in object space if ( actor->transform() ) light_position[i] = inv_mat * light_position[i]; } } actor->gocUniform( "light_position" )->setUniform( 4, light_position ); actor->gocUniform( "light_enable" )->setUniform1i( 4, light_enable ); } if ( glsl->getUniformLocation( "eye_position" ) != -1 ) { // pass the eye position in object space // eye postion fvec3 eye = ( fvec3 )camera->modelingMatrix().getT(); // world to object space if ( actor->transform() ) eye = inv_mat * eye; actor->gocUniform( "eye_position" )->setUniform( eye ); } if ( glsl->getUniformLocation( "eye_look" ) != -1 ) { // pass the eye look direction in object space // eye postion fvec3 look = -( fvec3 )camera->modelingMatrix().getZ(); // world to object space if ( actor->transform() ) { // look = inv_mat * look; look = ( fmat4 )actor->transform()->worldMatrix().getInverse().getTransposed() * look; } actor->gocUniform( "eye_look" )->setUniform( look ); } } //----------------------------------------------------------------------------- void RaycastVolume::bindActor( Actor* actor ) { actor->actorEventCallbacks()->erase( this ); actor->actorEventCallbacks()->push_back( this ); actor->setLod( 0, mGeometry.get() ); } //----------------------------------------------------------------------------- void RaycastVolume::onActorRenderStarted( Actor* actor, real clock, const Camera* camera, Renderable* rend, const Shader* shader, int pass ) { if ( pass>0 ) return; // setup uniform variables if ( shader->getGLSLProgram() ) updateUniforms( actor, clock, camera, rend, shader ); } //----------------------------------------------------------------------------- void RaycastVolume::generateTextureCoordinates( const ivec3& size ) { if ( !size.x() || !size.y() || !size.z() ) { Log::error( "RaycastVolume::generateTextureCoordinates(): failed! The size passed does not represent a 3D image.\n" ); return; } float dx = 0.5f/size.x(); float dy = 0.5f/size.y(); float dz = 0.5f/size.z(); float x0 = 0.0f + dx; float x1 = 1.0f - dx; float y0 = 0.0f + dy; float y1 = 1.0f - dy; float z0 = 0.0f + dz; float z1 = 1.0f - dz; fvec3 texc[] = { fvec3( x0,y0,z1 ), fvec3( x1,y0,z1 ), fvec3( x1,y1,z1 ), fvec3( x0,y1,z1 ), // mic fixme: i don't remember why we need z1 here and z0 below... fvec3( x0,y0,z0 ), fvec3( x1,y0,z0 ), fvec3( x1,y1,z0 ), fvec3( x0,y1,z0 ), }; memcpy( mTexCoord->ptr(), texc, sizeof( texc ) ); } //----------------------------------------------------------------------------- void RaycastVolume::generateTextureCoordinates(const ivec3& img_size, const ivec3& min_corner, const ivec3& max_corner) { if (!img_size.x() || !img_size.y() || !img_size.z()) { Log::error("RaycastVolume::setDisplayRegion(): failed! The size passed does not represent a 3D image.\n"); return; } float dx = 0.5f/img_size.x(); float dy = 0.5f/img_size.y(); float dz = 0.5f/img_size.z(); float x0 = min_corner.x()/(float)img_size.x() + dx; float x1 = max_corner.x()/(float)img_size.x() - dx; float y0 = min_corner.y()/(float)img_size.y() + dy; float y1 = max_corner.y()/(float)img_size.y() - dy; float z0 = min_corner.z()/(float)img_size.z() + dz; float z1 = max_corner.z()/(float)img_size.z() - dz; fvec3 texc[] = { fvec3( x0,y0,z1 ), fvec3( x1,y0,z1 ), fvec3( x1,y1,z1 ), fvec3( x0,y1,z1 ), fvec3( x0,y0,z0 ), fvec3( x1,y0,z0 ), fvec3( x1,y1,z0 ), fvec3( x0,y1,z0 ), }; memcpy( mTexCoord->ptr(), texc, sizeof(texc) ); } //----------------------------------------------------------------------------- void RaycastVolume::setBox( const AABB& box ) { mBox = box; // generate the box geometry float x0 = box.minCorner().x(); float y0 = box.minCorner().y(); float z0 = box.minCorner().z(); float x1 = box.maxCorner().x(); float y1 = box.maxCorner().y(); float z1 = box.maxCorner().z(); fvec3 box_verts[] = { fvec3( x0,y0,z1 ), fvec3( x1,y0,z1 ), fvec3( x1,y1,z1 ), fvec3( x0,y1,z1 ), fvec3( x0,y0,z0 ), fvec3( x1,y0,z0 ), fvec3( x1,y1,z0 ), fvec3( x0,y1,z0 ), }; memcpy( mVertCoord->ptr(), box_verts, sizeof( box_verts ) ); mGeometry->setBoundsDirty( true ); } //-----------------------------------------------------------------------------
41.996296
147
0.536202
[ "geometry", "render", "object", "vector", "transform", "3d" ]
5fbddc33cc119045629e8783c43b89e048790a22
1,797
cpp
C++
Library/Geometry/src/Topology_Based_Geometry/Tetrahedralized_Volume_2D.cpp
OrionQuest/Nova
473a4df24191097c6542c3ec935b3d1bdd2cf13a
[ "Apache-2.0" ]
23
2018-08-24T01:40:56.000Z
2021-01-14T06:58:44.000Z
Library/Geometry/src/Topology_Based_Geometry/Tetrahedralized_Volume_2D.cpp
SoldierDown/Nova
d2da3ee316687316d5a858cd2b95605c483859db
[ "Apache-2.0" ]
2
2017-07-04T11:25:17.000Z
2020-10-10T12:31:01.000Z
Library/Geometry/src/Topology_Based_Geometry/Tetrahedralized_Volume_2D.cpp
SoldierDown/Nova
d2da3ee316687316d5a858cd2b95605c483859db
[ "Apache-2.0" ]
7
2017-07-02T01:10:05.000Z
2020-01-29T17:59:31.000Z
//!##################################################################### //! \file Tetrahedralized_Volume_2D.cpp //!##################################################################### #include <nova/Geometry/Topology_Based_Geometry/Tetrahedralized_Volume.h> using namespace Nova; //###################################################################### // Initialize_Cube_Mesh //###################################################################### template<class T,int d> void Nova::Tetrahedralized_Volume<T,d>:: Initialize_Cube_Mesh(const Grid<T,d>& grid) { points.Clear();elements.Clear(); int m=grid.counts(0)+1,n=grid.counts(1)+1; for(int i=1;i<=m-1;++i) for(int j=1;j<=n-1;++j){ // counter-clockwise node ordering if(i%2){Add_Element(INDEX({i-1+m*(j-1),i+m*(j-1),i-1+m*j})); Add_Element(INDEX({i+m*(j-1),i+m*j,i-1+m*j}));} else{Add_Element(INDEX({i-1+m*(j-1),i+m*(j-1),i+m*j})); Add_Element(INDEX({i-1+m*(j-1),i+m*j,i-1+m*j}));}} for(int j=1;j<=n;++j) for(int i=1;i<=m;++i) Add_Vertex(grid.Node(T_INDEX({i,j}))); number_of_nodes=points.size(); } //###################################################################### // Get_Element //###################################################################### template<class T,int d> typename Nova::Tetrahedralized_Volume_Policy<T,d>::T_Element Nova::Tetrahedralized_Volume<T,d>:: Get_Element(const int id) const { assert(id>=0 && id<elements.size()); const INDEX& e=elements(id); return T_Element(points(e(0)),points(e(1)),points(e(2))); } //###################################################################### template class Nova::Tetrahedralized_Volume<float,2>; #ifdef COMPILE_WITH_DOUBLE_SUPPORT template class Nova::Tetrahedralized_Volume<double,2>; #endif
47.289474
120
0.481358
[ "geometry" ]
5fc662caa6122506e5be13b9964194794951e85b
26,116
cpp
C++
lib/Cinder/src/cinder/gl/Vbo.cpp
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
1
2018-07-20T03:56:15.000Z
2018-07-20T03:56:15.000Z
lib/Cinder/src/cinder/gl/Vbo.cpp
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
null
null
null
lib/Cinder/src/cinder/gl/Vbo.cpp
timmb/HarmonicMotion
4ddf8ce98377260e57b6293d093a144a25ce3132
[ "MIT" ]
null
null
null
/* Copyright (c) 2010, The Barbarian Group 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. 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 "cinder/gl/Vbo.h" #include <sstream> using namespace std; namespace cinder { namespace gl { //enum { CUSTOM_ATTR_FLOAT, CUSTOM_ATTR_FLOAT2, CUSTOM_ATTR_FLOAT3, CUSTOM_ATTR_FLOAT4, TOTAL_CUSTOM_ATTR_TYPES }; int VboMesh::Layout::sCustomAttrSizes[TOTAL_CUSTOM_ATTR_TYPES] = { 4, 8, 12, 16 }; GLint VboMesh::Layout::sCustomAttrNumComponents[TOTAL_CUSTOM_ATTR_TYPES] = { 1, 2, 3, 4 }; GLenum VboMesh::Layout::sCustomAttrTypes[TOTAL_CUSTOM_ATTR_TYPES] = { GL_FLOAT, GL_FLOAT, GL_FLOAT, GL_FLOAT }; Vbo::Obj::Obj( GLenum aTarget ) : mTarget( aTarget ) { glGenBuffers( 1, &mId ); } Vbo::Obj::~Obj() { glDeleteBuffers( 1, &mId ); } Vbo::Vbo( GLenum aTarget ) { mObj = shared_ptr<Vbo::Obj>( new Obj( aTarget ) ); } void Vbo::bind() { glBindBuffer( mObj->mTarget, mObj->mId ); } void Vbo::unbind() { glBindBuffer( mObj->mTarget, 0 ); } void Vbo::bufferData( size_t size, const void *data, GLenum usage ) { bind(); glBufferDataARB( mObj->mTarget, size, data, usage ); } void Vbo::bufferSubData( ptrdiff_t offset, size_t size, const void *data ) { bind(); glBufferSubDataARB( mObj->mTarget, offset, size, data ); } uint8_t* Vbo::map( GLenum access ) { bind(); return reinterpret_cast<uint8_t*>( glMapBuffer( mObj->mTarget, access ) ); } void Vbo::unmap() { bind(); GLboolean result = glUnmapBuffer( mObj->mTarget ); if( result != GL_TRUE ) throw VboFailedUnmapExc(); } bool VboMesh::Layout::hasStaticTexCoords() const { for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) if( ( mAttributes[ATTR_TEXCOORDS2D_0+t] == STATIC ) || ( mAttributes[ATTR_TEXCOORDS3D_0+t] == STATIC ) ) return true; return false; } bool VboMesh::Layout::hasDynamicTexCoords() const { for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) if( ( mAttributes[ATTR_TEXCOORDS2D_0+t] == DYNAMIC ) || ( mAttributes[ATTR_TEXCOORDS3D_0+t] == DYNAMIC ) ) return true; return false; } VboMesh::VboMesh( const TriMesh &triMesh, Layout layout ) : mObj( shared_ptr<Obj>( new Obj ) ) { if( layout.isDefaults() ) { // we need to start by preparing our layout if( triMesh.hasNormals() ) mObj->mLayout.setStaticNormals(); if( triMesh.hasColorsRGB() ) mObj->mLayout.setStaticColorsRGB(); if( triMesh.hasColorsRGBA() ) mObj->mLayout.setStaticColorsRGBA(); if( triMesh.hasTexCoords() ) mObj->mLayout.setStaticTexCoords2d(); mObj->mLayout.setStaticIndices(); mObj->mLayout.setStaticPositions(); } else mObj->mLayout = layout; mObj->mPrimitiveType = GL_TRIANGLES; mObj->mNumIndices = triMesh.getNumIndices(); mObj->mNumVertices = triMesh.getNumVertices(); initializeBuffers( false ); // upload the indices getIndexVbo().bufferData( sizeof(uint32_t) * triMesh.getNumIndices(), &(triMesh.getIndices()[0]), (mObj->mLayout.hasStaticIndices()) ? GL_STATIC_DRAW : GL_STREAM_DRAW ); // upload the verts for( int buffer = STATIC_BUFFER; buffer <= DYNAMIC_BUFFER; ++buffer ) { if( ! mObj->mBuffers[buffer] ) continue; uint8_t *ptr = mObj->mBuffers[buffer].map( GL_WRITE_ONLY ); bool copyPosition = ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticPositions() : mObj->mLayout.hasDynamicPositions(); bool copyNormal = ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticNormals() : mObj->mLayout.hasDynamicNormals() ) && triMesh.hasNormals(); bool copyColorRGB = ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticColorsRGB() : mObj->mLayout.hasDynamicColorsRGB() ) && triMesh.hasColorsRGB(); bool copyColorRGBA = ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticColorsRGBA() : mObj->mLayout.hasDynamicColorsRGBA() ) && triMesh.hasColorsRGBA(); bool copyTexCoord2D = ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticTexCoords2d() : mObj->mLayout.hasDynamicTexCoords2d() ) && triMesh.hasTexCoords(); for( size_t v = 0; v < mObj->mNumVertices; ++v ) { if( copyPosition ) { *(reinterpret_cast<Vec3f*>(ptr)) = triMesh.getVertices()[v]; ptr += sizeof( Vec3f ); } if( copyNormal ) { *(reinterpret_cast<Vec3f*>(ptr)) = triMesh.getNormals()[v]; ptr += sizeof( Vec3f ); } if( copyColorRGB ) { *(reinterpret_cast<Color*>(ptr)) = triMesh.getColorsRGB()[v]; ptr += sizeof( Color ); } if( copyColorRGBA ) { *(reinterpret_cast<ColorA*>(ptr)) = triMesh.getColorsRGBA()[v]; ptr += sizeof( ColorA ); } if( copyTexCoord2D ) { *(reinterpret_cast<Vec2f*>(ptr)) = triMesh.getTexCoords()[v]; ptr += sizeof( Vec2f ); } } mObj->mBuffers[buffer].unmap(); } unbindBuffers(); } VboMesh::VboMesh( const TriMesh2d &triMesh, Layout layout ) : mObj( shared_ptr<Obj>( new Obj ) ) { if( layout.isDefaults() ) { // we need to start by preparing our layout if( triMesh.hasColorsRgb() ) mObj->mLayout.setStaticColorsRGB(); if( triMesh.hasColorsRgba() ) mObj->mLayout.setStaticColorsRGBA(); if( triMesh.hasTexCoords() ) mObj->mLayout.setStaticTexCoords2d(); mObj->mLayout.setStaticIndices(); mObj->mLayout.setStaticPositions(); } else mObj->mLayout = layout; mObj->mPrimitiveType = GL_TRIANGLES; mObj->mNumIndices = triMesh.getNumIndices(); mObj->mNumVertices = triMesh.getNumVertices(); initializeBuffers( false ); // upload the indices getIndexVbo().bufferData( sizeof(uint32_t) * triMesh.getNumIndices(), &(triMesh.getIndices()[0]), (mObj->mLayout.hasStaticIndices()) ? GL_STATIC_DRAW : GL_STREAM_DRAW ); // upload the verts for( int buffer = STATIC_BUFFER; buffer <= DYNAMIC_BUFFER; ++buffer ) { if( ! mObj->mBuffers[buffer] ) continue; uint8_t *ptr = mObj->mBuffers[buffer].map( GL_WRITE_ONLY ); bool copyPosition = ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticPositions() : mObj->mLayout.hasDynamicPositions(); bool copyColorRGB = ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticColorsRGB() : mObj->mLayout.hasDynamicColorsRGB() ) && triMesh.hasColorsRgb(); bool copyColorRGBA = ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticColorsRGBA() : mObj->mLayout.hasDynamicColorsRGBA() ) && triMesh.hasColorsRgba(); bool copyTexCoord2D = ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticTexCoords2d() : mObj->mLayout.hasDynamicTexCoords2d() ) && triMesh.hasTexCoords(); for( size_t v = 0; v < mObj->mNumVertices; ++v ) { if( copyPosition ) { const Vec2f &p = triMesh.getVertices()[v]; *(reinterpret_cast<Vec3f*>(ptr)) = Vec3f( p.x, p.y, 0 ); ptr += sizeof( Vec3f ); } if( copyColorRGB ) { *(reinterpret_cast<Color*>(ptr)) = triMesh.getColorsRGB()[v]; ptr += sizeof( Color ); } if( copyColorRGBA ) { *(reinterpret_cast<ColorA*>(ptr)) = triMesh.getColorsRGBA()[v]; ptr += sizeof( ColorA ); } if( copyTexCoord2D ) { *(reinterpret_cast<Vec2f*>(ptr)) = triMesh.getTexCoords()[v]; ptr += sizeof( Vec2f ); } } mObj->mBuffers[buffer].unmap(); } unbindBuffers(); } VboMesh::VboMesh( size_t numVertices, size_t numIndices, Layout layout, GLenum primitiveType ) : mObj( shared_ptr<Obj>( new Obj ) ) { mObj->mLayout = layout; mObj->mPrimitiveType = primitiveType; mObj->mNumIndices = numIndices; mObj->mNumVertices = numVertices; initializeBuffers( true ); // allocate buffer for indices if( mObj->mLayout.hasIndices() ) mObj->mBuffers[INDEX_BUFFER].bufferData( sizeof(uint32_t) * mObj->mNumIndices, NULL, (mObj->mLayout.hasStaticIndices()) ? GL_STATIC_DRAW : GL_STREAM_DRAW ); unbindBuffers(); } VboMesh::VboMesh( size_t numVertices, size_t numIndices, Layout layout, GLenum primitiveType, Vbo *indexBuffer, Vbo *staticBuffer, Vbo *dynamicBuffer ) : mObj( shared_ptr<Obj>( new Obj ) ) { mObj->mLayout = layout; mObj->mPrimitiveType = primitiveType; mObj->mNumIndices = numIndices; mObj->mNumVertices = numVertices; if( indexBuffer ) { mObj->mBuffers[INDEX_BUFFER] = *indexBuffer; if( indexBuffer->getTarget() != GL_ELEMENT_ARRAY_BUFFER ) throw VboInvalidTargetExc(); } if( staticBuffer ) { mObj->mBuffers[STATIC_BUFFER] = *staticBuffer; if( staticBuffer->getTarget() != GL_ARRAY_BUFFER ) throw VboInvalidTargetExc(); } if( dynamicBuffer ) { mObj->mBuffers[DYNAMIC_BUFFER] = *dynamicBuffer; if( dynamicBuffer->getTarget() != GL_ARRAY_BUFFER ) throw VboInvalidTargetExc(); } initializeBuffers( true ); unbindBuffers(); } // If any buffers are not NULL they will be ignored void VboMesh::initializeBuffers( bool staticDataPlanar ) { bool hasStaticBuffer = mObj->mLayout.hasStaticPositions() || mObj->mLayout.hasStaticNormals() || mObj->mLayout.hasStaticColorsRGB() || mObj->mLayout.hasStaticColorsRGBA() || mObj->mLayout.hasStaticTexCoords() || ( ! mObj->mLayout.mCustomStatic.empty() ); bool hasDynamicBuffer = mObj->mLayout.hasDynamicPositions() || mObj->mLayout.hasDynamicNormals() || mObj->mLayout.hasDynamicColorsRGB() || mObj->mLayout.hasDynamicColorsRGBA() || mObj->mLayout.hasDynamicTexCoords() || ( ! mObj->mLayout.mCustomDynamic.empty() ); if( ( mObj->mLayout.hasStaticIndices() || mObj->mLayout.hasDynamicIndices() ) && ( ! mObj->mBuffers[INDEX_BUFFER] ) ) mObj->mBuffers[INDEX_BUFFER] = Vbo( GL_ELEMENT_ARRAY_BUFFER ); if( hasStaticBuffer && staticDataPlanar ) { // Planar static buffer size_t offset = 0; bool doSetup = false; if( ! mObj->mBuffers[STATIC_BUFFER] ) { mObj->mBuffers[STATIC_BUFFER] = Vbo( GL_ARRAY_BUFFER ); doSetup = true; } if( mObj->mLayout.hasStaticPositions() ) { mObj->mPositionOffset = offset; offset += sizeof(GLfloat) * 3 * mObj->mNumVertices; } if( mObj->mLayout.hasStaticNormals() ) { mObj->mNormalOffset = offset; offset += sizeof(GLfloat) * 3 * mObj->mNumVertices; } if( mObj->mLayout.hasStaticColorsRGB() ) { mObj->mColorRGBOffset = offset; offset += sizeof(GLfloat) * 3 * mObj->mNumVertices; } if( mObj->mLayout.hasStaticColorsRGBA() ) { mObj->mColorRGBAOffset = offset; offset += sizeof(GLfloat) * 4 * mObj->mNumVertices; } for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) { if( mObj->mLayout.hasStaticTexCoords2d( t ) ) { mObj->mTexCoordOffset[t] = offset; offset += sizeof(GLfloat) * 2 * mObj->mNumVertices; } else if( mObj->mLayout.hasStaticTexCoords3d( t ) ) { mObj->mTexCoordOffset[t] = offset; offset += sizeof(GLfloat) * 3 * mObj->mNumVertices; } } for( size_t c = 0; c < mObj->mLayout.mCustomStatic.size(); ++c ) { mObj->mLayout.mCustomStatic[c].second = offset; offset += VboMesh::Layout::sCustomAttrSizes[mObj->mLayout.mCustomStatic[c].first] * mObj->mNumVertices; } mObj->mStaticStride = 0; // setup the buffer to be the summed size if( doSetup ) mObj->mBuffers[STATIC_BUFFER].bufferData( offset, NULL, GL_STATIC_DRAW ); } else if( hasStaticBuffer && ( ! staticDataPlanar ) ) { // Interleaved static buffer size_t offset = 0; if( ! mObj->mBuffers[STATIC_BUFFER] ) mObj->mBuffers[STATIC_BUFFER] = Vbo( GL_ARRAY_BUFFER ); if( mObj->mLayout.hasStaticPositions() ) { mObj->mPositionOffset = offset; offset += sizeof(GLfloat) * 3; } if( mObj->mLayout.hasStaticNormals() ) { mObj->mNormalOffset = offset; offset += sizeof(GLfloat) * 3; } if( mObj->mLayout.hasStaticColorsRGB() ) { mObj->mColorRGBOffset = offset; offset += sizeof(GLfloat) * 3; } else if( mObj->mLayout.hasStaticColorsRGBA() ) { mObj->mColorRGBAOffset = offset; offset += sizeof(GLfloat) * 4; } for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) { if( mObj->mLayout.hasStaticTexCoords2d( t ) ) { mObj->mTexCoordOffset[t] = offset; offset += sizeof(GLfloat) * 2; } else if( mObj->mLayout.hasStaticTexCoords3d( t ) ) { mObj->mTexCoordOffset[t] = offset; offset += sizeof(GLfloat) * 3; } } for( size_t c = 0; c < mObj->mLayout.mCustomStatic.size(); ++c ) { mObj->mLayout.mCustomStatic[c].second = offset; offset += VboMesh::Layout::sCustomAttrSizes[mObj->mLayout.mCustomStatic[c].first]; } mObj->mStaticStride = offset; // setup the buffer to be the summed size mObj->mBuffers[STATIC_BUFFER].bufferData( mObj->mStaticStride * mObj->mNumVertices, NULL, GL_STATIC_DRAW ); } else { mObj->mStaticStride = 0; } if( hasDynamicBuffer ) { size_t offset = 0; if( ! mObj->mBuffers[DYNAMIC_BUFFER] ) mObj->mBuffers[DYNAMIC_BUFFER] = Vbo( GL_ARRAY_BUFFER ); if( mObj->mLayout.hasDynamicPositions() ) { mObj->mPositionOffset = offset; offset += sizeof(GLfloat) * 3; } if( mObj->mLayout.hasDynamicNormals() ) { mObj->mNormalOffset = offset; offset += sizeof(GLfloat) * 3; } if( mObj->mLayout.hasDynamicColorsRGB() ) { mObj->mColorRGBOffset = offset; offset += sizeof(GLfloat) * 3; } else if( mObj->mLayout.hasDynamicColorsRGBA() ) { mObj->mColorRGBAOffset = offset; offset += sizeof(GLfloat) * 4; } for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) { if( mObj->mLayout.hasDynamicTexCoords2d( t ) ) { mObj->mTexCoordOffset[t] = offset; offset += sizeof(GLfloat) * 2; } else if( mObj->mLayout.hasDynamicTexCoords3d( t ) ) { mObj->mTexCoordOffset[t] = offset; offset += sizeof(GLfloat) * 3; } } for( size_t c = 0; c < mObj->mLayout.mCustomDynamic.size(); ++c ) { mObj->mLayout.mCustomDynamic[c].second = offset; offset += VboMesh::Layout::sCustomAttrSizes[mObj->mLayout.mCustomDynamic[c].first]; } mObj->mDynamicStride = offset; // setup the buffer to be the summed size mObj->mBuffers[DYNAMIC_BUFFER].bufferData( mObj->mDynamicStride * mObj->mNumVertices, NULL, GL_STREAM_DRAW ); } else { mObj->mDynamicStride = 0; } // initialize all the custom attribute locations if( ! mObj->mLayout.mCustomStatic.empty() ) mObj->mCustomStaticLocations = vector<GLint>( mObj->mLayout.mCustomStatic.size(), -1 ); if( ! mObj->mLayout.mCustomDynamic.empty() ) mObj->mCustomDynamicLocations = vector<GLint>( mObj->mLayout.mCustomDynamic.size(), -1 ); } void VboMesh::enableClientStates() const { if( mObj->mLayout.hasPositions() ) glEnableClientState( GL_VERTEX_ARRAY ); else glDisableClientState( GL_VERTEX_ARRAY ); if( mObj->mLayout.hasNormals() ) glEnableClientState( GL_NORMAL_ARRAY ); else glDisableClientState( GL_NORMAL_ARRAY ); if( mObj->mLayout.hasColorsRGB() || mObj->mLayout.hasColorsRGBA() ) glEnableClientState( GL_COLOR_ARRAY ); else glDisableClientState( GL_COLOR_ARRAY ); for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) { if( mObj->mLayout.hasTexCoords( t ) ) { glClientActiveTexture( GL_TEXTURE0 + (GLenum)t ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); } } for( size_t a = 0; a < mObj->mCustomStaticLocations.size(); ++a ) { if( mObj->mCustomStaticLocations[a] < 0 ) throw; glEnableVertexAttribArray( mObj->mCustomStaticLocations[a] ); } for( size_t a = 0; a < mObj->mCustomDynamicLocations.size(); ++a ) { if( mObj->mCustomDynamicLocations[a] < 0 ) throw; glEnableVertexAttribArray( mObj->mCustomDynamicLocations[a] ); } } void VboMesh::disableClientStates() const { glDisableClientState( GL_VERTEX_ARRAY ); glDisableClientState( GL_NORMAL_ARRAY ); glDisableClientState( GL_COLOR_ARRAY ); for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) { if( mObj->mLayout.hasTexCoords( t ) ) { glClientActiveTexture( GL_TEXTURE0 + (GLenum)t ); glDisableClientState( GL_TEXTURE_COORD_ARRAY ); } } for( size_t a = 0; a < mObj->mCustomStaticLocations.size(); ++a ) { if( mObj->mCustomStaticLocations[a] < 0 ) throw; glDisableVertexAttribArray( mObj->mCustomStaticLocations[a] ); } for( size_t a = 0; a < mObj->mCustomDynamicLocations.size(); ++a ) { if( mObj->mCustomDynamicLocations[a] < 0 ) throw; glDisableVertexAttribArray( mObj->mCustomDynamicLocations[a] ); } } void VboMesh::bindAllData() const { if( mObj->mLayout.hasIndices() ) { mObj->mBuffers[INDEX_BUFFER].bind(); } for( int buffer = STATIC_BUFFER; buffer <= DYNAMIC_BUFFER; ++buffer ) { if( ! mObj->mBuffers[buffer] ) continue; mObj->mBuffers[buffer].bind(); uint8_t stride = ( buffer == STATIC_BUFFER ) ? mObj->mStaticStride : mObj->mDynamicStride; if( ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticNormals() : mObj->mLayout.hasDynamicNormals() ) ) glNormalPointer( GL_FLOAT, stride, ( const GLvoid *)mObj->mNormalOffset ); if( ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticColorsRGB() : mObj->mLayout.hasDynamicColorsRGB() ) ) glColorPointer( 3, GL_FLOAT, stride, ( const GLvoid *)mObj->mColorRGBOffset ); else if( ( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticColorsRGBA() : mObj->mLayout.hasDynamicColorsRGBA() ) ) glColorPointer( 4, GL_FLOAT, stride, ( const GLvoid *)mObj->mColorRGBAOffset ); for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) { if( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticTexCoords2d( t ) : mObj->mLayout.hasDynamicTexCoords2d( t ) ) { glClientActiveTexture( GL_TEXTURE0 + (GLenum)t ); glTexCoordPointer( 2, GL_FLOAT, stride, (const GLvoid *)mObj->mTexCoordOffset[t] ); } else if( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticTexCoords3d( t ) : mObj->mLayout.hasDynamicTexCoords3d( t ) ) { glClientActiveTexture( GL_TEXTURE0 + (GLenum)t ); glTexCoordPointer( 3, GL_FLOAT, stride, (const GLvoid *)mObj->mTexCoordOffset[t] ); } } if( ( buffer == STATIC_BUFFER ) ? mObj->mLayout.hasStaticPositions() : mObj->mLayout.hasDynamicPositions() ) glVertexPointer( 3, GL_FLOAT, stride, (const GLvoid*)mObj->mPositionOffset ); } for( int buffer = STATIC_BUFFER; buffer <= DYNAMIC_BUFFER; ++buffer ) { if( ! mObj->mBuffers[buffer] ) continue; const vector<pair<VboMesh::Layout::CustomAttr,size_t> > &attributes( ( buffer == DYNAMIC_BUFFER ) ? mObj->mLayout.mCustomDynamic : mObj->mLayout.mCustomStatic ); const vector<GLint> &locations( ( buffer == DYNAMIC_BUFFER ) ? mObj->mCustomDynamicLocations : mObj->mCustomStaticLocations ); size_t stride = ( ( buffer == DYNAMIC_BUFFER ) ? mObj->mDynamicStride : mObj->mStaticStride ); if( attributes.empty() ) continue; mObj->mBuffers[buffer].bind(); for( size_t a = 0; a < attributes.size(); ++a ) { const GLvoid *offset = reinterpret_cast<const GLvoid*>( attributes[a].second ); glVertexAttribPointer( locations[a], Layout::sCustomAttrNumComponents[attributes[a].first], Layout::sCustomAttrTypes[attributes[a].first], GL_FALSE, (GLsizei)stride, offset ); } } } void VboMesh::bindIndexBuffer() const { mObj->mBuffers[INDEX_BUFFER].bind(); } void VboMesh::unbindBuffers() { glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); } void VboMesh::bufferIndices( const std::vector<uint32_t> &indices ) { mObj->mBuffers[INDEX_BUFFER].bufferData( sizeof(uint32_t) * indices.size(), &(indices[0]), (mObj->mLayout.hasStaticIndices()) ? GL_STATIC_DRAW : GL_STREAM_DRAW ); } void VboMesh::bufferPositions( const std::vector<Vec3f> &positions ) { bufferPositions( &positions[0], positions.size() ); } void VboMesh::bufferPositions( const Vec3f *positions, size_t count ) { if( mObj->mLayout.hasDynamicPositions() ) { if( mObj->mDynamicStride == 0 ) getDynamicVbo().bufferSubData( mObj->mPositionOffset, sizeof(Vec3f) * count, positions ); else throw; } else if( mObj->mLayout.hasStaticPositions() ) { if( mObj->mStaticStride == 0 ) { // planar data getStaticVbo().bufferSubData( mObj->mPositionOffset, sizeof(Vec3f) * count, positions ); } else throw; } else throw; } void VboMesh::bufferNormals( const std::vector<Vec3f> &normals ) { if( mObj->mLayout.hasDynamicNormals() ) { if( mObj->mDynamicStride == 0 ) getDynamicVbo().bufferSubData( mObj->mNormalOffset, sizeof(Vec3f) * normals.size(), &(normals[0]) ); else throw; } else if( mObj->mLayout.hasStaticNormals() ) { if( mObj->mStaticStride == 0 ) { // planar data getStaticVbo().bufferSubData( mObj->mNormalOffset, sizeof(Vec3f) * normals.size(), &(normals[0]) ); } else throw; } else throw; } void VboMesh::bufferTexCoords2d( size_t unit, const std::vector<Vec2f> &texCoords ) { if( mObj->mLayout.hasDynamicTexCoords2d(unit) ) { if( mObj->mDynamicStride == 0 ) getDynamicVbo().bufferSubData( mObj->mTexCoordOffset[unit], sizeof(Vec2f) * texCoords.size(), &(texCoords[0]) ); else throw; } else if( mObj->mLayout.hasStaticTexCoords2d(unit) ) { if( mObj->mStaticStride == 0 ) { // planar data getStaticVbo().bufferSubData( mObj->mTexCoordOffset[unit], sizeof(Vec2f) * texCoords.size(), &(texCoords[0]) ); } else throw; } else throw; } void VboMesh::bufferTexCoords3d( size_t unit, const std::vector<Vec3f> &texCoords ) { if( mObj->mLayout.hasDynamicTexCoords3d(unit) ) { if( mObj->mDynamicStride == 0 ) getDynamicVbo().bufferSubData( mObj->mTexCoordOffset[unit], sizeof(Vec3f) * texCoords.size(), &(texCoords[0]) ); else throw; } else if( mObj->mLayout.hasStaticTexCoords3d(unit) ) { if( mObj->mStaticStride == 0 ) { // planar data getStaticVbo().bufferSubData( mObj->mTexCoordOffset[unit], sizeof(Vec3f) * texCoords.size(), &(texCoords[0]) ); } else throw; } else throw; } void VboMesh::bufferColorsRGB( const std::vector<Color> &colors ) { if( mObj->mLayout.hasDynamicColorsRGB() ) { if( mObj->mDynamicStride == 0 ) getDynamicVbo().bufferSubData( mObj->mColorRGBOffset, sizeof(Color) * colors.size(), &(colors[0]) ); else throw; } else if( mObj->mLayout.hasStaticColorsRGB() ) { if( mObj->mStaticStride == 0 ) { // planar data getStaticVbo().bufferSubData( mObj->mColorRGBOffset, sizeof(Color) * colors.size(), &(colors[0]) ); } else throw; } else throw; } void VboMesh::bufferColorsRGBA( const std::vector<ColorA> &colors ) { if( mObj->mLayout.hasDynamicColorsRGBA() ) { if( mObj->mDynamicStride == 0 ) getDynamicVbo().bufferSubData( mObj->mColorRGBAOffset, sizeof(ColorA) * colors.size(), &(colors[0]) ); else throw; } else if( mObj->mLayout.hasStaticColorsRGBA() ) { if( mObj->mStaticStride == 0 ) { // planar data getStaticVbo().bufferSubData( mObj->mColorRGBAOffset, sizeof(ColorA) * colors.size(), &(colors[0]) ); } else throw; } else throw; } VboMesh::VertexIter VboMesh::mapVertexBuffer() { return VertexIter( *this ); } void VboMesh::VertexIter::set( const VertexIter &other ) { mObj = other.mObj; mPtr = other.mPtr; mData = other.mData; mDataEnd = other.mDataEnd; mPositionOffset = other.mPositionOffset; mNormalOffset = other.mNormalOffset; mColorRGBOffset = other.mColorRGBOffset; mColorRGBAOffset = other.mColorRGBAOffset; mStride = other.mStride; for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) mTexCoordOffset[t] = other.mTexCoordOffset[t]; } VboMesh::VertexIter::VertexIter( const VboMesh &mesh ) : mObj( shared_ptr<Obj>( new Obj( mesh ) ) ) { mData = mObj->mData; mDataEnd = mObj->mDataEnd; mPtr = mData; mStride = mesh.mObj->mDynamicStride; mPositionOffset = mesh.mObj->mPositionOffset; mNormalOffset = mesh.mObj->mNormalOffset; mColorRGBOffset = mesh.mObj->mColorRGBOffset; mColorRGBAOffset = mesh.mObj->mColorRGBAOffset; for( size_t t = 0; t <= ATTR_MAX_TEXTURE_UNIT; ++t ) mTexCoordOffset[t] = mesh.mObj->mTexCoordOffset[t]; for( size_t c = 0; c < mesh.mObj->mLayout.mCustomDynamic.size(); ++c ) mObj->mCustomOffsets.push_back( mesh.mObj->mLayout.mCustomDynamic[c].second ); } VboMesh::VertexIter::Obj::Obj( const VboMesh &mesh ) : mVbo( mesh.getDynamicVbo() ) { // Buffer NULL data to tell the driver we don't care about what's in there (See NVIDIA's "Using Vertex Buffer Objects" whitepaper) mVbo.bind(); //mVbo.bufferData( mesh.mObj->mDynamicStride * mesh.mObj->mNumVertices, NULL, GL_STREAM_DRAW ); glBufferDataARB( GL_ARRAY_BUFFER, mesh.mObj->mDynamicStride * mesh.mObj->mNumVertices, NULL, GL_STREAM_DRAW ); //mData = mVbo.map( GL_WRITE_ONLY ); mData = reinterpret_cast<uint8_t*>( glMapBuffer( GL_ARRAY_BUFFER, GL_WRITE_ONLY ) ); mDataEnd = mData + mesh.mObj->mDynamicStride * mesh.getNumVertices(); } VboMesh::VertexIter::Obj::~Obj() { mVbo.unmap(); mVbo.unbind(); } } } // namespace cinder::gl
34.453826
263
0.67541
[ "mesh", "vector" ]
5fc91437bc815763d74eb4f9de602c27e0326a0f
1,578
cpp
C++
src/Rendering/Images/ImageLoadingScheduler.cpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
src/Rendering/Images/ImageLoadingScheduler.cpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
src/Rendering/Images/ImageLoadingScheduler.cpp
Frostie314159/FrostEngine
bb7781c5c90baf77ca836d69d6c38a4a5381e27f
[ "MIT" ]
null
null
null
#include "ImageLoadingScheduler.hpp" ImageLoadingScheduler::ImageLoadingScheduler(Config t_config){ this->m_threads = std::vector<std::pair<std::thread,std::atomic_bool>>(); this->m_threads.reserve(std::thread::hardware_concurrency() - std::stoi(t_config.getConfigEntry("ReservedThreads").value)); this->m_images = std::vector<std::shared_ptr<Image>>(); this->m_workerThread = std::thread(ImageLoadingScheduler::workLoop); } void ImageLoadingScheduler::workLoop(){ while(!this->m_terminate){ for(std::shared_ptr m_currentImage: this->m_images){ if(!m_currentImage.get()->isMutexLocked()){ std::lock_guard<std::mutex> m_activeThreadLockGuard(this->m_schedulerMutex); if(this->m_activeThreads < this->m_threads.size()){ for(int i=0;i<this->m_threads.size();i++){ if(this->m_threads.at(i).second){ this->m_threads.at(i).first.join(); this->m_threads.at(i).first = std::thread(ImageLoadingScheduler::loadImage, m_currentImage, i); } } } } }; } } void ImageLoadingScheduler::loadImage(std::shared_ptr<Image> t_imagePtr, size_t t_index){ this->m_threads.at(t_index).second = false; t_imagePtr.get()->load(); this->m_threads.at(t_index).second = true; } void ImageLoadingScheduler::destroy(){ this->m_terminate = true; for(int i=0;i<this->m_threads.size();i++) this->m_threads.at(i).first.join(); }
42.648649
127
0.61597
[ "vector" ]
5fcc7353cef75ec49776d50a34d8c158a25fbf3b
4,371
cpp
C++
BSenseApp/moc_bsenseprobe.cpp
mino98/bsense
22081c5f708489129374a839502363abb877ab42
[ "MIT" ]
null
null
null
BSenseApp/moc_bsenseprobe.cpp
mino98/bsense
22081c5f708489129374a839502363abb877ab42
[ "MIT" ]
null
null
null
BSenseApp/moc_bsenseprobe.cpp
mino98/bsense
22081c5f708489129374a839502363abb877ab42
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'bsenseprobe.h' ** ** Created: Wed Aug 25 14:18:47 2010 ** by: The Qt Meta Object Compiler version 62 (Qt 4.6.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "bsenseprobe.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'bsenseprobe.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.6.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_BSenseProbe[] = { // content: 4, // revision 0, // classname 0, 0, // classinfo 16, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 13, 12, 12, 12, 0x0a, 27, 12, 12, 12, 0x0a, 51, 12, 12, 12, 0x0a, 70, 12, 12, 12, 0x0a, 93, 12, 12, 12, 0x0a, 112, 12, 12, 12, 0x0a, 131, 12, 12, 12, 0x0a, 159, 12, 12, 12, 0x0a, 186, 184, 12, 12, 0x0a, 228, 184, 12, 12, 0x0a, 270, 184, 12, 12, 0x0a, 315, 184, 12, 12, 0x0a, 360, 12, 12, 12, 0x0a, 378, 12, 12, 12, 0x0a, 396, 12, 12, 12, 0x0a, 417, 12, 12, 12, 0x0a, 0 // eod }; static const char qt_meta_stringdata_BSenseProbe[] = { "BSenseProbe\0\0testNetwork()\0" "argumentsHttpFinished()\0postCodeFinished()\0" "emailAddressFinished()\0httpFinishedResp()\0" "recvHttpFinished()\0finishedWaitingBeforeRecv()\0" "finishedSendingFailure()\0,\0" "finishedItgSend(int,QProcess::ExitStatus)\0" "finishedItgRecv(int,QProcess::ExitStatus)\0" "finishedItgSendDec(int,QProcess::ExitStatus)\0" "finishedItgRecvDec(int,QProcess::ExitStatus)\0" "sendProcTimeout()\0recvProcTimeout()\0" "decSendProcTimeout()\0decRecvProcTimeout()\0" }; const QMetaObject BSenseProbe::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_BSenseProbe, qt_meta_data_BSenseProbe, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &BSenseProbe::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *BSenseProbe::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *BSenseProbe::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_BSenseProbe)) return static_cast<void*>(const_cast< BSenseProbe*>(this)); return QObject::qt_metacast(_clname); } int BSenseProbe::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: testNetwork(); break; case 1: argumentsHttpFinished(); break; case 2: postCodeFinished(); break; case 3: emailAddressFinished(); break; case 4: httpFinishedResp(); break; case 5: recvHttpFinished(); break; case 6: finishedWaitingBeforeRecv(); break; case 7: finishedSendingFailure(); break; case 8: finishedItgSend((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< QProcess::ExitStatus(*)>(_a[2]))); break; case 9: finishedItgRecv((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< QProcess::ExitStatus(*)>(_a[2]))); break; case 10: finishedItgSendDec((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< QProcess::ExitStatus(*)>(_a[2]))); break; case 11: finishedItgRecvDec((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< QProcess::ExitStatus(*)>(_a[2]))); break; case 12: sendProcTimeout(); break; case 13: recvProcTimeout(); break; case 14: decSendProcTimeout(); break; case 15: decRecvProcTimeout(); break; default: ; } _id -= 16; } return _id; } QT_END_MOC_NAMESPACE
36.425
133
0.60421
[ "object" ]
5fcf895b181fbb0c6531bd19ed3efb645e85246c
23,427
cpp
C++
es3/connection.cpp
Cyberax/extremes3
dc95b65a84778defc8fcc6d55554de2670cef6fc
[ "BSD-3-Clause" ]
null
null
null
es3/connection.cpp
Cyberax/extremes3
dc95b65a84778defc8fcc6d55554de2670cef6fc
[ "BSD-3-Clause" ]
null
null
null
es3/connection.cpp
Cyberax/extremes3
dc95b65a84778defc8fcc6d55554de2670cef6fc
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2013, Illumina 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 the Illumina, 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 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 "connection.h" #include "context.h" #include <curl/curl.h> #include "errors.h" #include <openssl/hmac.h> #include <openssl/md5.h> #include <tinyxml.h> #include "scope_guard.h" #include <boost/algorithm/string.hpp> using namespace es3; static std::string escape(const std::string &str) { char *res=curl_escape(str.c_str(), str.length()); ON_BLOCK_EXIT(&curl_free,res); return std::string(res); } s3_path es3::parse_path(const std::string &url) { s3_path res; if (url.find("s3://")!=0) throw std::bad_exception(); std::string bucket_and_path=url.substr(strlen("s3://")); size_t path_pos = bucket_and_path.find('/'); if (path_pos==0) err(errFatal) << "Malformed S3 URL - no bucket name: " << url; if (path_pos!=-1) { res.bucket_=bucket_and_path.substr(0, path_pos); res.path_=bucket_and_path.substr(path_pos); } else { res.bucket_=bucket_and_path; res.path_="/"; } if (res.path_.find("//")!=std::string::npos) err(errFatal) << "Malformed S3 URL - invalid '//' combination: " << url; return res; } s3_connection::s3_connection(const context_ptr &conn_data) : conn_data_(conn_data), header_list_(), num_lists_() { } s3_connection::~s3_connection() { if (header_list_) curl_slist_free_all(header_list_); } void s3_connection::checked(curl_ptr_t curl, int curl_code) { if (curl_code!=CURLE_OK) { char* error_buffer=conn_data_->err_buf_for(curl); assert(error_buffer); if (strlen(error_buffer)!=0) { assert(strlen(error_buffer)<=CURL_ERROR_SIZE); err(errWarn) << "curl error: " << error_buffer; } else err(errWarn) << "curl error: " << curl_easy_strerror((CURLcode)curl_code); conn_data_->taint(curl); } } void s3_connection::check_for_errors(curl_ptr_t curl, const std::string &curl_res) { long code=400; checked(curl, curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &code)); if (code<400) return; conn_data_->taint(curl); code_e err_level=errFatal; if (code>=500) err_level=errWarn; std::string def_error="HTTP code "+int_to_string(code)+" received."; TiXmlDocument doc; doc.Parse(curl_res.c_str()); if (!doc.Error()) { TiXmlHandle docHandle(&doc); TiXmlNode *s3_err_code=docHandle.FirstChild("Error") .FirstChild("Code") .FirstChild() .ToText(); TiXmlNode *message=docHandle.FirstChild("Error") .FirstChild("Message") .FirstChild() .ToText(); //Workaround for timeouts std::string msg_val = message->Value(); std::string err_code = s3_err_code->Value(); if (msg_val.find("Idle connections will be closed")!=-1) err_level=errWarn; //Lower error level if (msg_val.find("NoSuchUpload")!=-1) err_level=errWarn; //Lower error level if (s3_err_code && message) err(err_level) << "" << err_code << " - " << msg_val; } else err(err_level) << "" << def_error; } void s3_connection::prepare(curl_ptr_t curl, const std::string &verb, const s3_path &path, const header_map_t &opts) { s3_path cur_path=path; if (cur_path.path_.empty()) cur_path.path_.append("/"); curl_easy_reset(curl.get()); //memset(conn_data_->err_buf_for(curl.get()) , 0, CURL_ERROR_SIZE); //Set HTTP verb checked(curl, curl_easy_setopt(curl.get(), CURLOPT_CUSTOMREQUEST, verb.c_str())); //Do not do any automatic decompression checked(curl, curl_easy_setopt(curl.get(), CURLOPT_ENCODING , 0)); if (header_list_) { curl_slist_free_all(header_list_); header_list_ = 0; } //Add custom headers for(auto iter = opts.begin(), iend=opts.end(); iter!=iend; ++iter) { std::string header = iter->first + ": " + iter->second; header_list_ = curl_slist_append(header_list_, header.c_str()); } header_list_ = authenticate_req(header_list_, verb, cur_path, opts); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, header_list_)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_BUFFERSIZE, 16384*16)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_NOSIGNAL, 1)); set_url(curl, path, ""); } void s3_connection::set_url(curl_ptr_t curl, const s3_path &path, const std::string &args) { s3_path cur_path=path; if (cur_path.path_.empty()) cur_path.path_.append("/"); std::string url = conn_data_->use_ssl_?"https://" : "http://"; url.append(cur_path.bucket_); url.append(".").append(cur_path.zone_); url.append(".amazonaws.com"); url.append(cur_path.path_); url.append(args); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str())); } curl_slist* s3_connection::authenticate_req(struct curl_slist * header_list, const std::string &verb, const s3_path &path, const header_map_t &opts) { header_map_t my_opts = opts; //Make a 'Date' header std::string date_header=format_time(time(NULL)); my_opts["x-amz-date"] = date_header; header_list = curl_slist_append(header_list, (std::string("x-amz-date: ")+date_header).c_str()); std::string amz_headers; for(auto iter = my_opts.begin(); iter!=my_opts.end();++iter) { std::string lower_hdr = iter->first; std::transform(lower_hdr.begin(), lower_hdr.end(), lower_hdr.begin(), ::tolower); if (lower_hdr.find("x-amz")==0) amz_headers.append(lower_hdr).append(":") .append(iter->second).append("\n"); } //Signature std::string canonicalizedResource="/"+path.bucket_+path.path_; std::string stringToSign = verb + "\n" + try_get(opts, "content-md5") + "\n" + try_get(opts, "content-type") + "\n" + /*date_header +*/ "\n" + amz_headers + canonicalizedResource; std::string sign_res=sign(stringToSign) ; if (sign_res.empty()) sign_res.empty(); std::string auth="Authorization: AWS "+conn_data_->api_key_+":"+sign_res; return curl_slist_append(header_list, auth.c_str()); } std::string s3_connection::sign(const std::string &str) { if (str.length() >= INT_MAX) throw std::bad_exception(); const std::string &secret_key = conn_data_->secret_key; char md[EVP_MAX_MD_SIZE+1]={0}; unsigned int md_len=0; HMAC(EVP_sha1(), secret_key.c_str(), secret_key.length(), (const unsigned char*)str.c_str(), str.length(), (unsigned char*)md, &md_len); return base64_encode(md, md_len); } static size_t string_appender(const char *ptr, size_t size, size_t nmemb, void *userdata) { std::string *str = reinterpret_cast<std::string*>(userdata); str->append(ptr, ptr+size*nmemb); return size*nmemb; } std::string s3_connection::read_fully(const std::string &verb, const s3_path &path, const std::string &args, const header_map_t &opts) { std::string res; curl_ptr_t curl=conn_data_->get_curl(path.zone_, path.bucket_); prepare(curl, verb, path, opts); if (!args.empty()) set_url(curl, path, args); checked(curl, curl_easy_setopt( curl.get(), CURLOPT_WRITEFUNCTION, &string_appender)); checked(curl,curl_easy_setopt( curl.get(), CURLOPT_WRITEDATA, &res)); checked(curl,curl_easy_perform(curl.get())); check_for_errors(curl, res); return res; } static std::string extract_leaf(const std::string &path) { size_t idx=path.find_last_of('/'); if (idx==std::string::npos || idx==path.size()-1) return path; return path.substr(idx+1); } static void decrement(int *ptr, mutex_t *mtx, boost::condition_variable *cv) { u_guard_t lock(*mtx); (*ptr)--; cv->notify_all(); } s3_directory_ptr s3_connection::list_files_shallow(const s3_path &path, s3_directory_ptr target, bool try_to_root) { { const int num_reqs = conn_data_->concurrent_list_req_; u_guard_t lock(parallel_req_mutex_); while(num_reqs>0 && num_lists_>num_reqs) num_parallel_reqs_.wait(lock); num_lists_++; } ON_BLOCK_EXIT(&decrement, &num_lists_, &parallel_req_mutex_, &num_parallel_reqs_); if (!target) { target=s3_directory_ptr(new s3_directory()); target->absolute_name_ = path; if (try_to_root && *path.path_.rbegin() != '/') { size_t pos=path.path_.find_last_of('/'); if (pos==std::string::npos) target->absolute_name_.path_ = "/"; else target->absolute_name_.path_ = path.path_.substr(0, pos+1); } } std::string marker; while(true) { std::string args; assert(!path.path_.empty() && path.path_[0]=='/'); std::string no_leading_slash = path.path_.substr(1); if (no_leading_slash.empty()) args="?marker="+escape(marker)+"&delimiter=/"; else args="?prefix="+escape(no_leading_slash)+ "&marker="+escape(marker)+"&delimiter=/"; s3_path root=path; root.path_="/"; std::string list=read_fully("GET", root, args); TiXmlDocument doc; doc.Parse(list.c_str()); if (doc.Error()) err(errWarn) << "Failed to get file listing from /" << path; TiXmlHandle docHandle(&doc); TiXmlNode *node=docHandle.FirstChild("ListBucketResult") .FirstChild("IsTruncated") .ToNode(); if (!node) break; node=node->NextSibling(); if (!node) break; while(node) { std::string name; if (strcmp(node->Value(), "Contents")==0) { name = node->FirstChild("Key")-> FirstChild()->ToText()->Value(); std::string size = node->FirstChild("Size")-> FirstChild()->ToText()->Value(); std::string mtime = node->FirstChild("LastModified")-> FirstChild()->ToText()->Value(); if (*name.rbegin()!='/') { //Yes, Virginia, there are directory-like-files in S3 s3_file_ptr fl(new s3_file()); fl->name_ = extract_leaf(name); fl->absolute_name_=derive(target->absolute_name_, fl->name_); fl->size_ = atoll(size.c_str()); fl->mtime_str_ = mtime; fl->parent_ = target; target->files_[fl->name_]=fl; } } else if (strcmp(node->Value(), "CommonPrefixes")==0) { name = node->FirstChild("Prefix")-> FirstChild()->ToText()->Value(); //Trim trailing '/' std::string trimmed_name=name.substr(0, name.size()-1); s3_directory_ptr dir(new s3_directory()); dir->name_ = extract_leaf(trimmed_name); dir->absolute_name_=derive(target->absolute_name_, dir->name_+"/"); dir->parent_ = target; target->subdirs_[dir->name_] = dir; } node=node->NextSibling(); if (!node) marker = name; } std::string is_trunc=docHandle.FirstChild("ListBucketResult") .FirstChild("IsTruncated").FirstChild().Text()->Value(); if (is_trunc=="false") break; } return target; } static std::string find_header(void *ptr, size_t size, size_t nmemb, const std::string &header_name) { std::string line(reinterpret_cast<char*>(ptr), size*nmemb); std::string line_raw(reinterpret_cast<char*>(ptr), size*nmemb); std::transform(line.begin(), line.end(), line.begin(), ::tolower); size_t pos=line.find(':'); if(pos!=std::string::npos) { std::string name=trim(line.substr(0, pos)); std::string val=trim(line_raw.substr(pos+1)); if (name==header_name) return val; } return ""; } static size_t find_mtime(void *ptr, size_t size, size_t nmemb, void *userdata) { file_desc *info=reinterpret_cast<file_desc*>(userdata); std::string mtime=find_header(ptr, size, nmemb, "x-amz-meta-last-modified"); if (!mtime.empty()) info->mtime_=atoll(mtime.c_str()); std::string ln=find_header(ptr, size, nmemb, "x-amz-meta-size"); if (!ln.empty()) info->raw_size_ = atoll(ln.c_str()); std::string ln2=find_header(ptr, size, nmemb, "content-length"); if (!ln2.empty()) info->remote_size_ = atoll(ln2.c_str()); std::string cmpr=find_header(ptr, size, nmemb, "x-amz-meta-compressed"); if (cmpr=="true") info->compressed_=true; std::string md=find_header(ptr, size, nmemb, "x-amz-meta-file-mode"); if (!md.empty()) info->mode_ = atoll(md.c_str()); return size*nmemb; } static size_t find_etag(void *ptr, size_t size, size_t nmemb, void *userdata) { std::string etag=find_header(ptr, size, nmemb, "etag"); if (!etag.empty()) reinterpret_cast<std::string*>(userdata)->assign(etag); return size*nmemb; } file_desc s3_connection::find_mtime_and_size(const s3_path &path) { file_desc result={0}; result.compressed_=false; result.mode_ = 0664; result.remote_size_=result.raw_size_=0; curl_ptr_t curl=conn_data_->get_curl(path.zone_, path.bucket_); prepare(curl, "HEAD", path); //last-modified checked(curl, curl_easy_setopt( curl.get(), CURLOPT_HEADERFUNCTION, &::find_mtime)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &result)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1)); checked(curl, curl_easy_perform(curl.get())); long code=404; checked(curl, curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &code)); result.found_=code!=404; if (result.raw_size_==0) result.raw_size_=result.remote_size_; return result; } class buf_data { const char *buf_; size_t total_size_; size_t written_; MD5_CTX md5_ctx; public: buf_data(const char *buf, size_t total_size) : buf_(buf), total_size_(total_size), written_() { MD5_Init(&md5_ctx); } std::string get_md5() { unsigned char md[MD5_DIGEST_LENGTH+1]={0}; MD5_Final(md, &md5_ctx); return tobinhex(md, MD5_DIGEST_LENGTH); } static size_t read_func(char *bufptr, size_t size, size_t nitems, void *userp) { return reinterpret_cast<buf_data*>(userp)->simple_read( bufptr, size*nitems); } size_t simple_read(char *bufptr, size_t size) { size_t tocopy = std::min(total_size_-written_, size); if (tocopy!=0) { memcpy(bufptr, buf_+written_, tocopy); MD5_Update(&md5_ctx, bufptr, tocopy); written_+=tocopy; } return tocopy; } }; std::string s3_connection::upload_data(const s3_path &path, const std::string &upload_id, int part_num, const char *data, size_t size, const header_map_t& opts) { assert(data); std::string etag; buf_data read_data(data, size); s3_path fin_path=path; if (!upload_id.empty()) { assert(part_num>0); fin_path.path_+=std::string("?partNumber=")+int_to_string(part_num)+"&uploadId="+upload_id; } curl_ptr_t curl=conn_data_->get_curl(path.zone_, path.bucket_); prepare(curl, "PUT", fin_path, opts); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, &find_etag)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &etag)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_UPLOAD, 1)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_INFILESIZE_LARGE, uint64_t(size))); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, &buf_data::read_func)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_READDATA, &read_data)); std::string result; checked(curl, curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &string_appender)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &result)); checked(curl, curl_easy_perform(curl.get())); check_for_errors(curl, result); if (!etag.empty() && strcasecmp(etag.c_str(), ("\""+read_data.get_md5()+"\"").c_str())) abort(); //Data corruption. This SHOULD NOT happen! if (!upload_id.empty()) { s3_path chk_path=path; chk_path.path_ += std::string("?uploadId=")+upload_id; std::string args="&part-number-marker="+int_to_string(part_num-1)+"&max-parts=1"; std::string ans=read_fully("GET", chk_path, args); if (!check_part(ans, part_num)) err(errWarn) << "Failed to get information about part "<< int_to_string(part_num) << " for upload " << path; } return etag; } bool s3_connection::check_part(const std::string &ans, int part_num) { TiXmlDocument doc; doc.Parse(ans.c_str()); if (doc.Error()) return false; TiXmlHandle docHandle(&doc); TiXmlNode *node=docHandle.FirstChild("ListPartsResult") .FirstChild("Part") .ToNode(); if (!node) return false; node=node->FirstChild("PartNumber"); if (!node) return false; std::string text=node->FirstChild()->ToText()->Value(); if (text!=int_to_string(part_num)) return false; return true; } std::string lexioprev(const std::string &cur) { std::string res=cur; for(auto iter=res.rbegin(); iter!=res.rend();++iter) { char ch=*iter; ch--; if (ch>=',') { *iter=ch; break; } else *iter='z'; } return res; } std::string s3_connection::initiate_multipart( const s3_path &path, const header_map_t &opts) { s3_path up_path =path; up_path.path_+="?uploads"; std::string list=read_fully("POST", up_path, "", opts); TiXmlDocument doc; doc.Parse(list.c_str()); if (doc.Error()) err(errWarn) << "Failed to initiate multipart to " << path; TiXmlHandle docHandle(&doc); TiXmlNode *node=docHandle.FirstChild("InitiateMultipartUploadResult") .FirstChild("UploadId") .FirstChild() .ToText(); if (!node) err(errWarn) << "Incorrect document format - no upload ID"; std::string uploadId=node->Value(); //Validate that the upload is created s3_path all_paths=path; all_paths.path_="/?uploads"; std::string cur_uploads=read_fully("GET", all_paths, "&prefix="+path.path_.substr(1)); TiXmlDocument cur_uploads_xml; cur_uploads_xml.Parse(cur_uploads.c_str()); if (cur_uploads_xml.Error()) err(errWarn) << "Failed to initiate multipart to " << path; TiXmlHandle curDocHandle(&cur_uploads_xml); TiXmlNode *cur_node=curDocHandle.FirstChild("ListMultipartUploadsResult") .FirstChild("Upload").ToNode(); if (!cur_node) err(errWarn) << "Incorrect document format - no upload ID"; while(cur_node) { TiXmlHandle upHandle(cur_node); std::string val=upHandle.FirstChild("UploadId").FirstChild().ToText()->ValueStr(); // std::cerr<<"Val "<< val<<std::endl; if (val==uploadId) return uploadId; cur_node=cur_node->NextSibling(); } err(errWarn) << "Can't find an active upload with id="<<uploadId; } std::string s3_connection::complete_multipart(const s3_path &path, const std::string &upload_id, const std::vector<std::string> &etags) { std::string data="<CompleteMultipartUpload>"; for(size_t f=0;f<etags.size();++f) { data.append("<Part>\n"); data.append(" <PartNumber>") .append(int_to_string(f+1)) .append("</PartNumber>\n"); data.append(" <ETag>") .append(etags.at(f)) .append("</ETag>\n"); data.append("</Part>\n"); } data.append("</CompleteMultipartUpload>"); s3_path up_path=path; up_path.path_+="?uploadId="+upload_id; curl_ptr_t curl=conn_data_->get_curl(path.zone_, path.bucket_); prepare(curl, "POST", up_path); buf_data data_params(data.c_str(), data.size()); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_UPLOAD, 1)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_INFILESIZE_LARGE, uint64_t(data.size()))); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, &buf_data::read_func)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data_params)); std::string read_data; checked(curl, curl_easy_setopt( curl.get(), CURLOPT_WRITEFUNCTION, &string_appender)); checked(curl, curl_easy_setopt( curl.get(), CURLOPT_WRITEDATA, &read_data)); checked(curl, curl_easy_perform(curl.get())); check_for_errors(curl, read_data); VLOG(2) << "Completed multipart of " << path; return read_data; } class write_data { char *buf_; size_t total_size_; size_t written_; public: write_data(char *buf, size_t total_size) : buf_(buf), total_size_(total_size), written_() { } size_t written() const { return written_; } static size_t write_func(const char *bufptr, size_t size, size_t nitems, void *userp) { return reinterpret_cast<write_data*>(userp)->simple_write( bufptr, size*nitems); } size_t simple_write(const char *bufptr, size_t size) { size_t tocopy = std::min(total_size_-written_, size); if (tocopy!=0) { memcpy(buf_+written_, bufptr, tocopy); written_+=tocopy; } return tocopy; } }; void s3_connection::download_data(const s3_path &path, uint64_t offset, char *data, size_t size, const header_map_t& opts) { curl_ptr_t curl=conn_data_->get_curl(path.zone_, path.bucket_); prepare(curl, "GET", path, opts); checked(curl, curl_easy_setopt( curl.get(), CURLOPT_INFILESIZE_LARGE, uint64_t(size))); std::string range=int_to_string(offset)+"-"+ int_to_string(offset+size-1); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_RANGE, range.c_str())); write_data wd(data, size); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, &write_data::write_func)); checked(curl, curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &wd)); checked(curl, curl_easy_perform(curl.get())); check_for_errors(curl, std::string(data, std::min(wd.written(), size_t(1024)))); if (wd.written()!=size) err(errWarn) << "Size of a segment at offset " << offset << " of "<< path << " is incorrect."; } std::string s3_connection::find_region(const std::string &bucket) { s3_path path; path.zone_ = "s3"; path.bucket_ = bucket; path.path_ = "/?location"; std::string reg_data=read_fully("GET", path); TiXmlDocument doc; doc.Parse(reg_data.c_str()); if (doc.Error()) err(errWarn) << "Can't find region, bad document received. " << doc.ErrorDesc(); TiXmlHandle docHandle(&doc); TiXmlNode *n1=docHandle.FirstChild("LocationConstraint").ToNode(); if (!n1) err(errWarn) << "Incorrect document format - no location id"; TiXmlNode *node=docHandle.FirstChild("LocationConstraint") .FirstChild() .ToText(); if (!node) return "s3"; //Default location return std::string("s3-")+node->Value(); } void s3_connection::set_acl(const s3_path &path, const std::string &acl) { header_map_t hm; hm["x-amz-acl"]="public-read"; s3_path p1=path; p1.path_+="?acl"; std::string res=read_fully("PUT", p1, "", hm); //Result can be ignored - it's the exit code that is important. }
28.88656
120
0.684424
[ "vector", "transform" ]
5fd3d4a08943f42a3abc65cc9f38e8164eec21e3
5,228
cpp
C++
components/loopp/src/drivers/BLEScannerDriver.cpp
PleXone2019/esp32-beacon-scanner
83944402a48a47327bde1ec173160275fb3db6e3
[ "MIT" ]
110
2017-09-05T03:28:42.000Z
2022-03-13T10:06:36.000Z
components/loopp/src/drivers/BLEScannerDriver.cpp
PleXone2019/esp32-beacon-scanner
83944402a48a47327bde1ec173160275fb3db6e3
[ "MIT" ]
6
2017-12-14T22:01:46.000Z
2019-05-31T15:16:26.000Z
components/loopp/src/drivers/BLEScannerDriver.cpp
PleXone2019/esp32-beacon-scanner
83944402a48a47327bde1ec173160275fb3db6e3
[ "MIT" ]
21
2017-09-05T03:29:00.000Z
2022-03-09T13:28:59.000Z
// Copyright (C) 2018 Rob Caelers <rob.caelers@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #include "loopp/drivers/BLEScannerDriver.hpp" #include <string> #include <vector> #include <algorithm> #include "esp_log.h" #include "driver/gpio.h" #include "loopp/ble/AdvertisementDecoder.hpp" #include "loopp/drivers/DriverRegistry.hpp" #include "loopp/utils/memlog.hpp" using namespace loopp::drivers; // LOOPP_REGISTER_DRIVER("ble-scanner", BLEScannerDriver); using json = nlohmann::json; static const char *tag = "BLE-SCANNER"; BLEScannerDriver::BLEScannerDriver(loopp::drivers::DriverContext context, const nlohmann::json &config) : loop(context.get_loop()) , mqtt(context.get_mqtt()) , ble_scanner(loopp::ble::BLEScanner::instance()) { topic_scan = context.get_topic_root() + "scan"; auto it = config.find("feedback_pin"); if (it != config.end()) { pin_no = static_cast<gpio_num_t>(*it); feedback = true; gpio_pad_select_gpio(pin_no); gpio_set_direction(pin_no, GPIO_MODE_OUTPUT); } it = config.find("scan_type"); if (it != config.end()) { std::string type = *it; if (type == "active") { ble_scanner.set_scan_type(loopp::ble::BLEScanner::ScanType::Active); } else if (type == "passive") { ble_scanner.set_scan_type(loopp::ble::BLEScanner::ScanType::Passive); } else { throw std::runtime_error("invalid scan_type value: " + type); } } it = config.find("scan_interval"); if (it != config.end()) { uint16_t interval = *it; ble_scanner.set_scan_interval(interval); } it = config.find("scan_window"); if (it != config.end()) { uint16_t window = *it; ble_scanner.set_scan_window(window); } } BLEScannerDriver::~BLEScannerDriver() { } // https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c std::string BLEScannerDriver::base64_encode(const std::string &in) { std::string out; int val = 0, valb = -6; for (char c : in) { val = (val << 8) + c; valb += 8; while (valb >= 0) { out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val >> valb) & 0x3F]); valb -= 6; } } if (valb > -6) { out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val << 8) >> (valb + 8)) & 0x3F]); } while ((out.size() % 4) != 0u) { out.push_back('='); } return out; } void BLEScannerDriver::on_ble_scanner_scan_result(const loopp::ble::BLEScanner::ScanResult &result) { if (feedback) { static int led_state = 0; led_state ^= 1; gpio_set_level(pin_no, led_state); } scan_results.push_back(result); } void BLEScannerDriver::on_scan_timer() { loopp::utils::memlog("BLEScannerDriver::on_scan_timer entry"); try { json j; if (mqtt && mqtt->connected().get() && scan_results.size() > 0) { for (auto r : scan_results) { json jb; jb["mac"] = r.bda_as_string(); jb["bda"] = base64_encode(std::string(reinterpret_cast<char *>(r.bda), sizeof(r.bda))); jb["rssi"] = r.rssi; jb["adv_data"] = base64_encode(r.adv_data); decoder.decode(r.adv_data, jb); j.push_back(jb); } mqtt->publish(topic_scan, j.dump()); } } catch (std::exception &e) { ESP_LOGE(tag, "on_scan_timer. Exception: %s", e.what()); } scan_results.clear(); } void BLEScannerDriver::start() { auto self = shared_from_this(); scan_result_signal_connection = ble_scanner.scan_result_signal().connect( loopp::core::bind_loop(loop, [this, self](loopp::ble::BLEScanner::ScanResult scan_result) { on_ble_scanner_scan_result(scan_result); })); scan_timer = loop->add_periodic_timer(std::chrono::milliseconds(1000), [this, self]() { on_scan_timer(); }); ble_scanner.start(); } void BLEScannerDriver::stop() { loop->cancel_timer(scan_timer); scan_timer = 0; ble_scanner.stop(); scan_result_signal_connection.disconnect(); }
28.107527
141
0.652257
[ "vector" ]
5fd496c4e174aa62e15715dd00a2d2d983bf7715
75,935
cpp
C++
OpenNN/opennn/adaptive_moment_estimation.cpp
wagnrd/Pong
0c50b22e0805b2ae19ff07d25859a6358217b377
[ "MIT" ]
4
2019-03-06T16:53:27.000Z
2021-07-28T03:05:08.000Z
OpenNN/opennn/adaptive_moment_estimation.cpp
wagnrd/Pong
0c50b22e0805b2ae19ff07d25859a6358217b377
[ "MIT" ]
1
2021-02-11T17:10:29.000Z
2021-02-11T20:54:03.000Z
OpenNN/opennn/adaptive_moment_estimation.cpp
wagnrd/Pong
0c50b22e0805b2ae19ff07d25859a6358217b377
[ "MIT" ]
null
null
null
/****************************************************************************************************************/ /* */ /* OpenNN: Open Neural Networks Library */ /* www.opennn.net */ /* */ /* A D A P T I V E M O M E N T E S T I M A T I O N */ /* */ /* Carlos Barranquero */ /* Artificial Intelligence Techniques SL */ /* carlosbarranquero@artelnics.com */ /* */ /****************************************************************************************************************/ // Open NN includes #include "adaptive_moment_estimation.h" namespace OpenNN { /// Default constructor. /// It creates a adaptive moment estimation optimization algorithm not associated to any loss index object. /// It also initializes the class members to their default values. AdaptiveMomentEstimation::AdaptiveMomentEstimation() :OptimizationAlgorithm() { set_default(); } /// Loss index constructor. /// It creates a adaptive moment estimation optimization algorithm associated to a loss index. /// It also initializes the class members to their default values. /// @param new_loss_index_pointer Pointer to a loss index object. AdaptiveMomentEstimation::AdaptiveMomentEstimation(LossIndex* new_loss_index_pointer) : OptimizationAlgorithm(new_loss_index_pointer) { set_default(); } // XML CONSTRUCTOR /// XML constructor. /// It creates a gradient descent optimization algorithm not associated to any loss index object. /// It also loads the class members from a XML document. /// @param document TinyXML document with the members of a gradient descent object. AdaptiveMomentEstimation::AdaptiveMomentEstimation(const tinyxml2::XMLDocument& document) : OptimizationAlgorithm(document) { set_default(); from_XML(document); } // DESTRUCTOR /// Destructor. AdaptiveMomentEstimation::~AdaptiveMomentEstimation() { } // METHODS /// Returns the initial learning rate. const double& AdaptiveMomentEstimation::get_initial_learning_rate() const { return(initial_learning_rate); } /// Returns beta 1. const double& AdaptiveMomentEstimation::get_beta_1() const { return(beta_1); } /// Returns beta 2. const double& AdaptiveMomentEstimation::get_beta_2() const { return(beta_2); } /// Returns epsilon. const double& AdaptiveMomentEstimation::get_epsilon() const { return(epsilon); } /// Returns the minimum value for the norm of the parameters vector at wich a warning message is /// written to the screen. const double& AdaptiveMomentEstimation::get_warning_parameters_norm() const { return(warning_parameters_norm); } /// Returns the minimum value for the norm of the gradient vector at wich a warning message is written /// to the screen. const double& AdaptiveMomentEstimation::get_warning_gradient_norm() const { return(warning_gradient_norm); } /// Returns the value for the norm of the parameters vector at wich an error message is /// written to the screen and the program exits. const double& AdaptiveMomentEstimation::get_error_parameters_norm() const { return(error_parameters_norm); } /// Returns the value for the norm of the gradient vector at wich an error message is written /// to the screen and the program exits. const double& AdaptiveMomentEstimation::get_error_gradient_norm() const { return(error_gradient_norm); } /// Returns the minimum norm of the parameter increment vector used as a stopping criteria when training. const double& AdaptiveMomentEstimation::get_minimum_parameters_increment_norm() const { return(minimum_parameters_increment_norm); } /// Returns the minimum loss improvement during training. const double& AdaptiveMomentEstimation::get_minimum_loss_increase() const { return(minimum_loss_decrease); } /// Returns the goal value for the loss. /// This is used as a stopping criterion when training a multilayer perceptron const double& AdaptiveMomentEstimation::get_loss_goal() const { return(loss_goal); } /// Returns the goal value for the norm of the error function gradient. /// This is used as a stopping criterion when training a multilayer perceptron const double& AdaptiveMomentEstimation::get_gradient_norm_goal() const { return(gradient_norm_goal); } /// Returns the maximum number of selection failures during the training process. const size_t& AdaptiveMomentEstimation::get_maximum_selection_failures() const { return(maximum_selection_failures); } /// Returns the maximum training time. const double& AdaptiveMomentEstimation::get_maximum_time() const { return(maximum_time); } /// Returns true if the final model will be the neural network with the minimum selection error, false otherwise. const bool& AdaptiveMomentEstimation::get_return_minimum_selection_error_neural_network() const { return(return_minimum_selection_error_neural_network); } /// Returns true if the selection loss decrease stopping criteria has to be taken in account, false otherwise. const bool& AdaptiveMomentEstimation::get_apply_early_stopping() const { return(apply_early_stopping); } /// Returns true if the parameters history matrix is to be reserved, and false otherwise. const bool& AdaptiveMomentEstimation::get_reserve_parameters_history() const { return(reserve_parameters_history); } /// Returns true if the parameters norm history vector is to be reserved, and false otherwise. const bool& AdaptiveMomentEstimation::get_reserve_parameters_norm_history() const { return(reserve_parameters_norm_history); } /// Returns true if the loss history vector is to be reserved, and false otherwise. const bool& AdaptiveMomentEstimation::get_reserve_loss_history() const { return(reserve_loss_history); } /// Returns true if the gradient history vector of vectors is to be reserved, and false otherwise. const bool& AdaptiveMomentEstimation::get_reserve_gradient_history() const { return(reserve_gradient_history); } /// Returns true if the gradient norm history vector is to be reserved, and false otherwise. const bool& AdaptiveMomentEstimation::get_reserve_gradient_norm_history() const { return(reserve_gradient_norm_history); } /// Returns true if the training rate history vector is to be reserved, and false otherwise. const bool& AdaptiveMomentEstimation::get_reserve_learning_rate_history() const { return(reserve_learning_rate_history); } /// Returns true if the elapsed time history vector is to be reserved, and false otherwise. const bool& AdaptiveMomentEstimation::get_reserve_elapsed_time_history() const { return(reserve_elapsed_time_history); } /// Returns true if the selection loss history vector is to be reserved, and false otherwise. const bool& AdaptiveMomentEstimation::get_reserve_selection_error_history() const { return(reserve_selection_error_history); } /// Sets a pointer to a loss index object to be associated to the gradient descent object. /// It also sets that loss index to the learning rate algorithm. /// @param new_loss_index_pointer Pointer to a loss index object. void AdaptiveMomentEstimation::set_loss_index_pointer(LossIndex* new_loss_index_pointer) { loss_index_pointer = new_loss_index_pointer; } void AdaptiveMomentEstimation::set_default() { // TRAINING OPERATORS initial_learning_rate = 0.001; initial_decay = 0.0; beta_1 = 0.9; beta_2 = 0.999; epsilon = 1e-8; // TRAINING PARAMETERS warning_parameters_norm = 1.0e6; warning_gradient_norm = 1.0e6; error_parameters_norm = 1.0e9; error_gradient_norm = 1.0e9; // STOPPING CRITERIA minimum_parameters_increment_norm = 0.0; minimum_loss_decrease = 0.0; loss_goal = -numeric_limits<double>::max(); gradient_norm_goal = 0.0; maximum_selection_failures = 1000000; maximum_time = 1000.0; maximum_epochs_number = 10000; return_minimum_selection_error_neural_network = false; apply_early_stopping = true; // TRAINING HISTORY reserve_parameters_history = false; reserve_parameters_norm_history = false; reserve_loss_history = true; reserve_gradient_history = false; reserve_gradient_norm_history = false; reserve_selection_error_history = false; reserve_learning_rate_history = false; reserve_elapsed_time_history = false; // UTILITIES display = true; display_period = 5; } /// Makes the training history of all variables to reseved or not in memory: /// <ul> /// <li> Parameters. /// <li> Parameters norm. /// <li> Loss. /// <li> Gradient. /// <li> Gradient norm. /// <li> Selection loss. /// <li> Training direction. /// <li> Training direction norm. /// <li> Training rate. /// </ul> /// @param new_reserve_all_training_history True if the training history of all variables is to be reserved, false otherwise. void AdaptiveMomentEstimation::set_reserve_all_training_history(const bool& new_reserve_all_training_history) { // Multilayer perceptron reserve_parameters_history = new_reserve_all_training_history; reserve_parameters_norm_history = new_reserve_all_training_history; // Loss index reserve_loss_history = new_reserve_all_training_history; reserve_gradient_history = new_reserve_all_training_history; reserve_gradient_norm_history = new_reserve_all_training_history; reserve_selection_error_history = new_reserve_all_training_history; // Optimization algorithm reserve_learning_rate_history = new_reserve_all_training_history; reserve_elapsed_time_history = new_reserve_all_training_history; } /// Sets a new learning rate. /// @param new_learning_rate. void AdaptiveMomentEstimation::set_initial_learning_rate(const double& new_learning_rate) { initial_learning_rate= new_learning_rate; } /// Sets beta 1 generally close to 1. /// @param new_beta_1. void AdaptiveMomentEstimation::set_beta_1(const double& new_beta_1) { beta_1= new_beta_1; } /// Sets beta 2 generally close to 1. /// @param new_beta_2. void AdaptiveMomentEstimation::set_beta_2(const double& new_beta_2) { beta_2= new_beta_2; } /// Sets epsilon. /// @param epsilon. void AdaptiveMomentEstimation::set_epsilon(const double& new_epsilon) { epsilon= new_epsilon; } /// Sets a new value for the parameters vector norm at which a warning message is written to the /// screen. /// @param new_warning_parameters_norm Warning norm of parameters vector value. void AdaptiveMomentEstimation::set_warning_parameters_norm(const double& new_warning_parameters_norm) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_warning_parameters_norm < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_warning_parameters_norm(const double&) method.\n" << "Warning parameters norm must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set warning parameters norm warning_parameters_norm = new_warning_parameters_norm; } /// Sets a new value for the gradient vector norm at which /// a warning message is written to the screen. /// @param new_warning_gradient_norm Warning norm of gradient vector value. void AdaptiveMomentEstimation::set_warning_gradient_norm(const double& new_warning_gradient_norm) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_warning_gradient_norm < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_warning_gradient_norm(const double&) method.\n" << "Warning gradient norm must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set warning gradient norm warning_gradient_norm = new_warning_gradient_norm; } /// Sets a new value for the parameters vector norm at which an error message is written to the /// screen and the program exits. /// @param new_error_parameters_norm Error norm of parameters vector value. void AdaptiveMomentEstimation::set_error_parameters_norm(const double& new_error_parameters_norm) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_error_parameters_norm < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_error_parameters_norm(const double&) method.\n" << "Error parameters norm must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set error parameters norm error_parameters_norm = new_error_parameters_norm; } /// Sets a new value for the gradient vector norm at which an error message is written to the screen /// and the program exits. /// @param new_error_gradient_norm Error norm of gradient vector value. void AdaptiveMomentEstimation::set_error_gradient_norm(const double& new_error_gradient_norm) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_error_gradient_norm < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_error_gradient_norm(const double&) method.\n" << "Error gradient norm must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set error gradient norm error_gradient_norm = new_error_gradient_norm; } /// Set the a new maximum for the epochs number. /// @param new_maximum_epochs number New maximum epochs number. void AdaptiveMomentEstimation:: set_maximum_epochs_number(const size_t& new_maximum_epochs_number) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_maximum_epochs_number < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_maximum_epochs_number(const double&) method.\n" << "Maximum epochs number must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set maximum_epochs number maximum_epochs_number = new_maximum_epochs_number; } /// Sets a new value for the minimum parameters increment norm stopping criterion. /// @param new_minimum_parameters_increment_norm Value of norm of parameters increment norm used to stop training. void AdaptiveMomentEstimation::set_minimum_parameters_increment_norm(const double& new_minimum_parameters_increment_norm) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_minimum_parameters_increment_norm < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void new_minimum_parameters_increment_norm(const double&) method.\n" << "Minimum parameters increment norm must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set error training rate minimum_parameters_increment_norm = new_minimum_parameters_increment_norm; } /// Sets a new minimum loss improvement during training. /// @param new_minimum_loss_increase Minimum improvement in the loss between two iterations. void AdaptiveMomentEstimation::set_minimum_loss_increase(const double& new_minimum_loss_increase) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_minimum_loss_increase < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_minimum_loss_increase(const double&) method.\n" << "Minimum loss improvement must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set minimum loss improvement minimum_loss_decrease = new_minimum_loss_increase; } /// Sets a new goal value for the loss. /// This is used as a stopping criterion when training a multilayer perceptron /// @param new_loss_goal Goal value for the loss. void AdaptiveMomentEstimation::set_loss_goal(const double& new_loss_goal) { loss_goal = new_loss_goal; } /// Sets a new the goal value for the norm of the error function gradient. /// This is used as a stopping criterion when training a multilayer perceptron /// @param new_gradient_norm_goal Goal value for the norm of the error function gradient. void AdaptiveMomentEstimation::set_gradient_norm_goal(const double& new_gradient_norm_goal) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_gradient_norm_goal < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_gradient_norm_goal(const double&) method.\n" << "Gradient norm goal must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set gradient norm goal gradient_norm_goal = new_gradient_norm_goal; } /// Sets a new maximum number of selection failures. /// @param new_maximum_selection_failures Maximum number of iterations in which the selection evalutation decreases. void AdaptiveMomentEstimation::set_maximum_selection_error_increases(const size_t& new_maximum_selection_failures) { maximum_selection_failures = new_maximum_selection_failures; } /// Sets a new maximum training time. /// @param new_maximum_time Maximum training time. void AdaptiveMomentEstimation::set_maximum_time(const double& new_maximum_time) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_maximum_time < 0.0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_maximum_time(const double&) method.\n" << "Maximum time must be equal or greater than 0.\n"; throw logic_error(buffer.str()); } #endif // Set maximum time maximum_time = new_maximum_time; } /// Makes the minimum selection error neural network of all the iterations to be returned or not. /// @param new_return_minimum_selection_error_neural_network True if the final model will be the neural network with the minimum selection error, false otherwise. void AdaptiveMomentEstimation::set_return_minimum_selection_error_neural_network(const bool& new_return_minimum_selection_error_neural_network) { return_minimum_selection_error_neural_network = new_return_minimum_selection_error_neural_network; } /// Makes the selection loss decrease stopping criteria has to be taken in account or not. /// @param new_apply_early_stopping True if the selection loss decrease stopping criteria has to be taken in account, false otherwise. void AdaptiveMomentEstimation::set_apply_early_stopping(const bool& new_apply_early_stopping) { apply_early_stopping = new_apply_early_stopping; } /// Makes the parameters history vector of vectors to be reseved or not in memory. /// @param new_reserve_parameters_history True if the parameters history vector of vectors is to be reserved, false otherwise. void AdaptiveMomentEstimation::set_reserve_parameters_history(const bool& new_reserve_parameters_history) { reserve_parameters_history = new_reserve_parameters_history; } /// Makes the parameters norm history vector to be reseved or not in memory. /// @param new_reserve_parameters_norm_history True if the parameters norm history vector is to be reserved, false otherwise. void AdaptiveMomentEstimation::set_reserve_parameters_norm_history(const bool& new_reserve_parameters_norm_history) { reserve_parameters_norm_history = new_reserve_parameters_norm_history; } /// Makes the loss history vector to be reseved or not in memory. /// @param new_reserve_loss_history True if the loss history vector is to be reserved, false otherwise. void AdaptiveMomentEstimation::set_reserve_loss_history(const bool& new_reserve_loss_history) { reserve_loss_history = new_reserve_loss_history; } /// Makes the gradient history vector of vectors to be reseved or not in memory. /// @param new_reserve_gradient_history True if the gradient history matrix is to be reserved, false otherwise. void AdaptiveMomentEstimation::set_reserve_gradient_history(const bool& new_reserve_gradient_history) { reserve_gradient_history = new_reserve_gradient_history; } /// Makes the gradient norm history vector to be reseved or not in memory. /// @param new_reserve_gradient_norm_history True if the gradient norm history matrix is to be reserved, false /// otherwise. void AdaptiveMomentEstimation::set_reserve_gradient_norm_history(const bool& new_reserve_gradient_norm_history) { reserve_gradient_norm_history = new_reserve_gradient_norm_history; } /// Makes the learning_rate history vector to be reseved or not in memory. /// @param new_reserve_learning_rate_history True if the training rate history vector is to be reserved, false /// otherwise. void AdaptiveMomentEstimation::set_reserve_learning_rate_history(const bool& new_reserve_learning_rate_history) { reserve_learning_rate_history = new_reserve_learning_rate_history; } /// Makes the elapsed time over the iterations to be reseved or not in memory. This is a vector. /// @param new_reserve_elapsed_time_history True if the elapsed time history vector is to be reserved, false /// otherwise. void AdaptiveMomentEstimation::set_reserve_elapsed_time_history(const bool& new_reserve_elapsed_time_history) { reserve_elapsed_time_history = new_reserve_elapsed_time_history; } /// Makes the selection loss history to be reserved or not in memory. /// This is a vector. /// @param new_reserve_selection_error_history True if the selection loss history is to be reserved, false otherwise. void AdaptiveMomentEstimation::set_reserve_selection_error_history(const bool& new_reserve_selection_error_history) { reserve_selection_error_history = new_reserve_selection_error_history; } /// Sets a new number of iterations between the training showing progress. /// @param new_display_period /// Number of iterations between the training showing progress. void AdaptiveMomentEstimation::set_display_period(const size_t& new_display_period) { // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ if(new_display_period <= 0) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void set_display_period(const double&) method.\n" << "First training rate must be greater than 0.\n"; throw logic_error(buffer.str()); } #endif display_period = new_display_period; } string AdaptiveMomentEstimation::AdaptiveMomentEstimationResults::object_to_string() const { ostringstream buffer; // Parameters history if(!parameters_history.empty()) { if(!parameters_history[0].empty()) { buffer << "% Parameters history:\n" << parameters_history << "\n"; } } // Parameters norm history if(!parameters_norm_history.empty()) { buffer << "% Parameters norm history:\n" << parameters_norm_history << "\n"; } // Loss history if(!loss_history.empty()) { buffer << "% Loss history:\n" << loss_history << "\n"; } // Selection loss history if(!selection_error_history.empty()) { buffer << "% Selection loss history:\n" << selection_error_history << "\n"; } // Gradient history if(!gradient_history.empty()) { if(!gradient_history[0].empty()) { buffer << "% Gradient history:\n" << gradient_history << "\n"; } } // Gradient norm history if(!gradient_norm_history.empty()) { buffer << "% Gradient norm history:\n" << gradient_norm_history << "\n"; } // Training rate history if(!learning_rate_history.empty()) { buffer << "% learning rate history:\n" << learning_rate_history << "\n"; } // Elapsed time history if(!elapsed_time_history.empty()) { buffer << "% Elapsed time history:\n" << elapsed_time_history << "\n"; } // Stopping criterion if(!stopping_criterion.empty()) { buffer << "% Stopping criterion:\n" << stopping_criterion << "\n"; } return(buffer.str()); } Matrix<string> AdaptiveMomentEstimation::AdaptiveMomentEstimationResults::write_final_results(const int& precision) const { ostringstream buffer; Vector<string> names; Vector<string> values; // Final parameters norm names.push_back("Final parameters norm"); buffer.str(""); buffer << setprecision(precision) << final_parameters_norm; values.push_back(buffer.str()); // Final loss names.push_back("Final training error"); buffer.str(""); buffer << setprecision(precision) << final_loss; values.push_back(buffer.str()); names.push_back("Final selection error"); buffer.str(""); buffer << setprecision(precision) << final_selection_error; values.push_back(buffer.str()); // Final gradient norm names.push_back("Final gradient norm"); buffer.str(""); buffer << setprecision(precision) << final_gradient_norm; values.push_back(buffer.str()); // Iterations number names.push_back("Iterations number"); buffer.str(""); buffer << iterations_number; values.push_back(buffer.str()); // Elapsed time names.push_back("Elapsed time"); buffer.str(""); buffer << write_elapsed_time(elapsed_time); values.push_back(buffer.str()); // Stopping criteria names.push_back("Stopping criterion"); values.push_back(write_stopping_condition()); const size_t rows_number = names.size(); const size_t columns_number = 2; Matrix<string> final_results(rows_number, columns_number); final_results.set_column(0, names, "name"); final_results.set_column(1, values, "value"); return(final_results); } /// Resizes the training history variables which are to be reserved by the optimization algorithm. /// @param new_size Size of training history variables. void AdaptiveMomentEstimation::AdaptiveMomentEstimationResults::resize_training_history(const size_t& new_size) { // Control sentence(if debug) if(adaptive_moment_estimation_pointer->get_reserve_parameters_history()) { parameters_history.resize(new_size); } if(adaptive_moment_estimation_pointer->get_reserve_parameters_norm_history()) { parameters_norm_history.resize(new_size); } if(adaptive_moment_estimation_pointer->get_reserve_loss_history()) { loss_history.resize(new_size); } if(adaptive_moment_estimation_pointer->get_reserve_selection_error_history()) { selection_error_history.resize(new_size); } if(adaptive_moment_estimation_pointer->get_reserve_gradient_history()) { gradient_history.resize(new_size); } if(adaptive_moment_estimation_pointer->get_reserve_gradient_norm_history()) { gradient_norm_history.resize(new_size); } if(adaptive_moment_estimation_pointer->get_reserve_learning_rate_history()) { learning_rate_history.resize(new_size); } if(adaptive_moment_estimation_pointer->get_reserve_elapsed_time_history()) { elapsed_time_history.resize(new_size); } } /// Trains a neural network with an associated loss index, /// according to the gradient descent method. /// Training occurs according to the training parameters and stopping criteria. /// It returns a results structure with the history and the final values of the reserved variables. AdaptiveMomentEstimation::AdaptiveMomentEstimationResults* AdaptiveMomentEstimation::perform_training() { AdaptiveMomentEstimationResults* results_pointer = new AdaptiveMomentEstimationResults(this); // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ check(); #endif // Start training if(display) cout << "Training with adaptive moment estimator \"Adam\" ...\n"; // Data set stuff DataSet* data_set_pointer = loss_index_pointer->get_data_set_pointer(); const Instances& instances = data_set_pointer->get_instances(); const size_t selection_instances_number = instances.get_selection_instances_number(); // Neural network stuff NeuralNetwork* neural_network_pointer = loss_index_pointer->get_neural_network_pointer(); const size_t parameters_number = neural_network_pointer->get_parameters_number(); Vector<double> parameters(parameters_number); Vector<double> parameters_increment(parameters_number); double parameters_norm = 0.0; // Loss index stuff LossIndex::FirstOrderLoss first_order_loss(parameters_number); double training_error = 0.0; double old_training_error = 0.0; double selection_error = 0.0; double old_selection_error = 0.0; double loss = 0.0; double gradient_norm = 0.0; // Optimization algorithm stuff double learning_rate = initial_learning_rate; size_t selection_failures = 0; Vector<double> minimum_selection_error_parameters(parameters_number); double minimum_selection_error = numeric_limits<double>::max(); bool stop_training = false; time_t beginning_time, current_time; time(&beginning_time); double elapsed_time = 0.0; results_pointer->resize_training_history(maximum_epochs_number + 1); size_t learning_rate_iteration = 1; Vector<double>gradient_incremet(parameters_number,0.0); Vector<double>square_gradient_increment(parameters_number,0.0); Vector<double>last_square_gradient_increment(parameters_number,0.0); Vector<double>last_gradient_incremet(parameters_number,0.0); Vector<double>gradient_correction(parameters_number); Vector<double>gradient_square_correction(parameters_number); // Main loop for(size_t epoch = 0; epoch < epochs_number; epoch++) { const Vector< Vector<size_t> > training_batches = instances.get_training_batches(training_batch_size); const size_t batches_number = training_batches.size(); parameters = neural_network_pointer->get_parameters(); parameters_norm = parameters.calculate_L2_norm(); if(display && parameters_norm >= warning_parameters_norm) cout << "OpenNN Warning: Parameters norm is " << parameters_norm << ".\n"; loss = 0.0; for(size_t iteration = 0; iteration < batches_number; iteration++) { //Loss first_order_loss = loss_index_pointer->calculate_batch_first_order_loss(training_batches[iteration]); loss += first_order_loss.loss; // Gradient gradient_norm = first_order_loss.gradient.calculate_L2_norm(); if(display && gradient_norm >= warning_gradient_norm) cout << "OpenNN Warning: Gradient norm is " << gradient_norm << ".\n"; initial_decay > 0.0 ? learning_rate = initial_learning_rate * (1.0 / (1.0 + learning_rate_iteration*initial_decay)) : initial_learning_rate ; // Training parameters = neural_network_pointer->get_parameters(); gradient_incremet = last_gradient_incremet*beta_1 + first_order_loss.gradient*(1 - beta_1); square_gradient_increment = last_square_gradient_increment*beta_2 + first_order_loss.gradient*first_order_loss.gradient*(1 - beta_2); last_gradient_incremet = gradient_incremet; last_square_gradient_increment = square_gradient_increment; gradient_correction = gradient_incremet /(1 - pow(beta_1, learning_rate_iteration + 1)); gradient_square_correction = square_gradient_increment / (1 - pow(beta_2, learning_rate_iteration + 1)); parameters_increment = parameters - gradient_correction*learning_rate/(gradient_square_correction.calculate_square_root_elements() + epsilon); neural_network_pointer->set_parameters(parameters_increment); learning_rate_iteration++; } // Loss training_error = loss/static_cast<double>(batches_number); if(selection_instances_number > 0) selection_error = loss_index_pointer->calculate_selection_error(); if(epoch == 0) { minimum_selection_error = selection_error; minimum_selection_error_parameters = neural_network_pointer->get_parameters(); } else if(epoch != 0 && selection_error > old_selection_error) { selection_failures++; } else if(selection_error <= minimum_selection_error) { minimum_selection_error = selection_error; minimum_selection_error_parameters = neural_network_pointer->get_parameters(); } // Elapsed time time(&current_time); elapsed_time = difftime(current_time, beginning_time); // Training history neural network if(reserve_parameters_history) results_pointer->parameters_history[epoch] = parameters; if(reserve_parameters_norm_history) results_pointer->parameters_norm_history[epoch] = parameters_norm; // Training history loss index if(reserve_loss_history) results_pointer->loss_history[epoch] = training_error; if(reserve_gradient_norm_history) results_pointer->gradient_norm_history[epoch] = gradient_norm; if(reserve_selection_error_history) results_pointer->selection_error_history[epoch] = selection_error; // Training history optimization algorithm if(reserve_elapsed_time_history) results_pointer->elapsed_time_history[epoch] = elapsed_time; // Stopping Criteria if(selection_failures >= maximum_selection_failures && apply_early_stopping) { if(display) { cout << "Epoch " << epoch << ", iteration " << epoch << ": Maximum selection failures reached.\n" << "Selection failures: " << selection_failures << endl; } stop_training = true; results_pointer->stopping_condition = MaximumSelectionLossIncreases; } else if(epoch == maximum_epochs_number) { if(display) { cout << "Epoch " << epoch << ": Maximum number of iterations reached.\n"; } stop_training = true; results_pointer->stopping_condition = MaximumIterationsNumber; } else if(elapsed_time >= maximum_time) { if(display) { cout << "Epoch " << epoch << ": Maximum training time reached.\n"; } stop_training = true; results_pointer->stopping_condition = MaximumTime; } else if(training_error <= loss_goal) { if(display) { cout << "Epoch " << epoch << ": Loss goal reached.\n"; } stop_training = true; results_pointer->stopping_condition = LossGoal; } if(epoch != 0 && epoch % save_period == 0) { neural_network_pointer->save(neural_network_file_name); } if(stop_training) { if(display) { cout << "Parameters norm: " << parameters_norm << "\n" << "Training loss: " << training_error << "\n" << "Batch size: " << training_batch_size << "\n" << "Gradient norm: " << gradient_norm << "\n" << loss_index_pointer->write_information() << "Learning rate: " << learning_rate << "\n" << "Elapsed time: " << write_elapsed_time(elapsed_time)<<"\n" << "Selection error: " << selection_error << endl; } results_pointer->resize_training_history(1+epoch); results_pointer->final_parameters = parameters; results_pointer->final_parameters_norm = parameters_norm; results_pointer->final_loss = training_error; results_pointer->final_selection_error = selection_error; results_pointer->final_gradient_norm = gradient_norm; results_pointer->elapsed_time = elapsed_time; results_pointer->iterations_number = epoch; break; } else if(display && epoch % display_period == 0) { cout << "Epoch " << epoch << ";\n" << "Parameters norm: " << parameters_norm << "\n" << "Training loss: " << training_error << "\n" << "Batch size: " << training_batch_size << "\n" << "Gradient norm: " << gradient_norm << "\n" << loss_index_pointer->write_information() << "Learning rate: " << learning_rate<< "\n" << "Elapsed time: " << write_elapsed_time(elapsed_time)<<"\n" << "Selection error: " << selection_error << endl; } // Update stuff old_training_error = training_error; old_selection_error = selection_error; if(stop_training) break; } if(return_minimum_selection_error_neural_network) { parameters = minimum_selection_error_parameters; parameters_norm = parameters.calculate_L2_norm(); neural_network_pointer->set_parameters(parameters); selection_error = minimum_selection_error; } results_pointer->final_parameters = parameters; results_pointer->final_parameters_norm = parameters_norm; results_pointer->final_loss = training_error; results_pointer->final_selection_error = selection_error; results_pointer->final_gradient_norm = gradient_norm; results_pointer->elapsed_time = elapsed_time; return(results_pointer); } /* AdaptiveMomentEstimation::AdaptiveMomentEstimationResults* AdaptiveMomentEstimation::perform_training_cuda() { AdaptiveMomentEstimationResults* results_pointer = new AdaptiveMomentEstimationResults(this); // Control sentence(if debug) #ifdef __OPENNN_DEBUG__ check(); #endif // Start training if(display) cout << "Training with adaptive moment estimation...\n"; // Data set stuff DataSet* data_set_pointer = loss_index_pointer->get_data_set_pointer(); const Instances& instances = data_set_pointer->get_instances(); const size_t selection_instances_number = instances.get_selection_instances_number(); // Neural network stuff NeuralNetwork* neural_network_pointer = loss_index_pointer->get_neural_network_pointer(); MultilayerPerceptron* multilayer_perceptron_pointer = neural_network_pointer->get_multilayer_perceptron_pointer(); const size_t parameters_number = neural_network_pointer->get_parameters_number(); Vector<double> parameters(parameters_number); Vector<double> parameters_increment(parameters_number); Vector<double> last_increment(parameters_number,0.0); double parameters_norm = 0.0; const MultilayerPerceptron::Pointers multilayer_perceptron_pointers_device = multilayer_perceptron_pointer->host_to_device(); // Loss index stuff double training_error = 0.0; double old_training_error = 0.0; double selection_error = 0.0; double old_selection_error = 0.0; Vector<double> loss(instances.get_training_batches(training_batch_size).size()); Vector<double> gradient(parameters_number); double gradient_norm = 0.0; // Optimization algorithm stuff double learning_rate = initial_learning_rate; size_t selection_failures = 0; Vector<double> minimum_selection_error_parameters(parameters_number); double minimum_selection_error = numeric_limits<double>::max(); bool stop_training = false; time_t beginning_time, current_time; time(&beginning_time); double elapsed_time = 0.0; results_pointer->resize_training_history(maximum_epochs_number + 1); // Main loop for(size_t epoch = 0; epoch < epochs_number; epoch++) { const Vector< Vector<size_t> > training_batches = instances.get_training_batches(training_batch_size); const size_t batches_number = training_batches.size(); parameters = neural_network_pointer->get_parameters(); parameters_norm = parameters.calculate_L2_norm(); if(display && parameters_norm >= warning_parameters_norm) cout << "OpenNN Warning: Parameters norm is " << parameters_norm << ".\n"; for(size_t iteration = 0; iteration < batches_number; iteration++) { //Loss loss_index_pointer->calculate_batch_error_cuda(multilayer_perceptron_pointers_device); // Gradient gradient = loss_index_pointer->calculate_batch_error_gradient_cuda(multilayer_perceptron_pointers_device); gradient_norm = gradient.calculate_L2_norm(); if(display && gradient_norm >= warning_gradient_norm) cout << "OpenNN Warning: Gradient norm is " << gradient_norm << ".\n"; initial_decay > 0.0 ? learning_rate = initial_learning_rate * (1.0 / (1.0 + current_iteration*initial_decay)) : initial_learning_rate ; parameters = neural_network_pointer->get_parameters(); parameters_increment = gradient*(-learning_rate); if(momentum > 0.0) { parameters_increment += last_increment*momentum; last_increment = parameters_increment; neural_network_pointer->set_parameters(parameters + parameters_increment); } else { neural_network_pointer->set_parameters(parameters + parameters_increment); } } // Loss training_error = loss_index_pointer->calculate_training_error(); if(selection_instances_number > 0) selection_error = loss_index_pointer->calculate_selection_error(); if(epoch == 0) { minimum_selection_error = selection_error; minimum_selection_error_parameters = neural_network_pointer->get_parameters(); } else if(epoch != 0 && selection_error > old_selection_error) { selection_failures++; } else if(selection_error <= minimum_selection_error) { minimum_selection_error = selection_error; minimum_selection_error_parameters = neural_network_pointer->get_parameters(); } // Elapsed time time(&current_time); elapsed_time = difftime(current_time, beginning_time); // Training history neural network if(reserve_parameters_history) results_pointer->parameters_history[epoch] = parameters; if(reserve_parameters_norm_history) results_pointer->parameters_norm_history[epoch] = parameters_norm; // Training history loss index if(reserve_loss_history) results_pointer->loss_history[epoch] = training_error; if(reserve_gradient_norm_history) results_pointer->gradient_norm_history[epoch] = gradient_norm; if(reserve_selection_error_history) results_pointer->selection_error_history[epoch] = selection_error; // Training history optimization algorithm if(reserve_elapsed_time_history) results_pointer->elapsed_time_history[epoch] = elapsed_time; // Stopping Criteria if(selection_failures >= maximum_selection_failures && apply_early_stopping) { if(display) { cout << "Epoch " << epoch << ", iteration " << epoch << ": Maximum selection failures reached.\n" << "Selection failures: " << selection_failures << endl; } stop_training = true; results_pointer->stopping_condition = MaximumSelectionLossIncreases; } else if(epoch == maximum_epochs_number) { if(display) { cout << "Epoch " << epoch << ": Maximum number of iterations reached.\n"; } stop_training = true; results_pointer->stopping_condition = MaximumIterationsNumber; } else if(elapsed_time >= maximum_time) { if(display) { cout << "Epoch " << epoch << ": Maximum training time reached.\n"; } stop_training = true; results_pointer->stopping_condition = MaximumTime; } if(epoch != 0 && epoch % save_period == 0) { neural_network_pointer->save(neural_network_file_name); } if(stop_training) { if(display) { cout << "Parameters norm: " << parameters_norm << "\n" << "Training loss: " << training_error << "\n" << "Batch size: " << training_batch_size << "\n" << "Gradient norm: " << gradient_norm << "\n" << loss_index_pointer->write_information() << "Learning rate: " << learning_rate << "\n" << "Elapsed time: " << write_elapsed_time(elapsed_time)<<"\n" << "Selection error: " << selection_error << endl; } results_pointer->resize_training_history(1+epoch); results_pointer->final_parameters = parameters; results_pointer->final_parameters_norm = parameters_norm; results_pointer->final_loss = training_error; results_pointer->final_selection_error = selection_error; results_pointer->final_gradient_norm = gradient_norm; results_pointer->elapsed_time = elapsed_time; results_pointer->iterations_number = epoch; break; } else if(display && epoch % display_period == 0) { cout << "Epoch " << epoch << ";\n" << "Parameters norm: " << parameters_norm << "\n" << "Training loss: " << training_error << "\n" << "Batch size: " << training_batch_size << "\n" << "Gradient norm: " << gradient_norm << "\n" << loss_index_pointer->write_information() << "Learning rate: " << learning_rate<< "\n" << "Elapsed time: " << write_elapsed_time(elapsed_time)<<"\n" << "Selection error: " << selection_error << endl; } // Update stuff old_training_error = training_error; old_selection_error = selection_error; current_iteration++; if(stop_training) break; } if(return_minimum_selection_error_neural_network) { parameters = minimum_selection_error_parameters; parameters_norm = parameters.calculate_L2_norm(); neural_network_pointer->set_parameters(parameters); selection_error = minimum_selection_error; } results_pointer->final_parameters = parameters; results_pointer->final_parameters_norm = parameters_norm; results_pointer->final_loss = training_error; results_pointer->final_selection_error = selection_error; results_pointer->final_gradient_norm = gradient_norm; results_pointer->elapsed_time = elapsed_time; return(results_pointer); } */ void AdaptiveMomentEstimation::perform_training_void() { AdaptiveMomentEstimationResults* results = perform_training(); delete results; } string AdaptiveMomentEstimation::write_optimization_algorithm_type() const { return("GRADIENT_DESCENT"); } /// Writes as matrix of strings the most representative atributes. Matrix<string> AdaptiveMomentEstimation::to_string_matrix() const { ostringstream buffer; Vector<string> labels; Vector<string> values; // Minimum parameters increment norm labels.push_back("Minimum parameters increment norm"); buffer.str(""); buffer << minimum_parameters_increment_norm; values.push_back(buffer.str()); // Minimum loss decrease labels.push_back("Minimum loss decrease"); buffer.str(""); buffer << minimum_loss_decrease; values.push_back(buffer.str()); // Performance goal labels.push_back(" Performance goal"); buffer.str(""); buffer << loss_goal; values.push_back(buffer.str()); // Gradient norm goal labels.push_back("Gradient norm goal"); buffer.str(""); buffer << gradient_norm_goal; values.push_back(buffer.str()); // Maximum selection loss decreases labels.push_back("Maximum selection loss increases"); buffer.str(""); buffer << maximum_selection_failures; values.push_back(buffer.str()); // Maximum iterations number labels.push_back("Maximum epoch number"); buffer.str(""); buffer << maximum_epochs_number; values.push_back(buffer.str()); // Maximum time labels.push_back("Maximum time"); buffer.str(""); buffer << maximum_time; values.push_back(buffer.str()); // Reserve parameters norm history labels.push_back("Reserve parameters norm history"); buffer.str(""); if(reserve_parameters_norm_history) { buffer << "true"; } else { buffer << "false"; } values.push_back(buffer.str()); // Reserve loss history labels.push_back("Reserve loss history"); buffer.str(""); if(reserve_loss_history) { buffer << "true"; } else { buffer << "false"; } values.push_back(buffer.str()); // Reserve selection loss history labels.push_back("Reserve selection loss history"); buffer.str(""); if(reserve_selection_error_history) { buffer << "true"; } else { buffer << "false"; } values.push_back(buffer.str()); // Reserve gradient norm history labels.push_back("Reserve gradient norm history"); buffer.str(""); if(reserve_gradient_norm_history) { buffer << "true"; } else { buffer << "false"; } values.push_back(buffer.str()); const size_t rows_number = labels.size(); const size_t columns_number = 2; Matrix<string> string_matrix(rows_number, columns_number); string_matrix.set_column(0, labels, "name"); string_matrix.set_column(1, values, "value"); return(string_matrix); } /// Serializes the training parameters, the stopping criteria and other user stuff /// concerning the gradient descent object. tinyxml2::XMLDocument* AdaptiveMomentEstimation::to_XML() const { ostringstream buffer; tinyxml2::XMLDocument* document = new tinyxml2::XMLDocument; // Optimization algorithm tinyxml2::XMLElement* root_element = document->NewElement("AdaptiveMomentEstimation"); document->InsertFirstChild(root_element); tinyxml2::XMLElement* element = nullptr; tinyxml2::XMLText* text = nullptr; // Return minimum selection error neural network element = document->NewElement("ReturnMinimumSelectionErrorNN"); root_element->LinkEndChild(element); buffer.str(""); buffer << return_minimum_selection_error_neural_network; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Apply early stopping element = document->NewElement("ApplyEarlyStopping"); root_element->LinkEndChild(element); buffer.str(""); buffer << apply_early_stopping; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Warning parameters norm element = document->NewElement("WarningParametersNorm"); root_element->LinkEndChild(element); buffer.str(""); buffer << warning_parameters_norm; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Warning gradient norm element = document->NewElement("WarningGradientNorm"); root_element->LinkEndChild(element); buffer.str(""); buffer << warning_gradient_norm; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Error parameters norm element = document->NewElement("ErrorParametersNorm"); root_element->LinkEndChild(element); buffer.str(""); buffer << error_parameters_norm; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Error gradient norm element = document->NewElement("ErrorGradientNorm"); root_element->LinkEndChild(element); buffer.str(""); buffer << error_gradient_norm; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Minimum parameters increment norm element = document->NewElement("MinimumParametersIncrementNorm"); root_element->LinkEndChild(element); buffer.str(""); buffer << minimum_parameters_increment_norm; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Minimum loss decrease element = document->NewElement("MinimumLossDecrease"); root_element->LinkEndChild(element); buffer.str(""); buffer << minimum_loss_decrease; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Performance goal element = document->NewElement("LossGoal"); root_element->LinkEndChild(element); buffer.str(""); buffer << loss_goal; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Gradient norm goal element = document->NewElement("GradientNormGoal"); root_element->LinkEndChild(element); buffer.str(""); buffer << gradient_norm_goal; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Maximum selection loss decreases element = document->NewElement("MaximumSelectionLossDecreases"); root_element->LinkEndChild(element); buffer.str(""); buffer << maximum_selection_failures; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Maximum iterations number element = document->NewElement("MaximumIterationsNumber"); root_element->LinkEndChild(element); buffer.str(""); buffer << maximum_epochs_number; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Maximum time element = document->NewElement("MaximumTime"); root_element->LinkEndChild(element); buffer.str(""); buffer << maximum_time; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Reserve parameters norm history element = document->NewElement("ReserveParametersNormHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_parameters_norm_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Reserve parameters history element = document->NewElement("ReserveParametersHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_parameters_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Reserve loss history element = document->NewElement("ReservePerformanceHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_loss_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Reserve selection loss history element = document->NewElement("ReserveSelectionLossHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_selection_error_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Reserve gradient history element = document->NewElement("ReserveGradientHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_gradient_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Reserve gradient norm history element = document->NewElement("ReserveGradientNormHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_gradient_norm_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); //Reserve learning rate history element = document->NewElement("ReserveLearningRateHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_learning_rate_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); //Reserve elapsed time history element = document->NewElement("ReserveElapsedTimeHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_elapsed_time_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); //Reserve selection loss history element = document->NewElement("ReserveSelectionLossHistory"); root_element->LinkEndChild(element); buffer.str(""); buffer << reserve_selection_error_history; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Display period element = document->NewElement("DisplayPeriod"); root_element->LinkEndChild(element); buffer.str(""); buffer << display_period; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Save period element = document->NewElement("SavePeriod"); root_element->LinkEndChild(element); buffer.str(""); buffer << save_period; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); // Neural network file name element = document->NewElement("NeuralNetworkFileName"); root_element->LinkEndChild(element); text = document->NewText(neural_network_file_name.c_str()); element->LinkEndChild(text); // Display warnings element = document->NewElement("Display"); root_element->LinkEndChild(element); buffer.str(""); buffer << display; text = document->NewText(buffer.str().c_str()); element->LinkEndChild(text); return(document); } /// Serializes the gradient descent object into a XML document of the TinyXML library without keep the DOM tree in memory. /// See the OpenNN manual for more information about the format of this document. void AdaptiveMomentEstimation::write_XML(tinyxml2::XMLPrinter& file_stream) const { ostringstream buffer; //file_stream.OpenElement("AdaptiveMomentEstimation"); // Return minimum selection error neural network file_stream.OpenElement("ReturnMinimumSelectionErrorNN"); buffer.str(""); buffer << return_minimum_selection_error_neural_network; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Apply early stopping file_stream.OpenElement("ApplyEarlyStopping"); buffer.str(""); buffer << apply_early_stopping; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Minimum parameters increment norm file_stream.OpenElement("MinimumParametersIncrementNorm"); buffer.str(""); buffer << minimum_parameters_increment_norm; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Minimum loss decrease file_stream.OpenElement("MinimumLossDecrease"); buffer.str(""); buffer << minimum_loss_decrease; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Performance goal file_stream.OpenElement("LossGoal"); buffer.str(""); buffer << loss_goal; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Gradient norm goal file_stream.OpenElement("GradientNormGoal"); buffer.str(""); buffer << gradient_norm_goal; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Maximum selection loss decreases file_stream.OpenElement("MaximumSelectionLossDecreases"); buffer.str(""); buffer << maximum_selection_failures; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Maximum iterations number file_stream.OpenElement("MaximumIterationsNumber"); buffer.str(""); buffer << maximum_epochs_number; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Maximum time file_stream.OpenElement("MaximumTime"); buffer.str(""); buffer << maximum_time; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Reserve parameters norm history file_stream.OpenElement("ReserveParametersNormHistory"); buffer.str(""); buffer << reserve_parameters_norm_history; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Reserve loss history file_stream.OpenElement("ReservePerformanceHistory"); buffer.str(""); buffer << reserve_loss_history; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Reserve selection loss history file_stream.OpenElement("ReserveSelectionLossHistory"); buffer.str(""); buffer << reserve_selection_error_history; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); // Reserve gradient norm history file_stream.OpenElement("ReserveGradientNormHistory"); buffer.str(""); buffer << reserve_gradient_norm_history; file_stream.PushText(buffer.str().c_str()); file_stream.CloseElement(); } void AdaptiveMomentEstimation::from_XML(const tinyxml2::XMLDocument& document) { const tinyxml2::XMLElement* root_element = document.FirstChildElement("AdaptiveMomentEstimation"); if(!root_element) { ostringstream buffer; buffer << "OpenNN Exception: AdaptiveMomentEstimation class.\n" << "void from_XML(const tinyxml2::XMLDocument&) method.\n" << "Gradient descent element is nullptr.\n"; throw logic_error(buffer.str()); } // Warning parameters norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("WarningParametersNorm"); if(element) { const double new_warning_parameters_norm = atof(element->GetText()); try { set_warning_parameters_norm(new_warning_parameters_norm); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Warning gradient norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("WarningGradientNorm"); if(element) { const double new_warning_gradient_norm = atof(element->GetText()); try { set_warning_gradient_norm(new_warning_gradient_norm); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Error parameters norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ErrorParametersNorm"); if(element) { const double new_error_parameters_norm = atof(element->GetText()); try { set_error_parameters_norm(new_error_parameters_norm); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Error gradient norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ErrorGradientNorm"); if(element) { const double new_error_gradient_norm = atof(element->GetText()); try { set_error_gradient_norm(new_error_gradient_norm); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Return minimum selection error neural network const tinyxml2::XMLElement* return_minimum_selection_error_neural_network_element = root_element->FirstChildElement("ReturnMinimumSelectionErrorNN"); if(return_minimum_selection_error_neural_network_element) { string new_return_minimum_selection_error_neural_network = return_minimum_selection_error_neural_network_element->GetText(); try { set_return_minimum_selection_error_neural_network(new_return_minimum_selection_error_neural_network != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } // Apply early stopping const tinyxml2::XMLElement* apply_early_stopping_element = root_element->FirstChildElement("ApplyEarlyStopping"); if(apply_early_stopping_element) { string new_apply_early_stopping = apply_early_stopping_element->GetText(); try { set_apply_early_stopping(new_apply_early_stopping != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } // Minimum parameters increment norm { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MinimumParametersIncrementNorm"); if(element) { const double new_minimum_parameters_increment_norm = atof(element->GetText()); try { set_minimum_parameters_increment_norm(new_minimum_parameters_increment_norm); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Minimum loss decrease { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MinimumLossDecrease"); if(element) { const double new_minimum_loss_increase = atof(element->GetText()); try { set_minimum_loss_increase(new_minimum_loss_increase); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Performance goal { const tinyxml2::XMLElement* element = root_element->FirstChildElement("LossGoal"); if(element) { const double new_loss_goal = atof(element->GetText()); try { set_loss_goal(new_loss_goal); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Gradient norm goal { const tinyxml2::XMLElement* element = root_element->FirstChildElement("GradientNormGoal"); if(element) { const double new_gradient_norm_goal = atof(element->GetText()); try { set_gradient_norm_goal(new_gradient_norm_goal); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Maximum selection loss decreases { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumSelectionLossDecreases"); if(element) { const size_t new_maximum_selection_failures = static_cast<size_t>(atoi(element->GetText())); try { set_maximum_selection_error_increases(new_maximum_selection_failures); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Maximum iterations number { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumIterationsNumber"); if(element) { const size_t new_maximum_epochs_number = static_cast<size_t>(atoi(element->GetText())); try { set_maximum_epochs_number(new_maximum_epochs_number); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Maximum time { const tinyxml2::XMLElement* element = root_element->FirstChildElement("MaximumTime"); if(element) { const double new_maximum_time = atof(element->GetText()); try { set_maximum_time(new_maximum_time); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve parameters history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveParametersHistory"); if(element) { const string new_reserve_parameters_history = element->GetText(); try { set_reserve_parameters_history(new_reserve_parameters_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve parameters norm history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveParametersNormHistory"); if(element) { const string new_reserve_parameters_norm_history = element->GetText(); try { set_reserve_parameters_norm_history(new_reserve_parameters_norm_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve loss history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReservePerformanceHistory"); if(element) { const string new_reserve_loss_history = element->GetText(); try { set_reserve_loss_history(new_reserve_loss_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve selection loss history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveSelectionLossHistory"); if(element) { const string new_reserve_selection_error_history = element->GetText(); try { set_reserve_selection_error_history(new_reserve_selection_error_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve gradient history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveGradientHistory"); if(element) { const string new_reserve_gradient_history = element->GetText(); try { set_reserve_gradient_history(new_reserve_gradient_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve gradient norm history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveGradientNormHistory"); if(element) { const string new_reserve_gradient_norm_history = element->GetText(); try { set_reserve_gradient_norm_history(new_reserve_gradient_norm_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve training rate history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveLearningRateHistory"); if(element) { const string new_reserve_learning_rate_history = element->GetText(); try { set_reserve_learning_rate_history(new_reserve_learning_rate_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve elapsed time history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveElapsedTimeHistory"); if(element) { const string new_reserve_elapsed_time_history = element->GetText(); try { set_reserve_elapsed_time_history(new_reserve_elapsed_time_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Reserve selection loss history { const tinyxml2::XMLElement* element = root_element->FirstChildElement("ReserveSelectionLossHistory"); if(element) { const string new_reserve_selection_error_history = element->GetText(); try { set_reserve_selection_error_history(new_reserve_selection_error_history != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Display period { const tinyxml2::XMLElement* element = root_element->FirstChildElement("DisplayPeriod"); if(element) { const size_t new_display_period = static_cast<size_t>(atoi(element->GetText())); try { set_display_period(new_display_period); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Save period { const tinyxml2::XMLElement* element = root_element->FirstChildElement("SavePeriod"); if(element) { const size_t new_save_period = static_cast<size_t>(atoi(element->GetText())); try { set_save_period(new_save_period); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Neural network file name { const tinyxml2::XMLElement* element = root_element->FirstChildElement("NeuralNetworkFileName"); if(element) { const string new_neural_network_file_name = element->GetText(); try { set_neural_network_file_name(new_neural_network_file_name); } catch(const logic_error& e) { cerr << e.what() << endl; } } } // Display { const tinyxml2::XMLElement* element = root_element->FirstChildElement("Display"); if(element) { const string new_display = element->GetText(); try { set_display(new_display != "0"); } catch(const logic_error& e) { cerr << e.what() << endl; } } } } } // OpenNN: Open Neural Networks Library. // Copyright(C) 2005-2018 Artificial Intelligence Techniques, SL. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
27.512681
162
0.667176
[ "object", "vector", "model" ]
5fdf1a56fafe991ee44da692b24830099945f1b8
2,001
hpp
C++
src/third-party/spoa/simd_alignment_engine.hpp
PacificBiosciences/c3s
01974dda9addc67744d5d4880d921588ed1e2a08
[ "BSD-3-Clause-Clear" ]
6
2019-11-14T16:40:36.000Z
2020-06-12T10:06:57.000Z
src/third-party/spoa/simd_alignment_engine.hpp
armintoepfer/c3s
01974dda9addc67744d5d4880d921588ed1e2a08
[ "BSD-3-Clause-Clear" ]
2
2020-08-15T18:45:25.000Z
2020-11-26T13:46:42.000Z
src/third-party/spoa/simd_alignment_engine.hpp
armintoepfer/c3s
01974dda9addc67744d5d4880d921588ed1e2a08
[ "BSD-3-Clause-Clear" ]
3
2020-12-28T10:34:08.000Z
2020-12-28T10:34:31.000Z
/*! * @file simd_alignment_engine.hpp * * @brief SimdAlignmentEngine class header file */ #pragma once #include <stdint.h> #include <memory> #include <string> #include <utility> #include <vector> #include "alignment_engine.hpp" namespace spoa { class Graph; class SimdAlignmentEngine; std::unique_ptr<AlignmentEngine> createSimdAlignmentEngine(AlignmentType alignment_type, int8_t match, int8_t mismatch, int8_t gap); class SimdAlignmentEngine : public AlignmentEngine { public: ~SimdAlignmentEngine(); void prealloc(uint32_t max_sequence_size, uint32_t alphabet_size) override; Alignment align_sequence_with_graph(const char* sequence, uint32_t sequence_size, const std::unique_ptr<Graph>& graph) override; friend std::unique_ptr<AlignmentEngine> createSimdAlignmentEngine(AlignmentType alignment_type, int8_t match, int8_t mismatch, int8_t gap); private: SimdAlignmentEngine(AlignmentType alignment_type, int8_t match, int8_t mismatch, int8_t gap); SimdAlignmentEngine(const SimdAlignmentEngine&) = delete; const SimdAlignmentEngine& operator=(const SimdAlignmentEngine&) = delete; template <typename T> Alignment align(const char* sequence, uint32_t sequence_size, const std::unique_ptr<Graph>& graph) noexcept; void realloc(uint32_t matrix_width, uint32_t matrix_height, uint32_t num_codes); template <typename T> void initialize(const char* sequence, const std::unique_ptr<Graph>& graph, uint32_t normal_matrix_width, uint32_t matrix_width, uint32_t matrix_height) noexcept; struct Implementation; std::unique_ptr<Implementation> pimpl_; }; } // namespace spoa
32.803279
100
0.642179
[ "vector" ]
5fe31c37f6d558b3e066bfb2face2e0d09c46f2d
2,152
cpp
C++
src/Swoose/Swoose/QMMM/QmRegionSelection/SymmetryScores.cpp
qcscine/swoose
55a74259153845ade607784f26455fd96dddce07
[ "BSD-3-Clause" ]
2
2021-12-15T09:31:36.000Z
2021-12-15T09:35:36.000Z
src/Swoose/Swoose/QMMM/QmRegionSelection/SymmetryScores.cpp
qcscine/swoose
55a74259153845ade607784f26455fd96dddce07
[ "BSD-3-Clause" ]
null
null
null
src/Swoose/Swoose/QMMM/QmRegionSelection/SymmetryScores.cpp
qcscine/swoose
55a74259153845ade607784f26455fd96dddce07
[ "BSD-3-Clause" ]
null
null
null
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #include "SymmetryScores.h" #include "QmRegionSelector.h" #include "QmRegionSelectorSettings.h" #include "QmmmReferenceDataManager.h" namespace Scine { namespace Qmmm { double calculateSymmetryScoreForOneModel(const QmmmModel& model, const std::vector<double>& distances, int numberOfValuesForMean) { std::vector<double> distancesOfIncludedAtoms; std::vector<double> distancesOfExcludedAtoms; for (int i = 0; i < distances.size(); ++i) { if (std::find(model.qmAtomIndices.begin(), model.qmAtomIndices.end(), i) != model.qmAtomIndices.end()) distancesOfIncludedAtoms.push_back(distances[i]); else distancesOfExcludedAtoms.push_back(distances[i]); } std::sort(distancesOfExcludedAtoms.begin(), distancesOfExcludedAtoms.end()); std::sort(distancesOfIncludedAtoms.begin(), distancesOfIncludedAtoms.end(), std::greater<>()); double meanOfSmallest = 0.0; double meanOfLargest = 0.0; try { for (int k = 0; k < numberOfValuesForMean; ++k) { meanOfSmallest += distancesOfExcludedAtoms.at(k); } meanOfSmallest /= numberOfValuesForMean; for (int l = 0; l < numberOfValuesForMean; ++l) { meanOfLargest += distancesOfIncludedAtoms.at(l); } meanOfLargest /= numberOfValuesForMean; } catch (const std::out_of_range& e) { return 0.0; } return meanOfLargest / meanOfSmallest; } double calculateMaxAllowedSymmetryScore(const QmmmData& qmmmData, const Utils::Settings& settings) { if (qmmmData.symmetryScores.empty()) throw std::runtime_error("Symmetry scores could not be evaluated."); const double minSymmetryScore = *std::min_element(qmmmData.symmetryScores.begin(), qmmmData.symmetryScores.end() - qmmmData.nRef); const double tolerance = (settings.getDouble(SwooseUtilities::SettingsNames::tolerancePercentageSymmetryScore) / 100.0) * minSymmetryScore; return minSymmetryScore + tolerance; } } // namespace Qmmm } // namespace Scine
36.474576
131
0.725836
[ "vector", "model" ]
5fe86d5c5eaeec5e878a55c6099b06e9eb45db7c
7,763
cxx
C++
ZScoreMapping/ZScoreMapping.cxx
CSIM-Toolkits/ImageFeatureExtraction
ea121dce0e511b5e6d4bede9e03c4fc053ed01b2
[ "Apache-2.0" ]
null
null
null
ZScoreMapping/ZScoreMapping.cxx
CSIM-Toolkits/ImageFeatureExtraction
ea121dce0e511b5e6d4bede9e03c4fc053ed01b2
[ "Apache-2.0" ]
null
null
null
ZScoreMapping/ZScoreMapping.cxx
CSIM-Toolkits/ImageFeatureExtraction
ea121dce0e511b5e6d4bede9e03c4fc053ed01b2
[ "Apache-2.0" ]
null
null
null
#include "itkImageFileWriter.h" #include "itkImageRegionIterator.h" #include "itkHistogramMatchingImageFilter.h" #include <math.h> #include "itkPluginUtilities.h" #include "ZScoreMappingCLP.h" // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { template <typename TPixel> int DoIt( int argc, char * argv[], TPixel ) { PARSE_ARGS; typedef TPixel InputPixelType; typedef float OutputPixelType; typedef unsigned char LabelPixelType; const unsigned int Dimension = 3; typedef itk::Image<InputPixelType, Dimension> InputImageType; typedef itk::Image<LabelPixelType, Dimension> LabelImageType; typedef itk::Image<OutputPixelType, Dimension> OutputImageType; typedef itk::ImageFileReader<InputImageType> ReaderType; typedef itk::ImageFileReader<LabelImageType> LabelReaderType; typename ReaderType::Pointer readerInput = ReaderType::New(); typename ReaderType::Pointer readerTemplateMean = ReaderType::New(); typename ReaderType::Pointer readerTemplateSTD = ReaderType::New(); typename LabelReaderType::Pointer readerRegionMask = LabelReaderType::New(); readerInput->SetFileName( inputVolume.c_str() ); readerTemplateMean->SetFileName( inputTemplateMean.c_str() ); readerTemplateSTD->SetFileName( inputTemplateStd.c_str() ); readerInput->Update(); readerTemplateMean->Update(); readerTemplateSTD->Update(); //Apply histogram matching typedef itk::HistogramMatchingImageFilter<InputImageType,InputImageType> HistogramMatchingType; typename HistogramMatchingType::Pointer hMatch = HistogramMatchingType::New(); if (doHistogramMatching) { std::cout<<"Performing histogram matching"<<std::endl; hMatch->SetReferenceImage( readerTemplateMean->GetOutput() ); hMatch->SetInput( readerInput->GetOutput() ); hMatch->SetNumberOfHistogramLevels( 255 ); hMatch->SetNumberOfMatchPoints( 64 ); hMatch->Update(); } //Calculate Z-Score map typename OutputImageType::Pointer zScoreMap = OutputImageType::New(); zScoreMap->CopyInformation(readerInput->GetOutput()); zScoreMap->SetRegions(readerInput->GetOutput()->GetRequestedRegion()); zScoreMap->Allocate(); zScoreMap->FillBuffer(0); typedef itk::ImageRegionIterator<InputImageType> RegionIteratorType; typedef itk::ImageRegionIterator<OutputImageType> OutputRegionIteratorType; RegionIteratorType imgIt(doHistogramMatching?hMatch->GetOutput():readerInput->GetOutput(), doHistogramMatching?hMatch->GetOutput()->GetRequestedRegion():readerInput->GetOutput()->GetRequestedRegion()); RegionIteratorType tempMeanIt(readerTemplateMean->GetOutput(), readerTemplateMean->GetOutput()->GetRequestedRegion()); RegionIteratorType tempStdIt(readerTemplateSTD->GetOutput(), readerTemplateSTD->GetOutput()->GetRequestedRegion()); OutputRegionIteratorType zScoreIt(zScoreMap, zScoreMap->GetRequestedRegion()); if (regionMask == "") { std::cout<<"Calculating Z-Score mapping - full brain coverage"<<std::endl; imgIt.GoToBegin(); tempMeanIt.GoToBegin(); tempStdIt.GoToBegin(); zScoreIt.GoToBegin(); float temp_zscore=0.0; while(!imgIt.IsAtEnd()){ if (tempMeanIt.Get()>static_cast<InputPixelType>(0)) { temp_zscore = (static_cast<OutputPixelType>(imgIt.Get()) - static_cast<OutputPixelType>(tempMeanIt.Get())) / static_cast<OutputPixelType>(tempStdIt.Get()); //Preventing to add outlier in the z-score map if (temp_zscore> -10.0 && temp_zscore<10.0) { zScoreIt.Set(temp_zscore); } } ++imgIt; ++tempMeanIt; ++tempStdIt; ++zScoreIt; } }else{ std::cout<<"Calculating Z-Score mapping - region defined in label map"<<std::endl; readerRegionMask->SetFileName( regionMask.c_str() ); readerRegionMask->Update(); typedef itk::ImageRegionIterator<LabelImageType> LabelIteratorType; LabelIteratorType regionIt(readerRegionMask->GetOutput(), readerRegionMask->GetOutput()->GetRequestedRegion()); imgIt.GoToBegin(); tempMeanIt.GoToBegin(); tempStdIt.GoToBegin(); regionIt.GoToBegin(); zScoreIt.GoToBegin(); float temp_zscore=0.0; while(!imgIt.IsAtEnd()){ if (regionIt.Get()>static_cast<LabelPixelType>(0)) { temp_zscore = (static_cast<OutputPixelType>(imgIt.Get()) - static_cast<OutputPixelType>(tempMeanIt.Get())) / static_cast<OutputPixelType>(tempStdIt.Get()); //Preventing to add outlier in the z-score map if (temp_zscore > -10.0 && temp_zscore < 10.0) { zScoreIt.Set(temp_zscore); } } ++imgIt; ++tempMeanIt; ++tempStdIt; ++regionIt; ++zScoreIt; } } typedef itk::ImageFileWriter<OutputImageType> WriterType; typename WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outputVolume.c_str() ); writer->SetInput( zScoreMap ); writer->SetUseCompression(1); writer->Update(); return EXIT_SUCCESS; } } // end of anonymous namespace int main( int argc, char * argv[] ) { PARSE_ARGS; itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; try { itk::GetImageType(inputVolume, pixelType, componentType); // This filter handles all types on input, but only produces // signed types switch( componentType ) { case itk::ImageIOBase::UCHAR: return DoIt( argc, argv, static_cast<unsigned char>(0) ); break; case itk::ImageIOBase::CHAR: return DoIt( argc, argv, static_cast<signed char>(0) ); break; case itk::ImageIOBase::USHORT: return DoIt( argc, argv, static_cast<unsigned short>(0) ); break; case itk::ImageIOBase::SHORT: return DoIt( argc, argv, static_cast<short>(0) ); break; case itk::ImageIOBase::UINT: return DoIt( argc, argv, static_cast<unsigned int>(0) ); break; case itk::ImageIOBase::INT: return DoIt( argc, argv, static_cast<int>(0) ); break; case itk::ImageIOBase::ULONG: return DoIt( argc, argv, static_cast<unsigned long>(0) ); break; case itk::ImageIOBase::LONG: return DoIt( argc, argv, static_cast<long>(0) ); break; case itk::ImageIOBase::FLOAT: return DoIt( argc, argv, static_cast<float>(0) ); break; case itk::ImageIOBase::DOUBLE: return DoIt( argc, argv, static_cast<double>(0) ); break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: std::cerr << "Unknown input image pixel component type: "; std::cerr << itk::ImageIOBase::GetComponentTypeAsString( componentType ); std::cerr << std::endl; return EXIT_FAILURE; break; } } catch( itk::ExceptionObject & excep ) { std::cerr << argv[0] << ": exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
37.322115
139
0.636481
[ "object" ]
5fe9ac12894fc5a31966c2908c231776375967dd
7,292
hpp
C++
ThirdParty-mod/java2cpp/android/util/SparseIntArray.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/android/util/SparseIntArray.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/android/util/SparseIntArray.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.util.SparseIntArray ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_UTIL_SPARSEINTARRAY_HPP_DECL #define J2CPP_ANDROID_UTIL_SPARSEINTARRAY_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } #include <java/lang/Object.hpp> namespace j2cpp { namespace android { namespace util { class SparseIntArray; class SparseIntArray : public object<SparseIntArray> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) explicit SparseIntArray(jobject jobj) : object<SparseIntArray>(jobj) { } operator local_ref<java::lang::Object>() const; SparseIntArray(); SparseIntArray(jint); jint get(jint); jint get(jint, jint); void delete_(jint); void removeAt(jint); void put(jint, jint); jint size(); jint keyAt(jint); jint valueAt(jint); jint indexOfKey(jint); jint indexOfValue(jint); void clear(); void append(jint, jint); }; //class SparseIntArray } //namespace util } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_UTIL_SPARSEINTARRAY_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_UTIL_SPARSEINTARRAY_HPP_IMPL #define J2CPP_ANDROID_UTIL_SPARSEINTARRAY_HPP_IMPL namespace j2cpp { android::util::SparseIntArray::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::util::SparseIntArray::SparseIntArray() : object<android::util::SparseIntArray>( call_new_object< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(0), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(0) >() ) { } android::util::SparseIntArray::SparseIntArray(jint a0) : object<android::util::SparseIntArray>( call_new_object< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(1), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(1) >(a0) ) { } jint android::util::SparseIntArray::get(jint a0) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(2), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(2), jint >(get_jobject(), a0); } jint android::util::SparseIntArray::get(jint a0, jint a1) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(3), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(3), jint >(get_jobject(), a0, a1); } void android::util::SparseIntArray::delete_(jint a0) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(4), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(4), void >(get_jobject(), a0); } void android::util::SparseIntArray::removeAt(jint a0) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(5), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(5), void >(get_jobject(), a0); } void android::util::SparseIntArray::put(jint a0, jint a1) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(6), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(6), void >(get_jobject(), a0, a1); } jint android::util::SparseIntArray::size() { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(7), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(7), jint >(get_jobject()); } jint android::util::SparseIntArray::keyAt(jint a0) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(8), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(8), jint >(get_jobject(), a0); } jint android::util::SparseIntArray::valueAt(jint a0) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(9), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(9), jint >(get_jobject(), a0); } jint android::util::SparseIntArray::indexOfKey(jint a0) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(10), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(10), jint >(get_jobject(), a0); } jint android::util::SparseIntArray::indexOfValue(jint a0) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(11), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(11), jint >(get_jobject(), a0); } void android::util::SparseIntArray::clear() { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(12), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(12), void >(get_jobject()); } void android::util::SparseIntArray::append(jint a0, jint a1) { return call_method< android::util::SparseIntArray::J2CPP_CLASS_NAME, android::util::SparseIntArray::J2CPP_METHOD_NAME(13), android::util::SparseIntArray::J2CPP_METHOD_SIGNATURE(13), void >(get_jobject(), a0, a1); } J2CPP_DEFINE_CLASS(android::util::SparseIntArray,"android/util/SparseIntArray") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,0,"<init>","()V") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,1,"<init>","(I)V") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,2,"get","(I)I") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,3,"get","(II)I") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,4,"delete","(I)V") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,5,"removeAt","(I)V") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,6,"put","(II)V") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,7,"size","()I") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,8,"keyAt","(I)I") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,9,"valueAt","(I)I") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,10,"indexOfKey","(I)I") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,11,"indexOfValue","(I)I") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,12,"clear","()V") J2CPP_DEFINE_METHOD(android::util::SparseIntArray,13,"append","(II)V") } //namespace j2cpp #endif //J2CPP_ANDROID_UTIL_SPARSEINTARRAY_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
28.046154
83
0.716402
[ "object" ]
5feba7889da00c25277af9a3462c03ef3da11973
892
cpp
C++
ECF/tree/Node.cpp
KarlaSalamun/ECF
4bd21cf43d09435f034259a6b59129b1df6ad1b3
[ "MIT" ]
null
null
null
ECF/tree/Node.cpp
KarlaSalamun/ECF
4bd21cf43d09435f034259a6b59129b1df6ad1b3
[ "MIT" ]
null
null
null
ECF/tree/Node.cpp
KarlaSalamun/ECF
4bd21cf43d09435f034259a6b59129b1df6ad1b3
[ "MIT" ]
null
null
null
#include "../ECF_base.h" #include "Node.h" #include <iostream> namespace Tree { Node::Node(void) { size_ = 1; } /** * \brief Create a copy of an existing Node. * The associated primitive (pointer) is copied. */ Node::Node(NodeP node) { size_ = node->size_; depth_ = node->depth_; primitive_ = node->primitive_->copyWithNode(node->primitive_); } /** * \brief Create a copy of an existing Node with its Primitive pointer. * The associated primitive (pointer) is copied. */ Node::Node(PrimitiveP primitive) { primitive_ = primitive->copyWithNode(primitive); size_ = 1; } Node::~Node(void) { } /** * \brief Set the primitive this node points to (when creating a new tree node). * In case of an ephemereal random constant primitive, new primitive object is created. */ void Node::setPrimitive(PrimitiveP primitive) { primitive_ = primitive->assignToNode(primitive); } }
17.490196
87
0.701794
[ "object" ]
5ffc280ed9983008b7038fd10894cc947698c529
840
cc
C++
BOJ/1655.cc
Yaminyam/Algorithm
fe49b37b4b310f03273864bcd193fe88139f1c01
[ "MIT" ]
1
2019-05-18T00:02:12.000Z
2019-05-18T00:02:12.000Z
BOJ/1655.cc
siontama/Algorithm
bb419e0d4dd09682bd4542f90038b492ee232bd2
[ "MIT" ]
null
null
null
BOJ/1655.cc
siontama/Algorithm
bb419e0d4dd09682bd4542f90038b492ee232bd2
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<algorithm> #include<functional> #include<string> #include<vector> #include<queue> #include<stack> using namespace std; const int INF = numeric_limits<int>::max(); int main() { ios_base::sync_with_stdio(false); cin.tie(0); priority_queue<int, vector<int>, less<int>> maxheap; priority_queue<int, vector<int>, greater<int>> minheap; int n; cin >> n; int x; for (int i = 0; i < n; i++) { cin >> x; if (maxheap.size() > minheap.size()) { minheap.push(x); } else { maxheap.push(x); } if (!maxheap.empty() && !minheap.empty()) { if (maxheap.top() > minheap.top()) { int temp1 = maxheap.top(); int temp2 = minheap.top(); maxheap.pop(); minheap.pop(); maxheap.push(temp2); minheap.push(temp1); } } cout << maxheap.top() << "\n"; } }
17.142857
56
0.611905
[ "vector" ]
27032791592605ecaef3efe93c8c3b28920a88b0
4,073
cpp
C++
src/idonethdeepkin/Volturnos.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/idonethdeepkin/Volturnos.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/idonethdeepkin/Volturnos.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <idonethdeepkin/Volturnos.h> #include <UnitFactory.h> #include <Board.h> #include "IdonethDeepkinPrivate.h" namespace IdonethDeepkin { static const int g_basesize = 60; static const int g_wounds = 8; static const int g_pointsPerUnit = 260; bool Volturnos::s_registered = false; Volturnos::Volturnos(Enclave enclave, MountTrait trait, bool isGeneral) : IdonethDeepkinBase(enclave, "Volturnos", 14, g_wounds, 8, 3, true, g_pointsPerUnit), m_theAstraSolus(Weapon::Type::Melee, "The Astra Solus", 1, 5, 3, 3, -1, RAND_D3), m_deepmareJawsTalons(Weapon::Type::Melee, "Deepmare's Fanged Jaw and Talons", 2, 3, 3, 3, -1, 1), m_deepmareTails(Weapon::Type::Melee, "Deepmare's Lashing Tails", 2, 3, 3, 3, 0, 2) { m_keywords = {ORDER, AELF, IDONETH_DEEPKIN, HERO, AKHELIAN, AKHELIAN_KING, VOLTURNOS}; m_weapons = {&m_theAstraSolus, &m_deepmareJawsTalons, &m_deepmareTails}; m_battleFieldRole = Role::Leader; m_hasMount = true; m_deepmareTails.setMount(true); m_deepmareJawsTalons.setMount(true); setGeneral(isGeneral); s_globalBraveryMod.connect(this, &Volturnos::crestOfTheHighKings, &m_connection); auto model = new Model(g_basesize, wounds()); model->addMeleeWeapon(&m_theAstraSolus); model->addMeleeWeapon(&m_deepmareJawsTalons); model->addMeleeWeapon(&m_deepmareTails); addModel(model); } Volturnos::~Volturnos() { m_connection.disconnect(); } Unit *Volturnos::Create(const ParameterList &parameters) { auto enclave = (Enclave) GetEnumParam("Enclave", parameters, g_enclave[0]); auto trait = (MountTrait) GetEnumParam("Mount Trait", parameters, g_leviadonTrait[0]); auto general = GetBoolParam("General", parameters, false); return new Volturnos(enclave, trait, general); } void Volturnos::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { Create, IdonethDeepkinBase::ValueToString, IdonethDeepkinBase::EnumStringToInt, ComputePoints, { EnumParameter("Enclave", g_enclave[0], g_enclave), EnumParameter("Mount Trait", g_leviadonTrait[0], g_leviadonTrait), BoolParameter("General") }, ORDER, {IDONETH_DEEPKIN} }; s_registered = UnitFactory::Register("Volturnos", factoryMethod); } } void Volturnos::onCharged() { // Deepmare Horn auto units = Board::Instance()->getUnitsWithin(this, GetEnemyId(owningPlayer()), 1.0); if (!units.empty()) { int roll = Dice::RollD6(); if (roll >= 2) { units.front()->applyDamage({0, Dice::RollD3()}, this); } } IdonethDeepkinBase::onCharged(); } int Volturnos::crestOfTheHighKings(const Unit *target) { // The Crest of the High Kings if (target->hasKeyword(IDONETH_DEEPKIN) && (target->owningPlayer() == owningPlayer()) && (distanceTo(target) <= 18.0)) { return 1; } return 0; } int Volturnos::weaponRend(const Model* attackingModel, const Weapon *weapon, const Unit *target, int hitRoll, int woundRoll) const { // The Astra Solus if ((hitRoll >= 6) && (weapon->name() == m_theAstraSolus.name())) { return -5; } return IdonethDeepkinBase::weaponRend(attackingModel, weapon, target, hitRoll, woundRoll); } int Volturnos::ComputePoints(const ParameterList& /*parameters*/) { return g_pointsPerUnit; } } //namespace IdonethDeepkin
37.027273
136
0.606433
[ "model" ]
dfd4af745a37931ebb04f7f56cb2bd6e7723ea4b
7,250
cpp
C++
proteus/MeshAdaptPUMI/DumpMesh.cpp
acatwithacomputer/proteus
80dfad95da6ab4d18a88a035f55c26b03540a864
[ "MIT" ]
null
null
null
proteus/MeshAdaptPUMI/DumpMesh.cpp
acatwithacomputer/proteus
80dfad95da6ab4d18a88a035f55c26b03540a864
[ "MIT" ]
13
2018-02-08T23:22:59.000Z
2020-12-06T19:40:32.000Z
proteus/MeshAdaptPUMI/DumpMesh.cpp
acatwithacomputer/proteus
80dfad95da6ab4d18a88a035f55c26b03540a864
[ "MIT" ]
1
2020-02-17T03:25:34.000Z
2020-02-17T03:25:34.000Z
#include "DumpMesh.h" #include <PCU.h> /* see flcbdfWrappersModule.cpp: flcbdfWrappersConvertPUMIPartitionToPython and cmeshToolsModule.cpp: cmeshToolsBuildPythonMeshInterface */ static void print_int_2d(int* a, int h, int w, FILE* f) { for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) fprintf(f, "%d ", a[i * w + j]); fprintf(f, "\n"); } } static void print_double_2d(double* a, int h, int w, FILE* f) { for (int i = 0; i < h; ++i) { for (int j = 0; j < w; ++j) fprintf(f, "%f ", a[i * w + j]); fprintf(f, "\n"); } } static void dump_proteus_mesh_header(Mesh* m, FILE* f) { fprintf(f, "nElements_global = %d\n", m->nElements_global); fprintf(f, "nNodes_global = %d\n", m->nNodes_global); fprintf(f, "nNodes_element = %d\n", m->nNodes_element); fprintf(f, "nNodes_elementBoundary = %d\n", m->nNodes_elementBoundary); fprintf(f, "nElementBoundaries_element = %d\n", m->nElementBoundaries_element); fprintf(f, "nElementBoundaries_global = %d\n", m->nElementBoundaries_global); fprintf(f, "nInteriorElementBoundaries_global = %d\n", m->nInteriorElementBoundaries_global); fprintf(f, "nExteriorElementBoundaries_global = %d\n", m->nExteriorElementBoundaries_global); fprintf(f, "max_nElements_node = %d\n", m->max_nElements_node); fprintf(f, "nEdges_global = %d\n", m->nEdges_global); fprintf(f, "max_nNodeNeighbors_node = %d\n", m->max_nNodeNeighbors_node); } static void dump_proteus_subdomain(Mesh* m, FILE* f) { dump_proteus_mesh_header(m, f); fprintf(f, "elementNodesArray:\n"); print_int_2d(m->elementNodesArray, m->nElements_global, m->nNodes_element, f); fprintf(f, "nodeElementOffsets:\n"); if (!m->nodeElementOffsets) fprintf(f, " NULL\n"); else { for (int i = 0; i <= m->nNodes_global; ++i) fprintf(f, "%d\n", m->nodeElementOffsets[i]); int total = m->nodeElementOffsets[m->nNodes_global]; assert(total == m->nElements_global * m->nNodes_element); fprintf(f, "nodeElementsArray:\n"); for (int i = 0; i < total; ++i) fprintf(f, "%d\n", m->nodeElementsArray[i]); } fprintf(f, "elementNeighborsArray:\n"); print_int_2d(m->elementNeighborsArray, m->nElements_global, m->nElementBoundaries_element, f); fprintf(f, "elementBoundariesArray:\n"); print_int_2d(m->elementBoundariesArray, m->nElements_global, m->nElementBoundaries_element, f); fprintf(f, "elementBoundaryNodesArray:\n"); print_int_2d(m->elementBoundaryNodesArray, m->nElementBoundaries_global, m->nNodes_elementBoundary, f); fprintf(f, "elementBoundaryElementsArray:\n"); print_int_2d(m->elementBoundaryElementsArray, m->nElementBoundaries_global, 2, f); fprintf(f, "elementBoundaryLocalElementBoundariesArray:\n"); print_int_2d(m->elementBoundaryLocalElementBoundariesArray, m->nElementBoundaries_global, 2, f); fprintf(f, "interiorElementBoundariesArray:\n"); for (int i = 0; i < m->nInteriorElementBoundaries_global; ++i) fprintf(f, "%d\n", m->interiorElementBoundariesArray[i]); fprintf(f, "exteriorElementBoundariesArray:\n"); for (int i = 0; i < m->nExteriorElementBoundaries_global; ++i) fprintf(f, "%d\n", m->exteriorElementBoundariesArray[i]); fprintf(f, "edgeNodesArray:\n"); print_int_2d(m->edgeNodesArray, m->nEdges_global, 2, f); fprintf(f, "nodeStarOffsets:\n"); if (!m->nodeStarOffsets) fprintf(f, " NULL\n"); else { for (int i = 0; i <= m->nNodes_global; ++i) fprintf(f, "%d\n", m->nodeStarOffsets[i]); int total = m->nodeStarOffsets[m->nNodes_global]; assert(total == m->nEdges_global * 2); fprintf(f, "nodeStarArray:\n"); for (int i = 0; i < total; ++i) fprintf(f, "%d\n", m->nodeStarArray[i]); } fprintf(f, "elementMaterialTypes:\n"); for (int i = 0; i < m->nElements_global; ++i) fprintf(f, "%d\n", m->elementMaterialTypes[i]); fprintf(f, "elementBoundaryMaterialTypes:\n"); for (int i = 0; i < m->nElementBoundaries_global; ++i) fprintf(f, "%d\n", m->elementBoundaryMaterialTypes[i]); fprintf(f, "nodeMaterialTypes:\n"); for (int i = 0; i < m->nNodes_global; ++i) fprintf(f, "%d\n", m->nodeMaterialTypes[i]); fprintf(f, "nodeArray:\n"); print_double_2d(m->nodeArray, m->nNodes_global, 3, f); fprintf(f, "elementDiametersArray:\n"); for (int i = 0; i < m->nElements_global; ++i) fprintf(f, "%f\n", m->elementDiametersArray[i]); fprintf(f, "elementInnerDiametersArray:\n"); for (int i = 0; i < m->nElements_global; ++i) fprintf(f, "%f\n", m->elementInnerDiametersArray[i]); fprintf(f, "elementBoundaryDiametersArray:\n"); for (int i = 0; i < m->nElementBoundaries_global; ++i) fprintf(f, "%f\n", m->elementBoundaryDiametersArray[i]); fprintf(f, "elementBarycentersArray:\n"); print_double_2d(m->elementBarycentersArray, m->nElements_global, 3, f); print_double_2d(m->elementBoundaryBarycentersArray, m->nElementBoundaries_global, 3, f); fprintf(f, "nodeDiametersArray:\n"); for (int i = 0; i < m->nNodes_global; ++i) fprintf(f, "%f\n", m->nodeDiametersArray[i]); fprintf(f, "nodeSupportArray:\n"); for (int i = 0; i < m->nNodes_global; ++i) fprintf(f, "%f\n", m->nodeSupportArray[i]); fprintf(f, "h = %f\n", m->h); fprintf(f, "hMin = %f\n", m->hMin); fprintf(f, "sigmaMax = %f\n", m->sigmaMax); fprintf(f, "volume = %f\n", m->volume); } static void dump_proteus_parallel_arrays(Mesh* m, FILE* f) { int size = PCU_Comm_Peers(); fprintf(f, "elementOffsets_subdomain_owned:\n"); for (int i = 0; i <= size; ++i) fprintf(f, "%d\n", m->elementOffsets_subdomain_owned[i]); fprintf(f, "elementNumbering_subdomain2global:\n"); for (int i = 0; i < m->subdomainp->nElements_global; ++i) fprintf(f, "%d\n", m->elementNumbering_subdomain2global[i]); fprintf(f, "nodeOffsets_subdomain_owned:\n"); for (int i = 0; i <= size; ++i) fprintf(f, "%d\n", m->nodeOffsets_subdomain_owned[i]); fprintf(f, "nodeNumbering_subdomain2global:\n"); for (int i = 0; i < m->subdomainp->nNodes_global; ++i) fprintf(f, "%d\n", m->nodeNumbering_subdomain2global[i]); fprintf(f, "elementBoundaryOffsets_subdomain_owned:\n"); for (int i = 0; i <= size; ++i) fprintf(f, "%d\n", m->elementBoundaryOffsets_subdomain_owned[i]); fprintf(f, "elementBoundaryNumbering_subdomain2global:\n"); for (int i = 0; i < m->subdomainp->nElementBoundaries_global; ++i) fprintf(f, "%d\n", m->elementBoundaryNumbering_subdomain2global[i]); fprintf(f, "edgeOffsets_subdomain_owned:\n"); for (int i = 0; i <= size; ++i) fprintf(f, "%d\n", m->edgeOffsets_subdomain_owned[i]); fprintf(f, "edgeNumbering_subdomain2global:\n"); for (int i = 0; i < m->subdomainp->nEdges_global; ++i) fprintf(f, "%d\n", m->edgeNumbering_subdomain2global[i]); } void dump_proteus_mesh(Mesh* m, FILE* f) { fprintf(stderr,"%d dumping mesh file\n", PCU_Comm_Self()); if (PCU_Comm_Peers() > 1) { fprintf(f, "PARALLEL HEADER\n"); dump_proteus_mesh_header(m, f); fprintf(f, "PARALLEL ARRAYS\n"); dump_proteus_parallel_arrays(m, f); fprintf(f, "SUBDOMAIN\n"); dump_proteus_subdomain(m->subdomainp, f); } else { dump_proteus_subdomain(m, f); } }
40.960452
81
0.662345
[ "mesh" ]
dfd995f50449143c03cb20071e13af433f3f418e
7,476
cpp
C++
src/main/graph.cpp
kazuibasou/KDD2020
fc327ffc745c0cedbce85cfbffb606ac46df9a85
[ "MIT" ]
2
2020-11-07T05:50:39.000Z
2022-01-29T14:03:25.000Z
src/main/graph.cpp
kazuibasou/KDD2020
fc327ffc745c0cedbce85cfbffb606ac46df9a85
[ "MIT" ]
null
null
null
src/main/graph.cpp
kazuibasou/KDD2020
fc327ffc745c0cedbce85cfbffb606ac46df9a85
[ "MIT" ]
1
2021-05-12T04:51:52.000Z
2021-05-12T04:51:52.000Z
#include <iostream> #include <vector> #include <deque> #include <numeric> #include <random> #include <string.h> #include <stdio.h> #include <algorithm> #include <stdlib.h> #include "graph.h" //Sampled data for node v SampledData::SampledData(const int v){ index = v; ndata = std::vector<int>(); pubd = 0.0; d = 0.0; } SampledData::~SampledData(){ std::vector<int>().swap(ndata); } //Query node v SampledData Graph::Query(std::string model, const int v){ SampledData data(v); if(privacy[v] == 0){ data.ndata = nlist[v]; data.d = double(nlist[v].size()); } else{ data.ndata = std::vector<int>(); data.d = 0.0; } if(model == "ideal"){ data.pubd = double(pub_nlist[v].size()); } else if(model == "hidden"){ data.pubd = 0; } else{ printf("Error: Given model named %s is not defined.\n", model.c_str()); exit(0); } return data; } //graph structure Graph::Graph(){ N = 0; M = 0; nlist = std::vector<std::vector<int> >(); pub_nlist = std::vector<std::vector<int> >(); privacy = std::vector<int>(); } Graph::~Graph(){ std::vector<std::vector<int> >().swap(nlist); std::vector<std::vector<int> >().swap(pub_nlist); std::vector<int>().swap(privacy); } //connected subgraphs that consist of public nodes on graph PublicCluster::PublicCluster(const Graph &G){ N = 0; M = 0; V = std::vector<int>(); nlist = std::vector<std::vector<int> >(G.N,std::vector<int>(0)); } PublicCluster::~PublicCluster(){ std::vector<int>().swap(V); std::vector<std::vector<int> >().swap(nlist); } //read edge list of groph based on assumption that each node inndepedently becomes private with probability p. int Graph::readgraph(const char *graphdatafile,const char *readgraph){ FILE *gf; const char *dir = "../data/dataset/"; std::string gfpath = std::string(dir) + graphdatafile; gf = fopen(gfpath.c_str(), "r"); if(gf == NULL) { printf("Error: Could not open file named %s.\n",graphdatafile); exit(0); } char graphname[100]; int s = sizeof(readgraph)/sizeof(char); if(s > 100){ printf("Error: Length of name of readfile must be less than 100.\n"); exit(0); } int i,j; int frag = 0; std::string readfile = std::string(readgraph); while(fscanf(gf, "%s %d %d", graphname, &i , &j) != EOF) { if(strcmp(graphname,readfile.c_str()) == 0){ N = i; M = j; frag = 1; } } fclose(gf); if(frag == 0){ printf("Error: Could not find graph file named %s.txt.\n",readgraph); exit(0); } FILE *rf; std::string rfpath = std::string(dir) + std::string(readgraph) + ".txt"; rf = fopen(rfpath.c_str(), "r"); if(rf == NULL) { printf("Error: Could not open file named %s.txt.\n",readgraph); exit(0); } int x,y; nlist = std::vector<std::vector<int> >(N,std::vector<int>(0)); pub_nlist = std::vector<std::vector<int> >(N,std::vector<int>(0)); while(fscanf(rf, "%d %d", &x , &y) != EOF) { nlist[x].push_back(y); nlist[y].push_back(x); } fclose(rf); privacy = std::vector<int>(N,0); maxd = 0; for(i=0;i<N;++i){ std::sort(nlist[i].begin(),nlist[i].end()); if(int(nlist[i].size()) > maxd){ maxd = nlist[i].size(); } } return 0; } //read edge list of pokec graph int Graph::readpokec(const char *graphdatafile,const char *readgraph){ FILE *gf; const char *dir = "../data/dataset/"; std::string gfpath = std::string(dir) + graphdatafile; gf = fopen(gfpath.c_str(), "r"); if(gf == NULL) { printf("Error: Could not open file named %s.\n",graphdatafile); exit(0); } char graphname[100]; int s = sizeof(readgraph)/sizeof(char); if(s > 100){ printf("Error: Length of name of readfile must be less than 100.\n"); exit(0); } int i,j; int frag = 0; std::string readfile = std::string(readgraph); while(fscanf(gf, "%s %d %d", graphname, &i , &j) != EOF) { if(strcmp(graphname,readfile.c_str()) == 0){ N = i; M = j; frag = 1; } } fclose(gf); if(frag == 0){ printf("Error: Could not find graph file named %s.txt.\n",readgraph); exit(0); } FILE *rf; std::string rfpath = std::string(dir) + std::string(readgraph) + ".txt"; rf = fopen(rfpath.c_str(), "r"); if(rf == NULL) { printf("Error: Could not open file named %s.txt.\n",readgraph); exit(0); } int x,y; nlist = std::vector<std::vector<int> >(N,std::vector<int>(0)); pub_nlist = std::vector<std::vector<int> >(N,std::vector<int>(0)); while(fscanf(rf, "%d %d", &x , &y) != EOF) { nlist[x].push_back(y); nlist[y].push_back(x); } fclose(rf); maxd = 0; for(i=0;i<N;++i){ std::sort(nlist[i].begin(),nlist[i].end()); if(int(nlist[i].size()) > maxd){ maxd = nlist[i].size(); } } FILE *pf; std::string pfpath = std::string(dir) + std::string(readgraph) + "_privacy.txt"; pf = fopen(pfpath.c_str(), "r"); if(pf == NULL) { printf("Error: Could not open file named %s_privacy.txt.\n",readgraph); exit(0); } privacy = std::vector<int>(N,0); while(fscanf(pf, "%d %d", &x , &y) != EOF) { privacy[x] = y; } fclose(pf); return 0; } //Return a random integer from 0 to N-1 int generate_rand(const int N){ if(N == 0){ printf("Error: Given integer is zero.\n"); exit(0); } std::random_device rd; std::mt19937 mt(rd()); std::uniform_int_distribution<int> randN(0, N-1); return randN(mt); } //Return a random real number from 0.0 to 1.0 double generate_uniform_rand(){ std::random_device rd; std::mt19937 mt(rd()); std::uniform_real_distribution<double> uniformrand(0.0,1.0); return uniformrand(mt); } //Return a random real number from a to b double generate_uniform_rand_with_range(const double a,const double b){ std::random_device rd; std::mt19937 mt(rd()); std::uniform_real_distribution<double> uniformrand(a,b); return uniformrand(mt); } //Return the NRMSE obtained from estimate list double calc_NRMSE(const std::vector<double> &estimations,const double exact){ double nrmse = 0.0; int n = estimations.size(); double error; for(double estimation:estimations){ error = 1.0 - double(estimation)/exact; nrmse += double(error*error); } nrmse = double(nrmse)/n; nrmse = sqrt(nrmse); return nrmse; } //Set privacy labels of all nodes int Graph::set_privacy_labels(const double p){ privacy = std::vector<int>(N,0); double r; int i; for(i=0;i<N;++i){ r = generate_uniform_rand(); if(r <= p){ privacy[i] = 1; } } return 0; } //Return the largest public cluster of a graph with privacy labels PublicCluster return_LPC(Graph &G){ int i = 0; int j; int m = 0; int s = 0; int n = G.N; std::vector<int> search = G.privacy; PublicCluster LPC(G); while(std::accumulate(search.begin(), search.end(), 0) < n - m){ if(search[i] == 0){ PublicCluster PC(G); std::deque<int> Q; std::vector<int> visit(G.N,0); visit[i] = 1; Q.push_back(i); while(Q.empty() == false){ j = Q.front(); Q.pop_front(); PC.V.push_back(j); search[j] = 1; for(int k:G.nlist[j]){ if(G.privacy[k] == 0){ PC.nlist[j].push_back(k); if(visit[k] == 0){ visit[k] = 1; Q.push_back(k); } } } } s = PC.V.size(); if(s > m){ m = s; LPC.V = std::vector<int>(PC.V); LPC.nlist = std::vector<std::vector<int>>(PC.nlist); } } i += 1; } LPC.M = 0; for(int v:LPC.V){ LPC.M += LPC.nlist[v].size(); G.pub_nlist[v] = LPC.nlist[v]; } LPC.N = LPC.V.size(); LPC.M = int(LPC.M)/2; return LPC; } //Select a seed of a random walk int select_seed(PublicCluster LPC){ int index = generate_rand(LPC.N); return LPC.V[index]; }
22.183976
110
0.616774
[ "vector", "model" ]
dfdde3ffa605214cff1536a4fb31ef395e4fc324
10,914
cpp
C++
rt_manipulators_lib/src/hardware_joints.cpp
rt-net/rt_manipulators_cpp
311276d9f3a2cbdeb853947dd40b7d5a3700a633
[ "Apache-2.0" ]
7
2022-01-05T04:53:24.000Z
2022-03-10T05:28:28.000Z
rt_manipulators_lib/src/hardware_joints.cpp
rt-net/rt_manipulators_cpp
311276d9f3a2cbdeb853947dd40b7d5a3700a633
[ "Apache-2.0" ]
8
2022-02-07T02:57:25.000Z
2022-03-30T04:28:55.000Z
rt_manipulators_lib/src/hardware_joints.cpp
rt-net/rt_manipulators_cpp
311276d9f3a2cbdeb853947dd40b7d5a3700a633
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 RT Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <iostream> #include "hardware_joints.hpp" namespace hardware_joints { const group_map_t Joints::groups() const { return joint_groups_; } void Joints::append_group(const group_name_t & group_name, const joint::JointGroup & group) { auto joint_group_ptr = std::make_shared<joint::JointGroup>(group); joint_groups_.emplace(group_name, joint_group_ptr); } void Joints::append_joint(const joint_name_t & joint_name, const joint::Joint & joint) { auto joint_ptr = std::make_shared<joint::Joint>(joint); all_joints_.emplace(joint_name, joint_ptr); // IDからもJointにアクセスできる all_joints_ref_from_id_.emplace(joint.id(), joint_ptr); } std::shared_ptr<joint::JointGroup> Joints::group(const group_name_t & name) { return joint_groups_.at(name); } std::shared_ptr<joint::Joint> Joints::joint(const joint_name_t & name) { return all_joints_.at(name); } std::shared_ptr<joint::Joint> Joints::joint(const dxl_id_t & id) { return all_joints_ref_from_id_.at(id); } bool Joints::has_group(const group_name_t & name) { return joint_groups_.find(name) != joint_groups_.end(); } bool Joints::has_joint(const joint_name_t & name) { return all_joints_.find(name) != all_joints_.end(); } bool Joints::has_joint(const dxl_id_t & id) { return all_joints_ref_from_id_.find(id) != all_joints_ref_from_id_.end(); } bool Joints::get_position(const dxl_id_t & id, position_t & position) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } position = joint(id)->get_present_position(); return true; } bool Joints::get_position(const joint_name_t & joint_name, position_t & position) { if (!has_joint(joint_name)) { std::cerr << joint_name << "ジョイントは存在しません." << std::endl; return false; } position = joint(joint_name)->get_present_position(); return true; } bool Joints::get_positions(const group_name_t & group_name, std::vector<position_t> & positions) { if (!has_group(group_name)) { std::cerr << group_name << "はjoint_groupsに存在しません." << std::endl; return false; } for (const auto & joint_name : joint_groups_.at(group_name)->joint_names()) { positions.push_back(joint(joint_name)->get_present_position()); } return true; } bool Joints::get_velocity(const dxl_id_t & id, velocity_t & velocity) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } velocity = joint(id)->get_present_velocity(); return true; } bool Joints::get_velocity(const joint_name_t & joint_name, velocity_t & velocity) { if (!has_joint(joint_name)) { std::cerr << joint_name << "ジョイントは存在しません." << std::endl; return false; } velocity = joint(joint_name)->get_present_velocity(); return true; } bool Joints::get_velocities(const group_name_t & group_name, std::vector<velocity_t> & velocities) { if (!has_group(group_name)) { std::cerr << group_name << "はjoint_groupsに存在しません." << std::endl; return false; } for (const auto & joint_name : joint_groups_.at(group_name)->joint_names()) { velocities.push_back(joint(joint_name)->get_present_velocity()); } return true; } bool Joints::get_current(const dxl_id_t & id, current_t & current) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } current = joint(id)->get_present_current(); return true; } bool Joints::get_current(const joint_name_t & joint_name, current_t & current) { if (!has_joint(joint_name)) { std::cerr << joint_name << "ジョイントは存在しません." << std::endl; return false; } current = joint(joint_name)->get_present_current(); return true; } bool Joints::get_currents(const group_name_t & group_name, std::vector<current_t>& currents) { if (!has_group(group_name)) { std::cerr << group_name << "はjoint_groupsに存在しません." << std::endl; return false; } for (const auto & joint_name : joint_groups_.at(group_name)->joint_names()) { currents.push_back(joint(joint_name)->get_present_current()); } return true; } bool Joints::get_voltage(const dxl_id_t id, voltage_t & voltage) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } voltage = joint(id)->get_present_voltage(); return true; } bool Joints::get_voltage(const joint_name_t & joint_name, voltage_t & voltage) { if (!has_joint(joint_name)) { std::cerr << joint_name << "ジョイントは存在しません." << std::endl; return false; } voltage = joint(joint_name)->get_present_voltage(); return true; } bool Joints::get_voltages(const group_name_t & group_name, std::vector<voltage_t>& voltages) { if (!has_group(group_name)) { std::cerr << group_name << "はjoint_groupsに存在しません." << std::endl; return false; } for (const auto & joint_name : joint_groups_.at(group_name)->joint_names()) { voltages.push_back(joint(joint_name)->get_present_voltage()); } return true; } bool Joints::get_temperature(const dxl_id_t & id, temperature_t & temperature) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } temperature = joint(id)->get_present_temperature(); return true; } bool Joints::get_temperature(const joint_name_t & joint_name, temperature_t & temperature) { if (!has_joint(joint_name)) { std::cerr << joint_name << "ジョイントは存在しません." << std::endl; return false; } temperature = joint(joint_name)->get_present_temperature(); return true; } bool Joints::get_temperatures( const group_name_t & group_name, std::vector<temperature_t>& temperatures) { if (!has_group(group_name)) { std::cerr << group_name << "はjoint_groupsに存在しません." << std::endl; return false; } for (const auto & joint_name : joint_groups_.at(group_name)->joint_names()) { temperatures.push_back(joint(joint_name)->get_present_temperature()); } return true; } bool Joints::get_max_position_limit(const dxl_id_t & id, position_t & max_position_limit) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } max_position_limit = joint(id)->max_position_limit(); return true; } bool Joints::get_min_position_limit(const dxl_id_t & id, position_t & min_position_limit) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } min_position_limit = joint(id)->min_position_limit(); return true; } bool Joints::set_position(const dxl_id_t & id, const position_t & position) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } joint(id)->set_goal_position(position); return true; } bool Joints::set_position(const joint_name_t & joint_name, const position_t & position) { if (!has_joint(joint_name)) { std::cerr << joint_name << "ジョイントは存在しません." << std::endl; return false; } joint(joint_name)->set_goal_position(position); return true; } bool Joints::set_positions( const group_name_t & group_name, const std::vector<position_t> & positions) { if (!has_group(group_name)) { std::cerr << group_name << "はjoint_groupsに存在しません." << std::endl; return false; } if (joint_groups_.at(group_name)->joint_names().size() != positions.size()) { std::cerr << "目標値のサイズ:" << positions.size(); std::cerr << "がジョイント数:" << joint_groups_.at(group_name)->joint_names().size(); std::cerr << "と一致しません." << std::endl; return false; } for (size_t i = 0; i < positions.size(); i++) { auto joint_name = joint_groups_.at(group_name)->joint_names()[i]; joint(joint_name)->set_goal_position(positions[i]); } return true; } bool Joints::set_velocity(const dxl_id_t & id, const velocity_t & velocity) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } joint(id)->set_goal_velocity(velocity); return true; } bool Joints::set_velocity(const joint_name_t & joint_name, const velocity_t & velocity) { if (!has_joint(joint_name)) { std::cerr << joint_name << "ジョイントは存在しません." << std::endl; return false; } joint(joint_name)->set_goal_velocity(velocity); return true; } bool Joints::set_velocities( const group_name_t & group_name, const std::vector<velocity_t>& velocities) { if (!has_group(group_name)) { std::cerr << group_name << "はjoint_groupsに存在しません." << std::endl; return false; } if (joint_groups_.at(group_name)->joint_names().size() != velocities.size()) { std::cerr << "目標値のサイズ:" << velocities.size(); std::cerr << "がジョイント数:" << joint_groups_.at(group_name)->joint_names().size(); std::cerr << "と一致しません." << std::endl; return false; } for (size_t i = 0; i < velocities.size(); i++) { auto joint_name = joint_groups_.at(group_name)->joint_names()[i]; joint(joint_name)->set_goal_velocity(velocities[i]); } return true; } bool Joints::set_current(const dxl_id_t & id, const current_t & current) { if (!has_joint(id)) { std::cerr << "ID:" << std::to_string(id) << "のジョイントは存在しません." << std::endl; return false; } joint(id)->set_goal_current(current); return true; } bool Joints::set_current(const joint_name_t & joint_name, const current_t & current) { if (!has_joint(joint_name)) { std::cerr << joint_name << "ジョイントは存在しません." << std::endl; return false; } joint(joint_name)->set_goal_current(current); return true; } bool Joints::set_currents(const group_name_t & group_name, const std::vector<current_t>& currents) { if (!has_group(group_name)) { std::cerr << group_name << "はjoint_groupsに存在しません." << std::endl; return false; } if (joint_groups_.at(group_name)->joint_names().size() != currents.size()) { std::cerr << "目標値のサイズ:" << currents.size(); std::cerr << "がジョイント数:" << joint_groups_.at(group_name)->joint_names().size(); std::cerr << "と一致しません." << std::endl; return false; } for (size_t i = 0; i < currents.size(); i++) { auto joint_name = joint_groups_.at(group_name)->joint_names()[i]; joint(joint_name)->set_goal_current(currents[i]); } return true; } } // namespace hardware_joints
30.917847
100
0.683434
[ "vector" ]
dfdf29baa8424943e64db9978493c1926ec0aa0d
4,278
cpp
C++
07_Project/CutFirewood/Source/Game/Combo/Combo.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
07_Project/CutFirewood/Source/Game/Combo/Combo.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
07_Project/CutFirewood/Source/Game/Combo/Combo.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* ----------------------------------------------------------------------------------- * * File Combo.cpp * Ported By Young-Hwan Mun * Contact xmsoft77@gmail.com * * ----------------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft * Copyright (c) 2011 FOWCOM. All rights reserved. * * ----------------------------------------------------------------------------------- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * ----------------------------------------------------------------------------------- */ #include "Precompiled.h" #include "Combo.h" #include "Object/Sprite/Sprite.h" #include "Object/Label/LabelAtlasCostom.h" cCombo::cCombo ( JBaseScene* pScene ) : m_pScene ( pScene ) , m_pSprite ( nullptr ) , m_pLabel ( nullptr ) , m_nComboCount ( 0 ) , m_bIsScale ( false ) , m_bIsScaleAdd ( false ) , m_fScale ( 0 ) { // sprite m_pSprite = new cSprite ( "combo.png", eLayerGame_Combo, Point ( 2, 260 ) ); m_pSprite->setIsVisible ( false ); pScene->addDrawObject ( m_pSprite ); // label m_pLabel = new cLabelAtlasCostom ( "combo_num.png", 31, eLayerGame_Score, Point ( 43, 240 ) ); m_pLabel->addCharInfo ( '1', 0, 22, 18 ); m_pLabel->addCharInfo ( '2', 24, 35, 28 ); m_pLabel->addCharInfo ( '3', 61, 35, 28 ); m_pLabel->addCharInfo ( '4', 98, 35, 28 ); m_pLabel->addCharInfo ( '5', 135, 35, 28 ); m_pLabel->addCharInfo ( '6', 173, 35, 28 ); m_pLabel->addCharInfo ( '7', 210, 35, 28 ); m_pLabel->addCharInfo ( '8', 246, 36, 28 ); m_pLabel->addCharInfo ( '9', 283, 35, 28 ); m_pLabel->addCharInfo ( '0', 320, 35, 28 ); m_pLabel->setIsVisible ( false ); m_pLabel->setAnchorPoint ( Point ( 0.5f, 0.5f ) ); m_pLabel->setString ( "" ); pScene->addDrawObject ( m_pLabel ); } cCombo::~cCombo ( KDvoid ) { m_pSprite = nullptr; m_pLabel = nullptr; } KDvoid cCombo::setAdd ( KDvoid ) { // count ++m_nComboCount; // check if ( m_nComboCount <= 1 ) { return; } // sprite m_pSprite->setIsVisible ( true ); //label m_pLabel->setIsVisible ( true ); m_pLabel->setString ( String::createWithFormat ( "%d", m_nComboCount )->getCString ( ) ); Point tPoint = m_pLabel->getPoint ( ); if ( 43 - (KDint) ( m_pLabel->getSize ( ).width / 2 ) < 3 ) tPoint.x = 3 + (KDint) ( m_pLabel->getSize ( ).width / 2 ); else tPoint.x = 43; m_pLabel->setPoint ( tPoint ); // scale m_bIsScale = true; m_bIsScaleAdd = true; m_fScale = 1; } KDvoid cCombo::setZero ( KDvoid ) { // count m_nComboCount = 0; // sprite m_pSprite->setIsVisible ( false ); //label m_pLabel->setIsVisible ( false ); // scale m_bIsScale = false; m_bIsScaleAdd = false; } KDvoid cCombo::update ( KDdouble dLeftTime ) { if ( m_bIsScale == true ) { if ( m_bIsScaleAdd == true ) { m_fScale += dLeftTime * 3; if ( m_fScale > 1.5f ) { m_fScale = 1.5f; m_bIsScaleAdd = false; } } else { m_fScale -= dLeftTime * 3; if ( m_fScale < 1 ) { m_fScale = 1; m_bIsScale = false; } } m_pLabel->setScale ( m_fScale ); } else { m_pLabel->setScale ( 1 ); } }
28.711409
132
0.585554
[ "object" ]
dfe958859e64d2ff167b214a7104957ed50ac188
1,106
hpp
C++
libs/core/include/fcppt/mpl/map/keys.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
libs/core/include/fcppt/mpl/map/keys.hpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
libs/core/include/fcppt/mpl/map/keys.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_MPL_MAP_KEYS_HPP_INCLUDED #define FCPPT_MPL_MAP_KEYS_HPP_INCLUDED #include <fcppt/mpl/map/element_concept.hpp> #include <fcppt/mpl/map/element_key.hpp> #include <fcppt/mpl/map/object_concept.hpp> #include <fcppt/mpl/map/object_fwd.hpp> #include <fcppt/mpl/set/object_fwd.hpp> namespace fcppt::mpl::map { namespace detail { template<typename Map> struct keys; template<fcppt::mpl::map::element_concept... Elements> struct keys<fcppt::mpl::map::object<Elements...>> { using type = fcppt::mpl::set::object<fcppt::mpl::map::element_key<Elements>...>; }; } /** \brief They keys of a map as a set. \ingroup fcpptmpl Let <code>Map = map::object<element<K_1,V_1>,...,element<K_n,V_n>></code>. Then the result is \code set::object<K_1,...,K_n> \endcode */ template<fcppt::mpl::map::object_concept Map> using keys = typename fcppt::mpl::map::detail::keys<Map>::type; } #endif
26.97561
82
0.724231
[ "object" ]
5f0236e4701a10bcdce76c37b273612d25ee1b72
6,659
cc
C++
chrome/browser/autocomplete/autocomplete_edit_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-02-20T14:25:04.000Z
2019-12-13T13:58:28.000Z
chrome/browser/autocomplete/autocomplete_edit_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
chrome/browser/autocomplete/autocomplete_edit_unittest.cc
SlimKatLegacy/android_external_chromium
bc611cda58cc18d0dbaa8a7aee05eb3c0742e573
[ "BSD-3-Clause" ]
2
2017-08-09T09:03:23.000Z
2020-05-26T09:14:49.000Z
// Copyright (c) 2011 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/utf_string_conversions.h" #include "chrome/browser/autocomplete/autocomplete_edit.h" #include "chrome/browser/autocomplete/autocomplete_edit_view.h" #include "chrome/test/testing_browser_process.h" #include "chrome/test/testing_profile.h" #include "third_party/skia/include/core/SkBitmap.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class TestingAutocompleteEditView : public AutocompleteEditView { public: TestingAutocompleteEditView() {} virtual AutocompleteEditModel* model() { return NULL; } virtual const AutocompleteEditModel* model() const { return NULL; } virtual void SaveStateToTab(TabContents* tab) {} virtual void Update(const TabContents* tab_for_state_restoring) {} virtual void OpenURL(const GURL& url, WindowOpenDisposition disposition, PageTransition::Type transition, const GURL& alternate_nav_url, size_t selected_line, const string16& keyword) {} virtual string16 GetText() const { return string16(); } virtual bool IsEditingOrEmpty() const { return true; } virtual int GetIcon() const { return 0; } virtual void SetUserText(const string16& text) {} virtual void SetUserText(const string16& text, const string16& display_text, bool update_popup) {} virtual void SetWindowTextAndCaretPos(const string16& text, size_t caret_pos) {} virtual void SetForcedQuery() {} virtual bool IsSelectAll() { return false; } virtual bool DeleteAtEndPressed() { return false; } virtual void GetSelectionBounds(string16::size_type* start, string16::size_type* end) {} virtual void SelectAll(bool reversed) {} virtual void RevertAll() {} virtual void UpdatePopup() {} virtual void ClosePopup() {} virtual void SetFocus() {} virtual void OnTemporaryTextMaybeChanged(const string16& display_text, bool save_original_selection) {} virtual bool OnInlineAutocompleteTextMaybeChanged( const string16& display_text, size_t user_text_length) { return false; } virtual void OnRevertTemporaryText() {} virtual void OnBeforePossibleChange() {} virtual bool OnAfterPossibleChange() { return false; } virtual gfx::NativeView GetNativeView() const { return 0; } virtual CommandUpdater* GetCommandUpdater() { return NULL; } virtual void SetInstantSuggestion(const string16& input, bool animate_to_complete) {} virtual string16 GetInstantSuggestion() const { return string16(); } virtual int TextWidth() const { return 0; } virtual bool IsImeComposing() const { return false; } #if defined(TOOLKIT_VIEWS) virtual views::View* AddToView(views::View* parent) { return NULL; } virtual int OnPerformDrop(const views::DropTargetEvent& event) { return 0; } #endif private: DISALLOW_COPY_AND_ASSIGN(TestingAutocompleteEditView); }; class TestingAutocompleteEditController : public AutocompleteEditController { public: TestingAutocompleteEditController() {} virtual void OnAutocompleteAccept(const GURL& url, WindowOpenDisposition disposition, PageTransition::Type transition, const GURL& alternate_nav_url) OVERRIDE {} virtual void OnChanged() OVERRIDE {} virtual void OnSelectionBoundsChanged() OVERRIDE {} virtual void OnInputInProgress(bool in_progress) OVERRIDE {} virtual void OnKillFocus() OVERRIDE {} virtual void OnSetFocus() OVERRIDE {} virtual SkBitmap GetFavicon() const OVERRIDE { return SkBitmap(); } virtual string16 GetTitle() const OVERRIDE { return string16(); } virtual InstantController* GetInstant() OVERRIDE { return NULL; } virtual TabContentsWrapper* GetTabContentsWrapper() const OVERRIDE { return NULL; } private: DISALLOW_COPY_AND_ASSIGN(TestingAutocompleteEditController); }; } typedef testing::Test AutocompleteEditTest; // Tests various permutations of AutocompleteModel::AdjustTextForCopy. TEST(AutocompleteEditTest, AdjustTextForCopy) { struct Data { const char* perm_text; const int sel_start; const bool is_all_selected; const char* input; const char* expected_output; const bool write_url; const char* expected_url; } input[] = { // Test that http:// is inserted if all text is selected. { "a.b/c", 0, true, "a.b/c", "http://a.b/c", true, "http://a.b/c" }, // Test that http:// is inserted if the host is selected. { "a.b/c", 0, false, "a.b/", "http://a.b/", true, "http://a.b/" }, // Tests that http:// is inserted if the path is modified. { "a.b/c", 0, false, "a.b/d", "http://a.b/d", true, "http://a.b/d" }, // Tests that http:// isn't inserted if the host is modified. { "a.b/c", 0, false, "a.c/", "a.c/", false, "" }, // Tests that http:// isn't inserted if the start of the selection is 1. { "a.b/c", 1, false, "a.b/", "a.b/", false, "" }, // Tests that http:// isn't inserted if a portion of the host is selected. { "a.com/", 0, false, "a.co", "a.co", false, "" }, // Tests that http:// isn't inserted for an https url after the user nukes // https. { "https://a.com/", 0, false, "a.com/", "a.com/", false, "" }, // Tests that http:// isn't inserted if the user adds to the host. { "a.b/", 0, false, "a.bc/", "a.bc/", false, "" }, // Tests that we don't get double http if the user manually inserts http. { "a.b/", 0, false, "http://a.b/", "http://a.b/", true, "http://a.b/" }, }; ScopedTestingBrowserProcess browser_process; TestingAutocompleteEditView view; TestingAutocompleteEditController controller; TestingProfile profile; AutocompleteEditModel model(&view, &controller, &profile); for (size_t i = 0; i < ARRAYSIZE_UNSAFE(input); ++i) { model.UpdatePermanentText(ASCIIToUTF16(input[i].perm_text)); string16 result = ASCIIToUTF16(input[i].input); GURL url; bool write_url; model.AdjustTextForCopy(input[i].sel_start, input[i].is_all_selected, &result, &url, &write_url); EXPECT_EQ(ASCIIToUTF16(input[i].expected_output), result) << "@: " << i; EXPECT_EQ(input[i].write_url, write_url) << " @" << i; if (write_url) EXPECT_EQ(input[i].expected_url, url.spec()) << " @" << i; } }
41.61875
78
0.664664
[ "model" ]
5f138f652ee3499d537984b9820669f1092ccd1f
2,055
cc
C++
alidns/src/model/CopyGtmConfigRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
alidns/src/model/CopyGtmConfigRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
alidns/src/model/CopyGtmConfigRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/alidns/model/CopyGtmConfigRequest.h> using AlibabaCloud::Alidns::Model::CopyGtmConfigRequest; CopyGtmConfigRequest::CopyGtmConfigRequest() : RpcServiceRequest("alidns", "2015-01-09", "CopyGtmConfig") { setMethod(HttpRequest::Method::Post); } CopyGtmConfigRequest::~CopyGtmConfigRequest() {} std::string CopyGtmConfigRequest::getSourceId()const { return sourceId_; } void CopyGtmConfigRequest::setSourceId(const std::string& sourceId) { sourceId_ = sourceId; setParameter("SourceId", sourceId); } std::string CopyGtmConfigRequest::getTargetId()const { return targetId_; } void CopyGtmConfigRequest::setTargetId(const std::string& targetId) { targetId_ = targetId; setParameter("TargetId", targetId); } std::string CopyGtmConfigRequest::getCopyType()const { return copyType_; } void CopyGtmConfigRequest::setCopyType(const std::string& copyType) { copyType_ = copyType; setParameter("CopyType", copyType); } std::string CopyGtmConfigRequest::getUserClientIp()const { return userClientIp_; } void CopyGtmConfigRequest::setUserClientIp(const std::string& userClientIp) { userClientIp_ = userClientIp; setParameter("UserClientIp", userClientIp); } std::string CopyGtmConfigRequest::getLang()const { return lang_; } void CopyGtmConfigRequest::setLang(const std::string& lang) { lang_ = lang; setParameter("Lang", lang); }
24.176471
76
0.742092
[ "model" ]
5f13c42dd9980ac28de27d0fe8000b2beb2ed8b4
4,160
cpp
C++
BLEEPlib/src/BL2_peer_connectivity/AddrManager.cpp
kaistshadow/blockchain-sim
e0dbd23916b9a7ef24c3db6f43e969a63ad6b1f3
[ "MIT" ]
1
2021-09-17T14:18:11.000Z
2021-09-17T14:18:11.000Z
BLEEPlib/src/BL2_peer_connectivity/AddrManager.cpp
kaistshadow/blockchain-sim
e0dbd23916b9a7ef24c3db6f43e969a63ad6b1f3
[ "MIT" ]
12
2018-06-01T12:29:51.000Z
2021-12-11T06:58:01.000Z
BLEEPlib/src/BL2_peer_connectivity/AddrManager.cpp
kaistshadow/blockchain-sim
e0dbd23916b9a7ef24c3db6f43e969a63ad6b1f3
[ "MIT" ]
null
null
null
// "Copyright [2021] <kaistshadow>" #include <string> #include <memory> #include "AddrManager.h" using namespace libBLEEP_BL; #include "utility/UInt256.h" #include "utility/GlobalClock.h" #include "utility/Random.h" #include "crypto/SHA256.h" // private methods int AddrManager::GetNewBucket(Address& addr) { // h = H(domain address) // new_bucket = h % 1024 std::cout << "getnewbucket" << "\n"; unsigned char hash_buf[SHA256_BLOCK_SIZE]; SHA256_CTX ctx; sha256_init(&ctx); std::string addrStr = addr.GetString(); std::cout << "addrStr:" << addrStr << "\n"; sha256_update(&ctx, addrStr.c_str(), addrStr.size()); sha256_final(&ctx, hash_buf); libBLEEP::UINT256_t hash(hash_buf, 32); hash = hash % 1024; uint64_t Nbucket = hash.getint(); std::cout << "1024 mod result:" << Nbucket << "\n"; return Nbucket; } int AddrManager::GetBucketPosition(Address& addr, int Nbucket) { // new_slot = H(domain address, new_bucket) % 64 unsigned char hash_buf[SHA256_BLOCK_SIZE]; SHA256_CTX ctx; sha256_init(&ctx); std::string addrStr = addr.GetString(); sha256_update(&ctx, addrStr.c_str(), addrStr.size()); sha256_update(&ctx, (unsigned char*)&Nbucket, sizeof(int)); sha256_final(&ctx, hash_buf); libBLEEP::UINT256_t hash(hash_buf, 32); hash = hash % 64; uint64_t bucketPos = hash.getint(); std::cout << "bucket position:" << bucketPos << "\n"; return bucketPos; } // public methods AddrManager::AddrManager() { for (int bucket = 0; bucket < NUM_BUCKET; bucket++) { for (int entry = 0; entry < BUCKET_SIZE; entry++) { vvNew[bucket][entry] = -1; } } nIdCount = 0; } void AddrManager::Add(Address addr) { int bucket = GetNewBucket(addr); int bucketPosition = GetBucketPosition(addr, bucket); bool fInsert = (vvNew[bucket][bucketPosition] == -1); if (!fInsert) { // if there's already valid address in bucket // check whether it is same address or not // if it's the same address, update the timestamp. // otherwise just ignore the new address. // (TODO : replacement algorithm should be implemented) int existAddrId = vvNew[bucket][bucketPosition]; if (mapAddr[existAddrId].GetString() == addr.GetString()) { mapAddr[existAddrId].UpdateTimestamp(libBLEEP::GetGlobalClock()); } // // remove prev addr // mapAddr.erase(vvNew[bucket][bucketPosition]); // // overwrite // vvNew[bucket][bucketPosition] = addrId; // mapAddr[addrId] = addr; } else if (fInsert) { int addrId = nIdCount++; vvNew[bucket][bucketPosition] = addrId; mapAddr[addrId] = addr; } } std::vector<Address> AddrManager::GetAddresses() { // return randomly generated address vector std::vector<Address> vAddr; // get all ids std::vector<int> vIds; vIds.reserve(mapAddr.size()); for (auto const& imap : mapAddr) { vIds.push_back(imap.first); } // random shuffle auto rng = *(libBLEEP::get_global_random_source().get_default_random_source()); std::shuffle(std::begin(vIds), std::end(vIds), rng); for (unsigned int n = 0; n < vIds.size(); n++) { if (vAddr.size() >= 1000) // maximum size of address vector is 1000 break; const Address& addr = mapAddr[vIds[n]]; vAddr.push_back(addr); } return vAddr; } std::shared_ptr<Address> AddrManager::SelectAddressFromTable() { if (mapAddr.size() == 0) return nullptr; // get all ids std::vector<int> vIds; vIds.reserve(mapAddr.size()); for (auto const& imap : mapAddr) vIds.push_back(imap.first); // random shuffle auto rng = *(libBLEEP::get_global_random_source().get_default_random_source()); std::shuffle(std::begin(vIds), std::end(vIds), rng); return std::make_shared<Address>(mapAddr[vIds[0]]); } void AddrManager::PrintAddressTable() { std::cout << "stored addr num:" << mapAddr.size() << "\n"; for (auto x : mapAddr) { std::cout << x.second.GetString() << "\n"; } }
30.814815
83
0.625962
[ "vector" ]
5f1c8255772dcfebfed282a7ac57e518f08e0761
37,983
cpp
C++
aten/src/ATen/native/GridSampler.cpp
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
1
2019-07-21T02:13:22.000Z
2019-07-21T02:13:22.000Z
aten/src/ATen/native/GridSampler.cpp
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
aten/src/ATen/native/GridSampler.cpp
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
#include "ATen/ATen.h" #include "ATen/NativeFunctions.h" #include "ATen/detail/CUDAHooksInterface.h" #include "ATen/native/GridSampler.h" #ifdef _OPENMP #include <omp.h> #endif namespace at { namespace native { using at::native::detail::GridSamplerInterpolation; using at::native::detail::GridSamplerPadding; namespace { static inline int64_t clip_coordinates(int64_t in, int64_t clip_limit) { return std::min(clip_limit - 1, std::max(in, static_cast<int64_t>(0))); } static inline bool within_bounds_2d(int64_t h, int64_t w, int64_t H, int64_t W) { return h >= 0 && h < H && w >= 0 && w < W; } static inline bool within_bounds_3d(int64_t d, int64_t h, int64_t w, int64_t D, int64_t H, int64_t W) { return d >= 0 && d < D && h >= 0 && h < H && w >= 0 && w < W; } template<typename scalar_t> static inline void safe_add_2d(scalar_t *data, int64_t h, int64_t w, int64_t sH, int64_t sW, int64_t H, int64_t W, scalar_t delta) { if (within_bounds_2d(h, w, H, W)) { data[h * sH + w * sW] += delta; } } template<typename scalar_t> static inline void safe_add_3d(scalar_t *data, int64_t d, int64_t h, int64_t w, int64_t sD, int64_t sH, int64_t sW, int64_t D, int64_t H, int64_t W, scalar_t delta) { if (within_bounds_3d(d, h, w, D, H, W)) { data[d * sD + h * sH + w * sW] += delta; } } template<typename scalar_t> Tensor grid_sampler2d_cpu_impl(const Tensor& input, const Tensor& grid, GridSamplerInterpolation interpolation_mode, GridSamplerPadding padding_mode) { int64_t N = input.size(0); int64_t C = input.size(1); int64_t inp_H = input.size(2); int64_t inp_W = input.size(3); int64_t out_H = grid.size(1); int64_t out_W = grid.size(2); auto output = at::empty({N, C, out_H, out_W}, input.options()); int64_t inp_sN = input.stride(0); int64_t inp_sC = input.stride(1); int64_t inp_sH = input.stride(2); int64_t inp_sW = input.stride(3); int64_t grid_sN = grid.stride(0); int64_t grid_sH = grid.stride(1); int64_t grid_sW = grid.stride(2); int64_t grid_sCoor = grid.stride(3); int64_t out_sN = output.stride(0); int64_t out_sC = output.stride(1); int64_t out_sH = output.stride(2); int64_t out_sW = output.stride(3); scalar_t *inp_ptr = input.data<scalar_t>(); scalar_t *out_ptr = output.data<scalar_t>(); scalar_t *grid_ptr = grid.data<scalar_t>(); // loop over each output pixel #ifdef _OPENMP #pragma omp parallel for #endif for (int64_t n = 0; n < N; ++n) { scalar_t *grid_ptr_N = grid_ptr + n * grid_sN; scalar_t *inp_ptr_N = inp_ptr + n * inp_sN; for (int64_t h = 0; h < out_H; ++h) { for (int64_t w = 0; w < out_W; ++w) { // get the corresponding input x, y co-ordinates from grid scalar_t ix = grid_ptr_N[h * grid_sH + w * grid_sW]; scalar_t iy = grid_ptr_N[h * grid_sH + w * grid_sW + grid_sCoor]; // normalize ix, iy from [-1, 1] to [0, inp_W-1] & [0, inp_H-1] ix = ((ix + 1) / 2) * (inp_W - 1); iy = ((iy + 1) / 2) * (inp_H - 1); // get NE, NW, SE, SW pixel values from (x, y) int64_t ix_nw = static_cast<int64_t>(std::floor(ix)); int64_t iy_nw = static_cast<int64_t>(std::floor(iy)); int64_t ix_ne = ix_nw + 1; int64_t iy_ne = iy_nw; int64_t ix_sw = ix_nw; int64_t iy_sw = iy_nw + 1; int64_t ix_se = ix_nw + 1; int64_t iy_se = iy_nw + 1; // get surfaces to each neighbor: scalar_t nw = (ix_se - ix) * (iy_se - iy); scalar_t ne = (ix - ix_sw) * (iy_sw - iy); scalar_t sw = (ix_ne - ix) * (iy - iy_ne); scalar_t se = (ix - ix_nw) * (iy - iy_nw); if (padding_mode == GridSamplerPadding::Border) { // clip coordinates to image borders ix_nw = clip_coordinates(ix_nw, inp_W); iy_nw = clip_coordinates(iy_nw, inp_H); ix_ne = clip_coordinates(ix_ne, inp_W); iy_ne = clip_coordinates(iy_ne, inp_H); ix_sw = clip_coordinates(ix_sw, inp_W); iy_sw = clip_coordinates(iy_sw, inp_H); ix_se = clip_coordinates(ix_se, inp_W); iy_se = clip_coordinates(iy_se, inp_H); } // calculate bilinear weighted pixel value and set output pixel scalar_t *out_ptr_NCHW = out_ptr + n * out_sN + h * out_sH + w * out_sW; scalar_t *inp_ptr_NC = inp_ptr_N; for (int c = 0; c < C; ++c, out_ptr_NCHW += out_sC, inp_ptr_NC += inp_sC) { // (c, iy_nw, ix_nw) * nw + (c, iy_ne, ix_ne) * ne // + (c, iy_sw, ix_sw) * sw + (c, iy_se, ix_se) * se *out_ptr_NCHW = static_cast<scalar_t>(0); if (padding_mode != GridSamplerPadding::Zeros || within_bounds_2d(iy_nw, ix_nw, inp_H, inp_W)) { *out_ptr_NCHW += inp_ptr_NC[iy_nw * inp_sH + ix_nw * inp_sW] * nw; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_2d(iy_ne, ix_ne, inp_H, inp_W)) { *out_ptr_NCHW += inp_ptr_NC[iy_ne * inp_sH + ix_ne * inp_sW] * ne; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_2d(iy_sw, ix_sw, inp_H, inp_W)) { *out_ptr_NCHW += inp_ptr_NC[iy_sw * inp_sH + ix_sw * inp_sW] * sw; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_2d(iy_se, ix_se, inp_H, inp_W)) { *out_ptr_NCHW += inp_ptr_NC[iy_se * inp_sH + ix_se * inp_sW] * se; } } } } } return output; } template<typename scalar_t> Tensor grid_sampler3d_cpu_impl(const Tensor& input, const Tensor& grid, GridSamplerInterpolation interpolation_mode, GridSamplerPadding padding_mode) { int64_t N = input.size(0); int64_t C = input.size(1); int64_t inp_D = input.size(2); int64_t inp_H = input.size(3); int64_t inp_W = input.size(4); int64_t out_D = grid.size(1); int64_t out_H = grid.size(2); int64_t out_W = grid.size(3); auto output = at::empty({N, C, out_D, out_H, out_W}, input.options()); int64_t inp_sN = input.stride(0); int64_t inp_sC = input.stride(1); int64_t inp_sD = input.stride(2); int64_t inp_sH = input.stride(3); int64_t inp_sW = input.stride(4); int64_t grid_sN = grid.stride(0); int64_t grid_sD = grid.stride(1); int64_t grid_sH = grid.stride(2); int64_t grid_sW = grid.stride(3); int64_t grid_sCoor = grid.stride(4); int64_t out_sN = output.stride(0); int64_t out_sC = output.stride(1); int64_t out_sD = output.stride(2); int64_t out_sH = output.stride(3); int64_t out_sW = output.stride(4); scalar_t *inp_ptr = input.data<scalar_t>(); scalar_t *out_ptr = output.data<scalar_t>(); scalar_t *grid_ptr = grid.data<scalar_t>(); // loop over each output pixel #ifdef _OPENMP #pragma omp parallel for #endif for (int64_t n = 0; n < N; ++n) { scalar_t *grid_ptr_N = grid_ptr + n * grid_sN; scalar_t *inp_ptr_N = inp_ptr + n * inp_sN; for (int64_t d = 0; d < out_D; ++d) { for (int64_t h = 0; h < out_H; ++h) { for (int64_t w = 0; w < out_W; ++w) { // get the corresponding input x, y, z co-ordinates from grid scalar_t *grid_ptr_NDHW = grid_ptr_N + d * grid_sD + h * grid_sH + w * grid_sW; scalar_t ix = *grid_ptr_NDHW; scalar_t iy = grid_ptr_NDHW[grid_sCoor]; scalar_t iz = grid_ptr_NDHW[2 * grid_sCoor]; // normalize ix, iy, iz from [-1, 1] to [0, inp_W-1] & [0, inp_H-1] & [0, inp_D-1] ix = ((ix + 1) / 2) * (inp_W - 1); iy = ((iy + 1) / 2) * (inp_H - 1); iz = ((iz + 1) / 2) * (inp_D - 1); // get corner pixel values from (x, y, z) // for 4d, we used north-east-south-west // for 5d, we add top-bottom int64_t ix_tnw = static_cast<int64_t>(std::floor(ix)); int64_t iy_tnw = static_cast<int64_t>(std::floor(iy)); int64_t iz_tnw = static_cast<int64_t>(std::floor(iz)); int64_t ix_tne = ix_tnw + 1; int64_t iy_tne = iy_tnw; int64_t iz_tne = iz_tnw; int64_t ix_tsw = ix_tnw; int64_t iy_tsw = iy_tnw + 1; int64_t iz_tsw = iz_tnw; int64_t ix_tse = ix_tnw + 1; int64_t iy_tse = iy_tnw + 1; int64_t iz_tse = iz_tnw; int64_t ix_bnw = ix_tnw; int64_t iy_bnw = iy_tnw; int64_t iz_bnw = iz_tnw + 1; int64_t ix_bne = ix_tnw + 1; int64_t iy_bne = iy_tnw; int64_t iz_bne = iz_tnw + 1; int64_t ix_bsw = ix_tnw; int64_t iy_bsw = iy_tnw + 1; int64_t iz_bsw = iz_tnw + 1; int64_t ix_bse = ix_tnw + 1; int64_t iy_bse = iy_tnw + 1; int64_t iz_bse = iz_tnw + 1; // get surfaces to each neighbor: scalar_t tnw = (ix_bse - ix) * (iy_bse - iy) * (iz_bse - iz); scalar_t tne = (ix - ix_bsw) * (iy_bsw - iy) * (iz_bsw - iz); scalar_t tsw = (ix_bne - ix) * (iy - iy_bne) * (iz_bne - iz); scalar_t tse = (ix - ix_bnw) * (iy - iy_bnw) * (iz_bnw - iz); scalar_t bnw = (ix_tse - ix) * (iy_tse - iy) * (iz - iz_tse); scalar_t bne = (ix - ix_tsw) * (iy_tsw - iy) * (iz - iz_tsw); scalar_t bsw = (ix_tne - ix) * (iy - iy_tne) * (iz - iz_tne); scalar_t bse = (ix - ix_tnw) * (iy - iy_tnw) * (iz - iz_tnw); if (padding_mode == GridSamplerPadding::Border) { // clip coordinates to image borders ix_tnw = clip_coordinates(ix_tnw, inp_W); iy_tnw = clip_coordinates(iy_tnw, inp_H); iz_tnw = clip_coordinates(iz_tnw, inp_D); ix_tne = clip_coordinates(ix_tne, inp_W); iy_tne = clip_coordinates(iy_tne, inp_H); iz_tne = clip_coordinates(iz_tne, inp_D); ix_tsw = clip_coordinates(ix_tsw, inp_W); iy_tsw = clip_coordinates(iy_tsw, inp_H); iz_tsw = clip_coordinates(iz_tsw, inp_D); ix_tse = clip_coordinates(ix_tse, inp_W); iy_tse = clip_coordinates(iy_tse, inp_H); iz_tse = clip_coordinates(iz_tse, inp_D); ix_bnw = clip_coordinates(ix_bnw, inp_W); iy_bnw = clip_coordinates(iy_bnw, inp_H); iz_bnw = clip_coordinates(iz_bnw, inp_D); ix_bne = clip_coordinates(ix_bne, inp_W); iy_bne = clip_coordinates(iy_bne, inp_H); iz_bne = clip_coordinates(iz_bne, inp_D); ix_bsw = clip_coordinates(ix_bsw, inp_W); iy_bsw = clip_coordinates(iy_bsw, inp_H); iz_bsw = clip_coordinates(iz_bsw, inp_D); ix_bse = clip_coordinates(ix_bse, inp_W); iy_bse = clip_coordinates(iy_bse, inp_H); iz_bse = clip_coordinates(iz_bse, inp_D); } // calculate bilinear weighted pixel value and set output pixel scalar_t *out_ptr_NCDHW = out_ptr + n * out_sN + d * out_sD + h * out_sH + w * out_sW; scalar_t *inp_ptr_NC = inp_ptr_N; for (int c = 0; c < C; ++c, out_ptr_NCDHW += out_sC, inp_ptr_NC += inp_sC) { // (c, iz_tnw, iy_tnw, ix_tnw) * tnw + (c, iz_tne, iy_tne, ix_tne) * tne // + (c, iz_tsw, iy_tsw, ix_tsw) * tsw + (c, iz_tse, iy_tse, ix_tse) * tse // + (c, iz_bnw, iy_bnw, ix_bnw) * bnw + (c, iz_bne, iy_bne, ix_bne) * bne // + (c, iz_bsw, iy_bsw, ix_bsw) * bsw + (c, iz_bse, iy_bse, ix_bse) * bse *out_ptr_NCDHW = static_cast<scalar_t>(0); if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_tnw, iy_tnw, ix_tnw, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_tnw * inp_sD + iy_tnw * inp_sH + ix_tnw * inp_sW] * tnw; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_tne, iy_tne, ix_tne, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_tne * inp_sD + iy_tne * inp_sH + ix_tne * inp_sW] * tne; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_tsw, iy_tsw, ix_tsw, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_tsw * inp_sD + iy_tsw * inp_sH + ix_tsw * inp_sW] * tsw; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_tse, iy_tse, ix_tse, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_tse * inp_sD + iy_tse * inp_sH + ix_tse * inp_sW] * tse; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_bnw, iy_bnw, ix_bnw, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_bnw * inp_sD + iy_bnw * inp_sH + ix_bnw * inp_sW] * bnw; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_bne, iy_bne, ix_bne, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_bne * inp_sD + iy_bne * inp_sH + ix_bne * inp_sW] * bne; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_bsw, iy_bsw, ix_bsw, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_bsw * inp_sD + iy_bsw * inp_sH + ix_bsw * inp_sW] * bsw; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_bse, iy_bse, ix_bse, inp_D, inp_H, inp_W)) { *out_ptr_NCDHW += inp_ptr_NC[iz_bse * inp_sD + iy_bse * inp_sH + ix_bse * inp_sW] * bse; } } } } } } return output; } template<typename scalar_t> std::tuple<Tensor, Tensor> grid_sampler2d_backward_cpu_impl(const Tensor& grad_output, const Tensor& input, const Tensor& grid, GridSamplerInterpolation interpolation_mode, GridSamplerPadding padding_mode) { auto grad_input = at::zeros_like(input); auto grad_grid = at::empty_like(grid); int64_t N = input.size(0); int64_t C = input.size(1); int64_t inp_H = input.size(2); int64_t inp_W = input.size(3); int64_t out_H = grid.size(1); int64_t out_W = grid.size(2); int64_t inp_sN = input.stride(0); int64_t inp_sC = input.stride(1); int64_t inp_sH = input.stride(2); int64_t inp_sW = input.stride(3); int64_t grid_sN = grid.stride(0); int64_t grid_sH = grid.stride(1); int64_t grid_sW = grid.stride(2); int64_t grid_sCoor = grid.stride(3); int64_t gOut_sN = grad_output.stride(0); int64_t gOut_sC = grad_output.stride(1); int64_t gOut_sH = grad_output.stride(2); int64_t gOut_sW = grad_output.stride(3); int64_t gInp_sN = grad_input.stride(0); int64_t gInp_sC = grad_input.stride(1); int64_t gInp_sH = grad_input.stride(2); int64_t gInp_sW = grad_input.stride(3); int64_t gGrid_sN = grad_grid.stride(0); int64_t gGrid_sW = grad_grid.stride(2); scalar_t *inp_ptr = input.data<scalar_t>(); scalar_t *grid_ptr = grid.data<scalar_t>(); scalar_t *gOut_ptr = grad_output.data<scalar_t>(); scalar_t *gInp_ptr = grad_input.data<scalar_t>(); scalar_t *gGrid_ptr = grad_grid.data<scalar_t>(); // loop over each output pixel #ifdef _OPENMP #pragma omp parallel for #endif for (int64_t n = 0; n < N; ++n) { scalar_t *grid_ptr_N = grid_ptr + n * grid_sN; scalar_t *inp_ptr_N = inp_ptr + n * inp_sN; scalar_t *gGrid_ptr_NHW = gGrid_ptr + n * gGrid_sN; for (int64_t h = 0; h < out_H; ++h) { for (int64_t w = 0; w < out_W; ++w, gGrid_ptr_NHW += gGrid_sW /* grad_grid is contiguous */ ) { // get the corresponding input x, y co-ordinates from grid scalar_t ix = grid_ptr_N[h * grid_sH + w * grid_sW]; scalar_t iy = grid_ptr_N[h * grid_sH + w * grid_sW + grid_sCoor]; // normalize ix, iy from [-1, 1] to [0, inp_W-1] & [0, inp_H-1] ix = ((ix + 1) / 2) * (inp_W - 1); iy = ((iy + 1) / 2) * (inp_H - 1); // get NE, NW, SE, SW pixel values from (x, y) int64_t ix_nw = static_cast<int64_t>(std::floor(ix)); int64_t iy_nw = static_cast<int64_t>(std::floor(iy)); int64_t ix_ne = ix_nw + 1; int64_t iy_ne = iy_nw; int64_t ix_sw = ix_nw; int64_t iy_sw = iy_nw + 1; int64_t ix_se = ix_nw + 1; int64_t iy_se = iy_nw + 1; // get surfaces to each neighbor: scalar_t nw = (ix_se - ix) * (iy_se - iy); scalar_t ne = (ix - ix_sw) * (iy_sw - iy); scalar_t sw = (ix_ne - ix) * (iy - iy_ne); scalar_t se = (ix - ix_nw) * (iy - iy_nw); int64_t ix_nw_cl, iy_nw_cl, ix_ne_cl, iy_ne_cl, ix_sw_cl, iy_sw_cl, ix_se_cl, iy_se_cl; if (padding_mode == GridSamplerPadding::Border) { // get clipped NE, NW, SE, SW pixel values from (x, y) ix_nw_cl = clip_coordinates(ix_nw, inp_W); iy_nw_cl = clip_coordinates(iy_nw, inp_H); ix_ne_cl = clip_coordinates(ix_ne, inp_W); iy_ne_cl = clip_coordinates(iy_ne, inp_H); ix_sw_cl = clip_coordinates(ix_sw, inp_W); iy_sw_cl = clip_coordinates(iy_sw, inp_H); ix_se_cl = clip_coordinates(ix_se, inp_W); iy_se_cl = clip_coordinates(iy_se, inp_H); } else { ix_nw_cl = ix_nw; iy_nw_cl = iy_nw; ix_ne_cl = ix_ne; iy_ne_cl = iy_ne; ix_sw_cl = ix_sw; iy_sw_cl = iy_sw; ix_se_cl = ix_se; iy_se_cl = iy_se; } scalar_t gix = static_cast<scalar_t>(0), giy = static_cast<scalar_t>(0); scalar_t *gOut_ptr_NCHW = gOut_ptr + n * gOut_sN + h * gOut_sH + w * gOut_sW; scalar_t *gInp_ptr_NC = gInp_ptr + n * gInp_sN; scalar_t *inp_ptr_NC = inp_ptr_N; // calculate bilinear weighted pixel value and set output pixel for (int c = 0; c < C; ++c, gOut_ptr_NCHW += gOut_sC, gInp_ptr_NC += gInp_sC, inp_ptr_NC += inp_sC) { scalar_t gOut = *gOut_ptr_NCHW; // calculate and set grad_input safe_add_2d(gInp_ptr_NC, iy_nw_cl, ix_nw_cl, gInp_sH, gInp_sW, inp_H, inp_W, nw * gOut); safe_add_2d(gInp_ptr_NC, iy_ne_cl, ix_ne_cl, gInp_sH, gInp_sW, inp_H, inp_W, ne * gOut); safe_add_2d(gInp_ptr_NC, iy_sw_cl, ix_sw_cl, gInp_sH, gInp_sW, inp_H, inp_W, sw * gOut); safe_add_2d(gInp_ptr_NC, iy_se_cl, ix_se_cl, gInp_sH, gInp_sW, inp_H, inp_W, se * gOut); // calculate grad_grid if (padding_mode != GridSamplerPadding::Zeros || within_bounds_2d(iy_nw_cl, ix_nw_cl, inp_H, inp_W)) { scalar_t nw_val = inp_ptr_NC[iy_nw_cl * inp_sH + ix_nw_cl * inp_sW]; gix -= nw_val * (iy_se - iy) * gOut; giy -= nw_val * (ix_se - ix) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_2d(iy_ne_cl, ix_ne_cl, inp_H, inp_W)) { scalar_t ne_val = inp_ptr_NC[iy_ne_cl * inp_sH + ix_ne_cl * inp_sW]; gix += ne_val * (iy_sw - iy) * gOut; giy -= ne_val * (ix - ix_sw) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_2d(iy_sw_cl, ix_sw_cl, inp_H, inp_W)) { scalar_t sw_val = inp_ptr_NC[iy_sw_cl * inp_sH + ix_sw_cl * inp_sW]; gix -= sw_val * (iy - iy_ne) * gOut; giy += sw_val * (ix_ne - ix) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_2d(iy_se_cl, ix_se_cl, inp_H, inp_W)) { scalar_t se_val = inp_ptr_NC[iy_se_cl * inp_sH + ix_se_cl * inp_sW]; gix += se_val * (iy - iy_nw) * gOut; giy += se_val * (ix - ix_nw) * gOut; } } // un-normalize grad_grid values back to [-1, 1] constraints gix = gix * (inp_W - 1) / 2; giy = giy * (inp_H - 1) / 2; // assuming grad_grid is contiguous gGrid_ptr_NHW[0] = gix; gGrid_ptr_NHW[1] = giy; } } } return std::make_tuple(grad_input, grad_grid); } template<typename scalar_t> std::tuple<Tensor, Tensor> grid_sampler3d_backward_cpu_impl(const Tensor& grad_output, const Tensor& input, const Tensor& grid, GridSamplerInterpolation interpolation_mode, GridSamplerPadding padding_mode) { auto grad_input = at::zeros_like(input); auto grad_grid = at::empty_like(grid); int64_t N = input.size(0); int64_t C = input.size(1); int64_t inp_D = input.size(2); int64_t inp_H = input.size(3); int64_t inp_W = input.size(4); int64_t out_D = grid.size(1); int64_t out_H = grid.size(2); int64_t out_W = grid.size(3); int64_t inp_sN = input.stride(0); int64_t inp_sC = input.stride(1); int64_t inp_sD = input.stride(2); int64_t inp_sH = input.stride(3); int64_t inp_sW = input.stride(4); int64_t grid_sN = grid.stride(0); int64_t grid_sD = grid.stride(1); int64_t grid_sH = grid.stride(2); int64_t grid_sW = grid.stride(3); int64_t grid_sCoor = grid.stride(4); int64_t gOut_sN = grad_output.stride(0); int64_t gOut_sC = grad_output.stride(1); int64_t gOut_sD = grad_output.stride(2); int64_t gOut_sH = grad_output.stride(3); int64_t gOut_sW = grad_output.stride(4); int64_t gInp_sN = grad_input.stride(0); int64_t gInp_sC = grad_input.stride(1); int64_t gInp_sD = grad_input.stride(2); int64_t gInp_sH = grad_input.stride(3); int64_t gInp_sW = grad_input.stride(4); int64_t gGrid_sN = grad_grid.stride(0); int64_t gGrid_sW = grad_grid.stride(3); scalar_t *inp_ptr = input.data<scalar_t>(); scalar_t *grid_ptr = grid.data<scalar_t>(); scalar_t *gOut_ptr = grad_output.data<scalar_t>(); scalar_t *gInp_ptr = grad_input.data<scalar_t>(); scalar_t *gGrid_ptr = grad_grid.data<scalar_t>(); // loop over each output pixel #ifdef _OPENMP #pragma omp parallel for #endif for (int64_t n = 0; n < N; ++n) { scalar_t *grid_ptr_N = grid_ptr + n * grid_sN; scalar_t *inp_ptr_N = inp_ptr + n * inp_sN; scalar_t *gGrid_ptr_NDHW = gGrid_ptr + n * gGrid_sN; for (int64_t d = 0; d < out_D; ++d) { for (int64_t h = 0; h < out_H; ++h) { for (int64_t w = 0; w < out_W; ++w, gGrid_ptr_NDHW += gGrid_sW /* grad_grid is contiguous */ ) { // get the corresponding input x, y, z co-ordinates from grid scalar_t *grid_ptr_NDHW = grid_ptr_N + d * grid_sD + h * grid_sH + w * grid_sW; scalar_t ix = *grid_ptr_NDHW; scalar_t iy = grid_ptr_NDHW[grid_sCoor]; scalar_t iz = grid_ptr_NDHW[2 * grid_sCoor]; // normalize ix, iy, iz from [-1, 1] to [0, inp_W-1] & [0, inp_H-1] & [0, inp_D-1] ix = ((ix + 1) / 2) * (inp_W - 1); iy = ((iy + 1) / 2) * (inp_H - 1); iz = ((iz + 1) / 2) * (inp_D - 1); // get corner pixel values from (x, y, z) // for 4d, we used north-east-south-west // for 5d, we add top-bottom int64_t ix_tnw = static_cast<int64_t>(std::floor(ix)); int64_t iy_tnw = static_cast<int64_t>(std::floor(iy)); int64_t iz_tnw = static_cast<int64_t>(std::floor(iz)); int64_t ix_tne = ix_tnw + 1; int64_t iy_tne = iy_tnw; int64_t iz_tne = iz_tnw; int64_t ix_tsw = ix_tnw; int64_t iy_tsw = iy_tnw + 1; int64_t iz_tsw = iz_tnw; int64_t ix_tse = ix_tnw + 1; int64_t iy_tse = iy_tnw + 1; int64_t iz_tse = iz_tnw; int64_t ix_bnw = ix_tnw; int64_t iy_bnw = iy_tnw; int64_t iz_bnw = iz_tnw + 1; int64_t ix_bne = ix_tnw + 1; int64_t iy_bne = iy_tnw; int64_t iz_bne = iz_tnw + 1; int64_t ix_bsw = ix_tnw; int64_t iy_bsw = iy_tnw + 1; int64_t iz_bsw = iz_tnw + 1; int64_t ix_bse = ix_tnw + 1; int64_t iy_bse = iy_tnw + 1; int64_t iz_bse = iz_tnw + 1; // get surfaces to each neighbor: scalar_t tnw = (ix_bse - ix) * (iy_bse - iy) * (iz_bse - iz); scalar_t tne = (ix - ix_bsw) * (iy_bsw - iy) * (iz_bsw - iz); scalar_t tsw = (ix_bne - ix) * (iy - iy_bne) * (iz_bne - iz); scalar_t tse = (ix - ix_bnw) * (iy - iy_bnw) * (iz_bnw - iz); scalar_t bnw = (ix_tse - ix) * (iy_tse - iy) * (iz - iz_tse); scalar_t bne = (ix - ix_tsw) * (iy_tsw - iy) * (iz - iz_tsw); scalar_t bsw = (ix_tne - ix) * (iy - iy_tne) * (iz - iz_tne); scalar_t bse = (ix - ix_tnw) * (iy - iy_tnw) * (iz - iz_tnw); int64_t ix_tnw_cl, iy_tnw_cl, iz_tnw_cl, ix_tne_cl, iy_tne_cl, iz_tne_cl; int64_t ix_tsw_cl, iy_tsw_cl, iz_tsw_cl, ix_tse_cl, iy_tse_cl, iz_tse_cl; int64_t ix_bnw_cl, iy_bnw_cl, iz_bnw_cl, ix_bne_cl, iy_bne_cl, iz_bne_cl; int64_t ix_bsw_cl, iy_bsw_cl, iz_bsw_cl, ix_bse_cl, iy_bse_cl, iz_bse_cl; if (padding_mode == GridSamplerPadding::Border) { // clip coordinates to image borders ix_tnw_cl = clip_coordinates(ix_tnw, inp_W); iy_tnw_cl = clip_coordinates(iy_tnw, inp_H); iz_tnw_cl = clip_coordinates(iz_tnw, inp_D); ix_tne_cl = clip_coordinates(ix_tne, inp_W); iy_tne_cl = clip_coordinates(iy_tne, inp_H); iz_tne_cl = clip_coordinates(iz_tne, inp_D); ix_tsw_cl = clip_coordinates(ix_tsw, inp_W); iy_tsw_cl = clip_coordinates(iy_tsw, inp_H); iz_tsw_cl = clip_coordinates(iz_tsw, inp_D); ix_tse_cl = clip_coordinates(ix_tse, inp_W); iy_tse_cl = clip_coordinates(iy_tse, inp_H); iz_tse_cl = clip_coordinates(iz_tse, inp_D); ix_bnw_cl = clip_coordinates(ix_bnw, inp_W); iy_bnw_cl = clip_coordinates(iy_bnw, inp_H); iz_bnw_cl = clip_coordinates(iz_bnw, inp_D); ix_bne_cl = clip_coordinates(ix_bne, inp_W); iy_bne_cl = clip_coordinates(iy_bne, inp_H); iz_bne_cl = clip_coordinates(iz_bne, inp_D); ix_bsw_cl = clip_coordinates(ix_bsw, inp_W); iy_bsw_cl = clip_coordinates(iy_bsw, inp_H); iz_bsw_cl = clip_coordinates(iz_bsw, inp_D); ix_bse_cl = clip_coordinates(ix_bse, inp_W); iy_bse_cl = clip_coordinates(iy_bse, inp_H); iz_bse_cl = clip_coordinates(iz_bse, inp_D); } else { ix_tnw_cl = ix_tnw; iy_tnw_cl = iy_tnw; iz_tnw_cl = iz_tnw; ix_tne_cl = ix_tne; iy_tne_cl = iy_tne; iz_tne_cl = iz_tne; ix_tsw_cl = ix_tsw; iy_tsw_cl = iy_tsw; iz_tsw_cl = iz_tsw; ix_tse_cl = ix_tse; iy_tse_cl = iy_tse; iz_tse_cl = iz_tse; ix_bnw_cl = ix_bnw; iy_bnw_cl = iy_bnw; iz_bnw_cl = iz_bnw; ix_bne_cl = ix_bne; iy_bne_cl = iy_bne; iz_bne_cl = iz_bne; ix_bsw_cl = ix_bsw; iy_bsw_cl = iy_bsw; iz_bsw_cl = iz_bsw; ix_bse_cl = ix_bse; iy_bse_cl = iy_bse; iz_bse_cl = iz_bse; } scalar_t gix = static_cast<scalar_t>(0), giy = static_cast<scalar_t>(0), giz = static_cast<scalar_t>(0); scalar_t *gOut_ptr_NCDHW = gOut_ptr + n * gOut_sN + d * gOut_sD + h * gOut_sH + w * gOut_sW; scalar_t *gInp_ptr_NC = gInp_ptr + n * gInp_sN; scalar_t *inp_ptr_NC = inp_ptr_N; // calculate bilinear weighted pixel value and set output pixel for (int c = 0; c < C; ++c, gOut_ptr_NCDHW += gOut_sC, gInp_ptr_NC += gInp_sC, inp_ptr_NC += inp_sC) { scalar_t gOut = *gOut_ptr_NCDHW; // calculate and set grad_input safe_add_3d(gInp_ptr_NC, iz_tnw_cl, iy_tnw_cl, ix_tnw_cl, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tnw * gOut); safe_add_3d(gInp_ptr_NC, iz_tne_cl, iy_tne_cl, ix_tne_cl, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tne * gOut); safe_add_3d(gInp_ptr_NC, iz_tsw_cl, iy_tsw_cl, ix_tsw_cl, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tsw * gOut); safe_add_3d(gInp_ptr_NC, iz_tse_cl, iy_tse_cl, ix_tse_cl, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, tse * gOut); safe_add_3d(gInp_ptr_NC, iz_bnw_cl, iy_bnw_cl, ix_bnw_cl, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bnw * gOut); safe_add_3d(gInp_ptr_NC, iz_bne_cl, iy_bne_cl, ix_bne_cl, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bne * gOut); safe_add_3d(gInp_ptr_NC, iz_bsw_cl, iy_bsw_cl, ix_bsw_cl, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bsw * gOut); safe_add_3d(gInp_ptr_NC, iz_bse_cl, iy_bse_cl, ix_bse_cl, gInp_sD, gInp_sH, gInp_sW, inp_D, inp_H, inp_W, bse * gOut); // calculate grad_grid if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_tnw_cl, iy_tnw_cl, ix_tnw_cl, inp_D, inp_H, inp_W)) { scalar_t tnw_val = inp_ptr_NC[iz_tnw_cl * inp_sD + iy_tnw_cl * inp_sH + ix_tnw_cl * inp_sW]; gix -= tnw_val * (iy_bse - iy) * (iz_bse - iz) * gOut; giy -= tnw_val * (ix_bse - ix) * (iz_bse - iz) * gOut; giz -= tnw_val * (ix_bse - ix) * (iy_bse - iy) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_tne_cl, iy_tne_cl, ix_tne_cl, inp_D, inp_H, inp_W)) { scalar_t tne_val = inp_ptr_NC[iz_tne_cl * inp_sD + iy_tne_cl * inp_sH + ix_tne_cl * inp_sW]; gix += tne_val * (iy_bsw - iy) * (iz_bsw - iz) * gOut; giy -= tne_val * (ix - ix_bsw) * (iz_bsw - iz) * gOut; giz -= tne_val * (ix - ix_bsw) * (iy_bsw - iy) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_tsw_cl, iy_tsw_cl, ix_tsw_cl, inp_D, inp_H, inp_W)) { scalar_t tsw_val = inp_ptr_NC[iz_tsw_cl * inp_sD + iy_tsw_cl * inp_sH + ix_tsw_cl * inp_sW]; gix -= tsw_val * (iy - iy_bne) * (iz_bne - iz) * gOut; giy += tsw_val * (ix_bne - ix) * (iz_bne - iz) * gOut; giz -= tsw_val * (ix_bne - ix) * (iy - iy_bne) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_tse_cl, iy_tse_cl, ix_tse_cl, inp_D, inp_H, inp_W)) { scalar_t tse_val = inp_ptr_NC[iz_tse_cl * inp_sD + iy_tse_cl * inp_sH + ix_tse_cl * inp_sW]; gix += tse_val * (iy - iy_bnw) * (iz_bnw - iz) * gOut; giy += tse_val * (ix - ix_bnw) * (iz_bnw - iz) * gOut; giz -= tse_val * (ix - ix_bnw) * (iy - iy_bnw) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_bnw_cl, iy_bnw_cl, ix_bnw_cl, inp_D, inp_H, inp_W)) { scalar_t bnw_val = inp_ptr_NC[iz_bnw_cl * inp_sD + iy_bnw_cl * inp_sH + ix_bnw_cl * inp_sW]; gix -= bnw_val * (iy_tse - iy) * (iz - iz_tse) * gOut; giy -= bnw_val * (ix_tse - ix) * (iz - iz_tse) * gOut; giz += bnw_val * (ix_tse - ix) * (iy_tse - iy) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_bne_cl, iy_bne_cl, ix_bne_cl, inp_D, inp_H, inp_W)) { scalar_t bne_val = inp_ptr_NC[iz_bne_cl * inp_sD + iy_bne_cl * inp_sH + ix_bne_cl * inp_sW]; gix += bne_val * (iy_tsw - iy) * (iz - iz_tsw) * gOut; giy -= bne_val * (ix - ix_tsw) * (iz - iz_tsw) * gOut; giz += bne_val * (ix - ix_tsw) * (iy_tsw - iy) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_bsw_cl, iy_bsw_cl, ix_bsw_cl, inp_D, inp_H, inp_W)) { scalar_t bsw_val = inp_ptr_NC[iz_bsw_cl * inp_sD + iy_bsw_cl * inp_sH + ix_bsw_cl * inp_sW]; gix -= bsw_val * (iy - iy_tne) * (iz - iz_tne) * gOut; giy += bsw_val * (ix_tne - ix) * (iz - iz_tne) * gOut; giz += bsw_val * (ix_tne - ix) * (iy - iy_tne) * gOut; } if (padding_mode != GridSamplerPadding::Zeros || within_bounds_3d(iz_bse_cl, iy_bse_cl, ix_bse_cl, inp_D, inp_H, inp_W)) { scalar_t bse_val = inp_ptr_NC[iz_bse_cl * inp_sD + iy_bse_cl * inp_sH + ix_bse_cl * inp_sW]; gix += bse_val * (iy - iy_tnw) * (iz - iz_tnw) * gOut; giy += bse_val * (ix - ix_tnw) * (iz - iz_tnw) * gOut; giz += bse_val * (ix - ix_tnw) * (iy - iy_tnw) * gOut; } } // un-normalize grad_grid values back to [-1, 1] constraints gix = gix * (inp_W - 1) / 2; giy = giy * (inp_H - 1) / 2; giz = giz * (inp_D - 1) / 2; // assuming grad_grid is contiguous gGrid_ptr_NDHW[0] = gix; gGrid_ptr_NDHW[1] = giy; gGrid_ptr_NDHW[2] = giz; } } } } return std::make_tuple(grad_input, grad_grid); } } // No shape checking needed here. See # NOTE [ grid_sampler Native Functions ]. Tensor grid_sampler_2d_cpu(const Tensor& input, const Tensor& grid, int64_t interpolation_mode, int64_t padding_mode) { return AT_DISPATCH_FLOATING_TYPES(input.type(), "grid_sampler2d_cpu", [&] { return grid_sampler2d_cpu_impl<scalar_t>( input, grid, static_cast<GridSamplerInterpolation>(interpolation_mode), static_cast<GridSamplerPadding>(padding_mode)); }); } // No shape checking needed here. See # NOTE [ grid_sampler Native Functions ]. Tensor grid_sampler_3d_cpu(const Tensor& input, const Tensor& grid, int64_t interpolation_mode, int64_t padding_mode) { return AT_DISPATCH_FLOATING_TYPES(input.type(), "grid_sampler3d_cpu", [&] { return grid_sampler3d_cpu_impl<scalar_t>( input, grid, static_cast<GridSamplerInterpolation>(interpolation_mode), static_cast<GridSamplerPadding>(padding_mode)); }); } // No shape checking needed here. See # NOTE [ grid_sampler Native Functions ]. std::tuple<Tensor, Tensor> grid_sampler_2d_backward_cpu(const Tensor& grad_output, const Tensor& input, const Tensor& grid, int64_t interpolation_mode, int64_t padding_mode) { return AT_DISPATCH_FLOATING_TYPES(input.type(), "grid_sampler_2d_backward_cpu", [&] { return grid_sampler2d_backward_cpu_impl<scalar_t>( grad_output, input, grid, static_cast<GridSamplerInterpolation>(interpolation_mode), static_cast<GridSamplerPadding>(padding_mode)); }); } // No shape checking needed here. See # NOTE [ grid_sampler Native Functions ]. std::tuple<Tensor, Tensor> grid_sampler_3d_backward_cpu(const Tensor& grad_output, const Tensor& input, const Tensor& grid, int64_t interpolation_mode, int64_t padding_mode) { return AT_DISPATCH_FLOATING_TYPES(input.type(), "grid_sampler_3d_backward_cpu", [&] { return grid_sampler3d_backward_cpu_impl<scalar_t>( grad_output, input, grid, static_cast<GridSamplerInterpolation>(interpolation_mode), static_cast<GridSamplerPadding>(padding_mode)); }); } Tensor grid_sampler(const Tensor& input, const Tensor& grid, int64_t padding_mode) { AT_CHECK( (input.dim() == 4 || input.dim() == 5) && input.dim() == grid.dim(), "grid_sampler(): expected 4D or 5D input and grid with same number " "dimensions, but got input with sizes ", input.sizes(), " and grid with sizes ", grid.sizes()); AT_CHECK( input.size(0) == grid.size(0), "grid_sampler(): expected grid and input to have same batch size, but got " "input with sizes ", input.sizes(), " and grid with sizes ", grid.sizes()); AT_CHECK( grid.size(-1) == input.dim() - 2, "grid_sampler(): expected grid to have size ", input.dim() - 2, " in last " "dimension, but got grid with sizes ", grid.sizes()); // cudnn does not support inputs larger than 1024 if (at::native::cudnn_is_acceptable(input) && static_cast<GridSamplerPadding>(padding_mode) == GridSamplerPadding::Zeros && input.dim() == 4 && input.size(1) <= 1024) { return cudnn_grid_sampler(input, grid); } if (input.dim() == 4) { return at::grid_sampler_2d(input, grid, 0, padding_mode); } else { return at::grid_sampler_3d(input, grid, 0, padding_mode); } } }} // namespace at::native
48.633803
136
0.57631
[ "shape" ]
5f23adba701d171d3025b23e6bfc3f3350a06cf5
49,351
cpp
C++
imap/src/client/ImapSession.cpp
webOS-ports/mojomail
49358ac2878e010f5c6e3bd962f047c476c11fc3
[ "Apache-2.0" ]
6
2015-01-09T02:20:27.000Z
2021-01-02T08:14:23.000Z
mojomail/imap/src/client/ImapSession.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
3
2019-05-11T19:17:56.000Z
2021-11-24T16:04:36.000Z
mojomail/imap/src/client/ImapSession.cpp
openwebos/app-services
021d509d609fce0cb41a0e562650bdd1f3bf4e32
[ "Apache-2.0" ]
6
2015-01-09T02:21:13.000Z
2021-01-02T02:37:10.000Z
// @@@LICENSE // // Copyright (c) 2010-2013 LG Electronics, 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. // // LICENSE@@@ #include "client/ImapSession.h" #include <boost/lexical_cast.hpp> #include "data/ImapAccount.h" #include "data/ImapLoginSettings.h" #include "exceptions/MailException.h" #include "client/ImapRequestManager.h" #include <sstream> #include "ImapCoreDefs.h" #include "ImapPrivate.h" #include "client/SyncSession.h" #include "client/PowerManager.h" #include "exceptions/ExceptionUtils.h" #include "activity/ImapActivityFactory.h" #include "activity/ActivityBuilder.h" #include "network/NetworkStatus.h" #include "network/NetworkStatusMonitor.h" #include "stream/InflaterInputStream.h" #include "stream/DeflaterOutputStream.h" // Commands #include "commands/AutoDownloadCommand.h" #include "commands/CapabilityCommand.h" #include "commands/CompressCommand.h" #include "commands/ConnectCommand.h" #include "commands/FetchNewHeadersCommand.h" #include "commands/FetchPartCommand.h" #include "commands/IdleCommand.h" #include "commands/IdleYahooCommand.h" #include "commands/LoginCommand.h" #include "commands/LogoutCommand.h" #include "commands/AuthYahooCommand.h" #include "commands/NoopIdleCommand.h" #include "commands/SearchFolderCommand.h" #include "commands/SelectFolderCommand.h" #include "commands/ScheduleRetryCommand.h" #include "commands/SyncFolderListCommand.h" #include "commands/SyncEmailsCommand.h" #include "commands/SyncLocalChangesCommand.h" #include "commands/TLSCommand.h" #include "commands/UpSyncSentEmailsCommand.h" #include "commands/UpSyncDraftsCommand.h" using namespace std; #include <string> #include "ImapCoreDefs.h" #include "ImapConfig.h" // Read timeout for normal requests const int ImapSession::DEFAULT_REQUEST_TIMEOUT = 30; // 30 seconds // If we can't use IDLE, schedule a sync with this interval const int ImapSession::FALLBACK_SYNC_INTERVAL = 15 * 60; // 15 minutes // How long we can keep the power on in a transitory state const int ImapSession::STATE_POWER_TIMEOUT = 5 * 60; // 5 minutes // How long we can keep the power on in the OkToSync state const int ImapSession::SYNC_STATE_POWER_TIMEOUT = 30 * 60; // 30 minutes MojLogger ImapSession::s_log("com.palm.imap.session"); std::vector< MojRefCountedPtr<MojRefCounted> > ImapSession::s_asyncCleanupItems; guint ImapSession::s_asyncCleanupCallbackId = 0; ImapSession::ImapSession(const MojRefCountedPtr<ImapClient>& client, MojLogger& logger) : m_log(logger), m_dbInterface(NULL), m_fileCacheClient(NULL), m_busClient(NULL), m_commandManager(new CommandManager(1, true)), // only one command at a time; start paused m_requestManager(new ImapRequestManager(*this)), m_state(State_NeedsAccount), m_client(client), m_activitySet(NULL), m_recentUserInteraction(false), m_reconnectRequested(false), m_safeMode(false), m_compressionActive(false), m_shouldPush(false), m_idleMode(IdleMode_None), m_pushRetryCount(0), m_enteredStateTime(0), m_idleStartTime(0), m_sessionPushDuration(0), m_networkStatusSlot(this, &ImapSession::NetworkStatusAvailable), m_closedSlot(this, &ImapSession::ConnectionClosed), m_syncSessionDoneSlot(this, &ImapSession::SyncSessionDone), m_scheduleRetrySlot(this, &ImapSession::ScheduleRetryDone), m_activitiesEndedSlot(this, &ImapSession::ActivitiesEnded) { } ImapSession::~ImapSession() { } void ImapSession::SetDatabase(DatabaseInterface& dbInterface) { m_dbInterface = &dbInterface; } void ImapSession::SetFileCacheClient(FileCacheClient& fileCacheClient) { m_fileCacheClient = &fileCacheClient; } void ImapSession::SetBusClient(BusClient& busClient) { m_busClient = &busClient; } void ImapSession::SetPowerManager(const MojRefCountedPtr<PowerManager>& powerManager) { m_powerManager = powerManager; } void ImapSession::Connected(const MojRefCountedPtr<SocketConnection>& connection) { m_connection = connection; if(connection.get()) { m_inputStream = connection->GetInputStream(); m_outputStream = connection->GetOutputStream(); m_closedSlot.cancel(); // make sure it's not connected to a slot m_connection->WatchClosed(m_closedSlot); if(NeedLoginCapabilities()) { CheckLoginCapabilities(); } else { LoginCapabilityComplete(); } } else { CheckQueue(); } } bool ImapSession::NeedLoginCapabilities() { /* As an optimization, we don't bother checking the login capabilities unless needed. * * Note that we can run into problems by not checking for LOGINDISABLED; we may * incorrectly report "bad username/password" instead of "TLS required". * * ImapValidator should override this to always return true to avoid this problem. */ ImapLoginSettings::EncryptionType encryption = GetLoginSettings().GetEncryption(); if(encryption == ImapLoginSettings::Encrypt_TLSIfAvailable) { return true; } return false; } void ImapSession::CheckLoginCapabilities() { SetState(State_GettingLoginCapabilities); MojRefCountedPtr<CapabilityCommand> command(new CapabilityCommand(*this)); m_commandManager->RunCommand(command); } void ImapSession::LoginCapabilityComplete() { // Enable TLS if requested ImapLoginSettings::EncryptionType encryption = GetLoginSettings().GetEncryption(); bool supportsTLS = m_capabilities.HasCapability(Capabilities::STARTTLS); if(encryption == ImapLoginSettings::Encrypt_TLS || (encryption == ImapLoginSettings::Encrypt_TLSIfAvailable && supportsTLS)) { RunState(State_NeedsTLS); } else { RunState(State_LoginRequired); } } void ImapSession::TLSReady() { RunState(State_LoginRequired); } void ImapSession::SetAccount(boost::shared_ptr<ImapAccount>& account) { m_account = account; if(m_state == State_NeedsAccount) { MojLogDebug(m_log, "ImapSession %p set account object", this); SetState(State_NeedsConnection); if(m_commandManager->GetPendingCommandCount() > 0) CheckQueue(); } else { MojLogDebug(m_log, "ImapSession %p updated account object", this); } } void ImapSession::RunState(State newState) { SetState(newState); CheckQueue(); } void ImapSession::SetFolder(const MojObject& folderId) { m_folderId = folderId; } bool ImapSession::NeedsPowerInState(State state) const { switch(state) { case State_NeedsAccount: case State_NeedsConnection: case State_Idling: case State_InvalidCredentials: case State_AccountDeleted: return false; default: return true; } } bool ImapSession::IsConnected() const { switch(m_state) { case State_NeedsAccount: case State_NeedsConnection: case State_QueryingNetworkStatus: case State_Connecting: case State_InvalidCredentials: case State_AccountDeleted: case State_Disconnecting: case State_Cleanup: return false; default: return true; } } bool ImapSession::IsActive() const { if(m_commandManager->GetActiveCommandCount() > 0) return true; switch(m_state) { case State_NeedsConnection: case State_AccountDeleted: case State_InvalidCredentials: return false; default: break; } // Always active when connected to the server return true; } void ImapSession::SetState(State newState) { MojLogDebug(m_log, "changing session %p state from %s (%d) to %s (%d)", this, GetStateName(m_state), m_state, GetStateName(newState), newState); m_state = newState; if(newState != State_OkToSync) { // Disable running commands for any state other than State_OkToSync m_commandManager->Pause(); } m_stateTimer.Cancel(); if(NeedsPowerInState(m_state)) { // These states need power if(HasPowerManager()) { m_powerUser.Start(GetPowerManager(), "ImapSession active"); } // Kill power activity if it's stuck for more than 30 minutes m_stateTimer.SetTimeout(m_state == State_OkToSync ? SYNC_STATE_POWER_TIMEOUT : STATE_POWER_TIMEOUT, this, &ImapSession::StateTimeout); } else { // These states don't need power m_powerUser.Stop(); } if(m_client.get()) { // Tell the client that we're active/inactive m_client->UpdateSessionActive(this, IsActive()); } m_enteredStateTime = time(NULL); } void ImapSession::StateTimeout() { MojLogCritical(m_log, "ImapSession %p spent over %d minutes in state %s", this, (int)(time(NULL) - m_enteredStateTime)/60, GetStateName(m_state)); } void ImapSession::DisconnectSession() { if(IsConnected()) { MojLogInfo(m_log, "disconnecting session %p; current state: %s (%d)", this, GetStateName(m_state), m_state); SetState(State_Disconnecting); Disconnect(); } else { MojLogInfo(m_log, "session %p not connected", this); m_client->SessionDisconnected(m_folderId); } } const boost::shared_ptr<ImapAccount>& ImapSession::GetAccount() { return m_account; } InputStreamPtr& ImapSession::GetInputStream() { assert( m_inputStream.get() != NULL ); if(m_inputStream.get() != NULL) { return m_inputStream; } else { throw MailException("no input stream available", __FILE__, __LINE__); } } OutputStreamPtr& ImapSession::GetOutputStream() { assert( m_outputStream.get() != NULL ); if(m_outputStream.get() != NULL) { return m_outputStream; } else { throw MailException("no output stream available", __FILE__, __LINE__); } } const MojRefCountedPtr<SocketConnection>& ImapSession::GetConnection() { return m_connection; } bool ImapSession::CheckNetworkHealthForPush() { const NetworkStatus& networkStatus = m_client->GetNetworkStatusMonitor().GetCurrentStatus(); // FIXME: need to know which interface we're currently on if(networkStatus.IsKnown() && !ImapConfig::GetConfig().GetIgnoreNetworkStatus()) { boost::shared_ptr<InterfaceStatus> interfaceStatus = networkStatus.GetPersistentInterface(); if(interfaceStatus.get() != NULL) { InterfaceStatus::NetworkConfidence confidence = interfaceStatus->GetNetworkConfidence(); if(confidence == InterfaceStatus::POOR) { MojLogInfo(m_log, "can't push; poor network confidence"); return false; } } else { MojLogInfo(m_log, "can't push; no persistent interface"); return false; } } else { MojLogInfo(m_log, "network status unknown"); } return true; } int ImapSession::GetNoopIdleTimeout() { int keepAliveSeconds = 0; if(ImapConfig::GetConfig().GetKeepAliveForSync() && !m_account->IsYahoo() && m_folderId == m_account->GetInboxFolderId() && m_account->GetSyncFrequencyMins() > 0 && m_account->GetSyncFrequencyMins() <= 15) { // If keepAliveForSync is enabled, stay connected for up to 16 minutes waiting for the next sync. keepAliveSeconds = (m_account->GetSyncFrequencyMins() * 60) + 60; } else if(ImapConfig::GetConfig().GetSessionKeepAlive() > 0 && m_recentUserInteraction) { // If the user has recently interacted with the folder, keep it alive keepAliveSeconds = ImapConfig::GetConfig().GetSessionKeepAlive(); if(m_account->IsYahoo()) { // Max of 25 seconds for Yahoo, which doesn't like us to stay connected keepAliveSeconds = std::min(keepAliveSeconds, 25); } } return keepAliveSeconds; } void ImapSession::CommandComplete(Command* command) { m_commandManager->CommandComplete(command); if(m_reconnectRequested && m_state == State_OkToSync && m_commandManager->GetActiveCommandCount() == 0 && m_commandManager->GetPendingCommandCount() > 0) { // If requested (and no active commands), disconnect from the server after finishing this command MojLogInfo(m_log, "disconnecting and reconnecting to server"); Logout(); } else if(m_state == State_OkToSync && m_commandManager->GetPendingCommandCount() == 0 && m_commandManager->GetActiveCommandCount() == 0) { MojLogInfo(m_log, "no commands active or pending"); // Either disconnect or run IDLE command // TODO also check account settings if(IsValidId(m_folderId) && IsPushEnabled(m_folderId)) { m_shouldPush = CheckNetworkHealthForPush(); } else { m_shouldPush = false; } if(m_shouldPush) { //MojLogInfo(m_log, "running idle command for folderId %s", AsJsonString(m_folderId).c_str()); if(m_account->IsYahoo()) { m_idleCommand.reset(new IdleYahooCommand(*this, m_folderId)); m_idleMode = IdleMode_YahooPush; } else { m_idleCommand.reset(new IdleCommand(*this, m_folderId)); m_idleMode = IdleMode_IDLE; } // Create activity to maintain idle. // If the device is rebooted or IMAP crashes, the callback will restart idle. // The activity will get cancelled if the connection goes into retry mode. if(true) { ImapActivityFactory factory; ActivityBuilder ab; factory.BuildStartIdle(ab, m_client->GetAccountId(), m_folderId); // Create new activity only if one doesn't already exist if(GetActivitySet()->FindActivityByName(ab.GetName()).get() == NULL) { ActivityPtr activity = Activity::PrepareNewActivity(ab, true, true); activity->SetName(ab.GetName()); activity->SetEndAction(Activity::EndAction_Complete); activity->SetEndOrder(Activity::EndOrder_Last); GetActivitySet()->AddActivity(activity); // Start activity right away activity->Create(*m_client); } } m_idleStartTime = 0; SetState(State_PreparingToIdle); m_commandManager->RunCommand(m_idleCommand); } else if(GetNoopIdleTimeout() > 0) { // TODO: this code is currently disabled MojLogInfo(m_log, "running NOOP idle command"); m_idleCommand.reset(new NoopIdleCommand(*this, m_folderId, GetNoopIdleTimeout())); m_idleMode = IdleMode_NOOP; m_idleStartTime = 0; // Reset flag m_recentUserInteraction = false; SetState(State_PreparingToIdle); m_commandManager->RunCommand(m_idleCommand); } else { if(IsPushRequested(m_folderId) && !m_shouldPush) { MojLogInfo(m_log, "setting up scheduled sync instead of push"); // If we can't push, set up a scheduled sync ImapActivityFactory factory; ActivityBuilder ab; factory.BuildScheduledSync(ab, m_client->GetAccountId(), m_folderId, FALLBACK_SYNC_INTERVAL, false); GetActivitySet()->ReplaceActivity(ab.GetName(), ab.GetActivityObject()); } else { MojLogInfo(m_log, "nothing left to do; disconnecting"); } Logout(); } } else if(m_state == State_Disconnecting && m_commandManager->GetActiveCommandCount() == 0) { Disconnected(); } } // Report command failure. After reporting a failure, the caller should call CommandComplete(). void ImapSession::CommandFailure(Command* command, const exception& e) { } void ImapSession::CheckQueue() { MojLogTrace(m_log); MojLogDebug(m_log, "checking the session queue. current state: %s (%d). commands active: %d pending: %d", GetStateName(m_state), m_state, m_commandManager->GetActiveCommandCount(), m_commandManager->GetPendingCommandCount()); MojAssert( m_state == State_NeedsAccount || m_account.get() ); switch(m_state) { case State_NeedsAccount: { MojLogCritical(m_log, "unable to run commands, no account available"); break; } case State_NeedsConnection: { PrepareToConnect(); break; } case State_QueryingNetworkStatus: { break; } case State_Connecting: { break; } case State_NeedsTLS: { SetState(State_TLSNegotiation); MojLogInfo(m_log, "starting TLS negotiation"); MojRefCountedPtr<TLSCommand> command(new TLSCommand(*this)); m_commandManager->RunCommand(command); break; } case State_TLSNegotiation: { break; } case State_LoginRequired: { SetState(State_PendingLogin); if(IsYahoo()) { //MojLogInfo(m_log, "running Yahoo authentication command"); MojRefCountedPtr<AuthYahooCommand> command(new AuthYahooCommand(*this)); m_commandManager->RunCommand(command); } else { //MojLogInfo(m_log, "running login command"); MojRefCountedPtr<LoginCommand> command(new LoginCommand(*this)); m_commandManager->RunCommand(command); } break; } case State_PendingLogin: { break; } case State_GettingCapabilities: { break; } case State_RequestingCompression: { break; } case State_SelectingFolder: { break; } case State_OkToSync: { MojLogDebug(m_log, "checking session command queue"); m_commandManager->Resume(); break; } case State_PreparingToIdle: { // FIXME -- possibly call endIdle break; } case State_Idling: { if(m_commandManager->GetPendingCommandCount() > 0) { if(m_idleCommand.get()) { MojLogInfo(m_log, "ending idle; we have work to do (pending command: %s)", m_commandManager->Top()->Describe().c_str()); m_idleCommand->EndIdle(); m_idleCommand.reset(); } } break; } case State_InvalidCredentials: { //todo break; } case State_Disconnecting: { int numActiveCommands = m_commandManager->GetActiveCommandCount(); if(numActiveCommands == 0) { Disconnected(); } else { MojLogInfo(m_log, "session %p waiting for %d %s to finish", this, numActiveCommands, numActiveCommands > 1 ? "commands" : "command"); } break; } case State_Cleanup: { break; } case State_AccountDeleted: { // break; } default: { MojLogError(m_log, "unhandled session state %d", m_state); } } } void ImapSession::RunCommandsInQueue() { assert( m_account.get() != NULL ); m_commandManager->RunCommands(); } void ImapSession::SendRequest(const string& request, MojRefCountedPtr<ImapResponseParser> responseParser, int timeout, bool canLogRequest) { assert( m_requestManager.get() != NULL ); m_requestManager->SendRequest(request, responseParser, timeout, canLogRequest); } void ImapSession::UpdateRequestTimeout(const MojRefCountedPtr<ImapResponseParser>& responseParser, int timeoutSeconds) { m_requestManager->UpdateRequestTimeout(responseParser, timeoutSeconds); } LineReaderPtr& ImapSession::GetLineReader() { if(m_lineReader.get() == NULL) m_lineReader.reset( new LineReader(GetInputStream()) ); return m_lineReader; } void ImapSession::FolderListSynced() { // no longer does anything } void ImapSession::FolderSelected() { if(m_state == State_SelectingFolder) { RunState(State_OkToSync); } else { MojLogError(m_log, "%s called in wrong state", __PRETTY_FUNCTION__); } } void ImapSession::FolderSelectFailed() { // Turn on safe mode (disables asynchronous folder list syncing) m_safeMode = true; // FIXME handle possibly non-existent folder if(m_state == State_SelectingFolder) { SetState(State_Disconnecting); Disconnect(); } } void ImapSession::SyncAccount() { // FIXME Generally this doesn't do anything if the account is already sync'd CheckQueue(); } void ImapSession::SyncFolder(const MojObject& folderId, SyncParams syncParams) { // TODO: make sure this is the right folder, or switch folders if necessary MojObject status; syncParams.Status(status); MojLogInfo(m_log, "ImapSession::SyncFolder called on %s with sync params %s", AsJsonString(folderId).c_str(), AsJsonString(status).c_str()); // Set bind address for interface to connect to next time we connect. // This won't apply if we're already connected. if(!IsConnected() && !syncParams.GetBindAddress().empty()) { m_connectBindAddress = syncParams.GetBindAddress(); } if(syncParams.GetForceReconnect()) { m_reconnectRequested = true; } // Manual sync of the inbox should resync the folder list if(syncParams.GetForce() && m_account->GetInboxFolderId() == folderId) { syncParams.SetSyncFolderList(true); } // Check if we should re-sync the folder list if(syncParams.GetSyncFolderList() && IsConnected()) { MojRefCountedPtr<SyncFolderListCommand> command(new SyncFolderListCommand(*this)); m_commandManager->QueueCommand(command, false); } MojRefCountedPtr<ImapSyncSessionCommand> syncCommand; syncCommand.reset(new SyncEmailsCommand(*this, folderId, syncParams)); // Check if a similar request has already been queued MojRefCountedPtr<ImapCommand> pendingCommand = FindPendingCommand(syncCommand); if (pendingCommand.get()) { MojLogInfo(m_log, "debouncing sync request; a similar request is already queued"); CheckQueue(); return; } // If we're just syncing local changes, and there's already a sync session, debounce it. if (syncParams.GetSyncChanges() && !syncParams.GetSyncEmails()) { MojRefCountedPtr<SyncSession> syncSession = m_client->GetSyncSession(folderId); if (syncSession.get() && syncSession->IsActive()) { MojLogInfo(m_log, "debouncing sync local changes; a sync session is active"); return; } } if(syncParams.GetSyncChanges() && !syncParams.GetSyncEmails()) { // Just upload changes syncCommand.reset(new SyncLocalChangesCommand(*this, folderId)); m_commandManager->QueueCommand(syncCommand, false); m_recentUserInteraction = true; } else if(syncParams.GetSyncEmails()) { // Sync emails m_commandManager->QueueCommand(syncCommand, false); } else { // just check the queue syncCommand.reset(); } if(syncCommand.get()) { // Start sync session m_client->AddToSyncSession(m_folderId, syncCommand.get()); m_client->StartSyncSession(m_folderId, syncParams.GetSyncActivities()); } CheckQueue(); } void ImapSession::UpSyncSentEmails(const MojObject& folderId, const ActivityPtr& activity) { MojRefCountedPtr<UpSyncSentEmailsCommand> command(new UpSyncSentEmailsCommand(*this, folderId)); command->AddActivity(activity); m_commandManager->QueueCommand(command, false); CheckQueue(); } void ImapSession::UpSyncDrafts(const MojObject& folderId, const ActivityPtr& activity) { MojRefCountedPtr<UpSyncDraftsCommand> command(new UpSyncDraftsCommand(*this, folderId)); command->AddActivity(activity); m_commandManager->QueueCommand(command, false); CheckQueue(); } MojRefCountedPtr<ImapCommand> ImapSession::FindActiveCommand(const MojRefCountedPtr<ImapCommand>& needle) { ImapCommand& needleRef = *needle; ImapCommand::CommandType type = needleRef.GetType(); // No command can match unknown if(type == ImapCommand::CommandType_Unknown) { return NULL; } BOOST_FOREACH(const MojRefCountedPtr<Command>& activeCommand, m_commandManager->GetActiveCommandIterators()) { // Assume it's an ImapCommand ImapCommand* imapCommand = static_cast<ImapCommand*>(activeCommand.get()); if(imapCommand->GetType() == type) { if(imapCommand->Equals(needleRef)) { return MojRefCountedPtr<ImapCommand>(imapCommand); } } } return NULL; } MojRefCountedPtr<ImapCommand> ImapSession::FindPendingCommand(const MojRefCountedPtr<ImapCommand>& needle) { ImapCommand& needleRef = *needle; ImapCommand::CommandType type = needleRef.GetType(); // No command can match unknown if(type == ImapCommand::CommandType_Unknown) { return NULL; } BOOST_FOREACH(const MojRefCountedPtr<Command>& pendingCommand, m_commandManager->GetPendingCommandIterators()) { // Assume it's an ImapCommand ImapCommand* imapCommand = static_cast<ImapCommand*>(pendingCommand.get()); if(imapCommand->Equals(needleRef)) { return MojRefCountedPtr<ImapCommand>(imapCommand); } } return NULL; } void ImapSession::DownloadPart(const MojObject& folderId, const MojObject& emailId, const MojObject& partId, const MojRefCountedPtr<DownloadListener>& listener, Command::Priority priority) { MojRefCountedPtr<FetchPartCommand> command(new FetchPartCommand(*this, folderId, emailId, partId, priority)); // Look for an active command MojRefCountedPtr<ImapCommand> activeCommand = FindActiveCommand(command); if(activeCommand.get()) { MojLogDebug(m_log, "attaching download request to existing active command"); if(listener.get()) static_cast<FetchPartCommand*>(activeCommand.get())->AddDownloadListener(listener); return; } // Look for a pending command with equal or higher priority // TODO: requeue if a higher priority is needed MojRefCountedPtr<ImapCommand> pendingCommand = FindPendingCommand(command); if(pendingCommand.get() && pendingCommand->GetPriority() >= priority) { MojLogDebug(m_log, "attaching download request to existing pending command"); if(listener.get()) static_cast<FetchPartCommand*>(pendingCommand.get())->AddDownloadListener(listener); // Poke the queue in case it's not already running CheckQueue(); return; } // Otherwise, use the new command if(listener.get()) command->AddDownloadListener(listener); // If this is a high priority request, set m_recentUserInteraction to true if (priority >= Command::HighPriority) { m_recentUserInteraction = true; } m_commandManager->QueueCommand(command, false); CheckQueue(); } void ImapSession::SearchFolder(const MojObject& folderId, const MojRefCountedPtr<SearchRequest>& searchRequest) { MojRefCountedPtr<SearchFolderCommand> command(new SearchFolderCommand(*this, folderId, searchRequest)); m_commandManager->QueueCommand(command, false); CheckQueue(); } void ImapSession::AutoDownloadParts(const MojObject& folderId) { MojRefCountedPtr<AutoDownloadCommand> command(new AutoDownloadCommand(*this, folderId)); m_commandManager->QueueCommand(command, false); CheckQueue(); } void ImapSession::FetchNewHeaders(const MojObject& folderId) { MojRefCountedPtr<FetchNewHeadersCommand> command(new FetchNewHeadersCommand(*this, folderId)); m_commandManager->QueueCommand(command, false); CheckQueue(); } void ImapSession::PrepareToConnect() { SetState(State_QueryingNetworkStatus); m_reconnectRequested = false; m_sessionPushDuration = 0; if(m_client.get() && m_account.get()) m_shouldPush = IsPushRequested(m_folderId); QueryNetworkStatus(); } void ImapSession::QueryNetworkStatus() { if(m_client.get() != NULL && !m_client->GetNetworkStatusMonitor().HasCurrentStatus()) { m_client->GetNetworkStatusMonitor().WaitForStatus(m_networkStatusSlot); } else { // If we already have the network status, or don't have a client, move on QueryNetworkStatusDone(); } } MojErr ImapSession::NetworkStatusAvailable() { QueryNetworkStatusDone(); return MojErrNone; } void ImapSession::QueryNetworkStatusDone() { bool hasConnection = false; if(m_client.get() && !ImapConfig::GetConfig().GetIgnoreNetworkStatus()) { if(m_client->GetNetworkStatusMonitor().HasCurrentStatus()) { const NetworkStatus& status = m_client->GetNetworkStatusMonitor().GetCurrentStatus(); hasConnection = status.IsConnected(); if(hasConnection && IsPushRequested(m_folderId)) { boost::shared_ptr<InterfaceStatus> interface = status.GetPersistentInterface(); if(interface.get() != NULL) { MojLogDebug(m_log, "session %p setting bind address to %s", this, interface->GetIpAddress().c_str()); m_connectBindAddress = interface->GetIpAddress(); } } } else { // Unknown status; go ahead and try to connect MojLogDebug(m_log, "session %p network status unknown", this); hasConnection = true; } } else { // Ignore network status during validation hasConnection = true; } if(hasConnection) { SetState(State_Connecting); Connect(); } else { MojLogWarning(m_log, "session %p no network connection available", this); Disconnected(); } } void ImapSession::Connect() { MojRefCountedPtr<ConnectCommand> command(new ConnectCommand(*this, m_connectBindAddress)); // Clear bind address so it doesn't get reused unless we get another update // This way, we won't get stuck with a possibly invalid bind address. m_connectBindAddress.clear(); m_stats.connectAttemptCount++; m_commandManager->RunCommand(command); } void ImapSession::ConnectSuccess() { } bool ImapSession::ShouldReportError(MailError::ErrorCode errorCode) const { switch(errorCode) { // account errors case MailError::BAD_USERNAME_OR_PASSWORD: case MailError::ACCOUNT_WEB_LOGIN_REQUIRED: case MailError::ACCOUNT_UNKNOWN_AUTH_ERROR: case MailError::ACCOUNT_LOCKED: case MailError::IMAP_NOT_ENABLED: // ssl errors case MailError::SSL_CERTIFICATE_EXPIRED: case MailError::SSL_CERTIFICATE_NOT_TRUSTED: case MailError::SSL_CERTIFICATE_INVALID: case MailError::SSL_HOST_NAME_MISMATCHED: // configuration errors case MailError::CONFIG_NEEDS_SSL: case MailError::CONFIG_NO_SSL: // internal error case MailError::INTERNAL_ERROR: return true; default: return false; } } void ImapSession::ConnectFailure(const exception& exc) { MailError::ErrorInfo errorInfo = ExceptionUtils::GetErrorInfo(exc); if(ShouldReportError(errorInfo.errorCode)) ReportStatus(errorInfo.errorCode); Disconnected(); } void ImapSession::TLSFailure(const exception& exc) { MailError::ErrorInfo errorInfo = ExceptionUtils::GetErrorInfo(exc); if(ShouldReportError(errorInfo.errorCode)) ReportStatus(errorInfo.errorCode); Disconnect(); } void ImapSession::LoginSuccess() { m_stats.loginSuccessCount++; if (m_client.get()) { m_client->LoginSuccess(); // Clear existing account error, if there is one if(m_account.get() && m_account->GetError().errorCode != MailError::NONE) { ReportStatus(MailError::NONE); } } if(m_state == State_PendingLogin) { // IMAP requires refetching the capability list after logging in. // The LOGIN response may have already updated the capabilities; // if not, we need to ask for them. // FIXME capabilities should be set invalid when logging in or enabling TLS if(m_capabilities.IsValid()) { CapabilityComplete(); } else { QueryCapabilities(); } } else { MojLogError(m_log, "%s called in wrong state %d", __PRETTY_FUNCTION__, m_state); } } void ImapSession::LoginFailure(MailError::ErrorCode errorCode, const std::string& serverMessage) { MojLogError(m_log, "session %p: login failure: error %d: %s", this, errorCode, serverMessage.c_str()); if(ShouldReportError(errorCode)) { ReportStatus( MailError::ErrorInfo(errorCode, serverMessage) ); } Disconnect(); // TODO: Remove this } void ImapSession::AuthYahooSuccess() { LoginSuccess(); } void ImapSession::AuthYahooFailure(MailError::ErrorCode errorCode, const std::string& errorText) { LoginFailure(errorCode, errorText); } void ImapSession::QueryCapabilities() { SetState(State_GettingCapabilities); MojRefCountedPtr<CapabilityCommand> command(new CapabilityCommand(*this)); m_commandManager->RunCommand(command); } // This handles CAPABILITY both before and after login (as needed), // or if no capability update was needed void ImapSession::CapabilityComplete() { if(m_state == State_GettingLoginCapabilities) { LoginCapabilityComplete(); } else if(m_state == State_PendingLogin || m_state == State_GettingCapabilities) { // Check for compression support and whether it's enabled if(m_capabilities.HasCapability(Capabilities::COMPRESS_DEFLATE) && m_account->GetEnableCompression()) { RequestCompression(); } else { SelectFolder(); } } } void ImapSession::RequestCompression() { SetState(State_RequestingCompression); MojRefCountedPtr<CompressCommand> command(new CompressCommand(*this)); m_commandManager->RunCommand(command); } void ImapSession::CompressComplete(bool success) { if(success) { m_inputStream.reset(new InflaterInputStream(m_inputStream, -15)); // This uses 44KB per connection m_outputStream.reset(new DeflaterOutputStream(m_outputStream, -10, 5)); // This uses 20KB per connection m_lineReader.reset(new LineReader(m_inputStream)); m_compressionActive = true; } SelectFolder(); } void ImapSession::SelectFolder() { // Only sync folder lists if we're syncing the inbox if(m_account.get() == NULL || !IsValidId(m_folderId) || m_account->GetInboxFolderId() == m_folderId) { MojRefCountedPtr<SyncFolderListCommand> command(new SyncFolderListCommand(*this)); if (!m_safeMode) { // Run command asynchronously m_commandManager->RunCommand(command); } else { // Workaround if running asynchronously failed for some reason (bad IMAP server?) m_commandManager->QueueCommand(command, false); } // This can be done asynchronously; move on to SelectFolder } SetState(State_SelectingFolder); MojRefCountedPtr<SelectFolderCommand> command(new SelectFolderCommand(*this, m_folderId)); m_commandManager->RunCommand(command); } void ImapSession::IdleStarted(bool disconnectNow) { if(m_state == State_PreparingToIdle) { SetState(State_Idling); m_idleStartTime = time(NULL); // Yahoo wants us to disconnect from the server while we're idling if(disconnectNow) { Disconnect(); } // Check if any commands came in while we were starting idle if(m_commandManager->GetPendingCommandCount() > 0) { if(m_idleCommand.get()) { MojLogInfo(m_log, "ending idle early; we have work to do (pending command: %s)", m_commandManager->Top()->Describe().c_str()); m_idleCommand->EndIdle(); m_idleCommand.reset(); } } } } void ImapSession::IdleError(const std::exception& e, bool fatal) { MojLogError(m_log, "error while in idle: %s", e.what()); if(m_state == State_Idling || m_state == State_PreparingToIdle) { SetState(State_Disconnecting); Disconnect(); } } void ImapSession::IdleDone() { int lastPushDuration = m_idleStartTime > 0 ? (time(NULL) - m_idleStartTime) : 0; m_sessionPushDuration += lastPushDuration; IdleMode previousIdleMode = m_idleMode; m_idleMode = IdleMode_None; // Reset time so we don't have stale values m_idleStartTime = 0; if(m_state == State_Idling && m_account->IsYahoo()) { // Need to reconnect to server after we finish idle RunState(State_NeedsConnection); } else if(m_state == State_Disconnecting && m_account->IsYahoo()) { // Finish cleaning up disconnected connection SetState(State_Cleanup); CleanupAfterDisconnect(); } else if(m_state == State_Idling || m_state == State_PreparingToIdle) { // If m_state == State_PreparingToIdle && m_account->IsYahoo(), it's still connected to the server if(BetterInterfaceAvailable()) { MojLogInfo(m_log, "wifi network available; reconnecting on new interface"); m_reconnectRequested = true; Logout(); } else { RunState(State_OkToSync); } } else { // Something bad probably happened if(m_state == State_Disconnecting || m_state == State_Cleanup) { MojLogWarning(m_log, "push connection died after %d seconds (%.1f minutes total this session)", lastPushDuration, float(m_sessionPushDuration)/60); // For NOOP idle, it's OK if the NOOP fails since it just means we need to reconnect. if(previousIdleMode == IdleMode_NOOP) { m_reconnectRequested = true; } } else { MojLogWarning(m_log, "idle done in unexpected state %s (%d)", GetStateName(m_state), m_state); } } } // Cleanly log out void ImapSession::Logout() { if(m_connection.get() && ImapConfig::GetConfig().GetCleanDisconnect()) { // Send LOGOUT command to the server SetState(State_LoggingOut); MojRefCountedPtr<LogoutCommand> command(new LogoutCommand(*this)); m_commandManager->RunCommand(command); } else { // Just close the connection SetState(State_Disconnecting); Disconnect(); } } void ImapSession::LoggedOut() { if(m_state == State_LoggingOut) { // Logout command acknowledged by server SetState(State_Disconnecting); Disconnect(); } else { // Probably already disconnected by server } } const char* ImapSession::GetStateName(State state) { switch(state) { case State_NeedsAccount: return "NeedsAccount"; case State_NeedsConnection: return "NeedsConnection"; case State_QueryingNetworkStatus: return "QueryingNetworkStatus"; case State_Connecting: return "Connecting"; case State_GettingLoginCapabilities: return "GettingLoginCapabilities"; case State_NeedsTLS: return "NeedsTLS"; case State_TLSNegotiation: return "TLSNegotiation"; case State_LoginRequired: return "LoginRequired"; case State_PendingLogin: return "PendingLogin"; case State_GettingCapabilities: return "GettingCapabilities"; case State_RequestingCompression: return "RequestingCompression"; case State_SelectingFolder: return "SelectingFolder"; case State_OkToSync: return "OkToSync"; case State_PreparingToIdle: return "PreparingToIdle"; case State_Idling: return "Idling"; case State_LoggingOut: return "LoggingOut"; case State_Disconnecting: return "Disconnecting"; case State_Cleanup: return "Cleanup"; case State_InvalidCredentials: return "InvalidCredentials"; case State_AccountDeleted: return "AccountDeleted"; } return "unknown"; } void ImapSession::Status(MojObject& status) { MojErr err; err = status.putString("sessionState", GetStateName(m_state)); ErrorToException(err); MojObject timeStatus; err = timeStatus.put("enteredStateTime", (MojInt64) m_enteredStateTime); ErrorToException(err); err = timeStatus.put("secondsInState", (MojInt64) (time(NULL) - m_enteredStateTime)); ErrorToException(err); err = status.put("time", timeStatus); ErrorToException(err); err = status.put("folderId", m_folderId); ErrorToException(err); MojObject commandManagerStatus; m_commandManager->Status(commandManagerStatus); err = status.put("sessionCommands", commandManagerStatus); ErrorToException(err); if(m_requestManager.get()) { MojObject requestManagerStatus; m_requestManager->Status(requestManagerStatus); err = status.put("requestManager", requestManagerStatus); ErrorToException(err); } if(m_lineReader.get()) { MojObject lineReaderStatus; m_lineReader->Status(lineReaderStatus); err = status.put("lineReader", lineReaderStatus); ErrorToException(err); } if(m_connection.get()) { MojObject connectionStatus; m_connection->Status(connectionStatus); if(m_compressionActive) { err = connectionStatus.put("compression", true); ErrorToException(err); } err = status.put("connection", connectionStatus); ErrorToException(err); } // Stats if(true) { MojObject stats; err = stats.put("connectAttemptCount", m_stats.connectAttemptCount); ErrorToException(err); err = stats.put("loginSuccessCount", m_stats.loginSuccessCount); ErrorToException(err); err = status.put("stats", stats); ErrorToException(err); } } void ImapSession::FatalError(const std::string& reason) { if(IsConnected()) { MojLogInfo(m_log, "fatal error; disconnecting: %s", reason.c_str()); SetState(State_Disconnecting); Disconnect(); } } void ImapSession::Disconnect() { MojLogInfo(m_log, "session %p disconnecting from server", this); if(m_connection.get()) { // Keep a local reference so it doesn't get deleted while in Shutdown // We clear the m_connection reference in ImapSession::ConnectionClosed MojRefCountedPtr<SocketConnection> tempConnection = m_connection; tempConnection->Shutdown(); } else { ConnectionClosed(); } } void ImapSession::RequestLine(const MojRefCountedPtr<ImapResponseParser>& responseParser, int timeoutSeconds) { m_requestManager->RequestLine(responseParser, timeoutSeconds); } void ImapSession::RequestData(const MojRefCountedPtr<ImapResponseParser>& responseParser, size_t bytes, int timeoutSeconds) { m_requestManager->RequestData(responseParser, bytes, timeoutSeconds); } void ImapSession::WaitForParser(const MojRefCountedPtr<ImapResponseParser>& responseParser) { m_requestManager->WaitForParser(responseParser); } void ImapSession::ParserFinished(const MojRefCountedPtr<ImapResponseParser>& responseParser) { m_requestManager->ParserFinished(responseParser); } MojErr ImapSession::ConnectionClosed() { MojLogInfo(m_log, "session %p connection closed", this); // FIXME check other states (deleted, etc) if(m_state != State_NeedsConnection) { if(m_account->IsYahoo() && m_account->IsPush() && m_state == State_Idling) { // Yahoo is a special case: when it goes into idle, it disconnects from the server // In this case, we'll just delete the connection but stay in the idle state MojLogInfo(m_log, "Resetting connection object for Yahoo idle"); ResetConnection(); } else { // Clean up any incomplete Yahoo idle state if(m_account->IsYahoo() && m_idleCommand.get() && m_state == State_Disconnecting) { if(m_idleCommand.get()) { MojLogInfo(m_log, "ending idle; we are disconnecting"); m_idleCommand->EndIdle(); } } else { SetState(State_Disconnecting); } // If the state is still State_Disconnecting, check if all the commands are complete if(m_state == State_Disconnecting) CheckQueue(); } } return MojErrNone; } // This gets called after the connection is lost AND all commands have failed void ImapSession::Disconnected() { ResetConnection(); SetState(State_Cleanup); CleanupAfterDisconnect(); } void ImapSession::CollectConnectionStats(CompressionStats& stats) { // Collect stats if(m_compressionActive) { InflaterInputStream* iis = dynamic_cast<InflaterInputStream*>(m_inputStream.get()); if(iis != NULL) { InflaterInputStream::InflateStats inflateStats; iis->GetInflateStats(inflateStats); stats.totalBytesIn += inflateStats.bytesOut; stats.compressedBytesIn += inflateStats.bytesIn; } DeflaterOutputStream* dis = dynamic_cast<DeflaterOutputStream*>(m_outputStream.get()); if(dis != NULL) { DeflaterOutputStream::DeflateStats deflateStats; dis->GetDeflateStats(deflateStats); stats.totalBytesOut += deflateStats.bytesIn; stats.compressedBytesOut += deflateStats.bytesOut; } } } void ImapSession::ResetConnection() { CompressionStats stats; CollectConnectionStats(stats); if(m_compressionActive) { MojInt64 total = stats.totalBytesIn + stats.totalBytesOut; MojInt64 compressed = stats.compressedBytesIn + stats.compressedBytesOut; MojLogInfo(m_log, "saved %.1f/%.1f KB from compression this session", float(total - compressed)/1024, float(total)/1024); } m_stats.compressionStats += stats; // Schedule an async cleanup so this doesn't get cleaned up immediately if (m_requestManager.get()) { s_asyncCleanupItems.push_back(m_requestManager); ScheduleAsyncCleanup(); } m_connection.reset(); m_inputStream.reset(); m_outputStream.reset(); m_lineReader.reset(); m_folderSession.reset(); m_requestManager.reset(new ImapRequestManager(*this)); m_compressionActive = false; } // Cleanup sync sessions and activities // Part of State_Cleanup void ImapSession::CleanupAfterDisconnect() { if(m_client.get() && !m_client->DisableAccountInProgress()) { MojRefCountedPtr<SyncSession> syncSession = m_client->GetSyncSession(m_folderId); if(syncSession.get()) { MojLogInfo(m_log, "stopping sync session after disconnect"); // Indicate that the sync session may need to schedule a retry. // This will probably get ignored if the sync session is already ending (successful or not). syncSession->SetQueueStopped(); // Stop the sync session syncSession->RequestStop(m_syncSessionDoneSlot); } else { // Schedule push, if necessary SchedulePush(); } } else { EndActivities(); } } // Part of State_Cleanup MojErr ImapSession::SyncSessionDone() { try { SchedulePush(); } catch(const std::exception& e) { MojLogCritical(m_log, "exception in %s:%d: %s", __FILE__, __LINE__, e.what()); } return MojErrNone; } void ImapSession::SchedulePush() { if(m_shouldPush) { if(m_sessionPushDuration > 5 * 60) { // If we were able to idle for at least 5 minutes total, ignore any retry count. m_pushRetryCount = 0; } // If the connection is stable, and we didn't already retry, reconnect. if (m_pushRetryCount < 1 && CheckNetworkHealthForPush()) { MojLogInfo(m_log, "first push connect retry; reconnecting immediately"); m_reconnectRequested = true; m_pushRetryCount++; } } if(m_shouldPush && !m_reconnectRequested) { MojLogNotice(m_log, "scheduling retry after disconnect since push is enabled"); // Schedule retry if necessary // TODO: if we can tell that the interface went down, we can just reschedule the idle activity instead of a full sync. SyncParams syncParams; if(m_pushRetryCount > 0) { // FIXME hack so it goes to the next retry interval when scheduling push EmailAccount::RetryStatus retryStatus; retryStatus.SetReason("retry push"); retryStatus.SetInterval(60); m_client->GetAccount().SetRetry(retryStatus); } // Reset retry count m_pushRetryCount = 0; // FIXME don't reschedule if the sync session already scheduled a retry m_scheduleRetryCommand.reset(new ScheduleRetryCommand(*m_client, m_folderId, syncParams)); m_scheduleRetryCommand->Run(m_scheduleRetrySlot); } else { EndActivities(); } } // Part of State_Cleanup MojErr ImapSession::ScheduleRetryDone() { try { EndActivities(); } catch(const std::exception& e) { MojLogCritical(m_log, "exception in %s:%d: %s", __FILE__, __LINE__, e.what()); } return MojErrNone; } // This gets called after all sync sessions have shut down // Part of State_Cleanup void ImapSession::EndActivities() { if(m_activitySet.get()) { m_activitySet->EndActivities(m_activitiesEndedSlot); } else { ActivitiesEnded(); } } // Part of State_Cleanup MojErr ImapSession::ActivitiesEnded() { CleanupDone(); return MojErrNone; } // Part of State_Cleanup void ImapSession::CleanupDone() { MojLogInfo(m_log, "disconnect cleanup complete"); m_powerUser.Stop(); // Clear capabilities m_capabilities.Clear(); bool reconnectNow = false; if(m_reconnectRequested) { m_reconnectRequested = false; // Connect to the server and run any pending commands if(m_commandManager->GetPendingCommandCount() > 0 || IsPushRequested(m_folderId)) { reconnectNow = true; } } if(reconnectNow && (!HasClient() || !GetClient()->DisableAccountInProgress())) { PrepareToConnect(); } else { // FIXME check for invalid login state SetState(State_NeedsConnection); if(m_client.get()) { m_client->SessionDisconnected(m_folderId); } // Not going to retry right now; cancel pending commands CancelPendingCommands(ImapCommand::CancelType_NoConnection); } } bool ImapSession::IsPushRequested(const MojObject& folderId) { return m_account->IsPush() && folderId == m_account->GetInboxFolderId(); } bool ImapSession::IsPushAvailable(const MojObject& folderId) { return m_account->IsYahoo() || GetCapabilities().HasCapability(Capabilities::IDLE); } bool ImapSession::IsPushEnabled(const MojObject& folderId) { return IsPushRequested(folderId) && IsPushAvailable(folderId); } bool ImapSession::IsIdling() const { return m_state == State_Idling; } void ImapSession::WakeupIdle() { if(m_state == State_Idling) { if(m_idleCommand.get()) { MojLogInfo(m_log, "ending idle; wakeup called"); m_idleCommand->EndIdle(); m_idleCommand.reset(); } } } void ImapSession::ReportStatus(const MailError::ErrorInfo& errorInfo) { if(m_client.get()) { m_client->UpdateAccountStatus(errorInfo); } } const MojRefCountedPtr<ActivitySet>& ImapSession::GetActivitySet() { if(m_activitySet.get() == NULL) { m_activitySet.reset(new ActivitySet(GetBusClient())); } return m_activitySet; } void ImapSession::AddActivities(const std::vector<ActivityPtr>& activities) { BOOST_FOREACH(const ActivityPtr& activity, activities) { activity->SetEndAction(Activity::EndAction_Complete); GetActivitySet()->AddActivity(activity); } } void ImapSession::ForceReconnect(const std::string& reason) { m_reconnectRequested = true; if(m_state == State_OkToSync) { MojLogInfo(m_log, "terminating connection: %s", reason.c_str()); SetState(State_Disconnecting); Disconnect(); } } bool ImapSession::BetterInterfaceAvailable() { string currentBindAddress; if(m_connection.get()) { currentBindAddress = m_connection->GetBindAddress(); //MojLogDebug(m_log, "current interface: %s", currentBindAddress.c_str()); } if(m_client.get() && !currentBindAddress.empty()) { NetworkStatusMonitor& monitor = m_client->GetNetworkStatusMonitor(); if(monitor.HasCurrentStatus()) { const NetworkStatus& networkStatus = monitor.GetCurrentStatus(); boost::shared_ptr<InterfaceStatus> wanStatus = networkStatus.GetWanStatus(); boost::shared_ptr<InterfaceStatus> wifiStatus = networkStatus.GetWifiStatus(); // Check if Wifi is available and in good health if(wifiStatus.get() && wifiStatus->IsWakeOnWifiEnabled() && wifiStatus->GetNetworkConfidence() >= InterfaceStatus::EXCELLENT) { MojLogDebug(m_log, "wifi is excellent"); // Check if we're currently on WAN if(wanStatus.get() && wanStatus->GetIpAddress() == currentBindAddress) { // We should switch to Wifi return true; } } } } return false; } void ImapSession::CancelPendingCommands(ImapCommand::CancelType cancelType) { BOOST_FOREACH(const MojRefCountedPtr<Command>& pendingCommand, m_commandManager->GetPendingCommandIterators()) { // Assume it's an ImapCommand ImapCommand* imapCommand = static_cast<ImapCommand*>(pendingCommand.get()); bool cancelled = imapCommand->Cancel(cancelType); if (cancelled) { MojLogInfo(m_log, "cancelled command %s (%p)", imapCommand->Describe().c_str(), imapCommand); } } } void ImapSession::ScheduleAsyncCleanup() { if (!s_asyncCleanupCallbackId) { s_asyncCleanupCallbackId = g_idle_add(&ImapSession::AsyncCleanup, NULL); } } gboolean ImapSession::AsyncCleanup(gpointer data) { s_asyncCleanupCallbackId = 0; s_asyncCleanupItems.clear(); //fprintf(stderr, "async cleanup\n"); return false; }
27.850451
188
0.746429
[ "object", "vector" ]
5f25b96291a27364280a4fb019395bc508a6e7e8
2,222
cpp
C++
aws-cpp-sdk-fsx/source/model/DataRepositoryTaskStatus.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-fsx/source/model/DataRepositoryTaskStatus.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-fsx/source/model/DataRepositoryTaskStatus.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2022-03-23T15:17:18.000Z
2022-03-23T15:17:18.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/fsx/model/DataRepositoryTaskStatus.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace FSx { namespace Model { DataRepositoryTaskStatus::DataRepositoryTaskStatus() : m_totalCount(0), m_totalCountHasBeenSet(false), m_succeededCount(0), m_succeededCountHasBeenSet(false), m_failedCount(0), m_failedCountHasBeenSet(false), m_lastUpdatedTimeHasBeenSet(false) { } DataRepositoryTaskStatus::DataRepositoryTaskStatus(JsonView jsonValue) : m_totalCount(0), m_totalCountHasBeenSet(false), m_succeededCount(0), m_succeededCountHasBeenSet(false), m_failedCount(0), m_failedCountHasBeenSet(false), m_lastUpdatedTimeHasBeenSet(false) { *this = jsonValue; } DataRepositoryTaskStatus& DataRepositoryTaskStatus::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("TotalCount")) { m_totalCount = jsonValue.GetInt64("TotalCount"); m_totalCountHasBeenSet = true; } if(jsonValue.ValueExists("SucceededCount")) { m_succeededCount = jsonValue.GetInt64("SucceededCount"); m_succeededCountHasBeenSet = true; } if(jsonValue.ValueExists("FailedCount")) { m_failedCount = jsonValue.GetInt64("FailedCount"); m_failedCountHasBeenSet = true; } if(jsonValue.ValueExists("LastUpdatedTime")) { m_lastUpdatedTime = jsonValue.GetDouble("LastUpdatedTime"); m_lastUpdatedTimeHasBeenSet = true; } return *this; } JsonValue DataRepositoryTaskStatus::Jsonize() const { JsonValue payload; if(m_totalCountHasBeenSet) { payload.WithInt64("TotalCount", m_totalCount); } if(m_succeededCountHasBeenSet) { payload.WithInt64("SucceededCount", m_succeededCount); } if(m_failedCountHasBeenSet) { payload.WithInt64("FailedCount", m_failedCount); } if(m_lastUpdatedTimeHasBeenSet) { payload.WithDouble("LastUpdatedTime", m_lastUpdatedTime.SecondsWithMSPrecision()); } return payload; } } // namespace Model } // namespace FSx } // namespace Aws
20.2
85
0.737174
[ "model" ]
5f2aaffb60bd8edecb6d89eb3f4fa563d7c05098
10,885
cpp
C++
test/src/test_iterators.cpp
fecjanky/transform
8eaf0d034307d968fc3fb0f299568a9fc4e6d92d
[ "MIT" ]
1
2019-04-13T09:18:52.000Z
2019-04-13T09:18:52.000Z
test/src/test_iterators.cpp
fecjanky/transform
8eaf0d034307d968fc3fb0f299568a9fc4e6d92d
[ "MIT" ]
null
null
null
test/src/test_iterators.cpp
fecjanky/transform
8eaf0d034307d968fc3fb0f299568a9fc4e6d92d
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include <lranges.h> #include <forward_list> #include <list> #include <sstream> #include <string> #include <vector> TEST_CASE("Transform iterator on input iterator", "[transform][iterator][input]") { std::istringstream iss("a b c"); std::istream_iterator<char> begin { iss }; std::istream_iterator<char> end {}; using namespace lranges; auto upper = make_iterator_range(begin, end) | transform(toupper); static_assert(std::is_same<std::iterator_traits<decltype(upper.begin())>::iterator_category, std::iterator_traits<decltype(begin)>::iterator_category>::value, "keeps iterator category"); auto t_begin = upper.begin(); auto t_end = upper.end(); REQUIRE(t_begin != t_end); REQUIRE(t_begin == t_begin); REQUIRE(*t_begin == 'A'); ++t_begin; REQUIRE(*t_begin++ == 'B'); REQUIRE(*t_begin == 'C'); REQUIRE(*t_begin++ == 'C'); REQUIRE(t_begin == t_end); } TEST_CASE("Transform iterator on forward iterator", "[transform][iterator][forward]") { std::forward_list<char> list { 'a', 'b', 'c' }; using namespace lranges; auto upper = list | transform(toupper); static_assert(std::is_same<std::iterator_traits<decltype(upper.begin())>::iterator_category, std::iterator_traits<decltype(list)::iterator>::iterator_category>::value, "keeps iterator category"); auto t_begin = upper.begin(); auto t_end = upper.end(); REQUIRE(t_begin != t_end); REQUIRE(t_begin == t_begin); REQUIRE(*t_begin == 'A'); auto t_temp_A = t_begin; ++t_begin; auto t_temp_B = t_begin; REQUIRE(*t_begin++ == 'B'); REQUIRE(*t_begin == 'C'); auto t_temp_C = t_begin; REQUIRE(*t_begin++ == 'C'); REQUIRE(t_begin == t_end); REQUIRE(*t_temp_A == 'A'); REQUIRE(*t_temp_B == 'B'); REQUIRE(*t_temp_C == 'C'); // Ensure multi - pass guarantee std::vector<char> multi_pass(upper.begin(), upper.end()); REQUIRE(multi_pass.size() == 3); REQUIRE(multi_pass[0] == 'A'); REQUIRE(multi_pass[1] == 'B'); REQUIRE(multi_pass[2] == 'C'); } TEST_CASE("Transform iterator on bidirectional iterator", "[transform][iterator][bi-dir]") { std::list<char> list { 'a', 'b', 'c' }; using namespace lranges; auto upper = list | transform(toupper); static_assert(std::is_same<std::iterator_traits<decltype(upper.begin())>::iterator_category, std::iterator_traits<decltype(list)::iterator>::iterator_category>::value, "keeps iterator category"); auto t_begin = upper.begin(); auto t_end = upper.end(); REQUIRE(t_begin != t_end); REQUIRE(t_begin == t_begin); REQUIRE(*t_begin == 'A'); auto t_temp_A = t_begin; ++t_begin; auto t_temp_B = t_begin; REQUIRE(*t_begin++ == 'B'); REQUIRE(*t_begin == 'C'); --t_begin; REQUIRE(*t_begin == 'B'); ++t_begin; auto t_temp_C = t_begin; REQUIRE(*t_begin++ == 'C'); REQUIRE(t_begin-- == t_end); REQUIRE(*t_begin++ == 'C'); REQUIRE(t_begin == t_end); REQUIRE(*t_temp_A == 'A'); REQUIRE(*t_temp_B == 'B'); REQUIRE(*t_temp_C == 'C'); REQUIRE(*t_temp_C-- == 'C'); REQUIRE(*t_temp_C == 'B'); // Ensure multi - pass guarantee std::vector<char> multi_pass(upper.begin(), upper.end()); REQUIRE(multi_pass.size() == 3); REQUIRE(multi_pass[0] == 'A'); REQUIRE(multi_pass[1] == 'B'); REQUIRE(multi_pass[2] == 'C'); } TEST_CASE("Transform iterator on random access iterator", "[transform][iterator][random-access]") { std::vector<char> list { 'a', 'b', 'c' }; using namespace lranges; auto upper = list | transform(toupper); static_assert(std::is_same<std::iterator_traits<decltype(upper.begin())>::iterator_category, std::iterator_traits<decltype(list)::iterator>::iterator_category>::value, "keeps iterator category"); auto t_begin = upper.begin(); auto t_end = upper.end(); REQUIRE(t_begin != t_end); REQUIRE(t_begin == t_begin); REQUIRE(*t_begin == 'A'); auto t_temp_A = t_begin; ++t_begin; auto t_temp_B = t_begin; REQUIRE(*t_begin++ == 'B'); REQUIRE(*t_begin == 'C'); --t_begin; REQUIRE(*t_begin == 'B'); ++t_begin; auto t_temp_C = t_begin; REQUIRE(*t_begin++ == 'C'); REQUIRE(t_begin-- == t_end); REQUIRE(*t_begin++ == 'C'); REQUIRE(t_begin == t_end); REQUIRE(*t_temp_A == 'A'); t_temp_A += 2; REQUIRE(*t_temp_A == 'C'); t_temp_A -= 2; REQUIRE(*t_temp_A == 'A'); REQUIRE(t_temp_A[2] == 'C'); REQUIRE(*t_temp_B == 'B'); REQUIRE(*(t_temp_B + 1) == 'C'); REQUIRE(*(1 + t_temp_B) == 'C'); REQUIRE(*(t_temp_B - 1) == 'A'); REQUIRE((t_temp_C - t_temp_A) == 2); REQUIRE(*t_temp_C == 'C'); REQUIRE(*t_temp_C-- == 'C'); REQUIRE(*t_temp_C == 'B'); REQUIRE(t_temp_A < t_temp_B); REQUIRE(t_temp_A <= t_temp_A); REQUIRE(t_temp_A <= t_temp_B); REQUIRE(t_temp_B > t_temp_A); REQUIRE(t_temp_B >= t_temp_A); REQUIRE(t_temp_A >= t_temp_A); // Ensure multi - pass guarantee std::vector<char> multi_pass(upper.begin(), upper.end()); REQUIRE(multi_pass.size() == 3); REQUIRE(multi_pass[0] == 'A'); REQUIRE(multi_pass[1] == 'B'); REQUIRE(multi_pass[2] == 'C'); } TEST_CASE("Transform iterator on random access iterator multi-stage", "[transform][iterator][random-access]") { std::vector<char> list { 'a', 'b', 'c' }; using namespace lranges; auto upper = list | transform(toupper) | transform([](char c) { return ++c; }); static_assert(std::is_same<std::iterator_traits<decltype(upper.begin())>::iterator_category, std::iterator_traits<decltype(list)::iterator>::iterator_category>::value, "keeps iterator category"); auto t_begin = upper.begin(); auto t_end = upper.end(); REQUIRE(t_begin != t_end); REQUIRE(t_begin == t_begin); REQUIRE(*t_begin == 'B'); auto t_temp_A = t_begin; ++t_begin; auto t_temp_B = t_begin; REQUIRE(*t_begin++ == 'C'); REQUIRE(*t_begin == 'D'); --t_begin; REQUIRE(*t_begin == 'C'); ++t_begin; auto t_temp_C = t_begin; REQUIRE(*t_begin++ == 'D'); REQUIRE(t_begin-- == t_end); REQUIRE(*t_begin++ == 'D'); REQUIRE(t_begin == t_end); REQUIRE(*t_temp_A == 'B'); t_temp_A += 2; REQUIRE(*t_temp_A == 'D'); t_temp_A -= 2; REQUIRE(*t_temp_A == 'B'); REQUIRE(t_temp_A[2] == 'D'); REQUIRE(*t_temp_B == 'C'); REQUIRE(*(t_temp_B + 1) == 'D'); REQUIRE(*(1 + t_temp_B) == 'D'); REQUIRE(*(t_temp_B - 1) == 'B'); REQUIRE((t_temp_C - t_temp_A) == 2); REQUIRE(*t_temp_C == 'D'); REQUIRE(*t_temp_C-- == 'D'); REQUIRE(*t_temp_C == 'C'); REQUIRE(t_temp_A < t_temp_B); REQUIRE(t_temp_A <= t_temp_A); REQUIRE(t_temp_A <= t_temp_B); REQUIRE(t_temp_B > t_temp_A); REQUIRE(t_temp_B >= t_temp_A); REQUIRE(t_temp_A >= t_temp_A); // Ensure multi - pass guarantee std::vector<char> multi_pass(upper.begin(), upper.end()); REQUIRE(multi_pass.size() == 3); REQUIRE(multi_pass[0] == 'B'); REQUIRE(multi_pass[1] == 'C'); REQUIRE(multi_pass[2] == 'D'); } TEST_CASE("Filter drops to bidir iterator category", "[filter][iterator][random-access]") { std::vector<char> list { 'a', 'b', 'a', 'c' }; using namespace lranges; auto upper = list | transform(toupper) | filter([](char c) { return c > 'A'; }) | transform([](char c) { return ++c; }); static_assert(std::is_same<std::iterator_traits<decltype(upper.begin())>::iterator_category, std::bidirectional_iterator_tag>::value, "drops to forward iterator category"); auto t_begin = upper.begin(); auto t_end = upper.end(); REQUIRE(t_begin != t_end); REQUIRE(t_begin == t_begin); REQUIRE(*t_begin == 'C'); auto t_temp_C = t_begin; ++t_begin; auto t_temp_D = t_begin; REQUIRE(*t_begin++ == 'D'); REQUIRE(t_begin == t_end); REQUIRE(*t_temp_D-- == 'D'); REQUIRE(*t_temp_D == 'C'); ++t_temp_D; REQUIRE(*t_temp_D-- == 'D'); --t_begin; REQUIRE(*t_begin == 'D'); ++t_begin; REQUIRE(t_begin == t_end); // Ensure multi - pass guarantee std::vector<char> multi_pass(upper.begin(), upper.end()); REQUIRE(multi_pass.size() == 2); REQUIRE(multi_pass[0] == 'C'); REQUIRE(multi_pass[1] == 'D'); } TEST_CASE("Filter iterator post-fix decrement", "[filter][iterator][API]") { std::list<int> iss { 'a', 'b', 'c' }; using namespace lranges; auto upper = make_iterator_range(iss.begin(), iss.end()) | filter([](char c) { return c > 'a'; }); using t = std::iterator_traits<decltype(upper.begin())>::iterator_category; static_assert(std::is_same<std::iterator_traits<decltype(upper.begin())>::iterator_category, std::bidirectional_iterator_tag>::value, "keeps iterator category"); auto t_begin = upper.begin(); auto t_end = upper.end(); REQUIRE(t_begin != t_end); REQUIRE(t_begin == t_begin); REQUIRE(*t_begin == 'b'); ++t_begin; REQUIRE(*t_begin-- == 'c'); REQUIRE(*t_begin == 'b'); ++t_begin; REQUIRE(*t_begin++ == 'c'); REQUIRE(t_begin == t_end); } TEST_CASE("Filter iterator keeps iterator category of the iterator up until bi-dir", "[filter][iterator][input]") { std::istringstream iss("a b c"); std::istream_iterator<char> begin { iss }; std::istream_iterator<char> end {}; using namespace lranges; auto upper = make_iterator_range(begin, end) | transform(toupper) | filter([](char c) { return c > 'A'; }); using t = std::iterator_traits<decltype(upper.begin())>::iterator_category; static_assert(std::is_same<std::iterator_traits<decltype(upper.begin())>::iterator_category, std::iterator_traits<decltype(begin)>::iterator_category>::value, "keeps iterator category"); auto t_begin = upper.begin(); auto t_end = upper.end(); REQUIRE(t_begin != t_end); REQUIRE(t_begin == t_begin); REQUIRE(*t_begin == 'B'); ++t_begin; REQUIRE(*t_begin++ == 'C'); REQUIRE(t_begin == t_end); } TEST_CASE("min on ordered types", "[meta]") { using namespace lranges; using order = detail::meta::Ordered<char, int, double>; static_assert( std::is_same<order::min<char, char>::type, char>::value, "min: char,char -> char "); static_assert(std::is_same<order::min<char, int>::type, char>::value, "min : char, int->char "); static_assert(std::is_same<order::min<int, char>::type, char>::value, "min : int,char -> char"); static_assert( std::is_same<order::min<double, int>::type, int>::value, "min: double,int -> int"); }
32.492537
100
0.602664
[ "vector", "transform" ]
5f2cd3ea2ab936487c3757c2651024136e53fdc7
5,618
cpp
C++
enigma/rotor.cpp
JKalash/enigma
1219c9a2a149d885db329a77597eaa921c2fa0e6
[ "MIT" ]
1
2017-11-27T16:18:10.000Z
2017-11-27T16:18:10.000Z
enigma/rotor.cpp
JKalash/enigma
1219c9a2a149d885db329a77597eaa921c2fa0e6
[ "MIT" ]
null
null
null
enigma/rotor.cpp
JKalash/enigma
1219c9a2a149d885db329a77597eaa921c2fa0e6
[ "MIT" ]
null
null
null
// // Rotor.cpp // enigma // // Created by Joseph Kalash on 11/18/17. // Copyright © 2017 Joseph Kalash. All rights reserved. // #include <fstream> #include "rotor.hpp" #define ROTOR_SIZE 26 Rotor::Rotor(EnigmaTypes::path rotFile, EnigmaTypes::path posFile, EnigmaTypes::location rotorIndex) { //Check and store initial position loadPosition(posFile, rotorIndex); //Check and store rotor config file loadRotor(rotFile); } void Rotor::loadPosition(EnigmaTypes::path posFile, EnigmaTypes::location rotorIndex) { std::ifstream posInput(posFile); //Read pos file to figure out initial position EnigmaTypes::location posCounter = 0; std::string word; while (posCounter < rotorIndex && posInput >> word) posCounter++; //Read previous rotor positions if (posCounter < rotorIndex) { std::cout << "Could not find rotor starting position" << std::endl; exit(NO_ROTOR_STARTING_POSITION); } std::string posWord; posInput >> posWord; //Make sure string is only numeric / whitespace if( posWord.find_first_not_of("0123456789") != std::string::npos) { std::cout << "Rotor position file contains non numeric character in " << posWord << std::endl; exit(NON_NUMERIC_CHARACTER); } //Convert string to integer position = stoi(posWord); if(position < 0 || position > 25) { std::cout << "Rotor invalid position " << position << std::endl; exit(INVALID_INDEX); } // Close the file posInput.close(); } void Rotor::loadRotor(EnigmaTypes::path rotFile) { // Try to open the files std::ifstream rotInput(rotFile); if(!rotFile) { std::cout << "Could not open rotor configuration file" << rotFile << std::endl; exit(ERROR_OPENING_CONFIGURATION_FILE); } //We need to read 26 unique proper location integers plus optional notches EnigmaTypes::location locationsRead = 0; std::string locWord; while(locationsRead < ROTOR_SIZE && rotInput >> locWord) { //Validate every word read sequentially to exit with proper signal value //Make sure string is only numeric / whitespace if( locWord.find_first_not_of("0123456789") != std::string::npos) { std::cout << "Rotor file contains non numeric character in " << locWord << std::endl; exit(NON_NUMERIC_CHARACTER); } //Convert string to integer EnigmaTypes::location loc = stoi(locWord); if(loc < 0 || loc > 25) { std::cout << "Rotor file contains invalid index " << loc << std::endl; exit(INVALID_INDEX); } wirings.push_back(loc); // INVALID_ROTOR_MAPPING if connecting more than one input to same output // In other words, duplicate should never be allowed. To check, sort and traverse std::vector<EnigmaTypes::location> wiringDuplicates = wirings; //The assignment here calls the *copy* constructor of the vector class. It's a DEEP copy. std::sort(wiringDuplicates.begin(), wiringDuplicates.end()); for(int i = 0; i < wiringDuplicates.size() - 1; i++) { if (wiringDuplicates[i] == wiringDuplicates[i + 1]) { std::cout << "Rotor file " << rotFile << " is attempting to map more than one output to " << wiringDuplicates[i] << std::endl; exit(INVALID_ROTOR_MAPPING); } } locationsRead++; } if (locationsRead < ROTOR_SIZE) { std::cout << "Rotor file does not provide mapping for all inputs" << std::endl; exit(INVALID_ROTOR_MAPPING); } //Read any optional notch while(rotInput >> locWord) { if( locWord.find_first_not_of("0123456789") != std::string::npos) { std::cout << "Rotor file contains non numeric character in " << locWord << std::endl; exit(NON_NUMERIC_CHARACTER); } //Convert string to integer EnigmaTypes::location notchLoc = stoi(locWord); if(notchLoc < 0 || notchLoc > 25) { std::cout << "Rotor file contains invalid index " << notchLoc << std::endl; exit(INVALID_INDEX); } //Add valid notch location notches.push_back(notchLoc); } // Close the file rotInput.close(); } EnigmaTypes::location Rotor::map(EnigmaTypes::location original, bool rightToleft) const { /* For right to left, we need to return the value at index 'original' shifted by position * For left to right we need to find the index of value 'original' shifted by position */ //Figure out what's in input 'original' EnigmaTypes::location charaterAtOriginal = (original - position + ROTOR_SIZE) % ROTOR_SIZE; if(rightToleft) { EnigmaTypes::location map = wirings[charaterAtOriginal]; //The map is at its initial position shifted by pos mod 26 return (map + position) % 26; } //Find what character maps to the charAtOriginal for(int i = 0; i < wirings.size(); i++) if (charaterAtOriginal == wirings[i]) return (i + position) % ROTOR_SIZE; //Should never be reached return original; } bool Rotor::shouldrotateLeftRotor() const { for(int i = 0; i < notches.size(); i++) if(notches[i] == position) return true; return false; } void Rotor::rotate() { position = (position+1) % ROTOR_SIZE; }
32.102857
163
0.610716
[ "vector" ]
5f3110d31741ccad9cd0de140f8a0336614b5c0a
1,385
cc
C++
Parameters.cc
filakhtov/qemu-wrapper
38d8cb6ed0e33519ef60d5430640d3847be1e212
[ "Unlicense" ]
1
2022-02-14T14:43:45.000Z
2022-02-14T14:43:45.000Z
Parameters.cc
filakhtov/qemu-wrapper
38d8cb6ed0e33519ef60d5430640d3847be1e212
[ "Unlicense" ]
null
null
null
Parameters.cc
filakhtov/qemu-wrapper
38d8cb6ed0e33519ef60d5430640d3847be1e212
[ "Unlicense" ]
null
null
null
#include "Parameters.hh" Modifier::Modifier(const std::string& n) : name{n}, value{} { } Modifier::Modifier(const std::string& n, const std::string& v) : name{n}, value{v} { } Modifier::operator std::string(void) const { if (this->value.size()) { return std::move(this->name + "=" + this->value); } return this->name; } std::string Parameter::modifiersToString(void) const { if (!this->modifiers.size()) { return ""; } std::string result{}; for (const auto& modifier : this->modifiers) { result += modifier; result += ","; } return std::move(std::string{result.cbegin(), result.cend() - 1}); } Parameter::Parameter(const std::string& n, const std::vector<Modifier>& m) : name{n}, modifiers{m} { } Parameter::Parameter(const std::string& n) : name{n}, modifiers{} { } std::string Parameter::getName(void) const noexcept { return std::move(std::string{"-" + this->name}); } bool Parameter::hasValue(void) const noexcept { return this->modifiers.size() > 0; } std::string Parameter::getValue(void) const { return std::move(this->modifiersToString()); } Parameters::Parameters(void) : parameters{} { } void Parameters::push(const Parameter& p) { this->parameters.push_back(p); } const std::vector<Parameter>& Parameters::getParameters(void) const noexcept { return this->parameters; }
19.236111
98
0.640433
[ "vector" ]
5f38405156c0a9469f0d18b676d44fa594596d99
12,120
hh
C++
src/mem/ruby/network/garnet2.0/GarnetNetwork.hh
wjwyyjr/Gem5_task_graph
0e233b5053d6dcd518a2ad6fddd23eaeb9c3a8ee
[ "BSD-3-Clause" ]
null
null
null
src/mem/ruby/network/garnet2.0/GarnetNetwork.hh
wjwyyjr/Gem5_task_graph
0e233b5053d6dcd518a2ad6fddd23eaeb9c3a8ee
[ "BSD-3-Clause" ]
null
null
null
src/mem/ruby/network/garnet2.0/GarnetNetwork.hh
wjwyyjr/Gem5_task_graph
0e233b5053d6dcd518a2ad6fddd23eaeb9c3a8ee
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2008 Princeton University * Copyright (c) 2016 Georgia Institute of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders 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. * * Authors: Niket Agarwal * Tushar Krishna */ #ifndef __MEM_RUBY_NETWORK_GARNET2_0_GARNETNETWORK_HH__ #define __MEM_RUBY_NETWORK_GARNET2_0_GARNETNETWORK_HH__ #include <iostream> #include <vector> #include "base/output.hh" #include "debug/TaskGraph.hh" #include "mem/ruby/common/Consumer.hh" #include "mem/ruby/network/Network.hh" #include "mem/ruby/network/fault_model/FaultModel.hh" #include "mem/ruby/network/garnet2.0/CommonTypes.hh" #include "mem/ruby/network/garnet2.0/GraphTask.hh" #include "params/GarnetNetwork.hh" #include "sim/sim_exit.hh" class FaultModel; class NetworkInterface; class Router; class NetDest; class NetworkLink; class CreditLink; class GarnetNetwork : public Network, public Consumer { public: typedef GarnetNetworkParams Params; GarnetNetwork(const Params *p); ~GarnetNetwork(); void init(); //add for task graph void wakeup(); void scheduleWakeupAbsolute(Cycles time); // Configuration (set externally) // for 2D topology int getNumRows() const { return m_num_rows; } int getNumCols() { return m_num_cols; } // for network uint32_t getNiFlitSize() const { return m_ni_flit_size; } uint32_t getVCsPerVnet() const { return m_vcs_per_vnet; } uint32_t getBuffersPerDataVC() { return m_buffers_per_data_vc; } uint32_t getBuffersPerCtrlVC() { return m_buffers_per_ctrl_vc; } int getRoutingAlgorithm() const { return m_routing_algorithm; } bool isFaultModelEnabled() const { return m_enable_fault_model; } FaultModel* fault_model; //for Task Graph bool isTaskGraphEnabled() { return m_task_graph_enable; } std::string getTaskGraphFilename() { return m_task_graph_file; } int getTokenLenInPkt() { return m_token_packet_length; } bool loadTraffic(std::string filename); bool checkApplicationFinish(); //for construct architecture in task graph mode bool constructArchitecture(std::string filename); int getNodeIdbyCoreId(int core_id); //for read the application configuration bool readApplicationConfig(std::string filename); bool IsPrintTaskExecuInfo(){return m_print_task_execution_info;} void PrintAppDelay(); void PrintTaskWaitingInfo(); //for Ring Topology std::string getTopology() { return m_topology; } // Internal configuration bool isVNetOrdered(int vnet) const { return m_ordered[vnet]; } VNET_type get_vnet_type(int vc) { int vnet = vc/getVCsPerVnet(); return m_vnet_type[vnet]; } int getNumRouters(); int get_router_id(int ni); //record PE-7 position for initial task judgement in NI int get_entrance_NI(){ return entrance_NI; } int get_entrance_core(){ return entrance_core; } int get_entrance_idx_in_NI(){ return entrance_idx_in_NI; } int get_m_num_application(){ return m_num_application; } // Methods used by Topology to setup the network void makeExtOutLink(SwitchID src, NodeID dest, BasicLink* link, const NetDest& routing_table_entry); void makeExtInLink(NodeID src, SwitchID dest, BasicLink* link, const NetDest& routing_table_entry); void makeInternalLink(SwitchID src, SwitchID dest, BasicLink* link, const NetDest& routing_table_entry, PortDirection src_outport_dirn, PortDirection dest_inport_dirn); //! Function for performing a functional write. The return value //! indicates the number of messages that were written. uint32_t functionalWrite(Packet *pkt); // Stats void collateStats(); void regStats(); void print(std::ostream& out) const; // increment counters void increment_injected_packets(int vnet) { m_packets_injected[vnet]++; } void increment_received_packets(int vnet) { m_packets_received[vnet]++; } void increment_packet_network_latency(Cycles latency, int vnet) { m_packet_network_latency[vnet] += latency; } void increment_packet_queueing_latency(Cycles latency, int vnet) { m_packet_queueing_latency[vnet] += latency; } void increment_injected_flits(int vnet) { m_flits_injected[vnet]++; } void increment_received_flits(int vnet) { m_flits_received[vnet]++; } void increment_flit_network_latency(Cycles latency, int vnet) { m_flit_network_latency[vnet] += latency; } void increment_flit_queueing_latency(Cycles latency, int vnet) { m_flit_queueing_latency[vnet] += latency; } void increment_total_hops(int hops) { m_total_hops += hops; } void add_execution_time_to_total(int ex_time) { m_total_task_execution_time += ex_time; } //record the latenty for src and dst void add_src_dst_latency(int src, int dst, int latency){ src_dst_latency[src][dst] += latency; } //add the task to num_completed_tasks //To output the ete delay when run simulation //shoulb ensure not over m_applicaton_execution_iterations[app_idx] void add_num_completed_tasks(int app_idx, int ex_iters){ //Note here! ex_iters should minus 1 num_completed_tasks[app_idx][ex_iters-1]++; if(num_completed_tasks[app_idx][ex_iters-1] == m_num_task[app_idx]){ //if num_tasks satisfied, then we can ensure the iteration had done. current_execution_iterations[app_idx]++; assert(ex_iters==current_execution_iterations[app_idx]); output_ete_delay(app_idx, ex_iters-1); } } //update start, end time void update_start_end_time(int app_idx, int ex_iters, int start, int end){ //compare the task start time and end time task_start_time[app_idx][ex_iters] = (start<task_start_time[app_idx][ex_iters])?\ start:task_start_time[app_idx][ex_iters]; task_end_time[app_idx][ex_iters] = (end>task_end_time[app_idx][ex_iters])?\ end:task_end_time[app_idx][ex_iters]; } //print ete-delay for certain iteration of one application void output_ete_delay(int app_idx, int ex_iters); //for debug OutputStream *task_start_time_vs_id; OutputStream *task_start_end_time_vs_id; OutputStream *task_start_time_vs_id_iters; //for the ete delay OutputStream *throughput_info; OutputStream *app_delay_running_info; // OutputStream *start_time_info; // OutputStream *end_time_info; // OutputStream *ete_info; OutputStream *network_performance_info; //for the task waiting time OutputStream *task_waiting_time_info; // bool back_pressure(int m_id); // update the in memory remianed information for the src task in src core when record pkt void update_in_memory_info(int core_id, int app_idx, int src_task_id, int edge_id); // find greatest common divisor, for ratio token in NI int gcd(int a, int b){ return b ? gcd(b,a%b):a; } std::vector<int> get_ratio_token(int *iterations); protected: // Configuration int m_num_rows; int m_num_cols; uint32_t m_ni_flit_size; uint32_t m_vcs_per_vnet; uint32_t m_buffers_per_ctrl_vc; uint32_t m_buffers_per_data_vc; int m_routing_algorithm; bool m_enable_fault_model; bool m_task_graph_enable; std::string m_task_graph_file; int m_token_packet_length; std::string m_topology; std::string m_architecture_file; bool m_print_task_execution_info; uint32_t m_vcs_for_allocation; std::string m_vc_allocation_object; //for task graph int m_num_proc; int* m_num_task; int* m_num_edge; int* m_num_head_task; std::vector<std::vector<int> > task_start_time; std::vector<std::vector<int> > task_end_time; std::vector<std::vector<int> > ETE_delay; std::vector<std::vector<int> > head_task; //for construct architecture in task graph mode std::map<int, int> m_core_id_node_id; //core_id -> node_id //for multi-application traffic int m_num_application; int m_total_execution_iterations; std::string* m_application_name; int* m_applicaton_execution_iterations; //for print ete_delay when run simulation int* current_execution_iterations; int** num_completed_tasks; //for record point to point pkt lantency int m_num_core; int** src_dst_latency; //for vc to check vc_allocation_object position std::vector<int> vc_allocation_object_position; //record PE-7 position for initial task judgement in NI int entrance_NI; int entrance_core; int entrance_idx_in_NI; // Statistical variables Stats::Vector m_packets_received; Stats::Vector m_packets_injected; Stats::Vector m_packet_network_latency; Stats::Vector m_packet_queueing_latency; Stats::Formula m_avg_packet_vnet_latency; Stats::Formula m_avg_packet_vqueue_latency; Stats::Formula m_avg_packet_network_latency; Stats::Formula m_avg_packet_queueing_latency; Stats::Formula m_avg_packet_latency; Stats::Vector m_flits_received; Stats::Vector m_flits_injected; Stats::Vector m_flit_network_latency; Stats::Vector m_flit_queueing_latency; Stats::Formula m_avg_flit_vnet_latency; Stats::Formula m_avg_flit_vqueue_latency; Stats::Formula m_avg_flit_network_latency; Stats::Formula m_avg_flit_queueing_latency; Stats::Formula m_avg_flit_latency; Stats::Scalar m_total_ext_in_link_utilization; Stats::Scalar m_total_ext_out_link_utilization; Stats::Scalar m_total_int_link_utilization; Stats::Scalar m_average_link_utilization; Stats::Vector m_average_vc_load; Stats::Scalar m_total_hops; Stats::Formula m_avg_hops; //add for TG Stats::Scalar m_total_task_execution_time; int m_in_mem_size; int m_out_mem_size; private: GarnetNetwork(const GarnetNetwork& obj); GarnetNetwork& operator=(const GarnetNetwork& obj); std::vector<VNET_type > m_vnet_type; std::vector<Router *> m_routers; // All Routers in Network std::vector<NetworkLink *> m_networklinks; // All flit links in the network std::vector<CreditLink *> m_creditlinks; // All credit links in the network std::vector<NetworkInterface *> m_nis; // All NI's in Network }; inline std::ostream& operator<<(std::ostream& out, const GarnetNetwork& obj) { obj.print(out); out << std::flush; return out; } #endif //__MEM_RUBY_NETWORK_GARNET2_0_GARNETNETWORK_HH__
34.628571
93
0.723102
[ "vector" ]
5f4e3161816965da064945ab859d6dd7b8ef8f84
86,270
cxx
C++
src/AspNetCore/Src/forwardinghandler.cxx
mimiagaj/aspnetCore
bce531f61a051c09c9fc2b38a7e72cee6123c95f
[ "MIT" ]
1
2020-08-25T22:41:04.000Z
2020-08-25T22:41:04.000Z
src/AspNetCore/Src/forwardinghandler.cxx
mimiagaj/ASPNETCORE
bce531f61a051c09c9fc2b38a7e72cee6123c95f
[ "MIT" ]
null
null
null
src/AspNetCore/Src/forwardinghandler.cxx
mimiagaj/ASPNETCORE
bce531f61a051c09c9fc2b38a7e72cee6123c95f
[ "MIT" ]
null
null
null
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. #include "precomp.hxx" // Just to be aware of the FORWARDING_HANDLER object size. C_ASSERT(sizeof(FORWARDING_HANDLER) <= 632); #define DEF_MAX_FORWARDS 32 #define HEX_TO_ASCII(c) ((CHAR)(((c) < 10) ? ((c) + '0') : ((c) + 'a' - 10))) #define BUFFER_SIZE (8192UL) #define ENTITY_BUFFER_SIZE (6 + BUFFER_SIZE + 2) #define STR_ANCM_CHILDREQUEST "ANCM_WasCreateProcessFailure" HINTERNET FORWARDING_HANDLER::sm_hSession = NULL; STRU FORWARDING_HANDLER::sm_strErrorFormat; HANDLE FORWARDING_HANDLER::sm_hEventLog = NULL; ALLOC_CACHE_HANDLER * FORWARDING_HANDLER::sm_pAlloc = NULL; TRACE_LOG * FORWARDING_HANDLER::sm_pTraceLog = NULL; PROTOCOL_CONFIG FORWARDING_HANDLER::sm_ProtocolConfig; FORWARDING_HANDLER::FORWARDING_HANDLER( __in IHttpContext * pW3Context ) : m_Signature(FORWARDING_HANDLER_SIGNATURE), m_cRefs(1), m_pW3Context(pW3Context), m_pChildRequestContext(NULL), m_hRequest(NULL), m_fHandleClosedDueToClient(FALSE), m_fResponseHeadersReceivedAndSet(FALSE), m_fDoReverseRewriteHeaders(FALSE), m_msStartTime(0), m_BytesToReceive(0), m_BytesToSend(0), m_pEntityBuffer(NULL), m_cchLastSend(0), m_cEntityBuffers(0), m_cBytesBuffered(0), m_cMinBufferLimit(0), m_pszOriginalHostHeader(NULL), m_RequestStatus(FORWARDER_START), m_pDisconnect(NULL), m_pszHeaders(NULL), m_cchHeaders(0), m_fWebSocketEnabled(FALSE), m_cContentLength(0), m_pWebSocket(NULL), m_pApplication(NULL), m_pAppOfflineHtm(NULL), m_fErrorHandled(FALSE), m_fWebSocketUpgrade(FALSE), m_fFinishRequest(FALSE), m_fClientDisconnected(FALSE) { InitializeSRWLock(&m_RequestLock); } FORWARDING_HANDLER::~FORWARDING_HANDLER( VOID ) { // // Destructor has started. // m_Signature = FORWARDING_HANDLER_SIGNATURE_FREE; // // RemoveRequest() should already have been called and m_pDisconnect // has been freed or m_pDisconnect was never initialized. // // Disconnect notification cleanup would happen first, before // the FORWARDING_HANDLER instance got removed from m_pSharedhandler list. // The m_pServer cleanup would happen afterwards, since there may be a // call pending from SHARED_HANDLER to FORWARDING_HANDLER::SetStatusAndHeaders() // DBG_ASSERT(m_pDisconnect == NULL); FreeResponseBuffers(); if (m_pWebSocket) { m_pWebSocket->Terminate(); m_pWebSocket = NULL; } if (m_pChildRequestContext != NULL) { m_pChildRequestContext->ReleaseClonedContext(); m_pChildRequestContext = NULL; } // // The m_pDisconnect must have happened by now the m_pServer // is the only cleanup left. // RemoveRequest(); if (m_hRequest != NULL) { // m_hRequest should have already been closed and set to NULL // if not, we cannot close it as it may callback and cause AV // let's do our best job here WinHttpSetStatusCallback(m_hRequest, NULL, NULL, NULL); WinHttpCloseHandle(m_hRequest); m_hRequest = NULL; } if(m_pApplication != NULL) { m_pApplication->DereferenceApplication(); m_pApplication = NULL; } if(m_pAppOfflineHtm != NULL) { m_pAppOfflineHtm->DereferenceAppOfflineHtm(); m_pAppOfflineHtm = NULL; } m_pW3Context = NULL; } // static void * FORWARDING_HANDLER::operator new(size_t) { DBG_ASSERT(sm_pAlloc != NULL); if (sm_pAlloc == NULL) { return NULL; } return sm_pAlloc->Alloc(); } // static void FORWARDING_HANDLER::operator delete(void * pMemory) { DBG_ASSERT(sm_pAlloc != NULL); if (sm_pAlloc != NULL) { sm_pAlloc->Free(pMemory); } } VOID FORWARDING_HANDLER::ReferenceForwardingHandler( VOID ) const { LONG cRefs = InterlockedIncrement(&m_cRefs); if (sm_pTraceLog != NULL) { WriteRefTraceLog(sm_pTraceLog, cRefs, this); } } VOID FORWARDING_HANDLER::DereferenceForwardingHandler( VOID ) const { DBG_ASSERT(m_cRefs != 0); LONG cRefs = 0; if ((cRefs = InterlockedDecrement(&m_cRefs)) == 0) { delete this; } if (sm_pTraceLog != NULL) { WriteRefTraceLog(sm_pTraceLog, cRefs, this); } } HRESULT FORWARDING_HANDLER::SetStatusAndHeaders( PCSTR pszHeaders, DWORD ) { HRESULT hr; IHttpResponse * pResponse = m_pW3Context->GetResponse(); IHttpRequest * pRequest = m_pW3Context->GetRequest(); STACK_STRA(strHeaderName, 128); STACK_STRA(strHeaderValue, 2048); DWORD index = 0; PSTR pchNewline; PCSTR pchEndofHeaderValue; BOOL fServerHeaderPresent = FALSE; _ASSERT(pszHeaders != NULL); // // The first line is the status line // PSTR pchStatus = const_cast<PSTR>(strchr(pszHeaders, ' ')); if (pchStatus == NULL) { return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } while (*pchStatus == ' ') { pchStatus++; } USHORT uStatus = static_cast<USHORT>(atoi(pchStatus)); if (m_fWebSocketEnabled && uStatus != 101) { // // Expected 101 response. // m_fWebSocketEnabled = FALSE; } pchStatus = strchr(pchStatus, ' '); if (pchStatus == NULL) { return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } while (*pchStatus == ' ') { pchStatus++; } if (*pchStatus == '\r' || *pchStatus == '\n') { pchStatus--; } pchNewline = strchr(pchStatus, '\n'); if (pchNewline == NULL) { return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } if (uStatus != 200) { // // Skip over any spaces before the '\n' // for (pchEndofHeaderValue = pchNewline - 1; (pchEndofHeaderValue > pchStatus) && ((*pchEndofHeaderValue == ' ') || (*pchEndofHeaderValue == '\r')); pchEndofHeaderValue--) {} // // Copy the status description // if (FAILED(hr = strHeaderValue.Copy( pchStatus, (DWORD)(pchEndofHeaderValue - pchStatus) + 1)) || FAILED(hr = pResponse->SetStatus(uStatus, strHeaderValue.QueryStr(), 0, S_OK, NULL, TRUE))) { return hr; } } for (index = static_cast<DWORD>(pchNewline - pszHeaders) + 1; pszHeaders[index] != '\r' && pszHeaders[index] != '\n' && pszHeaders[index] != '\0'; index = static_cast<DWORD>(pchNewline - pszHeaders) + 1) { // // Find the ':' in Header : Value\r\n // PCSTR pchColon = strchr(pszHeaders + index, ':'); // // Find the '\n' in Header : Value\r\n // pchNewline = const_cast<PSTR>(strchr(pszHeaders + index, '\n')); if (pchNewline == NULL) { return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } // // Take care of header continuation // while (pchNewline[1] == ' ' || pchNewline[1] == '\t') { pchNewline = strchr(pchNewline + 1, '\n'); } DBG_ASSERT( (pchColon != NULL) && (pchColon < pchNewline)); if ((pchColon == NULL) || (pchColon >= pchNewline)) { return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } // // Skip over any spaces before the ':' // PCSTR pchEndofHeaderName; for (pchEndofHeaderName = pchColon - 1; (pchEndofHeaderName >= pszHeaders + index) && (*pchEndofHeaderName == ' '); pchEndofHeaderName--) {} pchEndofHeaderName++; // // Copy the header name // if (FAILED(hr = strHeaderName.Copy( pszHeaders + index, (DWORD)(pchEndofHeaderName - pszHeaders) - index))) { return hr; } // // Skip over the ':' and any trailing spaces // for (index = static_cast<DWORD>(pchColon - pszHeaders) + 1; pszHeaders[index] == ' '; index++) {} // // Skip over any spaces before the '\n' // for (pchEndofHeaderValue = pchNewline - 1; (pchEndofHeaderValue >= pszHeaders + index) && ((*pchEndofHeaderValue == ' ') || (*pchEndofHeaderValue == '\r')); pchEndofHeaderValue--) {} pchEndofHeaderValue++; // // Copy the header value // if (pchEndofHeaderValue == pszHeaders + index) { strHeaderValue.Reset(); } else if (FAILED(hr = strHeaderValue.Copy( pszHeaders + index, (DWORD)(pchEndofHeaderValue - pszHeaders) - index))) { return hr; } // // Do not pass the transfer-encoding:chunked, Connection, Date or // Server headers along // DWORD headerIndex = g_pResponseHeaderHash->GetIndex(strHeaderName.QueryStr()); if (headerIndex == UNKNOWN_INDEX) { hr = pResponse->SetHeader(strHeaderName.QueryStr(), strHeaderValue.QueryStr(), static_cast<USHORT>(strHeaderValue.QueryCCH()), FALSE); // fReplace } else { switch (headerIndex) { case HttpHeaderTransferEncoding: if (!strHeaderValue.Equals("chunked", TRUE)) { break; } __fallthrough; case HttpHeaderConnection: case HttpHeaderDate: continue; case HttpHeaderServer: fServerHeaderPresent = TRUE; break; case HttpHeaderContentLength: if (pRequest->GetRawHttpRequest()->Verb != HttpVerbHEAD) { m_cContentLength = _atoi64(strHeaderValue.QueryStr()); } break; } hr = pResponse->SetHeader(static_cast<HTTP_HEADER_ID>(headerIndex), strHeaderValue.QueryStr(), static_cast<USHORT>(strHeaderValue.QueryCCH()), TRUE); // fReplace } if (FAILED(hr)) { return hr; } } // // Explicitly remove the Server header if the back-end didn't set one. // if (!fServerHeaderPresent) { pResponse->DeleteHeader("Server"); } if (m_fDoReverseRewriteHeaders) { hr = DoReverseRewrite(pResponse); if (FAILED(hr)) { return hr; } } m_fResponseHeadersReceivedAndSet = TRUE; return S_OK; } HRESULT FORWARDING_HANDLER::DoReverseRewrite( __in IHttpResponse *pResponse ) { DBG_ASSERT(pResponse == m_pW3Context->GetResponse()); BOOL fSecure = (m_pW3Context->GetRequest()->GetRawHttpRequest()->pSslInfo != NULL); STRA strTemp; PCSTR pszHeader; PCSTR pszStartHost; PCSTR pszEndHost; HTTP_RESPONSE_HEADERS *pHeaders; HRESULT hr; // // Content-Location and Location are easy, one known header in // http[s]://host/url format // pszHeader = pResponse->GetHeader(HttpHeaderContentLocation); if (pszHeader != NULL) { if (_strnicmp(pszHeader, "http://", 7) == 0) { pszStartHost = pszHeader + 7; } else if (_strnicmp(pszHeader, "https://", 8) == 0) { pszStartHost = pszHeader + 8; } else { goto Location; } pszEndHost = strchr(pszStartHost, '/'); if (FAILED(hr = strTemp.Copy(fSecure ? "https://" : "http://")) || FAILED(hr = strTemp.Append(m_pszOriginalHostHeader))) { return hr; } if (pszEndHost != NULL && FAILED(hr = strTemp.Append(pszEndHost))) { return hr; } if (FAILED(hr = pResponse->SetHeader(HttpHeaderContentLocation, strTemp.QueryStr(), static_cast<USHORT>(strTemp.QueryCCH()), TRUE))) { return hr; } } Location: pszHeader = pResponse->GetHeader(HttpHeaderLocation); if (pszHeader != NULL) { if (_strnicmp(pszHeader, "http://", 7) == 0) { pszStartHost = pszHeader + 7; } else if (_strnicmp(pszHeader, "https://", 8) == 0) { pszStartHost = pszHeader + 8; } else { goto SetCookie; } pszEndHost = strchr(pszStartHost, '/'); if (FAILED(hr = strTemp.Copy(fSecure ? "https://" : "http://")) || FAILED(hr = strTemp.Append(m_pszOriginalHostHeader))) { return hr; } if (pszEndHost != NULL && FAILED(hr = strTemp.Append(pszEndHost))) { return hr; } if (FAILED(hr = pResponse->SetHeader(HttpHeaderLocation, strTemp.QueryStr(), static_cast<USHORT>(strTemp.QueryCCH()), TRUE))) { return hr; } } SetCookie: // // Set-Cookie is different - possibly multiple unknown headers with // syntax name=value ; ... ; Domain=.host ; ... // pHeaders = &pResponse->GetRawHttpResponse()->Headers; for (DWORD i = 0; i<pHeaders->UnknownHeaderCount; i++) { if (_stricmp(pHeaders->pUnknownHeaders[i].pName, "Set-Cookie") != 0) { continue; } pszHeader = pHeaders->pUnknownHeaders[i].pRawValue; pszStartHost = strchr(pszHeader, ';'); while (pszStartHost != NULL) { pszStartHost++; while (IsSpace(*pszStartHost)) { pszStartHost++; } if (_strnicmp(pszStartHost, "Domain", 6) != 0) { pszStartHost = strchr(pszStartHost, ';'); continue; } pszStartHost += 6; while (IsSpace(*pszStartHost)) { pszStartHost++; } if (*pszStartHost != '=') { break; } pszStartHost++; while (IsSpace(*pszStartHost)) { pszStartHost++; } if (*pszStartHost == '.') { pszStartHost++; } pszEndHost = pszStartHost; while (!IsSpace(*pszEndHost) && *pszEndHost != ';' && *pszEndHost != '\0') { pszEndHost++; } if (FAILED(hr = strTemp.Copy(pszHeader, static_cast<DWORD>(pszStartHost - pszHeader))) || FAILED(hr = strTemp.Append(m_pszOriginalHostHeader)) || FAILED(hr = strTemp.Append(pszEndHost))) { return hr; } pszHeader = (PCSTR)m_pW3Context->AllocateRequestMemory(strTemp.QueryCCH() + 1); if (pszHeader == NULL) { return E_OUTOFMEMORY; } StringCchCopyA(const_cast<PSTR>(pszHeader), strTemp.QueryCCH() + 1, strTemp.QueryStr()); pHeaders->pUnknownHeaders[i].pRawValue = pszHeader; pHeaders->pUnknownHeaders[i].RawValueLength = static_cast<USHORT>(strTemp.QueryCCH()); break; } } return S_OK; } HRESULT FORWARDING_HANDLER::GetHeaders( const PROTOCOL_CONFIG * pProtocol, PCWSTR * ppszHeaders, DWORD * pcchHeaders, ASPNETCORE_CONFIG* pAspNetCoreConfig, SERVER_PROCESS* pServerProcess ) { HRESULT hr = S_OK; PCSTR pszCurrentHeader; PCSTR ppHeadersToBeRemoved; PCSTR pszFinalHeader; USHORT cchCurrentHeader; DWORD cchFinalHeader; BOOL fSecure = FALSE; // dummy. Used in SplitUrl. Value will not be used // as ANCM always use http protocol to communicate with backend STRU struDestination; STRU struUrl; STACK_STRA(strTemp, 64); HTTP_REQUEST_HEADERS *pHeaders; IHttpRequest *pRequest = m_pW3Context->GetRequest(); MULTISZA mszMsAspNetCoreHeaders; // // We historically set the host section in request url to the new host header // this is wrong but Kestrel has dependency on it. // should change it in the future // if (FAILED(hr = PATH::SplitUrl(pRequest->GetRawHttpRequest()->CookedUrl.pFullUrl, &fSecure, &struDestination, &struUrl)) || FAILED(hr = strTemp.CopyW(struDestination.QueryStr())) || FAILED(hr = pRequest->SetHeader(HttpHeaderHost, strTemp.QueryStr(), static_cast<USHORT>(strTemp.QueryCCH()), TRUE))) // fReplace { return hr; } // // Strip all headers starting with MS-ASPNETCORE. // These headers are generated by the asp.net core module and // passed to the process it creates. // pHeaders = &m_pW3Context->GetRequest()->GetRawHttpRequest()->Headers; for (DWORD i = 0; i<pHeaders->UnknownHeaderCount; i++) { if (_strnicmp(pHeaders->pUnknownHeaders[i].pName, "MS-ASPNETCORE", 13) == 0) { mszMsAspNetCoreHeaders.Append(pHeaders->pUnknownHeaders[i].pName, (DWORD)pHeaders->pUnknownHeaders[i].NameLength); } } ppHeadersToBeRemoved = mszMsAspNetCoreHeaders.First(); // // iterate the list of headers to be removed and delete them from the request. // while (ppHeadersToBeRemoved != NULL) { m_pW3Context->GetRequest()->DeleteHeader(ppHeadersToBeRemoved); ppHeadersToBeRemoved = mszMsAspNetCoreHeaders.Next(ppHeadersToBeRemoved); } if (pServerProcess->QueryGuid() != NULL) { hr = m_pW3Context->GetRequest()->SetHeader("MS-ASPNETCORE-TOKEN", pServerProcess->QueryGuid(), (USHORT)strlen(pServerProcess->QueryGuid()), TRUE); if (FAILED(hr)) { return hr; } } if (pAspNetCoreConfig->QueryForwardWindowsAuthToken() && (_wcsicmp(m_pW3Context->GetUser()->GetAuthenticationType(), L"negotiate") == 0 || _wcsicmp(m_pW3Context->GetUser()->GetAuthenticationType(), L"ntlm") == 0)) { if (m_pW3Context->GetUser()->GetPrimaryToken() != NULL && m_pW3Context->GetUser()->GetPrimaryToken() != INVALID_HANDLE_VALUE) { HANDLE hTargetTokenHandle = NULL; hr = pServerProcess->SetWindowsAuthToken(m_pW3Context->GetUser()->GetPrimaryToken(), &hTargetTokenHandle); if (FAILED(hr)) { return hr; } // // set request header with target token value // CHAR pszHandleStr[16] = { 0 }; if (_ui64toa_s((UINT64)hTargetTokenHandle, pszHandleStr, 16, 16) != 0) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); return hr; } hr = m_pW3Context->GetRequest()->SetHeader("MS-ASPNETCORE-WINAUTHTOKEN", pszHandleStr, (USHORT)strlen(pszHandleStr), TRUE); if (FAILED(hr)) { return hr; } } } if (!pProtocol->QueryXForwardedForName()->IsEmpty()) { strTemp.Reset(); pszCurrentHeader = pRequest->GetHeader(pProtocol->QueryXForwardedForName()->QueryStr(), &cchCurrentHeader); if (pszCurrentHeader != NULL) { if (FAILED(hr = strTemp.Copy(pszCurrentHeader, cchCurrentHeader)) || FAILED(hr = strTemp.Append(", ", 2))) { return hr; } } if (FAILED(hr = m_pW3Context->GetServerVariable("REMOTE_ADDR", &pszFinalHeader, &cchFinalHeader))) { return hr; } if (pRequest->GetRawHttpRequest()->Address.pRemoteAddress->sa_family == AF_INET6) { if (FAILED(hr = strTemp.Append("[", 1)) || FAILED(hr = strTemp.Append(pszFinalHeader, cchFinalHeader)) || FAILED(hr = strTemp.Append("]", 1))) { return hr; } } else { if (FAILED(hr = strTemp.Append(pszFinalHeader, cchFinalHeader))) { return hr; } } if (pProtocol->QueryIncludePortInXForwardedFor()) { if (FAILED(hr = m_pW3Context->GetServerVariable("REMOTE_PORT", &pszFinalHeader, &cchFinalHeader))) { return hr; } if (FAILED(hr = strTemp.Append(":", 1)) || FAILED(hr = strTemp.Append(pszFinalHeader, cchFinalHeader))) { return hr; } } if (FAILED(hr = pRequest->SetHeader(pProtocol->QueryXForwardedForName()->QueryStr(), strTemp.QueryStr(), static_cast<USHORT>(strTemp.QueryCCH()), TRUE))) // fReplace { return hr; } } if (!pProtocol->QuerySslHeaderName()->IsEmpty()) { const HTTP_SSL_INFO *pSslInfo = pRequest->GetRawHttpRequest()->pSslInfo; LPSTR pszScheme = "http"; if (pSslInfo != NULL) { pszScheme = "https"; } strTemp.Reset(); pszCurrentHeader = pRequest->GetHeader(pProtocol->QuerySslHeaderName()->QueryStr(), &cchCurrentHeader); if (pszCurrentHeader != NULL) { if (FAILED(hr = strTemp.Copy(pszCurrentHeader, cchCurrentHeader)) || FAILED(hr = strTemp.Append(", ", 2))) { return hr; } } if (FAILED(hr = strTemp.Append(pszScheme))) { return hr; } if (FAILED(pRequest->SetHeader(pProtocol->QuerySslHeaderName()->QueryStr(), strTemp.QueryStr(), (USHORT)strTemp.QueryCCH(), TRUE))) { return hr; } } if (!pProtocol->QueryClientCertName()->IsEmpty()) { if (pRequest->GetRawHttpRequest()->pSslInfo == NULL || pRequest->GetRawHttpRequest()->pSslInfo->pClientCertInfo == NULL) { pRequest->DeleteHeader(pProtocol->QueryClientCertName()->QueryStr()); } else { // Resize the buffer large enough to hold the encoded certificate info if (FAILED(hr = strTemp.Resize( 1 + (pRequest->GetRawHttpRequest()->pSslInfo->pClientCertInfo->CertEncodedSize + 2) / 3 * 4))) { return hr; } Base64Encode( pRequest->GetRawHttpRequest()->pSslInfo->pClientCertInfo->pCertEncoded, pRequest->GetRawHttpRequest()->pSslInfo->pClientCertInfo->CertEncodedSize, strTemp.QueryStr(), strTemp.QuerySize(), NULL); strTemp.SyncWithBuffer(); if (FAILED(hr = pRequest->SetHeader( pProtocol->QueryClientCertName()->QueryStr(), strTemp.QueryStr(), static_cast<USHORT>(strTemp.QueryCCH()), TRUE))) // fReplace { return hr; } } } // // Remove the connection header // if (!m_fWebSocketEnabled) { pRequest->DeleteHeader(HttpHeaderConnection); } // // Get all the headers to send to the client // hr = m_pW3Context->GetServerVariable("ALL_RAW", ppszHeaders, pcchHeaders); if (FAILED(hr)) { return hr; } return S_OK; } HRESULT FORWARDING_HANDLER::CreateWinHttpRequest( __in const IHttpRequest * pRequest, __in const PROTOCOL_CONFIG * pProtocol, __in HINTERNET hConnect, __inout STRU * pstrUrl, ASPNETCORE_CONFIG* pAspNetCoreConfig, SERVER_PROCESS* pServerProcess ) { HRESULT hr = S_OK; PCWSTR pszVersion = NULL; PCSTR pszVerb; STACK_STRU(strVerb, 32); // // Create the request handle for this request (leave some fields blank, // we will fill them when sending the request) // pszVerb = pRequest->GetHttpMethod(); if (FAILED(hr = strVerb.CopyA(pszVerb))) { goto Finished; } //pszVersion = pProtocol->QueryVersion(); if (pszVersion == NULL) { DWORD cchUnused; hr = m_pW3Context->GetServerVariable( "HTTP_VERSION", &pszVersion, &cchUnused); if (FAILED(hr)) { goto Finished; } } m_hRequest = WinHttpOpenRequest(hConnect, strVerb.QueryStr(), pstrUrl->QueryStr(), pszVersion, WINHTTP_NO_REFERER, WINHTTP_DEFAULT_ACCEPT_TYPES, WINHTTP_FLAG_ESCAPE_DISABLE_QUERY | g_OptionalWinHttpFlags); if (m_hRequest == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } if (!WinHttpSetTimeouts(m_hRequest, pProtocol->QueryTimeout(), pProtocol->QueryTimeout(), pProtocol->QueryTimeout(), pProtocol->QueryTimeout())) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } DWORD dwResponseBufferLimit = pProtocol->QueryResponseBufferLimit(); if (!WinHttpSetOption(m_hRequest, WINHTTP_OPTION_MAX_RESPONSE_DRAIN_SIZE, &dwResponseBufferLimit, sizeof(dwResponseBufferLimit))) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } DWORD dwMaxHeaderSize = pProtocol->QueryMaxResponseHeaderSize(); if (!WinHttpSetOption(m_hRequest, WINHTTP_OPTION_MAX_RESPONSE_HEADER_SIZE, &dwMaxHeaderSize, sizeof(dwMaxHeaderSize))) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } DWORD dwOption = WINHTTP_DISABLE_COOKIES; dwOption |= WINHTTP_DISABLE_AUTHENTICATION; if (!pProtocol->QueryDoKeepAlive()) { dwOption |= WINHTTP_DISABLE_KEEP_ALIVE; } if (!WinHttpSetOption(m_hRequest, WINHTTP_OPTION_DISABLE_FEATURE, &dwOption, sizeof(dwOption))) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } if (WinHttpSetStatusCallback(m_hRequest, FORWARDING_HANDLER::OnWinHttpCompletion, (WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_FLAG_HANDLES | WINHTTP_CALLBACK_STATUS_SENDING_REQUEST), NULL) == WINHTTP_INVALID_STATUS_CALLBACK) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } hr = GetHeaders(pProtocol, &m_pszHeaders, &m_cchHeaders, pAspNetCoreConfig, pServerProcess); if (FAILED(hr)) { goto Finished; } Finished: return hr; } REQUEST_NOTIFICATION_STATUS FORWARDING_HANDLER::OnExecuteRequestHandler( VOID ) { REQUEST_NOTIFICATION_STATUS retVal = RQ_NOTIFICATION_CONTINUE; HRESULT hr = S_OK; bool fRequestLocked = FALSE; ASPNETCORE_CONFIG *pAspNetCoreConfig = NULL; FORWARDER_CONNECTION *pConnection = NULL; STACK_STRU(strDestination, 32); STACK_STRU(strUrl, 2048); STACK_STRU(struEscapedUrl, 2048); STACK_STRU(strDescription, 128); HINTERNET hConnect = NULL; IHttpRequest *pRequest = m_pW3Context->GetRequest(); IHttpResponse *pResponse = m_pW3Context->GetResponse(); PROTOCOL_CONFIG *pProtocol = &sm_ProtocolConfig; APPLICATION_MANAGER *pApplicationManager = NULL; SERVER_PROCESS *pServerProcess = NULL; USHORT cchHostName = 0; BOOL fSecure = FALSE; BOOL fProcessStartFailure = FALSE; HTTP_DATA_CHUNK *pDataChunk = NULL; DBG_ASSERT(m_RequestStatus == FORWARDER_START); // // Take a reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); m_pszOriginalHostHeader = pRequest->GetHeader(HttpHeaderHost, &cchHostName); // read per site aspNetCore configuration. hr = ASPNETCORE_CONFIG::GetConfig(m_pW3Context, &pAspNetCoreConfig); if (FAILED(hr)) { // configuration error. goto Failure; } // override Protocol related config from aspNetCore config pProtocol->OverrideConfig(pAspNetCoreConfig); // // parse original url // if (FAILED(hr = PATH::SplitUrl(pRequest->GetRawHttpRequest()->CookedUrl.pFullUrl, &fSecure, &strDestination, &strUrl))) { goto Failure; } if (FAILED(hr = PATH::EscapeAbsPath(pRequest, &struEscapedUrl))) { goto Failure; } m_fDoReverseRewriteHeaders = pProtocol->QueryReverseRewriteHeaders(); IHttpConnection * pClientConnection = m_pW3Context->GetConnection(); if (pClientConnection == NULL || !pClientConnection->IsConnected()) { hr = HRESULT_FROM_WIN32(WSAECONNRESET); goto Failure; } m_cMinBufferLimit = pProtocol->QueryMinResponseBuffer(); // // Find the application that is supposed to service this request. // pApplicationManager = APPLICATION_MANAGER::GetInstance(); if (pApplicationManager == NULL) { hr = E_OUTOFMEMORY; goto Failure; } hr = pApplicationManager->GetApplication(m_pW3Context, &m_pApplication); if (FAILED(hr)) { goto Failure; } m_pAppOfflineHtm = m_pApplication->QueryAppOfflineHtm(); if (m_pAppOfflineHtm != NULL) { m_pAppOfflineHtm->ReferenceAppOfflineHtm(); } if (m_pApplication->AppOfflineFound() && m_pAppOfflineHtm != NULL) { HTTP_DATA_CHUNK DataChunk; PCSTR pszANCMHeader; DWORD cchANCMHeader; BOOL fCompletionExpected = FALSE; if (FAILED(m_pW3Context->GetServerVariable(STR_ANCM_CHILDREQUEST, &pszANCMHeader, &cchANCMHeader))) // first time failure { if (SUCCEEDED(hr = m_pW3Context->CloneContext( CLONE_FLAG_BASICS | CLONE_FLAG_HEADERS | CLONE_FLAG_ENTITY, &m_pChildRequestContext )) && SUCCEEDED(hr = m_pChildRequestContext->SetServerVariable( STR_ANCM_CHILDREQUEST, L"1")) && SUCCEEDED(hr = m_pW3Context->ExecuteRequest( TRUE, // fAsync m_pChildRequestContext, EXECUTE_FLAG_DISABLE_CUSTOM_ERROR, // by pass Custom Error module NULL, // pHttpUser &fCompletionExpected))) { if (!fCompletionExpected) { retVal = RQ_NOTIFICATION_CONTINUE; } else { retVal = RQ_NOTIFICATION_PENDING; } goto Finished; } // // fail to create child request, fall back to default 502 error // } DataChunk.DataChunkType = HttpDataChunkFromMemory; DataChunk.FromMemory.pBuffer = (PVOID)m_pAppOfflineHtm->m_Contents.QueryStr(); DataChunk.FromMemory.BufferLength = m_pAppOfflineHtm->m_Contents.QueryCB(); if (FAILED(hr = pResponse->WriteEntityChunkByReference(&DataChunk))) { goto Finished; } pResponse->SetStatus(503, "Service Unavailable", 0, hr); pResponse->SetHeader("Content-Type", "text/html", (USHORT)strlen("text/html"), FALSE ); // no need to check return hresult goto Finished; } hr = m_pApplication->GetProcess(m_pW3Context, pAspNetCoreConfig, &pServerProcess); if (FAILED(hr)) { fProcessStartFailure = TRUE; goto Failure; } if (pServerProcess == NULL) { hr = HRESULT_FROM_WIN32(ERROR_CREATE_FAILED); goto Failure; } if (pServerProcess->QueryWinHttpConnection() == NULL) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE); goto Failure; } hConnect = pServerProcess->QueryWinHttpConnection()->QueryHandle(); // // Mark request as websocket if upgrade header is present. // if (g_fWebSocketSupported) { USHORT cchHeader = 0; PCSTR pszWebSocketHeader = pRequest->GetHeader("Upgrade", &cchHeader); if (cchHeader == 9 && _stricmp(pszWebSocketHeader, "websocket") == 0) { m_fWebSocketEnabled = TRUE; } } hr = CreateWinHttpRequest(pRequest, pProtocol, hConnect, &struEscapedUrl, pAspNetCoreConfig, pServerProcess); if (FAILED(hr)) { goto Failure; } // // Register for connection disconnect notification with http.sys. // N.B. This feature is currently disabled due to synchronization conditions. // // disabling this disconnect notification as it causes synchronization/AV issue // will re-enable it in the future after investigation //if (g_fAsyncDisconnectAvailable) //{ // m_pDisconnect = static_cast<ASYNC_DISCONNECT_CONTEXT *>( // pClientConnection->GetModuleContextContainer()-> // GetConnectionModuleContext(g_pModuleId)); // if (m_pDisconnect == NULL) // { // m_pDisconnect = new ASYNC_DISCONNECT_CONTEXT; // if (m_pDisconnect == NULL) // { // hr = E_OUTOFMEMORY; // goto Failure; // } // hr = pClientConnection->GetModuleContextContainer()-> // SetConnectionModuleContext(m_pDisconnect, // g_pModuleId); // DBG_ASSERT(hr != HRESULT_FROM_WIN32(ERROR_ALREADY_ASSIGNED)); // if (FAILED(hr)) // { // goto Failure; // } // } // // // // Issue: There is a window of opportunity to miss on the disconnect // // notification if it happens before the SetHandler() call is made. // // It is suboptimal for performance, but should functionally be OK. // // // m_pDisconnect->SetHandler(this); //} // // Read lock on the WinHTTP handle to protect from server closing // the handle while it is in use. // AcquireSRWLockShared(&m_RequestLock); fRequestLocked = TRUE; if (m_hRequest == NULL) { hr = HRESULT_FROM_WIN32(WSAECONNRESET); goto Failure; } // // Begins normal request handling. Send request to server. // m_RequestStatus = FORWARDER_SENDING_REQUEST; // // Calculate the bytes to receive from the content length. // DWORD cbContentLength = 0; PCSTR pszContentLength = pRequest->GetHeader(HttpHeaderContentLength); if (pszContentLength != NULL) { cbContentLength = m_BytesToReceive = atol(pszContentLength); if (m_BytesToReceive == INFINITE) { hr = HRESULT_FROM_WIN32(WSAECONNRESET); goto Failure; } } else if (pRequest->GetHeader(HttpHeaderTransferEncoding) != NULL) { m_BytesToReceive = INFINITE; } if (m_fWebSocketEnabled) { // // Set the upgrade flag for a websocket request. // if (!WinHttpSetOption(m_hRequest, WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET, NULL, 0)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } } m_cchLastSend = m_cchHeaders; // // Remember the handler being processed in the current thread // before staring a WinHTTP operation. // DBG_ASSERT(fRequestLocked); DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == NULL); TlsSetValue(g_dwTlsIndex, this); DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == this); // // WinHttpSendRequest can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpSendRequest(m_hRequest, m_pszHeaders, m_cchHeaders, NULL, 0, cbContentLength, reinterpret_cast<DWORD_PTR>(static_cast<PVOID>(this)))) { hr = HRESULT_FROM_WIN32(GetLastError()); DebugPrintf(ASPNETCORE_DEBUG_FLAG_INFO, "FORWARDING_HANDLER::OnExecuteRequestHandler, Send request failed"); DereferenceForwardingHandler(); goto Failure; } // // Async WinHTTP operation is in progress. Release this thread meanwhile, // OnWinHttpCompletion method should resume the work by posting an IIS completion. // retVal = RQ_NOTIFICATION_PENDING; goto Finished; Failure: // // Reset status for consistency. // m_RequestStatus = FORWARDER_DONE; pResponse->DisableKernelCache(); pResponse->GetRawHttpResponse()->EntityChunkCount = 0; // // Finish the request on failure. // retVal = RQ_NOTIFICATION_FINISH_REQUEST; if (hr == HRESULT_FROM_WIN32(WSAECONNRESET)) { pResponse->SetStatus(400, "Bad Request", 0, hr); goto Finished; } else if (fProcessStartFailure && !pAspNetCoreConfig->QueryDisableStartUpErrorPage()) { PCSTR pszANCMHeader; DWORD cchANCMHeader; BOOL fCompletionExpected = FALSE; if (FAILED(m_pW3Context->GetServerVariable(STR_ANCM_CHILDREQUEST, &pszANCMHeader, &cchANCMHeader))) // first time failure { if (SUCCEEDED(hr = m_pW3Context->CloneContext( CLONE_FLAG_BASICS | CLONE_FLAG_HEADERS | CLONE_FLAG_ENTITY, &m_pChildRequestContext )) && SUCCEEDED(hr = m_pChildRequestContext->SetServerVariable( STR_ANCM_CHILDREQUEST, L"1")) && SUCCEEDED(hr = m_pW3Context->ExecuteRequest( TRUE, // fAsync m_pChildRequestContext, EXECUTE_FLAG_DISABLE_CUSTOM_ERROR, // by pass Custom Error module NULL, // pHttpUser &fCompletionExpected))) { if (!fCompletionExpected) { retVal = RQ_NOTIFICATION_CONTINUE; } else { retVal = RQ_NOTIFICATION_PENDING; } goto Finished; } // // fail to create child request, fall back to default 502 error // } else { if (SUCCEEDED(pApplicationManager->Get502ErrorPage(&pDataChunk))) { if (FAILED(hr = pResponse->WriteEntityChunkByReference(pDataChunk))) { goto Finished; } pResponse->SetStatus(502, "Bad Gateway", 5, hr); pResponse->SetHeader("Content-Type", "text/html", (USHORT)strlen("text/html"), FALSE ); goto Finished; } } } // // default error behavior // pResponse->SetStatus(502, "Bad Gateway", 3, hr); if (hr > HRESULT_FROM_WIN32(WINHTTP_ERROR_BASE) && hr <= HRESULT_FROM_WIN32(WINHTTP_ERROR_LAST)) { #pragma prefast (suppress : __WARNING_FUNCTION_NEEDS_REVIEW, "Function and parameters reviewed.") FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE, g_hWinHttpModule, HRESULT_CODE(hr), 0, strDescription.QueryStr(), strDescription.QuerySizeCCH(), NULL); } else { LoadString(g_hModule, IDS_SERVER_ERROR, strDescription.QueryStr(), strDescription.QuerySizeCCH()); } strDescription.SyncWithBuffer(); if (strDescription.QueryCCH() != 0) { pResponse->SetErrorDescription( strDescription.QueryStr(), strDescription.QueryCCH(), FALSE); } Finished: if (pConnection != NULL) { pConnection->DereferenceForwarderConnection(); pConnection = NULL; } if (pServerProcess != NULL) { pServerProcess->DereferenceServerProcess(); pServerProcess = NULL; } if (fRequestLocked) { DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == this); TlsSetValue(g_dwTlsIndex, NULL); ReleaseSRWLockShared(&m_RequestLock); DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == NULL); } if (retVal != RQ_NOTIFICATION_PENDING) { // // Remove request so that load-balancing algorithms like minCurrentRequests/minAverageResponseTime // get the correct time when we received the last byte of response, rather than when we received // ack from client about last byte of response - which could be much later. // RemoveRequest(); } DereferenceForwardingHandler(); // // Do not use this object after dereferencing it, it may be gone. // return retVal; } VOID FORWARDING_HANDLER::RemoveRequest() { if (m_pDisconnect != NULL) { m_pDisconnect->ResetHandler(); m_pDisconnect = NULL; } } REQUEST_NOTIFICATION_STATUS FORWARDING_HANDLER::OnAsyncCompletion( DWORD cbCompletion, HRESULT hrCompletionStatus ) /*++ Routine Description: Handle the completion from IIS and continue the execution of this request based on the current state. Arguments: cbCompletion - Number of bytes associated with this completion dwCompletionStatus - the win32 status associated with this completion Return Value: REQUEST_NOTIFICATION_STATUS --*/ { HRESULT hr = S_OK; REQUEST_NOTIFICATION_STATUS retVal = RQ_NOTIFICATION_CONTINUE; BOOL fLocked = FALSE; bool fClientError = FALSE; BOOL fClosed = FALSE; if (sm_pTraceLog != NULL) { WriteRefTraceLogEx(sm_pTraceLog, m_cRefs, this, "FORWARDING_HANDLER::OnAsyncCompletion Enter", reinterpret_cast<PVOID>(static_cast<DWORD_PTR>(cbCompletion)), reinterpret_cast<PVOID>(static_cast<DWORD_PTR>(hrCompletionStatus))); } // // Take a reference so that object does not go away as a result of // async completion. // // Read lock on the WinHTTP handle to protect from server closing // the handle while it is in use. // ReferenceForwardingHandler(); DBG_ASSERT(m_pW3Context != NULL); __analysis_assume(m_pW3Context != NULL); // // OnAsyncCompletion can be called on a Winhttp io completion thread. // Hence we need to check the TLS before we acquire the shared lock. // if (TlsGetValue(g_dwTlsIndex) != this) { DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == NULL); AcquireSRWLockShared(&m_RequestLock); TlsSetValue(g_dwTlsIndex, this); DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == this); fLocked = TRUE; } if (m_hRequest == NULL) { if (m_RequestStatus == FORWARDER_DONE && m_fFinishRequest) { retVal = RQ_NOTIFICATION_FINISH_REQUEST; goto Finished; } fClientError = m_fHandleClosedDueToClient; goto Failure; } else if (m_RequestStatus == FORWARDER_RECEIVED_WEBSOCKET_RESPONSE) { DebugPrintf(ASPNETCORE_DEBUG_FLAG_INFO, "FORWARDING_HANDLER::OnAsyncCompletion, Send completed for 101 response"); // // This should be the write completion of the 101 response. // m_pWebSocket = new WEBSOCKET_HANDLER(); if (m_pWebSocket == NULL) { hr = E_OUTOFMEMORY; goto Finished; } hr = m_pWebSocket->ProcessRequest(this, m_pW3Context, m_hRequest); if (FAILED(hr)) { goto Failure; } // // WebSocket upgrade is successful. Close the WinHttpRequest Handle // WinHttpSetStatusCallback(m_hRequest, FORWARDING_HANDLER::OnWinHttpCompletion, WINHTTP_CALLBACK_FLAG_HANDLES, NULL); fClosed = WinHttpCloseHandle(m_hRequest); DBG_ASSERT(fClosed); if (fClosed) { m_fWebSocketUpgrade = TRUE; m_hRequest = NULL; } else { hr = HRESULT_FROM_WIN32(GetLastError()); goto Failure; } retVal = RQ_NOTIFICATION_PENDING; goto Finished; } else if (m_RequestStatus == FORWARDER_RESET_CONNECTION) { hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_INVALID_SERVER_RESPONSE); goto Failure; } // // Begins normal completion handling. There is already a shared acquired // for protecting the WinHTTP request handle from being closed. // switch (m_RequestStatus) { case FORWARDER_RECEIVING_RESPONSE: // // This is a completion of a write (send) to http.sys, abort in case of // failure, if there is more data available from WinHTTP, read it // or else ask if there is more. // if (FAILED(hrCompletionStatus)) { hr = hrCompletionStatus; fClientError = TRUE; goto Failure; } hr = OnReceivingResponse(); if (FAILED(hr)) { goto Failure; } break; case FORWARDER_SENDING_REQUEST: hr = OnSendingRequest(cbCompletion, hrCompletionStatus, &fClientError); if (FAILED(hr)) { goto Failure; } break; default: DBG_ASSERT(m_RequestStatus == FORWARDER_DONE); goto Finished; } // // Either OnReceivingResponse or OnSendingRequest initiated an // async WinHTTP operation, release this thread meanwhile, // OnWinHttpCompletion method should resume the work by posting an IIS completion. // retVal = RQ_NOTIFICATION_PENDING; goto Finished; Failure: // // Reset status for consistency. // m_RequestStatus = FORWARDER_DONE; // // Do the right thing based on where the error originated from. // IHttpResponse *pResponse = m_pW3Context->GetResponse(); pResponse->DisableKernelCache(); pResponse->GetRawHttpResponse()->EntityChunkCount = 0; // double check to set right status code if (!m_pW3Context->GetConnection()->IsConnected()) { fClientError = TRUE; } if (fClientError) { if (!m_fResponseHeadersReceivedAndSet) { pResponse->SetStatus(400, "Bad Request", 0, HRESULT_FROM_WIN32(WSAECONNRESET)); } else { // // Response headers from origin server were // already received and set for the current response. // Honor the response status. // } } else { STACK_STRU(strDescription, 128); pResponse->SetStatus(502, "Bad Gateway", 3, hr); if (hr > HRESULT_FROM_WIN32(WINHTTP_ERROR_BASE) && hr <= HRESULT_FROM_WIN32(WINHTTP_ERROR_LAST)) { #pragma prefast (suppress : __WARNING_FUNCTION_NEEDS_REVIEW, "Function and parameters reviewed.") FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE, g_hWinHttpModule, HRESULT_CODE(hr), 0, strDescription.QueryStr(), strDescription.QuerySizeCCH(), NULL); } else { LoadString(g_hModule, IDS_SERVER_ERROR, strDescription.QueryStr(), strDescription.QuerySizeCCH()); } (VOID)strDescription.SyncWithBuffer(); if (strDescription.QueryCCH() != 0) { pResponse->SetErrorDescription( strDescription.QueryStr(), strDescription.QueryCCH(), FALSE); } if (hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_INVALID_SERVER_RESPONSE)) { pResponse->ResetConnection(); goto Finished; } } // // Finish the request on failure. // retVal = RQ_NOTIFICATION_FINISH_REQUEST; Finished: if (fLocked) { DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == this); TlsSetValue(g_dwTlsIndex, NULL); ReleaseSRWLockShared(&m_RequestLock); DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == NULL); } if (retVal != RQ_NOTIFICATION_PENDING) { // // Remove request so that load-balancing algorithms like minCurrentRequests/minAverageResponseTime // get the correct time when we received the last byte of response, rather than when we received // ack from client about last byte of response - which could be much later. // RemoveRequest(); } DereferenceForwardingHandler(); // // Do not use this object after dereferencing it, it may be gone. // return retVal; } HRESULT FORWARDING_HANDLER::OnSendingRequest( DWORD cbCompletion, HRESULT hrCompletionStatus, __out bool * pfClientError ) { HRESULT hr = S_OK; // // This is a completion for a read from http.sys, abort in case // of failure, if we read anything write it out over WinHTTP, // but we have already reached EOF, now read the response // if (hrCompletionStatus == HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)) { DBG_ASSERT(m_BytesToReceive == 0 || m_BytesToReceive == INFINITE); if (m_BytesToReceive == INFINITE) { m_BytesToReceive = 0; m_cchLastSend = 5; // "0\r\n\r\n" // // WinHttpWriteData can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpWriteData(m_hRequest, "0\r\n\r\n", 5, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); DereferenceForwardingHandler(); goto Failure; } } else { m_RequestStatus = FORWARDER_RECEIVING_RESPONSE; // // WinHttpReceiveResponse can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpReceiveResponse(m_hRequest, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); DereferenceForwardingHandler(); goto Failure; } } } else if (SUCCEEDED(hrCompletionStatus)) { DWORD cbOffset; if (m_BytesToReceive != INFINITE) { m_BytesToReceive -= cbCompletion; cbOffset = 6; } else { // // For chunk-encoded requests, need to re-chunk the // entity body // // Add the CRLF just before and after the chunk data // m_pEntityBuffer[4] = '\r'; m_pEntityBuffer[5] = '\n'; m_pEntityBuffer[cbCompletion + 6] = '\r'; m_pEntityBuffer[cbCompletion + 7] = '\n'; if (cbCompletion < 0x10) { cbOffset = 3; m_pEntityBuffer[3] = HEX_TO_ASCII(cbCompletion); cbCompletion += 5; } else if (cbCompletion < 0x100) { cbOffset = 2; m_pEntityBuffer[2] = HEX_TO_ASCII(cbCompletion >> 4); m_pEntityBuffer[3] = HEX_TO_ASCII(cbCompletion & 0xf); cbCompletion += 6; } else if (cbCompletion < 0x1000) { cbOffset = 1; m_pEntityBuffer[1] = HEX_TO_ASCII(cbCompletion >> 8); m_pEntityBuffer[2] = HEX_TO_ASCII((cbCompletion >> 4) & 0xf); m_pEntityBuffer[3] = HEX_TO_ASCII(cbCompletion & 0xf); cbCompletion += 7; } else { DBG_ASSERT(cbCompletion < 0x10000); cbOffset = 0; m_pEntityBuffer[0] = HEX_TO_ASCII(cbCompletion >> 12); m_pEntityBuffer[1] = HEX_TO_ASCII((cbCompletion >> 8) & 0xf); m_pEntityBuffer[2] = HEX_TO_ASCII((cbCompletion >> 4) & 0xf); m_pEntityBuffer[3] = HEX_TO_ASCII(cbCompletion & 0xf); cbCompletion += 8; } } m_cchLastSend = cbCompletion; // // WinHttpWriteData can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpWriteData(m_hRequest, m_pEntityBuffer + cbOffset, cbCompletion, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); DereferenceForwardingHandler(); goto Failure; } } else { hr = hrCompletionStatus; *pfClientError = TRUE; goto Failure; } Failure: return hr; } HRESULT FORWARDING_HANDLER::OnReceivingResponse( ) { HRESULT hr = S_OK; if (m_cBytesBuffered >= m_cMinBufferLimit) { FreeResponseBuffers(); } if (m_BytesToSend == 0) { // // If response buffering is enabled, try to read large chunks // at a time - also treat very small buffering limit as no // buffering // m_BytesToSend = min(m_cMinBufferLimit, BUFFER_SIZE); if (m_BytesToSend < BUFFER_SIZE / 2) { // // Disable buffering. // m_BytesToSend = 0; } } if (m_BytesToSend == 0) { // // No buffering enabled. // // WinHttpQueryDataAvailable can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpQueryDataAvailable(m_hRequest, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); DereferenceForwardingHandler(); goto Failure; } } else { // // Buffering enabled. // if (m_pEntityBuffer == NULL) { m_pEntityBuffer = GetNewResponseBuffer(min(m_BytesToSend, BUFFER_SIZE)); if (m_pEntityBuffer == NULL) { hr = E_OUTOFMEMORY; goto Failure; } } // // WinHttpReadData can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpReadData(m_hRequest, m_pEntityBuffer, min(m_BytesToSend, BUFFER_SIZE), NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); DereferenceForwardingHandler(); goto Failure; } } Failure: return hr; } VOID FORWARDING_HANDLER::OnWinHttpCompletionInternal( HINTERNET hRequest, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength ) /*++ Routine Description: Completion call associated with a WinHTTP operation Arguments: hRequest - The winhttp request handle associated with this completion dwInternetStatus - enum specifying what the completion is for lpvStatusInformation - completion specific information dwStatusInformationLength - length of the above information Return Value: None --*/ { HRESULT hr = S_OK; bool fIsCompletionThread = FALSE; bool fClientError = FALSE; bool fAnotherCompletionExpected = FALSE; DBG_ASSERT(m_pW3Context != NULL); __analysis_assume(m_pW3Context != NULL); IHttpResponse * pResponse = m_pW3Context->GetResponse(); BOOL fDerefForwardingHandler = TRUE; BOOL fEndRequest = FALSE; UNREFERENCED_PARAMETER(dwStatusInformationLength); if (sm_pTraceLog != NULL) { WriteRefTraceLogEx(sm_pTraceLog, m_cRefs, this, "FORWARDING_HANDLER::OnWinHttpCompletionInternal Enter", reinterpret_cast<PVOID>(static_cast<DWORD_PTR>(dwInternetStatus)), NULL); } // // ReadLock on the winhttp handle to protect from a client disconnect/ // server stop closing the handle while we are using it. // // WinHttp can call async completion on the same thread/stack, so // we have to account for that and not try to take the lock again, // otherwise, we could end up in a deadlock. // // Take a reference so that object does not go away as a result of // async completion - release one reference when async operation is // initiated, two references if async operation is not initiated // if (TlsGetValue(g_dwTlsIndex) != this) { DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == NULL); AcquireSRWLockShared(&m_RequestLock); TlsSetValue(g_dwTlsIndex, this); fIsCompletionThread = TRUE; DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == this); } fEndRequest = (dwInternetStatus == WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING); if (!fEndRequest) { if (!m_pW3Context->GetConnection()->IsConnected()) { m_fClientDisconnected = TRUE; if (m_hRequest != NULL) { WinHttpSetStatusCallback(m_hRequest, FORWARDING_HANDLER::OnWinHttpCompletion, WINHTTP_CALLBACK_FLAG_HANDLES, NULL); if (WinHttpCloseHandle(m_hRequest)) { m_hRequest = NULL; } else { // if WinHttpCloseHandle failed, we are already in failure path // nothing can can be done here } } hr = ERROR_CONNECTION_ABORTED; fClientError = m_fHandleClosedDueToClient = TRUE; fDerefForwardingHandler = FALSE; // wait for HANDLE_CLOSING callback to clean up fAnotherCompletionExpected = !fEndRequest; goto Failure; } } if (m_RequestStatus == FORWARDER_RECEIVED_WEBSOCKET_RESPONSE) { fDerefForwardingHandler = FALSE; fAnotherCompletionExpected = TRUE; if(m_pWebSocket == NULL) { goto Finished; } switch (dwInternetStatus) { case WINHTTP_CALLBACK_STATUS_SHUTDOWN_COMPLETE: m_pWebSocket->OnWinHttpShutdownComplete(); break; case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: m_pWebSocket->OnWinHttpSendComplete( (WINHTTP_WEB_SOCKET_STATUS*)lpvStatusInformation ); break; case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: m_pWebSocket->OnWinHttpReceiveComplete( (WINHTTP_WEB_SOCKET_STATUS*)lpvStatusInformation ); break; case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: m_pWebSocket->OnWinHttpIoError( (WINHTTP_WEB_SOCKET_ASYNC_RESULT*)lpvStatusInformation ); break; } goto Finished; } switch (dwInternetStatus) { case WINHTTP_CALLBACK_STATUS_SENDREQUEST_COMPLETE: case WINHTTP_CALLBACK_STATUS_WRITE_COMPLETE: hr = OnWinHttpCompletionSendRequestOrWriteComplete(hRequest, dwInternetStatus, &fClientError, &fAnotherCompletionExpected); break; case WINHTTP_CALLBACK_STATUS_HEADERS_AVAILABLE: hr = OnWinHttpCompletionStatusHeadersAvailable(hRequest, &fAnotherCompletionExpected); break; case WINHTTP_CALLBACK_STATUS_DATA_AVAILABLE: hr = OnWinHttpCompletionStatusDataAvailable(hRequest, *reinterpret_cast<const DWORD *>(lpvStatusInformation), // dwBytes &fAnotherCompletionExpected); break; case WINHTTP_CALLBACK_STATUS_READ_COMPLETE: hr = OnWinHttpCompletionStatusReadComplete(pResponse, dwStatusInformationLength, &fAnotherCompletionExpected); break; case WINHTTP_CALLBACK_STATUS_REQUEST_ERROR: hr = HRESULT_FROM_WIN32(static_cast<const WINHTTP_ASYNC_RESULT *>(lpvStatusInformation)->dwError); break; case WINHTTP_CALLBACK_STATUS_SENDING_REQUEST: // // This is a notification, not a completion. This notifiation happens // during the Send Request operation. // fDerefForwardingHandler = FALSE; fAnotherCompletionExpected = TRUE; break; case WINHTTP_CALLBACK_STATUS_REQUEST_SENT: // // Need to ignore this event. We get it as a side-effect of registering // for WINHTTP_CALLBACK_STATUS_SENDING_REQUEST (which we actually need). // hr = S_OK; fDerefForwardingHandler = FALSE; fAnotherCompletionExpected = TRUE; break; case WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING: if (m_RequestStatus != FORWARDER_DONE) { hr = ERROR_CONNECTION_ABORTED; fClientError = m_fHandleClosedDueToClient; } else { fDerefForwardingHandler = m_fClientDisconnected && !m_fWebSocketUpgrade; } m_hRequest = NULL; m_pWebSocket = NULL; fAnotherCompletionExpected = FALSE; break; case WINHTTP_CALLBACK_STATUS_CONNECTION_CLOSED: hr = ERROR_CONNECTION_ABORTED; break; default: // // E_UNEXPECTED is rarely used, if seen means that this condition may been occurred. // DBG_ASSERT(FALSE); hr = E_UNEXPECTED; if (sm_pTraceLog != NULL) { WriteRefTraceLogEx(sm_pTraceLog, m_cRefs, this, "FORWARDING_HANDLER::OnWinHttpCompletionInternal Unexpected WinHTTP Status", reinterpret_cast<PVOID>(static_cast<DWORD_PTR>(dwInternetStatus)), NULL); } break; } // // Handle failure code for switch statement above. // if (FAILED(hr)) { goto Failure; } // // WinHTTP completion handled successfully. // goto Finished; Failure: m_RequestStatus = FORWARDER_DONE; if (!m_fErrorHandled) { m_fErrorHandled = TRUE; if (hr == HRESULT_FROM_WIN32(ERROR_WINHTTP_INVALID_SERVER_RESPONSE)) { m_RequestStatus = FORWARDER_RESET_CONNECTION; goto Finished; } pResponse->DisableKernelCache(); pResponse->GetRawHttpResponse()->EntityChunkCount = 0; fClientError = !m_pW3Context->GetConnection()->IsConnected(); if (fClientError) { if (!m_fResponseHeadersReceivedAndSet) { pResponse->SetStatus(400, "Bad Request", 0, HRESULT_FROM_WIN32(WSAECONNRESET)); } else { // // Response headers from origin server were // already received and set for the current response. // Honor the response status. // } } else { STACK_STRU(strDescription, 128); pResponse->SetStatus(502, "Bad Gateway", 3, hr); if (hr > HRESULT_FROM_WIN32(WINHTTP_ERROR_BASE) && hr <= HRESULT_FROM_WIN32(WINHTTP_ERROR_LAST)) { #pragma prefast (suppress : __WARNING_FUNCTION_NEEDS_REVIEW, "Function and parameters reviewed.") FormatMessage( FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_HMODULE, g_hWinHttpModule, HRESULT_CODE(hr), 0, strDescription.QueryStr(), strDescription.QuerySizeCCH(), NULL); } else { LoadString(g_hModule, IDS_SERVER_ERROR, strDescription.QueryStr(), strDescription.QuerySizeCCH()); } strDescription.SyncWithBuffer(); if (strDescription.QueryCCH() != 0) { pResponse->SetErrorDescription( strDescription.QueryStr(), strDescription.QueryCCH(), FALSE); } } } Finished: if (fIsCompletionThread) { DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == this); TlsSetValue(g_dwTlsIndex, NULL); ReleaseSRWLockShared(&m_RequestLock); DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == NULL); } if (fDerefForwardingHandler) { DereferenceForwardingHandler(); } // // Do not use this object after dereferencing it, it may be gone. // // // Completion may had been already posted to IIS if an async // operation was started in this method (either WinHTTP or IIS e.g. ReadyEntityBody) // If fAnotherCompletionExpected is false, this method must post the completion. // if (m_RequestStatus == FORWARDER_DONE) { if (m_hRequest != NULL) { WinHttpSetStatusCallback(m_hRequest, FORWARDING_HANDLER::OnWinHttpCompletion, WINHTTP_CALLBACK_FLAG_HANDLES, NULL); if(WinHttpCloseHandle(m_hRequest)) { m_hRequest = NULL; } } if (m_pWebSocket != NULL) { m_pWebSocket->TerminateRequest(); m_pWebSocket = NULL; } if(fEndRequest) { // only postCompletion after WINHTTP_CALLBACK_STATUS_HANDLE_CLOSING // so that no further WinHttp callback will be called // in case of websocket, m_hRequest has already been closed after upgrade // websocket will handle completion m_fFinishRequest = TRUE; m_pW3Context->PostCompletion(0); } } else if (!fAnotherCompletionExpected) { // // Since we use TLS to guard WinHttp operation, call PostCompletion instead of // IndicateCompletion to allow cleaning up the TLS before thread reuse. // m_pW3Context->PostCompletion(0); // // No code executed after posting the completion. // } } HRESULT FORWARDING_HANDLER::OnWinHttpCompletionSendRequestOrWriteComplete( HINTERNET hRequest, DWORD, __out bool * pfClientError, __out bool * pfAnotherCompletionExpected ) { HRESULT hr = S_OK; IHttpRequest * pRequest = m_pW3Context->GetRequest(); // // completion for sending the initial request or request entity to // winhttp, get more request entity if available, else start receiving // the response // if (m_BytesToReceive > 0) { if (m_pEntityBuffer == NULL) { m_pEntityBuffer = GetNewResponseBuffer( ENTITY_BUFFER_SIZE); if (m_pEntityBuffer == NULL) { hr = E_OUTOFMEMORY; goto Finished; } } if (sm_pTraceLog != NULL) { WriteRefTraceLogEx(sm_pTraceLog, m_cRefs, this, "Calling ReadEntityBody", NULL, NULL); } hr = pRequest->ReadEntityBody( m_pEntityBuffer + 6, min(m_BytesToReceive, BUFFER_SIZE), TRUE, // fAsync NULL, // pcbBytesReceived NULL); // pfCompletionPending if (hr == HRESULT_FROM_WIN32(ERROR_HANDLE_EOF)) { DBG_ASSERT(m_BytesToReceive == 0 || m_BytesToReceive == INFINITE); // // ERROR_HANDLE_EOF is not an error. // hr = S_OK; if (m_BytesToReceive == INFINITE) { m_BytesToReceive = 0; m_cchLastSend = 5; // // WinHttpWriteData can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpWriteData(m_hRequest, "0\r\n\r\n", 5, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); DereferenceForwardingHandler(); goto Finished; } *pfAnotherCompletionExpected = TRUE; goto Finished; } } else if (FAILED(hr)) { *pfClientError = TRUE; goto Finished; } else { // // ReadEntityBody will post a completion to IIS. // *pfAnotherCompletionExpected = TRUE; goto Finished; } } m_RequestStatus = FORWARDER_RECEIVING_RESPONSE; // // WinHttpReceiveResponse can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpReceiveResponse(hRequest, NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); DereferenceForwardingHandler(); goto Finished; } *pfAnotherCompletionExpected = TRUE; Finished: return hr; } HRESULT FORWARDING_HANDLER::OnWinHttpCompletionStatusHeadersAvailable( HINTERNET hRequest, __out bool * pfAnotherCompletionExpected ) { HRESULT hr = S_OK; STACK_BUFFER(bufHeaderBuffer, 2048); STACK_STRA(strHeaders, 2048); DWORD dwHeaderSize = bufHeaderBuffer.QuerySize(); UNREFERENCED_PARAMETER(pfAnotherCompletionExpected); // // Headers are available, read the status line and headers and pass // them on to the client // // WinHttpQueryHeaders operates synchronously, // no need for taking reference. // dwHeaderSize = bufHeaderBuffer.QuerySize(); if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, bufHeaderBuffer.QueryPtr(), &dwHeaderSize, WINHTTP_NO_HEADER_INDEX)) { if (!bufHeaderBuffer.Resize(dwHeaderSize)) { hr = E_OUTOFMEMORY; goto Finished; } // // WinHttpQueryHeaders operates synchronously, // no need for taking reference. // if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS_CRLF, WINHTTP_HEADER_NAME_BY_INDEX, bufHeaderBuffer.QueryPtr(), &dwHeaderSize, WINHTTP_NO_HEADER_INDEX)) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Finished; } } if (FAILED(hr = strHeaders.CopyW( reinterpret_cast<PWSTR>(bufHeaderBuffer.QueryPtr())))) { goto Finished; } // Issue: The reason we add trailing \r\n is to eliminate issues that have been observed // in some configurations where status and headers would not have final \r\n nor \r\n\r\n // (last header was null terminated).That caused crash within header parsing code that expected valid // format. Parsing code was fized to return ERROR_INVALID_PARAMETER, but we still should make // Example of a status+header string that was causing problems (note the missing \r\n at the end) // HTTP/1.1 302 Moved Permanently\r\n....\r\nLocation:http://site\0 // if (!strHeaders.IsEmpty() && strHeaders.QueryStr()[strHeaders.QueryCCH() - 1] != '\n') { hr = strHeaders.Append("\r\n"); if (FAILED(hr)) { goto Finished; } } if (FAILED(hr = SetStatusAndHeaders( strHeaders.QueryStr(), strHeaders.QueryCCH()))) { goto Finished; } FreeResponseBuffers(); // // If the request was websocket, and response was 101, // trigger a flush, so that IIS's websocket module // can get a chance to initialize and complete the handshake. // if (m_fWebSocketEnabled) { m_RequestStatus = FORWARDER_RECEIVED_WEBSOCKET_RESPONSE; hr = m_pW3Context->GetResponse()->Flush( TRUE, TRUE, NULL, NULL); if (FAILED(hr)) { *pfAnotherCompletionExpected = FALSE; } else { *pfAnotherCompletionExpected = TRUE; } } Finished: return hr; } HRESULT FORWARDING_HANDLER::OnWinHttpCompletionStatusDataAvailable( HINTERNET hRequest, DWORD dwBytes, __out bool * pfAnotherCompletionExpected ) { HRESULT hr = S_OK; // // Response data is available from winhttp, read it // if (dwBytes == 0) { if (m_cContentLength != 0) { hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_INVALID_SERVER_RESPONSE); goto Finished; } m_RequestStatus = FORWARDER_DONE; goto Finished; } m_BytesToSend = dwBytes; if (m_cContentLength != 0) { m_cContentLength -= dwBytes; } m_pEntityBuffer = GetNewResponseBuffer( min(m_BytesToSend, BUFFER_SIZE)); if (m_pEntityBuffer == NULL) { hr = E_OUTOFMEMORY; goto Finished; } // // WinHttpReadData can operate asynchronously. // // Take reference so that object does not go away as a result of // async completion. // ReferenceForwardingHandler(); if (!WinHttpReadData(hRequest, m_pEntityBuffer, min(m_BytesToSend, BUFFER_SIZE), NULL)) { hr = HRESULT_FROM_WIN32(GetLastError()); DereferenceForwardingHandler(); goto Finished; } *pfAnotherCompletionExpected = TRUE; Finished: return hr; } HRESULT FORWARDING_HANDLER::OnWinHttpCompletionStatusReadComplete( __in IHttpResponse * pResponse, DWORD dwStatusInformationLength, __out bool * pfAnotherCompletionExpected ) { HRESULT hr = S_OK; // // Response data has been read from winhttp, send it to the client // m_BytesToSend -= dwStatusInformationLength; if (m_cMinBufferLimit >= BUFFER_SIZE / 2) { if (m_cContentLength != 0) { m_cContentLength -= dwStatusInformationLength; } // // If we were not using WinHttpQueryDataAvailable and winhttp // did not fill our buffer, we must have reached the end of the // response // if (dwStatusInformationLength == 0 || m_BytesToSend != 0) { if (m_cContentLength != 0) { hr = HRESULT_FROM_WIN32(ERROR_WINHTTP_INVALID_SERVER_RESPONSE); goto Finished; } m_RequestStatus = FORWARDER_DONE; } } else { DBG_ASSERT(dwStatusInformationLength != 0); } if (dwStatusInformationLength == 0) { goto Finished; } else { m_cBytesBuffered += dwStatusInformationLength; HTTP_DATA_CHUNK Chunk; Chunk.DataChunkType = HttpDataChunkFromMemory; Chunk.FromMemory.pBuffer = m_pEntityBuffer; Chunk.FromMemory.BufferLength = dwStatusInformationLength; if (FAILED(hr = pResponse->WriteEntityChunkByReference(&Chunk))) { goto Finished; } } if (m_cBytesBuffered >= m_cMinBufferLimit) { // // Always post a completion to resume the WinHTTP data pump. // hr = pResponse->Flush(TRUE, // fAsync TRUE, // fMoreData NULL); // pcbSent if (FAILED(hr)) { goto Finished; } *pfAnotherCompletionExpected = TRUE; } else { *pfAnotherCompletionExpected = FALSE; } Finished: return hr; } // static HRESULT FORWARDING_HANDLER::StaticInitialize( BOOL fEnableReferenceCountTracing ) /*++ Routine Description: Global initialization routine for FORWARDING_HANDLERs Arguments: fEnableReferenceCountTracing - True if ref count tracing should be use. Return Value: HRESULT --*/ { HRESULT hr = S_OK; sm_pAlloc = new ALLOC_CACHE_HANDLER; if (sm_pAlloc == NULL) { hr = E_OUTOFMEMORY; goto Failure; } hr = sm_pAlloc->Initialize(sizeof(FORWARDING_HANDLER), 64); // nThreshold if (FAILED(hr)) { goto Failure; } // // Open the session handle, specify random user-agent that will be // overwritten by the client // sm_hSession = WinHttpOpen(L"", WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, WINHTTP_FLAG_ASYNC); if (sm_hSession == NULL) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Failure; } // // Don't set non-blocking callbacks WINHTTP_OPTION_ASSURED_NON_BLOCKING_CALLBACKS, // as we will call WinHttpQueryDataAvailable to get response on the same thread // that we received callback from Winhttp on completing sending/forwarding the request // // // Setup the callback function // if (WinHttpSetStatusCallback(sm_hSession, FORWARDING_HANDLER::OnWinHttpCompletion, (WINHTTP_CALLBACK_FLAG_ALL_COMPLETIONS | WINHTTP_CALLBACK_STATUS_SENDING_REQUEST), NULL) == WINHTTP_INVALID_STATUS_CALLBACK) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Failure; } // // Make sure we see the redirects (rather than winhttp doing it // automatically) // DWORD dwRedirectOption = WINHTTP_OPTION_REDIRECT_POLICY_NEVER; if (!WinHttpSetOption(sm_hSession, WINHTTP_OPTION_REDIRECT_POLICY, &dwRedirectOption, sizeof(dwRedirectOption))) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Failure; } // Initialize Application Manager APPLICATION_MANAGER *pApplicationManager = APPLICATION_MANAGER::GetInstance(); if (pApplicationManager == NULL) { hr = E_OUTOFMEMORY; goto Failure; } hr = pApplicationManager->Initialize(); if (FAILED(hr)) { goto Failure; } // Initialize PROTOCOL_CONFIG sm_ProtocolConfig.Initialize(); if (FAILED(hr = sm_strErrorFormat.Resize(256))) { goto Failure; } if (LoadString(g_hModule, IDS_INVALID_PROPERTY, sm_strErrorFormat.QueryStr(), sm_strErrorFormat.QuerySizeCCH()) == 0) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Failure; } sm_strErrorFormat.SyncWithBuffer(); // If RegisterEventSource failed, we cannot do any thing about it // No need to check whether the returned handle is valid if (g_pHttpServer->IsCommandLineLaunch()) { sm_hEventLog = RegisterEventSource(NULL, ASPNETCORE_IISEXPRESS_EVENT_PROVIDER); } else { sm_hEventLog = RegisterEventSource(NULL, ASPNETCORE_EVENT_PROVIDER); } g_dwTlsIndex = TlsAlloc(); if (g_dwTlsIndex == TLS_OUT_OF_INDEXES) { hr = HRESULT_FROM_WIN32(GetLastError()); goto Failure; } if (fEnableReferenceCountTracing) { sm_pTraceLog = CreateRefTraceLog(10000, 0); } return S_OK; Failure: StaticTerminate(); return hr; } // static VOID FORWARDING_HANDLER::StaticTerminate( VOID ) /*++ Routine Description: Global termination routine for FORWARDING_HANDLERs Arguments: None Return Value: None --*/ { // // Delete all the statics // APPLICATION_MANAGER::Cleanup(); // // wait for all server processes to go away // for a max of 10 seconds. // DWORD tickCount = GetTickCount(); while (g_dwActiveServerProcesses > 0) { if ((GetTickCount() - tickCount) > 10000) { break; } Sleep(250); } if (sm_hSession != NULL) { WinHttpCloseHandle(sm_hSession); sm_hSession = NULL; } if (sm_hEventLog != NULL) { DeregisterEventSource(sm_hEventLog); sm_hEventLog = NULL; } if (g_dwTlsIndex != TLS_OUT_OF_INDEXES) { DBG_REQUIRE(TlsFree(g_dwTlsIndex)); g_dwTlsIndex = TLS_OUT_OF_INDEXES; } sm_strErrorFormat.Reset(); if (sm_pTraceLog != NULL) { DestroyRefTraceLog(sm_pTraceLog); sm_pTraceLog = NULL; } if (sm_pAlloc != NULL) { delete sm_pAlloc; sm_pAlloc = NULL; } } VOID CopyMultiSzToOutput( IGlobalRSCAQueryProvider * pProvider, PCWSTR pszList, DWORD * pcbData ) { PBYTE pvData; DWORD cbData = 0; PCWSTR pszListCopy = pszList; while (*pszList != L'\0') { cbData += (static_cast<DWORD>(wcslen(pszList)) + 1) * sizeof(WCHAR); pszList += wcslen(pszList) + 1; } cbData += sizeof(WCHAR); if (FAILED(pProvider->GetOutputBuffer(cbData, &pvData))) { return; } memcpy(pvData, pszListCopy, cbData); *pcbData = cbData; } struct AFFINITY_LOOKUP_CONTEXT { DWORD timeout; PCWSTR pszServer; BUFFER * pHostNames; DWORD cbData; }; struct CACHE_CONTEXT { PCSTR pszHostName; IGlobalRSCAQueryProvider *pProvider; __field_bcount_part(cbBuffer, cbData) PBYTE pvData; DWORD cbData; DWORD cbBuffer; }; VOID FORWARDING_HANDLER::TerminateRequest( bool fClientInitiated ) { bool fAcquiredLock = FALSE; if (TlsGetValue(g_dwTlsIndex) != this) { DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == NULL); AcquireSRWLockShared(&m_RequestLock); TlsSetValue(g_dwTlsIndex, this); DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == this); fAcquiredLock = TRUE; } if (m_hRequest != NULL) { WinHttpSetStatusCallback(m_hRequest, FORWARDING_HANDLER::OnWinHttpCompletion, WINHTTP_CALLBACK_FLAG_HANDLES, NULL); if (WinHttpCloseHandle(m_hRequest)) { m_hRequest = NULL; } m_fHandleClosedDueToClient = fClientInitiated; } // // If the request is a websocket request, initiate cleanup. // if (m_pWebSocket != NULL) { m_pWebSocket->TerminateRequest(); } if (fAcquiredLock) { DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == this); TlsSetValue(g_dwTlsIndex, NULL); ReleaseSRWLockShared(&m_RequestLock); DBG_ASSERT(TlsGetValue(g_dwTlsIndex) == NULL); } } BYTE * FORWARDING_HANDLER::GetNewResponseBuffer( DWORD dwBufferSize ) { DWORD dwNeededSize = (m_cEntityBuffers + 1) * sizeof(BYTE *); if (dwNeededSize > m_buffEntityBuffers.QuerySize() && !m_buffEntityBuffers.Resize( max(dwNeededSize, m_buffEntityBuffers.QuerySize() * 2))) { return NULL; } BYTE *pBuffer = (BYTE *)HeapAlloc(GetProcessHeap(), 0, // dwFlags dwBufferSize); if (pBuffer == NULL) { return NULL; } m_buffEntityBuffers.QueryPtr()[m_cEntityBuffers] = pBuffer; m_cEntityBuffers++; return pBuffer; } VOID FORWARDING_HANDLER::FreeResponseBuffers() { BYTE **pBuffers = m_buffEntityBuffers.QueryPtr(); for (DWORD i = 0; i<m_cEntityBuffers; i++) { HeapFree(GetProcessHeap(), 0, // dwFlags pBuffers[i]); } m_cEntityBuffers = 0; m_pEntityBuffer = NULL; m_cBytesBuffered = 0; }
27.439567
126
0.571091
[ "object" ]
5f4f4414965471a1c939131acfb1551dffbf92b5
601
cpp
C++
aws-cpp-sdk-customer-profiles/source/model/GetIdentityResolutionJobRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-customer-profiles/source/model/GetIdentityResolutionJobRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-customer-profiles/source/model/GetIdentityResolutionJobRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/customer-profiles/model/GetIdentityResolutionJobRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::CustomerProfiles::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; GetIdentityResolutionJobRequest::GetIdentityResolutionJobRequest() : m_domainNameHasBeenSet(false), m_jobIdHasBeenSet(false) { } Aws::String GetIdentityResolutionJobRequest::SerializePayload() const { return {}; }
20.724138
72
0.767055
[ "model" ]
5f4fa964a75060c08d4aabf74dde3e33cffa238f
32,788
cpp
C++
Engine/Script/Bindings/BSFBind.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
16
2018-12-22T02:09:05.000Z
2022-03-09T20:38:59.000Z
Engine/Script/Bindings/BSFBind.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
46
2018-04-02T11:06:01.000Z
2019-12-14T11:16:04.000Z
Engine/Script/Bindings/BSFBind.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
14
2018-04-09T02:26:15.000Z
2021-09-11T03:12:15.000Z
// ------------------------------------ // #include "BSFBind.h" #include "Define.h" #include "Logger.h" // For Float type conversions #include "Common/Types.h" #include "Engine.h" #include "Exceptions.h" #include "Rendering/Graphics.h" #include "BsApplication.h" #include "bsfCore/Material/BsMaterial.h" #include "bsfCore/Material/BsShader.h" #include "bsfCore/Scene/BsSceneObject.h" #include "bsfEngine/Resources/BsBuiltinResources.h" #include "bsfUtility/Math/BsMatrix4.h" #include "bsfUtility/Math/BsRay.h" #include <type_traits> using namespace Leviathan; // ------------------------------------ // #define CHECK_SELF \ if(!self) \ throw InvalidState("Invalid bsf object handle"); // Proxies etc. // ------------------------------------ // void ColorProxy(void* memory, float r, float g, float b, float a) { new(memory) bs::Color(r, g, b, a); } void ColorVector4Proxy(void* memory, const bs::Vector4& values) { new(memory) bs::Color(values.x, values.y, values.z, values.w); } void MatrixProxy(void* memory, const bs::Vector3& position, const bs::Vector3& scale, const bs::Quaternion& orientation) { new(memory) bs::Matrix4; static_cast<bs::Matrix4*>(memory)->setTRS(position, orientation, scale); } void MatrixProxyUninitialized(void* memory) { new(memory) bs::Matrix4; } void DegreeProxy(void* memory, float degree) { new(memory) bs::Degree(degree); } void DegreeProxyRadian(void* memory, const bs::Radian& radian) { new(memory) bs::Degree(radian); } bs::Radian DegreeToRadianCast(bs::Degree* self) { return *self; } void RadianProxy(void* memory, float radian) { new(memory) bs::Radian(radian); } void RadianProxyDegree(void* memory, const bs::Degree& degree) { new(memory) bs::Radian(degree); } bs::Degree RadianToDegreeCast(bs::Radian* self) { return *self; } void QuaternionProxyValues(void* memory, float W, float X, float Y, float Z) { new(memory) bs::Quaternion(W, X, Y, Z); } void QuaternionProxyAroundAxis( void* memory, const bs::Radian& radian, const bs::Vector3& vector) { new(memory) bs::Quaternion(vector, radian); } void QuaternionProxyAroundAxisOtherWay( void* memory, const bs::Vector3& vector, const bs::Radian& radian) { new(memory) bs::Quaternion(vector, radian); } void Vector3Proxy(void* memory, float x, float y, float z) { new(memory) bs::Vector3(x, y, z); } void Vector4Proxy(void* memory, float x, float y, float z, float w) { new(memory) bs::Vector4(x, y, z, w); } void PlaneFromNormalProxy(void* memory, const bs::Vector3& normal, float f) { new(memory) bs::Plane(normal, f); } void RayProxy(void* memory, const bs::Vector3& origin, const bs::Vector3& direction) { new(memory) bs::Ray(origin, direction); } bool RayIntersectsPlaneProxy(const bs::Ray* self, const bs::Plane& plane, float& distance) { bool intersects; std::tie(intersects, distance) = self->intersects(plane); return intersects; } void SceneObjectSetParent( bs::HSceneObject& self, const bs::HSceneObject& parent, bool keepWorldTransform) { CHECK_SELF; self->setParent(parent, keepWorldTransform); } void SceneObjectRemoveFromParent(bs::HSceneObject& self) { CHECK_SELF; self->setParent(bs::HSceneObject(), false); } void SceneObjectSetPosition(bs::HSceneObject& self, const bs::Vector3& position) { CHECK_SELF; self->setPosition(position); } bs::Vector3 SceneObjectGetPosition(bs::HSceneObject& self) { CHECK_SELF; return self->getLocalTransform().getPosition(); } void SceneObjectSetRotation(bs::HSceneObject& self, const bs::Quaternion& orientation) { CHECK_SELF; self->setRotation(orientation); } void MaterialSetTextureProxy( bs::HMaterial& self, const std::string& name, const bs::HTexture& texture) { if(!self || self->isDestroyed()) { asGetActiveContext()->SetException("method called on invalid HMaterial instance"); return; } self->setTexture(name.c_str(), texture); } void MaterialSetVec44Proxy( bs::HMaterial& self, const std::string& name, const bs::Vector4& value) { if(!self || self->isDestroyed()) { asGetActiveContext()->SetException("method called on invalid HMaterial instance"); return; } self->setVec4(name.c_str(), value); } template<class T> void DefaultHandleConstructor(void* memory) { new(memory) T(); } template<class T> void HandleCopyConstructor(void* memory, const T& other) { new(memory) T(other); } template<class T> void HandleDestructor(void* memory) { ((T*)memory)->~T(); } template<class T> bool HandleHasValue(T& self) { return self.operator bool(); } template<class HandleT, class HeldT, bool HandleParam> bool ResourceHandleHasValue(HandleT& self) { return self.operator int bs::TResourceHandle<HeldT, HandleParam>::template Bool_struct<HeldT>::*() == 1; } template<class T> bool HandleIsNotDestroyed(T& self) { return !self.isDestroyed(); } template<class T> void ResetHandle(T& self) { self = nullptr; } // ------------------------------------ // // Utility helpers void ShaderFromNameFactory(void* memory, const std::string& name) { auto shader = Engine::Get()->GetGraphics()->LoadShaderByName(name); if(!shader) { asGetActiveContext()->SetException( "no shader could be loaded with the specified name"); return; } new(memory) bs::HShader(std::move(shader)); } void ShaderFromType(void* memory, bs::BuiltinShader type) { auto resource = bs::gBuiltinResources().getBuiltinShader(type); if(!resource) { asGetActiveContext()->SetException("invalid inbuilt shader"); return; } new(memory) bs::HShader(std::move(resource)); } void MaterialFromShaderFactory(void* memory, const bs::HShader& shader) { auto material = bs::Material::create(shader); if(!material) { asGetActiveContext()->SetException("failed to create a material from the shader"); return; } new(memory) bs::HMaterial(std::move(material)); } void TextureFromNameFactory(void* memory, const std::string& name) { auto texture = Engine::Get()->GetGraphics()->LoadTextureByName(name); if(!texture) { asGetActiveContext()->SetException( "no texture could be loaded with the specified name"); return; } new(memory) bs::HTexture(std::move(texture)); } // ------------------------------------ // // Start of the actual bind namespace Leviathan { template<class HandleT, class HeldT> bool RegisterBSFShandleType(const char* type, asIScriptEngine* engine) { if(engine->RegisterObjectType( type, sizeof(HandleT), asOBJ_VALUE | asGetTypeTraits<HandleT>()) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour(type, asBEHAVE_CONSTRUCT, "void f()", asFUNCTION(DefaultHandleConstructor<HandleT>), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour(type, asBEHAVE_CONSTRUCT, ("void f(" + std::string(type) + " &in other)").c_str(), asFUNCTION(HandleCopyConstructor<HandleT>), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour(type, asBEHAVE_DESTRUCT, "void f()", asFUNCTION(HandleDestructor<HandleT>), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod(type, (std::string(type) + "& opAssign(" + type + " &in other)").c_str(), asMETHODPR(HandleT, operator=,(const HandleT&), HandleT&), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod(type, "void reset()", asFUNCTION(ResetHandle<HandleT>), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if constexpr(std::is_base_of_v<bs::GameObjectHandleBase, HandleT>) { if(engine->RegisterObjectMethod(type, "bool valid() const", asFUNCTION(HandleIsNotDestroyed<HandleT>), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } } else { if constexpr(std::is_base_of_v<bs::TResourceHandleBase<true>, HandleT>) { if(engine->RegisterObjectMethod(type, "bool valid() const", asFUNCTION((ResourceHandleHasValue<HandleT, HeldT, true>)), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } else if constexpr(std::is_base_of_v<bs::TResourceHandleBase<false>, HandleT>) { if(engine->RegisterObjectMethod(type, "bool valid() const", asFUNCTION((ResourceHandleHasValue<HandleT, HeldT, false>)), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } } else { if(engine->RegisterObjectMethod(type, "bool valid() const", asFUNCTION(HandleHasValue<HandleT>), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } } } } return true; } // For float binding bool BindBSFTypeDefs(asIScriptEngine* engine) { if(engine->RegisterTypedef("Scene", "int32") < 0) { ANGELSCRIPT_REGISTERFAIL; } // if constexpr(std::is_same_v<float, float>) { // if(engine->RegisterTypedef("float", "float") < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // } else if constexpr(std::is_same_v<float, double>) { // if(engine->RegisterTypedef("float", "double") < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // } else { // // Would really love this to be a static assert but apparently that doesn't work // LOG_FATAL("Unknown float used while trying to bind as stuff"); // } return true; } bool BindVector3(asIScriptEngine* engine) { if(engine->RegisterObjectType("Vector3", sizeof(bs::Vector3), asOBJ_VALUE | asGetTypeTraits<bs::Vector3>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Vector3", asBEHAVE_CONSTRUCT, "void f(float x, float y, float z)", asFUNCTION(Vector3Proxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Vector3", "float x", asOFFSET(bs::Vector3, x)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Vector3", "float y", asOFFSET(bs::Vector3, y)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Vector3", "float z", asOFFSET(bs::Vector3, z)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->SetDefaultNamespace("bs::Vector3") < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterGlobalProperty( "const bs::Vector3 UNIT_X", const_cast<bs::Vector3*>(&bs::Vector3::UNIT_X)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterGlobalProperty( "const bs::Vector3 UNIT_Y", const_cast<bs::Vector3*>(&bs::Vector3::UNIT_Y)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterGlobalProperty( "const bs::Vector3 UNIT_Z", const_cast<bs::Vector3*>(&bs::Vector3::UNIT_Z)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->SetDefaultNamespace("bs") < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } bool BindVector4(asIScriptEngine* engine) { if(engine->RegisterObjectType("Vector4", sizeof(bs::Vector4), asOBJ_VALUE | asGetTypeTraits<bs::Vector4>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Vector4", asBEHAVE_CONSTRUCT, "void f(float x, float y, float z, float w)", asFUNCTION(Vector4Proxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Vector4", "float x", asOFFSET(bs::Vector4, x)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Vector4", "float y", asOFFSET(bs::Vector4, y)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Vector4", "float z", asOFFSET(bs::Vector4, z)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Vector4", "float w", asOFFSET(bs::Vector4, w)) < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } bool BindColour(asIScriptEngine* engine) { if(engine->RegisterObjectType("Color", sizeof(bs::Color), asOBJ_VALUE | asGetTypeTraits<bs::Color>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Color", asBEHAVE_CONSTRUCT, "void f(float r, float g, float b, float a = 1.0)", asFUNCTION(ColorProxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Color", asBEHAVE_CONSTRUCT, "void f(const Vector4 &in values)", asFUNCTION(ColorVector4Proxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Color", "float r", asOFFSET(bs::Color, r)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Color", "float g", asOFFSET(bs::Color, g)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Color", "float b", asOFFSET(bs::Color, b)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Color", "float a", asOFFSET(bs::Color, a)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Color", "void getHSB(float &out hue, float &out saturation, float &out brightness) " "const", asMETHOD(bs::Color, getHSB), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->SetDefaultNamespace("bs::Color") < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterGlobalFunction( "bs::Color fromHSB(float hue, float saturation, float brightness)", asFUNCTION(bs::Color::fromHSB), asCALL_CDECL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->SetDefaultNamespace("bs") < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } bool BindMatrix4(asIScriptEngine* engine) { if(engine->RegisterObjectType("Matrix4", sizeof(bs::Matrix4), asOBJ_VALUE | asGetTypeTraits<bs::Matrix4>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Matrix4", asBEHAVE_CONSTRUCT, "void f(const Vector3 &in trans, const Vector3 &in scale = bs::Vector3(1, 1, " "1), " "const Quaternion &in orientation = bs::Quaternion::IDENTITY)", asFUNCTION(MatrixProxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Matrix4", "void setTRS(const Vector3 &in trans, const Vector3 &in scale = " "bs::Vector3(1, 1, 1), const Quaternion &in orientation = " "bs::Quaternion::IDENTITY)", asMETHOD(bs::Matrix4, setTRS), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Matrix4", "Vector3 getTranslation() const", asMETHODPR(bs::Matrix4, getTranslation, () const, bs::Vector3), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Matrix4", "void decomposition(Vector3 &out position, Quaternion &out rotation, Vector3 " "&out " "scale) const", asMETHOD(bs::Matrix4, decomposition), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } // if(engine->RegisterObjectMethod("Matrix4", "Quaternion extractQuaternion() const", // asMETHOD(bs::Matrix4, get), asCALL_THISCALL) < 0) { // ANGELSCRIPT_REGISTERFAIL; // } if(engine->SetDefaultNamespace("bs::Matrix4") < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterGlobalProperty("const bs::Matrix4 IDENTITY", const_cast<bs::Matrix4*>(&bs::Matrix4::IDENTITY)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->SetDefaultNamespace("bs") < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } bool BindAnglesAndQuaternion(asIScriptEngine* engine) { if(engine->RegisterObjectType("Radian", sizeof(bs::Radian), asOBJ_VALUE | asGetTypeTraits<bs::Radian>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectType("Degree", sizeof(bs::Degree), asOBJ_VALUE | asGetTypeTraits<bs::Degree>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectType("Quaternion", sizeof(bs::Quaternion), asOBJ_VALUE | asGetTypeTraits<bs::Quaternion>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Quaternion", asBEHAVE_CONSTRUCT, "void f(float w, float x, float y, float z)", asFUNCTION(QuaternionProxyValues), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Quaternion", "Vector3 xAxis() const", asMETHOD(bs::Quaternion, xAxis), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Quaternion", "Vector3 yAxis() const", asMETHOD(bs::Quaternion, yAxis), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Quaternion", "Vector3 zAxis() const", asMETHOD(bs::Quaternion, zAxis), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Quaternion", "Quaternion inverse() const", asMETHOD(bs::Quaternion, inverse), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Quaternion", "Vector3 opMul(const Vector3 &in vec) const", asMETHOD(bs::Quaternion, rotate), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Quaternion", "Vector3 rotate(const Vector3 &in vec) const", asMETHOD(bs::Quaternion, rotate), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Quaternion", "Quaternion opMul(const Quaternion &in vec) const", asMETHODPR(bs::Quaternion, operator*,(const bs::Quaternion&) const, bs::Quaternion), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Quaternion", "Quaternion& opAssign(const Quaternion &in quat)", asMETHODPR(bs::Quaternion, operator=,(const bs::Quaternion&), bs::Quaternion&), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Quaternion", "float x", asOFFSET(bs::Quaternion, x)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Quaternion", "float y", asOFFSET(bs::Quaternion, y)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Quaternion", "float z", asOFFSET(bs::Quaternion, z)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Quaternion", "float w", asOFFSET(bs::Quaternion, w)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->SetDefaultNamespace("bs::Quaternion") < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterGlobalProperty("const bs::Quaternion IDENTITY", const_cast<bs::Quaternion*>(&bs::Quaternion::IDENTITY)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->SetDefaultNamespace("bs") < 0) { ANGELSCRIPT_REGISTERFAIL; } // ------------------------------------ // if(engine->RegisterObjectBehaviour("Radian", asBEHAVE_CONSTRUCT, "void f(float radians)", asFUNCTION(RadianProxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Radian", asBEHAVE_CONSTRUCT, "void f(const Degree &in degree)", asFUNCTION(RadianProxyDegree), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Degree", asBEHAVE_CONSTRUCT, "void f(float degrees)", asFUNCTION(DegreeProxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Degree", asBEHAVE_CONSTRUCT, "void f(const Radian &in radian)", asFUNCTION(DegreeProxyRadian), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Radian", "Degree opImplConv() const", asFUNCTION(RadianToDegreeCast), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Radian", "float valueDegrees() const", asMETHOD(bs::Radian, valueDegrees), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Radian", "float valueRadians() const", asMETHOD(bs::Radian, valueRadians), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Radian", "float valueAngleUnits() const", asMETHOD(bs::Radian, valueRadians), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Degree", "Radian opImplConv() const", asFUNCTION(DegreeToRadianCast), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Degree", "float valueDegrees() const", asMETHOD(bs::Degree, valueDegrees), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Degree", "float valueRadians() const", asMETHOD(bs::Degree, valueRadians), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Degree", "float valueAngleUnits() const", asMETHOD(bs::Degree, valueDegrees), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Quaternion", asBEHAVE_CONSTRUCT, "void f(const Radian &in radian, const Vector3 &in vector)", asFUNCTION(QuaternionProxyAroundAxis), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Quaternion", asBEHAVE_CONSTRUCT, "void f(const Vector3 &in vector, const Radian &in radian)", asFUNCTION(QuaternionProxyAroundAxisOtherWay), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } bool BindPlane(asIScriptEngine* engine) { if(engine->RegisterObjectType("Plane", sizeof(bs::Plane), asOBJ_VALUE | asGetTypeTraits<bs::Plane>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Plane", asBEHAVE_CONSTRUCT, "void f(const Vector3 &in normal, float f)", asFUNCTION(PlaneFromNormalProxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Plane", "Vector3 normal", asOFFSET(bs::Plane, normal)) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectProperty("Plane", "float dy", asOFFSET(bs::Plane, d)) < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } bool BindRay(asIScriptEngine* engine) { if(engine->RegisterObjectType("Ray", sizeof(bs::Ray), asOBJ_VALUE | asGetTypeTraits<bs::Ray>() | asOBJ_POD | asOBJ_APP_CLASS_ALLFLOATS) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("Ray", asBEHAVE_CONSTRUCT, "void f(const Vector3 &in origin, const Vector3 &in direction)", asFUNCTION(RayProxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Ray", "bool intersects(const Plane &in plane, float &out distance) const", asFUNCTION(RayIntersectsPlaneProxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("Ray", "Vector3 getPoint(float t) const", asMETHOD(bs::Ray, getPoint), asCALL_THISCALL) < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } // ------------------------------------ // // bool BindRenderQueue(asIScriptEngine* engine) // { // if(engine->RegisterObjectType("RenderQueue", 0, asOBJ_REF | asOBJ_NOCOUNT) < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // if(engine->SetDefaultNamespace("bs::RenderQueue") < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // if(engine->RegisterEnum("Modes") < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // if(engine->RegisterEnumValue("Modes", "V1_LEGACY", bs::RenderQueue::V1_LEGACY) < 0) // { // ANGELSCRIPT_REGISTERFAIL; // } // if(engine->RegisterEnumValue("Modes", "V1_FAST", bs::RenderQueue::V1_FAST) < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // if(engine->RegisterEnumValue("Modes", "FAST", bs::RenderQueue::FAST) < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // if(engine->SetDefaultNamespace("bs") < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // if(engine->RegisterObjectMethod("RenderQueue", // "void setRenderQueueMode(uint8 rqId, bs::RenderQueue::Modes newMode) const", // asMETHOD(bs::RenderQueue, setRenderQueueMode), asCALL_THISCALL) < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // return true; // } // ------------------------------------ // bool BindScene(asIScriptEngine* engine) { if(!RegisterBSFShandleType<bs::HSceneObject, bs::SceneObject>("HSceneObject", engine)) return false; if(engine->RegisterObjectMethod("HSceneObject", "void setParent(const HSceneObject &in parent, bool keepWorldTransform)", asFUNCTION(SceneObjectSetParent), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("HSceneObject", "void removeFromParent()", asFUNCTION(SceneObjectRemoveFromParent), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("HSceneObject", "void setPosition(const Vector3 &in pos)", asFUNCTION(SceneObjectSetPosition), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("HSceneObject", "Vector3 getPosition() const", asFUNCTION(SceneObjectGetPosition), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("HSceneObject", "void setOrientation(const Quaternion &in quaterion)", asFUNCTION(SceneObjectSetRotation), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("HSceneObject", "void setRotation(const Quaternion &in quaterion)", asFUNCTION(SceneObjectSetRotation), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } // ------------------------------------ // // HRenderable if(!RegisterBSFShandleType<bs::HRenderable, bs::Renderable>("HRenderable", engine)) return false; // ------------------------------------ // // Scene // if(engine->RegisterObjectMethod("SceneManager", "RenderQueue& getRenderQueue()", // asMETHOD(bs::SceneManager, getRenderQueue), asCALL_THISCALL) < 0) { // ANGELSCRIPT_REGISTERFAIL; // } return true; } bool BindTextures(asIScriptEngine* engine) { if(!RegisterBSFShandleType<bs::HTexture, bs::Texture>("HTexture", engine)) return false; if(engine->RegisterObjectBehaviour("HTexture", asBEHAVE_CONSTRUCT, "void f(const string &in name)", asFUNCTION(TextureFromNameFactory), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } bool BindMaterials(asIScriptEngine* engine) { if(engine->RegisterEnum("BuiltinShader") < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->SetDefaultNamespace("bs::BuiltinShader") < 0) { ANGELSCRIPT_REGISTERFAIL; } ANGELSCRIPT_REGISTER_ENUM_VALUE_WITH_NAME( "BuiltinShader", "Standard", bs::BuiltinShader::Standard); ANGELSCRIPT_REGISTER_ENUM_VALUE_WITH_NAME( "BuiltinShader", "Transparent", bs::BuiltinShader::Transparent); ANGELSCRIPT_REGISTER_ENUM_VALUE_WITH_NAME( "BuiltinShader", "ParticlesUnlit", bs::BuiltinShader::ParticlesUnlit); ANGELSCRIPT_REGISTER_ENUM_VALUE_WITH_NAME( "BuiltinShader", "ParticlesLit", bs::BuiltinShader::ParticlesLit); ANGELSCRIPT_REGISTER_ENUM_VALUE_WITH_NAME( "BuiltinShader", "ParticlesLitOpaque", bs::BuiltinShader::ParticlesLitOpaque); ANGELSCRIPT_REGISTER_ENUM_VALUE_WITH_NAME( "BuiltinShader", "Decal", bs::BuiltinShader::Decal); if(engine->SetDefaultNamespace("bs") < 0) { ANGELSCRIPT_REGISTERFAIL; } if(!RegisterBSFShandleType<bs::HShader, bs::Shader>("HShader", engine)) return false; if(engine->RegisterObjectBehaviour("HShader", asBEHAVE_CONSTRUCT, "void f(const string &in name)", asFUNCTION(ShaderFromNameFactory), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectBehaviour("HShader", asBEHAVE_CONSTRUCT, "void f(BuiltinShader type)", asFUNCTION(ShaderFromType), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(!RegisterBSFShandleType<bs::HMaterial, bs::Material>("HMaterial", engine)) return false; if(engine->RegisterObjectBehaviour("HMaterial", asBEHAVE_CONSTRUCT, "void f(const HShader &in shader)", asFUNCTION(MaterialFromShaderFactory), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("HMaterial", "void setTexture(const string &in name, const HTexture &in texture)", asFUNCTION(MaterialSetTextureProxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } if(engine->RegisterObjectMethod("HMaterial", "void setVec4(const string &in name, const Vector4 &in value)", asFUNCTION(MaterialSetVec44Proxy), asCALL_CDECL_OBJFIRST) < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; } bool BindMeshes(asIScriptEngine* engine) { // ------------------------------------ // // Mesh if(!RegisterBSFShandleType<bs::HMesh, bs::Mesh>("HMesh", engine)) return false; return true; } } // namespace Leviathan // ------------------------------------ // bool Leviathan::BindBSF(asIScriptEngine* engine) { // This doesn't need to be restored if we fail // if(engine->SetDefaultNamespace("bs") < 0) { ANGELSCRIPT_REGISTERFAIL; } if(!BindBSFTypeDefs(engine)) return false; if(!BindVector3(engine)) return false; if(!BindVector4(engine)) return false; if(!BindColour(engine)) return false; if(!BindAnglesAndQuaternion(engine)) return false; if(!BindMatrix4(engine)) return false; if(!BindPlane(engine)) return false; if(!BindRay(engine)) return false; if(!BindTextures(engine)) return false; if(!BindMaterials(engine)) return false; if(!BindMeshes(engine)) return false; // if(!BindRenderQueue(engine)) // return false; if(!BindScene(engine)) return false; // if(engine->RegisterObjectType("Root", 0, asOBJ_REF | asOBJ_NOCOUNT) < 0) { // ANGELSCRIPT_REGISTERFAIL; // } // ------------------ Global functions ------------------ // // if(engine->RegisterGlobalFunction( // "Root@ Getbs()", asFUNCTION(ScriptGetbs), asCALL_CDECL) < 0) { // ANGELSCRIPT_REGISTERFAIL; // } if(engine->SetDefaultNamespace("") < 0) { ANGELSCRIPT_REGISTERFAIL; } return true; }
30.080734
95
0.641973
[ "mesh", "object", "vector" ]
5f507da4832caa0d0ed400c3e6027ff551dc12c9
732
cpp
C++
lib/generator/overworld/populators/MegaTaigaPopulator.cpp
NetherGamesMC/noiselib
56fc48ea1367e1d08b228dfa580b513fbec8ca31
[ "MIT" ]
14
2021-08-16T18:58:30.000Z
2022-02-13T01:12:31.000Z
lib/generator/overworld/populators/MegaTaigaPopulator.cpp
NetherGamesMC/ext-vanillagenerator
56fc48ea1367e1d08b228dfa580b513fbec8ca31
[ "MIT" ]
2
2021-06-21T15:10:01.000Z
2021-07-19T01:48:00.000Z
lib/generator/overworld/populators/MegaTaigaPopulator.cpp
NetherGamesMC/ext-vanillagenerator
56fc48ea1367e1d08b228dfa580b513fbec8ca31
[ "MIT" ]
3
2021-06-21T02:10:39.000Z
2021-08-04T01:36:08.000Z
#include <lib/objects/constants/BiomeList.h> #include "MegaTaigaPopulator.h" void MegaTaigaPopulator::InitPopulators() { treeDecorator_.SetAmount(10); treeDecorator_.SetTrees({{52, redwoodTree}, {26, tallRedwoodTree}, {36, megaPineTree}, {3, megaSpruceTree}}); deadBushDecorator_.SetAmount(0); taigaBrownMushroomDecorator.SetAmount(3); taigaBrownMushroomDecorator.SetUseFixedHeightRange(); taigaBrownMushroomDecorator.SetDensity(0.25); taigaRedMushroomDecorator.SetAmount(3); taigaRedMushroomDecorator.SetDensity(0.125); } std::vector<uint_fast8_t> MegaTaigaPopulator::GetBiomes() const { return {MEGA_TAIGA, MEGA_TAIGA_HILLS}; } // TODO: StoneBoulderDecorator, for now, it is not really an important decorator.
38.526316
111
0.793716
[ "vector" ]
34ffee58596608c5f48725b3e40594f845cc8e34
404
cpp
C++
src/Object.cpp
beckylum0216/temp3dgame
0cf45aaa1fae6e4762840dcc9c5a044c9a37e4f7
[ "MIT" ]
1
2019-11-28T08:45:27.000Z
2019-11-28T08:45:27.000Z
src/Object.cpp
beckylum0216/temp3dgame
0cf45aaa1fae6e4762840dcc9c5a044c9a37e4f7
[ "MIT" ]
null
null
null
src/Object.cpp
beckylum0216/temp3dgame
0cf45aaa1fae6e4762840dcc9c5a044c9a37e4f7
[ "MIT" ]
null
null
null
// // Created by becky on 27/11/2019. // #include "Object.h" bool Object::Import(std::string path) { Assimp::Importer import; const aiScene *scene; scene = import.ReadFile(path, aiProcessPreset_TargetRealtime_Quality); if(!scene) { std::cout << import.GetErrorString() << std::endl; } std::cout << "type of: " << scene->mMeshes[0] << std::endl; return true; }
19.238095
74
0.616337
[ "object" ]
550cb9c34ea82faa07b1d21b25f1f386cde2a0e8
7,032
cc
C++
test/test_discrete_weights.cc
snsinfu/cxx-distr
0ceafc9b34064dafdc70b61da84f3c936a10b892
[ "BSL-1.0" ]
null
null
null
test/test_discrete_weights.cc
snsinfu/cxx-distr
0ceafc9b34064dafdc70b61da84f3c936a10b892
[ "BSL-1.0" ]
4
2020-12-27T17:10:03.000Z
2020-12-28T18:42:40.000Z
test/test_discrete_weights.cc
snsinfu/cxx-distr
0ceafc9b34064dafdc70b61da84f3c936a10b892
[ "BSL-1.0" ]
null
null
null
// Copyright snsinfu 2020. // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <algorithm> #include <initializer_list> #include <numeric> #include <sstream> #include <string> #include <catch.hpp> #include <discrete_distribution.hpp> TEST_CASE("discrete_weights - is default constructible") { cxx::discrete_weights weights; (void) weights; } TEST_CASE("discrete_weights - is constructible from weights") { // Vector std::vector<double> const values = {1.0, 2.0, 3.0}; cxx::discrete_weights weights_v{values}; (void) weights_v; // Initializer list cxx::discrete_weights weights_i = {1.0, 2.0, 3.0}; (void) weights_i; } TEST_CASE("discrete_weights - is equality comparable") { cxx::discrete_weights const weights_A = {1.2, 3.4, 5.6}; cxx::discrete_weights const weights_B = {1.2, 3.4, 5.6}; cxx::discrete_weights const weights_C = {5.6, 3.4, 1.2}; cxx::discrete_weights const weights_D = {1.2, 3.4, 5.6, 7.8}; cxx::discrete_weights const weights_E = {1.2, 3.4}; CHECK(weights_A == weights_A); CHECK(weights_A == weights_B); CHECK(weights_A != weights_C); CHECK(weights_A != weights_D); CHECK(weights_A != weights_E); } TEST_CASE("discrete_weights - is copyable") { cxx::discrete_weights origin = {1.0, 2.0, 3.0}; cxx::discrete_weights clone = origin; cxx::discrete_weights weights; weights = origin; CHECK(clone == origin); CHECK(weights == origin); } TEST_CASE("discrete_weights::size - is the number of events") { cxx::discrete_weights weights1 = {1.0}; cxx::discrete_weights weights2 = {1.0, 2.0}; cxx::discrete_weights weights3 = {1.0, 2.0, 3.0}; CHECK(weights1.size() == 1); CHECK(weights2.size() == 2); CHECK(weights3.size() == 3); } TEST_CASE("discrete_weights::data - points to the weight values") { cxx::discrete_weights const weights = {1.0, 2.0, 3.0}; double const* values = weights.data(); CHECK(values[0] == 1.0); CHECK(values[1] == 2.0); CHECK(values[2] == 3.0); } TEST_CASE("discrete_weights::begin/end - contains the weight values") { std::vector<double> const expected = {1.0, 2.0, 3.0}; cxx::discrete_weights const weights{expected}; std::vector<double> const values{weights.begin(), weights.end()}; CHECK(values == expected); } TEST_CASE("discrete_weights::operator[] - returns the weight of an event") { cxx::discrete_weights const weights = {1.2, 3.4, 5.6, 7.8}; CHECK(weights[0] == 1.2); CHECK(weights[1] == 3.4); CHECK(weights[2] == 5.6); CHECK(weights[3] == 7.8); } TEST_CASE("discrete_weights::sum - returns the sum of the weights") { cxx::discrete_weights const weights1 = {1.0}; CHECK(weights1.sum() == Approx(1.0)); cxx::discrete_weights const weights2 = {1.0, 2.0}; CHECK(weights2.sum() == Approx(1.0 + 2.0)); cxx::discrete_weights const weights3 = {1.0, 2.0, 3.0}; CHECK(weights3.sum() == Approx(1.0 + 2.0 + 3.0)); } TEST_CASE("discrete_weights::update - updates weight value") { cxx::discrete_weights weights = {1.2, 3.4, 5.6}; auto const* data = weights.data(); REQUIRE(data[0] == 1.2); REQUIRE(data[1] == 3.4); REQUIRE(data[2] == 5.6); REQUIRE(weights.sum() == Approx(1.2 + 3.4 + 5.6)); weights.update(1, 2.3); weights.update(2, 3.4); // Weight is actually updated in-place. CHECK(data[0] == 1.2); CHECK(data[1] == 2.3); CHECK(data[2] == 3.4); // Sum is also updated. CHECK(weights.sum() == Approx(1.2 + 2.3 + 3.4)); } TEST_CASE("discrete_weights::find - finds the correct event") { // 0.0 1.0 2.0 3.0 4.0 5.0 6.0 // |----|---------|--------------| // |___/|________/|_____________/ // 0 2 3 // Note: The element 1 has zero weight, so it won't be found. cxx::discrete_weights const weights = {1.0, 0.0, 2.0, 3.0}; CHECK(weights.find(0.0) == 0); CHECK(weights.find(0.5) == 0); CHECK(weights.find(1.0) == 2); CHECK(weights.find(1.5) == 2); CHECK(weights.find(2.0) == 2); CHECK(weights.find(2.5) == 2); CHECK(weights.find(3.0) == 3); CHECK(weights.find(3.5) == 3); CHECK(weights.find(4.0) == 3); CHECK(weights.find(4.5) == 3); CHECK(weights.find(5.0) == 3); CHECK(weights.find(5.5) == 3); } TEST_CASE("discrete_weights::find - returns edge event for overshoot probe") { // Logically the probe should be in the half-open interval [0, S) where S // is the sum of weights. But in practice numerical errors can result in // undershoot or overshoot. Here we check robustness against such errors. cxx::discrete_weights const weights = {1.0, 2.0, 3.0}; CHECK(weights.find(-0.1) == 0); CHECK(weights.find(-0.0) == 0); CHECK(weights.find(6.0) == 2); CHECK(weights.find(6.1) == 2); } TEST_CASE("discrete_weights::find - finds the correct event after weight update") { // 0.0 1.0 2.0 3.0 4.0 5.0 6.0 // |----|---------|--------------| // |___/|________/|_____________/ // 0 2 3 cxx::discrete_weights weights = {1.0, 0.0, 2.0, 3.0}; REQUIRE(weights.find(2.5) == 2); REQUIRE(weights.find(4.0) == 3); REQUIRE(weights.find(5.5) == 3); // 0.0 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 // |----|---------|---------|--------------| // |___/|________/|________/|_____________/ // 0 1 2 3 weights.update(1, 2.0); CHECK(weights.find(2.5) == 1); CHECK(weights.find(4.0) == 2); CHECK(weights.find(5.5) == 3); // 0.0 1.0 2.0 3.0 4.0 5.0 6.0 // |----|---------|--------------| // |___/|________/|_____________/ // 0 1 3 weights.update(2, 0.0); CHECK(weights.find(2.5) == 1); CHECK(weights.find(4.0) == 3); CHECK(weights.find(5.5) == 3); } TEST_CASE("discrete_weights - is deserializable") { std::string const source_form = "3 1.2 3.4 5.6"; std::vector<double> const expected_values = {1.2, 3.4, 5.6}; cxx::discrete_weights weights; std::istringstream ss{source_form}; ss >> weights; // We do not test for exact accuracy. CHECK(weights.size() == expected_values.size()); for (std::size_t i = 0; i < expected_values.size(); i++) { CHECK(weights[i] == Approx(expected_values[i])); } } TEST_CASE("discrete_weights - is serializable") { // Serialization result is indirectly tested via roundtrip because we // cannot be sure how parameters are serialized exactly. cxx::discrete_weights const origin = {1.2, 3.4, 5.6}; cxx::discrete_weights roundtrip; std::ostringstream os; os << origin; std::istringstream is{os.str()}; is >> roundtrip; // We do not test for exact accuracy. CHECK(roundtrip.size() == origin.size()); for (std::size_t i = 0; i < origin.size(); i++) { CHECK(roundtrip[i] == Approx(origin[i])); } }
27.794466
81
0.597696
[ "vector" ]
551039c1c37da082b40535d8e52d1b3cd0ef33c4
1,841
cc
C++
src/base/event.cc
likilli/MyServer
1d2fe6339e2c1afc4c3ded0ff0d8f9dc747d61fc
[ "MIT" ]
2
2021-12-10T06:44:02.000Z
2021-12-17T02:38:19.000Z
src/base/event.cc
likilli/MyServer
1d2fe6339e2c1afc4c3ded0ff0d8f9dc747d61fc
[ "MIT" ]
1
2021-12-21T16:28:49.000Z
2021-12-21T16:28:49.000Z
src/base/event.cc
likilli/MyServer
1d2fe6339e2c1afc4c3ded0ff0d8f9dc747d61fc
[ "MIT" ]
null
null
null
#include "event.h" // condition implementation #if defined(USE_SELECT) #include <sys/select.h> #include <vector> #include <algorithm> #include <cassert> fd_set rfds{}; fd_set wfds{}; int fd_max{-1}; std::vector<Event> events{}; static bool isLoopRunning{false}; /** * * @param socket * @param event_type * @param cb */ void EventAdd(int socket, int event_type, Callback cb) { assert(cb != nullptr); Event e{socket, event_type, std::move(cb)}; fd_max = socket >= fd_max ? socket + 1 : fd_max; auto iter = std::find(events.begin(), events.end(), e); if (iter == events.end()) events.emplace_back(e); } /** * * @param socket * @param event_type */ void EventDel(int socket, int event_type) { Event e{socket, event_type, nullptr}; auto iter = std::find(events.begin(), events.end(), e); if (iter != events.end()) events.erase(iter); } void EventLoopRun() { if (isLoopRunning) return; isLoopRunning = true; while (true) { struct timeval timeout{0, 1000}; int select_rc = select(fd_max, &rfds, &wfds, nullptr, &timeout); if (select_rc == -1) break; for (const auto &t : events) { if (FD_ISSET(t.socket, &rfds) || FD_ISSET(t.socket, &wfds)) { t.callback_(); } } FD_ZERO(&rfds); FD_ZERO(&wfds); for_each(events.begin(), events.end(), [&](const Event &t) { if (t.event_type == READ) FD_SET(t.socket, &rfds); else FD_SET(t.socket, &wfds); }); } } int GetEventQuantity() { return static_cast<int>(events.size()); } #elif defined(USE_EPOLL) /* * todo : implement */ #elif defined(USE_LIBEVENT) /* * todo: implement */ #endif
17.046296
72
0.560022
[ "vector" ]
55138e7f4cf22b35a63b06a8d175daffdf37e977
2,272
cpp
C++
USACOcontests/gold/2020.01/boards.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
14
2019-08-14T00:43:10.000Z
2021-12-16T05:43:31.000Z
USACOcontests/gold/2020.01/boards.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
null
null
null
USACOcontests/gold/2020.01/boards.cpp
eyangch/competitive-programming
59839efcec72cb792e61b7d316f83ad54f16a166
[ "MIT" ]
6
2020-12-30T03:30:17.000Z
2022-03-11T03:40:02.000Z
/* Solution: O(P logP) Sort springboards by x1 value (decreasing) and another one by x2 value (decreasing) Iterate through the x2 sorted array and add viable starting points from the x1 array to a strictly increasing map Query the starting point with greater or equal y value than the current x2 y2 point (dist = x-val + y-val + end dist) Subtract the current end point distance to start from that value = d2e Get minimum (d2e + x1 + x2) throughout all points. */ #include <bits/stdc++.h> using namespace std; struct board{ int x, y, x2, y2, i; }; struct si_map{ map<int, int> m; void insert(int id, int val){ auto it = m.lower_bound(id); if(it != m.end() && it -> second <= val){ return; } it = m.lower_bound(id); vector<int> rm; while(it != m.begin()){ it--; if(it -> second < val) break; rm.push_back(it->first); } for(int i : rm){ m.erase(i); } m[id] = val; } int lb(int id){ return m.lower_bound(id) -> second; } }; int N, P; board b[100000], b2[100000]; int di[100000]; si_map m; int32_t main(){ ios::sync_with_stdio(false); cin.tie(NULL); freopen("boards.in", "r", stdin); freopen("boards.out", "w", stdout); cin >> N >> P; for(int i = 0; i < P; i++){ cin >> b[i].x >> b[i].y >> b[i].x2 >> b[i].y2; b[i].i = i; } copy(b, b+P, b2); sort(b, b+P, [](board a, board b){ if(a.x2 == b.x2) return a.y2 > b.y2; return a.x2 > b.x2; }); sort(b2, b2+P, [](board a, board b){ if(a.x == b.x) return a.y > b.y; return a.x > b.x; }); m.insert(N, N+N); int ptrb = 0; int ans = 2e9; for(int i = 0; i < P; i++){ while(ptrb < P && b2[ptrb].x >= b[i].x2){ if(b2[ptrb].x == b[i].x2 && b2[ptrb].y < b[i].y2) break; int score = b2[ptrb].x + b2[ptrb].y + di[b2[ptrb].i]; m.insert(b2[ptrb].y, score); ptrb++; } di[b[i].i] = (N - b[i].x2) + (N - b[i].y2); int d2e = m.lb(b[i].y2); d2e -= b[i].x2 + b[i].y2; di[b[i].i] = d2e; ans = min(ans, d2e + b[i].x + b[i].y); } cout << ans << endl; }
27.047619
117
0.495599
[ "vector" ]
5517768324ce5ade04ede16ae4a34e21813efe51
2,294
cpp
C++
src/RequestHandler/CommandRequestHandler.cpp
eiji-shimizu/laravel_sample_queue
b5fd66a56c32f7893856e5ac344137e7d6f63648
[ "MIT" ]
null
null
null
src/RequestHandler/CommandRequestHandler.cpp
eiji-shimizu/laravel_sample_queue
b5fd66a56c32f7893856e5ac344137e7d6f63648
[ "MIT" ]
null
null
null
src/RequestHandler/CommandRequestHandler.cpp
eiji-shimizu/laravel_sample_queue
b5fd66a56c32f7893856e5ac344137e7d6f63648
[ "MIT" ]
null
null
null
#include "LSQ.h" #include "ServerApplication/Subsystems/LSQSubsystem.h" #include "ServerApplication/Subsystems/LSQQueue.h" #include "RequestHandler/CommandRequestHandler.h" #include "Poco/URI.h" #include <sstream> namespace LSQ { const std::string HELP = "help"; const std::string COUNT = "count"; const std::string LIST = "list"; const std::string NEXT = "next"; const std::string helpText() { std::ostringstream oss; oss << HELP << " : show help message." << std::endl << COUNT << " : show current queue elements size." << std::endl << LIST << " : disp elements of queue." << std::endl << NEXT << " : show next element id." << std::endl; return oss.str(); } void CommandRequestHandler::handleRequest(HTTPServerRequest &request, HTTPServerResponse &response) { try { app().logger().information("[START] CommandRequestHandler::handleRequest"); response.setChunkedTransferEncoding(true); response.setContentType("text"); Poco::URI url(request.getURI()); std::vector<std::string> segments; url.getPathSegments(segments); if (segments.size() >= 2) { std::string command = segments[1]; if (command == HELP) { response.send() << helpText() << std::endl; } else if (command == COUNT) { response.send() << "queue size is " << app().getSubsystem<LSQQueue>().size() << std::endl; } else if (command == LIST) { response.send() << "list command" << std::endl; } else if (command == NEXT) { response.send() << "next element id is " << app().getSubsystem<LSQQueue>().lastId() + 1 << std::endl; } else { response.send() << "command not found" << std::endl; } } app().logger().information("[END] CommandRequestHandler::handleRequest"); } catch (const std::exception &e) { app().logger().error(e.what()); response.send() << FAILED(); } catch (...) { app().logger().error("unexpected error."); response.send() << FAILED(); } } } // namespace LSQ
29.037975
117
0.543156
[ "vector" ]
551cd51801c60fea9994a90254abc256b577e11b
51,926
cpp
C++
SheepShaver/src/BeOS/main_beos.cpp
jvernet/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
940
2015-01-04T12:20:10.000Z
2022-03-29T12:35:27.000Z
SheepShaver/src/BeOS/main_beos.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
163
2015-02-10T09:08:10.000Z
2022-03-13T05:48:10.000Z
SheepShaver/src/BeOS/main_beos.cpp
Seanpm2001-virtual-machines/macemu
c616a0dae0f451fc15016765c896175fae3f46cf
[ "Intel", "X11" ]
188
2015-01-07T19:46:11.000Z
2022-03-26T19:06:00.000Z
/* * main_beos.cpp - Emulation core, BeOS implementation * * SheepShaver (C) 1997-2008 Christian Bauer and Marc Hellwig * * 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 */ /* * NOTES: * * SheepShaver uses three run-time environments, reflected by the value of XLM_RUN_MODE. * The two modes which are also present in the original MacOS, are: * MODE_68K - 68k emulator is active * MODE_NATIVE - 68k emulator is inactive * In the original MacOS, these two modes have different memory mappings and exception * tables. Under SheepShaver, the only difference is the handling of interrupts (see below). * SheepShaver extends the 68k emulator with special opcodes (EMUL_OP) to perform faster * mode switches when patching 68k routines with PowerPC code and adds a third run mode: * MODE_EMUL_OP - 68k emulator active, but native register usage * * Switches between MODE_68K and MODE_NATIVE are only done with the Mixed Mode Manager * (via nanokernel patches). The switch from MODE_68K to MODE_EMUL_OP occurs when executin * one of the EMUL_OP 68k opcodes. When the opcode routine is done, it returns to MODE_68K. * * The Execute68k() routine allows EMUL_OP routines to execute 68k subroutines. It switches * from MODE_EMUL_OP back to MODE_68K, so it must not be used by native routines (executing * in MODE_NATIVE) nor by any other thread than the emul_thread (because the 68k emulator * is not reentrant). When the 68k subroutine returns, it switches back to MODE_EMUL_OP. * It is OK for a 68k routine called with Execute68k() to contain an EMUL_OP opcode. * * The handling of interrupts depends on the current run mode: * MODE_68K - The USR1 signal handler sets one bit in the processor's CR. The 68k emulator * will then execute the 68k interrupt routine when fetching the next instruction. * MODE_NATIVE - The USR1 signal handler switches back to the original stack (signals run * on a separate signal stack) and enters the External Interrupt routine in the * nanokernel. * MODE_EMUL_OP - The USR1 signal handler directly executes the 68k interrupt routine * with Execute68k(). Before doing this, it must first check the current 68k interrupt * level which is stored in XLM_68K_R25. This variable is set to the current level * when entering EMUL_OP mode. Execute68k() also uses it to restore the level so that * Execute68k()'d routines will run at the same interrupt level as the EMUL_OP routine * it was called from. */ #include <Path.h> #include <unistd.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "sysdeps.h" #include "main.h" #include "version.h" #include "prefs.h" #include "prefs_editor.h" #include "cpu_emulation.h" #include "emul_op.h" #include "xlowmem.h" #include "xpram.h" #include "timer.h" #include "adb.h" #include "video.h" #include "sys.h" #include "macos_util.h" #include "rom_patches.h" #include "user_strings.h" #include "sheep_driver.h" #define DEBUG 0 #include "debug.h" // Enable Execute68k() safety checks? #define SAFE_EXEC_68K 0 // Save FP regs in Execute68k()? #define SAVE_FP_EXEC_68K 0 // Interrupts in EMUL_OP mode? #define INTERRUPTS_IN_EMUL_OP_MODE 1 // Interrupts in native mode? #define INTERRUPTS_IN_NATIVE_MODE 1 // Constants const char APP_SIGNATURE[] = "application/x-vnd.cebix-SheepShaver"; const char ROM_FILE_NAME[] = "ROM"; const char ROM_FILE_NAME2[] = "Mac OS ROM"; const char KERNEL_AREA_NAME[] = "Macintosh Kernel Data"; const char KERNEL_AREA2_NAME[] = "Macintosh Kernel Data 2"; const char RAM_AREA_NAME[] = "Macintosh RAM"; const char ROM_AREA_NAME[] = "Macintosh ROM"; const char DR_CACHE_AREA_NAME[] = "Macintosh DR Cache"; const char DR_EMULATOR_AREA_NAME[] = "Macintosh DR Emulator"; const char SHEEP_AREA_NAME[] = "SheepShaver Virtual Stack"; const uintptr ROM_BASE = 0x40800000; // Base address of ROM const uint32 SIG_STACK_SIZE = 8192; // Size of signal stack const uint32 MSG_START = 'strt'; // Emulator start message // Application object class SheepShaver : public BApplication { public: SheepShaver() : BApplication(APP_SIGNATURE) { // Find application directory and cwd to it app_info the_info; GetAppInfo(&the_info); BEntry the_file(&the_info.ref); BEntry the_dir; the_file.GetParent(&the_dir); BPath the_path; the_dir.GetPath(&the_path); chdir(the_path.Path()); // Initialize other variables sheep_fd = -1; emulator_data = NULL; kernel_area = kernel_area2 = rom_area = ram_area = dr_cache_area = dr_emulator_area = -1; emul_thread = nvram_thread = tick_thread = -1; ReadyForSignals = false; AllowQuitting = true; NVRAMThreadActive = true; TickThreadActive = true; memset(last_xpram, 0, XPRAM_SIZE); } virtual void ReadyToRun(void); virtual void MessageReceived(BMessage *msg); void StartEmulator(void); virtual bool QuitRequested(void); virtual void Quit(void); thread_id emul_thread; // Emulator thread thread_id nvram_thread; // NVRAM watchdog thread thread_id tick_thread; // 60Hz thread KernelData *kernel_data; // Pointer to Kernel Data EmulatorData *emulator_data; bool ReadyForSignals; // Flag: emul_thread ready to receive signals bool AllowQuitting; // Flag: Alt-Q quitting allowed bool NVRAMThreadActive; // nvram_thread will exit when this is false bool TickThreadActive; // tick_thread will exit when this is false uint8 last_xpram[XPRAM_SIZE]; // Buffer for monitoring XPRAM changes private: static status_t emul_func(void *arg); static status_t nvram_func(void *arg); static status_t tick_func(void *arg); static void sigusr1_invoc(int sig, void *arg, vregs *r); void sigusr1_handler(vregs *r); static void sigsegv_invoc(int sig, void *arg, vregs *r); static void sigill_invoc(int sig, void *arg, vregs *r); void jump_to_rom(uint32 entry); void init_rom(void); void load_rom(void); int sheep_fd; // FD of sheep driver area_id kernel_area; // Kernel Data area ID area_id kernel_area2; // Alternate Kernel Data area ID area_id rom_area; // ROM area ID area_id ram_area; // RAM area ID area_id dr_cache_area; // DR Cache area ID area_id dr_emulator_area; // DR Emulator area ID struct sigaction sigusr1_action; // Interrupt signal (of emulator thread) struct sigaction sigsegv_action; // Data access exception signal (of emulator thread) struct sigaction sigill_action; // Illegal instruction exception signal (of emulator thread) // Exceptions class area_error {}; class file_open_error {}; class file_read_error {}; class rom_size_error {}; }; // Global variables SheepShaver *the_app; // Pointer to application object #if !EMULATED_PPC void *TOC; // TOC pointer #endif uint32 RAMBase; // Base address of Mac RAM uint32 RAMSize; // Size of Mac RAM uint32 ROMBase; // Base address of Mac ROM uint32 KernelDataAddr; // Address of Kernel Data uint32 BootGlobsAddr; // Address of BootGlobs structure at top of Mac RAM uint32 DRCacheAddr; // Address of DR Cache uint32 DREmulatorAddr; // Address of DR Emulator uint32 PVR; // Theoretical PVR int64 CPUClockSpeed; // Processor clock speed (Hz) int64 BusClockSpeed; // Bus clock speed (Hz) int64 TimebaseSpeed; // Timebase clock speed (Hz) system_info SysInfo; // System information uint8 *RAMBaseHost; // Base address of Mac RAM (host address space) uint8 *ROMBaseHost; // Base address of Mac ROM (host address space) static void *sig_stack = NULL; // Stack for signal handlers static void *extra_stack = NULL; // Stack for SIGSEGV inside interrupt handler uint32 SheepMem::page_size; // Size of a native page uintptr SheepMem::zero_page = 0; // Address of ro page filled in with zeros uintptr SheepMem::base; // Address of SheepShaver data uintptr SheepMem::proc; // Bottom address of SheepShave procedures uintptr SheepMem::data; // Top of SheepShaver data (stack like storage) static area_id SheepMemArea; // SheepShaver data area ID // Prototypes static void sigsegv_handler(vregs *r); static void sigill_handler(vregs *r); /* * Create application object and start it */ int main(int argc, char **argv) { tzset(); the_app = new SheepShaver(); the_app->Run(); delete the_app; return 0; } /* * Run application */ #if !EMULATED_PPC static asm void *get_toc(void) { mr r3,r2 blr } #endif void SheepShaver::ReadyToRun(void) { // Print some info printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR); printf(" %s\n", GetString(STR_ABOUT_TEXT2)); #if !EMULATED_PPC // Get TOC pointer TOC = get_toc(); #endif // Get system info get_system_info(&SysInfo); switch (SysInfo.cpu_type) { case B_CPU_PPC_601: PVR = 0x00010000; break; case B_CPU_PPC_603: PVR = 0x00030000; break; case B_CPU_PPC_603e: PVR = 0x00060000; break; case B_CPU_PPC_604: PVR = 0x00040000; break; case B_CPU_PPC_604e: PVR = 0x00090000; break; case B_CPU_PPC_750: PVR = 0x00080000; break; default: PVR = 0x00040000; break; } CPUClockSpeed = SysInfo.cpu_clock_speed; BusClockSpeed = SysInfo.bus_clock_speed; TimebaseSpeed = BusClockSpeed / 4; // Delete old areas area_id old_kernel_area = find_area(KERNEL_AREA_NAME); if (old_kernel_area > 0) delete_area(old_kernel_area); area_id old_kernel2_area = find_area(KERNEL_AREA2_NAME); if (old_kernel2_area > 0) delete_area(old_kernel2_area); area_id old_ram_area = find_area(RAM_AREA_NAME); if (old_ram_area > 0) delete_area(old_ram_area); area_id old_rom_area = find_area(ROM_AREA_NAME); if (old_rom_area > 0) delete_area(old_rom_area); area_id old_dr_cache_area = find_area(DR_CACHE_AREA_NAME); if (old_dr_cache_area > 0) delete_area(old_dr_cache_area); area_id old_dr_emulator_area = find_area(DR_EMULATOR_AREA_NAME); if (old_dr_emulator_area > 0) delete_area(old_dr_emulator_area); // Read preferences int argc = 0; char **argv = NULL; PrefsInit(NULL, argc, argv); // Init system routines SysInit(); // Test amount of RAM available for areas if (SysInfo.max_pages * B_PAGE_SIZE < 16 * 1024 * 1024) { ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR)); PostMessage(B_QUIT_REQUESTED); return; } // Show preferences editor (or start emulator directly) if (!PrefsFindBool("nogui")) PrefsEditor(MSG_START); else PostMessage(MSG_START); } /* * Message received */ void SheepShaver::MessageReceived(BMessage *msg) { switch (msg->what) { case MSG_START: StartEmulator(); break; default: BApplication::MessageReceived(msg); } } /* * Start emulator */ void SheepShaver::StartEmulator(void) { char str[256]; // Open sheep driver and remap low memory sheep_fd = open("/dev/sheep", 0); if (sheep_fd < 0) { sprintf(str, GetString(STR_NO_SHEEP_DRIVER_ERR), strerror(sheep_fd), sheep_fd); ErrorAlert(str); PostMessage(B_QUIT_REQUESTED); return; } status_t res = ioctl(sheep_fd, SHEEP_UP); if (res < 0) { sprintf(str, GetString(STR_SHEEP_UP_ERR), strerror(res), res); ErrorAlert(str); PostMessage(B_QUIT_REQUESTED); return; } // Create areas for Kernel Data kernel_data = (KernelData *)KERNEL_DATA_BASE; kernel_area = create_area(KERNEL_AREA_NAME, &kernel_data, B_EXACT_ADDRESS, KERNEL_AREA_SIZE, B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (kernel_area < 0) { sprintf(str, GetString(STR_NO_KERNEL_DATA_ERR), strerror(kernel_area), kernel_area); ErrorAlert(str); PostMessage(B_QUIT_REQUESTED); return; } emulator_data = &kernel_data->ed; KernelDataAddr = (uint32)kernel_data; D(bug("Kernel Data area %ld at %p, Emulator Data at %p\n", kernel_area, kernel_data, emulator_data)); void *kernel_data2 = (void *)KERNEL_DATA2_BASE; kernel_area2 = clone_area(KERNEL_AREA2_NAME, &kernel_data2, B_EXACT_ADDRESS, B_READ_AREA | B_WRITE_AREA, kernel_area); if (kernel_area2 < 0) { sprintf(str, GetString(STR_NO_KERNEL_DATA_ERR), strerror(kernel_area2), kernel_area2); ErrorAlert(str); PostMessage(B_QUIT_REQUESTED); return; } D(bug("Kernel Data 2 area %ld at %p\n", kernel_area2, kernel_data2)); // Create area for SheepShaver data if (!SheepMem::Init()) { sprintf(str, GetString(STR_NO_SHEEP_MEM_AREA_ERR), strerror(SheepMemArea), SheepMemArea); ErrorAlert(str); PostMessage(B_QUIT_REQUESTED); return; } // Create area for Mac RAM RAMSize = PrefsFindInt32("ramsize") & 0xfff00000; // Round down to 1MB boundary if (RAMSize < 8*1024*1024) { WarningAlert(GetString(STR_SMALL_RAM_WARN)); RAMSize = 8*1024*1024; } RAMBase = 0x10000000; ram_area = create_area(RAM_AREA_NAME, (void **)&RAMBase, B_BASE_ADDRESS, RAMSize, B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (ram_area < 0) { sprintf(str, GetString(STR_NO_RAM_AREA_ERR), strerror(ram_area), ram_area); ErrorAlert(str); PostMessage(B_QUIT_REQUESTED); return; } RAMBaseHost = (uint8 *)RAMBase; D(bug("RAM area %ld at %p\n", ram_area, RAMBaseHost)); // Create area and load Mac ROM try { init_rom(); } catch (area_error) { ErrorAlert(GetString(STR_NO_ROM_AREA_ERR)); PostMessage(B_QUIT_REQUESTED); return; } catch (file_open_error) { ErrorAlert(GetString(STR_NO_ROM_FILE_ERR)); PostMessage(B_QUIT_REQUESTED); return; } catch (file_read_error) { ErrorAlert(GetString(STR_ROM_FILE_READ_ERR)); PostMessage(B_QUIT_REQUESTED); return; } catch (rom_size_error) { ErrorAlert(GetString(STR_ROM_SIZE_ERR)); PostMessage(B_QUIT_REQUESTED); return; } // Create area for DR Cache DRCacheAddr = DR_CACHE_BASE; dr_cache_area = create_area(DR_CACHE_AREA_NAME, (void **)&DRCacheAddr, B_EXACT_ADDRESS, DR_CACHE_SIZE, B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (dr_cache_area < 0) { sprintf(str, GetString(STR_NO_KERNEL_DATA_ERR), strerror(dr_cache_area), dr_cache_area); ErrorAlert(str); PostMessage(B_QUIT_REQUESTED); return; } D(bug("DR Cache area %ld at %p\n", dr_cache_area, DRCacheAddr)); // Create area for DR Emulator DREmulatorAddr = DR_EMULATOR_BASE; dr_emulator_area = create_area(DR_EMULATOR_AREA_NAME, (void **)&DREmulatorAddr, B_EXACT_ADDRESS, DR_EMULATOR_SIZE, B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (dr_emulator_area < 0) { sprintf(str, GetString(STR_NO_KERNEL_DATA_ERR), strerror(dr_emulator_area), dr_emulator_area); ErrorAlert(str); PostMessage(B_QUIT_REQUESTED); return; } D(bug("DR Emulator area %ld at %p\n", dr_emulator_area, DREmulatorAddr)); // Initialize everything if (!InitAll(NULL)) { PostMessage(B_QUIT_REQUESTED); return; } D(bug("Initialization complete\n")); // Clear caches (as we loaded and patched code) and write protect ROM #if !EMULATED_PPC clear_caches(ROMBaseHost, ROM_AREA_SIZE, B_INVALIDATE_ICACHE | B_FLUSH_DCACHE); #endif set_area_protection(rom_area, B_READ_AREA); // Initialize extra low memory D(bug("Initializing extra Low Memory...\n")); WriteMacInt32(XLM_SHEEP_OBJ, (uint32)this); // Pointer to SheepShaver object D(bug("Extra Low Memory initialized\n")); // Disallow quitting with Alt-Q from now on AllowQuitting = false; // Start 60Hz interrupt tick_thread = spawn_thread(tick_func, "60Hz", B_URGENT_DISPLAY_PRIORITY, this); resume_thread(tick_thread); // Start NVRAM watchdog thread memcpy(last_xpram, XPRAM, XPRAM_SIZE); nvram_thread = spawn_thread(nvram_func, "NVRAM Watchdog", B_LOW_PRIORITY, this); resume_thread(nvram_thread); // Start emulator thread emul_thread = spawn_thread(emul_func, "MacOS", B_NORMAL_PRIORITY, this); resume_thread(emul_thread); } /* * Quit requested */ bool SheepShaver::QuitRequested(void) { if (AllowQuitting) return BApplication::QuitRequested(); else return false; } void SheepShaver::Quit(void) { status_t l; // Stop 60Hz interrupt if (tick_thread > 0) { TickThreadActive = false; wait_for_thread(tick_thread, &l); } // Stop NVRAM watchdog if (nvram_thread > 0) { status_t l; NVRAMThreadActive = false; suspend_thread(nvram_thread); // Wake thread up from snooze() snooze(1000); resume_thread(nvram_thread); while (wait_for_thread(nvram_thread, &l) == B_INTERRUPTED) ; } // Wait for emulator thread to finish if (emul_thread > 0) wait_for_thread(emul_thread, &l); // Deinitialize everything ExitAll(); // Delete SheepShaver globals SheepMem::Exit(); // Delete DR Emulator area if (dr_emulator_area >= 0) delete_area(dr_emulator_area); // Delete DR Cache area if (dr_cache_area >= 0) delete_area(dr_cache_area); // Delete ROM area if (rom_area >= 0) delete_area(rom_area); // Delete RAM area if (ram_area >= 0) delete_area(ram_area); // Delete Kernel Data area2 if (kernel_area2 >= 0) delete_area(kernel_area2); if (kernel_area >= 0) delete_area(kernel_area); // Unmap low memory and close sheep driver if (sheep_fd >= 0) { ioctl(sheep_fd, SHEEP_DOWN); close(sheep_fd); } // Exit system routines SysExit(); // Exit preferences PrefsExit(); BApplication::Quit(); } /* * Create area for ROM (sets rom_area) and load ROM file * * area_error : Cannot create area * file_open_error: Cannot open ROM file * file_read_error: Cannot read ROM file */ void SheepShaver::init_rom(void) { // Size of a native page page_size = B_PAGE_SIZE; // Create area for ROM ROMBase = ROM_BASE; rom_area = create_area(ROM_AREA_NAME, (void **)&ROMBase, B_EXACT_ADDRESS, ROM_AREA_SIZE, B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (rom_area < 0) throw area_error(); ROMBaseHost = (uint8 *)ROMBase; D(bug("ROM area %ld at %p\n", rom_area, rom_addr)); // Load ROM load_rom(); } /* * Load ROM file * * file_open_error: Cannot open ROM file (nor use built-in ROM) * file_read_error: Cannot read ROM file */ void SheepShaver::load_rom(void) { // Get rom file path from preferences const char *rom_path = PrefsFindString("rom"); // Try to open ROM file BFile file(rom_path && *rom_path ? rom_path : ROM_FILE_NAME, B_READ_ONLY); if (file.InitCheck() != B_NO_ERROR) { // Failed, then ask memory_mess driver for ROM uint8 *rom = new uint8[ROM_SIZE]; // Reading directly into the area doesn't work ssize_t actual = read(sheep_fd, (void *)rom, ROM_SIZE); if (actual == ROM_SIZE) { memcpy(ROMBaseHost, rom, ROM_SIZE); delete[] rom; return; } else throw file_open_error(); } printf(GetString(STR_READING_ROM_FILE)); // Get file size off_t rom_size = 0; file.GetSize(&rom_size); uint8 *rom = new uint8[ROM_SIZE]; // Reading directly into the area doesn't work ssize_t actual = file.Read((void *)rom, ROM_SIZE); // Decode Mac ROM if (!DecodeROM(rom, actual)) { if (rom_size != 4*1024*1024) throw rom_size_error(); else throw file_read_error(); } delete[] rom; } /* * Emulator thread function */ status_t SheepShaver::emul_func(void *arg) { SheepShaver *obj = (SheepShaver *)arg; // Install interrupt signal handler sigemptyset(&obj->sigusr1_action.sa_mask); obj->sigusr1_action.sa_handler = (__signal_func_ptr)(obj->sigusr1_invoc); obj->sigusr1_action.sa_flags = 0; obj->sigusr1_action.sa_userdata = arg; sigaction(SIGUSR1, &obj->sigusr1_action, NULL); // Install data access signal handler sigemptyset(&obj->sigsegv_action.sa_mask); obj->sigsegv_action.sa_handler = (__signal_func_ptr)(obj->sigsegv_invoc); obj->sigsegv_action.sa_flags = 0; obj->sigsegv_action.sa_userdata = arg; sigaction(SIGSEGV, &obj->sigsegv_action, NULL); #if !EMULATED_PPC // Install illegal instruction signal handler sigemptyset(&obj->sigill_action.sa_mask); obj->sigill_action.sa_handler = (__signal_func_ptr)(obj->sigill_invoc); obj->sigill_action.sa_flags = 0; obj->sigill_action.sa_userdata = arg; sigaction(SIGILL, &obj->sigill_action, NULL); #endif // Exceptions will send signals disable_debugger(true); // Install signal stack sig_stack = malloc(SIG_STACK_SIZE); extra_stack = malloc(SIG_STACK_SIZE); set_signal_stack(sig_stack, SIG_STACK_SIZE); // We're now ready to receive signals obj->ReadyForSignals = true; // Jump to ROM boot routine D(bug("Jumping to ROM\n")); obj->jump_to_rom(ROMBase + 0x310000); D(bug("Returned from ROM\n")); // We're no longer ready to receive signals obj->ReadyForSignals = false; obj->AllowQuitting = true; // Quit program be_app->PostMessage(B_QUIT_REQUESTED); return 0; } /* * Jump into Mac ROM, start 680x0 emulator * (also contains other EMUL_RETURN and EMUL_OP routines) */ #if EMULATED_PPC extern void emul_ppc(uint32 start); extern void init_emul_ppc(void); void SheepShaver::jump_to_rom(uint32 entry) { init_emul_ppc(); emul_ppc(entry); } #else asm void SheepShaver::jump_to_rom(register uint32 entry) { // Create stack frame mflr r0 stw r0,8(r1) mfcr r0 stw r0,4(r1) stwu r1,-(56+19*4+18*8)(r1) // Save PowerPC registers stmw r13,56(r1) stfd f14,56+19*4+0*8(r1) stfd f15,56+19*4+1*8(r1) stfd f16,56+19*4+2*8(r1) stfd f17,56+19*4+3*8(r1) stfd f18,56+19*4+4*8(r1) stfd f19,56+19*4+5*8(r1) stfd f20,56+19*4+6*8(r1) stfd f21,56+19*4+7*8(r1) stfd f22,56+19*4+8*8(r1) stfd f23,56+19*4+9*8(r1) stfd f24,56+19*4+10*8(r1) stfd f25,56+19*4+11*8(r1) stfd f26,56+19*4+12*8(r1) stfd f27,56+19*4+13*8(r1) stfd f28,56+19*4+14*8(r1) stfd f29,56+19*4+15*8(r1) stfd f30,56+19*4+16*8(r1) stfd f31,56+19*4+17*8(r1) // Move entry address to ctr, get pointer to Emulator Data mtctr r4 lwz r4,SheepShaver.emulator_data(r3) // Skip over EMUL_RETURN routine and get its address bl @1 /* * EMUL_RETURN: Returned from emulator */ // Restore PowerPC registers lwz r1,XLM_EMUL_RETURN_STACK lwz r2,XLM_TOC lmw r13,56(r1) lfd f14,56+19*4+0*8(r1) lfd f15,56+19*4+1*8(r1) lfd f16,56+19*4+2*8(r1) lfd f17,56+19*4+3*8(r1) lfd f18,56+19*4+4*8(r1) lfd f19,56+19*4+5*8(r1) lfd f20,56+19*4+6*8(r1) lfd f21,56+19*4+7*8(r1) lfd f22,56+19*4+8*8(r1) lfd f23,56+19*4+9*8(r1) lfd f24,56+19*4+10*8(r1) lfd f25,56+19*4+11*8(r1) lfd f26,56+19*4+12*8(r1) lfd f27,56+19*4+13*8(r1) lfd f28,56+19*4+14*8(r1) lfd f29,56+19*4+15*8(r1) lfd f30,56+19*4+16*8(r1) lfd f31,56+19*4+17*8(r1) // Exiting from 68k emulator li r0,1 stw r0,XLM_IRQ_NEST li r0,MODE_NATIVE stw r0,XLM_RUN_MODE // Return to caller of jump_to_rom() lwz r0,56+19*4+18*8+8(r1) mtlr r0 lwz r0,56+19*4+18*8+4(r1) mtcrf 0xff,r0 addi r1,r1,56+19*4+18*8 blr // Save address of EMUL_RETURN routine for 68k emulator patch @1 mflr r0 stw r0,XLM_EMUL_RETURN_PROC // Skip over EXEC_RETURN routine and get its address bl @2 /* * EXEC_RETURN: Returned from 68k routine executed with Execute68k() */ // Save r25 (contains current 68k interrupt level) stw r25,XLM_68K_R25 // Reentering EMUL_OP mode li r0,MODE_EMUL_OP stw r0,XLM_RUN_MODE // Save 68k registers lwz r4,56+19*4+18*8+12(r1) stw r8,M68kRegisters.d[0](r4) stw r9,M68kRegisters.d[1](r4) stw r10,M68kRegisters.d[2](r4) stw r11,M68kRegisters.d[3](r4) stw r12,M68kRegisters.d[4](r4) stw r13,M68kRegisters.d[5](r4) stw r14,M68kRegisters.d[6](r4) stw r15,M68kRegisters.d[7](r4) stw r16,M68kRegisters.a[0](r4) stw r17,M68kRegisters.a[1](r4) stw r18,M68kRegisters.a[2](r4) stw r19,M68kRegisters.a[3](r4) stw r20,M68kRegisters.a[4](r4) stw r21,M68kRegisters.a[5](r4) stw r22,M68kRegisters.a[6](r4) // Restore PowerPC registers lmw r13,56(r1) #if SAVE_FP_EXEC_68K lfd f14,56+19*4+0*8(r1) lfd f15,56+19*4+1*8(r1) lfd f16,56+19*4+2*8(r1) lfd f17,56+19*4+3*8(r1) lfd f18,56+19*4+4*8(r1) lfd f19,56+19*4+5*8(r1) lfd f20,56+19*4+6*8(r1) lfd f21,56+19*4+7*8(r1) lfd f22,56+19*4+8*8(r1) lfd f23,56+19*4+9*8(r1) lfd f24,56+19*4+10*8(r1) lfd f25,56+19*4+11*8(r1) lfd f26,56+19*4+12*8(r1) lfd f27,56+19*4+13*8(r1) lfd f28,56+19*4+14*8(r1) lfd f29,56+19*4+15*8(r1) lfd f30,56+19*4+16*8(r1) lfd f31,56+19*4+17*8(r1) #endif // Return to caller lwz r0,56+19*4+18*8+8(r1) mtlr r0 addi r1,r1,56+19*4+18*8 blr // Stave address of EXEC_RETURN routine for 68k emulator patch @2 mflr r0 stw r0,XLM_EXEC_RETURN_PROC // Skip over EMUL_BREAK/EMUL_OP routine and get its address bl @3 /* * EMUL_BREAK/EMUL_OP: Execute native routine, selector in r5 (my own private mode switch) * * 68k registers are stored in a M68kRegisters struct on the stack * which the native routine may read and modify */ // Save r25 (contains current 68k interrupt level) stw r25,XLM_68K_R25 // Entering EMUL_OP mode within 68k emulator li r0,MODE_EMUL_OP stw r0,XLM_RUN_MODE // Create PowerPC stack frame, reserve space for M68kRegisters mr r3,r1 subi r1,r1,56 // Fake "caller" frame rlwinm r1,r1,0,0,29 // Align stack mfcr r0 rlwinm r0,r0,0,11,8 stw r0,4(r1) mfxer r0 stw r0,16(r1) stw r2,12(r1) stwu r1,-(56+16*4+15*8)(r1) lwz r2,XLM_TOC // Save 68k registers stw r8,56+M68kRegisters.d[0](r1) stw r9,56+M68kRegisters.d[1](r1) stw r10,56+M68kRegisters.d[2](r1) stw r11,56+M68kRegisters.d[3](r1) stw r12,56+M68kRegisters.d[4](r1) stw r13,56+M68kRegisters.d[5](r1) stw r14,56+M68kRegisters.d[6](r1) stw r15,56+M68kRegisters.d[7](r1) stw r16,56+M68kRegisters.a[0](r1) stw r17,56+M68kRegisters.a[1](r1) stw r18,56+M68kRegisters.a[2](r1) stw r19,56+M68kRegisters.a[3](r1) stw r20,56+M68kRegisters.a[4](r1) stw r21,56+M68kRegisters.a[5](r1) stw r22,56+M68kRegisters.a[6](r1) stw r3,56+M68kRegisters.a[7](r1) stfd f0,56+16*4+0*8(r1) stfd f1,56+16*4+1*8(r1) stfd f2,56+16*4+2*8(r1) stfd f3,56+16*4+3*8(r1) stfd f4,56+16*4+4*8(r1) stfd f5,56+16*4+5*8(r1) stfd f6,56+16*4+6*8(r1) stfd f7,56+16*4+7*8(r1) mffs f0 stfd f8,56+16*4+8*8(r1) stfd f9,56+16*4+9*8(r1) stfd f10,56+16*4+10*8(r1) stfd f11,56+16*4+11*8(r1) stfd f12,56+16*4+12*8(r1) stfd f13,56+16*4+13*8(r1) stfd f0,56+16*4+14*8(r1) // Execute native routine addi r3,r1,56 mr r4,r24 bl EmulOp // Restore 68k registers lwz r8,56+M68kRegisters.d[0](r1) lwz r9,56+M68kRegisters.d[1](r1) lwz r10,56+M68kRegisters.d[2](r1) lwz r11,56+M68kRegisters.d[3](r1) lwz r12,56+M68kRegisters.d[4](r1) lwz r13,56+M68kRegisters.d[5](r1) lwz r14,56+M68kRegisters.d[6](r1) lwz r15,56+M68kRegisters.d[7](r1) lwz r16,56+M68kRegisters.a[0](r1) lwz r17,56+M68kRegisters.a[1](r1) lwz r18,56+M68kRegisters.a[2](r1) lwz r19,56+M68kRegisters.a[3](r1) lwz r20,56+M68kRegisters.a[4](r1) lwz r21,56+M68kRegisters.a[5](r1) lwz r22,56+M68kRegisters.a[6](r1) lwz r3,56+M68kRegisters.a[7](r1) lfd f13,56+16*4+14*8(r1) lfd f0,56+16*4+0*8(r1) lfd f1,56+16*4+1*8(r1) lfd f2,56+16*4+2*8(r1) lfd f3,56+16*4+3*8(r1) lfd f4,56+16*4+4*8(r1) lfd f5,56+16*4+5*8(r1) lfd f6,56+16*4+6*8(r1) lfd f7,56+16*4+7*8(r1) mtfsf 0xff,f13 lfd f8,56+16*4+8*8(r1) lfd f9,56+16*4+9*8(r1) lfd f10,56+16*4+10*8(r1) lfd f11,56+16*4+11*8(r1) lfd f12,56+16*4+12*8(r1) lfd f13,56+16*4+13*8(r1) // Delete PowerPC stack frame lwz r2,56+16*4+15*8+12(r1) lwz r0,56+16*4+15*8+16(r1) mtxer r0 lwz r0,56+16*4+15*8+4(r1) mtcrf 0xff,r0 mr r1,r3 // Reeintering 68k emulator li r0,MODE_68K stw r0,XLM_RUN_MODE // Set r0 to 0 for 68k emulator li r0,0 // Execute next 68k opcode rlwimi r29,r27,3,13,28 lhau r27,2(r24) mtlr r29 blr // Save address of EMUL_BREAK/EMUL_OP routine for 68k emulator patch @3 mflr r0 stw r0,XLM_EMUL_OP_PROC // Save stack pointer for EMUL_RETURN stw r1,XLM_EMUL_RETURN_STACK // Preset registers for ROM boot routine lis r3,0x40b0 // Pointer to ROM boot structure ori r3,r3,0xd000 // 68k emulator is now active li r0,MODE_68K stw r0,XLM_RUN_MODE // Jump to ROM bctr } #endif #if !EMULATED_PPC /* * Execute 68k subroutine (must be ended with RTS) * This must only be called by the emul_thread when in EMUL_OP mode * r->a[7] is unused, the routine runs on the caller's stack */ #if SAFE_EXEC_68K void execute_68k(uint32 pc, M68kRegisters *r); void Execute68k(uint32 pc, M68kRegisters *r) { if (*(uint32 *)XLM_RUN_MODE != MODE_EMUL_OP) printf("FATAL: Execute68k() not called from EMUL_OP mode\n"); if (find_thread(NULL) != the_app->emul_thread) printf("FATAL: Execute68k() not called from emul_thread\n"); execute_68k(pc, r); } asm void execute_68k(register uint32 pc, register M68kRegisters *r) #else asm void Execute68k(register uint32 pc, register M68kRegisters *r) #endif { // Create stack frame mflr r0 stw r0,8(r1) stw r4,12(r1) stwu r1,-(56+19*4+18*8)(r1) // Save PowerPC registers stmw r13,56(r1) #if SAVE_FP_EXEC_68K stfd f14,56+19*4+0*8(r1) stfd f15,56+19*4+1*8(r1) stfd f16,56+19*4+2*8(r1) stfd f17,56+19*4+3*8(r1) stfd f18,56+19*4+4*8(r1) stfd f19,56+19*4+5*8(r1) stfd f20,56+19*4+6*8(r1) stfd f21,56+19*4+7*8(r1) stfd f22,56+19*4+8*8(r1) stfd f23,56+19*4+9*8(r1) stfd f24,56+19*4+10*8(r1) stfd f25,56+19*4+11*8(r1) stfd f26,56+19*4+12*8(r1) stfd f27,56+19*4+13*8(r1) stfd f28,56+19*4+14*8(r1) stfd f29,56+19*4+15*8(r1) stfd f30,56+19*4+16*8(r1) stfd f31,56+19*4+17*8(r1) #endif // Set up registers for 68k emulator lwz r31,XLM_KERNEL_DATA // Pointer to Kernel Data addi r31,r31,0x1000 li r0,0 mtcrf 0xff,r0 creqv 11,11,11 // Supervisor mode lwz r8,M68kRegisters.d[0](r4) lwz r9,M68kRegisters.d[1](r4) lwz r10,M68kRegisters.d[2](r4) lwz r11,M68kRegisters.d[3](r4) lwz r12,M68kRegisters.d[4](r4) lwz r13,M68kRegisters.d[5](r4) lwz r14,M68kRegisters.d[6](r4) lwz r15,M68kRegisters.d[7](r4) lwz r16,M68kRegisters.a[0](r4) lwz r17,M68kRegisters.a[1](r4) lwz r18,M68kRegisters.a[2](r4) lwz r19,M68kRegisters.a[3](r4) lwz r20,M68kRegisters.a[4](r4) lwz r21,M68kRegisters.a[5](r4) lwz r22,M68kRegisters.a[6](r4) li r23,0 mr r24,r3 lwz r25,XLM_68K_R25 // MSB of SR li r26,0 li r28,0 // VBR lwz r29,0x74(r31) // Pointer to opcode table lwz r30,0x78(r31) // Address of emulator // Push return address (points to EXEC_RETURN opcode) on stack li r0,XLM_EXEC_RETURN_OPCODE stwu r0,-4(r1) // Reentering 68k emulator li r0,MODE_68K stw r0,XLM_RUN_MODE // Set r0 to 0 for 68k emulator li r0,0 // Execute 68k opcode lha r27,0(r24) rlwimi r29,r27,3,13,28 lhau r27,2(r24) mtlr r29 blr } /* * Execute 68k A-Trap from EMUL_OP routine * r->a[7] is unused, the routine runs on the caller's stack */ void Execute68kTrap(uint16 trap, M68kRegisters *r) { uint16 proc[2] = {trap, M68K_RTS}; Execute68k((uint32)proc, r); } /* * Quit emulator (must only be called from main thread) */ asm void QuitEmulator(void) { lwz r0,XLM_EMUL_RETURN_PROC mtlr r0 blr } #endif /* * Dump 68k registers */ void Dump68kRegs(M68kRegisters *r) { // Display 68k registers for (int i=0; i<8; i++) { printf("d%d: %08lx", i, r->d[i]); if (i == 3 || i == 7) printf("\n"); else printf(", "); } for (int i=0; i<8; i++) { printf("a%d: %08lx", i, r->a[i]); if (i == 3 || i == 7) printf("\n"); else printf(", "); } } /* * Make code executable */ void MakeExecutable(int dummy, uint32 start, uint32 length) { if ((start >= ROMBase) && (start < (ROMBase + ROM_SIZE))) return; clear_caches((void *)start, length, B_INVALIDATE_ICACHE | B_FLUSH_DCACHE); } /* * NVRAM watchdog thread (saves NVRAM every minute) */ status_t SheepShaver::nvram_func(void *arg) { SheepShaver *obj = (SheepShaver *)arg; while (obj->NVRAMThreadActive) { snooze(60*1000000); if (memcmp(obj->last_xpram, XPRAM, XPRAM_SIZE)) { memcpy(obj->last_xpram, XPRAM, XPRAM_SIZE); SaveXPRAM(); } } return 0; } /* * 60Hz thread (really 60.15Hz) */ status_t SheepShaver::tick_func(void *arg) { SheepShaver *obj = (SheepShaver *)arg; int tick_counter = 0; bigtime_t current = system_time(); while (obj->TickThreadActive) { // Wait current += 16625; snooze_until(current, B_SYSTEM_TIMEBASE); // Pseudo Mac 1Hz interrupt, update local time if (++tick_counter > 60) { tick_counter = 0; WriteMacInt32(0x20c, TimerDateTime()); } // 60Hz interrupt if (ReadMacInt32(XLM_IRQ_NEST) == 0) { SetInterruptFlag(INTFLAG_VIA); TriggerInterrupt(); } } return 0; } /* * Trigger signal USR1 from another thread */ void TriggerInterrupt(void) { idle_resume(); #if 0 WriteMacInt32(0x16a, ReadMacInt32(0x16a) + 1); #else if (the_app->emul_thread > 0 && the_app->ReadyForSignals) send_signal(the_app->emul_thread, SIGUSR1); #endif } /* * Mutexes */ struct B2_mutex { int dummy; //!! }; B2_mutex *B2_create_mutex(void) { return new B2_mutex; } void B2_lock_mutex(B2_mutex *mutex) { } void B2_unlock_mutex(B2_mutex *mutex) { } void B2_delete_mutex(B2_mutex *mutex) { delete mutex; } /* * Set/clear interrupt flags (must be done atomically!) */ volatile uint32 InterruptFlags = 0; void SetInterruptFlag(uint32 flag) { atomic_or((int32 *)&InterruptFlags, flag); } void ClearInterruptFlag(uint32 flag) { atomic_and((int32 *)&InterruptFlags, ~flag); } /* * Disable interrupts */ void DisableInterrupt(void) { atomic_add((int32 *)XLM_IRQ_NEST, 1); } /* * Enable interrupts */ void EnableInterrupt(void) { atomic_add((int32 *)XLM_IRQ_NEST, -1); } /* * USR1 handler */ void SheepShaver::sigusr1_invoc(int sig, void *arg, vregs *r) { ((SheepShaver *)arg)->sigusr1_handler(r); } #if !EMULATED_PPC static asm void ppc_interrupt(register uint32 entry) { fralloc // Get address of return routine bl @1 // Return routine frfree blr @1 // Prepare registers for nanokernel interrupt routine mtctr r1 lwz r1,XLM_KERNEL_DATA stw r6,0x018(r1) mfctr r6 stw r6,0x004(r1) lwz r6,0x65c(r1) stw r7,0x13c(r6) stw r8,0x144(r6) stw r9,0x14c(r6) stw r10,0x154(r6) stw r11,0x15c(r6) stw r12,0x164(r6) stw r13,0x16c(r6) mflr r10 mfcr r13 lwz r7,0x660(r1) mflr r12 rlwimi. r7,r7,8,0,0 li r11,0 ori r11,r11,0xf072 // MSR (SRR1) mtcrf 0x70,r11 li r8,0 // Enter nanokernel mtlr r3 blr } #endif void SheepShaver::sigusr1_handler(vregs *r) { // Do nothing if interrupts are disabled if ((*(int32 *)XLM_IRQ_NEST) > 0) return; // Interrupt action depends on current run mode switch (*(uint32 *)XLM_RUN_MODE) { case MODE_68K: // 68k emulator active, trigger 68k interrupt level 1 *(uint16 *)(kernel_data->v[0x67c >> 2]) = 1; r->cr |= kernel_data->v[0x674 >> 2]; break; #if INTERRUPTS_IN_NATIVE_MODE case MODE_NATIVE: // 68k emulator inactive, in nanokernel? if (r->r1 != KernelDataAddr) { // No, prepare for 68k interrupt level 1 *(uint16 *)(kernel_data->v[0x67c >> 2]) = 1; *(uint32 *)(kernel_data->v[0x658 >> 2] + 0xdc) |= kernel_data->v[0x674 >> 2]; // Execute nanokernel interrupt routine (this will activate the 68k emulator) atomic_add((int32 *)XLM_IRQ_NEST, 1); if (ROMType == ROMTYPE_NEWWORLD) ppc_interrupt(ROMBase + 0x312b1c); else ppc_interrupt(ROMBase + 0x312a3c); } break; #endif #if INTERRUPTS_IN_EMUL_OP_MODE case MODE_EMUL_OP: // 68k emulator active, within EMUL_OP routine, execute 68k interrupt routine directly when interrupt level is 0 if ((*(uint32 *)XLM_68K_R25 & 7) == 0) { // Set extra stack for SIGSEGV handler set_signal_stack(extra_stack, SIG_STACK_SIZE); #if 1 // Execute full 68k interrupt routine M68kRegisters r; uint32 old_r25 = *(uint32 *)XLM_68K_R25; // Save interrupt level *(uint32 *)XLM_68K_R25 = 0x21; // Execute with interrupt level 1 static const uint16 proc[] = { 0x3f3c, 0x0000, // move.w #$0000,-(sp) (fake format word) 0x487a, 0x000a, // pea @1(pc) (return address) 0x40e7, // move sr,-(sp) (saved SR) 0x2078, 0x0064, // move.l $64,a0 0x4ed0, // jmp (a0) M68K_RTS // @1 }; Execute68k((uint32)proc, &r); *(uint32 *)XLM_68K_R25 = old_r25; // Restore interrupt level #else // Only update cursor if (HasMacStarted()) { if (InterruptFlags & INTFLAG_VIA) { ClearInterruptFlag(INTFLAG_VIA); ADBInterrupt(); ExecuteNative(NATIVE_VIDEO_VBL); } } #endif // Reset normal signal stack set_signal_stack(sig_stack, SIG_STACK_SIZE); } break; #endif } } /* * SIGSEGV handler */ static uint32 segv_r[32]; #if !EMULATED_PPC asm void SheepShaver::sigsegv_invoc(register int sig, register void *arg, register vregs *r) { mflr r0 stw r0,8(r1) stwu r1,-56(r1) lwz r3,segv_r(r2) stmw r13,13*4(r3) mr r3,r5 bl sigsegv_handler lwz r3,segv_r(r2) lmw r13,13*4(r3) lwz r0,56+8(r1) mtlr r0 addi r1,r1,56 blr } #endif static void sigsegv_handler(vregs *r) { char str[256]; // Fetch volatile registers segv_r[0] = r->r0; segv_r[1] = r->r1; segv_r[2] = r->r2; segv_r[3] = r->r3; segv_r[4] = r->r4; segv_r[5] = r->r5; segv_r[6] = r->r6; segv_r[7] = r->r7; segv_r[8] = r->r8; segv_r[9] = r->r9; segv_r[10] = r->r10; segv_r[11] = r->r11; segv_r[12] = r->r12; // Get opcode and divide into fields uint32 opcode = *(uint32 *)r->pc; uint32 primop = opcode >> 26; uint32 exop = (opcode >> 1) & 0x3ff; uint32 ra = (opcode >> 16) & 0x1f; uint32 rb = (opcode >> 11) & 0x1f; uint32 rd = (opcode >> 21) & 0x1f; uint32 imm = opcode & 0xffff; // Fault in Mac ROM or RAM? bool mac_fault = (r->pc >= ROMBase) && (r->pc < (ROMBase + ROM_AREA_SIZE)) || (r->pc >= RAMBase) && (r->pc < (RAMBase + RAMSize)); if (mac_fault) { // "VM settings" during MacOS 8 installation if (r->pc == ROMBase + 0x488160 && segv_r[20] == 0xf8000000) { r->pc += 4; segv_r[8] = 0; goto rti; // MacOS 8.5 installation } else if (r->pc == ROMBase + 0x488140 && segv_r[16] == 0xf8000000) { r->pc += 4; segv_r[8] = 0; goto rti; // MacOS 8 serial drivers on startup } else if (r->pc == ROMBase + 0x48e080 && (segv_r[8] == 0xf3012002 || segv_r[8] == 0xf3012000)) { r->pc += 4; segv_r[8] = 0; goto rti; // MacOS 8.1 serial drivers on startup } else if (r->pc == ROMBase + 0x48c5e0 && (segv_r[20] == 0xf3012002 || segv_r[20] == 0xf3012000)) { r->pc += 4; goto rti; } else if (r->pc == ROMBase + 0x4a10a0 && (segv_r[20] == 0xf3012002 || segv_r[20] == 0xf3012000)) { r->pc += 4; goto rti; } } // Analyze opcode enum { TYPE_UNKNOWN, TYPE_LOAD, TYPE_STORE } transfer_type = TYPE_UNKNOWN; enum { SIZE_UNKNOWN, SIZE_BYTE, SIZE_HALFWORD, SIZE_WORD } transfer_size = SIZE_UNKNOWN; enum { MODE_UNKNOWN, MODE_NORM, MODE_U, MODE_X, MODE_UX } addr_mode = MODE_UNKNOWN; switch (primop) { case 31: switch (exop) { case 23: // lwzx transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_X; break; case 55: // lwzux transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break; case 87: // lbzx transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break; case 119: // lbzux transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break; case 151: // stwx transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_X; break; case 183: // stwux transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break; case 215: // stbx transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break; case 247: // stbux transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break; case 279: // lhzx transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break; case 311: // lhzux transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break; case 343: // lhax transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break; case 375: // lhaux transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break; case 407: // sthx transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break; case 439: // sthux transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break; } break; case 32: // lwz transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break; case 33: // lwzu transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_U; break; case 34: // lbz transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break; case 35: // lbzu transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break; case 36: // stw transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break; case 37: // stwu transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_U; break; case 38: // stb transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break; case 39: // stbu transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break; case 40: // lhz transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break; case 41: // lhzu transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break; case 42: // lha transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break; case 43: // lhau transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break; case 44: // sth transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break; case 45: // sthu transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break; } // Calculate effective address uint32 addr = 0; switch (addr_mode) { case MODE_X: case MODE_UX: if (ra == 0) addr = segv_r[rb]; else addr = segv_r[ra] + segv_r[rb]; break; case MODE_NORM: case MODE_U: if (ra == 0) addr = (int32)(int16)imm; else addr = segv_r[ra] + (int32)(int16)imm; break; default: break; } // Ignore ROM writes if (transfer_type == TYPE_STORE && addr >= ROMBase && addr < ROMBase + ROM_SIZE) { D(bug("WARNING: %s write access to ROM at %p, pc %p\n", transfer_size == SIZE_BYTE ? "Byte" : transfer_size == SIZE_HALFWORD ? "Halfword" : "Word", addr, r->pc)); if (addr_mode == MODE_U || addr_mode == MODE_UX) segv_r[ra] = addr; r->pc += 4; goto rti; } // Fault in Mac ROM or RAM? if (mac_fault) { // Ignore illegal memory accesses? if (PrefsFindBool("ignoresegv")) { if (addr_mode == MODE_U || addr_mode == MODE_UX) segv_r[ra] = addr; if (transfer_type == TYPE_LOAD) segv_r[rd] = 0; r->pc += 4; goto rti; } // In GUI mode, show error alert if (!PrefsFindBool("nogui")) { if (transfer_type == TYPE_LOAD || transfer_type == TYPE_STORE) sprintf(str, GetString(STR_MEM_ACCESS_ERR), transfer_size == SIZE_BYTE ? "byte" : transfer_size == SIZE_HALFWORD ? "halfword" : "word", transfer_type == TYPE_LOAD ? GetString(STR_MEM_ACCESS_READ) : GetString(STR_MEM_ACCESS_WRITE), addr, r->pc, segv_r[24], segv_r[1]); else sprintf(str, GetString(STR_UNKNOWN_SEGV_ERR), r->pc, segv_r[24], segv_r[1], opcode); ErrorAlert(str); QuitEmulator(); return; } } // For all other errors, jump into debugger sprintf(str, "SIGSEGV\n" " pc %08lx lr %08lx ctr %08lx msr %08lx\n" " xer %08lx cr %08lx fpscr %08lx\n" " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n" " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n" " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n" " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n" " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n" " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n" " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n" " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n", r->pc, r->lr, r->ctr, r->msr, r->xer, r->cr, r->fpscr, r->r0, r->r1, r->r2, r->r3, r->r4, r->r5, r->r6, r->r7, r->r8, r->r9, r->r10, r->r11, r->r12, segv_r[13], segv_r[14], segv_r[15], segv_r[16], segv_r[17], segv_r[18], segv_r[19], segv_r[20], segv_r[21], segv_r[22], segv_r[23], segv_r[24], segv_r[25], segv_r[26], segv_r[27], segv_r[28], segv_r[29], segv_r[30], segv_r[31]); VideoQuitFullScreen(); disable_debugger(false); debugger(str); exit(1); return; rti: // Restore volatile registers r->r0 = segv_r[0]; r->r1 = segv_r[1]; r->r2 = segv_r[2]; r->r3 = segv_r[3]; r->r4 = segv_r[4]; r->r5 = segv_r[5]; r->r6 = segv_r[6]; r->r7 = segv_r[7]; r->r8 = segv_r[8]; r->r9 = segv_r[9]; r->r10 = segv_r[10]; r->r11 = segv_r[11]; r->r12 = segv_r[12]; } /* * SIGILL handler */ #if !EMULATED_PPC asm void SheepShaver::sigill_invoc(register int sig, register void *arg, register vregs *r) { mflr r0 stw r0,8(r1) stwu r1,-56(r1) lwz r3,segv_r(r2) stmw r13,13*4(r3) mr r3,r5 bl sigill_handler lwz r3,segv_r(r2) lmw r13,13*4(r3) lwz r0,56+8(r1) mtlr r0 addi r1,r1,56 blr } #endif static void sigill_handler(vregs *r) { char str[256]; // Fetch volatile registers segv_r[0] = r->r0; segv_r[1] = r->r1; segv_r[2] = r->r2; segv_r[3] = r->r3; segv_r[4] = r->r4; segv_r[5] = r->r5; segv_r[6] = r->r6; segv_r[7] = r->r7; segv_r[8] = r->r8; segv_r[9] = r->r9; segv_r[10] = r->r10; segv_r[11] = r->r11; segv_r[12] = r->r12; // Get opcode and divide into fields uint32 opcode = *(uint32 *)r->pc; uint32 primop = opcode >> 26; uint32 exop = (opcode >> 1) & 0x3ff; uint32 ra = (opcode >> 16) & 0x1f; uint32 rb = (opcode >> 11) & 0x1f; uint32 rd = (opcode >> 21) & 0x1f; uint32 imm = opcode & 0xffff; // Fault in Mac ROM or RAM? bool mac_fault = (r->pc >= ROMBase) && (r->pc < (ROMBase + ROM_AREA_SIZE)) || (r->pc >= RAMBase) && (r->pc < (RAMBase + RAMSize)); if (mac_fault) { switch (primop) { case 9: // POWER instructions case 22: power_inst: sprintf(str, GetString(STR_POWER_INSTRUCTION_ERR), r->pc, segv_r[1], opcode); ErrorAlert(str); QuitEmulator(); return; case 31: switch (exop) { case 83: // mfmsr segv_r[rd] = 0xf072; r->pc += 4; goto rti; case 210: // mtsr case 242: // mtsrin case 306: // tlbie r->pc += 4; goto rti; case 339: { // mfspr int spr = ra | (rb << 5); switch (spr) { case 0: // MQ case 22: // DEC case 952: // MMCR0 case 953: // PMC1 case 954: // PMC2 case 955: // SIA case 956: // MMCR1 case 957: // PMC3 case 958: // PMC4 case 959: // SDA r->pc += 4; goto rti; case 25: // SDR1 segv_r[rd] = 0xdead001f; r->pc += 4; goto rti; case 287: // PVR segv_r[rd] = PVR; r->pc += 4; goto rti; } break; } case 467: { // mtspr int spr = ra | (rb << 5); switch (spr) { case 0: // MQ case 22: // DEC case 275: // SPRG3 case 528: // IBAT0U case 529: // IBAT0L case 530: // IBAT1U case 531: // IBAT1L case 532: // IBAT2U case 533: // IBAT2L case 534: // IBAT3U case 535: // IBAT3L case 536: // DBAT0U case 537: // DBAT0L case 538: // DBAT1U case 539: // DBAT1L case 540: // DBAT2U case 541: // DBAT2L case 542: // DBAT3U case 543: // DBAT3L case 952: // MMCR0 case 953: // PMC1 case 954: // PMC2 case 955: // SIA case 956: // MMCR1 case 957: // PMC3 case 958: // PMC4 case 959: // SDA r->pc += 4; goto rti; } break; } case 29: case 107: case 152: case 153: // POWER instructions case 184: case 216: case 217: case 248: case 264: case 277: case 331: case 360: case 363: case 488: case 531: case 537: case 541: case 664: case 665: case 696: case 728: case 729: case 760: case 920: case 921: case 952: goto power_inst; } } // In GUI mode, show error alert if (!PrefsFindBool("nogui")) { sprintf(str, GetString(STR_UNKNOWN_SEGV_ERR), r->pc, segv_r[24], segv_r[1], opcode); ErrorAlert(str); QuitEmulator(); return; } } // For all other errors, jump into debugger sprintf(str, "SIGILL\n" " pc %08lx lr %08lx ctr %08lx msr %08lx\n" " xer %08lx cr %08lx fpscr %08lx\n" " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n" " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n" " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n" " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n" " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n" " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n" " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n" " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n", r->pc, r->lr, r->ctr, r->msr, r->xer, r->cr, r->fpscr, r->r0, r->r1, r->r2, r->r3, r->r4, r->r5, r->r6, r->r7, r->r8, r->r9, r->r10, r->r11, r->r12, segv_r[13], segv_r[14], segv_r[15], segv_r[16], segv_r[17], segv_r[18], segv_r[19], segv_r[20], segv_r[21], segv_r[22], segv_r[23], segv_r[24], segv_r[25], segv_r[26], segv_r[27], segv_r[28], segv_r[29], segv_r[30], segv_r[31]); VideoQuitFullScreen(); disable_debugger(false); debugger(str); exit(1); return; rti: // Restore volatile registers r->r0 = segv_r[0]; r->r1 = segv_r[1]; r->r2 = segv_r[2]; r->r3 = segv_r[3]; r->r4 = segv_r[4]; r->r5 = segv_r[5]; r->r6 = segv_r[6]; r->r7 = segv_r[7]; r->r8 = segv_r[8]; r->r9 = segv_r[9]; r->r10 = segv_r[10]; r->r11 = segv_r[11]; r->r12 = segv_r[12]; } /* * Helpers to share 32-bit addressable data with MacOS */ bool SheepMem::Init(void) { // Delete old area area_id old_sheep_area = find_area(SHEEP_AREA_NAME); if (old_sheep_area > 0) delete_area(old_sheep_area); // Create area for SheepShaver data proc = base = 0x60000000; SheepMemArea = create_area(SHEEP_AREA_NAME, (void **)&base, B_BASE_ADDRESS, size, B_NO_LOCK, B_READ_AREA | B_WRITE_AREA); if (SheepMemArea < 0) return false; // Create read-only area with all bits set to 0 static const uint8 const_zero_page[4096] = {0,}; zero_page = const_zero_page; D(bug("SheepShaver area %ld at %p\n", SheepMemArea, base)); data = base + size; return true; } void SheepMem::Exit(void) { if (SheepMemArea >= 0) delete_area(SheepMemArea); } /* * Display error alert */ void ErrorAlert(const char *text) { if (PrefsFindBool("nogui")) { printf(GetString(STR_SHELL_ERROR_PREFIX), text); return; } char str[256]; sprintf(str, GetString(STR_GUI_ERROR_PREFIX), text); VideoQuitFullScreen(); BAlert *alert = new BAlert(GetString(STR_ERROR_ALERT_TITLE), str, GetString(STR_QUIT_BUTTON), NULL, NULL, B_WIDTH_AS_USUAL, B_STOP_ALERT); alert->Go(); } /* * Display warning alert */ void WarningAlert(const char *text) { if (PrefsFindBool("nogui")) { printf(GetString(STR_SHELL_WARNING_PREFIX), text); return; } char str[256]; sprintf(str, GetString(STR_GUI_WARNING_PREFIX), text); BAlert *alert = new BAlert(GetString(STR_WARNING_ALERT_TITLE), str, GetString(STR_OK_BUTTON), NULL, NULL, B_WIDTH_AS_USUAL, B_INFO_ALERT); alert->Go(); } /* * Display choice alert */ bool ChoiceAlert(const char *text, const char *pos, const char *neg) { char str[256]; sprintf(str, GetString(STR_GUI_WARNING_PREFIX), text); BAlert *alert = new BAlert(GetString(STR_WARNING_ALERT_TITLE), str, pos, neg, NULL, B_WIDTH_AS_USUAL, B_INFO_ALERT); return alert->Go() == 0; }
25.756944
271
0.678754
[ "object" ]
552218e9cd63588131b2e4eedcd8df580ef4f162
5,842
cpp
C++
src/scene/joint.cpp
Sangeun44/Half-Edge-Mesh
0ab055fd5aee275c64167ac2b5ae75278e9dc488
[ "MIT" ]
null
null
null
src/scene/joint.cpp
Sangeun44/Half-Edge-Mesh
0ab055fd5aee275c64167ac2b5ae75278e9dc488
[ "MIT" ]
null
null
null
src/scene/joint.cpp
Sangeun44/Half-Edge-Mesh
0ab055fd5aee275c64167ac2b5ae75278e9dc488
[ "MIT" ]
null
null
null
#include "joint.h" int Joint::id = -1; Joint::Joint(GLWidget277 *context): Drawable(context), thisID(), name(), parent(nullptr), children(std::vector<Joint*>()), position(), rotation(), joint_bindMatrix(), selected(false) { } GLenum Joint::drawMode() { return GL_LINES; } void Joint::setSelected(bool select) { selected = select; } int Joint::getID() const { return this->thisID; } bool Joint::getSelected() const { return selected; } void Joint::setName(const QString name) { setText(0, name); this->name = name; } void Joint::setPosition(const glm::vec3 pos) { this->position = pos; } void Joint::setID() { thisID = ++id; } void Joint::setParent(Joint* parent) { this->parent = parent; } void Joint::setChildren(Joint* child) { children.push_back(child); QTreeWidgetItem::addChild(child); } void Joint::setRotation(const glm::quat rotate) { this->rotation = rotate; } void Joint::setRotation(const glm::vec4 rot) { glm::quat quat_rot = glm::angleAxis(rot.x, glm::vec3(rot.y,rot.z,rot.w)); this->rotation = quat_rot; } QString Joint::getName() const { return name; } glm::vec3 Joint::getPosition() const { return position; } Joint* Joint::getParent() const { return parent; } std::vector<Joint*> Joint::getChildren() const { return children; } glm::quat Joint::getRotation() const { return rotation; } glm::mat4 Joint::getJoint_BindMatrix() const { return joint_bindMatrix; } glm::mat4 Joint::getLocalTrans() const { glm::vec4 col1 = glm::vec4(1,0,0,0); glm::vec4 col2 = glm::vec4(0,1,0,0); glm::vec4 col3 = glm::vec4(0,0,1,0); glm::vec4 pos_col = glm::vec4(position.x, position.y, position.z, 1); glm::mat4 translation_mat = glm::mat4(col1, col2, col3, pos_col); glm::mat4 rotation_mat = glm::mat4_cast(rotation); glm::mat4 localTransMat = translation_mat * rotation_mat; return localTransMat; } glm::mat4 Joint::traverse(Joint* joint, glm::mat4 overall){ if(joint->getParent() != nullptr) { Joint* parent = joint->getParent(); overall = parent->getOverallTrans() * overall; } return overall; } glm::mat4 Joint::getOverallTrans() { glm::mat4 curr = this->getLocalTrans(); return traverse(this, curr); } void Joint::setJoint_BindMatrix() { glm::mat4 overall = this->getOverallTrans(); glm::mat4 bind = glm::inverse(overall); this->joint_bindMatrix = bind; } void Joint::create() { //all vbo data std::vector<glm::vec3> col = std::vector<glm::vec3>(); std::vector<glm::vec4> pos = std::vector<glm::vec4>(); std::vector<GLuint> idx = std::vector<GLuint>(); //joint connections glm::vec3 yellow = glm::vec3(1,1,0); glm::vec3 red = glm::vec3(1,0,0); //joint circles glm::vec3 red_wheel = glm::vec3(1,0,0); glm::vec3 blue_wheel = glm::vec3(0,0,1); glm::vec3 green_wheel = glm::vec3(0,1,0); //if this joint is selected if(this->getSelected() == true) { red_wheel = glm::vec3(1,1,1); blue_wheel = glm::vec3(1,1,1); green_wheel = glm::vec3(1,1,1); } int index = 0; const float divisions = 20; float angle = 360/divisions; int numVerts = 0; glm::vec4 origin = glm::vec4(0,0,0,1); glm::vec4 curr_pos = this->getOverallTrans() * origin; glm::vec4 x = glm::vec4(origin.x, origin.y, origin.z + 0.5, origin.w); do { pos.push_back(this->getOverallTrans() * x); col.push_back(red_wheel); x = glm::rotateX(x, glm::radians(angle)); ++numVerts; } while(numVerts != divisions); do { idx.push_back(index); idx.push_back((++index) % numVerts); } while(index < numVerts); numVerts = 0; glm::vec4 y = glm::vec4(origin.x, origin.y, origin.z + 0.5, origin.w); do { pos.push_back(this->getOverallTrans() * y); col.push_back(blue_wheel); y = glm::rotateY(y, glm::radians(angle)); ++numVerts; } while(numVerts != divisions); do { idx.push_back(index); idx.push_back((++index) % numVerts + divisions); } while(index < numVerts + divisions); numVerts = 0; glm::vec4 z = glm::vec4(origin.x + 0.5, origin.y, origin.z, origin.w); do { pos.push_back(this->getOverallTrans() * z); col.push_back(green_wheel); z = glm::rotateZ(z, glm::radians(angle)); ++numVerts; } while(numVerts != divisions); do { idx.push_back(index); idx.push_back((++index) % numVerts + divisions + divisions); } while(index < numVerts + divisions + divisions); //create lines between joints. if this joint has a child if(this->getChildren().size() > 0) { std::vector<Joint*> curr_children = this->getChildren(); for(Joint* child : curr_children) { glm::vec4 vertRed_pos = curr_pos; glm::vec4 child_pos = glm::vec4(child->getOverallTrans() * origin); glm::vec4 vertPointYellow_pos = child_pos; pos.push_back(vertPointYellow_pos); col.push_back(yellow); idx.push_back(index); pos.push_back(vertRed_pos); col.push_back(red); idx.push_back(++index); } } count = idx.size(); generateIdx(); mp_context->glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, bufIdx); mp_context->glBufferData(GL_ELEMENT_ARRAY_BUFFER, idx.size() * sizeof(GLuint), idx.data(), GL_STATIC_DRAW); generatePos(); mp_context->glBindBuffer(GL_ARRAY_BUFFER, bufPos); mp_context->glBufferData(GL_ARRAY_BUFFER, pos.size() * sizeof(glm::vec4), pos.data(), GL_STATIC_DRAW); generateCol(); mp_context->glBindBuffer(GL_ARRAY_BUFFER, bufCol); mp_context->glBufferData(GL_ARRAY_BUFFER, col.size() * sizeof(glm::vec4), col.data(), GL_STATIC_DRAW); }
25.510917
182
0.623074
[ "vector" ]
552a992ea001aadcfb37c7fa30c88431142d5417
646
cpp
C++
0264. Ugly Number II/solution.cpp
Pluto-Zy/LeetCode
3bb39fc5c000b344fd8727883b095943bd29c247
[ "MIT" ]
null
null
null
0264. Ugly Number II/solution.cpp
Pluto-Zy/LeetCode
3bb39fc5c000b344fd8727883b095943bd29c247
[ "MIT" ]
null
null
null
0264. Ugly Number II/solution.cpp
Pluto-Zy/LeetCode
3bb39fc5c000b344fd8727883b095943bd29c247
[ "MIT" ]
null
null
null
class Solution { public: int nthUglyNumber(int n) { // 从已经生成的丑数中 *2 *3 *5 得到后续丑数 // 每个丑数都应乘 3 次 // 重点是对结果排序 // 使用 3 个指针,分别指向 3 种乘法当前工作到的整数 std::vector<int> dp(n); dp[0] = 1; auto _ptr_2 = 0, _ptr_3 = _ptr_2, _ptr_5 = _ptr_2; for (int i = 1; i < n; ++i) { int _temp_2 = dp[_ptr_2] * 2, _temp_3 = dp[_ptr_3] * 3, _temp_5 = dp[_ptr_5] * 5; dp[i] = std::min<int>({_temp_2, _temp_3, _temp_5}); if (dp[i] == _temp_2) ++_ptr_2; // cannot use `else if` here !!! if (dp[i] == _temp_3) ++_ptr_3; if (dp[i] == _temp_5) ++_ptr_5; } return dp[n - 1]; } };
26.916667
87
0.50774
[ "vector" ]
552c1fcf9dff7f6b7b0a1321925f2a0aea7952e0
6,259
cpp
C++
src/qnoesiswindow.cpp
ZeroPass/NoesisGui-Qt-Binding
4d8c6615d3e1578bbd77ba789416a5d5f72b043f
[ "MIT" ]
2
2018-01-15T15:24:10.000Z
2020-06-26T20:30:09.000Z
src/qnoesiswindow.cpp
ZeroPass/NoesisGui-Qt-Binding
4d8c6615d3e1578bbd77ba789416a5d5f72b043f
[ "MIT" ]
null
null
null
src/qnoesiswindow.cpp
ZeroPass/NoesisGui-Qt-Binding
4d8c6615d3e1578bbd77ba789416a5d5f72b043f
[ "MIT" ]
2
2018-08-28T08:45:47.000Z
2020-06-26T20:30:11.000Z
#include "qnoesiswindow.h" #include "qnsrenderdevice.h" #include <QDebug> #include <QTimer> #include <NsCore/PtrForward.h> #include <NsCore/HashMap.h> #include <NsCore/Ptr.h> using namespace Noesis; using namespace Noesis::Core; using namespace Noesis::Gui; using namespace Noesis::GUI; using namespace Noesis::Render; QNoesisWindow::QNoesisWindow(QWindow *parent) : QNoesisWindow(Ptr<IView>(), parent) {} QNoesisWindow::QNoesisWindow(FrameworkElement* content, QWindow* parent) : QNoesisWindow(CreateView(content), parent) {} QNoesisWindow::QNoesisWindow(const Ptr<IView>& view, QWindow* parent) : QWindow(parent), m_animating(false), m_frame(0) { setSurfaceType(QWindow::OpenGLSurface); setView(view); setAnimating(true); } QNoesisWindow::~QNoesisWindow() { m_ctx.reset(); m_vgctx.Reset(); /* Delete m_view */ // TODO: improve code below! QTimer* t = new QTimer; t->setSingleShot(true); connect(t, &QTimer::timeout, [t, v = m_view]() mutable { v.Reset(); // QOpenGlCntext should be deleted by now! t->deleteLater(); }); // Start timer // 1s interval, ensures that QOpenGlContext is deleted before m_view t->start(1000); } void QNoesisWindow::setView(const Ptr<IView>& view) { if(!view) return; m_view = view; m_view->SetSize(this->width(), this->height()); } Ptr<IView> QNoesisWindow::view() const { return m_view; } void QNoesisWindow::setVGOptions(const Noesis::VGOptions& opt) { m_vgopt = opt; } void QNoesisWindow::initialize() { glEnable(GL_MULTISAMPLE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Init VGContext Ptr<QNsRenderDevice> device = *new QNsRenderDevice; m_vgctx = Noesis::GUI::CreateVGContext(device.GetPtr(), m_vgopt); m_view->GetRenderer()->Init(m_vgctx.GetPtr()); } void QNoesisWindow::render() { m_view->Update(m_elapsed.elapsed() / 1000.0); Noesis::IRenderer* nsRenderer = m_view->GetRenderer(); nsRenderer->UpdateRenderTree(); // Render offscreen textures if (nsRenderer->NeedsOffscreen()) { nsRenderer->RenderOffscreen(); } // Restore state. This must be done per frame because NoesisGUI modifies the GPU state // TODO: improve this by adding a SaveState() and RestoreState() to GLRenderDevice glColorMask(true, true, true, true); glClearStencil(0); glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); // Update viewport const qreal pr = this->devicePixelRatio(); glViewport(0, 0, this->width() * pr, this->height() * pr); // Render View nsRenderer->Render(); glFlush(); glFinish(); m_frame++; } void QNoesisWindow::renderLater() { requestUpdate(); } bool QNoesisWindow::event(QEvent* e) { switch (e->type()) { case QEvent::UpdateRequest: renderNow(); return true; default: return QWindow::event(e); } } void QNoesisWindow::exposeEvent(QExposeEvent* e) { Q_UNUSED(e); if (isExposed()) { renderNow(); } } void QNoesisWindow::resizeEvent(QResizeEvent* e) { if(m_view) { const qreal pr = this->devicePixelRatio(); m_view->SetSize(e->size().width() * pr, e->size().height() * pr); } QWindow::resizeEvent(e); } void QNoesisWindow::mousePressEvent(QMouseEvent* e) { if(!m_view) return; if(e->button() & Qt::LeftButton) { m_view->MouseButtonDown(e->x(), e->y(), Noesis::MouseButton_Left); } else if(e->button() & Qt::RightButton) { m_view->MouseButtonDown(e->x(), e->y(), Noesis::MouseButton_Right); } else if(e->button() & Qt::MiddleButton) { m_view->MouseButtonDown(e->x(), e->y(), Noesis::MouseButton_Middle); } else if(e->button() & Qt::XButton1) { m_view->MouseButtonDown(e->x(), e->y(), Noesis::MouseButton_XButton1); } else if(e->button() & Qt::XButton2) { m_view->MouseButtonDown(e->x(), e->y(), Noesis::MouseButton_XButton2); } } void QNoesisWindow::mouseReleaseEvent(QMouseEvent* e) { if(!m_view) return; if(e->button() & Qt::LeftButton) { m_view->MouseButtonUp(e->x(), e->y(), Noesis::MouseButton_Left); } else if(e->button() & Qt::RightButton) { m_view->MouseButtonUp(e->x(), e->y(), Noesis::MouseButton_Right); } else if(e->button() & Qt::MiddleButton) { m_view->MouseButtonUp(e->x(), e->y(), Noesis::MouseButton_Middle); } else if(e->button() & Qt::XButton1) { m_view->MouseButtonUp(e->x(), e->y(), Noesis::MouseButton_XButton1); } else if(e->button() & Qt::XButton2) { m_view->MouseButtonUp(e->x(), e->y(), Noesis::MouseButton_XButton2); } } void QNoesisWindow::mouseDoubleClickEvent(QMouseEvent* e) { if(!m_view) return; if(e->button() & Qt::LeftButton) { m_view->MouseDoubleClick(e->x(), e->y(), Noesis::MouseButton_Left); } else if(e->button() & Qt::RightButton) { m_view->MouseDoubleClick(e->x(), e->y(), Noesis::MouseButton_Right); } else if(e->button() & Qt::MiddleButton) { m_view->MouseDoubleClick(e->x(), e->y(), Noesis::MouseButton_Middle); } else if(e->button() & Qt::XButton1) { m_view->MouseDoubleClick(e->x(), e->y(), Noesis::MouseButton_XButton1); } else if(e->button() & Qt::XButton2) { m_view->MouseDoubleClick(e->x(), e->y(), Noesis::MouseButton_XButton2); } } void QNoesisWindow::mouseMoveEvent(QMouseEvent* e) { if(m_view) { m_view->MouseMove(e->x(), e->y()); } } void QNoesisWindow::renderNow() { if (!isExposed() || !m_view) return; bool needsInitialize = false; if (!m_ctx) { m_ctx.reset(new QOpenGLContext(this)); m_ctx->setFormat(requestedFormat()); m_ctx->create(); needsInitialize = true; } m_ctx->makeCurrent(this); if (needsInitialize) { initializeOpenGLFunctions(); initialize(); m_elapsed.start(); } render(); m_ctx->swapBuffers(this); if (m_animating){ renderLater(); } } void QNoesisWindow::setAnimating(bool animating) { m_animating = animating; if (animating){ renderLater(); } }
23.530075
90
0.628215
[ "render" ]
55300edddab3eed65b4a2da09843c2cb5159ad8d
1,610
cpp
C++
src/MsgSaver.cpp
whunmr/msgtest
0ada56dce0c23d78018b5667ea3ccf6a7ea3bae0
[ "Apache-2.0" ]
2
2017-03-09T07:22:38.000Z
2020-03-31T00:42:22.000Z
src/MsgSaver.cpp
whunmr/msgtest
0ada56dce0c23d78018b5667ea3ccf6a7ea3bae0
[ "Apache-2.0" ]
1
2017-04-11T06:29:33.000Z
2017-04-11T06:29:33.000Z
src/MsgSaver.cpp
whunmr/msgtest
0ada56dce0c23d78018b5667ea3ccf6a7ea3bae0
[ "Apache-2.0" ]
2
2017-10-26T11:49:20.000Z
2018-09-12T01:54:11.000Z
#include <msgtest/MsgSaver.h> MSGTEST_NS_START const void* PayloadAddressTempHolder::payloadAddr_; //////////////////////////////////////////////////////////////////////////// MsgSaverBase::MsgSaverBase() : payload_(nullptr) , len_(0) , payload_mem_addr_(&payload_) , len_mem_addr_(&len_) { /**/ } MsgSaverBase::~MsgSaverBase() { //Mock predicate object will be copy construct and saved, //we need to pass the address of the payload_ into the copyed Saver, //then the original saver and the copyed saver both will see the same payload. bool isCopyConstructedPredicate = *payload_mem_addr_ != &payload_; if ( ! isCopyConstructedPredicate) { free(*payload_mem_addr_); *payload_mem_addr_ = nullptr; } } //////////////////////////////////////////////////////////////////////////// //Called by through ::mockcpp::checkWith( bool(*)(T) ) bool MsgSaverBase::operator()(size_t len) { assert((*payload_mem_addr_ == nullptr) && "Can only save one message in one instance."); assert((PayloadAddressTempHolder::payloadAddr_ != nullptr) && "Should use checkWith(globalPayloadAddressTempHolder). to record msg addr first."); if (len > 0) { *payload_mem_addr_ = malloc(len); if (*payload_mem_addr_ != nullptr) { memcpy(*payload_mem_addr_, PayloadAddressTempHolder::payloadAddr_, len); *len_mem_addr_ = len; } } return true; } MSGTEST_NS_END
35.777778
153
0.554658
[ "object" ]
553601b412c3f56bb88589a7c789d9c1b5284617
959
cpp
C++
src/Bridge.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
null
null
null
src/Bridge.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
1
2019-08-14T13:36:33.000Z
2019-08-14T13:36:33.000Z
src/Bridge.cpp
luka1199/bridges
117c91d714aa19fa4c5138b032583e3efe93d142
[ "MIT" ]
null
null
null
// Copyright 2018, // Author: Luka Steinbach <luka.steinbach@gmx.de> #include "./Bridge.h" #include <string> #include <vector> // _____________________________________________________________________________ Bridge::Bridge(int x, int y) : Field(x, y) { _weight = 0; _directionHor = false; _symbol = _symbolsHor[0]; } // _____________________________________________________________________________ Bridge::~Bridge() {} // _____________________________________________________________________________ void Bridge::addWeight() { _weight = (_weight + 1) % 3; if (_directionHor) { _symbol = _symbolsHor[_weight]; } else { _symbol = _symbolsVer[_weight]; } } // _____________________________________________________________________________ int Bridge::getCount() const { return _weight; } // _____________________________________________________________________________ std::string Bridge::getType() const { return "type_bridge"; }
25.918919
80
0.773723
[ "vector" ]
5537b7f928531126affd7601c46438543581d6d0
167
cpp
C++
tests/priority_queue.cpp
justcppdev/priority_queue
a9ec169417162a559afabc1ef04dd72e010f9504
[ "MIT" ]
null
null
null
tests/priority_queue.cpp
justcppdev/priority_queue
a9ec169417162a559afabc1ef04dd72e010f9504
[ "MIT" ]
null
null
null
tests/priority_queue.cpp
justcppdev/priority_queue
a9ec169417162a559afabc1ef04dd72e010f9504
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <vector> #include "priority_queue.hpp" TEST_CASE("simple test", "") { priority_queue_t<int> queue; REQUIRE( queue.empty() ); }
15.181818
32
0.670659
[ "vector" ]
554036fffe3111e6179f49e5252bde2935e394a8
828
cc
C++
leet_code/Shortest_Unsorted_Continuous_Subarray/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
1
2020-04-11T22:04:23.000Z
2020-04-11T22:04:23.000Z
leet_code/Shortest_Unsorted_Continuous_Subarray/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
leet_code/Shortest_Unsorted_Continuous_Subarray/solve.cc
ldy121/algorithm
7939cb4c15e2bc655219c934f00c2bb74ddb4eec
[ "Apache-2.0" ]
null
null
null
class Solution { private : const int invalid = -1; public: int findUnsortedSubarray(vector<int>& nums) { auto min = *nums.rbegin(), max = *nums.begin(); auto idx = 0; auto left = invalid, right = invalid; idx = 0; for_each(nums.begin(), nums.end(), [&max, &right, &idx](auto val) { if (val >= max) { max = val; } else { right = idx; } ++idx; }); idx = nums.size() - 1; for_each(nums.rbegin(), nums.rend(), [&min, &left, &idx](auto val) { if (val <= min) { min = val; } else { left = idx; } --idx; }); return (left == invalid) ? 0 : (right - left + 1); } };
25.090909
76
0.396135
[ "vector" ]
55468443aa54fa06eb2345702e44bc83ee5ed866
65,800
cpp
C++
source/Lib/TLibDecoder/SEIread.cpp
AjayKumarSahu20/SHVC_2
2ce6fe131ab12eadf8d51b3408081529b5ad9366
[ "BSD-3-Clause" ]
2
2019-12-25T07:41:29.000Z
2021-11-25T11:50:12.000Z
source/Lib/TLibDecoder/SEIread.cpp
AjayKumarSahu20/SHVC_2
2ce6fe131ab12eadf8d51b3408081529b5ad9366
[ "BSD-3-Clause" ]
null
null
null
source/Lib/TLibDecoder/SEIread.cpp
AjayKumarSahu20/SHVC_2
2ce6fe131ab12eadf8d51b3408081529b5ad9366
[ "BSD-3-Clause" ]
null
null
null
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2014, ITU/ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ITU/ISO/IEC 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. */ /** \file SEIread.cpp \brief reading functionality for SEI messages */ #include "TLibCommon/CommonDef.h" #include "TLibCommon/TComBitStream.h" #include "TLibCommon/SEI.h" #include "TLibCommon/TComSlice.h" #include "SyntaxElementParser.h" #include "SEIread.h" //! \ingroup TLibDecoder //! \{ #if ENC_DEC_TRACE Void xTraceSEIHeader() { fprintf( g_hTrace, "=========== SEI message ===========\n"); } Void xTraceSEIMessageType(SEI::PayloadType payloadType) { switch (payloadType) { case SEI::DECODED_PICTURE_HASH: fprintf( g_hTrace, "=========== Decoded picture hash SEI message ===========\n"); break; case SEI::USER_DATA_UNREGISTERED: fprintf( g_hTrace, "=========== User Data Unregistered SEI message ===========\n"); break; case SEI::ACTIVE_PARAMETER_SETS: fprintf( g_hTrace, "=========== Active Parameter sets SEI message ===========\n"); break; case SEI::BUFFERING_PERIOD: fprintf( g_hTrace, "=========== Buffering period SEI message ===========\n"); break; case SEI::PICTURE_TIMING: fprintf( g_hTrace, "=========== Picture timing SEI message ===========\n"); break; case SEI::RECOVERY_POINT: fprintf( g_hTrace, "=========== Recovery point SEI message ===========\n"); break; case SEI::FRAME_PACKING: fprintf( g_hTrace, "=========== Frame Packing Arrangement SEI message ===========\n"); break; case SEI::DISPLAY_ORIENTATION: fprintf( g_hTrace, "=========== Display Orientation SEI message ===========\n"); break; case SEI::TEMPORAL_LEVEL0_INDEX: fprintf( g_hTrace, "=========== Temporal Level Zero Index SEI message ===========\n"); break; case SEI::REGION_REFRESH_INFO: fprintf( g_hTrace, "=========== Gradual Decoding Refresh Information SEI message ===========\n"); break; case SEI::DECODING_UNIT_INFO: fprintf( g_hTrace, "=========== Decoding Unit Information SEI message ===========\n"); break; case SEI::TONE_MAPPING_INFO: fprintf( g_hTrace, "===========Tone Mapping Info SEI message ===========\n"); break; #if P0050_KNEE_FUNCTION_SEI case SEI::KNEE_FUNCTION_INFO: fprintf( g_hTrace, "=========== Knee Function Information SEI message ===========\n"); break; #endif #if Q0074_COLOUR_REMAPPING_SEI case SEI::COLOUR_REMAPPING_INFO: fprintf( g_hTrace, "===========Colour Remapping Information SEI message ===========\n"); break; #endif case SEI::SOP_DESCRIPTION: fprintf( g_hTrace, "=========== SOP Description SEI message ===========\n"); break; case SEI::SCALABLE_NESTING: fprintf( g_hTrace, "=========== Scalable Nesting SEI message ===========\n"); break; #if SVC_EXTENSION #if LAYERS_NOT_PRESENT_SEI case SEI::LAYERS_NOT_PRESENT: fprintf( g_hTrace, "=========== Layers Present SEI message ===========\n"); break; #endif #if N0383_IL_CONSTRAINED_TILE_SETS_SEI case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS: fprintf( g_hTrace, "=========== Inter Layer Constrained Tile Sets SEI message ===========\n"); break; #endif #if SUB_BITSTREAM_PROPERTY_SEI case SEI::SUB_BITSTREAM_PROPERTY: fprintf( g_hTrace, "=========== Sub-bitstream property SEI message ===========\n"); break; #endif #if O0164_MULTI_LAYER_HRD case SEI::BSP_NESTING: fprintf( g_hTrace, "=========== Bitstream parition nesting SEI message ===========\n"); break; case SEI::BSP_INITIAL_ARRIVAL_TIME: fprintf( g_hTrace, "=========== Bitstream parition initial arrival time SEI message ===========\n"); break; #if !REMOVE_BSP_HRD_SEI case SEI::BSP_HRD: fprintf( g_hTrace, "=========== Bitstream parition HRD parameters SEI message ===========\n"); break; #endif #endif #if Q0078_ADD_LAYER_SETS case SEI::OUTPUT_LAYER_SET_NESTING: fprintf(g_hTrace, "=========== Output layer set nesting SEI message ===========\n"); break; case SEI::VPS_REWRITING: fprintf(g_hTrace, "=========== VPS rewriting SEI message ===========\n"); break; #endif #endif //SVC_EXTENSION default: fprintf( g_hTrace, "=========== Unknown SEI message ===========\n"); break; } } #endif /** * unmarshal a single SEI message from bitstream bs */ #if LAYERS_NOT_PRESENT_SEI void SEIReader::parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps) #else void SEIReader::parseSEImessage(TComInputBitstream* bs, SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps) #endif { setBitstream(bs); assert(!m_pcBitstream->getNumBitsUntilByteAligned()); do { #if LAYERS_NOT_PRESENT_SEI xReadSEImessage(seis, nalUnitType, vps, sps); #else xReadSEImessage(seis, nalUnitType, sps); #endif /* SEI messages are an integer number of bytes, something has failed * in the parsing if bitstream not byte-aligned */ assert(!m_pcBitstream->getNumBitsUntilByteAligned()); } while (m_pcBitstream->getNumBitsLeft() > 8); UInt rbspTrailingBits; READ_CODE(8, rbspTrailingBits, "rbsp_trailing_bits"); assert(rbspTrailingBits == 0x80); } #if O0164_MULTI_LAYER_HRD #if LAYERS_NOT_PRESENT_SEI Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, const SEIScalableNesting *nestingSei, const SEIBspNesting *bspNestingSei) #else Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps, const SEIScalableNesting *nestingSei) #endif #else #if LAYERS_NOT_PRESENT_SEI Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps) #else Void SEIReader::xReadSEImessage(SEIMessages& seis, const NalUnitType nalUnitType, TComSPS *sps) #endif #endif { #if ENC_DEC_TRACE xTraceSEIHeader(); #endif Int payloadType = 0; UInt val = 0; do { READ_CODE (8, val, "payload_type"); payloadType += val; } while (val==0xFF); UInt payloadSize = 0; do { READ_CODE (8, val, "payload_size"); payloadSize += val; } while (val==0xFF); #if ENC_DEC_TRACE xTraceSEIMessageType((SEI::PayloadType)payloadType); #endif /* extract the payload for this single SEI message. * This allows greater safety in erroneous parsing of an SEI message * from affecting subsequent messages. * After parsing the payload, bs needs to be restored as the primary * bitstream. */ TComInputBitstream *bs = getBitstream(); setBitstream(bs->extractSubstream(payloadSize * 8)); SEI *sei = NULL; if(nalUnitType == NAL_UNIT_PREFIX_SEI) { switch (payloadType) { case SEI::USER_DATA_UNREGISTERED: sei = new SEIuserDataUnregistered; xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize); break; case SEI::ACTIVE_PARAMETER_SETS: sei = new SEIActiveParameterSets; xParseSEIActiveParameterSets((SEIActiveParameterSets&) *sei, payloadSize); break; case SEI::DECODING_UNIT_INFO: if (!sps) { printf ("Warning: Found Decoding unit SEI message, but no active SPS is available. Ignoring."); } else { sei = new SEIDecodingUnitInfo; #if VPS_VUI_BSP_HRD_PARAMS xParseSEIDecodingUnitInfo((SEIDecodingUnitInfo&) *sei, payloadSize, sps, nestingSei, bspNestingSei, vps); #else xParseSEIDecodingUnitInfo((SEIDecodingUnitInfo&) *sei, payloadSize, sps); #endif } break; case SEI::BUFFERING_PERIOD: if (!sps) { printf ("Warning: Found Buffering period SEI message, but no active SPS is available. Ignoring."); } else { sei = new SEIBufferingPeriod; #if VPS_VUI_BSP_HRD_PARAMS xParseSEIBufferingPeriod((SEIBufferingPeriod&) *sei, payloadSize, sps, nestingSei, bspNestingSei, vps); #else xParseSEIBufferingPeriod((SEIBufferingPeriod&) *sei, payloadSize, sps); #endif } break; case SEI::PICTURE_TIMING: if (!sps) { printf ("Warning: Found Picture timing SEI message, but no active SPS is available. Ignoring."); } else { sei = new SEIPictureTiming; #if VPS_VUI_BSP_HRD_PARAMS xParseSEIPictureTiming((SEIPictureTiming&)*sei, payloadSize, sps, nestingSei, bspNestingSei, vps); #else xParseSEIPictureTiming((SEIPictureTiming&)*sei, payloadSize, sps); #endif } break; case SEI::RECOVERY_POINT: sei = new SEIRecoveryPoint; xParseSEIRecoveryPoint((SEIRecoveryPoint&) *sei, payloadSize); break; case SEI::FRAME_PACKING: sei = new SEIFramePacking; xParseSEIFramePacking((SEIFramePacking&) *sei, payloadSize); break; case SEI::DISPLAY_ORIENTATION: sei = new SEIDisplayOrientation; xParseSEIDisplayOrientation((SEIDisplayOrientation&) *sei, payloadSize); break; case SEI::TEMPORAL_LEVEL0_INDEX: sei = new SEITemporalLevel0Index; xParseSEITemporalLevel0Index((SEITemporalLevel0Index&) *sei, payloadSize); break; case SEI::REGION_REFRESH_INFO: sei = new SEIGradualDecodingRefreshInfo; xParseSEIGradualDecodingRefreshInfo((SEIGradualDecodingRefreshInfo&) *sei, payloadSize); break; case SEI::TONE_MAPPING_INFO: sei = new SEIToneMappingInfo; xParseSEIToneMappingInfo((SEIToneMappingInfo&) *sei, payloadSize); break; #if P0050_KNEE_FUNCTION_SEI case SEI::KNEE_FUNCTION_INFO: sei = new SEIKneeFunctionInfo; xParseSEIKneeFunctionInfo((SEIKneeFunctionInfo&) *sei, payloadSize); break; #endif #if Q0074_COLOUR_REMAPPING_SEI case SEI::COLOUR_REMAPPING_INFO: sei = new SEIColourRemappingInfo; xParseSEIColourRemappingInfo((SEIColourRemappingInfo&) *sei, payloadSize); break; #endif case SEI::SOP_DESCRIPTION: sei = new SEISOPDescription; xParseSEISOPDescription((SEISOPDescription&) *sei, payloadSize); break; case SEI::SCALABLE_NESTING: sei = new SEIScalableNesting; #if LAYERS_NOT_PRESENT_SEI xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, vps, sps); #else xParseSEIScalableNesting((SEIScalableNesting&) *sei, nalUnitType, payloadSize, sps); #endif break; #if SVC_EXTENSION #if LAYERS_NOT_PRESENT_SEI case SEI::LAYERS_NOT_PRESENT: if (!vps) { printf ("Warning: Found Layers not present SEI message, but no active VPS is available. Ignoring."); } else { sei = new SEILayersNotPresent; xParseSEILayersNotPresent((SEILayersNotPresent&) *sei, payloadSize, vps); } break; #endif #if N0383_IL_CONSTRAINED_TILE_SETS_SEI case SEI::INTER_LAYER_CONSTRAINED_TILE_SETS: sei = new SEIInterLayerConstrainedTileSets; xParseSEIInterLayerConstrainedTileSets((SEIInterLayerConstrainedTileSets&) *sei, payloadSize); break; #endif #if SUB_BITSTREAM_PROPERTY_SEI case SEI::SUB_BITSTREAM_PROPERTY: sei = new SEISubBitstreamProperty; #if OLS_IDX_CHK xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei, vps); #else xParseSEISubBitstreamProperty((SEISubBitstreamProperty&) *sei); #endif break; #endif #if O0164_MULTI_LAYER_HRD case SEI::BSP_NESTING: sei = new SEIBspNesting; #if LAYERS_NOT_PRESENT_SEI xParseSEIBspNesting((SEIBspNesting&) *sei, nalUnitType, vps, sps, *nestingSei); #else xParseSEIBspNesting((SEIBspNesting&) *sei, nalUnitType, sps, *nestingSei); #endif break; case SEI::BSP_INITIAL_ARRIVAL_TIME: sei = new SEIBspInitialArrivalTime; xParseSEIBspInitialArrivalTime((SEIBspInitialArrivalTime&) *sei, vps, sps, *nestingSei, *bspNestingSei); break; #if !REMOVE_BSP_HRD_SEI case SEI::BSP_HRD: sei = new SEIBspHrd; xParseSEIBspHrd((SEIBspHrd&) *sei, sps, *nestingSei); break; #endif #endif #if Q0078_ADD_LAYER_SETS case SEI::OUTPUT_LAYER_SET_NESTING: sei = new SEIOutputLayerSetNesting; #if LAYERS_NOT_PRESENT_SEI xParseSEIOutputLayerSetNesting((SEIOutputLayerSetNesting&)*sei, nalUnitType, vps, sps); #else xParseSEIOutputLayerSetNesting((SEIOutputLayerSetNesting&)*sei, nalUnitType, sps); #endif break; case SEI::VPS_REWRITING: sei = new SEIVPSRewriting; xParseSEIVPSRewriting((SEIVPSRewriting&)*sei); break; #endif #if Q0189_TMVP_CONSTRAINTS case SEI::TMVP_CONSTRAINTS: sei = new SEITMVPConstrains; xParseSEITMVPConstraints((SEITMVPConstrains&) *sei, payloadSize); break; #endif #if Q0247_FRAME_FIELD_INFO case SEI::FRAME_FIELD_INFO: sei = new SEIFrameFieldInfo; xParseSEIFrameFieldInfo ((SEIFrameFieldInfo&) *sei, payloadSize); break; #endif #endif //SVC_EXTENSION break; default: for (UInt i = 0; i < payloadSize; i++) { UInt seiByte; READ_CODE (8, seiByte, "unknown prefix SEI payload byte"); } printf ("Unknown prefix SEI message (payloadType = %d) was found!\n", payloadType); } } else { switch (payloadType) { case SEI::USER_DATA_UNREGISTERED: sei = new SEIuserDataUnregistered; xParseSEIuserDataUnregistered((SEIuserDataUnregistered&) *sei, payloadSize); break; case SEI::DECODED_PICTURE_HASH: sei = new SEIDecodedPictureHash; xParseSEIDecodedPictureHash((SEIDecodedPictureHash&) *sei, payloadSize); break; default: for (UInt i = 0; i < payloadSize; i++) { UInt seiByte; READ_CODE (8, seiByte, "unknown suffix SEI payload byte"); } printf ("Unknown suffix SEI message (payloadType = %d) was found!\n", payloadType); } } if (sei != NULL) { seis.push_back(sei); } /* By definition the underlying bitstream terminates in a byte-aligned manner. * 1. Extract all bar the last MIN(bitsremaining,nine) bits as reserved_payload_extension_data * 2. Examine the final 8 bits to determine the payload_bit_equal_to_one marker * 3. Extract the remainingreserved_payload_extension_data bits. * * If there are fewer than 9 bits available, extract them. */ Int payloadBitsRemaining = getBitstream()->getNumBitsLeft(); if (payloadBitsRemaining) /* more_data_in_payload() */ { for (; payloadBitsRemaining > 9; payloadBitsRemaining--) { UInt reservedPayloadExtensionData; READ_CODE (1, reservedPayloadExtensionData, "reserved_payload_extension_data"); } /* 2 */ Int finalBits = getBitstream()->peekBits(payloadBitsRemaining); Int finalPayloadBits = 0; for (Int mask = 0xff; finalBits & (mask >> finalPayloadBits); finalPayloadBits++) { continue; } /* 3 */ for (; payloadBitsRemaining > 9 - finalPayloadBits; payloadBitsRemaining--) { UInt reservedPayloadExtensionData; READ_FLAG (reservedPayloadExtensionData, "reserved_payload_extension_data"); } UInt dummy; READ_FLAG (dummy, "payload_bit_equal_to_one"); payloadBitsRemaining--; while (payloadBitsRemaining) { READ_FLAG (dummy, "payload_bit_equal_to_zero"); payloadBitsRemaining--; } } /* restore primary bitstream for sei_message */ getBitstream()->deleteFifo(); delete getBitstream(); setBitstream(bs); } #if P0138_USE_ALT_CPB_PARAMS_FLAG /** * Check if SEI message contains payload extension */ Bool SEIReader::xPayloadExtensionPresent() { Int payloadBitsRemaining = getBitstream()->getNumBitsLeft(); Bool payloadExtensionPresent = false; if (payloadBitsRemaining > 8) { payloadExtensionPresent = true; } else { Int finalBits = getBitstream()->peekBits(payloadBitsRemaining); while (payloadBitsRemaining && (finalBits & 1) == 0) { payloadBitsRemaining--; finalBits >>= 1; } payloadBitsRemaining--; if (payloadBitsRemaining > 0) { payloadExtensionPresent = true; } } return payloadExtensionPresent; } #endif /** * parse bitstream bs and unpack a user_data_unregistered SEI message * of payloasSize bytes into sei. */ Void SEIReader::xParseSEIuserDataUnregistered(SEIuserDataUnregistered &sei, UInt payloadSize) { assert(payloadSize >= 16); UInt val; for (UInt i = 0; i < 16; i++) { READ_CODE (8, val, "uuid_iso_iec_11578"); sei.uuid_iso_iec_11578[i] = val; } sei.userDataLength = payloadSize - 16; if (!sei.userDataLength) { sei.userData = 0; return; } sei.userData = new UChar[sei.userDataLength]; for (UInt i = 0; i < sei.userDataLength; i++) { READ_CODE (8, val, "user_data" ); sei.userData[i] = val; } } /** * parse bitstream bs and unpack a decoded picture hash SEI message * of payloadSize bytes into sei. */ Void SEIReader::xParseSEIDecodedPictureHash(SEIDecodedPictureHash& sei, UInt /*payloadSize*/) { UInt val; READ_CODE (8, val, "hash_type"); sei.method = static_cast<SEIDecodedPictureHash::Method>(val); for(Int yuvIdx = 0; yuvIdx < 3; yuvIdx++) { if(SEIDecodedPictureHash::MD5 == sei.method) { for (UInt i = 0; i < 16; i++) { READ_CODE(8, val, "picture_md5"); sei.digest[yuvIdx][i] = val; } } else if(SEIDecodedPictureHash::CRC == sei.method) { READ_CODE(16, val, "picture_crc"); sei.digest[yuvIdx][0] = val >> 8 & 0xFF; sei.digest[yuvIdx][1] = val & 0xFF; } else if(SEIDecodedPictureHash::CHECKSUM == sei.method) { READ_CODE(32, val, "picture_checksum"); sei.digest[yuvIdx][0] = (val>>24) & 0xff; sei.digest[yuvIdx][1] = (val>>16) & 0xff; sei.digest[yuvIdx][2] = (val>>8) & 0xff; sei.digest[yuvIdx][3] = val & 0xff; } } } Void SEIReader::xParseSEIActiveParameterSets(SEIActiveParameterSets& sei, UInt /*payloadSize*/) { UInt val; READ_CODE(4, val, "active_video_parameter_set_id"); sei.activeVPSId = val; READ_FLAG( val, "self_contained_cvs_flag"); sei.m_selfContainedCvsFlag = val ? true : false; READ_FLAG( val, "no_parameter_set_update_flag"); sei.m_noParameterSetUpdateFlag = val ? true : false; READ_UVLC( val, "num_sps_ids_minus1"); sei.numSpsIdsMinus1 = val; sei.activeSeqParameterSetId.resize(sei.numSpsIdsMinus1 + 1); #if R0247_SEI_ACTIVE sei.layerSpsIdx.resize(sei.numSpsIdsMinus1 + 1); #endif for (Int i=0; i < (sei.numSpsIdsMinus1 + 1); i++) { READ_UVLC(val, "active_seq_parameter_set_id"); sei.activeSeqParameterSetId[i] = val; } #if R0247_SEI_ACTIVE for (Int i=1; i < (sei.numSpsIdsMinus1 + 1); i++) { READ_UVLC(val, "layer_sps_idx"); sei.layerSpsIdx[i] = val; } #endif xParseByteAlign(); } #if VPS_VUI_BSP_HRD_PARAMS Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt /*payloadSize*/, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps) #else Void SEIReader::xParseSEIDecodingUnitInfo(SEIDecodingUnitInfo& sei, UInt /*payloadSize*/, TComSPS *sps) #endif { UInt val; READ_UVLC(val, "decoding_unit_idx"); sei.m_decodingUnitIdx = val; #if VPS_VUI_BSP_HRD_PARAMS TComHRD *hrd; if( bspNestingSei ) // If DU info SEI contained inside a BSP nesting SEI message { assert( nestingSei ); Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx; Int seiOlsIdx = bspNestingSei->m_seiOlsIdx; Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1; Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1; std::vector<Int> hrdIdx(maxValues, 0); std::vector<TComHRD *> hrdVec; std::vector<Int> syntaxElemLen(maxValues, 0); for(Int i = 0; i < maxValues; i++) { hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx); hrdVec.push_back(vps->getBspHrd(hrdIdx[i])); syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1; if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) ) { assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23 } if( i > 0 ) { assert( hrdVec[i]->getSubPicCpbParamsPresentFlag() == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() ); assert( hrdVec[i]->getSubPicCpbParamsInPicTimingSEIFlag() == hrdVec[i-1]->getSubPicCpbParamsInPicTimingSEIFlag() ); assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1() == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() ); // To be done: Check CpbDpbDelaysPresentFlag } } hrd = hrdVec[0]; } else { TComVUI *vui = sps->getVuiParameters(); hrd = vui->getHrdParameters(); } #else TComVUI *vui = sps->getVuiParameters(); TComHrd *hrd = vui->getHrdParameters(); #endif if(hrd->getSubPicCpbParamsInPicTimingSEIFlag()) { READ_CODE( ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), val, "du_spt_cpb_removal_delay"); sei.m_duSptCpbRemovalDelay = val; } else { sei.m_duSptCpbRemovalDelay = 0; } READ_FLAG( val, "dpb_output_du_delay_present_flag"); sei.m_dpbOutputDuDelayPresentFlag = val ? true : false; if(sei.m_dpbOutputDuDelayPresentFlag) { READ_CODE(hrd->getDpbOutputDelayDuLengthMinus1() + 1, val, "pic_spt_dpb_output_du_delay"); sei.m_picSptDpbOutputDuDelay = val; } xParseByteAlign(); } #if VPS_VUI_BSP_HRD_PARAMS Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt /*payloadSize*/, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps) #else Void SEIReader::xParseSEIBufferingPeriod(SEIBufferingPeriod& sei, UInt /*payloadSize*/, TComSPS *sps) #endif { Int i, nalOrVcl; UInt code; #if VPS_VUI_BSP_HRD_PARAMS TComHRD *pHRD; if( bspNestingSei ) // If BP SEI contained inside a BSP nesting SEI message { assert( nestingSei ); Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx; Int seiOlsIdx = bspNestingSei->m_seiOlsIdx; Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1; Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1; std::vector<Int> hrdIdx(maxValues, 0); std::vector<TComHRD *> hrdVec; std::vector<Int> syntaxElemLen(maxValues, 0); for(i = 0; i < maxValues; i++) { hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx); hrdVec.push_back(vps->getBspHrd(hrdIdx[i])); syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1; if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) ) { assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23 } if( i > 0 ) { assert( hrdVec[i]->getCpbRemovalDelayLengthMinus1() == hrdVec[i-1]->getCpbRemovalDelayLengthMinus1() ); assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1() == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() ); assert( hrdVec[i]->getSubPicCpbParamsPresentFlag() == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() ); } } pHRD = hrdVec[i]; } else { TComVUI *vui = sps->getVuiParameters(); pHRD = vui->getHrdParameters(); } // To be done: When contained in an BSP HRD SEI message, the hrd structure is to be chosen differently. #else TComVUI *pVUI = sps->getVuiParameters(); TComHRD *pHRD = pVUI->getHrdParameters(); #endif READ_UVLC( code, "bp_seq_parameter_set_id" ); sei.m_bpSeqParameterSetId = code; if( !pHRD->getSubPicCpbParamsPresentFlag() ) { READ_FLAG( code, "irap_cpb_params_present_flag" ); sei.m_rapCpbParamsPresentFlag = code; } if( sei.m_rapCpbParamsPresentFlag ) { READ_CODE( pHRD->getCpbRemovalDelayLengthMinus1() + 1, code, "cpb_delay_offset" ); sei.m_cpbDelayOffset = code; READ_CODE( pHRD->getDpbOutputDelayLengthMinus1() + 1, code, "dpb_delay_offset" ); sei.m_dpbDelayOffset = code; } //read splicing flag and cpb_removal_delay_delta READ_FLAG( code, "concatenation_flag"); sei.m_concatenationFlag = code; READ_CODE( ( pHRD->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_delta_minus1" ); sei.m_auCpbRemovalDelayDelta = code + 1; for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ ) { if( ( ( nalOrVcl == 0 ) && ( pHRD->getNalHrdParametersPresentFlag() ) ) || ( ( nalOrVcl == 1 ) && ( pHRD->getVclHrdParametersPresentFlag() ) ) ) { for( i = 0; i < ( pHRD->getCpbCntMinus1( 0 ) + 1 ); i ++ ) { READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_cpb_removal_delay" ); sei.m_initialCpbRemovalDelay[i][nalOrVcl] = code; READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_cpb_removal_delay_offset" ); sei.m_initialCpbRemovalDelayOffset[i][nalOrVcl] = code; if( pHRD->getSubPicCpbParamsPresentFlag() || sei.m_rapCpbParamsPresentFlag ) { READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_alt_cpb_removal_delay" ); sei.m_initialAltCpbRemovalDelay[i][nalOrVcl] = code; READ_CODE( ( pHRD->getInitialCpbRemovalDelayLengthMinus1() + 1 ) , code, "initial_alt_cpb_removal_delay_offset" ); sei.m_initialAltCpbRemovalDelayOffset[i][nalOrVcl] = code; } } } } #if P0138_USE_ALT_CPB_PARAMS_FLAG sei.m_useAltCpbParamsFlag = false; sei.m_useAltCpbParamsFlagPresent = false; if (xPayloadExtensionPresent()) { READ_FLAG (code, "use_alt_cpb_params_flag"); sei.m_useAltCpbParamsFlag = code; sei.m_useAltCpbParamsFlagPresent = true; } #endif xParseByteAlign(); } #if VPS_VUI_BSP_HRD_PARAMS Void SEIReader::xParseSEIPictureTiming(SEIPictureTiming& sei, UInt /*payloadSize*/, TComSPS *sps, const SEIScalableNesting* nestingSei, const SEIBspNesting* bspNestingSei, TComVPS *vps) #else Void SEIReader::xParseSEIPictureTiming(SEIPictureTiming& sei, UInt /*payloadSize*/, TComSPS *sps) #endif { Int i; UInt code; #if VPS_VUI_BSP_HRD_PARAMS TComHRD *hrd; TComVUI *vui = sps->getVuiParameters(); if( bspNestingSei ) // If BP SEI contained inside a BSP nesting SEI message { assert( nestingSei ); Int psIdx = bspNestingSei->m_seiPartitioningSchemeIdx; Int seiOlsIdx = bspNestingSei->m_seiOlsIdx; Int maxTemporalId = nestingSei->m_nestingMaxTemporalIdPlus1[0] - 1; Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1; std::vector<Int> hrdIdx(maxValues, 0); std::vector<TComHRD *> hrdVec; std::vector<Int> syntaxElemLen(maxValues, 0); for(i = 0; i < maxValues; i++) { hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei->m_bspIdx); hrdVec.push_back(vps->getBspHrd(hrdIdx[i])); syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1; if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) ) { assert( syntaxElemLen[i] == 24 ); // Default of value init_cpb_removal_delay_length_minus1 is 23 } if( i > 0 ) { assert( hrdVec[i]->getSubPicCpbParamsPresentFlag() == hrdVec[i-1]->getSubPicCpbParamsPresentFlag() ); assert( hrdVec[i]->getSubPicCpbParamsInPicTimingSEIFlag() == hrdVec[i-1]->getSubPicCpbParamsInPicTimingSEIFlag() ); assert( hrdVec[i]->getCpbRemovalDelayLengthMinus1() == hrdVec[i-1]->getCpbRemovalDelayLengthMinus1() ); assert( hrdVec[i]->getDpbOutputDelayLengthMinus1() == hrdVec[i-1]->getDpbOutputDelayLengthMinus1() ); assert( hrdVec[i]->getDpbOutputDelayDuLengthMinus1() == hrdVec[i-1]->getDpbOutputDelayDuLengthMinus1() ); assert( hrdVec[i]->getDuCpbRemovalDelayLengthMinus1() == hrdVec[i-1]->getDuCpbRemovalDelayLengthMinus1() ); // To be done: Check CpbDpbDelaysPresentFlag } } hrd = hrdVec[0]; } else { hrd = vui->getHrdParameters(); } // To be done: When contained in an BSP HRD SEI message, the hrd structure is to be chosen differently. #else TComVUI *vui = sps->getVuiParameters(); TComHRD *hrd = vui->getHrdParameters(); #endif if( vui->getFrameFieldInfoPresentFlag() ) { READ_CODE( 4, code, "pic_struct" ); sei.m_picStruct = code; READ_CODE( 2, code, "source_scan_type" ); sei.m_sourceScanType = code; READ_FLAG( code, "duplicate_flag" ); sei.m_duplicateFlag = ( code == 1 ? true : false ); } if( hrd->getCpbDpbDelaysPresentFlag()) { READ_CODE( ( hrd->getCpbRemovalDelayLengthMinus1() + 1 ), code, "au_cpb_removal_delay_minus1" ); sei.m_auCpbRemovalDelay = code + 1; READ_CODE( ( hrd->getDpbOutputDelayLengthMinus1() + 1 ), code, "pic_dpb_output_delay" ); sei.m_picDpbOutputDelay = code; if(hrd->getSubPicCpbParamsPresentFlag()) { READ_CODE(hrd->getDpbOutputDelayDuLengthMinus1()+1, code, "pic_dpb_output_du_delay" ); sei.m_picDpbOutputDuDelay = code; } if( hrd->getSubPicCpbParamsPresentFlag() && hrd->getSubPicCpbParamsInPicTimingSEIFlag() ) { READ_UVLC( code, "num_decoding_units_minus1"); sei.m_numDecodingUnitsMinus1 = code; READ_FLAG( code, "du_common_cpb_removal_delay_flag" ); sei.m_duCommonCpbRemovalDelayFlag = code; if( sei.m_duCommonCpbRemovalDelayFlag ) { READ_CODE( ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_common_cpb_removal_delay_minus1" ); sei.m_duCommonCpbRemovalDelayMinus1 = code; } if( sei.m_numNalusInDuMinus1 != NULL ) { delete sei.m_numNalusInDuMinus1; } sei.m_numNalusInDuMinus1 = new UInt[ ( sei.m_numDecodingUnitsMinus1 + 1 ) ]; if( sei.m_duCpbRemovalDelayMinus1 != NULL ) { delete sei.m_duCpbRemovalDelayMinus1; } sei.m_duCpbRemovalDelayMinus1 = new UInt[ ( sei.m_numDecodingUnitsMinus1 + 1 ) ]; for( i = 0; i <= sei.m_numDecodingUnitsMinus1; i ++ ) { READ_UVLC( code, "num_nalus_in_du_minus1"); sei.m_numNalusInDuMinus1[ i ] = code; if( ( !sei.m_duCommonCpbRemovalDelayFlag ) && ( i < sei.m_numDecodingUnitsMinus1 ) ) { READ_CODE( ( hrd->getDuCpbRemovalDelayLengthMinus1() + 1 ), code, "du_cpb_removal_delay_minus1" ); sei.m_duCpbRemovalDelayMinus1[ i ] = code; } } } } xParseByteAlign(); } Void SEIReader::xParseSEIRecoveryPoint(SEIRecoveryPoint& sei, UInt /*payloadSize*/) { Int iCode; UInt uiCode; READ_SVLC( iCode, "recovery_poc_cnt" ); sei.m_recoveryPocCnt = iCode; READ_FLAG( uiCode, "exact_matching_flag" ); sei.m_exactMatchingFlag = uiCode; READ_FLAG( uiCode, "broken_link_flag" ); sei.m_brokenLinkFlag = uiCode; xParseByteAlign(); } Void SEIReader::xParseSEIFramePacking(SEIFramePacking& sei, UInt /*payloadSize*/) { UInt val; READ_UVLC( val, "frame_packing_arrangement_id" ); sei.m_arrangementId = val; READ_FLAG( val, "frame_packing_arrangement_cancel_flag" ); sei.m_arrangementCancelFlag = val; if ( !sei.m_arrangementCancelFlag ) { READ_CODE( 7, val, "frame_packing_arrangement_type" ); sei.m_arrangementType = val; assert((sei.m_arrangementType > 2) && (sei.m_arrangementType < 6) ); READ_FLAG( val, "quincunx_sampling_flag" ); sei.m_quincunxSamplingFlag = val; READ_CODE( 6, val, "content_interpretation_type" ); sei.m_contentInterpretationType = val; READ_FLAG( val, "spatial_flipping_flag" ); sei.m_spatialFlippingFlag = val; READ_FLAG( val, "frame0_flipped_flag" ); sei.m_frame0FlippedFlag = val; READ_FLAG( val, "field_views_flag" ); sei.m_fieldViewsFlag = val; READ_FLAG( val, "current_frame_is_frame0_flag" ); sei.m_currentFrameIsFrame0Flag = val; READ_FLAG( val, "frame0_self_contained_flag" ); sei.m_frame0SelfContainedFlag = val; READ_FLAG( val, "frame1_self_contained_flag" ); sei.m_frame1SelfContainedFlag = val; if ( sei.m_quincunxSamplingFlag == 0 && sei.m_arrangementType != 5) { READ_CODE( 4, val, "frame0_grid_position_x" ); sei.m_frame0GridPositionX = val; READ_CODE( 4, val, "frame0_grid_position_y" ); sei.m_frame0GridPositionY = val; READ_CODE( 4, val, "frame1_grid_position_x" ); sei.m_frame1GridPositionX = val; READ_CODE( 4, val, "frame1_grid_position_y" ); sei.m_frame1GridPositionY = val; } READ_CODE( 8, val, "frame_packing_arrangement_reserved_byte" ); sei.m_arrangementReservedByte = val; READ_FLAG( val, "frame_packing_arrangement_persistence_flag" ); sei.m_arrangementPersistenceFlag = val ? true : false; } READ_FLAG( val, "upsampled_aspect_ratio" ); sei.m_upsampledAspectRatio = val; xParseByteAlign(); } Void SEIReader::xParseSEIDisplayOrientation(SEIDisplayOrientation& sei, UInt /*payloadSize*/) { UInt val; READ_FLAG( val, "display_orientation_cancel_flag" ); sei.cancelFlag = val; if( !sei.cancelFlag ) { READ_FLAG( val, "hor_flip" ); sei.horFlip = val; READ_FLAG( val, "ver_flip" ); sei.verFlip = val; READ_CODE( 16, val, "anticlockwise_rotation" ); sei.anticlockwiseRotation = val; READ_FLAG( val, "display_orientation_persistence_flag" ); sei.persistenceFlag = val; } xParseByteAlign(); } Void SEIReader::xParseSEITemporalLevel0Index(SEITemporalLevel0Index& sei, UInt /*payloadSize*/) { UInt val; READ_CODE ( 8, val, "tl0_idx" ); sei.tl0Idx = val; READ_CODE ( 8, val, "rap_idx" ); sei.rapIdx = val; xParseByteAlign(); } Void SEIReader::xParseSEIGradualDecodingRefreshInfo(SEIGradualDecodingRefreshInfo& sei, UInt /*payloadSize*/) { UInt val; READ_FLAG( val, "gdr_foreground_flag" ); sei.m_gdrForegroundFlag = val ? 1 : 0; xParseByteAlign(); } Void SEIReader::xParseSEIToneMappingInfo(SEIToneMappingInfo& sei, UInt /*payloadSize*/) { Int i; UInt val; READ_UVLC( val, "tone_map_id" ); sei.m_toneMapId = val; READ_FLAG( val, "tone_map_cancel_flag" ); sei.m_toneMapCancelFlag = val; if ( !sei.m_toneMapCancelFlag ) { READ_FLAG( val, "tone_map_persistence_flag" ); sei.m_toneMapPersistenceFlag = val; READ_CODE( 8, val, "coded_data_bit_depth" ); sei.m_codedDataBitDepth = val; READ_CODE( 8, val, "target_bit_depth" ); sei.m_targetBitDepth = val; READ_UVLC( val, "model_id" ); sei.m_modelId = val; switch(sei.m_modelId) { case 0: { READ_CODE( 32, val, "min_value" ); sei.m_minValue = val; READ_CODE( 32, val, "max_value" ); sei.m_maxValue = val; break; } case 1: { READ_CODE( 32, val, "sigmoid_midpoint" ); sei.m_sigmoidMidpoint = val; READ_CODE( 32, val, "sigmoid_width" ); sei.m_sigmoidWidth = val; break; } case 2: { UInt num = 1u << sei.m_targetBitDepth; sei.m_startOfCodedInterval.resize(num+1); for(i = 0; i < num; i++) { READ_CODE( ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "start_of_coded_interval" ); sei.m_startOfCodedInterval[i] = val; } sei.m_startOfCodedInterval[num] = 1u << sei.m_codedDataBitDepth; break; } case 3: { READ_CODE( 16, val, "num_pivots" ); sei.m_numPivots = val; sei.m_codedPivotValue.resize(sei.m_numPivots); sei.m_targetPivotValue.resize(sei.m_numPivots); for(i = 0; i < sei.m_numPivots; i++ ) { READ_CODE( ((( sei.m_codedDataBitDepth + 7 ) >> 3 ) << 3), val, "coded_pivot_value" ); sei.m_codedPivotValue[i] = val; READ_CODE( ((( sei.m_targetBitDepth + 7 ) >> 3 ) << 3), val, "target_pivot_value" ); sei.m_targetPivotValue[i] = val; } break; } case 4: { READ_CODE( 8, val, "camera_iso_speed_idc" ); sei.m_cameraIsoSpeedIdc = val; if( sei.m_cameraIsoSpeedIdc == 255) //Extended_ISO { READ_CODE( 32, val, "camera_iso_speed_value" ); sei.m_cameraIsoSpeedValue = val; } READ_CODE( 8, val, "exposure_index_idc" ); sei.m_exposureIndexIdc = val; if( sei.m_exposureIndexIdc == 255) //Extended_ISO { READ_CODE( 32, val, "exposure_index_value" ); sei.m_exposureIndexValue = val; } READ_FLAG( val, "exposure_compensation_value_sign_flag" ); sei.m_exposureCompensationValueSignFlag = val; READ_CODE( 16, val, "exposure_compensation_value_numerator" ); sei.m_exposureCompensationValueNumerator = val; READ_CODE( 16, val, "exposure_compensation_value_denom_idc" ); sei.m_exposureCompensationValueDenomIdc = val; READ_CODE( 32, val, "ref_screen_luminance_white" ); sei.m_refScreenLuminanceWhite = val; READ_CODE( 32, val, "extended_range_white_level" ); sei.m_extendedRangeWhiteLevel = val; READ_CODE( 16, val, "nominal_black_level_luma_code_value" ); sei.m_nominalBlackLevelLumaCodeValue = val; READ_CODE( 16, val, "nominal_white_level_luma_code_value" ); sei.m_nominalWhiteLevelLumaCodeValue= val; READ_CODE( 16, val, "extended_white_level_luma_code_value" ); sei.m_extendedWhiteLevelLumaCodeValue = val; break; } default: { assert(!"Undefined SEIToneMapModelId"); break; } }//switch model id }// if(!sei.m_toneMapCancelFlag) xParseByteAlign(); } #if P0050_KNEE_FUNCTION_SEI Void SEIReader::xParseSEIKneeFunctionInfo(SEIKneeFunctionInfo& sei, UInt /*payloadSize*/){ Int i; UInt val; READ_UVLC( val, "knee_function_id" ); sei.m_kneeId = val; READ_FLAG( val, "knee_function_cancel_flag" ); sei.m_kneeCancelFlag = val; if ( !sei.m_kneeCancelFlag ) { READ_FLAG( val, "knee_function_persistence_flag" ); sei.m_kneePersistenceFlag = val; READ_FLAG( val, "mapping_flag" ); sei.m_kneeMappingFlag = val; READ_CODE( 32, val, "input_d_range" ); sei.m_kneeInputDrange = val; READ_CODE( 32, val, "input_disp_luminance" ); sei.m_kneeInputDispLuminance = val; READ_CODE( 32, val, "output_d_range" ); sei.m_kneeOutputDrange = val; READ_CODE( 32, val, "output_disp_luminance" ); sei.m_kneeOutputDispLuminance = val; READ_UVLC( val, "num_knee_points_minus1" ); sei.m_kneeNumKneePointsMinus1 = val; assert( sei.m_kneeNumKneePointsMinus1 > 0 ); sei.m_kneeInputKneePoint.resize(sei.m_kneeNumKneePointsMinus1+1); sei.m_kneeOutputKneePoint.resize(sei.m_kneeNumKneePointsMinus1+1); for(i = 0; i <= sei.m_kneeNumKneePointsMinus1; i++ ) { READ_CODE( 10, val, "input_knee_point" ); sei.m_kneeInputKneePoint[i] = val; READ_CODE( 10, val, "output_knee_point" ); sei.m_kneeOutputKneePoint[i] = val; } } } #endif #if Q0074_COLOUR_REMAPPING_SEI Void SEIReader::xParseSEIColourRemappingInfo(SEIColourRemappingInfo& sei, UInt /*payloadSize*/) { UInt uiVal; Int iVal; READ_UVLC( uiVal, "colour_remap_id" ); sei.m_colourRemapId = uiVal; READ_FLAG( uiVal, "colour_remap_cancel_flag" ); sei.m_colourRemapCancelFlag = uiVal; if( !sei.m_colourRemapCancelFlag ) { READ_FLAG( uiVal, "colour_remap_persistence_flag" ); sei.m_colourRemapPersistenceFlag = uiVal; READ_FLAG( uiVal, "colour_remap_video_signal_info_present_flag" ); sei.m_colourRemapVideoSignalInfoPresentFlag = uiVal; if ( sei.m_colourRemapVideoSignalInfoPresentFlag ) { READ_FLAG( uiVal, "colour_remap_full_range_flag" ); sei.m_colourRemapFullRangeFlag = uiVal; READ_CODE( 8, uiVal, "colour_remap_primaries" ); sei.m_colourRemapPrimaries = uiVal; READ_CODE( 8, uiVal, "colour_remap_transfer_function" ); sei.m_colourRemapTransferFunction = uiVal; READ_CODE( 8, uiVal, "colour_remap_matrix_coefficients" ); sei.m_colourRemapMatrixCoefficients = uiVal; } READ_CODE( 8, uiVal, "colour_remap_input_bit_depth" ); sei.m_colourRemapInputBitDepth = uiVal; READ_CODE( 8, uiVal, "colour_remap_bit_depth" ); sei.m_colourRemapBitDepth = uiVal; for( Int c=0 ; c<3 ; c++ ) { READ_CODE( 8, uiVal, "pre_lut_num_val_minus1[c]" ); sei.m_preLutNumValMinus1[c] = (uiVal==0) ? 1 : uiVal; sei.m_preLutCodedValue[c].resize(sei.m_preLutNumValMinus1[c]+1); sei.m_preLutTargetValue[c].resize(sei.m_preLutNumValMinus1[c]+1); if( uiVal> 0 ) for ( Int i=0 ; i<=sei.m_preLutNumValMinus1[c] ; i++ ) { READ_CODE( (( sei.m_colourRemapInputBitDepth + 7 ) >> 3 ) << 3, uiVal, "pre_lut_coded_value[c][i]" ); sei.m_preLutCodedValue[c][i] = uiVal; READ_CODE( (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "pre_lut_target_value[c][i]" ); sei.m_preLutTargetValue[c][i] = uiVal; } else // pre_lut_num_val_minus1[c] == 0 { sei.m_preLutCodedValue[c][0] = 0; sei.m_preLutTargetValue[c][0] = 0; sei.m_preLutCodedValue[c][1] = (1 << sei.m_colourRemapInputBitDepth) - 1 ; sei.m_preLutTargetValue[c][1] = (1 << sei.m_colourRemapBitDepth) - 1 ; } } READ_FLAG( uiVal, "colour_remap_matrix_present_flag" ); sei.m_colourRemapMatrixPresentFlag = uiVal; if( sei.m_colourRemapMatrixPresentFlag ) { READ_CODE( 4, uiVal, "log2_matrix_denom" ); sei.m_log2MatrixDenom = uiVal; for ( Int c=0 ; c<3 ; c++ ) for ( Int i=0 ; i<3 ; i++ ) { READ_SVLC( iVal, "colour_remap_coeffs[c][i]" ); sei.m_colourRemapCoeffs[c][i] = iVal; } } else // setting default matrix (I3) { sei.m_log2MatrixDenom = 0; for ( Int c=0 ; c<3 ; c++ ) for ( Int i=0 ; i<3 ; i++ ) sei.m_colourRemapCoeffs[c][i] = (c==i) ? 1 : 0; } for( Int c=0 ; c<3 ; c++ ) { READ_CODE( 8, uiVal, "post_lut_num_val_minus1[c]" ); sei.m_postLutNumValMinus1[c] = (uiVal==0) ? 1 : uiVal; sei.m_postLutCodedValue[c].resize(sei.m_postLutNumValMinus1[c]+1); sei.m_postLutTargetValue[c].resize(sei.m_postLutNumValMinus1[c]+1); if( uiVal > 0 ) for ( Int i=0 ; i<=sei.m_postLutNumValMinus1[c] ; i++ ) { READ_CODE( (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "post_lut_coded_value[c][i]" ); sei.m_postLutCodedValue[c][i] = uiVal; READ_CODE( (( sei.m_colourRemapBitDepth + 7 ) >> 3 ) << 3, uiVal, "post_lut_target_value[c][i]" ); sei.m_postLutTargetValue[c][i] = uiVal; } else { sei.m_postLutCodedValue[c][0] = 0; sei.m_postLutTargetValue[c][0] = 0; sei.m_postLutTargetValue[c][1] = (1 << sei.m_colourRemapBitDepth) - 1; sei.m_postLutCodedValue[c][1] = (1 << sei.m_colourRemapBitDepth) - 1; } } } xParseByteAlign(); } #endif Void SEIReader::xParseSEISOPDescription(SEISOPDescription &sei, UInt payloadSize) { Int iCode; UInt uiCode; READ_UVLC( uiCode, "sop_seq_parameter_set_id" ); sei.m_sopSeqParameterSetId = uiCode; READ_UVLC( uiCode, "num_pics_in_sop_minus1" ); sei.m_numPicsInSopMinus1 = uiCode; for (UInt i = 0; i <= sei.m_numPicsInSopMinus1; i++) { READ_CODE( 6, uiCode, "sop_desc_vcl_nalu_type" ); sei.m_sopDescVclNaluType[i] = uiCode; READ_CODE( 3, sei.m_sopDescTemporalId[i], "sop_desc_temporal_id" ); sei.m_sopDescTemporalId[i] = uiCode; if (sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_W_RADL && sei.m_sopDescVclNaluType[i] != NAL_UNIT_CODED_SLICE_IDR_N_LP) { READ_UVLC( sei.m_sopDescStRpsIdx[i], "sop_desc_st_rps_idx" ); sei.m_sopDescStRpsIdx[i] = uiCode; } if (i > 0) { READ_SVLC( iCode, "sop_desc_poc_delta" ); sei.m_sopDescPocDelta[i] = iCode; } } xParseByteAlign(); } #if Q0189_TMVP_CONSTRAINTS Void SEIReader::xParseSEITMVPConstraints (SEITMVPConstrains& sei, UInt payloadSize) { UInt uiCode; READ_UVLC( uiCode, "prev_pics_not_used_flag" ); sei.prev_pics_not_used_flag = uiCode; READ_UVLC( uiCode, "no_intra_layer_col_pic_flag" ); sei.no_intra_layer_col_pic_flag = uiCode; xParseByteAlign(); } #endif #if Q0247_FRAME_FIELD_INFO Void SEIReader::xParseSEIFrameFieldInfo (SEIFrameFieldInfo& sei, UInt payloadSize) { UInt code; READ_CODE( 4, code, "ffinfo_pic_struct" ); sei.m_ffinfo_picStruct = code; READ_CODE( 2, code, "ffinfo_source_scan_type" ); sei.m_ffinfo_sourceScanType = code; READ_FLAG( code, "ffinfo_duplicate_flag" ); sei.m_ffinfo_duplicateFlag = ( code == 1 ? true : false ); xParseByteAlign(); } #endif #if LAYERS_NOT_PRESENT_SEI Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComVPS *vps, TComSPS *sps) #else Void SEIReader::xParseSEIScalableNesting(SEIScalableNesting& sei, const NalUnitType nalUnitType, UInt payloadSize, TComSPS *sps) #endif { UInt uiCode; SEIMessages seis; READ_FLAG( uiCode, "bitstream_subset_flag" ); sei.m_bitStreamSubsetFlag = uiCode; READ_FLAG( uiCode, "nesting_op_flag" ); sei.m_nestingOpFlag = uiCode; if (sei.m_nestingOpFlag) { READ_FLAG( uiCode, "default_op_flag" ); sei.m_defaultOpFlag = uiCode; READ_UVLC( uiCode, "nesting_num_ops_minus1" ); sei.m_nestingNumOpsMinus1 = uiCode; for (UInt i = sei.m_defaultOpFlag; i <= sei.m_nestingNumOpsMinus1; i++) { READ_CODE( 3, uiCode, "nesting_max_temporal_id_plus1" ); sei.m_nestingMaxTemporalIdPlus1[i] = uiCode; READ_UVLC( uiCode, "nesting_op_idx" ); sei.m_nestingOpIdx[i] = uiCode; } } else { READ_FLAG( uiCode, "all_layers_flag" ); sei.m_allLayersFlag = uiCode; if (!sei.m_allLayersFlag) { READ_CODE( 3, uiCode, "nesting_no_op_max_temporal_id_plus1" ); sei.m_nestingNoOpMaxTemporalIdPlus1 = uiCode; READ_UVLC( uiCode, "nesting_num_layers_minus1" ); sei.m_nestingNumLayersMinus1 = uiCode; for (UInt i = 0; i <= sei.m_nestingNumLayersMinus1; i++) { READ_CODE( 6, uiCode, "nesting_layer_id" ); sei.m_nestingLayerId[i] = uiCode; } } } // byte alignment while ( m_pcBitstream->getNumBitsRead() % 8 != 0 ) { UInt code; READ_FLAG( code, "nesting_zero_bit" ); } sei.m_callerOwnsSEIs = false; // read nested SEI messages do { #if O0164_MULTI_LAYER_HRD #if LAYERS_NOT_PRESENT_SEI xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, &sei); #else xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps, &sei); #endif #else #if LAYERS_NOT_PRESENT_SEI xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps); #else xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps); #endif #endif } while (m_pcBitstream->getNumBitsLeft() > 8); } Void SEIReader::xParseByteAlign() { UInt code; if( m_pcBitstream->getNumBitsRead() % 8 != 0 ) { READ_FLAG( code, "bit_equal_to_one" ); assert( code == 1 ); } while( m_pcBitstream->getNumBitsRead() % 8 != 0 ) { READ_FLAG( code, "bit_equal_to_zero" ); assert( code == 0 ); } } #if SVC_EXTENSION #if LAYERS_NOT_PRESENT_SEI Void SEIReader::xParseSEILayersNotPresent(SEILayersNotPresent &sei, UInt payloadSize, TComVPS *vps) { UInt uiCode; UInt i = 0; READ_UVLC( uiCode, "lp_sei_active_vps_id" ); sei.m_activeVpsId = uiCode; assert(vps->getVPSId() == sei.m_activeVpsId); sei.m_vpsMaxLayers = vps->getMaxLayers(); for (; i < sei.m_vpsMaxLayers; i++) { READ_FLAG( uiCode, "layer_not_present_flag" ); sei.m_layerNotPresentFlag[i] = uiCode ? true : false; } for (; i < MAX_LAYERS; i++) { sei.m_layerNotPresentFlag[i] = false; } xParseByteAlign(); } #endif #if N0383_IL_CONSTRAINED_TILE_SETS_SEI Void SEIReader::xParseSEIInterLayerConstrainedTileSets (SEIInterLayerConstrainedTileSets &sei, UInt payloadSize) { UInt uiCode; READ_FLAG( uiCode, "il_all_tiles_exact_sample_value_match_flag" ); sei.m_ilAllTilesExactSampleValueMatchFlag = uiCode; READ_FLAG( uiCode, "il_one_tile_per_tile_set_flag" ); sei.m_ilOneTilePerTileSetFlag = uiCode; if( !sei.m_ilOneTilePerTileSetFlag ) { READ_UVLC( uiCode, "il_num_sets_in_message_minus1" ); sei.m_ilNumSetsInMessageMinus1 = uiCode; if( sei.m_ilNumSetsInMessageMinus1 ) { READ_FLAG( uiCode, "skipped_tile_set_present_flag" ); sei.m_skippedTileSetPresentFlag = uiCode; } else { sei.m_skippedTileSetPresentFlag = false; } UInt numSignificantSets = sei.m_ilNumSetsInMessageMinus1 - (sei.m_skippedTileSetPresentFlag ? 1 : 0) + 1; for( UInt i = 0; i < numSignificantSets; i++ ) { READ_UVLC( uiCode, "ilcts_id" ); sei.m_ilctsId[i] = uiCode; READ_UVLC( uiCode, "il_num_tile_rects_in_set_minus1" ) ;sei.m_ilNumTileRectsInSetMinus1[i] = uiCode; for( UInt j = 0; j <= sei.m_ilNumTileRectsInSetMinus1[i]; j++ ) { READ_UVLC( uiCode, "il_top_left_tile_index" ); sei.m_ilTopLeftTileIndex[i][j] = uiCode; READ_UVLC( uiCode, "il_bottom_right_tile_index" ); sei.m_ilBottomRightTileIndex[i][j] = uiCode; } READ_CODE( 2, uiCode, "ilc_idc" ); sei.m_ilcIdc[i] = uiCode; if( sei.m_ilAllTilesExactSampleValueMatchFlag ) { READ_FLAG( uiCode, "il_exact_sample_value_match_flag" ); sei.m_ilExactSampleValueMatchFlag[i] = uiCode; } } } else { READ_CODE( 2, uiCode, "all_tiles_ilc_idc" ); sei.m_allTilesIlcIdc = uiCode; } xParseByteAlign(); } #endif #if SUB_BITSTREAM_PROPERTY_SEI #if OLS_IDX_CHK Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei, TComVPS *vps) #else Void SEIReader::xParseSEISubBitstreamProperty(SEISubBitstreamProperty &sei) #endif { UInt uiCode; READ_CODE( 4, uiCode, "active_vps_id" ); sei.m_activeVpsId = uiCode; READ_UVLC( uiCode, "num_additional_sub_streams_minus1" ); sei.m_numAdditionalSubStreams = uiCode + 1; for( Int i = 0; i < sei.m_numAdditionalSubStreams; i++ ) { READ_CODE( 2, uiCode, "sub_bitstream_mode[i]" ); sei.m_subBitstreamMode[i] = uiCode; READ_UVLC( uiCode, "output_layer_set_idx_to_vps[i]" ); #if OLS_IDX_CHK // The value of output_layer_set_idx_to_vps[ i ] shall be in the range of 0 to NumOutputLayerSets − 1, inclusive. assert(uiCode > 0 && uiCode <= vps->getNumOutputLayerSets()-1); #endif sei.m_outputLayerSetIdxToVps[i] = uiCode; READ_CODE( 3, uiCode, "highest_sub_layer_id[i]" ); sei.m_highestSublayerId[i] = uiCode; READ_CODE( 16, uiCode, "avg_bit_rate[i]" ); sei.m_avgBitRate[i] = uiCode; READ_CODE( 16, uiCode, "max_bit_rate[i]" ); sei.m_maxBitRate[i] = uiCode; } xParseByteAlign(); } #endif #if O0164_MULTI_LAYER_HRD #if LAYERS_NOT_PRESENT_SEI Void SEIReader::xParseSEIBspNesting(SEIBspNesting &sei, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei) #else Void SEIReader::xParseSEIBspNesting(SEIBspNesting &sei, const NalUnitType nalUnitType, TComSPS *sps, const SEIScalableNesting &nestingSei) #endif { UInt uiCode; READ_UVLC( uiCode, "bsp_idx" ); sei.m_bspIdx = uiCode; // byte alignment while ( m_pcBitstream->getNumBitsRead() % 8 != 0 ) { UInt code; READ_FLAG( code, "bsp_nesting_zero_bit" ); } sei.m_callerOwnsSEIs = false; // read nested SEI messages #if NESTING_SEI_EXTENSIBILITY Int numSeiMessages = 0; READ_UVLC( uiCode, "num_seis_in_bsp_minus1" ); assert( uiCode <= MAX_SEIS_IN_BSP_NESTING ); numSeiMessages = uiCode; for(Int i = 0; i < numSeiMessages; i++) { xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, &nestingSei, &sei); } #else do { #if LAYERS_NOT_PRESENT_SEI xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps, &nestingSei, &sei); #else xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps, &nestingSei); #endif } while (m_pcBitstream->getNumBitsLeft() > 8); #endif } Void SEIReader::xParseSEIBspInitialArrivalTime(SEIBspInitialArrivalTime &sei, TComVPS *vps, TComSPS *sps, const SEIScalableNesting &nestingSei, const SEIBspNesting &bspNestingSei) { assert(vps->getVpsVuiPresentFlag()); #if VPS_VUI_BSP_HRD_PARAMS UInt uiCode; Int psIdx = bspNestingSei.m_seiPartitioningSchemeIdx; Int seiOlsIdx = bspNestingSei.m_seiOlsIdx; Int maxTemporalId = nestingSei.m_nestingMaxTemporalIdPlus1[0]; Int maxValues = vps->getNumBspSchedulesMinus1(seiOlsIdx, psIdx, maxTemporalId) + 1; std::vector<Int> hrdIdx(0, maxValues); std::vector<TComHRD *> hrdVec; std::vector<Int> syntaxElemLen; for(Int i = 0; i < maxValues; i++) { hrdIdx[i] = vps->getBspHrdIdx( seiOlsIdx, psIdx, maxTemporalId, i, bspNestingSei.m_bspIdx); hrdVec[i] = vps->getBspHrd(hrdIdx[i]); syntaxElemLen[i] = hrdVec[i]->getInitialCpbRemovalDelayLengthMinus1() + 1; if ( !(hrdVec[i]->getNalHrdParametersPresentFlag() || hrdVec[i]->getVclHrdParametersPresentFlag()) ) { assert( syntaxElemLen[i] == 24 ); // Default value of init_cpb_removal_delay_length_minus1 is 23 } if( i > 0 ) { assert( hrdVec[i]->getNalHrdParametersPresentFlag() == hrdVec[i-1]->getNalHrdParametersPresentFlag() ); assert( hrdVec[i]->getVclHrdParametersPresentFlag() == hrdVec[i-1]->getVclHrdParametersPresentFlag() ); } } if (hrdVec[0]->getNalHrdParametersPresentFlag()) { for(UInt i = 0; i < maxValues; i++) { READ_CODE( syntaxElemLen[i], uiCode, "nal_initial_arrival_delay[i]" ); sei.m_nalInitialArrivalDelay[i] = uiCode; } } if( hrdVec[0]->getVclHrdParametersPresentFlag() ) { for(UInt i = 0; i < maxValues; i++) { READ_CODE( syntaxElemLen[i], uiCode, "vcl_initial_arrival_delay[i]" ); sei.m_vclInitialArrivalDelay[i] = uiCode; } } #else UInt schedCombCnt = vps->getNumBspSchedCombinations(nestingSei.m_nestingOpIdx[0]); UInt len; UInt hrdIdx; UInt uiCode; if (schedCombCnt > 0) { hrdIdx = vps->getBspCombHrdIdx(nestingSei.m_nestingOpIdx[0], 0, bspNestingSei.m_bspIdx); } else { hrdIdx = 0; } TComHRD *hrd = vps->getBspHrd(hrdIdx); if (hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag()) { len = hrd->getInitialCpbRemovalDelayLengthMinus1() + 1; } else { len = 23 + 1; } if (hrd->getNalHrdParametersPresentFlag()) { for(UInt i = 0; i < schedCombCnt; i++) { READ_CODE( len, uiCode, "nal_initial_arrival_delay" ); sei.m_nalInitialArrivalDelay[i] = uiCode; } } #if BSP_INIT_ARRIVAL_SEI if( hrd->getVclHrdParametersPresentFlag() ) #else else #endif { for(UInt i = 0; i < schedCombCnt; i++) { READ_CODE( len, uiCode, "vcl_initial_arrival_delay" ); sei.m_vclInitialArrivalDelay[i] = uiCode; } } #endif } #if !REMOVE_BSP_HRD_SEI Void SEIReader::xParseSEIBspHrd(SEIBspHrd &sei, TComSPS *sps, const SEIScalableNesting &nestingSei) { UInt uiCode; READ_UVLC( uiCode, "sei_num_bsp_hrd_parameters_minus1" ); sei.m_seiNumBspHrdParametersMinus1 = uiCode; for (UInt i = 0; i <= sei.m_seiNumBspHrdParametersMinus1; i++) { if (i > 0) { READ_FLAG( uiCode, "sei_bsp_cprms_present_flag" ); sei.m_seiBspCprmsPresentFlag[i] = uiCode; } xParseHrdParameters(sei.hrd, i==0 ? 1 : sei.m_seiBspCprmsPresentFlag[i], nestingSei.m_nestingMaxTemporalIdPlus1[0]-1); } for (UInt h = 0; h <= nestingSei.m_nestingNumOpsMinus1; h++) { UInt lsIdx = nestingSei.m_nestingOpIdx[h]; READ_UVLC( uiCode, "num_sei_bitstream_partitions_minus1[i]"); sei.m_seiNumBitstreamPartitionsMinus1[lsIdx] = uiCode; #if HRD_BPB Int chkPart=0; #endif UInt i; for(i = 0; i <= sei.m_seiNumBitstreamPartitionsMinus1[lsIdx]; i++) { #if HRD_BPB UInt nl=0; UInt j; for(j = 0; j < sei.m_vpsMaxLayers; j++) { if (sei.m_layerIdIncludedFlag[lsIdx][j]) { nl++; } } for (j = 0; j < nl; j++) { #else for (UInt j = 0; j < sei.m_vpsMaxLayers; j++) { if (sei.m_layerIdIncludedFlag[lsIdx][j]) { #endif READ_FLAG( uiCode, "sei_layer_in_bsp_flag[lsIdx][i][j]" ); sei.m_seiLayerInBspFlag[lsIdx][i][j] = uiCode; } #if !HRD_BPB } #endif #if HRD_BPB chkPart+=sei.m_seiLayerInBspFlag[lsIdx][i][j]; #endif } #if HRD_BPB assert(chkPart<=1); #endif #if HRD_BPB if(sei.m_seiNumBitstreamPartitionsMinus1[lsIdx]==0) { Int chkPartition1=0; Int chkPartition2=0; for (UInt j = 0; j < sei.m_vpsMaxLayers; j++) { if( sei.m_layerIdIncludedFlag[lsIdx][j] ) { chkPartition1+=sei.m_seiLayerInBspFlag[lsIdx][0][j]; chkPartition2++; } } assert(chkPartition1!=chkPartition2); } #endif READ_UVLC( uiCode, "sei_num_bsp_sched_combinations_minus1[i]"); sei.m_seiNumBspSchedCombinationsMinus1[lsIdx] = uiCode; for (i = 0; i <= sei.m_seiNumBspSchedCombinationsMinus1[lsIdx]; i++) { for (UInt j = 0; j <= sei.m_seiNumBitstreamPartitionsMinus1[lsIdx]; j++) { READ_UVLC( uiCode, "sei_bsp_comb_hrd_idx[lsIdx][i][j]"); sei.m_seiBspCombHrdIdx[lsIdx][i][j] = uiCode; #if HRD_BPB assert(uiCode <= sei.m_seiNumBspHrdParametersMinus1); #endif READ_UVLC( uiCode, "sei_bsp_comb_sched_idx[lsIdx][i][j]"); sei.m_seiBspCombScheddx[lsIdx][i][j] = uiCode; #if HRD_BPB assert(uiCode <= sei.hrd->getCpbCntMinus1( sps->getMaxTLayers()-1 )); #endif } } } } #endif Void SEIReader::xParseHrdParameters(TComHRD *hrd, Bool commonInfPresentFlag, UInt maxNumSubLayersMinus1) { UInt uiCode; if( commonInfPresentFlag ) { READ_FLAG( uiCode, "nal_hrd_parameters_present_flag" ); hrd->setNalHrdParametersPresentFlag( uiCode == 1 ? true : false ); READ_FLAG( uiCode, "vcl_hrd_parameters_present_flag" ); hrd->setVclHrdParametersPresentFlag( uiCode == 1 ? true : false ); if( hrd->getNalHrdParametersPresentFlag() || hrd->getVclHrdParametersPresentFlag() ) { READ_FLAG( uiCode, "sub_pic_cpb_params_present_flag" ); hrd->setSubPicCpbParamsPresentFlag( uiCode == 1 ? true : false ); if( hrd->getSubPicCpbParamsPresentFlag() ) { READ_CODE( 8, uiCode, "tick_divisor_minus2" ); hrd->setTickDivisorMinus2( uiCode ); READ_CODE( 5, uiCode, "du_cpb_removal_delay_length_minus1" ); hrd->setDuCpbRemovalDelayLengthMinus1( uiCode ); READ_FLAG( uiCode, "sub_pic_cpb_params_in_pic_timing_sei_flag" ); hrd->setSubPicCpbParamsInPicTimingSEIFlag( uiCode == 1 ? true : false ); READ_CODE( 5, uiCode, "dpb_output_delay_du_length_minus1" ); hrd->setDpbOutputDelayDuLengthMinus1( uiCode ); } READ_CODE( 4, uiCode, "bit_rate_scale" ); hrd->setBitRateScale( uiCode ); READ_CODE( 4, uiCode, "cpb_size_scale" ); hrd->setCpbSizeScale( uiCode ); if( hrd->getSubPicCpbParamsPresentFlag() ) { READ_CODE( 4, uiCode, "cpb_size_du_scale" ); hrd->setDuCpbSizeScale( uiCode ); } READ_CODE( 5, uiCode, "initial_cpb_removal_delay_length_minus1" ); hrd->setInitialCpbRemovalDelayLengthMinus1( uiCode ); READ_CODE( 5, uiCode, "au_cpb_removal_delay_length_minus1" ); hrd->setCpbRemovalDelayLengthMinus1( uiCode ); READ_CODE( 5, uiCode, "dpb_output_delay_length_minus1" ); hrd->setDpbOutputDelayLengthMinus1( uiCode ); } } Int i, j, nalOrVcl; for( i = 0; i <= maxNumSubLayersMinus1; i ++ ) { READ_FLAG( uiCode, "fixed_pic_rate_general_flag" ); hrd->setFixedPicRateFlag( i, uiCode == 1 ? true : false ); if( !hrd->getFixedPicRateFlag( i ) ) { READ_FLAG( uiCode, "fixed_pic_rate_within_cvs_flag" ); hrd->setFixedPicRateWithinCvsFlag( i, uiCode == 1 ? true : false ); } else { hrd->setFixedPicRateWithinCvsFlag( i, true ); } hrd->setLowDelayHrdFlag( i, 0 ); // Infered to be 0 when not present hrd->setCpbCntMinus1 ( i, 0 ); // Infered to be 0 when not present if( hrd->getFixedPicRateWithinCvsFlag( i ) ) { READ_UVLC( uiCode, "elemental_duration_in_tc_minus1" ); hrd->setPicDurationInTcMinus1( i, uiCode ); } else { READ_FLAG( uiCode, "low_delay_hrd_flag" ); hrd->setLowDelayHrdFlag( i, uiCode == 1 ? true : false ); } if (!hrd->getLowDelayHrdFlag( i )) { READ_UVLC( uiCode, "cpb_cnt_minus1" ); hrd->setCpbCntMinus1( i, uiCode ); } for( nalOrVcl = 0; nalOrVcl < 2; nalOrVcl ++ ) { if( ( ( nalOrVcl == 0 ) && ( hrd->getNalHrdParametersPresentFlag() ) ) || ( ( nalOrVcl == 1 ) && ( hrd->getVclHrdParametersPresentFlag() ) ) ) { for( j = 0; j <= ( hrd->getCpbCntMinus1( i ) ); j ++ ) { READ_UVLC( uiCode, "bit_rate_value_minus1" ); hrd->setBitRateValueMinus1( i, j, nalOrVcl, uiCode ); READ_UVLC( uiCode, "cpb_size_value_minus1" ); hrd->setCpbSizeValueMinus1( i, j, nalOrVcl, uiCode ); if( hrd->getSubPicCpbParamsPresentFlag() ) { READ_UVLC( uiCode, "cpb_size_du_value_minus1" ); hrd->setDuCpbSizeValueMinus1( i, j, nalOrVcl, uiCode ); READ_UVLC( uiCode, "bit_rate_du_value_minus1" ); hrd->setDuBitRateValueMinus1( i, j, nalOrVcl, uiCode ); } READ_FLAG( uiCode, "cbr_flag" ); hrd->setCbrFlag( i, j, nalOrVcl, uiCode == 1 ? true : false ); } } } } } #endif #if Q0078_ADD_LAYER_SETS #if LAYERS_NOT_PRESENT_SEI Void SEIReader::xParseSEIOutputLayerSetNesting(SEIOutputLayerSetNesting& sei, const NalUnitType nalUnitType, TComVPS *vps, TComSPS *sps) #else Void SEIReader::xParseSEIOutputLayerSetNesting(SEIOutputLayerSetNesting& sei, const NalUnitType nalUnitType, TComSPS *sps) #endif { UInt uiCode; SEIMessages seis; READ_FLAG(uiCode, "ols_flag"); sei.m_olsFlag = uiCode; READ_UVLC(uiCode, "num_ols_indices_minus1"); sei.m_numOlsIndicesMinus1 = uiCode; for (Int i = 0; i <= sei.m_numOlsIndicesMinus1; i++) { READ_UVLC(uiCode, "ols_idx[i]"); sei.m_olsIdx[i] = uiCode; } // byte alignment while (m_pcBitstream->getNumBitsRead() % 8 != 0) { UInt code; READ_FLAG(code, "ols_nesting_zero_bit"); } sei.m_callerOwnsSEIs = false; // read nested SEI messages do { #if O0164_MULTI_LAYER_HRD #if LAYERS_NOT_PRESENT_SEI xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps); #else xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps); #endif #else #if LAYERS_NOT_PRESENT_SEI xReadSEImessage(sei.m_nestedSEIs, nalUnitType, vps, sps); #else xReadSEImessage(sei.m_nestedSEIs, nalUnitType, sps); #endif #endif } while (m_pcBitstream->getNumBitsLeft() > 8); } Void SEIReader::xParseSEIVPSRewriting(SEIVPSRewriting &sei) { } #endif #endif //SVC_EXTENSION //! \}
38.012709
191
0.666505
[ "vector", "model" ]
55490522903414bbf024f3532ad51946c949950b
3,872
cpp
C++
kittycat/PWCatsApi.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
1
2021-02-05T23:20:07.000Z
2021-02-05T23:20:07.000Z
kittycat/PWCatsApi.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
kittycat/PWCatsApi.cpp
siilky/catomania
cb3a05cbef523d16b8929b390e190e0cd5924ee9
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "PWCatsApi.h" #include "version.h" #include "util.h" void PWCatsRequest::reset(QNetworkReply *r) { if (reply_) { delete reply_; } reply_ = r; isParsed_ = false; error_.clear(); } // PWCatsPriceHistoryRequest::PriceElement::PriceElement(const QJsonObject & o) : price(toUInt(o["price"])) , count(toUInt(o["count"])) , name(o["name"].toString()) { if (o.contains("lastupdate")) { ts = o["lastupdate"].toInt(); //QDateTime dt = QDateTime::fromTime_t(t); // was: "yyyy-MM-dd HH:mm:ss" "2016-04-22 09:08:16" } else { qWarning() << "pwcats api: Missing lastupdate field"; ts = 0; } } PWCatsPriceHistoryRequest::PriceHistoryElement::PriceHistoryElement(const QJsonObject & o) : sell(toUInt(o["sell"])) , buy(toUInt(o["buy"])) , time(toUInt(o["time"])) { } template< template<typename, typename ...> class Array, typename Value, typename ... A> static bool getArray(const QJsonObject & o, const QString & name, typename Array<Value, A ...> & array) { array.clear(); QJsonObject::const_iterator it = o.find(name); if (it != o.end() && it->isArray()) { const QJsonArray arr = it->toArray(); for (int i = 0; i < arr.size(); i++) { array.push_back(Value(arr[i].toObject())); } return true; } return false; } // PWCatsPriceHistoryRequest::PWCatsPriceHistoryRequest(int serverId, unsigned itemId) : serverId_(serverId) , itemId_(itemId) { query.addQueryItem("s", QString::number(serverId)); query.addQueryItem("i", QString::number(itemId)); query.addQueryItem("h", getHashString(serverId, itemId)); } void PWCatsPriceHistoryRequest::onRequestFinished() { if (reply_->error() == QNetworkReply::NoError) { QByteArray data = reply_->readAll(); QJsonDocument json = QJsonDocument::fromJson(data); if (!json.isNull() && json.isObject()) { QJsonObject o = json.object(); bool success = o["success"].toBool(false); if (success) { getArray(o, "catsell", sellList); getArray(o, "catbuy", buyList); getArray(o, "komiss_sell", comSellList); getArray(o, "komiss_buy", comBuyList); getArray(o, "static", history); isParsed_ = true; } else { error_ = o["message"].toString(); } } else { error_ = "Invalid format"; } // don't need reply anymore reply_->deleteLater(); reply_ = 0; } emit finished(); } QByteArray PWCatsPriceHistoryRequest::getHashString(int serverId, unsigned itemId) { QDate now = QDateTime::currentDateTimeUtc().date(); QString str = QString("%1%2%3%4%5") .arg(serverId) .arg(now.month(), 2, 10, QLatin1Char('0')) .arg(now.day(), 2, 10, QLatin1Char('0')) .arg(itemId) .arg(now.year()); QByteArray data = str.toLatin1().toBase64(); return QCryptographicHash::hash(data, QCryptographicHash::Sha1).toHex(); } PWCatsApi::PWCatsApi(QObject *parent) : QObject(parent) , qnam_(new QNetworkAccessManager(this)) { } PWCatsApi::~PWCatsApi() { } void PWCatsApi::get(PWCatsRequest *request) { QUrl url("https://pwcats.info/api"); url.setQuery(request->query); qDebug() << "Requesting" << url.toString(); QNetworkRequest req(url); req.setRawHeader("User-Agent", (QString("CatOmania 2.%0/Win") .arg(QString::fromWCharArray(g_revision))).toLatin1()); request->reset(qnam_->get(req)); connect(request->reply_, &QNetworkReply::finished, request, &PWCatsRequest::onRequestFinished); }
26.162162
105
0.582903
[ "object" ]
554b9a7972a9dc157181a52aa4bcf256fa97abeb
458
cpp
C++
Leetcode/Day015/reshape_matrix.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day015/reshape_matrix.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day015/reshape_matrix.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) { int el = nums.size()*nums[0].size(); int n = nums[0].size(); if(el != (r*c)) return nums; vector<vector<int>> ans(r, vector<int> (c,0)); for(int i=0; i<el; i++) //main logic ans[i/c][i%c] = nums[i/n][i%n]; return ans; } };
22.9
79
0.436681
[ "vector" ]
554c80df8ac046b1dab70531fc57e39f149592e7
3,108
cpp
C++
source/muilib/gui/MWndNamespace.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
1
2022-01-30T07:40:31.000Z
2022-01-30T07:40:31.000Z
source/muilib/gui/MWndNamespace.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
null
null
null
source/muilib/gui/MWndNamespace.cpp
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
null
null
null
#include "MWndNamespace.h" #include "MWndcollection.h" /** constructor */ MWndNamespace::MWndNamespace( MWndCollection* pOwner ) : ivPtOwner( pOwner ) { } /** destructor */ MWndNamespace::~MWndNamespace() { ivId2Wnd.clear(); ivWnd2Id.clear(); ivPtOwner = 0; } /** registers a object at the context */ void MWndNamespace::regObj( MObject* pObj, const String& id ) { ASSERT( pObj ); ASSERT( id != "" ); ASSERT( getObj( id ) == 0 ); ivId2Wnd.insert( StrObjMap::value_type( id, pObj ) ); ivWnd2Id.insert( ObjStrMap::value_type( pObj, id ) ); } /** unregisters a object from the context */ void MWndNamespace::unregObj( MObject* pObj ) { ASSERT( pObj ); StrObjMapIter i1 = ivId2Wnd.find( getId( pObj ) ); if( i1 != ivId2Wnd.end() ) ivId2Wnd.erase( ivId2Wnd.find( getId( pObj ) ) ); ObjStrMapIter i2 = ivWnd2Id.find( pObj ); if( i2 != ivWnd2Id.end() ) ivWnd2Id.erase( ivWnd2Id.find( pObj ) ); } /** returns a object from the context */ MObject* MWndNamespace::getObj( const String& id ) { ASSERT( id != "" ); StrObjMapIter i = ivId2Wnd.find( id ); if( i != ivId2Wnd.end() ) return i->second; else return 0; } /** returns the id of a object */ String MWndNamespace::getId( MObject* pObj ) { ASSERT( pObj ); ObjStrMapIter i = ivWnd2Id.find( pObj ); if( i != ivWnd2Id.end() ) return i->second; else return ""; } /** returns a namespace for the given control if available */ MWndNamespace* MWndNamespace::getNamespace( MWnd* pControl ) { MWndNamespace* pBack = 0; MWndCollection* pt = (MWndCollection*) pControl->getParent(); while( pt ) { if( pt->getNamespace() ) { pBack = pt->getNamespace(); break; } pt = (MWndCollection*) pt->getParent(); } return pBack; } /** registers a object in the next available namespace, returns false if failed */ bool MWndNamespace::regObjNS( MObject* pObj, MWnd* pControl, const String& id ) { MWndNamespace* pNameSpace = getNamespace( pControl ); if( pNameSpace ) pNameSpace->regObj( pObj, id ); return pNameSpace != 0; } /** registers a object in the next available namespace, returns false if failed */ bool MWndNamespace::unregObjNS( MObject* pObj, MWnd* pControl ) { MWndNamespace* pNameSpace = getNamespace( pControl ); if( pNameSpace ) pNameSpace->unregObj( pObj ); return pNameSpace != 0; } /** returns the object in the given namespace, if available */ MObject* MWndNamespace::getObjNS( MWndCollection* pCollection, const String& id ) { MObject* pBack = 0; MWndNamespace* pNS = pCollection->getNamespace(); if( pNS ) pBack = pNS->getObj( id ); return pBack; } /** returns the object in the given namespace or in upper namespaces, if available */ MObject* MWndNamespace::getObjFullNS( MWndCollection* pCollection, const String& id ) { MObject* pBack = 0; while( pCollection && pBack == 0 ) { MWndNamespace* pNS = pCollection->getNamespace(); if( pNS ) pBack = pNS->getObj( id ); pCollection = (MWndCollection*) pCollection->getParent(); } return pBack; }
25.064516
86
0.656049
[ "object" ]
554fb5fd4fca39812b82eefe3389d928911cfe21
38,137
cpp
C++
tests/model/model.cpp
nickerso/libcellml
9fe5ecabc3e63c49d5ee8539ed2c8ce572a9712a
[ "Apache-2.0" ]
1
2021-02-15T01:09:04.000Z
2021-02-15T01:09:04.000Z
tests/model/model.cpp
nickerso/libcellml
9fe5ecabc3e63c49d5ee8539ed2c8ce572a9712a
[ "Apache-2.0" ]
8
2019-09-01T23:37:50.000Z
2021-05-27T21:20:34.000Z
tests/model/model.cpp
nickerso/libcellml
9fe5ecabc3e63c49d5ee8539ed2c8ce572a9712a
[ "Apache-2.0" ]
1
2022-02-04T06:11:40.000Z
2022-02-04T06:11:40.000Z
/* Copyright libCellML Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "gtest/gtest.h" #include <libcellml> #include "test_utils.h" TEST(Model, setGetId) { const std::string id = "modelID"; libcellml::ModelPtr m = libcellml::Model::create(); m->setId(id); EXPECT_EQ(id, m->id()); m->removeId(); EXPECT_EQ("", m->id()); } TEST(Model, name) { const std::string n = "name"; const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"name\"/>\n"; libcellml::ModelPtr m = libcellml::Model::create(); m->setName(n); EXPECT_EQ(n, m->name()); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); auto m2 = libcellml::Model::create(n); const std::string a2 = printer->printModel(m2); EXPECT_EQ(e, a2); } TEST(Model, unsetName) { const std::string n = "name"; const std::string eName = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"name\"/>\n"; const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\"/>\n"; libcellml::ModelPtr m = libcellml::Model::create(); m->setName(n); EXPECT_EQ(n, m->name()); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(eName, a); m->setName(""); EXPECT_EQ("", m->name()); a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Model, invalidName) { const std::string n = "invalid name"; const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"invalid name\"/>\n"; libcellml::ModelPtr m = libcellml::Model::create(); m->setName(n); EXPECT_EQ(n, m->name()); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Model, addComponent) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component/>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Model, addValidNamedComponent) { const std::string in = "valid_name"; const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"valid_name\"/>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); c->setName(in); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Model, addInvalidNamedComponent) { const std::string in = "invalid name"; const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"invalid name\"/>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c = libcellml::Component::create(); c->setName(in); m->addComponent(c); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Model, addTwoNamedComponents) { const std::string name1 = "component_1"; const std::string name2 = "component_2"; const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"component_1\"/>\n" " <component name=\"component_2\"/>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c1 = libcellml::Component::create(); c1->setName(name1); m->addComponent(c1); libcellml::ComponentPtr c2 = libcellml::Component::create(); m->addComponent(c2); // once the component is added, we should be able to change the handle to the component and have those changes // reflected in the model? Yes we are using shared pointers. c2->setName(name2); // so should this give an error? Nope libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); } TEST(Model, countComponents) { libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c1 = libcellml::Component::create(); libcellml::ComponentPtr c2 = libcellml::Component::create(); c1->setName("child1"); c2->setName("child2"); EXPECT_EQ(size_t(0), m->componentCount()); m->addComponent(c1); m->addComponent(c2); EXPECT_EQ(size_t(2), m->componentCount()); } TEST(Model, containsComponent) { libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c1 = libcellml::Component::create(); libcellml::ComponentPtr c2 = libcellml::Component::create(); c1->setName("child1"); c2->setName("child2"); EXPECT_FALSE(m->containsComponent("child1")); m->addComponent(c1); m->addComponent(c2); EXPECT_TRUE(m->containsComponent("child2")); } TEST(Model, removeComponent) { const std::string e1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"child2\"/>\n" "</model>\n"; const std::string e2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"child2\"/>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c1 = libcellml::Component::create(); libcellml::ComponentPtr c2 = libcellml::Component::create(); c1->setName("child1"); c2->setName("child2"); m->addComponent(c1); m->addComponent(c2); EXPECT_EQ(size_t(2), m->componentCount()); EXPECT_TRUE(m->removeComponent(0)); EXPECT_EQ(size_t(1), m->componentCount()); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(e1, a); EXPECT_FALSE(m->removeComponent(1)); m->addComponent(c1); // Remove the first occurrence of "child1". EXPECT_TRUE(m->removeComponent("child1")); EXPECT_EQ(size_t(1), m->componentCount()); a = printer->printModel(m); EXPECT_EQ(e2, a); // Expect no change to model. EXPECT_FALSE(m->removeComponent("child3")); EXPECT_EQ(size_t(1), m->componentCount()); } TEST(Model, componentMethods) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"childA\"/>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c1 = libcellml::Component::create(); c1->setName("child1"); m->addComponent(c1); libcellml::ComponentPtr cA = m->component(0); cA->setName("childA"); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); // Using const version of overloaded method const libcellml::ComponentPtr cB = m->component(0); // Can do this as we just have a const pointer cB->setName("gus"); EXPECT_EQ("gus", cB->name()); EXPECT_EQ(nullptr, m->component(4)); } TEST(Model, takeComponentMethods) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\"/>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c1 = libcellml::Component::create(); libcellml::ComponentPtr c2 = libcellml::Component::create(); c1->setName("child1"); c2->setName("child2"); m->addComponent(c1); m->addComponent(c2); libcellml::ComponentPtr c02 = m->takeComponent(1); EXPECT_EQ(size_t(1), m->componentCount()); EXPECT_EQ(m->takeComponent(4), nullptr); EXPECT_EQ("child2", c02->name()); EXPECT_EQ(nullptr, c02->parent()); libcellml::ComponentPtr c01 = m->takeComponent("child1"); EXPECT_NE(nullptr, c01); EXPECT_EQ(size_t(0), m->componentCount()); EXPECT_EQ("child1", c01->name()); EXPECT_EQ(nullptr, c01->parent()); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); // Expect no change. EXPECT_EQ(size_t(0), m->componentCount()); EXPECT_EQ(nullptr, m->takeComponent("child4")); EXPECT_EQ(size_t(0), m->componentCount()); } static int count = 0; class big_and_complicated { // lots of complicated code public: int id; big_and_complicated() : id(count + 101) { ++count; } ~big_and_complicated() { --count; } }; struct structure { structure() : m_data {new big_and_complicated {}} { std::cout << "structure constructor: " << m_data->id << std::endl; } structure(const structure &rhs) : m_data {new big_and_complicated {}} { std::cout << "structure copy constructor: " << rhs.m_data->id << std::endl; m_data->id = rhs.m_data->id; } structure(structure &&rhs) noexcept : m_data(rhs.m_data) { std::cout << "structure move constructor: " << m_data->id << std::endl; rhs.m_data = nullptr; } structure &operator=(structure rhs) { rhs.swap(*this); return *this; } void swap(structure &rhs) noexcept { std::swap(m_data, rhs.m_data); } ~structure() { std::cout << "structure destructor: "; if (m_data != nullptr) { std::cout << m_data->id << std::endl; } else { std::cout << std::endl; } delete m_data; } private: big_and_complicated *m_data = nullptr; }; TEST(Model, replaceComponent) { const std::string e_orig = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"child1\"/>\n" " <component name=\"child2\"/>\n" "</model>\n"; const std::string e_after = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"child1\"/>\n" " <component name=\"child3\"/>\n" "</model>\n"; const std::string e_post = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component name=\"child5\"/>\n" " <component name=\"child3\"/>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ComponentPtr c1 = libcellml::Component::create(); libcellml::ComponentPtr c2 = libcellml::Component::create(); libcellml::ComponentPtr c3 = libcellml::Component::create(); libcellml::ComponentPtr c4 = libcellml::Component::create(); libcellml::ComponentPtr c5 = libcellml::Component::create(); c1->setName("child1"); c2->setName("child2"); c3->setName("child3"); c4->setName("child4"); c5->setName("child5"); m->addComponent(c1); m->addComponent(c2); libcellml::PrinterPtr printer = libcellml::Printer::create(); std::string a = printer->printModel(m); EXPECT_EQ(e_orig, a); // Attempt to replace non-existent component. EXPECT_FALSE(m->replaceComponent(5, c3)); // Replace existing component. EXPECT_TRUE(m->replaceComponent(1, c3)); EXPECT_EQ(m, c3->parent()); a = printer->printModel(m); EXPECT_EQ(e_after, a); // Nothing happens when trying to replace a component that doesn't match // the given name. EXPECT_FALSE(m->replaceComponent("child5", c4)); EXPECT_EQ(nullptr, c4->parent()); EXPECT_TRUE(m->replaceComponent("child1", c4)); EXPECT_EQ(m, c4->parent()); EXPECT_TRUE(m->replaceComponent(c4, c5)); EXPECT_EQ(m, c5->parent()); a = printer->printModel(m); EXPECT_EQ(e_post, a); } TEST(Model, constructors) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"my_name\">\n" " <component/>\n" "</model>\n"; const std::string n = "my_name"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ModelPtr m1; libcellml::ModelPtr m2; m->setName(n); m->addComponent(libcellml::Component::create()); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(e, a); //Testing copy constructor libcellml::ModelPtr &m3(m); EXPECT_EQ("my_name", m3->name()); // Testing model assignment m1 = m; EXPECT_EQ("my_name", m->name()); // Testing move assignment for model m2 = std::move(m1); EXPECT_EQ("my_name", m2->name()); // Testing move constructor for component libcellml::ModelPtr m4 = std::move(m2); EXPECT_EQ("my_name", m4->name()); } TEST(Model, setAndCheckIdsAllEntities) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"mname\" id=\"mid\">\n" " <import xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"some-other-model.xml\" id=\"i1id\">\n" " <component component_ref=\"a_component_in_that_model\" name=\"c1name\" id=\"c1id\"/>\n" " </import>\n" " <import xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"some-other-different-model.xml\" id=\"i2id\">\n" " <units units_ref=\"a_units_in_that_model\" name=\"u1name\" id=\"u1id\"/>\n" " </import>\n" " <units name=\"u2name\" id=\"u2id\"/>\n" " <units name=\"u3name\" id=\"u3id\"/>\n" " <component name=\"c2name\" id=\"c2id\">\n" " <variable name=\"vname\" units=\"u1name\" id=\"vid\"/>\n" " <reset id=\"r1id\">\n" " <test_value id=\"tvid\"/>\n" " <reset_value id=\"rvid\"/>\n" " </reset>\n" " </component>\n" "</model>\n"; libcellml::ModelPtr m = libcellml::Model::create(); libcellml::ImportSourcePtr i1 = libcellml::ImportSource::create(); libcellml::ImportSourcePtr i2 = libcellml::ImportSource::create(); libcellml::ComponentPtr c1 = libcellml::Component::create(); libcellml::ComponentPtr c2 = libcellml::Component::create(); libcellml::VariablePtr v = libcellml::Variable::create(); libcellml::UnitsPtr u1 = libcellml::Units::create(); libcellml::UnitsPtr u2 = libcellml::Units::create(); libcellml::UnitsPtr u3 = libcellml::Units::create(); libcellml::ResetPtr r1 = libcellml::Reset::create(); i1->setUrl("some-other-model.xml"); c1->setSourceComponent(i1, "a_component_in_that_model"); i2->setUrl("some-other-different-model.xml"); u1->setSourceUnits(i2, "a_units_in_that_model"); m->setName("mname"); c1->setName("c1name"); c2->setName("c2name"); v->setName("vname"); u1->setName("u1name"); u2->setName("u2name"); u3->setName("u3name"); m->setId("mid"); i1->setId("i1id"); i2->setId("i2id"); c1->setId("c1id"); c2->setId("c2id"); v->setId("vid"); u1->setId("u1id"); u2->setId("u2id"); u3->setId("u3id"); r1->setId("r1id"); r1->setTestValueId("tvid"); r1->setResetValueId("rvid"); v->setUnits(u1); c2->addReset(r1); c2->addVariable(v); m->addUnits(u1); m->addUnits(u2); m->addUnits(u3); m->addComponent(c1); m->addComponent(c2); libcellml::PrinterPtr printer = libcellml::Printer::create(); const std::string a = printer->printModel(m); EXPECT_EQ(a, e); } TEST(Model, equivalentVariableCountReportsCorrectlyAfterUsingRemoveComponent) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"model\">\n" " <component name=\"c1\">\n" " <variable name=\"v1\" units=\"dimensionless\"/>\n" " </component>\n" " <component name=\"c2\">\n" " <variable name=\"v2\" units=\"dimensionless\"/>\n" " </component>\n" " <connection component_1=\"c1\" component_2=\"c2\">\n" " <map_variables variable_1=\"v1\" variable_2=\"v2\"/>\n" " </connection>\n" "</model>\n"; auto parser = libcellml::Parser::create(); auto model = parser->parseModel(e); model->removeComponent("c1"); EXPECT_EQ(size_t(0), model->component(0)->variable(0)->equivalentVariableCount()); EXPECT_EQ(nullptr, model->component(0)->variable(0)->equivalentVariable(0)); } TEST(Model, removeComponentInsensitiveToOrder) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"parsed_model\">\n" " <component name=\"c1\">\n" " <variable name=\"v1\" units=\"dimensionless\"/>\n" " </component>\n" " <component name=\"c2\">\n" " <variable name=\"v2\" units=\"dimensionless\"/>\n" " </component>\n" "</model>\n"; auto parser = libcellml::Parser::create(); auto modelParsed = parser->parseModel(e); auto modelApi = libcellml::Model::create("api_model"); // I want to move a component from modelParsed to modelApi auto c1Parsed = modelParsed->component("c1"); modelApi->addComponent(c1Parsed); // Expect one component each EXPECT_EQ(size_t(1), modelParsed->componentCount()); EXPECT_EQ(size_t(1), modelApi->componentCount()); // Remove it from the parsed model: this does nothing because the parent pointer // has already been changed when it was added to the modelApi modelParsed->removeComponent(c1Parsed); // Still expect one component each EXPECT_EQ(size_t(1), modelParsed->componentCount()); EXPECT_EQ(size_t(1), modelApi->componentCount()); // If the order of operations is switched the behaviour is the same: // Get a pointer to the second component in the parsed model. auto c2Parsed = modelParsed->component("c2"); // Remove it from the parsed model. modelParsed->removeComponent(c2Parsed); // Add it to the api model. modelApi->addComponent(c2Parsed); EXPECT_EQ(size_t(0), modelParsed->componentCount()); EXPECT_EQ(size_t(2), modelApi->componentCount()); } TEST(Model, cleanEmptyComponents) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <import xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"\">\n" " <component component_ref=\"\" name=\"\"/>\n" " </import>\n" " <component name=\"c1\"/>\n" " <component id=\"c2\"/>\n" " <component>\n" " <variable/>\n" " </component>\n" " <component>\n" " <reset/>\n" " </component>\n" " <component>abc</component>\n" "</model>\n"; auto model = libcellml::Model::create(); auto c1 = libcellml::Component::create("c1"); auto c2 = libcellml::Component::create(); c2->setId("c2"); auto c3 = libcellml::Component::create(); auto v = libcellml::Variable::create(); c3->addVariable(v); auto c4 = libcellml::Component::create(); auto r = libcellml::Reset::create(); c4->addReset(r); auto c5 = libcellml::Component::create(); c5->setMath("abc"); auto c6 = libcellml::Component::create(); auto importSource = libcellml::ImportSource::create(); c6->setImportSource(importSource); auto c7 = libcellml::Component::create(); model->addComponent(c1); model->addComponent(c2); model->addComponent(c3); model->addComponent(c4); model->addComponent(c5); model->addComponent(c6); model->addComponent(c7); EXPECT_EQ(size_t(7), model->componentCount()); // Call the Model::clean() function to remove empty component. model->clean(); EXPECT_EQ(size_t(6), model->componentCount()); // Check the correct component was cleaned. auto p = libcellml::Printer::create(); EXPECT_EQ(e, p->printModel(model)); } TEST(Model, cleanEmptyUnits) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <import xmlns:xlink=\"http://www.w3.org/1999/xlink\" xlink:href=\"\">\n" " <units units_ref=\"\" name=\"\"/>\n" " </import>\n" " <units name=\"u1\"/>\n" " <units id=\"u2\"/>\n" " <units>\n" " <unit units=\"u4\"/>\n" " </units>\n" "</model>\n"; auto model = libcellml::Model::create(); auto u1 = libcellml::Units::create("u1"); auto u2 = libcellml::Units::create(); u2->setId("u2"); auto u3 = libcellml::Units::create(); auto importSource = libcellml::ImportSource::create(); u3->setImportSource(importSource); auto u4 = libcellml::Units::create(); u4->addUnit("u4"); auto u5 = libcellml::Units::create(); model->addUnits(u1); model->addUnits(u2); model->addUnits(u3); model->addUnits(u4); model->addUnits(u5); EXPECT_EQ(size_t(5), model->unitsCount()); // Call the Model::clean() function to remove empty components and units. model->clean(); EXPECT_EQ(size_t(4), model->unitsCount()); // Check the correct units is being cleaned. auto p = libcellml::Printer::create(); EXPECT_EQ(e, p->printModel(model)); } TEST(Model, cleanEmptyComponentEncapsulation) { const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\">\n" " <component/>\n" " <component name=\"c2\"/>\n" " <component/>\n" " <component name=\"c4\"/>\n" " <encapsulation>\n" " <component_ref>\n" " <component_ref component=\"c2\"/>\n" " <component_ref>\n" " <component_ref component=\"c4\"/>\n" " </component_ref>\n" " </component_ref>\n" " </encapsulation>\n" "</model>\n"; auto model = libcellml::Model::create(); auto c1 = libcellml::Component::create(); auto c2 = libcellml::Component::create("c2"); auto c3 = libcellml::Component::create(); auto c4 = libcellml::Component::create("c4"); auto c5 = libcellml::Component::create(); auto c6 = libcellml::Component::create(); model->addComponent(c1); c1->addComponent(c2); c1->addComponent(c3); c3->addComponent(c4); c3->addComponent(c5); c5->addComponent(c6); // Call the Model::clean() function to remove empty components. model->clean(); auto p = libcellml::Printer::create(); EXPECT_EQ(e, p->printModel(model)); } TEST(Model, cleanModel) { // Make a model with empty components and empty import sources. const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"dirtyModel\">\n" " <units name=\"namedEmptyUnits\"/>\n" " <units id=\"nonEmptyId\"/>\n" " <component name=\"namedEmptyComponent\"/>\n" " <component name=\"nonEmptyComponent\">\n" " <variable name=\"x\" units=\"requiredUnits\"/>\n" " </component>\n" " <component id=\"nonEmptyComponentId\"/>\n" "</model>\n"; auto parser = libcellml::Parser::create(); auto model = parser->parseModel(fileContents("dirty_model.cellml")); auto printer = libcellml::Printer::create(); EXPECT_EQ(size_t(4), model->componentCount()); EXPECT_EQ(size_t(3), model->unitsCount()); // Call the Model::clean() function to remove empty components and units. model->clean(); EXPECT_EQ(size_t(3), model->componentCount()); EXPECT_EQ(size_t(2), model->unitsCount()); EXPECT_EQ(e, printer->printModel(model)); } TEST(Model, cleanEncapsulatedModel) { // Make a model with empty components and empty import sources. const std::string e = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<model xmlns=\"http://www.cellml.org/cellml/2.0#\" name=\"dirtyModel\">\n" " <component name=\"component\"/>\n" " <component name=\"emptyChildComponent\"/>\n" " <component name=\"nonEmptyComponent\">\n" " <variable name=\"x\" units=\"dimensionless\"/>\n" " </component>\n" " <encapsulation>\n" " <component_ref component=\"component\">\n" " <component_ref component=\"emptyChildComponent\"/>\n" " <component_ref component=\"nonEmptyComponent\"/>\n" " </component_ref>\n" " </encapsulation>\n" "</model>\n"; auto parser = libcellml::Parser::create(); auto model = parser->parseModel(fileContents("dirty_encapsulated_model.cellml")); auto printer = libcellml::Printer::create(); model->clean(); EXPECT_EQ(e, printer->printModel(model)); } libcellml::ModelPtr commonSetupImportedUnits() { auto model = libcellml::Model::create(); auto myConcreteUnits = libcellml::Units::create("myConcreteUnits"); auto myImportedUnits = libcellml::Units::create("myImportedUnits"); auto import = libcellml::ImportSource::create(); import->setUrl("import.cellml"); myImportedUnits->setImportSource(import); model->addUnits(myConcreteUnits); model->addUnits(myImportedUnits); EXPECT_TRUE(model->units("myImportedUnits")->isImport()); EXPECT_FALSE(model->units("myConcreteUnits")->isImport()); EXPECT_EQ(size_t(2), model->unitsCount()); return model; } TEST(Model, removeImportedUnitsByName) { auto model = commonSetupImportedUnits(); EXPECT_TRUE(model->removeUnits("myConcreteUnits")); EXPECT_TRUE(model->removeUnits("myImportedUnits")); EXPECT_EQ(size_t(0), model->unitsCount()); } TEST(Model, removeImportedUnitsByIndex) { auto model = commonSetupImportedUnits(); EXPECT_TRUE(model->removeUnits(0)); EXPECT_TRUE(model->removeUnits(0)); EXPECT_EQ(size_t(0), model->unitsCount()); } TEST(Model, removeImportedUnitsByReference) { auto model = commonSetupImportedUnits(); auto myConcreteUnits = model->units(0); auto myImportedUnits = model->units(1); EXPECT_TRUE(model->removeUnits(myConcreteUnits)); EXPECT_TRUE(model->removeUnits(myImportedUnits)); EXPECT_EQ(size_t(0), model->unitsCount()); } TEST(Model, takeImportedUnitsByName) { auto model = commonSetupImportedUnits(); auto takeUnits1 = model->takeUnits("myImportedUnits"); auto takeUnits2 = model->takeUnits("myConcreteUnits"); EXPECT_EQ(size_t(0), model->unitsCount()); } TEST(Model, takeImportedUnitsByIndex) { auto model = commonSetupImportedUnits(); auto takeUnits1 = model->takeUnits(0); auto takeUnits2 = model->takeUnits(0); EXPECT_EQ(size_t(0), model->unitsCount()); } TEST(Model, replaceImportedUnitsByName) { auto model = libcellml::Model::create(); auto myConcreteUnits1 = libcellml::Units::create("myConcreteUnits1"); auto myImportedUnits1 = libcellml::Units::create("myImportedUnits1"); auto myConcreteUnits2 = libcellml::Units::create("myConcreteUnits2"); auto myImportedUnits2 = libcellml::Units::create("myImportedUnits2"); auto import1 = libcellml::ImportSource::create(); auto import2 = libcellml::ImportSource::create(); import1->setUrl("import1.cellml"); import2->setUrl("import2.cellml"); myImportedUnits1->setImportSource(import1); myImportedUnits2->setImportSource(import2); model->addUnits(myConcreteUnits1); model->addUnits(myImportedUnits2); EXPECT_EQ(size_t(2), model->unitsCount()); // REPLACE concrete -> imported by name. EXPECT_TRUE(model->replaceUnits("myConcreteUnits1", myImportedUnits1)); EXPECT_EQ(size_t(2), model->unitsCount()); // REPLACE imported -> concrete by name. EXPECT_TRUE(model->replaceUnits("myImportedUnits2", myConcreteUnits2)); EXPECT_EQ(size_t(2), model->unitsCount()); } TEST(Model, replaceImportedUnitsByIndex) { auto model = libcellml::Model::create(); auto myConcreteUnits1 = libcellml::Units::create("myConcreteUnits1"); auto myImportedUnits1 = libcellml::Units::create("myImportedUnits1"); auto myConcreteUnits2 = libcellml::Units::create("myConcreteUnits2"); auto myImportedUnits2 = libcellml::Units::create("myImportedUnits2"); auto import1 = libcellml::ImportSource::create(); auto import2 = libcellml::ImportSource::create(); import1->setUrl("import1.cellml"); import2->setUrl("import2.cellml"); myImportedUnits1->setImportSource(import1); myImportedUnits2->setImportSource(import2); model->addUnits(myConcreteUnits1); model->addUnits(myImportedUnits2); EXPECT_EQ(size_t(2), model->unitsCount()); // REPLACE concrete -> imported by index. EXPECT_TRUE(model->replaceUnits(0, myImportedUnits1)); EXPECT_EQ(size_t(2), model->unitsCount()); // REPLACE imported -> concrete by index. EXPECT_TRUE(model->replaceUnits(1, myConcreteUnits2)); EXPECT_EQ(size_t(2), model->unitsCount()); } TEST(Model, replaceImportedUnitsByReference) { auto model = libcellml::Model::create(); auto myConcreteUnits1 = libcellml::Units::create("myConcreteUnits1"); auto myImportedUnits1 = libcellml::Units::create("myImportedUnits1"); auto myConcreteUnits2 = libcellml::Units::create("myConcreteUnits2"); auto myImportedUnits2 = libcellml::Units::create("myImportedUnits2"); auto import1 = libcellml::ImportSource::create(); auto import2 = libcellml::ImportSource::create(); import1->setUrl("import1.cellml"); import2->setUrl("import2.cellml"); myImportedUnits1->setImportSource(import1); myImportedUnits2->setImportSource(import2); model->addUnits(myConcreteUnits1); model->addUnits(myImportedUnits2); EXPECT_EQ(size_t(2), model->unitsCount()); // REPLACE concrete -> imported by reference. EXPECT_TRUE(model->replaceUnits(myConcreteUnits1, myImportedUnits1)); EXPECT_EQ(size_t(2), model->unitsCount()); // REPLACE imported -> concrete by reference. EXPECT_TRUE(model->replaceUnits(myImportedUnits2, myConcreteUnits2)); EXPECT_EQ(size_t(2), model->unitsCount()); } libcellml::ModelPtr commonSetupImportedComponent() { auto model = libcellml::Model::create(); auto myConcreteComponent = libcellml::Component::create("myConcreteComponent"); auto myImportedComponent = libcellml::Component::create("myImportedComponent"); auto import = libcellml::ImportSource::create(); import->setUrl("import.cellml"); myImportedComponent->setImportSource(import); model->addComponent(myConcreteComponent); model->addComponent(myImportedComponent); EXPECT_TRUE(model->component("myImportedComponent")->isImport()); EXPECT_FALSE(model->component("myConcreteComponent")->isImport()); EXPECT_EQ(size_t(2), model->componentCount()); return model; } TEST(Model, removeImportedComponentByName) { auto model = commonSetupImportedComponent(); EXPECT_TRUE(model->removeComponent("myConcreteComponent")); EXPECT_TRUE(model->removeComponent("myImportedComponent")); EXPECT_EQ(size_t(0), model->componentCount()); } TEST(Model, removeImportedComponentByIndex) { auto model = commonSetupImportedComponent(); EXPECT_TRUE(model->removeComponent(0)); EXPECT_TRUE(model->removeComponent(0)); EXPECT_EQ(size_t(0), model->componentCount()); } TEST(Model, removeImportedComponentByReference) { auto model = commonSetupImportedComponent(); auto myConcreteComponent = model->component(0); auto myImportedComponent = model->component(1); EXPECT_TRUE(model->removeComponent(myConcreteComponent)); EXPECT_TRUE(model->removeComponent(myImportedComponent)); EXPECT_EQ(size_t(0), model->componentCount()); } TEST(Model, takeImportedComponentByName) { auto model = commonSetupImportedComponent(); auto takeComponent1 = model->takeComponent("myImportedComponent"); auto takeComponent2 = model->takeComponent("myConcreteComponent"); EXPECT_EQ(size_t(0), model->componentCount()); } TEST(Model, takeImportedComponentByIndex) { auto model = commonSetupImportedComponent(); auto takeComponent1 = model->takeComponent(0); auto takeComponent2 = model->takeComponent(0); EXPECT_EQ(size_t(0), model->componentCount()); } TEST(Model, replaceImportedComponentByName) { auto model = libcellml::Model::create(); auto myConcreteComponent1 = libcellml::Component::create("myConcreteComponent1"); auto myImportedComponent1 = libcellml::Component::create("myImportedComponent1"); auto myConcreteComponent2 = libcellml::Component::create("myConcreteComponent2"); auto myImportedComponent2 = libcellml::Component::create("myImportedComponent2"); auto import1 = libcellml::ImportSource::create(); auto import2 = libcellml::ImportSource::create(); import1->setUrl("import1.cellml"); import2->setUrl("import2.cellml"); myImportedComponent1->setImportSource(import1); myImportedComponent2->setImportSource(import2); model->addComponent(myConcreteComponent1); model->addComponent(myImportedComponent2); EXPECT_EQ(size_t(2), model->componentCount()); // REPLACE concrete -> imported by name. EXPECT_TRUE(model->replaceComponent("myConcreteComponent1", myImportedComponent1)); EXPECT_EQ(size_t(2), model->componentCount()); // REPLACE imported -> concrete by name. EXPECT_TRUE(model->replaceComponent("myImportedComponent2", myConcreteComponent2)); EXPECT_EQ(size_t(2), model->componentCount()); } TEST(Model, replaceImportedComponentByIndex) { auto model = libcellml::Model::create(); auto myConcreteComponent1 = libcellml::Component::create("myConcreteComponent1"); auto myImportedComponent1 = libcellml::Component::create("myImportedComponent1"); auto myConcreteComponent2 = libcellml::Component::create("myConcreteComponent2"); auto myImportedComponent2 = libcellml::Component::create("myImportedComponent2"); auto import1 = libcellml::ImportSource::create(); auto import2 = libcellml::ImportSource::create(); import1->setUrl("import1.cellml"); import2->setUrl("import2.cellml"); myImportedComponent1->setImportSource(import1); myImportedComponent2->setImportSource(import2); model->addComponent(myConcreteComponent1); model->addComponent(myImportedComponent2); EXPECT_EQ(size_t(2), model->componentCount()); // REPLACE concrete -> imported by index. EXPECT_TRUE(model->replaceComponent(0, myImportedComponent1)); EXPECT_EQ(size_t(2), model->componentCount()); // REPLACE imported -> concrete by index. EXPECT_TRUE(model->replaceComponent(1, myConcreteComponent2)); EXPECT_EQ(size_t(2), model->componentCount()); } TEST(Model, replaceImportedComponentByReference) { auto model = libcellml::Model::create(); auto myConcreteComponent1 = libcellml::Component::create("myConcreteComponent1"); auto myImportedComponent1 = libcellml::Component::create("myImportedComponent1"); auto myConcreteComponent2 = libcellml::Component::create("myConcreteComponent2"); auto myImportedComponent2 = libcellml::Component::create("myImportedComponent2"); auto import1 = libcellml::ImportSource::create(); auto import2 = libcellml::ImportSource::create(); import1->setUrl("import1.cellml"); import2->setUrl("import2.cellml"); myImportedComponent1->setImportSource(import1); myImportedComponent2->setImportSource(import2); model->addComponent(myConcreteComponent1); model->addComponent(myImportedComponent2); EXPECT_EQ(size_t(2), model->componentCount()); // REPLACE concrete -> imported by index. EXPECT_TRUE(model->replaceComponent(myConcreteComponent1, myImportedComponent1)); EXPECT_EQ(size_t(2), model->componentCount()); // REPLACE imported -> concrete by index. EXPECT_TRUE(model->replaceComponent(myImportedComponent2, myConcreteComponent2)); EXPECT_EQ(size_t(2), model->componentCount()); } TEST(Model, removeAllComponentsImportedChild) { auto model = libcellml::Model::create(); auto c1 = libcellml::Component::create("c1"); auto c2 = libcellml::Component::create("c2"); auto import = libcellml::ImportSource::create(); c2->setImportSource(import); model->addComponent(c2); model->addComponent(c1); EXPECT_EQ(size_t(2), model->componentCount()); model->removeAllComponents(); EXPECT_EQ(size_t(0), model->componentCount()); }
32.707547
125
0.641398
[ "model" ]
5550509b051f01f5f513249220731d66fa07b98b
387
cpp
C++
source/scene_graph/scene_graph.cpp
burz/tap
61f8f2cf2022db99e02992340735e342f4a8394d
[ "MIT" ]
1
2016-10-07T01:52:57.000Z
2016-10-07T01:52:57.000Z
source/scene_graph/scene_graph.cpp
burz/tap
61f8f2cf2022db99e02992340735e342f4a8394d
[ "MIT" ]
null
null
null
source/scene_graph/scene_graph.cpp
burz/tap
61f8f2cf2022db99e02992340735e342f4a8394d
[ "MIT" ]
null
null
null
#include "scene_graph.h" Scene_graph::Scene_graph() : head() { } Scene_graph::~Scene_graph() { } void Scene_graph::add(Geometry *geometry) { int position = 0; while(position < head.number_of_children) { } head.add_child(geometry); } void Scene_graph::add(Scene_graph_node *node) { } void Scene_graph::render(const Camera &camera) { head.cull_and_draw(camera); }
12.09375
46
0.692506
[ "geometry", "render" ]
556186e8454cb74976c07059dfde3050d29032f5
8,985
cpp
C++
src/example_filters.cpp
dringakn/ROSExamples
f4f19d21fab3630c112148e198f117f0466032c4
[ "MIT" ]
2
2020-07-14T19:37:43.000Z
2020-07-15T04:38:09.000Z
src/example_filters.cpp
dringakn/ROSExamples
f4f19d21fab3630c112148e198f117f0466032c4
[ "MIT" ]
null
null
null
src/example_filters.cpp
dringakn/ROSExamples
f4f19d21fab3630c112148e198f117f0466032c4
[ "MIT" ]
null
null
null
/** * Author: Dr. Ing. Ahmad Kamal Nasir * Email: dringakn@gmail.com * Description: * The following example shows how to create mean/median/digital * filters (single/multi channels). Furthermore, how to concatenate * different filters (e.g. increment filter) using chain. * Filter chain can be used to implement band-pass filter. * chain works with built-in filters such as * filters/IncrementFilterInt * filters/MeanFilterFloat * filters/MultiChannelMedianFilterDouble * or with dervied filters as plugin. * * Note: Either use mean filter or increment filter as they have the same * ifndef tag. Otherwise, modify the increment.h file to correct the * ifndef tag. Use plotjuggler to visulize the data. * Filter configurations are stored in filters.yaml file. * * roslaunch ros_examples example_filters.launch * **/ #include <filters/filter_chain.h> // Filter chain #include <filters/increment.h> // Pre-implemented ROS filter #include <filters/mean.h> // Pre-implemented ROS filter #include <filters/median.h> // Pre-implemented ROS filter #include <filters/transfer_function.h> // Pre-implemented ROS filter #include <random_numbers/random_numbers.h> // Random number generator #include <ros/ros.h> // ROS functionality #include <std_msgs/Float32MultiArray.h> // Array message #include <std_msgs/Float64.h> // double message using namespace std; using namespace filters; int main(int argc, char* argv[]) { cout.precision(3); ros::init(argc, argv, "example_filters"); ros::NodeHandle nh("~"); random_numbers::RandomNumberGenerator rng; double update_rate = 1; nh.getParam("update_rate", update_rate); const int CHANNELS = 3; // Number of channels for multi-channel filter // Circular buffer RealtimeCircularBuffer<double> circBuff(10, 0); // Single channel mean/average filter FilterBase<double>* avgFilter = new MeanFilter<double>(); avgFilter->configure("MeanFilter", nh); // Private nh, wrt to node ns // Multi-channel mean/average filter MultiChannelFilterBase<double>* avgMFilter = new MultiChannelMeanFilter<double>(); avgMFilter->configure(CHANNELS, "MultiChannelMeanFilter", nh); // Single channel median filter FilterBase<double>* medFilter = new MedianFilter<double>(); medFilter->configure("MedianFilter", nh); // Multi-channel median filter MultiChannelFilterBase<double>* medMFilter = new MultiChannelMedianFilter<double>(); medMFilter->configure(CHANNELS, "MultiChannelMedianFilter", nh); /* Single-channel low-pass transfer function (digital) filter: a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1]+ ... + b[n_b]*x[n-n_b] - a[1]*y[n-1]- ... - a[n_a]*y[n-n_a] If a[0] is not equal to 1, the coefficients are normalized by a[0]. Example config: <filter type="TransferFunctionFilter" name="filter_name"> <params a="1.0 0.5" b="0.2 0.2"/> </filter> */ FilterBase<double>* tfFilter = new SingleChannelTransferFunctionFilter<double>(); tfFilter->configure("SingleChannelLowPass", nh); // Multi-channel low-pass transfer function filter MultiChannelFilterBase<double>* tfMFilter = new MultiChannelTransferFunctionFilter<double>(); tfMFilter->configure(CHANNELS, "MultiChannelLowPass", nh); // Increment filter for filter chain testing FilterBase<double>* incFilter = new IncrementFilter<double>(); incFilter->configure("IncrementFilter", nh); // Multi-chain Increment filter for filter chain testing MultiChannelFilterBase<int>* incMFilter = new MultiChannelIncrementFilter<int>(); incMFilter->configure(CHANNELS, "MultiChannelIncrementFilter", nh); // Chain filter FilterChain<int> chainFilter("int"); chainFilter.configure("ThreeIncrements", nh); // Topics and messages for publishing ros::Publisher pubInc = nh.advertise<std_msgs::Float64>("/inc_filter", 1); ros::Publisher pubMean = nh.advertise<std_msgs::Float64>("/mean_filter", 1); ros::Publisher pubMedian = nh.advertise<std_msgs::Float64>("/median_filter", 1); ros::Publisher pubTF = nh.advertise<std_msgs::Float64>("/digital_filter", 1); ros::Publisher pubMInc = nh.advertise<std_msgs::Float32MultiArray>("/multi_inc_filter", 1); ros::Publisher pubMMean = nh.advertise<std_msgs::Float32MultiArray>("/multi_mean_filter", 1); ros::Publisher pubMMedian = nh.advertise<std_msgs::Float32MultiArray>("/multi_median_filter", 1); ros::Publisher pubMTF = nh.advertise<std_msgs::Float32MultiArray>("/multi_digital_filter", 1); std_msgs::Float64 msgMean, msgMedian, msgTF, msgInc; std_msgs::Float32MultiArray msgMMean, msgMMedian, msgMTF, msgMInc; msgMMean.layout.dim.push_back(std_msgs::MultiArrayDimension()); msgMMedian.layout.dim.push_back(std_msgs::MultiArrayDimension()); msgMTF.layout.dim.push_back(std_msgs::MultiArrayDimension()); msgMInc.layout.dim.push_back(std_msgs::MultiArrayDimension()); msgMMean.layout.data_offset = msgMMedian.layout.data_offset = msgMTF.layout.data_offset = msgMInc.layout.data_offset = 0; // offset msgMMean.layout.dim[0].label = "MeanFiltered"; // Array name msgMMedian.layout.dim[0].label = "MedianFiltered"; msgMTF.layout.dim[0].label = "DigitalFiltered"; msgMInc.layout.dim[0].label = "IncFiltered"; msgMMean.layout.dim[0].size = msgMMedian.layout.dim[0].size = msgMTF.layout.dim[0].size = msgMInc.layout.dim[0].size = CHANNELS; // Number of elements msgMMean.layout.dim[0].stride = msgMMedian.layout.dim[0].stride = msgMTF.layout.dim[0].stride = msgMInc.layout.dim[0].stride = CHANNELS * 4; // Number of bytes msgMInc.data.resize(CHANNELS); // Adjust array size msgMMean.data.resize(CHANNELS); // Adjust array size msgMMedian.data.resize(CHANNELS); // Adjust array size msgMTF.data.resize(CHANNELS); // Adjust array size double in, out; // single-channel filter input/output vector<double> inputs(CHANNELS); // multi-channel filter inputs vector<double> outputs(CHANNELS); // multi-channel filter outputs ros::Rate loop_rate(update_rate); while (ros::ok()) { // Generate a single-channel filter sample in = rng.gaussian(0, 1); // Generate multi-channel filter sample for (int i = 0; i < CHANNELS; i++) inputs[i] = rng.gaussian(0, 1); // Add it to the circular buffer circBuff.push_back(in); cout << "Circular Buffer: "; for (int i = 0; i < circBuff.size(); i++) cout << circBuff[i] << ((i < circBuff.size() - 1) ? ", " : "\r\n"); // Pass it to the mean/average filter ang get the filtered output avgFilter->update(in, msgMean.data); avgMFilter->update(inputs, outputs); cout << "Mean : " << in << " -> " << msgMean.data << endl; for (int i = 0; i < CHANNELS; i++) { cout << "Mean-" << i << ": " << inputs[i] << " -> " << outputs[i] << endl; msgMMean.data[i] = outputs[i]; } // Pass it to the median filter ang get the filtered output medFilter->update(in, msgMedian.data); medMFilter->update(inputs, outputs); cout << "Median : " << in << " -> " << msgMedian.data << endl; for (int i = 0; i < CHANNELS; i++) { cout << "Median-" << i << ": " << inputs[i] << " -> " << outputs[i] << endl; msgMMedian.data[i] = outputs[i]; } // Pass it to the low-pass tf filter ang get the filtered output tfFilter->update(in, msgTF.data); tfMFilter->update(inputs, outputs); cout << "TF : " << in << " -> " << msgTF.data << endl; for (int i = 0; i < CHANNELS; i++) { cout << "TF-" << i << ": " << inputs[i] << " -> " << outputs[i] << endl; msgMTF.data[i] = outputs[i]; } // Pass it to the increment filter ang get the incremented output (in+1) incFilter->update(in, msgInc.data); std::vector<int> vin(begin(inputs), end(inputs)), vout(CHANNELS); incMFilter->update(vin, vout); cout << "INC : " << in << " -> " << msgInc.data << endl; for (int i = 0; i < CHANNELS; i++) { cout << "INC-" << i << ": " << vin[i] << " -> " << vout[i] << endl; msgMInc.data[i] = vout[i]; } // Pass it to the chain filter ang get the incremented output int intIn = 1, intOut = 0; chainFilter.update(intIn, intOut); cout << "CHAIN : " << intIn << " -> " << intOut << endl; // chainFilter.update(in, out); // cout << "CHAIN : " << in << " -> " << out << endl; cout << endl; // Publish it on respective topics pubMean.publish(msgMean); pubMedian.publish(msgMedian); pubTF.publish(msgTF); pubMMean.publish(msgMMean); pubMMedian.publish(msgMMedian); pubMTF.publish(msgMTF); ros::spinOnce(); loop_rate.sleep(); } return 0; }
41.40553
80
0.648859
[ "vector" ]
55654904fb7ef127170b196e614fc8acef3f4cf3
3,530
cpp
C++
tc 160+/FoxProgression.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
3
2015-05-25T06:24:37.000Z
2016-09-10T07:58:00.000Z
tc 160+/FoxProgression.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
null
null
null
tc 160+/FoxProgression.cpp
ibudiselic/contest-problem-solutions
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
[ "BSD-2-Clause" ]
5
2015-05-25T06:24:40.000Z
2021-08-19T19:22:29.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; class FoxProgression { public: int theCount(vector <int> seq) { if (seq.size() == 1) { return -1; } int add = seq[1] - seq[0]; int mul = seq[1] / seq[0]; vector<int> possible; bool ok = true; for (int i=1; i<(int)seq.size(); ++i) { if (seq[i-1]+add != seq[i]) { ok = false; break; } } if (ok) { possible.push_back(seq.back() + add); } if (seq[1]>=seq[0] && seq[1]%seq[0]==0) { ok = true; for (int i=1; i<(int)seq.size(); ++i) { if (seq[i-1]*mul != seq[i]) { ok = false; break; } } if (ok) { possible.push_back(seq.back()*mul); } } sort(possible.begin(), possible.end()); return unique(possible.begin(), possible.end()) - possible.begin(); } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {1, 2, 4, 8}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(0, Arg1, theCount(Arg0)); } void test_case_1() { int Arr0[] = {5, 3, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(1, Arg1, theCount(Arg0)); } void test_case_2() { int Arr0[] = {1, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(2, Arg1, theCount(Arg0)); } void test_case_3() { int Arr0[] = {8, 4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(3, Arg1, theCount(Arg0)); } void test_case_4() { int Arr0[] = {1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = -1; verify_case(4, Arg1, theCount(Arg0)); } void test_case_5() { int Arr0[] = {4, 8}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(5, Arg1, theCount(Arg0)); } void test_case_6() { int Arr0[] = {1, 3, 4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 0; verify_case(6, Arg1, theCount(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { FoxProgression ___test; ___test.run_test(-1); } // END CUT HERE
42.53012
365
0.516714
[ "vector" ]
5565b37187eca8a73a6b8cbdc6cf33e416c7909b
9,239
cpp
C++
src/puzzles/sudoku/board.cpp
huwlloyd-mmu/jpop
8a749ec5d92b3a6d67ea898a5b4282113dc7ea4b
[ "MIT" ]
null
null
null
src/puzzles/sudoku/board.cpp
huwlloyd-mmu/jpop
8a749ec5d92b3a6d67ea898a5b4282113dc7ea4b
[ "MIT" ]
null
null
null
src/puzzles/sudoku/board.cpp
huwlloyd-mmu/jpop
8a749ec5d92b3a6d67ea898a5b4282113dc7ea4b
[ "MIT" ]
null
null
null
#include "board.h" #include <iostream> #include <iomanip> #include <inttypes.h> #include <string> #include <sstream> #include <fstream> // // description of a sudoku board, with functions for setting cells and propagating constraints // Board::Board(const string &fileOrPuzzleString, bool fromFile) { string puzzleString; if (fromFile) puzzleString = ReadFile(fileOrPuzzleString); else puzzleString = fileOrPuzzleString; // check this is an order 3, 4, or 5 puzzle switch (puzzleString.length()) { case 81: order = 3; break; case 256: order = 4; break; case 625: order = 5; break; case 1296: order = 6; break; case 2401: order = 7; break; case 4096: order = 8; break; default: std::cerr << "wrong number of cells for a sudoku board!" << std::endl; order = 0; break; } numUnits = order * order; numCells = numUnits * numUnits; cells = new ValueSet[numCells]; int maxVal = numUnits; for (int i = 0; i < numCells; i++) cells[i].Init(maxVal); // set all possibilities for all cells for ( int i = 0; i < numCells; i++ ) { cells[i] = ~cells[i]; } // set the known cells one by one numInfeasible = 0; numFixedCells = 0; for (int i = 0; i < numCells; i++) { if (puzzleString[i] != '.') { int value; switch (order) { case 3: value = (int)(puzzleString[i] - '0'); break; case 4: if (puzzleString[i] >= '0' && puzzleString[i] <= '9') value = 1+(int)(puzzleString[i] - '0'); else value = 11 + (int)(puzzleString[i] - 'a'); break; case 5: default: value = 1+(int)(puzzleString[i] - 'a'); } SetCell( i, ValueSet(maxVal, (int64_t)1 << (value-1) )); } } } Board::Board(const Board &other) { Copy(other); } void Board::Copy(const Board& other) { order = other.order; numUnits = order * order; numCells = numUnits * numUnits; if (cells == nullptr) cells = new ValueSet[numCells]; int maxVal = numUnits; for (int i = 0; i < numCells; i++) cells[i] = other.GetCell(i); numFixedCells = other.FixedCellCount(); numInfeasible = other.InfeasibleCellCount(); } Board::~Board() { if ( cells != nullptr ) delete [] cells; } std::string Board::ReadFile(const std::string &fileName) { char *puzString; ifstream inFile; inFile.open(fileName); if (inFile.is_open()) { int order, idum; inFile >> order; int numCells = order * order*order*order; inFile >> idum; puzString = new char[numCells + 1]; for (int i = 0; i < numCells; i++) { int val; inFile >> val; if (val == -1) puzString[i] = '.'; else if (order == 3) puzString[i] = '1' + (val - 1); else if (order == 4) if (val < 11) puzString[i] = '0' + val - 1; else puzString[i] = 'a' + val - 11; else puzString[i] = 'a' + val - 1; } puzString[numCells] = 0; inFile.close(); string retVal = string(puzString); delete[] puzString; return retVal; } else { cerr << "could not open file: " << fileName << endl; return string(); } } int Board::RowCell(int iRow, int iCell) const { // returns cell index of the iCell'th cell in the iRow'th row return iRow * numUnits + iCell; } int Board::ColCell(int iCol, int iCell) const { // returns cell index of the iCell'th cell in the iCol'th column return iCell * numUnits + iCol; } int Board::BoxCell(int iBox, int iCell) const { // returns cell index of the iCell'th cell in the iBox'th box int boxCol = iBox%order; int boxRow = iBox / order; int topCorner = (boxCol*order) + boxRow*order*order*order; return topCorner + (iCell%order) + (iCell / order)*order*order; } int Board::RowForCell(int iCell) const { // returns index of the row which contains cell iCell return iCell / numUnits; } int Board::ColForCell(int iCell) const { // returns index of the column which contains cell iCell return iCell % numUnits; } int Board::BoxForCell(int iCell) const { // returns index of the box which contains cell iCell return order*(iCell / (order*order*order)) + ((iCell%(order*order))/order); } string Board::AsString(bool useNumbers, bool showUnfixed ) { /* Form a human-readable string from the board, using either numbers (1..numUnits) or a single character per cell (9x9 - 1-9, 16x16 0-f, 25x25 - a-y). If showUnfixed is true, show the possibilies in an unfixed cell (otherwise represent it is as '.'). If order is 4 or 5 and showUnfixed is true, force useNumbers to false for readability. */ if ( showUnfixed ) useNumbers = false; stringstream puzString; string alphabet; if ( !useNumbers ) { if ( order == 3 ) alphabet = string("123456789"); else if (order == 4 ) alphabet = string("0123456789abcdef"); else alphabet = string("abcdefghijklmnopqrstuvwxy"); } vector<string> cellStrings; unsigned int maxLen = 0; for (int i = 0; i < numCells; i++) { string cellContents; if ( !useNumbers ) { if ( !showUnfixed && !cells[i].Fixed()) cellContents = string("."); else cellContents = cells[i].toString(alphabet); } else cellContents = to_string(cells[i].Index() + 1); if (cellContents.size() > maxLen ) maxLen = (int)cellContents.size(); cellStrings.push_back(cellContents); } int pitch = maxLen+1; for ( int i = 0; i < numCells; i++ ) { puzString << setw(pitch) << cellStrings[i] << " "; if ( i%numUnits == numUnits -1 ) { if ( i != numCells-1 ) puzString << endl; } else if (i%order == order-1 ) puzString << string("|"); if ( i%(numUnits*order) == numUnits*order-1 && i != numCells-1) { for ( int j = 0; j < order; j++ ) { for ( int k = 0; k < order*(pitch+1); k++ ) puzString << '-'; if ( j != order-1 ) puzString << '+'; } puzString << endl; } } return puzString.str(); } void Board::ConstrainCell(int i ) { if ( cells[i].Empty() || cells[i].Fixed() ) return; // already set or empty int iBox, iCol, iRow; iBox = BoxForCell(i); iCol = ColForCell(i); iRow = RowForCell(i); // set of all fixed cells in row, column, box ValueSet colFixed(numUnits), rowFixed(numUnits), boxFixed(numUnits); // set of all open values in row, column, box, not including this cell ValueSet colAll(numUnits), rowAll(numUnits), boxAll(numUnits); for (int j = 0; j < numUnits; j++) { int k; k = BoxCell(iBox, j); if (k != i) { if ( cells[k].Fixed() ) boxFixed += cells[k]; boxAll += cells[k]; } k = ColCell(iCol, j); if (k != i) { if ( cells[k].Fixed() ) colFixed += cells[k]; colAll += cells[k]; } k = RowCell(iRow, j); if (k != i) { if ( cells[k].Fixed() ) rowFixed += cells[k]; rowAll += cells[k]; } } ValueSet fixedCellsConstraint = ~(rowFixed + colFixed + boxFixed); if ( fixedCellsConstraint.Fixed() ) SetCell( i, fixedCellsConstraint ); // only one possibility left else { // eliminate all the values already taken in this cell's units cells[i] ^= fixedCellsConstraint; // are any of the remaining values for this cell in the only possible // place in a unit? If so, set the cell to that value if ((cells[i]-rowAll).Fixed()) SetCell(i, cells[i]-rowAll); else if ((cells[i]-colAll).Fixed()) SetCell(i, cells[i]-colAll); else if ((cells[i]-boxAll).Fixed()) SetCell(i, cells[i]-boxAll); } if ( cells[i].Empty()) numInfeasible++; } void Board::SetCell(int i, const ValueSet &c ) { if ( cells[i].Fixed()) return; // already set // set the cell cells[i] = c; ++numFixedCells; // propagate the constraints int iBox, iCol, iRow; iBox = BoxForCell(i); iCol = ColForCell(i); iRow = RowForCell(i); for (int j = 0; j < numUnits; j++) { int k; k = BoxCell(iBox, j); if (k != i) ConstrainCell(k); k = ColCell(iCol, j); if (k != i) ConstrainCell(k); k = RowCell(iRow, j); if (k != i) ConstrainCell(k); } } const ValueSet& Board::GetCell(int i) const { return cells[i]; } int Board::FixedCellCount(void) const { return numFixedCells; } int Board::InfeasibleCellCount(void) const { return numInfeasible; } int Board::CellCount(void) const { return numCells; } int Board::GetNumUnits(void) const { return numUnits; } bool Board::CheckSolution(const Board& other) const { // check that other is 1/ a solution, 2/ consistent with this board if (other.CellCount() != CellCount()) return false; bool isSolution = true; bool isConsistent = true; // check its a solution // first - all cells must be filled for (int i = 0; i < other.CellCount(); i++) { if (!other.GetCell(i).Fixed()) isSolution = false; } // second - all rows, columns, boxes must have one of each number for (int i = 0; i < numUnits; i++) { ValueSet row, col, box; row.Init(numUnits); col.Init(numUnits); box.Init(numUnits); for (int j = 0; j < numUnits; j++) { row += other.GetCell(RowCell(i, j)); col += other.GetCell(ColCell(i, j)); box += other.GetCell(BoxCell(i, j)); } if (row.Count() != numUnits || col.Count() != numUnits || box.Count() != numUnits ) isSolution = false; } // check consistency with this board for (int i = 0; i < CellCount(); i++) { if (GetCell(i).Fixed()) { if (GetCell(i).Index() != other.GetCell(i).Index() ) isConsistent = false; } } return isSolution && isConsistent; }
21.738824
119
0.625392
[ "vector" ]
5569ba91d6192b8cd9e991b309a131d7b7685be6
4,619
cc
C++
ai/DeepCoder/docker/DeepCoder/test/find-program-test.cc
quanpan302/test
313c6e310be0ef608543c23bd52a5466047cd378
[ "Apache-2.0" ]
null
null
null
ai/DeepCoder/docker/DeepCoder/test/find-program-test.cc
quanpan302/test
313c6e310be0ef608543c23bd52a5466047cd378
[ "Apache-2.0" ]
null
null
null
ai/DeepCoder/docker/DeepCoder/test/find-program-test.cc
quanpan302/test
313c6e310be0ef608543c23bd52a5466047cd378
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include "find-program.h" using namespace std; using namespace dsl; TEST(DfsTest, FindProgramTest1) { vector<Example> examples = { {{Value({2, 1, 5})}, Value(1)}, {{Value({-1, 1, 5})}, Value(-1)} }; Attribute attr({Statement(0, Function::ReadList, {}), Statement(1, Function::Minimum, {0})}); auto p = dfs(2, attr, examples); EXPECT_TRUE(static_cast<bool>(p)); EXPECT_EQ(2, p.value().size()); EXPECT_EQ(1, p.value()[1].variable); EXPECT_EQ(Function::Minimum, p.value()[1].function); EXPECT_EQ(0, p.value()[1].arguments[0].variable().value()); } TEST(DfsTest, FindProgramTest2) { vector<Example> examples = { {{Value({2, 1, 5})}, Value({4, 1, 25})}, {{Value({-1, 1, 5})}, Value({1, 1, 25})} }; Attribute attr({ Statement(0, Function::ReadList, {}), Statement(1, Function::Map, {OneArgumentLambda::Pow2, 0}) }); auto p = dfs(2, attr, examples); EXPECT_TRUE(static_cast<bool>(p)); EXPECT_EQ(2, p.value().size()); EXPECT_EQ(1, p.value()[1].variable); EXPECT_EQ(Function::Map, p.value()[1].function); EXPECT_EQ(OneArgumentLambda::Pow2, p.value()[1].arguments[0].one_argument_lambda().value()); EXPECT_EQ(0, p.value()[1].arguments[1].variable().value()); } TEST(DfsTest, FindProgramTest3) { vector<Example> examples = { {{Value({2, 1, 5})}, Value(25)}, {{Value({-1, 1, 5})}, Value(25)} }; Attribute attr({ Statement(0, Function::ReadList, {}), Statement(1, Function::Map, {OneArgumentLambda::Pow2, 0}), Statement(2, Function::Maximum, {1}) }); auto p = dfs(2, attr, examples); EXPECT_TRUE(static_cast<bool>(p)); EXPECT_EQ(3, p.value().size()); EXPECT_EQ(1, p.value()[1].variable); EXPECT_EQ(Function::Map, p.value()[1].function); EXPECT_EQ(OneArgumentLambda::Pow2, p.value()[1].arguments[0].one_argument_lambda().value()); EXPECT_EQ(0, p.value()[1].arguments[1].variable().value()); EXPECT_EQ(2, p.value()[2].variable); EXPECT_EQ(Function::Maximum, p.value()[2].function); EXPECT_EQ(1, p.value()[2].arguments[0].variable().value()); } TEST(SortAndAddTest, FindProgramTest1) { vector<Example> examples = { {{Value({2, 1, 5})}, Value(1)}, {{Value({-1, 1, 5})}, Value(-1)} }; Attribute attr({Statement(0, Function::ReadList, {}), Statement(1, Function::Minimum, {0})}); auto p = sort_and_add(2, attr, examples); EXPECT_TRUE(static_cast<bool>(p)); EXPECT_EQ(2, p.value().size()); EXPECT_EQ(1, p.value()[1].variable); EXPECT_EQ(Function::Minimum, p.value()[1].function); EXPECT_EQ(0, p.value()[1].arguments[0].variable().value()); } TEST(SortAndAddTest, FindProgramTest2) { vector<Example> examples = { {{Value({2, 1, 5})}, Value({4, 1, 25})}, {{Value({-1, 1, 5})}, Value({1, 1, 25})} }; Attribute attr({ Statement(0, Function::ReadList, {}), Statement(1, Function::Map, {OneArgumentLambda::Pow2, 0}) }); auto p = sort_and_add(2, attr, examples); EXPECT_TRUE(static_cast<bool>(p)); EXPECT_EQ(2, p.value().size()); EXPECT_EQ(1, p.value()[1].variable); EXPECT_EQ(Function::Map, p.value()[1].function); EXPECT_EQ(OneArgumentLambda::Pow2, p.value()[1].arguments[0].one_argument_lambda().value()); EXPECT_EQ(0, p.value()[1].arguments[1].variable().value()); } TEST(SortAndAddTest, FindProgramTest3) { vector<Example> examples = { {{Value({2, 1, 5})}, Value(25)}, {{Value({-1, 1, 5})}, Value(25)} }; Attribute attr({ Statement(0, Function::ReadList, {}), Statement(1, Function::Map, {OneArgumentLambda::Pow2, 0}), Statement(2, Function::Maximum, {1}) }); auto p = sort_and_add(2, attr, examples); EXPECT_TRUE(static_cast<bool>(p)); EXPECT_EQ(3, p.value().size()); EXPECT_EQ(1, p.value()[1].variable); EXPECT_EQ(Function::Map, p.value()[1].function); EXPECT_EQ(OneArgumentLambda::Pow2, p.value()[1].arguments[0].one_argument_lambda().value()); EXPECT_EQ(0, p.value()[1].arguments[1].variable().value()); EXPECT_EQ(2, p.value()[2].variable); EXPECT_EQ(Function::Maximum, p.value()[2].function); EXPECT_EQ(1, p.value()[2].arguments[0].variable().value()); }
39.478632
97
0.564841
[ "vector" ]
556d88f7f7a31a42df5f823601a1fdcc3fbbe544
2,058
cc
C++
nipah/readdata.cc
sarabjeet29/Nipah
cc198157f8727bf79224ea679c98672b140b786c
[ "MIT" ]
null
null
null
nipah/readdata.cc
sarabjeet29/Nipah
cc198157f8727bf79224ea679c98672b140b786c
[ "MIT" ]
null
null
null
nipah/readdata.cc
sarabjeet29/Nipah
cc198157f8727bf79224ea679c98672b140b786c
[ "MIT" ]
null
null
null
#include "readdata.h" void read_cached_Gxy(double alpha, double nu, int M, int N, vector<cdouble>& Gxy) { ostringstream dirStringStream, fileStringStream; ifstream inputFile; const char * filepath; const char * dirpath; string line; double realval, imagval; dirStringStream << "./results/alpha=" << int(alpha*100)/100.0 << ",nu=" << int(nu*100)/100.0; dirpath = dirStringStream.str().c_str(); fileStringStream << dirStringStream.str().c_str() << "/Gxy_M=" << M << "_N=" << N << ".txt"; filepath = fileStringStream.str().c_str(); inputFile.open( filepath ); int i = 0; if (inputFile.is_open()) { while ( getline (inputFile, line) ) { istringstream ss(line); ss >> realval >> imagval; Gxy.push_back(cdouble(realval, imagval)); i++; } inputFile.close(); } } void read_cached_Hxzuw(double alpha, double nu, double p, double q, int M, int N, vector<cdouble>& Hxzuw) { ostringstream dirStringStream, fileStringStream; gzFile inputFile; const char * filepath; const char * dirpath; double realval, imagval; string line; dirStringStream << "./results/alpha=" << int(alpha*100)/100.0 << ",nu=" << int(nu*100)/100.0 << "/p=" << int(p*100)/100.0 << ",q=" << int(q*100)/100.0;; dirpath = dirStringStream.str().c_str(); fileStringStream << dirStringStream.str().c_str() << "/Hxzuw_M=" << M << "_N=" << N << ".gz"; filepath = fileStringStream.str().c_str(); inputFile = gzopen(filepath, "rb"); unsigned int size; gzread(inputFile, (void*) &size, sizeof(size)); string data; data.resize(size / sizeof(char)); gzread(inputFile, (void*) data.data(), size); istringstream iss(data); string token; while(getline(iss, token, '\n')) { istringstream values(token); values >> realval >> imagval; Hxzuw.push_back(cdouble(realval, imagval)); } Hxzuw[0] = cdouble(1,0); gzclose(inputFile); }
32.666667
156
0.592323
[ "vector" ]
535c7ba30495fe00afd3b652822e3aae568e496b
1,639
cpp
C++
server/sources/bullet.cpp
Lukasz98/2D-Shooter-LAN-Game
714e25494e92359982bcfa71a31be3254ff256ce
[ "MIT" ]
5
2018-01-20T19:04:53.000Z
2020-04-09T09:35:02.000Z
server/sources/bullet.cpp
Lukasz98/Sfml-Test
714e25494e92359982bcfa71a31be3254ff256ce
[ "MIT" ]
null
null
null
server/sources/bullet.cpp
Lukasz98/Sfml-Test
714e25494e92359982bcfa71a31be3254ff256ce
[ "MIT" ]
null
null
null
#include "../headers/bullet.h" Bullet::Bullet(sf::Vector2f pos, sf::Vector2f speedRatio, int ownerId, int bulletId) { position = pos; this->ownerId = ownerId; this->bulletId = bulletId; speed = 1000.0f; power = 2.0f; this->speedRatio = speedRatio; size = sf::Vector2f(7.0f, 7.0f); } Bullet::~Bullet() { //LOG("Bullet::destructor"); } bool Bullet::Update(float dt) { this->dt = dt; position.x += speed * speedRatio.x * dt; position.y += speed * speedRatio.y * dt; if (power <= 0.0f) return false; return true; } void Bullet::Overlaps(const MapObject * object) { if (isCollision(object->GetPosition(), object->GetSize())) { CollisionReact(10.0f); } } void Bullet::Overlaps(E_Player * ePlayer) { if (ePlayer->GetId() == ownerId) return; sf::Vector2f p = ePlayer->GetPosition(); sf::Vector2f s = ePlayer->GetSize(); if (Math_calc::GetLength(p, position) < s.x * 0.6f) { CollisionReact(10.0f); ePlayer->Damage(51.0f); } } bool Bullet::isCollision(sf::Vector2f objectPos, sf::Vector2f objectSize) { bool collision = true; if (position.x > objectPos.x + objectSize.x) collision = false; if (position.x + size.x * 2 < objectPos.x) collision = false; if (position.y > objectPos.y + objectSize.y) collision = false; if (position.y + size.x * 2 < objectPos.y) collision = false; return collision; } void Bullet::CollisionReact(float power) { this->power -= power; }
21.285714
85
0.574741
[ "object" ]
53656f8fc4139bd6d778c2db39361cd41c329570
2,560
cpp
C++
algo-0126.cpp
jasson15/leetcode-cpp
f20efb521d7cc8405e83c95faf4d45fba2f6d93c
[ "MIT" ]
null
null
null
algo-0126.cpp
jasson15/leetcode-cpp
f20efb521d7cc8405e83c95faf4d45fba2f6d93c
[ "MIT" ]
null
null
null
algo-0126.cpp
jasson15/leetcode-cpp
f20efb521d7cc8405e83c95faf4d45fba2f6d93c
[ "MIT" ]
null
null
null
class Solution { public: int findShortestPath(string& beginWord, string& endWord, unordered_set<string>& dict, unordered_map<string, vector<string>>& graph) { int ret = 2, wlen = beginWord.size(); dict.erase(beginWord); dict.erase(endWord); unordered_set<string> head = { beginWord }, tail = { endWord }; bool flip = false; while(head.size()){ if (head.size() > tail.size()) { swap(head, tail); flip = !flip; } unordered_set<string> nhead; bool found = false; // find nexts int len = head.size(), k = 0; for(auto it = head.begin(); k < len; ++it, ++k){ string cur = *it; for(int i = 0; i < wlen; i++){ char c = cur[i]; for(int j = 0; j < 26; j++){ cur[i] = 'a' + j; if (cur[i] == c) continue; if (tail.find(cur) != tail.end()) found = true; if (tail.find(cur) != tail.end() || dict.find(cur) != dict.end()){ if (flip) graph[cur].push_back(*it); else graph[*it].push_back(cur); nhead.insert(cur); } } cur[i] = c; } } if (found) return ret; for(auto it = nhead.begin(); it != nhead.end(); ++it) dict.erase(*it); swap(head, nhead); ret++; } return 0; } void dfs(vector<vector<string>>& ret, string& beginWord, string& endWord, vector<string>& path, unordered_map<string, vector<string>>& graph){ if (beginWord == endWord) { ret.push_back(path); return; } for(auto& next : graph[beginWord]){ path.push_back(next); dfs(ret, next, endWord, path, graph); path.pop_back(); } } vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) { unordered_map<string, vector<string>> graph; int depth = findShortestPath(beginWord, endWord, wordList, graph); vector<vector<string>> ret; vector<string> path = { beginWord }; dfs(ret, beginWord, endWord, path, graph); return ret; } };
38.208955
146
0.448047
[ "vector" ]
536663c371d7f0b1528844a66feb110510c9db07
270
cpp
C++
Cpp_primer_5th/code_part3/prog3_36.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part3/prog3_36.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
Cpp_primer_5th/code_part3/prog3_36.cpp
Links789/Cpp_primer_5th
18a60b75c358a79fdf006f8cb978c9be6e6aedd5
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <vector> using namespace std; int main(){ int sc1[5] = {1,2,3,4,5}; int sc2[5] = {2,3,4,5,6}; for(int i = 0; i <5 ; i++){ if(sc1[i] == sc2[i]) cout << "y" << endl; else cout << "n" << endl; } return 0; }
13.5
28
0.514815
[ "vector" ]
536a08c3ad5fb700d72c3ae54d1bbb304859d8c2
984
cpp
C++
MFC++/SourceCodes/Chapter7/LambdaExpression.cpp
CoodingPenguin/StudyMaterial
b6d8084fc38673ad6ffb54bc0bc60b2471168810
[ "MIT" ]
9
2019-02-21T20:20:25.000Z
2020-04-14T15:18:59.000Z
MFC++/SourceCodes/Chapter7/LambdaExpression.cpp
CoodingPenguin/StudyMaterial
b6d8084fc38673ad6ffb54bc0bc60b2471168810
[ "MIT" ]
null
null
null
MFC++/SourceCodes/Chapter7/LambdaExpression.cpp
CoodingPenguin/StudyMaterial
b6d8084fc38673ad6ffb54bc0bc60b2471168810
[ "MIT" ]
2
2019-07-09T02:01:37.000Z
2020-01-07T18:45:25.000Z
/* Written by @nErumin (Github) * 2017-01-03 * * Topic - 람다 표현식의 형식을 살펴보자. */ #include <algorithm> #include <numeric> #include <vector> #include <list> #include <deque> #include <string> #include <iostream> #include <forward_list> using namespace std; template <typename Iter, typename Value> Iter findFirstBiggerElement(Iter begin, Iter end, Value val) { return find_if(begin, end, [val](Value elem) { return elem > val; }); } template <typename Iter> void printElements(Iter begin, Iter end) { for_each(begin, end, [](auto value) { cout << value << endl; }); } int main() { auto addFunc = [](int a, int b = 5) -> int { return a + b; }; auto subFunc = [](int a, int b) { return a - b; }; auto fooFunc = [] { cout << "Foo!" << endl; }; addFunc(10, 20); subFunc(20, 30); fooFunc(); vector<int> intVec{ 1, 2, 3, 4, 5 }; auto iter = findFirstBiggerElement(intVec.cbegin(), intVec.cend(), 100); printElements(intVec.cbegin(), intVec.cend()); return 0; }
19.294118
73
0.64126
[ "vector" ]