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
dcd69873df973de9199e1e39585374a498a340fa
3,560
cpp
C++
OpenGL/src/Model.cpp
Zaangetsuu/OpenGL
9f01092bdee14aff7e8716728e40021dd6772851
[ "MIT" ]
null
null
null
OpenGL/src/Model.cpp
Zaangetsuu/OpenGL
9f01092bdee14aff7e8716728e40021dd6772851
[ "MIT" ]
null
null
null
OpenGL/src/Model.cpp
Zaangetsuu/OpenGL
9f01092bdee14aff7e8716728e40021dd6772851
[ "MIT" ]
null
null
null
#include "Model.h" #include <iostream> #include <assimp/Importer.hpp> #include <assimp/postprocess.h> #include "VertexBuffer.h" #include "VertexBufferLayout.h" Model::Model(const char* path) { loadModel(path); } Model::~Model() { } void Model::AddInstancedArray(const VertexBuffer& vbo, const VertexBufferLayout& layout, unsigned position) { unsigned int nbElems = layout.GetElements().size(); for (auto& mesh : m_Meshes) { auto& vao = mesh.m_VAO; vao->Bind(); vao->AddBuffer(vbo, layout, position); for (unsigned int j = 0; j < nbElems; ++j) { vao->DefineInstancedAttribute(position + j, 1); } vao->Unbind(); } } void Model::loadModel(const std::string& path) { Assimp::Importer importer; const aiScene *scene = importer.ReadFile(path, aiProcess_Triangulate | aiProcess_FlipUVs); if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { std::cout << "Error : Model loading : " << importer.GetErrorString() << std::endl; return; } m_Directory = path.substr(0, path.find_last_of('/')) + "/"; processNode(scene->mRootNode, scene); } void Model::processNode(aiNode* node, const aiScene* scene) { for (unsigned int i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; m_Meshes.push_back(processMesh(mesh, scene)); } for (unsigned int i = 0; i < node->mNumChildren; i++) { processNode(node->mChildren[i], scene); } } Mesh Model::processMesh(aiMesh* mesh, const aiScene* scene) { std::vector<Vertex> vertices; std::vector<unsigned int> indices; std::vector<TextureInformation> textures; // Vertices for (unsigned int i = 0; i < mesh->mNumVertices; i++) { Vertex vertex; vertex.Position = glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z); vertex.Normal = glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z); if (mesh->HasTextureCoords(0)) { vertex.TexCoords = glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y); } else { vertex.TexCoords = glm::vec2(0.0f, 0.0f); } vertices.push_back(vertex); } // Indices for (unsigned int i = 0; i < mesh->mNumFaces; i++) { for (unsigned int j = 0; j < mesh->mFaces[i].mNumIndices; j++) { indices.push_back(mesh->mFaces[i].mIndices[j]); } } // Textures if (mesh->mMaterialIndex >= 0) { aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; std::vector<TextureInformation> diffuseMaps = loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); std::vector<TextureInformation> specularMaps = loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); std::vector<TextureInformation> reflectionMaps = loadMaterialTextures(material, aiTextureType_AMBIENT, "texture_reflection"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); textures.insert(textures.end(), reflectionMaps.begin(), reflectionMaps.end()); } return Mesh(vertices, indices, textures); } std::vector<TextureInformation> Model::loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName) { std::vector<TextureInformation> textures; for (unsigned int i = 0; i < mat->GetTextureCount(type); i++) { aiString str; (void)mat->GetTexture(type, i, &str); TextureInformation texture; texture.type = typeName; texture.path = m_Directory + str.C_Str(); textures.push_back(texture); } return textures; }
27.8125
127
0.692135
[ "mesh", "vector", "model" ]
dcdbf3e735e39631f23d49000f6fbcd368260cd7
7,625
hpp
C++
Browser/links.hpp
venam/Browser
3118593d18bd9ff488c5eb17b173f8b8fddd615b
[ "curl" ]
36
2015-01-14T08:56:27.000Z
2021-11-06T23:36:58.000Z
Browser/links.hpp
informaticacba/Browser
3118593d18bd9ff488c5eb17b173f8b8fddd615b
[ "curl" ]
3
2016-02-23T04:24:57.000Z
2018-10-17T08:38:36.000Z
Browser/links.hpp
informaticacba/Browser
3118593d18bd9ff488c5eb17b173f8b8fddd615b
[ "curl" ]
14
2016-02-23T00:21:10.000Z
2021-11-06T23:36:59.000Z
/* Copyright (c) 2013, Patrick Louis <patrick at unixhub.net> All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. The author is informed of the use of his/her code. The author does not have to consent to the use; however he/she must be informed. 2. If the author wishes to know when his/her code is being used, it the duty of the author to provide a current email address at the top of his/her code, above or included in the copyright statement. 3. The author can opt out of being contacted, by not providing a form of contact in the copyright statement. 4. If any portion of the author’s code is used, credit must be given. a. For example, if the author’s code is being modified and/or redistributed in the form of a closed-source binary program, then the end user must still be made somehow aware that the author’s work has contributed to that program. b. If the code is being modified and/or redistributed in the form of code to be compiled, then the author’s name in the copyright statement is sufficient. 5. The following copyright statement must be included at the beginning of the code, regardless of binary form or source code form. 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. Except as contained in this notice, the name of a copyright holder shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization of the copyright holder. */ #ifndef LINKS_HPP_INCLUDED #define LINKS_HPP_INCLUDED #include <cstring> #include <iostream> #include <vector> #include <iomanip> #include <map> #include "regex.hpp" class links_class; class link_struct; std::ostream &operator<<( std::ostream &flux, link_struct const& link_to_display ); class link_struct { public: std::string url() { return url_; } std::string name() { return name_; } std::string title() { return title_; } std::string target() { return target_; } std::string clas() { return class_; } std::string id() { return id_; } friend class links_class; friend std::ostream &operator<<( std::ostream &flux, link_struct const& link_to_display ); private: protected: std::string url_; std::string name_; std::string title_; std::string target_; std::string class_; std::string id_; void clear_link(); void stream_it(std::ostream & flux) const; }; class links_class { public: //overload the << to cout all forms //overload [ ] to return int size(); std::string all(); link_struct operator[ ] (int ite); void getlinks(std::string raw_input); void clear(); private: protected: std::vector <link_struct> links_array; }; ///===============================clear the links array==============================/// void links_class::clear() { links_array.clear(); } ///==================================================================================/// ///=========================Return all the links=====================================/// std::string links_class::all() { std::string output=""; for(int i=0;i<size();i++) { output+=links_array[i].url(); output+="\n"; } return output; } ///==================================================================================/// ///=========Get all links in a raw_html_input and saves it in an array===============/// void links_class::getlinks(std::string raw_input) { std::vector <std::string> temp_raw_links_container; //wrong!!! there thousands of a in a page //a better way to do that would be: //remove all comments //find href ... go backward until we find a 'a' // or maybe here untile we find '<' //then go backward ignoring spaces // the first char should be a '<' (we save that as the first index) //then go forward after the href until we find < //ignore spaces //if there's a slash or backslash //we continue ignoring spaces and if it's followed by a 'a' //and after the 'a' we have a ' ' or a '>' (we save that as the last index) //then voila!! get_from_intern(raw_input, "href","a", temp_raw_links_container); link_struct temp_link; for(unsigned int ii=0;ii<temp_raw_links_container.size();ii++) { temp_link.clear_link(); temp_link.target_ = get_after_equal(temp_raw_links_container[ii], "target"); temp_link.id_ = get_after_equal(temp_raw_links_container[ii], "id"); temp_link.class_ = get_after_equal(temp_raw_links_container[ii], "class"); temp_link.title_ = get_after_equal(temp_raw_links_container[ii], "title"); temp_link.url_ = get_after_equal(temp_raw_links_container[ii], "href"); temp_link.name_ = get_between_two_closed(temp_raw_links_container[ii],"a"); links_array.push_back(temp_link); } } ///==================================================================================/// ///===============================EMPTY A LINK_struct================================/// void link_struct::clear_link() { url_ = ""; name_ = ""; title_ = ""; target_= ""; id_ = ""; class_ = ""; } ///==================================================================================/// ///=======================Overloading of the streaming operator======================/// //return simply the url, the part the most used of a link void link_struct::stream_it(std::ostream & flux) const { flux << url_; } std::ostream &operator<<( std::ostream &flux, link_struct const& link_to_display ) { link_to_display.stream_it(flux); // <- we change it here return flux; } ///==================================================================================/// ///==================Return the number of links found in a page======================/// int links_class::size() { return (links_array.size()); } ///==================================================================================/// ///======================Overloading of [] to return the link========================/// link_struct links_class::operator[ ] (int ite) { //return the link which has a url, name, title, target if((unsigned int)ite<links_array.size() && ite>-1) return (links_array[ite]); else { std::cerr<<"\n[!] No Such link, using the last link as default\n"; return (links_array[links_array.size()-1]); } } ///==================================================================================/// #endif // LINKS_HPP_INCLUDED
37.195122
241
0.585311
[ "vector" ]
dce52b5835ef3f9618f6c132ba28b86f97367988
6,423
cpp
C++
src/netlist/event_system/event_handler.cpp
kammoh/hal
3bd7f56ec59639bcb9c0976ed074412e707e330e
[ "MIT" ]
1
2022-03-30T22:20:19.000Z
2022-03-30T22:20:19.000Z
src/netlist/event_system/event_handler.cpp
kammoh/hal
3bd7f56ec59639bcb9c0976ed074412e707e330e
[ "MIT" ]
null
null
null
src/netlist/event_system/event_handler.cpp
kammoh/hal
3bd7f56ec59639bcb9c0976ed074412e707e330e
[ "MIT" ]
null
null
null
#include "hal_core/netlist/event_system/event_handler.h" #include "hal_core/netlist/event_system/event_log.h" #include "hal_core/netlist/gate.h" #include "hal_core/netlist/grouping.h" #include "hal_core/netlist/module.h" #include "hal_core/netlist/netlist.h" namespace hal { template<> std::vector<std::string> EnumStrings<NetlistEvent::event>::data = {"id_changed", "input_filename_changed", "design_name_changed", "device_name_changed", "marked_global_vcc", "marked_global_gnd", "unmarked_global_vcc", "unmarked_global_gnd", "marked_global_input", "marked_global_output", "marked_global_inout", "unmarked_global_input", "unmarked_global_output", "unmarked_global_inout"}; template<> std::vector<std::string> EnumStrings<GateEvent::event>::data = {"created", "removed", "name_changed", "location_changed", "boolean_function_changed"}; template<> std::vector<std::string> EnumStrings<NetEvent::event>::data = {"created", "removed", "name_changed", "src_added", "src_removed", "dst_added", "dst_removed"}; template<> std::vector<std::string> EnumStrings<ModuleEvent::event>::data = {"created", "removed", "name_changed", "type_changed", "parent_changed", "submodule_added", "submodule_removed", "gate_assigned", "gate_removed", "input_port_name_changed", "output_port_name_changed"}; template<> std::vector<std::string> EnumStrings<GroupingEvent::event>::data = {"created", "removed", "name_changed", "gate_assigned", "gate_removed", "net_assigned", "net_removed", "module_assigned", "module_removed"}; EventHandler::EventHandler() : netlist_event_enabled(true), module_event_enabled(true), gate_event_enabled(true), net_event_enabled(true), grouping_event_enabled(true) { } void EventHandler::event_enable_all(bool flag) { netlist_event_enabled = flag; module_event_enabled = flag; gate_event_enabled = flag; net_event_enabled = flag; grouping_event_enabled = flag; } void EventHandler::notify(NetlistEvent::event c, Netlist* netlist, u32 associated_data) { if (netlist_event_enabled) { m_netlist_callback(c, netlist, associated_data); event_log::handle_netlist_event(c, netlist, associated_data); } } void EventHandler::notify(GateEvent::event c, Gate* gate, u32 associated_data) { if (gate_event_enabled) { m_gate_callback(c, gate, associated_data); event_log::handle_gate_event(c, gate, associated_data); } } void EventHandler::notify(NetEvent::event c, Net* net, u32 associated_data) { if (net_event_enabled) { m_net_callback(c, net, associated_data); event_log::handle_net_event(c, net, associated_data); } } void EventHandler::notify(ModuleEvent::event c, Module* module, u32 associated_data) { // ModuleEvent::dump(c, true); if (module_event_enabled) { m_module_callback(c, module, associated_data); event_log::handle_module_event(c, module, associated_data); } } void EventHandler::notify(GroupingEvent::event c, Grouping* grouping, u32 associated_data) { if (grouping_event_enabled) { m_grouping_callback(c, grouping, associated_data); event_log::handle_grouping_event(c, grouping, associated_data); } } void EventHandler::register_callback(const std::string& name, std::function<void(GateEvent::event, Gate*, u32)> function) { m_gate_callback.add_callback(name, function); } void EventHandler::register_callback(const std::string& name, std::function<void(GroupingEvent::event, Grouping*, u32)> function) { m_grouping_callback.add_callback(name, function); } void EventHandler::register_callback(const std::string& name, std::function<void(ModuleEvent::event, Module*, u32)> function) { m_module_callback.add_callback(name, function); } void EventHandler::register_callback(const std::string& name, std::function<void(NetEvent::event, Net*, u32)> function) { m_net_callback.add_callback(name, function); } void EventHandler::register_callback(const std::string& name, std::function<void(NetlistEvent::event, Netlist*, u32)> function) { m_netlist_callback.add_callback(name, function); } void EventHandler::unregister_callback(const std::string& name) { m_netlist_callback.remove_callback(name); m_module_callback.remove_callback(name); m_gate_callback.remove_callback(name); m_net_callback.remove_callback(name); m_grouping_callback.remove_callback(name); } } // namespace hal
44.916084
171
0.513779
[ "vector" ]
dce5438bf45f2f00022ae793898103c7fc01e49a
15,434
cc
C++
chrome/browser/chromeos/file_system_provider/fileapi/buffering_file_stream_writer_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/file_system_provider/fileapi/buffering_file_stream_writer_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/chromeos/file_system_provider/fileapi/buffering_file_stream_writer_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/file_system_provider/fileapi/buffering_file_stream_writer.h" #include <memory> #include <string> #include <vector> #include "base/macros.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "content/public/test/test_browser_thread_bundle.h" #include "net/base/io_buffer.h" #include "net/base/net_errors.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace file_system_provider { namespace { // Size of the intermediate buffer in bytes. const int kIntermediateBufferLength = 8; // Testing text to be written. The length must be 5 bytes, to invoke all code // paths for buffering. const char kShortTextToWrite[] = "Kitty"; // Testing text to be written. The length must be longr than the intermediate // buffer length, in order to invoke a direct write. const char kLongTextToWrite[] = "Welcome to my world!"; // Pushes a value to the passed log vector. template <typename T> void LogValue(std::vector<T>* log, T value) { log->push_back(value); } // Fake inner file stream writer. class FakeFileStreamWriter : public storage::FileStreamWriter { public: FakeFileStreamWriter(std::vector<std::string>* write_log, std::vector<int>* flush_log, int* cancel_counter, net::Error write_error) : pending_bytes_(0), write_log_(write_log), flush_log_(flush_log), cancel_counter_(cancel_counter), write_error_(write_error) {} ~FakeFileStreamWriter() override {} // storage::FileStreamWriter overrides. int Write(net::IOBuffer* buf, int buf_len, const net::CompletionCallback& callback) override { DCHECK(write_log_); write_log_->push_back(std::string(buf->data(), buf_len)); pending_bytes_ += buf_len; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, write_error_ == net::OK ? buf_len : write_error_)); return net::ERR_IO_PENDING; } int Cancel(const net::CompletionCallback& callback) override { DCHECK(cancel_counter_); DCHECK_EQ(net::OK, write_error_); ++(*cancel_counter_); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, net::OK)); return net::ERR_IO_PENDING; } int Flush(const net::CompletionCallback& callback) override { DCHECK(flush_log_); flush_log_->push_back(pending_bytes_); pending_bytes_ = 0; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, net::OK)); return net::ERR_IO_PENDING; } private: int pending_bytes_; std::vector<std::string>* write_log_; // Not owned. std::vector<int>* flush_log_; // Not owned. int* cancel_counter_; // Not owned. net::Error write_error_; DISALLOW_COPY_AND_ASSIGN(FakeFileStreamWriter); }; } // namespace class FileSystemProviderBufferingFileStreamWriterTest : public testing::Test { protected: FileSystemProviderBufferingFileStreamWriterTest() {} void SetUp() override { short_text_buffer_ = make_scoped_refptr(new net::StringIOBuffer(kShortTextToWrite)); long_text_buffer_ = make_scoped_refptr(new net::StringIOBuffer(kLongTextToWrite)); ASSERT_LT(short_text_buffer_->size(), long_text_buffer_->size()); } ~FileSystemProviderBufferingFileStreamWriterTest() override {} content::TestBrowserThreadBundle thread_bundle_; scoped_refptr<net::StringIOBuffer> short_text_buffer_; scoped_refptr<net::StringIOBuffer> long_text_buffer_; }; TEST_F(FileSystemProviderBufferingFileStreamWriterTest, Write) { std::vector<std::string> inner_write_log; std::vector<int> inner_flush_log; BufferingFileStreamWriter writer( base::WrapUnique(new FakeFileStreamWriter( &inner_write_log, &inner_flush_log, NULL, net::OK)), kIntermediateBufferLength); ASSERT_LT(kIntermediateBufferLength, 2 * short_text_buffer_->size()); // Writing for the first time should succeed, but buffer the write without // calling the inner file stream writer. { std::vector<int> write_log; const int result = writer.Write(short_text_buffer_.get(), short_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(short_text_buffer_->size(), result); EXPECT_EQ(0u, write_log.size()); EXPECT_EQ(0u, inner_write_log.size()); EXPECT_EQ(0u, inner_flush_log.size()); } // Writing for the second time should however flush the intermediate buffer, // since it is full. { inner_write_log.clear(); inner_flush_log.clear(); std::vector<int> write_log; const int result = writer.Write(short_text_buffer_.get(), short_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::ERR_IO_PENDING, result); const std::string expected_inner_write = (std::string(kShortTextToWrite) + kShortTextToWrite) .substr(0, kIntermediateBufferLength); ASSERT_EQ(1u, inner_write_log.size()); EXPECT_EQ(expected_inner_write, inner_write_log[0]); ASSERT_EQ(1u, write_log.size()); EXPECT_EQ(short_text_buffer_->size(), write_log[0]); EXPECT_EQ(0u, inner_flush_log.size()); } // There should be a remainder in the intermediate buffer. Calling flush // should invoke a write on the inner file stream writer. { inner_write_log.clear(); inner_flush_log.clear(); std::vector<int> flush_log; const int result = writer.Flush(base::Bind(&LogValue<int>, &flush_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::ERR_IO_PENDING, result); ASSERT_EQ(1u, flush_log.size()); EXPECT_EQ(net::OK, flush_log[0]); const std::string expected_inner_write = (std::string(kShortTextToWrite) + kShortTextToWrite) .substr(kIntermediateBufferLength, std::string::npos); ASSERT_EQ(1u, inner_write_log.size()); EXPECT_EQ(expected_inner_write, inner_write_log[0]); const int expected_inner_flush = 2 * short_text_buffer_->size(); ASSERT_EQ(1u, inner_flush_log.size()); EXPECT_EQ(expected_inner_flush, inner_flush_log[0]); } } TEST_F(FileSystemProviderBufferingFileStreamWriterTest, Write_WithError) { std::vector<std::string> inner_write_log; std::vector<int> inner_flush_log; BufferingFileStreamWriter writer( std::unique_ptr<storage::FileStreamWriter>(new FakeFileStreamWriter( &inner_write_log, &inner_flush_log, NULL, net::ERR_FAILED)), kIntermediateBufferLength); ASSERT_LT(kIntermediateBufferLength, 2 * short_text_buffer_->size()); // Writing for the first time should succeed, but buffer the write without // calling the inner file stream writer. Because of that, the error will // not be generated unless the intermediate buffer is flushed. { std::vector<int> write_log; const int result = writer.Write(short_text_buffer_.get(), short_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(short_text_buffer_->size(), result); EXPECT_EQ(0u, write_log.size()); EXPECT_EQ(0u, inner_write_log.size()); EXPECT_EQ(0u, inner_flush_log.size()); } // Writing for the second time should however flush the intermediate buffer, // since it is full. That should generate an error. { inner_write_log.clear(); inner_flush_log.clear(); std::vector<int> write_log; const int result = writer.Write(short_text_buffer_.get(), short_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::ERR_IO_PENDING, result); const std::string expected_inner_write = (std::string(kShortTextToWrite) + kShortTextToWrite) .substr(0, kIntermediateBufferLength); ASSERT_EQ(1u, inner_write_log.size()); EXPECT_EQ(expected_inner_write, inner_write_log[0]); ASSERT_EQ(1u, write_log.size()); EXPECT_EQ(net::ERR_FAILED, write_log[0]); EXPECT_EQ(0u, inner_flush_log.size()); } } TEST_F(FileSystemProviderBufferingFileStreamWriterTest, Write_Directly) { std::vector<std::string> inner_write_log; std::vector<int> inner_flush_log; BufferingFileStreamWriter writer( std::unique_ptr<storage::FileStreamWriter>(new FakeFileStreamWriter( &inner_write_log, &inner_flush_log, NULL, net::OK)), kIntermediateBufferLength); ASSERT_GT(kIntermediateBufferLength, short_text_buffer_->size()); ASSERT_LT(kIntermediateBufferLength, long_text_buffer_->size()); // Write few bytes first, so the intermediate buffer is not empty. { std::vector<int> write_log; const int result = writer.Write(short_text_buffer_.get(), short_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(short_text_buffer_->size(), result); EXPECT_EQ(0u, write_log.size()); EXPECT_EQ(0u, inner_flush_log.size()); } // Request writing a long chunk of data, which is longr than size of the // intermediate buffer. { inner_write_log.clear(); inner_flush_log.clear(); std::vector<int> write_log; const int result = writer.Write(long_text_buffer_.get(), long_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::ERR_IO_PENDING, result); ASSERT_EQ(2u, inner_write_log.size()); EXPECT_EQ(kShortTextToWrite, inner_write_log[0]); EXPECT_EQ(kLongTextToWrite, inner_write_log[1]); ASSERT_EQ(1u, write_log.size()); EXPECT_EQ(long_text_buffer_->size(), write_log[0]); EXPECT_EQ(0u, inner_flush_log.size()); } // Write a long chunk again, to test the case with an empty intermediate // buffer. { inner_write_log.clear(); inner_flush_log.clear(); std::vector<int> write_log; const int result = writer.Write(long_text_buffer_.get(), long_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::ERR_IO_PENDING, result); ASSERT_EQ(1u, inner_write_log.size()); EXPECT_EQ(kLongTextToWrite, inner_write_log[0]); ASSERT_EQ(1u, write_log.size()); EXPECT_EQ(long_text_buffer_->size(), write_log[0]); EXPECT_EQ(0u, inner_flush_log.size()); } } TEST_F(FileSystemProviderBufferingFileStreamWriterTest, Cancel) { std::vector<std::string> inner_write_log; std::vector<int> inner_flush_log; int inner_cancel_counter = 0; BufferingFileStreamWriter writer( std::unique_ptr<storage::FileStreamWriter>(new FakeFileStreamWriter( &inner_write_log, &inner_flush_log, &inner_cancel_counter, net::OK)), kIntermediateBufferLength); // Write directly, so there is something to actually cancel. Note, that // buffered writes which do not invoke flushing the intermediate buffer finish // immediately, so they are not cancellable. std::vector<int> write_log; const int write_result = writer.Write(long_text_buffer_.get(), long_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); EXPECT_EQ(net::ERR_IO_PENDING, write_result); std::vector<int> cancel_log; const int cancel_result = writer.Cancel(base::Bind(&LogValue<int>, &cancel_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::ERR_IO_PENDING, cancel_result); ASSERT_EQ(1u, cancel_log.size()); EXPECT_EQ(net::OK, cancel_log[0]); EXPECT_EQ(1, inner_cancel_counter); } TEST_F(FileSystemProviderBufferingFileStreamWriterTest, Flush) { std::vector<std::string> inner_write_log; std::vector<int> inner_flush_log; BufferingFileStreamWriter writer( std::unique_ptr<storage::FileStreamWriter>(new FakeFileStreamWriter( &inner_write_log, &inner_flush_log, NULL, net::OK)), kIntermediateBufferLength); // Write less bytes than size of the intermediate buffer. std::vector<int> write_log; const int write_result = writer.Write(short_text_buffer_.get(), short_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(short_text_buffer_->size(), write_result); EXPECT_EQ(0u, write_log.size()); EXPECT_EQ(0u, inner_write_log.size()); EXPECT_EQ(0u, inner_flush_log.size()); // Calling Flush() will force flushing the intermediate buffer before it's // filled out. std::vector<int> flush_log; const int flush_result = writer.Flush(base::Bind(&LogValue<int>, &flush_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::ERR_IO_PENDING, flush_result); ASSERT_EQ(1u, flush_log.size()); EXPECT_EQ(net::OK, flush_log[0]); ASSERT_EQ(1u, inner_write_log.size()); EXPECT_EQ(kShortTextToWrite, inner_write_log[0]); ASSERT_EQ(1u, inner_flush_log.size()); EXPECT_EQ(short_text_buffer_->size(), inner_flush_log[0]); } TEST_F(FileSystemProviderBufferingFileStreamWriterTest, Flush_AfterWriteError) { std::vector<std::string> inner_write_log; std::vector<int> inner_flush_log; BufferingFileStreamWriter writer( std::unique_ptr<storage::FileStreamWriter>(new FakeFileStreamWriter( &inner_write_log, &inner_flush_log, NULL, net::ERR_FAILED)), kIntermediateBufferLength); // Write less bytes than size of the intermediate buffer. This should succeed // since the inner file stream writer is not invoked. std::vector<int> write_log; const int write_result = writer.Write(short_text_buffer_.get(), short_text_buffer_->size(), base::Bind(&LogValue<int>, &write_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(short_text_buffer_->size(), write_result); EXPECT_EQ(0u, write_log.size()); EXPECT_EQ(0u, inner_write_log.size()); EXPECT_EQ(0u, inner_flush_log.size()); // Calling Flush() will force flushing the intermediate buffer before it's // filled out. That should cause failing. std::vector<int> flush_log; const int flush_result = writer.Flush(base::Bind(&LogValue<int>, &flush_log)); base::RunLoop().RunUntilIdle(); EXPECT_EQ(net::ERR_IO_PENDING, flush_result); ASSERT_EQ(1u, flush_log.size()); EXPECT_EQ(net::ERR_FAILED, flush_log[0]); ASSERT_EQ(1u, inner_write_log.size()); EXPECT_EQ(kShortTextToWrite, inner_write_log[0]); // Flush of the inner file stream writer is not invoked, since a Write method // invocation fails before it. EXPECT_EQ(0u, inner_flush_log.size()); } } // namespace file_system_provider } // namespace chromeos
37.100962
94
0.687962
[ "vector" ]
dceb41102f63aa940f1689c63e3235485962c561
4,902
cpp
C++
vegastrike/objconv/hashtest.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/objconv/hashtest.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/objconv/hashtest.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#ifndef _WIN32 #include <ext/hash_map> #define stdext __gnu_cxx #else #include <hash_map> #endif #ifndef _WIN32 #include <sys/time.h> #include <sys/types.h> #else #include <windows.h> static LONGLONG ttime; static LONGLONG newtime = 0; static LONGLONG freq; static double dblnewtime; #endif #include <map> #include "../src/vs_random.h" VSRandom vsrandom( 11376130011 ); size_t globmax = 1024; class size { public: size_t num; size() { num = (size_t) vsrandom.genrand_int32()%globmax; } bool operator==( const size &a ) const { return this->num == a.num; } operator size_t() const { return num; } }; bool operator<( const size &a, const size &b ) { return a.num < b.num; } #ifndef _WIN32 namespace stdext { template < > class hash< size > { hash< size_t >a; public: size_t operator()( const size &s ) const { return a( s.num ); } }; } #endif double firsttime = 0; double queryTime() { #ifdef _WIN32 LONGLONG tmpnewtime; QueryPerformanceCounter( (LARGE_INTEGER*) &tmpnewtime ); return ( (double) tmpnewtime )/(double) freq-firsttime; #elif 1 struct timeval tv; (void) gettimeofday( &tv, NULL ); double tmpnewtime = (double) tv.tv_sec+(double) tv.tv_usec*1.e-6; return tmpnewtime-firsttime; #elif defined (HAVE_SDL) double tmpnewtime = SDL_GetTicks()*1.e-3; return tmpnewtime-firsttime; #else # error "We have no way to determine the time on this system." return 0.; #endif } double getTime() { return queryTime(); } std::map< size_t, size_t > pod; stdext::hash_map< size, size >clas; int main( int argc, char **argv ) { #ifdef _WIN32 QueryPerformanceFrequency( (LARGE_INTEGER*) &freq ); QueryPerformanceCounter( (LARGE_INTEGER*) &ttime ); #endif size_t lima = (size_t) atof( argv[1] ); size_t limb = (size_t) atof( argv[2] ); size_t limc = (size_t) atof( argv[3] ); size_t limd = (size_t) atof( argv[4] ); size_t lime = (size_t) atof( argv[5] ); globmax = lime; std::vector< size >sdata( limb ); double first = getTime(); for (size_t i = 0; i < lima; ++i) { size ins, dat; pod[ins.num] = dat.num; clas[ins] = dat; } double second = getTime(); int sum = 0; size tmp; for (size_t j = 0; j < limc; ++j) for (size_t i = 0; i < limb; ++i) { size_t num = sdata[i].num; sum += (pod.find( num ) != pod.end() ? pod.find( num )->second : 0); } double third = getTime(); for (size_t j = 0; j < limc; ++j) for (size_t i = 0; i < limb; ++i) { size_t num = sdata[i].num; tmp.num = num; sum += (clas.find( tmp ) != clas.end() ? clas.find( tmp )->second.num : 0); } double fourth = getTime(); for (size_t j = 0; j < limc; ++j) { for (size_t i = 0; i < limb; ++i) { size_t num = sdata[i].num; pod.insert( std::pair< size_t, size_t > ( num, num ) ); } if (j != limc-1 && j < limd) { for (size_t i = 0; i < limb; ++i) { size_t num = sdata[i].num; if ( pod.find( num ) == pod.end() ) { //printf ("error deleting item not in class\n"); } else { pod.erase( pod.find( num ) ); } } } } double fifth = getTime(); for (size_t j = 0; j < limc; ++j) { for (size_t i = 0; i < limb; ++i) { tmp.num = sdata[i].num; clas.insert( std::pair< size, size > ( tmp, tmp ) ); } if (j != limc-1) { for (size_t i = 0; i < limb; ++i) { tmp.num = sdata[i].num; if ( clas.find( tmp ) == clas.end() ) { //printf ("error deleting item not in class\n"); } else { clas.erase( clas.find( tmp ) ); } } } } double sixth = getTime(); for (size_t j = 0; j < limc; ++j) for (size_t i = 0; i < limb; ++i) { size_t num = sdata[i].num; sum += pod.find( num )->second; } double seventh = getTime(); for (size_t j = 0; j < limc; ++j) for (size_t i = 0; i < limb; ++i) { size_t num = sdata[i].num; tmp.num = num; sum += clas.find( tmp )->second.num; } double eighth = getTime(); printf( "Outer Array Size %d. Num Important Elem %d. Repeats %d. Num Erases %d\nInitial Hit Percent %f\n", pod.size(), sdata.size(), limc, limd, sdata.size()/(double) lime ); printf( "Find Percent Times %f %f\n", third-second, fourth-third ); printf( "Insert/Erase Times %f %f\n", fifth-fourth, sixth-fifth ); printf( "Find all itm Times %f %f\n", seventh-sixth, eighth-seventh ); return sum; }
27.852273
110
0.526316
[ "vector" ]
dceba6c61bb7f22cae64457d1287d31daaae7a1a
3,257
hpp
C++
NWNXLib/Utils.hpp
GideonCrawle/unified
2a310e0012badfcc9675bd8c8554613b5354e21a
[ "MIT" ]
null
null
null
NWNXLib/Utils.hpp
GideonCrawle/unified
2a310e0012badfcc9675bd8c8554613b5354e21a
[ "MIT" ]
null
null
null
NWNXLib/Utils.hpp
GideonCrawle/unified
2a310e0012badfcc9675bd8c8554613b5354e21a
[ "MIT" ]
null
null
null
#pragma once #include "API/CGameObject.hpp" #include "API/CNWSScriptVarTable.hpp" #include "API/Vector.hpp" #include "API/CGameEffect.hpp" #include "API/CExoLocString.hpp" #include "API/CNWSMessage.hpp" #include "Utils/String.hpp" #include <string> #include <cstring> namespace NWNXLib::Utils { std::string ObjectIDToString(const ObjectID id); std::string GetCurrentScript(); void ExecuteScript(const std::string& script, ObjectID oidOwner); // Since there's no RTTI, and NWN's dynamic casts don't work in NWNX. // These return nullptr if the object type isn't right. CNWSArea* AsNWSArea(CGameObject* obj); CNWSAreaOfEffectObject* AsNWSAreaOfEffectObject(CGameObject* obj); CNWSCreature* AsNWSCreature(CGameObject* obj); CNWSDoor* AsNWSDoor(CGameObject* obj); CNWSEncounter* AsNWSEncounter(CGameObject* obj); CNWSItem* AsNWSItem(CGameObject* obj); CNWSModule* AsNWSModule(CGameObject* obj); CNWSObject* AsNWSObject(CGameObject* obj); CNWSPlaceable* AsNWSPlaceable(CGameObject* obj); CNWSSoundObject* AsNWSSoundObject(CGameObject* obj); CNWSStore* AsNWSStore(CGameObject* obj); CNWSTrigger* AsNWSTrigger(CGameObject* obj); CNWSWaypoint* AsNWSWaypoint(CGameObject* obj); CGameObject* GetGameObject(ObjectID objectId); CNWSModule* GetModule(); // Wrappers around non-virtual methods repeated for all NWS types bool AcquireItem(CNWSItem *pItem, CGameObject *pOwner); bool AddToArea(CGameObject *pObject, CNWSArea *pArea, float x, float y, float z); bool operator==(Vector& v1, Vector& v2); bool operator!=(Vector& v1, Vector& v2); // Returns TRUE if the var tables have the same variables with same values bool CompareVariables(CNWSScriptVarTable *pVars1, CNWSScriptVarTable *pVars2); CNWSScriptVarTable *GetScriptVarTable(CGameObject *pObject); void DestroyGameEffect(CGameEffect* pEffect); std::string ExtractLocString(CExoLocString& locStr, int32_t nID = 0, uint8_t bGender = 0); template <typename T> inline T PeekMessage(CNWSMessage *pMessage, int32_t offset) { static_assert(std::is_pod<T>::value); T value; uint8_t *ptr = pMessage->m_pnReadBuffer + pMessage->m_nReadBufferPtr + offset; std::memcpy(&value, ptr, sizeof(T)); return value; } template <> inline std::string PeekMessage<std::string>(CNWSMessage *pMessage, int32_t offset) { std::string string; auto length = PeekMessage<int32_t>(pMessage, offset); string.reserve(length + 1); string.assign(reinterpret_cast<const char*>(pMessage->m_pnReadBuffer + pMessage->m_nReadBufferPtr + offset + 4), length); string[length] = '\0'; return string; } void AddStealthEvent(int32_t which, ObjectID oidSelf, ObjectID oidTarget); void AddObjectEnterAreaEvent(ObjectID oid, ObjectID oidArea); void AddObjectExitAreaEvent(ObjectID oid, ObjectID oidArea); void AddOnAcquireItemEvent(ObjectID oidItem, ObjectID oidBy, ObjectID oidFrom, int32_t stackSize); void AddOnLoseItemEvent(ObjectID oidItem, ObjectID oidBy); void AddDestroyObjectEvent(ObjectID oid); // Returns the SP int PushScriptContext(ObjectID oid, bool valid = true); int PopScriptContext(); void SetOrientation(CNWSObject *pObject, float facing); }
35.021505
125
0.745471
[ "object", "vector" ]
dced0c6384a53fde67b4d50fc58b47eea5df9b87
12,792
cpp
C++
multimedia/danim/src/appel/utils/ipc.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
multimedia/danim/src/appel/utils/ipc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
multimedia/danim/src/appel/utils/ipc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/******************************************************************************* Copyright (c) 1995-96 Microsoft Corporation Abstract: {Insert General Comment Here} *******************************************************************************/ #include "headers.h" #include "privinc/ipc.h" #pragma warning(disable:4200) DeclareTag(tagIPCEntry, "IPC", "Entry/Exit"); DeclareTag(tagIPC, "IPC", "General Msgs"); UINT DAMessageId; static DWORD DAThreadTlsIndex = 0xFFFFFFFF; static CritSect * threadCS = NULL; typedef list <DAThread *> DAThreadList; static DAThreadList * threadList = NULL; #define DATHREAD_CLASS "ThreadClass" bool DAIPCWorker::AttachToThread() { DetachFromThread(); _hwnd = ::CreateWindow (DATHREAD_CLASS, "", 0, 0, 0, 0, 0, NULL, NULL, hInst, NULL); if (!_hwnd) return false; // Store the object in the user data area of the window SetWindowLongPtr (_hwnd, GWLP_USERDATA, (LONG_PTR) this) ; _dwThreadId = GetCurrentThreadId(); #if DEVELOPER_DEBUG char buf[1024]; wsprintf(buf, "IPCWorker(%s): Attaching to thread - threadid - %#lx, hwnd - %#lx\n", GetName(), _dwThreadId, _hwnd); OutputDebugString(buf); #endif return true; } void DAIPCWorker::DetachFromThread() { // Cleanup by removing everything associated with the hwnd if (_hwnd) { #if DEVELOPER_DEBUG char buf[1024]; wsprintf(buf, "IPCWorker(%s): Detaching from thread - threadid - %#lx, hwnd - %#lx\n", GetName(), _dwThreadId, _hwnd); OutputDebugString(buf); #endif SetWindowLongPtr (_hwnd, GWLP_USERDATA, NULL) ; DestroyWindow(_hwnd); _hwnd = NULL; _dwThreadId = 0; } } bool DAIPCWorker::SendMsg(DWORD dwMsg, DWORD dwTimeout, DWORD dwNum, va_list args) { bool ret; // Create the packet to send DAIPCPacket * packet = MakePacket(dwMsg, dwTimeout != 0, dwNum, args); if (packet) { ret = SendPacket(*packet, dwTimeout); } else { ret = false; } if (packet) packet->Release(); return ret; } DAIPCWorker::DAIPCPacket * DAIPCWorker::MakePacket(DWORD dwMsg, bool bSync, DWORD dwNum, va_list args) { // Create the packet to send DAIPCWorker::DAIPCPacket * packet = new (dwNum) DAIPCWorker::DAIPCPacket; if (packet == NULL) return NULL; // Setup the basic information if (!packet->Init(dwMsg, bSync)) { delete packet; return NULL; } // Get the arguments DWORD_PTR * p = packet->GetParams(); for (int i = 0; i < dwNum; i++) p[i] = va_arg(args, DWORD_PTR); return packet; } bool DAIPCWorker::SendPacket(DAIPCPacket & p, DWORD dwTimeout) { // Create the message to send // If we are calling from the same thread and we are synchronous // then we need to call directly otherwise just queue the message if (_dwThreadId == GetCurrentThreadId() && p.IsSync()) { LRESULT r; IPCProc(_hwnd, DAMessageId, (WPARAM) &p, 0, r); return true; } else { // Add a reference for the posted message queue p.AddRef(); // Post the message to the window if (!PostMessage(_hwnd, DAMessageId, (WPARAM) &p, 0)) { // If we failed to post the message then we need to // release the packet since the receiver will not do it p.Release(); return false; } if (p.IsSync()) { // Need to wait for the message to be processed // TODO: Should add a reasonable timeout // TODO: Should add some diagnostics to detect deadlock // TODO: We should wait for a smaller period of time and // poll to see if the thread has terminated or we can do a // waitformultipleobjects on the thread handle WaitForSingleObject(p.GetSync(), dwTimeout); } } return true; } bool DAIPCWorker::IPCProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT & res) { res = 0; if (msg != DAMessageId) return true; DAIPCPacket * p = (DAIPCPacket *)wParam; ProcessMsg(p->GetMsg(), p->GetNumParam(), p->GetParams()); if (p->IsSync()) SetEvent(p->GetSync()); p->Release(); return false; } LRESULT CALLBACK DAIPCWorker::WindowProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { TraceTag((tagIPCEntry, "WindowProc: 0x%lx, 0x%lx, 0x%lx, 0x%lx", hwnd, msg, wParam, lParam)); // Get the worker data associated with the window DAIPCWorker * t = (DAIPCWorker *) GetWindowLongPtr (hwnd, GWLP_USERDATA) ; LRESULT res; // Callthe IPCProc and if it returns true call the default winproc if (!t || t->IPCProc(hwnd, msg, wParam, lParam, res)) res = DefWindowProc (hwnd, msg, wParam, lParam); return res; } // // DAThread // DAThread::DAThread() : _dwThreadId(0), _hThread(NULL), _hMsgQEvent(NULL), _bDoingWork(false) { if (threadList) { // Add ourselves to the list of threads CritSectGrabber csg(*threadCS); threadList->push_back(this); } } DAThread::~DAThread() { // Ensure the thread is stopped Stop(); if (threadList) { CritSectGrabber csg(*threadCS); threadList->remove(this); } } bool DAThread::Start() { if (IsStarted()) return true; if (!AddRefDLL()) return false; // Create necessary events first _hMsgQEvent = CreateEvent(NULL,TRUE,FALSE,NULL); if (_hMsgQEvent != NULL) { // Create the thread _hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)DAWorker, this, 0, (LPDWORD)&_dwThreadId); if (_hThread != NULL) { // wait until the message queue has been created DWORD dwRes ; { // make the expected event be first so we can check it // below // TODO: We may want to add a timeout here to ensure // we did not lock up for some reason HANDLE h[] = { _hMsgQEvent,_hThread } ; dwRes = WaitForMultipleObjects(2,h,FALSE,INFINITE) ; } CloseHandle(_hMsgQEvent); _hMsgQEvent = NULL; // Check the result to see if the event was signalled or the // thread exited unexpectedly // The expected event is the first in the array above // Return true indicating everything is going fine if (dwRes == WAIT_OBJECT_0) { return true; } // Fall through if we failed TraceTag((tagError, "GarbageCollector::StartThread: Thread terminated unexpectedly")); } else { TraceTag((tagError, "DAThread:Start: Failed to create thread")); } } else { TraceTag((tagError, "DAThread:Start: Failed to create terminate event")); } ReleaseDLL(); Kill(); return false; } bool DAThread::Terminate(bool bKill) { bool ret = true; // See if the thread is alive if (_dwThreadId) { if (bKill) { if (_dwThreadId != GetCurrentThreadId()) ::TerminateThread(_hThread, 0); } else { // Send terminate message to ensure the thread wakes up SendAsyncMsg(DAT_TERMINATE); } _dwThreadId = 0; Assert (_hThread); CloseHandle(_hThread); _hThread = NULL; } if (_hMsgQEvent) { CloseHandle(_hMsgQEvent); _hMsgQEvent = NULL; } return ret; } int DAThread::workerRoutine() { if (!InitThread()) { DeinitThread(); return -1; } MSG msg; while (GetMessage(&msg, NULL, NULL, NULL)) { if (msg.message == DAMessageId && ((DAIPCPacket *)msg.wParam)->GetMsg() == DAT_TERMINATE) break; TranslateMessage(&msg); DispatchMessage(&msg); } if (!DeinitThread()) return -1; return 0; } bool DAThread::InitThread() { if (!AttachToThread()) return false; { MSG msg; // force message queue to be created PeekMessage(&msg, NULL, NULL, NULL, PM_NOREMOVE); } // set event that indicates thread's msg queue created SetEvent(_hMsgQEvent); if (!TlsSetValue(DAThreadTlsIndex, this)) return false; // CoInitialize so we can call COM stuff // this doesn't exist on ie3.02 platfroms. //CoInitializeEx(NULL, COINIT_MULTITHREADED); CoInitialize(NULL); return true; } bool DAThread::DeinitThread() { DetachFromThread(); // Clean up COM CoUninitialize(); FreeLibraryAndExitThread(hInst, 0); return true; } bool DAThread::AddRefDLL() { bool bRet = false; char buf[MAX_PATH + 1]; if (GetModuleFileName(hInst, buf, ARRAY_SIZE(buf)) == 0) { TraceTag((tagError, "DAThread::AddRefDLL: Failed to getmodulefilename - %hr", GetLastError())); goto done; } HINSTANCE new_hinst; new_hinst = LoadLibrary(buf); if (new_hinst == NULL) { TraceTag((tagError, "DAThread::AddRefDLL: Failed to LoadLibrary(%s) - %hr", buf, GetLastError())); goto done; } Assert(new_hinst == hInst); bRet = true; done: return bRet; } void DAThread::ReleaseDLL() { FreeLibrary(hInst); } // // General IPC stuff // DAThread * GetCurrentDAThread() { return (DAThread *) TlsGetValue(DAThreadTlsIndex); } static void RegisterWindowClass () { WNDCLASS windowclass; memset (&windowclass, 0, sizeof(windowclass)); windowclass.style = 0; windowclass.lpfnWndProc = DAIPCWorker::WindowProc; windowclass.hInstance = hInst; windowclass.hCursor = NULL; windowclass.hbrBackground = NULL; windowclass.lpszClassName = DATHREAD_CLASS; RegisterClass (&windowclass); } // ========================================= // Initialization // ========================================= void InitializeModule_IPC() { RegisterWindowClass(); DAMessageId = RegisterWindowMessage(_T("IPCMessage")); DAThreadTlsIndex = TlsAlloc(); // If result is 0xFFFFFFFF, allocation failed. Assert(DAThreadTlsIndex != 0xFFFFFFFF); threadCS = THROWING_ALLOCATOR(CritSect); threadList = THROWING_ALLOCATOR(DAThreadList); } void DeinitializeModule_IPC(bool bShutdown) { // Iterate through the list and stop all the threads - but do not // destroy them if (threadList) { for (DAThreadList::iterator i = threadList->begin(); i != threadList->end(); i++) { (*i)->Terminate(bShutdown); } } // We need to set the threadList and threadCS to NULL to ensure // that when the thread objects are destroyed later on during // deinitialization they do not try to access the no longer // valid list delete threadList; threadList = NULL; delete threadCS; threadCS = NULL; if (DAThreadTlsIndex != 0xFFFFFFFF) TlsFree(DAThreadTlsIndex); }
23.955056
94
0.516417
[ "object" ]
dceed565a0b8fef271ae8fb54527450b532e5878
9,282
cpp
C++
src/variant_detection/variant_detection.cpp
eseiler/iGenVar
a3597065c54bcf0aba8b951202007c7286ea7fc6
[ "BSD-3-Clause" ]
null
null
null
src/variant_detection/variant_detection.cpp
eseiler/iGenVar
a3597065c54bcf0aba8b951202007c7286ea7fc6
[ "BSD-3-Clause" ]
null
null
null
src/variant_detection/variant_detection.cpp
eseiler/iGenVar
a3597065c54bcf0aba8b951202007c7286ea7fc6
[ "BSD-3-Clause" ]
null
null
null
#include "variant_detection/variant_detection.hpp" #include <seqan3/core/debug_stream.hpp> #include <seqan3/io/sam_file/input.hpp> // SAM/BAM support (seqan3::sam_file_input) #include "modules/sv_detection_methods/analyze_cigar_method.hpp" // for the split read method #include "modules/sv_detection_methods/analyze_read_pair_method.hpp" // for the read pair method #include "modules/sv_detection_methods/analyze_split_read_method.hpp" // for the cigar string method #include "variant_detection/bam_functions.hpp" // for hasFlag* functions using seqan3::operator""_tag; std::deque<std::string> read_header_information(auto & alignment_file, std::map<std::string, int32_t> & references_lengths) { // Check that the file is sorted before proceeding. if (alignment_file.header().sorting != "coordinate") { throw seqan3::format_error{"ERROR: Input file must be sorted by coordinate (e.g. samtools sort)"}; } // Get the information from \@SQ tag, more precise the values of the SN and LN tags std::deque<std::string> const ref_ids = alignment_file.header().ref_ids(); std::vector<std::tuple<int32_t, std::string>> ref_id_info = alignment_file.header().ref_id_info; size_t i = 0; for(std::string const & ref_id : ref_ids) { int32_t ref_length = std::get<0>(ref_id_info[i]); if (references_lengths.find(ref_id) != references_lengths.end()) { if (references_lengths[ref_id] != ref_length) { std::cerr << "Warning: The reference id " << ref_id << " was found twice in the input files with " << "different length: " << references_lengths[ref_id] << " and " << ref_length << '\n'; } } else { references_lengths.emplace(ref_id, ref_length); } ++i; } return ref_ids; } void detect_junctions_in_short_reads_sam_file([[maybe_unused]] std::vector<Junction> & junctions, std::map<std::string, int32_t> & references_lengths, cmd_arguments const & args) { // Open input alignment file using my_fields = seqan3::fields<seqan3::field::flag, // 2: FLAG seqan3::field::ref_id, // 3: RNAME seqan3::field::ref_offset, // 4: POS seqan3::field::mapq>; // 5: MAPQ // Set number of decompression threads seqan3::contrib::bgzf_thread_count = args.threads; seqan3::sam_file_input alignment_short_reads_file{args.alignment_short_reads_file_path, my_fields{}}; std::deque<std::string> const ref_ids = read_header_information(alignment_short_reads_file, references_lengths); uint32_t num_good = 0; for (auto & record : alignment_short_reads_file) { seqan3::sam_flag const flag = record.flag(); // 2: FLAG int32_t const ref_id = record.reference_id().value_or(-1); // 3: RNAME int32_t const ref_pos = record.reference_position().value_or(-1); // 4: POS uint8_t const mapq = record.mapping_quality(); // 5: MAPQ if (hasFlagUnmapped(flag) || hasFlagSecondary(flag) || hasFlagDuplicate(flag) || mapq < 20 || ref_id < 0 || ref_pos < 0) continue; for (detection_methods method : args.methods) { switch (method) { case detection_methods::cigar_string: // Detect junctions from CIGAR string seqan3::debug_stream << "The cigar string method for short reads is not yet implemented.\n"; break; case detection_methods::split_read: // Detect junctions from split read evidence (SA tag, seqan3::debug_stream << "The split read method for short reads is not yet implemented.\n"; break; case detection_methods::read_pairs: // Detect junctions from read pair evidence if (hasFlagMultiple(flag)) { analyze_read_pair(); } break; case detection_methods::read_depth: // Detect junctions from read depth evidence seqan3::debug_stream << "The read depth method for short reads is not yet implemented.\n"; break; } } if (gVerbose) { ++num_good; if (num_good % 100000 == 0) { seqan3::debug_stream << num_good << " good alignments from short read file." << std::endl; } } } } void detect_junctions_in_long_reads_sam_file(std::vector<Junction> & junctions, std::map<std::string, int32_t> & references_lengths, cmd_arguments const & args) { // Open input alignment file using my_fields = seqan3::fields<seqan3::field::id, // 1: QNAME seqan3::field::flag, // 2: FLAG seqan3::field::ref_id, // 3: RNAME seqan3::field::ref_offset, // 4: POS seqan3::field::mapq, // 5: MAPQ seqan3::field::cigar, // 6: CIGAR seqan3::field::seq, // 10:SEQ seqan3::field::tags>; // Set number of decompression threads seqan3::contrib::bgzf_thread_count = args.threads; seqan3::sam_file_input alignment_long_reads_file{args.alignment_long_reads_file_path, my_fields{}}; std::deque<std::string> const ref_ids = read_header_information(alignment_long_reads_file, references_lengths); uint32_t num_good = 0; for (auto & record : alignment_long_reads_file) { std::string const query_name = record.id(); // 1: QNAME seqan3::sam_flag const flag = record.flag(); // 2: FLAG int32_t const ref_id = record.reference_id().value_or(-1); // 3: RNAME int32_t const ref_pos = record.reference_position().value_or(-1); // 4: POS uint8_t const mapq = record.mapping_quality(); // 5: MAPQ std::vector<seqan3::cigar> cigar = record.cigar_sequence(); // 6: CIGAR seqan3::dna5_vector const seq = record.sequence(); // 10:SEQ auto tags = record.tags(); if (hasFlagUnmapped(flag) || hasFlagSecondary(flag) || hasFlagDuplicate(flag) || mapq < 20 || ref_id < 0 || ref_pos < 0) continue; std::string const ref_name = ref_ids[ref_id]; for (detection_methods method : args.methods) { switch (method) { case detection_methods::cigar_string: // Detect junctions from CIGAR string analyze_cigar(query_name, ref_name, ref_pos, cigar, seq, junctions, args.min_var_length); break; case detection_methods::split_read: // Detect junctions from split read evidence (SA tag, if (!hasFlagSupplementary(flag)) // primary alignments only) { std::string const sa_tag = tags.get<"SA"_tag>(); if (!sa_tag.empty()) { analyze_sa_tag(query_name, flag, ref_name, ref_pos, mapq, cigar, seq, sa_tag, args, junctions); } } break; case detection_methods::read_pairs: // There are no read pairs in long reads. break; case detection_methods::read_depth: // Detect junctions from read depth evidence seqan3::debug_stream << "The read depth method for long reads is not yet implemented.\n"; break; } } if (gVerbose) { ++num_good; if (num_good % 100000 == 0) { seqan3::debug_stream << num_good << " good alignments from long read file." << std::endl; } } } }
48.596859
116
0.501724
[ "vector" ]
fd602fcaf0af347825c2cf858b91654ac9313577
3,686
hpp
C++
src/include/gloam/core/util/dcg/stl/range_t.hpp
Dylan95/gloam
2ddee49cbdb0a0b87118407074def4da29738424
[ "MIT" ]
null
null
null
src/include/gloam/core/util/dcg/stl/range_t.hpp
Dylan95/gloam
2ddee49cbdb0a0b87118407074def4da29738424
[ "MIT" ]
null
null
null
src/include/gloam/core/util/dcg/stl/range_t.hpp
Dylan95/gloam
2ddee49cbdb0a0b87118407074def4da29738424
[ "MIT" ]
null
null
null
//AUTOGENERATED_TEXT_E6585F83424849_START #ifndef INCLUDE_GAURD_E6585F83424849_INCLUDE_GLOAM_CORE_UTIL_DCG_STL_RANGE_T_HPP #define INCLUDE_GAURD_E6585F83424849_INCLUDE_GLOAM_CORE_UTIL_DCG_STL_RANGE_T_HPP //AUTOGENERATED_TEXT_E6585F83424849_END #include <iterator> #include <vector> //AUTOGENERATED_TEXT_E6585F83424849_START namespace gloam{ //AUTOGENERATED_TEXT_E6585F83424849_END //forward iterator template<class T> using ForwardIterator = std::iterator<std::forward_iterator_tag, T>; template<class T> using RangeIterator = ForwardIterator<T>; //the most complicated type of iterator template<class T> using RandomAccessIter = std::iterator<std::random_access_iterator_tag, T>; //range based for loop: for(item : container){ ... } //'It' should be derived from RangeIter template<class It> class range_t{ public: virtual It begin() = 0; virtual It end() = 0; }; //'It' should be derived from RangeIter template<class T> class PtrRange : range_t<T*>{ T* mBegin; T* mEnd; public: PtrRange(T* mBegin, T* mEnd) : mBegin(mBegin), mEnd(mEnd) {} PtrRange(T* mBegin, size_t n) : mBegin(mBegin), mEnd(mBegin + n) {} virtual T* begin(){ return(mBegin); } virtual T* end(){ return(mEnd); } }; //'It' should be derived from RangeIter template<class T> class NumRange{ T mBegin; T mEnd; public: NumRange(T mBegin, T mEnd) : mBegin(mBegin), mEnd(mEnd) {} NumRange(T mBegin, size_t n) : mBegin(mBegin), mEnd(mBegin + n) {} virtual T begin(){ return(mBegin); } virtual T end(){ return(mEnd); } }; /* template<class T> using range_t_vector = range_t<typename std::vector<T>::iterator>; template<class T> using range_t_ptr = range_t<T*>; */ //for converting between smart pointers //using std::dynamic_pointer_cast; /*IterOut begin(range_t v){ return(v.begin()); } IterOut end(range_t v){ return(v.end()); }*/ /*iterator begin(range_t r){ return(r.begin()); } iterator end(range_t r){ return(r.end()); }*/ /* example implementation: class MyIterator : public std::iterator<std::input_iterator_tag, int> { int* p; public: MyIterator(int* x) :p(x) {} MyIterator(const MyIterator& mit) : p(mit.p) {} MyIterator& operator++() {++p;return *this;} MyIterator operator++(int) {MyIterator tmp(*this); operator++(); return tmp;} bool operator==(const MyIterator& rhs) {return p==rhs.p;} bool operator!=(const MyIterator& rhs) {return p!=rhs.p;} int& operator*() {return *p;} }; template<class Tag, class T> using Iter = std::iterator<Tag,T>; */ //AUTOGENERATED_TEXT_E6585F83424849_START } #endif /*Copyright (c) 2016, Dylan Carleton Gundlach 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. */ //AUTOGENERATED_TEXT_E6585F83424849_END
22.47561
460
0.740369
[ "vector" ]
fd64508b6f30a51108bce38f9e13664fea18ece1
832
hpp
C++
cache/list.hpp
comparch-security/smart-cache-evict
89f7413fb3afef0c2c69012f6a19f60dabc041ab
[ "BSD-2-Clause-FreeBSD" ]
7
2019-06-11T11:30:32.000Z
2022-03-01T00:44:05.000Z
cache/list.hpp
comparch-security/smart-cache-evict
89f7413fb3afef0c2c69012f6a19f60dabc041ab
[ "BSD-2-Clause-FreeBSD" ]
1
2022-03-14T10:24:33.000Z
2022-03-20T08:06:54.000Z
cache/list.hpp
comparch-security/smart-cache-evict
89f7413fb3afef0c2c69012f6a19f60dabc041ab
[ "BSD-2-Clause-FreeBSD" ]
1
2021-03-08T03:15:50.000Z
2021-03-08T03:15:50.000Z
#ifndef SCE_LIST_HPP #define SCE_LIST_HPP #include "common/definitions.hpp" #include <vector> extern void traverse_list_1(elem_t *ptr); extern void traverse_list_2(elem_t *ptr); extern void traverse_list_3(elem_t *ptr); extern void traverse_list_4(elem_t *ptr); extern void traverse_list_rr(elem_t *ptr); extern void traverse_list_ran(elem_t *ptr); extern void traverse_list_param(elem_t *ptr, int repeat, int dist, int step); typedef void (*traverse_func)(elem_t *); extern traverse_func choose_traverse_func(int); extern int list_size(elem_t *ptr); extern elem_t *pick_from_list(elem_t **ptr, int pksz); extern elem_t *append_list(elem_t *lptr, elem_t *rptr); extern std::vector<elem_t *> split_list(elem_t *lptr, int way); extern elem_t *combine_lists(std::vector<elem_t *>lists); extern void print_list(elem_t *ptr); #endif
33.28
77
0.786058
[ "vector" ]
fd6650836aff9430f5958d9ecc209903e9716731
1,960
cc
C++
src/simulation.cc
aberry-21/dining_philosophers
3a7f385075d7b947072e9a18937cef5d98838de5
[ "MIT" ]
null
null
null
src/simulation.cc
aberry-21/dining_philosophers
3a7f385075d7b947072e9a18937cef5d98838de5
[ "MIT" ]
null
null
null
src/simulation.cc
aberry-21/dining_philosophers
3a7f385075d7b947072e9a18937cef5d98838de5
[ "MIT" ]
null
null
null
// // Created by Aaron Berry on 5/19/21. // #include <thread> #include <vector> #include "includes/simulation.h" #include "includes/philosophers.h" // Constructor (initialization threads and mutexes) simulation::simulation(config *config) : config_(config) { auto size = config_->GetNumberOfPhilo(); philos_.reserve(size); std::vector<std::shared_ptr<std::mutex>> mtx; mtx.reserve(size); for (int i = 0; i < size; ++i) { std::shared_ptr<std::mutex> fork = std::make_shared<std::mutex>(); mtx.emplace_back(fork); } for (int i = 0; i < size; ++i) { philos_.emplace_back(mtx[i], mtx[(i + 1) % size], config_, i + 1); } for (int i = 0; i < size; ++i) { std::thread(&simulation::Routine, this, std::ref(philos_[i])).detach(); } } // Start all thread and supervisor void simulation::StartSimulation() { config_->GetTimer().StartSimulationTime(); ready_ = true; cv_.notify_all(); std::thread(&simulation::Supervisor, this).join(); } // Private functions // Start live philosophers void simulation::Routine(philosophers& philo) { std::unique_lock<std::mutex> lk(m_); cv_.wait(lk, [this](){return ready_;}); lk.unlock(); philo.PhiloLive(); } // Check number of philosopher's dinners bool simulation::CheckCountEat() { for (int i = 0; i < config_->GetNumberOfPhilo(); ++i) { if (philos_[i].GetCountEat() != 0) { return false; } } return true; } // Start live thread supervisor void simulation::Supervisor() { std::unique_lock<std::mutex> lk(m_); cv_.wait(lk, [this](){return ready_;}); lk.unlock(); while (true) { for (int i = 0; i < config_->GetNumberOfPhilo(); ++i) { if (static_cast<int>(config_->GetTimer().GetTimeSimulation() - philos_[i].GetTimeLastEat()) >= config_->GetTimeToDie() + 5) { philos_[i].SayDied(); return; } } if (config_->IsLimitLunch() && CheckCountEat()) { return; } } }
26.486486
75
0.623469
[ "vector" ]
fd6dda37343008992bd3af116c7967ff95a74edb
37,883
cpp
C++
host.cpp
caosjr/qrmethod_opencl_intel_fpga
d06de98ba44801955c90e3a0d466c488ff0abd82
[ "Apache-2.0" ]
null
null
null
host.cpp
caosjr/qrmethod_opencl_intel_fpga
d06de98ba44801955c90e3a0d466c488ff0abd82
[ "Apache-2.0" ]
null
null
null
host.cpp
caosjr/qrmethod_opencl_intel_fpga
d06de98ba44801955c90e3a0d466c488ff0abd82
[ "Apache-2.0" ]
1
2022-02-28T06:13:00.000Z
2022-02-28T06:13:00.000Z
#include <stdio.h> #include <string> #include <stdlib.h> #include <math.h> #include <unistd.h> #include <sys/time.h> #include "CL/opencl.h" #include "AOCLUtils/aocl_utils.h" #define TAM 47 #define PROGRAM_NAME "qr_method_article_sqrt_single_v3.aocx" #define KERNEL_FUNC "qr_method" using namespace aocl_utils; /** * * Specific functions definition in OpenCL * */ extern "C" { bool init_opencl_data_structure_dense_(int *n, bool *success); void init_structure_single_dense (int *n, double dataQ[], double dataR[]); int qr_method_fpga(int *n); void free_resources(); static void dump_error (const char *str, cl_int status); } char dname[500]; //name of the platform /** * * OpenCL common variables * */ cl_uint num_devices, num_platforms; cl_platform_id platform = NULL; cl_device_id device; cl_context context = NULL; cl_kernel kernel; cl_command_queue queue; cl_program program = NULL; cl_event computation_event, send_event, receive_event; double *input_q_buf, *input_r_buf; //pointers to buffers void print_matrix(double *matrix){ for (int i = 0; i < TAM; i++){ for (int j = 0; j < TAM; j++) { printf("%lf\t", matrix[i*TAM + j]); } printf("\n"); } } void print_vector(double *vector){ for (int i = 0; i < TAM; i++){ printf("%lf\t", vector[i]); } } void mult_mat_vector_transpose_dense_(double *dataQT, double *dataB, double *result){ int i, j, k; double sum; for(i = 0;i < TAM;i++){ sum = 0; for(k = 0; k < TAM;k++){ sum += dataQT[k*TAM + i] * dataB[k]; //Q is transposed } result[i] = sum; } } void backward_substitution_dense(double *dataR, double *dataX, double *dataY){ int i, j; dataX[TAM-1] = dataY[TAM-1]/dataR[(TAM-1)*TAM + (TAM-1)]; for (i = (TAM-2); i >= 0; i--) { dataX[i] = dataY[i]; for (j = i+1; j < TAM; j++) { dataX[i] -= dataR[j*TAM + i] * dataX[j]; }; dataX[i] = dataX[i] / dataR[i*TAM + i]; }; } void qr_method_original_dense_software_(int *n, double *dataQ, double *dataR){ int j, k, m; double sum = 0; for (k = 0; k < TAM; k++){ sum = 0; for (m = 0; m < TAM; m++){ sum += dataQ[m*TAM + k] * dataQ[m*TAM + k]; } dataR[k*TAM + k] = sqrt(sum); for (m = 0; m < TAM; m++) { dataQ[m*TAM + k] = dataQ[m*TAM + k]/dataR[k*TAM + k]; } for (j = k+1; j < TAM; j++){ sum = 0; for (m = 0; m < TAM; m++){ sum += dataQ[m*TAM + j] * dataQ[m*TAM + k]; } dataR[k*TAM + j] = sum; sum = 0; for (m = 0; m < TAM; m++){ dataQ[m*TAM + j] = dataQ[m*TAM + j] - (dataR[k*TAM + j] * dataQ[m*TAM + k]); } } } } bool init_opencl_data_structure_dense_(int *n, bool *success){ cl_int status; int ARRAY_SIZE = *n; // get the platform ID status = clGetPlatformIDs(1, &platform, &num_platforms); if(status != CL_SUCCESS) { dump_error("Failed clGetPlatformIDs.", status); free_resources(); return 1; } if(num_platforms != 1) { printf("Found %d platforms!\n", num_platforms); free_resources(); return 1; } // get the device ID status = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, 1, &device, &num_devices); if(status != CL_SUCCESS) { dump_error("Failed clGetDeviceIDs.", status); free_resources(); return 1; } if(num_devices != 1) { printf("Found %d devices!\n", num_devices); free_resources(); return 1; } // create a context context = clCreateContext(0, 1, &device, NULL, NULL, &status); if(status != CL_SUCCESS) { dump_error("Failed clCreateContext.", status); free_resources(); return 1; } input_q_buf = (double*)clSVMAllocAltera(context, 0, ARRAY_SIZE*ARRAY_SIZE * sizeof (double), 1024); input_r_buf = (double*)clSVMAllocAltera(context, 0, ARRAY_SIZE*ARRAY_SIZE * sizeof (double), 1024); if(!input_q_buf || !input_r_buf) { dump_error("Failed to allocate buffers.", status); free_resources(); return 1; } // create a command queue queue = clCreateCommandQueue(context, device, CL_QUEUE_PROFILING_ENABLE, &status); if(status != CL_SUCCESS) { dump_error("Failed clCreateCommandQueue.", status); free_resources(); return 1; } // create the program cl_int kernel_status; size_t binsize = 0; unsigned char * binary_file = loadBinaryFile(PROGRAM_NAME, &binsize); // Colocar aqui o nome do arquivo Kernel if(!binary_file) { dump_error("Failed loadBinaryFile.", status); free_resources(); return 1; } program = clCreateProgramWithBinary(context, 1, &device, &binsize, (const unsigned char**)&binary_file, &kernel_status, &status); if(status != CL_SUCCESS) { dump_error("Failed clCreateProgramWithBinary.", status); free_resources(); return 1; } delete [] binary_file; // build the program status = clBuildProgram(program, 0, NULL, "", NULL, NULL); if(status != CL_SUCCESS) { dump_error("Failed clBuildProgram.", status); free_resources(); return 1; } // create the kernel kernel = clCreateKernel(program, KERNEL_FUNC, &status); if(status != CL_SUCCESS) { dump_error("Failed clCreateKernel.", status); free_resources(); return 1; } //This variable is not mandatory, I kept because I needed it for another project *success = true; return true; } void init_structure_single_dense (int *n, double dataQ[], double dataR[]) { int ARRAY_SIZE = *n; if(num_devices == 0) { checkError(-1, "No devices"); } memcpy(input_q_buf, dataQ, ARRAY_SIZE*ARRAY_SIZE * sizeof(double)); memcpy(input_r_buf, dataR, ARRAY_SIZE*ARRAY_SIZE * sizeof(double)); } int qr_method_fpga (int *n){ cl_int status; int ARRAY_SIZE = *n; struct timeval before, after; // set the arguments status = clSetKernelArgSVMPointerAltera(kernel, 0, (void*)input_q_buf); if(status != CL_SUCCESS) { dump_error("Failed set arg 0.", status); return 1; } status = clSetKernelArgSVMPointerAltera(kernel, 1, (void*)input_r_buf); if(status != CL_SUCCESS) { dump_error("Failed Set arg 1.", status); free_resources(); return 1; } gettimeofday(&before, NULL); status = clEnqueueSVMMap(queue, CL_FALSE, CL_MAP_READ | CL_MAP_WRITE, (void*) input_q_buf, ARRAY_SIZE * ARRAY_SIZE * sizeof (double), 0, NULL, NULL); if(status != CL_SUCCESS) { dump_error("Failed clEnqueueSVMMap", status); free_resources(); return 1; } status = clEnqueueSVMMap(queue, CL_FALSE, CL_MAP_READ | CL_MAP_WRITE, (void *) input_r_buf, ARRAY_SIZE * ARRAY_SIZE * sizeof (double), 0, NULL, &send_event); if(status != CL_SUCCESS) { dump_error("Failed clEnqueueSVMMap", status); free_resources(); return 1; } clWaitForEvents(1, &send_event); clReleaseEvent(send_event); gettimeofday(&after, NULL); printf("Send: %ld\n", ((after.tv_sec * 1000000 + after.tv_usec) - (before.tv_sec * 1000000 + before.tv_usec))); // execução kernel gettimeofday(&before, NULL); status = clEnqueueTask(queue, kernel, 0, NULL, &computation_event); clWaitForEvents(1, &computation_event); clReleaseEvent(computation_event); gettimeofday(&after, NULL); printf("Solve: %ld\n", ((after.tv_sec * 1000000 + after.tv_usec) - (before.tv_sec * 1000000 + before.tv_usec))); if (status != CL_SUCCESS) { dump_error("Failed to launch kernel.", status); free_resources(); return 1; } gettimeofday(&before, NULL); status = clEnqueueSVMUnmap(queue, (void *)input_q_buf, 0, NULL, NULL); if(status != CL_SUCCESS) { dump_error("Failed clEnqueueSVMUnmap", status); free_resources(); return 1; } status = clEnqueueSVMUnmap(queue, (void *)input_r_buf, 0, NULL, &receive_event); if(status != CL_SUCCESS) { dump_error("Failed clEnqueueSVMUnmap", status); free_resources(); return 1; } clWaitForEvents(1, &receive_event); clReleaseEvent(receive_event); gettimeofday(&after, NULL); printf("Receive: %ld\n", ((after.tv_sec * 1000000 + after.tv_usec) - (before.tv_sec * 1000000 + before.tv_usec))); clFinish(queue); return 0; } static void dump_error(const char *str, cl_int status) { printf("%s\n", str); printf("Error code: %d\n", status); } // free the resources allocated during initialization void free_resources() { if(kernel) clReleaseKernel(kernel); if(program) clReleaseProgram(program); if(queue) clReleaseCommandQueue(queue); if(input_q_buf) clSVMFreeAltera(context,input_q_buf); if(input_r_buf) clSVMFreeAltera(context,input_r_buf); if(context) clReleaseContext(context); } void qr_method_original_dense_(int *n, double *dataQ, double *dataR){ int j, k, m; double sum = 0; for (k = 0; k < TAM; k++){ sum = 0; for (m = 0; m < TAM; m++){ sum += dataQ[m*TAM + k] * dataQ[m*TAM + k]; } dataR[k*TAM + k] = sqrt(sum); for (m = 0; m < TAM; m++) { dataQ[m*TAM + k] = dataQ[m*TAM + k]/dataR[k*TAM + k]; } for (j = k+1; j < TAM; j++){ sum = 0; for (m = 0; m < TAM; m++){ sum += dataQ[m*TAM + j] * dataQ[m*TAM + k]; } dataR[k*TAM + j] = sum; sum = 0; for (m = 0; m < TAM; m++){ dataQ[m*TAM + j] = dataQ[m*TAM + j] - (dataR[k*TAM + j] * dataQ[m*TAM + k]); } } } } void qr_method_article_dense_(int *n, double *dataQ, double *dataR){ int j, k, m; double sum = 0; double r2[TAM]; double rn[TAM*TAM]; memset(r2, 0, sizeof(r2)); memset(rn, 0, sizeof(rn)); for (k = 0; k < TAM; k++) { sum = 0; for (m = 0; m < TAM; m++) { sum += dataQ[m * TAM + k] * dataQ[m * TAM + k]; } r2[k] = sum; for (j = k + 1; j < TAM; j++) { sum = 0; for (m = 0; m < TAM; m++) { sum += dataQ[m * TAM + k] * dataQ[m * TAM + j]; } rn[k * TAM + j] = sum; } for (j = k + 1; j < TAM; j++) { for (m = 0; m < TAM; m++) { dataQ[m * TAM + j] = dataQ[m * TAM + j] - ((rn[k * TAM + j] / r2[k]) * dataQ[m * TAM + k]); } } } for (k = 0; k < TAM; k++) { dataR[k*TAM + k] = sqrt(r2[k]); for (j = k + 1; j < TAM; j++) { dataR[k * TAM + j] = rn[k * TAM + j] / dataR[k * TAM + k]; } for (m = 0; m < TAM; m++) { dataQ[m*TAM + k] = dataQ[m*TAM + k]/dataR[k*TAM + k]; } } } int main() { double dataA[TAM*TAM] = {0.008356, -0.000000, 0.000020, -0.000020, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000001, -0.000000, -0.000001, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.007629, -0.000000, 0.015962, -0.007629, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, 0.000000, 0.000000, -0.000000, -0.000000, 0.000000, 0.000000, 0.000000, -0.000000, 0.000013, -0.000000, -0.000000, 0.008346, -0.000013, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, 0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.032613, -0.046712, 0.155322, -0.018533, -0.000000, -0.000073, -0.000000, -0.000000, -0.000000, -0.000030, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000026, -0.000000, -0.000000, -0.000000, 0.000138, 0.095613, 0.000000, 0.000023, 0.000045, -0.000000, -0.087712, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, 0.000000, 0.000000, -0.000000, -0.000000, 0.000000, -0.000047, -0.095742, -0.000001, -0.000000, -0.000000, -0.000000, -0.023654, -0.023654, 0.031988, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.048183, -0.000000, -0.000000, -0.000000, -0.000000, 0.056517, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.048183, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -77436.298921, -0.000000, -0.138916, 0.162288, -0.023372, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.065714, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 77443.051476, -0.000000, -0.131427, -1.839983, -0.000000, -0.000000, -0.000000, -6.036983, 6.571366, -0.000000, -0.328568, -0.000000, -0.000000, -0.871035, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.985705, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -719149154.597408, 840256257.842559, -242214206.473636, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.029333, 0.000000, 0.006097, 0.171589, -0.000533, -0.000000, -0.006097, -0.171276, 0.000000, 0.000000, -0.000000, 0.124019, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 14.142115, -1.261046, 0.229139, 0.001837, 0.716671, 0.167367, 11.272654, 0.007067, 0.443049, 0.299556, -0.005173, 0.015943, 0.000000, 0.000220, 0.000000, 0.000000, -0.006292, -0.000000, -0.229139, -0.631153, -0.171600, -11.272654, -0.000020, -0.006640, -0.000000, -0.393519, -0.000000, -0.003725, 0.000905, -0.000000, 0.010573, 0.010287, 0.000000, -0.000000, -0.000000, -0.000000, -0.020860, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.011478, 0.040672, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, -0.000000, 0.000000, 0.000000, 0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000002, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000001, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000001, -0.000000, -0.000000, -0.000000, -0.000000, 0.008335, -0.000000, -0.000000, -0.000001, -0.000001, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000005, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000002, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000001, -0.000002, -0.000000, -0.000000, -0.000000, -0.000002, 0.008339, -0.000000, -0.000005, -0.000000, -0.000000, -0.000002, -0.000000, -0.000000, -0.000000, -0.000000, -0.000001, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000001, -0.000000, -0.000001, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000215, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008549, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000215, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.008333, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.009451, -0.009451, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.009451, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.009451, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.017785, 0.000000, 0.000000, 0.000000, -0.000000, -0.000000, 0.000000, 0.000000, 0.000000, -0.000000, -0.000000, -0.000000, 0.005308, -0.004859, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.003942, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000159, -0.001759, -0.002895, -0.000181, -0.000449, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000479, 0.013207, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000690, -0.000000, -0.000000, 0.008437, -0.008437, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.008437, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.011801, -0.003554, -0.000440, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.016770, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.004870, -0.004125, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.004125, -0.000000, -0.000000, -0.000000, -0.001842, -0.000000, -0.000000, -0.002951, -0.000000, -0.000000, -0.002214, -0.000745, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.013203, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.288037, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.030734, -0.000000, -0.000000, -0.000000, -0.000000, -0.288037, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.296370, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 12.694951, -0.000000, -0.000000, 0.518466, -0.000000, -0.000000, -0.518466, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -12.694951, -57.897810, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -71.111227, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 2908.112258, -2836.992698, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.004870, -0.004632, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.004632, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.010080, -0.000238, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.013203, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.014853, 0.113279, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.001832, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000869, -0.001094, -0.000000, -0.001288, -0.000000, -0.128132, -0.000000, -0.000000, -0.000000, -0.000000, -0.011605, 0.000000, 0.000000, 0.000000, -0.000000, -0.000000, 0.000000, 0.149903, 0.000000, -0.000381, -0.000000, -0.000000, 0.004870, -0.008844, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000896, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.001140, -0.004927, -0.001844, -0.000000, -0.000896, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, 0.013203, -0.000000, -0.000000, -0.000000, 0.004870, -0.004870, 0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, -0.000000, 0.000000, -0.000000, 0.013203 }; int i = 0, size = TAM; bool success = false; double dataB[TAM] = {7,4,0,3,6,9,0,3,3,8,0,8,0,1,4,6,7,9,2,4,6,9,8,7,3,4,7,4,1,7,1,3,1,1,2,4,0,6,5,1,9,4,1,9,2,9,9}; double *dataR = (double*) malloc(TAM*TAM*sizeof(double)); double *dataQ = (double*) malloc(TAM*TAM*sizeof(double)); double *dataX = (double*) malloc(TAM*sizeof(double)); double *dataY = (double*) malloc(TAM*sizeof(double)); struct timeval before, after; memcpy(dataQ, dataA, sizeof(dataA)); memset(dataR, 0, sizeof(dataR)); memset(dataY, 0, sizeof(dataY)); memset(dataX, 0, sizeof(dataX)); /*printf("\n\nMatriz A\n"); print_matrix(dataA); printf("\n\nMatriz Q\n"); print_matrix(dataQ); printf("\n\nMatriz R\n"); print_matrix(dataR);*/ // software execution /*gettimeofday(&before, NULL); qr_method_original_dense_(&size, dataQ, dataR); qr_method_article_dense_(&size, dataQ, dataR); gettimeofday(&after, NULL); printf("Solve: %ld\n", ((after.tv_sec * 1000000 + after.tv_usec) - (before.tv_sec * 1000000 + before.tv_usec))); mult_mat_vector_transpose_dense_(dataQ, dataB, dataY); backward_substitution_dense(dataR, dataX, dataY);*/ //hardware execution init_opencl_data_structure_dense_(&size, &success); init_structure_single_dense(&size, dataQ, dataR); qr_method_fpga(&size); gettimeofday(&before, NULL); for (i = 0; i < 1; i++){ //this for was used for some experiments, not necessary! mult_mat_vector_transpose_dense_(input_q_buf, dataB, dataY); backward_substitution_dense(input_r_buf, dataX, dataY); } gettimeofday(&after, NULL); printf("Solve all stages: %ld\n", ((after.tv_sec * 1000000 + after.tv_usec) - (before.tv_sec * 1000000 + before.tv_usec))); printf("\n"); free(dataQ); free(dataR); free(dataX); free(dataY); free_resources(); return 0; }
76.070281
552
0.608294
[ "vector" ]
fd752eb164bd7c7283a4aec778ffbf87156b3f8c
12,841
cc
C++
src/communication/ipv6/addressing/IPv6Address.cc
openDSME/CometOS
1907325847f2efa746bd76854b65578201c383d8
[ "BSD-3-Clause" ]
3
2019-01-14T19:08:07.000Z
2021-01-19T11:57:16.000Z
src/communication/ipv6/addressing/IPv6Address.cc
openDSME/CometOS
1907325847f2efa746bd76854b65578201c383d8
[ "BSD-3-Clause" ]
1
2016-11-11T14:35:03.000Z
2016-11-11T14:35:03.000Z
src/communication/ipv6/addressing/IPv6Address.cc
openDSME/CometOS
1907325847f2efa746bd76854b65578201c383d8
[ "BSD-3-Clause" ]
2
2020-09-14T08:27:09.000Z
2020-10-19T14:41:48.000Z
/* * CometOS --- a component-based, extensible, tiny operating system * for wireless networks * * Copyright (c) 2015, Institute of Telematics, Hamburg 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /** * @author Martin Ringwelski */ #include "IPv6Address.h" #include <string.h> #include "OutputStream.h" const uint8_t IPv6Address::MAX_PREFIX_LENGTH; bool IPv6Address::operator== (IPv6Address const & other) const { return (address[0] == other.getAddressPart(0) && address[1] == other.getAddressPart(1) && address[2] == other.getAddressPart(2) && address[3] == other.getAddressPart(3) && address[4] == other.getAddressPart(4) && address[5] == other.getAddressPart(5) && address[6] == other.getAddressPart(6) && address[7] == other.getAddressPart(7)); } bool IPv6Address::operator< (IPv6Address const & other) const { for (uint8_t i = 0; i < 8; i++) { if (address[i] < other.getAddressPart(i)) { return true; } else if (address[i] > other.getAddressPart(i)) { return false; } } return false; } bool IPv6Address::operator> (IPv6Address const & other) const { for (uint8_t i = 0; i < 8; i++) { if (address[i] > other.getAddressPart(i)) { return true; } else if (address[i] < other.getAddressPart(i)) { return false; } } return false; } bool IPv6Address::constructMask(uint8_t length, uint16_t mask[8]) const { uint8_t i; uint16_t numShifts = length & 0xF; uint8_t whole = length >> 4; if (length > 128) { ASSERT(false); return false; } for (i = 0; i < whole; i++) { mask[i] = 0xFFFF; } if (numShifts > 0) { mask[i] = 0xFFFF << (16 - numShifts); } return true; } /** * getPrefix * returns the prefix of the address. * * @param length length of the prefix in bits * * @return IPv6Address Object with the prefix and the rest 0 */ IPv6Address IPv6Address::getPrefix (uint8_t length) const { uint16_t mask[8] = {0,0,0,0,0,0,0,0}; constructMask(length, mask); IPv6Address ret(address[0] & mask[0], address[1] & mask[1], address[2] & mask[2], address[3] & mask[3], address[4] & mask[4], address[5] & mask[5], address[6] & mask[6], address[7] & mask[7]); return ret; } /** * getSuffix * returns the suffix of the address. * * @param length length of the prefix in bits * * @return IPv6Address Object with the suffix and the rest 0 */ IPv6Address IPv6Address::getSuffix (uint8_t length) const { uint16_t mask[8] = {0,0,0,0,0,0,0,0}; constructMask(length, mask); IPv6Address ret( address[0] & ~mask[0], address[1] & ~mask[1], address[2] & ~mask[2], address[3] & ~mask[3], address[4] & ~mask[4], address[5] & ~mask[5], address[6] & ~mask[6], address[7] & ~mask[7]); return ret; } void IPv6Address::setPrefix (IPv6Address const & prefix, uint8_t length) { uint16_t mask[8] = {0,0,0,0,0,0,0,0}; constructMask(length, mask); for (uint8_t i = 0; i < 8; i++) { address[i] = (address[i] & ~mask[i]) | (prefix.getAddressPart(i) & mask[i]); } } void IPv6Address::setSuffix (IPv6Address const & suffix, uint8_t length) { uint16_t mask[8] = {0,0,0,0,0,0,0,0}; constructMask(length, mask); for (uint8_t i = 0; i < 8; i++) { address[i] = (address[i] & mask[i]) | (suffix.getAddressPart(i) & ~mask[i]); } } void IPv6Address::writeAddress(uint8_t dest[16]) const { dest[0] = address[0] >> 8; dest[1] = address[0] & 0xFF; dest[2] = address[1] >> 8; dest[3] = address[1] & 0xFF; dest[4] = address[2] >> 8; dest[5] = address[2] & 0xFF; dest[6] = address[3] >> 8; dest[7] = address[3] & 0xFF; dest[8] = address[4] >> 8; dest[9] = address[4] & 0xFF; dest[10] = address[5] >> 8; dest[11] = address[5] & 0xFF; dest[12] = address[6] >> 8; dest[13] = address[6] & 0xFF; dest[14] = address[7] >> 8; dest[15] = address[7] & 0xFF; } bool IPv6Address::matches (IPv6Address const & addr, uint8_t length) const { uint16_t mask[8] = {0,0,0,0,0,0,0,0}; constructMask(length, mask); return (((address[0]^addr.getAddressPart(0))&mask[0]) | ((address[1]^addr.getAddressPart(1))&mask[1]) | ((address[2]^addr.getAddressPart(2))&mask[2]) | ((address[3]^addr.getAddressPart(3))&mask[3]) | ((address[4]^addr.getAddressPart(4))&mask[4]) | ((address[5]^addr.getAddressPart(5))&mask[5]) | ((address[6]^addr.getAddressPart(6))&mask[6]) | ((address[7]^addr.getAddressPart(7))&mask[7])) == 0; } bool IPv6Address::isUnspecified () const { return rangeIsZero(0,7); } bool IPv6Address::isLoopback () const { return (rangeIsZero(0,6) && address[7] == 1 ); } bool IPv6Address::isLoopbackBroadcast () const { return ( address[0] == 0xff01 && rangeIsZero(1,6) && address[7] == 1 ); } bool IPv6Address::isLocalBroadcast () const { return ( address[0] == 0xff02 && rangeIsZero(1,6) && address[7] == 1 ); } bool IPv6Address::isLoopbackRouterBroadcast() const { return ( address[0] == 0xff01 && rangeIsZero(1,6) && address[7] == 2 ); } bool IPv6Address::isLocalRouterBroadcast() const { return ( address[0] == 0xff02 && rangeIsZero(1,6) && address[7] == 2 ); } bool IPv6Address::isSiteRouterBroadcast() const { return ( address[0] == 0xff05 && rangeIsZero(1,6) && address[7] == 2 ); } // Helper: finds the longest sequence of zeroes in the address (at least with len=2) static void findGap(const uint16_t *groups, int& start, int& end) { start = end = 0; int beg = -1; for (int i=0; i<8; i++) { if (beg==-1 && groups[i]==0) { // begin counting beg = i; } else if (beg!=-1 && groups[i]!=0) { // end counting if (i-beg>=2 && i-beg>end-start) { start = beg; end = i; } beg = -1; } } // check last zero-seq if (beg!=-1 && beg<=6 && 8-beg>end-start) { start = beg; end = 8; } } cometos::SString<40> IPv6Address::str() const { cometos::SString<40> ret; if (isUnspecified()) { ret = "<unspec>"; return ret; } // find longest sequence of zeros in groups[] int start, end; findGap(address, start, end); if (start==0 && end==8) { ret = "::0"; // the unspecified address is a special case return ret; } // print groups, replacing gap with "::" for (int i=0; i<start; i++) { ret += ((i==0?"":":")); ret.append(address[i], cometos::SString_HEX); } if (start!=end) { ret += "::"; } for (int j=end; j<8; j++) { ret += (j==end?"":":"); ret.append(address[j], cometos::SString_HEX); } return ret; } #if defined(OMNETPP) || defined(BOARD_python) || defined(BOARD_local) static int parseGroups(const char *&s, int *groups) { int k = 0; while (k < 8) { char *e; groups[k] = strtoul(s, &e, 16); if (s==e) { // no hex digit converted if (k!=0) s--; // "unskip" preceding ':' return k; } // if negative or too big, return (s will point to beginning of large number) if (groups[k]<0 || groups[k]> (int)0xffff) return k; k++; // group[k] successfully stored s = e; // skip converted hex number if (*s!=':' || k==8) return k; s++; // skip ':' } return k; } bool IPv6Address::doTryParse(const char *&addr) { if (!strcmp(addr, "<unspec>")) { addr += 8; address[0] = address[1] = address[2] = address[3] = address[4] = address[5] = address[6] = address[7] = 0; return true; } // parse and store 16-bit units int groups[8]; int numGroups = parseGroups(addr, groups); // if address string contains "::", parse and store second half too if (*addr==':' && *(addr+1)==':') { addr += 2; int suffixGroups[8]; int numSuffixGroups = parseGroups(addr, suffixGroups); // merge suffixGroups[] into groups[] if (numGroups+numSuffixGroups>8) return false; // too many for (int i=numGroups; i<8; i++) { int j = i-8+numSuffixGroups; groups[i] = j<0 ? 0 : suffixGroups[j]; } numGroups = 8; } if (numGroups!=8) return false; // too few // copy groups to d[] for (unsigned int i=0; i<8; i++) address[i] = groups[i]; return true; } bool IPv6Address::tryParse(const char *addr) { if (!addr) return false; if (!doTryParse(addr)) return false; if (*addr!=0) return false; // illegal trailing character return true; } bool IPv6Address::tryParseAddrWithPrefix(const char *addr, uint8_t prefixLen) { if (!addr) return false; if (!doTryParse(addr)) return false; if (*addr!='/') return false; // no '/' after address addr++; // parse prefix char *e; prefixLen = strtoul(addr, &e, 10); if (addr==e) return false; // no number after '/' if (*e!=0) return false; // garbage after number if (prefixLen>128) return false; // wrong len value return true; } #endif namespace cometos { void serialize(ByteVector& buffer, const IPv6Address& value) { serialize(buffer, value.getAddressPart(7)); serialize(buffer, value.getAddressPart(6)); serialize(buffer, value.getAddressPart(5)); serialize(buffer, value.getAddressPart(4)); serialize(buffer, value.getAddressPart(3)); serialize(buffer, value.getAddressPart(2)); serialize(buffer, value.getAddressPart(1)); serialize(buffer, value.getAddressPart(0)); } void unserialize(ByteVector& buffer, IPv6Address& value) { uint16_t addr[8]; unserialize(buffer, addr[0]); unserialize(buffer, addr[1]); unserialize(buffer, addr[2]); unserialize(buffer, addr[3]); unserialize(buffer, addr[4]); unserialize(buffer, addr[5]); unserialize(buffer, addr[6]); unserialize(buffer, addr[7]); value.set(addr); } void serialize(ByteVector& buffer, const uint16_nbo& value) { serialize(buffer, value.lsb); serialize(buffer, value.msb); } void unserialize(ByteVector& buffer, uint16_nbo& value) { unserialize(buffer, value.msb); unserialize(buffer, value.lsb); } void serialize(ByteVector& buffer, const uint32_nbo& value) { serialize(buffer, value.lsb); serialize(buffer, value.msb); } void unserialize(ByteVector& buffer, uint32_nbo& value) { unserialize(buffer, value.msb); unserialize(buffer, value.lsb); } } //#endif //ifdef OMNETPP
27.854664
114
0.576902
[ "object" ]
fd75ced2c8fd0d5d2b537ffd6c06fe567483d602
6,000
cpp
C++
sdk/core/azure-core/src/http/url.cpp
chidozieononiwu/azure-sdk-for-cpp
7d9032fcc815523231d6ff3e1d96d6212e94b079
[ "MIT" ]
null
null
null
sdk/core/azure-core/src/http/url.cpp
chidozieononiwu/azure-sdk-for-cpp
7d9032fcc815523231d6ff3e1d96d6212e94b079
[ "MIT" ]
null
null
null
sdk/core/azure-core/src/http/url.cpp
chidozieononiwu/azure-sdk-for-cpp
7d9032fcc815523231d6ff3e1d96d6212e94b079
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include "azure/core/url.hpp" #include "azure/core/internal/strings.hpp" #include <algorithm> #include <cctype> #include <iterator> #include <limits> #include <stdexcept> #include <vector> using namespace Azure::Core; Url::Url(const std::string& url) { std::string::const_iterator pos = url.begin(); const std::string schemeEnd = "://"; auto schemeIter = url.find(schemeEnd); if (schemeIter != std::string::npos) { std::transform(url.begin(), url.begin() + schemeIter, std::back_inserter(m_scheme), [](char c) { return static_cast<char>( Azure::Core::_internal::StringExtensions::ToLower(static_cast<unsigned char>(c))); }); pos = url.begin() + schemeIter + schemeEnd.length(); } auto hostIter = std::find_if(pos, url.end(), [](char c) { return c == '/' || c == '?' || c == ':'; }); m_host = std::string(pos, hostIter); pos = hostIter; if (pos != url.end() && *pos == ':') { auto port_ite = std::find_if_not( pos + 1, url.end(), [](char c) { return std::isdigit(static_cast<unsigned char>(c)); }); auto portNumber = std::stoi(std::string(pos + 1, port_ite)); // stoi will throw out_of_range when `int` is overflow, but we need to throw if uint16 is // overflow auto maxPortNumberSupported = std::numeric_limits<uint16_t>::max(); if (portNumber > maxPortNumberSupported) { throw std::out_of_range( "The port number is out of range. The max supported number is " + std::to_string(maxPortNumberSupported) + "."); } // cast is safe because the overflow was detected before m_port = static_cast<uint16_t>(portNumber); pos = port_ite; } if (pos != url.end() && (*pos != '/') && (*pos != '?')) { // only char `\` or `?` is valid after the port (or the end of the url). Any other char is an // invalid input throw std::invalid_argument("The port number contains invalid characters."); } if (pos != url.end() && (*pos == '/')) { auto pathIter = std::find(pos + 1, url.end(), '?'); m_encodedPath = std::string(pos + 1, pathIter); pos = pathIter; } if (pos != url.end() && *pos == '?') { auto queryIter = std::find(pos + 1, url.end(), '#'); AppendQueryParameters(std::string(pos + 1, queryIter)); pos = queryIter; } } std::string Url::Decode(const std::string& value) { const static std::vector<int> hexTable = []() { std::vector<int> t(256, -1); for (int i = 0; i < 10; ++i) { t[static_cast<std::size_t>('0') + i] = i; } for (int i = 10; i < 16; ++i) { t[static_cast<std::size_t>('A') + i - 10] = i; t[static_cast<std::size_t>('a') + i - 10] = i; } return t; }(); std::string decodedValue; for (std::size_t i = 0; i < value.size();) { char c = value[i]; if (c == '+') { decodedValue += ' '; ++i; } else if (c == '%') { if (i + 2 >= value.size() || hexTable[value[i + 1]] < 0 || hexTable[value[i + 2]] < 0) { throw std::runtime_error("failed when decoding url component"); } int v = (hexTable[value[i + 1]] << 4) + hexTable[value[i + 2]]; decodedValue += static_cast<std::string::value_type>(v); i += 3; } else { decodedValue += value[i]; ++i; } } return decodedValue; } std::string Url::Encode(const std::string& value, const std::string& doNotEncodeSymbols) { const char* hex = "0123456789ABCDEF"; std::unordered_set<unsigned char> noEncodingSymbolsSet( doNotEncodeSymbols.begin(), doNotEncodeSymbols.end()); std::string encoded; for (char c : value) { unsigned char uc = c; // encode if char is not in the default non-encoding set AND if it is NOT in chars to ignore // from user input if (defaultNonUrlEncodeChars.find(uc) == defaultNonUrlEncodeChars.end() && noEncodingSymbolsSet.find(uc) == noEncodingSymbolsSet.end()) { encoded += '%'; encoded += hex[(uc >> 4) & 0x0f]; encoded += hex[uc & 0x0f]; } else { encoded += c; } } return encoded; } void Url::AppendQueryParameters(const std::string& query) { std::string::const_iterator cur = query.begin(); if (cur != query.end() && *cur == '?') { ++cur; } while (cur != query.end()) { auto key_end = std::find(cur, query.end(), '='); std::string query_key = std::string(cur, key_end); cur = key_end; if (cur != query.end()) { ++cur; } auto value_end = std::find(cur, query.end(), '&'); std::string query_value = std::string(cur, value_end); cur = value_end; if (cur != query.end()) { ++cur; } m_encodedQueryParameters[std::move(query_key)] = std::move(query_value); } } std::string Url::GetUrlWithoutQuery(bool relative) const { std::string url; if (!relative) { if (!m_scheme.empty()) { url += m_scheme + "://"; } url += m_host; if (m_port != 0) { url += ":" + std::to_string(m_port); } } if (!m_encodedPath.empty()) { if (!relative) { url += "/"; } url += m_encodedPath; } return url; } std::string Url::GetRelativeUrl() const { return GetUrlWithoutQuery(true) + _detail::FormatEncodedUrlQueryParameters(m_encodedQueryParameters); } std::string Url::GetAbsoluteUrl() const { return GetUrlWithoutQuery(false) + _detail::FormatEncodedUrlQueryParameters(m_encodedQueryParameters); } const std::unordered_set<unsigned char> Url::defaultNonUrlEncodeChars = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.', '_', '~'};
26.315789
100
0.563167
[ "vector", "transform" ]
fd80cbc8157ea22da837b424b026292aef64d7eb
1,953
cpp
C++
lib/src/EBTools/VoFIterator.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
10
2018-02-01T20:57:36.000Z
2022-03-17T02:57:49.000Z
lib/src/EBTools/VoFIterator.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
19
2018-10-04T21:37:18.000Z
2022-02-25T16:20:11.000Z
lib/src/EBTools/VoFIterator.cpp
rmrsk/Chombo-3.3
f2119e396460c1bb19638effd55eb71c2b35119e
[ "BSD-3-Clause-LBNL" ]
11
2019-01-12T23:33:32.000Z
2021-08-09T15:19:50.000Z
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif // ANAG, LBNL #include "VoFIterator.H" #include "EBGraph.H" #include "CH_Timer.H" #include "NamespaceHeader.H" /********************************/ const Vector<VolIndex> VoFIterator::getVector() const { CH_assert(m_isDefined); return m_vols; } /********************************/ VoFIterator::VoFIterator() { m_isDefined = false; } /********************************/ VoFIterator::~VoFIterator() { } /********************************/ VoFIterator::VoFIterator(const IntVectSet& a_ivs, const EBGraph& a_ebgraph) { define(a_ivs, a_ebgraph); } /********************************/ void VoFIterator::define(const IntVectSet& a_ivs, const EBGraph& a_ebgraph) { CH_TIMELEAF("VoFIterator::define"); //can't do this because minbox is broken // CH_assert((a_ebgraph.getRegion().contains(a_ivs.minBox())|| // a_ivs.isEmpty())); m_isDefined = true; m_vols.resize(0); for (IVSIterator ivsit(a_ivs); ivsit.ok(); ++ivsit) { m_vols.append(a_ebgraph.getVoFs(ivsit())); } reset(); } /********************************/ void VoFIterator::reset() { CH_assert(isDefined()); m_ivol = 0; } /********************************/ void VoFIterator::operator++() { CH_assert(isDefined()); m_ivol++; } /********************************/ const VolIndex& VoFIterator::operator() () const { CH_assert(isDefined()); CH_assert(m_ivol < m_vols.size()); return m_vols[m_ivol]; } /********************************/ bool VoFIterator::ok() const { return (m_ivol < m_vols.size()); } /********************************/ bool VoFIterator::isDefined() const { return m_isDefined; } /********************************/ #include "NamespaceFooter.H"
21
65
0.509985
[ "vector" ]
fd8201c98281fde26d0464603d958dc73b5a631c
10,182
hh
C++
reasoner/cturtle-1.0.6/src/Model.hh
nie-ine/microservice-reasoning-task
d340231b14d379e32d1ca49242011acaec872342
[ "MIT" ]
14
2016-03-14T19:19:28.000Z
2020-11-07T01:47:11.000Z
src/Model.hh
melgi/turtle
bcd3184fe7799f5113b6fe130b36a2fe2fa086c8
[ "Apache-2.0" ]
10
2016-02-01T12:37:20.000Z
2019-01-14T21:45:32.000Z
src/Model.hh
melgi/turtle
bcd3184fe7799f5113b6fe130b36a2fe2fa086c8
[ "Apache-2.0" ]
2
2016-09-07T12:00:09.000Z
2020-01-09T21:19:19.000Z
// // Copyright 2016 Giovanni Mels // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef N3_MODEL_HH #define N3_MODEL_HH #include <cstddef> #include <string> #include <ostream> #include <vector> #include <utility> namespace turtle { class URIResource; class BlankNode; class RDFList; class Literal; class BooleanLiteral; class IntegerLiteral; class DoubleLiteral; class DecimalLiteral; class StringLiteral; template<typename T> struct Cloneable { virtual T *clone() const = 0; virtual ~Cloneable() {}; }; struct N3NodeVisitor { virtual void visit(const URIResource &resource) = 0; virtual void visit(const BlankNode &blankNode) = 0; virtual void visit(const Literal &literal) = 0; virtual void visit(const RDFList &list) = 0; virtual void visit(const BooleanLiteral &literal) = 0; virtual void visit(const IntegerLiteral &literal) = 0; virtual void visit(const DoubleLiteral &literal) = 0; virtual void visit(const DecimalLiteral &literal) = 0; virtual void visit(const StringLiteral &literal) = 0; virtual ~N3NodeVisitor() {} }; struct N3Node : public Cloneable<N3Node> { virtual std::ostream &print(std::ostream &out) const = 0; virtual void visit(N3NodeVisitor &visitor) const = 0; }; std::ostream &operator<<(std::ostream &out, const N3Node &n); struct Resource : public N3Node { virtual Resource *clone() const = 0; }; class URIResource : public Resource { std::string m_uri; public: explicit URIResource(const std::string &uri) : Resource(), m_uri(uri) {} explicit URIResource(std::string &&uri) : Resource(), m_uri(std::move(uri)) {} const std::string &uri() const { return m_uri; } std::ostream &print(std::ostream &out) const override { out << '<' << m_uri << '>'; return out; } URIResource *clone() const override { return new URIResource(m_uri); } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class BlankNode : public Resource { std::string m_id; public: explicit BlankNode(const std::string &id) : Resource(), m_id(id) {} explicit BlankNode(std::string &&id) : Resource(), m_id(std::move(id)) {} const std::string &id() const { return m_id; } std::ostream &print(std::ostream &out) const override { out << "_:b" << m_id; return out; } BlankNode *clone() const override { return new BlankNode(m_id); } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class RDFList : public Resource { std::vector<N3Node *> m_elements; typedef std::vector<N3Node *>::iterator iterator; typedef std::vector<N3Node *>::const_iterator const_iterator; public: RDFList() : m_elements() {} RDFList(const RDFList &list) : RDFList() { m_elements.reserve(list.m_elements.size()); for (N3Node *n : list.m_elements) { m_elements.push_back(n->clone()); } } RDFList(RDFList &&list) : RDFList() { m_elements.swap(list.m_elements); } RDFList& operator=(RDFList list) { m_elements.swap(list.m_elements); return *this; } RDFList& operator=(RDFList &&list) noexcept { m_elements.swap(list.m_elements); return *this; } ~RDFList() { for (N3Node *n : m_elements) delete n; } void add(N3Node *element) { m_elements.push_back(element); } N3Node *&operator[](std::size_t index) { return m_elements[index]; } N3Node * const &operator[](std::size_t index) const { return m_elements[index]; } std::size_t size() const { return m_elements.size(); } iterator begin() { return m_elements.begin(); } iterator end() { return m_elements.end(); } const_iterator begin() const { return m_elements.begin(); } const_iterator end() const { return m_elements.end(); } bool empty() const { return m_elements.empty(); } std::ostream &print(std::ostream &out) const override { out << '('; for (N3Node *n : m_elements) out << ' ' << *n; out << ')'; return out; } RDFList *clone() const override { return new RDFList(*this); } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class Literal : public N3Node { protected: std::string m_lexical; const std::string *m_datatype; Literal(const std::string &lexical, const std::string *datatype) : N3Node(), m_lexical(lexical), m_datatype(datatype) {} Literal(std::string &&lexical, const std::string *datatype) noexcept : N3Node(), m_lexical(std::move(lexical)), m_datatype(datatype) {} public: const std::string &lexical() const { return m_lexical; } const std::string &datatype() const { return *m_datatype; } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class BooleanLiteral : public Literal { public: explicit BooleanLiteral(const std::string &value) : Literal(value, &TYPE) {} static const std::string TYPE; static const BooleanLiteral VALUE_TRUE; static const BooleanLiteral VALUE_FALSE; static const BooleanLiteral VALUE_1; static const BooleanLiteral VALUE_0; std::ostream &print(std::ostream &out) const { out << lexical(); return out; } bool value() const { return m_lexical == VALUE_TRUE.m_lexical || m_lexical == "1"; } BooleanLiteral *clone() const override { return new BooleanLiteral(m_lexical); } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class IntegerLiteral : public Literal { public: static const std::string TYPE; explicit IntegerLiteral(const std::string &value) : Literal(value, &TYPE) {} std::ostream &print(std::ostream &out) const override { out << lexical(); return out; } IntegerLiteral *clone() const override { return new IntegerLiteral(m_lexical); } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class DoubleLiteral : public Literal { public: static const std::string TYPE; explicit DoubleLiteral(const std::string &value) : Literal(value, &TYPE) {} std::ostream &print(std::ostream &out) const override { out << lexical(); return out; } DoubleLiteral *clone() const override { return new DoubleLiteral(m_lexical); } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class DecimalLiteral : public Literal { public: static const std::string TYPE; explicit DecimalLiteral(const std::string &value) : Literal(value, &TYPE) {} std::ostream &print(std::ostream &out) const override { out << lexical(); return out; } DecimalLiteral *clone() const override { return new DecimalLiteral(m_lexical); } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class StringLiteral : public Literal { std::string m_language; public: static const std::string TYPE; explicit StringLiteral(const std::string &value, const std::string &language = std::string()) : Literal(value, &TYPE), m_language(language) {} explicit StringLiteral(std::string &&value, std::string &&language = std::string()) : Literal(std::move(value), &TYPE), m_language(std::move(language)) {} const std::string &language() const { return m_language; } std::ostream &print(std::ostream &out) const override { out << '"' << lexical() << '"'; if (!language().empty()) out << '@' << language(); return out; } StringLiteral *clone() const override { return new StringLiteral(m_lexical, m_language); } void visit(N3NodeVisitor &visitor) const override { visitor.visit(*this); } }; class OtherLiteral : public Literal { /* keeps a copy of the type uri */ std::string m_datatype_copy; public: explicit OtherLiteral(const std::string &value, const std::string &datatype) : Literal(value, nullptr), m_datatype_copy(datatype) { m_datatype = &m_datatype_copy; } explicit OtherLiteral(std::string &&value, std::string &&datatype) noexcept : Literal(std::move(value), nullptr), m_datatype_copy(std::move(datatype)) { m_datatype = &m_datatype_copy; } OtherLiteral(const OtherLiteral &other) : Literal(other.m_lexical, nullptr), m_datatype_copy(other.m_datatype_copy) { m_datatype = &m_datatype_copy; } OtherLiteral(OtherLiteral &&other) noexcept : Literal(std::move(other.m_lexical), nullptr), m_datatype_copy(std::move(other.m_datatype_copy)) { m_datatype = &m_datatype_copy; } OtherLiteral& operator=(OtherLiteral other) { swap(other); return *this; } OtherLiteral& operator=(OtherLiteral &&other) noexcept { swap(other); return *this; } std::ostream &print(std::ostream &out) const override { out << '"' << lexical() << '"' << '@' << '<' << datatype() << '>'; return out; } OtherLiteral *clone() const override { return new OtherLiteral(m_lexical, m_datatype_copy); } void swap(OtherLiteral &other) noexcept { m_lexical.swap(other.m_lexical); m_datatype_copy.swap(other.m_datatype_copy); // m_datatype = &m_datatype_copy; } }; inline void swap(OtherLiteral &x, OtherLiteral &y) noexcept { x.swap(y); } struct RDF { static const std::string NS; static const URIResource type; static const URIResource first; static const URIResource rest; static const URIResource nil; }; struct XSD { static const std::string NS; }; } #endif /* N3_MODEL_HH */
21.345912
156
0.660774
[ "vector" ]
fd85c350f34c79d7ac85cca3170c78aa62ed5770
1,572
cpp
C++
Codeforces/DIV 3 Advanced upsolve grind - 2 (1700 - 1700)/D.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
2
2021-09-14T15:57:24.000Z
2022-03-18T14:11:04.000Z
Codeforces/DIV 3 Advanced upsolve grind - 2 (1700 - 1700)/D.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
null
null
null
Codeforces/DIV 3 Advanced upsolve grind - 2 (1700 - 1700)/D.cpp
noobie7/Codes
4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4
[ "MIT" ]
null
null
null
/* "An anomaly, I'm Muhammad Ali Cause I know one day I'm gonna be the" - Greatest, Eminem */ #pragma GCC optimize ("O3") #pragma GCC target ("sse4") #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; typedef long long int ll; #define ff first #define Shazam ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); #define ss second #define all(c) c.begin(),c.end() #define endl "\n" #define test() int t; cin>>t; while(t--) #define fl(i,a,b) for(int i = a ; i <b ;i++) #define get(a) fl(i,0,a.size()) cin>>a[i]; #define pra(a) fl(i,0,a.size()) cout<<a[i]<<" "; cout<<endl; #define pr(a,n) fl(i,0,n) cout<<a[i]<<" "; cout<<endl; typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; const ll INF = 2e18; const int inf = 2e9; const int mod1 = 1e9 + 7; #define Y cout << "YES" << endl; return 0; #define F cout << "NO" << endl; int main(){ Shazam; vector<int> c(12); // x1 y1 x2 y2 x3 y3 x4 y4 x5 y5 x6 y6 // 0 1 2 3 4 5 6 7 8 9 10 11 for(int &i : c){ cin >> i; i *= 2; } auto ok = [&](int x, int y){ return (x < c[4] || c[6] < x || y < c[5] || c[7] < y) && (x < c[8] || c[10] < x || y < c[9] || c[11] < y); }; for(int i = c[0]; i <= c[2]; i++){ if(ok(i, c[1])){Y} if(ok(i, c[3])){Y} } for(int i = c[1]; i <= c[3]; i++){ if(ok(c[0], i)){Y} if(ok(c[2], i)){Y} } F return 0; }
29.111111
114
0.541985
[ "vector" ]
fd8605c6b2312559e494f42af07ab6bd34b2d4dc
2,125
hpp
C++
src/include/Renderer/OpenGL/CommandQueue.hpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
1
2017-10-30T22:49:06.000Z
2017-10-30T22:49:06.000Z
src/include/Renderer/OpenGL/CommandQueue.hpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
null
null
null
src/include/Renderer/OpenGL/CommandQueue.hpp
foxostro/PinkTopaz
cd8275a93ea34a56f640f915d4b6c769e82e9dc2
[ "MIT" ]
null
null
null
// // CommandQueue.hpp // PinkTopaz // // Created by Andrew Fox on 2/24/17. // // #ifndef CommandQueue_hpp #define CommandQueue_hpp #include "Renderer/OpenGL/OpenGLException.hpp" #include <vector> #include <mutex> #include <thread> #include <string> #include <functional> #include <spdlog/spdlog.h> // Exception for when the command queue attempts to execute on the wrong thread. class CommandQueueInappropriateThreadOpenGLException : public OpenGLException { public: CommandQueueInappropriateThreadOpenGLException() : OpenGLException("This command queue can only be executed on the " \ "thread on which it was constructed. This is " \ "expected to be the OpenGL thread.") {} }; // Queues OpenGL API calls to be made at a later time on the proper thread. // The OpenGL API must only be accessed from a blessed render thread. To fit // this into the modern world of multithreaded applications, we use the // CommandQueue to queue up commands to be run on that thread later. class CommandQueue { public: CommandQueue(std::shared_ptr<spdlog::logger> log); ~CommandQueue() = default; // Cancel all tasks with the specified ID. Cancelled tasks are simply never // executed. Once a task begins executing, it cannot be cancelled. void cancel(unsigned id); // Immediately execute all commands in the command queue. void execute(); // Add a task to the command queue for later execution. // The specified ID allows the task to be cancelled later via cancel(). void enqueue(unsigned id, const std::string &label, std::function<void()> &&task); // Add a queue to the command queue for later execution. void enqueue(CommandQueue &otherQueue); private: std::thread::id _mainThreadId; std::mutex _queueLock; // The queue stores information about the task to execute. struct Task { unsigned id; std::string label; std::function<void()> fn; }; typedef std::vector<Task> Queue; Queue _queue; std::shared_ptr<spdlog::logger> _log; }; #endif /* CommandQueue_hpp */
27.960526
86
0.697412
[ "render", "vector" ]
fd88f0d6b4be975072952b1cd340af2a8ae3e35e
134,277
cpp
C++
FreeBSD/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
4
2016-08-22T22:02:55.000Z
2017-03-04T22:56:44.000Z
FreeBSD/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp
TigerBSD/FreeBSD-Custom-ThinkPad
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
FreeBSD/contrib/llvm/tools/lldb/source/Interpreter/CommandInterpreter.cpp
TigerBSD/TigerBSD
3d092f261b362f73170871403397fc5d6b89d1dc
[ "0BSD" ]
null
null
null
//===-- CommandInterpreter.cpp ----------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include <string> #include <vector> #include <stdlib.h> #include "CommandObjectScript.h" #include "lldb/Interpreter/CommandObjectRegexCommand.h" #include "../Commands/CommandObjectApropos.h" #include "../Commands/CommandObjectArgs.h" #include "../Commands/CommandObjectBreakpoint.h" #include "../Commands/CommandObjectBugreport.h" #include "../Commands/CommandObjectDisassemble.h" #include "../Commands/CommandObjectExpression.h" #include "../Commands/CommandObjectFrame.h" #include "../Commands/CommandObjectGUI.h" #include "../Commands/CommandObjectHelp.h" #include "../Commands/CommandObjectLog.h" #include "../Commands/CommandObjectMemory.h" #include "../Commands/CommandObjectPlatform.h" #include "../Commands/CommandObjectPlugin.h" #include "../Commands/CommandObjectProcess.h" #include "../Commands/CommandObjectQuit.h" #include "../Commands/CommandObjectRegister.h" #include "../Commands/CommandObjectSettings.h" #include "../Commands/CommandObjectSource.h" #include "../Commands/CommandObjectCommands.h" #include "../Commands/CommandObjectSyntax.h" #include "../Commands/CommandObjectTarget.h" #include "../Commands/CommandObjectThread.h" #include "../Commands/CommandObjectType.h" #include "../Commands/CommandObjectVersion.h" #include "../Commands/CommandObjectWatchpoint.h" #include "../Commands/CommandObjectLanguage.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Log.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/State.h" #include "lldb/Core/Stream.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/Timer.h" #ifndef LLDB_DISABLE_LIBEDIT #include "lldb/Host/Editline.h" #endif #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Interpreter/Args.h" #include "lldb/Interpreter/CommandCompletions.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/Options.h" #include "lldb/Interpreter/OptionValueProperties.h" #include "lldb/Interpreter/Property.h" #include "lldb/Target/Process.h" #include "lldb/Target/Thread.h" #include "lldb/Target/TargetList.h" #include "lldb/Utility/CleanUp.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Path.h" using namespace lldb; using namespace lldb_private; static const char *k_white_space = " \t\v"; static PropertyDefinition g_properties[] = { { "expand-regex-aliases", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, regular expression alias commands will show the expanded command that will be executed. This can be used to debug new regular expression alias commands." }, { "prompt-on-quit", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will prompt you before quitting if there are any live processes being debugged. If false, LLDB will quit without asking in any case." }, { "stop-command-source-on-error", OptionValue::eTypeBoolean, true, true, nullptr, nullptr, "If true, LLDB will stop running a 'command source' script upon encountering an error." }, { "space-repl-prompts", OptionValue::eTypeBoolean, true, false, nullptr, nullptr, "If true, blank lines will be printed between between REPL submissions." }, { nullptr , OptionValue::eTypeInvalid, true, 0 , nullptr, nullptr, nullptr } }; enum { ePropertyExpandRegexAliases = 0, ePropertyPromptOnQuit = 1, ePropertyStopCmdSourceOnError = 2, eSpaceReplPrompts = 3 }; ConstString & CommandInterpreter::GetStaticBroadcasterClass () { static ConstString class_name ("lldb.commandInterpreter"); return class_name; } CommandInterpreter::CommandInterpreter(Debugger &debugger, ScriptLanguage script_language, bool synchronous_execution) : Broadcaster(&debugger, CommandInterpreter::GetStaticBroadcasterClass().AsCString()), Properties(OptionValuePropertiesSP(new OptionValueProperties(ConstString("interpreter")))), IOHandlerDelegate(IOHandlerDelegate::Completion::LLDBCommand), m_debugger(debugger), m_synchronous_execution(synchronous_execution), m_skip_lldbinit_files(false), m_skip_app_init_files(false), m_script_interpreter_sp(), m_command_io_handler_sp(), m_comment_char('#'), m_batch_command_mode(false), m_truncation_warning(eNoTruncation), m_command_source_depth(0), m_num_errors(0), m_quit_requested(false), m_stopped_for_crash(false) { debugger.SetScriptLanguage (script_language); SetEventName (eBroadcastBitThreadShouldExit, "thread-should-exit"); SetEventName (eBroadcastBitResetPrompt, "reset-prompt"); SetEventName (eBroadcastBitQuitCommandReceived, "quit"); CheckInWithManager (); m_collection_sp->Initialize (g_properties); } bool CommandInterpreter::GetExpandRegexAliases () const { const uint32_t idx = ePropertyExpandRegexAliases; return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0); } bool CommandInterpreter::GetPromptOnQuit () const { const uint32_t idx = ePropertyPromptOnQuit; return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0); } void CommandInterpreter::SetPromptOnQuit (bool b) { const uint32_t idx = ePropertyPromptOnQuit; m_collection_sp->SetPropertyAtIndexAsBoolean (nullptr, idx, b); } void CommandInterpreter::ResolveCommand(const char *command_line, CommandReturnObject &result) { std::string command = command_line; if (ResolveCommandImpl(command, result) != nullptr) { result.AppendMessageWithFormat("%s", command.c_str()); result.SetStatus(eReturnStatusSuccessFinishResult); } } bool CommandInterpreter::GetStopCmdSourceOnError () const { const uint32_t idx = ePropertyStopCmdSourceOnError; return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0); } bool CommandInterpreter::GetSpaceReplPrompts () const { const uint32_t idx = eSpaceReplPrompts; return m_collection_sp->GetPropertyAtIndexAsBoolean (nullptr, idx, g_properties[idx].default_uint_value != 0); } void CommandInterpreter::Initialize () { Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); CommandReturnObject result; LoadCommandDictionary (); // Set up some initial aliases. CommandObjectSP cmd_obj_sp = GetCommandSPExact ("quit", false); if (cmd_obj_sp) { AddAlias ("q", cmd_obj_sp); AddAlias ("exit", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("_regexp-attach",false); if (cmd_obj_sp) { AddAlias ("attach", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("process detach",false); if (cmd_obj_sp) { AddAlias ("detach", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("process continue", false); if (cmd_obj_sp) { AddAlias ("c", cmd_obj_sp); AddAlias ("continue", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("_regexp-break",false); if (cmd_obj_sp) AddAlias ("b", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("_regexp-tbreak",false); if (cmd_obj_sp) AddAlias ("tbreak", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("thread step-inst", false); if (cmd_obj_sp) { AddAlias ("stepi", cmd_obj_sp); AddAlias ("si", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("thread step-inst-over", false); if (cmd_obj_sp) { AddAlias ("nexti", cmd_obj_sp); AddAlias ("ni", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("thread step-in", false); if (cmd_obj_sp) { AddAlias ("s", cmd_obj_sp); AddAlias ("step", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("thread step-over", false); if (cmd_obj_sp) { AddAlias ("n", cmd_obj_sp); AddAlias ("next", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("thread step-out", false); if (cmd_obj_sp) { AddAlias ("finish", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("frame select", false); if (cmd_obj_sp) { AddAlias ("f", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("thread select", false); if (cmd_obj_sp) { AddAlias ("t", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("_regexp-jump",false); if (cmd_obj_sp) { AddAlias ("j", cmd_obj_sp); AddAlias ("jump", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("_regexp-list", false); if (cmd_obj_sp) { AddAlias ("l", cmd_obj_sp); AddAlias ("list", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("_regexp-env", false); if (cmd_obj_sp) { AddAlias ("env", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("memory read", false); if (cmd_obj_sp) AddAlias ("x", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("_regexp-up", false); if (cmd_obj_sp) AddAlias ("up", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("_regexp-down", false); if (cmd_obj_sp) AddAlias ("down", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("_regexp-display", false); if (cmd_obj_sp) AddAlias ("display", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("disassemble", false); if (cmd_obj_sp) AddAlias ("dis", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("disassemble", false); if (cmd_obj_sp) AddAlias ("di", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("_regexp-undisplay", false); if (cmd_obj_sp) AddAlias ("undisplay", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("_regexp-bt", false); if (cmd_obj_sp) AddAlias ("bt", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("target create", false); if (cmd_obj_sp) AddAlias ("file", cmd_obj_sp); cmd_obj_sp = GetCommandSPExact ("target modules", false); if (cmd_obj_sp) AddAlias ("image", cmd_obj_sp); OptionArgVectorSP alias_arguments_vector_sp (new OptionArgVector); cmd_obj_sp = GetCommandSPExact ("expression", false); if (cmd_obj_sp) { ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp); AddAlias ("p", cmd_obj_sp); AddAlias ("print", cmd_obj_sp); AddAlias ("call", cmd_obj_sp); AddOrReplaceAliasOptions ("p", alias_arguments_vector_sp); AddOrReplaceAliasOptions ("print", alias_arguments_vector_sp); AddOrReplaceAliasOptions ("call", alias_arguments_vector_sp); alias_arguments_vector_sp.reset (new OptionArgVector); ProcessAliasOptionsArgs (cmd_obj_sp, "-O -- ", alias_arguments_vector_sp); AddAlias ("po", cmd_obj_sp); AddOrReplaceAliasOptions ("po", alias_arguments_vector_sp); } cmd_obj_sp = GetCommandSPExact ("process kill", false); if (cmd_obj_sp) { AddAlias ("kill", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("process launch", false); if (cmd_obj_sp) { alias_arguments_vector_sp.reset (new OptionArgVector); #if defined (__arm__) || defined (__arm64__) || defined (__aarch64__) ProcessAliasOptionsArgs (cmd_obj_sp, "--", alias_arguments_vector_sp); #else #if defined(__APPLE__) std::string shell_option; shell_option.append("--shell-expand-args"); shell_option.append(" true"); shell_option.append(" --"); ProcessAliasOptionsArgs (cmd_obj_sp, shell_option.c_str(), alias_arguments_vector_sp); #else std::string shell_option; shell_option.append("--shell="); shell_option.append(HostInfo::GetDefaultShell().GetPath()); shell_option.append(" --"); ProcessAliasOptionsArgs (cmd_obj_sp, shell_option.c_str(), alias_arguments_vector_sp); #endif #endif AddAlias ("r", cmd_obj_sp); AddAlias ("run", cmd_obj_sp); AddOrReplaceAliasOptions ("r", alias_arguments_vector_sp); AddOrReplaceAliasOptions ("run", alias_arguments_vector_sp); } cmd_obj_sp = GetCommandSPExact ("target symbols add", false); if (cmd_obj_sp) { AddAlias ("add-dsym", cmd_obj_sp); } cmd_obj_sp = GetCommandSPExact ("breakpoint set", false); if (cmd_obj_sp) { alias_arguments_vector_sp.reset (new OptionArgVector); ProcessAliasOptionsArgs (cmd_obj_sp, "--func-regex %1", alias_arguments_vector_sp); AddAlias ("rbreak", cmd_obj_sp); AddOrReplaceAliasOptions("rbreak", alias_arguments_vector_sp); } } void CommandInterpreter::Clear() { m_command_io_handler_sp.reset(); if (m_script_interpreter_sp) m_script_interpreter_sp->Clear(); } const char * CommandInterpreter::ProcessEmbeddedScriptCommands (const char *arg) { // This function has not yet been implemented. // Look for any embedded script command // If found, // get interpreter object from the command dictionary, // call execute_one_command on it, // get the results as a string, // substitute that string for current stuff. return arg; } void CommandInterpreter::LoadCommandDictionary () { Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__); lldb::ScriptLanguage script_language = m_debugger.GetScriptLanguage(); m_command_dict["apropos"] = CommandObjectSP (new CommandObjectApropos (*this)); m_command_dict["breakpoint"]= CommandObjectSP (new CommandObjectMultiwordBreakpoint (*this)); m_command_dict["bugreport"] = CommandObjectSP (new CommandObjectMultiwordBugreport (*this)); m_command_dict["command"] = CommandObjectSP (new CommandObjectMultiwordCommands (*this)); m_command_dict["disassemble"] = CommandObjectSP (new CommandObjectDisassemble (*this)); m_command_dict["expression"]= CommandObjectSP (new CommandObjectExpression (*this)); m_command_dict["frame"] = CommandObjectSP (new CommandObjectMultiwordFrame (*this)); m_command_dict["gui"] = CommandObjectSP (new CommandObjectGUI (*this)); m_command_dict["help"] = CommandObjectSP (new CommandObjectHelp (*this)); m_command_dict["log"] = CommandObjectSP (new CommandObjectLog (*this)); m_command_dict["memory"] = CommandObjectSP (new CommandObjectMemory (*this)); m_command_dict["platform"] = CommandObjectSP (new CommandObjectPlatform (*this)); m_command_dict["plugin"] = CommandObjectSP (new CommandObjectPlugin (*this)); m_command_dict["process"] = CommandObjectSP (new CommandObjectMultiwordProcess (*this)); m_command_dict["quit"] = CommandObjectSP (new CommandObjectQuit (*this)); m_command_dict["register"] = CommandObjectSP (new CommandObjectRegister (*this)); m_command_dict["script"] = CommandObjectSP (new CommandObjectScript (*this, script_language)); m_command_dict["settings"] = CommandObjectSP (new CommandObjectMultiwordSettings (*this)); m_command_dict["source"] = CommandObjectSP (new CommandObjectMultiwordSource (*this)); m_command_dict["target"] = CommandObjectSP (new CommandObjectMultiwordTarget (*this)); m_command_dict["thread"] = CommandObjectSP (new CommandObjectMultiwordThread (*this)); m_command_dict["type"] = CommandObjectSP (new CommandObjectType (*this)); m_command_dict["version"] = CommandObjectSP (new CommandObjectVersion (*this)); m_command_dict["watchpoint"]= CommandObjectSP (new CommandObjectMultiwordWatchpoint (*this)); m_command_dict["language"] = CommandObjectSP (new CommandObjectLanguage(*this)); const char *break_regexes[][2] = {{"^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "breakpoint set --file '%1' --line %2"}, {"^/([^/]+)/$", "breakpoint set --source-pattern-regexp '%1'"}, {"^([[:digit:]]+)[[:space:]]*$", "breakpoint set --line %1"}, {"^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "breakpoint set --address %1"}, {"^[\"']?([-+]?\\[.*\\])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}, {"^(-.*)$", "breakpoint set %1"}, {"^(.*[^[:space:]])`(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%2' --shlib '%1'"}, {"^\\&(.*[^[:space:]])[[:space:]]*$", "breakpoint set --name '%1' --skip-prologue=0"}, {"^[\"']?(.*[^[:space:]\"'])[\"']?[[:space:]]*$", "breakpoint set --name '%1'"}}; size_t num_regexes = llvm::array_lengthof(break_regexes); std::unique_ptr<CommandObjectRegexCommand> break_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-break", "Set a breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.\n", "\n_regexp-break <filename>:<linenum> # _regexp-break main.c:12 // Break on line 12 of main.c\n" "_regexp-break <linenum> # _regexp-break 12 // Break on line 12 of current file\n" "_regexp-break <address> # _regexp-break 0x1234000 // Break on address 0x1234000\n" "_regexp-break <name> # _regexp-break main // Break in 'main' after the prologue\n" "_regexp-break &<name> # _regexp-break &main // Break on the first instruction in 'main'\n" "_regexp-break <module>`<name> # _regexp-break libc.so`malloc // Break in 'malloc' only in the 'libc.so' shared library\n" "_regexp-break /<source-regex>/ # _regexp-break /break here/ // Break on all lines that match the regular expression 'break here' in the current file.\n", 2, CommandCompletions::eSymbolCompletion | CommandCompletions::eSourceFileCompletion, false)); if (break_regex_cmd_ap.get()) { bool success = true; for (size_t i = 0; i < num_regexes; i++) { success = break_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], break_regexes[i][1]); if (!success) break; } success = break_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); if (success) { CommandObjectSP break_regex_cmd_sp(break_regex_cmd_ap.release()); m_command_dict[break_regex_cmd_sp->GetCommandName ()] = break_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> tbreak_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-tbreak", "Set a one shot breakpoint using a regular expression to specify the location, where <linenum> is in decimal and <address> is in hex.", "_regexp-tbreak [<filename>:<linenum>]\n_regexp-break [<linenum>]\n_regexp-break [<address>]\n_regexp-break <...>", 2, CommandCompletions::eSymbolCompletion | CommandCompletions::eSourceFileCompletion, false)); if (tbreak_regex_cmd_ap.get()) { bool success = true; for (size_t i = 0; i < num_regexes; i++) { // If you add a resultant command string longer than 1024 characters be sure to increase the size of this buffer. char buffer[1024]; int num_printed = snprintf(buffer, 1024, "%s %s", break_regexes[i][1], "-o"); assert (num_printed < 1024); UNUSED_IF_ASSERT_DISABLED(num_printed); success = tbreak_regex_cmd_ap->AddRegexCommand (break_regexes[i][0], buffer); if (!success) break; } success = tbreak_regex_cmd_ap->AddRegexCommand("^$", "breakpoint list --full"); if (success) { CommandObjectSP tbreak_regex_cmd_sp(tbreak_regex_cmd_ap.release()); m_command_dict[tbreak_regex_cmd_sp->GetCommandName ()] = tbreak_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> attach_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-attach", "Attach to a process id if in decimal, otherwise treat the argument as a process name to attach to.", "_regexp-attach [<pid>]\n_regexp-attach [<process-name>]", 2, 0, false)); if (attach_regex_cmd_ap.get()) { if (attach_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "process attach --pid %1") && attach_regex_cmd_ap->AddRegexCommand("^(-.*|.* -.*)$", "process attach %1") && // Any options that are specified get passed to 'process attach' attach_regex_cmd_ap->AddRegexCommand("^(.+)$", "process attach --name '%1'") && attach_regex_cmd_ap->AddRegexCommand("^$", "process attach")) { CommandObjectSP attach_regex_cmd_sp(attach_regex_cmd_ap.release()); m_command_dict[attach_regex_cmd_sp->GetCommandName ()] = attach_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> down_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-down", "Go down \"n\" frames in the stack (1 frame by default).", "_regexp-down [n]", 2, 0, false)); if (down_regex_cmd_ap.get()) { if (down_regex_cmd_ap->AddRegexCommand("^$", "frame select -r -1") && down_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r -%1")) { CommandObjectSP down_regex_cmd_sp(down_regex_cmd_ap.release()); m_command_dict[down_regex_cmd_sp->GetCommandName ()] = down_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> up_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-up", "Go up \"n\" frames in the stack (1 frame by default).", "_regexp-up [n]", 2, 0, false)); if (up_regex_cmd_ap.get()) { if (up_regex_cmd_ap->AddRegexCommand("^$", "frame select -r 1") && up_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "frame select -r %1")) { CommandObjectSP up_regex_cmd_sp(up_regex_cmd_ap.release()); m_command_dict[up_regex_cmd_sp->GetCommandName ()] = up_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> display_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-display", "Add an expression evaluation stop-hook.", "_regexp-display expression", 2, 0, false)); if (display_regex_cmd_ap.get()) { if (display_regex_cmd_ap->AddRegexCommand("^(.+)$", "target stop-hook add -o \"expr -- %1\"")) { CommandObjectSP display_regex_cmd_sp(display_regex_cmd_ap.release()); m_command_dict[display_regex_cmd_sp->GetCommandName ()] = display_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> undisplay_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-undisplay", "Remove an expression evaluation stop-hook.", "_regexp-undisplay stop-hook-number", 2, 0, false)); if (undisplay_regex_cmd_ap.get()) { if (undisplay_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "target stop-hook delete %1")) { CommandObjectSP undisplay_regex_cmd_sp(undisplay_regex_cmd_ap.release()); m_command_dict[undisplay_regex_cmd_sp->GetCommandName ()] = undisplay_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> connect_gdb_remote_cmd_ap(new CommandObjectRegexCommand (*this, "gdb-remote", "Connect to a remote GDB server. If no hostname is provided, localhost is assumed.", "gdb-remote [<hostname>:]<portnum>", 2, 0, false)); if (connect_gdb_remote_cmd_ap.get()) { if (connect_gdb_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin gdb-remote connect://%1") && connect_gdb_remote_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "process connect --plugin gdb-remote connect://localhost:%1")) { CommandObjectSP command_sp(connect_gdb_remote_cmd_ap.release()); m_command_dict[command_sp->GetCommandName ()] = command_sp; } } std::unique_ptr<CommandObjectRegexCommand> connect_kdp_remote_cmd_ap(new CommandObjectRegexCommand (*this, "kdp-remote", "Connect to a remote KDP server. udp port 41139 is the default port number.", "kdp-remote <hostname>[:<portnum>]", 2, 0, false)); if (connect_kdp_remote_cmd_ap.get()) { if (connect_kdp_remote_cmd_ap->AddRegexCommand("^([^:]+:[[:digit:]]+)$", "process connect --plugin kdp-remote udp://%1") && connect_kdp_remote_cmd_ap->AddRegexCommand("^(.+)$", "process connect --plugin kdp-remote udp://%1:41139")) { CommandObjectSP command_sp(connect_kdp_remote_cmd_ap.release()); m_command_dict[command_sp->GetCommandName ()] = command_sp; } } std::unique_ptr<CommandObjectRegexCommand> bt_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-bt", "Show a backtrace. An optional argument is accepted; if that argument is a number, it specifies the number of frames to display. If that argument is 'all', full backtraces of all threads are displayed.", "bt [<digit>|all]", 2, 0, false)); if (bt_regex_cmd_ap.get()) { // accept but don't document "bt -c <number>" -- before bt was a regex command if you wanted to backtrace // three frames you would do "bt -c 3" but the intention is to have this emulate the gdb "bt" command and // so now "bt 3" is the preferred form, in line with gdb. if (bt_regex_cmd_ap->AddRegexCommand("^([[:digit:]]+)$", "thread backtrace -c %1") && bt_regex_cmd_ap->AddRegexCommand("^-c ([[:digit:]]+)$", "thread backtrace -c %1") && bt_regex_cmd_ap->AddRegexCommand("^all$", "thread backtrace all") && bt_regex_cmd_ap->AddRegexCommand("^$", "thread backtrace")) { CommandObjectSP command_sp(bt_regex_cmd_ap.release()); m_command_dict[command_sp->GetCommandName ()] = command_sp; } } std::unique_ptr<CommandObjectRegexCommand> list_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-list", "Implements the GDB 'list' command in all of its forms except FILE:FUNCTION and maps them to the appropriate 'source list' commands.", "_regexp-list [<line>]\n_regexp-list [<file>:<line>]\n_regexp-list [<file>:<line>]", 2, CommandCompletions::eSourceFileCompletion, false)); if (list_regex_cmd_ap.get()) { if (list_regex_cmd_ap->AddRegexCommand("^([0-9]+)[[:space:]]*$", "source list --line %1") && list_regex_cmd_ap->AddRegexCommand("^(.*[^[:space:]])[[:space:]]*:[[:space:]]*([[:digit:]]+)[[:space:]]*$", "source list --file '%1' --line %2") && list_regex_cmd_ap->AddRegexCommand("^\\*?(0x[[:xdigit:]]+)[[:space:]]*$", "source list --address %1") && list_regex_cmd_ap->AddRegexCommand("^-[[:space:]]*$", "source list --reverse") && list_regex_cmd_ap->AddRegexCommand("^-([[:digit:]]+)[[:space:]]*$", "source list --reverse --count %1") && list_regex_cmd_ap->AddRegexCommand("^(.+)$", "source list --name \"%1\"") && list_regex_cmd_ap->AddRegexCommand("^$", "source list")) { CommandObjectSP list_regex_cmd_sp(list_regex_cmd_ap.release()); m_command_dict[list_regex_cmd_sp->GetCommandName ()] = list_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> env_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-env", "Implements a shortcut to viewing and setting environment variables.", "_regexp-env\n_regexp-env FOO=BAR", 2, 0, false)); if (env_regex_cmd_ap.get()) { if (env_regex_cmd_ap->AddRegexCommand("^$", "settings show target.env-vars") && env_regex_cmd_ap->AddRegexCommand("^([A-Za-z_][A-Za-z_0-9]*=.*)$", "settings set target.env-vars %1")) { CommandObjectSP env_regex_cmd_sp(env_regex_cmd_ap.release()); m_command_dict[env_regex_cmd_sp->GetCommandName ()] = env_regex_cmd_sp; } } std::unique_ptr<CommandObjectRegexCommand> jump_regex_cmd_ap(new CommandObjectRegexCommand (*this, "_regexp-jump", "Sets the program counter to a new address.", "_regexp-jump [<line>]\n" "_regexp-jump [<+-lineoffset>]\n" "_regexp-jump [<file>:<line>]\n" "_regexp-jump [*<addr>]\n", 2, 0, false)); if (jump_regex_cmd_ap.get()) { if (jump_regex_cmd_ap->AddRegexCommand("^\\*(.*)$", "thread jump --addr %1") && jump_regex_cmd_ap->AddRegexCommand("^([0-9]+)$", "thread jump --line %1") && jump_regex_cmd_ap->AddRegexCommand("^([^:]+):([0-9]+)$", "thread jump --file %1 --line %2") && jump_regex_cmd_ap->AddRegexCommand("^([+\\-][0-9]+)$", "thread jump --by %1")) { CommandObjectSP jump_regex_cmd_sp(jump_regex_cmd_ap.release()); m_command_dict[jump_regex_cmd_sp->GetCommandName ()] = jump_regex_cmd_sp; } } } int CommandInterpreter::GetCommandNamesMatchingPartialString (const char *cmd_str, bool include_aliases, StringList &matches) { CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_str, matches); if (include_aliases) { CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_str, matches); } return matches.GetSize(); } CommandObjectSP CommandInterpreter::GetCommandSP (const char *cmd_cstr, bool include_aliases, bool exact, StringList *matches) { CommandObject::CommandMap::iterator pos; CommandObjectSP command_sp; std::string cmd(cmd_cstr); if (HasCommands()) { pos = m_command_dict.find(cmd); if (pos != m_command_dict.end()) command_sp = pos->second; } if (include_aliases && HasAliases()) { pos = m_alias_dict.find(cmd); if (pos != m_alias_dict.end()) command_sp = pos->second; } if (HasUserCommands()) { pos = m_user_dict.find(cmd); if (pos != m_user_dict.end()) command_sp = pos->second; } if (!exact && !command_sp) { // We will only get into here if we didn't find any exact matches. CommandObjectSP user_match_sp, alias_match_sp, real_match_sp; StringList local_matches; if (matches == nullptr) matches = &local_matches; unsigned int num_cmd_matches = 0; unsigned int num_alias_matches = 0; unsigned int num_user_matches = 0; // Look through the command dictionaries one by one, and if we get only one match from any of // them in toto, then return that, otherwise return an empty CommandObjectSP and the list of matches. if (HasCommands()) { num_cmd_matches = CommandObject::AddNamesMatchingPartialString (m_command_dict, cmd_cstr, *matches); } if (num_cmd_matches == 1) { cmd.assign(matches->GetStringAtIndex(0)); pos = m_command_dict.find(cmd); if (pos != m_command_dict.end()) real_match_sp = pos->second; } if (include_aliases && HasAliases()) { num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd_cstr, *matches); } if (num_alias_matches == 1) { cmd.assign(matches->GetStringAtIndex (num_cmd_matches)); pos = m_alias_dict.find(cmd); if (pos != m_alias_dict.end()) alias_match_sp = pos->second; } if (HasUserCommands()) { num_user_matches = CommandObject::AddNamesMatchingPartialString (m_user_dict, cmd_cstr, *matches); } if (num_user_matches == 1) { cmd.assign (matches->GetStringAtIndex (num_cmd_matches + num_alias_matches)); pos = m_user_dict.find (cmd); if (pos != m_user_dict.end()) user_match_sp = pos->second; } // If we got exactly one match, return that, otherwise return the match list. if (num_user_matches + num_cmd_matches + num_alias_matches == 1) { if (num_cmd_matches) return real_match_sp; else if (num_alias_matches) return alias_match_sp; else return user_match_sp; } } else if (matches && command_sp) { matches->AppendString (cmd_cstr); } return command_sp; } bool CommandInterpreter::AddCommand (const char *name, const lldb::CommandObjectSP &cmd_sp, bool can_replace) { if (name && name[0]) { std::string name_sstr(name); bool found = (m_command_dict.find (name_sstr) != m_command_dict.end()); if (found && !can_replace) return false; if (found && m_command_dict[name_sstr]->IsRemovable() == false) return false; m_command_dict[name_sstr] = cmd_sp; return true; } return false; } bool CommandInterpreter::AddUserCommand (std::string name, const lldb::CommandObjectSP &cmd_sp, bool can_replace) { if (!name.empty()) { const char* name_cstr = name.c_str(); // do not allow replacement of internal commands if (CommandExists(name_cstr)) { if (can_replace == false) return false; if (m_command_dict[name]->IsRemovable() == false) return false; } if (UserCommandExists(name_cstr)) { if (can_replace == false) return false; if (m_user_dict[name]->IsRemovable() == false) return false; } m_user_dict[name] = cmd_sp; return true; } return false; } CommandObjectSP CommandInterpreter::GetCommandSPExact (const char *cmd_cstr, bool include_aliases) { Args cmd_words (cmd_cstr); // Break up the command string into words, in case it's a multi-word command. CommandObjectSP ret_val; // Possibly empty return value. if (cmd_cstr == nullptr) return ret_val; if (cmd_words.GetArgumentCount() == 1) return GetCommandSP(cmd_cstr, include_aliases, true, nullptr); else { // We have a multi-word command (seemingly), so we need to do more work. // First, get the cmd_obj_sp for the first word in the command. CommandObjectSP cmd_obj_sp = GetCommandSP (cmd_words.GetArgumentAtIndex (0), include_aliases, true, nullptr); if (cmd_obj_sp.get() != nullptr) { // Loop through the rest of the words in the command (everything passed in was supposed to be part of a // command name), and find the appropriate sub-command SP for each command word.... size_t end = cmd_words.GetArgumentCount(); for (size_t j= 1; j < end; ++j) { if (cmd_obj_sp->IsMultiwordObject()) { cmd_obj_sp = cmd_obj_sp->GetSubcommandSP (cmd_words.GetArgumentAtIndex (j)); if (cmd_obj_sp.get() == nullptr) // The sub-command name was invalid. Fail and return the empty 'ret_val'. return ret_val; } else // We have more words in the command name, but we don't have a multiword object. Fail and return // empty 'ret_val'. return ret_val; } // We successfully looped through all the command words and got valid command objects for them. Assign the // last object retrieved to 'ret_val'. ret_val = cmd_obj_sp; } } return ret_val; } CommandObject * CommandInterpreter::GetCommandObjectExact (const char *cmd_cstr, bool include_aliases) { return GetCommandSPExact (cmd_cstr, include_aliases).get(); } CommandObject * CommandInterpreter::GetCommandObject (const char *cmd_cstr, StringList *matches) { CommandObject *command_obj = GetCommandSP (cmd_cstr, false, true, matches).get(); // If we didn't find an exact match to the command string in the commands, look in // the aliases. if (command_obj) return command_obj; command_obj = GetCommandSP (cmd_cstr, true, true, matches).get(); if (command_obj) return command_obj; // If there wasn't an exact match then look for an inexact one in just the commands command_obj = GetCommandSP(cmd_cstr, false, false, nullptr).get(); // Finally, if there wasn't an inexact match among the commands, look for an inexact // match in both the commands and aliases. if (command_obj) { if (matches) matches->AppendString(command_obj->GetCommandName()); return command_obj; } return GetCommandSP(cmd_cstr, true, false, matches).get(); } bool CommandInterpreter::CommandExists (const char *cmd) { return m_command_dict.find(cmd) != m_command_dict.end(); } bool CommandInterpreter::ProcessAliasOptionsArgs (lldb::CommandObjectSP &cmd_obj_sp, const char *options_args, OptionArgVectorSP &option_arg_vector_sp) { bool success = true; OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); if (!options_args || (strlen (options_args) < 1)) return true; std::string options_string (options_args); Args args (options_args); CommandReturnObject result; // Check to see if the command being aliased can take any command options. Options *options = cmd_obj_sp->GetOptions (); if (options) { // See if any options were specified as part of the alias; if so, handle them appropriately. options->NotifyOptionParsingStarting (); args.Unshift ("dummy_arg"); args.ParseAliasOptions (*options, result, option_arg_vector, options_string); args.Shift (); if (result.Succeeded()) options->VerifyPartialOptions (result); if (!result.Succeeded() && result.GetStatus() != lldb::eReturnStatusStarted) { result.AppendError ("Unable to create requested alias.\n"); return false; } } if (!options_string.empty()) { if (cmd_obj_sp->WantsRawCommandString ()) option_arg_vector->push_back (OptionArgPair ("<argument>", OptionArgValue (-1, options_string))); else { const size_t argc = args.GetArgumentCount(); for (size_t i = 0; i < argc; ++i) if (strcmp (args.GetArgumentAtIndex (i), "") != 0) option_arg_vector->push_back (OptionArgPair ("<argument>", OptionArgValue (-1, std::string (args.GetArgumentAtIndex (i))))); } } return success; } bool CommandInterpreter::GetAliasFullName (const char *cmd, std::string &full_name) { bool exact_match = (m_alias_dict.find(cmd) != m_alias_dict.end()); if (exact_match) { full_name.assign(cmd); return exact_match; } else { StringList matches; size_t num_alias_matches; num_alias_matches = CommandObject::AddNamesMatchingPartialString (m_alias_dict, cmd, matches); if (num_alias_matches == 1) { // Make sure this isn't shadowing a command in the regular command space: StringList regular_matches; const bool include_aliases = false; const bool exact = false; CommandObjectSP cmd_obj_sp(GetCommandSP (cmd, include_aliases, exact, &regular_matches)); if (cmd_obj_sp || regular_matches.GetSize() > 0) return false; else { full_name.assign (matches.GetStringAtIndex(0)); return true; } } else return false; } } bool CommandInterpreter::AliasExists (const char *cmd) { return m_alias_dict.find(cmd) != m_alias_dict.end(); } bool CommandInterpreter::UserCommandExists (const char *cmd) { return m_user_dict.find(cmd) != m_user_dict.end(); } void CommandInterpreter::AddAlias (const char *alias_name, CommandObjectSP& command_obj_sp) { command_obj_sp->SetIsAlias (true); m_alias_dict[alias_name] = command_obj_sp; } bool CommandInterpreter::RemoveAlias (const char *alias_name) { CommandObject::CommandMap::iterator pos = m_alias_dict.find(alias_name); if (pos != m_alias_dict.end()) { m_alias_dict.erase(pos); return true; } return false; } bool CommandInterpreter::RemoveCommand (const char *cmd) { auto pos = m_command_dict.find(cmd); if (pos != m_command_dict.end()) { if (pos->second->IsRemovable()) { // Only regular expression objects or python commands are removable m_command_dict.erase(pos); return true; } } return false; } bool CommandInterpreter::RemoveUser (const char *alias_name) { CommandObject::CommandMap::iterator pos = m_user_dict.find(alias_name); if (pos != m_user_dict.end()) { m_user_dict.erase(pos); return true; } return false; } void CommandInterpreter::GetAliasHelp (const char *alias_name, const char *command_name, StreamString &help_string) { help_string.Printf ("'%s", command_name); OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); if (option_arg_vector_sp) { OptionArgVector *options = option_arg_vector_sp.get(); for (size_t i = 0; i < options->size(); ++i) { OptionArgPair cur_option = (*options)[i]; std::string opt = cur_option.first; OptionArgValue value_pair = cur_option.second; std::string value = value_pair.second; if (opt.compare("<argument>") == 0) { help_string.Printf (" %s", value.c_str()); } else { help_string.Printf (" %s", opt.c_str()); if ((value.compare ("<no-argument>") != 0) && (value.compare ("<need-argument") != 0)) { help_string.Printf (" %s", value.c_str()); } } } } help_string.Printf ("'"); } size_t CommandInterpreter::FindLongestCommandWord (CommandObject::CommandMap &dict) { CommandObject::CommandMap::const_iterator pos; CommandObject::CommandMap::const_iterator end = dict.end(); size_t max_len = 0; for (pos = dict.begin(); pos != end; ++pos) { size_t len = pos->first.size(); if (max_len < len) max_len = len; } return max_len; } void CommandInterpreter::GetHelp (CommandReturnObject &result, uint32_t cmd_types) { const char * help_prologue = GetDebugger().GetIOHandlerHelpPrologue(); if (help_prologue != NULL) { OutputFormattedHelpText(result.GetOutputStream(), NULL, help_prologue); } CommandObject::CommandMap::const_iterator pos; size_t max_len = FindLongestCommandWord (m_command_dict); if ( (cmd_types & eCommandTypesBuiltin) == eCommandTypesBuiltin ) { result.AppendMessage("Debugger commands:"); result.AppendMessage(""); for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) { if (!(cmd_types & eCommandTypesHidden) && (pos->first.compare(0, 1, "_") == 0)) continue; OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), max_len); } result.AppendMessage(""); } if (!m_alias_dict.empty() && ( (cmd_types & eCommandTypesAliases) == eCommandTypesAliases )) { result.AppendMessageWithFormat("Current command abbreviations " "(type '%shelp command alias' for more info):\n", GetCommandPrefix()); result.AppendMessage(""); max_len = FindLongestCommandWord (m_alias_dict); for (pos = m_alias_dict.begin(); pos != m_alias_dict.end(); ++pos) { StreamString sstr; StreamString translation_and_help; std::string entry_name = pos->first; std::string second_entry = pos->second.get()->GetCommandName(); GetAliasHelp (pos->first.c_str(), pos->second->GetCommandName(), sstr); translation_and_help.Printf ("(%s) %s", sstr.GetData(), pos->second->GetHelp()); OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", translation_and_help.GetData(), max_len); } result.AppendMessage(""); } if (!m_user_dict.empty() && ( (cmd_types & eCommandTypesUserDef) == eCommandTypesUserDef )) { result.AppendMessage ("Current user-defined commands:"); result.AppendMessage(""); max_len = FindLongestCommandWord (m_user_dict); for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) { OutputFormattedHelpText (result.GetOutputStream(), pos->first.c_str(), "--", pos->second->GetHelp(), max_len); } result.AppendMessage(""); } result.AppendMessageWithFormat("For more information on any command, type '%shelp <command-name>'.\n", GetCommandPrefix()); } CommandObject * CommandInterpreter::GetCommandObjectForCommand (std::string &command_string) { // This function finds the final, lowest-level, alias-resolved command object whose 'Execute' function will // eventually be invoked by the given command line. CommandObject *cmd_obj = nullptr; size_t start = command_string.find_first_not_of (k_white_space); size_t end = 0; bool done = false; while (!done) { if (start != std::string::npos) { // Get the next word from command_string. end = command_string.find_first_of (k_white_space, start); if (end == std::string::npos) end = command_string.size(); std::string cmd_word = command_string.substr (start, end - start); if (cmd_obj == nullptr) // Since cmd_obj is NULL we are on our first time through this loop. Check to see if cmd_word is a valid // command or alias. cmd_obj = GetCommandObject (cmd_word.c_str()); else if (cmd_obj->IsMultiwordObject ()) { // Our current object is a multi-word object; see if the cmd_word is a valid sub-command for our object. CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject (cmd_word.c_str()); if (sub_cmd_obj) cmd_obj = sub_cmd_obj; else // cmd_word was not a valid sub-command word, so we are done done = true; } else // We have a cmd_obj and it is not a multi-word object, so we are done. done = true; // If we didn't find a valid command object, or our command object is not a multi-word object, or // we are at the end of the command_string, then we are done. Otherwise, find the start of the // next word. if (!cmd_obj || !cmd_obj->IsMultiwordObject() || end >= command_string.size()) done = true; else start = command_string.find_first_not_of (k_white_space, end); } else // Unable to find any more words. done = true; } if (end == command_string.size()) command_string.clear(); else command_string = command_string.substr(end); return cmd_obj; } static const char *k_valid_command_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"; static void StripLeadingSpaces (std::string &s) { if (!s.empty()) { size_t pos = s.find_first_not_of (k_white_space); if (pos == std::string::npos) s.clear(); else if (pos == 0) return; s.erase (0, pos); } } static size_t FindArgumentTerminator (const std::string &s) { const size_t s_len = s.size(); size_t offset = 0; while (offset < s_len) { size_t pos = s.find ("--", offset); if (pos == std::string::npos) break; if (pos > 0) { if (isspace(s[pos-1])) { // Check if the string ends "\s--" (where \s is a space character) // or if we have "\s--\s". if ((pos + 2 >= s_len) || isspace(s[pos+2])) { return pos; } } } offset = pos + 2; } return std::string::npos; } static bool ExtractCommand (std::string &command_string, std::string &command, std::string &suffix, char &quote_char) { command.clear(); suffix.clear(); StripLeadingSpaces (command_string); bool result = false; quote_char = '\0'; if (!command_string.empty()) { const char first_char = command_string[0]; if (first_char == '\'' || first_char == '"') { quote_char = first_char; const size_t end_quote_pos = command_string.find (quote_char, 1); if (end_quote_pos == std::string::npos) { command.swap (command_string); command_string.erase (); } else { command.assign (command_string, 1, end_quote_pos - 1); if (end_quote_pos + 1 < command_string.size()) command_string.erase (0, command_string.find_first_not_of (k_white_space, end_quote_pos + 1)); else command_string.erase (); } } else { const size_t first_space_pos = command_string.find_first_of (k_white_space); if (first_space_pos == std::string::npos) { command.swap (command_string); command_string.erase(); } else { command.assign (command_string, 0, first_space_pos); command_string.erase(0, command_string.find_first_not_of (k_white_space, first_space_pos)); } } result = true; } if (!command.empty()) { // actual commands can't start with '-' or '_' if (command[0] != '-' && command[0] != '_') { size_t pos = command.find_first_not_of(k_valid_command_chars); if (pos > 0 && pos != std::string::npos) { suffix.assign (command.begin() + pos, command.end()); command.erase (pos); } } } return result; } CommandObject * CommandInterpreter::BuildAliasResult (const char *alias_name, std::string &raw_input_string, std::string &alias_result, CommandReturnObject &result) { CommandObject *alias_cmd_obj = nullptr; Args cmd_args (raw_input_string); alias_cmd_obj = GetCommandObject (alias_name); StreamString result_str; if (alias_cmd_obj) { std::string alias_name_str = alias_name; if ((cmd_args.GetArgumentCount() == 0) || (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0)) cmd_args.Unshift (alias_name); result_str.Printf ("%s", alias_cmd_obj->GetCommandName ()); OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); if (option_arg_vector_sp.get()) { OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); for (size_t i = 0; i < option_arg_vector->size(); ++i) { OptionArgPair option_pair = (*option_arg_vector)[i]; OptionArgValue value_pair = option_pair.second; int value_type = value_pair.first; std::string option = option_pair.first; std::string value = value_pair.second; if (option.compare ("<argument>") == 0) result_str.Printf (" %s", value.c_str()); else { result_str.Printf (" %s", option.c_str()); if (value_type != OptionParser::eNoArgument) { if (value_type != OptionParser::eOptionalArgument) result_str.Printf (" "); int index = GetOptionArgumentPosition (value.c_str()); if (index == 0) result_str.Printf ("%s", value.c_str()); else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) { result.AppendErrorWithFormat ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", index); result.SetStatus (eReturnStatusFailed); return nullptr; } else { size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); if (strpos != std::string::npos) raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index))); result_str.Printf ("%s", cmd_args.GetArgumentAtIndex (index)); } } } } } alias_result = result_str.GetData(); } return alias_cmd_obj; } Error CommandInterpreter::PreprocessCommand (std::string &command) { // The command preprocessor needs to do things to the command // line before any parsing of arguments or anything else is done. // The only current stuff that gets preprocessed is anything enclosed // in backtick ('`') characters is evaluated as an expression and // the result of the expression must be a scalar that can be substituted // into the command. An example would be: // (lldb) memory read `$rsp + 20` Error error; // Error for any expressions that might not evaluate size_t start_backtick; size_t pos = 0; while ((start_backtick = command.find ('`', pos)) != std::string::npos) { if (start_backtick > 0 && command[start_backtick-1] == '\\') { // The backtick was preceded by a '\' character, remove the slash // and don't treat the backtick as the start of an expression command.erase(start_backtick-1, 1); // No need to add one to start_backtick since we just deleted a char pos = start_backtick; } else { const size_t expr_content_start = start_backtick + 1; const size_t end_backtick = command.find ('`', expr_content_start); if (end_backtick == std::string::npos) return error; else if (end_backtick == expr_content_start) { // Empty expression (two backticks in a row) command.erase (start_backtick, 2); } else { std::string expr_str (command, expr_content_start, end_backtick - expr_content_start); ExecutionContext exe_ctx(GetExecutionContext()); Target *target = exe_ctx.GetTargetPtr(); // Get a dummy target to allow for calculator mode while processing backticks. // This also helps break the infinite loop caused when target is null. if (!target) target = m_debugger.GetDummyTarget(); if (target) { ValueObjectSP expr_result_valobj_sp; EvaluateExpressionOptions options; options.SetCoerceToId(false); options.SetUnwindOnError(true); options.SetIgnoreBreakpoints(true); options.SetKeepInMemory(false); options.SetTryAllThreads(true); options.SetTimeoutUsec(0); ExpressionResults expr_result = target->EvaluateExpression (expr_str.c_str(), exe_ctx.GetFramePtr(), expr_result_valobj_sp, options); if (expr_result == eExpressionCompleted) { Scalar scalar; if (expr_result_valobj_sp) expr_result_valobj_sp = expr_result_valobj_sp->GetQualifiedRepresentationIfAvailable(expr_result_valobj_sp->GetDynamicValueType(), true); if (expr_result_valobj_sp->ResolveValue (scalar)) { command.erase (start_backtick, end_backtick - start_backtick + 1); StreamString value_strm; const bool show_type = false; scalar.GetValue (&value_strm, show_type); size_t value_string_size = value_strm.GetSize(); if (value_string_size) { command.insert (start_backtick, value_strm.GetData(), value_string_size); pos = start_backtick + value_string_size; continue; } else { error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str()); } } else { error.SetErrorStringWithFormat("expression value didn't result in a scalar value for the expression '%s'", expr_str.c_str()); } } else { if (expr_result_valobj_sp) error = expr_result_valobj_sp->GetError(); if (error.Success()) { switch (expr_result) { case eExpressionSetupError: error.SetErrorStringWithFormat("expression setup error for the expression '%s'", expr_str.c_str()); break; case eExpressionParseError: error.SetErrorStringWithFormat ("expression parse error for the expression '%s'", expr_str.c_str()); break; case eExpressionResultUnavailable: error.SetErrorStringWithFormat ("expression error fetching result for the expression '%s'", expr_str.c_str()); case eExpressionCompleted: break; case eExpressionDiscarded: error.SetErrorStringWithFormat("expression discarded for the expression '%s'", expr_str.c_str()); break; case eExpressionInterrupted: error.SetErrorStringWithFormat("expression interrupted for the expression '%s'", expr_str.c_str()); break; case eExpressionHitBreakpoint: error.SetErrorStringWithFormat("expression hit breakpoint for the expression '%s'", expr_str.c_str()); break; case eExpressionTimedOut: error.SetErrorStringWithFormat("expression timed out for the expression '%s'", expr_str.c_str()); break; case eExpressionStoppedForDebug: error.SetErrorStringWithFormat("expression stop at entry point for debugging for the expression '%s'", expr_str.c_str()); break; } } } } } if (error.Fail()) break; } } return error; } bool CommandInterpreter::HandleCommand (const char *command_line, LazyBool lazy_add_to_history, CommandReturnObject &result, ExecutionContext *override_context, bool repeat_on_empty_command, bool no_context_switching) { std::string command_string (command_line); std::string original_command_string (command_line); Log *log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMANDS)); Host::SetCrashDescriptionWithFormat ("HandleCommand(command = \"%s\")", command_line); // Make a scoped cleanup object that will clear the crash description string // on exit of this function. lldb_utility::CleanUp <const char *> crash_description_cleanup(nullptr, Host::SetCrashDescription); if (log) log->Printf ("Processing command: %s", command_line); Timer scoped_timer (__PRETTY_FUNCTION__, "Handling command: %s.", command_line); if (!no_context_switching) UpdateExecutionContext (override_context); bool add_to_history; if (lazy_add_to_history == eLazyBoolCalculate) add_to_history = (m_command_source_depth == 0); else add_to_history = (lazy_add_to_history == eLazyBoolYes); bool empty_command = false; bool comment_command = false; if (command_string.empty()) empty_command = true; else { const char *k_space_characters = "\t\n\v\f\r "; size_t non_space = command_string.find_first_not_of (k_space_characters); // Check for empty line or comment line (lines whose first // non-space character is the comment character for this interpreter) if (non_space == std::string::npos) empty_command = true; else if (command_string[non_space] == m_comment_char) comment_command = true; else if (command_string[non_space] == CommandHistory::g_repeat_char) { const char *history_string = m_command_history.FindString(command_string.c_str() + non_space); if (history_string == nullptr) { result.AppendErrorWithFormat ("Could not find entry: %s in history", command_string.c_str()); result.SetStatus(eReturnStatusFailed); return false; } add_to_history = false; command_string = history_string; original_command_string = history_string; } } if (empty_command) { if (repeat_on_empty_command) { if (m_command_history.IsEmpty()) { result.AppendError ("empty command"); result.SetStatus(eReturnStatusFailed); return false; } else { command_line = m_repeat_command.c_str(); command_string = command_line; original_command_string = command_line; if (m_repeat_command.empty()) { result.AppendErrorWithFormat("No auto repeat.\n"); result.SetStatus (eReturnStatusFailed); return false; } } add_to_history = false; } else { result.SetStatus (eReturnStatusSuccessFinishNoResult); return true; } } else if (comment_command) { result.SetStatus (eReturnStatusSuccessFinishNoResult); return true; } Error error (PreprocessCommand (command_string)); if (error.Fail()) { result.AppendError (error.AsCString()); result.SetStatus(eReturnStatusFailed); return false; } // Phase 1. // Before we do ANY kind of argument processing, we need to figure out what // the real/final command object is for the specified command. This gets // complicated by the fact that the user could have specified an alias, and, // in translating the alias, there may also be command options and/or even // data (including raw text strings) that need to be found and inserted into // the command line as part of the translation. So this first step is plain // look-up and replacement, resulting in: // 1. the command object whose Execute method will actually be called // 2. a revised command string, with all substitutions and replacements // taken care of // From 1 above, we can determine whether the Execute function wants raw // input or not. CommandObject *cmd_obj = ResolveCommandImpl(command_string, result); // Although the user may have abbreviated the command, the command_string now // has the command expanded to the full name. For example, if the input // was "br s -n main", command_string is now "breakpoint set -n main". if (log) { log->Printf("HandleCommand, cmd_obj : '%s'", cmd_obj ? cmd_obj->GetCommandName() : "<not found>"); log->Printf("HandleCommand, (revised) command_string: '%s'", command_string.c_str()); const bool wants_raw_input = (cmd_obj != NULL) ? cmd_obj->WantsRawCommandString() : false; log->Printf("HandleCommand, wants_raw_input:'%s'", wants_raw_input ? "True" : "False"); } // Phase 2. // Take care of things like setting up the history command & calling the appropriate Execute method on the // CommandObject, with the appropriate arguments. if (cmd_obj != nullptr) { if (add_to_history) { Args command_args (command_string); const char *repeat_command = cmd_obj->GetRepeatCommand(command_args, 0); if (repeat_command != nullptr) m_repeat_command.assign(repeat_command); else m_repeat_command.assign(original_command_string.c_str()); m_command_history.AppendString (original_command_string); } std::string remainder; const std::size_t actual_cmd_name_len = strlen (cmd_obj->GetCommandName()); if (actual_cmd_name_len < command_string.length()) remainder = command_string.substr (actual_cmd_name_len); // Remove any initial spaces size_t pos = remainder.find_first_not_of (k_white_space); if (pos != 0 && pos != std::string::npos) remainder.erase(0, pos); if (log) log->Printf ("HandleCommand, command line after removing command name(s): '%s'", remainder.c_str()); cmd_obj->Execute (remainder.c_str(), result); } else { // We didn't find the first command object, so complete the first argument. Args command_args (command_string); StringList matches; int num_matches; int cursor_index = 0; int cursor_char_position = strlen (command_args.GetArgumentAtIndex(0)); bool word_complete; num_matches = HandleCompletionMatches (command_args, cursor_index, cursor_char_position, 0, -1, word_complete, matches); if (num_matches > 0) { std::string error_msg; error_msg.assign ("ambiguous command '"); error_msg.append(command_args.GetArgumentAtIndex(0)); error_msg.append ("'."); error_msg.append (" Possible completions:"); for (int i = 0; i < num_matches; i++) { error_msg.append ("\n\t"); error_msg.append (matches.GetStringAtIndex (i)); } error_msg.append ("\n"); result.AppendRawError (error_msg.c_str()); } else result.AppendErrorWithFormat ("Unrecognized command '%s'.\n", command_args.GetArgumentAtIndex (0)); result.SetStatus (eReturnStatusFailed); } if (log) log->Printf ("HandleCommand, command %s", (result.Succeeded() ? "succeeded" : "did not succeed")); return result.Succeeded(); } int CommandInterpreter::HandleCompletionMatches (Args &parsed_line, int &cursor_index, int &cursor_char_position, int match_start_point, int max_return_elements, bool &word_complete, StringList &matches) { int num_command_matches = 0; bool look_for_subcommand = false; // For any of the command completions a unique match will be a complete word. word_complete = true; if (cursor_index == -1) { // We got nothing on the command line, so return the list of commands bool include_aliases = true; num_command_matches = GetCommandNamesMatchingPartialString ("", include_aliases, matches); } else if (cursor_index == 0) { // The cursor is in the first argument, so just do a lookup in the dictionary. CommandObject *cmd_obj = GetCommandObject (parsed_line.GetArgumentAtIndex(0), &matches); num_command_matches = matches.GetSize(); if (num_command_matches == 1 && cmd_obj && cmd_obj->IsMultiwordObject() && matches.GetStringAtIndex(0) != nullptr && strcmp (parsed_line.GetArgumentAtIndex(0), matches.GetStringAtIndex(0)) == 0) { if (parsed_line.GetArgumentCount() == 1) { word_complete = true; } else { look_for_subcommand = true; num_command_matches = 0; matches.DeleteStringAtIndex(0); parsed_line.AppendArgument (""); cursor_index++; cursor_char_position = 0; } } } if (cursor_index > 0 || look_for_subcommand) { // We are completing further on into a commands arguments, so find the command and tell it // to complete the command. // First see if there is a matching initial command: CommandObject *command_object = GetCommandObject (parsed_line.GetArgumentAtIndex(0)); if (command_object == nullptr) { return 0; } else { parsed_line.Shift(); cursor_index--; num_command_matches = command_object->HandleCompletion (parsed_line, cursor_index, cursor_char_position, match_start_point, max_return_elements, word_complete, matches); } } return num_command_matches; } int CommandInterpreter::HandleCompletion (const char *current_line, const char *cursor, const char *last_char, int match_start_point, int max_return_elements, StringList &matches) { // We parse the argument up to the cursor, so the last argument in parsed_line is // the one containing the cursor, and the cursor is after the last character. Args parsed_line(llvm::StringRef(current_line, last_char - current_line)); Args partial_parsed_line(llvm::StringRef(current_line, cursor - current_line)); // Don't complete comments, and if the line we are completing is just the history repeat character, // substitute the appropriate history line. const char *first_arg = parsed_line.GetArgumentAtIndex(0); if (first_arg) { if (first_arg[0] == m_comment_char) return 0; else if (first_arg[0] == CommandHistory::g_repeat_char) { const char *history_string = m_command_history.FindString (first_arg); if (history_string != nullptr) { matches.Clear(); matches.InsertStringAtIndex(0, history_string); return -2; } else return 0; } } int num_args = partial_parsed_line.GetArgumentCount(); int cursor_index = partial_parsed_line.GetArgumentCount() - 1; int cursor_char_position; if (cursor_index == -1) cursor_char_position = 0; else cursor_char_position = strlen (partial_parsed_line.GetArgumentAtIndex(cursor_index)); if (cursor > current_line && cursor[-1] == ' ') { // We are just after a space. If we are in an argument, then we will continue // parsing, but if we are between arguments, then we have to complete whatever the next // element would be. // We can distinguish the two cases because if we are in an argument (e.g. because the space is // protected by a quote) then the space will also be in the parsed argument... const char *current_elem = partial_parsed_line.GetArgumentAtIndex(cursor_index); if (cursor_char_position == 0 || current_elem[cursor_char_position - 1] != ' ') { parsed_line.InsertArgumentAtIndex(cursor_index + 1, "", '\0'); cursor_index++; cursor_char_position = 0; } } int num_command_matches; matches.Clear(); // Only max_return_elements == -1 is supported at present: assert (max_return_elements == -1); bool word_complete; num_command_matches = HandleCompletionMatches (parsed_line, cursor_index, cursor_char_position, match_start_point, max_return_elements, word_complete, matches); if (num_command_matches <= 0) return num_command_matches; if (num_args == 0) { // If we got an empty string, insert nothing. matches.InsertStringAtIndex(0, ""); } else { // Now figure out if there is a common substring, and if so put that in element 0, otherwise // put an empty string in element 0. std::string command_partial_str; if (cursor_index >= 0) command_partial_str.assign(parsed_line.GetArgumentAtIndex(cursor_index), parsed_line.GetArgumentAtIndex(cursor_index) + cursor_char_position); std::string common_prefix; matches.LongestCommonPrefix (common_prefix); const size_t partial_name_len = command_partial_str.size(); common_prefix.erase (0, partial_name_len); // If we matched a unique single command, add a space... // Only do this if the completer told us this was a complete word, however... if (num_command_matches == 1 && word_complete) { char quote_char = parsed_line.GetArgumentQuoteCharAtIndex(cursor_index); common_prefix = Args::EscapeLLDBCommandArgument(common_prefix, quote_char); if (quote_char != '\0') common_prefix.push_back(quote_char); common_prefix.push_back(' '); } matches.InsertStringAtIndex(0, common_prefix.c_str()); } return num_command_matches; } CommandInterpreter::~CommandInterpreter () { } void CommandInterpreter::UpdatePrompt (const char *new_prompt) { EventSP prompt_change_event_sp (new Event(eBroadcastBitResetPrompt, new EventDataBytes (new_prompt)));; BroadcastEvent (prompt_change_event_sp); if (m_command_io_handler_sp) m_command_io_handler_sp->SetPrompt(new_prompt); } bool CommandInterpreter::Confirm (const char *message, bool default_answer) { // Check AutoConfirm first: if (m_debugger.GetAutoConfirm()) return default_answer; IOHandlerConfirm *confirm = new IOHandlerConfirm(m_debugger, message, default_answer); IOHandlerSP io_handler_sp (confirm); m_debugger.RunIOHandler (io_handler_sp); return confirm->GetResponse(); } OptionArgVectorSP CommandInterpreter::GetAliasOptions (const char *alias_name) { OptionArgMap::iterator pos; OptionArgVectorSP ret_val; std::string alias (alias_name); if (HasAliasOptions()) { pos = m_alias_options.find (alias); if (pos != m_alias_options.end()) ret_val = pos->second; } return ret_val; } void CommandInterpreter::RemoveAliasOptions (const char *alias_name) { OptionArgMap::iterator pos = m_alias_options.find(alias_name); if (pos != m_alias_options.end()) { m_alias_options.erase (pos); } } void CommandInterpreter::AddOrReplaceAliasOptions (const char *alias_name, OptionArgVectorSP &option_arg_vector_sp) { m_alias_options[alias_name] = option_arg_vector_sp; } bool CommandInterpreter::HasCommands () { return (!m_command_dict.empty()); } bool CommandInterpreter::HasAliases () { return (!m_alias_dict.empty()); } bool CommandInterpreter::HasUserCommands () { return (!m_user_dict.empty()); } bool CommandInterpreter::HasAliasOptions () { return (!m_alias_options.empty()); } void CommandInterpreter::BuildAliasCommandArgs (CommandObject *alias_cmd_obj, const char *alias_name, Args &cmd_args, std::string &raw_input_string, CommandReturnObject &result) { OptionArgVectorSP option_arg_vector_sp = GetAliasOptions (alias_name); bool wants_raw_input = alias_cmd_obj->WantsRawCommandString(); // Make sure that the alias name is the 0th element in cmd_args std::string alias_name_str = alias_name; if (alias_name_str.compare (cmd_args.GetArgumentAtIndex(0)) != 0) cmd_args.Unshift (alias_name); Args new_args (alias_cmd_obj->GetCommandName()); if (new_args.GetArgumentCount() == 2) new_args.Shift(); if (option_arg_vector_sp.get()) { if (wants_raw_input) { // We have a command that both has command options and takes raw input. Make *sure* it has a // " -- " in the right place in the raw_input_string. size_t pos = raw_input_string.find(" -- "); if (pos == std::string::npos) { // None found; assume it goes at the beginning of the raw input string raw_input_string.insert (0, " -- "); } } OptionArgVector *option_arg_vector = option_arg_vector_sp.get(); const size_t old_size = cmd_args.GetArgumentCount(); std::vector<bool> used (old_size + 1, false); used[0] = true; for (size_t i = 0; i < option_arg_vector->size(); ++i) { OptionArgPair option_pair = (*option_arg_vector)[i]; OptionArgValue value_pair = option_pair.second; int value_type = value_pair.first; std::string option = option_pair.first; std::string value = value_pair.second; if (option.compare ("<argument>") == 0) { if (!wants_raw_input || (value.compare("--") != 0)) // Since we inserted this above, make sure we don't insert it twice new_args.AppendArgument (value.c_str()); } else { if (value_type != OptionParser::eOptionalArgument) new_args.AppendArgument (option.c_str()); if (value.compare ("<no-argument>") != 0) { int index = GetOptionArgumentPosition (value.c_str()); if (index == 0) { // value was NOT a positional argument; must be a real value if (value_type != OptionParser::eOptionalArgument) new_args.AppendArgument (value.c_str()); else { char buffer[255]; ::snprintf (buffer, sizeof (buffer), "%s%s", option.c_str(), value.c_str()); new_args.AppendArgument (buffer); } } else if (static_cast<size_t>(index) >= cmd_args.GetArgumentCount()) { result.AppendErrorWithFormat ("Not enough arguments provided; you need at least %d arguments to use this alias.\n", index); result.SetStatus (eReturnStatusFailed); return; } else { // Find and remove cmd_args.GetArgumentAtIndex(i) from raw_input_string size_t strpos = raw_input_string.find (cmd_args.GetArgumentAtIndex (index)); if (strpos != std::string::npos) { raw_input_string = raw_input_string.erase (strpos, strlen (cmd_args.GetArgumentAtIndex (index))); } if (value_type != OptionParser::eOptionalArgument) new_args.AppendArgument (cmd_args.GetArgumentAtIndex (index)); else { char buffer[255]; ::snprintf (buffer, sizeof(buffer), "%s%s", option.c_str(), cmd_args.GetArgumentAtIndex (index)); new_args.AppendArgument (buffer); } used[index] = true; } } } } for (size_t j = 0; j < cmd_args.GetArgumentCount(); ++j) { if (!used[j] && !wants_raw_input) new_args.AppendArgument (cmd_args.GetArgumentAtIndex (j)); } cmd_args.Clear(); cmd_args.SetArguments (new_args.GetArgumentCount(), new_args.GetConstArgumentVector()); } else { result.SetStatus (eReturnStatusSuccessFinishNoResult); // This alias was not created with any options; nothing further needs to be done, unless it is a command that // wants raw input, in which case we need to clear the rest of the data from cmd_args, since its in the raw // input string. if (wants_raw_input) { cmd_args.Clear(); cmd_args.SetArguments (new_args.GetArgumentCount(), new_args.GetConstArgumentVector()); } return; } result.SetStatus (eReturnStatusSuccessFinishNoResult); return; } int CommandInterpreter::GetOptionArgumentPosition (const char *in_string) { int position = 0; // Any string that isn't an argument position, i.e. '%' followed by an integer, gets a position // of zero. const char *cptr = in_string; // Does it start with '%' if (cptr[0] == '%') { ++cptr; // Is the rest of it entirely digits? if (isdigit (cptr[0])) { const char *start = cptr; while (isdigit (cptr[0])) ++cptr; // We've gotten to the end of the digits; are we at the end of the string? if (cptr[0] == '\0') position = atoi (start); } } return position; } void CommandInterpreter::SourceInitFile (bool in_cwd, CommandReturnObject &result) { FileSpec init_file; if (in_cwd) { // In the current working directory we don't load any program specific // .lldbinit files, we only look for a "./.lldbinit" file. if (m_skip_lldbinit_files) return; init_file.SetFile ("./.lldbinit", true); } else { // If we aren't looking in the current working directory we are looking // in the home directory. We will first see if there is an application // specific ".lldbinit" file whose name is "~/.lldbinit" followed by a // "-" and the name of the program. If this file doesn't exist, we fall // back to just the "~/.lldbinit" file. We also obey any requests to not // load the init files. llvm::SmallString<64> home_dir_path; llvm::sys::path::home_directory(home_dir_path); FileSpec profilePath(home_dir_path.c_str(), false); profilePath.AppendPathComponent(".lldbinit"); std::string init_file_path = profilePath.GetPath(); if (m_skip_app_init_files == false) { FileSpec program_file_spec(HostInfo::GetProgramFileSpec()); const char *program_name = program_file_spec.GetFilename().AsCString(); if (program_name) { char program_init_file_name[PATH_MAX]; ::snprintf (program_init_file_name, sizeof(program_init_file_name), "%s-%s", init_file_path.c_str(), program_name); init_file.SetFile (program_init_file_name, true); if (!init_file.Exists()) init_file.Clear(); } } if (!init_file && !m_skip_lldbinit_files) init_file.SetFile (init_file_path.c_str(), false); } // If the file exists, tell HandleCommand to 'source' it; this will do the actual broadcasting // of the commands back to any appropriate listener (see CommandObjectSource::Execute for more details). if (init_file.Exists()) { const bool saved_batch = SetBatchCommandMode (true); CommandInterpreterRunOptions options; options.SetSilent (true); options.SetStopOnError (false); options.SetStopOnContinue (true); HandleCommandsFromFile (init_file, nullptr, // Execution context options, result); SetBatchCommandMode (saved_batch); } else { // nothing to be done if the file doesn't exist result.SetStatus(eReturnStatusSuccessFinishNoResult); } } const char * CommandInterpreter::GetCommandPrefix() { const char * prefix = GetDebugger().GetIOHandlerCommandPrefix(); return prefix == NULL ? "" : prefix; } PlatformSP CommandInterpreter::GetPlatform (bool prefer_target_platform) { PlatformSP platform_sp; if (prefer_target_platform) { ExecutionContext exe_ctx(GetExecutionContext()); Target *target = exe_ctx.GetTargetPtr(); if (target) platform_sp = target->GetPlatform(); } if (!platform_sp) platform_sp = m_debugger.GetPlatformList().GetSelectedPlatform(); return platform_sp; } void CommandInterpreter::HandleCommands (const StringList &commands, ExecutionContext *override_context, CommandInterpreterRunOptions &options, CommandReturnObject &result) { size_t num_lines = commands.GetSize(); // If we are going to continue past a "continue" then we need to run the commands synchronously. // Make sure you reset this value anywhere you return from the function. bool old_async_execution = m_debugger.GetAsyncExecution(); // If we've been given an execution context, set it at the start, but don't keep resetting it or we will // cause series of commands that change the context, then do an operation that relies on that context to fail. if (override_context != nullptr) UpdateExecutionContext (override_context); if (!options.GetStopOnContinue()) { m_debugger.SetAsyncExecution (false); } for (size_t idx = 0; idx < num_lines; idx++) { const char *cmd = commands.GetStringAtIndex(idx); if (cmd[0] == '\0') continue; if (options.GetEchoCommands()) { result.AppendMessageWithFormat ("%s %s\n", m_debugger.GetPrompt(), cmd); } CommandReturnObject tmp_result; // If override_context is not NULL, pass no_context_switching = true for // HandleCommand() since we updated our context already. // We might call into a regex or alias command, in which case the add_to_history will get lost. This // m_command_source_depth dingus is the way we turn off adding to the history in that case, so set it up here. if (!options.GetAddToHistory()) m_command_source_depth++; bool success = HandleCommand(cmd, options.m_add_to_history, tmp_result, nullptr, /* override_context */ true, /* repeat_on_empty_command */ override_context != nullptr /* no_context_switching */); if (!options.GetAddToHistory()) m_command_source_depth--; if (options.GetPrintResults()) { if (tmp_result.Succeeded()) result.AppendMessageWithFormat("%s", tmp_result.GetOutputData()); } if (!success || !tmp_result.Succeeded()) { const char *error_msg = tmp_result.GetErrorData(); if (error_msg == nullptr || error_msg[0] == '\0') error_msg = "<unknown error>.\n"; if (options.GetStopOnError()) { result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' failed with %s", (uint64_t)idx, cmd, error_msg); result.SetStatus (eReturnStatusFailed); m_debugger.SetAsyncExecution (old_async_execution); return; } else if (options.GetPrintResults()) { result.AppendMessageWithFormat ("Command #%" PRIu64 " '%s' failed with %s", (uint64_t)idx + 1, cmd, error_msg); } } if (result.GetImmediateOutputStream()) result.GetImmediateOutputStream()->Flush(); if (result.GetImmediateErrorStream()) result.GetImmediateErrorStream()->Flush(); // N.B. Can't depend on DidChangeProcessState, because the state coming into the command execution // could be running (for instance in Breakpoint Commands. // So we check the return value to see if it is has running in it. if ((tmp_result.GetStatus() == eReturnStatusSuccessContinuingNoResult) || (tmp_result.GetStatus() == eReturnStatusSuccessContinuingResult)) { if (options.GetStopOnContinue()) { // If we caused the target to proceed, and we're going to stop in that case, set the // status in our real result before returning. This is an error if the continue was not the // last command in the set of commands to be run. if (idx != num_lines - 1) result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' continued the target.\n", (uint64_t)idx + 1, cmd); else result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' continued the target.\n", (uint64_t)idx + 1, cmd); result.SetStatus(tmp_result.GetStatus()); m_debugger.SetAsyncExecution (old_async_execution); return; } } // Also check for "stop on crash here: bool should_stop = false; if (tmp_result.GetDidChangeProcessState() && options.GetStopOnCrash()) { TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget()); if (target_sp) { ProcessSP process_sp (target_sp->GetProcessSP()); if (process_sp) { for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) { StopReason reason = thread_sp->GetStopReason(); if (reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation) { should_stop = true; break; } } } } if (should_stop) { if (idx != num_lines - 1) result.AppendErrorWithFormat("Aborting reading of commands after command #%" PRIu64 ": '%s' stopped with a signal or exception.\n", (uint64_t)idx + 1, cmd); else result.AppendMessageWithFormat("Command #%" PRIu64 " '%s' stopped with a signal or exception.\n", (uint64_t)idx + 1, cmd); result.SetStatus(tmp_result.GetStatus()); m_debugger.SetAsyncExecution (old_async_execution); return; } } } result.SetStatus (eReturnStatusSuccessFinishResult); m_debugger.SetAsyncExecution (old_async_execution); return; } // Make flags that we can pass into the IOHandler so our delegates can do the right thing enum { eHandleCommandFlagStopOnContinue = (1u << 0), eHandleCommandFlagStopOnError = (1u << 1), eHandleCommandFlagEchoCommand = (1u << 2), eHandleCommandFlagPrintResult = (1u << 3), eHandleCommandFlagStopOnCrash = (1u << 4) }; void CommandInterpreter::HandleCommandsFromFile (FileSpec &cmd_file, ExecutionContext *context, CommandInterpreterRunOptions &options, CommandReturnObject &result) { if (cmd_file.Exists()) { StreamFileSP input_file_sp (new StreamFile()); std::string cmd_file_path = cmd_file.GetPath(); Error error = input_file_sp->GetFile().Open(cmd_file_path.c_str(), File::eOpenOptionRead); if (error.Success()) { Debugger &debugger = GetDebugger(); uint32_t flags = 0; if (options.m_stop_on_continue == eLazyBoolCalculate) { if (m_command_source_flags.empty()) { // Stop on continue by default flags |= eHandleCommandFlagStopOnContinue; } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnContinue) { flags |= eHandleCommandFlagStopOnContinue; } } else if (options.m_stop_on_continue == eLazyBoolYes) { flags |= eHandleCommandFlagStopOnContinue; } if (options.m_stop_on_error == eLazyBoolCalculate) { if (m_command_source_flags.empty()) { if (GetStopCmdSourceOnError()) flags |= eHandleCommandFlagStopOnError; } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnError) { flags |= eHandleCommandFlagStopOnError; } } else if (options.m_stop_on_error == eLazyBoolYes) { flags |= eHandleCommandFlagStopOnError; } if (options.GetStopOnCrash()) { if (m_command_source_flags.empty()) { // Echo command by default flags |= eHandleCommandFlagStopOnCrash; } else if (m_command_source_flags.back() & eHandleCommandFlagStopOnCrash) { flags |= eHandleCommandFlagStopOnCrash; } } if (options.m_echo_commands == eLazyBoolCalculate) { if (m_command_source_flags.empty()) { // Echo command by default flags |= eHandleCommandFlagEchoCommand; } else if (m_command_source_flags.back() & eHandleCommandFlagEchoCommand) { flags |= eHandleCommandFlagEchoCommand; } } else if (options.m_echo_commands == eLazyBoolYes) { flags |= eHandleCommandFlagEchoCommand; } if (options.m_print_results == eLazyBoolCalculate) { if (m_command_source_flags.empty()) { // Print output by default flags |= eHandleCommandFlagPrintResult; } else if (m_command_source_flags.back() & eHandleCommandFlagPrintResult) { flags |= eHandleCommandFlagPrintResult; } } else if (options.m_print_results == eLazyBoolYes) { flags |= eHandleCommandFlagPrintResult; } if (flags & eHandleCommandFlagPrintResult) { debugger.GetOutputFile()->Printf("Executing commands in '%s'.\n", cmd_file_path.c_str()); } // Used for inheriting the right settings when "command source" might have // nested "command source" commands lldb::StreamFileSP empty_stream_sp; m_command_source_flags.push_back(flags); IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger, IOHandler::Type::CommandInterpreter, input_file_sp, empty_stream_sp, // Pass in an empty stream so we inherit the top input reader output stream empty_stream_sp, // Pass in an empty stream so we inherit the top input reader error stream flags, nullptr, // Pass in NULL for "editline_name" so no history is saved, or written debugger.GetPrompt(), NULL, false, // Not multi-line debugger.GetUseColor(), 0, *this)); const bool old_async_execution = debugger.GetAsyncExecution(); // Set synchronous execution if we are not stopping on continue if ((flags & eHandleCommandFlagStopOnContinue) == 0) debugger.SetAsyncExecution (false); m_command_source_depth++; debugger.RunIOHandler(io_handler_sp); if (!m_command_source_flags.empty()) m_command_source_flags.pop_back(); m_command_source_depth--; result.SetStatus (eReturnStatusSuccessFinishNoResult); debugger.SetAsyncExecution (old_async_execution); } else { result.AppendErrorWithFormat ("error: an error occurred read file '%s': %s\n", cmd_file_path.c_str(), error.AsCString()); result.SetStatus (eReturnStatusFailed); } } else { result.AppendErrorWithFormat ("Error reading commands from file %s - file not found.\n", cmd_file.GetFilename().AsCString("<Unknown>")); result.SetStatus (eReturnStatusFailed); return; } } ScriptInterpreter * CommandInterpreter::GetScriptInterpreter(bool can_create) { if (m_script_interpreter_sp) return m_script_interpreter_sp.get(); if (!can_create) return nullptr; lldb::ScriptLanguage script_lang = GetDebugger().GetScriptLanguage(); m_script_interpreter_sp = PluginManager::GetScriptInterpreterForLanguage(script_lang, *this); return m_script_interpreter_sp.get(); } bool CommandInterpreter::GetSynchronous () { return m_synchronous_execution; } void CommandInterpreter::SetSynchronous (bool value) { m_synchronous_execution = value; } void CommandInterpreter::OutputFormattedHelpText (Stream &strm, const char *prefix, const char *help_text) { const uint32_t max_columns = m_debugger.GetTerminalWidth(); if (prefix == NULL) prefix = ""; size_t prefix_width = strlen(prefix); size_t line_width_max = max_columns - prefix_width; const char *help_text_end = help_text + strlen(help_text); const char *line_start = help_text; if (line_width_max < 16) line_width_max = help_text_end - help_text + prefix_width; strm.IndentMore (prefix_width); while (line_start < help_text_end) { // Break each line at the first newline or last space/tab before // the maximum number of characters that fit on a line. Lines with no // natural break are left unbroken to wrap. const char *line_end = help_text_end; const char *line_scan = line_start; const char *line_scan_end = help_text_end; while (line_scan < line_scan_end) { char next = *line_scan; if (next == '\t' || next == ' ') { line_end = line_scan; line_scan_end = line_start + line_width_max; } else if (next == '\n' || next == '\0') { line_end = line_scan; break; } ++line_scan; } // Prefix the first line, indent subsequent lines to line up if (line_start == help_text) strm.Write (prefix, prefix_width); else strm.Indent(); strm.Write (line_start, line_end - line_start); strm.EOL(); // When a line breaks at whitespace consume it before continuing line_start = line_end; char next = *line_start; if (next == '\n') ++line_start; else while (next == ' ' || next == '\t') next = *(++line_start); } strm.IndentLess (prefix_width); } void CommandInterpreter::OutputFormattedHelpText (Stream &strm, const char *word_text, const char *separator, const char *help_text, size_t max_word_len) { StreamString prefix_stream; prefix_stream.Printf (" %-*s %s ", (int)max_word_len, word_text, separator); OutputFormattedHelpText (strm, prefix_stream.GetData(), help_text); } void CommandInterpreter::OutputHelpText (Stream &strm, const char *word_text, const char *separator, const char *help_text, uint32_t max_word_len) { int indent_size = max_word_len + strlen (separator) + 2; strm.IndentMore (indent_size); StreamString text_strm; text_strm.Printf ("%-*s %s %s", max_word_len, word_text, separator, help_text); const uint32_t max_columns = m_debugger.GetTerminalWidth(); size_t len = text_strm.GetSize(); const char *text = text_strm.GetData(); uint32_t chars_left = max_columns; for (uint32_t i = 0; i < len; i++) { if ((text[i] == ' ' && ::strchr((text+i+1), ' ') && chars_left < ::strchr((text+i+1), ' ')-(text+i)) || text[i] == '\n') { chars_left = max_columns - indent_size; strm.EOL(); strm.Indent(); } else { strm.PutChar(text[i]); chars_left--; } } strm.EOL(); strm.IndentLess(indent_size); } void CommandInterpreter::FindCommandsForApropos (const char *search_word, StringList &commands_found, StringList &commands_help, bool search_builtin_commands, bool search_user_commands) { CommandObject::CommandMap::const_iterator pos; if (search_builtin_commands) { for (pos = m_command_dict.begin(); pos != m_command_dict.end(); ++pos) { const char *command_name = pos->first.c_str(); CommandObject *cmd_obj = pos->second.get(); if (cmd_obj->HelpTextContainsWord (search_word)) { commands_found.AppendString (command_name); commands_help.AppendString (cmd_obj->GetHelp()); } if (cmd_obj->IsMultiwordObject()) cmd_obj->AproposAllSubCommands (command_name, search_word, commands_found, commands_help); } } if (search_user_commands) { for (pos = m_user_dict.begin(); pos != m_user_dict.end(); ++pos) { const char *command_name = pos->first.c_str(); CommandObject *cmd_obj = pos->second.get(); if (cmd_obj->HelpTextContainsWord (search_word)) { commands_found.AppendString (command_name); commands_help.AppendString (cmd_obj->GetHelp()); } if (cmd_obj->IsMultiwordObject()) cmd_obj->AproposAllSubCommands (command_name, search_word, commands_found, commands_help); } } } void CommandInterpreter::UpdateExecutionContext (ExecutionContext *override_context) { if (override_context != nullptr) { m_exe_ctx_ref = *override_context; } else { const bool adopt_selected = true; m_exe_ctx_ref.SetTargetPtr (m_debugger.GetSelectedTarget().get(), adopt_selected); } } size_t CommandInterpreter::GetProcessOutput () { // The process has stuff waiting for stderr; get it and write it out to the appropriate place. char stdio_buffer[1024]; size_t len; size_t total_bytes = 0; Error error; TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget()); if (target_sp) { ProcessSP process_sp (target_sp->GetProcessSP()); if (process_sp) { while ((len = process_sp->GetSTDOUT (stdio_buffer, sizeof (stdio_buffer), error)) > 0) { size_t bytes_written = len; m_debugger.GetOutputFile()->Write (stdio_buffer, bytes_written); total_bytes += len; } while ((len = process_sp->GetSTDERR (stdio_buffer, sizeof (stdio_buffer), error)) > 0) { size_t bytes_written = len; m_debugger.GetErrorFile()->Write (stdio_buffer, bytes_written); total_bytes += len; } } } return total_bytes; } void CommandInterpreter::IOHandlerInputComplete (IOHandler &io_handler, std::string &line) { const bool is_interactive = io_handler.GetIsInteractive(); if (is_interactive == false) { // When we are not interactive, don't execute blank lines. This will happen // sourcing a commands file. We don't want blank lines to repeat the previous // command and cause any errors to occur (like redefining an alias, get an error // and stop parsing the commands file). if (line.empty()) return; // When using a non-interactive file handle (like when sourcing commands from a file) // we need to echo the command out so we don't just see the command output and no // command... if (io_handler.GetFlags().Test(eHandleCommandFlagEchoCommand)) io_handler.GetOutputStreamFile()->Printf("%s%s\n", io_handler.GetPrompt(), line.c_str()); } lldb_private::CommandReturnObject result; HandleCommand(line.c_str(), eLazyBoolCalculate, result); // Now emit the command output text from the command we just executed if (io_handler.GetFlags().Test(eHandleCommandFlagPrintResult)) { // Display any STDOUT/STDERR _prior_ to emitting the command result text GetProcessOutput (); if (!result.GetImmediateOutputStream()) { const char *output = result.GetOutputData(); if (output && output[0]) io_handler.GetOutputStreamFile()->PutCString(output); } // Now emit the command error text from the command we just executed if (!result.GetImmediateErrorStream()) { const char *error = result.GetErrorData(); if (error && error[0]) io_handler.GetErrorStreamFile()->PutCString(error); } } switch (result.GetStatus()) { case eReturnStatusInvalid: case eReturnStatusSuccessFinishNoResult: case eReturnStatusSuccessFinishResult: case eReturnStatusStarted: break; case eReturnStatusSuccessContinuingNoResult: case eReturnStatusSuccessContinuingResult: if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnContinue)) io_handler.SetIsDone(true); break; case eReturnStatusFailed: m_num_errors++; if (io_handler.GetFlags().Test(eHandleCommandFlagStopOnError)) io_handler.SetIsDone(true); break; case eReturnStatusQuit: m_quit_requested = true; io_handler.SetIsDone(true); break; } // Finally, if we're going to stop on crash, check that here: if (!m_quit_requested && result.GetDidChangeProcessState() && io_handler.GetFlags().Test(eHandleCommandFlagStopOnCrash)) { bool should_stop = false; TargetSP target_sp (m_debugger.GetTargetList().GetSelectedTarget()); if (target_sp) { ProcessSP process_sp (target_sp->GetProcessSP()); if (process_sp) { for (ThreadSP thread_sp : process_sp->GetThreadList().Threads()) { StopReason reason = thread_sp->GetStopReason(); if ((reason == eStopReasonSignal || reason == eStopReasonException || reason == eStopReasonInstrumentation) && !result.GetAbnormalStopWasExpected()) { should_stop = true; break; } } } } if (should_stop) { io_handler.SetIsDone(true); m_stopped_for_crash = true; } } } bool CommandInterpreter::IOHandlerInterrupt (IOHandler &io_handler) { ExecutionContext exe_ctx (GetExecutionContext()); Process *process = exe_ctx.GetProcessPtr(); if (process) { StateType state = process->GetState(); if (StateIsRunningState(state)) { process->Halt(); return true; // Don't do any updating when we are running } } ScriptInterpreter *script_interpreter = GetScriptInterpreter (false); if (script_interpreter) { if (script_interpreter->Interrupt()) return true; } return false; } void CommandInterpreter::GetLLDBCommandsFromIOHandler (const char *prompt, IOHandlerDelegate &delegate, bool asynchronously, void *baton) { Debugger &debugger = GetDebugger(); IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger, IOHandler::Type::CommandList, "lldb", // Name of input reader for history prompt, // Prompt NULL, // Continuation prompt true, // Get multiple lines debugger.GetUseColor(), 0, // Don't show line numbers delegate)); // IOHandlerDelegate if (io_handler_sp) { io_handler_sp->SetUserData (baton); if (asynchronously) debugger.PushIOHandler(io_handler_sp); else debugger.RunIOHandler(io_handler_sp); } } void CommandInterpreter::GetPythonCommandsFromIOHandler (const char *prompt, IOHandlerDelegate &delegate, bool asynchronously, void *baton) { Debugger &debugger = GetDebugger(); IOHandlerSP io_handler_sp (new IOHandlerEditline (debugger, IOHandler::Type::PythonCode, "lldb-python", // Name of input reader for history prompt, // Prompt NULL, // Continuation prompt true, // Get multiple lines debugger.GetUseColor(), 0, // Don't show line numbers delegate)); // IOHandlerDelegate if (io_handler_sp) { io_handler_sp->SetUserData (baton); if (asynchronously) debugger.PushIOHandler(io_handler_sp); else debugger.RunIOHandler(io_handler_sp); } } bool CommandInterpreter::IsActive () { return m_debugger.IsTopIOHandler (m_command_io_handler_sp); } lldb::IOHandlerSP CommandInterpreter::GetIOHandler(bool force_create, CommandInterpreterRunOptions *options) { // Always re-create the IOHandlerEditline in case the input // changed. The old instance might have had a non-interactive // input and now it does or vice versa. if (force_create || !m_command_io_handler_sp) { // Always re-create the IOHandlerEditline in case the input // changed. The old instance might have had a non-interactive // input and now it does or vice versa. uint32_t flags = 0; if (options) { if (options->m_stop_on_continue == eLazyBoolYes) flags |= eHandleCommandFlagStopOnContinue; if (options->m_stop_on_error == eLazyBoolYes) flags |= eHandleCommandFlagStopOnError; if (options->m_stop_on_crash == eLazyBoolYes) flags |= eHandleCommandFlagStopOnCrash; if (options->m_echo_commands != eLazyBoolNo) flags |= eHandleCommandFlagEchoCommand; if (options->m_print_results != eLazyBoolNo) flags |= eHandleCommandFlagPrintResult; } else { flags = eHandleCommandFlagEchoCommand | eHandleCommandFlagPrintResult; } m_command_io_handler_sp.reset(new IOHandlerEditline (m_debugger, IOHandler::Type::CommandInterpreter, m_debugger.GetInputFile(), m_debugger.GetOutputFile(), m_debugger.GetErrorFile(), flags, "lldb", m_debugger.GetPrompt(), NULL, // Continuation prompt false, // Don't enable multiple line input, just single line commands m_debugger.GetUseColor(), 0, // Don't show line numbers *this)); } return m_command_io_handler_sp; } void CommandInterpreter::RunCommandInterpreter(bool auto_handle_events, bool spawn_thread, CommandInterpreterRunOptions &options) { // Always re-create the command interpreter when we run it in case // any file handles have changed. bool force_create = true; m_debugger.PushIOHandler(GetIOHandler(force_create, &options)); m_stopped_for_crash = false; if (auto_handle_events) m_debugger.StartEventHandlerThread(); if (spawn_thread) { m_debugger.StartIOHandlerThread(); } else { m_debugger.ExecuteIOHandlers(); if (auto_handle_events) m_debugger.StopEventHandlerThread(); } } CommandObject * CommandInterpreter::ResolveCommandImpl(std::string &command_line, CommandReturnObject &result) { std::string scratch_command(command_line); // working copy so we don't modify command_line unless we succeed CommandObject *cmd_obj = nullptr; StreamString revised_command_line; bool wants_raw_input = false; size_t actual_cmd_name_len = 0; std::string next_word; StringList matches; bool done = false; while (!done) { char quote_char = '\0'; std::string suffix; ExtractCommand(scratch_command, next_word, suffix, quote_char); if (cmd_obj == nullptr) { std::string full_name; if (GetAliasFullName(next_word.c_str(), full_name)) { std::string alias_result; cmd_obj = BuildAliasResult(full_name.c_str(), scratch_command, alias_result, result); revised_command_line.Printf("%s", alias_result.c_str()); if (cmd_obj) { wants_raw_input = cmd_obj->WantsRawCommandString(); actual_cmd_name_len = strlen(cmd_obj->GetCommandName()); } } else { cmd_obj = GetCommandObject(next_word.c_str(), &matches); if (cmd_obj) { actual_cmd_name_len += strlen(cmd_obj->GetCommandName()); revised_command_line.Printf("%s", cmd_obj->GetCommandName()); wants_raw_input = cmd_obj->WantsRawCommandString(); } else { revised_command_line.Printf ("%s", next_word.c_str()); } } } else { if (cmd_obj->IsMultiwordObject ()) { CommandObject *sub_cmd_obj = cmd_obj->GetSubcommandObject(next_word.c_str()); if (sub_cmd_obj) { // The subcommand's name includes the parent command's name, // so restart rather than append to the revised_command_line. actual_cmd_name_len = strlen(sub_cmd_obj->GetCommandName()) + 1; revised_command_line.Clear(); revised_command_line.Printf("%s", sub_cmd_obj->GetCommandName()); cmd_obj = sub_cmd_obj; wants_raw_input = cmd_obj->WantsRawCommandString(); } else { if (quote_char) revised_command_line.Printf(" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char); else revised_command_line.Printf(" %s%s", next_word.c_str(), suffix.c_str()); done = true; } } else { if (quote_char) revised_command_line.Printf(" %c%s%s%c", quote_char, next_word.c_str(), suffix.c_str(), quote_char); else revised_command_line.Printf(" %s%s", next_word.c_str(), suffix.c_str()); done = true; } } if (cmd_obj == nullptr) { const size_t num_matches = matches.GetSize(); if (matches.GetSize() > 1) { StreamString error_msg; error_msg.Printf("Ambiguous command '%s'. Possible matches:\n", next_word.c_str()); for (uint32_t i = 0; i < num_matches; ++i) { error_msg.Printf("\t%s\n", matches.GetStringAtIndex(i)); } result.AppendRawError(error_msg.GetString().c_str()); } else { // We didn't have only one match, otherwise we wouldn't get here. assert(num_matches == 0); result.AppendErrorWithFormat("'%s' is not a valid command.\n", next_word.c_str()); } result.SetStatus(eReturnStatusFailed); return nullptr; } if (cmd_obj->IsMultiwordObject()) { if (!suffix.empty()) { result.AppendErrorWithFormat("command '%s' did not recognize '%s%s%s' as valid (subcommand might be invalid).\n", cmd_obj->GetCommandName(), next_word.empty() ? "" : next_word.c_str(), next_word.empty() ? " -- " : " ", suffix.c_str()); result.SetStatus(eReturnStatusFailed); return nullptr; } } else { // If we found a normal command, we are done done = true; if (!suffix.empty()) { switch (suffix[0]) { case '/': // GDB format suffixes { Options *command_options = cmd_obj->GetOptions(); if (command_options && command_options->SupportsLongOption("gdb-format")) { std::string gdb_format_option("--gdb-format="); gdb_format_option += (suffix.c_str() + 1); bool inserted = false; std::string &cmd = revised_command_line.GetString(); size_t arg_terminator_idx = FindArgumentTerminator(cmd); if (arg_terminator_idx != std::string::npos) { // Insert the gdb format option before the "--" that terminates options gdb_format_option.append(1,' '); cmd.insert(arg_terminator_idx, gdb_format_option); inserted = true; } if (!inserted) revised_command_line.Printf(" %s", gdb_format_option.c_str()); if (wants_raw_input && FindArgumentTerminator(cmd) == std::string::npos) revised_command_line.PutCString(" --"); } else { result.AppendErrorWithFormat("the '%s' command doesn't support the --gdb-format option\n", cmd_obj->GetCommandName()); result.SetStatus(eReturnStatusFailed); return nullptr; } } break; default: result.AppendErrorWithFormat("unknown command shorthand suffix: '%s'\n", suffix.c_str()); result.SetStatus(eReturnStatusFailed); return nullptr; } } } if (scratch_command.empty()) done = true; } if (!scratch_command.empty()) revised_command_line.Printf(" %s", scratch_command.c_str()); if (cmd_obj != NULL) command_line = revised_command_line.GetData(); return cmd_obj; }
39.493235
256
0.542811
[ "object", "vector" ]
fd8973369a8a44592c43c76c602472e1e8225b0f
3,426
cpp
C++
Marlin-2.0.x/Marlin/src/HAL/SAMD51/eeprom_flash.cpp
tajchert/Ender-5-Marlin-
9a90eb58b8282ec28fb28922d4163ca8d0f7cccd
[ "MIT" ]
5
2020-05-17T21:16:41.000Z
2021-06-11T04:46:31.000Z
Marlin-2.0.x/Marlin/src/HAL/SAMD51/eeprom_flash.cpp
tajchert/Ender-5-Marlin-
9a90eb58b8282ec28fb28922d4163ca8d0f7cccd
[ "MIT" ]
1
2020-05-07T07:34:13.000Z
2020-09-12T09:09:44.000Z
Marlin/src/HAL/SAMD51/eeprom_flash.cpp
dwhitlockii/Marlin_corexy_SKR-Pro1.1_bltouch
1f8aa64218067a134250b8c1017826e8abf87296
[ "MIT" ]
null
null
null
/** * Marlin 3D Printer Firmware * * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * SAMD51 HAL developed by Giuliano Zaro (AKA GMagician) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #ifdef __SAMD51__ #include "../../inc/MarlinConfig.h" #if ENABLED(FLASH_EEPROM_EMULATION) #include "../shared/eeprom_api.h" #define NVMCTRL_CMD(c) do{ \ SYNC(!NVMCTRL->STATUS.bit.READY); \ NVMCTRL->INTFLAG.bit.DONE = true; \ NVMCTRL->CTRLB.reg = c | NVMCTRL_CTRLB_CMDEX_KEY; \ SYNC(NVMCTRL->INTFLAG.bit.DONE); \ }while(0) #define NVMCTRL_FLUSH() do{ \ if (NVMCTRL->SEESTAT.bit.LOAD) \ NVMCTRL_CMD(NVMCTRL_CTRLB_CMD_SEEFLUSH); \ }while(0) size_t PersistentStore::capacity() { const uint8_t psz = NVMCTRL->SEESTAT.bit.PSZ, sblk = NVMCTRL->SEESTAT.bit.SBLK; return (!psz && !sblk) ? 0 : (psz <= 2) ? (0x200 << psz) : (sblk == 1 || psz == 3) ? 4096 : (sblk == 2 || psz == 4) ? 8192 : (sblk <= 4 || psz == 5) ? 16384 : (sblk >= 9 && psz == 7) ? 65536 : 32768; } bool PersistentStore::access_start() { NVMCTRL->SEECFG.reg = NVMCTRL_SEECFG_WMODE_BUFFERED; // Buffered mode and segment reallocation active if (NVMCTRL->SEESTAT.bit.RLOCK) NVMCTRL_CMD(NVMCTRL_CTRLB_CMD_USEE); // Unlock E2P data write access return true; } bool PersistentStore::access_finish() { NVMCTRL_FLUSH(); if (!NVMCTRL->SEESTAT.bit.LOCK) NVMCTRL_CMD(NVMCTRL_CTRLB_CMD_LSEE); // Lock E2P data write access return true; } bool PersistentStore::write_data(int &pos, const uint8_t *value, size_t size, uint16_t *crc) { while (size--) { const uint8_t v = *value; SYNC(NVMCTRL->SEESTAT.bit.BUSY); if (NVMCTRL->INTFLAG.bit.SEESFULL) NVMCTRL_FLUSH(); // Next write will trigger a sector reallocation. I need to flush 'pagebuffer' ((volatile uint8_t *)SEEPROM_ADDR)[pos] = v; SYNC(!NVMCTRL->INTFLAG.bit.SEEWRC); crc16(crc, &v, 1); pos++; value++; } return false; } bool PersistentStore::read_data(int &pos, uint8_t* value, size_t size, uint16_t *crc, const bool writing/*=true*/) { while (size--) { SYNC(NVMCTRL->SEESTAT.bit.BUSY); uint8_t c = ((volatile uint8_t *)SEEPROM_ADDR)[pos]; if (writing) *value = c; crc16(crc, &c, 1); pos++; value++; } return false; } #endif // FLASH_EEPROM_EMULATION #endif // __SAMD51__
35.319588
116
0.585814
[ "3d" ]
fd8a81f95a59c6d8fadd034408264d90c852f651
24,264
cc
C++
src/kudu/fs/dir_manager.cc
rajesh-ibm-power/kudu
cb8f0138c345b5209899e95db8d5c63994d2c721
[ "Apache-2.0" ]
6
2020-05-12T02:18:48.000Z
2021-04-15T20:39:21.000Z
src/kudu/fs/dir_manager.cc
rajesh-ibm-power/kudu
cb8f0138c345b5209899e95db8d5c63994d2c721
[ "Apache-2.0" ]
16
2020-01-19T07:17:00.000Z
2020-06-10T09:43:55.000Z
src/kudu/fs/dir_manager.cc
rajesh-ibm-power/kudu
cb8f0138c345b5209899e95db8d5c63994d2c721
[ "Apache-2.0" ]
1
2020-03-13T09:59:08.000Z
2020-03-13T09:59:08.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "kudu/fs/dir_manager.h" #include <errno.h> #include <algorithm> #include <functional> #include <iterator> #include <memory> #include <ostream> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include <glog/logging.h> #include "kudu/fs/dir_util.h" #include "kudu/fs/fs.pb.h" #include "kudu/gutil/map-util.h" #include "kudu/gutil/port.h" #include "kudu/gutil/strings/join.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/util/env.h" #include "kudu/util/env_util.h" #include "kudu/util/oid_generator.h" #include "kudu/util/path_util.h" #include "kudu/util/pb_util.h" #include "kudu/util/random_util.h" #include "kudu/util/scoped_cleanup.h" #include "kudu/util/stopwatch.h" #include "kudu/util/threadpool.h" using std::set; using std::string; using std::unique_ptr; using std::unordered_map; using std::unordered_set; using std::vector; using strings::Substitute; namespace kudu { namespace { // Wrapper for env_util::DeleteTmpFilesRecursively that is suitable for parallel // execution on a data directory's thread pool (which requires the return value // be void). void DeleteTmpFilesRecursively(Env* env, const string& path) { WARN_NOT_OK(env_util::DeleteTmpFilesRecursively(env, path), "Error while deleting temp files"); } } // anonymous namespace namespace fs { Dir::Dir(Env* env, DirMetrics* metrics, FsType fs_type, string dir, unique_ptr<DirInstanceMetadataFile> metadata_file, unique_ptr<ThreadPool> pool) : env_(env), metrics_(metrics), fs_type_(fs_type), dir_(std::move(dir)), metadata_file_(std::move(metadata_file)), pool_(std::move(pool)), is_shutdown_(false), is_full_(false), available_bytes_(0) { } Dir::~Dir() { Shutdown(); } void Dir::Shutdown() { if (is_shutdown_) { return; } WaitOnClosures(); pool_->Shutdown(); is_shutdown_ = true; } void Dir::ExecClosure(const std::function<void()>& task) { Status s = pool_->Submit(task); if (!s.ok()) { WARN_NOT_OK( s, "Could not submit task to thread pool, running it synchronously"); task(); } } void Dir::WaitOnClosures() { pool_->Wait(); } Status Dir::RefreshAvailableSpace(RefreshMode mode) { switch (mode) { case RefreshMode::EXPIRED_ONLY: { std::lock_guard<simple_spinlock> l(lock_); DCHECK(last_space_check_.Initialized()); MonoTime expiry = last_space_check_ + MonoDelta::FromSeconds( available_space_cache_secs()); if (MonoTime::Now() < expiry) { break; } FALLTHROUGH_INTENDED; // Root was previously full, check again. } case RefreshMode::ALWAYS: { int64_t available_bytes_new; Status s = env_util::VerifySufficientDiskSpace( env_, dir_, 0, reserved_bytes(), &available_bytes_new); bool is_full_new; if (PREDICT_FALSE(s.IsIOError() && s.posix_code() == ENOSPC)) { LOG(WARNING) << Substitute( "Insufficient disk space under path $0: will retry after $1 seconds: $2", dir_, available_space_cache_secs(), s.ToString()); s = Status::OK(); is_full_new = true; } else { is_full_new = false; } RETURN_NOT_OK_PREPEND(s, "Could not refresh fullness"); // Catch other types of IOErrors, etc. { std::lock_guard<simple_spinlock> l(lock_); if (metrics_ && is_full_ != is_full_new) { metrics_->dirs_full->IncrementBy(is_full_new ? 1 : -1); } is_full_ = is_full_new; last_space_check_ = MonoTime::Now(); available_bytes_ = available_bytes_new; } break; } default: LOG(FATAL) << "Unknown check mode"; } return Status::OK(); } DirManagerOptions::DirManagerOptions(const string& dir_type) : dir_type(dir_type), read_only(false), update_instances(UpdateInstanceBehavior::UPDATE_AND_IGNORE_FAILURES) {} vector<string> DirManager::GetRootNames(const CanonicalizedRootsList& root_list) { vector<string> roots; std::transform(root_list.begin(), root_list.end(), std::back_inserter(roots), [&] (const CanonicalizedRootAndStatus& r) { return r.path; }); return roots; } vector<string> DirManager::GetRoots() const { return GetRootNames(canonicalized_fs_roots_); } vector<string> DirManager::GetDirs() const { return JoinPathSegmentsV(GetRoots(), dir_name()); } DirManager::DirManager(Env* env, unique_ptr<DirMetrics> dir_metrics, int num_threads_per_dir, const DirManagerOptions& opts, CanonicalizedRootsList canonicalized_data_roots) : env_(env), num_threads_per_dir_(num_threads_per_dir), opts_(opts), canonicalized_fs_roots_(std::move(canonicalized_data_roots)), metrics_(std::move(dir_metrics)), rng_(GetRandomSeed32()) { DCHECK_GT(canonicalized_fs_roots_.size(), 0); DCHECK(opts_.update_instances == UpdateInstanceBehavior::DONT_UPDATE || !opts_.read_only); DCHECK(!opts_.dir_type.empty()); } DirManager::~DirManager() { Shutdown(); } void DirManager::WaitOnClosures() { for (const auto& dir : dirs_) { dir->WaitOnClosures(); } } void DirManager::Shutdown() { // We may be waiting here for a while on outstanding closures. LOG_SLOW_EXECUTION(INFO, 1000, Substitute("waiting on $0 block manager thread pools", dirs_.size())) { for (const auto& dir : dirs_) { dir->Shutdown(); } } } Status DirManager::Create() { CHECK(!opts_.read_only); vector<string> all_uuids; for (const auto& r : canonicalized_fs_roots_) { RETURN_NOT_OK_PREPEND(r.status, "Could not create directory manager with disks failed"); } vector<unique_ptr<DirInstanceMetadataFile>> loaded_instances; bool has_existing_instances; RETURN_NOT_OK(LoadInstances(&loaded_instances, &has_existing_instances)); if (has_existing_instances) { return Status::AlreadyPresent("instance files already exist"); } // If none of the instances exist, we can assume this is a new deployment and // we should try creating some a new set of instance files. RETURN_NOT_OK_PREPEND(CreateNewDirectoriesAndUpdateInstances(std::move(loaded_instances)), "could not create new data directories"); return Status::OK(); } Status DirManager::CreateNewDirectoriesAndUpdateInstances( vector<unique_ptr<DirInstanceMetadataFile>> instances) { CHECK(!opts_.read_only); CHECK_NE(UpdateInstanceBehavior::DONT_UPDATE, opts_.update_instances); vector<string> created_dirs; vector<string> created_files; auto deleter = MakeScopedCleanup([&]() { // Delete files first so that the directories will be empty when deleted. for (const auto& f : created_files) { WARN_NOT_OK(env_->DeleteFile(f), "Could not delete file " + f); } // Delete directories in reverse order since parent directories will have // been added before child directories. for (auto it = created_dirs.rbegin(); it != created_dirs.rend(); it++) { WARN_NOT_OK(env_->DeleteDir(*it), "Could not delete dir " + *it); } }); // First, de-duplicate the instance UUIDs. If we have duplicates, something's // wrong. Maybe an operator manually duplicated some instance files. set<string> all_uuids; for (const auto& instance : instances) { InsertIfNotPresent(&all_uuids, instance->uuid()); } if (all_uuids.size() != instances.size()) { return Status::InvalidArgument( Substitute("instance files contain duplicate UUIDs: $0 directories provided, " "$1 unique UUIDs found ($2)", instances.size(), all_uuids.size(), JoinStrings(all_uuids, ", "))); } // Determine which instance files are healthy (and can thus be updated), and // which don't exist. Create any that don't exist. // // Note: we don't bother trying to create/update the instance if the file is // otherwise unhealthy. vector<unique_ptr<DirInstanceMetadataFile>> healthy_instances; for (auto& instance : instances) { if (instance->healthy()) { healthy_instances.emplace_back(std::move(instance)); continue; } if (instance->health_status().IsNotFound()) { bool created_dir = false; RETURN_NOT_OK(instance->Create(all_uuids, &created_dir)); if (created_dir) { created_dirs.emplace_back(instance->dir()); } created_files.emplace_back(instance->path()); } } // Go through the healthy instances and look for instances that don't have // the full complete set of instance UUIDs. vector<unique_ptr<DirInstanceMetadataFile>> instances_to_update; for (auto& instance : healthy_instances) { DCHECK(instance->healthy()); const auto& dir_set = instance->metadata()->dir_set(); set<string> instance_uuids; for (int i = 0; i < dir_set.all_uuids_size(); i++) { InsertIfNotPresent(&instance_uuids, dir_set.all_uuids(i)); } // If an instance file disagrees with the expected UUIDs, rewrite it. if (all_uuids != instance_uuids) { instances_to_update.emplace_back(std::move(instance)); } } // If any of the instance files need to be updated because they didn't match // the expected set of UUIDs, update them now. // Note: Having a consistent set of instance files isn't a correctness // requirement, but it can be useful for degbugging. if (!instances_to_update.empty()) { RETURN_NOT_OK(UpdateHealthyInstances(instances_to_update, all_uuids)); } // Ensure newly created directories are synchronized to disk. if (sync_dirs()) { WARN_NOT_OK(env_util::SyncAllParentDirs(env_, created_dirs, created_files), "could not sync newly created data directories"); } // Success: don't delete any files. deleter.cancel(); return Status::OK(); } Status DirManager::UpdateHealthyInstances( const vector<unique_ptr<DirInstanceMetadataFile>>& instances_to_update, const set<string>& new_all_uuids) { unordered_map<string, string> copies_to_restore; unordered_set<string> copies_to_delete; auto cleanup = MakeScopedCleanup([&] { for (const auto& f : copies_to_delete) { WARN_NOT_OK(env_->DeleteFile(f), Substitute("Could not delete file $0", f)); } for (const auto& copy_and_original : copies_to_restore) { const auto& copy_filename = copy_and_original.first; const auto& original_filename = copy_and_original.second; WARN_NOT_OK(env_->RenameFile(copy_filename, original_filename), Substitute("Could not restore file $0 from $1", original_filename, copy_filename)); } }); // Make a copy of every existing instance metadata file. This is done before // performing any updates, so that if there's a failure while copying, // there's no metadata to restore. // // We'll keep track of the copies so we can delete them on success, or use // them to restore on failure. WritableFileOptions opts; opts.sync_on_close = true; for (const auto& instance : instances_to_update) { if (!instance->healthy()) { continue; } const string& instance_filename = instance->path(); string copy_filename = instance_filename + kTmpInfix; Status s = env_util::CopyFile(env_, instance_filename, copy_filename, opts); if (PREDICT_FALSE(!s.ok())) { s = s.CloneAndPrepend("unable to backup existing instance file"); instance->SetInstanceFailed(s); LOG(WARNING) << s.ToString(); continue; } InsertOrDie(&copies_to_delete, copy_filename); } // Update the instance metadata files with the new set of UUIDs. for (const auto& instance : instances_to_update) { if (!instance->healthy()) { continue; } const string& instance_filename = instance->path(); string copy_filename = instance_filename + kTmpInfix; // Put together the PB and perform the update. DirInstanceMetadataPB new_pb = *instance->metadata(); new_pb.mutable_dir_set()->mutable_all_uuids()->Clear(); for (const auto& uuid : new_all_uuids) { new_pb.mutable_dir_set()->add_all_uuids(uuid); } // We're about to update the file; if we fail midway, we should try to // restore them from our backups if we can. InsertOrDie(&copies_to_restore, copy_filename, instance_filename); CHECK_EQ(1, copies_to_delete.erase(copy_filename)); Status s = pb_util::WritePBContainerToPath( env_, instance_filename, new_pb, pb_util::OVERWRITE, sync_dirs() ? pb_util::SYNC : pb_util::NO_SYNC); // We've failed to update for some reason, so restore our original file. // Since we're renaming our copy, we don't have to delete it. if (PREDICT_FALSE(!s.ok())) { s = s.CloneAndPrepend("unable to update instance file"); instance->SetInstanceFailed(s); LOG(WARNING) << Substitute("unable to overwrite existing instance file $0: $1", instance_filename, s.ToString()); } } // If we are not tolerating errors (e.g. we're running the update_dirs tool) // and we've hit an error, return now and clean up what we've changed. if (opts_.update_instances == UpdateInstanceBehavior::UPDATE_AND_ERROR_ON_FAILURE) { for (const auto& instance : instances_to_update) { RETURN_NOT_OK_PREPEND(instance->health_status(), "at least one instance file failed to update"); } } // Success; we only need to delete our copies. InsertKeysFromMap(copies_to_restore, &copies_to_delete); copies_to_restore.clear(); return Status::OK(); } Status DirManager::LoadInstances( vector<unique_ptr<DirInstanceMetadataFile>>* instance_files, bool* has_existing_instances) { LockMode lock_mode; if (!lock_dirs()) { lock_mode = LockMode::NONE; } else if (opts_.read_only) { lock_mode = LockMode::OPTIONAL; } else { lock_mode = LockMode::MANDATORY; } vector<string> missing_roots_tmp; vector<unique_ptr<DirInstanceMetadataFile>> loaded_instances; ObjectIdGenerator gen; for (int i = 0; i < canonicalized_fs_roots_.size(); i++) { const auto& root = canonicalized_fs_roots_[i]; string dir = JoinPathSegments(root.path, dir_name()); string instance_filename = JoinPathSegments(dir, instance_metadata_filename()); // Initialize the instance with a backup UUID. In case the load fails, this // will be the UUID for our instnace. string backup_uuid = gen.Next(); unique_ptr<DirInstanceMetadataFile> instance( new DirInstanceMetadataFile(env_, std::move(backup_uuid), opts_.dir_type, instance_filename)); if (PREDICT_FALSE(!root.status.ok())) { instance->SetInstanceFailed(root.status); } else { // This may return OK and mark 'instance' as unhealthy if the file could // not be loaded (e.g. not found, disk errors). RETURN_NOT_OK_PREPEND(instance->LoadFromDisk(), Substitute("could not load $0", instance_filename)); } // Try locking the instance. if (instance->healthy() && lock_mode != LockMode::NONE) { // This may return OK and mark 'instance' as unhealthy if the file could // not be locked due to non-locking issues (e.g. disk errors). Status s = instance->Lock(); if (!s.ok()) { if (lock_mode == LockMode::OPTIONAL) { LOG(WARNING) << s.ToString(); LOG(WARNING) << "Proceeding without lock"; } else { DCHECK(LockMode::MANDATORY == lock_mode); return s; } } } loaded_instances.emplace_back(std::move(instance)); } int num_healthy_instances = 0; for (const auto& instance : loaded_instances) { if (instance->healthy()) { num_healthy_instances++; } } if (has_existing_instances) { *has_existing_instances = num_healthy_instances > 0; } instance_files->swap(loaded_instances); return Status::OK(); } Status DirManager::PopulateDirectoryMaps(const vector<unique_ptr<Dir>>& dirs) { // Go through our instances and assign them each a UUID index. for (int idx = 0; idx < dirs.size(); idx++) { Dir* dir = dirs[idx].get(); InsertToMaps(dir->instance()->uuid(), idx, dir); } return Status::OK(); } void DirManager::InsertToMaps(const string& uuid, int idx, Dir* dir) { if (!dir->instance()->healthy()) { if (metrics_) { metrics_->dirs_failed->IncrementBy(1); } InsertOrDie(&failed_dirs_, idx); } InsertOrDie(&uuid_by_root_, DirName(dir->dir()), uuid); InsertOrDie(&uuid_by_idx_, idx, uuid); InsertOrDie(&idx_by_uuid_, uuid, idx); InsertOrDie(&dir_by_uuid_idx_, idx, dir); InsertOrDie(&uuid_idx_by_dir_, dir, idx); InsertOrDie(&tablets_by_uuid_idx_map_, idx, {}); } Status DirManager::Open() { if (canonicalized_fs_roots_.size() > max_dirs()) { return Status::InvalidArgument(Substitute("too many directories provided $0, max is $1", canonicalized_fs_roots_.size(), max_dirs())); } vector<unique_ptr<DirInstanceMetadataFile>> loaded_instances; // Load the instance files from disk. bool has_existing_instances; RETURN_NOT_OK_PREPEND(LoadInstances(&loaded_instances, &has_existing_instances), "failed to load instance files"); if (!has_existing_instances) { return Status::NotFound( "could not open directory manager, no healthy directories found"); } // Note: the file block manager should not be updated because its block // indexing algorithm depends on a fixed set of directories. if (!opts_.read_only && opts_.dir_type != "file" && opts_.update_instances != UpdateInstanceBehavior::DONT_UPDATE) { RETURN_NOT_OK_PREPEND( CreateNewDirectoriesAndUpdateInstances( std::move(loaded_instances)), "could not add new directories"); RETURN_NOT_OK_PREPEND(LoadInstances(&loaded_instances, &has_existing_instances), "failed to load instance files after updating"); if (!has_existing_instances) { return Status::IOError( "could not open directory manager, no healthy directories found"); } } // All instances are present and accounted for. Time to create the in-memory // directory structures. vector<unique_ptr<Dir>> dirs; for (int i = 0; i < loaded_instances.size(); i++) { auto& instance = loaded_instances[i]; const string dir = instance->dir(); // Figure out what filesystem the directory is on. FsType fs_type = FsType::OTHER; if (instance->healthy()) { bool result = false; Status fs_check = env_->IsOnExtFilesystem(dir, &result); if (fs_check.ok()) { if (result) { fs_type = FsType::EXT; } else { fs_check = env_->IsOnXfsFilesystem(dir, &result); if (fs_check.ok() && result) { fs_type = FsType::XFS; } } } // If we hit a disk error, consider the directory failed. if (PREDICT_FALSE(fs_check.IsDiskFailure())) { instance->SetInstanceFailed(fs_check.CloneAndPrepend("failed to check FS type")); } else { RETURN_NOT_OK(fs_check); } } // Create a per-dir thread pool. unique_ptr<ThreadPool> pool; RETURN_NOT_OK(ThreadPoolBuilder(Substitute("dir $0", i)) .set_max_threads(num_threads_per_dir_) .set_trace_metric_prefix("dirs") .Build(&pool)); unique_ptr<Dir> new_dir = CreateNewDir(env_, metrics_.get(), fs_type, dir, std::move(instance), std::move(pool)); dirs.emplace_back(std::move(new_dir)); } // Use the per-dir thread pools to delete temporary files in parallel. for (const auto& dir : dirs) { if (dir->instance()->healthy()) { auto* d = dir.get(); dir->ExecClosure([this, d]() { DeleteTmpFilesRecursively(this->env_, d->dir()); }); } } for (const auto& dir : dirs) { dir->WaitOnClosures(); } RETURN_NOT_OK(PopulateDirectoryMaps(dirs)); dirs_ = std::move(dirs); // From this point onwards, the in-memory maps are the source of truth about // the state of each dir. // Initialize the 'fullness' status of the directories. for (const auto& dd : dirs_) { int uuid_idx; CHECK(FindUuidIndexByDir(dd.get(), &uuid_idx)); if (ContainsKey(failed_dirs_, uuid_idx)) { continue; } Status refresh_status = dd->RefreshAvailableSpace(Dir::RefreshMode::ALWAYS); if (PREDICT_FALSE(!refresh_status.ok())) { if (refresh_status.IsDiskFailure()) { RETURN_NOT_OK(MarkDirFailed(uuid_idx, refresh_status.ToString())); continue; } return refresh_status; } } return Status::OK(); } Dir* DirManager::FindDirByUuidIndex(int uuid_idx) const { DCHECK_LT(uuid_idx, dirs_.size()); return FindPtrOrNull(dir_by_uuid_idx_, uuid_idx); } bool DirManager::FindUuidIndexByDir(Dir* dir, int* uuid_idx) const { return FindCopy(uuid_idx_by_dir_, dir, uuid_idx); } bool DirManager::FindUuidIndexByRoot(const string& root, int* uuid_idx) const { string uuid; if (FindUuidByRoot(root, &uuid)) { return FindUuidIndexByUuid(uuid, uuid_idx); } return false; } bool DirManager::FindUuidIndexByUuid(const string& uuid, int* uuid_idx) const { return FindCopy(idx_by_uuid_, uuid, uuid_idx); } bool DirManager::FindUuidByRoot(const string& root, string* uuid) const { return FindCopy(uuid_by_root_, root, uuid); } set<string> DirManager::FindTabletsByDirUuidIdx(int uuid_idx) const { DCHECK_LT(uuid_idx, dirs_.size()); shared_lock<rw_spinlock> lock(dir_group_lock_.get_lock()); const set<string>* tablet_set_ptr = FindOrNull(tablets_by_uuid_idx_map_, uuid_idx); if (tablet_set_ptr) { return *tablet_set_ptr; } return {}; } void DirManager::MarkDirFailedByUuid(const std::string& uuid) { int uuid_idx; CHECK(FindUuidIndexByUuid(uuid, &uuid_idx)); WARN_NOT_OK(MarkDirFailed(uuid_idx), "Failed to handle disk failure"); } Status DirManager::MarkDirFailed(int uuid_idx, const string& error_message) { DCHECK_LT(uuid_idx, dirs_.size()); std::lock_guard<percpu_rwlock> lock(dir_group_lock_); Dir* dir = FindDirByUuidIndex(uuid_idx); DCHECK(dir); if (InsertIfNotPresent(&failed_dirs_, uuid_idx)) { if (failed_dirs_.size() == dirs_.size()) { // TODO(awong): pass 'error_message' as a Status instead of an string so // we can avoid returning this artificial status. return Status::IOError(Substitute("All dirs have failed: ", error_message)); } if (metrics_) { metrics_->dirs_failed->IncrementBy(1); } string error_prefix = ""; if (!error_message.empty()) { error_prefix = Substitute("$0: ", error_message); } LOG(ERROR) << error_prefix << Substitute("Directory $0 marked as failed", dir->dir()); } return Status::OK(); } bool DirManager::IsDirFailed(int uuid_idx) const { DCHECK_LT(uuid_idx, dirs_.size()); shared_lock<rw_spinlock> lock(dir_group_lock_.get_lock()); return ContainsKey(failed_dirs_, uuid_idx); } bool DirManager::IsTabletInFailedDir(const string& tablet_id) const { const set<int> failed_dirs = GetFailedDirs(); for (int failed_dir : failed_dirs) { if (ContainsKey(FindTabletsByDirUuidIdx(failed_dir), tablet_id)) { return true; } } return false; } } // namespace fs } // namespace kudu
34.91223
100
0.679443
[ "vector", "transform" ]
fd9388126c75fa396e582c55536e2c9e755da69e
677
cpp
C++
410.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
8
2018-10-31T11:00:19.000Z
2020-07-31T05:25:06.000Z
410.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
null
null
null
410.cpp
zfang399/LeetCode-Problems
4cb25718a3d1361569f5ee6fde7b4a9a4fde2186
[ "MIT" ]
2
2018-05-31T11:29:22.000Z
2019-09-11T06:34:40.000Z
class Solution { public: int splitArray(vector<int>& nums, int m) { int n = nums.size(); vector<vector<int>> dp(m, vector<int>(n, 0)); dp[0][0] = nums[0]; for(int i = 1; i < n; i++){ dp[0][i] = dp[0][i - 1] + nums[i]; } for(int i = 1; i < m; i++){ for(int j = 0; j < n; j++){ int minij = 2147483647; for(int k = 0; k < j; k++){ int maxsub = max(dp[i - 1][k], dp[0][j] - dp[0][k]); minij = min(minij, maxsub); } dp[i][j] = minij; } } return dp[m - 1][n - 1]; } };
27.08
72
0.354505
[ "vector" ]
fd942adaec209f2bbd15a1b1eb46c1c42293390e
29,372
cpp
C++
aws-cpp-sdk-codeguru-reviewer/source/CodeGuruReviewerClient.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-codeguru-reviewer/source/CodeGuruReviewerClient.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-codeguru-reviewer/source/CodeGuruReviewerClient.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/core/utils/Outcome.h> #include <aws/core/auth/AWSAuthSigner.h> #include <aws/core/client/CoreErrors.h> #include <aws/core/client/RetryStrategy.h> #include <aws/core/http/HttpClient.h> #include <aws/core/http/HttpResponse.h> #include <aws/core/http/HttpClientFactory.h> #include <aws/core/auth/AWSCredentialsProviderChain.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <aws/core/utils/threading/Executor.h> #include <aws/core/utils/DNS.h> #include <aws/core/utils/logging/LogMacros.h> #include <aws/codeguru-reviewer/CodeGuruReviewerClient.h> #include <aws/codeguru-reviewer/CodeGuruReviewerEndpoint.h> #include <aws/codeguru-reviewer/CodeGuruReviewerErrorMarshaller.h> #include <aws/codeguru-reviewer/model/AssociateRepositoryRequest.h> #include <aws/codeguru-reviewer/model/CreateCodeReviewRequest.h> #include <aws/codeguru-reviewer/model/DescribeCodeReviewRequest.h> #include <aws/codeguru-reviewer/model/DescribeRecommendationFeedbackRequest.h> #include <aws/codeguru-reviewer/model/DescribeRepositoryAssociationRequest.h> #include <aws/codeguru-reviewer/model/DisassociateRepositoryRequest.h> #include <aws/codeguru-reviewer/model/ListCodeReviewsRequest.h> #include <aws/codeguru-reviewer/model/ListRecommendationFeedbackRequest.h> #include <aws/codeguru-reviewer/model/ListRecommendationsRequest.h> #include <aws/codeguru-reviewer/model/ListRepositoryAssociationsRequest.h> #include <aws/codeguru-reviewer/model/ListTagsForResourceRequest.h> #include <aws/codeguru-reviewer/model/PutRecommendationFeedbackRequest.h> #include <aws/codeguru-reviewer/model/TagResourceRequest.h> #include <aws/codeguru-reviewer/model/UntagResourceRequest.h> using namespace Aws; using namespace Aws::Auth; using namespace Aws::Client; using namespace Aws::CodeGuruReviewer; using namespace Aws::CodeGuruReviewer::Model; using namespace Aws::Http; using namespace Aws::Utils::Json; static const char* SERVICE_NAME = "codeguru-reviewer"; static const char* ALLOCATION_TAG = "CodeGuruReviewerClient"; CodeGuruReviewerClient::CodeGuruReviewerClient(const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<CodeGuruReviewerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } CodeGuruReviewerClient::CodeGuruReviewerClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials), SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<CodeGuruReviewerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } CodeGuruReviewerClient::CodeGuruReviewerClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider, const Client::ClientConfiguration& clientConfiguration) : BASECLASS(clientConfiguration, Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider, SERVICE_NAME, Aws::Region::ComputeSignerRegion(clientConfiguration.region)), Aws::MakeShared<CodeGuruReviewerErrorMarshaller>(ALLOCATION_TAG)), m_executor(clientConfiguration.executor) { init(clientConfiguration); } CodeGuruReviewerClient::~CodeGuruReviewerClient() { } void CodeGuruReviewerClient::init(const Client::ClientConfiguration& config) { SetServiceClientName("CodeGuru Reviewer"); m_configScheme = SchemeMapper::ToString(config.scheme); if (config.endpointOverride.empty()) { m_uri = m_configScheme + "://" + CodeGuruReviewerEndpoint::ForRegion(config.region, config.useDualStack); } else { OverrideEndpoint(config.endpointOverride); } } void CodeGuruReviewerClient::OverrideEndpoint(const Aws::String& endpoint) { if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0) { m_uri = endpoint; } else { m_uri = m_configScheme + "://" + endpoint; } } AssociateRepositoryOutcome CodeGuruReviewerClient::AssociateRepository(const AssociateRepositoryRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/associations"); return AssociateRepositoryOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } AssociateRepositoryOutcomeCallable CodeGuruReviewerClient::AssociateRepositoryCallable(const AssociateRepositoryRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< AssociateRepositoryOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->AssociateRepository(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::AssociateRepositoryAsync(const AssociateRepositoryRequest& request, const AssociateRepositoryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->AssociateRepositoryAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::AssociateRepositoryAsyncHelper(const AssociateRepositoryRequest& request, const AssociateRepositoryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, AssociateRepository(request), context); } CreateCodeReviewOutcome CodeGuruReviewerClient::CreateCodeReview(const CreateCodeReviewRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/codereviews"); return CreateCodeReviewOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } CreateCodeReviewOutcomeCallable CodeGuruReviewerClient::CreateCodeReviewCallable(const CreateCodeReviewRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< CreateCodeReviewOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateCodeReview(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::CreateCodeReviewAsync(const CreateCodeReviewRequest& request, const CreateCodeReviewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->CreateCodeReviewAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::CreateCodeReviewAsyncHelper(const CreateCodeReviewRequest& request, const CreateCodeReviewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, CreateCodeReview(request), context); } DescribeCodeReviewOutcome CodeGuruReviewerClient::DescribeCodeReview(const DescribeCodeReviewRequest& request) const { if (!request.CodeReviewArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("DescribeCodeReview", "Required field: CodeReviewArn, is not set"); return DescribeCodeReviewOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [CodeReviewArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/codereviews/"); uri.AddPathSegment(request.GetCodeReviewArn()); return DescribeCodeReviewOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } DescribeCodeReviewOutcomeCallable CodeGuruReviewerClient::DescribeCodeReviewCallable(const DescribeCodeReviewRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeCodeReviewOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeCodeReview(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::DescribeCodeReviewAsync(const DescribeCodeReviewRequest& request, const DescribeCodeReviewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeCodeReviewAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::DescribeCodeReviewAsyncHelper(const DescribeCodeReviewRequest& request, const DescribeCodeReviewResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeCodeReview(request), context); } DescribeRecommendationFeedbackOutcome CodeGuruReviewerClient::DescribeRecommendationFeedback(const DescribeRecommendationFeedbackRequest& request) const { if (!request.CodeReviewArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("DescribeRecommendationFeedback", "Required field: CodeReviewArn, is not set"); return DescribeRecommendationFeedbackOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [CodeReviewArn]", false)); } if (!request.RecommendationIdHasBeenSet()) { AWS_LOGSTREAM_ERROR("DescribeRecommendationFeedback", "Required field: RecommendationId, is not set"); return DescribeRecommendationFeedbackOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [RecommendationId]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/feedback/"); uri.AddPathSegment(request.GetCodeReviewArn()); return DescribeRecommendationFeedbackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } DescribeRecommendationFeedbackOutcomeCallable CodeGuruReviewerClient::DescribeRecommendationFeedbackCallable(const DescribeRecommendationFeedbackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeRecommendationFeedbackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeRecommendationFeedback(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::DescribeRecommendationFeedbackAsync(const DescribeRecommendationFeedbackRequest& request, const DescribeRecommendationFeedbackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeRecommendationFeedbackAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::DescribeRecommendationFeedbackAsyncHelper(const DescribeRecommendationFeedbackRequest& request, const DescribeRecommendationFeedbackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeRecommendationFeedback(request), context); } DescribeRepositoryAssociationOutcome CodeGuruReviewerClient::DescribeRepositoryAssociation(const DescribeRepositoryAssociationRequest& request) const { if (!request.AssociationArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("DescribeRepositoryAssociation", "Required field: AssociationArn, is not set"); return DescribeRepositoryAssociationOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AssociationArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/associations/"); uri.AddPathSegment(request.GetAssociationArn()); return DescribeRepositoryAssociationOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } DescribeRepositoryAssociationOutcomeCallable CodeGuruReviewerClient::DescribeRepositoryAssociationCallable(const DescribeRepositoryAssociationRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DescribeRepositoryAssociationOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeRepositoryAssociation(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::DescribeRepositoryAssociationAsync(const DescribeRepositoryAssociationRequest& request, const DescribeRepositoryAssociationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DescribeRepositoryAssociationAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::DescribeRepositoryAssociationAsyncHelper(const DescribeRepositoryAssociationRequest& request, const DescribeRepositoryAssociationResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DescribeRepositoryAssociation(request), context); } DisassociateRepositoryOutcome CodeGuruReviewerClient::DisassociateRepository(const DisassociateRepositoryRequest& request) const { if (!request.AssociationArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("DisassociateRepository", "Required field: AssociationArn, is not set"); return DisassociateRepositoryOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [AssociationArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/associations/"); uri.AddPathSegment(request.GetAssociationArn()); return DisassociateRepositoryOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER)); } DisassociateRepositoryOutcomeCallable CodeGuruReviewerClient::DisassociateRepositoryCallable(const DisassociateRepositoryRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< DisassociateRepositoryOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DisassociateRepository(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::DisassociateRepositoryAsync(const DisassociateRepositoryRequest& request, const DisassociateRepositoryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->DisassociateRepositoryAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::DisassociateRepositoryAsyncHelper(const DisassociateRepositoryRequest& request, const DisassociateRepositoryResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, DisassociateRepository(request), context); } ListCodeReviewsOutcome CodeGuruReviewerClient::ListCodeReviews(const ListCodeReviewsRequest& request) const { if (!request.TypeHasBeenSet()) { AWS_LOGSTREAM_ERROR("ListCodeReviews", "Required field: Type, is not set"); return ListCodeReviewsOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [Type]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/codereviews"); return ListCodeReviewsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListCodeReviewsOutcomeCallable CodeGuruReviewerClient::ListCodeReviewsCallable(const ListCodeReviewsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListCodeReviewsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListCodeReviews(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::ListCodeReviewsAsync(const ListCodeReviewsRequest& request, const ListCodeReviewsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListCodeReviewsAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::ListCodeReviewsAsyncHelper(const ListCodeReviewsRequest& request, const ListCodeReviewsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListCodeReviews(request), context); } ListRecommendationFeedbackOutcome CodeGuruReviewerClient::ListRecommendationFeedback(const ListRecommendationFeedbackRequest& request) const { if (!request.CodeReviewArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("ListRecommendationFeedback", "Required field: CodeReviewArn, is not set"); return ListRecommendationFeedbackOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [CodeReviewArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/feedback/"); uri.AddPathSegment(request.GetCodeReviewArn()); uri.AddPathSegments("/RecommendationFeedback"); return ListRecommendationFeedbackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListRecommendationFeedbackOutcomeCallable CodeGuruReviewerClient::ListRecommendationFeedbackCallable(const ListRecommendationFeedbackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListRecommendationFeedbackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListRecommendationFeedback(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::ListRecommendationFeedbackAsync(const ListRecommendationFeedbackRequest& request, const ListRecommendationFeedbackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListRecommendationFeedbackAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::ListRecommendationFeedbackAsyncHelper(const ListRecommendationFeedbackRequest& request, const ListRecommendationFeedbackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListRecommendationFeedback(request), context); } ListRecommendationsOutcome CodeGuruReviewerClient::ListRecommendations(const ListRecommendationsRequest& request) const { if (!request.CodeReviewArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("ListRecommendations", "Required field: CodeReviewArn, is not set"); return ListRecommendationsOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [CodeReviewArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/codereviews/"); uri.AddPathSegment(request.GetCodeReviewArn()); uri.AddPathSegments("/Recommendations"); return ListRecommendationsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListRecommendationsOutcomeCallable CodeGuruReviewerClient::ListRecommendationsCallable(const ListRecommendationsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListRecommendationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListRecommendations(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::ListRecommendationsAsync(const ListRecommendationsRequest& request, const ListRecommendationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListRecommendationsAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::ListRecommendationsAsyncHelper(const ListRecommendationsRequest& request, const ListRecommendationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListRecommendations(request), context); } ListRepositoryAssociationsOutcome CodeGuruReviewerClient::ListRepositoryAssociations(const ListRepositoryAssociationsRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/associations"); return ListRepositoryAssociationsOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListRepositoryAssociationsOutcomeCallable CodeGuruReviewerClient::ListRepositoryAssociationsCallable(const ListRepositoryAssociationsRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListRepositoryAssociationsOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListRepositoryAssociations(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::ListRepositoryAssociationsAsync(const ListRepositoryAssociationsRequest& request, const ListRepositoryAssociationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListRepositoryAssociationsAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::ListRepositoryAssociationsAsyncHelper(const ListRepositoryAssociationsRequest& request, const ListRepositoryAssociationsResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListRepositoryAssociations(request), context); } ListTagsForResourceOutcome CodeGuruReviewerClient::ListTagsForResource(const ListTagsForResourceRequest& request) const { if (!request.ResourceArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("ListTagsForResource", "Required field: ResourceArn, is not set"); return ListTagsForResourceOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ResourceArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/tags/"); uri.AddPathSegment(request.GetResourceArn()); return ListTagsForResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_GET, Aws::Auth::SIGV4_SIGNER)); } ListTagsForResourceOutcomeCallable CodeGuruReviewerClient::ListTagsForResourceCallable(const ListTagsForResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< ListTagsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTagsForResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::ListTagsForResourceAsync(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->ListTagsForResourceAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::ListTagsForResourceAsyncHelper(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, ListTagsForResource(request), context); } PutRecommendationFeedbackOutcome CodeGuruReviewerClient::PutRecommendationFeedback(const PutRecommendationFeedbackRequest& request) const { Aws::Http::URI uri = m_uri; uri.AddPathSegments("/feedback"); return PutRecommendationFeedbackOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_PUT, Aws::Auth::SIGV4_SIGNER)); } PutRecommendationFeedbackOutcomeCallable CodeGuruReviewerClient::PutRecommendationFeedbackCallable(const PutRecommendationFeedbackRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< PutRecommendationFeedbackOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->PutRecommendationFeedback(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::PutRecommendationFeedbackAsync(const PutRecommendationFeedbackRequest& request, const PutRecommendationFeedbackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->PutRecommendationFeedbackAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::PutRecommendationFeedbackAsyncHelper(const PutRecommendationFeedbackRequest& request, const PutRecommendationFeedbackResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, PutRecommendationFeedback(request), context); } TagResourceOutcome CodeGuruReviewerClient::TagResource(const TagResourceRequest& request) const { if (!request.ResourceArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("TagResource", "Required field: ResourceArn, is not set"); return TagResourceOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ResourceArn]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/tags/"); uri.AddPathSegment(request.GetResourceArn()); return TagResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER)); } TagResourceOutcomeCallable CodeGuruReviewerClient::TagResourceCallable(const TagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, TagResource(request), context); } UntagResourceOutcome CodeGuruReviewerClient::UntagResource(const UntagResourceRequest& request) const { if (!request.ResourceArnHasBeenSet()) { AWS_LOGSTREAM_ERROR("UntagResource", "Required field: ResourceArn, is not set"); return UntagResourceOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [ResourceArn]", false)); } if (!request.TagKeysHasBeenSet()) { AWS_LOGSTREAM_ERROR("UntagResource", "Required field: TagKeys, is not set"); return UntagResourceOutcome(Aws::Client::AWSError<CodeGuruReviewerErrors>(CodeGuruReviewerErrors::MISSING_PARAMETER, "MISSING_PARAMETER", "Missing required field [TagKeys]", false)); } Aws::Http::URI uri = m_uri; uri.AddPathSegments("/tags/"); uri.AddPathSegment(request.GetResourceArn()); return UntagResourceOutcome(MakeRequest(uri, request, Aws::Http::HttpMethod::HTTP_DELETE, Aws::Auth::SIGV4_SIGNER)); } UntagResourceOutcomeCallable CodeGuruReviewerClient::UntagResourceCallable(const UntagResourceRequest& request) const { auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } ); auto packagedFunction = [task]() { (*task)(); }; m_executor->Submit(packagedFunction); return task->get_future(); } void CodeGuruReviewerClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } ); } void CodeGuruReviewerClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const { handler(this, request, UntagResource(request), context); }
55.210526
271
0.803282
[ "model" ]
fd9614dfa0205a396e1429606434249976f4fb91
2,503
hpp
C++
generator/collector_interface.hpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
null
null
null
generator/collector_interface.hpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
1
2019-05-14T15:26:55.000Z
2019-05-16T11:00:33.000Z
generator/collector_interface.hpp
vmihaylenko/omim
00087f340e723fc611cbc82e0ae898b9053b620a
[ "Apache-2.0" ]
null
null
null
#pragma once #include "base/assert.hpp" #include <memory> #include <string> struct OsmElement; class RelationElement; namespace feature { class FeatureBuilder; } // namespace feature namespace base { class GeoObjectId; } // namespace base namespace feature { class MetalinesBuilder; } // namespace feature namespace routing { class CameraCollector; class RestrictionWriter; class RoadAccessWriter; } // namespace routing namespace generator { class CollectorAddresses; class CollectorCollection; class CollectorTag; class MaxspeedsCollector; class CityAreaCollector; namespace cache { class IntermediateDataReader; } // namespace cache namespace regions { class CollectorRegionInfo; } // namespace regions // Implementing this interface allows an object to collect data from RelationElement, // OsmElement and FeatureBuilder elements. class CollectorInterface { public: CollectorInterface(std::string const & filename = {}) : m_filename(filename) {} virtual ~CollectorInterface() = default; virtual std::shared_ptr<CollectorInterface> Clone(std::shared_ptr<cache::IntermediateDataReader> const & = {}) const = 0; virtual void Collect(OsmElement const &) {} virtual void CollectRelation(RelationElement const &) {} virtual void CollectFeature(feature::FeatureBuilder const &, OsmElement const &) {} virtual void Save() = 0; virtual void Merge(CollectorInterface const &) = 0; virtual void MergeInto(CityAreaCollector &) const { FailIfMethodUnsupported(); } virtual void MergeInto(routing::CameraCollector &) const { FailIfMethodUnsupported(); } virtual void MergeInto(routing::RestrictionWriter &) const { FailIfMethodUnsupported(); } virtual void MergeInto(routing::RoadAccessWriter &) const { FailIfMethodUnsupported(); } virtual void MergeInto(CollectorAddresses &) const { FailIfMethodUnsupported(); } virtual void MergeInto(CollectorTag &) const { FailIfMethodUnsupported(); } virtual void MergeInto(MaxspeedsCollector &) const { FailIfMethodUnsupported(); } virtual void MergeInto(feature::MetalinesBuilder &) const { FailIfMethodUnsupported(); } virtual void MergeInto(regions::CollectorRegionInfo &) const { FailIfMethodUnsupported(); } virtual void MergeInto(CollectorCollection &) const { FailIfMethodUnsupported(); } std::string const & GetFilename() const { return m_filename; } private: void FailIfMethodUnsupported() const { CHECK(false, ("This method is unsupported.")); } std::string m_filename; }; } // namespace generator
30.156627
93
0.770276
[ "object" ]
fd978b86ea614060a04e4101b7669fee7f5d79e0
32,795
cpp
C++
src/cpu/x64/jit_avx2_1x1_convolution.cpp
NomotoKazuhiro/oneDNN
18795301d6776bc1431ec808cba7bdf83d191bf8
[ "Apache-2.0" ]
13
2020-05-29T07:39:23.000Z
2021-11-22T14:01:28.000Z
src/cpu/x64/jit_avx2_1x1_convolution.cpp
NomotoKazuhiro/oneDNN
18795301d6776bc1431ec808cba7bdf83d191bf8
[ "Apache-2.0" ]
8
2020-09-04T02:05:19.000Z
2021-12-24T02:18:37.000Z
src/cpu/x64/jit_avx2_1x1_convolution.cpp
NomotoKazuhiro/oneDNN
18795301d6776bc1431ec808cba7bdf83d191bf8
[ "Apache-2.0" ]
24
2020-08-07T04:21:48.000Z
2021-12-09T02:03:35.000Z
/******************************************************************************* * Copyright 2016-2020 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "common/c_types_map.hpp" #include "common/dnnl_thread.hpp" #include "common/type_helpers.hpp" #include "common/utils.hpp" #include "cpu/x64/jit_generator.hpp" #include "cpu/x64/jit_avx2_1x1_convolution.hpp" namespace dnnl { namespace impl { namespace cpu { namespace x64 { using namespace dnnl::impl::status; using namespace dnnl::impl::memory_tracking::names; using namespace dnnl::impl::utils; #define data_blk_off(f, n, c, d, h, w) \ ((ndims == 3) ? (f).blk_off(n, c, w) \ : ((ndims == 4) ? (f).blk_off(n, c, h, w) \ : (f).blk_off(n, c, d, h, w))) /* convolution forward */ void jit_avx2_1x1_convolution_fwd_t::execute_forward( const exec_ctx_t &ctx) const { auto src = CTX_IN_MEM(const data_t *, DNNL_ARG_SRC); auto weights = CTX_IN_MEM(const data_t *, DNNL_ARG_WEIGHTS); auto bias = CTX_IN_MEM(const data_t *, DNNL_ARG_BIAS); auto dst = CTX_OUT_MEM(data_t *, DNNL_ARG_DST); auto weights_dw = CTX_IN_MEM( const data_t *, DNNL_ARG_ATTR_POST_OP_DW | DNNL_ARG_WEIGHTS); auto bias_dw = CTX_IN_MEM( const data_t *, DNNL_ARG_ATTR_POST_OP_DW | DNNL_ARG_BIAS); auto scratchpad = ctx.get_scratchpad_grantor(); const auto &jcp = kernel_->jcp; // TODO (Roma): remove this restriction assert(jcp.stride_w == 1 && jcp.stride_h == 1); if (pd()->wants_padded_bias()) { auto padded_bias = scratchpad.get<data_t>(key_conv_padded_bias); utils::array_copy(padded_bias, bias, jcp.oc_without_padding); utils::array_set(padded_bias + jcp.oc_without_padding, 0.f, jcp.oc - jcp.oc_without_padding); bias = padded_bias; } parallel(0, [&](const int ithr, const int nthr) { execute_forward_thr(ithr, nthr, src, weights, bias, weights_dw, bias_dw, dst, scratchpad); }); if (pd()->wants_zero_pad_dst()) ctx.memory(DNNL_ARG_DST)->zero_pad(ctx.stream()); } void jit_avx2_1x1_convolution_fwd_t::execute_forward_thr(const int ithr, const int nthr, const data_t *src, const data_t *weights, const data_t *bias, const data_t *weights_dw, const data_t *bias_dw, data_t *dst, const memory_tracking::grantor_t &scratchpad) const { const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const memory_desc_wrapper weights_d(pd()->weights_md(0)); const memory_desc_wrapper dw_weights_d( pd()->arg_md(DNNL_ARG_ATTR_POST_OP_DW | DNNL_ARG_WEIGHTS)); const memory_desc_wrapper dw_bias_d( pd()->arg_md(DNNL_ARG_ATTR_POST_OP_DW | DNNL_ARG_BIAS)); const auto &jcp = kernel_->jcp; auto rtus_space = pd()->rtus_.reduce_src_ ? scratchpad.get<data_t>(key_conv_rtus_space) : NULL; const int ndims = dst_d.ndims(); const int stride_d = (ndims == 5) ? pd()->desc()->strides[0] : 1; const int stride_h = (ndims == 3) ? 1 : pd()->desc()->strides[ndims - 4]; const int stride_w = pd()->desc()->strides[ndims - 3]; const int nb_oc = jcp.nb_load; const int nb_ic = jcp.nb_reduce; const int nb_ic_blocking = jcp.nb_reduce_blocking; auto p = jit_1x1_conv_call_s(); auto rp = rtus_driver_t<avx2>::call_params_t(); // override some constants for fused dw_conv const int os_block = jcp.with_dw_conv ? jcp.ow : jcp.bcast_block; const int nb_bcast = jcp.with_dw_conv ? jcp.oh : jcp.nb_bcast; const int nb_bcast_blocking = jcp.with_dw_conv ? 1 : jcp.nb_bcast_blocking; const int nb_bcast_blocking_max = jcp.with_dw_conv ? 1 : jcp.nb_bcast_blocking_max; const int nb_load_blocking = jcp.nb_load_blocking; const int nb_load_blocking_max = jcp.with_dw_conv ? jcp.nb_load_blocking : jcp.nb_load_blocking_max; // Begin: declare Variables needed for dw conv. data_t *pbuf; size_t row_offset; const int nb_buffer = jcp.nb_load_blocking; auto jcp_dw = pd()->jcp_dw_; std::vector<data_t *> addrs; void (*dw_jit_ker)(jit_conv_call_s *) = nullptr; auto step = [](int default_step, int remaining, int tail_step) { assert(default_step <= tail_step); return remaining < tail_step ? remaining : default_step; }; auto init_bcast = [&](int iwork, int bcast_end, int &n, int &g, int &bcast_step, int &od, int &oh, int &ow, int &id, int &ih, int &iw) { int osb {0}; nd_iterator_init(iwork, n, jcp.mb, g, jcp.ngroups, osb, nb_bcast); bcast_step = step( nb_bcast_blocking, nb_bcast - osb, nb_bcast_blocking_max); bcast_step = nstl::min(bcast_step, bcast_end - iwork); const int os = osb * os_block; const int os_2d = os % (jcp.oh * jcp.ow); od = os / (jcp.oh * jcp.ow); oh = os_2d / jcp.ow; ow = os_2d % jcp.ow; id = od * stride_d; ih = oh * stride_h; iw = ow * stride_w; rp.iw_start = iw; p.bcast_dim = this_block_size(os, jcp.os, bcast_step * os_block); rp.os = p.bcast_dim; }; auto init_load = [&](int ocb, int ocb_end, int &load_step) { load_step = step(nb_load_blocking, ocb_end - ocb, nb_load_blocking_max); p.load_dim = this_block_size( ocb * jcp.oc_block, jcp.oc, load_step * jcp.oc_block); }; auto ker_1x1 = [&](int ocb, int icb, int ocb_start, int n, int g, int od, int oh, int ow, int id, int ih, int iw) { const bool is_dst_layout_nxc = utils::one_of(jcp.dst_tag, format_tag::nwc, format_tag::nhwc, format_tag::ndhwc); const int oc_off_idx = is_dst_layout_nxc ? g * jcp.oc + ocb * jcp.oc_block : g * nb_oc + ocb; p.output_data = jcp.with_dw_conv ? pbuf + (oh % jcp_dw->kh) * row_offset : &dst[data_blk_off(dst_d, n, oc_off_idx, od, oh, ow)]; p.bias_data = &bias[oc_off_idx * (is_dst_layout_nxc ? 1 : jcp.oc_block)]; p.first_last_flag = 0 | (icb == 0 ? FLAG_REDUCE_FIRST : 0) | (icb + nb_ic_blocking >= nb_ic ? FLAG_REDUCE_LAST : 0); p.reduce_dim = this_block_size( icb * jcp.ic_block, jcp.ic, nb_ic_blocking * jcp.ic_block); rp.icb = p.reduce_dim; p.load_data = &weights[pd()->with_groups() ? weights_d.blk_off(g, ocb, icb) : weights_d.blk_off(ocb, icb)]; const bool is_src_layout_nxc = utils::one_of(jcp.src_tag, format_tag::nwc, format_tag::nhwc, format_tag::ndhwc); const int ic_off_idx = is_src_layout_nxc ? g * jcp.ic + icb * jcp.ic_block : g * nb_ic + icb; if (pd()->rtus_.reduce_src_) { rp.ws = rtus_space + ithr * pd()->rtus_.space_per_thread_ + (is_src_layout_nxc ? ic_off_idx : jcp.is * ic_off_idx * jcp.ic_block); if (ocb == ocb_start) { rp.src = src + data_blk_off(src_d, n, ic_off_idx, id, ih, iw); rtus_driver_->ker_(&rp); } p.bcast_data = rp.ws; } else p.bcast_data = src + data_blk_off(src_d, n, ic_off_idx, id, ih, iw); kernel_->jit_ker(&p); }; auto conv_1x1 = [&](int bcast_start, int bcast_end, int ocb_start, int ocb_end) { if (bcast_start >= bcast_end || ocb_start >= ocb_end) return; int iwork = bcast_start; while (iwork < bcast_end) { int n {0}, g {0}, bcast_step, od, oh, ow, id, ih, iw; init_bcast( iwork, bcast_end, n, g, bcast_step, od, oh, ow, id, ih, iw); int ocb = ocb_start; while (ocb < ocb_end) { int load_step; init_load(ocb, ocb_end, load_step); for (int icb = 0; icb < nb_ic; icb += nb_ic_blocking) { ker_1x1(ocb, icb, ocb_start, n, g, od, oh, ow, id, ih, iw); } ocb += load_step; } iwork += bcast_step; } }; auto ker_dw = [&](int n, int ocb_start, int load_step, int &dw_oh) { int oh_1x1 = nstl::max(dw_oh * jcp_dw->stride_h - jcp_dw->t_pad, 0); for (int i = 0; i < jcp_dw->kh; ++i) addrs[i] = pbuf + ((oh_1x1++) % jcp_dw->kh) * row_offset; const auto ocb_end = ocb_start + load_step; const auto wch_stride = jcp_dw->iw * jcp_dw->nb_ch_blocking * jcp_dw->ch_block; const int dil_h = jcp_dw->dilate_h + 1; const int str_h = jcp_dw->stride_h; const int ch_num = jcp_dw->nb_ch_blocking; const int ow = 0; const int kw = 0; for (int ch = ocb_start; ch < ocb_end; ch += jcp_dw->nb_ch_blocking) { const int i_t_overflow = nstl::max(0, (int)(jcp_dw->t_pad - dw_oh * str_h)); const int i_b_overflow = nstl::max(jcp_dw->ih, (int)(dw_oh * str_h + (jcp_dw->kh - 1) * dil_h - jcp_dw->t_pad + 1)) - jcp_dw->ih; const int kh = div_up(i_t_overflow, dil_h); const int kh_padding = jcp_dw->kh - div_up(i_t_overflow, dil_h) - div_up(i_b_overflow, dil_h); jit_conv_call_s par_conv_dw; par_conv_dw.src = addrs.data(); par_conv_dw.dst = &dst[dst_d.blk_off(n, ch, dw_oh, ow)]; par_conv_dw.filt = &weights_dw[dw_weights_d.blk_off(ch, 0, 0, kh, kw)]; if (bias) par_conv_dw.bias = &bias_dw[dw_bias_d.blk_off(ch * jcp_dw->ch_block)]; par_conv_dw.kh_padding = (size_t)nstl::max(0, kh_padding); par_conv_dw.ch_blocks = nstl::min(ch + ch_num, jcp_dw->nb_ch) - ch; dw_jit_ker(&par_conv_dw); for (int i = 0; i < jcp_dw->kh; ++i) addrs[i] += wch_stride; } }; auto conv_dw = [&]() { // Set variables memory_tracking::grantor_t dw_scratchpad( scratchpad, memory_tracking::names::prefix_fusion); auto dw_conv_buffer = dw_scratchpad.get<data_t>(key_fusion_inout_buffer); dw_jit_ker = kernel_dw_avx2 ? kernel_dw_avx2->jit_ker : kernel_dw_sse41->jit_ker; const auto dw_conv_buffer_size_ = (size_t)jcp_dw->kh * jcp.ow * nb_buffer * jcp.oc_block; pbuf = dw_conv_buffer + ithr * dw_conv_buffer_size_; row_offset = dw_conv_buffer_size_ / jcp_dw->kh; addrs.resize(jcp_dw->kh); int bcast_start {0}, bcast_end {0}, ocb_start {0}, ocb_end {0}; balance2D(nthr, ithr, jcp.mb * jcp.ngroups * jcp_dw->oh, bcast_start, bcast_end, nb_oc, ocb_start, ocb_end, 1); while (ocb_start < ocb_end) { int load_step; init_load(ocb_start, ocb_end, load_step); int oh_1x1 = 0; auto bcast_iter = bcast_start; while (bcast_iter < bcast_end) { int n, g, oh_dw; nd_iterator_init(bcast_iter, n, jcp.mb, g, jcp.ngroups, oh_dw, jcp_dw->oh); if (oh_dw == 0) oh_1x1 = 0; // Reset over mb boundary const int oh_1x1_range = oh_dw * jcp_dw->stride_h - jcp_dw->t_pad; const int oh_1x1_begin = nstl::max(oh_1x1_range, 0); const int oh_1x1_end = nstl::min(oh_1x1_range + jcp_dw->kh, jcp.oh); oh_1x1 = nstl::max( oh_1x1_begin, oh_1x1); // Skip rows computed previously // dw_spatial to 1x1 spatial conversion. if jcp.oh != jcp_dw->oh const int bcast_start_1x1 = n * jcp.ngroups * jcp.oh + g * jcp.oh + oh_1x1; const int bcast_end_1x1 = bcast_start_1x1 - oh_1x1 + oh_1x1_end; conv_1x1(bcast_start_1x1, bcast_end_1x1, ocb_start, ocb_start + load_step); oh_1x1 = oh_1x1_end; ker_dw(n, g * nb_oc + ocb_start, load_step, oh_dw); bcast_iter += nb_bcast_blocking; } ocb_start += load_step; } }; if (jcp.with_dw_conv) { conv_dw(); } else { int start {0}, end {0}; const int work_amount = jcp.mb * jcp.ngroups * jcp.nb_bcast; balance211(work_amount, nthr, ithr, start, end); conv_1x1(start, end, 0, jcp.nb_load); } } /* convolution backward wtr data */ void jit_avx2_1x1_convolution_bwd_data_t::execute_backward_data( const exec_ctx_t &ctx) const { auto diff_dst = CTX_IN_MEM(const data_t *, DNNL_ARG_DIFF_DST); auto weights = CTX_IN_MEM(const data_t *, DNNL_ARG_WEIGHTS); auto diff_src = CTX_OUT_MEM(data_t *, DNNL_ARG_DIFF_SRC); const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md()); const memory_desc_wrapper weights_d(pd()->weights_md(0)); const memory_desc_wrapper diff_src_d(pd()->diff_src_md()); const auto &jcp = kernel_->jcp; auto rtus_space = pd()->rtus_.reduce_src_ ? ctx.get_scratchpad_grantor().get<data_t>(key_conv_rtus_space) : NULL; // TODO (Roma): remove this restriction assert(jcp.stride_w == 1 && jcp.stride_h == 1 && jcp.stride_d == 1); const int ndims = diff_dst_d.ndims(); const int stride_d = (ndims == 5) ? pd()->desc()->strides[0] : 1; const int stride_h = (ndims == 3) ? 1 : pd()->desc()->strides[ndims - 4]; const int stride_w = pd()->desc()->strides[ndims - 3]; const int nb_ic = jcp.nb_load; const int nb_oc = jcp.nb_reduce; const int os_block = jcp.bcast_block; const int nb_oc_blocking = jcp.nb_reduce_blocking; const int work_amount = jcp.mb * jcp.ngroups * jcp.nb_bcast; auto step = [](int default_step, int remaining, int tail_step) { assert(default_step <= tail_step); return remaining < tail_step ? remaining : default_step; }; auto ker = [&](const int ithr, const int nthr) { auto p = jit_1x1_conv_call_s(); auto rp = rtus_driver_t<avx2>::call_params_t(); int start {0}, end {0}; balance211(work_amount, nthr, ithr, start, end); int load_step = 0; for (int icb = 0; icb < jcp.nb_load; icb += load_step) { load_step = step(jcp.nb_load_blocking, jcp.nb_load - icb, jcp.nb_load_blocking_max); p.load_dim = this_block_size( icb * jcp.ic_block, jcp.ic, load_step * jcp.ic_block); rp.icb = p.load_dim; int bcast_step; for (int iwork = start; iwork < end; iwork += bcast_step) { int n {0}, g {0}, osb {0}; nd_iterator_init( iwork, n, jcp.mb, g, jcp.ngroups, osb, jcp.nb_bcast); bcast_step = step(jcp.nb_bcast_blocking, jcp.nb_bcast - osb, jcp.nb_bcast_blocking_max); bcast_step = nstl::min(bcast_step, end - iwork); const int os = osb * os_block; p.bcast_dim = this_block_size(os, jcp.os, bcast_step * os_block); rp.os = p.bcast_dim; const int od = os / (jcp.oh * jcp.ow); const int os_2d = os % (jcp.oh * jcp.ow); const int oh = os_2d / jcp.ow; const int ow = os_2d % jcp.ow; const int id = od * stride_d; const int ih = oh * stride_h; const int iw = ow * stride_w; rp.iw_start = iw; const bool is_dsrc_layout_nxc = utils::one_of(jcp.src_tag, format_tag::nwc, format_tag::nhwc, format_tag::ndhwc); const int ic_off_idx = is_dsrc_layout_nxc ? g * jcp.ic + icb * jcp.ic_block : g * nb_ic + icb; rp.src = diff_src + data_blk_off(diff_src_d, n, ic_off_idx, id, ih, iw); if (pd()->rtus_.reduce_src_) { rp.ws = rtus_space + ithr * pd()->rtus_.space_per_thread_; p.output_data = rp.ws; } else p.output_data = rp.src; for (int ocb = 0; ocb < jcp.nb_reduce; ocb += jcp.nb_reduce_blocking) { const bool is_ddst_layout_nxc = utils::one_of(jcp.dst_tag, format_tag::nwc, format_tag::nhwc, format_tag::ndhwc); const int oc_off_idx = is_ddst_layout_nxc ? g * jcp.oc + ocb * jcp.oc_block : g * nb_oc + ocb; size_t diff_dst_off = data_blk_off( diff_dst_d, n, oc_off_idx, od, oh, ow); p.bcast_data = &diff_dst[diff_dst_off]; p.load_data = &weights[pd()->with_groups() ? weights_d.blk_off(g, ocb, icb) : weights_d.blk_off(ocb, icb)]; p.first_last_flag = ocb == 0 ? FLAG_REDUCE_FIRST : 0; p.reduce_dim = this_block_size(ocb * jcp.oc_block, jcp.oc, nb_oc_blocking * jcp.oc_block); kernel_->jit_ker(&p); } if (pd()->rtus_.reduce_src_) rtus_driver_->ker_(&rp); } } }; parallel(jcp.nthr, ker); } /* convolution backward wtr weights */ jit_avx2_1x1_convolution_bwd_weights_t::jit_avx2_1x1_convolution_bwd_weights_t( const pd_t *apd) : primitive_t(apd), kernel_(nullptr), rtus_driver_(nullptr) { kernel_ = new jit_avx2_1x1_conv_kernel_f32(pd()->jcp_, *pd()->attr()); reducer_weights_ = new cpu_reducer_2d_t<data_type::f32>(pd()->reducer_wei_conf_); reducer_bias_ = new cpu_reducer_t<data_type::f32>(pd()->reducer_bia_conf_); if (pd()->with_bias()) assert(reducer_weights_->balancer().nthr_ == reducer_bias_->balancer().nthr_); init_rtus_driver<avx2>(this); } void jit_avx2_1x1_convolution_bwd_weights_t::execute_backward_weights( const exec_ctx_t &ctx) const { auto diff_dst = CTX_IN_MEM(const data_t *, DNNL_ARG_DIFF_DST); auto src = CTX_IN_MEM(const data_t *, DNNL_ARG_SRC); auto diff_weights = CTX_OUT_MEM(data_t *, DNNL_ARG_DIFF_WEIGHTS); auto diff_bias_in = CTX_OUT_MEM(data_t *, DNNL_ARG_DIFF_BIAS); auto scratchpad = ctx.get_scratchpad_grantor(); const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md()); const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper diff_weights_d(pd()->diff_weights_md(0)); const memory_desc_wrapper diff_bias_d(pd()->diff_weights_md(1)); const auto &jcp = kernel_->jcp; auto rtus_space = pd()->rtus_.reduce_src_ ? scratchpad.get<data_t>(key_conv_rtus_space) : NULL; const bool is_bias_padded = pd()->with_bias() && (jcp.oc_without_padding % jcp.oc_block != 0); data_t *diff_bias = is_bias_padded ? scratchpad.get<data_t>(key_conv_padded_bias) : diff_bias_in; auto reducer_bia_scratchpad = memory_tracking::grantor_t(scratchpad, prefix_reducer_bia); auto rb = this->reducer_bias_; rb->init(reducer_bia_scratchpad); auto reducer_wei_scratchpad = memory_tracking::grantor_t(scratchpad, prefix_reducer_wei); auto rw = this->reducer_weights_; rw->init(reducer_wei_scratchpad); const int ndims = diff_dst_d.ndims(); // TODO (Roma): remove this restriction assert(jcp.stride_w == 1 && jcp.stride_h == 1); const int nb_ic = jcp.nb_bcast; const int nb_ic_blocking = jcp.nb_bcast_blocking; const int bcast_work = div_up(nb_ic, nb_ic_blocking); const int nb_oc = jcp.nb_load; const int nb_oc_blocking = jcp.nb_load_blocking; const int load_work = div_up(nb_oc, nb_oc_blocking); const int sp_dim = jcp.reduce_dim; const int mb_sp_work = jcp.mb * sp_dim; const int stride_d = (ndims == 5) ? pd()->desc()->strides[0] : 1; const int stride_h = (ndims == 3) ? 1 : pd()->desc()->strides[ndims - 4]; const int stride_w = pd()->desc()->strides[ndims - 3]; const bool is_src_layout_nxc = utils::one_of( jcp.src_tag, format_tag::nwc, format_tag::nhwc, format_tag::ndhwc); const bool is_ddst_layout_nxc = utils::one_of( jcp.dst_tag, format_tag::nwc, format_tag::nhwc, format_tag::ndhwc); auto step = [](int default_step, int remaining, int tail_step) { assert(default_step <= tail_step); return remaining < tail_step ? remaining : default_step; }; auto oc_ic_sp_loop = [=](int sp_start, int sp_end, bool first_image, data_t *store_to, size_t store_to_ld, const data_t *diff_dst, const data_t *src, int ithr) { auto p = jit_1x1_conv_call_s(); auto rp = rtus_driver_t<avx2>::call_params_t(); p.output_stride = store_to_ld * sizeof(float); int oc_b_step = 0; for (int oc_b = 0; oc_b < nb_oc_blocking; oc_b += oc_b_step) { oc_b_step = step(nb_oc_blocking, nb_oc_blocking - oc_b, jcp.nb_load_blocking_max); p.load_dim = this_block_size( oc_b * jcp.oc_block, jcp.oc, oc_b_step * jcp.oc_block); int ic_b_step = 0; for (int ic_b = 0; ic_b < nb_ic_blocking; ic_b += ic_b_step) { ic_b_step = step(nb_ic_blocking, nb_ic_blocking - ic_b, jcp.nb_bcast_blocking_max); p.bcast_dim = this_block_size( ic_b * jcp.ic_block, jcp.ic, ic_b_step * jcp.ic_block); rp.icb = p.bcast_dim; p.output_data = store_to + oc_b * store_to_ld + ic_b * jcp.ic_block * jcp.oc_block; /* spatial reduction */ int sp_step = 0; for (int sp = sp_start; sp < sp_end; sp += sp_step) { sp_step = step(jcp.nb_reduce_blocking, sp_end - sp, jcp.nb_reduce_blocking_max); p.reduce_dim = sp_step * jcp.reduce_block; rp.os = p.reduce_dim; p.first_last_flag = sp == sp_start && first_image ? FLAG_REDUCE_FIRST : 0; p.load_data = diff_dst + (oc_b * jcp.reduce_dim + sp) * (is_ddst_layout_nxc ? jcp.oc : jcp.oc_block); if (pd()->rtus_.reduce_src_) { const int od = sp / (jcp.oh * jcp.ow); const int sp_2d = sp % (jcp.oh * jcp.ow); const int oh = sp_2d / jcp.ow; const int ow = sp_2d % jcp.ow; const int id = od * stride_d; const int ih = oh * stride_h; const int iw = ow * stride_w; rp.iw_start = iw; rp.ws = rtus_space + ithr * pd()->rtus_.space_per_thread_ + (ic_b * jcp.is + sp) * jcp.ic_block; size_t src_offset = iw * src_d.blocking_desc().strides[ndims - 1]; if (ndims > 3) src_offset += ih * src_d.blocking_desc().strides[ndims - 2]; if (ndims == 5) src_offset += id * src_d.blocking_desc().strides[ndims - 3]; rp.src = src + src_offset; if (oc_b == 0) rtus_driver_->ker_(&rp); p.bcast_data = rp.ws; } else p.bcast_data = src + (ic_b * jcp.reduce_dim + sp) * (is_src_layout_nxc ? jcp.ic : jcp.ic_block); kernel_->jit_ker(&p); } } } }; auto ker = [&](const int ithr, const int nthr) { assert(nthr == rw->balancer().nthr_); const int w_njobs = rw->balancer().ithr_njobs(ithr); if (w_njobs == 0) return; /* setup: independent work (oc, ic) */ const int w_job_start = rw->balancer().ithr_job_off(ithr); int g {0}, load_i {0}, bcast_i {0}; nd_iterator_init(w_job_start, g, jcp.ngroups, load_i, load_work, bcast_i, bcast_work); /* setup: reduction work (mb, sp) */ int mb_sp_start {0}, mb_sp_end {0}; balance211(mb_sp_work, rw->balancer().nthr_per_group_, rw->balancer().id_in_group(ithr), mb_sp_start, mb_sp_end); int img_start {0}, sp_start {0}; nd_iterator_init(mb_sp_start, img_start, jcp.mb, sp_start, sp_dim); /* independent work */ for (int iwork = 0; iwork < w_njobs; ++iwork) { const int oc_b = nb_oc_blocking * load_i; const int ic_b = nb_ic_blocking * bcast_i; const int oc_off_idx = is_ddst_layout_nxc ? g * jcp.oc + oc_b * jcp.oc_block : g * nb_oc + oc_b; const int ic_off_idx = is_src_layout_nxc ? g * jcp.ic + ic_b * jcp.ic_block : g * nb_ic + ic_b; data_t *store_to; size_t store_to_ld; if (rw->balancer().nthr_per_group_ == 1) { const size_t off = pd()->with_groups() ? diff_weights_d.blk_off(g, oc_b, ic_b) : diff_weights_d.blk_off(oc_b, ic_b); store_to = &diff_weights[off]; store_to_ld = rnd_up(jcp.ic, jcp.ic_block) * jcp.oc_block; } else { const size_t off = (size_t)iwork * rw->balancer().job_size_; store_to = rw->get_local_ptr(ithr, reducer_wei_scratchpad) + off; store_to_ld = nb_ic_blocking * jcp.ic_block * jcp.oc_block; } /* reduction work */ int img = img_start; int sp = sp_start; int sp_step = 0; for (int mb_sp = mb_sp_start; mb_sp < mb_sp_end; mb_sp += sp_step) { sp_step = nstl::min(sp_dim - sp, mb_sp_end - mb_sp); const bool first_image = img == img_start; if (first_image && rw->balancer().nthr_per_group_ > 1) { // Zero-pad the scratchpad when nthr > 1 (since most threads // write to scratchpad) so that zero-padding is maintained // for the final output after reduction array_set(rw->get_local_ptr(ithr, reducer_wei_scratchpad) + iwork * rw->balancer().job_size_, 0, rw->balancer().job_size_); } oc_ic_sp_loop(sp, sp + sp_step, first_image, store_to, store_to_ld, &diff_dst[diff_dst_d.blk_off(img, oc_off_idx)], &src[src_d.blk_off(img, ic_off_idx)], ithr); sp = 0; img += 1; } nd_iterator_step( g, jcp.ngroups, load_i, load_work, bcast_i, bcast_work); } if (dnnl_thr_syncable()) rw->reduce(ithr, diff_weights, reducer_wei_scratchpad); }; auto ker_bias = [&](int ithr, int nthr) { assert(nthr == rb->balancer().nthr_); const int b_job_start = rb->balancer().ithr_job_off(ithr); const int b_njobs = rb->balancer().ithr_njobs(ithr); if (b_njobs == 0) return; /* reduction dimension */ int img_start {0}, img_end {0}; balance211(jcp.mb, rb->balancer().nthr_per_group_, rb->balancer().id_in_group(ithr), img_start, img_end); /* jobs */ int g_start {0}, ocb_start {0}; nd_iterator_init(b_job_start, g_start, jcp.ngroups, ocb_start, nb_oc); for (int img = img_start; img < img_end; ++img) { int g = g_start, ocb = ocb_start; for (int b_job_loc = 0; b_job_loc < b_njobs; ++b_job_loc) { const int oc_off_idx = is_ddst_layout_nxc ? g * jcp.oc + ocb * jcp.oc_block : g * nb_oc + ocb; const data_t *d_dst = &diff_dst[diff_dst_d.blk_off(img, oc_off_idx)]; data_t *d_bias = rb->get_local_ptr(ithr, diff_bias, reducer_bia_scratchpad) + b_job_loc * rb->balancer().job_size_; if (img == img_start) for (int o = 0; o < 8; ++o) d_bias[o] = 0.; const int spatial_shift = is_ddst_layout_nxc ? jcp.oc : jcp.oc_block; const int max_oc = this_block_size( ocb * jcp.oc_block, jcp.oc, jcp.oc_block); for (int hw = 0; hw < jcp.os; ++hw) { PRAGMA_OMP_SIMD() for (int o = 0; o < max_oc; ++o) d_bias[o] += d_dst[o]; d_dst += spatial_shift; } nd_iterator_step(g, jcp.ngroups, ocb, nb_oc); } } if (dnnl_thr_syncable()) rb->reduce(ithr, diff_bias, reducer_bia_scratchpad); }; if (dnnl_thr_syncable()) { assert(IMPLICATION(pd()->with_bias(), rw->balancer().nthr_ == rb->balancer().nthr_)); parallel(rw->balancer().nthr_, [&](const int ithr, const int nthr) { ker(ithr, nthr); if (pd()->with_bias()) ker_bias(ithr, nthr); }); } else { parallel(rw->balancer().nthr_, [&](int ithr, int nthr) { ker(ithr, nthr); }); parallel(rw->balancer().nthr_, [&](int ithr, int nthr) { assert(nthr == rw->balancer().nthr_); MAYBE_UNUSED(nthr); if (rw->balancer().ithr_njobs(ithr) == 0) return; rw->reduce_nolock(ithr, diff_weights, reducer_wei_scratchpad); }); if (pd()->with_bias()) { parallel(rb->balancer().nthr_, [&](int ithr, int nthr) { ker_bias(ithr, nthr); }); parallel(rb->balancer().nthr_, [&](int ithr, int nthr) { assert(nthr == rb->balancer().nthr_); MAYBE_UNUSED(nthr); if (rb->balancer().ithr_njobs(ithr) == 0) return; rb->reduce_nolock(ithr, diff_bias, reducer_bia_scratchpad); }); } } /* TODO: put this in ker_bias */ if (is_bias_padded) { assert(IMPLICATION(!is_ddst_layout_nxc, jcp.ngroups == 1)); const int padded_stride = utils::rnd_up(jcp.oc, jcp.oc_block); const int stride = jcp.oc_without_padding; for (int g = 0; g < jcp.ngroups; ++g) { utils::array_copy(diff_bias_in + g * stride, diff_bias + g * padded_stride, stride); } } } } // namespace x64 } // namespace cpu } // namespace impl } // namespace dnnl
40.688586
80
0.541515
[ "vector" ]
fd97c8a92557adf5916802829c69276440dd3d85
885
hpp
C++
src/utility/DFStyleCreator.hpp
timorl/neurohex
597be23c6b9109550d96c0eb925b20b6d9f0bea6
[ "MIT" ]
1
2015-08-28T08:09:17.000Z
2015-08-28T08:09:17.000Z
src/utility/DFStyleCreator.hpp
timorl/neurohex
597be23c6b9109550d96c0eb925b20b6d9f0bea6
[ "MIT" ]
null
null
null
src/utility/DFStyleCreator.hpp
timorl/neurohex
597be23c6b9109550d96c0eb925b20b6d9f0bea6
[ "MIT" ]
null
null
null
#ifndef UTILITY_DFSTYLECREATOR_HPP #define UTILITY_DFSTYLECREATOR_HPP #include<vector> #include<string> #include<sstream> #include<utility> namespace utility { /** * @brief A creator of Dwarf Fortress style data. */ class DFStyleCreator { public: /** * @brief Construct a creator for the given stream. * @param[in] outputStream The stream to which the created data will be send. */ DFStyleCreator( std::ostream & outputStream ) : outputStream(outputStream) {std::boolalpha(outputStream);} /** * @brief Starts a new token with the specified name. */ void startToken(const std::string & type); /** * @brief Adds another part of the token. */ template<class Data> void addToToken(const Data & data); /** * @brief Finishes the token. */ void endToken(); private: std::ostream & outputStream; }; } #endif
20.113636
109
0.667797
[ "vector" ]
fd98e760a0bdd80a0f1600d825a279b827546f13
6,867
cpp
C++
cs6366-computer-graphics/program3/program3/GLCamera.cpp
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
3
2017-03-17T15:15:11.000Z
2020-10-01T16:05:17.000Z
cs6366-computer-graphics/program3/program3/GLCamera.cpp
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
null
null
null
cs6366-computer-graphics/program3/program3/GLCamera.cpp
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
7
2016-02-07T22:56:26.000Z
2021-02-26T02:50:28.000Z
#include "GLCamera.h" using namespace std; GLCamera::GLCamera() { init(); } GLvoid GLCamera::init() { FOVY = 60.0; FOVX = 60.0; ASPECT_RATIO = 1.0; NEAR_CLIPPING_PLANE = 1.0; FAR_CLIPPING_PLANE = 10e4; DEFAULT_TRANSLATE_STEP = 0.0; DEFAULT_ROTATE_ANGLE = 0.0; memset( m_translateDelta, 0, 3*sizeof(GLfloat) ); memset( m_rotateDelta, 0, 3*sizeof(GLfloat) ); memset( m_projMatr, 0, 16*sizeof(GLfloat) ); memset( m_modelViewMatr, 0, 16*sizeof(GLfloat) ); memset( m_tempMatr, 0, 16*sizeof(GLfloat) ); memset( m_pos, 0, 4*sizeof(GLfloat) ); m_pos[3] = 1.0f; m_invertYLook = false; m_invertXLook = false; m_fovY = FOVY; m_fovX = FOVX; m_aspect = ASPECT_RATIO; m_zNear = NEAR_CLIPPING_PLANE; m_zFar = FAR_CLIPPING_PLANE; m_clipDelta = 0.05f; } GLCamera::~GLCamera() { } GLvoid GLCamera::translate( GLfloat x, GLfloat y, GLfloat z ) { glMatrixMode( GL_MODELVIEW ); glGetFloatv( GL_MODELVIEW_MATRIX, m_modelViewMatr ); glLoadIdentity(); glTranslatef( x, y, z ); glMultMatrixf( m_modelViewMatr ); glGetFloatv( GL_MODELVIEW_MATRIX, m_modelViewMatr ); } GLvoid GLCamera::translate( const vec3f& v ) { translate( v[0], v[1], v[2] ); } GLvoid GLCamera::translate( GLubyte axis, GLint dir ) { if ( axis == 'u' || axis == 'U' || axis == 'x' || axis == 'X' ) { translate( dir * m_translateDelta[0], 0.0, 0.0 ); } else if ( axis == 'v' || axis == 'V' || axis == 'y' || axis == 'Y' ) { translate( 0.0, dir * m_translateDelta[1], 0.0 ); } else if ( axis == 'n' || axis == 'N' || axis == 'z' || axis == 'Z' ) { translate( 0.0, 0.0, dir * m_translateDelta[2] ); } } GLvoid GLCamera::rotate( GLubyte axis, GLfloat theta ) { if ( axis == 'u' || axis == 'U' || axis == 'x' || axis == 'X' ) { rotateU( theta ); } else if ( axis == 'v' || axis == 'V' || axis == 'y' || axis == 'Y' ) { rotateV( theta ); } else if ( axis == 'n' || axis == 'N' || axis == 'z' || axis == 'Z' ) { rotateN( theta ); } } GLvoid GLCamera::rotate( const vec3f& v, GLfloat theta ) { /* NOT IN USE ATM */ } GLvoid GLCamera::rotate( GLubyte axis, GLint dir ) { if ( axis == 'u' || axis == 'U' || axis == 'x' || axis == 'X' ) { rotateU( dir * m_rotateDelta[0] ); } else if ( axis == 'v' || axis == 'V' || axis == 'y' || axis == 'Y' ) { rotateV( dir * m_rotateDelta[1] ); } else if ( axis == 'n' || axis == 'N' || axis == 'z' || axis == 'Z' ) { rotateN( dir * m_rotateDelta[2] ); } } GLvoid GLCamera::rotateU( GLfloat theta ) { glMatrixMode( GL_MODELVIEW ); glGetFloatv( GL_MODELVIEW_MATRIX, m_modelViewMatr ); glLoadIdentity(); glRotatef( theta, 1.0, 0.0, 0.0 ); glMultMatrixf( m_modelViewMatr ); glGetFloatv( GL_MODELVIEW_MATRIX, m_modelViewMatr ); } GLvoid GLCamera::rotateV( GLfloat theta ) { glMatrixMode( GL_MODELVIEW ); glGetFloatv( GL_MODELVIEW_MATRIX, m_modelViewMatr ); glLoadIdentity(); glRotatef( theta, 0.0, 1.0, 0.0 ); glMultMatrixf( m_modelViewMatr ); glGetFloatv( GL_MODELVIEW_MATRIX, m_modelViewMatr ); } GLvoid GLCamera::rotateN( GLfloat theta ) { glMatrixMode( GL_MODELVIEW ); glGetFloatv( GL_MODELVIEW_MATRIX, m_modelViewMatr ); glLoadIdentity(); glRotatef( theta, 0.0, 0.0, 1.0 ); glMultMatrixf( m_modelViewMatr ); glGetFloatv( GL_MODELVIEW_MATRIX, m_modelViewMatr ); } GLvoid GLCamera::moveClippingPlane( GLubyte plane, GLint dir ) { if ( plane == 'f' ) { m_zFar *= (1.0f + ((GLfloat)dir * m_clipDelta)); if ( m_zFar < m_zNear ) { m_zFar = m_zNear; } } if ( plane == 'n' ) { m_zNear *= (1.0f + ((GLfloat)dir * m_clipDelta)); if ( m_zNear > m_zFar ) { m_zNear = m_zFar; } } updatePerspective( m_aspect ); } GLvoid GLCamera::updatePerspective( GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar ) { m_aspect = aspect; glMatrixMode( GL_PROJECTION ); glLoadIdentity(); gluPerspective( fovy, m_aspect, zNear, zFar ); glGetFloatv( GL_PROJECTION_MATRIX, m_projMatr ); } GLvoid GLCamera::updatePerspective( GLfloat aspect) { updatePerspective( m_fovY, aspect, m_zNear, m_zFar ); } GLvoid GLCamera::centerOn( const Model& m, GLint width, GLint height ) { // Update model view matrix to be equivalent to lookAt GLfloat modelHeight = (m.m_box[4] - m.m_box[1]); GLfloat modelWidth = (m.m_box[3] - m.m_box[0]); GLfloat ez; if ( modelWidth <= modelHeight ) { ez = m.m_center[2] + modelHeight/(GLfloat)tan((FOVY/2.0)*conv::DegToRad); } else { ez = m.m_center[2] + modelWidth/(GLfloat)tan((FOVY/2.0)*conv::DegToRad); } // Update modelview matrix lookAt( m.m_center[0], m.m_center[1], ez, m.m_center[0], m.m_center[1], m.m_center[2], 0, 1, 0 ); // Update clipping planes to fit model m_zNear = NEAR_CLIPPING_PLANE; m_zFar = ez + fun::dist(m.m_center[0], m.m_center[1], ez, m.m_center[0], m.m_center[1], m.m_box[5] - m.m_box[2] ) + 10.0f; // Update perspective matrix updatePerspective( (GLfloat)width / (GLfloat)height ); // Update deltas for proper translation/rotation control calcTranslateDelta( m ); calcRotateDelta( m ); } GLvoid GLCamera::lookAt( GLfloat ex, GLfloat ey, GLfloat ez, GLfloat cx, GLfloat cy, GLfloat cz, GLfloat ux, GLfloat uy, GLfloat uz ) { glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); gluLookAt( ex, ey, ez, cx, cy, cz, ux, uy, uz ); glGetFloatv( GL_MODELVIEW_MATRIX, m_projMatr ); } GLvoid GLCamera::print() { cout << "GLCamera:" << endl; cout << " fovy = " << m_fovY << endl; cout << " aspect = " << m_aspect << endl; cout << " near, far = " << m_zNear << " " << m_zFar << endl; cout << " modelview = " << endl; cout << " [" << m_modelViewMatr[0] << " " << m_modelViewMatr[4] << " " << m_modelViewMatr[8] << " " << m_modelViewMatr[12] << "]" << endl; cout << " [" << m_modelViewMatr[1] << " " << m_modelViewMatr[5] << " " << m_modelViewMatr[9] << " " << m_modelViewMatr[13] << "]" << endl; cout << " [" << m_modelViewMatr[2] << " " << m_modelViewMatr[6] << " " << m_modelViewMatr[10] << " " << m_modelViewMatr[14] << "]" << endl; cout << " [" << m_modelViewMatr[3] << " " << m_modelViewMatr[7] << " " << m_modelViewMatr[11] << " " << m_modelViewMatr[15] << "]" << endl; cout << " projection = " << endl; cout << " [" << m_projMatr[0] << " " << m_projMatr[4] << " " << m_projMatr[8] << " " << m_projMatr[12] << "]" << endl; cout << " [" << m_projMatr[1] << " " << m_projMatr[5] << " " << m_projMatr[9] << " " << m_projMatr[13] << "]" << endl; cout << " [" << m_projMatr[2] << " " << m_projMatr[6] << " " << m_projMatr[10] << " " << m_projMatr[14] << "]" << endl; cout << " [" << m_projMatr[3] << " " << m_projMatr[7] << " " << m_projMatr[11] << " " << m_projMatr[15] << "]" << endl; }
33.497561
144
0.591816
[ "model" ]
fd990159029b51b5783a31535120ceccab18d494
79,544
cpp
C++
src/slg/engines/pathoclbase/compiletextures.cpp
TeVexo/LuxCore
95d85566d9adc87fa4ea367cd7530f0a25e64d1d
[ "Apache-2.0" ]
null
null
null
src/slg/engines/pathoclbase/compiletextures.cpp
TeVexo/LuxCore
95d85566d9adc87fa4ea367cd7530f0a25e64d1d
[ "Apache-2.0" ]
null
null
null
src/slg/engines/pathoclbase/compiletextures.cpp
TeVexo/LuxCore
95d85566d9adc87fa4ea367cd7530f0a25e64d1d
[ "Apache-2.0" ]
null
null
null
/*************************************************************************** * Copyright 1998-2018 by authors (see AUTHORS.txt) * * * * This file is part of LuxCoreRender. * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* * See the License for the specific language governing permissions and * * limitations under the License. * ***************************************************************************/ #if !defined(LUXRAYS_DISABLE_OPENCL) #include <iosfwd> #include <limits> #include <boost/lexical_cast.hpp> #include <boost/algorithm/string.hpp> #include "slg/engines/pathoclbase/compiledscene.h" #include "slg/kernels/kernels.h" #include "slg/textures/band.h" #include "slg/textures/bilerp.h" #include "slg/textures/blackbody.h" #include "slg/textures/blender_texture.h" #include "slg/textures/brick.h" #include "slg/textures/checkerboard.h" #include "slg/textures/colordepth.h" #include "slg/textures/constfloat.h" #include "slg/textures/constfloat3.h" #include "slg/textures/cloud.h" #include "slg/textures/densitygrid.h" #include "slg/textures/dots.h" #include "slg/textures/fbm.h" #include "slg/textures/fresnelapprox.h" #include "slg/textures/fresnel/fresnelcolor.h" #include "slg/textures/fresnel/fresnelconst.h" #include "slg/textures/fresnel/fresnelluxpop.h" #include "slg/textures/fresnel/fresnelpreset.h" #include "slg/textures/fresnel/fresnelsopra.h" #include "slg/textures/fresnel/fresneltexture.h" #include "slg/textures/hitpoint/hitpointcolor.h" #include "slg/textures/hitpoint/position.h" #include "slg/textures/hitpoint/shadingnormal.h" #include "slg/textures/hsv.h" #include "slg/textures/imagemaptex.h" #include "slg/textures/irregulardata.h" #include "slg/textures/lampspectrum.h" #include "slg/textures/marble.h" #include "slg/textures/math/abs.h" #include "slg/textures/math/add.h" #include "slg/textures/math/clamp.h" #include "slg/textures/math/divide.h" #include "slg/textures/math/greaterthan.h" #include "slg/textures/math/lessthan.h" #include "slg/textures/math/mix.h" #include "slg/textures/math/power.h" #include "slg/textures/math/remap.h" #include "slg/textures/math/scale.h" #include "slg/textures/math/subtract.h" #include "slg/textures/normalmap.h" #include "slg/textures/object_id.h" #include "slg/textures/windy.h" #include "slg/textures/wrinkled.h" #include "slg/textures/uv.h" #include "slg/textures/vectormath/dotproduct.h" #include "slg/textures/vectormath/makefloat3.h" #include "slg/textures/vectormath/splitfloat3.h" using namespace std; using namespace luxrays; using namespace slg; using namespace slg::blender; void CompiledScene::CompileTextureMapping2D(slg::ocl::TextureMapping2D *mapping, const TextureMapping2D *m) { switch (m->GetType()) { case UVMAPPING2D: { mapping->type = slg::ocl::UVMAPPING2D; const UVMapping2D *uvm = static_cast<const UVMapping2D *>(m); mapping->uvMapping2D.sinTheta = uvm->sinTheta; mapping->uvMapping2D.cosTheta = uvm->cosTheta; mapping->uvMapping2D.uScale = uvm->uScale; mapping->uvMapping2D.vScale = uvm->vScale; mapping->uvMapping2D.uDelta = uvm->uDelta; mapping->uvMapping2D.vDelta = uvm->vDelta; break; } default: throw runtime_error("Unknown 2D texture mapping in CompiledScene::CompileTextureMapping2D: " + boost::lexical_cast<string>(m->GetType())); } } void CompiledScene::CompileTextureMapping3D(slg::ocl::TextureMapping3D *mapping, const TextureMapping3D *m) { switch (m->GetType()) { case UVMAPPING3D: { mapping->type = slg::ocl::UVMAPPING3D; const UVMapping3D *uvm = static_cast<const UVMapping3D *>(m); memcpy(&mapping->worldToLocal.m, &uvm->worldToLocal.m, sizeof(float[4][4])); memcpy(&mapping->worldToLocal.mInv, &uvm->worldToLocal.mInv, sizeof(float[4][4])); break; } case GLOBALMAPPING3D: { mapping->type = slg::ocl::GLOBALMAPPING3D; const GlobalMapping3D *gm = static_cast<const GlobalMapping3D *>(m); memcpy(&mapping->worldToLocal.m, &gm->worldToLocal.m, sizeof(float[4][4])); memcpy(&mapping->worldToLocal.mInv, &gm->worldToLocal.mInv, sizeof(float[4][4])); break; } case LOCALMAPPING3D: { mapping->type = slg::ocl::LOCALMAPPING3D; const LocalMapping3D *gm = static_cast<const LocalMapping3D *>(m); memcpy(&mapping->worldToLocal.m, &gm->worldToLocal.m, sizeof(float[4][4])); memcpy(&mapping->worldToLocal.mInv, &gm->worldToLocal.mInv, sizeof(float[4][4])); break; } default: throw runtime_error("Unknown 3D texture mapping in CompiledScene::CompileTextureMapping3D: " + boost::lexical_cast<string>(m->GetType())); } } float *CompiledScene::CompileDistribution1D(const Distribution1D *dist, u_int *size) { const u_int count = dist->GetCount(); // Here, I assume sizeof(u_int) = sizeof(float) *size = sizeof(u_int) + count * sizeof(float) + (count + 1) * sizeof(float); // Size is expressed in bytes while I'm working with float float *compDist = new float[*size / sizeof(float)]; *((u_int *)&compDist[0]) = count; copy(dist->GetFuncs(), dist->GetFuncs() + count, compDist + 1); copy(dist->GetCDFs(), dist->GetCDFs() + count + 1, compDist + 1 + count); return compDist; } float *CompiledScene::CompileDistribution2D(const Distribution2D *dist, u_int *size) { u_int marginalSize; float *marginalDist = CompileDistribution1D(dist->GetMarginalDistribution(), &marginalSize); u_int condSize; vector<float *> condDists; for (u_int i = 0; i < dist->GetHeight(); ++i) { condDists.push_back(CompileDistribution1D(dist->GetConditionalDistribution(i), &condSize)); } // Here, I assume sizeof(u_int) = sizeof(float) *size = 2 * sizeof(u_int) + marginalSize + condDists.size() * condSize; // Size is expressed in bytes while I'm working with float float *compDist = new float[*size / sizeof(float)]; *((u_int *)&compDist[0]) = dist->GetWidth(); *((u_int *)&compDist[1]) = dist->GetHeight(); float *ptr = &compDist[2]; const u_int marginalSize4 = marginalSize / sizeof(float); copy(marginalDist, marginalDist + marginalSize4, ptr); ptr += marginalSize4; delete[] marginalDist; const u_int condSize4 = condSize / sizeof(float); for (u_int i = 0; i < dist->GetHeight(); ++i) { copy(condDists[i], condDists[i] + condSize4, ptr); ptr += condSize4; delete[] condDists[i]; } return compDist; } void CompiledScene::CompileTextures() { wasMaterialsCompiled = true; const u_int texturesCount = scene->texDefs.GetSize(); SLG_LOG("Compile " << texturesCount << " Textures"); //SLG_LOG(" Texture size: " << sizeof(slg::ocl::Texture)); //-------------------------------------------------------------------------- // Translate textures //-------------------------------------------------------------------------- const double tStart = WallClockTime(); usedTextureTypes.clear(); // The following textures source code are statically defined and always included usedTextureTypes.insert(CONST_FLOAT); usedTextureTypes.insert(CONST_FLOAT3); usedTextureTypes.insert(IMAGEMAP); usedTextureTypes.insert(FRESNELCONST_TEX); usedTextureTypes.insert(FRESNELCOLOR_TEX); usedTextureTypes.insert(NORMALMAP_TEX); texs.resize(texturesCount); for (u_int i = 0; i < texturesCount; ++i) { const Texture *t = scene->texDefs.GetTexture(i); slg::ocl::Texture *tex = &texs[i]; usedTextureTypes.insert(t->GetType()); switch (t->GetType()) { case CONST_FLOAT: { const ConstFloatTexture *cft = static_cast<const ConstFloatTexture *>(t); tex->type = slg::ocl::CONST_FLOAT; tex->constFloat.value = cft->GetValue(); break; } case CONST_FLOAT3: { const ConstFloat3Texture *cft = static_cast<const ConstFloat3Texture *>(t); tex->type = slg::ocl::CONST_FLOAT3; ASSIGN_SPECTRUM(tex->constFloat3.color, cft->GetColor()); break; } case IMAGEMAP: { const ImageMapTexture *imt = static_cast<const ImageMapTexture *>(t); tex->type = slg::ocl::IMAGEMAP; const ImageMap *im = imt->GetImageMap(); tex->imageMapTex.gain = imt->GetGain(); CompileTextureMapping2D(&tex->imageMapTex.mapping, imt->GetTextureMapping()); tex->imageMapTex.imageMapIndex = scene->imgMapCache.GetImageMapIndex(im); break; } case SCALE_TEX: { const ScaleTexture *st = static_cast<const ScaleTexture *>(t); tex->type = slg::ocl::SCALE_TEX; const Texture *tex1 = st->GetTexture1(); tex->scaleTex.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = st->GetTexture2(); tex->scaleTex.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case FRESNEL_APPROX_N: { const FresnelApproxNTexture *ft = static_cast<const FresnelApproxNTexture *>(t); tex->type = slg::ocl::FRESNEL_APPROX_N; const Texture *tx = ft->GetTexture(); tex->fresnelApproxN.texIndex = scene->texDefs.GetTextureIndex(tx); break; } case FRESNEL_APPROX_K: { const FresnelApproxKTexture *ft = static_cast<const FresnelApproxKTexture *>(t); tex->type = slg::ocl::FRESNEL_APPROX_K; const Texture *tx = ft->GetTexture(); tex->fresnelApproxK.texIndex = scene->texDefs.GetTextureIndex(tx); break; } case CHECKERBOARD2D: { const CheckerBoard2DTexture *cb = static_cast<const CheckerBoard2DTexture *>(t); tex->type = slg::ocl::CHECKERBOARD2D; CompileTextureMapping2D(&tex->checkerBoard2D.mapping, cb->GetTextureMapping()); const Texture *tex1 = cb->GetTexture1(); tex->checkerBoard2D.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = cb->GetTexture2(); tex->checkerBoard2D.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case CHECKERBOARD3D: { const CheckerBoard3DTexture *cb = static_cast<const CheckerBoard3DTexture *>(t); tex->type = slg::ocl::CHECKERBOARD3D; CompileTextureMapping3D(&tex->checkerBoard3D.mapping, cb->GetTextureMapping()); const Texture *tex1 = cb->GetTexture1(); tex->checkerBoard3D.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = cb->GetTexture2(); tex->checkerBoard3D.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case MIX_TEX: { const MixTexture *mt = static_cast<const MixTexture *>(t); tex->type = slg::ocl::MIX_TEX; const Texture *amount = mt->GetAmountTexture(); tex->mixTex.amountTexIndex = scene->texDefs.GetTextureIndex(amount); const Texture *tex1 = mt->GetTexture1(); tex->mixTex.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = mt->GetTexture2(); tex->mixTex.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case CLOUD_TEX: { const CloudTexture *ft = static_cast<const CloudTexture *>(t); tex->type = slg::ocl::CLOUD_TEX; CompileTextureMapping3D(&tex->cloud.mapping, ft->GetTextureMapping()); tex->cloud.radius = ft->GetRadius(); tex->cloud.numspheres = ft->GetNumSpheres(); tex->cloud.spheresize = ft->GetSphereSize(); tex->cloud.sharpness = ft->GetSharpness(); tex->cloud.basefadedistance = ft->GetBaseFadeDistance(); tex->cloud.baseflatness = ft->GetBaseFlatness(); tex->cloud.variability = ft->GetVariability(); tex->cloud.omega = ft->GetOmega(); tex->cloud.noisescale = ft->GetNoiseScale(); tex->cloud.noiseoffset = ft->GetNoiseOffset(); tex->cloud.turbulence = ft->GetTurbulenceAmount(); tex->cloud.octaves = ft->GetNumOctaves(); break; } case FBM_TEX: { const FBMTexture *ft = static_cast<const FBMTexture *>(t); tex->type = slg::ocl::FBM_TEX; CompileTextureMapping3D(&tex->fbm.mapping, ft->GetTextureMapping()); tex->fbm.octaves = ft->GetOctaves(); tex->fbm.omega = ft->GetOmega(); break; } case MARBLE: { const MarbleTexture *mt = static_cast<const MarbleTexture *>(t); tex->type = slg::ocl::MARBLE; CompileTextureMapping3D(&tex->marble.mapping, mt->GetTextureMapping()); tex->marble.octaves = mt->GetOctaves(); tex->marble.omega = mt->GetOmega(); tex->marble.scale = mt->GetScale(); tex->marble.variation = mt->GetVariation(); break; } case DOTS: { const DotsTexture *dt = static_cast<const DotsTexture *>(t); tex->type = slg::ocl::DOTS; CompileTextureMapping2D(&tex->dots.mapping, dt->GetTextureMapping()); const Texture *insideTex = dt->GetInsideTex(); tex->dots.insideIndex = scene->texDefs.GetTextureIndex(insideTex); const Texture *outsideTex = dt->GetOutsideTex(); tex->dots.outsideIndex = scene->texDefs.GetTextureIndex(outsideTex); break; } case BRICK: { const BrickTexture *bt = static_cast<const BrickTexture *>(t); tex->type = slg::ocl::BRICK; CompileTextureMapping3D(&tex->brick.mapping, bt->GetTextureMapping()); const Texture *tex1 = bt->GetTexture1(); tex->brick.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = bt->GetTexture2(); tex->brick.tex2Index = scene->texDefs.GetTextureIndex(tex2); const Texture *tex3 = bt->GetTexture3(); tex->brick.tex3Index = scene->texDefs.GetTextureIndex(tex3); switch (bt->GetBond()) { case FLEMISH: tex->brick.bond = slg::ocl::FLEMISH; break; default: case RUNNING: tex->brick.bond = slg::ocl::RUNNING; break; case ENGLISH: tex->brick.bond = slg::ocl::ENGLISH; break; case HERRINGBONE: tex->brick.bond = slg::ocl::HERRINGBONE; break; case BASKET: tex->brick.bond = slg::ocl::BASKET; break; case KETTING: tex->brick.bond = slg::ocl::KETTING; break; } tex->brick.offsetx = bt->GetOffset().x; tex->brick.offsety = bt->GetOffset().y; tex->brick.offsetz = bt->GetOffset().z; tex->brick.brickwidth = bt->GetBrickWidth(); tex->brick.brickheight = bt->GetBrickHeight(); tex->brick.brickdepth = bt->GetBrickDepth(); tex->brick.mortarsize = bt->GetMortarSize(); tex->brick.proportion = bt->GetProportion(); tex->brick.invproportion = bt->GetInvProportion(); tex->brick.run = bt->GetRun(); tex->brick.mortarwidth = bt->GetMortarWidth(); tex->brick.mortarheight = bt->GetMortarHeight(); tex->brick.mortardepth = bt->GetMortarDepth(); tex->brick.bevelwidth = bt->GetBevelWidth(); tex->brick.bevelheight = bt->GetBevelHeight(); tex->brick.beveldepth = bt->GetBevelDepth(); tex->brick.usebevel = bt->GetUseBevel(); break; } case ADD_TEX: { const AddTexture *st = static_cast<const AddTexture *>(t); tex->type = slg::ocl::ADD_TEX; const Texture *tex1 = st->GetTexture1(); tex->addTex.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = st->GetTexture2(); tex->addTex.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case SUBTRACT_TEX: { const SubtractTexture *st = static_cast<const SubtractTexture *>(t); tex->type = slg::ocl::SUBTRACT_TEX; const Texture *tex1 = st->GetTexture1(); tex->subtractTex.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = st->GetTexture2(); tex->subtractTex.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case WINDY: { const WindyTexture *wt = static_cast<const WindyTexture *>(t); tex->type = slg::ocl::WINDY; CompileTextureMapping3D(&tex->windy.mapping, wt->GetTextureMapping()); break; } case WRINKLED: { const WrinkledTexture *wt = static_cast<const WrinkledTexture *>(t); tex->type = slg::ocl::WRINKLED; CompileTextureMapping3D(&tex->wrinkled.mapping, wt->GetTextureMapping()); tex->wrinkled.octaves = wt->GetOctaves(); tex->wrinkled.omega = wt->GetOmega(); break; } case BLENDER_BLEND: { const BlenderBlendTexture *wt = static_cast<const BlenderBlendTexture *>(t); tex->type = slg::ocl::BLENDER_BLEND; CompileTextureMapping3D(&tex->blenderBlend.mapping, wt->GetTextureMapping()); tex->blenderBlend.direction = wt->GetDirection(); tex->blenderBlend.bright = wt->GetBright(); tex->blenderBlend.contrast = wt->GetContrast(); switch (wt->GetProgressionType()) { default: case TEX_LIN: tex->blenderBlend.type = slg::ocl::TEX_LIN; break; case TEX_QUAD: tex->blenderBlend.type = slg::ocl::TEX_QUAD; break; case TEX_EASE: tex->blenderBlend.type = slg::ocl::TEX_EASE; break; case TEX_DIAG: tex->blenderBlend.type = slg::ocl::TEX_DIAG; break; case TEX_SPHERE: tex->blenderBlend.type = slg::ocl::TEX_SPHERE; break; case TEX_HALO: tex->blenderBlend.type = slg::ocl::TEX_HALO; break; case TEX_RAD: tex->blenderBlend.type = slg::ocl::TEX_RAD; break; } break; } case BLENDER_CLOUDS: { const BlenderCloudsTexture *wt = static_cast<const BlenderCloudsTexture *>(t); tex->type = slg::ocl::BLENDER_CLOUDS; CompileTextureMapping3D(&tex->blenderClouds.mapping, wt->GetTextureMapping()); tex->blenderClouds.noisesize = wt->GetNoiseSize(); tex->blenderClouds.noisedepth = wt->GetNoiseDepth(); tex->blenderClouds.bright = wt->GetBright(); tex->blenderClouds.contrast = wt->GetContrast(); tex->blenderClouds.hard = wt->GetNoiseType(); switch (wt->GetNoiseBasis()) { default: case BLENDER_ORIGINAL: tex->blenderClouds.noisebasis = slg::ocl::BLENDER_ORIGINAL; break; case ORIGINAL_PERLIN: tex->blenderClouds.noisebasis = slg::ocl::ORIGINAL_PERLIN; break; case IMPROVED_PERLIN: tex->blenderClouds.noisebasis = slg::ocl::IMPROVED_PERLIN; break; case VORONOI_F1: tex->blenderClouds.noisebasis = slg::ocl::VORONOI_F1; break; case VORONOI_F2: tex->blenderClouds.noisebasis = slg::ocl::VORONOI_F2; break; case VORONOI_F3: tex->blenderClouds.noisebasis = slg::ocl::VORONOI_F3; break; case VORONOI_F4: tex->blenderClouds.noisebasis = slg::ocl::VORONOI_F4; break; case VORONOI_F2_F1: tex->blenderClouds.noisebasis = slg::ocl::VORONOI_F2_F1; break; case VORONOI_CRACKLE: tex->blenderClouds.noisebasis = slg::ocl::VORONOI_CRACKLE; break; case CELL_NOISE: tex->blenderClouds.noisebasis = slg::ocl::CELL_NOISE; break; } break; } case BLENDER_DISTORTED_NOISE: { const BlenderDistortedNoiseTexture *wt = static_cast<const BlenderDistortedNoiseTexture *>(t); tex->type = slg::ocl::BLENDER_DISTORTED_NOISE; CompileTextureMapping3D(&tex->blenderDistortedNoise.mapping, wt->GetTextureMapping()); tex->blenderDistortedNoise.distortion = wt->GetDistortion(); tex->blenderDistortedNoise.noisesize = wt->GetNoiseSize(); tex->blenderDistortedNoise.bright = wt->GetBright(); tex->blenderDistortedNoise.contrast = wt->GetContrast(); switch (wt->GetNoiseDistortion()) { default: case BLENDER_ORIGINAL: tex->blenderDistortedNoise.noisedistortion = slg::ocl::BLENDER_ORIGINAL; break; case ORIGINAL_PERLIN: tex->blenderDistortedNoise.noisedistortion = slg::ocl::ORIGINAL_PERLIN; break; case IMPROVED_PERLIN: tex->blenderDistortedNoise.noisedistortion = slg::ocl::IMPROVED_PERLIN; break; case VORONOI_F1: tex->blenderDistortedNoise.noisedistortion = slg::ocl::VORONOI_F1; break; case VORONOI_F2: tex->blenderDistortedNoise.noisedistortion = slg::ocl::VORONOI_F2; break; case VORONOI_F3: tex->blenderDistortedNoise.noisedistortion = slg::ocl::VORONOI_F3; break; case VORONOI_F4: tex->blenderDistortedNoise.noisedistortion = slg::ocl::VORONOI_F4; break; case VORONOI_F2_F1: tex->blenderDistortedNoise.noisedistortion = slg::ocl::VORONOI_F2_F1; break; case VORONOI_CRACKLE: tex->blenderDistortedNoise.noisedistortion = slg::ocl::VORONOI_CRACKLE; break; case CELL_NOISE: tex->blenderDistortedNoise.noisedistortion = slg::ocl::CELL_NOISE; break; } switch (wt->GetNoiseBasis()) { default: case BLENDER_ORIGINAL: tex->blenderDistortedNoise.noisebasis = slg::ocl::BLENDER_ORIGINAL; break; case ORIGINAL_PERLIN: tex->blenderDistortedNoise.noisebasis = slg::ocl::ORIGINAL_PERLIN; break; case IMPROVED_PERLIN: tex->blenderDistortedNoise.noisebasis = slg::ocl::IMPROVED_PERLIN; break; case VORONOI_F1: tex->blenderDistortedNoise.noisebasis = slg::ocl::VORONOI_F1; break; case VORONOI_F2: tex->blenderDistortedNoise.noisebasis = slg::ocl::VORONOI_F2; break; case VORONOI_F3: tex->blenderDistortedNoise.noisebasis = slg::ocl::VORONOI_F3; break; case VORONOI_F4: tex->blenderDistortedNoise.noisebasis = slg::ocl::VORONOI_F4; break; case VORONOI_F2_F1: tex->blenderDistortedNoise.noisebasis = slg::ocl::VORONOI_F2_F1; break; case VORONOI_CRACKLE: tex->blenderDistortedNoise.noisebasis = slg::ocl::VORONOI_CRACKLE; break; case CELL_NOISE: tex->blenderDistortedNoise.noisebasis = slg::ocl::CELL_NOISE; break; } break; } case BLENDER_MAGIC: { const BlenderMagicTexture *wt = static_cast<const BlenderMagicTexture *>(t); tex->type = slg::ocl::BLENDER_MAGIC; CompileTextureMapping3D(&tex->blenderMagic.mapping, wt->GetTextureMapping()); tex->blenderMagic.noisedepth = wt->GetNoiseDepth(); tex->blenderMagic.turbulence = wt->GetTurbulence(); tex->blenderMagic.bright = wt->GetBright(); tex->blenderMagic.contrast = wt->GetContrast(); break; } case BLENDER_MARBLE: { const BlenderMarbleTexture *wt = static_cast<const BlenderMarbleTexture *>(t); tex->type = slg::ocl::BLENDER_MARBLE; CompileTextureMapping3D(&tex->blenderMarble.mapping, wt->GetTextureMapping()); tex->blenderMarble.turbulence = wt->GetTurbulence(); tex->blenderMarble.noisesize = wt->GetNoiseSize(); tex->blenderMarble.noisedepth = wt->GetNoiseDepth(); tex->blenderMarble.bright = wt->GetBright(); tex->blenderMarble.contrast = wt->GetContrast(); tex->blenderMarble.hard = wt->GetNoiseType(); switch (wt->GetNoiseBasis2()) { default: case TEX_SIN: tex->blenderMarble.noisebasis2 = slg::ocl::TEX_SIN; break; case TEX_SAW: tex->blenderMarble.noisebasis2 = slg::ocl::TEX_SAW; break; case TEX_TRI: tex->blenderMarble.noisebasis2 = slg::ocl::TEX_TRI; break; } switch (wt->GetMarbleType()) { default: case TEX_SOFT: tex->blenderMarble.type = slg::ocl::TEX_SOFT; break; case TEX_SHARP: tex->blenderMarble.type = slg::ocl::TEX_SHARP; break; case TEX_SHARPER: tex->blenderMarble.type = slg::ocl::TEX_SHARPER; break; } switch (wt->GetNoiseBasis()) { default: case BLENDER_ORIGINAL: tex->blenderMarble.noisebasis = slg::ocl::BLENDER_ORIGINAL; break; case ORIGINAL_PERLIN: tex->blenderMarble.noisebasis = slg::ocl::ORIGINAL_PERLIN; break; case IMPROVED_PERLIN: tex->blenderMarble.noisebasis = slg::ocl::IMPROVED_PERLIN; break; case VORONOI_F1: tex->blenderMarble.noisebasis = slg::ocl::VORONOI_F1; break; case VORONOI_F2: tex->blenderMarble.noisebasis = slg::ocl::VORONOI_F2; break; case VORONOI_F3: tex->blenderMarble.noisebasis = slg::ocl::VORONOI_F3; break; case VORONOI_F4: tex->blenderMarble.noisebasis = slg::ocl::VORONOI_F4; break; case VORONOI_F2_F1: tex->blenderMarble.noisebasis = slg::ocl::VORONOI_F2_F1; break; case VORONOI_CRACKLE: tex->blenderMarble.noisebasis = slg::ocl::VORONOI_CRACKLE; break; case CELL_NOISE: tex->blenderMarble.noisebasis = slg::ocl::CELL_NOISE; break; } break; } case BLENDER_MUSGRAVE: { const BlenderMusgraveTexture *wt = static_cast<const BlenderMusgraveTexture *>(t); tex->type = slg::ocl::BLENDER_MUSGRAVE; CompileTextureMapping3D(&tex->blenderMusgrave.mapping, wt->GetTextureMapping()); tex->blenderMusgrave.dimension = wt->GetDimension(); tex->blenderMusgrave.intensity = wt->GetIntensity(); tex->blenderMusgrave.lacunarity = wt->GetLacunarity(); tex->blenderMusgrave.offset = wt->GetOffset(); tex->blenderMusgrave.gain = wt->GetGain(); tex->blenderMusgrave.octaves = wt->GetOctaves(); tex->blenderMusgrave.noisesize = wt->GetNoiseSize(); tex->blenderMusgrave.bright = wt->GetBright(); tex->blenderMusgrave.contrast = wt->GetContrast(); switch (wt->GetMusgraveType()) { default: case TEX_MULTIFRACTAL: tex->blenderMusgrave.type = slg::ocl::TEX_MULTIFRACTAL; break; case TEX_RIDGED_MULTIFRACTAL: tex->blenderMusgrave.type = slg::ocl::TEX_RIDGED_MULTIFRACTAL; break; case TEX_HYBRID_MULTIFRACTAL: tex->blenderMusgrave.type = slg::ocl::TEX_HYBRID_MULTIFRACTAL; break; case TEX_FBM: tex->blenderMusgrave.type = slg::ocl::TEX_FBM; break; case TEX_HETERO_TERRAIN: tex->blenderMusgrave.type = slg::ocl::TEX_HETERO_TERRAIN; break; } switch (wt->GetNoiseBasis()) { default: case BLENDER_ORIGINAL: tex->blenderMusgrave.noisebasis = slg::ocl::BLENDER_ORIGINAL; break; case ORIGINAL_PERLIN: tex->blenderMusgrave.noisebasis = slg::ocl::ORIGINAL_PERLIN; break; case IMPROVED_PERLIN: tex->blenderMusgrave.noisebasis = slg::ocl::IMPROVED_PERLIN; break; case VORONOI_F1: tex->blenderMusgrave.noisebasis = slg::ocl::VORONOI_F1; break; case VORONOI_F2: tex->blenderMusgrave.noisebasis = slg::ocl::VORONOI_F2; break; case VORONOI_F3: tex->blenderMusgrave.noisebasis = slg::ocl::VORONOI_F3; break; case VORONOI_F4: tex->blenderMusgrave.noisebasis = slg::ocl::VORONOI_F4; break; case VORONOI_F2_F1: tex->blenderMusgrave.noisebasis = slg::ocl::VORONOI_F2_F1; break; case VORONOI_CRACKLE: tex->blenderMusgrave.noisebasis = slg::ocl::VORONOI_CRACKLE; break; case CELL_NOISE: tex->blenderMusgrave.noisebasis = slg::ocl::CELL_NOISE; break; } break; } case BLENDER_NOISE: { const BlenderNoiseTexture *nt = static_cast<const BlenderNoiseTexture *>(t); tex->type = slg::ocl::BLENDER_NOISE; tex->blenderNoise.noisedepth = nt->GetNoiseDepth(); tex->blenderNoise.bright = nt->GetBright(); tex->blenderNoise.contrast = nt->GetContrast(); break; } case BLENDER_STUCCI: { const BlenderStucciTexture *wt = static_cast<const BlenderStucciTexture *>(t); tex->type = slg::ocl::BLENDER_STUCCI; CompileTextureMapping3D(&tex->blenderStucci.mapping, wt->GetTextureMapping()); tex->blenderStucci.noisesize = wt->GetNoiseSize(); tex->blenderStucci.turbulence = wt->GetTurbulence(); tex->blenderStucci.bright = wt->GetBright(); tex->blenderStucci.contrast = wt->GetContrast(); tex->blenderStucci.hard = wt->GetNoiseType(); switch (wt->GetStucciType()) { default: case TEX_PLASTIC: tex->blenderStucci.type = slg::ocl::TEX_PLASTIC; break; case TEX_WALL_IN: tex->blenderStucci.type = slg::ocl::TEX_WALL_IN; break; case TEX_WALL_OUT: tex->blenderStucci.type = slg::ocl::TEX_WALL_OUT; break; } switch (wt->GetNoiseBasis()) { default: case BLENDER_ORIGINAL: tex->blenderStucci.noisebasis = slg::ocl::BLENDER_ORIGINAL; break; case ORIGINAL_PERLIN: tex->blenderStucci.noisebasis = slg::ocl::ORIGINAL_PERLIN; break; case IMPROVED_PERLIN: tex->blenderStucci.noisebasis = slg::ocl::IMPROVED_PERLIN; break; case VORONOI_F1: tex->blenderStucci.noisebasis = slg::ocl::VORONOI_F1; break; case VORONOI_F2: tex->blenderStucci.noisebasis = slg::ocl::VORONOI_F2; break; case VORONOI_F3: tex->blenderStucci.noisebasis = slg::ocl::VORONOI_F3; break; case VORONOI_F4: tex->blenderStucci.noisebasis = slg::ocl::VORONOI_F4; break; case VORONOI_F2_F1: tex->blenderStucci.noisebasis = slg::ocl::VORONOI_F2_F1; break; case VORONOI_CRACKLE: tex->blenderStucci.noisebasis = slg::ocl::VORONOI_CRACKLE; break; case CELL_NOISE: tex->blenderStucci.noisebasis = slg::ocl::CELL_NOISE; break; } break; } case BLENDER_WOOD: { const BlenderWoodTexture *wt = static_cast<const BlenderWoodTexture *>(t); tex->type = slg::ocl::BLENDER_WOOD; CompileTextureMapping3D(&tex->blenderWood.mapping, wt->GetTextureMapping()); tex->blenderWood.turbulence = wt->GetTurbulence(); tex->blenderWood.bright = wt->GetBright(); tex->blenderWood.contrast = wt->GetContrast(); tex->blenderWood.hard = wt->GetNoiseType(); tex->blenderWood.noisesize = wt->GetNoiseSize(); switch (wt->GetNoiseBasis2()) { default: case TEX_SIN: tex->blenderWood.noisebasis2 = slg::ocl::TEX_SIN; break; case TEX_SAW: tex->blenderWood.noisebasis2 = slg::ocl::TEX_SAW; break; case TEX_TRI: tex->blenderWood.noisebasis2 = slg::ocl::TEX_TRI; break; } switch (wt->GetWoodType()) { default: case BANDS: tex->blenderWood.type = slg::ocl::BANDS; break; case RINGS: tex->blenderWood.type = slg::ocl::RINGS; break; case BANDNOISE: tex->blenderWood.type = slg::ocl::BANDNOISE; break; case RINGNOISE: tex->blenderWood.type = slg::ocl::RINGNOISE; break; } switch (wt->GetNoiseBasis()) { default: case BLENDER_ORIGINAL: tex->blenderWood.noisebasis = slg::ocl::BLENDER_ORIGINAL; break; case ORIGINAL_PERLIN: tex->blenderWood.noisebasis = slg::ocl::ORIGINAL_PERLIN; break; case IMPROVED_PERLIN: tex->blenderWood.noisebasis = slg::ocl::IMPROVED_PERLIN; break; case VORONOI_F1: tex->blenderWood.noisebasis = slg::ocl::VORONOI_F1; break; case VORONOI_F2: tex->blenderWood.noisebasis = slg::ocl::VORONOI_F2; break; case VORONOI_F3: tex->blenderWood.noisebasis = slg::ocl::VORONOI_F3; break; case VORONOI_F4: tex->blenderWood.noisebasis = slg::ocl::VORONOI_F4; break; case VORONOI_F2_F1: tex->blenderWood.noisebasis = slg::ocl::VORONOI_F2_F1; break; case VORONOI_CRACKLE: tex->blenderWood.noisebasis = slg::ocl::VORONOI_CRACKLE; break; case CELL_NOISE: tex->blenderWood.noisebasis = slg::ocl::CELL_NOISE; break; } break; } case BLENDER_VORONOI: { const BlenderVoronoiTexture *wt = static_cast<const BlenderVoronoiTexture *>(t); tex->type = slg::ocl::BLENDER_VORONOI; CompileTextureMapping3D(&tex->blenderVoronoi.mapping, wt->GetTextureMapping()); tex->blenderVoronoi.feature_weight1 = wt->GetFeatureWeight1(); tex->blenderVoronoi.feature_weight2 = wt->GetFeatureWeight2(); tex->blenderVoronoi.feature_weight3 = wt->GetFeatureWeight3(); tex->blenderVoronoi.feature_weight4 = wt->GetFeatureWeight4(); tex->blenderVoronoi.noisesize = wt->GetNoiseSize(); tex->blenderVoronoi.intensity = wt->GetIntensity(); tex->blenderVoronoi.exponent = wt->GetExponent(); tex->blenderVoronoi.bright = wt->GetBright(); tex->blenderVoronoi.contrast = wt->GetContrast(); switch (wt->GetDistMetric()) { default: case ACTUAL_DISTANCE: tex->blenderVoronoi.distancemetric = slg::ocl::ACTUAL_DISTANCE; break; case DISTANCE_SQUARED: tex->blenderVoronoi.distancemetric = slg::ocl::DISTANCE_SQUARED; break; case MANHATTAN: tex->blenderVoronoi.distancemetric = slg::ocl::MANHATTAN; break; case CHEBYCHEV: tex->blenderVoronoi.distancemetric = slg::ocl::CHEBYCHEV; break; case MINKOWSKI_HALF: tex->blenderVoronoi.distancemetric = slg::ocl::MINKOWSKI_HALF; break; case MINKOWSKI_FOUR: tex->blenderVoronoi.distancemetric = slg::ocl::MINKOWSKI_FOUR; break; case MINKOWSKI: tex->blenderVoronoi.distancemetric = slg::ocl::MANHATTAN; break; } break; } case UV_TEX: { const UVTexture *uvt = static_cast<const UVTexture *>(t); tex->type = slg::ocl::UV_TEX; CompileTextureMapping2D(&tex->uvTex.mapping, uvt->GetTextureMapping()); break; } case BAND_TEX: { const BandTexture *bt = static_cast<const BandTexture *>(t); tex->type = slg::ocl::BAND_TEX; switch (bt->GetInterpolationType()) { case BandTexture::NONE: tex->band.interpType = slg::ocl::INTERP_NONE; break; default: case BandTexture::LINEAR: tex->band.interpType = slg::ocl::INTERP_LINEAR; break; case BandTexture::CUBIC: tex->band.interpType = slg::ocl::INTERP_CUBIC; break; } const Texture *amount = bt->GetAmountTexture(); tex->band.amountTexIndex = scene->texDefs.GetTextureIndex(amount); const vector<float> &offsets = bt->GetOffsets(); const vector<Spectrum> &values = bt->GetValues(); if (offsets.size() > BAND_TEX_MAX_SIZE) throw runtime_error("BandTexture with more than " + ToString(BAND_TEX_MAX_SIZE) + " are not supported"); tex->band.size = offsets.size(); for (u_int i = 0; i < BAND_TEX_MAX_SIZE; ++i) { if (i < offsets.size()) { tex->band.offsets[i] = offsets[i]; ASSIGN_SPECTRUM(tex->band.values[i], values[i]); } else { tex->band.offsets[i] = 1.f; tex->band.values[i].c[0] = 0.f; tex->band.values[i].c[1] = 0.f; tex->band.values[i].c[2] = 0.f; } } break; } case HITPOINTCOLOR: { tex->type = slg::ocl::HITPOINTCOLOR; break; } case HITPOINTALPHA: { tex->type = slg::ocl::HITPOINTALPHA; break; } case HITPOINTGREY: { const HitPointGreyTexture *hpg = static_cast<const HitPointGreyTexture *>(t); tex->type = slg::ocl::HITPOINTGREY; tex->hitPointGrey.channel = hpg->GetChannel(); break; } case NORMALMAP_TEX: { const NormalMapTexture *nmt = static_cast<const NormalMapTexture *>(t); tex->type = slg::ocl::NORMALMAP_TEX; const Texture *normalTex = nmt->GetTexture(); tex->normalMap.texIndex = scene->texDefs.GetTextureIndex(normalTex); tex->normalMap.scale = nmt->GetScale(); break; } case BLACKBODY_TEX: { const BlackBodyTexture *bbt = static_cast<const BlackBodyTexture *>(t); tex->type = slg::ocl::BLACKBODY_TEX; ASSIGN_SPECTRUM(tex->blackBody.rgb, bbt->GetRGB()); break; } case IRREGULARDATA_TEX: { const IrregularDataTexture *idt = static_cast<const IrregularDataTexture *>(t); tex->type = slg::ocl::IRREGULARDATA_TEX; ASSIGN_SPECTRUM(tex->irregularData.rgb, idt->GetRGB()); break; } case DENSITYGRID_TEX: { const DensityGridTexture *dgt = static_cast<const DensityGridTexture *>(t); tex->type = slg::ocl::DENSITYGRID_TEX; CompileTextureMapping3D(&tex->densityGrid.mapping, dgt->GetTextureMapping()); tex->densityGrid.nx = dgt->GetWidth(); tex->densityGrid.ny = dgt->GetHeight(); tex->densityGrid.nz = dgt->GetDepth(); tex->densityGrid.imageMapIndex = scene->imgMapCache.GetImageMapIndex(dgt->GetImageMap()); break; } case FRESNELCOLOR_TEX: { const FresnelColorTexture *fct = static_cast<const FresnelColorTexture *>(t); tex->type = slg::ocl::FRESNELCOLOR_TEX; const Texture *krTex = fct->GetKr(); tex->fresnelColor.krIndex = scene->texDefs.GetTextureIndex(krTex); break; } case FRESNELCONST_TEX: { const FresnelConstTexture *fct = static_cast<const FresnelConstTexture *>(t); tex->type = slg::ocl::FRESNELCONST_TEX; ASSIGN_SPECTRUM(tex->fresnelConst.n, fct->GetN()); ASSIGN_SPECTRUM(tex->fresnelConst.k, fct->GetK()); break; } case ABS_TEX: { const AbsTexture *at = static_cast<const AbsTexture *>(t); tex->type = slg::ocl::ABS_TEX; const Texture *refTex = at->GetTexture(); tex->absTex.texIndex = scene->texDefs.GetTextureIndex(refTex); break; } case CLAMP_TEX: { const ClampTexture *ct = static_cast<const ClampTexture *>(t); tex->type = slg::ocl::CLAMP_TEX; const Texture *refTex = ct->GetTexture(); tex->clampTex.texIndex = scene->texDefs.GetTextureIndex(refTex); tex->clampTex.minVal = ct->GetMinVal(); tex->clampTex.maxVal = ct->GetMaxVal(); break; } case BILERP_TEX: { const BilerpTexture *bt = static_cast<const BilerpTexture *>(t); tex->type = slg::ocl::BILERP_TEX; const Texture *t00 = bt->GetTexture00(); const Texture *t01 = bt->GetTexture01(); const Texture *t10 = bt->GetTexture10(); const Texture *t11 = bt->GetTexture11(); tex->bilerpTex.t00Index = scene->texDefs.GetTextureIndex(t00); tex->bilerpTex.t01Index = scene->texDefs.GetTextureIndex(t01); tex->bilerpTex.t10Index = scene->texDefs.GetTextureIndex(t10); tex->bilerpTex.t11Index = scene->texDefs.GetTextureIndex(t11); break; } case COLORDEPTH_TEX: { const ColorDepthTexture *ct = static_cast<const ColorDepthTexture *>(t); tex->type = slg::ocl::COLORDEPTH_TEX; const Texture *ktTex = ct->GetKt(); tex->colorDepthTex.ktIndex = scene->texDefs.GetTextureIndex(ktTex); tex->colorDepthTex.dVal = ct->GetD(); break; } case HSV_TEX: { const HsvTexture *ht = static_cast<const HsvTexture *>(t); tex->type = slg::ocl::HSV_TEX; tex->hsvTex.texIndex = scene->texDefs.GetTextureIndex(ht->GetTexture()); tex->hsvTex.hueTexIndex = scene->texDefs.GetTextureIndex(ht->GetHue()); tex->hsvTex.satTexIndex = scene->texDefs.GetTextureIndex(ht->GetSaturation()); tex->hsvTex.valTexIndex = scene->texDefs.GetTextureIndex(ht->GetValue()); break; } case DIVIDE_TEX: { const DivideTexture *dt = static_cast<const DivideTexture *>(t); tex->type = slg::ocl::DIVIDE_TEX; const Texture *tex1 = dt->GetTexture1(); tex->divideTex.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = dt->GetTexture2(); tex->divideTex.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case REMAP_TEX: { const RemapTexture *rt = static_cast<const RemapTexture *>(t); tex->type = slg::ocl::REMAP_TEX; const Texture *valueTex = rt->GetValueTex(); tex->remapTex.valueTexIndex = scene->texDefs.GetTextureIndex(valueTex); const Texture *sourceMinTex = rt->GetSourceMinTex(); tex->remapTex.sourceMinTexIndex = scene->texDefs.GetTextureIndex(sourceMinTex); const Texture *sourceMaxTex = rt->GetSourceMaxTex(); tex->remapTex.sourceMaxTexIndex = scene->texDefs.GetTextureIndex(sourceMaxTex); const Texture *targetMinTex = rt->GetTargetMinTex(); tex->remapTex.targetMinTexIndex = scene->texDefs.GetTextureIndex(targetMinTex); const Texture *targetMaxTex = rt->GetTargetMaxTex(); tex->remapTex.targetMaxTexIndex = scene->texDefs.GetTextureIndex(targetMaxTex); break; } case OBJECTID_TEX: { tex->type = slg::ocl::OBJECTID_TEX; break; } case OBJECTID_COLOR_TEX: { tex->type = slg::ocl::OBJECTID_COLOR_TEX; break; } case OBJECTID_NORMALIZED_TEX: { tex->type = slg::ocl::OBJECTID_NORMALIZED_TEX; break; } case DOT_PRODUCT_TEX: { const DotProductTexture *dpt = static_cast<const DotProductTexture *>(t); tex->type = slg::ocl::DOT_PRODUCT_TEX; const Texture *tex1 = dpt->GetTexture1(); tex->dotProductTex.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = dpt->GetTexture2(); tex->dotProductTex.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case GREATER_THAN_TEX: { const GreaterThanTexture *gtt = static_cast<const GreaterThanTexture *>(t); tex->type = slg::ocl::GREATER_THAN_TEX; const Texture *tex1 = gtt->GetTexture1(); tex->greaterThanTex.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = gtt->GetTexture2(); tex->greaterThanTex.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case LESS_THAN_TEX: { const LessThanTexture *ltt = static_cast<const LessThanTexture *>(t); tex->type = slg::ocl::LESS_THAN_TEX; const Texture *tex1 = ltt->GetTexture1(); tex->lessThanTex.tex1Index = scene->texDefs.GetTextureIndex(tex1); const Texture *tex2 = ltt->GetTexture2(); tex->lessThanTex.tex2Index = scene->texDefs.GetTextureIndex(tex2); break; } case POWER_TEX: { const PowerTexture *pt = static_cast<const PowerTexture *>(t); tex->type = slg::ocl::POWER_TEX; const Texture *base = pt->GetBase(); tex->powerTex.baseTexIndex = scene->texDefs.GetTextureIndex(base); const Texture *exponent = pt->GetExponent(); tex->powerTex.exponentTexIndex = scene->texDefs.GetTextureIndex(exponent); break; } case SHADING_NORMAL_TEX: { tex->type = slg::ocl::SHADING_NORMAL_TEX; break; } case POSITION_TEX: { tex->type = slg::ocl::POSITION_TEX; break; } case SPLIT_FLOAT3: { const SplitFloat3Texture *sf3t = static_cast<const SplitFloat3Texture *>(t); tex->type = slg::ocl::SPLIT_FLOAT3; const Texture *t = sf3t->GetTexture(); tex->splitFloat3Tex.texIndex = scene->texDefs.GetTextureIndex(t); tex->splitFloat3Tex.channel = sf3t->GetChannel(); break; } case MAKE_FLOAT3: { const MakeFloat3Texture *mf3t = static_cast<const MakeFloat3Texture *>(t); tex->type = slg::ocl::MAKE_FLOAT3; const Texture *t1 = mf3t->GetTexture1(); tex->makeFloat3Tex.tex1Index = scene->texDefs.GetTextureIndex(t1); const Texture *t2 = mf3t->GetTexture2(); tex->makeFloat3Tex.tex2Index = scene->texDefs.GetTextureIndex(t2); const Texture *t3 = mf3t->GetTexture3(); tex->makeFloat3Tex.tex3Index = scene->texDefs.GetTextureIndex(t3); break; } default: throw runtime_error("Unknown texture in CompiledScene::CompileTextures(): " + boost::lexical_cast<string>(t->GetType())); break; } } const double tEnd = WallClockTime(); SLG_LOG("Textures compilation time: " << int((tEnd - tStart) * 1000.0) << "ms"); } //------------------------------------------------------------------------------ // Dynamic OpenCL code generation for texture evaluation //------------------------------------------------------------------------------ static string AddTextureSourceCall(const vector<slg::ocl::Texture> &texs, const string &type, const u_int i) { stringstream ss; const slg::ocl::Texture *tex = &texs[i]; switch (tex->type) { case slg::ocl::CONST_FLOAT: ss << "ConstFloatTexture_ConstEvaluate" << type << "(&texs[" << i << "])"; break; case slg::ocl::CONST_FLOAT3: ss << "ConstFloat3Texture_ConstEvaluate" << type << "(&texs[" << i << "])"; break; case slg::ocl::IMAGEMAP: ss << "ImageMapTexture_ConstEvaluate" << type << "(&texs[" << i << "], hitPoint IMAGEMAPS_PARAM)"; break; case slg::ocl::FRESNELCONST_TEX: ss << "FresnelConstTexture_ConstEvaluate" << type << "(&texs[" << i << "])"; break; case slg::ocl::FRESNELCOLOR_TEX: ss << "FresnelColorTexture_ConstEvaluate" << type << "(&texs[" << i << "])"; break; case slg::ocl::NORMALMAP_TEX: ss << "NormalMapTexture_ConstEvaluate" << type << "(&texs[" << i << "])"; break; default: ss << "Texture_Index" << i << "_Evaluate" << type << "(&texs[" << i << "], hitPoint TEXTURES_PARAM)"; break; } return ss.str(); } static string AddTextureBumpSourceCall(const vector<slg::ocl::Texture> &texs, const u_int i) { stringstream ss; const slg::ocl::Texture *tex = &texs[i]; switch (tex->type) { case slg::ocl::CONST_FLOAT: ss << "ConstFloatTexture_Bump(hitPoint)"; break; case slg::ocl::CONST_FLOAT3: ss << "ConstFloat3Texture_Bump(hitPoint)"; break; case slg::ocl::IMAGEMAP: ss << "ImageMapTexture_Bump(&texs[" << i << "], hitPoint, sampleDistance IMAGEMAPS_PARAM)"; break; case slg::ocl::FRESNELCONST_TEX: ss << "FresnelConstTexture_Bump(hitPoint)"; break; case slg::ocl::FRESNELCOLOR_TEX: ss << "FresnelColorTexture_Bump(hitPoint)"; break; case slg::ocl::NORMALMAP_TEX: ss << "NormalMapTexture_Bump(&texs[" << i << "], hitPoint, sampleDistance TEXTURES_PARAM)"; break; case slg::ocl::ADD_TEX: case slg::ocl::SUBTRACT_TEX: case slg::ocl::MIX_TEX: case slg::ocl::SCALE_TEX: ss << "Texture_Index" << i << "_Bump(hitPoint, sampleDistance TEXTURES_PARAM)"; break; default: ss << "GenericTexture_Bump(" << i << ", hitPoint, sampleDistance TEXTURES_PARAM)"; break; } return ss.str(); } static void AddTextureSource(stringstream &source, const string &texName, const string &returnType, const string &type, const u_int i, const string &texArgs) { source << "OPENCL_FORCE_INLINE " << returnType << " Texture_Index" << i << "_Evaluate" << type << "(__global const Texture *texture,\n" "\t\t__global HitPoint *hitPoint\n" "\t\tTEXTURES_PARAM_DECL) {\n" "\treturn " << texName << "Texture_ConstEvaluate" << type << "(hitPoint" << ((texArgs.length() > 0) ? (", " + texArgs) : "") << ");\n" "}\n"; } static void AddTextureSource(stringstream &source, const string &texName, const u_int i, const string &texArgs) { AddTextureSource(source, texName, "float", "Float", i, texArgs); AddTextureSource(source, texName, "float3", "Spectrum", i, texArgs); } static void AddTextureBumpSource(stringstream &source, const vector<slg::ocl::Texture> &texs) { const u_int texturesCount = texs.size(); for (u_int i = 0; i < texturesCount; ++i) { const slg::ocl::Texture *tex = &texs[i]; switch (tex->type) { case slg::ocl::CONST_FLOAT: case slg::ocl::CONST_FLOAT3: case slg::ocl::IMAGEMAP: case slg::ocl::FRESNELCONST_TEX: case slg::ocl::FRESNELCOLOR_TEX: case slg::ocl::NORMALMAP_TEX: break; case slg::ocl::ADD_TEX: { source << "#if defined(PARAM_ENABLE_TEX_ADD)\n"; source << "OPENCL_FORCE_INLINE float3 Texture_Index" << i << "_Bump(__global HitPoint *hitPoint,\n" "\t\tconst float sampleDistance\n" "\t\tTEXTURES_PARAM_DECL) {\n" "\tconst float3 tex1ShadeN = " << AddTextureBumpSourceCall(texs, tex->addTex.tex1Index) <<";\n" "\tconst float3 tex2ShadeN = " << AddTextureBumpSourceCall(texs, tex->addTex.tex2Index) <<";\n" "\treturn normalize(tex1ShadeN + tex2ShadeN - VLOAD3F(&hitPoint->shadeN.x));\n" "}\n"; source << "#endif\n"; break; } case slg::ocl::SUBTRACT_TEX: { source << "#if defined(PARAM_ENABLE_TEX_SUBTRACT)\n"; source << "OPENCL_FORCE_INLINE float3 Texture_Index" << i << "_Bump(__global HitPoint *hitPoint,\n" "\t\tconst float sampleDistance\n" "\t\tTEXTURES_PARAM_DECL) {\n" "\tconst float3 tex1ShadeN = " << AddTextureBumpSourceCall(texs, tex->subtractTex.tex1Index) << ";\n" "\tconst float3 tex2ShadeN = " << AddTextureBumpSourceCall(texs, tex->subtractTex.tex2Index) << ";\n" "\treturn normalize(tex1ShadeN - tex2ShadeN + VLOAD3F(&hitPoint->shadeN.x));\n" "}\n"; source << "#endif\n"; break; } case slg::ocl::MIX_TEX: { source << "#if defined(PARAM_ENABLE_TEX_MIX)\n"; source << "OPENCL_FORCE_INLINE float3 Texture_Index" << i << "_Bump(__global HitPoint *hitPoint,\n" "\t\tconst float sampleDistance\n" "\t\tTEXTURES_PARAM_DECL) {\n" "\tconst float3 shadeN = VLOAD3F(&hitPoint->shadeN.x);\n" "\tconst float3 u = normalize(VLOAD3F(&hitPoint->dpdu.x));\n" "\tconst float3 v = normalize(cross(shadeN, u));\n" "\tfloat3 n = " << AddTextureBumpSourceCall(texs, tex->mixTex.tex1Index) << ";\n" "\tfloat nn = dot(n, shadeN);\n" "\tconst float du1 = dot(n, u) / nn;\n" "\tconst float dv1 = dot(n, v) / nn;\n" "\tn = " << AddTextureBumpSourceCall(texs, tex->mixTex.tex2Index) << ";\n" "\tnn = dot(n, shadeN);\n" "\tconst float du2 = dot(n, u) / nn;\n" "\tconst float dv2 = dot(n, v) / nn;\n" "\tn = " << AddTextureBumpSourceCall(texs, tex->mixTex.amountTexIndex) << ";\n" "\tnn = dot(n, shadeN);\n" "\tconst float dua = dot(n, u) / nn;\n" "\tconst float dva = dot(n, v) / nn;\n" "\tconst float t1 = " << AddTextureSourceCall(texs, "Float", tex->mixTex.tex1Index) << ";\n" "\tconst float t2 = " << AddTextureSourceCall(texs, "Float", tex->mixTex.tex2Index) << ";\n" "\tconst float amt = clamp(" << AddTextureSourceCall(texs, "Float", tex->mixTex.amountTexIndex) << ", 0.f, 1.f);\n" "\tconst float du = mix(du1, du2, amt) + dua * (t2 - t1);\n" "\tconst float dv = mix(dv1, dv2, amt) + dva * (t2 - t1);\n" "\treturn normalize(shadeN + du * u + dv * v);\n" "}\n"; source << "#endif\n"; break; } case slg::ocl::SCALE_TEX: { source << "#if defined(PARAM_ENABLE_TEX_SCALE)\n"; source << "OPENCL_FORCE_INLINE float3 Texture_Index" << i << "_Bump(__global HitPoint *hitPoint,\n" "\t\tconst float sampleDistance\n" "\t\tTEXTURES_PARAM_DECL) {\n" "\tconst float3 shadeN = VLOAD3F(&hitPoint->shadeN.x);\n" "\tconst float3 u = normalize(VLOAD3F(&hitPoint->dpdu.x));\n" "\tconst float3 v = normalize(cross(shadeN, u));\n" "\tconst float3 n1 = " << AddTextureBumpSourceCall(texs, tex->scaleTex.tex1Index) << ";\n" "\tconst float nn1 = dot(n1, shadeN);\n" "\tfloat du1, dv1;\n" "\tif (nn1 != 0.f) {\n" "\t\tdu1 = dot(n1, u) / nn1;\n" "\t\tdv1 = dot(n1, v) / nn1;\n" "\t}\n" "\tconst float3 n2 = " << AddTextureBumpSourceCall(texs, tex->scaleTex.tex2Index) << ";\n" "\tconst float nn2 = dot(n2, shadeN);\n" "\tfloat du2, dv2;\n" "\tif (nn2 != 0.f) {\n" "\t\tdu2 = dot(n2, u) / nn2;\n" "\t\tdv2 = dot(n2, v) / nn2;\n" "\t}\n" "\tconst float t1 = " << AddTextureSourceCall(texs, "Float", tex->scaleTex.tex1Index) << ";\n" "\tconst float t2 = " << AddTextureSourceCall(texs, "Float", tex->scaleTex.tex2Index) << ";\n" "\tconst float du = du1 * t2 + t1 * du2;\n" "\tconst float dv = dv1 * t2 + t1 * dv2;\n" "\treturn normalize(shadeN + du * u + dv * v);\n" "}\n"; source << "#endif\n"; break; } default: // Nothing to do for textures using GenericTexture_Bump() break; } } //-------------------------------------------------------------------------- // Generate the code for evaluating a generic texture bump //-------------------------------------------------------------------------- source << "OPENCL_FORCE_NOT_INLINE float3 Texture_Bump(const uint texIndex, " "__global HitPoint *hitPoint, const float sampleDistance " "TEXTURES_PARAM_DECL) {\n" "\t__global const Texture *tex = &texs[texIndex];\n"; //-------------------------------------------------------------------------- // For textures source code that it is not dynamically generated //-------------------------------------------------------------------------- source << "\tswitch (tex->type) {\n" "#if defined(PARAM_ENABLE_TEX_CONST_FLOAT)\n" "\t\tcase CONST_FLOAT: return ConstFloatTexture_Bump(hitPoint);\n" "#endif\n" "#if defined(PARAM_ENABLE_TEX_CONST_FLOAT3)\n" "\t\tcase CONST_FLOAT3: return ConstFloat3Texture_Bump(hitPoint);\n" "#endif\n" // I can have an IMAGEMAP texture only if PARAM_HAS_IMAGEMAPS is defined "#if defined(PARAM_ENABLE_TEX_IMAGEMAP) && defined(PARAM_HAS_IMAGEMAPS)\n" "\t\tcase IMAGEMAP: return ImageMapTexture_Bump(tex, hitPoint, sampleDistance IMAGEMAPS_PARAM);\n" "#endif\n" "#if defined(PARAM_ENABLE_TEX_FRESNELCONST)\n" "\t\tcase FRESNELCONST_TEX: return FresnelConstTexture_Bump(hitPoint);\n" "#endif\n" "#if defined(PARAM_ENABLE_TEX_FRESNELCOLOR)\n" "\t\tcase FRESNELCOLOR_TEX: return FresnelColorTexture_Bump(hitPoint);\n" "#endif\n" "#if defined(PARAM_ENABLE_TEX_NORMALMAP)\n" "\t\tcase NORMALMAP_TEX: return NormalMapTexture_Bump(tex, hitPoint, sampleDistance TEXTURES_PARAM);\n" "#endif\n" "\t\tdefault: break;\n" "\t}\n"; //-------------------------------------------------------------------------- // For textures source code that it is dynamically generated //-------------------------------------------------------------------------- source << "\tswitch (texIndex) {\n"; for (u_int i = 0; i < texturesCount; ++i) { // Generate the case only for dynamically generated code const slg::ocl::Texture *tex = &texs[i]; switch (tex->type) { case slg::ocl::CONST_FLOAT: case slg::ocl::CONST_FLOAT3: case slg::ocl::IMAGEMAP: case slg::ocl::FRESNELCONST_TEX: case slg::ocl::FRESNELCOLOR_TEX: case slg::ocl::NORMALMAP_TEX: // For textures source code that it is not dynamically generated break; case slg::ocl::ADD_TEX: case slg::ocl::SUBTRACT_TEX: case slg::ocl::MIX_TEX: case slg::ocl::SCALE_TEX: // For textures source code that it must be dynamically generated source << "\t\tcase " << i << ": return Texture_Index" << i << "_Bump(hitPoint, sampleDistance TEXTURES_PARAM);\n"; break; default: // For all others using GenericTexture_Bump() break; } } source << "\t\tdefault: return GenericTexture_Bump(texIndex, hitPoint, sampleDistance TEXTURES_PARAM);\n" "\t}\n" "}\n"; } static void AddTexturesSwitchSourceCode(stringstream &source, const vector<slg::ocl::Texture> &texs, const string &type, const string &returnType) { const u_int texturesCount = texs.size(); // Generate the code for evaluating a generic texture source << "OPENCL_FORCE_NOT_INLINE " << returnType << " Texture_Get" << type << "Value(const uint texIndex, __global HitPoint *hitPoint TEXTURES_PARAM_DECL) {\n" "\t __global const Texture *tex = &texs[texIndex];\n"; //-------------------------------------------------------------------------- // For textures source code that it is not dynamically generated //-------------------------------------------------------------------------- source << "\tswitch (tex->type) {\n" "#if defined(PARAM_ENABLE_TEX_CONST_FLOAT)\n" "\t\tcase CONST_FLOAT: return ConstFloatTexture_ConstEvaluate" << type << "(tex);\n" "#endif\n" "#if defined(PARAM_ENABLE_TEX_CONST_FLOAT3)\n" "\t\tcase CONST_FLOAT3: return ConstFloat3Texture_ConstEvaluate" << type << "(tex);\n" "#endif\n" // I can have an IMAGEMAP texture only if PARAM_HAS_IMAGEMAPS is defined "#if defined(PARAM_ENABLE_TEX_IMAGEMAP) && defined(PARAM_HAS_IMAGEMAPS)\n" "\t\tcase IMAGEMAP: return ImageMapTexture_ConstEvaluate" << type << "(tex, hitPoint IMAGEMAPS_PARAM);\n" "#endif\n" "#if defined(PARAM_ENABLE_TEX_FRESNELCONST)\n" "\t\tcase FRESNELCONST_TEX: return FresnelConstTexture_ConstEvaluate" << type << "(tex);\n" "#endif\n" "#if defined(PARAM_ENABLE_TEX_FRESNELCOLOR)\n" "\t\tcase FRESNELCOLOR_TEX: return FresnelColorTexture_ConstEvaluate" << type << "(tex);\n" "#endif\n" "#if defined(PARAM_ENABLE_TEX_NORMALMAP)\n" "\t\tcase NORMALMAP_TEX: return NormalMapTexture_ConstEvaluate" << type << "(tex);\n" "#endif\n" "\t\tdefault: break;\n" << "\t}\n"; //-------------------------------------------------------------------------- // For textures source code that it is dynamically generated //-------------------------------------------------------------------------- source << "\tswitch (texIndex) {\n"; for (u_int i = 0; i < texturesCount; ++i) { // Generate the case only for dynamically generated code const slg::ocl::Texture *tex = &texs[i]; switch (tex->type) { case slg::ocl::CONST_FLOAT: case slg::ocl::CONST_FLOAT3: case slg::ocl::IMAGEMAP: case slg::ocl::FRESNELCONST_TEX: case slg::ocl::FRESNELCOLOR_TEX: case slg::ocl::NORMALMAP_TEX: // For textures source code that it is not dynamically generated break; default: source << "\t\tcase " << i << ": return Texture_Index" << i << "_Evaluate" << type << "(tex, hitPoint TEXTURES_PARAM);\n"; break; } } // This default should be never be reached as all cases should be catch by previous switches source << "\t\tdefault: return 0.f;\n" "\t}\n" "}\n"; } string CompiledScene::GetTexturesEvaluationSourceCode() const { // Generate the source code for each texture that reference other textures // and constant textures stringstream source; const u_int texturesCount = texs.size(); for (u_int i = 0; i < texturesCount; ++i) { const slg::ocl::Texture *tex = &texs[i]; switch (tex->type) { case slg::ocl::CONST_FLOAT: case slg::ocl::CONST_FLOAT3: case slg::ocl::IMAGEMAP: case slg::ocl::FRESNELCONST_TEX: case slg::ocl::FRESNELCOLOR_TEX: case slg::ocl::NORMALMAP_TEX: // Constant textures source code is not dynamically generated break; case slg::ocl::SCALE_TEX: { AddTextureSource(source, "Scale", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->scaleTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->scaleTex.tex2Index)); AddTextureSource(source, "Scale", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->scaleTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->scaleTex.tex2Index)); break; } case FRESNEL_APPROX_N: AddTextureSource(source, "FresnelApproxN", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->fresnelApproxN.texIndex)); AddTextureSource(source, "FresnelApproxN", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->fresnelApproxN.texIndex)); break; case FRESNEL_APPROX_K: AddTextureSource(source, "FresnelApproxK", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->fresnelApproxK.texIndex)); AddTextureSource(source, "FresnelApproxK", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->fresnelApproxK.texIndex)); break; case slg::ocl::MIX_TEX: { AddTextureSource(source, "Mix", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->mixTex.amountTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->mixTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->mixTex.tex2Index)); AddTextureSource(source, "Mix", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Float", tex->mixTex.amountTexIndex) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->mixTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->mixTex.tex2Index)); break; } case slg::ocl::ADD_TEX: { AddTextureSource(source, "Add", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->addTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->addTex.tex2Index)); AddTextureSource(source, "Add", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->addTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->addTex.tex2Index)); break; } case slg::ocl::SUBTRACT_TEX: { AddTextureSource(source, "Subtract", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->subtractTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->subtractTex.tex2Index)); AddTextureSource(source, "Subtract", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->subtractTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->subtractTex.tex2Index)); break; } case slg::ocl::HITPOINTCOLOR: AddTextureSource(source, "HitPointColor", i, ""); break; case slg::ocl::HITPOINTALPHA: AddTextureSource(source, "HitPointAlpha", i, ""); break; case slg::ocl::HITPOINTGREY: AddTextureSource(source, "HitPointGrey", i, "texture->hitPointGrey.channel"); break; case slg::ocl::BLENDER_BLEND: AddTextureSource(source, "BlenderBlend", i, "texture->blenderBlend.type, " "texture->blenderBlend.direction, " "texture->blenderBlend.contrast, " "texture->blenderBlend.bright, " "&texture->blenderBlend.mapping"); break; case slg::ocl::BLENDER_CLOUDS: AddTextureSource(source, "BlenderClouds", i, "texture->blenderClouds.noisebasis, " "texture->blenderClouds.noisesize, " "texture->blenderClouds.noisedepth, " "texture->blenderClouds.contrast, " "texture->blenderClouds.bright, " "texture->blenderClouds.hard, " "&texture->blenderClouds.mapping"); break; case slg::ocl::BLENDER_DISTORTED_NOISE: AddTextureSource(source, "BlenderDistortedNoise", i, "texture->blenderDistortedNoise.noisedistortion, " "texture->blenderDistortedNoise.noisebasis, " "texture->blenderDistortedNoise.distortion, " "texture->blenderDistortedNoise.noisesize, " "texture->blenderDistortedNoise.contrast, " "texture->blenderDistortedNoise.bright, " "&texture->blenderDistortedNoise.mapping"); break; case slg::ocl::BLENDER_MAGIC: AddTextureSource(source, "BlenderMagic", "float", "Float", i, "texture->blenderMagic.noisedepth, " "texture->blenderMagic.turbulence, " "texture->blenderMagic.contrast, " "texture->blenderMagic.bright, " "&texture->blenderMagic.mapping"); AddTextureSource(source, "BlenderMagic", "float3", "Spectrum", i, "texture->blenderMagic.noisedepth, " "texture->blenderMagic.turbulence, " "texture->blenderMagic.contrast, " "texture->blenderMagic.bright, " "&texture->blenderMagic.mapping"); break; case slg::ocl::BLENDER_MARBLE: AddTextureSource(source, "BlenderMarble", i, "texture->blenderMarble.type, " "texture->blenderMarble.noisebasis, " "texture->blenderMarble.noisebasis2, " "texture->blenderMarble.noisesize, " "texture->blenderMarble.turbulence, " "texture->blenderMarble.noisedepth, " "texture->blenderMarble.contrast, " "texture->blenderMarble.bright, " "texture->blenderMarble.hard, " "&texture->blenderMagic.mapping"); break; case slg::ocl::BLENDER_MUSGRAVE: AddTextureSource(source, "BlenderMusgrave", i, "texture->blenderMusgrave.type, " "texture->blenderMusgrave.noisebasis, " "texture->blenderMusgrave.dimension, " "texture->blenderMusgrave.intensity, " "texture->blenderMusgrave.lacunarity, " "texture->blenderMusgrave.offset, " "texture->blenderMusgrave.gain, " "texture->blenderMusgrave.octaves, " "texture->blenderMusgrave.noisesize, " "texture->blenderMusgrave.contrast, " "texture->blenderMusgrave.bright, " "&texture->blenderMusgrave.mapping"); break; case slg::ocl::BLENDER_NOISE: AddTextureSource(source, "BlenderNoise", i, "texture->blenderNoise.noisedepth, " "texture->blenderNoise.bright, " "texture->blenderNoise.contrast"); break; case slg::ocl::BLENDER_STUCCI: AddTextureSource(source, "BlenderStucci", i, "texture->blenderStucci.type, " "texture->blenderStucci.noisebasis, " "texture->blenderStucci.noisesize, " "texture->blenderStucci.turbulence, " "texture->blenderStucci.contrast, " "texture->blenderStucci.bright, " "texture->blenderStucci.hard, " "&texture->blenderStucci.mapping"); break; case slg::ocl::BLENDER_WOOD: AddTextureSource(source, "BlenderWood", i, "texture->blenderWood.type, " "texture->blenderWood.noisebasis2, " "texture->blenderWood.noisebasis, " "texture->blenderWood.noisesize, " "texture->blenderWood.turbulence, " "texture->blenderWood.contrast, " "texture->blenderWood.bright, " "texture->blenderWood.hard, " "&texture->blenderWood.mapping"); break; case slg::ocl::BLENDER_VORONOI: AddTextureSource(source, "BlenderVoronoi", i, "texture->blenderVoronoi.distancemetric, " "texture->blenderVoronoi.feature_weight1, " "texture->blenderVoronoi.feature_weight2, " "texture->blenderVoronoi.feature_weight3, " "texture->blenderVoronoi.feature_weight4, " "texture->blenderVoronoi.noisesize, " "texture->blenderVoronoi.intensity, " "texture->blenderVoronoi.exponent, " "texture->blenderVoronoi.contrast, " "texture->blenderVoronoi.bright, " "&texture->blenderVoronoi.mapping"); break; case slg::ocl::CHECKERBOARD2D: AddTextureSource(source, "CheckerBoard2D", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->checkerBoard2D.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->checkerBoard2D.tex2Index) + ", " + "&texture->checkerBoard2D.mapping"); AddTextureSource(source, "CheckerBoard2D", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->checkerBoard2D.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->checkerBoard2D.tex2Index) + ", " + "&texture->checkerBoard2D.mapping"); break; case slg::ocl::CHECKERBOARD3D: AddTextureSource(source, "CheckerBoard3D", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->checkerBoard3D.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->checkerBoard3D.tex2Index) + ", " + "&texture->checkerBoard3D.mapping"); AddTextureSource(source, "CheckerBoard3D", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->checkerBoard3D.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->checkerBoard3D.tex2Index) + ", " + "&texture->checkerBoard3D.mapping"); break; case slg::ocl::CLOUD_TEX: AddTextureSource(source, "Cloud", i, "texture->cloud.radius, " "texture->cloud.numspheres, " "texture->cloud.spheresize, " "texture->cloud.sharpness, " "texture->cloud.basefadedistance, " "texture->cloud.baseflatness, " "texture->cloud.variability, " "texture->cloud.omega, " "texture->cloud.noisescale, " "texture->cloud.noiseoffset, " "texture->cloud.turbulence, " "texture->cloud.octaves, " "&texture->cloud.mapping"); break; case slg::ocl::FBM_TEX: AddTextureSource(source, "FBM", i, "texture->fbm.omega, " "texture->fbm.octaves, " "&texture->fbm.mapping"); break; case slg::ocl::MARBLE: AddTextureSource(source, "Marble", i, "texture->marble.scale, " "texture->marble.omega, " "texture->marble.octaves, " "texture->marble.variation, " "&texture->marble.mapping"); break; case slg::ocl::DOTS: AddTextureSource(source, "Dots", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->dots.insideIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->dots.outsideIndex) + ", " + "&texture->dots.mapping"); AddTextureSource(source, "Dots", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->dots.insideIndex) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->dots.outsideIndex) + ", " + "&texture->dots.mapping"); break; case slg::ocl::BRICK: AddTextureSource(source, "Brick", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->brick.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->brick.tex2Index) + ", " + AddTextureSourceCall(texs, "Float", tex->brick.tex3Index) + ", " + "texture->brick.bond, " "texture->brick.brickwidth, " "texture->brick.brickheight, " "texture->brick.brickdepth, " "texture->brick.mortarsize, " "(float3)(texture->brick.offsetx, texture->brick.offsety, texture->brick.offsetz), " "texture->brick.run, " "texture->brick.mortarwidth, " "texture->brick.mortarheight, " "texture->brick.mortardepth, " "texture->brick.proportion, " "texture->brick.invproportion, " "&texture->brick.mapping"); AddTextureSource(source, "Brick", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->brick.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->brick.tex2Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->brick.tex3Index) + ", " + "texture->brick.bond, " "texture->brick.brickwidth, " "texture->brick.brickheight, " "texture->brick.brickdepth, " "texture->brick.mortarsize, " "(float3)(texture->brick.offsetx, texture->brick.offsety, texture->brick.offsetz), " "texture->brick.run, " "texture->brick.mortarwidth, " "texture->brick.mortarheight, " "texture->brick.mortardepth, " "texture->brick.proportion, " "texture->brick.invproportion, " "&texture->brick.mapping"); break; case slg::ocl::WINDY: AddTextureSource(source, "Windy", i, "&texture->windy.mapping"); break; case slg::ocl::WRINKLED: AddTextureSource(source, "Wrinkled", i, "texture->marble.omega, " "texture->marble.octaves, " "&texture->wrinkled.mapping"); break; case slg::ocl::UV_TEX: AddTextureSource(source, "UV", i, "&texture->uvTex.mapping"); break; case slg::ocl::BAND_TEX: AddTextureSource(source, "Band", "float", "Float", i, "texture->band.interpType, " "texture->band.size, " "texture->band.offsets, " "texture->band.values, " + AddTextureSourceCall(texs, "Float", tex->band.amountTexIndex)); AddTextureSource(source, "Band", "float3", "Spectrum", i, "texture->band.interpType, " "texture->band.size, " "texture->band.offsets, " "texture->band.values, " + AddTextureSourceCall(texs, "Float", tex->band.amountTexIndex)); break; case slg::ocl::BLACKBODY_TEX: AddTextureSource(source, "BlackBody", i, ToOCLString(tex->blackBody.rgb)); break; case slg::ocl::IRREGULARDATA_TEX: AddTextureSource(source, "IrregularData", i, ToOCLString(tex->irregularData.rgb)); break; case slg::ocl::DENSITYGRID_TEX: AddTextureSource(source, "DensityGrid", i, "texture->densityGrid.nx, " "texture->densityGrid.ny, " "texture->densityGrid.nz, " "texture->densityGrid.imageMapIndex, " "&texture->densityGrid.mapping " "IMAGEMAPS_PARAM"); break; case slg::ocl::ABS_TEX: { AddTextureSource(source, "Abs", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->absTex.texIndex)); AddTextureSource(source, "Abs", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->absTex.texIndex)); break; } case slg::ocl::CLAMP_TEX: { AddTextureSource(source, "Clamp", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->clampTex.texIndex) + ", " + "texture->clampTex.minVal, " "texture->clampTex.maxVal"); AddTextureSource(source, "Clamp", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->clampTex.texIndex) + ", " + "texture->clampTex.minVal, " "texture->clampTex.maxVal"); break; } case slg::ocl::BILERP_TEX: { AddTextureSource(source, "Bilerp", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->bilerpTex.t00Index) + ", " + AddTextureSourceCall(texs, "Float", tex->bilerpTex.t01Index) + ", " + AddTextureSourceCall(texs, "Float", tex->bilerpTex.t10Index) + ", " + AddTextureSourceCall(texs, "Float", tex->bilerpTex.t11Index)); AddTextureSource(source, "Bilerp", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->bilerpTex.t00Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->bilerpTex.t01Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->bilerpTex.t10Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->bilerpTex.t11Index)); break; } case slg::ocl::COLORDEPTH_TEX: { AddTextureSource(source, "ColorDepth", "float", "Float", i, "texture->colorDepthTex.dVal, " + AddTextureSourceCall(texs, "Float", tex->colorDepthTex.ktIndex)); AddTextureSource(source, "ColorDepth", "float3", "Spectrum", i, "texture->colorDepthTex.dVal, " + AddTextureSourceCall(texs, "Spectrum", tex->colorDepthTex.ktIndex)); break; } case slg::ocl::HSV_TEX: { AddTextureSource(source, "Hsv", "float", "Float", i, AddTextureSourceCall(texs, "Spectrum", tex->hsvTex.texIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->hsvTex.hueTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->hsvTex.satTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->hsvTex.valTexIndex)); AddTextureSource(source, "Hsv", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->hsvTex.texIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->hsvTex.hueTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->hsvTex.satTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->hsvTex.valTexIndex)); break; } case slg::ocl::DIVIDE_TEX: { AddTextureSource(source, "Divide", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->divideTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->divideTex.tex2Index)); AddTextureSource(source, "Divide", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->divideTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->divideTex.tex2Index)); break; } case slg::ocl::REMAP_TEX: { AddTextureSource(source, "Remap", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->remapTex.valueTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->remapTex.sourceMinTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->remapTex.sourceMaxTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->remapTex.targetMinTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->remapTex.targetMaxTexIndex)); AddTextureSource(source, "Remap", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->remapTex.valueTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->remapTex.sourceMinTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->remapTex.sourceMaxTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->remapTex.targetMinTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->remapTex.targetMaxTexIndex)); break; } case slg::ocl::OBJECTID_TEX: { AddTextureSource(source, "ObjectID", i, ""); break; } case slg::ocl::OBJECTID_COLOR_TEX: { AddTextureSource(source, "ObjectIDColor", i, ""); break; } case slg::ocl::OBJECTID_NORMALIZED_TEX: { AddTextureSource(source, "ObjectIDNormalized", i, ""); break; } case slg::ocl::DOT_PRODUCT_TEX: { AddTextureSource(source, "DotProduct", "float", "Float", i, AddTextureSourceCall(texs, "Spectrum", tex->dotProductTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->dotProductTex.tex2Index)); AddTextureSource(source, "DotProduct", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->dotProductTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Spectrum", tex->dotProductTex.tex2Index)); break; } case slg::ocl::GREATER_THAN_TEX: { AddTextureSource(source, "GreaterThan", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->greaterThanTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->greaterThanTex.tex2Index)); AddTextureSource(source, "GreaterThan", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Float", tex->greaterThanTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->greaterThanTex.tex2Index)); break; } case slg::ocl::LESS_THAN_TEX: { AddTextureSource(source, "LessThan", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->lessThanTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->lessThanTex.tex2Index)); AddTextureSource(source, "LessThan", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Float", tex->lessThanTex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->lessThanTex.tex2Index)); break; } case slg::ocl::POWER_TEX: { AddTextureSource(source, "Power", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->powerTex.baseTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->powerTex.exponentTexIndex)); AddTextureSource(source, "Power", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Float", tex->powerTex.baseTexIndex) + ", " + AddTextureSourceCall(texs, "Float", tex->powerTex.exponentTexIndex)); break; } case slg::ocl::SHADING_NORMAL_TEX: { AddTextureSource(source, "ShadingNormal", i, ""); break; } case slg::ocl::POSITION_TEX: { AddTextureSource(source, "Position", i, ""); break; } case slg::ocl::SPLIT_FLOAT3: { AddTextureSource(source, "SplitFloat3", "float", "Float", i, AddTextureSourceCall(texs, "Spectrum", tex->splitFloat3Tex.texIndex) + ", " + "texture->splitFloat3Tex.channel"); AddTextureSource(source, "SplitFloat3", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Spectrum", tex->splitFloat3Tex.texIndex) + ", " + "texture->splitFloat3Tex.channel"); break; } case slg::ocl::MAKE_FLOAT3: { AddTextureSource(source, "MakeFloat3", "float", "Float", i, AddTextureSourceCall(texs, "Float", tex->makeFloat3Tex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->makeFloat3Tex.tex2Index) + ", " + AddTextureSourceCall(texs, "Float", tex->makeFloat3Tex.tex3Index)); AddTextureSource(source, "MakeFloat3", "float3", "Spectrum", i, AddTextureSourceCall(texs, "Float", tex->makeFloat3Tex.tex1Index) + ", " + AddTextureSourceCall(texs, "Float", tex->makeFloat3Tex.tex2Index) + ", " + AddTextureSourceCall(texs, "Float", tex->makeFloat3Tex.tex3Index)); break; } default: throw runtime_error("Unknown texture in CompiledScene::GetTexturesEvaluationSourceCode(): " + boost::lexical_cast<string>(tex->type)); break; } } // Generate the code for evaluating a generic float texture AddTexturesSwitchSourceCode(source, texs, "Float", "float"); // Generate the code for evaluating a generic float texture AddTexturesSwitchSourceCode(source, texs, "Spectrum", "float3"); // Add bump and normal mapping functions source << slg::ocl::KernelSource_texture_bump_funcs; source << "#if defined(PARAM_HAS_BUMPMAPS)\n"; AddTextureBumpSource(source, texs); source << "#endif\n"; return source.str(); } #endif
38.839844
162
0.655436
[ "vector", "3d" ]
fd9b01638ddba40eb7f3d4677202934dee1f7144
2,860
cpp
C++
tools/train/source/optimizer/SGD.cpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
3
2020-09-26T03:40:17.000Z
2021-12-26T06:58:11.000Z
tools/train/source/optimizer/SGD.cpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
2
2020-06-19T08:04:43.000Z
2020-10-23T03:34:44.000Z
tools/train/source/optimizer/SGD.cpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
1
2021-06-06T06:54:53.000Z
2021-06-06T06:54:53.000Z
// // SGD.cpp // MNN // // Created by MNN on 2019/11/22. // Copyright © 2018, Alibaba Group Holding Limited // #include "SGD.hpp" #include "OpGrad.hpp" using namespace MNN::Express; namespace MNN { namespace Train { void SGD::setLearningRate(float rate) { mLearningRate = rate; } void SGD::setMomentum(float momentum) { mMomentum = momentum; } void SGD::setWeightDecay(float decay) { mWeightDecay = decay; } void SGD::setRegularizationMethod(RegularizationMethod method) { mRegularizationMethod = method; } float SGD::currentLearningRate() { return mLearningRate; } float SGD::getMomentum() { return mMomentum; } float SGD::getWeightDecay() { return mWeightDecay; } SGD::RegularizationMethod SGD::getRegularizationMethod() { return mRegularizationMethod; } void SGD::onAppend(Express::VARP p) { mHistory[p] = _Const(0.0f, p->getInfo()->dim, p->getInfo()->order); } void SGD::onRemove(Express::VARP p) { mHistory.erase(p); } Express::VARP SGD::regularizeParameters(Express::VARP param, Express::VARP grad) { VARP addWeightDecayGrad; if (mRegularizationMethod == L1) { auto temp = _Sign(param); addWeightDecayGrad = _Const(mWeightDecay, {}, NCHW) * temp + grad; } else if (mRegularizationMethod == L2) { addWeightDecayGrad = _Const(mWeightDecay, {}, NCHW) * param + grad; } else if (mRegularizationMethod == L1L2) { auto temp = _Sign(param); auto L1 = _Const(mWeightDecay, {}, NCHW) * temp; auto L2 = _Const(mWeightDecay, {}, NCHW) * param; addWeightDecayGrad = L1 + L2 + grad; } return addWeightDecayGrad; } Express::VARP SGD::onComputeUpdateValue(Express::VARP param, Express::VARP grad) { auto lr = _Const(mLearningRate, {}, NCHW); mHistory[param] = lr * grad + _Const(mMomentum, {}, NCHW) * mHistory[param]; mHistory[param].fix(Express::VARP::CONSTANT); //FUNC_PRINT_ALL(_ReduceMax(grad)->readMap<float>()[0], f); return mHistory[param]; } std::map<Express::VARP, Express::VARP> SGD::onGetNextParameter(Express::VARP loss) { auto grad = OpGrad::grad(loss, parameters(), mGradBlockExprName); std::vector<VARP> prepareCompute; for (auto& iter : grad) { prepareCompute.emplace_back(iter.second); } Variable::prepareCompute(prepareCompute); for (auto& iter : grad) { // apply regularization auto addWeightDecayGrad = regularizeParameters(iter.first, iter.second); addWeightDecayGrad.fix(Express::VARP::CONSTANT); // apply momentum, etc. auto updateValue = this->onComputeUpdateValue(iter.first, addWeightDecayGrad); // apply update auto newParameter = iter.first - updateValue; iter.second = newParameter; } return grad; } } // namespace Train } // namespace MNN
27.238095
86
0.661888
[ "vector" ]
fda3b609cb740a4233a39b23d78a0ccf72ba46e2
57,119
cpp
C++
ui/src/virtualconsole.cpp
pixeldoc2000/qlcplus
21b2921360c249f3f8aae707bb35b6db5e619b43
[ "Apache-2.0" ]
null
null
null
ui/src/virtualconsole.cpp
pixeldoc2000/qlcplus
21b2921360c249f3f8aae707bb35b6db5e619b43
[ "Apache-2.0" ]
null
null
null
ui/src/virtualconsole.cpp
pixeldoc2000/qlcplus
21b2921360c249f3f8aae707bb35b6db5e619b43
[ "Apache-2.0" ]
null
null
null
/* Q Light Controller virtualconsole.cpp Copyright (c) Heikki Junnila Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <QDesktopWidget> #include <QApplication> #include <QInputDialog> #include <QColorDialog> #include <QActionGroup> #include <QHBoxLayout> #include <QVBoxLayout> #include <QMessageBox> #include <QFileDialog> #include <QFontDialog> #include <QScrollArea> #include <QKeyEvent> #include <QMenuBar> #include <QToolBar> #include <QString> #include <QDebug> #include <QMenu> #include <QList> #include <QtXml> #include "vcpropertieseditor.h" #include "addvcbuttonmatrix.h" #include "addvcslidermatrix.h" #include "vcaudiotriggers.h" #include "virtualconsole.h" #include "dmxdumpfactory.h" #include "vcproperties.h" #include "vcspeeddial.h" #include "vcsoloframe.h" #include "mastertimer.h" #include "vcdockarea.h" #include "outputmap.h" #include "vccuelist.h" #include "inputmap.h" #include "vcbutton.h" #include "vcslider.h" #include "vcframe.h" #include "vclabel.h" #include "vcxypad.h" #include "vcclock.h" #include "doc.h" #define SETTINGS_VC_SIZE "virtualconsole/size" VirtualConsole* VirtualConsole::s_instance = NULL; /**************************************************************************** * Initialization ****************************************************************************/ VirtualConsole::VirtualConsole(QWidget* parent, Doc* doc) : QWidget(parent) , m_doc(doc) , m_latestWidgetId(0) , m_editAction(EditNone) , m_toolbar(NULL) , m_addActionGroup(NULL) , m_editActionGroup(NULL) , m_bgActionGroup(NULL) , m_fgActionGroup(NULL) , m_fontActionGroup(NULL) , m_frameActionGroup(NULL) , m_stackingActionGroup(NULL) , m_addButtonAction(NULL) , m_addButtonMatrixAction(NULL) , m_addSliderAction(NULL) , m_addSliderMatrixAction(NULL) , m_addKnobAction(NULL) , m_addSpeedDialAction(NULL) , m_addXYPadAction(NULL) , m_addCueListAction(NULL) , m_addFrameAction(NULL) , m_addSoloFrameAction(NULL) , m_addLabelAction(NULL) , m_addAudioTriggersAction(NULL) , m_addClockAction(NULL) , m_toolsSettingsAction(NULL) , m_editCutAction(NULL) , m_editCopyAction(NULL) , m_editPasteAction(NULL) , m_editDeleteAction(NULL) , m_editPropertiesAction(NULL) , m_editRenameAction(NULL) , m_bgColorAction(NULL) , m_bgImageAction(NULL) , m_bgDefaultAction(NULL) , m_fgColorAction(NULL) , m_fgDefaultAction(NULL) , m_fontAction(NULL) , m_resetFontAction(NULL) , m_frameSunkenAction(NULL) , m_frameRaisedAction(NULL) , m_frameNoneAction(NULL) , m_stackingRaiseAction(NULL) , m_stackingLowerAction(NULL) , m_customMenu(NULL) , m_editMenu(NULL) , m_addMenu(NULL) , m_dockArea(NULL) , m_contentsLayout(NULL) , m_scrollArea(NULL) , m_contents(NULL) , m_tapModifierDown(false) { Q_ASSERT(s_instance == NULL); s_instance = this; Q_ASSERT(doc != NULL); /* Main layout */ new QHBoxLayout(this); layout()->setMargin(1); layout()->setSpacing(1); initActions(); initDockArea(); m_contentsLayout = new QVBoxLayout; layout()->addItem(m_contentsLayout); initMenuBar(); initContents(); // Propagate mode changes to all widgets connect(m_doc, SIGNAL(modeChanged(Doc::Mode)), this, SLOT(slotModeChanged(Doc::Mode))); // Use the initial mode slotModeChanged(m_doc->mode()); // Nothing is selected updateActions(); } VirtualConsole::~VirtualConsole() { s_instance = NULL; } VirtualConsole* VirtualConsole::instance() { return s_instance; } Doc *VirtualConsole::getDoc() { return m_doc; } quint32 VirtualConsole::newWidgetId() { quint32 currId = m_latestWidgetId; m_latestWidgetId++; qDebug() << Q_FUNC_INFO << "Creating new ID: " << currId; return currId; } /***************************************************************************** * Properties *****************************************************************************/ VCProperties VirtualConsole::properties() const { return m_properties; } /***************************************************************************** * Selected widget *****************************************************************************/ void VirtualConsole::setEditAction(VirtualConsole::EditAction action) { m_editAction = action; } VirtualConsole::EditAction VirtualConsole::editAction() const { return m_editAction; } const QList <VCWidget*> VirtualConsole::selectedWidgets() const { return m_selectedWidgets; } void VirtualConsole::setWidgetSelected(VCWidget* widget, bool select) { Q_ASSERT(widget != NULL); if (select == false) { m_selectedWidgets.removeAll(widget); widget->update(); } else if (select == true && m_selectedWidgets.indexOf(widget) == -1) { m_selectedWidgets.append(widget); widget->update(); } /* Change the custom menu to the latest-selected widget's menu */ updateCustomMenu(); /* Enable or disable actions */ updateActions(); } bool VirtualConsole::isWidgetSelected(VCWidget* widget) const { if (widget == NULL || m_selectedWidgets.indexOf(widget) == -1) return false; else return true; } void VirtualConsole::clearWidgetSelection() { /* Get a copy of selected widget list */ QList <VCWidget*> widgets(m_selectedWidgets); /* Clear the list so isWidgetSelected() returns false for all widgets */ m_selectedWidgets.clear(); /* Update all widgets to clear the selection frame around them */ QListIterator <VCWidget*> it(widgets); while (it.hasNext() == true) it.next()->update(); /* Change the custom menu to the latest-selected widget's menu */ updateCustomMenu(); /* Enable or disable actions */ updateActions(); } void VirtualConsole::reselectWidgets() { QList <VCWidget*> widgets(m_selectedWidgets); clearWidgetSelection(); foreach (VCWidget* w, widgets) setWidgetSelected(w, true); } /***************************************************************************** * Actions, menu- and toolbar *****************************************************************************/ QMenu* VirtualConsole::customMenu() const { return m_customMenu; } QMenu* VirtualConsole::editMenu() const { return m_editMenu; } QMenu* VirtualConsole::addMenu() const { return m_addMenu; } void VirtualConsole::initActions() { /* Add menu actions */ m_addButtonAction = new QAction(QIcon(":/button.png"), tr("New Button"), this); connect(m_addButtonAction, SIGNAL(triggered(bool)), this, SLOT(slotAddButton()), Qt::QueuedConnection); m_addButtonMatrixAction = new QAction(QIcon(":/buttonmatrix.png"), tr("New Button Matrix"), this); connect(m_addButtonMatrixAction, SIGNAL(triggered(bool)), this, SLOT(slotAddButtonMatrix()), Qt::QueuedConnection); m_addSliderAction = new QAction(QIcon(":/slider.png"), tr("New Slider"), this); connect(m_addSliderAction, SIGNAL(triggered(bool)), this, SLOT(slotAddSlider()), Qt::QueuedConnection); m_addSliderMatrixAction = new QAction(QIcon(":/slidermatrix.png"), tr("New Slider Matrix"), this); connect(m_addSliderMatrixAction, SIGNAL(triggered(bool)), this, SLOT(slotAddSliderMatrix()), Qt::QueuedConnection); m_addKnobAction = new QAction(QIcon(":/knob.png"), tr("New Knob"), this); connect(m_addKnobAction, SIGNAL(triggered(bool)), this, SLOT(slotAddKnob()), Qt::QueuedConnection); m_addSpeedDialAction = new QAction(QIcon(":/speed.png"), tr("New Speed Dial"), this); connect(m_addSpeedDialAction, SIGNAL(triggered(bool)), this, SLOT(slotAddSpeedDial()), Qt::QueuedConnection); m_addXYPadAction = new QAction(QIcon(":/xypad.png"), tr("New XY pad"), this); connect(m_addXYPadAction, SIGNAL(triggered(bool)), this, SLOT(slotAddXYPad()), Qt::QueuedConnection); m_addCueListAction = new QAction(QIcon(":/cuelist.png"), tr("New Cue list"), this); connect(m_addCueListAction, SIGNAL(triggered(bool)), this, SLOT(slotAddCueList()), Qt::QueuedConnection); m_addFrameAction = new QAction(QIcon(":/frame.png"), tr("New Frame"), this); connect(m_addFrameAction, SIGNAL(triggered(bool)), this, SLOT(slotAddFrame()), Qt::QueuedConnection); m_addSoloFrameAction = new QAction(QIcon(":/soloframe.png"), tr("New Solo frame"), this); connect(m_addSoloFrameAction, SIGNAL(triggered(bool)), this, SLOT(slotAddSoloFrame()), Qt::QueuedConnection); m_addLabelAction = new QAction(QIcon(":/label.png"), tr("New Label"), this); connect(m_addLabelAction, SIGNAL(triggered(bool)), this, SLOT(slotAddLabel()), Qt::QueuedConnection); m_addAudioTriggersAction = new QAction(QIcon(":/audioinput.png"), tr("New Audio Triggers"), this); connect(m_addAudioTriggersAction, SIGNAL(triggered(bool)), this, SLOT(slotAddAudioTriggers()), Qt::QueuedConnection); m_addClockAction = new QAction(QIcon(":/clock.png"), tr("New Clock"), this); connect(m_addClockAction, SIGNAL(triggered(bool)), this, SLOT(slotAddClock()), Qt::QueuedConnection); /* Put add actions under the same group */ m_addActionGroup = new QActionGroup(this); m_addActionGroup->setExclusive(false); m_addActionGroup->addAction(m_addButtonAction); m_addActionGroup->addAction(m_addButtonMatrixAction); m_addActionGroup->addAction(m_addSliderAction); m_addActionGroup->addAction(m_addSliderMatrixAction); m_addActionGroup->addAction(m_addKnobAction); m_addActionGroup->addAction(m_addSpeedDialAction); m_addActionGroup->addAction(m_addXYPadAction); m_addActionGroup->addAction(m_addCueListAction); m_addActionGroup->addAction(m_addFrameAction); m_addActionGroup->addAction(m_addSoloFrameAction); m_addActionGroup->addAction(m_addLabelAction); m_addActionGroup->addAction(m_addAudioTriggersAction); m_addActionGroup->addAction(m_addClockAction); /* Tools menu actions */ m_toolsSettingsAction = new QAction(QIcon(":/configure.png"), tr("Virtual Console Settings"), this); connect(m_toolsSettingsAction, SIGNAL(triggered(bool)), this, SLOT(slotToolsSettings())); // Prevent this action from ending up to the application menu on OSX // and crashing the app after VC window is closed. m_toolsSettingsAction->setMenuRole(QAction::NoRole); /* Edit menu actions */ m_editCutAction = new QAction(QIcon(":/editcut.png"), tr("Cut"), this); connect(m_editCutAction, SIGNAL(triggered(bool)), this, SLOT(slotEditCut())); m_editCopyAction = new QAction(QIcon(":/editcopy.png"), tr("Copy"), this); connect(m_editCopyAction, SIGNAL(triggered(bool)), this, SLOT(slotEditCopy())); m_editPasteAction = new QAction(QIcon(":/editpaste.png"), tr("Paste"), this); m_editPasteAction->setEnabled(false); connect(m_editPasteAction, SIGNAL(triggered(bool)), this, SLOT(slotEditPaste())); m_editDeleteAction = new QAction(QIcon(":/editdelete.png"), tr("Delete"), this); connect(m_editDeleteAction, SIGNAL(triggered(bool)), this, SLOT(slotEditDelete())); m_editPropertiesAction = new QAction(QIcon(":/edit.png"), tr("Widget Properties"), this); connect(m_editPropertiesAction, SIGNAL(triggered(bool)), this, SLOT(slotEditProperties())); m_editRenameAction = new QAction(QIcon(":/editclear.png"), tr("Rename Widget"), this); connect(m_editRenameAction, SIGNAL(triggered(bool)), this, SLOT(slotEditRename())); /* Put edit actions under the same group */ m_editActionGroup = new QActionGroup(this); m_editActionGroup->setExclusive(false); m_editActionGroup->addAction(m_editCutAction); m_editActionGroup->addAction(m_editCopyAction); m_editActionGroup->addAction(m_editPasteAction); m_editActionGroup->addAction(m_editDeleteAction); m_editActionGroup->addAction(m_editPropertiesAction); m_editActionGroup->addAction(m_editRenameAction); /* Background menu actions */ m_bgColorAction = new QAction(QIcon(":/color.png"), tr("Background Color"), this); connect(m_bgColorAction, SIGNAL(triggered(bool)), this, SLOT(slotBackgroundColor())); m_bgImageAction = new QAction(QIcon(":/image.png"), tr("Background Image"), this); connect(m_bgImageAction, SIGNAL(triggered(bool)), this, SLOT(slotBackgroundImage())); m_bgDefaultAction = new QAction(QIcon(":/undo.png"), tr("Default"), this); connect(m_bgDefaultAction, SIGNAL(triggered(bool)), this, SLOT(slotBackgroundNone())); /* Put BG actions under the same group */ m_bgActionGroup = new QActionGroup(this); m_bgActionGroup->setExclusive(false); m_bgActionGroup->addAction(m_bgColorAction); m_bgActionGroup->addAction(m_bgImageAction); m_bgActionGroup->addAction(m_bgDefaultAction); /* Foreground menu actions */ m_fgColorAction = new QAction(QIcon(":/fontcolor.png"), tr("Font Colour"), this); connect(m_fgColorAction, SIGNAL(triggered(bool)), this, SLOT(slotForegroundColor())); m_fgDefaultAction = new QAction(QIcon(":/undo.png"), tr("Default"), this); connect(m_fgDefaultAction, SIGNAL(triggered(bool)), this, SLOT(slotForegroundNone())); /* Put FG actions under the same group */ m_fgActionGroup = new QActionGroup(this); m_fgActionGroup->setExclusive(false); m_fgActionGroup->addAction(m_fgColorAction); m_fgActionGroup->addAction(m_fgDefaultAction); /* Font menu actions */ m_fontAction = new QAction(QIcon(":/fonts.png"), tr("Font"), this); connect(m_fontAction, SIGNAL(triggered(bool)), this, SLOT(slotFont())); m_resetFontAction = new QAction(QIcon(":/undo.png"), tr("Default"), this); connect(m_resetFontAction, SIGNAL(triggered(bool)), this, SLOT(slotResetFont())); /* Put font actions under the same group */ m_fontActionGroup = new QActionGroup(this); m_fontActionGroup->setExclusive(false); m_fontActionGroup->addAction(m_fontAction); m_fontActionGroup->addAction(m_resetFontAction); /* Frame menu actions */ m_frameSunkenAction = new QAction(QIcon(":/framesunken.png"), tr("Sunken"), this); connect(m_frameSunkenAction, SIGNAL(triggered(bool)), this, SLOT(slotFrameSunken())); m_frameRaisedAction = new QAction(QIcon(":/frameraised.png"), tr("Raised"), this); connect(m_frameRaisedAction, SIGNAL(triggered(bool)), this, SLOT(slotFrameRaised())); m_frameNoneAction = new QAction(QIcon(":/framenone.png"), tr("None"), this); connect(m_frameNoneAction, SIGNAL(triggered(bool)), this, SLOT(slotFrameNone())); /* Put frame actions under the same group */ m_frameActionGroup = new QActionGroup(this); m_frameActionGroup->setExclusive(false); m_frameActionGroup->addAction(m_frameRaisedAction); m_frameActionGroup->addAction(m_frameSunkenAction); m_frameActionGroup->addAction(m_frameNoneAction); /* Stacking menu actions */ m_stackingRaiseAction = new QAction(QIcon(":/up.png"), tr("Bring to front"), this); connect(m_stackingRaiseAction, SIGNAL(triggered(bool)), this, SLOT(slotStackingRaise())); m_stackingLowerAction = new QAction(QIcon(":/down.png"), tr("Send to back"), this); connect(m_stackingLowerAction, SIGNAL(triggered(bool)), this, SLOT(slotStackingLower())); /* Put stacking actions under the same group */ m_stackingActionGroup = new QActionGroup(this); m_stackingActionGroup->setExclusive(false); m_stackingActionGroup->addAction(m_stackingRaiseAction); m_stackingActionGroup->addAction(m_stackingLowerAction); } void VirtualConsole::initMenuBar() { /* Add menu */ m_addMenu = new QMenu(this); m_addMenu->setTitle(tr("&Add")); m_addMenu->addAction(m_addButtonAction); m_addMenu->addAction(m_addButtonMatrixAction); m_addMenu->addSeparator(); m_addMenu->addAction(m_addSliderAction); m_addMenu->addAction(m_addSliderMatrixAction); m_addMenu->addAction(m_addKnobAction); m_addMenu->addAction(m_addSpeedDialAction); m_addMenu->addSeparator(); m_addMenu->addAction(m_addXYPadAction); m_addMenu->addAction(m_addCueListAction); m_addMenu->addAction(m_addAudioTriggersAction); m_addMenu->addSeparator(); m_addMenu->addAction(m_addFrameAction); m_addMenu->addAction(m_addSoloFrameAction); m_addMenu->addAction(m_addLabelAction); m_addMenu->addAction(m_addClockAction); /* Edit menu */ m_editMenu = new QMenu(this); m_editMenu->setTitle(tr("&Edit")); m_editMenu->addAction(m_editCutAction); m_editMenu->addAction(m_editCopyAction); m_editMenu->addAction(m_editPasteAction); m_editMenu->addAction(m_editDeleteAction); m_editMenu->addSeparator(); m_editMenu->addAction(m_editPropertiesAction); m_editMenu->addAction(m_editRenameAction); m_editMenu->addSeparator(); /* Background Menu */ QMenu* bgMenu = new QMenu(m_editMenu); bgMenu->setTitle(tr("&Background")); m_editMenu->addMenu(bgMenu); bgMenu->addAction(m_bgColorAction); bgMenu->addAction(m_bgImageAction); bgMenu->addAction(m_bgDefaultAction); /* Foreground menu */ QMenu* fgMenu = new QMenu(m_editMenu); fgMenu->setTitle(tr("&Foreground")); m_editMenu->addMenu(fgMenu); fgMenu->addAction(m_fgColorAction); fgMenu->addAction(m_fgDefaultAction); /* Font menu */ QMenu* fontMenu = new QMenu(m_editMenu); fontMenu->setTitle(tr("F&ont")); m_editMenu->addMenu(fontMenu); fontMenu->addAction(m_fontAction); fontMenu->addAction(m_resetFontAction); /* Frame menu */ QMenu* frameMenu = new QMenu(m_editMenu); frameMenu->setTitle(tr("F&rame")); m_editMenu->addMenu(frameMenu); frameMenu->addAction(m_frameSunkenAction); frameMenu->addAction(m_frameRaisedAction); frameMenu->addAction(m_frameNoneAction); /* Stacking order menu */ QMenu* stackMenu = new QMenu(m_editMenu); stackMenu->setTitle(tr("Stacking &order")); m_editMenu->addMenu(stackMenu); stackMenu->addAction(m_stackingRaiseAction); stackMenu->addAction(m_stackingLowerAction); /* Add a separator that separates the common edit items from a custom widget menu that gets appended to the edit menu when a selected widget provides one. */ m_editMenu->addSeparator(); /* Toolbar */ m_toolbar = new QToolBar(this); m_toolbar->setIconSize(QSize(26,26)); m_contentsLayout->addWidget(m_toolbar); m_toolbar->addAction(m_addButtonAction); m_toolbar->addAction(m_addButtonMatrixAction); m_toolbar->addAction(m_addSliderAction); m_toolbar->addAction(m_addSliderMatrixAction); m_toolbar->addAction(m_addKnobAction); m_toolbar->addAction(m_addSpeedDialAction); m_toolbar->addAction(m_addXYPadAction); m_toolbar->addAction(m_addCueListAction); m_toolbar->addAction(m_addFrameAction); m_toolbar->addAction(m_addSoloFrameAction); m_toolbar->addAction(m_addLabelAction); m_toolbar->addAction(m_addAudioTriggersAction); m_toolbar->addAction(m_addClockAction); m_toolbar->addSeparator(); m_toolbar->addAction(m_editCutAction); m_toolbar->addAction(m_editCopyAction); m_toolbar->addAction(m_editPasteAction); m_toolbar->addSeparator(); m_toolbar->addAction(m_editDeleteAction); m_toolbar->addSeparator(); m_toolbar->addAction(m_editPropertiesAction); m_toolbar->addAction(m_editRenameAction); m_toolbar->addSeparator(); m_toolbar->addAction(m_stackingRaiseAction); m_toolbar->addAction(m_stackingLowerAction); m_toolbar->addSeparator(); m_toolbar->addAction(m_bgColorAction); m_toolbar->addAction(m_bgImageAction); m_toolbar->addAction(m_fgColorAction); m_toolbar->addAction(m_fontAction); m_toolbar->addSeparator(); m_toolbar->addAction(m_toolsSettingsAction); } void VirtualConsole::updateCustomMenu() { /* Get rid of the custom menu, but delete it later because this might be called from the very menu that is being deleted. */ if (m_customMenu != NULL) { delete m_customMenu; m_customMenu = NULL; } if (m_selectedWidgets.size() > 0) { /* Change the custom menu to the last selected widget's menu */ VCWidget* latestWidget = m_selectedWidgets.last(); m_customMenu = latestWidget->customMenu(m_editMenu); if (m_customMenu != NULL) m_editMenu->addMenu(m_customMenu); } else { /* Change the custom menu to the bottom frame's menu */ Q_ASSERT(contents() != NULL); m_customMenu = contents()->customMenu(m_editMenu); if (m_customMenu != NULL) m_editMenu->addMenu(m_customMenu); } } void VirtualConsole::updateActions() { /* When selected widgets is empty, all actions go to main draw area. */ if (m_selectedWidgets.isEmpty() == true) { /* Enable widget additions to draw area */ m_addActionGroup->setEnabled(true); /* Disable edit actions that can't be allowed for draw area */ m_editCutAction->setEnabled(false); m_editCopyAction->setEnabled(false); m_editDeleteAction->setEnabled(false); m_editRenameAction->setEnabled(false); m_editPropertiesAction->setEnabled(false); /* All the rest are disabled for draw area, except BG & font */ m_frameActionGroup->setEnabled(false); m_stackingActionGroup->setEnabled(false); /* Enable paste to draw area if there's something to paste */ if (m_clipboard.isEmpty() == true) m_editPasteAction->setEnabled(false); else m_editPasteAction->setEnabled(true); } else { /* Enable edit actions for other widgets */ m_editCutAction->setEnabled(true); m_editCopyAction->setEnabled(true); m_editDeleteAction->setEnabled(true); m_editRenameAction->setEnabled(true); m_editPropertiesAction->setEnabled(true); /* Enable all common properties */ m_bgActionGroup->setEnabled(true); m_fgActionGroup->setEnabled(true); m_fontActionGroup->setEnabled(true); m_frameActionGroup->setEnabled(true); m_stackingActionGroup->setEnabled(true); /* Check, whether the last selected widget can hold children */ if (m_selectedWidgets.last()->allowChildren() == true) { /* Enable paste for widgets that can hold children */ if (m_clipboard.isEmpty() == true) m_editPasteAction->setEnabled(false); else m_editPasteAction->setEnabled(true); /* Enable also new additions */ m_addActionGroup->setEnabled(true); } else { /* No pasted children possible */ m_editPasteAction->setEnabled(false); } } if (contents()->children().count() == 0) m_latestWidgetId = 0; } /***************************************************************************** * Add menu callbacks *****************************************************************************/ VCWidget* VirtualConsole::closestParent() const { /* If nothing is selected, return the bottom-most contents frame */ if (m_selectedWidgets.isEmpty() == true) return contents(); /* Find the next VCWidget in the hierarchy that accepts children */ VCWidget* widget = m_selectedWidgets.last(); while (widget != NULL) { if (widget->allowChildren() == true) return widget; else widget = qobject_cast<VCWidget*> (widget->parentWidget()); } return NULL; } void VirtualConsole::checkWidgetPage(VCWidget *widget, VCWidget *parent) { if (parent->type() == VCWidget::FrameWidget) { VCFrame *frame = (VCFrame *)parent; if (frame->multipageMode() == true) { widget->setPage(frame->currentPage()); frame->addWidgetToPageMap(widget); } } else if (parent->type() == VCWidget::SoloFrameWidget) { VCSoloFrame *frame = (VCSoloFrame *)parent; if (frame->multipageMode() == true) { widget->setPage(frame->currentPage()); frame->addWidgetToPageMap(widget); } } } void VirtualConsole::slotAddButton() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCButton* button = new VCButton(parent, m_doc); setupWidget(button, parent); m_doc->setModified(); } void VirtualConsole::slotAddButtonMatrix() { VCWidget* parent(closestParent()); if (parent == NULL) return; AddVCButtonMatrix abm(this, m_doc); if (abm.exec() == QDialog::Rejected) return; int h = abm.horizontalCount(); int v = abm.verticalCount(); int sz = abm.buttonSize(); VCFrame* frame = NULL; if (abm.frameStyle() == AddVCButtonMatrix::NormalFrame) frame = new VCFrame(parent, m_doc); else frame = new VCSoloFrame(parent, m_doc); Q_ASSERT(frame != NULL); frame->setID(newWidgetId()); frame->setHeaderVisible(false); checkWidgetPage(frame, parent); // Resize the parent frame to fit the buttons nicely and toggle resizing off frame->resize(QSize((h * sz) + 20, (v * sz) + 20)); frame->setAllowResize(false); for (int y = 0; y < v; y++) { for (int x = 0; x < h; x++) { VCButton* button = new VCButton(frame, m_doc); Q_ASSERT(button != NULL); button->setID(newWidgetId()); button->move(QPoint(10 + (x * sz), 10 + (y * sz))); button->resize(QSize(sz, sz)); button->show(); int index = (y * h) + x; if (index < abm.functions().size()) { quint32 fid = abm.functions().at(index); Function* function = m_doc->function(fid); if (function != NULL) { button->setFunction(fid); button->setCaption(function->name()); } } } } // Show the frame after adding buttons to prevent flickering frame->show(); frame->move(parent->lastClickPoint()); frame->setAllowChildren(false); // Don't allow more children clearWidgetSelection(); setWidgetSelected(frame, true); m_doc->setModified(); } void VirtualConsole::slotAddSlider() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCSlider* slider = new VCSlider(parent, m_doc); setupWidget(slider, parent); m_doc->setModified(); } void VirtualConsole::slotAddSliderMatrix() { VCWidget* parent(closestParent()); if (parent == NULL) return; AddVCSliderMatrix avsm(this); if (avsm.exec() == QDialog::Rejected) return; int width = avsm.width(); int height = avsm.height(); int count = avsm.amount(); VCFrame* frame = new VCFrame(parent, m_doc); Q_ASSERT(frame != NULL); frame->setID(newWidgetId()); frame->setHeaderVisible(false); checkWidgetPage(frame, parent); // Resize the parent frame to fit the sliders nicely frame->resize(QSize((count * width) + 20, height + 20)); frame->setAllowResize(false); for (int i = 0; i < count; i++) { VCSlider* slider = new VCSlider(frame, m_doc); Q_ASSERT(slider != NULL); slider->setID(newWidgetId()); slider->move(QPoint(10 + (width * i), 10)); slider->resize(QSize(width, height)); slider->show(); } // Show the frame after adding buttons to prevent flickering frame->show(); frame->move(parent->lastClickPoint()); frame->setAllowChildren(false); // Don't allow more children clearWidgetSelection(); setWidgetSelected(frame, true); m_doc->setModified(); } void VirtualConsole::slotAddKnob() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCSlider* knob = new VCSlider(parent, m_doc); setupWidget(knob, parent); knob->resize(QSize(60, 90)); knob->setWidgetStyle(VCSlider::WKnob); knob->setCaption(tr("Knob %1").arg(knob->id())); m_doc->setModified(); } void VirtualConsole::slotAddSpeedDial() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCSpeedDial* dial = new VCSpeedDial(parent, m_doc); setupWidget(dial, parent); m_doc->setModified(); } void VirtualConsole::slotAddXYPad() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCXYPad* xypad = new VCXYPad(parent, m_doc); setupWidget(xypad, parent); m_doc->setModified(); } void VirtualConsole::slotAddCueList() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCCueList* cuelist = new VCCueList(parent, m_doc); setupWidget(cuelist, parent); m_doc->setModified(); } void VirtualConsole::slotAddFrame() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCFrame* frame = new VCFrame(parent, m_doc, true); setupWidget(frame, parent); m_doc->setModified(); } void VirtualConsole::slotAddSoloFrame() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCSoloFrame* soloframe = new VCSoloFrame(parent, m_doc, true); setupWidget(soloframe, parent); m_doc->setModified(); } void VirtualConsole::slotAddLabel() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCLabel* label = new VCLabel(parent, m_doc); setupWidget(label, parent); m_doc->setModified(); } void VirtualConsole::slotAddAudioTriggers() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCAudioTriggers* triggers = new VCAudioTriggers(parent, m_doc); setupWidget(triggers, parent); connect(triggers, SIGNAL(enableRequest(quint32)), this, SLOT(slotEnableAudioTriggers(quint32))); m_doc->setModified(); } void VirtualConsole::slotAddClock() { VCWidget* parent(closestParent()); if (parent == NULL) return; VCClock* clock = new VCClock(parent, m_doc); setupWidget(clock, parent); m_doc->setModified(); } /***************************************************************************** * Tools menu callbacks *****************************************************************************/ void VirtualConsole::slotToolsSettings() { VCPropertiesEditor vcpe(this, m_properties, m_doc->inputMap()); if (vcpe.exec() == QDialog::Accepted) { m_properties = vcpe.properties(); contents()->resize(m_properties.size()); m_doc->outputMap()->setGrandMasterChannelMode(m_properties.grandMasterChannelMode()); m_doc->outputMap()->setGrandMasterValueMode(m_properties.grandMasterValueMode()); if (m_dockArea != NULL) m_dockArea->setGrandMasterInvertedAppearance(m_properties.grandMasterSlideMode()); QSettings settings; settings.setValue(SETTINGS_BUTTON_SIZE, vcpe.buttonSize()); settings.setValue(SETTINGS_BUTTON_STATUSLED, vcpe.buttonStatusLED()); settings.setValue(SETTINGS_SLIDER_SIZE, vcpe.sliderSize()); settings.setValue(SETTINGS_SPEEDDIAL_SIZE, vcpe.speedDialSize()); settings.setValue(SETTINGS_SPEEDDIAL_VALUE, vcpe.speedDialValue()); settings.setValue(SETTINGS_XYPAD_SIZE, vcpe.xypadSize()); settings.setValue(SETTINGS_CUELIST_SIZE, vcpe.cuelistSize()); settings.setValue(SETTINGS_FRAME_SIZE, vcpe.frameSize()); settings.setValue(SETTINGS_SOLOFRAME_SIZE, vcpe.soloFrameSize()); settings.setValue(SETTINGS_AUDIOTRIGGERS_SIZE, vcpe.audioTriggersSize()); m_doc->setModified(); } } /***************************************************************************** * Edit menu callbacks *****************************************************************************/ void VirtualConsole::slotEditCut() { /* No need to delete widgets in clipboard because they are actually just MOVED to another parent during Paste when m_editAction == EditCut. Cutting the widgets does nothing to them unless Paste is invoked. */ /* Make the edit action valid only if there's something to cut */ if (m_selectedWidgets.size() == 0) { m_editAction = EditNone; m_clipboard.clear(); m_editPasteAction->setEnabled(false); } else { m_editAction = EditCut; m_clipboard = m_selectedWidgets; m_editPasteAction->setEnabled(true); } updateActions(); } void VirtualConsole::slotEditCopy() { /* Make the edit action valid only if there's something to copy */ if (m_selectedWidgets.size() == 0) { m_editAction = EditNone; m_clipboard.clear(); m_editPasteAction->setEnabled(false); } else { m_editAction = EditCopy; m_clipboard = m_selectedWidgets; m_editPasteAction->setEnabled(true); } } void VirtualConsole::slotEditPaste() { if (m_clipboard.size() == 0) { /* Invalidate the edit action if there's nothing to paste */ m_editAction = EditNone; m_editPasteAction->setEnabled(false); return; } VCWidget* parent; VCWidget* widget; QRect bounds; Q_ASSERT(contents() != NULL); /* Select the parent that gets the cut clipboard contents */ parent = closestParent(); /* Get the bounding rect for all selected widgets */ QListIterator <VCWidget*> it(m_clipboard); while (it.hasNext() == true) { widget = it.next(); Q_ASSERT(widget != NULL); bounds = bounds.united(widget->geometry()); } /* Get the upcoming parent's last mouse click point */ QPoint cp(parent->lastClickPoint()); if (m_editAction == EditCut) { it.toFront(); while (it.hasNext() == true) { widget = it.next(); Q_ASSERT(widget != NULL); if (widget == parent) continue; /* Get widget's relative pos to the bounding rect */ QPoint p(widget->x() - bounds.x() + cp.x(), widget->y() - bounds.y() + cp.y()); /* Reparent and move to the correct place */ widget->setParent(parent); widget->move(p); widget->show(); } /* Clear clipboard after pasting stuff that was CUT */ m_clipboard.clear(); m_editPasteAction->setEnabled(false); } else if (m_editAction == EditCopy) { it.toFront(); while (it.hasNext() == true) { widget = it.next(); Q_ASSERT(widget != NULL); if (widget == parent) continue; /* Get widget's relative pos to the bounding rect */ QPoint p(widget->x() - bounds.x() + cp.x(), widget->y() - bounds.y() + cp.y()); /* Create a copy and move to correct place */ VCWidget* copy = widget->createCopy(parent); Q_ASSERT(copy != NULL); copy->move(p); copy->show(); } } updateActions(); } void VirtualConsole::slotEditDelete() { QString msg(tr("Do you wish to delete the selected widgets?")); QString title(tr("Delete widgets")); int result = QMessageBox::question(this, title, msg, QMessageBox::Yes, QMessageBox::No); if (result == QMessageBox::Yes) { while (m_selectedWidgets.isEmpty() == false) { /* Consume the selected list until it is empty and delete each widget. */ VCWidget* widget = m_selectedWidgets.takeFirst(); m_widgetsMap.remove(widget->id()); VCWidget* parent = qobject_cast<VCWidget*> (widget->parentWidget()); widget->deleteLater(); if (parent != NULL) { if (parent->type() == VCWidget::FrameWidget) { VCFrame *frame = (VCFrame *)parent; if (frame->multipageMode() == true) frame->removeWidgetFromPageMap(widget); } else if (parent->type() == VCWidget::SoloFrameWidget) { VCSoloFrame *frame = (VCSoloFrame *)parent; if (frame->multipageMode() == true) frame->removeWidgetFromPageMap(widget); } } /* Remove the widget from clipboard as well so that deleted widgets won't be pasted anymore anywhere */ m_clipboard.removeAll(widget); m_editPasteAction->setEnabled(false); } updateActions(); } } void VirtualConsole::slotEditProperties() { VCWidget* widget; Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) widget = contents(); else widget = m_selectedWidgets.last(); if (widget != NULL) widget->editProperties(); } void VirtualConsole::slotEditRename() { if (m_selectedWidgets.isEmpty() == true) return; bool ok = false; QString text(m_selectedWidgets.last()->caption()); text = QInputDialog::getText(this, tr("Rename widgets"), tr("Caption:"), QLineEdit::Normal, text, &ok); if (ok == true) { VCWidget* widget; foreach(widget, m_selectedWidgets) widget->setCaption(text); } } /***************************************************************************** * Background menu callbacks *****************************************************************************/ void VirtualConsole::slotBackgroundColor() { QColor color; Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) color = contents()->backgroundColor(); else color = m_selectedWidgets.last()->backgroundColor(); color = QColorDialog::getColor(color); if (color.isValid() == true) { if (m_selectedWidgets.isEmpty() == true) { contents()->setBackgroundColor(color); } else { VCWidget* widget; foreach(widget, m_selectedWidgets) widget->setBackgroundColor(color); } } } void VirtualConsole::slotBackgroundImage() { QString path; Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) path = contents()->backgroundImage(); else path = m_selectedWidgets.last()->backgroundImage(); path = QFileDialog::getOpenFileName(this, tr("Select background image"), path, "Images (*.png *.xpm *.jpg *.gif)"); if (path.isEmpty() == false) { if (m_selectedWidgets.isEmpty() == true) { contents()->setBackgroundImage(path); } else { VCWidget* widget; foreach(widget, m_selectedWidgets) widget->setBackgroundImage(path); } } } void VirtualConsole::slotBackgroundNone() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) { contents()->resetBackgroundColor(); } else { VCWidget* widget; foreach(widget, m_selectedWidgets) widget->resetBackgroundColor(); } } /***************************************************************************** * Foreground menu callbacks *****************************************************************************/ void VirtualConsole::slotForegroundColor() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) return; QColor color(m_selectedWidgets.last()->foregroundColor()); color = QColorDialog::getColor(color); if (color.isValid() == true) { VCWidget* widget; foreach(widget, m_selectedWidgets) widget->setForegroundColor(color); } } void VirtualConsole::slotForegroundNone() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) return; VCWidget* widget; foreach(widget, m_selectedWidgets) widget->resetForegroundColor(); } /***************************************************************************** * Font menu callbacks *****************************************************************************/ void VirtualConsole::slotFont() { bool ok = false; QFont font; Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) font = contents()->font(); else font = m_selectedWidgets.last()->font(); /* This crashes with Qt 4.6.x on OSX. Upgrade to 4.7.x. */ font = QFontDialog::getFont(&ok, font); if (ok == true) { if (m_selectedWidgets.isEmpty() == true) { contents()->setFont(font); } else { VCWidget* widget; foreach(widget, m_selectedWidgets) widget->setFont(font); } } } void VirtualConsole::slotResetFont() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) { contents()->resetFont(); } else { VCWidget* widget; foreach(widget, m_selectedWidgets) widget->resetFont(); } } /***************************************************************************** * Stacking menu callbacks *****************************************************************************/ void VirtualConsole::slotStackingRaise() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) return; VCWidget* widget; foreach(widget, m_selectedWidgets) widget->raise(); } void VirtualConsole::slotStackingLower() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) return; VCWidget* widget; foreach(widget, m_selectedWidgets) widget->lower(); } void VirtualConsole::slotEnableAudioTriggers(quint32 id) { QList<VCWidget *> widgetsList = getChildren((VCWidget *)m_contents); VCAudioTriggers *enableWidget = NULL; foreach (VCWidget *widget, widgetsList) { if (widget->type() == VCWidget::AudioTriggersWidget) { VCAudioTriggers *triggers = (VCAudioTriggers *)widget; if (widget->id() == id) enableWidget = triggers; else triggers->enableCapture(false); } } if (enableWidget != NULL) enableWidget->enableCapture(true); } /***************************************************************************** * Frame menu callbacks *****************************************************************************/ void VirtualConsole::slotFrameSunken() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) return; VCWidget* widget; foreach(widget, m_selectedWidgets) widget->setFrameStyle(KVCFrameStyleSunken); } void VirtualConsole::slotFrameRaised() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) return; VCWidget* widget; foreach(widget, m_selectedWidgets) widget->setFrameStyle(KVCFrameStyleRaised); } void VirtualConsole::slotFrameNone() { Q_ASSERT(contents() != NULL); if (m_selectedWidgets.isEmpty() == true) return; VCWidget* widget; foreach(widget, m_selectedWidgets) widget->setFrameStyle(KVCFrameStyleNone); } /***************************************************************************** * Dock area *****************************************************************************/ VCDockArea* VirtualConsole::dockArea() const { return m_dockArea; } void VirtualConsole::initDockArea() { if (m_dockArea != NULL) delete m_dockArea; m_dockArea = new VCDockArea(this, m_doc->outputMap(), m_doc->inputMap()); m_dockArea->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Expanding); // Add the dock area into the master horizontal layout layout()->addWidget(m_dockArea); /* Show the dock area by default */ m_dockArea->show(); } /***************************************************************************** * Contents *****************************************************************************/ VCFrame* VirtualConsole::contents() const { return m_contents; } void VirtualConsole::resetContents() { if (m_contents != NULL) delete m_contents; Q_ASSERT(m_scrollArea != NULL); m_contents = new VCFrame(m_scrollArea, m_doc); m_contents->setFrameStyle(0); // Get virtual console size from properties QSize size(m_properties.size()); contents()->resize(size); contents()->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); m_scrollArea->setWidget(contents()); /* Disconnect old key handlers to prevent duplicates */ disconnect(this, SIGNAL(keyPressed(const QKeySequence&)), contents(), SLOT(slotKeyPressed(const QKeySequence&))); disconnect(this, SIGNAL(keyReleased(const QKeySequence&)), contents(), SLOT(slotKeyReleased(const QKeySequence&))); /* Connect new key handlers */ connect(this, SIGNAL(keyPressed(const QKeySequence&)), contents(), SLOT(slotKeyPressed(const QKeySequence&))); connect(this, SIGNAL(keyReleased(const QKeySequence&)), contents(), SLOT(slotKeyReleased(const QKeySequence&))); /* Make the contents area take up all available space */ contents()->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); m_clipboard.clear(); m_selectedWidgets.clear(); m_latestWidgetId = 0; m_widgetsMap.clear(); /* Update actions' enabled status */ updateActions(); /* Reset all properties but size */ m_properties.setTapModifier(Qt::ControlModifier); m_properties.setGrandMasterChannelMode(UniverseArray::GMIntensity); m_properties.setGrandMasterValueMode(UniverseArray::GMReduce); m_properties.setGrandMasterInputSource(InputMap::invalidUniverse(), InputMap::invalidChannel()); } void VirtualConsole::setupWidget(VCWidget *widget, VCWidget *parent) { Q_ASSERT(widget != NULL); Q_ASSERT(parent != NULL); widget->setID(newWidgetId()); checkWidgetPage(widget, parent); widget->show(); widget->move(parent->lastClickPoint()); clearWidgetSelection(); setWidgetSelected(widget, true); } VCWidget *VirtualConsole::widget(quint32 id) { if (id == VCWidget::invalidId()) return NULL; return m_widgetsMap[id]; /* QList<VCWidget *> widgetsList = getChildren((VCWidget *)m_contents); foreach (QObject *object, widgetsList) { VCWidget *widget = (VCWidget *)object; quint32 wid = widget->id(); if (wid == id) return widget; } return NULL; */ } void VirtualConsole::initContents() { Q_ASSERT(layout() != NULL); m_scrollArea = new QScrollArea(this); m_contentsLayout->addWidget(m_scrollArea); m_scrollArea->setAlignment(Qt::AlignCenter); m_scrollArea->setWidgetResizable(false); resetContents(); } /***************************************************************************** * Key press handler *****************************************************************************/ bool VirtualConsole::isTapModifierDown() const { return m_tapModifierDown; } void VirtualConsole::keyPressEvent(QKeyEvent* event) { if (event->isAutoRepeat() == true) { event->ignore(); return; } if ((event->modifiers() & Qt::ControlModifier) != 0) m_tapModifierDown = true; QKeySequence seq(event->key() | (event->modifiers() & ~Qt::ControlModifier)); emit keyPressed(seq); event->accept(); } void VirtualConsole::keyReleaseEvent(QKeyEvent* event) { if (event->isAutoRepeat() == true) { event->ignore(); return; } if ((event->modifiers() & Qt::ControlModifier) == 0) m_tapModifierDown = false; QKeySequence seq(event->key() | event->modifiers()); emit keyReleased(seq); event->accept(); } /***************************************************************************** * Main application mode *****************************************************************************/ void VirtualConsole::slotModeChanged(Doc::Mode mode) { QString config; if (mode == Doc::Operate) { // Don't allow editing or adding in operate mode m_toolsSettingsAction->setEnabled(false); m_editActionGroup->setEnabled(false); m_addActionGroup->setEnabled(false); m_bgActionGroup->setEnabled(false); m_fgActionGroup->setEnabled(false); m_fontActionGroup->setEnabled(false); m_frameActionGroup->setEnabled(false); m_stackingActionGroup->setEnabled(false); // Disable action shortcuts in operate mode m_addButtonAction->setShortcut(QKeySequence()); m_addButtonMatrixAction->setShortcut(QKeySequence()); m_addSliderAction->setShortcut(QKeySequence()); m_addSliderMatrixAction->setShortcut(QKeySequence()); m_addKnobAction->setShortcut(QKeySequence()); m_addSpeedDialAction->setShortcut(QKeySequence()); m_addXYPadAction->setShortcut(QKeySequence()); m_addCueListAction->setShortcut(QKeySequence()); m_addFrameAction->setShortcut(QKeySequence()); m_addSoloFrameAction->setShortcut(QKeySequence()); m_addLabelAction->setShortcut(QKeySequence()); m_addAudioTriggersAction->setShortcut(QKeySequence()); m_addClockAction->setShortcut(QKeySequence()); m_editCutAction->setShortcut(QKeySequence()); m_editCopyAction->setShortcut(QKeySequence()); m_editPasteAction->setShortcut(QKeySequence()); m_editDeleteAction->setShortcut(QKeySequence()); m_editPropertiesAction->setShortcut(QKeySequence()); m_bgColorAction->setShortcut(QKeySequence()); m_bgImageAction->setShortcut(QKeySequence()); m_bgDefaultAction->setShortcut(QKeySequence()); m_fgColorAction->setShortcut(QKeySequence()); m_fgDefaultAction->setShortcut(QKeySequence()); m_fontAction->setShortcut(QKeySequence()); m_resetFontAction->setShortcut(QKeySequence()); m_frameSunkenAction->setShortcut(QKeySequence()); m_frameRaisedAction->setShortcut(QKeySequence()); m_frameNoneAction->setShortcut(QKeySequence()); m_stackingRaiseAction->setShortcut(QKeySequence()); m_stackingLowerAction->setShortcut(QKeySequence()); // Hide toolbar; there's nothing usable there in operate mode m_toolbar->hide(); } else { // Allow editing and adding in design mode m_toolsSettingsAction->setEnabled(true); m_editActionGroup->setEnabled(true); m_addActionGroup->setEnabled(true); m_bgActionGroup->setEnabled(true); m_fgActionGroup->setEnabled(true); m_fontActionGroup->setEnabled(true); m_frameActionGroup->setEnabled(true); m_stackingActionGroup->setEnabled(true); // Set action shortcuts for design mode m_addButtonAction->setShortcut(QKeySequence("CTRL+SHIFT+B")); m_addButtonMatrixAction->setShortcut(QKeySequence("CTRL+SHIFT+M")); m_addSliderAction->setShortcut(QKeySequence("CTRL+SHIFT+S")); m_addSliderMatrixAction->setShortcut(QKeySequence("CTRL+SHIFT+I")); m_addKnobAction->setShortcut(QKeySequence("CTRL+SHIFT+K")); m_addSpeedDialAction->setShortcut(QKeySequence("CTRL+SHIFT+D")); m_addXYPadAction->setShortcut(QKeySequence("CTRL+SHIFT+X")); m_addCueListAction->setShortcut(QKeySequence("CTRL+SHIFT+C")); m_addFrameAction->setShortcut(QKeySequence("CTRL+SHIFT+F")); m_addSoloFrameAction->setShortcut(QKeySequence("CTRL+SHIFT+O")); m_addLabelAction->setShortcut(QKeySequence("CTRL+SHIFT+L")); m_addAudioTriggersAction->setShortcut(QKeySequence("CTRL+SHIFT+A")); m_addClockAction->setShortcut(QKeySequence("CTRL+SHIFT+T")); m_editCutAction->setShortcut(QKeySequence("CTRL+X")); m_editCopyAction->setShortcut(QKeySequence("CTRL+C")); m_editPasteAction->setShortcut(QKeySequence("CTRL+V")); m_editDeleteAction->setShortcut(QKeySequence("Delete")); m_editPropertiesAction->setShortcut(QKeySequence("CTRL+E")); m_bgColorAction->setShortcut(QKeySequence("SHIFT+B")); m_bgImageAction->setShortcut(QKeySequence("SHIFT+I")); m_bgDefaultAction->setShortcut(QKeySequence("SHIFT+ALT+B")); m_fgColorAction->setShortcut(QKeySequence("SHIFT+F")); m_fgDefaultAction->setShortcut(QKeySequence("SHIFT+ALT+F")); m_fontAction->setShortcut(QKeySequence("SHIFT+O")); m_resetFontAction->setShortcut(QKeySequence("SHIFT+ALT+O")); m_frameSunkenAction->setShortcut(QKeySequence("SHIFT+S")); m_frameRaisedAction->setShortcut(QKeySequence("SHIFT+R")); m_frameNoneAction->setShortcut(QKeySequence("SHIFT+ALT+S")); m_stackingRaiseAction->setShortcut(QKeySequence("SHIFT+UP")); m_stackingLowerAction->setShortcut(QKeySequence("SHIFT+DOWN")); // Show toolbar m_toolbar->show(); } } /***************************************************************************** * Load & Save *****************************************************************************/ bool VirtualConsole::loadXML(const QDomElement& root) { if (root.tagName() != KXMLQLCVirtualConsole) { qWarning() << Q_FUNC_INFO << "Virtual Console node not found"; return false; } QDomNode node = root.firstChild(); while (node.isNull() == false) { QDomElement tag = node.toElement(); if (tag.tagName() == KXMLQLCVCProperties) { /* Properties */ m_properties.loadXML(tag); QSize size(m_properties.size()); contents()->resize(size); contents()->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed)); } else if (tag.tagName() == KXMLQLCVCFrame) { /* Contents */ Q_ASSERT(m_contents != NULL); m_contents->loadXML(&tag); } else { qWarning() << Q_FUNC_INFO << "Unknown Virtual Console tag" << tag.tagName(); } /* Next node */ node = node.nextSibling(); } return true; } bool VirtualConsole::saveXML(QDomDocument* doc, QDomElement* wksp_root) { Q_ASSERT(doc != NULL); Q_ASSERT(wksp_root != NULL); /* Virtual Console entry */ QDomElement vc_root = doc->createElement(KXMLQLCVirtualConsole); wksp_root->appendChild(vc_root); /* Contents */ Q_ASSERT(m_contents != NULL); m_contents->saveXML(doc, &vc_root); /* Properties */ m_properties.saveXML(doc, &vc_root); return true; } QList<VCWidget *> VirtualConsole::getChildren(VCWidget *obj) { QList<VCWidget *> list; if (obj == NULL) return list; QListIterator <VCWidget*> it(obj->findChildren<VCWidget*>()); while (it.hasNext() == true) { VCWidget* child = it.next(); list.append(child); list.append(getChildren(child)); } return list; } void VirtualConsole::postLoad() { m_contents->postLoad(); /* apply GM values this should probably be placed in another place, but at the moment m_properties is just loaded in VirtualConsole */ m_doc->outputMap()->setGrandMasterValue(255); m_doc->outputMap()->setGrandMasterValueMode(m_properties.grandMasterValueMode()); m_doc->outputMap()->setGrandMasterChannelMode(m_properties.grandMasterChannelMode()); /* Go through widgets, check IDs and register */ /* widgets to the map */ QList<VCWidget *> widgetsList = getChildren((VCWidget *)m_contents); foreach (VCWidget *widget, widgetsList) { quint32 wid = widget->id(); if(wid == VCWidget::invalidId()) widget->setID(newWidgetId()); else if (wid >= m_latestWidgetId) m_latestWidgetId = wid + 1; m_widgetsMap[widget->id()] = widget; } qDebug() << "Next ID to assign:" << m_latestWidgetId; }
31.644875
121
0.625309
[ "geometry", "object" ]
fda9cf39569e9827681dbfa4593235f7b800b3eb
193,775
cpp
C++
renderdoc/driver/vulkan/vk_common.cpp
zlin4/RenderDocImageDump
569d09ee5776cbfa8ed6b96004f3bde460214eb9
[ "MIT" ]
3
2018-04-13T20:02:31.000Z
2020-10-07T20:41:23.000Z
renderdoc/driver/vulkan/vk_common.cpp
zlin4/RenderDocImageDump
569d09ee5776cbfa8ed6b96004f3bde460214eb9
[ "MIT" ]
null
null
null
renderdoc/driver/vulkan/vk_common.cpp
zlin4/RenderDocImageDump
569d09ee5776cbfa8ed6b96004f3bde460214eb9
[ "MIT" ]
4
2019-11-01T23:13:49.000Z
2022-01-31T09:10:11.000Z
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2015-2017 Baldur Karlsson * * 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 "vk_common.h" #include "vk_core.h" #include "vk_manager.h" #include "vk_resources.h" const uint32_t AMD_PCI_ID = 0x1002; const uint32_t NV_PCI_ID = 0x10DE; // utility struct for firing one-shot command buffers to begin/end markers struct ScopedCommandBuffer { ScopedCommandBuffer(VkCommandBuffer cmdbuf, WrappedVulkan *vk) { core = vk; cmd = cmdbuf; local = (cmd == VK_NULL_HANDLE); if(local) { VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; cmd = vk->GetNextCmd(); VkResult vkr = ObjDisp(cmd)->BeginCommandBuffer(Unwrap(cmd), &beginInfo); RDCASSERTEQUAL(vkr, VK_SUCCESS); } } ~ScopedCommandBuffer() { VkResult vkr = ObjDisp(cmd)->EndCommandBuffer(Unwrap(cmd)); RDCASSERTEQUAL(vkr, VK_SUCCESS); core->SubmitCmds(); } WrappedVulkan *core; VkCommandBuffer cmd; bool local; }; WrappedVulkan *VkMarkerRegion::vk = NULL; VkMarkerRegion::VkMarkerRegion(const std::string &marker, VkCommandBuffer cmd) { if(cmd == VK_NULL_HANDLE) { RDCERR("Cannot auto-allocate a command buffer for a scoped VkMarkerRegion"); return; } cmdbuf = cmd; Begin(marker, cmd); } VkMarkerRegion::~VkMarkerRegion() { if(cmdbuf) End(cmdbuf); } void VkMarkerRegion::Begin(const std::string &marker, VkCommandBuffer cmd) { if(!vk) return; // check for presence of the marker extension if(!ObjDisp(vk->GetDev())->CmdDebugMarkerBeginEXT) return; ScopedCommandBuffer scope(cmd, vk); VkDebugMarkerMarkerInfoEXT markerInfo = {}; markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT; markerInfo.pMarkerName = marker.c_str(); ObjDisp(scope.cmd)->CmdDebugMarkerBeginEXT(Unwrap(scope.cmd), &markerInfo); } void VkMarkerRegion::Set(const std::string &marker, VkCommandBuffer cmd) { // check for presence of the marker extension if(!ObjDisp(vk->GetDev())->CmdDebugMarkerBeginEXT) return; ScopedCommandBuffer scope(cmd, vk); VkDebugMarkerMarkerInfoEXT markerInfo = {}; markerInfo.sType = VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT; markerInfo.pMarkerName = marker.c_str(); ObjDisp(scope.cmd)->CmdDebugMarkerInsertEXT(Unwrap(scope.cmd), &markerInfo); } void VkMarkerRegion::End(VkCommandBuffer cmd) { // check for presence of the marker extension if(!ObjDisp(vk->GetDev())->CmdDebugMarkerBeginEXT) return; ScopedCommandBuffer scope(cmd, vk); ObjDisp(scope.cmd)->CmdDebugMarkerEndEXT(Unwrap(scope.cmd)); } VkAccessFlags MakeAccessMask(VkImageLayout layout) { switch(layout) { case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: return VkAccessFlags(VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT); case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: return VkAccessFlags(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT); case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: return VkAccessFlags(VK_ACCESS_TRANSFER_WRITE_BIT); case VK_IMAGE_LAYOUT_PREINITIALIZED: return VkAccessFlags(VK_ACCESS_HOST_WRITE_BIT); case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: return VkAccessFlags(VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT); case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: return VkAccessFlags(VK_ACCESS_INPUT_ATTACHMENT_READ_BIT | VK_ACCESS_SHADER_READ_BIT); case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: return VkAccessFlags(VK_ACCESS_TRANSFER_READ_BIT); default: break; } return VkAccessFlags(0); } void ReplacePresentableImageLayout(VkImageLayout &layout) { if(layout == VK_IMAGE_LAYOUT_PRESENT_SRC_KHR) layout = VK_IMAGE_LAYOUT_GENERAL; } void ReplaceExternalQueueFamily(uint32_t &srcQueueFamily, uint32_t &dstQueueFamily) { if(srcQueueFamily == VK_QUEUE_FAMILY_EXTERNAL_KHR || dstQueueFamily == VK_QUEUE_FAMILY_EXTERNAL_KHR) { // we should ignore this family transition since we're not synchronising with an // external access. srcQueueFamily = dstQueueFamily = VK_QUEUE_FAMILY_IGNORED; } } int SampleCount(VkSampleCountFlagBits countFlag) { switch(countFlag) { case VK_SAMPLE_COUNT_1_BIT: return 1; case VK_SAMPLE_COUNT_2_BIT: return 2; case VK_SAMPLE_COUNT_4_BIT: return 4; case VK_SAMPLE_COUNT_8_BIT: return 8; case VK_SAMPLE_COUNT_16_BIT: return 16; case VK_SAMPLE_COUNT_32_BIT: return 32; case VK_SAMPLE_COUNT_64_BIT: return 64; default: RDCERR("Unrecognised/not single flag %x", countFlag); break; } return 1; } int SampleIndex(VkSampleCountFlagBits countFlag) { switch(countFlag) { case VK_SAMPLE_COUNT_1_BIT: return 0; case VK_SAMPLE_COUNT_2_BIT: return 1; case VK_SAMPLE_COUNT_4_BIT: return 2; case VK_SAMPLE_COUNT_8_BIT: return 3; case VK_SAMPLE_COUNT_16_BIT: return 4; case VK_SAMPLE_COUNT_32_BIT: return 5; case VK_SAMPLE_COUNT_64_BIT: return 6; default: RDCERR("Unrecognised/not single flag %x", countFlag); break; } return 0; } int StageIndex(VkShaderStageFlagBits stageFlag) { switch(stageFlag) { case VK_SHADER_STAGE_VERTEX_BIT: return 0; case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: return 1; case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: return 2; case VK_SHADER_STAGE_GEOMETRY_BIT: return 3; case VK_SHADER_STAGE_FRAGMENT_BIT: return 4; case VK_SHADER_STAGE_COMPUTE_BIT: return 5; default: RDCERR("Unrecognised/not single flag %x", stageFlag); break; } return 0; } void DoPipelineBarrier(VkCommandBuffer cmd, uint32_t count, VkImageMemoryBarrier *barriers) { ObjDisp(cmd)->CmdPipelineBarrier(Unwrap(cmd), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, NULL, // global memory barriers 0, NULL, // buffer memory barriers count, barriers); // image memory barriers } void DoPipelineBarrier(VkCommandBuffer cmd, uint32_t count, VkBufferMemoryBarrier *barriers) { ObjDisp(cmd)->CmdPipelineBarrier(Unwrap(cmd), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, NULL, // global memory barriers count, barriers, // buffer memory barriers 0, NULL); // image memory barriers } void DoPipelineBarrier(VkCommandBuffer cmd, uint32_t count, VkMemoryBarrier *barriers) { ObjDisp(cmd)->CmdPipelineBarrier(Unwrap(cmd), VK_PIPELINE_STAGE_ALL_COMMANDS_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, count, barriers, // global memory barriers 0, NULL, // buffer memory barriers 0, NULL); // image memory barriers } ResourceFormat MakeResourceFormat(VkFormat fmt) { ResourceFormat ret; ret.special = false; ret.specialFormat = SpecialFormat::Unknown; ret.strname = ToStr::Get(fmt).substr(10); // 3 == strlen("VK_FORMAT_") ret.compByteWidth = 0; ret.compCount = 0; ret.compType = CompType::Typeless; ret.srgbCorrected = false; if(fmt == VK_FORMAT_UNDEFINED) { return ret; } switch(fmt) { case VK_FORMAT_R4G4_UNORM_PACK8: ret.special = true; ret.specialFormat = SpecialFormat::R4G4; break; case VK_FORMAT_R4G4B4A4_UNORM_PACK16: case VK_FORMAT_B4G4R4A4_UNORM_PACK16: ret.special = true; ret.specialFormat = SpecialFormat::R4G4B4A4; break; case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: case VK_FORMAT_A2B10G10R10_SNORM_PACK32: case VK_FORMAT_A2R10G10B10_SNORM_PACK32: case VK_FORMAT_A2B10G10R10_USCALED_PACK32: case VK_FORMAT_A2R10G10B10_USCALED_PACK32: case VK_FORMAT_A2B10G10R10_SSCALED_PACK32: case VK_FORMAT_A2R10G10B10_SSCALED_PACK32: case VK_FORMAT_A2B10G10R10_UINT_PACK32: case VK_FORMAT_A2R10G10B10_UINT_PACK32: case VK_FORMAT_A2B10G10R10_SINT_PACK32: case VK_FORMAT_A2R10G10B10_SINT_PACK32: ret.special = true; ret.specialFormat = SpecialFormat::R10G10B10A2; break; case VK_FORMAT_B10G11R11_UFLOAT_PACK32: ret.special = true; ret.specialFormat = SpecialFormat::R11G11B10; break; case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: ret.special = true; ret.specialFormat = SpecialFormat::R9G9B9E5; break; case VK_FORMAT_R5G6B5_UNORM_PACK16: case VK_FORMAT_B5G6R5_UNORM_PACK16: ret.special = true; ret.specialFormat = SpecialFormat::R5G6B5; break; case VK_FORMAT_R5G5B5A1_UNORM_PACK16: case VK_FORMAT_B5G5R5A1_UNORM_PACK16: case VK_FORMAT_A1R5G5B5_UNORM_PACK16: ret.special = true; ret.specialFormat = SpecialFormat::R5G5B5A1; break; case VK_FORMAT_D16_UNORM_S8_UINT: ret.special = true; ret.specialFormat = SpecialFormat::D16S8; break; case VK_FORMAT_D24_UNORM_S8_UINT: ret.special = true; ret.specialFormat = SpecialFormat::D24S8; break; case VK_FORMAT_D32_SFLOAT_S8_UINT: ret.special = true; ret.specialFormat = SpecialFormat::D32S8; break; case VK_FORMAT_BC1_RGB_UNORM_BLOCK: case VK_FORMAT_BC1_RGB_SRGB_BLOCK: case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::BC1; break; case VK_FORMAT_BC2_UNORM_BLOCK: case VK_FORMAT_BC2_SRGB_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::BC2; break; case VK_FORMAT_BC3_UNORM_BLOCK: case VK_FORMAT_BC3_SRGB_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::BC3; break; case VK_FORMAT_BC4_UNORM_BLOCK: case VK_FORMAT_BC4_SNORM_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::BC4; break; case VK_FORMAT_BC5_UNORM_BLOCK: case VK_FORMAT_BC5_SNORM_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::BC5; break; case VK_FORMAT_BC6H_UFLOAT_BLOCK: case VK_FORMAT_BC6H_SFLOAT_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::BC6; break; case VK_FORMAT_BC7_UNORM_BLOCK: case VK_FORMAT_BC7_SRGB_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::BC7; break; case VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::ETC2; break; case VK_FORMAT_EAC_R11_UNORM_BLOCK: case VK_FORMAT_EAC_R11_SNORM_BLOCK: case VK_FORMAT_EAC_R11G11_UNORM_BLOCK: case VK_FORMAT_EAC_R11G11_SNORM_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::EAC; break; case VK_FORMAT_ASTC_4x4_UNORM_BLOCK: case VK_FORMAT_ASTC_4x4_SRGB_BLOCK: case VK_FORMAT_ASTC_5x4_UNORM_BLOCK: case VK_FORMAT_ASTC_5x4_SRGB_BLOCK: case VK_FORMAT_ASTC_5x5_UNORM_BLOCK: case VK_FORMAT_ASTC_5x5_SRGB_BLOCK: case VK_FORMAT_ASTC_6x5_UNORM_BLOCK: case VK_FORMAT_ASTC_6x5_SRGB_BLOCK: case VK_FORMAT_ASTC_6x6_UNORM_BLOCK: case VK_FORMAT_ASTC_6x6_SRGB_BLOCK: case VK_FORMAT_ASTC_8x5_UNORM_BLOCK: case VK_FORMAT_ASTC_8x5_SRGB_BLOCK: case VK_FORMAT_ASTC_8x6_UNORM_BLOCK: case VK_FORMAT_ASTC_8x6_SRGB_BLOCK: case VK_FORMAT_ASTC_8x8_UNORM_BLOCK: case VK_FORMAT_ASTC_8x8_SRGB_BLOCK: case VK_FORMAT_ASTC_10x5_UNORM_BLOCK: case VK_FORMAT_ASTC_10x5_SRGB_BLOCK: case VK_FORMAT_ASTC_10x6_UNORM_BLOCK: case VK_FORMAT_ASTC_10x6_SRGB_BLOCK: case VK_FORMAT_ASTC_10x8_UNORM_BLOCK: case VK_FORMAT_ASTC_10x8_SRGB_BLOCK: case VK_FORMAT_ASTC_10x10_UNORM_BLOCK: case VK_FORMAT_ASTC_10x10_SRGB_BLOCK: case VK_FORMAT_ASTC_12x10_UNORM_BLOCK: case VK_FORMAT_ASTC_12x10_SRGB_BLOCK: case VK_FORMAT_ASTC_12x12_UNORM_BLOCK: case VK_FORMAT_ASTC_12x12_SRGB_BLOCK: ret.special = true; ret.specialFormat = SpecialFormat::ASTC; break; default: break; } switch(fmt) { case VK_FORMAT_B4G4R4A4_UNORM_PACK16: case VK_FORMAT_B5G6R5_UNORM_PACK16: case VK_FORMAT_B5G5R5A1_UNORM_PACK16: case VK_FORMAT_A1R5G5B5_UNORM_PACK16: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SNORM: case VK_FORMAT_B8G8R8A8_USCALED: case VK_FORMAT_B8G8R8A8_SSCALED: case VK_FORMAT_B8G8R8A8_UINT: case VK_FORMAT_B8G8R8A8_SINT: case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2B10G10R10_SNORM_PACK32: case VK_FORMAT_A2B10G10R10_USCALED_PACK32: case VK_FORMAT_A2B10G10R10_SSCALED_PACK32: case VK_FORMAT_A2B10G10R10_UINT_PACK32: case VK_FORMAT_A2B10G10R10_SINT_PACK32: ret.bgraOrder = true; break; default: break; } switch(fmt) { case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_SNORM: case VK_FORMAT_R8_USCALED: case VK_FORMAT_R8_SSCALED: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R8_SRGB: case VK_FORMAT_R16_UNORM: case VK_FORMAT_R16_SNORM: case VK_FORMAT_R16_USCALED: case VK_FORMAT_R16_SSCALED: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16_SFLOAT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32_SFLOAT: case VK_FORMAT_R64_SFLOAT: case VK_FORMAT_D16_UNORM: case VK_FORMAT_X8_D24_UNORM_PACK32: case VK_FORMAT_D32_SFLOAT: case VK_FORMAT_S8_UINT: case VK_FORMAT_BC4_UNORM_BLOCK: case VK_FORMAT_BC4_SNORM_BLOCK: case VK_FORMAT_EAC_R11_UNORM_BLOCK: case VK_FORMAT_EAC_R11_SNORM_BLOCK: ret.compCount = 1; break; case VK_FORMAT_R4G4_UNORM_PACK8: case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8G8_SNORM: case VK_FORMAT_R8G8_USCALED: case VK_FORMAT_R8G8_SSCALED: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8_SRGB: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16_SNORM: case VK_FORMAT_R16G16_USCALED: case VK_FORMAT_R16G16_SSCALED: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16_SFLOAT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32_SFLOAT: case VK_FORMAT_R64G64_SFLOAT: case VK_FORMAT_D16_UNORM_S8_UINT: case VK_FORMAT_D24_UNORM_S8_UINT: case VK_FORMAT_D32_SFLOAT_S8_UINT: case VK_FORMAT_BC5_UNORM_BLOCK: case VK_FORMAT_BC5_SNORM_BLOCK: case VK_FORMAT_EAC_R11G11_UNORM_BLOCK: case VK_FORMAT_EAC_R11G11_SNORM_BLOCK: ret.compCount = 2; break; case VK_FORMAT_R5G6B5_UNORM_PACK16: case VK_FORMAT_R8G8B8_UNORM: case VK_FORMAT_R8G8B8_SNORM: case VK_FORMAT_R8G8B8_USCALED: case VK_FORMAT_R8G8B8_SSCALED: case VK_FORMAT_R8G8B8_UINT: case VK_FORMAT_R8G8B8_SINT: case VK_FORMAT_R8G8B8_SRGB: case VK_FORMAT_R16G16B16_UNORM: case VK_FORMAT_R16G16B16_SNORM: case VK_FORMAT_R16G16B16_USCALED: case VK_FORMAT_R16G16B16_SSCALED: case VK_FORMAT_R16G16B16_UINT: case VK_FORMAT_R16G16B16_SINT: case VK_FORMAT_R16G16B16_SFLOAT: case VK_FORMAT_R32G32B32_UINT: case VK_FORMAT_R32G32B32_SINT: case VK_FORMAT_R32G32B32_SFLOAT: case VK_FORMAT_R64G64B64_SFLOAT: case VK_FORMAT_B10G11R11_UFLOAT_PACK32: case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: case VK_FORMAT_BC1_RGB_UNORM_BLOCK: case VK_FORMAT_BC1_RGB_SRGB_BLOCK: case VK_FORMAT_BC6H_UFLOAT_BLOCK: case VK_FORMAT_BC6H_SFLOAT_BLOCK: case VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: case VK_FORMAT_B5G6R5_UNORM_PACK16: case VK_FORMAT_B8G8R8_UNORM: case VK_FORMAT_B8G8R8_SNORM: case VK_FORMAT_B8G8R8_USCALED: case VK_FORMAT_B8G8R8_SSCALED: case VK_FORMAT_B8G8R8_UINT: case VK_FORMAT_B8G8R8_SINT: case VK_FORMAT_B8G8R8_SRGB: ret.compCount = 3; break; case VK_FORMAT_R4G4B4A4_UNORM_PACK16: case VK_FORMAT_R5G5B5A1_UNORM_PACK16: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SNORM: case VK_FORMAT_R8G8B8A8_USCALED: case VK_FORMAT_R8G8B8A8_SSCALED: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_SNORM_PACK32: case VK_FORMAT_A2R10G10B10_USCALED_PACK32: case VK_FORMAT_A2R10G10B10_SSCALED_PACK32: case VK_FORMAT_A2R10G10B10_UINT_PACK32: case VK_FORMAT_A2R10G10B10_SINT_PACK32: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_R16G16B16A16_SNORM: case VK_FORMAT_R16G16B16A16_USCALED: case VK_FORMAT_R16G16B16A16_SSCALED: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16G16B16A16_SFLOAT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_R32G32B32A32_SINT: case VK_FORMAT_R32G32B32A32_SFLOAT: case VK_FORMAT_R64G64B64A64_SFLOAT: case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: case VK_FORMAT_BC2_UNORM_BLOCK: case VK_FORMAT_BC2_SRGB_BLOCK: case VK_FORMAT_BC3_UNORM_BLOCK: case VK_FORMAT_BC3_SRGB_BLOCK: case VK_FORMAT_BC7_UNORM_BLOCK: case VK_FORMAT_BC7_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: case VK_FORMAT_B4G4R4A4_UNORM_PACK16: case VK_FORMAT_B5G5R5A1_UNORM_PACK16: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SNORM: case VK_FORMAT_B8G8R8A8_USCALED: case VK_FORMAT_B8G8R8A8_SSCALED: case VK_FORMAT_B8G8R8A8_UINT: case VK_FORMAT_B8G8R8A8_SINT: case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_A8B8G8R8_SNORM_PACK32: case VK_FORMAT_A8B8G8R8_USCALED_PACK32: case VK_FORMAT_A8B8G8R8_SSCALED_PACK32: case VK_FORMAT_A8B8G8R8_SINT_PACK32: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2B10G10R10_SNORM_PACK32: case VK_FORMAT_A2B10G10R10_USCALED_PACK32: case VK_FORMAT_A2B10G10R10_SSCALED_PACK32: case VK_FORMAT_A2B10G10R10_UINT_PACK32: case VK_FORMAT_A2B10G10R10_SINT_PACK32: ret.compCount = 4; break; default: break; } switch(fmt) { case VK_FORMAT_R8_SRGB: case VK_FORMAT_R8G8_SRGB: case VK_FORMAT_R8G8B8_SRGB: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_BC1_RGB_SRGB_BLOCK: case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: case VK_FORMAT_BC2_SRGB_BLOCK: case VK_FORMAT_BC3_SRGB_BLOCK: case VK_FORMAT_BC7_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: case VK_FORMAT_ASTC_4x4_SRGB_BLOCK: case VK_FORMAT_ASTC_5x4_SRGB_BLOCK: case VK_FORMAT_ASTC_5x5_SRGB_BLOCK: case VK_FORMAT_ASTC_6x5_SRGB_BLOCK: case VK_FORMAT_ASTC_6x6_SRGB_BLOCK: case VK_FORMAT_ASTC_8x5_SRGB_BLOCK: case VK_FORMAT_ASTC_8x6_SRGB_BLOCK: case VK_FORMAT_ASTC_8x8_SRGB_BLOCK: case VK_FORMAT_ASTC_10x5_SRGB_BLOCK: case VK_FORMAT_ASTC_10x6_SRGB_BLOCK: case VK_FORMAT_ASTC_10x8_SRGB_BLOCK: case VK_FORMAT_ASTC_10x10_SRGB_BLOCK: case VK_FORMAT_ASTC_12x10_SRGB_BLOCK: case VK_FORMAT_ASTC_12x12_SRGB_BLOCK: case VK_FORMAT_B8G8R8_SRGB: case VK_FORMAT_B8G8R8A8_SRGB: ret.srgbCorrected = true; break; default: break; } switch(fmt) { case VK_FORMAT_R4G4_UNORM_PACK8: case VK_FORMAT_R4G4B4A4_UNORM_PACK16: case VK_FORMAT_R5G6B5_UNORM_PACK16: case VK_FORMAT_R5G5B5A1_UNORM_PACK16: case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_SRGB: case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8G8_SRGB: case VK_FORMAT_R8G8B8_UNORM: case VK_FORMAT_R8G8B8_SRGB: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: case VK_FORMAT_R16_UNORM: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16B16_UNORM: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_BC1_RGB_UNORM_BLOCK: case VK_FORMAT_BC1_RGB_SRGB_BLOCK: case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: case VK_FORMAT_BC2_UNORM_BLOCK: case VK_FORMAT_BC2_SRGB_BLOCK: case VK_FORMAT_BC3_UNORM_BLOCK: case VK_FORMAT_BC3_SRGB_BLOCK: case VK_FORMAT_BC4_UNORM_BLOCK: case VK_FORMAT_BC5_UNORM_BLOCK: case VK_FORMAT_BC7_UNORM_BLOCK: case VK_FORMAT_BC7_SRGB_BLOCK: case VK_FORMAT_BC6H_UFLOAT_BLOCK: case VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK: case VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK: case VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK: case VK_FORMAT_EAC_R11_UNORM_BLOCK: case VK_FORMAT_EAC_R11G11_UNORM_BLOCK: case VK_FORMAT_ASTC_4x4_UNORM_BLOCK: case VK_FORMAT_ASTC_4x4_SRGB_BLOCK: case VK_FORMAT_ASTC_5x4_UNORM_BLOCK: case VK_FORMAT_ASTC_5x4_SRGB_BLOCK: case VK_FORMAT_ASTC_5x5_UNORM_BLOCK: case VK_FORMAT_ASTC_5x5_SRGB_BLOCK: case VK_FORMAT_ASTC_6x5_UNORM_BLOCK: case VK_FORMAT_ASTC_6x5_SRGB_BLOCK: case VK_FORMAT_ASTC_6x6_UNORM_BLOCK: case VK_FORMAT_ASTC_6x6_SRGB_BLOCK: case VK_FORMAT_ASTC_8x5_UNORM_BLOCK: case VK_FORMAT_ASTC_8x5_SRGB_BLOCK: case VK_FORMAT_ASTC_8x6_UNORM_BLOCK: case VK_FORMAT_ASTC_8x6_SRGB_BLOCK: case VK_FORMAT_ASTC_8x8_UNORM_BLOCK: case VK_FORMAT_ASTC_8x8_SRGB_BLOCK: case VK_FORMAT_ASTC_10x5_UNORM_BLOCK: case VK_FORMAT_ASTC_10x5_SRGB_BLOCK: case VK_FORMAT_ASTC_10x6_UNORM_BLOCK: case VK_FORMAT_ASTC_10x6_SRGB_BLOCK: case VK_FORMAT_ASTC_10x8_UNORM_BLOCK: case VK_FORMAT_ASTC_10x8_SRGB_BLOCK: case VK_FORMAT_ASTC_10x10_UNORM_BLOCK: case VK_FORMAT_ASTC_10x10_SRGB_BLOCK: case VK_FORMAT_ASTC_12x10_UNORM_BLOCK: case VK_FORMAT_ASTC_12x10_SRGB_BLOCK: case VK_FORMAT_ASTC_12x12_UNORM_BLOCK: case VK_FORMAT_ASTC_12x12_SRGB_BLOCK: case VK_FORMAT_B4G4R4A4_UNORM_PACK16: case VK_FORMAT_B5G5R5A1_UNORM_PACK16: case VK_FORMAT_B5G6R5_UNORM_PACK16: case VK_FORMAT_B8G8R8_UNORM: case VK_FORMAT_B8G8R8_SRGB: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: case VK_FORMAT_A2B10G10R10_UNORM_PACK32: ret.compType = CompType::UNorm; break; case VK_FORMAT_R8_SNORM: case VK_FORMAT_R8G8_SNORM: case VK_FORMAT_R8G8B8_SNORM: case VK_FORMAT_R8G8B8A8_SNORM: case VK_FORMAT_A2R10G10B10_SNORM_PACK32: case VK_FORMAT_R16_SNORM: case VK_FORMAT_R16G16_SNORM: case VK_FORMAT_R16G16B16_SNORM: case VK_FORMAT_R16G16B16A16_SNORM: case VK_FORMAT_BC4_SNORM_BLOCK: case VK_FORMAT_BC5_SNORM_BLOCK: case VK_FORMAT_BC6H_SFLOAT_BLOCK: case VK_FORMAT_EAC_R11_SNORM_BLOCK: case VK_FORMAT_EAC_R11G11_SNORM_BLOCK: case VK_FORMAT_B8G8R8_SNORM: case VK_FORMAT_B8G8R8A8_SNORM: case VK_FORMAT_A8B8G8R8_SNORM_PACK32: case VK_FORMAT_A2B10G10R10_SNORM_PACK32: ret.compType = CompType::SNorm; break; case VK_FORMAT_R8_USCALED: case VK_FORMAT_R8G8_USCALED: case VK_FORMAT_R8G8B8_USCALED: case VK_FORMAT_R8G8B8A8_USCALED: case VK_FORMAT_R16_USCALED: case VK_FORMAT_R16G16_USCALED: case VK_FORMAT_R16G16B16_USCALED: case VK_FORMAT_R16G16B16A16_USCALED: case VK_FORMAT_A2R10G10B10_USCALED_PACK32: case VK_FORMAT_B8G8R8_USCALED: case VK_FORMAT_B8G8R8A8_USCALED: case VK_FORMAT_A2B10G10R10_USCALED_PACK32: ret.compType = CompType::UScaled; break; case VK_FORMAT_R8_SSCALED: case VK_FORMAT_R8G8_SSCALED: case VK_FORMAT_R8G8B8_SSCALED: case VK_FORMAT_R8G8B8A8_SSCALED: case VK_FORMAT_A8B8G8R8_SSCALED_PACK32: case VK_FORMAT_A2R10G10B10_SSCALED_PACK32: case VK_FORMAT_R16_SSCALED: case VK_FORMAT_R16G16_SSCALED: case VK_FORMAT_R16G16B16_SSCALED: case VK_FORMAT_R16G16B16A16_SSCALED: case VK_FORMAT_B8G8R8_SSCALED: case VK_FORMAT_B8G8R8A8_SSCALED: case VK_FORMAT_A2B10G10R10_SSCALED_PACK32: ret.compType = CompType::SScaled; break; case VK_FORMAT_R8_UINT: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8B8_UINT: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_A8B8G8R8_UINT_PACK32: case VK_FORMAT_A2R10G10B10_UINT_PACK32: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16B16_UINT: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R32_UINT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32B32_UINT: case VK_FORMAT_R32G32B32A32_UINT: // Maybe S8 should be identified by something else? case VK_FORMAT_S8_UINT: case VK_FORMAT_B8G8R8_UINT: case VK_FORMAT_B8G8R8A8_UINT: case VK_FORMAT_A2B10G10R10_UINT_PACK32: ret.compType = CompType::UInt; break; case VK_FORMAT_R8_SINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8B8_SINT: case VK_FORMAT_A8B8G8R8_SINT_PACK32: case VK_FORMAT_A2R10G10B10_SINT_PACK32: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16B16_SINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32B32_SINT: case VK_FORMAT_R32G32B32A32_SINT: case VK_FORMAT_B8G8R8_SINT: case VK_FORMAT_B8G8R8A8_SINT: case VK_FORMAT_A2B10G10R10_SINT_PACK32: ret.compType = CompType::SInt; break; case VK_FORMAT_R16_SFLOAT: case VK_FORMAT_R16G16_SFLOAT: case VK_FORMAT_R16G16B16_SFLOAT: case VK_FORMAT_R16G16B16A16_SFLOAT: case VK_FORMAT_R32_SFLOAT: case VK_FORMAT_R32G32_SFLOAT: case VK_FORMAT_R32G32B32_SFLOAT: case VK_FORMAT_R32G32B32A32_SFLOAT: case VK_FORMAT_B10G11R11_UFLOAT_PACK32: case VK_FORMAT_E5B9G9R9_UFLOAT_PACK32: ret.compType = CompType::Float; break; case VK_FORMAT_R64_SFLOAT: case VK_FORMAT_R64G64_SFLOAT: case VK_FORMAT_R64G64B64_SFLOAT: case VK_FORMAT_R64G64B64A64_SFLOAT: ret.compType = CompType::Double; break; case VK_FORMAT_D16_UNORM: case VK_FORMAT_X8_D24_UNORM_PACK32: case VK_FORMAT_D32_SFLOAT: ret.compType = CompType::Depth; break; default: break; } switch(fmt) { case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_SNORM: case VK_FORMAT_R8_USCALED: case VK_FORMAT_R8_SSCALED: case VK_FORMAT_R8_UINT: case VK_FORMAT_R8_SINT: case VK_FORMAT_R8_SRGB: case VK_FORMAT_R8G8_UNORM: case VK_FORMAT_R8G8_SNORM: case VK_FORMAT_R8G8_USCALED: case VK_FORMAT_R8G8_SSCALED: case VK_FORMAT_R8G8_UINT: case VK_FORMAT_R8G8_SINT: case VK_FORMAT_R8G8_SRGB: case VK_FORMAT_R8G8B8_UNORM: case VK_FORMAT_R8G8B8_SNORM: case VK_FORMAT_R8G8B8_USCALED: case VK_FORMAT_R8G8B8_SSCALED: case VK_FORMAT_R8G8B8_UINT: case VK_FORMAT_R8G8B8_SINT: case VK_FORMAT_R8G8B8_SRGB: case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SNORM: case VK_FORMAT_R8G8B8A8_USCALED: case VK_FORMAT_R8G8B8A8_SSCALED: case VK_FORMAT_R8G8B8A8_UINT: case VK_FORMAT_R8G8B8A8_SINT: case VK_FORMAT_R8G8B8A8_SRGB: case VK_FORMAT_S8_UINT: case VK_FORMAT_B8G8R8_UNORM: case VK_FORMAT_B8G8R8_SNORM: case VK_FORMAT_B8G8R8_USCALED: case VK_FORMAT_B8G8R8_SSCALED: case VK_FORMAT_B8G8R8_UINT: case VK_FORMAT_B8G8R8_SINT: case VK_FORMAT_B8G8R8_SRGB: case VK_FORMAT_A8B8G8R8_UNORM_PACK32: case VK_FORMAT_A8B8G8R8_SNORM_PACK32: case VK_FORMAT_A8B8G8R8_USCALED_PACK32: case VK_FORMAT_A8B8G8R8_SSCALED_PACK32: case VK_FORMAT_A8B8G8R8_SINT_PACK32: case VK_FORMAT_A8B8G8R8_SRGB_PACK32: case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SNORM: case VK_FORMAT_B8G8R8A8_USCALED: case VK_FORMAT_B8G8R8A8_SSCALED: case VK_FORMAT_B8G8R8A8_UINT: case VK_FORMAT_B8G8R8A8_SINT: case VK_FORMAT_B8G8R8A8_SRGB: ret.compByteWidth = 1; break; case VK_FORMAT_R16_UNORM: case VK_FORMAT_R16_SNORM: case VK_FORMAT_R16_USCALED: case VK_FORMAT_R16_SSCALED: case VK_FORMAT_R16_UINT: case VK_FORMAT_R16_SINT: case VK_FORMAT_R16_SFLOAT: case VK_FORMAT_R16G16_UNORM: case VK_FORMAT_R16G16_SNORM: case VK_FORMAT_R16G16_USCALED: case VK_FORMAT_R16G16_SSCALED: case VK_FORMAT_R16G16_UINT: case VK_FORMAT_R16G16_SINT: case VK_FORMAT_R16G16_SFLOAT: case VK_FORMAT_R16G16B16_UNORM: case VK_FORMAT_R16G16B16_SNORM: case VK_FORMAT_R16G16B16_USCALED: case VK_FORMAT_R16G16B16_SSCALED: case VK_FORMAT_R16G16B16_UINT: case VK_FORMAT_R16G16B16_SINT: case VK_FORMAT_R16G16B16_SFLOAT: case VK_FORMAT_R16G16B16A16_UNORM: case VK_FORMAT_R16G16B16A16_SNORM: case VK_FORMAT_R16G16B16A16_USCALED: case VK_FORMAT_R16G16B16A16_SSCALED: case VK_FORMAT_R16G16B16A16_UINT: case VK_FORMAT_R16G16B16A16_SINT: case VK_FORMAT_R16G16B16A16_SFLOAT: case VK_FORMAT_D16_UNORM: ret.compByteWidth = 2; break; case VK_FORMAT_X8_D24_UNORM_PACK32: ret.compByteWidth = 3; break; case VK_FORMAT_R32_UINT: case VK_FORMAT_R32_SINT: case VK_FORMAT_R32_SFLOAT: case VK_FORMAT_R32G32_UINT: case VK_FORMAT_R32G32_SINT: case VK_FORMAT_R32G32_SFLOAT: case VK_FORMAT_R32G32B32_UINT: case VK_FORMAT_R32G32B32_SINT: case VK_FORMAT_R32G32B32_SFLOAT: case VK_FORMAT_R32G32B32A32_UINT: case VK_FORMAT_R32G32B32A32_SINT: case VK_FORMAT_R32G32B32A32_SFLOAT: case VK_FORMAT_D32_SFLOAT: ret.compByteWidth = 4; break; case VK_FORMAT_R64_SFLOAT: case VK_FORMAT_R64G64_SFLOAT: case VK_FORMAT_R64G64B64_SFLOAT: case VK_FORMAT_R64G64B64A64_SFLOAT: ret.compByteWidth = 8; break; default: break; } return ret; } VkFormat MakeVkFormat(ResourceFormat fmt) { VkFormat ret = VK_FORMAT_UNDEFINED; if(fmt.special) { switch(fmt.specialFormat) { case SpecialFormat::BC1: { if(fmt.compCount == 3) ret = fmt.srgbCorrected ? VK_FORMAT_BC1_RGB_SRGB_BLOCK : VK_FORMAT_BC1_RGB_UNORM_BLOCK; else ret = fmt.srgbCorrected ? VK_FORMAT_BC1_RGBA_SRGB_BLOCK : VK_FORMAT_BC1_RGBA_UNORM_BLOCK; break; } case SpecialFormat::BC2: ret = fmt.srgbCorrected ? VK_FORMAT_BC2_SRGB_BLOCK : VK_FORMAT_BC2_UNORM_BLOCK; break; case SpecialFormat::BC3: ret = fmt.srgbCorrected ? VK_FORMAT_BC3_SRGB_BLOCK : VK_FORMAT_BC3_UNORM_BLOCK; break; case SpecialFormat::BC4: ret = fmt.compType == CompType::SNorm ? VK_FORMAT_BC4_SNORM_BLOCK : VK_FORMAT_BC4_UNORM_BLOCK; break; case SpecialFormat::BC5: ret = fmt.compType == CompType::SNorm ? VK_FORMAT_BC5_SNORM_BLOCK : VK_FORMAT_BC5_UNORM_BLOCK; break; case SpecialFormat::BC6: ret = fmt.compType == CompType::SNorm ? VK_FORMAT_BC6H_SFLOAT_BLOCK : VK_FORMAT_BC6H_UFLOAT_BLOCK; break; case SpecialFormat::BC7: ret = fmt.srgbCorrected ? VK_FORMAT_BC7_SRGB_BLOCK : VK_FORMAT_BC7_UNORM_BLOCK; break; case SpecialFormat::ETC2: { if(fmt.compCount == 3) ret = fmt.srgbCorrected ? VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK : VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK; else ret = fmt.srgbCorrected ? VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK : VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK; break; } case SpecialFormat::EAC: { if(fmt.compCount == 1) ret = fmt.compType == CompType::SNorm ? VK_FORMAT_EAC_R11_SNORM_BLOCK : VK_FORMAT_EAC_R11_UNORM_BLOCK; else if(fmt.compCount == 2) ret = fmt.compType == CompType::SNorm ? VK_FORMAT_EAC_R11G11_SNORM_BLOCK : VK_FORMAT_EAC_R11G11_UNORM_BLOCK; break; } case SpecialFormat::R10G10B10A2: if(fmt.compType == CompType::UNorm) ret = fmt.bgraOrder ? VK_FORMAT_A2B10G10R10_UNORM_PACK32 : VK_FORMAT_A2R10G10B10_UNORM_PACK32; else if(fmt.compType == CompType::UInt) ret = fmt.bgraOrder ? VK_FORMAT_A2B10G10R10_UINT_PACK32 : VK_FORMAT_A2R10G10B10_UINT_PACK32; else if(fmt.compType == CompType::UScaled) ret = fmt.bgraOrder ? VK_FORMAT_A2B10G10R10_USCALED_PACK32 : VK_FORMAT_A2R10G10B10_USCALED_PACK32; else if(fmt.compType == CompType::SNorm) ret = fmt.bgraOrder ? VK_FORMAT_A2B10G10R10_SNORM_PACK32 : VK_FORMAT_A2R10G10B10_SNORM_PACK32; else if(fmt.compType == CompType::SInt) ret = fmt.bgraOrder ? VK_FORMAT_A2B10G10R10_SINT_PACK32 : VK_FORMAT_A2R10G10B10_SINT_PACK32; else if(fmt.compType == CompType::SScaled) ret = fmt.bgraOrder ? VK_FORMAT_A2B10G10R10_SSCALED_PACK32 : VK_FORMAT_A2R10G10B10_SSCALED_PACK32; break; case SpecialFormat::R11G11B10: ret = VK_FORMAT_B10G11R11_UFLOAT_PACK32; break; case SpecialFormat::R5G6B5: ret = VK_FORMAT_B5G6R5_UNORM_PACK16; break; case SpecialFormat::R5G5B5A1: ret = fmt.bgraOrder ? VK_FORMAT_B5G5R5A1_UNORM_PACK16 : VK_FORMAT_R5G5B5A1_UNORM_PACK16; break; case SpecialFormat::R9G9B9E5: ret = VK_FORMAT_E5B9G9R9_UFLOAT_PACK32; break; case SpecialFormat::R4G4B4A4: ret = fmt.bgraOrder ? VK_FORMAT_R4G4B4A4_UNORM_PACK16 : VK_FORMAT_B4G4R4A4_UNORM_PACK16; break; case SpecialFormat::R4G4: ret = VK_FORMAT_R4G4_UNORM_PACK8; break; case SpecialFormat::D24S8: ret = VK_FORMAT_D24_UNORM_S8_UINT; break; case SpecialFormat::D32S8: ret = VK_FORMAT_D32_SFLOAT_S8_UINT; break; default: RDCERR("Unsupported special format %u", fmt.specialFormat); break; } } else if(fmt.compCount == 4) { if(fmt.srgbCorrected) { ret = fmt.bgraOrder ? VK_FORMAT_B8G8R8A8_SRGB : VK_FORMAT_R8G8B8A8_SRGB; } else if(fmt.compByteWidth == 4) { if(fmt.compType == CompType::Float) ret = VK_FORMAT_R32G32B32A32_SFLOAT; else if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R32G32B32A32_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R32G32B32A32_UINT; else RDCERR("Unrecognised component type"); } else if(fmt.compByteWidth == 2) { if(fmt.compType == CompType::Float) ret = VK_FORMAT_R16G16B16A16_SFLOAT; else if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R16G16B16A16_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R16G16B16A16_UINT; else if(fmt.compType == CompType::SNorm) ret = VK_FORMAT_R16G16B16A16_SNORM; else if(fmt.compType == CompType::UNorm) ret = VK_FORMAT_R16G16B16A16_UNORM; else if(fmt.compType == CompType::SScaled) ret = VK_FORMAT_R16G16B16A16_SSCALED; else if(fmt.compType == CompType::UScaled) ret = VK_FORMAT_R16G16B16A16_USCALED; else RDCERR("Unrecognised component type"); } else if(fmt.compByteWidth == 1) { if(fmt.compType == CompType::SInt) ret = fmt.bgraOrder ? VK_FORMAT_B8G8R8A8_SINT : VK_FORMAT_R8G8B8A8_SINT; else if(fmt.compType == CompType::UInt) ret = fmt.bgraOrder ? VK_FORMAT_B8G8R8A8_UINT : VK_FORMAT_R8G8B8A8_UINT; else if(fmt.compType == CompType::SNorm) ret = fmt.bgraOrder ? VK_FORMAT_B8G8R8A8_SNORM : VK_FORMAT_R8G8B8A8_SNORM; else if(fmt.compType == CompType::UNorm) ret = fmt.bgraOrder ? VK_FORMAT_B8G8R8A8_UNORM : VK_FORMAT_R8G8B8A8_UNORM; else if(fmt.compType == CompType::SScaled) ret = fmt.bgraOrder ? VK_FORMAT_B8G8R8A8_SSCALED : VK_FORMAT_R8G8B8A8_SSCALED; else if(fmt.compType == CompType::UScaled) ret = fmt.bgraOrder ? VK_FORMAT_B8G8R8A8_USCALED : VK_FORMAT_R8G8B8A8_USCALED; else RDCERR("Unrecognised component type"); } else { RDCERR("Unrecognised 4-component byte width: %d", fmt.compByteWidth); } } else if(fmt.compCount == 3) { if(fmt.srgbCorrected) { ret = VK_FORMAT_R8G8B8_SRGB; } else if(fmt.compByteWidth == 4) { if(fmt.compType == CompType::Float) ret = VK_FORMAT_R32G32B32_SFLOAT; else if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R32G32B32_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R32G32B32_UINT; else RDCERR("Unrecognised component type"); } else if(fmt.compByteWidth == 2) { if(fmt.compType == CompType::Float) ret = VK_FORMAT_R16G16B16_SFLOAT; else if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R16G16B16_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R16G16B16_UINT; else if(fmt.compType == CompType::SNorm) ret = VK_FORMAT_R16G16B16_SNORM; else if(fmt.compType == CompType::UNorm) ret = VK_FORMAT_R16G16B16_UNORM; else if(fmt.compType == CompType::SScaled) ret = VK_FORMAT_R16G16B16_SSCALED; else if(fmt.compType == CompType::UScaled) ret = VK_FORMAT_R16G16B16_USCALED; else RDCERR("Unrecognised component type"); } else if(fmt.compByteWidth == 1) { if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R8G8B8_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R8G8B8_UINT; else if(fmt.compType == CompType::SNorm) ret = VK_FORMAT_R8G8B8_SNORM; else if(fmt.compType == CompType::UNorm) ret = VK_FORMAT_R8G8B8_UNORM; else if(fmt.compType == CompType::SScaled) ret = VK_FORMAT_R8G8B8_SSCALED; else if(fmt.compType == CompType::UScaled) ret = VK_FORMAT_R8G8B8_USCALED; else RDCERR("Unrecognised component type"); } else { RDCERR("Unrecognised 3-component byte width: %d", fmt.compByteWidth); } } else if(fmt.compCount == 2) { if(fmt.compByteWidth == 4) { if(fmt.compType == CompType::Float) ret = VK_FORMAT_R32G32_SFLOAT; else if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R32G32_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R32G32_UINT; else RDCERR("Unrecognised component type"); } else if(fmt.compByteWidth == 2) { if(fmt.compType == CompType::Float) ret = VK_FORMAT_R16G16_SFLOAT; else if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R16G16_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R16G16_UINT; else if(fmt.compType == CompType::SNorm) ret = VK_FORMAT_R16G16_SNORM; else if(fmt.compType == CompType::UNorm) ret = VK_FORMAT_R16G16_UNORM; else if(fmt.compType == CompType::SScaled) ret = VK_FORMAT_R16G16_SSCALED; else if(fmt.compType == CompType::UScaled) ret = VK_FORMAT_R16G16_USCALED; else RDCERR("Unrecognised component type"); } else if(fmt.compByteWidth == 1) { if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R8G8_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R8G8_UINT; else if(fmt.compType == CompType::SNorm) ret = VK_FORMAT_R8G8_SNORM; else if(fmt.compType == CompType::UNorm) ret = VK_FORMAT_R8G8_UNORM; else if(fmt.compType == CompType::SScaled) ret = VK_FORMAT_R8G8_SSCALED; else if(fmt.compType == CompType::UScaled) ret = VK_FORMAT_R8G8_USCALED; else RDCERR("Unrecognised component type"); } else { RDCERR("Unrecognised 3-component byte width: %d", fmt.compByteWidth); } } else if(fmt.compCount == 1) { if(fmt.compByteWidth == 4) { if(fmt.compType == CompType::Float) ret = VK_FORMAT_R32_SFLOAT; else if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R32_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R32_UINT; else if(fmt.compType == CompType::Depth) ret = VK_FORMAT_D32_SFLOAT; else RDCERR("Unrecognised component type"); } else if(fmt.compByteWidth == 2) { if(fmt.compType == CompType::Float) ret = VK_FORMAT_R16_SFLOAT; else if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R16_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R16_UINT; else if(fmt.compType == CompType::SNorm) ret = VK_FORMAT_R16_SNORM; else if(fmt.compType == CompType::UNorm) ret = VK_FORMAT_R16_UNORM; else if(fmt.compType == CompType::Depth) ret = VK_FORMAT_D16_UNORM; else if(fmt.compType == CompType::UScaled) ret = VK_FORMAT_R16_USCALED; else if(fmt.compType == CompType::SScaled) ret = VK_FORMAT_R16_SSCALED; else RDCERR("Unrecognised component type"); } else if(fmt.compByteWidth == 1) { if(fmt.compType == CompType::SInt) ret = VK_FORMAT_R8_SINT; else if(fmt.compType == CompType::UInt) ret = VK_FORMAT_R8_UINT; else if(fmt.compType == CompType::SNorm) ret = VK_FORMAT_R8_SNORM; else if(fmt.compType == CompType::UNorm) ret = VK_FORMAT_R8_UNORM; else if(fmt.compType == CompType::UScaled) ret = VK_FORMAT_R8_USCALED; else if(fmt.compType == CompType::SScaled) ret = VK_FORMAT_R8_SSCALED; else RDCERR("Unrecognised component type"); } else { RDCERR("Unrecognised 3-component byte width: %d", fmt.compByteWidth); } } else { RDCERR("Unrecognised component count: %d", fmt.compCount); } if(ret == VK_FORMAT_UNDEFINED) RDCERR("No known vulkan format corresponding to resource format!"); return ret; } Topology MakePrimitiveTopology(VkPrimitiveTopology Topo, uint32_t patchControlPoints) { switch(Topo) { default: break; case VK_PRIMITIVE_TOPOLOGY_POINT_LIST: return Topology::PointList; break; case VK_PRIMITIVE_TOPOLOGY_LINE_LIST: return Topology::LineList; break; case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP: return Topology::LineStrip; break; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST: return Topology::TriangleList; break; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP: return Topology::TriangleStrip; break; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN: return Topology::TriangleFan; break; case VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY: return Topology::LineList_Adj; break; case VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY: return Topology::LineStrip_Adj; break; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY: return Topology::TriangleList_Adj; break; case VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY: return Topology::TriangleStrip_Adj; break; case VK_PRIMITIVE_TOPOLOGY_PATCH_LIST: return PatchList_Topology(patchControlPoints); break; } return Topology::Unknown; } VkPrimitiveTopology MakeVkPrimitiveTopology(Topology Topo) { switch(Topo) { case Topology::LineLoop: RDCWARN("Unsupported primitive topology on Vulkan: %x", Topo); break; default: return VK_PRIMITIVE_TOPOLOGY_MAX_ENUM; case Topology::PointList: return VK_PRIMITIVE_TOPOLOGY_POINT_LIST; case Topology::LineStrip: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP; case Topology::LineList: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST; case Topology::LineStrip_Adj: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case Topology::LineList_Adj: return VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY; case Topology::TriangleStrip: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP; case Topology::TriangleFan: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; case Topology::TriangleList: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; case Topology::TriangleStrip_Adj: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; case Topology::TriangleList_Adj: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case Topology::PatchList_1CPs: case Topology::PatchList_2CPs: case Topology::PatchList_3CPs: case Topology::PatchList_4CPs: case Topology::PatchList_5CPs: case Topology::PatchList_6CPs: case Topology::PatchList_7CPs: case Topology::PatchList_8CPs: case Topology::PatchList_9CPs: case Topology::PatchList_10CPs: case Topology::PatchList_11CPs: case Topology::PatchList_12CPs: case Topology::PatchList_13CPs: case Topology::PatchList_14CPs: case Topology::PatchList_15CPs: case Topology::PatchList_16CPs: case Topology::PatchList_17CPs: case Topology::PatchList_18CPs: case Topology::PatchList_19CPs: case Topology::PatchList_20CPs: case Topology::PatchList_21CPs: case Topology::PatchList_22CPs: case Topology::PatchList_23CPs: case Topology::PatchList_24CPs: case Topology::PatchList_25CPs: case Topology::PatchList_26CPs: case Topology::PatchList_27CPs: case Topology::PatchList_28CPs: case Topology::PatchList_29CPs: case Topology::PatchList_30CPs: case Topology::PatchList_31CPs: case Topology::PatchList_32CPs: return VK_PRIMITIVE_TOPOLOGY_PATCH_LIST; } return VK_PRIMITIVE_TOPOLOGY_MAX_ENUM; } AddressMode MakeAddressMode(VkSamplerAddressMode addr) { switch(addr) { case VK_SAMPLER_ADDRESS_MODE_REPEAT: return AddressMode::Wrap; case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT: return AddressMode::Mirror; case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE: return AddressMode::ClampEdge; case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER: return AddressMode::ClampBorder; case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE: return AddressMode::MirrorOnce; default: break; } return AddressMode::Wrap; } void MakeBorderColor(VkBorderColor border, FloatVector *BorderColor) { // we don't distinguish float/int, assume it matches switch(border) { case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK: case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK: *BorderColor = FloatVector(0.0f, 0.0f, 0.0f, 0.0f); break; case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK: case VK_BORDER_COLOR_INT_OPAQUE_BLACK: *BorderColor = FloatVector(0.0f, 0.0f, 0.0f, 1.0f); break; case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE: case VK_BORDER_COLOR_INT_OPAQUE_WHITE: *BorderColor = FloatVector(1.0f, 1.0f, 1.0f, 1.0f); break; default: memset(BorderColor, 0, sizeof(FloatVector)); break; } } CompareFunc MakeCompareFunc(VkCompareOp func) { switch(func) { case VK_COMPARE_OP_NEVER: return CompareFunc::Never; case VK_COMPARE_OP_LESS: return CompareFunc::Less; case VK_COMPARE_OP_EQUAL: return CompareFunc::Equal; case VK_COMPARE_OP_LESS_OR_EQUAL: return CompareFunc::LessEqual; case VK_COMPARE_OP_GREATER: return CompareFunc::Greater; case VK_COMPARE_OP_NOT_EQUAL: return CompareFunc::NotEqual; case VK_COMPARE_OP_GREATER_OR_EQUAL: return CompareFunc::GreaterEqual; case VK_COMPARE_OP_ALWAYS: return CompareFunc::AlwaysTrue; default: break; } return CompareFunc::AlwaysTrue; } static FilterMode MakeFilterMode(VkFilter f) { switch(f) { case VK_FILTER_NEAREST: return FilterMode::Point; case VK_FILTER_LINEAR: return FilterMode::Linear; case VK_FILTER_CUBIC_IMG: return FilterMode::Cubic; default: break; } return FilterMode::NoFilter; } static FilterMode MakeFilterMode(VkSamplerMipmapMode f) { switch(f) { case VK_SAMPLER_MIPMAP_MODE_NEAREST: return FilterMode::Point; case VK_SAMPLER_MIPMAP_MODE_LINEAR: return FilterMode::Linear; default: break; } return FilterMode::NoFilter; } TextureFilter MakeFilter(VkFilter minFilter, VkFilter magFilter, VkSamplerMipmapMode mipmapMode, bool anisoEnable, bool compareEnable) { TextureFilter ret; if(anisoEnable) { ret.minify = ret.magnify = ret.mip = FilterMode::Anisotropic; } else { ret.minify = MakeFilterMode(minFilter); ret.magnify = MakeFilterMode(magFilter); ret.mip = MakeFilterMode(mipmapMode); } ret.func = compareEnable ? FilterFunc::Comparison : FilterFunc::Normal; return ret; } LogicOp MakeLogicOp(VkLogicOp op) { switch(op) { case VK_LOGIC_OP_CLEAR: return LogicOp::Clear; case VK_LOGIC_OP_AND: return LogicOp::And; case VK_LOGIC_OP_AND_REVERSE: return LogicOp::AndReverse; case VK_LOGIC_OP_COPY: return LogicOp::Copy; case VK_LOGIC_OP_AND_INVERTED: return LogicOp::AndInverted; case VK_LOGIC_OP_NO_OP: return LogicOp::NoOp; case VK_LOGIC_OP_XOR: return LogicOp::Xor; case VK_LOGIC_OP_OR: return LogicOp::Or; case VK_LOGIC_OP_NOR: return LogicOp::Nor; case VK_LOGIC_OP_EQUIVALENT: return LogicOp::Equivalent; case VK_LOGIC_OP_INVERT: return LogicOp::Invert; case VK_LOGIC_OP_OR_REVERSE: return LogicOp::OrReverse; case VK_LOGIC_OP_COPY_INVERTED: return LogicOp::CopyInverted; case VK_LOGIC_OP_OR_INVERTED: return LogicOp::OrInverted; case VK_LOGIC_OP_NAND: return LogicOp::Nand; case VK_LOGIC_OP_SET: return LogicOp::Set; default: break; } return LogicOp::NoOp; } BlendMultiplier MakeBlendMultiplier(VkBlendFactor blend) { switch(blend) { case VK_BLEND_FACTOR_ZERO: return BlendMultiplier::Zero; case VK_BLEND_FACTOR_ONE: return BlendMultiplier::One; case VK_BLEND_FACTOR_SRC_COLOR: return BlendMultiplier::SrcCol; case VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR: return BlendMultiplier::InvSrcCol; case VK_BLEND_FACTOR_DST_COLOR: return BlendMultiplier::DstCol; case VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR: return BlendMultiplier::InvDstCol; case VK_BLEND_FACTOR_SRC_ALPHA: return BlendMultiplier::SrcAlpha; case VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA: return BlendMultiplier::InvSrcAlpha; case VK_BLEND_FACTOR_DST_ALPHA: return BlendMultiplier::DstAlpha; case VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA: return BlendMultiplier::InvDstAlpha; case VK_BLEND_FACTOR_CONSTANT_COLOR: return BlendMultiplier::FactorRGB; case VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR: return BlendMultiplier::InvFactorRGB; case VK_BLEND_FACTOR_CONSTANT_ALPHA: return BlendMultiplier::FactorAlpha; case VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA: return BlendMultiplier::InvFactorAlpha; case VK_BLEND_FACTOR_SRC_ALPHA_SATURATE: return BlendMultiplier::SrcAlphaSat; case VK_BLEND_FACTOR_SRC1_COLOR: return BlendMultiplier::Src1Col; case VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR: return BlendMultiplier::InvSrc1Col; case VK_BLEND_FACTOR_SRC1_ALPHA: return BlendMultiplier::Src1Alpha; case VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA: return BlendMultiplier::InvSrc1Alpha; default: break; } return BlendMultiplier::One; } BlendOp MakeBlendOp(VkBlendOp op) { // Need to update this when we support VK_EXT_blend_operation_advanced switch(op) { case VK_BLEND_OP_ADD: return BlendOp::Add; case VK_BLEND_OP_SUBTRACT: return BlendOp::Subtract; case VK_BLEND_OP_REVERSE_SUBTRACT: return BlendOp::ReversedSubtract; case VK_BLEND_OP_MIN: return BlendOp::Minimum; case VK_BLEND_OP_MAX: return BlendOp::Maximum; default: break; } return BlendOp::Add; } StencilOp MakeStencilOp(VkStencilOp op) { switch(op) { case VK_STENCIL_OP_KEEP: return StencilOp::Keep; case VK_STENCIL_OP_ZERO: return StencilOp::Zero; case VK_STENCIL_OP_REPLACE: return StencilOp::Replace; case VK_STENCIL_OP_INCREMENT_AND_CLAMP: return StencilOp::IncSat; case VK_STENCIL_OP_DECREMENT_AND_CLAMP: return StencilOp::DecSat; case VK_STENCIL_OP_INVERT: return StencilOp::Invert; case VK_STENCIL_OP_INCREMENT_AND_WRAP: return StencilOp::IncWrap; case VK_STENCIL_OP_DECREMENT_AND_WRAP: return StencilOp::DecWrap; default: break; } return StencilOp::Keep; } // we cast to this type when serialising as a placeholder indicating that // the given flags field doesn't have any bits defined enum VkFlagWithNoBits { FlagWithNoBits_Dummy_Bit = 1, }; template <> string ToStrHelper<false, VkResourceType>::Get(const VkResourceType &el) { switch(el) { TOSTR_CASE_STRINGIZE(eResUnknown) TOSTR_CASE_STRINGIZE(eResPhysicalDevice) TOSTR_CASE_STRINGIZE(eResInstance) TOSTR_CASE_STRINGIZE(eResDevice) TOSTR_CASE_STRINGIZE(eResQueue) TOSTR_CASE_STRINGIZE(eResDeviceMemory) TOSTR_CASE_STRINGIZE(eResBuffer) TOSTR_CASE_STRINGIZE(eResBufferView) TOSTR_CASE_STRINGIZE(eResImage) TOSTR_CASE_STRINGIZE(eResImageView) TOSTR_CASE_STRINGIZE(eResFramebuffer) TOSTR_CASE_STRINGIZE(eResRenderPass) TOSTR_CASE_STRINGIZE(eResShaderModule) TOSTR_CASE_STRINGIZE(eResPipelineCache) TOSTR_CASE_STRINGIZE(eResPipelineLayout) TOSTR_CASE_STRINGIZE(eResPipeline) TOSTR_CASE_STRINGIZE(eResSampler) TOSTR_CASE_STRINGIZE(eResDescriptorPool) TOSTR_CASE_STRINGIZE(eResDescriptorSetLayout) TOSTR_CASE_STRINGIZE(eResDescriptorSet) TOSTR_CASE_STRINGIZE(eResCommandPool) TOSTR_CASE_STRINGIZE(eResCommandBuffer) TOSTR_CASE_STRINGIZE(eResFence) TOSTR_CASE_STRINGIZE(eResEvent) TOSTR_CASE_STRINGIZE(eResQueryPool) TOSTR_CASE_STRINGIZE(eResSemaphore) TOSTR_CASE_STRINGIZE(eResSwapchain) TOSTR_CASE_STRINGIZE(eResSurface) default: break; } return StringFormat::Fmt("VkResourceType<%d>", el); } template <> string ToStrHelper<false, VkQueueFlagBits>::Get(const VkQueueFlagBits &el) { string ret; if(el & VK_QUEUE_GRAPHICS_BIT) ret += " | VK_QUEUE_GRAPHICS_BIT"; if(el & VK_QUEUE_COMPUTE_BIT) ret += " | VK_QUEUE_COMPUTE_BIT"; if(el & VK_QUEUE_TRANSFER_BIT) ret += " | VK_QUEUE_TRANSFER_BIT"; if(el & VK_QUEUE_SPARSE_BINDING_BIT) ret += " | VK_QUEUE_SPARSE_BINDING_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkFlagWithNoBits>::Get(const VkFlagWithNoBits &el) { if(el != 0) return StringFormat::Fmt("Invalid bits set: %x", el); return ""; } template <> string ToStrHelper<false, VkPipelineCreateFlagBits>::Get(const VkPipelineCreateFlagBits &el) { string ret; if(el & VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT) ret += " | VK_PIPELINE_CREATE_DISABLE_OPTIMIZATION_BIT"; if(el & VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT) ret += " | VK_PIPELINE_CREATE_ALLOW_DERIVATIVES_BIT"; if(el & VK_PIPELINE_CREATE_DERIVATIVE_BIT) ret += " | VK_PIPELINE_CREATE_DERIVATIVE_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkPipelineStageFlagBits>::Get(const VkPipelineStageFlagBits &el) { string ret; if(el & VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT) ret += " | VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT"; if(el & VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT) ret += " | VK_PIPELINE_STAGE_DRAW_INDIRECT_BIT"; if(el & VK_PIPELINE_STAGE_VERTEX_INPUT_BIT) ret += " | VK_PIPELINE_STAGE_VERTEX_INPUT_BIT"; if(el & VK_PIPELINE_STAGE_VERTEX_SHADER_BIT) ret += " | VK_PIPELINE_STAGE_VERTEX_SHADER_BIT"; if(el & VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT) ret += " | VK_PIPELINE_STAGE_TESSELLATION_CONTROL_SHADER_BIT"; if(el & VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT) ret += " | VK_PIPELINE_STAGE_TESSELLATION_EVALUATION_SHADER_BIT"; if(el & VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT) ret += " | VK_PIPELINE_STAGE_GEOMETRY_SHADER_BIT"; if(el & VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT) ret += " | VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT"; if(el & VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT) ret += " | VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT"; if(el & VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT) ret += " | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT"; if(el & VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT) ret += " | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT"; if(el & VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT) ret += " | VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT"; if(el & VK_PIPELINE_STAGE_TRANSFER_BIT) ret += " | VK_PIPELINE_STAGE_TRANSFER_BIT"; if(el & VK_PIPELINE_STAGE_HOST_BIT) ret += " | VK_PIPELINE_STAGE_HOST_BIT"; if(el & VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT) ret += " | VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT"; if(el & VK_PIPELINE_STAGE_ALL_COMMANDS_BIT) ret += " | VK_PIPELINE_STAGE_ALL_COMMANDS_BIT"; if(el & VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX) ret += " | VK_PIPELINE_STAGE_COMMAND_PROCESS_BIT_NVX"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkBufferUsageFlagBits>::Get(const VkBufferUsageFlagBits &el) { string ret = ""; if(el & VK_BUFFER_USAGE_TRANSFER_SRC_BIT) ret += " | VK_BUFFER_USAGE_TRANSFER_SRC_BIT"; if(el & VK_BUFFER_USAGE_TRANSFER_DST_BIT) ret += " | VK_BUFFER_USAGE_TRANSFER_DST_BIT"; if(el & VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT) ret += " | VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT"; if(el & VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT) ret += " | VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT"; if(el & VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT) ret += " | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT"; if(el & VK_BUFFER_USAGE_STORAGE_BUFFER_BIT) ret += " | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT"; if(el & VK_BUFFER_USAGE_INDEX_BUFFER_BIT) ret += " | VK_BUFFER_USAGE_INDEX_BUFFER_BIT"; if(el & VK_BUFFER_USAGE_VERTEX_BUFFER_BIT) ret += " | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT"; if(el & VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT) ret += " | VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkImageUsageFlagBits>::Get(const VkImageUsageFlagBits &el) { string ret = ""; if(el & VK_IMAGE_USAGE_TRANSFER_SRC_BIT) ret += " | VK_IMAGE_USAGE_TRANSFER_SRC_BIT"; if(el & VK_IMAGE_USAGE_TRANSFER_DST_BIT) ret += " | VK_IMAGE_USAGE_TRANSFER_DST_BIT"; if(el & VK_IMAGE_USAGE_SAMPLED_BIT) ret += " | VK_IMAGE_USAGE_SAMPLED_BIT"; if(el & VK_IMAGE_USAGE_STORAGE_BIT) ret += " | VK_IMAGE_USAGE_STORAGE_BIT"; if(el & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) ret += " | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT"; if(el & VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT) ret += " | VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT"; if(el & VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT) ret += " | VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT"; if(el & VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT) ret += " | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkBufferCreateFlagBits>::Get(const VkBufferCreateFlagBits &el) { string ret; if(el & VK_BUFFER_CREATE_SPARSE_BINDING_BIT) ret += " | VK_BUFFER_CREATE_SPARSE_BINDING_BIT"; if(el & VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT) ret += " | VK_BUFFER_CREATE_SPARSE_RESIDENCY_BIT"; if(el & VK_BUFFER_CREATE_SPARSE_ALIASED_BIT) ret += " | VK_BUFFER_CREATE_SPARSE_ALIASED_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkImageCreateFlagBits>::Get(const VkImageCreateFlagBits &el) { string ret; if(el & VK_IMAGE_CREATE_SPARSE_BINDING_BIT) ret += " | VK_IMAGE_CREATE_SPARSE_BINDING_BIT"; if(el & VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT) ret += " | VK_IMAGE_CREATE_SPARSE_RESIDENCY_BIT"; if(el & VK_IMAGE_CREATE_SPARSE_ALIASED_BIT) ret += " | VK_IMAGE_CREATE_SPARSE_ALIASED_BIT"; if(el & VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT) ret += " | VK_IMAGE_CREATE_MUTABLE_FORMAT_BIT"; if(el & VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT) ret += " | VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT"; if(el & VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR) ret += " | VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkSparseMemoryBindFlagBits>::Get(const VkSparseMemoryBindFlagBits &el) { string ret; if(el & VK_SPARSE_MEMORY_BIND_METADATA_BIT) ret += " | VK_SPARSE_MEMORY_BIND_METADATA_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkCommandPoolCreateFlagBits>::Get(const VkCommandPoolCreateFlagBits &el) { string ret; if(el & VK_COMMAND_POOL_CREATE_TRANSIENT_BIT) ret += " | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT"; if(el & VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT) ret += " | VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkCommandPoolResetFlagBits>::Get(const VkCommandPoolResetFlagBits &el) { string ret; if(el & VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT) ret += " | VK_COMMAND_POOL_RESET_RELEASE_RESOURCES_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkCommandBufferUsageFlagBits>::Get(const VkCommandBufferUsageFlagBits &el) { string ret; if(el & VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT) ret += " | VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT"; if(el & VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT) ret += " | VK_COMMAND_BUFFER_USAGE_RENDER_PASS_CONTINUE_BIT"; if(el & VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT) ret += " | VK_COMMAND_BUFFER_USAGE_SIMULTANEOUS_USE_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkDescriptorPoolCreateFlagBits>::Get(const VkDescriptorPoolCreateFlagBits &el) { string ret; if(el & VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT) ret += " | VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkFenceCreateFlagBits>::Get(const VkFenceCreateFlagBits &el) { string ret; if(el & VK_FENCE_CREATE_SIGNALED_BIT) ret += " | VK_FENCE_CREATE_SIGNALED_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkQueryPipelineStatisticFlagBits>::Get( const VkQueryPipelineStatisticFlagBits &el) { string ret; if(el & VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_VERTICES_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_INPUT_ASSEMBLY_PRIMITIVES_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_VERTEX_SHADER_INVOCATIONS_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_INVOCATIONS_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_GEOMETRY_SHADER_PRIMITIVES_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_INVOCATIONS_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_CLIPPING_PRIMITIVES_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_FRAGMENT_SHADER_INVOCATIONS_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_CONTROL_SHADER_PATCHES_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_TESSELLATION_EVALUATION_SHADER_INVOCATIONS_BIT"; if(el & VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT) ret += " | VK_QUERY_PIPELINE_STATISTIC_COMPUTE_SHADER_INVOCATIONS_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkQueryControlFlagBits>::Get(const VkQueryControlFlagBits &el) { string ret; if(el & VK_QUERY_CONTROL_PRECISE_BIT) ret += " | VK_QUERY_CONTROL_PRECISE_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkQueryResultFlagBits>::Get(const VkQueryResultFlagBits &el) { string ret; if(el & VK_QUERY_RESULT_64_BIT) ret += " | VK_QUERY_RESULT_64_BIT"; if(el & VK_QUERY_RESULT_WAIT_BIT) ret += " | VK_QUERY_RESULT_WAIT_BIT"; if(el & VK_QUERY_RESULT_WITH_AVAILABILITY_BIT) ret += " | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT"; if(el & VK_QUERY_RESULT_PARTIAL_BIT) ret += " | VK_QUERY_RESULT_PARTIAL_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkAttachmentDescriptionFlagBits>::Get(const VkAttachmentDescriptionFlagBits &el) { string ret; if(el & VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT) ret += " | VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkSampleCountFlagBits>::Get(const VkSampleCountFlagBits &el) { string ret; if(el & VK_SAMPLE_COUNT_1_BIT) ret += " | VK_SAMPLE_COUNT_1_BIT"; if(el & VK_SAMPLE_COUNT_2_BIT) ret += " | VK_SAMPLE_COUNT_2_BIT"; if(el & VK_SAMPLE_COUNT_4_BIT) ret += " | VK_SAMPLE_COUNT_4_BIT"; if(el & VK_SAMPLE_COUNT_8_BIT) ret += " | VK_SAMPLE_COUNT_8_BIT"; if(el & VK_SAMPLE_COUNT_16_BIT) ret += " | VK_SAMPLE_COUNT_16_BIT"; if(el & VK_SAMPLE_COUNT_32_BIT) ret += " | VK_SAMPLE_COUNT_32_BIT"; if(el & VK_SAMPLE_COUNT_64_BIT) ret += " | VK_SAMPLE_COUNT_64_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkImageAspectFlagBits>::Get(const VkImageAspectFlagBits &el) { string ret; if(el & VK_IMAGE_ASPECT_COLOR_BIT) ret += " | VK_IMAGE_ASPECT_COLOR_BIT"; if(el & VK_IMAGE_ASPECT_DEPTH_BIT) ret += " | VK_IMAGE_ASPECT_DEPTH_BIT"; if(el & VK_IMAGE_ASPECT_STENCIL_BIT) ret += " | VK_IMAGE_ASPECT_STENCIL_BIT"; if(el & VK_IMAGE_ASPECT_METADATA_BIT) ret += " | VK_IMAGE_ASPECT_METADATA_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkDependencyFlagBits>::Get(const VkDependencyFlagBits &el) { string ret; if(el & VK_DEPENDENCY_BY_REGION_BIT) ret += " | VK_DEPENDENCY_BY_REGION_BIT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkShaderStageFlagBits>::Get(const VkShaderStageFlagBits &el) { string ret; if(el == VK_SHADER_STAGE_ALL_GRAPHICS) return "VK_SHADER_STAGE_ALL_GRAPHICS"; if(el == VK_SHADER_STAGE_ALL) return "VK_SHADER_STAGE_ALL"; if(el & VK_SHADER_STAGE_VERTEX_BIT) ret += " | VK_SHADER_STAGE_VERTEX"; if(el & VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT) ret += " | VK_SHADER_STAGE_TESSELLATION_CONTROL"; if(el & VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT) ret += " | VK_SHADER_STAGE_TESSELLATION_EVALUATION"; if(el & VK_SHADER_STAGE_GEOMETRY_BIT) ret += " | VK_SHADER_STAGE_GEOMETRY"; if(el & VK_SHADER_STAGE_FRAGMENT_BIT) ret += " | VK_SHADER_STAGE_FRAGMENT"; if(el & VK_SHADER_STAGE_COMPUTE_BIT) ret += " | VK_SHADER_STAGE_COMPUTE"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkStencilFaceFlagBits>::Get(const VkStencilFaceFlagBits &el) { // technically a bitfield but each combination has a particular meaning if(el == VK_STENCIL_FACE_FRONT_BIT) return "VK_STENCIL_FACE_FRONT"; if(el == VK_STENCIL_FACE_BACK_BIT) return "VK_STENCIL_FACE_BACK"; if(el == VK_STENCIL_FRONT_AND_BACK) return "VK_STENCIL_FRONT_AND_BACK"; if(el == 0) return "VK_STENCIL_FACE_NONE"; return StringFormat::Fmt("VkStencilFaceFlagBits<%d>", el); } template <> string ToStrHelper<false, VkCullModeFlagBits>::Get(const VkCullModeFlagBits &el) { // technically a bitfield but each combination has a particular meaning if(el == VK_CULL_MODE_NONE) return "VK_CULL_MODE_NONE"; if(el == VK_CULL_MODE_FRONT_BIT) return "VK_CULL_MODE_FRONT"; if(el == VK_CULL_MODE_BACK_BIT) return "VK_CULL_MODE_BACK"; if(el == VK_CULL_MODE_FRONT_AND_BACK) return "VK_CULL_MODE_FRONT_AND_BACK"; return StringFormat::Fmt("VkCullModeFlagBits<%d>", el); } template <> string ToStrHelper<false, VkPipelineBindPoint>::Get(const VkPipelineBindPoint &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_PIPELINE_BIND_POINT_COMPUTE) TOSTR_CASE_STRINGIZE(VK_PIPELINE_BIND_POINT_GRAPHICS) default: break; } return StringFormat::Fmt("VkPipelineBindPoint<%d>", el); } template <> string ToStrHelper<false, VkIndexType>::Get(const VkIndexType &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_INDEX_TYPE_UINT16) TOSTR_CASE_STRINGIZE(VK_INDEX_TYPE_UINT32) default: break; } return StringFormat::Fmt("VkIndexType<%d>", el); } template <> string ToStrHelper<false, VkImageType>::Get(const VkImageType &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_IMAGE_TYPE_1D) TOSTR_CASE_STRINGIZE(VK_IMAGE_TYPE_2D) TOSTR_CASE_STRINGIZE(VK_IMAGE_TYPE_3D) default: break; } return StringFormat::Fmt("VkImageType<%d>", el); } template <> string ToStrHelper<false, VkImageTiling>::Get(const VkImageTiling &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_IMAGE_TILING_LINEAR) TOSTR_CASE_STRINGIZE(VK_IMAGE_TILING_OPTIMAL) default: break; } return StringFormat::Fmt("VkImageTiling<%d>", el); } template <> string ToStrHelper<false, VkImageViewType>::Get(const VkImageViewType &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_IMAGE_VIEW_TYPE_1D) TOSTR_CASE_STRINGIZE(VK_IMAGE_VIEW_TYPE_2D) TOSTR_CASE_STRINGIZE(VK_IMAGE_VIEW_TYPE_3D) TOSTR_CASE_STRINGIZE(VK_IMAGE_VIEW_TYPE_CUBE) TOSTR_CASE_STRINGIZE(VK_IMAGE_VIEW_TYPE_1D_ARRAY) TOSTR_CASE_STRINGIZE(VK_IMAGE_VIEW_TYPE_2D_ARRAY) TOSTR_CASE_STRINGIZE(VK_IMAGE_VIEW_TYPE_CUBE_ARRAY) default: break; } return StringFormat::Fmt("VkImageViewType<%d>", el); } template <> string ToStrHelper<false, VkVertexInputRate>::Get(const VkVertexInputRate &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_VERTEX_INPUT_RATE_VERTEX) TOSTR_CASE_STRINGIZE(VK_VERTEX_INPUT_RATE_INSTANCE) default: break; } return StringFormat::Fmt("VkVertexInputRate<%d>", el); } template <> string ToStrHelper<false, VkPolygonMode>::Get(const VkPolygonMode &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_POLYGON_MODE_FILL) TOSTR_CASE_STRINGIZE(VK_POLYGON_MODE_LINE) TOSTR_CASE_STRINGIZE(VK_POLYGON_MODE_POINT) TOSTR_CASE_STRINGIZE(VK_POLYGON_MODE_FILL_RECTANGLE_NV) default: break; } return StringFormat::Fmt("VkPolygonMode<%d>", el); } template <> string ToStrHelper<false, VkFrontFace>::Get(const VkFrontFace &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_FRONT_FACE_COUNTER_CLOCKWISE) TOSTR_CASE_STRINGIZE(VK_FRONT_FACE_CLOCKWISE) default: break; } return StringFormat::Fmt("VkFrontFace<%d>", el); } template <> string ToStrHelper<false, VkBlendFactor>::Get(const VkBlendFactor &el) { switch(el) { case VK_BLEND_FACTOR_ZERO: return "ZERO"; case VK_BLEND_FACTOR_ONE: return "ONE"; case VK_BLEND_FACTOR_SRC_COLOR: return "SRC_COLOR"; case VK_BLEND_FACTOR_ONE_MINUS_SRC_COLOR: return "INV_SRC_COLOR"; case VK_BLEND_FACTOR_DST_COLOR: return "DST_COLOR"; case VK_BLEND_FACTOR_ONE_MINUS_DST_COLOR: return "INV_DST_COLOR"; case VK_BLEND_FACTOR_SRC_ALPHA: return "SRC_ALPHA"; case VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA: return "INV_SRC_ALPHA"; case VK_BLEND_FACTOR_DST_ALPHA: return "DST_ALPHA"; case VK_BLEND_FACTOR_ONE_MINUS_DST_ALPHA: return "INV_DST_ALPHA"; case VK_BLEND_FACTOR_CONSTANT_COLOR: return "CONST_COLOR"; case VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_COLOR: return "INV_CONST_COLOR"; case VK_BLEND_FACTOR_CONSTANT_ALPHA: return "CONST_ALPHA"; case VK_BLEND_FACTOR_ONE_MINUS_CONSTANT_ALPHA: return "INV_CONST_ALPHA"; case VK_BLEND_FACTOR_SRC_ALPHA_SATURATE: return "SRC_ALPHA_SAT"; case VK_BLEND_FACTOR_SRC1_COLOR: return "SRC1_COLOR"; case VK_BLEND_FACTOR_ONE_MINUS_SRC1_COLOR: return "INV_SRC1_COLOR"; case VK_BLEND_FACTOR_SRC1_ALPHA: return "SRC1_ALPHA"; case VK_BLEND_FACTOR_ONE_MINUS_SRC1_ALPHA: return "INV_SRC1_ALPHA"; default: break; } return StringFormat::Fmt("VkBlendFactor<%d>", el); } template <> string ToStrHelper<false, VkBlendOp>::Get(const VkBlendOp &el) { // Need to update this when we support VK_EXT_blend_operation_advanced switch(el) { case VK_BLEND_OP_ADD: return "ADD"; case VK_BLEND_OP_SUBTRACT: return "SUB"; case VK_BLEND_OP_REVERSE_SUBTRACT: return "REV_SUB"; case VK_BLEND_OP_MIN: return "MIN"; case VK_BLEND_OP_MAX: return "MAX"; default: break; } return StringFormat::Fmt("VkBlendOp<%d>", el); } template <> string ToStrHelper<false, VkDynamicState>::Get(const VkDynamicState &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_VIEWPORT) TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_SCISSOR) TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_LINE_WIDTH) TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_DEPTH_BIAS) TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_BLEND_CONSTANTS) TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_DEPTH_BOUNDS) TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK) TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_STENCIL_WRITE_MASK) TOSTR_CASE_STRINGIZE(VK_DYNAMIC_STATE_STENCIL_REFERENCE) default: break; } return StringFormat::Fmt("VkDynamicState<%d>", el); } template <> string ToStrHelper<false, VkAttachmentLoadOp>::Get(const VkAttachmentLoadOp &el) { switch(el) { case VK_ATTACHMENT_LOAD_OP_LOAD: return "Load"; case VK_ATTACHMENT_LOAD_OP_CLEAR: return "Clear"; case VK_ATTACHMENT_LOAD_OP_DONT_CARE: return "Don't Care"; default: break; } return StringFormat::Fmt("VkAttachmentLoadOp<%d>", el); } template <> string ToStrHelper<false, VkAttachmentStoreOp>::Get(const VkAttachmentStoreOp &el) { switch(el) { case VK_ATTACHMENT_STORE_OP_STORE: return "Store"; case VK_ATTACHMENT_STORE_OP_DONT_CARE: return "Don't Care"; default: break; } return StringFormat::Fmt("VkAttachmentStoreOp<%d>", el); } template <> string ToStrHelper<false, VkStencilOp>::Get(const VkStencilOp &el) { switch(el) { case VK_STENCIL_OP_KEEP: return "KEEP"; case VK_STENCIL_OP_ZERO: return "ZERO"; case VK_STENCIL_OP_REPLACE: return "REPLACE"; case VK_STENCIL_OP_INCREMENT_AND_CLAMP: return "INC_SAT"; case VK_STENCIL_OP_DECREMENT_AND_CLAMP: return "DEC_SAT"; case VK_STENCIL_OP_INVERT: return "INVERT"; case VK_STENCIL_OP_INCREMENT_AND_WRAP: return "INC_WRAP"; case VK_STENCIL_OP_DECREMENT_AND_WRAP: return "DEC_WRAP"; default: break; } return StringFormat::Fmt("VkStencilOp<%d>", el); } template <> string ToStrHelper<false, VkLogicOp>::Get(const VkLogicOp &el) { switch(el) { case VK_LOGIC_OP_CLEAR: return "CLEAR"; case VK_LOGIC_OP_AND: return "AND"; case VK_LOGIC_OP_AND_REVERSE: return "AND_REV"; case VK_LOGIC_OP_COPY: return "COPY"; case VK_LOGIC_OP_AND_INVERTED: return "AND_INV"; case VK_LOGIC_OP_NO_OP: return "NOOP"; case VK_LOGIC_OP_XOR: return "XOR"; case VK_LOGIC_OP_OR: return "OR"; case VK_LOGIC_OP_NOR: return "NOR"; case VK_LOGIC_OP_EQUIVALENT: return "EQUIV"; case VK_LOGIC_OP_INVERT: return "INVERT"; case VK_LOGIC_OP_OR_REVERSE: return "OR_REV"; case VK_LOGIC_OP_COPY_INVERTED: return "COPY_INV"; case VK_LOGIC_OP_OR_INVERTED: return "OR_INV"; case VK_LOGIC_OP_NAND: return "NAND"; case VK_LOGIC_OP_SET: return "SET"; default: break; } return StringFormat::Fmt("VkLogicOp<%d>", el); } template <> string ToStrHelper<false, VkCompareOp>::Get(const VkCompareOp &el) { switch(el) { case VK_COMPARE_OP_NEVER: return "NEVER"; case VK_COMPARE_OP_LESS: return "LESS"; case VK_COMPARE_OP_EQUAL: return "EQUAL"; case VK_COMPARE_OP_LESS_OR_EQUAL: return "LESS_EQUAL"; case VK_COMPARE_OP_GREATER: return "GREATER"; case VK_COMPARE_OP_NOT_EQUAL: return "NOT_EQUAL"; case VK_COMPARE_OP_GREATER_OR_EQUAL: return "GREATER_EQUAL"; case VK_COMPARE_OP_ALWAYS: return "ALWAYS"; default: break; } return StringFormat::Fmt("VkCompareOp<%d>", el); } template <> string ToStrHelper<false, VkFilter>::Get(const VkFilter &el) { switch(el) { case VK_FILTER_NEAREST: return "NEAREST"; case VK_FILTER_LINEAR: return "LINEAR"; default: break; } return StringFormat::Fmt("VkFilter<%d>", el); } template <> string ToStrHelper<false, VkSamplerMipmapMode>::Get(const VkSamplerMipmapMode &el) { switch(el) { case VK_SAMPLER_MIPMAP_MODE_NEAREST: return "NEAREST"; case VK_SAMPLER_MIPMAP_MODE_LINEAR: return "LINEAR"; default: break; } return StringFormat::Fmt("VkTexMipmapMode<%d>", el); } template <> string ToStrHelper<false, VkSamplerAddressMode>::Get(const VkSamplerAddressMode &el) { switch(el) { case VK_SAMPLER_ADDRESS_MODE_REPEAT: return "WRAP"; case VK_SAMPLER_ADDRESS_MODE_MIRRORED_REPEAT: return "MIRROR_WRAP"; case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE: return "CLAMP_EDGE"; case VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER: return "CLAMP_BORDER"; case VK_SAMPLER_ADDRESS_MODE_MIRROR_CLAMP_TO_EDGE: return "MIRROR_CLAMP"; default: break; } return StringFormat::Fmt("VkSamplerAddressMode<%d>", el); } template <> string ToStrHelper<false, VkBorderColor>::Get(const VkBorderColor &el) { switch(el) { case VK_BORDER_COLOR_FLOAT_TRANSPARENT_BLACK: return "float(0,0,0,0)"; case VK_BORDER_COLOR_INT_TRANSPARENT_BLACK: return "int(0,0,0,0)"; case VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK: return "float(0,0,0,1)"; case VK_BORDER_COLOR_INT_OPAQUE_BLACK: return "int(0,0,0,1)"; case VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE: return "float(1,1,1,1)"; case VK_BORDER_COLOR_INT_OPAQUE_WHITE: return "int(1,1,1,1)"; default: break; } return StringFormat::Fmt("VkBorderColor<%d>", el); } template <> string ToStrHelper<false, VkPrimitiveTopology>::Get(const VkPrimitiveTopology &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_POINT_LIST) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_LINE_LIST) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_LINE_STRIP) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_LINE_LIST_WITH_ADJACENCY) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY) TOSTR_CASE_STRINGIZE(VK_PRIMITIVE_TOPOLOGY_PATCH_LIST) default: break; } return StringFormat::Fmt("VkPrimitiveTopology<%d>", el); } template <> string ToStrHelper<false, VkDescriptorType>::Get(const VkDescriptorType &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_SAMPLER) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) TOSTR_CASE_STRINGIZE(VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) default: break; } return StringFormat::Fmt("VkDescriptorType<%d>", el); } template <> string ToStrHelper<false, VkQueryType>::Get(const VkQueryType &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_QUERY_TYPE_OCCLUSION) TOSTR_CASE_STRINGIZE(VK_QUERY_TYPE_PIPELINE_STATISTICS) TOSTR_CASE_STRINGIZE(VK_QUERY_TYPE_TIMESTAMP) default: break; } return StringFormat::Fmt("VkQueryType<%d>", el); } template <> string ToStrHelper<false, VkPhysicalDeviceType>::Get(const VkPhysicalDeviceType &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_PHYSICAL_DEVICE_TYPE_OTHER) TOSTR_CASE_STRINGIZE(VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU) TOSTR_CASE_STRINGIZE(VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) TOSTR_CASE_STRINGIZE(VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU) TOSTR_CASE_STRINGIZE(VK_PHYSICAL_DEVICE_TYPE_CPU) default: break; } return StringFormat::Fmt("VkPhysicalDeviceType<%d>", el); } template <> string ToStrHelper<false, VkMemoryHeapFlagBits>::Get(const VkMemoryHeapFlagBits &el) { string ret; if(el & VK_MEMORY_HEAP_DEVICE_LOCAL_BIT) ret += " | VK_MEMORY_HEAP_DEVICE_LOCAL_BIT"; if(!ret.empty()) ret = ret.substr(3); if(ret.empty()) return "-"; return ret; } template <> string ToStrHelper<false, VkMemoryPropertyFlagBits>::Get(const VkMemoryPropertyFlagBits &el) { string ret; if(el & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) ret += " | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT"; if(el & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT) ret += " | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT"; if(el & VK_MEMORY_PROPERTY_HOST_COHERENT_BIT) ret += " | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT"; if(el & VK_MEMORY_PROPERTY_HOST_CACHED_BIT) ret += " | VK_MEMORY_PROPERTY_HOST_CACHED_BIT"; if(el & VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT) ret += " | VK_MEMORY_PROPERTY_LAZILY_ALLOCATED_BIT"; if(!ret.empty()) ret = ret.substr(3); else ret = "-"; return ret; } template <> string ToStrHelper<false, VkAccessFlagBits>::Get(const VkAccessFlagBits &el) { string ret; if(el & VK_ACCESS_INDIRECT_COMMAND_READ_BIT) ret += " | VK_ACCESS_INDIRECT_COMMAND_READ_BIT"; if(el & VK_ACCESS_INDEX_READ_BIT) ret += " | VK_ACCESS_INDEX_READ_BIT"; if(el & VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT) ret += " | VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT"; if(el & VK_ACCESS_UNIFORM_READ_BIT) ret += " | VK_ACCESS_UNIFORM_READ_BIT"; if(el & VK_ACCESS_INPUT_ATTACHMENT_READ_BIT) ret += " | VK_ACCESS_INPUT_ATTACHMENT_READ_BIT"; if(el & VK_ACCESS_SHADER_READ_BIT) ret += " | VK_ACCESS_SHADER_READ_BIT"; if(el & VK_ACCESS_SHADER_WRITE_BIT) ret += " | VK_ACCESS_SHADER_WRITE_BIT"; if(el & VK_ACCESS_COLOR_ATTACHMENT_READ_BIT) ret += " | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT"; if(el & VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT) ret += " | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT"; if(el & VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT) ret += " | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT"; if(el & VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT) ret += " | VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT"; if(el & VK_ACCESS_TRANSFER_READ_BIT) ret += " | VK_ACCESS_TRANSFER_READ_BIT"; if(el & VK_ACCESS_TRANSFER_WRITE_BIT) ret += " | VK_ACCESS_TRANSFER_WRITE_BIT"; if(el & VK_ACCESS_HOST_READ_BIT) ret += " | VK_ACCESS_HOST_READ_BIT"; if(el & VK_ACCESS_HOST_WRITE_BIT) ret += " | VK_ACCESS_HOST_WRITE_BIT"; if(el & VK_ACCESS_MEMORY_READ_BIT) ret += " | VK_ACCESS_MEMORY_READ_BIT"; if(el & VK_ACCESS_MEMORY_WRITE_BIT) ret += " | VK_ACCESS_MEMORY_WRITE_BIT"; if(el & VK_ACCESS_COMMAND_PROCESS_READ_BIT_NVX) ret += " | VK_ACCESS_COMMAND_PROCESS_READ_BIT_NVX"; if(el & VK_ACCESS_COMMAND_PROCESS_WRITE_BIT_NVX) ret += " | VK_ACCESS_COMMAND_PROCESS_WRITE_BIT_NVX"; if(el & VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT) ret += " | VK_ACCESS_COLOR_ATTACHMENT_READ_NONCOHERENT_BIT_EXT"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkSharingMode>::Get(const VkSharingMode &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_SHARING_MODE_EXCLUSIVE) TOSTR_CASE_STRINGIZE(VK_SHARING_MODE_CONCURRENT) default: break; } return StringFormat::Fmt("VkSharingMode<%d>", el); } template <> string ToStrHelper<false, VkCommandBufferLevel>::Get(const VkCommandBufferLevel &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_COMMAND_BUFFER_LEVEL_PRIMARY) TOSTR_CASE_STRINGIZE(VK_COMMAND_BUFFER_LEVEL_SECONDARY) default: break; } return StringFormat::Fmt("VkCommandBufferLevel<%d>", el); } template <> string ToStrHelper<false, VkSubpassContents>::Get(const VkSubpassContents &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_SUBPASS_CONTENTS_INLINE) TOSTR_CASE_STRINGIZE(VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS) default: break; } return StringFormat::Fmt("VkSubpassContents<%d>", el); } template <> string ToStrHelper<false, VkImageLayout>::Get(const VkImageLayout &el) { switch(el) { case VK_IMAGE_LAYOUT_UNDEFINED: return "UNDEFINED"; case VK_IMAGE_LAYOUT_GENERAL: return "GENERAL"; case VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: return "COLOR_ATTACHMENT_OPTIMAL"; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: return "DEPTH_STENCIL_ATTACHMENT_OPTIMAL"; case VK_IMAGE_LAYOUT_DEPTH_STENCIL_READ_ONLY_OPTIMAL: return "DEPTH_STENCIL_READ_ONLY_OPTIMAL"; case VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: return "SHADER_READ_ONLY_OPTIMAL"; case VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: return "TRANSFER_SRC_OPTIMAL"; case VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: return "TRANSFER_DST_OPTIMAL"; case VK_IMAGE_LAYOUT_PREINITIALIZED: return "PREINITIALIZED"; case VK_IMAGE_LAYOUT_PRESENT_SRC_KHR: return "PRESENT_SRC_KHR"; case VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR: return "SHARED_PRESENT_SRC_KHR"; default: break; } return StringFormat::Fmt("VkImageLayout<%d>", el); } template <> string ToStrHelper<false, VkStructureType>::Get(const VkStructureType &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_APPLICATION_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SUBMIT_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_BIND_SPARSE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_FENCE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EVENT_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_BARRIER) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PRESENT_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DISPLAY_MODE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DISPLAY_SURFACE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DISPLAY_PRESENT_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_WAYLAND_SURFACE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MIR_SURFACE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_RASTERIZATION_ORDER_AMD) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_NAME_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEBUG_MARKER_OBJECT_TAG_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEBUG_MARKER_MARKER_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_IMAGE_CREATE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_MEMORY_ALLOCATE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_TEXTURE_LOD_GATHER_FORMAT_PROPERTIES_AMD) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_RENDER_PASS_MULTIVIEW_CREATE_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_FEATURES_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PROPERTIES_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_QUEUE_FAMILY_PROPERTIES_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SPARSE_IMAGE_FORMAT_PROPERTIES_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SPARSE_IMAGE_FORMAT_INFO_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_FLAGS_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_BIND_BUFFER_MEMORY_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GROUP_RENDER_PASS_BEGIN_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GROUP_COMMAND_BUFFER_BEGIN_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GROUP_SUBMIT_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GROUP_BIND_SPARSE_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_CAPABILITIES_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_ACQUIRE_NEXT_IMAGE_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GROUP_PRESENT_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GROUP_SWAPCHAIN_CREATE_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_VALIDATION_FLAGS_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_VI_SURFACE_CREATE_INFO_NN) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_GROUP_PROPERTIES_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GROUP_DEVICE_CREATE_INFO_KHX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_BUFFER_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXTERNAL_BUFFER_PROPERTIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_ID_PROPERTIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_WIN32_HANDLE_PROPERTIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_GET_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_FD_PROPERTIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_GET_FD_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_SEMAPHORE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXTERNAL_SEMAPHORE_PROPERTIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_D3D12_FENCE_SUBMIT_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SEMAPHORE_GET_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMPORT_SEMAPHORE_FD_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SEMAPHORE_GET_FD_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PUSH_DESCRIPTOR_PROPERTIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PRESENT_REGIONS_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DESCRIPTOR_UPDATE_TEMPLATE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_OBJECT_TABLE_CREATE_INFO_NVX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_INDIRECT_COMMANDS_LAYOUT_CREATE_INFO_NVX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_CMD_PROCESS_COMMANDS_INFO_NVX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_CMD_RESERVE_SPACE_FOR_COMMANDS_INFO_NVX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GENERATED_COMMANDS_LIMITS_NVX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_GENERATED_COMMANDS_FEATURES_NVX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_W_SCALING_STATE_CREATE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES2_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DISPLAY_POWER_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DEVICE_EVENT_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_DISPLAY_EVENT_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SWAPCHAIN_COUNTER_CREATE_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PRESENT_TIMES_INFO_GOOGLE) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MULTIVIEW_PER_VIEW_ATTRIBUTES_PROPERTIES_NVX) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_SWIZZLE_STATE_CREATE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DISCARD_RECTANGLE_PROPERTIES_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_DISCARD_RECTANGLE_STATE_CREATE_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_HDR_METADATA_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXPORT_FENCE_CREATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMPORT_FENCE_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_EXPORT_FENCE_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_FENCE_GET_WIN32_HANDLE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_FENCE_GET_FD_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SURFACE_FORMAT_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VARIABLE_POINTER_FEATURES_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IOS_SURFACE_CREATE_INFO_MVK) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MACOS_SURFACE_CREATE_INFO_MVK) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_DEDICATED_REQUIREMENTS_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_FILTER_MINMAX_PROPERTIES_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SAMPLER_REDUCTION_MODE_CREATE_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_BUFFER_MEMORY_REQUIREMENTS_INFO_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_IMAGE_SPARSE_MEMORY_REQUIREMENTS_INFO_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_SPARSE_IMAGE_MEMORY_REQUIREMENTS_2_KHR) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_FEATURES_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_BLEND_OPERATION_ADVANCED_PROPERTIES_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_ADVANCED_STATE_CREATE_INFO_EXT) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_TO_COLOR_STATE_CREATE_INFO_NV) TOSTR_CASE_STRINGIZE(VK_STRUCTURE_TYPE_PIPELINE_COVERAGE_MODULATION_STATE_CREATE_INFO_NV) default: break; } return StringFormat::Fmt("VkStructureType<%d>", el); } template <> string ToStrHelper<false, VkComponentSwizzle>::Get(const VkComponentSwizzle &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_COMPONENT_SWIZZLE_IDENTITY) TOSTR_CASE_STRINGIZE(VK_COMPONENT_SWIZZLE_ZERO) TOSTR_CASE_STRINGIZE(VK_COMPONENT_SWIZZLE_ONE) TOSTR_CASE_STRINGIZE(VK_COMPONENT_SWIZZLE_R) TOSTR_CASE_STRINGIZE(VK_COMPONENT_SWIZZLE_G) TOSTR_CASE_STRINGIZE(VK_COMPONENT_SWIZZLE_B) TOSTR_CASE_STRINGIZE(VK_COMPONENT_SWIZZLE_A) default: break; } return StringFormat::Fmt("VkComponentSwizzle<%d>", el); } template <> string ToStrHelper<false, VkFormat>::Get(const VkFormat &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_FORMAT_UNDEFINED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R4G4_UNORM_PACK8) TOSTR_CASE_STRINGIZE(VK_FORMAT_R4G4B4A4_UNORM_PACK16) TOSTR_CASE_STRINGIZE(VK_FORMAT_B4G4R4A4_UNORM_PACK16) TOSTR_CASE_STRINGIZE(VK_FORMAT_R5G6B5_UNORM_PACK16) TOSTR_CASE_STRINGIZE(VK_FORMAT_B5G6R5_UNORM_PACK16) TOSTR_CASE_STRINGIZE(VK_FORMAT_R5G5B5A1_UNORM_PACK16) TOSTR_CASE_STRINGIZE(VK_FORMAT_B5G5R5A1_UNORM_PACK16) TOSTR_CASE_STRINGIZE(VK_FORMAT_A1R5G5B5_UNORM_PACK16) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8_SRGB) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8_SRGB) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8_SRGB) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8_SRGB) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8A8_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8A8_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8A8_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8A8_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8A8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8A8_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R8G8B8A8_SRGB) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8A8_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8A8_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8A8_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8A8_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8A8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8A8_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_B8G8R8A8_SRGB) TOSTR_CASE_STRINGIZE(VK_FORMAT_A8B8G8R8_UNORM_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A8B8G8R8_SNORM_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A8B8G8R8_USCALED_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A8B8G8R8_SSCALED_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A8B8G8R8_UINT_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A8B8G8R8_SINT_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A8B8G8R8_SRGB_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2R10G10B10_UNORM_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2R10G10B10_SNORM_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2R10G10B10_USCALED_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2R10G10B10_SSCALED_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2R10G10B10_UINT_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2R10G10B10_SINT_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2B10G10R10_UNORM_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2B10G10R10_SNORM_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2B10G10R10_USCALED_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2B10G10R10_SSCALED_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2B10G10R10_UINT_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_A2B10G10R10_SINT_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16A16_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16A16_SNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16A16_USCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16A16_SSCALED) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16A16_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16A16_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R16G16B16A16_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32B32_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32B32_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32B32_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32B32A32_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32B32A32_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R32G32B32A32_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64B64_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64B64_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64B64_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64B64A64_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64B64A64_SINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_R64G64B64A64_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_B10G11R11_UFLOAT_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_E5B9G9R9_UFLOAT_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_D16_UNORM) TOSTR_CASE_STRINGIZE(VK_FORMAT_X8_D24_UNORM_PACK32) TOSTR_CASE_STRINGIZE(VK_FORMAT_D32_SFLOAT) TOSTR_CASE_STRINGIZE(VK_FORMAT_S8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_D16_UNORM_S8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_D24_UNORM_S8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_D32_SFLOAT_S8_UINT) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC1_RGB_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC1_RGB_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC1_RGBA_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC1_RGBA_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC2_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC2_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC3_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC3_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC4_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC4_SNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC5_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC5_SNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC6H_UFLOAT_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC6H_SFLOAT_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC7_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_BC7_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ETC2_R8G8B8_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ETC2_R8G8B8A1_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ETC2_R8G8B8A1_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ETC2_R8G8B8A8_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ETC2_R8G8B8A8_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_EAC_R11_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_EAC_R11_SNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_EAC_R11G11_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_EAC_R11G11_SNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_4x4_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_4x4_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_5x4_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_5x4_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_5x5_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_5x5_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_6x5_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_6x5_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_6x6_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_6x6_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_8x5_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_8x5_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_8x6_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_8x6_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_8x8_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_8x8_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_10x5_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_10x5_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_10x6_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_10x6_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_10x8_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_10x8_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_10x10_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_10x10_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_12x10_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_12x10_SRGB_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_12x12_UNORM_BLOCK) TOSTR_CASE_STRINGIZE(VK_FORMAT_ASTC_12x12_SRGB_BLOCK) default: break; } return StringFormat::Fmt("VkFormat<%d>", el); } template <> string ToStrHelper<false, VkResult>::Get(const VkResult &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_SUCCESS) TOSTR_CASE_STRINGIZE(VK_NOT_READY) TOSTR_CASE_STRINGIZE(VK_TIMEOUT) TOSTR_CASE_STRINGIZE(VK_EVENT_SET) TOSTR_CASE_STRINGIZE(VK_EVENT_RESET) TOSTR_CASE_STRINGIZE(VK_INCOMPLETE) TOSTR_CASE_STRINGIZE(VK_ERROR_OUT_OF_HOST_MEMORY) TOSTR_CASE_STRINGIZE(VK_ERROR_OUT_OF_DEVICE_MEMORY) TOSTR_CASE_STRINGIZE(VK_ERROR_INITIALIZATION_FAILED) TOSTR_CASE_STRINGIZE(VK_ERROR_DEVICE_LOST) TOSTR_CASE_STRINGIZE(VK_ERROR_MEMORY_MAP_FAILED) TOSTR_CASE_STRINGIZE(VK_ERROR_LAYER_NOT_PRESENT) TOSTR_CASE_STRINGIZE(VK_ERROR_EXTENSION_NOT_PRESENT) TOSTR_CASE_STRINGIZE(VK_ERROR_FEATURE_NOT_PRESENT) TOSTR_CASE_STRINGIZE(VK_ERROR_INCOMPATIBLE_DRIVER) TOSTR_CASE_STRINGIZE(VK_ERROR_TOO_MANY_OBJECTS) TOSTR_CASE_STRINGIZE(VK_ERROR_FORMAT_NOT_SUPPORTED) TOSTR_CASE_STRINGIZE(VK_ERROR_SURFACE_LOST_KHR) TOSTR_CASE_STRINGIZE(VK_ERROR_NATIVE_WINDOW_IN_USE_KHR) TOSTR_CASE_STRINGIZE(VK_SUBOPTIMAL_KHR) TOSTR_CASE_STRINGIZE(VK_ERROR_OUT_OF_DATE_KHR) TOSTR_CASE_STRINGIZE(VK_ERROR_INCOMPATIBLE_DISPLAY_KHR) TOSTR_CASE_STRINGIZE(VK_ERROR_VALIDATION_FAILED_EXT) TOSTR_CASE_STRINGIZE(VK_ERROR_INVALID_SHADER_NV) TOSTR_CASE_STRINGIZE(VK_ERROR_OUT_OF_POOL_MEMORY_KHR) TOSTR_CASE_STRINGIZE(VK_ERROR_INVALID_EXTERNAL_HANDLE_KHR) default: break; } return StringFormat::Fmt("VkResult<%d>", el); } template <> string ToStrHelper<false, VkMemoryType>::Get(const VkMemoryType &el) { return StringFormat::Fmt("VkMemoryType<heap %u, %s>", el.heapIndex, ToStr::Get((VkMemoryPropertyFlagBits)el.propertyFlags).c_str()); } template <> string ToStrHelper<false, VkMemoryHeap>::Get(const VkMemoryHeap &el) { return StringFormat::Fmt("VkMemoryHeap<%.3fMB, %s>", float(el.size) / (1024.0f * 1024.0f), ToStr::Get((VkMemoryHeapFlagBits)el.flags).c_str()); } template <> string ToStrHelper<false, VkRect2D>::Get(const VkRect2D &el) { return StringFormat::Fmt("VkRect2D<%dx%d+%d+%d>", el.extent.width, el.extent.height, el.offset.x, el.offset.y); } template <> string ToStrHelper<false, VkClearRect>::Get(const VkClearRect &el) { return StringFormat::Fmt("VkClearRect<%dx%d+%d+%d %u->%u>", el.rect.extent.width, el.rect.extent.height, el.rect.offset.x, el.rect.offset.y, el.baseArrayLayer, el.baseArrayLayer + el.layerCount); } template <> string ToStrHelper<false, VkClearAttachment>::Get(const VkClearAttachment &el) { return StringFormat::Fmt("%s[%u] = %s", ToStr::Get((VkImageAspectFlagBits)el.aspectMask).c_str(), el.colorAttachment, ToStr::Get(el.clearValue).c_str()); } template <> string ToStrHelper<false, VkQueueFamilyProperties>::Get(const VkQueueFamilyProperties &el) { return StringFormat::Fmt( "%s x %u, %u bits, %s", ToStr::Get((VkQueueFlagBits)el.queueFlags).c_str(), el.queueCount, el.timestampValidBits, ToStr::Get(el.minImageTransferGranularity).c_str()); } template <> string ToStrHelper<false, VkExtent2D>::Get(const VkExtent2D &el) { return StringFormat::Fmt("VkExtent<%u,%u>", el.width, el.height); } template <> string ToStrHelper<false, VkExtent3D>::Get(const VkExtent3D &el) { return StringFormat::Fmt("VkExtent<%u,%u,%u>", el.width, el.height, el.depth); } template <> string ToStrHelper<false, VkOffset2D>::Get(const VkOffset2D &el) { return StringFormat::Fmt("VkOffset<%d,%d>", el.x, el.y); } template <> string ToStrHelper<false, VkOffset3D>::Get(const VkOffset3D &el) { return StringFormat::Fmt("VkOffset<%d,%d,%d>", el.x, el.y, el.z); } template <> string ToStrHelper<false, VkViewport>::Get(const VkViewport &el) { return StringFormat::Fmt("VkViewport<%f,%f, %fx%f, %f-%f>", el.x, el.y, el.width, el.height, el.minDepth, el.maxDepth); } template <> string ToStrHelper<false, VkClearColorValue>::Get(const VkClearColorValue &el) { return StringFormat::Fmt("VkClearColorValue<%f,%f,%f,%f>", el.float32[0], el.float32[1], el.float32[2], el.float32[3]); } template <> string ToStrHelper<false, VkClearDepthStencilValue>::Get(const VkClearDepthStencilValue &el) { return StringFormat::Fmt("VkClearDepthStencilValue<%f %u>", el.depth, el.stencil); } template <> string ToStrHelper<false, VkClearValue>::Get(const VkClearValue &el) { return StringFormat::Fmt("VkClearValue[ col:<%f,%f,%f,%f> / d:%f s:%u ]", el.color.float32[0], el.color.float32[1], el.color.float32[2], el.color.float32[3], el.depthStencil.depth, el.depthStencil.stencil); } template <> string ToStrHelper<false, VkAttachmentReference>::Get(const VkAttachmentReference &el) { return StringFormat::Fmt("VkAttachmentReference<%u, %s>", el.attachment, ToStr::Get(el.layout).c_str()); } //////////////////////////////////////////////////////////// // VK_KHR_surface //////////////////////////////////////////////////////////// template <> string ToStrHelper<false, VkSurfaceTransformFlagBitsKHR>::Get(const VkSurfaceTransformFlagBitsKHR &el) { string ret; if(el & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR) ret += " | VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR"; if(el & VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR) ret += " | VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR"; if(el & VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR) ret += " | VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR"; if(el & VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR) ret += " | VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_BIT_KHR"; if(el & VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR) ret += " | VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_90_BIT_KHR"; if(el & VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR) ret += " | VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_180_BIT_KHR"; if(el & VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR) ret += " | VK_SURFACE_TRANSFORM_HORIZONTAL_MIRROR_ROTATE_270_BIT_KHR"; if(el & VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR) ret += " | VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkCompositeAlphaFlagBitsKHR>::Get(const VkCompositeAlphaFlagBitsKHR &el) { string ret; if(el & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR) ret += " | VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR"; if(el & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR) ret += " | VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR"; if(el & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR) ret += " | VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR"; if(el & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR) ret += " | VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR"; if(!ret.empty()) ret = ret.substr(3); return ret; } template <> string ToStrHelper<false, VkColorSpaceKHR>::Get(const VkColorSpaceKHR &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_COLORSPACE_SRGB_NONLINEAR_KHR) default: break; } return StringFormat::Fmt("VkColorSpaceKHR<%d>", el); } template <> string ToStrHelper<false, VkPresentModeKHR>::Get(const VkPresentModeKHR &el) { switch(el) { TOSTR_CASE_STRINGIZE(VK_PRESENT_MODE_IMMEDIATE_KHR) TOSTR_CASE_STRINGIZE(VK_PRESENT_MODE_MAILBOX_KHR) TOSTR_CASE_STRINGIZE(VK_PRESENT_MODE_FIFO_KHR) TOSTR_CASE_STRINGIZE(VK_PRESENT_MODE_FIFO_RELAXED_KHR) default: break; } return StringFormat::Fmt("VkPresentModeKHR<%d>", el); } // we know the object will be a non-dispatchable object type #define SerialiseObjectInternal(type, name, obj, opt) \ { \ VulkanResourceManager *rm = (VulkanResourceManager *)GetUserData(); \ ResourceId id; \ if(m_Mode >= WRITING) \ id = GetResID(obj); \ Serialise(name, id); \ if(m_Mode < WRITING) \ { \ obj = VK_NULL_HANDLE; \ if(id != ResourceId()) \ { \ if(rm->HasLiveResource(id)) \ obj = Unwrap(rm->GetLiveHandle<type>(id)); \ else if(!opt) \ /* It can be OK for a resource to have no live equivalent if the */ \ /* capture decided its not needed, which some APIs do fairly often. */ \ RDCWARN("Capture may be missing reference to " #type " resource."); \ } \ } \ } #define SerialiseObject(type, name, obj) SerialiseObjectInternal(type, name, obj, false) #define SerialiseObjectOptional(type, name, obj) SerialiseObjectInternal(type, name, obj, true) static void SerialiseNext(Serialiser *ser, VkStructureType &sType, const void *&pNext) { ser->Serialise("sType", sType); if(ser->IsReading()) { pNext = NULL; } else { if(pNext == NULL) return; VkGenericStruct *next = (VkGenericStruct *)pNext; while(next) { // we can ignore this entirely, we don't need to serialise or replay it as we won't // actually use external memory. Unwrapping, if necessary, happens elsewhere if(next->sType == VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_NV || next->sType == VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_NV || next->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_NV || next->sType == VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_NV || next->sType == VK_STRUCTURE_TYPE_WIN32_KEYED_MUTEX_ACQUIRE_RELEASE_INFO_NV || next->sType == VK_STRUCTURE_TYPE_EXPORT_MEMORY_ALLOCATE_INFO_KHR || next->sType == VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO_KHR || next->sType == VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_BUFFER_CREATE_INFO_KHR || next->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR || next->sType == VK_STRUCTURE_TYPE_EXPORT_MEMORY_WIN32_HANDLE_INFO_KHR || next->sType == VK_STRUCTURE_TYPE_IMPORT_MEMORY_FD_INFO_KHR || next->sType == VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_CREATE_INFO_KHR || next->sType == VK_STRUCTURE_TYPE_EXPORT_SEMAPHORE_WIN32_HANDLE_INFO_KHR) { // do nothing } // likewise we don't create real swapchains, so we can ignore surface counters else if(next->sType == VK_STRUCTURE_TYPE_SWAPCHAIN_COUNTER_CREATE_INFO_EXT) { // do nothing } // for now we don't serialise dedicated memory on replay as it's only a performance hint, // and is only required in conjunction with shared memory (which we don't replay). In future // it might be helpful to serialise this for informational purposes. else if(next->sType == VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_MEMORY_ALLOCATE_INFO_NV || next->sType == VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_IMAGE_CREATE_INFO_NV || next->sType == VK_STRUCTURE_TYPE_DEDICATED_ALLOCATION_BUFFER_CREATE_INFO_NV || next->sType == VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO_KHR) { // do nothing } else { RDCERR("Unrecognised extension structure type %d", next->sType); } next = (VkGenericStruct *)next->pNext; } } } template <typename T> void SerialiseOptionalObject(Serialiser *ser, const char *name, T *&el) { bool present; present = el != NULL; ser->Serialise((string(name) + "Present").c_str(), present); if(present) { if(ser->IsReading()) el = new T; ser->Serialise(name, *el); } else if(ser->IsReading()) { el = NULL; } } template <> void Serialiser::Serialise(const char *name, VkDeviceQueueCreateInfo &el) { ScopedContext scope(this, name, "VkDeviceQueueCreateInfo", 0, true); // RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO); if(m_Mode >= WRITING && el.sType != VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO) RDCWARN("sType not set properly: %u", el.sType); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("queueFamilyIndex", el.queueFamilyIndex); Serialise("queueCount", el.queueCount); if(m_Mode == READING) el.pQueuePriorities = NULL; SerialisePODArray("pQueuePriorities", (float *&)el.pQueuePriorities, el.queueCount); } // technically this doesn't need a serialise function as it's POD, // but we give it one just for ease of printing etc. template <> void Serialiser::Serialise(const char *name, VkPhysicalDeviceFeatures &el) { ScopedContext scope(this, name, "VkPhysicalDeviceFeatures", 0, true); Serialise("robustBufferAccess", el.robustBufferAccess); Serialise("fullDrawIndexUint32", el.fullDrawIndexUint32); Serialise("imageCubeArray", el.imageCubeArray); Serialise("independentBlend", el.independentBlend); Serialise("geometryShader", el.geometryShader); Serialise("tessellationShader", el.tessellationShader); Serialise("sampleRateShading", el.sampleRateShading); Serialise("dualSrcBlend", el.dualSrcBlend); Serialise("logicOp", el.logicOp); Serialise("multiDrawIndirect", el.multiDrawIndirect); Serialise("drawIndirectFirstInstance", el.drawIndirectFirstInstance); Serialise("depthClamp", el.depthClamp); Serialise("depthBiasClamp", el.depthBiasClamp); Serialise("fillModeNonSolid", el.fillModeNonSolid); Serialise("depthBounds", el.depthBounds); Serialise("wideLines", el.wideLines); Serialise("largePoints", el.largePoints); Serialise("alphaToOne", el.alphaToOne); Serialise("multiViewport", el.multiViewport); Serialise("samplerAnisotropy", el.samplerAnisotropy); Serialise("textureCompressionETC2", el.textureCompressionETC2); Serialise("textureCompressionASTC_LDR", el.textureCompressionASTC_LDR); Serialise("textureCompressionBC", el.textureCompressionBC); Serialise("occlusionQueryPrecise", el.occlusionQueryPrecise); Serialise("pipelineStatisticsQuery", el.pipelineStatisticsQuery); Serialise("vertexPipelineStoresAndAtomics", el.vertexPipelineStoresAndAtomics); Serialise("fragmentStoresAndAtomics", el.fragmentStoresAndAtomics); Serialise("shaderTessellationAndGeometryPointSize", el.shaderTessellationAndGeometryPointSize); Serialise("shaderImageGatherExtended", el.shaderImageGatherExtended); Serialise("shaderStorageImageExtendedFormats", el.shaderStorageImageExtendedFormats); Serialise("shaderStorageImageMultisample", el.shaderStorageImageMultisample); Serialise("shaderStorageImageReadWithoutFormat", el.shaderStorageImageReadWithoutFormat); Serialise("shaderStorageImageWriteWithoutFormat", el.shaderStorageImageWriteWithoutFormat); Serialise("shaderUniformBufferArrayDynamicIndexing", el.shaderUniformBufferArrayDynamicIndexing); Serialise("shaderSampledImageArrayDynamicIndexing", el.shaderSampledImageArrayDynamicIndexing); Serialise("shaderStorageBufferArrayDynamicIndexing", el.shaderStorageBufferArrayDynamicIndexing); Serialise("shaderStorageImageArrayDynamicIndexing", el.shaderStorageImageArrayDynamicIndexing); Serialise("shaderClipDistance", el.shaderClipDistance); Serialise("shaderCullDistance", el.shaderCullDistance); Serialise("shaderFloat64", el.shaderFloat64); Serialise("shaderInt64", el.shaderInt64); Serialise("shaderInt16", el.shaderInt16); Serialise("shaderResourceResidency", el.shaderResourceResidency); Serialise("shaderResourceMinLod", el.shaderResourceMinLod); Serialise("sparseBinding", el.sparseBinding); Serialise("sparseResidencyBuffer", el.sparseResidencyBuffer); Serialise("sparseResidencyImage2D", el.sparseResidencyImage2D); Serialise("sparseResidencyImage3D", el.sparseResidencyImage3D); Serialise("sparseResidency2Samples", el.sparseResidency2Samples); Serialise("sparseResidency4Samples", el.sparseResidency4Samples); Serialise("sparseResidency8Samples", el.sparseResidency8Samples); Serialise("sparseResidency16Samples", el.sparseResidency16Samples); Serialise("sparseResidencyAliased", el.sparseResidencyAliased); Serialise("variableMultisampleRate", el.variableMultisampleRate); Serialise("inheritedQueries", el.inheritedQueries); } template <> void Serialiser::Serialise(const char *name, VkPhysicalDeviceMemoryProperties &el) { ScopedContext scope(this, name, "VkPhysicalDeviceMemoryProperties", 0, true); VkMemoryType *types = el.memoryTypes; VkMemoryHeap *heaps = el.memoryHeaps; SerialisePODArray("memoryTypes", types, el.memoryTypeCount); SerialisePODArray("memoryHeaps", heaps, el.memoryHeapCount); } template <> void Serialiser::Serialise(const char *name, VkPhysicalDeviceLimits &el) { ScopedContext scope(this, name, "VkPhysicalDeviceLimits", 0, true); Serialise("maxImageDimension1D", el.maxImageDimension1D); Serialise("maxImageDimension2D", el.maxImageDimension2D); Serialise("maxImageDimension3D", el.maxImageDimension3D); Serialise("maxImageDimensionCube", el.maxImageDimensionCube); Serialise("maxImageArrayLayers", el.maxImageArrayLayers); Serialise("maxTexelBufferElements", el.maxTexelBufferElements); Serialise("maxUniformBufferRange", el.maxUniformBufferRange); Serialise("maxStorageBufferRange", el.maxStorageBufferRange); Serialise("maxPushConstantsSize", el.maxPushConstantsSize); Serialise("maxMemoryAllocationCount", el.maxMemoryAllocationCount); Serialise("maxSamplerAllocationCount", el.maxSamplerAllocationCount); Serialise("bufferImageGranularity", el.bufferImageGranularity); Serialise("sparseAddressSpaceSize", el.sparseAddressSpaceSize); Serialise("maxBoundDescriptorSets", el.maxBoundDescriptorSets); Serialise("maxPerStageDescriptorSamplers", el.maxPerStageDescriptorSamplers); Serialise("maxPerStageDescriptorUniformBuffers", el.maxPerStageDescriptorUniformBuffers); Serialise("maxPerStageDescriptorStorageBuffers", el.maxPerStageDescriptorStorageBuffers); Serialise("maxPerStageDescriptorSampledImages", el.maxPerStageDescriptorSampledImages); Serialise("maxPerStageDescriptorStorageImages", el.maxPerStageDescriptorStorageImages); Serialise("maxPerStageDescriptorInputAttachments", el.maxPerStageDescriptorInputAttachments); Serialise("maxPerStageResources", el.maxPerStageResources); Serialise("maxDescriptorSetSamplers", el.maxDescriptorSetSamplers); Serialise("maxDescriptorSetUniformBuffers", el.maxDescriptorSetUniformBuffers); Serialise("maxDescriptorSetUniformBuffersDynamic", el.maxDescriptorSetUniformBuffersDynamic); Serialise("maxDescriptorSetStorageBuffers", el.maxDescriptorSetStorageBuffers); Serialise("maxDescriptorSetStorageBuffersDynamic", el.maxDescriptorSetStorageBuffersDynamic); Serialise("maxDescriptorSetSampledImages", el.maxDescriptorSetSampledImages); Serialise("maxDescriptorSetStorageImages", el.maxDescriptorSetStorageImages); Serialise("maxDescriptorSetInputAttachments", el.maxDescriptorSetInputAttachments); Serialise("maxVertexInputAttributes", el.maxVertexInputAttributes); Serialise("maxVertexInputBindings", el.maxVertexInputBindings); Serialise("maxVertexInputAttributeOffset", el.maxVertexInputAttributeOffset); Serialise("maxVertexInputBindingStride", el.maxVertexInputBindingStride); Serialise("maxVertexOutputComponents", el.maxVertexOutputComponents); Serialise("maxTessellationGenerationLevel", el.maxTessellationGenerationLevel); Serialise("maxTessellationPatchSize", el.maxTessellationPatchSize); Serialise("maxTessellationControlPerVertexInputComponents", el.maxTessellationControlPerVertexInputComponents); Serialise("maxTessellationControlPerVertexOutputComponents", el.maxTessellationControlPerVertexOutputComponents); Serialise("maxTessellationControlPerPatchOutputComponents", el.maxTessellationControlPerPatchOutputComponents); Serialise("maxTessellationControlTotalOutputComponents", el.maxTessellationControlTotalOutputComponents); Serialise("maxTessellationEvaluationInputComponents", el.maxTessellationEvaluationInputComponents); Serialise("maxTessellationEvaluationOutputComponents", el.maxTessellationEvaluationOutputComponents); Serialise("maxGeometryShaderInvocations", el.maxGeometryShaderInvocations); Serialise("maxGeometryInputComponents", el.maxGeometryInputComponents); Serialise("maxGeometryOutputComponents", el.maxGeometryOutputComponents); Serialise("maxGeometryOutputVertices", el.maxGeometryOutputVertices); Serialise("maxGeometryTotalOutputComponents", el.maxGeometryTotalOutputComponents); Serialise("maxFragmentInputComponents", el.maxFragmentInputComponents); Serialise("maxFragmentOutputAttachments", el.maxFragmentOutputAttachments); Serialise("maxFragmentDualSrcAttachments", el.maxFragmentDualSrcAttachments); Serialise("maxFragmentCombinedOutputResources", el.maxFragmentCombinedOutputResources); Serialise("maxComputeSharedMemorySize", el.maxComputeSharedMemorySize); SerialisePODArray<3>("maxComputeWorkGroupCount", el.maxComputeWorkGroupCount); Serialise("maxComputeWorkGroupInvocations", el.maxComputeWorkGroupInvocations); SerialisePODArray<3>("maxComputeWorkGroupSize", el.maxComputeWorkGroupSize); Serialise("subPixelPrecisionBits", el.subPixelPrecisionBits); Serialise("subTexelPrecisionBits", el.subTexelPrecisionBits); Serialise("mipmapPrecisionBits", el.mipmapPrecisionBits); Serialise("maxDrawIndexedIndexValue", el.maxDrawIndexedIndexValue); Serialise("maxDrawIndirectCount", el.maxDrawIndirectCount); Serialise("maxSamplerLodBias", el.maxSamplerLodBias); Serialise("maxSamplerAnisotropy", el.maxSamplerAnisotropy); Serialise("maxViewports", el.maxViewports); SerialisePODArray<2>("maxViewportDimensions", el.maxViewportDimensions); SerialisePODArray<2>("viewportBoundsRange", el.viewportBoundsRange); Serialise("viewportSubPixelBits", el.viewportSubPixelBits); uint64_t minMemoryMapAlignment = (uint64_t)el.minMemoryMapAlignment; Serialise("minMemoryMapAlignment", minMemoryMapAlignment); el.minMemoryMapAlignment = (size_t)minMemoryMapAlignment; Serialise("minTexelBufferOffsetAlignment", el.minTexelBufferOffsetAlignment); Serialise("minUniformBufferOffsetAlignment", el.minUniformBufferOffsetAlignment); Serialise("minStorageBufferOffsetAlignment", el.minStorageBufferOffsetAlignment); Serialise("minTexelOffset", el.minTexelOffset); Serialise("maxTexelOffset", el.maxTexelOffset); Serialise("minTexelGatherOffset", el.minTexelGatherOffset); Serialise("maxTexelGatherOffset", el.maxTexelGatherOffset); Serialise("minInterpolationOffset", el.minInterpolationOffset); Serialise("maxInterpolationOffset", el.maxInterpolationOffset); Serialise("subPixelInterpolationOffsetBits", el.subPixelInterpolationOffsetBits); Serialise("maxFramebufferWidth", el.maxFramebufferWidth); Serialise("maxFramebufferHeight", el.maxFramebufferHeight); Serialise("maxFramebufferLayers", el.maxFramebufferLayers); Serialise("framebufferColorSampleCounts", el.framebufferColorSampleCounts); Serialise("framebufferDepthSampleCounts", el.framebufferDepthSampleCounts); Serialise("framebufferStencilSampleCounts", el.framebufferStencilSampleCounts); Serialise("framebufferNoAttachmentsSampleCounts", el.framebufferNoAttachmentsSampleCounts); Serialise("maxColorAttachments", el.maxColorAttachments); Serialise("sampledImageColorSampleCounts", el.sampledImageColorSampleCounts); Serialise("sampledImageIntegerSampleCounts", el.sampledImageIntegerSampleCounts); Serialise("sampledImageDepthSampleCounts", el.sampledImageDepthSampleCounts); Serialise("sampledImageStencilSampleCounts", el.sampledImageStencilSampleCounts); Serialise("storageImageSampleCounts", el.storageImageSampleCounts); Serialise("maxSampleMaskWords", el.maxSampleMaskWords); Serialise("timestampComputeAndGraphics", el.timestampComputeAndGraphics); Serialise("timestampPeriod", el.timestampPeriod); Serialise("maxClipDistances", el.maxClipDistances); Serialise("maxCullDistances", el.maxCullDistances); Serialise("maxCombinedClipAndCullDistances", el.maxCombinedClipAndCullDistances); Serialise("discreteQueuePriorities", el.discreteQueuePriorities); SerialisePODArray<2>("pointSizeRange", el.pointSizeRange); SerialisePODArray<2>("lineWidthRange", el.lineWidthRange); Serialise("pointSizeGranularity", el.pointSizeGranularity); Serialise("lineWidthGranularity", el.lineWidthGranularity); Serialise("strictLines", el.strictLines); Serialise("standardSampleLocations", el.standardSampleLocations); Serialise("optimalBufferCopyOffsetAlignment", el.optimalBufferCopyOffsetAlignment); Serialise("optimalBufferCopyRowPitchAlignment", el.optimalBufferCopyRowPitchAlignment); Serialise("nonCoherentAtomSize", el.nonCoherentAtomSize); } template <> void Serialiser::Serialise(const char *name, VkPhysicalDeviceSparseProperties &el) { ScopedContext scope(this, name, "VkPhysicalDeviceSparseProperties", 0, true); Serialise("residencyStandard2DBlockShape", el.residencyStandard2DBlockShape); Serialise("residencyStandard2DMultisampleBlockShape", el.residencyStandard2DMultisampleBlockShape); Serialise("residencyStandard3DBlockShape", el.residencyStandard3DBlockShape); Serialise("residencyAlignedMipSize", el.residencyAlignedMipSize); Serialise("residencyNonResidentStrict", el.residencyNonResidentStrict); } template <> void Serialiser::Serialise(const char *name, VkPhysicalDeviceProperties &el) { ScopedContext scope(this, name, "VkPhysicalDeviceProperties", 0, true); Serialise("apiVersion", el.apiVersion); Serialise("driverVersion", el.driverVersion); Serialise("vendorID", el.vendorID); Serialise("deviceID", el.deviceID); Serialise("deviceType", el.deviceType); string deviceName; if(m_Mode == WRITING) deviceName = el.deviceName; Serialise("deviceName", deviceName); if(m_Mode == READING) { RDCEraseEl(el.deviceName); memcpy(el.deviceName, deviceName.c_str(), RDCMIN(deviceName.size(), (size_t)VK_MAX_PHYSICAL_DEVICE_NAME_SIZE)); } SerialisePODArray<VK_UUID_SIZE>("pipelineCacheUUID", el.pipelineCacheUUID); Serialise("limits", el.limits); Serialise("sparseProperties", el.sparseProperties); } template <> void Serialiser::Serialise(const char *name, VkDeviceCreateInfo &el) { ScopedContext scope(this, name, "VkDeviceCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); SerialiseComplexArray("pQueueCreateInfos", (VkDeviceQueueCreateInfo *&)el.pQueueCreateInfos, el.queueCreateInfoCount); // need to do this by hand to use string DB Serialise("extensionCount", el.enabledExtensionCount); if(m_Mode == READING) el.ppEnabledExtensionNames = el.enabledExtensionCount ? new char *[el.enabledExtensionCount] : NULL; // cast away const on array so we can assign to it on reading const char **exts = (const char **)el.ppEnabledExtensionNames; for(uint32_t i = 0; i < el.enabledExtensionCount; i++) { string s = ""; if(m_Mode == WRITING && exts[i] != NULL) s = exts[i]; Serialise("ppEnabledExtensionNames", s); if(m_Mode == READING) { m_StringDB.insert(s); exts[i] = m_StringDB.find(s)->c_str(); } } // need to do this by hand to use string DB Serialise("layerCount", el.enabledLayerCount); if(m_Mode == READING) el.ppEnabledLayerNames = el.enabledLayerCount ? new char *[el.enabledLayerCount] : NULL; // cast away const on array so we can assign to it on reading const char **layers = (const char **)el.ppEnabledLayerNames; for(uint32_t i = 0; i < el.enabledLayerCount; i++) { string s = ""; if(m_Mode == WRITING && layers[i] != NULL) s = layers[i]; Serialise("ppEnabledLayerNames", s); if(m_Mode == READING) { m_StringDB.insert(s); layers[i] = m_StringDB.find(s)->c_str(); } } SerialiseOptionalObject(this, "pEnabledFeatures", (VkPhysicalDeviceFeatures *&)el.pEnabledFeatures); } template <> void Serialiser::Deserialise(const VkDeviceCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete for(uint32_t i = 0; i < el->queueCreateInfoCount; i++) delete[] el->pQueueCreateInfos[i].pQueuePriorities; delete[] el->pQueueCreateInfos; delete[] el->ppEnabledExtensionNames; delete[] el->ppEnabledLayerNames; delete el->pEnabledFeatures; } } template <> void Serialiser::Serialise(const char *name, VkBufferCreateInfo &el) { ScopedContext scope(this, name, "VkBufferCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkBufferCreateFlagBits &)el.flags); Serialise("size", el.size); Serialise("usage", (VkBufferUsageFlagBits &)el.usage); Serialise("sharingMode", el.sharingMode); if(m_Mode == READING) { el.pQueueFamilyIndices = NULL; el.queueFamilyIndexCount = 0; } if(el.sharingMode == VK_SHARING_MODE_CONCURRENT) { SerialisePODArray("pQueueFamilyIndices", (uint32_t *&)el.pQueueFamilyIndices, el.queueFamilyIndexCount); } else { // for backwards compatibility with captures, ignore the family count and serialise empty array uint32_t zero = 0; uint32_t *empty = NULL; SerialisePODArray("pQueueFamilyIndices", empty, zero); delete[] empty; } } template <> void Serialiser::Deserialise(const VkBufferCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pQueueFamilyIndices; } } template <> void Serialiser::Serialise(const char *name, VkBufferViewCreateInfo &el) { ScopedContext scope(this, name, "VkBufferViewCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_BUFFER_VIEW_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); SerialiseObject(VkBuffer, "buffer", el.buffer); Serialise("format", el.format); Serialise("offset", el.offset); Serialise("range", el.range); } template <> void Serialiser::Serialise(const char *name, VkImageCreateInfo &el) { ScopedContext scope(this, name, "VkImageCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkImageCreateFlagBits &)el.flags); Serialise("imageType", el.imageType); Serialise("format", el.format); Serialise("extent", el.extent); Serialise("mipLevels", el.mipLevels); Serialise("arraySize", el.arrayLayers); Serialise("samples", el.samples); Serialise("tiling", el.tiling); Serialise("usage", (VkImageUsageFlagBits &)el.usage); Serialise("sharingMode", el.sharingMode); if(m_Mode == READING) { el.pQueueFamilyIndices = NULL; el.queueFamilyIndexCount = 0; } if(el.sharingMode == VK_SHARING_MODE_CONCURRENT) { SerialisePODArray("pQueueFamilyIndices", (uint32_t *&)el.pQueueFamilyIndices, el.queueFamilyIndexCount); } else { // for backwards compatibility with captures, ignore the family count and serialise empty array uint32_t zero = 0; uint32_t empty[1] = {0}; SerialisePODArray("pQueueFamilyIndices", (uint32_t *&)empty, zero); } Serialise("initialLayout", el.initialLayout); } template <> void Serialiser::Deserialise(const VkImageCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pQueueFamilyIndices; } } template <> void Serialiser::Serialise(const char *name, VkImageViewCreateInfo &el) { ScopedContext scope(this, name, "VkImageViewCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); SerialiseObject(VkImage, "image", el.image); Serialise("viewType", el.viewType); Serialise("format", el.format); Serialise("components", el.components); Serialise("subresourceRange", el.subresourceRange); } template <> void Serialiser::Serialise(const char *name, VkSparseMemoryBind &el) { ScopedContext scope(this, name, "VkSparseMemoryBind", 0, true); Serialise("resourceOffset", el.resourceOffset); Serialise("size", el.size); SerialiseObject(VkDeviceMemory, "memory", el.memory); Serialise("memoryOffset", el.memoryOffset); Serialise("flags", (VkSparseMemoryBindFlagBits &)el.flags); } template <> void Serialiser::Serialise(const char *name, VkSparseBufferMemoryBindInfo &el) { ScopedContext scope(this, name, "VkSparseBufferMemoryBindInfo", 0, true); SerialiseObject(VkBuffer, "buffer", el.buffer); SerialiseComplexArray("pBinds", (VkSparseMemoryBind *&)el.pBinds, el.bindCount); } template <> void Serialiser::Serialise(const char *name, VkSparseImageOpaqueMemoryBindInfo &el) { ScopedContext scope(this, name, "VkSparseImageOpaqueMemoryBindInfo", 0, true); SerialiseObject(VkImage, "image", el.image); SerialiseComplexArray("pBinds", (VkSparseMemoryBind *&)el.pBinds, el.bindCount); } template <> void Serialiser::Serialise(const char *name, VkSparseImageMemoryBind &el) { ScopedContext scope(this, name, "VkSparseImageMemoryBind", 0, true); Serialise("subresource", el.subresource); Serialise("offset", el.offset); Serialise("extent", el.extent); SerialiseObject(VkDeviceMemory, "memory", el.memory); Serialise("memoryOffset", el.memoryOffset); Serialise("flags", (VkSparseMemoryBindFlagBits &)el.flags); } template <> void Serialiser::Serialise(const char *name, VkSparseImageMemoryBindInfo &el) { ScopedContext scope(this, name, "VkSparseImageMemoryBindInfo", 0, true); SerialiseObject(VkImage, "image", el.image); SerialiseComplexArray("pBinds", (VkSparseImageMemoryBind *&)el.pBinds, el.bindCount); } template <> void Serialiser::Serialise(const char *name, VkBindSparseInfo &el) { ScopedContext scope(this, name, "VkBindSparseInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_BIND_SPARSE_INFO); SerialiseNext(this, el.sType, el.pNext); // do this one by hand because it's an array of objects that aren't Serialise // overloaded Serialise("waitSemaphoreCount", el.waitSemaphoreCount); if(m_Mode == READING) el.pWaitSemaphores = el.waitSemaphoreCount ? new VkSemaphore[el.waitSemaphoreCount] : NULL; VkSemaphore *waitsems = (VkSemaphore *)el.pWaitSemaphores; for(uint32_t i = 0; i < el.waitSemaphoreCount; i++) SerialiseObject(VkSemaphore, "pWaitSemaphores", waitsems[i]); SerialiseComplexArray("pBufferBinds", (VkSparseBufferMemoryBindInfo *&)el.pBufferBinds, el.bufferBindCount); SerialiseComplexArray("pImageOpaqueBinds", (VkSparseImageOpaqueMemoryBindInfo *&)el.pImageOpaqueBinds, el.imageOpaqueBindCount); SerialiseComplexArray("pImageBinds", (VkSparseImageMemoryBindInfo *&)el.pImageBinds, el.imageBindCount); // do this one by hand because it's an array of objects that aren't Serialise // overloaded Serialise("signalSemaphoreCount", el.signalSemaphoreCount); if(m_Mode == READING) el.pSignalSemaphores = el.signalSemaphoreCount ? new VkSemaphore[el.signalSemaphoreCount] : NULL; VkSemaphore *sigsems = (VkSemaphore *)el.pSignalSemaphores; for(uint32_t i = 0; i < el.signalSemaphoreCount; i++) SerialiseObject(VkSemaphore, "pSignalSemaphores", sigsems[i]); } template <> void Serialiser::Deserialise(const VkBindSparseInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pWaitSemaphores; for(uint32_t i = 0; i < el->bufferBindCount; i++) delete[] el->pBufferBinds[i].pBinds; delete[] el->pBufferBinds; for(uint32_t i = 0; i < el->imageOpaqueBindCount; i++) delete[] el->pImageOpaqueBinds[i].pBinds; delete[] el->pImageOpaqueBinds; delete[] el->pImageBinds; delete[] el->pSignalSemaphores; } } template <> void Serialiser::Serialise(const char *name, VkFramebufferCreateInfo &el) { ScopedContext scope(this, name, "VkFramebufferCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); SerialiseObject(VkRenderPass, "renderPass", el.renderPass); Serialise("width", el.width); Serialise("height", el.height); Serialise("layers", el.layers); // do this one by hand because it's an array of objects that aren't Serialise // overloaded Serialise("attachmentCount", el.attachmentCount); if(m_Mode == READING) el.pAttachments = el.attachmentCount ? new VkImageView[el.attachmentCount] : NULL; VkImageView *attaches = (VkImageView *)el.pAttachments; for(uint32_t i = 0; i < el.attachmentCount; i++) SerialiseObject(VkImageView, "pAttachments", attaches[i]); } template <> void Serialiser::Deserialise(const VkFramebufferCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pAttachments; } } template <> void Serialiser::Serialise(const char *name, VkAttachmentDescription &el) { ScopedContext scope(this, name, "VkAttachmentDescription", 0, true); Serialise("flags", (VkAttachmentDescriptionFlagBits &)el.flags); Serialise("format", el.format); Serialise("samples", el.samples); Serialise("loadOp", el.loadOp); Serialise("storeOp", el.storeOp); Serialise("stencilLoadOp", el.stencilLoadOp); Serialise("stencilStoreOp", el.stencilStoreOp); Serialise("initialLayout", el.initialLayout); Serialise("finalLayout", el.finalLayout); } template <> void Serialiser::Serialise(const char *name, VkSubpassDescription &el) { ScopedContext scope(this, name, "VkSubpassDescription", 0, true); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("pipelineBindPoint", el.pipelineBindPoint); SerialiseOptionalObject(this, "pDepthStencilAttachment", (VkAttachmentReference *&)el.pDepthStencilAttachment); if(m_Mode == READING) { el.pInputAttachments = NULL; el.pColorAttachments = NULL; el.pResolveAttachments = NULL; el.pPreserveAttachments = NULL; } SerialisePODArray("inputAttachments", (VkAttachmentReference *&)el.pInputAttachments, el.inputAttachmentCount); SerialisePODArray("colorAttachments", (VkAttachmentReference *&)el.pColorAttachments, el.colorAttachmentCount); bool hasResolves = (el.pResolveAttachments != NULL); Serialise("hasResolves", hasResolves); if(hasResolves) SerialisePODArray("resolveAttachments", (VkAttachmentReference *&)el.pResolveAttachments, el.colorAttachmentCount); SerialisePODArray("preserveAttachments", (VkAttachmentReference *&)el.pPreserveAttachments, el.preserveAttachmentCount); } template <> void Serialiser::Serialise(const char *name, VkSubpassDependency &el) { ScopedContext scope(this, name, "VkSubpassDependency", 0, true); Serialise("srcSubpass", el.srcSubpass); Serialise("destSubpass", el.dstSubpass); Serialise("srcStageMask", (VkPipelineStageFlagBits &)el.srcStageMask); Serialise("destStageMask", (VkPipelineStageFlagBits &)el.dstStageMask); Serialise("srcAccessMask", (VkAccessFlagBits &)el.srcAccessMask); Serialise("dstAccessMask", (VkAccessFlagBits &)el.dstAccessMask); Serialise("dependencyFlags", (VkDependencyFlagBits &)el.dependencyFlags); } template <> void Serialiser::Serialise(const char *name, VkRenderPassCreateInfo &el) { ScopedContext scope(this, name, "VkRenderPassCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); SerialiseComplexArray("pAttachments", (VkAttachmentDescription *&)el.pAttachments, el.attachmentCount); SerialiseComplexArray("pSubpasses", (VkSubpassDescription *&)el.pSubpasses, el.subpassCount); SerialiseComplexArray("pDependencies", (VkSubpassDependency *&)el.pDependencies, el.dependencyCount); } template <> void Serialiser::Deserialise(const VkRenderPassCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pAttachments; for(uint32_t i = 0; i < el->subpassCount; i++) { delete el->pSubpasses[i].pDepthStencilAttachment; delete[] el->pSubpasses[i].pInputAttachments; delete[] el->pSubpasses[i].pColorAttachments; delete[] el->pSubpasses[i].pResolveAttachments; if(el->pSubpasses[i].pPreserveAttachments) delete[] el->pSubpasses[i].pPreserveAttachments; } delete[] el->pSubpasses; delete[] el->pDependencies; } } template <> void Serialiser::Serialise(const char *name, VkRenderPassBeginInfo &el) { ScopedContext scope(this, name, "VkRenderPassBeginInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO); SerialiseNext(this, el.sType, el.pNext); SerialiseObject(VkRenderPass, "renderPass", el.renderPass); SerialiseObject(VkFramebuffer, "framebuffer", el.framebuffer); Serialise("renderArea", el.renderArea); if(m_Mode == READING) el.pClearValues = NULL; SerialisePODArray("pClearValues", (VkClearValue *&)el.pClearValues, el.clearValueCount); } template <> void Serialiser::Deserialise(const VkRenderPassBeginInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pClearValues; } } template <> void Serialiser::Serialise(const char *name, VkVertexInputBindingDescription &el) { ScopedContext scope(this, name, "VkVertexInputBindingDescription", 0, true); Serialise("binding", el.binding); Serialise("strideInBytes", el.stride); Serialise("inputRate", el.inputRate); } template <> void Serialiser::Serialise(const char *name, VkVertexInputAttributeDescription &el) { ScopedContext scope(this, name, "VkVertexInputAttributeDescription", 0, true); Serialise("location", el.location); Serialise("binding", el.binding); Serialise("format", el.format); Serialise("offset", el.offset); } template <> void Serialiser::Serialise(const char *name, VkPipelineVertexInputStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineVertexInputStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); SerialiseComplexArray("pVertexBindingDescriptions", (VkVertexInputBindingDescription *&)el.pVertexBindingDescriptions, el.vertexBindingDescriptionCount); SerialiseComplexArray("pVertexAttributeDescriptions", (VkVertexInputAttributeDescription *&)el.pVertexAttributeDescriptions, el.vertexAttributeDescriptionCount); } template <> void Serialiser::Serialise(const char *name, VkPipelineInputAssemblyStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineInputAssemblyStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("topology", el.topology); Serialise("primitiveRestartEnable", el.primitiveRestartEnable); } template <> void Serialiser::Serialise(const char *name, VkPipelineTessellationStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineTessStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("patchControlPoints", el.patchControlPoints); } template <> void Serialiser::Serialise(const char *name, VkPipelineViewportStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineViewportStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); if(m_Mode == READING) { el.pViewports = NULL; el.pScissors = NULL; } // need to handle these arrays potentially being NULL if they're dynamic bool hasViews = (el.pViewports != NULL); bool hasScissors = (el.pScissors != NULL); Serialise("hasViews", hasViews); Serialise("hasScissors", hasScissors); if(hasViews) SerialisePODArray("viewports", (VkViewport *&)el.pViewports, el.viewportCount); else Serialise("viewportCount", el.viewportCount); if(hasScissors) SerialisePODArray("scissors", (VkRect2D *&)el.pScissors, el.scissorCount); else Serialise("scissorCount", el.scissorCount); } template <> void Serialiser::Serialise(const char *name, VkPipelineRasterizationStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineRasterStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("depthClampEnable", el.depthClampEnable); Serialise("rasterizerDiscardEnable", el.rasterizerDiscardEnable); Serialise("polygonMode", el.polygonMode); Serialise("cullMode", el.cullMode); Serialise("frontFace", el.frontFace); Serialise("depthBiasEnable", el.depthBiasEnable); Serialise("depthBiasConstantFactor", el.depthBiasConstantFactor); Serialise("depthBiasClamp", el.depthBiasClamp); Serialise("depthBiasSlopeFactor", el.depthBiasSlopeFactor); Serialise("lineWidth", el.lineWidth); } template <> void Serialiser::Serialise(const char *name, VkPipelineMultisampleStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineMultisampleStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("rasterizationSamples", el.rasterizationSamples); RDCASSERT(el.rasterizationSamples <= VK_SAMPLE_COUNT_32_BIT); Serialise("sampleShadingEnable", el.sampleShadingEnable); Serialise("minSampleShading", el.minSampleShading); SerialiseOptionalObject(this, "sampleMask", (VkSampleMask *&)el.pSampleMask); Serialise("alphaToCoverageEnable", el.alphaToCoverageEnable); Serialise("alphaToOneEnable", el.alphaToOneEnable); } template <> void Serialiser::Serialise(const char *name, VkPipelineColorBlendAttachmentState &el) { ScopedContext scope(this, name, "VkPipelineColorBlendAttachmentState", 0, true); Serialise("blendEnable", el.blendEnable); Serialise("srcColorBlendFactor", el.srcColorBlendFactor); Serialise("dstColorBlendFactor", el.dstColorBlendFactor); Serialise("colorBlendOp", el.colorBlendOp); Serialise("srcAlphaBlendFactor", el.srcAlphaBlendFactor); Serialise("dstAlphaBlendFactor", el.dstAlphaBlendFactor); Serialise("alphaBlendOp", el.alphaBlendOp); Serialise("channelWriteMask", el.colorWriteMask); } template <> void Serialiser::Serialise(const char *name, VkPipelineColorBlendStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineColorBlendStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("logicOpEnable", el.logicOpEnable); Serialise("logicOp", el.logicOp); Serialise("attachmentCount", el.attachmentCount); SerialiseComplexArray("pAttachments", (VkPipelineColorBlendAttachmentState *&)el.pAttachments, el.attachmentCount); SerialisePODArray<4>("blendConstants", el.blendConstants); } template <> void Serialiser::Serialise(const char *name, VkPipelineDepthStencilStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineDepthStencilStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("depthTestEnable", el.depthTestEnable); Serialise("depthWriteEnable", el.depthWriteEnable); Serialise("depthCompareOp", el.depthCompareOp); Serialise("depthBoundsTestEnable", el.depthBoundsTestEnable); Serialise("stencilEnable", el.stencilTestEnable); Serialise("front", el.front); Serialise("back", el.back); Serialise("minDepthBounds", el.minDepthBounds); Serialise("maxDepthBounds", el.maxDepthBounds); } template <> void Serialiser::Serialise(const char *name, VkPipelineDynamicStateCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineDynamicStateCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); if(m_Mode == READING) el.pDynamicStates = NULL; SerialisePODArray("dynamicStates", (VkDynamicState *&)el.pDynamicStates, el.dynamicStateCount); } template <> void Serialiser::Serialise(const char *name, VkCommandPoolCreateInfo &el) { ScopedContext scope(this, name, "VkCommandPoolCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkCommandPoolCreateFlagBits &)el.flags); Serialise("queueFamilyIndex", el.queueFamilyIndex); } template <> void Serialiser::Serialise(const char *name, VkCommandBufferAllocateInfo &el) { ScopedContext scope(this, name, "VkCommandBufferAllocateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO); SerialiseNext(this, el.sType, el.pNext); SerialiseObject(VkCommandPool, "commandPool", el.commandPool); Serialise("level", el.level); Serialise("bufferCount", el.commandBufferCount); } template <> void Serialiser::Serialise(const char *name, VkCommandBufferInheritanceInfo &el) { ScopedContext scope(this, name, "VkCommandBufferInheritanceInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_COMMAND_BUFFER_INHERITANCE_INFO); SerialiseNext(this, el.sType, el.pNext); SerialiseObject(VkRenderPass, "renderPass", el.renderPass); Serialise("subpass", el.subpass); SerialiseObject(VkFramebuffer, "framebuffer", el.framebuffer); Serialise("occlusionQueryEnable", el.occlusionQueryEnable); Serialise("queryFlags", (VkQueryControlFlagBits &)el.queryFlags); Serialise("pipelineStatistics", (VkQueryPipelineStatisticFlagBits &)el.pipelineStatistics); } template <> void Serialiser::Serialise(const char *name, VkCommandBufferBeginInfo &el) { ScopedContext scope(this, name, "VkCommandBufferBeginInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkCommandBufferUsageFlagBits &)el.flags); SerialiseOptionalObject(this, "el.pInheritanceInfo", (VkCommandBufferInheritanceInfo *&)el.pInheritanceInfo); } template <> void Serialiser::Deserialise(const VkCommandBufferBeginInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete el->pInheritanceInfo; } } template <> void Serialiser::Serialise(const char *name, VkStencilOpState &el) { ScopedContext scope(this, name, "VkStencilOpState", 0, true); Serialise("failOp", el.failOp); Serialise("passOp", el.passOp); Serialise("depthFailOp", el.depthFailOp); Serialise("compareOp", el.compareOp); Serialise("compareMask", el.compareMask); Serialise("writeMask", el.writeMask); Serialise("reference", el.reference); } template <> void Serialiser::Serialise(const char *name, VkQueryPoolCreateInfo &el) { ScopedContext scope(this, name, "VkQueryPoolCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("queryType", el.queryType); Serialise("queryCount", el.queryCount); Serialise("pipelineStatistics", (VkQueryPipelineStatisticFlagBits &)el.pipelineStatistics); } template <> void Serialiser::Serialise(const char *name, VkSemaphoreCreateInfo &el) { ScopedContext scope(this, name, "VkSemaphoreCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); } template <> void Serialiser::Serialise(const char *name, VkEventCreateInfo &el) { ScopedContext scope(this, name, "VkEventCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_EVENT_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); } template <> void Serialiser::Serialise(const char *name, VkFenceCreateInfo &el) { ScopedContext scope(this, name, "VkFenceCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_FENCE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFenceCreateFlagBits &)el.flags); } template <> void Serialiser::Serialise(const char *name, VkSamplerCreateInfo &el) { ScopedContext scope(this, name, "VkSamplerCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("minFilter", el.minFilter); Serialise("magFilter", el.magFilter); Serialise("mipmapMode", el.mipmapMode); Serialise("addressModeU", el.addressModeU); Serialise("addressModeV", el.addressModeV); Serialise("addressModeW", el.addressModeW); Serialise("mipLodBias", el.mipLodBias); Serialise("anisotropyEnable", el.anisotropyEnable); Serialise("maxAnisotropy", el.maxAnisotropy); Serialise("compareEnable", el.compareEnable); Serialise("compareOp", el.compareOp); Serialise("minLod", el.minLod); Serialise("maxLod", el.maxLod); Serialise("borderColor", el.borderColor); Serialise("unnormalizedCoordinates", el.unnormalizedCoordinates); } template <> void Serialiser::Serialise(const char *name, VkPipelineShaderStageCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineShaderStageCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); Serialise("stage", el.stage); SerialiseObject(VkShaderModule, "module", el.module); string s = ""; if(m_Mode >= WRITING && el.pName != NULL) s = el.pName; Serialise("pName", s); if(m_Mode == READING) { if(s == "") { el.pName = ""; } else { string str; str.assign((char *)m_BufferHead - s.length(), s.length()); m_StringDB.insert(str); el.pName = m_StringDB.find(str)->c_str(); } } SerialiseOptionalObject(this, "el.pSpecializationInfo", (VkSpecializationInfo *&)el.pSpecializationInfo); } template <> void Serialiser::Serialise(const char *name, VkSpecializationMapEntry &el) { ScopedContext scope(this, name, "VkSpecializationMapEntry", 0, true); Serialise("constantId", el.constantID); Serialise("offset", el.offset); uint64_t size = el.size; Serialise("size", size); if(m_Mode == READING) el.size = (size_t)size; } template <> void Serialiser::Serialise(const char *name, VkSpecializationInfo &el) { ScopedContext scope(this, name, "VkSpecializationInfo", 0, true); uint64_t dataSize = el.dataSize; Serialise("dataSize", dataSize); size_t sz = (size_t)dataSize; if(m_Mode == READING) { el.pData = NULL; el.dataSize = sz; } SerialiseBuffer("pData", (byte *&)el.pData, sz); SerialiseComplexArray("pMapEntries", (VkSpecializationMapEntry *&)el.pMapEntries, el.mapEntryCount); } template <> void Serialiser::Serialise(const char *name, VkPipelineCacheCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineCacheCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); uint64_t initialDataSize = el.initialDataSize; Serialise("codeSize", initialDataSize); el.initialDataSize = (size_t)initialDataSize; if(m_Mode == READING) el.pInitialData = NULL; SerialiseBuffer("initialData", (byte *&)el.pInitialData, el.initialDataSize); } template <> void Serialiser::Deserialise(const VkPipelineCacheCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[](byte *)(el->pInitialData); } } template <> void Serialiser::Serialise(const char *name, VkPipelineLayoutCreateInfo &el) { ScopedContext scope(this, name, "VkPipelineLayoutCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); // need to do this one by hand since it's just an array of objects that don't themselves have // a Serialise overload Serialise("descriptorSetCount", el.setLayoutCount); if(m_Mode == READING) el.pSetLayouts = el.setLayoutCount ? new VkDescriptorSetLayout[el.setLayoutCount] : NULL; // cast away const on array so we can assign to it on reading VkDescriptorSetLayout *layouts = (VkDescriptorSetLayout *)el.pSetLayouts; for(uint32_t i = 0; i < el.setLayoutCount; i++) SerialiseObject(VkDescriptorSetLayout, "layout", layouts[i]); SerialiseComplexArray("pPushConstantRanges", (VkPushConstantRange *&)el.pPushConstantRanges, el.pushConstantRangeCount); } template <> void Serialiser::Deserialise(const VkPipelineLayoutCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pSetLayouts; delete[] el->pPushConstantRanges; } } template <> void Serialiser::Serialise(const char *name, VkShaderModuleCreateInfo &el) { ScopedContext scope(this, name, "VkShaderModuleCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); uint64_t codeSize = el.codeSize; Serialise("codeSize", codeSize); el.codeSize = (size_t)codeSize; size_t sz = (size_t)codeSize; if(m_Mode == READING) el.pCode = NULL; SerialiseBuffer("pCode", (byte *&)el.pCode, sz); } template <> void Serialiser::Deserialise(const VkShaderModuleCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[](byte *)(el->pCode); } } template <> void Serialiser::Serialise(const char *name, VkImageSubresourceRange &el) { ScopedContext scope(this, name, "VkImageSubresourceRange", 0, true); Serialise("aspectMask", (VkImageAspectFlagBits &)el.aspectMask); Serialise("baseMipLevel", el.baseMipLevel); Serialise("levelCount", el.levelCount); Serialise("baseArrayLayer", el.baseArrayLayer); Serialise("layerCount", el.layerCount); } template <> void Serialiser::Serialise(const char *name, VkImageSubresourceLayers &el) { ScopedContext scope(this, name, "VkImageSubresourceLayers", 0, true); Serialise("aspectMask", (VkImageAspectFlagBits &)el.aspectMask); Serialise("mipLevel", el.mipLevel); Serialise("baseArrayLayer", el.baseArrayLayer); Serialise("layerCount", el.layerCount); } template <> void Serialiser::Serialise(const char *name, VkImageSubresource &el) { ScopedContext scope(this, name, "VkImageSubresource", 0, true); Serialise("aspectMask", (VkImageAspectFlagBits &)el.aspectMask); Serialise("mipLevel", el.mipLevel); Serialise("arrayLayer", el.arrayLayer); } template <> void Serialiser::Serialise(const char *name, VkMemoryAllocateInfo &el) { ScopedContext scope(this, name, "VkMemoryAllocateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("allocationSize", el.allocationSize); Serialise("memoryTypeIndex", el.memoryTypeIndex); } template <> void Serialiser::Serialise(const char *name, VkMemoryBarrier &el) { ScopedContext scope(this, name, "VkMemoryBarrier", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_MEMORY_BARRIER); SerialiseNext(this, el.sType, el.pNext); Serialise("srcAccessMask", (VkAccessFlagBits &)el.srcAccessMask); Serialise("dstAccessMask", (VkAccessFlagBits &)el.dstAccessMask); } template <> void Serialiser::Serialise(const char *name, VkBufferMemoryBarrier &el) { ScopedContext scope(this, name, "VkBufferMemoryBarrier", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER); SerialiseNext(this, el.sType, el.pNext); Serialise("srcAccessMask", (VkAccessFlagBits &)el.srcAccessMask); Serialise("dstAccessMask", (VkAccessFlagBits &)el.dstAccessMask); // serialise as signed because then QUEUE_FAMILY_IGNORED is -1 and queue // family index won't be legitimately larger than 2 billion Serialise("srcQueueFamilyIndex", (int32_t &)el.srcQueueFamilyIndex); Serialise("dstQueueFamilyIndex", (int32_t &)el.dstQueueFamilyIndex); SerialiseObject(VkBuffer, "buffer", el.buffer); Serialise("offset", el.offset); Serialise("size", el.size); } template <> void Serialiser::Serialise(const char *name, VkImageMemoryBarrier &el) { ScopedContext scope(this, name, "VkImageMemoryBarrier", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER); SerialiseNext(this, el.sType, el.pNext); Serialise("srcAccessMask", (VkAccessFlagBits &)el.srcAccessMask); Serialise("dstAccessMask", (VkAccessFlagBits &)el.dstAccessMask); Serialise("oldLayout", el.oldLayout); Serialise("newLayout", el.newLayout); // serialise as signed because then QUEUE_FAMILY_IGNORED is -1 and queue // family index won't be legitimately larger than 2 billion Serialise("srcQueueFamilyIndex", (int32_t &)el.srcQueueFamilyIndex); Serialise("dstQueueFamilyIndex", (int32_t &)el.dstQueueFamilyIndex); SerialiseObject(VkImage, "image", el.image); Serialise("subresourceRange", el.subresourceRange); } template <> void Serialiser::Serialise(const char *name, VkGraphicsPipelineCreateInfo &el) { ScopedContext scope(this, name, "VkGraphicsPipelineCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkPipelineCreateFlagBits &)el.flags); SerialiseObject(VkPipelineLayout, "layout", el.layout); SerialiseObject(VkRenderPass, "renderPass", el.renderPass); Serialise("subpass", el.subpass); SerialiseObject(VkPipeline, "basePipelineHandle", el.basePipelineHandle); Serialise("basePipelineIndex", el.basePipelineIndex); SerialiseOptionalObject(this, "pVertexInputState", (VkPipelineVertexInputStateCreateInfo *&)el.pVertexInputState); SerialiseOptionalObject(this, "pInputAssemblyState", (VkPipelineInputAssemblyStateCreateInfo *&)el.pInputAssemblyState); SerialiseOptionalObject(this, "pTessellationState", (VkPipelineTessellationStateCreateInfo *&)el.pTessellationState); SerialiseOptionalObject(this, "pViewportState", (VkPipelineViewportStateCreateInfo *&)el.pViewportState); SerialiseOptionalObject(this, "pRasterState", (VkPipelineRasterizationStateCreateInfo *&)el.pRasterizationState); SerialiseOptionalObject(this, "pMultisampleState", (VkPipelineMultisampleStateCreateInfo *&)el.pMultisampleState); SerialiseOptionalObject(this, "pDepthStencilState", (VkPipelineDepthStencilStateCreateInfo *&)el.pDepthStencilState); SerialiseOptionalObject(this, "pColorBlendState", (VkPipelineColorBlendStateCreateInfo *&)el.pColorBlendState); SerialiseOptionalObject(this, "pDynamicState", (VkPipelineDynamicStateCreateInfo *&)el.pDynamicState); SerialiseComplexArray("pStages", (VkPipelineShaderStageCreateInfo *&)el.pStages, el.stageCount); } template <> void Serialiser::Deserialise(const VkGraphicsPipelineCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete if(el->pVertexInputState) { RDCASSERT(el->pVertexInputState->pNext == NULL); // otherwise delete delete[] el->pVertexInputState->pVertexBindingDescriptions; delete[] el->pVertexInputState->pVertexAttributeDescriptions; delete el->pVertexInputState; } if(el->pInputAssemblyState) { RDCASSERT(el->pInputAssemblyState->pNext == NULL); // otherwise delete delete el->pInputAssemblyState; } if(el->pTessellationState) { RDCASSERT(el->pTessellationState->pNext == NULL); // otherwise delete delete el->pTessellationState; } if(el->pViewportState) { RDCASSERT(el->pViewportState->pNext == NULL); // otherwise delete if(el->pViewportState->pViewports) delete[] el->pViewportState->pViewports; if(el->pViewportState->pScissors) delete[] el->pViewportState->pScissors; delete el->pViewportState; } if(el->pRasterizationState) { RDCASSERT(el->pRasterizationState->pNext == NULL); // otherwise delete delete el->pRasterizationState; } if(el->pMultisampleState) { RDCASSERT(el->pMultisampleState->pNext == NULL); // otherwise delete delete el->pMultisampleState->pSampleMask; delete el->pMultisampleState; } if(el->pDepthStencilState) { RDCASSERT(el->pDepthStencilState->pNext == NULL); // otherwise delete delete el->pDepthStencilState; } if(el->pColorBlendState) { RDCASSERT(el->pColorBlendState->pNext == NULL); // otherwise delete delete[] el->pColorBlendState->pAttachments; delete el->pColorBlendState; } if(el->pDynamicState) { RDCASSERT(el->pDynamicState->pNext == NULL); // otherwise delete if(el->pDynamicState->pDynamicStates) delete[] el->pDynamicState->pDynamicStates; delete el->pDynamicState; } for(uint32_t i = 0; i < el->stageCount; i++) { RDCASSERT(el->pStages[i].pNext == NULL); // otherwise delete if(el->pStages[i].pSpecializationInfo) { delete[](byte *)(el->pStages[i].pSpecializationInfo->pData); delete[] el->pStages[i].pSpecializationInfo->pMapEntries; delete el->pStages[i].pSpecializationInfo; } } delete[] el->pStages; } } template <> void Serialiser::Serialise(const char *name, VkComputePipelineCreateInfo &el) { ScopedContext scope(this, name, "VkComputePipelineCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("stage", el.stage); Serialise("flags", (VkPipelineCreateFlagBits &)el.flags); SerialiseObject(VkPipelineLayout, "layout", el.layout); SerialiseObject(VkPipeline, "basePipelineHandle", el.basePipelineHandle); Serialise("basePipelineIndex", el.basePipelineIndex); } template <> void Serialiser::Deserialise(const VkComputePipelineCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete RDCASSERT(el->stage.pNext == NULL); // otherwise delete if(el->stage.pSpecializationInfo) { delete[](byte *)(el->stage.pSpecializationInfo->pData); delete[] el->stage.pSpecializationInfo->pMapEntries; delete el->stage.pSpecializationInfo; } } } template <> void Serialiser::Serialise(const char *name, VkDescriptorPoolSize &el) { ScopedContext scope(this, name, "VkDescriptorPoolSize", 0, true); Serialise("type", el.type); Serialise("descriptorCount", el.descriptorCount); } template <> void Serialiser::Serialise(const char *name, VkDescriptorPoolCreateInfo &el) { ScopedContext scope(this, name, "VkDescriptorPoolCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkDescriptorPoolCreateFlagBits &)el.flags); Serialise("maxSets", el.maxSets); SerialiseComplexArray("pTypeCount", (VkDescriptorPoolSize *&)el.pPoolSizes, el.poolSizeCount); } template <> void Serialiser::Deserialise(const VkDescriptorPoolCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pPoolSizes; } } template <> void Serialiser::Serialise(const char *name, VkDescriptorSetAllocateInfo &el) { ScopedContext scope(this, name, "VkDescriptorSetAllocateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO); SerialiseNext(this, el.sType, el.pNext); SerialiseObject(VkDescriptorPool, "descriptorPool", el.descriptorPool); // need to do this one by hand since it's just an array of objects that don't themselves have // a Serialise overload Serialise("descriptorSetCount", el.descriptorSetCount); if(m_Mode == READING) el.pSetLayouts = el.descriptorSetCount ? new VkDescriptorSetLayout[el.descriptorSetCount] : NULL; // cast away const on array so we can assign to it on reading VkDescriptorSetLayout *layouts = (VkDescriptorSetLayout *)el.pSetLayouts; for(uint32_t i = 0; i < el.descriptorSetCount; i++) SerialiseObject(VkDescriptorSetLayout, "pSetLayouts", layouts[i]); } template <> void Serialiser::Deserialise(const VkDescriptorSetAllocateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete delete[] el->pSetLayouts; } } template <> void Serialiser::Serialise(const char *name, VkDescriptorImageInfo &el) { ScopedContext scope(this, name, "VkDescriptorImageInfo", 0, true); SerialiseObjectOptional(VkSampler, "sampler", el.sampler); SerialiseObjectOptional(VkImageView, "imageView", el.imageView); Serialise("imageLayout", el.imageLayout); } template <> void Serialiser::Serialise(const char *name, VkDescriptorBufferInfo &el) { ScopedContext scope(this, name, "VkDescriptorBufferInfo", 0, true); SerialiseObjectOptional(VkBuffer, "buffer", el.buffer); Serialise("offset", el.offset); Serialise("range", el.range); } template <> void Serialiser::Serialise(const char *name, VkWriteDescriptorSet &el) { ScopedContext scope(this, name, "VkWriteDescriptorSet", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET); SerialiseNext(this, el.sType, el.pNext); SerialiseObjectOptional(VkDescriptorSet, "dstSet", el.dstSet); Serialise("dstBinding", el.dstBinding); Serialise("dstArrayElement", el.dstArrayElement); Serialise("descriptorType", el.descriptorType); if(m_Mode == READING) { el.pImageInfo = NULL; el.pBufferInfo = NULL; el.pTexelBufferView = NULL; } // only serialise the array type used, the others are ignored if(el.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLER || el.descriptorType == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER || el.descriptorType == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE || el.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE || el.descriptorType == VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT) { SerialiseComplexArray("pImageInfo", (VkDescriptorImageInfo *&)el.pImageInfo, el.descriptorCount); } else if(el.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER || el.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER || el.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC || el.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC) { SerialiseComplexArray("pBufferInfo", (VkDescriptorBufferInfo *&)el.pBufferInfo, el.descriptorCount); } else if(el.descriptorType == VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER || el.descriptorType == VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER) { // need to do this one by hand since it's just an array of objects that don't themselves have // a Serialise overload Serialise("descriptorCount", el.descriptorCount); if(m_Mode == READING) el.pTexelBufferView = el.descriptorCount ? new VkBufferView[el.descriptorCount] : NULL; // cast away const on array so we can assign to it on reading VkBufferView *views = (VkBufferView *)el.pTexelBufferView; for(uint32_t i = 0; i < el.descriptorCount; i++) SerialiseObjectOptional(VkBufferView, "pTexelBufferView", views[i]); } } template <> void Serialiser::Deserialise(const VkWriteDescriptorSet *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete if(el->pImageInfo) delete[] el->pImageInfo; if(el->pBufferInfo) delete[] el->pBufferInfo; if(el->pTexelBufferView) delete[] el->pTexelBufferView; } } template <> void Serialiser::Serialise(const char *name, VkCopyDescriptorSet &el) { ScopedContext scope(this, name, "VkCopyDescriptorSet", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_COPY_DESCRIPTOR_SET); SerialiseNext(this, el.sType, el.pNext); SerialiseObjectOptional(VkDescriptorSet, "srcSet", el.srcSet); Serialise("srcBinding", el.srcBinding); Serialise("srcArrayElement", el.srcArrayElement); SerialiseObjectOptional(VkDescriptorSet, "destSet", el.dstSet); Serialise("destBinding", el.dstBinding); Serialise("destArrayElement", el.dstArrayElement); Serialise("descriptorCount", el.descriptorCount); } template <> void Serialiser::Serialise(const char *name, VkPushConstantRange &el) { ScopedContext scope(this, name, "VkPushConstantRange", 0, true); Serialise("stageFlags", (VkShaderStageFlagBits &)el.stageFlags); Serialise("offset", el.offset); Serialise("size", el.size); } template <> void Serialiser::Serialise(const char *name, VkDescriptorSetLayoutBinding &el) { ScopedContext scope(this, name, "VkDescriptorSetLayoutBinding", 0, true); Serialise("binding", el.binding); Serialise("descriptorType", el.descriptorType); Serialise("descriptorCount", el.descriptorCount); Serialise("stageFlags", (VkShaderStageFlagBits &)el.stageFlags); bool hasSamplers = el.pImmutableSamplers != NULL; Serialise("hasSamplers", hasSamplers); // do this one by hand because it's an array of objects that aren't Serialise // overloaded if(m_Mode == READING) { if(hasSamplers) el.pImmutableSamplers = el.descriptorCount ? new VkSampler[el.descriptorCount] : NULL; else el.pImmutableSamplers = NULL; } VkSampler *samplers = (VkSampler *)el.pImmutableSamplers; for(uint32_t i = 0; hasSamplers && i < el.descriptorCount; i++) { SerialiseObject(VkSampler, "pImmutableSampler", samplers[i]); } } template <> void Serialiser::Serialise(const char *name, VkDescriptorSetLayoutCreateInfo &el) { ScopedContext scope(this, name, "VkDescriptorSetLayoutCreateInfo", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); SerialiseComplexArray("pBindings", (VkDescriptorSetLayoutBinding *&)el.pBindings, el.bindingCount); } template <> void Serialiser::Deserialise(const VkDescriptorSetLayoutCreateInfo *const el) const { if(m_Mode == READING) { RDCASSERT(el->pNext == NULL); // otherwise delete for(uint32_t i = 0; i < el->bindingCount; i++) if(el->pBindings[i].pImmutableSamplers) delete[] el->pBindings[i].pImmutableSamplers; delete[] el->pBindings; } } template <> void Serialiser::Serialise(const char *name, VkComponentMapping &el) { ScopedContext scope(this, name, "VkComponentMapping", 0, true); Serialise("r", el.r); Serialise("g", el.g); Serialise("b", el.b); Serialise("a", el.a); } template <> void Serialiser::Serialise(const char *name, VkBufferImageCopy &el) { ScopedContext scope(this, name, "VkBufferImageCopy", 0, true); Serialise("memOffset", el.bufferOffset); Serialise("bufferRowLength", el.bufferRowLength); Serialise("bufferImageHeight", el.bufferImageHeight); Serialise("imageSubresource", el.imageSubresource); Serialise("imageOffset", el.imageOffset); Serialise("imageExtent", el.imageExtent); } template <> void Serialiser::Serialise(const char *name, VkBufferCopy &el) { ScopedContext scope(this, name, "VkBufferCopy", 0, true); Serialise("srcOffset", el.srcOffset); Serialise("dstOffset", el.dstOffset); Serialise("size", el.size); } template <> void Serialiser::Serialise(const char *name, VkImageCopy &el) { ScopedContext scope(this, name, "VkImageCopy", 0, true); Serialise("srcSubresource", el.srcSubresource); Serialise("srcOffset", el.srcOffset); Serialise("dstSubresource", el.dstSubresource); Serialise("dstOffset", el.dstOffset); Serialise("extent", el.extent); } template <> void Serialiser::Serialise(const char *name, VkImageBlit &el) { ScopedContext scope(this, name, "VkImageBlit", 0, true); Serialise("srcSubresource", el.srcSubresource); SerialisePODArray<2>("srcOffsets", el.srcOffsets); Serialise("dstSubresource", el.dstSubresource); SerialisePODArray<2>("dstOffsets", el.dstOffsets); } template <> void Serialiser::Serialise(const char *name, VkImageResolve &el) { ScopedContext scope(this, name, "VkImageResolve", 0, true); Serialise("srcSubresource", el.srcSubresource); Serialise("srcOffset", el.srcOffset); Serialise("dstSubresource", el.dstSubresource); Serialise("dstOffset", el.dstOffset); Serialise("extent", el.extent); } template <> void Serialiser::Serialise(const char *name, VkRect2D &el) { ScopedContext scope(this, name, "VkRect2D", 0, true); Serialise("offset", el.offset); Serialise("extent", el.extent); } template <> void Serialiser::Serialise(const char *name, VkSwapchainCreateInfoKHR &el) { ScopedContext scope(this, name, "VkSwapchainCreateInfoKHR", 0, true); RDCASSERT(m_Mode < WRITING || el.sType == VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR); SerialiseNext(this, el.sType, el.pNext); Serialise("flags", (VkFlagWithNoBits &)el.flags); // don't need the surface Serialise("minImageCount", el.minImageCount); Serialise("imageFormat", el.imageFormat); Serialise("imageColorSpace", el.imageColorSpace); Serialise("imageExtent", el.imageExtent); Serialise("imageArrayLayers", el.imageArrayLayers); Serialise("imageUsage", el.imageUsage); // SHARING: sharingMode, queueFamilyCount, pQueueFamilyIndices Serialise("preTransform", el.preTransform); Serialise("compositeAlpha", el.compositeAlpha); Serialise("presentMode", el.presentMode); Serialise("clipped", el.clipped); // don't need the old swap chain } // this isn't a real vulkan type, it's our own "anything that could be in a descriptor" // structure that template <> void Serialiser::Serialise(const char *name, DescriptorSetSlot &el) { SerialiseObject(VkBuffer, "bufferInfo.buffer", el.bufferInfo.buffer); Serialise("bufferInfo.offset", el.bufferInfo.offset); Serialise("bufferInfo.range", el.bufferInfo.range); SerialiseObject(VkSampler, "imageInfo.sampler", el.imageInfo.sampler); SerialiseObject(VkImageView, "imageInfo.imageView", el.imageInfo.imageView); Serialise("imageInfo.imageLayout", el.imageInfo.imageLayout); SerialiseObject(VkBufferView, "texelBufferView", el.texelBufferView); }
37.618909
106
0.75953
[ "object" ]
fdaa4692f8e7ce4d3cddb690a80738c2117fe79a
2,413
cpp
C++
Uva/Uva_AC/10530 Guessing Game.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
3
2018-05-11T07:33:20.000Z
2020-08-30T11:02:02.000Z
Uva/Uva_AC/10530 Guessing Game.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
1
2018-05-11T18:10:26.000Z
2018-05-12T18:00:28.000Z
Uva/Uva_AC/10530 Guessing Game.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
null
null
null
/*************************************************** * Problem name : 10530 Guessing Game.cpp * OJ : Uva * Verdict : AC * Date : 18.06.2017 * Problem Type : AdHoc * Author Name : Saikat Sharma * University : CSE, MBSTU ***************************************************/ #include<iostream> #include<cstdio> #include<algorithm> #include<climits> #include<cstring> #include<string> #include<sstream> #include<cmath> #include<vector> #include<queue> #include<cstdlib> #include<deque> #include<stack> #include<map> #include<set> #define __FastIO ios_base::sync_with_stdio(false); cin.tie(0) #define SET(a) memset(a,-1,sizeof(a)) #define pii pair<int,int> #define pll pair <int, int> #define debug printf("#########\n") #define nl printf("\n") #define sl(n) scanf("%lld", &n) #define sf(n) scanf("%lf", &n) #define si(n) scanf("%d", &n) #define ss(n) scanf("%s", n) #define pb push_back #define MAX 10 using namespace std; typedef long long ll; typedef unsigned long long ull; template <typename T> std::string NumberToString ( T Number ) { std::ostringstream ss; ss << Number; return ss.str(); } ll gcd(ll a, ll b) { if (a % b == 0) return b; return gcd(b, a % b); } /************************************ Code Start Here ******************************************************/ int main () { int n, ans; string str; vector<int>H, L; while (scanf("%d", &n) == 1 && n != 0) { while (getline(cin, str)) { if (str == "right on") { ans = n; break; }else if (str == "too high") { H.push_back(n); } else if (str == "too low") { L.push_back(n); } scanf("%d", &n); } //printf("%d\n", ans); bool flag = false; int sz = H.size(); for (int i = 0; i < sz; i++) { if (ans >= H[i]) { flag = true ; break; } } if (flag) printf("Stan is dishonest\n"); else { sz = L.size(); for (int i = 0; i < sz; i++) { if (L[i] >= ans) { flag = true; } } if (flag) printf("Stan is dishonest\n"); else printf("Stan may be honest\n"); } L.clear(); H.clear(); } return 0; }
25.135417
109
0.452549
[ "vector" ]
fdac96be3dd4244f3d428bd6eb088f2d49fb959a
4,535
cpp
C++
main/source/mod/AvHPistol.cpp
fmoraw/NS
6c3ae93ca7f929f24da4b8f2d14ea0602184cf08
[ "Unlicense" ]
27
2015-01-05T19:25:14.000Z
2022-03-20T00:34:34.000Z
main/source/mod/AvHPistol.cpp
fmoraw/NS
6c3ae93ca7f929f24da4b8f2d14ea0602184cf08
[ "Unlicense" ]
9
2015-01-14T06:51:46.000Z
2021-03-19T12:07:18.000Z
main/source/mod/AvHPistol.cpp
fmoraw/NS
6c3ae93ca7f929f24da4b8f2d14ea0602184cf08
[ "Unlicense" ]
5
2015-01-11T10:31:24.000Z
2021-01-06T01:32:58.000Z
//======== (C) Copyright 2002 Charles G. Cleveland All rights reserved. ========= // // The copyright to the contents herein is the property of Charles G. Cleveland. // The contents may be used and/or copied only with the written permission of // Charles G. Cleveland, or in accordance with the terms and conditions stipulated in // the agreement/contract under which the contents have been supplied. // // Purpose: // // $Workfile: AvHPistol.cpp $ // $Date: 2002/11/22 21:28:17 $ // //------------------------------------------------------------------------------- // $Log: AvHPistol.cpp,v $ // Revision 1.13 2002/11/22 21:28:17 Flayra // - mp_consistency changes // // Revision 1.12 2002/10/16 20:53:09 Flayra // - Removed weapon upgrade sounds // // Revision 1.11 2002/10/03 18:46:58 Flayra // - Added heavy view model // // Revision 1.10 2002/08/09 01:09:00 Flayra // - Made pistol faster to deploy // // Revision 1.9 2002/07/24 19:09:17 Flayra // - Linux issues // // Revision 1.8 2002/07/24 18:45:42 Flayra // - Linux and scripting changes // // Revision 1.7 2002/07/08 17:08:52 Flayra // - Tweaked for bullet spread // // Revision 1.6 2002/06/25 17:50:59 Flayra // - Reworking for correct player animations and new enable/disable state, new view model artwork, alien weapon refactoring // // Revision 1.5 2002/06/03 16:37:31 Flayra // - Constants and tweaks to make weapon anims and times correct with new artwork, added different deploy times (this should be refactored a bit more) // // Revision 1.4 2002/05/28 17:44:58 Flayra // - Tweak weapon deploy volume, as Valve's sounds weren't normalized // // Revision 1.3 2002/05/23 02:33:20 Flayra // - Post-crash checkin. Restored @Backup from around 4/16. Contains changes for last four weeks of development. // //=============================================================================== #include "AvHMarineWeapons.h" #include "AvHPlayer.h" #ifdef AVH_CLIENT #include "cl_dll/eventscripts.h" #include "cl_dll/in_defs.h" #include "cl_dll/wrect.h" #include "cl_dll/cl_dll.h" #endif #include "../common/hldm.h" #include "../common/event_api.h" #include "../common/event_args.h" #include "../common/vector_util.h" #include "AvHMarineWeapons.h" #include "../dlls/util.h" LINK_ENTITY_TO_CLASS(kwPistol, AvHPistol); void V_PunchAxis( int axis, float punch ); void AvHPistol::Init() { this->mRange = kHGRange; this->mDamage = BALANCE_VAR(kHGDamage); } int AvHPistol::GetBarrelLength() const { return kHGBarrelLength; } float AvHPistol::GetRateOfFire() const { return BALANCE_VAR(kHGROF); } int AvHPistol::GetDeployAnimation() const { return 6; } char* AvHPistol::GetDeploySound() const { return kHGDeploySound; } float AvHPistol::GetDeployTime() const { return .35f; } int AvHPistol::GetEmptyShootAnimation() const { return 5; } char* AvHPistol::GetHeavyViewModel() const { return kHGHVVModel; } char* AvHPistol::GetPlayerModel() const { return kHGPModel; } Vector AvHPistol::GetProjectileSpread() const { return kHGSpread; } char* AvHPistol::GetViewModel() const { return kHGVModel; } char* AvHPistol::GetWorldModel() const { return kHGWModel; } int AvHPistol::GetReloadAnimation() const { int theReloadAnimation = 2; // If empty, use empty reload bool theHasAmmo = (this->m_iClip > 0);// || (this->m_pPlayer->m_rgAmmo[this->m_iPrimaryAmmoType] > 0); if(!theHasAmmo) { theReloadAnimation = 3; } return theReloadAnimation; } int AvHPistol::GetShootAnimation() const { return 4; } bool AvHPistol::GetHasMuzzleFlash() const { return true; } bool AvHPistol::GetMustPressTriggerForEachShot() const { return true; } float AvHPistol::GetReloadTime(void) const { return 3.0f; } void AvHPistol::Precache() { AvHMarineWeapon::Precache(); PRECACHE_UNMODIFIED_MODEL(kHGEjectModel); PRECACHE_UNMODIFIED_SOUND(kHGFireSound1); PRECACHE_UNMODIFIED_SOUND(kHGReloadSound); PRECACHE_UNMODIFIED_MODEL(kGenericWallpuff); this->mEvent = PRECACHE_EVENT(1, kHGEventName); } void AvHPistol::Spawn() { AvHMarineWeapon::Spawn(); Precache(); this->m_iId = AVH_WEAPON_PISTOL; this->m_iDefaultAmmo = BALANCE_VAR(kHGMaxClip)*(BALANCE_VAR(kMarineSpawnClips) + 1); // Set our class name this->pev->classname = MAKE_STRING(kwsPistol); SET_MODEL(ENT(this->pev), kHGWModel); FallInit();// get ready to fall down. }
23.25641
151
0.66527
[ "vector", "model" ]
fdaf9c7f84c6c0c83937ff44af37aa18307c42ae
2,843
hpp
C++
libs/ledger/include/ledger/dag/dag_interface.hpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
96
2018-08-23T16:49:05.000Z
2021-11-25T00:47:16.000Z
libs/ledger/include/ledger/dag/dag_interface.hpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
1,011
2018-08-17T12:25:21.000Z
2021-11-18T09:30:19.000Z
libs/ledger/include/ledger/dag/dag_interface.hpp
chr15murray/ledger
85be05221f19598de8c6c58652139a1f2d9e362f
[ "Apache-2.0" ]
65
2018-08-20T20:05:40.000Z
2022-02-26T23:54:35.000Z
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2020 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "ledger/dag/dag_epoch.hpp" #include "ledger/dag/dag_hash.hpp" #include "ledger/dag/dag_node.hpp" #include "ledger/upow/work.hpp" #include <cstdint> #include <set> #include <vector> namespace fetch { namespace crypto { class Prover; } namespace ledger { /** * DAG implementation. */ class DAGInterface { public: using ConstByteArray = byte_array::ConstByteArray; using NodeHash = DAGHash; using EpochHash = DAGHash; using CertificatePtr = std::shared_ptr<crypto::Prover>; // TODO(HUT): cleanly define things here using MissingTXs = std::set<NodeHash>; using MissingNodes = std::set<DAGNode>; enum class DAGTypes { DATA }; DAGInterface() = default; virtual ~DAGInterface() = default; // TODO(HUT): resolve this part of the interface virtual void AddTransaction(chain::Transaction const &tx, DAGTypes type) = 0; virtual void AddWork(Work const &work) = 0; virtual void AddArbitrary(ConstByteArray const &payload) = 0; virtual DAGEpoch CreateEpoch(uint64_t block_number) = 0; virtual bool CommitEpoch(DAGEpoch) = 0; virtual bool RevertToEpoch(uint64_t) = 0; virtual uint64_t CurrentEpoch() const = 0; virtual bool HasEpoch(EpochHash const &hash) = 0; virtual bool SatisfyEpoch(DAGEpoch const &) = 0; virtual std::vector<DAGNode> GetLatest(bool previous_epoch_only) = 0; // Functions used for syncing virtual std::vector<DAGNode> GetRecentlyAdded() = 0; virtual MissingTXs GetRecentlyMissing() = 0; virtual bool GetDAGNode(DAGHash const &hash, DAGNode &node) = 0; virtual bool GetWork(DAGHash const &hash, Work &work) = 0; virtual bool AddDAGNode(DAGNode node) = 0; }; } // namespace ledger } // namespace fetch
35.098765
82
0.592684
[ "vector" ]
fdb512873a62425779e211273f422ca31940e535
844
cpp
C++
src/island.cpp
mayankmusaddi/PlaneSimulation-OpenGL
cc863f0e80e9a85c0ffe033e7aa6a9f44edd11b6
[ "MIT" ]
null
null
null
src/island.cpp
mayankmusaddi/PlaneSimulation-OpenGL
cc863f0e80e9a85c0ffe033e7aa6a9f44edd11b6
[ "MIT" ]
null
null
null
src/island.cpp
mayankmusaddi/PlaneSimulation-OpenGL
cc863f0e80e9a85c0ffe033e7aa6a9f44edd11b6
[ "MIT" ]
null
null
null
#include "island.h" #include "main.h" #include "primitives.h" Island::Island(float x, float y,float z, float size) { this->position = glm::vec3(x, y, z); this->rotation = 90; this->size = size; int n=40; GLfloat island[100000]; makeCylinder(0,0,0, size , size*0.80f, 10.0f , n , island); this->island = create3DObject(GL_TRIANGLES, 4*n*3 , island, COLOR_YELLOW , GL_FILL); } void Island::draw(glm::mat4 VP) { Matrices.model = glm::mat4(1.0f); glm::mat4 translate = glm::translate (this->position); // glTranslatef glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(1, 0, 0)); Matrices.model *= (translate * rotate); glm::mat4 MVP = VP * Matrices.model; glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]); draw3DObject(this->island); }
33.76
100
0.636256
[ "model" ]
fdb6bcc9102cb8ea23a2b09b69ce0883c22807b3
2,923
cpp
C++
sensing/pointcloud_preprocessor/src/pointcloud_accumulator/pointcloud_accumulator_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
58
2021-11-30T09:03:46.000Z
2022-03-31T15:25:17.000Z
sensing/pointcloud_preprocessor/src/pointcloud_accumulator/pointcloud_accumulator_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
425
2021-11-30T02:24:44.000Z
2022-03-31T10:26:37.000Z
sensing/pointcloud_preprocessor/src/pointcloud_accumulator/pointcloud_accumulator_nodelet.cpp
meliketanrikulu/autoware.universe
04f2b53ae1d7b41846478641ad6ff478c3d5a247
[ "Apache-2.0" ]
69
2021-11-30T02:09:18.000Z
2022-03-31T15:38:29.000Z
// Copyright 2020 Tier IV, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "pointcloud_preprocessor/pointcloud_accumulator/pointcloud_accumulator_nodelet.hpp" #include <vector> namespace pointcloud_preprocessor { PointcloudAccumulatorComponent::PointcloudAccumulatorComponent(const rclcpp::NodeOptions & options) : Filter("PointcloudAccumulator", options) { // set initial parameters { accumulation_time_sec_ = static_cast<double>(declare_parameter("accumulation_time_sec", 2.0)); pointcloud_buffer_.set_capacity( static_cast<size_t>(declare_parameter("pointcloud_buffer_size", 50))); } using std::placeholders::_1; set_param_res_ = this->add_on_set_parameters_callback( std::bind(&PointcloudAccumulatorComponent::paramCallback, this, _1)); } void PointcloudAccumulatorComponent::filter( const PointCloud2ConstPtr & input, [[maybe_unused]] const IndicesPtr & indices, PointCloud2 & output) { std::scoped_lock lock(mutex_); pointcloud_buffer_.push_front(input); rclcpp::Time last_time = input->header.stamp; pcl::PointCloud<pcl::PointXYZ> pcl_input; pcl::PointCloud<pcl::PointXYZ> pcl_output; for (size_t i = 0; i < pointcloud_buffer_.size(); i++) { if (accumulation_time_sec_ < (last_time - pointcloud_buffer_.at(i)->header.stamp).seconds()) { break; } pcl::fromROSMsg(*pointcloud_buffer_.at(i), pcl_input); pcl_output += pcl_input; } pcl::toROSMsg(pcl_output, output); output.header = input->header; } rcl_interfaces::msg::SetParametersResult PointcloudAccumulatorComponent::paramCallback( const std::vector<rclcpp::Parameter> & p) { std::scoped_lock lock(mutex_); if (get_param(p, "accumulation_time_sec", accumulation_time_sec_)) { RCLCPP_DEBUG(get_logger(), "Setting new accumulation time to: %f.", accumulation_time_sec_); } int pointcloud_buffer_size; if (get_param(p, "pointcloud_buffer_size", pointcloud_buffer_size)) { pointcloud_buffer_.set_capacity((size_t)pointcloud_buffer_size); RCLCPP_DEBUG(get_logger(), "Setting new buffer size to: %d.", pointcloud_buffer_size); } rcl_interfaces::msg::SetParametersResult result; result.successful = true; result.reason = "success"; return result; } } // namespace pointcloud_preprocessor #include <rclcpp_components/register_node_macro.hpp> RCLCPP_COMPONENTS_REGISTER_NODE(pointcloud_preprocessor::PointcloudAccumulatorComponent)
36.5375
99
0.762573
[ "vector" ]
fdb6ee6da6c140a88a003c5fc5a6c8a5286f0d28
445
cpp
C++
CODECHEF/REMISS.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
CODECHEF/REMISS.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
CODECHEF/REMISS.cpp
aqfaridi/Competitve-Programming-Codes
d055de2f42d3d6bc36e03e67804a1dd6b212241f
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <sstream> #include <vector> #include <iomanip> #include <cmath> using namespace std; typedef long long LL; typedef pair<int,int> pii; #define MAX 100010 #define MOD 1000000007 int main() { ios::sync_with_stdio(false); int t,a,b; cin>>t; while(t--) { cin>>a>>b; cout<<max(a,b)<<" "<<a+b<<endl; } return 0; }
15.892857
39
0.611236
[ "vector" ]
fdbb41d1fe8da07aa3896247853a1e97407cce0e
3,315
cc
C++
NativePatcher_cef_binary_3.3163.1671.win32/BridgeBuilder/dev_snap/tests/cefclient/browser/osr_accessibility_node.cc
prepare/kn_patches
f6566c8f06c92d965a453d1f8de23d6d003cd71f
[ "MIT" ]
170
2019-12-11T18:22:27.000Z
2022-02-09T08:32:35.000Z
NativePatcher_cef_binary_3.3163.1671.win32/BridgeBuilder/dev_snap/tests/cefclient/browser/osr_accessibility_node.cc
prepare/kn_patches
f6566c8f06c92d965a453d1f8de23d6d003cd71f
[ "MIT" ]
113
2019-12-14T04:28:04.000Z
2021-09-26T18:40:27.000Z
NativePatcher_cef_binary_3.3163.1671.win32/BridgeBuilder/dev_snap/tests/cefclient/browser/osr_accessibility_node.cc
prepare/kn_patches
f6566c8f06c92d965a453d1f8de23d6d003cd71f
[ "MIT" ]
24
2020-01-03T07:49:21.000Z
2021-10-31T14:43:13.000Z
// Copyright 2017 The Chromium Embedded Framework Authors. Portions copyright // 2013 The Chromium Authors. All rights reserved. Use of this source code is // governed by a BSD-style license that can be found in the LICENSE file. // Base class implementation for CEF Acccessibility node. This is subclassed and // used by both IAccessible/NSAccessibility protocol implementation. #include "tests/cefclient/browser/osr_accessibility_node.h" #include "tests/cefclient/browser/osr_accessibility_helper.h" namespace client { OsrAXNode::OsrAXNode(CefRefPtr<CefDictionaryValue> value, OsrAccessibilityHelper* helper) : node_id_(-1), platform_accessibility_(NULL), parent_(NULL), accessibility_helper_(helper) { UpdateValue(value); } void OsrAXNode::UpdateValue(CefRefPtr<CefDictionaryValue> value) { if (value && value->HasKey("id")) { node_id_ = value->GetInt("id"); if (value->HasKey("role")) role_ = value->GetString("role"); if (value->HasKey("child_ids")) { CefRefPtr<CefListValue> childs = value->GetList("child_ids"); // Reset child Ids child_ids_.clear(); for (size_t idx = 0; idx < childs->GetSize(); idx++) child_ids_.push_back(childs->GetInt(idx)); } // Update Location if (value->HasKey("location")) { CefRefPtr<CefDictionaryValue> loc = value->GetDictionary("location"); if (loc) { location_ = CefRect(loc->GetDouble("x"), loc->GetDouble("y"), loc->GetDouble("width"), loc->GetDouble("height")); } } // Update offsets if (value->HasKey("offset_container_id")) { offset_container_id_ = value->GetInt("offset_container_id"); } // Update attributes if (value->HasKey("attributes")) { attributes_ = value->GetDictionary("attributes"); if (attributes_ && attributes_->HasKey("name")) name_ = attributes_->GetString("name"); if (attributes_ && attributes_->HasKey("value")) value_ = attributes_->GetString("value"); if (attributes_ && attributes_->HasKey("description")) description_ = attributes_->GetString("description"); } } } CefWindowHandle OsrAXNode::GetWindowHandle() const { if (accessibility_helper_) return accessibility_helper_->GetWindowHandle(); return NULL; } CefRefPtr<CefBrowser> OsrAXNode::GetBrowser() const { if (accessibility_helper_) return accessibility_helper_->GetBrowser(); return NULL; } void OsrAXNode::SetParent(OsrAXNode* parent) { parent_ = parent; } CefRect OsrAXNode::AxLocation() const { CefRect loc = location_; OsrAXNode* offsetNode = accessibility_helper_->GetNode(offset_container_id_); // Add offset from parent Lcoation if (offsetNode) { CefRect offset = offsetNode->AxLocation(); loc.x += offset.x; loc.y += offset.y; } return loc; } OsrAXNode* OsrAXNode::ChildAtIndex(int index) const { if (index < GetChildCount()) return accessibility_helper_->GetNode(child_ids_[index]); else return NULL; } // Create and return the platform specific OsrAXNode Object OsrAXNode* OsrAXNode::CreateNode(CefRefPtr<CefDictionaryValue> value, OsrAccessibilityHelper* helper) { return new OsrAXNode(value, helper); } } // namespace client
31.571429
80
0.682051
[ "object" ]
fdbbc557f42721c9e0d84828e6f0ff097cda1089
11,941
cc
C++
ARDriver.cc
jinchenglee/PTAMM
5c001bc502d17def2374e81a3f1f6c1b8e1711cc
[ "Zlib" ]
4
2021-01-19T18:41:04.000Z
2021-08-03T18:56:13.000Z
ARDriver.cc
jinchenglee/PTAMM
5c001bc502d17def2374e81a3f1f6c1b8e1711cc
[ "Zlib" ]
1
2020-05-27T10:27:39.000Z
2020-05-27T10:27:39.000Z
ARDriver.cc
jinchenglee/PTAMM
5c001bc502d17def2374e81a3f1f6c1b8e1711cc
[ "Zlib" ]
2
2020-11-17T12:43:55.000Z
2021-01-20T03:27:20.000Z
// Copyright 2009 Isis Innovation Limited #define GL_GLEXT_PROTOTYPES 1 #include "ARDriver.h" #include "Map.h" #include "Games.h" #include <cvd/image_io.h> namespace PTAMM { using namespace GVars3; using namespace CVD; using namespace std; static bool CheckFramebufferStatus(); /** * Constructor * @param cam Reference to the camera * @param irFrameSize the size of the frame * @param glw the glwindow * @param map the current map */ ARDriver::ARDriver(const ATANCamera &cam, ImageRef irFrameSize, GLWindow2 &glw, Map &map) :mCamera(cam), mGLWindow(glw), mpMap( &map ) { mirFrameSize = irFrameSize; mCamera.SetImageSize(mirFrameSize); mbInitialised = false; } /** * Initialize the AR driver */ void ARDriver::Init() { mbInitialised = true; mirFBSize = GV3::get<ImageRef>("ARDriver.FrameBufferSize", ImageRef(1200,900), SILENT); glGenTextures(1, &mnFrameTex); glBindTexture(GL_TEXTURE_RECTANGLE_ARB,mnFrameTex); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, mirFrameSize.x, mirFrameSize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); MakeFrameBuffer(); try { CVD::img_load(mLostOverlay, "ARData/Overlays/searching.png"); } catch(CVD::Exceptions::All err) { cerr << "Failed to load searching image " << "\"ARData/Overlays/searching.png\"" << ": " << err.what << endl; } } /** * Reset the game and the frame counter */ void ARDriver::Reset() { if(mpMap->pGame) { mpMap->pGame->Reset(); } mnCounter = 0; } /** * Render the AR composite image * @param imFrame The camera frame * @param se3CfromW The camera position * @param bLost Is the camera lost */ void ARDriver::Render(Image<Rgb<CVD::byte> > &imFrame, SE3<> se3CfromW, bool bLost) { if(!mbInitialised) { Init(); Reset(); }; mse3CfromW = se3CfromW; mnCounter++; // Upload the image to our frame texture glBindTexture(GL_TEXTURE_RECTANGLE_ARB, mnFrameTex); glTexSubImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, 0, 0, mirFrameSize.x, mirFrameSize.y, GL_RGB, GL_UNSIGNED_BYTE, imFrame.data()); // Set up rendering to go the FBO, draw undistorted video frame into BG glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,mnFrameBuffer); CheckFramebufferStatus(); glViewport(0,0,mirFBSize.x,mirFBSize.y); DrawFBBackGround(); glClearDepth(1); glClear(GL_DEPTH_BUFFER_BIT); // Set up 3D projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); //only draw 3d stuff if not lost. if(!bLost) { glMultMatrix(mCamera.MakeUFBLinearFrustumMatrix(0.005, 100)); glMultMatrix(se3CfromW); DrawFadingGrid(); if(mpMap->pGame) { mpMap->pGame->Draw3D( mGLWindow, *mpMap, se3CfromW); } } glDisable(GL_DEPTH_TEST); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_BLEND); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Set up for drawing 2D stuff: glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0); DrawDistortedFB(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); mGLWindow.SetupViewport(); mGLWindow.SetupVideoOrtho(); mGLWindow.SetupVideoRasterPosAndZoom(); //2d drawing if(!bLost) { if(mpMap->pGame) { mpMap->pGame->Draw2D(mGLWindow, *mpMap); } } else { //draw the lost ar overlays glEnable(GL_BLEND); glRasterPos2i( ( mGLWindow.size().x - mLostOverlay.size().x )/2, ( mGLWindow.size().y - mLostOverlay.size().y )/2 ); glDrawPixels(mLostOverlay); glDisable(GL_BLEND); } } /** * Make the frame buffer */ void ARDriver::MakeFrameBuffer() { // Needs nvidia drivers >= 97.46 cout << " ARDriver: Creating FBO... "; glGenTextures(1, &mnFrameBufferTex); glBindTexture(GL_TEXTURE_RECTANGLE_ARB,mnFrameBufferTex); glTexImage2D(GL_TEXTURE_RECTANGLE_ARB, 0, GL_RGBA, mirFBSize.x, mirFBSize.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_NEAREST); GLuint DepthBuffer; glGenRenderbuffersEXT(1, &DepthBuffer); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, DepthBuffer); glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT24, mirFBSize.x, mirFBSize.y); glGenFramebuffersEXT(1, &mnFrameBuffer); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, mnFrameBuffer); glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_RECTANGLE_ARB, mnFrameBufferTex, 0); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, DepthBuffer); CheckFramebufferStatus(); cout << " .. created FBO." << endl; glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); } /** * check the status of the frame buffer */ static bool CheckFramebufferStatus() { GLenum n; n = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); if(n == GL_FRAMEBUFFER_COMPLETE_EXT) return true; // All good cout << "glCheckFrameBufferStatusExt returned an error." << endl; return false; } /** * Draw the background (the image from the camera) */ void ARDriver::DrawFBBackGround() { static bool bFirstRun = true; static GLuint nList; mGLWindow.SetupUnitOrtho(); glEnable(GL_TEXTURE_RECTANGLE_ARB); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, mnFrameTex); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glDisable(GL_POLYGON_SMOOTH); glDisable(GL_BLEND); // Cache the cpu-intesive projections in a display list.. if(bFirstRun) { bFirstRun = false; nList = glGenLists(1); glNewList(nList, GL_COMPILE_AND_EXECUTE); glColor3f(1,1,1); // How many grid divisions in the x and y directions to use? int nStepsX = 24; // Pretty arbitrary.. int nStepsY = (int) (nStepsX * ((double) mirFrameSize.x / mirFrameSize.y)); // Scaled by aspect ratio if(nStepsY < 2) nStepsY = 2; for(int ystep = 0; ystep< nStepsY; ystep++) { glBegin(GL_QUAD_STRIP); for(int xstep = 0; xstep <= nStepsX; xstep++) for(int yystep = ystep; yystep<=ystep+1; yystep++) // Two y-coords in one go - magic. { Vector<2> v2Iter; v2Iter[0] = (double) xstep / nStepsX; v2Iter[1] = (double) yystep / nStepsY; // If this is a border quad, draw a little beyond the // outside of the frame, this avoids strange jaggies // at the edge of the reconstructed frame later: if(xstep == 0 || yystep == 0 || xstep == nStepsX || yystep == nStepsY) for(int i=0; i<2; i++) v2Iter[i] = v2Iter[i] * 1.02 - 0.01; Vector<2> v2UFBDistorted = v2Iter; Vector<2> v2UFBUnDistorted = mCamera.UFBLinearProject(mCamera.UFBUnProject(v2UFBDistorted)); glTexCoord2d(v2UFBDistorted[0] * mirFrameSize.x, v2UFBDistorted[1] * mirFrameSize.y); glVertex(v2UFBUnDistorted); } glEnd(); } glEndList(); } else glCallList(nList); glDisable(GL_TEXTURE_RECTANGLE_ARB); } /** * Draw the distorted frame buffer */ void ARDriver::DrawDistortedFB() { static bool bFirstRun = true; static GLuint nList; mGLWindow.SetupViewport(); mGLWindow.SetupUnitOrtho(); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glEnable(GL_TEXTURE_RECTANGLE_ARB); glBindTexture(GL_TEXTURE_RECTANGLE_ARB, mnFrameBufferTex); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_RECTANGLE_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glDisable(GL_POLYGON_SMOOTH); glDisable(GL_BLEND); if(bFirstRun) { bFirstRun = false; nList = glGenLists(1); glNewList(nList, GL_COMPILE_AND_EXECUTE); // How many grid divisions in the x and y directions to use? int nStepsX = 24; // Pretty arbitrary.. int nStepsY = (int) (nStepsX * ((double) mirFrameSize.x / mirFrameSize.y)); // Scaled by aspect ratio if(nStepsY < 2) nStepsY = 2; glColor3f(1,1,1); for(int ystep = 0; ystep<nStepsY; ystep++) { glBegin(GL_QUAD_STRIP); for(int xstep = 0; xstep<=nStepsX; xstep++) for(int yystep = ystep; yystep<=ystep + 1; yystep++) // Two y-coords in one go - magic. { Vector<2> v2Iter; v2Iter[0] = (double) xstep / nStepsX; v2Iter[1] = (double) yystep / nStepsY; Vector<2> v2UFBDistorted = v2Iter; Vector<2> v2UFBUnDistorted = mCamera.UFBLinearProject(mCamera.UFBUnProject(v2UFBDistorted)); glTexCoord2d(v2UFBUnDistorted[0] * mirFBSize.x, (1.0 - v2UFBUnDistorted[1]) * mirFBSize.y); glVertex(v2UFBDistorted); } glEnd(); } glEndList(); } else glCallList(nList); glDisable(GL_TEXTURE_RECTANGLE_ARB); } /** * Draw the fading grid */ void ARDriver::DrawFadingGrid() { double dStrength; if(mnCounter >= 60) return; if(mnCounter < 30) dStrength = 1.0; dStrength = (60 - mnCounter) / 30.0; glColor4f(1,1,1,dStrength); int nHalfCells = 8; if(mnCounter < 8) nHalfCells = mnCounter + 1; int nTot = nHalfCells * 2 + 1; Vector<3> aaVertex[17][17]; for(int i=0; i<nTot; i++) for(int j=0; j<nTot; j++) { Vector<3> v3; v3[0] = (i - nHalfCells) * 0.1; v3[1] = (j - nHalfCells) * 0.1; v3[2] = 0.0; aaVertex[i][j] = v3; } glEnable(GL_LINE_SMOOTH); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glLineWidth(2); for(int i=0; i<nTot; i++) { glBegin(GL_LINE_STRIP); for(int j=0; j<nTot; j++) glVertex(aaVertex[i][j]); glEnd(); glBegin(GL_LINE_STRIP); for(int j=0; j<nTot; j++) glVertex(aaVertex[j][i]); glEnd(); }; } /** * What to do when the user clicks on the screen. * Calculates the 3d postion of the click on the plane * and passes info to a game, if there is one. * @param nButton the button pressed * @param irWin the window x, y location */ void ARDriver::HandleClick(int nButton, ImageRef irWin ) { //The window may have been resized, so want to work out the coords based on the orignal image size Vector<2> v2VidCoords = mGLWindow.VidFromWinCoords( irWin ); Vector<2> v2UFBCoords; #ifdef WIN32 Vector<2> v2PlaneCoords; v2PlaneCoords[0] = numeric_limits<double>::quiet_NaN(); v2PlaneCoords[1] = numeric_limits<double>::quiet_NaN(); #else Vector<2> v2PlaneCoords; v2PlaneCoords[0] = NAN; v2PlaneCoords[1] = NAN; #endif Vector<3> v3RayDirn_W; // Work out image coords 0..1: v2UFBCoords[0] = (v2VidCoords[0] + 0.5) / mCamera.GetImageSize()[0]; v2UFBCoords[1] = (v2VidCoords[1] + 0.5) / mCamera.GetImageSize()[1]; // Work out plane coords: Vector<2> v2ImPlane = mCamera.UnProject(v2VidCoords); Vector<3> v3C = unproject(v2ImPlane); Vector<4> v4C = unproject(v3C); SE3<> se3CamInv = mse3CfromW.inverse(); Vector<4> v4W = se3CamInv * v4C; double t = se3CamInv.get_translation()[2]; double dDistToPlane = -t / (v4W[2] - t); if(v4W[2] -t <= 0) // Clicked the wrong side of the horizon? { v4C.slice<0,3>() *= dDistToPlane; Vector<4> v4Result = se3CamInv * v4C; v2PlaneCoords = v4Result.slice<0,2>(); // <--- result } // Ray dirn: v3RayDirn_W = v4W.slice<0,3>() - se3CamInv.get_translation(); normalize(v3RayDirn_W); if(mpMap->pGame) { mpMap->pGame->HandleClick(v2VidCoords, v2UFBCoords, v3RayDirn_W, v2PlaneCoords, nButton); } } /** * Handle the user pressing a key * @param sKey the key the user pressed. */ void ARDriver::HandleKeyPress( std::string sKey ) { if(mpMap && mpMap->pGame ) { mpMap->pGame->HandleKeyPress( sKey ); } } /** * Load a game by name. * @param sName Name of the game */ void ARDriver::LoadGame(std::string sName) { if(mpMap->pGame) { delete mpMap->pGame; mpMap->pGame = NULL; } mpMap->pGame = LoadAGame( sName, ""); if( mpMap->pGame ) { mpMap->pGame->Init(); } } /** * Advance the game logic */ void ARDriver::AdvanceLogic() { if(mpMap->pGame) { mpMap->pGame->Advance(); } } }
25.790497
142
0.682941
[ "render", "vector", "3d" ]
fdc02d960763df986c98e3a28665426fd7a38e32
24,400
hpp
C++
include/Row.hpp
AVAInformationSystems/voltdb-client-cpp
e93d30b326ee6d484ed1eb2a35ec3d3263f43d49
[ "MIT" ]
null
null
null
include/Row.hpp
AVAInformationSystems/voltdb-client-cpp
e93d30b326ee6d484ed1eb2a35ec3d3263f43d49
[ "MIT" ]
null
null
null
include/Row.hpp
AVAInformationSystems/voltdb-client-cpp
e93d30b326ee6d484ed1eb2a35ec3d3263f43d49
[ "MIT" ]
1
2020-10-06T11:40:05.000Z
2020-10-06T11:40:05.000Z
/* This file is part of VoltDB. * Copyright (C) 2008-2018 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef VOLTDB_ROW_HPP_ #define VOLTDB_ROW_HPP_ #include "ByteBuffer.hpp" #include "Column.hpp" #include <string> #include <vector> #include "Exception.hpp" #include "WireType.h" #include <stdint.h> #include "Decimal.hpp" #include <sstream> #include "Geography.hpp" #include "GeographyPoint.hpp" namespace voltdb { /* * Representation of a row of tabular data from a Table. Every row contains a shared pointer * to its origin table which may also contain a shared pointer to the message the table was originally * from. Retain references with care to avoid memory leaks. */ class Row { public: /* * Construct a row from a buffer containing the row data. */ #ifdef SWIG %ignore Row(SharedByteBuffer rowData, boost::shared_ptr<std::vector<voltdb::Column> > columns); #endif Row(SharedByteBuffer& rowData, boost::shared_ptr<std::vector<voltdb::Column> >& columns) : m_data(rowData), m_columns(columns), m_wasNull(false), m_offsets(columns->size()), m_hasCalculatedOffsets(false) { } /* * Retrieve the value at the specified column index as bytes. The type of the column * must be Varbinary. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return Whether the buffer provided was large enough. */ bool getVarbinary(int32_t column, int32_t bufsize, uint8_t *out_value, int32_t *out_len) { validateType(WIRE_TYPE_VARBINARY, column); return m_data.getBytes(getOffset(column), m_wasNull, bufsize, out_value, out_len); } /* * Retrieve the value at the specified column index as a Decimal. The type of the column * must be Decimal. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return Decimal value at the specified column */ Decimal getDecimal(int32_t column) { validateType(WIRE_TYPE_DECIMAL, column); char data[16]; m_data.get(getOffset(column), data, 16); Decimal retval(data); m_wasNull = retval.isNull(); return retval; } /* * Retrieve the value at the specified column index as a Timestamp. The type of the column * must be Timestamp. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return Timestamp value at the specified column */ int64_t getTimestamp(int32_t column) { validateType(WIRE_TYPE_TIMESTAMP, column); int64_t retval = m_data.getInt64(getOffset(column)); if (retval == INT64_MIN) m_wasNull = true; return retval; } /* * Retrieve the value at the specified column index as an int64_t/BIGINT. The type of the column * must be BIGINT, INTEGER, SMALLINT, or TINYINT. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return int64 value at the specified column */ int64_t getInt64(int32_t column) { WireType type = validateType(WIRE_TYPE_BIGINT, column); int64_t retval; switch (type) { case WIRE_TYPE_BIGINT: retval = m_data.getInt64(getOffset(column)); if (retval == INT64_MIN) m_wasNull = true; break; case WIRE_TYPE_INTEGER: retval = m_data.getInt32(getOffset(column)); if (retval == INT32_MIN) m_wasNull = true; break; case WIRE_TYPE_SMALLINT: retval = m_data.getInt16(getOffset(column)); if (retval == INT16_MIN) m_wasNull = true; break; case WIRE_TYPE_TINYINT: retval = m_data.getInt8(getOffset(column)); if (retval == INT8_MIN) m_wasNull = true; break; default: assert(false); } return retval; } /* * Retrieve the value at the specified column index as an int32_t/INTEGER. The type of the column * must be INTEGER, SMALLINT, or TINYINT. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return int32 value at the specified column */ int32_t getInt32(int32_t column) { WireType type = validateType(WIRE_TYPE_INTEGER, column); int32_t retval; switch (type) { case WIRE_TYPE_INTEGER: retval = m_data.getInt32(getOffset(column)); if (retval == INT32_MIN) m_wasNull = true; break; case WIRE_TYPE_SMALLINT: retval = m_data.getInt16(getOffset(column)); if (retval == INT16_MIN) m_wasNull = true; break; case WIRE_TYPE_TINYINT: retval = m_data.getInt8(getOffset(column)); if (retval == INT8_MIN) m_wasNull = true; break; default: assert(false); } return retval; } /* * Retrieve the value at the specified column index as an int16_t/SMALLINT. The type of the column * must be SMALLINT, or TINYINT. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return int16 value at the specified column */ int16_t getInt16(int32_t column) { WireType type = validateType(WIRE_TYPE_SMALLINT, column); int16_t retval; switch (type) { case WIRE_TYPE_SMALLINT: retval = m_data.getInt16(getOffset(column)); if (retval == INT16_MIN) m_wasNull = true; break; case WIRE_TYPE_TINYINT: retval = m_data.getInt8(getOffset(column)); if (retval == INT8_MIN) m_wasNull = true; break; default: assert(false); } return retval; } /* * Retrieve the value at the specified column index as an int8_t/TINYINT. The type of the column * must be TINYINT. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return int8 value at the specified column */ int8_t getInt8(int32_t column) { validateType(WIRE_TYPE_TINYINT, column); int8_t retval = m_data.getInt8(getOffset(column)); if (retval == INT8_MIN) { m_wasNull = true; } return retval; } /* * Retrieve the value at the specified column index as a double. The type of the column * must be FLOAT. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return double value at the specified column */ double getDouble(int32_t column) { validateType(WIRE_TYPE_FLOAT, column); double retval = m_data.getDouble(getOffset(column)); if (retval <= -1.7E+308) { m_wasNull = true; } return retval; } /* * Retrieve the value at the specified column index as an string. The type of the column * must be STRING. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return String value at the specified column */ std::string getString(int32_t column) { validateType(WIRE_TYPE_STRING, column); return m_data.getString(getOffset(column), m_wasNull); } /* * Retrieve the value at the specified column index as a geographical point. * * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return the deserialized GeographyPoint value. */ GeographyPoint getGeographyPoint(int32_t column) { validateType(WIRE_TYPE_GEOGRAPHY_POINT, column); GeographyPoint gpoint(m_data, getOffset(column), m_wasNull); return gpoint; } /* * Retrieve the value at the specified column index as a geographical object. * * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return the deserialized geography value. */ Geography getGeography(int32_t column) { validateType(WIRE_TYPE_GEOGRAPHY, column); m_wasNull = false; return Geography(m_data, getOffset(column), m_wasNull); } /* * Returns true if the value at the specified column index is NULL and false otherwise * @throws InvalidColumnException The name of the column was invalid. * @return true if the value is NULL and false otherwise */ bool isNull(int32_t column) { if (column < 0 || column >= static_cast<ssize_t>(m_columns->size())) { throw InvalidColumnException(column, m_columns->size()); } WireType columnType = m_columns->at(static_cast<size_t>(column)).type(); switch (columnType) { case WIRE_TYPE_DECIMAL: getDecimal(column); break; case WIRE_TYPE_TIMESTAMP: getTimestamp(column); break; case WIRE_TYPE_BIGINT: getInt64(column); break; case WIRE_TYPE_INTEGER: getInt32(column); break; case WIRE_TYPE_SMALLINT: getInt64(column); break; case WIRE_TYPE_TINYINT: getInt8(column); break; case WIRE_TYPE_FLOAT: getDouble(column); break; case WIRE_TYPE_STRING: getString(column); break; case WIRE_TYPE_VARBINARY: int out_len; getVarbinary(column, 0, NULL, &out_len); break; case WIRE_TYPE_GEOGRAPHY: getGeography(column); break; case WIRE_TYPE_GEOGRAPHY_POINT: getGeographyPoint(column); break; default: throw UnsupportedTypeException(wireTypeToString(columnType)); } return wasNull(); } /* * Retrieve the value from the column with the specified name as bytes. The type of the column * must be Varbinary. * @throws InvalidColumnException The index of the column was invalid or the type of the column does * not match the type of the get method. * @return Whether the buffer provided was large enough. */ bool getVarbinary(const std::string& cname, int32_t bufsize, uint8_t *out_value, int32_t *out_len) { return getVarbinary(getColumnIndexByName(cname), bufsize, out_value, out_len); } /* * Retrieve the value from the column with the specified name as a Decimal. The type of the column * must be Decimal. * @throws InvalidColumnException No column with the specified name exists or the type of the getter * does not match the column type. * @return Decimal value at the specified column */ Decimal getDecimal(const std::string& cname) { return getDecimal(getColumnIndexByName(cname)); } /* * Retrieve the value from the column with the specified name as a Timestamp. The type of the column * must be Timestamp. * @throws InvalidColumnException No column with the specified name exists or the type of the getter * does not match the column type. * @return Timestamp value at the specified column */ int64_t getTimestamp(const std::string& cname) { return getTimestamp(getColumnIndexByName(cname)); } /* * Retrieve the value from the column with the specified name as a int64_t/BIGINT. The type of the column * must be BIGINT, INTEGER, SMALLINT, TINYINT. * @throws InvalidColumnException No column with the specified name exists or the type of the getter * does not match the column type. * @return int64 value at the specified column */ int64_t getInt64(const std::string& cname) { return getInt64(getColumnIndexByName(cname)); } /* * Retrieve the value from the column with the specified name as a int32_t/INTEGER. The type of the column * must be INTEGER, SMALLINT, TINYINT. * @throws InvalidColumnException No column with the specified name exists or the type of the getter * does not match the column type. * @return int32 value at the specified column */ int32_t getInt32(const std::string& cname) { return getInt32(getColumnIndexByName(cname)); } /* * Retrieve the value from the column with the specific name as a int16_t/SMALLINT. The type of the column * must be SMALLINT, TINYINT. * @throws InvalidColumnException No column with the specified name exists or the type of the getter * does not match the column type. * @return int16 value at the specified column */ int16_t getInt16(const std::string& cname) { return getInt16(getColumnIndexByName(cname)); } /* * Retrieve the value from the column with the specific name as a int8_t/TINYINT. The type of the column * must be TINYINT. * @throws InvalidColumnException No column with the specified name exists or the type of the getter * does not match the column type. * @return int8 value at the specified column */ int8_t getInt8(const std::string& cname) { return getInt8(getColumnIndexByName(cname)); } /* * Retrieve the value from the column with the specific name as a double. The type of the column * must be FLOAT. * @throws InvalidColumnException No column with the specified name exists or the type of the getter * does not match the column type. * @return double value at the specified column */ double getDouble(const std::string& cname) { return getDouble(getColumnIndexByName(cname)); } /* * Retrieve the value from the column with the specific name as a std::string. The type of the column * must be STRING. * @throws InvalidColumnException No column with the specified name exists or the type of the getter * does not match the column type. * @return string value at the specified column */ std::string getString(const std::string& cname) { return getString(getColumnIndexByName(cname)); } /* * Retrieve the value at the specified column name as a geographical point. * This data type is not currently supported by the C++ client so this always * throws an exception. * @throws UnsupportedTypeException always * @return never returns */ GeographyPoint getGeographyPoint(const std::string& cname) { return getGeographyPoint(getColumnIndexByName(cname)); } /* * Retrieve the value at the specified column name as a geographical object. * This data type is not currently supported by the C++ client so this always * throws an exception. * @throws UnsupportedTypeException always * @return never returns */ Geography getGeography(const std::string& cname) { return getGeography(getColumnIndexByName(cname)); } /* * Returns true if the value in the column with the specified name is NULL and false otherwise * @throws InvalidColumnException The name of the column was invalid. * @return true if the value is NULL and false otherwise */ bool isNull(const std::string& cname) { int32_t column = getColumnIndexByName(cname); return isNull(column); } /* * Returns true if the value of the last column returned via a getter was null */ bool wasNull() { return m_wasNull; } /* * Returns a string representation of this row */ std::string toString() { std::ostringstream ostream; toString(ostream, std::string("")); return ostream.str(); } /* * Returns a string representation of this row with the specified level of indentation * before each line */ void toString(std::ostringstream &ostream, const std::string& indent) { ostream << indent; const int32_t size = static_cast<int32_t>(m_columns->size()); for (int32_t ii = 0; ii < size; ii++) { if (ii != 0) { ostream << ", "; } if (isNull(ii)) { ostream << "NULL"; continue; } switch(m_columns->at(ii).type()) { case WIRE_TYPE_TINYINT: ostream << static_cast<int32_t>(getInt8(ii)); break; case WIRE_TYPE_SMALLINT: ostream << getInt16(ii); break; case WIRE_TYPE_INTEGER: ostream << getInt32(ii); break; case WIRE_TYPE_BIGINT: ostream << getInt64(ii); break; case WIRE_TYPE_FLOAT: ostream << getDouble(ii); break; case WIRE_TYPE_STRING: ostream << "\"" << getString(ii) << "\""; break; case WIRE_TYPE_TIMESTAMP: ostream << getTimestamp(ii); break; case WIRE_TYPE_DECIMAL: ostream << getDecimal(ii).toString(); break; case WIRE_TYPE_VARBINARY: ostream << "VARBINARY VALUE"; break; case WIRE_TYPE_GEOGRAPHY_POINT: ostream << getGeographyPoint(ii).toString(); break; case WIRE_TYPE_GEOGRAPHY: ostream << getGeography(ii).toString(); break; default: assert(false); } } } int32_t columnCount() const { return static_cast<int32_t>(m_columns->size()); } std::vector<voltdb::Column> columns() const { return *m_columns; } private: WireType validateType(WireType type, int32_t index) { if (index < 0 || index >= static_cast<ssize_t>(m_columns->size())) { throw InvalidColumnException(index, m_columns->size()); } WireType columnType = m_columns->at(static_cast<size_t>(index)).type(); switch (columnType) { case WIRE_TYPE_INTEGER: if (type != WIRE_TYPE_BIGINT && type != WIRE_TYPE_INTEGER) { throw InvalidColumnException(getColumnNameByIndex(index), type, wireTypeToString(type), wireTypeToString(WIRE_TYPE_INTEGER)); } break; case WIRE_TYPE_SMALLINT: if (type != WIRE_TYPE_BIGINT && type != WIRE_TYPE_INTEGER && type != WIRE_TYPE_SMALLINT) { throw InvalidColumnException(getColumnNameByIndex(index), type, wireTypeToString(type), wireTypeToString(WIRE_TYPE_SMALLINT)); } break; case WIRE_TYPE_TINYINT: if (type != WIRE_TYPE_BIGINT && type != WIRE_TYPE_INTEGER && type != WIRE_TYPE_SMALLINT && type != WIRE_TYPE_TINYINT) { throw InvalidColumnException(getColumnNameByIndex(index), type, wireTypeToString(type), wireTypeToString(WIRE_TYPE_TINYINT)); } break; case WIRE_TYPE_TIMESTAMP: case WIRE_TYPE_BIGINT: case WIRE_TYPE_FLOAT: case WIRE_TYPE_STRING: case WIRE_TYPE_VARBINARY: case WIRE_TYPE_GEOGRAPHY: case WIRE_TYPE_GEOGRAPHY_POINT: case WIRE_TYPE_DECIMAL: /* * No implicit conversions for these types. The column type * and the actual type must be identical. */ if (columnType != type) { throw InvalidColumnException(getColumnNameByIndex(index), type, wireTypeToString(type), wireTypeToString(columnType)); } break; default: throw UnsupportedTypeException(wireTypeToString(columnType)); break; } return columnType; } int32_t getColumnIndexByName(const std::string& name) { for (int32_t ii = 0; ii < static_cast<ssize_t>(m_columns->size()); ii++) { if (m_columns->at(static_cast<size_t>(ii)).name() == name) { return ii; } } throw InvalidColumnException(name); } const std::string& getColumnNameByIndex(int32_t index){ return m_columns->at(index).name(); } void ensureCalculatedOffsets() { if (m_hasCalculatedOffsets == true) return; m_offsets[0] = m_data.position(); for (int32_t i = 1; i < static_cast<ssize_t>(m_columns->size()); i++) { // // To calculate the offset at index i, given that the // offset at i-1 is correct. we calculate the size of the // data at offset i-1 and add it to the offset at index i-1, // to get the index at i. // WireType type = m_columns->at(static_cast<size_t>(i - 1)).type(); if (isVariableSized(type)) { int32_t length = m_data.getInt32(m_offsets[static_cast<size_t>(i - 1)]); if (length == -1) { m_offsets[static_cast<size_t>(i)] = m_offsets[static_cast<size_t>(i - 1)] + 4; } else if (length < 0) { assert(false); } else { m_offsets[static_cast<size_t>(i)] = m_offsets[static_cast<size_t>(i - 1)] + length + 4; } } else { // // These are all fixed sized data values. // int32_t length = 0; switch (type) { case WIRE_TYPE_DECIMAL: length = 16; break; case WIRE_TYPE_TIMESTAMP: case WIRE_TYPE_BIGINT: case WIRE_TYPE_FLOAT: length = 8; break; case WIRE_TYPE_INTEGER: length = 4; break; case WIRE_TYPE_SMALLINT: length = 2; break; case WIRE_TYPE_TINYINT: length = 1; break; case WIRE_TYPE_GEOGRAPHY_POINT: length = 2 * sizeof(double); break; default: throw UnsupportedTypeException(wireTypeToString(type)); } m_offsets[static_cast<size_t>(i)] = m_offsets[static_cast<size_t>(i - 1)] + length; } } m_hasCalculatedOffsets = true; } int32_t getOffset(int32_t index) { m_wasNull = false; ensureCalculatedOffsets(); assert(index >= 0); assert(static_cast<size_t>(index) < m_offsets.size()); return m_offsets[static_cast<size_t>(index)]; } SharedByteBuffer m_data; boost::shared_ptr<std::vector<voltdb::Column> > m_columns; bool m_wasNull; std::vector<int32_t> m_offsets; bool m_hasCalculatedOffsets; }; } #endif /* VOLTDB_ROW_HPP_ */
38.485804
142
0.622992
[ "object", "vector" ]
fdc7c605b2e0cecfc52d4c859f959afd8a4447bc
1,396
cpp
C++
Torre_de_Hanoi_Novamente_.cpp
costadev00/ED2_UFU
2fea18870793c773be5cdc949fe36c59c8bea75d
[ "MIT" ]
1
2021-03-19T04:33:37.000Z
2021-03-19T04:33:37.000Z
Torre_de_Hanoi_Novamente_.cpp
costadev00/ED2_UFU
2fea18870793c773be5cdc949fe36c59c8bea75d
[ "MIT" ]
null
null
null
Torre_de_Hanoi_Novamente_.cpp
costadev00/ED2_UFU
2fea18870793c773be5cdc949fe36c59c8bea75d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio \ ios_base::sync_with_stdio(false); \ cin.tie(NULL) using namespace std; typedef long long ll; typedef long double ld; #define endl "\n" #define MOD 1000000007 #define vi vector<int> #define pb push_back #define read(st) getline(cin, st) #define FOR(i, a, b) for (int i = a; i < b; i++) bool isPerfectSquare(int x) { // Find floating point value of // square root of x. if (x >= 0) { int sr = sqrt(x); // if product of square root //is equal, then // return T/F return (sr * sr == x); } // else return false if n<0 return false; } int maxb[51] = {0}; int last[51] = {0}; int lookup(int x) { int prox = 1; int haste = 0; while (1) { bool isnNew = true; for (int i = 1; i <= haste; i++) { if (isPerfectSquare(last[i] + prox)) { isnNew = false; last[i] = prox; } } if (isnNew) { maxb[haste] = prox - 1; last[++haste] = prox; if (haste >= x + 1) break; } prox++; } return last[haste] - 1; } int main() { fastio; int n, x; cin >> n; while (n--) { cin >> x; cout << lookup(x) << endl; } return 0; }
17.234568
48
0.457736
[ "vector" ]
fdc9bd40386af75ed2c223824882f42912de4466
4,307
hpp
C++
cradle/src/alia/ui/system.hpp
dotdecimal/open-cradle
f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d
[ "MIT" ]
null
null
null
cradle/src/alia/ui/system.hpp
dotdecimal/open-cradle
f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d
[ "MIT" ]
null
null
null
cradle/src/alia/ui/system.hpp
dotdecimal/open-cradle
f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d
[ "MIT" ]
4
2018-09-28T17:12:54.000Z
2022-03-20T14:22:29.000Z
#ifndef ALIA_UI_SYSTEM_HPP #define ALIA_UI_SYSTEM_HPP #include <alia/ui/internals.hpp> // This files defines the top-level interface to the UI system. // It's used by backends. namespace alia { // Initialize the UI system. void initialize_ui( ui_system& ui, alia__shared_ptr<ui_controller> const& controller, alia__shared_ptr<alia::surface> const& surface, vector<2,float> const& ppi, alia__shared_ptr<os_interface> const& os, alia__shared_ptr<style_tree> const& style); // Update the UI system. // This detects changes in the UI contents and updates the layout of the UI. // It also resolves what's under the mouse cursor and updates the UI // accordingly. // If current_cursor is not NULL, it will receive the cursor that the UI has // requested for the current frame. void update_ui(ui_system& ui, vector<2,unsigned> const& size, ui_time_type millisecond_tick_count, mouse_cursor* current_cursor = 0); // Returns true iff there are pending timer requests. bool has_timer_requests(ui_system& ui); // Check expired timer requests in the UI and issue the corresponding events. // The return value is true iff any requests were processed. bool process_timer_requests(ui_system& system, ui_time_type now); // Get the number of milliseconds until the UI expects to update next. // The system can safely idle for this many milliseconds if no external events // occur. // If the return value is none, it means that there are no future updates // scheduled, so the system can simply sleep until the next external event. optional<ui_time_type> get_time_until_next_update(ui_system& system, ui_time_type now); // Render the UI to the associated surface. void render_ui(ui_system& system); // The following are for sending mouse events to the UI. void process_mouse_move( ui_system& ui, ui_time_type time, vector<2,int> const& position); void process_mouse_leave( ui_system& ui, ui_time_type time); void process_mouse_press( ui_system& ui, ui_time_type time, vector<2,int> const& position, mouse_button button); void process_mouse_release( ui_system& ui, ui_time_type time, vector<2,int> const& position, mouse_button button); void process_double_click( ui_system& ui, ui_time_type time, vector<2,int> const& position, mouse_button button); void process_mouse_wheel( ui_system& ui, ui_time_type time, float movement); // The following are for sending keyboard events to the UI. bool process_text_input( ui_system& ui, ui_time_type time, utf8_string const& text); bool process_key_press( ui_system& ui, ui_time_type time, key_event_info const& info); bool process_key_release( ui_system& ui, ui_time_type time, key_event_info const& info); void process_focus_loss( ui_system& ui, ui_time_type time); void process_focus_gain( ui_system& ui, ui_time_type time); // process_key_press calls both of the following. // process_focused_key_press will only pass the key to the widget with the // keyboard focus (if any). // process_background_key_press will pass it to any widget that's listening. bool process_focused_key_press( ui_system& ui, ui_time_type time, key_event_info const& info); bool process_background_key_press( ui_system& ui, ui_time_type time, key_event_info const& info); // Move the keyboard focus forward and backwards through the focus order. void advance_focus(ui_system& ui); void regress_focus(ui_system& ui); // Clear the keyboard focus (so that no widget has focus). void clear_focus(ui_system& ui); // Issue an untargeted event to the UI system. void issue_event(ui_system& system, ui_event& event); // Issue a targeted event to the UI system. void issue_targeted_event(ui_system& system, ui_event& event, routable_widget_id const& target); // Issue a refresh event to the UI system. // Note that this is called as part of update_ui, so it's normally not // necessary to call this separately. void refresh_ui(ui_system& ui); // Get the time in microseconds that the last refresh event took to process. int get_last_refresh_duration(ui_system& ui); // Set a new style for the UI system. void set_system_style(ui_system& system, alia__shared_ptr<style_tree> const& style); static inline void on_ui_style_change(ui_system& system) { inc_version(system.style.id); } } #endif
36.193277
78
0.769909
[ "render", "vector" ]
fdcd984c263798e3cf881e3960227abbf02acef8
33,142
cpp
C++
SbgatCore/source/SBGATMassPropertiesUQ.cpp
bbercovici/SBGAT
93e935baff49eb742470d7d593931f0573f0c062
[ "MIT" ]
6
2017-11-29T02:47:00.000Z
2021-09-26T05:25:44.000Z
SbgatCore/source/SBGATMassPropertiesUQ.cpp
bbercovici/SBGAT
93e935baff49eb742470d7d593931f0573f0c062
[ "MIT" ]
34
2017-02-09T15:38:35.000Z
2019-04-25T20:53:37.000Z
SbgatCore/source/SBGATMassPropertiesUQ.cpp
bbercovici/SBGAT
93e935baff49eb742470d7d593931f0573f0c062
[ "MIT" ]
1
2019-03-12T12:20:25.000Z
2019-03-12T12:20:25.000Z
#include <SBGATMassPropertiesUQ.hpp> #include <RigidBodyKinematics.hpp> #include <vtkCleanPolyData.h> #include <vtkOBJReader.h> #include <SBGATPolyhedronGravityModel.hpp> #include <SBGATObjWriter.hpp> #pragma omp declare reduction( + : arma::mat : omp_out += omp_in ) \ initializer( omp_priv = arma::zeros<arma::mat>(omp_orig.n_rows,omp_orig.n_cols)) #pragma omp declare reduction( + : arma::rowvec : omp_out += omp_in ) \ initializer( omp_priv = arma::zeros<arma::rowvec>(omp_orig.n_cols)) arma::rowvec::fixed<9> SBGATMassPropertiesUQ::PartialDeltaVfPartialTf(const int & f) const{ double r0[3]; double r1[3]; double r2[3]; arma::rowvec::fixed<9> partial; this -> model -> GetVerticesInFacet(f,r0,r1,r2); arma::vec::fixed<3> C0 = {r0[0],r0[1],r0[2]}; arma::vec::fixed<3> C1 = {r1[0],r1[1],r1[2]}; arma::vec::fixed<3> C2 = {r2[0],r2[1],r2[2]}; partial.subvec(0,2) = arma::cross(C1,C2).t(); partial.subvec(3,5) = - C0.t() * RBK::tilde(C2); partial.subvec(6,8) = C0.t() * RBK::tilde(C1); return 1./6 * partial; } arma::mat::fixed<3,9> SBGATMassPropertiesUQ::PartialDeltaCMfPartialTf(){ arma::mat::fixed<3,9> triple_I; triple_I.cols(0,2) = arma::eye<arma::mat>(3,3); triple_I.cols(3,5) = arma::eye<arma::mat>(3,3); triple_I.cols(6,8) = arma::eye<arma::mat>(3,3); return 1./4 * triple_I ; } void SBGATMassPropertiesUQ::TestPartials(std::string input,double tol,bool shape_in_meters){ std::cout << "\tRunning SBGATMassPropertiesUQ::TestPartials on " << input << std::endl; SBGATMassPropertiesUQ::TestPartialDeltaVfPartialTf(input,tol,shape_in_meters); SBGATMassPropertiesUQ::TestPartialDeltaIfPartialTf(input,tol,shape_in_meters); SBGATMassPropertiesUQ::TestGetPartialVolumePartialC(input,tol,shape_in_meters); SBGATMassPropertiesUQ::TestGetPartialComPartialC(input,tol,shape_in_meters); SBGATMassPropertiesUQ::TestPartialEqDeltaIfErPartialTf(input,tol,shape_in_meters); SBGATMassPropertiesUQ::TestGetPartialIPartialC(input,tol,shape_in_meters); SBGATMassPropertiesUQ::TestGetPartialAllInertiaPartialC(input,tol,shape_in_meters); SBGATMassPropertiesUQ::TestGetPartialSigmaPartialC(input,tol,shape_in_meters); } void SBGATMassPropertiesUQ::TestPartialDeltaVfPartialTf(std::string input,double tol,bool shape_in_meters){ std::cout << "\t In TestPartialDeltaVfPartialTf ... "; int successes = 0; arma::arma_rng::set_seed(0); int N = 1000; // Reading vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader -> SetFileName(input.c_str()); reader -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner -> SetInputConnection (reader -> GetOutputPort()); cleaner -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner -> Update(); #pragma omp parallel for reduction(+:successes) for (int i = 0; i < N ; ++i){ vtkSmartPointer<vtkPolyData> input_shape = vtkSmartPointer<vtkPolyData>::New(); input_shape -> DeepCopy(cleaner -> GetOutput()); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_prop = vtkSmartPointer<SBGATMassProperties>::New(); mass_prop -> SetInputData(input_shape); mass_prop -> SetDensity(1970); if (shape_in_meters) mass_prop -> SetScaleMeters(); else mass_prop -> SetScaleKiloMeters(); mass_prop -> Update(); SBGATMassPropertiesUQ shape_uq; shape_uq.SetModel(mass_prop); shape_uq.PrecomputeMassPropertiesPartials(); int N_facets = vtkPolyData::SafeDownCast(mass_prop -> GetInput()) -> GetNumberOfCells(); arma::ivec f_vec = arma::randi<arma::ivec>(1,arma::distr_param(0,N_facets - 1)); int f = f_vec(0); // Nominal Volume double volume = mass_prop -> GetDeltaV(f); // Deviation arma::vec::fixed<9> delta_Tf = 1e-3 * arma::randn<arma::vec>(9) / mass_prop -> GetScaleFactor(); // Linear dUf double dV_lin = arma::dot(shape_uq.PartialDeltaVfPartialTf(f) , mass_prop -> GetScaleFactor()* delta_Tf); // Apply Tf deviation shape_uq. ApplyTfDeviation(delta_Tf,f); // Perturbed Uf double volume_p = mass_prop -> GetDeltaV(f); // Non-linear dUf double dV = volume_p - volume; if(std::abs(dV - dV_lin) / std::abs(dV_lin) < tol){ ++successes; } } std::cout << "\t Passed TestPartialDeltaVfPartialTf with " << double(successes)/N * 100 << " \% of successes. \n"; } void SBGATMassPropertiesUQ::TestGetPartialVolumePartialC(std::string input,double tol,bool shape_in_meters){ std::cout << "\t In TestGetPartialVolumePartialC ... "; int successes = 0; arma::arma_rng::set_seed(0); int N = 1000; #pragma omp parallel for reduction(+:successes) for (int i = 0; i < N ; ++i){ // Reading vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader -> SetFileName(input.c_str()); reader -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner -> SetInputConnection (reader -> GetOutputPort()); cleaner -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner -> Update(); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_prop = vtkSmartPointer<SBGATMassProperties>::New(); mass_prop -> SetInputConnection(cleaner -> GetOutputPort()); mass_prop -> SetDensity(1970); if (shape_in_meters) mass_prop -> SetScaleMeters(); else mass_prop -> SetScaleKiloMeters(); mass_prop -> Update(); SBGATMassPropertiesUQ shape_uq; shape_uq.SetModel(mass_prop); shape_uq.PrecomputeMassPropertiesPartials(); // Nominal Volume double volume = mass_prop -> GetVolume(); // Deviation arma::vec delta_C = 1e-3 * arma::randn<arma::vec>(3 * mass_prop -> GetN_vertices() ) / mass_prop -> GetScaleFactor(); // Linear dUf double dV_lin = mass_prop -> GetScaleFactor() * arma::dot(shape_uq.GetPartialVolumePartialC() , delta_C); // Apply Tf deviation shape_uq. ApplyDeviation(delta_C); // Perturbed Uf double volume_p = mass_prop -> GetVolume(); // Non-linear dUf double dV = volume_p - volume; if(std::abs(dV - dV_lin) / std::abs(dV_lin) < tol){ ++successes; } } std::cout << "\t Passed TestGetPartialVolumePartialC with " << double(successes)/N * 100 << " \% of successes. \n"; } void SBGATMassPropertiesUQ::TestGetPartialComPartialC(std::string input,double tol,bool shape_in_meters){ std::cout << "\t In TestGetPartialComPartialC ... "; int successes = 0; arma::arma_rng::set_seed(0); int N = 1000; #pragma omp parallel for reduction(+:successes) for (int i = 0; i < N ; ++i){ // Reading vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader -> SetFileName(input.c_str()); reader -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner -> SetInputConnection (reader -> GetOutputPort()); cleaner -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner -> Update(); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_prop = vtkSmartPointer<SBGATMassProperties>::New(); mass_prop -> SetInputConnection(cleaner -> GetOutputPort()); mass_prop -> SetDensity(1970); if (shape_in_meters) mass_prop -> SetScaleMeters(); else mass_prop -> SetScaleKiloMeters(); mass_prop -> Update(); SBGATMassPropertiesUQ shape_uq; shape_uq.SetModel(mass_prop); shape_uq.PrecomputeMassPropertiesPartials(); // Nominal Volume arma::vec::fixed<3> com = mass_prop -> GetCenterOfMass(); // Deviation arma::vec delta_C = 1e-3 * arma::randn<arma::vec>(3 * mass_prop -> GetN_vertices() ) / mass_prop -> GetScaleFactor(); // Linear dUf arma::vec::fixed<3> dcom_lin = shape_uq.GetPartialComPartialC() * delta_C * mass_prop -> GetScaleFactor() ; // Apply Tf deviation shape_uq. ApplyDeviation(delta_C); // Perturbed Uf arma::vec::fixed<3> com_p = mass_prop -> GetCenterOfMass(); // Non-linear dUf arma::vec::fixed<3> dcom = com_p - com; if(arma::norm(dcom - dcom_lin) / arma::norm(dcom_lin) < tol){ ++successes; } } std::cout << "\t Passed TestGetPartialComPartialC with " << double(successes)/N * 100 << " \% of successes. \n"; } void SBGATMassPropertiesUQ::ApplyTfDeviation(arma::vec::fixed<9> delta_Tf,const int & f){ int v0_index,v1_index,v2_index; this -> model -> GetIndicesVerticesInFacet(f,v0_index,v1_index,v2_index); double r0[3],r1[3],r2[3]; vtkPolyData * polydata = vtkPolyData::SafeDownCast(this -> model -> GetInput()); polydata -> GetPoint(v0_index,r0); polydata -> GetPoint(v1_index,r1); polydata -> GetPoint(v2_index,r2); r0[0] += delta_Tf(0); r0[1] += delta_Tf(1); r0[2] += delta_Tf(2); r1[0] += delta_Tf(3); r1[1] += delta_Tf(4); r1[2] += delta_Tf(5); r2[0] += delta_Tf(6); r2[1] += delta_Tf(7); r2[2] += delta_Tf(8); polydata -> GetPoints() -> SetPoint(v0_index,r0); polydata -> GetPoints() -> SetPoint(v1_index,r1); polydata -> GetPoints() -> SetPoint(v2_index,r2); polydata -> GetPoints() -> Modified(); polydata -> Modified(); this -> model -> Modified(); this -> model -> Update(); } void SBGATMassPropertiesUQ::TestGetPartialIPartialC(std::string input,double tol,bool shape_in_meters) { std::cout << "\t In TestGetPartialIPartialC ... "; int successes = 0; arma::arma_rng::set_seed(0); int N = 1000; #pragma omp parallel for reduction(+:successes) for (int i = 0; i < N ; ++i){ // Reading vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader -> SetFileName(input.c_str()); reader -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner -> SetInputConnection (reader -> GetOutputPort()); cleaner -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner -> Update(); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_prop = vtkSmartPointer<SBGATMassProperties>::New(); mass_prop -> SetInputConnection(cleaner -> GetOutputPort()); mass_prop -> SetDensity(1970); if (shape_in_meters) mass_prop -> SetScaleMeters(); else mass_prop -> SetScaleKiloMeters(); mass_prop -> Update(); SBGATMassPropertiesUQ shape_uq; shape_uq.SetModel(mass_prop); shape_uq.PrecomputeMassPropertiesPartials(); // Nominal arma::mat deltaI_mat = mass_prop -> GetUnitDensityInertiaTensor() ; arma::vec::fixed<6> deltaI = {deltaI_mat(0,0),deltaI_mat(1,1),deltaI_mat(2,2),deltaI_mat(0,1),deltaI_mat(0,2),deltaI_mat(1,2)}; // Deviation arma::vec delta_C = 1e-3 * arma::randn<arma::vec>(3 * mass_prop -> GetN_vertices() ) / mass_prop -> GetScaleFactor(); // Linear arma::vec::fixed<6> ddeltaI_lin = mass_prop -> GetScaleFactor() * shape_uq.GetPartialIPartialC() * delta_C; // Apply deviation shape_uq. ApplyDeviation(delta_C); // Nominal arma::mat deltaI_mat_p = mass_prop -> GetUnitDensityInertiaTensor() ; arma::vec::fixed<6> deltaI_p = {deltaI_mat_p(0,0),deltaI_mat_p(1,1),deltaI_mat_p(2,2),deltaI_mat_p(0,1),deltaI_mat_p(0,2),deltaI_mat_p(1,2)}; // Non-linear arma::vec::fixed<6> ddeltaI = deltaI_p - deltaI; if(arma::norm(arma::vectorise(ddeltaI - ddeltaI_lin)) / arma::norm(arma::vectorise(ddeltaI_lin)) < tol){ ++successes; } } std::cout << "\t Passed TestGetPartialIPartialC with " << double(successes)/N * 100 << " \% of successes. \n"; } void SBGATMassPropertiesUQ::TestGetPartialSigmaPartialC(std::string input,double tol,bool shape_in_meters) { std::cout << "\t In TestGetPartialSigmaPartialC ... "; int successes = 0; arma::arma_rng::set_seed(0); int N = 1000; #pragma omp parallel for reduction(+:successes) for (int i = 0; i < N ; ++i){ // Reading vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader -> SetFileName(input.c_str()); reader -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner -> SetInputConnection (reader -> GetOutputPort()); cleaner -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner -> Update(); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_prop = vtkSmartPointer<SBGATMassProperties>::New(); mass_prop -> SetInputConnection(cleaner -> GetOutputPort()); mass_prop -> SetDensity(1970); if (shape_in_meters) mass_prop -> SetScaleMeters(); else mass_prop -> SetScaleKiloMeters(); mass_prop -> Update(); SBGATMassPropertiesUQ shape_uq; shape_uq.SetModel(mass_prop); shape_uq.PrecomputeMassPropertiesPartials(); // Nominal arma::vec::fixed<3> sigma = RBK::dcm_to_mrp(mass_prop -> GetPrincipalAxes()) ; // Deviation arma::vec delta_C = 1e-3 * arma::randn<arma::vec>(3 * mass_prop -> GetN_vertices() ) / mass_prop -> GetScaleFactor(); // Linear arma::vec::fixed<3> dsigma_lin = mass_prop -> GetScaleFactor() * shape_uq.GetPartialSigmaPartialC() * delta_C; // Apply deviation shape_uq. ApplyDeviation(delta_C); // Perturbed arma::vec::fixed<3> sigma_p = RBK::dcm_to_mrp(mass_prop -> GetPrincipalAxes()) ; // Non-linear arma::vec::fixed<3> dsigma = RBK::dcm_to_mrp(RBK::mrp_to_dcm(sigma_p) * RBK::mrp_to_dcm(sigma).t()); if(arma::norm(RBK::dcm_to_mrp(RBK::mrp_to_dcm(dsigma) * RBK::mrp_to_dcm(dsigma_lin).t())) / arma::norm(dsigma_lin) < tol){ ++successes; } } std::cout << "\t Passed TestGetPartialSigmaPartialC with " << double(successes)/N * 100 << " \% of successes. \n"; } void SBGATMassPropertiesUQ::TestGetPartialAllInertiaPartialC(std::string input,double tol,bool shape_in_meters) { std::cout << "\t In TestGetPartialAllInertiaPartialC ... "; int successes = 0; arma::arma_rng::set_seed(0); int N = 1000; #pragma omp parallel for reduction(+:successes) for (int i = 0; i < N ; ++i){ // Reading vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader -> SetFileName(input.c_str()); reader -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner -> SetInputConnection (reader -> GetOutputPort()); cleaner -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner -> Update(); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_prop = vtkSmartPointer<SBGATMassProperties>::New(); mass_prop -> SetInputConnection(cleaner -> GetOutputPort()); mass_prop -> SetDensity(1970); if (shape_in_meters) mass_prop -> SetScaleMeters(); else mass_prop -> SetScaleKiloMeters(); mass_prop -> Update(); SBGATMassPropertiesUQ shape_uq; shape_uq.SetModel(mass_prop); shape_uq.PrecomputeMassPropertiesPartials(); // Nominal double V = mass_prop -> GetVolume(); arma::vec::fixed<3> com = mass_prop -> GetCenterOfMass(); arma::mat deltaI_mat = mass_prop -> GetUnitDensityInertiaTensor() ; arma::vec::fixed<6> deltaI = {deltaI_mat(0,0),deltaI_mat(1,1),deltaI_mat(2,2),deltaI_mat(0,1),deltaI_mat(0,2),deltaI_mat(1,2)}; // Deviation arma::vec delta_C = 1e-3 * arma::randn<arma::vec>(3 * mass_prop -> GetN_vertices() ) / mass_prop -> GetScaleFactor(); // Linear double dV_lin = arma::dot(shape_uq.GetPartialVolumePartialC(),mass_prop -> GetScaleFactor() * delta_C); arma::vec::fixed<3> dcom_lin = shape_uq.GetPartialComPartialC() * mass_prop -> GetScaleFactor() * delta_C; arma::vec::fixed<6> ddeltaI_lin = mass_prop -> GetScaleFactor() * shape_uq.GetPartialIPartialC() * delta_C; // Apply deviation shape_uq. ApplyDeviation(delta_C); double V_p = mass_prop -> GetVolume(); arma::vec::fixed<3> com_p = mass_prop -> GetCenterOfMass(); double dV =V_p - V; arma::vec::fixed<3> dcom = com_p - com; arma::mat deltaI_mat_p = mass_prop -> GetUnitDensityInertiaTensor() ; arma::vec::fixed<6> deltaI_p = {deltaI_mat_p(0,0),deltaI_mat_p(1,1),deltaI_mat_p(2,2),deltaI_mat_p(0,1),deltaI_mat_p(0,2),deltaI_mat_p(1,2)}; // Non-linear arma::vec::fixed<6> ddeltaI = deltaI_p - deltaI; if(arma::abs(arma::vectorise(ddeltaI - ddeltaI_lin)).max() / arma::norm(arma::vectorise(ddeltaI_lin)) < tol){ if (std::abs(dV - dV_lin)/std::abs(dV_lin) < tol){ if(arma::abs(dcom - dcom_lin).max() / arma::norm(dcom_lin) < tol){ ++successes; } } } } std::cout << "\t Passed TestGetPartialAllInertiaPartialC with " << double(successes)/N * 100 << " \% of successes \n"; } void SBGATMassPropertiesUQ::TestPartialDeltaIfPartialTf(std::string input,double tol,bool shape_in_meters) { std::cout << "\t In TestPartialDeltaIfPartialTf ... "; int successes = 0; arma::arma_rng::set_seed(0); int N = 1000; #pragma omp parallel for reduction(+:successes) for (int i = 0; i < N ; ++i){ // Reading vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader -> SetFileName(input.c_str()); reader -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner -> SetInputConnection (reader -> GetOutputPort()); cleaner -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner -> Update(); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_prop = vtkSmartPointer<SBGATMassProperties>::New(); mass_prop -> SetInputConnection(cleaner -> GetOutputPort()); mass_prop -> SetDensity(1970); if (shape_in_meters) mass_prop -> SetScaleMeters(); else mass_prop -> SetScaleKiloMeters(); mass_prop -> Update(); SBGATMassPropertiesUQ shape_uq; shape_uq.SetModel(mass_prop); shape_uq.PrecomputeMassPropertiesPartials(); int N_facets = vtkPolyData::SafeDownCast(mass_prop -> GetInput()) -> GetNumberOfCells(); arma::ivec f_vec = arma::randi<arma::ivec>(1,arma::distr_param(0,N_facets - 1)); int f = f_vec(0); // Nominal arma::mat deltaIf_mat = mass_prop -> GetDeltaIOverDeltaV(f) * mass_prop -> GetDeltaV(f) ; arma::vec::fixed<6> deltaIf = {deltaIf_mat(0,0),deltaIf_mat(1,1),deltaIf_mat(2,2),deltaIf_mat(0,1),deltaIf_mat(0,2),deltaIf_mat(1,2)}; // Deviation arma::vec::fixed<9> delta_Tf = 1e-3 * arma::randn<arma::vec>(9) / mass_prop -> GetScaleFactor(); // Linear arma::vec::fixed<6> ddeltaIf_lin = mass_prop -> GetScaleFactor() * shape_uq.PartialDeltaIfPartialTf(f) * delta_Tf; // Apply Tf deviation shape_uq. ApplyTfDeviation(delta_Tf,f); // Nominal arma::mat deltaIf_mat_p = mass_prop -> GetDeltaIOverDeltaV(f) * mass_prop -> GetDeltaV(f) ; arma::vec::fixed<6> deltaIf_p = {deltaIf_mat_p(0,0),deltaIf_mat_p(1,1),deltaIf_mat_p(2,2),deltaIf_mat_p(0,1),deltaIf_mat_p(0,2),deltaIf_mat_p(1,2)}; // Non-linear arma::vec::fixed<6> ddeltaIf = deltaIf_p - deltaIf; if(arma::norm(arma::vectorise(ddeltaIf - ddeltaIf_lin)) / arma::norm(arma::vectorise(ddeltaIf_lin)) < tol){ ++successes; } } std::cout << "\t Passed TestPartialDeltaIfPartialTf with " << double(successes)/N * 100 << " \% of successes. \n"; } arma::mat::fixed<3,9> SBGATMassPropertiesUQ::PartialDeltaComPartialTf(const int & f) const{ SBGATMassProperties * mass_model = nullptr; mass_model = SBGATMassProperties::SafeDownCast(this -> model); if (!mass_model){ mass_model = SBGATPolyhedronGravityModel::SafeDownCast(this -> model); } return (1./mass_model -> GetVolume() * ((mass_model -> GetDeltaCM(f) - mass_model -> GetCenterOfMass()) * this -> PartialDeltaVfPartialTf(f) + mass_model -> GetDeltaV(f) * SBGATMassPropertiesUQ::PartialDeltaCMfPartialTf())); } arma::rowvec::fixed<9> SBGATMassPropertiesUQ::PartialEqDeltaIfErPartialTf(const int & f,const int & q, const int & r,const arma::vec::fixed<9> & Tf) const{ SBGATMassProperties * mass_model = nullptr; mass_model = SBGATMassProperties::SafeDownCast(this -> model); if (!mass_model){ mass_model = SBGATPolyhedronGravityModel::SafeDownCast(this -> model); } arma::vec::fixed<3> e_q = arma::zeros<arma::vec >(3); arma::vec::fixed<3> e_r = arma::zeros<arma::vec >(3); e_q(q) = 1; e_r(r) = 1; arma::rowvec::fixed<9> partial = (arma::dot(e_q, mass_model -> GetDeltaIOverDeltaV(f) * e_r) * this -> PartialDeltaVfPartialTf(f) + mass_model -> GetDeltaV(f) * this -> PartialEqDeltaIOverDeltaVfErPartialTf(e_q,e_r,Tf)); return partial; } arma::rowvec::fixed<9> SBGATMassPropertiesUQ::PartialEqDeltaIOverDeltaVfErPartialTf(const arma::vec::fixed<3> & e_q,const arma::vec::fixed<3> & e_r, const arma::vec::fixed<9> & Tf) const { arma::rowvec::fixed<9> partial; arma::mat::fixed<3,9> A,A_0,A_1,A_2; A.cols(0,2) = arma::eye<arma::mat>(3,3); A.cols(3,5) = arma::eye<arma::mat>(3,3); A.cols(6,8) = arma::eye<arma::mat>(3,3); A_0.cols(0,2) = arma::eye<arma::mat>(3,3); A_0.cols(3,5) = arma::zeros<arma::mat>(3,3); A_0.cols(6,8) = arma::zeros<arma::mat>(3,3); A_1.cols(0,2) = arma::zeros<arma::mat>(3,3); A_1.cols(3,5) = arma::eye<arma::mat>(3,3); A_1.cols(6,8) = arma::zeros<arma::mat>(3,3); A_2.cols(0,2) = arma::zeros<arma::mat>(3,3); A_2.cols(3,5) = arma::zeros<arma::mat>(3,3); A_2.cols(6,8) = arma::eye<arma::mat>(3,3); partial = Tf.t() * (A.t() * (RBK::tilde(e_q) * RBK::tilde(e_r) + RBK::tilde(e_r) * RBK::tilde(e_q)) * A + A_0.t() * (RBK::tilde(e_q) * RBK::tilde(e_r) + RBK::tilde(e_r) * RBK::tilde(e_q)) * A_0 + A_1.t() * (RBK::tilde(e_q) * RBK::tilde(e_r) + RBK::tilde(e_r) * RBK::tilde(e_q)) * A_1 + A_2.t() * (RBK::tilde(e_q) * RBK::tilde(e_r) + RBK::tilde(e_r) * RBK::tilde(e_q)) * A_2); return -1./20 * partial; } arma::mat::fixed<6,9> SBGATMassPropertiesUQ::PartialDeltaIfPartialTf(const int & f) const{ arma::mat::fixed<6,9> partial; double r0[3]; double r1[3]; double r2[3]; this -> model -> GetVerticesInFacet(f,r0,r1,r2); arma::vec::fixed<9> Tf = arma::vec({r0[0],r0[1],r0[2],r1[0],r1[1],r1[2],r2[0],r2[1],r2[2]}); partial.row(0) = this -> PartialEqDeltaIfErPartialTf(f,0,0,Tf); partial.row(1) = this -> PartialEqDeltaIfErPartialTf(f,1,1,Tf); partial.row(2) = this -> PartialEqDeltaIfErPartialTf(f,2,2,Tf); partial.row(3) = this -> PartialEqDeltaIfErPartialTf(f,0,1,Tf); partial.row(4) = this -> PartialEqDeltaIfErPartialTf(f,0,2,Tf); partial.row(5) = this -> PartialEqDeltaIfErPartialTf(f,1,2,Tf); return partial ; } void SBGATMassPropertiesUQ::TestPartialEqDeltaIfErPartialTf(std::string input,double tol,bool shape_in_meters){ std::cout << "\t In TestPartialEqDeltaIfErPartialTf ... "; int successes = 0; arma::arma_rng::set_seed(0); int N = 1000; // Reading vtkSmartPointer<vtkOBJReader> reader = vtkSmartPointer<vtkOBJReader>::New(); reader -> SetFileName(input.c_str()); reader -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner -> SetInputConnection (reader -> GetOutputPort()); cleaner -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner -> Update(); #pragma omp parallel for reduction(+:successes) for (int i = 0; i < N ; ++i){ vtkSmartPointer<vtkPolyData> input_shape = vtkSmartPointer<vtkPolyData>::New(); input_shape -> DeepCopy(cleaner -> GetOutput()); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_prop = vtkSmartPointer<SBGATMassProperties>::New(); mass_prop -> SetInputData(input_shape); mass_prop -> SetDensity(1970); if (shape_in_meters) mass_prop -> SetScaleMeters(); else mass_prop -> SetScaleKiloMeters(); mass_prop -> Update(); SBGATMassPropertiesUQ shape_uq; shape_uq.SetModel(mass_prop); shape_uq.PrecomputeMassPropertiesPartials(); int N_facets = vtkPolyData::SafeDownCast(mass_prop -> GetInput()) -> GetNumberOfCells(); arma::ivec f_vec = arma::randi<arma::ivec>(1,arma::distr_param(0,N_facets - 1)); int f = f_vec(0); arma::ivec indices_vec = arma::randi<arma::ivec>(2,arma::distr_param(0,2)); arma::vec::fixed<3> e_q = arma::zeros<arma::vec>(3); arma::vec::fixed<3> e_r = arma::zeros<arma::vec>(3); e_q(indices_vec(0)) = 1; e_r(indices_vec(1)) = 1; // Nominal double Iqf = arma::dot(e_q,mass_prop -> GetDeltaIOverDeltaV(f) * mass_prop -> GetDeltaV(f) * e_r); // Deviation arma::vec::fixed<9> delta_Tf = 1e-3 * arma::randn<arma::vec>(9) / mass_prop -> GetScaleFactor(); // Linear dUf double r0[3]; double r1[3]; double r2[3]; mass_prop -> GetVerticesInFacet(f,r0,r1,r2); arma::vec::fixed<9> Tf = arma::vec({r0[0],r0[1],r0[2],r1[0],r1[1],r1[2],r2[0],r2[1],r2[2]}); double dIqf_lin = arma::dot(shape_uq.PartialEqDeltaIfErPartialTf(f,indices_vec(0),indices_vec(1), Tf) , mass_prop -> GetScaleFactor()* delta_Tf); // Apply Tf deviation shape_uq. ApplyTfDeviation(delta_Tf,f); // Perturbed double Iqf_p = arma::dot(e_q,mass_prop -> GetDeltaIOverDeltaV(f) * mass_prop -> GetDeltaV(f) * e_r); // Non-linear dUf double dIqf = Iqf_p - Iqf; if(std::abs(dIqf - dIqf_lin) / std::abs(dIqf_lin) < tol){ ++successes; } } std::cout << "\t Passed TestPartialEqDeltaIfErPartialTf with " << double(successes)/N * 100 << " \% of successes. \n"; } void SBGATMassPropertiesUQ::ApplyDeviation(const arma::vec & delta_C){ vtkPolyData * polydata = vtkPolyData::SafeDownCast(this -> model -> GetInput()); int N_C = polydata -> GetNumberOfPoints(); assert(3 * N_C == delta_C.n_rows); double r[3]; for (int i = 0; i < N_C; ++i){ polydata -> GetPoint(i,r); r[0] += delta_C(3 * i); r[1] += delta_C(3 * i + 1); r[2] += delta_C(3 * i + 2); polydata -> GetPoints() -> SetPoint(i,r); } polydata -> GetPoints() -> Modified(); polydata -> Modified(); this -> model -> Modified(); SBGATMassProperties::SafeDownCast(this -> model) -> Update(); } arma::mat::fixed<3,6> SBGATMassPropertiesUQ::PartialSigmaPartialI() const{ SBGATMassProperties * mass_model = nullptr; mass_model = SBGATMassProperties::SafeDownCast(this -> model); if (!mass_model){ mass_model = SBGATPolyhedronGravityModel::SafeDownCast(this -> model); } arma::mat::fixed<3,3> BP = mass_model -> GetPrincipalAxes().t(); arma::vec::fixed<3> moments = mass_model -> GetUnitDensityInertiaMoments(); arma::mat::fixed<3,6> W1,W2,W3; W1 = W2 = W3 = arma::zeros<arma::mat>(3,6); W1(0,0) = 1; W1(1,3) = 1; W1(2,4) = 1; W2(0,3) = 1; W2(1,1) = 1; W2(2,5) = 1; W3(0,4) = 1; W3(1,5) = 1; W3(2,2) = 1; arma::mat::fixed<9,3> H = arma::zeros<arma::mat>(9,3); arma::mat::fixed<9,6> V = arma::zeros<arma::mat>(9,6); arma::mat::fixed<3,3> D = arma::diagmat(moments); int index = 0; for (int q = 0; q < 3; ++q){ arma::vec::fixed<3> e_q = arma::zeros<arma::vec>(3); e_q(q) = 1; arma::vec::fixed<3> f_q = BP * e_q; for (int r = 0; r < 3; ++r){ arma::vec::fixed<3> e_r= arma::zeros<arma::vec>(3); e_r(r) = 1; arma::vec::fixed<3> f_r = BP * e_r; double delta_rq; if (r==q){ delta_rq = 1; } else{ delta_rq = 0; } arma::mat::fixed<3,6> Fq = arma::zeros<arma::mat>(3,6); Fq.row(0) = f_q.t() * W1; Fq.row(1) = f_q.t() * W2; Fq.row(2) = f_q.t() * W3; arma::rowvec::fixed<6> J_rq = f_r.t() * Fq; H.row(index) = e_r.t() * ( D * RBK::tilde(e_q) - RBK::tilde(D * e_q)); V.row(index) = (J_rq - delta_rq * e_r.t() * this -> precomputed_partialUnitDensityMomentsPartialI)/4; ++index; } } return arma::inv(H.t() * H) * H.t() * V; } arma::mat::fixed<3,6> SBGATMassPropertiesUQ::PartialUnitDensityMomentsPartialI() const{ SBGATMassProperties * mass_model = nullptr; mass_model = SBGATMassProperties::SafeDownCast(this -> model); if (!mass_model){ mass_model = SBGATPolyhedronGravityModel::SafeDownCast(this -> model); } arma::mat::fixed<3,3> eigvec = mass_model -> GetPrincipalAxes().t(); arma::mat::fixed<3,6> W1,W2,W3; W1 = W2 = W3 = arma::zeros<arma::mat>(3,6); W1(0,0) = 1; W1(1,3) = 1; W1(2,4) = 1; W2(0,3) = 1; W2(1,1) = 1; W2(2,5) = 1; W3(0,4) = 1; W3(1,5) = 1; W3(2,2) = 1; arma::mat::fixed<3,6> U1,U2,U3; U1.row(0) = eigvec.col(0).t() * W1; U1.row(1) = eigvec.col(0).t() * W2; U1.row(2) = eigvec.col(0).t() * W3; U2.row(0) = eigvec.col(1).t() * W1; U2.row(1) = eigvec.col(1).t() * W2; U2.row(2) = eigvec.col(1).t() * W3; U3.row(0) = eigvec.col(2).t() * W1; U3.row(1) = eigvec.col(2).t() * W2; U3.row(2) = eigvec.col(2).t() * W3; arma::mat::fixed<3,6> dMdI = arma::zeros<arma::mat>(3,6); dMdI.row(0) = eigvec.col(0).t() * U1; dMdI.row(1) = eigvec.col(1).t() * U2; dMdI.row(2) = eigvec.col(2).t() * U3; return dMdI; } /** Evaluates the partial of the volume, center of mass and mrp orienting the principal axes relative to the vertices coordinates and stores the computed partials in designated containers */ void SBGATMassPropertiesUQ::PrecomputeMassPropertiesPartials(){ arma::rowvec dVdC = arma::zeros<arma::rowvec>(3 * this -> model -> GetN_vertices()); arma::mat dCOMdC = arma::zeros<arma::mat>(3,3 * this -> model -> GetN_vertices()); arma::mat dIdC = arma::zeros<arma::mat>(6,3 * this -> model -> GetN_vertices()); #pragma omp parallel for reduction(+:dVdC) reduction(+:dCOMdC,dIdC) for (int f = 0; f < this -> model -> GetN_facets(); ++f){ arma::sp_mat connect_table = this -> PartialTfPartialC(f); dVdC += this -> PartialDeltaVfPartialTf(f) * connect_table; dCOMdC += this -> PartialDeltaComPartialTf(f) * connect_table; dIdC += this -> PartialDeltaIfPartialTf(f) * connect_table; } this -> precomputed_partialVpartialC.clear(); this -> precomputed_partialGpartialC.clear(); this -> precomputed_partialSigmapartialC.clear(); this -> precomputed_partialIpartialC.clear(); this -> precomputed_partialVpartialC = dVdC; this -> precomputed_partialGpartialC = dCOMdC; this -> precomputed_partialIpartialC = dIdC; this -> precomputed_partialUnitDensityMomentsPartialI = this -> PartialUnitDensityMomentsPartialI(); this -> precomputed_partialSigmapartialI = this -> PartialSigmaPartialI(); this -> precomputed_partialSigmapartialC = this -> precomputed_partialSigmapartialI * precomputed_partialIpartialC; } void SBGATMassPropertiesUQ::RunMCUQVolumeCOMInertia(std::string path_to_shape, const double & density, const bool & shape_in_meters, const arma::mat & C_CC, const unsigned int & N_samples, std::string output_dir, int N_saved_shapes, arma::mat & deviations, arma::vec & all_volumes, arma::mat & all_com, arma::mat & all_inertia){ // Reading vtkSmartPointer<vtkOBJReader> reader_mc = vtkSmartPointer<vtkOBJReader>::New(); reader_mc -> SetFileName(path_to_shape.c_str()); reader_mc -> Update(); // Cleaning vtkSmartPointer<vtkCleanPolyData> cleaner_mc = vtkSmartPointer<vtkCleanPolyData>::New(); cleaner_mc -> SetInputConnection (reader_mc -> GetOutputPort()); cleaner_mc -> SetOutputPointsPrecision ( vtkAlgorithm::DesiredOutputPrecision::DOUBLE_PRECISION ); cleaner_mc -> Update(); if (all_volumes.size() != N_samples){ all_volumes.clear(); all_volumes = arma::vec (N_samples); } if (deviations.size() != N_samples){ deviations.clear(); deviations = arma::mat(3 * cleaner_mc -> GetOutput() -> GetNumberOfPoints(), N_samples); } if (all_com.size() != N_samples){ all_com.clear(); all_com = arma::mat(3,N_samples); } if (all_inertia.size() != N_samples){ all_inertia.clear(); all_inertia = arma::mat(6,N_samples); } for (unsigned int i = 0; i < N_samples ; ++i){ deviations.col(i) = C_CC * arma::randn<arma::vec>(3 * cleaner_mc -> GetOutput() -> GetNumberOfPoints()); } #pragma omp parallel for for (unsigned int i = 0; i < N_samples ; ++i){ vtkSmartPointer<vtkPolyData> shape_copy = vtkSmartPointer<vtkPolyData>::New(); shape_copy -> DeepCopy(cleaner_mc -> GetOutput()); // Creating the PGM dyads vtkSmartPointer<SBGATMassProperties> mass_filter_mc = vtkSmartPointer<SBGATMassProperties>::New(); mass_filter_mc -> SetInputData(shape_copy); mass_filter_mc -> SetDensity(density); if (shape_in_meters){ mass_filter_mc -> SetScaleMeters(); } else{ mass_filter_mc -> SetScaleKiloMeters(); } SBGATMassPropertiesUQ shape_uq_mc; shape_uq_mc. SetModel(mass_filter_mc); shape_uq_mc. ApplyDeviation(deviations.col(i)); all_volumes(i) = mass_filter_mc -> GetVolume(); all_com.col(i) = mass_filter_mc -> GetCenterOfMass(); arma::mat I = mass_filter_mc -> GetUnitDensityInertiaTensor() ; arma::vec::fixed<6> I_param = {I(0,0),I(1,1),I(2,2),I(0,1),I(0,2),I(1,2)}; all_inertia.col(i) = I_param; if (i < N_saved_shapes){ shape_uq_mc. TakeAndSaveSlice(0,output_dir + "slice_x_" + std::to_string(i) + ".txt",0); shape_uq_mc. TakeAndSaveSlice(1,output_dir + "slice_y_" + std::to_string(i) + ".txt",0); shape_uq_mc. TakeAndSaveSlice(2,output_dir + "slice_z_" + std::to_string(i) + ".txt",0); vtkSmartPointer<SBGATObjWriter> writer = vtkSmartPointer<SBGATObjWriter>::New(); writer -> SetInputData(mass_filter_mc -> GetInput()); writer -> SetFileName(std::string({output_dir + "mc_shape_" + std::to_string(i) + ".obj"}).c_str()); writer -> Update(); } } }
28.350727
155
0.687707
[ "model" ]
fdd24c649ac77c9436a46d6268dce244e4818413
866
cpp
C++
src/structured_grid/mpc_pk/PMBld.cpp
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
37
2017-04-26T16:27:07.000Z
2022-03-01T07:38:57.000Z
src/structured_grid/mpc_pk/PMBld.cpp
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
494
2016-09-14T02:31:13.000Z
2022-03-13T18:57:05.000Z
src/structured_grid/mpc_pk/PMBld.cpp
fmyuan/amanzi
edb7b815ae6c22956c8519acb9d87b92a9915ed4
[ "RSA-MD" ]
43
2016-09-26T17:58:40.000Z
2022-03-25T02:29:59.000Z
#include <winstd.H> #include <PorousMedia.H> // -------------------------------------------------------------------- // ----- PMBld class instantiation // -------------------------------------------------------------------- PMBld nsbld; LevelBld* getLevelBld() { return &nsbld; } // -------------------------------------------------------------------- // ----- PMBld class implementation // -------------------------------------------------------------------- void PMBld::variableSetUp() { PorousMedia::variableSetUp(); } void PMBld::variableCleanUp() { PorousMedia::variableCleanUp(); } AmrLevel* PMBld::operator()() { return new PorousMedia; } AmrLevel* PMBld::operator()(Amr &papa, int lev, const Geometry &level_geom, const BoxArray &ba, Real time) { return new PorousMedia(papa, lev, level_geom, ba, time); }
19.244444
71
0.438799
[ "geometry" ]
fdd88bdf8a476f187d6d76c5e234bfe2a6fafb5b
4,173
cpp
C++
physx/source/simulationcontroller/src/ScRigidCore.cpp
rextimmy/PhysX
b39f46cb024615ebb23546e24515d2075f8ff034
[ "BSD-3-Clause" ]
5
2021-05-22T15:05:45.000Z
2022-01-17T02:15:16.000Z
physx/source/simulationcontroller/src/ScRigidCore.cpp
rextimmy/PhysX
b39f46cb024615ebb23546e24515d2075f8ff034
[ "BSD-3-Clause" ]
null
null
null
physx/source/simulationcontroller/src/ScRigidCore.cpp
rextimmy/PhysX
b39f46cb024615ebb23546e24515d2075f8ff034
[ "BSD-3-Clause" ]
3
2020-02-03T09:01:27.000Z
2022-03-02T04:10:47.000Z
// // 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 NVIDIA CORPORATION 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 ''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. // // Copyright (c) 2008-2021 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #include "ScBodyCore.h" #include "ScStaticCore.h" #include "ScRigidSim.h" #include "ScShapeSim.h" #include "ScScene.h" #include "ScPhysics.h" using namespace physx; using namespace Sc; static ShapeSim& getSimForShape(const ShapeCore& core, const ActorSim& actorSim) { return *static_cast<ShapeSim*>(actorSim.getElements_()[core.mSimIndex]); } RigidCore::RigidCore(const PxActorType::Enum type) : ActorCore(type, PxActorFlag::eVISUALIZATION, PX_DEFAULT_CLIENT, 0) { } RigidCore::~RigidCore() { } void RigidCore::addShapeToScene(ShapeCore& shapeCore) { RigidSim* sim = getSim(); PX_ASSERT(sim); if(!sim) return; sim->getScene().addShape_(*sim, shapeCore); } void RigidCore::removeShapeFromScene(ShapeCore& shapeCore, bool wakeOnLostTouch) { RigidSim* sim = getSim(); if(!sim) return; ShapeSim& s = getSimForShape(shapeCore, *sim); sim->getScene().removeShape_(s, wakeOnLostTouch); } void RigidCore::onShapeChange(ShapeCore& shape, ShapeChangeNotifyFlags notifyFlags, PxShapeFlags oldShapeFlags, bool forceBoundsUpdate) { // DS: We pass flags to avoid searching multiple times or exposing RigidSim outside SC, and this form is // more convenient for the Scb::Shape::syncState method. If we start hitting this a lot we should do it // a different way, but shape modification after insertion is rare. RigidSim* sim = getSim(); if(!sim) return; ShapeSim& s = getSimForShape(shape, *sim); if(notifyFlags & ShapeChangeNotifyFlag::eGEOMETRY) s.onVolumeOrTransformChange(forceBoundsUpdate); if(notifyFlags & ShapeChangeNotifyFlag::eMATERIAL) s.onMaterialChange(); if(notifyFlags & ShapeChangeNotifyFlag::eRESET_FILTERING) s.onResetFiltering(); if(notifyFlags & ShapeChangeNotifyFlag::eSHAPE2BODY) s.onVolumeOrTransformChange(forceBoundsUpdate); if(notifyFlags & ShapeChangeNotifyFlag::eFILTERDATA) s.onFilterDataChange(); if(notifyFlags & ShapeChangeNotifyFlag::eFLAGS) s.onFlagChange(oldShapeFlags); if(notifyFlags & ShapeChangeNotifyFlag::eCONTACTOFFSET) s.onContactOffsetChange(); if(notifyFlags & ShapeChangeNotifyFlag::eRESTOFFSET) s.onRestOffsetChange(); } RigidSim* RigidCore::getSim() const { return static_cast<RigidSim*>(ActorCore::getSim()); } PxU32 RigidCore::getRigidID() const { return static_cast<RigidSim*>(ActorCore::getSim())->getRigidID(); } PxActor* RigidCore::getPxActor() const { return Ps::pointerOffset<PxActor*>(const_cast<RigidCore*>(this), gOffsetTable.scCore2PxActor[getActorCoreType()]); }
35.974138
135
0.767074
[ "shape" ]
fdda213bd603b449f9019de99056def53c2060aa
9,446
cpp
C++
src/Tread/TexListBox.cpp
hogsy/xtread
9d4eaf2778b8b687256788c7617b19542986bf32
[ "MIT" ]
1
2019-07-20T12:10:20.000Z
2019-07-20T12:10:20.000Z
src/Tread/TexListBox.cpp
hogsy/xtread
9d4eaf2778b8b687256788c7617b19542986bf32
[ "MIT" ]
null
null
null
src/Tread/TexListBox.cpp
hogsy/xtread
9d4eaf2778b8b687256788c7617b19542986bf32
[ "MIT" ]
null
null
null
// TexListBox.cpp : implementation file // #include "stdafx.h" #include "tread3d.h" #include "TexListBox.h" #include "texapi.h" #include "Tread3DDoc.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define CLIST_BORDER_SIZE 3 #define CLIST_CAPTION_SIZE 14 #define CLIST_TOTAL_HEIGHT ((CLIST_BORDER_SIZE<<1) + CLIST_CAPTION_SIZE) #define CLIST_TOTAL_WIDTH ((CLIST_BORDER_SIZE<<1)) ///////////////////////////////////////////////////////////////////////////// // CTexListBox CTexListBox::CTexListBox() { m_pTexList = NULL; m_pTexture = NULL; m_nMaxWidth = m_nMaxHeight = 64; m_nCount = 0; } CTexListBox::~CTexListBox() { } BEGIN_MESSAGE_MAP(CTexListBox, CListBox) //{{AFX_MSG_MAP(CTexListBox) ON_WM_ERASEBKGND() ON_WM_SIZE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTexListBox message handlers void CTexListBox::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct) { int x, y, nWidth, nHeight, rech, recw; CFont* pOldFont; CDC* pDC; CTexture* pTex; pDC = CDC::FromHandle(lpDrawItemStruct->hDC); //Device context pTex = (CTexture*)lpDrawItemStruct->itemData; //texture item if(pTex == NULL) { pOldFont = pDC->SelectObject(&ftText); pDC->SetTextColor(RGB(255, 255, 255)); pDC->TextOut(20, 10, "No matching texture(s)"); pDC->SelectObject(pOldFont); pDC->FillSolidRect(&m_rcClient, RGB(0, 0, 0)); return; } if(m_pTexture == NULL) { CRect rcItem, rcDraw; rcItem = lpDrawItemStruct->rcItem; rcDraw = rcItem; if(m_pTexture == NULL) { // Has current focus. if(lpDrawItemStruct->itemAction & ODA_FOCUS) { // Focus rect if(lpDrawItemStruct->itemState & ODS_FOCUS) { pDC->Draw3dRect(&rcDraw, RGB(200, 200, 0), RGB(160, 160, 0)); InflateRect(&rcDraw, -1, -1); pDC->Draw3dRect(&rcDraw, RGB(200, 200, 0), RGB(160, 160, 0)); InflateRect(&rcDraw, -1, -1); pDC->Draw3dRect(&rcDraw, RGB(200, 200, 0), RGB(160, 160, 0)); } else { pDC->Draw3dRect(&rcDraw, RGB(0, 0, 0), RGB(0, 0, 0)); InflateRect(&rcDraw, -1, -1); pDC->Draw3dRect(&rcDraw, RGB(0, 0, 0), RGB(0, 0, 0)); InflateRect(&rcDraw, -1, -1); pDC->Draw3dRect(&rcDraw, RGB(0, 0, 0), RGB(0, 0, 0)); } return; } } pTex->Load(); //load the texture rcDraw = rcItem; InflateRect(&rcDraw, -CLIST_BORDER_SIZE, -CLIST_BORDER_SIZE); // Determine the width/height of the object. nWidth = (pTex->m_nWidth > m_nMaxWidth) ? m_nMaxWidth : pTex->m_nWidth; nHeight = (pTex->m_nHeight > m_nMaxHeight) ? m_nMaxHeight : pTex->m_nHeight; recw = rcDraw.right - rcDraw.left; rech = rcDraw.bottom - rcDraw.top - CLIST_CAPTION_SIZE; // Find the center for the texture. x = rcDraw.left + (recw >> 1) - (nWidth >> 1); y = rcDraw.top + (rech >> 1) - (nHeight >> 1); bih.bmiHeader.biWidth = pTex->m_nSclWidth; bih.bmiHeader.biHeight = -pTex->m_nSclHeight; // Display the bitmap. StretchDIBits(pDC->m_hDC, x, y, nWidth, nHeight, 0, 0, pTex->m_nSclWidth, pTex->m_nSclHeight, pTex->m_pData, (BITMAPINFO*)&bih, DIB_RGB_COLORS, SRCCOPY); if(m_nMaxHeight == 32) return; // Below the texture itself. rcDraw = rcItem; InflateRect(&rcDraw, -CLIST_BORDER_SIZE, -CLIST_BORDER_SIZE); // Move to position. rcDraw.top = rcDraw.bottom - CLIST_CAPTION_SIZE; pDC->FillSolidRect(&rcDraw, RGB(0, 90, 180)); // Locate text position. x = rcDraw.left + 1; y = rcDraw.top + 1; // Write the text. pOldFont = pDC->SelectObject(&ftText); pDC->SetTextColor(RGB(255, 255, 255)); pDC->SetBkColor(RGB(0, 90, 180)); pDC->TextOut(x, y, pTex->m_sName); pDC->SelectObject(pOldFont); } else if(m_pTexture != NULL) { //int nWidth, nHeight; CRect rcClient; pTex->Load(); GetClientRect(&rcClient); nWidth = rcClient.right - rcClient.left; nHeight = rcClient.bottom - rcClient.top; pDC->FillSolidRect(&rcClient, RGB(0, 0, 0)); // Draw the texture info. nWidth = (pTex->m_nWidth > m_nMaxWidth) ? m_nMaxWidth : pTex->m_nWidth; nHeight = (pTex->m_nHeight > m_nMaxHeight) ? m_nMaxHeight : pTex->m_nHeight; bih.bmiHeader.biWidth = pTex->m_nSclWidth; bih.bmiHeader.biHeight = -pTex->m_nSclHeight; // Display the bitmap. StretchDIBits(pDC->m_hDC, 0, 0, nWidth, nHeight, 0, 0, pTex->m_nSclWidth, pTex->m_nSclHeight, pTex->m_pData, (BITMAPINFO*)&bih, DIB_RGB_COLORS, SRCCOPY); } else pDC->FillSolidRect(&m_rcClient, RGB(0, 0, 0)); } void CTexListBox::MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct) { lpMeasureItemStruct->itemWidth = m_nMaxWidth + CLIST_TOTAL_WIDTH; lpMeasureItemStruct->itemHeight = m_nMaxHeight + CLIST_TOTAL_HEIGHT; } void CTexListBox::Initialize() { SetMaxItemSize(64, 64); ftText.CreateFont(12, 0, 0, 0, 170, false, false, false, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, "Arial"); bih.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bih.bmiHeader.biPlanes = 1; bih.bmiHeader.biBitCount = 24; bih.bmiHeader.biCompression = BI_RGB; bih.bmiHeader.biSizeImage = 0; GetClientRect(&m_rcClient); } void CTexListBox::SetMaxItemSize(int nWidth, int nHeight) { m_nMaxWidth = nWidth; m_nMaxHeight = nHeight; SetItemHeight(0, m_nMaxWidth + CLIST_TOTAL_HEIGHT); SetColumnWidth(m_nMaxHeight + CLIST_TOTAL_WIDTH); RedrawWindow(); } bool CTexListBox::SetTexturePointer(CTexture* pTexture) { int n; ResetContent(); m_pTexList = NULL; m_pTexMru = NULL; m_pTexture = pTexture; if(m_pTexture == NULL) { EnableWindow(false); return false; } m_nCount = 1; n = AddString(m_pTexture->m_sName); SetItemData(n, (ULONG)m_pTexture); EnableWindow(true); return true; } bool CTexListBox::SetTexturePointer(CTexture** pTexList, int nCount) { ResetContent(); m_pTexMru = NULL; m_pTexture = NULL; m_pTexList = pTexList; m_nCount = nCount; if((m_pTexList == NULL) || (m_nCount <= 0)) { EnableWindow(false); return false; } int n; for(int i = 0; i < nCount; i++) { n = AddString(m_pTexList[i]->m_sName); SetItemData(n, (ULONG)m_pTexList[i]); } EnableWindow(true); return true; } bool CTexListBox::SetTexturePointer(CLinkedList<TEXMRUREF>* pTexMru) { int n; int k = 0; TEXMRUREF* pRef; ResetContent(); m_pTexList = NULL; m_pTexture = NULL; m_pTexMru = pTexMru; if((m_pTexMru == NULL) || (m_pTexMru->IsEmpty())) { EnableWindow(false); return false; } m_pTexMru->First(); for(pRef = m_pTexMru->GetCurItem(); pRef != NULL; pRef = m_pTexMru->GetNextItem()) { n = AddString(pRef->sName); SetItemData(n, (ULONG)pRef->pTex); k++; } m_nCount = k; EnableWindow(true); return true; } void CTexListBox::Update() { int n; int k = 0; TEXMRUREF* pRef; ResetContent(); if(m_pTexture != NULL) { n = AddString(m_pTexture->m_sName); SetItemData(n, (ULONG)m_pTexture); EnableWindow(true); } else if(m_pTexList != NULL) { for(int i = 0; i < m_nCount; i++) { n = AddString(m_pTexList[i]->m_sName); SetItemData(n, (ULONG)m_pTexList[i]); } EnableWindow(true); } else if(m_pTexMru != NULL) { m_pTexMru->First(); for(pRef = m_pTexMru->GetCurItem(); pRef != NULL; pRef = m_pTexMru->GetNextItem()) { n = AddString(pRef->sName); SetItemData(n, (ULONG)pRef->pTex); k++; } m_nCount = k; EnableWindow(true); } else EnableWindow(false); } void CTexListBox::Update(CString sFilter) { int n; int k = 0; TEXMRUREF* pRef; ResetContent(); if(m_pTexture != NULL) { n = AddString(m_pTexture->m_sName); SetItemData(n, (ULONG)m_pTexture); EnableWindow(true); } else if(m_pTexList != NULL) { for(int i = 0; i < m_nCount; i++) { if(m_pTexList[i]->m_sName.Find(sFilter) != -1) { n = AddString((LPCTSTR)m_pTexList[i]); SetItemData(n, (ULONG)m_pTexList[i]); } } EnableWindow(true); } else if(m_pTexMru != NULL) { m_pTexMru->First(); for(pRef = m_pTexMru->GetCurItem(); pRef != NULL; pRef = m_pTexMru->GetNextItem()) { if(pRef->sName.Find(sFilter) != -1) { n = AddString((LPCTSTR)pRef->sName); SetItemData(n, (ULONG)pRef->pTex); k++; } } m_nCount = k; EnableWindow(true); } else EnableWindow(false); } BOOL CTexListBox::OnEraseBkgnd(CDC* pDC) { //CRect rcItem; //GetClientRect(&rcItem); pDC->FillSolidRect(&m_rcClient, RGB(0, 0, 0)); return true; } int CTexListBox::CompareItem(LPCOMPAREITEMSTRUCT lpCompareItemStruct) { // return -1 = item 1 sorts before item 2 // return 0 = item 1 and item 2 sort the same // return 1 = item 1 sorts after item 2 int i; CTexture* pTex1, *pTex2; pTex1 = (CTexture*)lpCompareItemStruct->itemData1; pTex2 = (CTexture*)lpCompareItemStruct->itemData2; if((pTex1 == NULL) || (pTex2 == NULL)) return -1; i = strcmp(pTex1->m_sName, pTex2->m_sName); (i < 0) ? i = -1 : (i > 0) ? i = 1 : i = 0; return i; } void CTexListBox::ResetList() { ResetContent(); } void CTexListBox::OnSize(UINT nType, int cx, int cy) { CListBox::OnSize(nType, cx, cy); // TODO: Add your message handler code here GetClientRect(&m_rcClient); } CTexture* CTexListBox::GetTexturePointer() { if(m_pTexture != NULL) return m_pTexture; if(m_pTexList != NULL) return m_pTexList[0]; if(m_pTexMru != NULL) { TEXMRUREF* pRef = m_pTexMru->GetCurItem(); if(pRef != NULL) return pRef->pTex; } return NULL; }
21.131991
84
0.654986
[ "object" ]
fddaa1b946461d5c312a1132231c5edad5bf238b
4,453
hh
C++
src/agents/pacman/rl/rl_pacman_agent.hh
albertsgrc/q-mspacman
8a697c3d16ac0b38d170bbcabfadef414befdee1
[ "MIT" ]
3
2019-01-07T10:15:21.000Z
2019-03-25T15:36:39.000Z
src/agents/pacman/rl/rl_pacman_agent.hh
albertsgrc/q-mspacman
8a697c3d16ac0b38d170bbcabfadef414befdee1
[ "MIT" ]
null
null
null
src/agents/pacman/rl/rl_pacman_agent.hh
albertsgrc/q-mspacman
8a697c3d16ac0b38d170bbcabfadef414befdee1
[ "MIT" ]
1
2019-05-26T07:48:21.000Z
2019-05-26T07:48:21.000Z
// // Created by Albert Segarra Roca on 18/12/16. // #ifndef RL_PACMAN_AGENT_HH #define RL_PACMAN_AGENT_HH #include <limits> #include <cassert> #include "../../agent.hh" #include "neural_network.hh" #include "../../../arguments.hh" #include "../../../pathfinding/bfs.hh" #include "rl_pacman_agent_inputs.hh" class RL_Pacman_Agent: public Agent { public: double mse_sum; double mse_sum_last; double reward; vector<double> previous_input; vector<double> input; vector<double> max_input; uint n_games; Neural_Network nn; RL_Pacman_Agent() : reward(0), n_games(1), nn(RL_Pacman_Agent_Inputs::n_inputs, Arguments::n_hidden_layers, Arguments::n_hidden_neurons, 1, Arguments::learning_rate, Arguments::activation_function) { previous_input = vector<double>(RL_Pacman_Agent_Inputs::n_inputs, 0.0); max_input = vector<double>(RL_Pacman_Agent_Inputs::n_inputs); input = vector<double>(RL_Pacman_Agent_Inputs::n_inputs); mse_sum_last = mse_sum = 0.0; } inline Direction take_action(const State& s, uint ghost_id) override { const Position& pos = s.pacman.pos; RL_Pacman_Agent_Inputs::set_input(); RL_Pacman_Agent_Inputs::compute_undirected(s, input); Direction best_dir; double max_q = numeric_limits<double>::lowest(); vector<char>& valid_dirs = PathMagic::dirs(pos); vector<Direction> valid_dirs_no_opposite; for (char i : valid_dirs) { const Direction& d = Direction::LIST[(int)i]; if (not d.isOpposite(s.pacman.dir)) valid_dirs_no_opposite.push_back(d); RL_Pacman_Agent_Inputs::compute_directed(d, s, input); if (Arguments::show_inputs) { cout << "Direction " << Direction::name(i) << ":" << endl; RL_Pacman_Agent_Inputs::debug(input); cout << endl; } double q = nn.recall(&input[0])[0]; if (q > max_q) { max_input = input; max_q = q; best_dir = d; } } double progression = double(n_games)/Arguments::plays; bool should_explore = Arguments::exploration_strategy == ANNEALING ? randdouble() >= clamp(progression, Arguments::exploration_annealing_min_progression, Arguments::exploration_annealing_max_progression) : (randdouble() < Arguments::exploration_epsilon and progression < Arguments::exploration_epsilon_stop_progression); Direction take; if (should_explore) { // epsilon-learning (prob. 0.1) is also really good! if (Arguments::smart_exploration) { if (s.pacman.pos != s.pacman.prev) { take = valid_dirs_no_opposite.size() > 0 ? valid_dirs_no_opposite[randint(valid_dirs_no_opposite.size())] : s.pacman.dir.opposite(); } else take = s.pacman.dir; } else take = Direction::LIST[(int)valid_dirs[randint(valid_dirs.size())]]; } else take = best_dir; // If the game ended previously there's no sense of future reward for the last move of the game // Note that the first train of all games is a bit sketchy (all inputs 0, reward 0) but doesn't matter // in the long term double expected[1] = { reward + (s.round > 1 ? Arguments::discount_factor*max_q : 0) }; double mse = nn.train(&previous_input[0], expected); mse_sum += mse; previous_input.swap(max_input); reward = Arguments::reward_step; return take; }; inline void notify_game_result(bool won) override { reward += won ? Arguments::reward_win : Arguments::reward_lose; ++n_games; mse_sum_last = mse_sum; mse_sum = 0.0; }; inline void notify_eaten_pill() override { reward += Arguments::reward_pill; }; inline void notify_eaten_powerpill() override { reward += Arguments::reward_powerpill; } inline void notify_killed_ghost() override { reward += Arguments::reward_kill_ghost; } inline void notify_reverse_direction() override { reward += Arguments::reward_reverse; } }; #endif //RL_PACMAN_AGENT_HH
35.062992
178
0.606108
[ "vector" ]
fddee33adfd2847b1f7c8cbb4c70068944937a45
164,119
cpp
C++
Side Scrolling Platformer/Test/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_30Table.cpp
sarahCarroll/MobileAppDev3
1da94bc8b552baa781286638f156aabac143b3bd
[ "Apache-2.0" ]
1
2018-12-18T17:07:37.000Z
2018-12-18T17:07:37.000Z
Side Scrolling Platformer/Test/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_30Table.cpp
sarahCarroll/MobileAppDev3
1da94bc8b552baa781286638f156aabac143b3bd
[ "Apache-2.0" ]
null
null
null
Side Scrolling Platformer/Test/Il2CppOutputProject/Source/il2cppOutput/Il2CppCompilerCalculateTypeValues_30Table.cpp
sarahCarroll/MobileAppDev3
1da94bc8b552baa781286638f156aabac143b3bd
[ "Apache-2.0" ]
null
null
null
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "il2cpp-class-internals.h" #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" // System.Action struct Action_t1264377477; // System.Action`1<UnityEngine.AsyncOperation> struct Action_1_t1617499438; // System.AsyncCallback struct AsyncCallback_t3962456242; // System.Char[] struct CharU5BU5D_t3528271667; // System.Collections.Generic.IEnumerable`1<System.String> struct IEnumerable_1_t827303578; // System.Collections.Generic.List`1<UnityEngine.BeforeRenderHelper/OrderBlock> struct List_1_t3058052573; // System.DelegateData struct DelegateData_t1677132599; // System.Delegate[] struct DelegateU5BU5D_t1703627840; // System.Func`1<System.Boolean> struct Func_1_t3822001908; // System.IAsyncResult struct IAsyncResult_t767004451; // System.Reflection.MethodInfo struct MethodInfo_t; // System.String struct String_t; // System.Type struct Type_t; // System.Void struct Void_t1185182177; // UnityEngine.Application/LogCallback struct LogCallback_t3588208630; // UnityEngine.Application/LowMemoryCallback struct LowMemoryCallback_t4104246196; // UnityEngine.Camera struct Camera_t4157153871; // UnityEngine.Camera/CameraCallback struct CameraCallback_t190067161; // UnityEngine.CullingGroup/StateChanged struct StateChanged_t2136737110; // UnityEngine.DisallowMultipleComponent[] struct DisallowMultipleComponentU5BU5D_t3936143868; // UnityEngine.Events.UnityAction struct UnityAction_t3245792599; // UnityEngine.ExecuteInEditMode[] struct ExecuteInEditModeU5BU5D_t3239458680; // UnityEngine.Gyroscope struct Gyroscope_t3288342876; // UnityEngine.RequireComponent[] struct RequireComponentU5BU5D_t2245623724; #ifndef U3CMODULEU3E_T692745531_H #define U3CMODULEU3E_T692745531_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t692745531 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T692745531_H #ifndef U3CMODULEU3E_T692745532_H #define U3CMODULEU3E_T692745532_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t692745532 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T692745532_H #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H #ifndef ATTRIBUTE_T861562559_H #define ATTRIBUTE_T861562559_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Attribute struct Attribute_t861562559 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTE_T861562559_H #ifndef UTILITIES_T3288484762_H #define UTILITIES_T3288484762_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Linq.Utilities struct Utilities_t3288484762 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UTILITIES_T3288484762_H #ifndef VALUETYPE_T3640485471_H #define VALUETYPE_T3640485471_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t3640485471 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t3640485471_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t3640485471_marshaled_com { }; #endif // VALUETYPE_T3640485471_H #ifndef APPLICATION_T1852185770_H #define APPLICATION_T1852185770_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Application struct Application_t1852185770 : public RuntimeObject { public: public: }; struct Application_t1852185770_StaticFields { public: // UnityEngine.Application/LowMemoryCallback UnityEngine.Application::lowMemory LowMemoryCallback_t4104246196 * ___lowMemory_0; // UnityEngine.Application/LogCallback UnityEngine.Application::s_LogCallbackHandler LogCallback_t3588208630 * ___s_LogCallbackHandler_1; // UnityEngine.Application/LogCallback UnityEngine.Application::s_LogCallbackHandlerThreaded LogCallback_t3588208630 * ___s_LogCallbackHandlerThreaded_2; // System.Func`1<System.Boolean> UnityEngine.Application::wantsToQuit Func_1_t3822001908 * ___wantsToQuit_3; // System.Action UnityEngine.Application::quitting Action_t1264377477 * ___quitting_4; public: inline static int32_t get_offset_of_lowMemory_0() { return static_cast<int32_t>(offsetof(Application_t1852185770_StaticFields, ___lowMemory_0)); } inline LowMemoryCallback_t4104246196 * get_lowMemory_0() const { return ___lowMemory_0; } inline LowMemoryCallback_t4104246196 ** get_address_of_lowMemory_0() { return &___lowMemory_0; } inline void set_lowMemory_0(LowMemoryCallback_t4104246196 * value) { ___lowMemory_0 = value; Il2CppCodeGenWriteBarrier((&___lowMemory_0), value); } inline static int32_t get_offset_of_s_LogCallbackHandler_1() { return static_cast<int32_t>(offsetof(Application_t1852185770_StaticFields, ___s_LogCallbackHandler_1)); } inline LogCallback_t3588208630 * get_s_LogCallbackHandler_1() const { return ___s_LogCallbackHandler_1; } inline LogCallback_t3588208630 ** get_address_of_s_LogCallbackHandler_1() { return &___s_LogCallbackHandler_1; } inline void set_s_LogCallbackHandler_1(LogCallback_t3588208630 * value) { ___s_LogCallbackHandler_1 = value; Il2CppCodeGenWriteBarrier((&___s_LogCallbackHandler_1), value); } inline static int32_t get_offset_of_s_LogCallbackHandlerThreaded_2() { return static_cast<int32_t>(offsetof(Application_t1852185770_StaticFields, ___s_LogCallbackHandlerThreaded_2)); } inline LogCallback_t3588208630 * get_s_LogCallbackHandlerThreaded_2() const { return ___s_LogCallbackHandlerThreaded_2; } inline LogCallback_t3588208630 ** get_address_of_s_LogCallbackHandlerThreaded_2() { return &___s_LogCallbackHandlerThreaded_2; } inline void set_s_LogCallbackHandlerThreaded_2(LogCallback_t3588208630 * value) { ___s_LogCallbackHandlerThreaded_2 = value; Il2CppCodeGenWriteBarrier((&___s_LogCallbackHandlerThreaded_2), value); } inline static int32_t get_offset_of_wantsToQuit_3() { return static_cast<int32_t>(offsetof(Application_t1852185770_StaticFields, ___wantsToQuit_3)); } inline Func_1_t3822001908 * get_wantsToQuit_3() const { return ___wantsToQuit_3; } inline Func_1_t3822001908 ** get_address_of_wantsToQuit_3() { return &___wantsToQuit_3; } inline void set_wantsToQuit_3(Func_1_t3822001908 * value) { ___wantsToQuit_3 = value; Il2CppCodeGenWriteBarrier((&___wantsToQuit_3), value); } inline static int32_t get_offset_of_quitting_4() { return static_cast<int32_t>(offsetof(Application_t1852185770_StaticFields, ___quitting_4)); } inline Action_t1264377477 * get_quitting_4() const { return ___quitting_4; } inline Action_t1264377477 ** get_address_of_quitting_4() { return &___quitting_4; } inline void set_quitting_4(Action_t1264377477 * value) { ___quitting_4 = value; Il2CppCodeGenWriteBarrier((&___quitting_4), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // APPLICATION_T1852185770_H #ifndef ATTRIBUTEHELPERENGINE_T2735742303_H #define ATTRIBUTEHELPERENGINE_T2735742303_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AttributeHelperEngine struct AttributeHelperEngine_t2735742303 : public RuntimeObject { public: public: }; struct AttributeHelperEngine_t2735742303_StaticFields { public: // UnityEngine.DisallowMultipleComponent[] UnityEngine.AttributeHelperEngine::_disallowMultipleComponentArray DisallowMultipleComponentU5BU5D_t3936143868* ____disallowMultipleComponentArray_0; // UnityEngine.ExecuteInEditMode[] UnityEngine.AttributeHelperEngine::_executeInEditModeArray ExecuteInEditModeU5BU5D_t3239458680* ____executeInEditModeArray_1; // UnityEngine.RequireComponent[] UnityEngine.AttributeHelperEngine::_requireComponentArray RequireComponentU5BU5D_t2245623724* ____requireComponentArray_2; public: inline static int32_t get_offset_of__disallowMultipleComponentArray_0() { return static_cast<int32_t>(offsetof(AttributeHelperEngine_t2735742303_StaticFields, ____disallowMultipleComponentArray_0)); } inline DisallowMultipleComponentU5BU5D_t3936143868* get__disallowMultipleComponentArray_0() const { return ____disallowMultipleComponentArray_0; } inline DisallowMultipleComponentU5BU5D_t3936143868** get_address_of__disallowMultipleComponentArray_0() { return &____disallowMultipleComponentArray_0; } inline void set__disallowMultipleComponentArray_0(DisallowMultipleComponentU5BU5D_t3936143868* value) { ____disallowMultipleComponentArray_0 = value; Il2CppCodeGenWriteBarrier((&____disallowMultipleComponentArray_0), value); } inline static int32_t get_offset_of__executeInEditModeArray_1() { return static_cast<int32_t>(offsetof(AttributeHelperEngine_t2735742303_StaticFields, ____executeInEditModeArray_1)); } inline ExecuteInEditModeU5BU5D_t3239458680* get__executeInEditModeArray_1() const { return ____executeInEditModeArray_1; } inline ExecuteInEditModeU5BU5D_t3239458680** get_address_of__executeInEditModeArray_1() { return &____executeInEditModeArray_1; } inline void set__executeInEditModeArray_1(ExecuteInEditModeU5BU5D_t3239458680* value) { ____executeInEditModeArray_1 = value; Il2CppCodeGenWriteBarrier((&____executeInEditModeArray_1), value); } inline static int32_t get_offset_of__requireComponentArray_2() { return static_cast<int32_t>(offsetof(AttributeHelperEngine_t2735742303_StaticFields, ____requireComponentArray_2)); } inline RequireComponentU5BU5D_t2245623724* get__requireComponentArray_2() const { return ____requireComponentArray_2; } inline RequireComponentU5BU5D_t2245623724** get_address_of__requireComponentArray_2() { return &____requireComponentArray_2; } inline void set__requireComponentArray_2(RequireComponentU5BU5D_t2245623724* value) { ____requireComponentArray_2 = value; Il2CppCodeGenWriteBarrier((&____requireComponentArray_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTEHELPERENGINE_T2735742303_H #ifndef BEFORERENDERHELPER_T1336903776_H #define BEFORERENDERHELPER_T1336903776_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.BeforeRenderHelper struct BeforeRenderHelper_t1336903776 : public RuntimeObject { public: public: }; struct BeforeRenderHelper_t1336903776_StaticFields { public: // System.Collections.Generic.List`1<UnityEngine.BeforeRenderHelper/OrderBlock> UnityEngine.BeforeRenderHelper::s_OrderBlocks List_1_t3058052573 * ___s_OrderBlocks_0; public: inline static int32_t get_offset_of_s_OrderBlocks_0() { return static_cast<int32_t>(offsetof(BeforeRenderHelper_t1336903776_StaticFields, ___s_OrderBlocks_0)); } inline List_1_t3058052573 * get_s_OrderBlocks_0() const { return ___s_OrderBlocks_0; } inline List_1_t3058052573 ** get_address_of_s_OrderBlocks_0() { return &___s_OrderBlocks_0; } inline void set_s_OrderBlocks_0(List_1_t3058052573 * value) { ___s_OrderBlocks_0 = value; Il2CppCodeGenWriteBarrier((&___s_OrderBlocks_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BEFORERENDERHELPER_T1336903776_H #ifndef CLASSLIBRARYINITIALIZER_T2339504045_H #define CLASSLIBRARYINITIALIZER_T2339504045_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ClassLibraryInitializer struct ClassLibraryInitializer_t2339504045 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CLASSLIBRARYINITIALIZER_T2339504045_H #ifndef GYROSCOPE_T3288342876_H #define GYROSCOPE_T3288342876_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Gyroscope struct Gyroscope_t3288342876 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GYROSCOPE_T3288342876_H #ifndef INPUT_T1431474628_H #define INPUT_T1431474628_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Input struct Input_t1431474628 : public RuntimeObject { public: public: }; struct Input_t1431474628_StaticFields { public: // UnityEngine.Gyroscope UnityEngine.Input::m_MainGyro Gyroscope_t3288342876 * ___m_MainGyro_0; public: inline static int32_t get_offset_of_m_MainGyro_0() { return static_cast<int32_t>(offsetof(Input_t1431474628_StaticFields, ___m_MainGyro_0)); } inline Gyroscope_t3288342876 * get_m_MainGyro_0() const { return ___m_MainGyro_0; } inline Gyroscope_t3288342876 ** get_address_of_m_MainGyro_0() { return &___m_MainGyro_0; } inline void set_m_MainGyro_0(Gyroscope_t3288342876 * value) { ___m_MainGyro_0 = value; Il2CppCodeGenWriteBarrier((&___m_MainGyro_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INPUT_T1431474628_H #ifndef NOALLOCHELPERS_T1437076930_H #define NOALLOCHELPERS_T1437076930_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.NoAllocHelpers struct NoAllocHelpers_t1437076930 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NOALLOCHELPERS_T1437076930_H #ifndef PLAYERCONNECTIONINTERNAL_T3892293164_H #define PLAYERCONNECTIONINTERNAL_T3892293164_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.PlayerConnectionInternal struct PlayerConnectionInternal_t3892293164 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PLAYERCONNECTIONINTERNAL_T3892293164_H #ifndef SETUPCOROUTINE_T2062820429_H #define SETUPCOROUTINE_T2062820429_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SetupCoroutine struct SetupCoroutine_t2062820429 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SETUPCOROUTINE_T2062820429_H #ifndef UNITYSTRING_T1423233093_H #define UNITYSTRING_T1423233093_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.UnityString struct UnityString_t1423233093 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYSTRING_T1423233093_H #ifndef YIELDINSTRUCTION_T403091072_H #define YIELDINSTRUCTION_T403091072_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.YieldInstruction struct YieldInstruction_t403091072 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.YieldInstruction struct YieldInstruction_t403091072_marshaled_pinvoke { }; // Native definition for COM marshalling of UnityEngine.YieldInstruction struct YieldInstruction_t403091072_marshaled_com { }; #endif // YIELDINSTRUCTION_T403091072_H #ifndef __STATICARRAYINITTYPESIZEU3D1024_T4211899788_H #define __STATICARRAYINITTYPESIZEU3D1024_T4211899788_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 struct __StaticArrayInitTypeSizeU3D1024_t4211899788 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D1024_t4211899788__padding[1024]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D1024_T4211899788_H #ifndef __STATICARRAYINITTYPESIZEU3D120_T3297148302_H #define __STATICARRAYINITTYPESIZEU3D120_T3297148302_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=120 struct __StaticArrayInitTypeSizeU3D120_t3297148302 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D120_t3297148302__padding[120]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D120_T3297148302_H #ifndef __STATICARRAYINITTYPESIZEU3D256_T1757367634_H #define __STATICARRAYINITTYPESIZEU3D256_T1757367634_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=256 struct __StaticArrayInitTypeSizeU3D256_t1757367634 { public: union { struct { union { }; }; uint8_t __StaticArrayInitTypeSizeU3D256_t1757367634__padding[256]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // __STATICARRAYINITTYPESIZEU3D256_T1757367634_H #ifndef ENUM_T4135868527_H #define ENUM_T4135868527_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t4135868527 : public ValueType_t3640485471 { public: public: }; struct Enum_t4135868527_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t3528271667* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t3528271667* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t3528271667** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t3528271667* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t4135868527_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t4135868527_marshaled_com { }; #endif // ENUM_T4135868527_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef VOID_T1185182177_H #define VOID_T1185182177_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t1185182177 { public: union { struct { }; uint8_t Void_t1185182177__padding[1]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1185182177_H #ifndef ADDCOMPONENTMENU_T415040132_H #define ADDCOMPONENTMENU_T415040132_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AddComponentMenu struct AddComponentMenu_t415040132 : public Attribute_t861562559 { public: // System.String UnityEngine.AddComponentMenu::m_AddComponentMenu String_t* ___m_AddComponentMenu_0; // System.Int32 UnityEngine.AddComponentMenu::m_Ordering int32_t ___m_Ordering_1; public: inline static int32_t get_offset_of_m_AddComponentMenu_0() { return static_cast<int32_t>(offsetof(AddComponentMenu_t415040132, ___m_AddComponentMenu_0)); } inline String_t* get_m_AddComponentMenu_0() const { return ___m_AddComponentMenu_0; } inline String_t** get_address_of_m_AddComponentMenu_0() { return &___m_AddComponentMenu_0; } inline void set_m_AddComponentMenu_0(String_t* value) { ___m_AddComponentMenu_0 = value; Il2CppCodeGenWriteBarrier((&___m_AddComponentMenu_0), value); } inline static int32_t get_offset_of_m_Ordering_1() { return static_cast<int32_t>(offsetof(AddComponentMenu_t415040132, ___m_Ordering_1)); } inline int32_t get_m_Ordering_1() const { return ___m_Ordering_1; } inline int32_t* get_address_of_m_Ordering_1() { return &___m_Ordering_1; } inline void set_m_Ordering_1(int32_t value) { ___m_Ordering_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ADDCOMPONENTMENU_T415040132_H #ifndef ASSEMBLYISEDITORASSEMBLY_T3442416807_H #define ASSEMBLYISEDITORASSEMBLY_T3442416807_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AssemblyIsEditorAssembly struct AssemblyIsEditorAssembly_t3442416807 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASSEMBLYISEDITORASSEMBLY_T3442416807_H #ifndef ASSETFILENAMEEXTENSIONATTRIBUTE_T1361241164_H #define ASSETFILENAMEEXTENSIONATTRIBUTE_T1361241164_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AssetFileNameExtensionAttribute struct AssetFileNameExtensionAttribute_t1361241164 : public Attribute_t861562559 { public: // System.String UnityEngine.AssetFileNameExtensionAttribute::<preferredExtension>k__BackingField String_t* ___U3CpreferredExtensionU3Ek__BackingField_0; // System.Collections.Generic.IEnumerable`1<System.String> UnityEngine.AssetFileNameExtensionAttribute::<otherExtensions>k__BackingField RuntimeObject* ___U3CotherExtensionsU3Ek__BackingField_1; public: inline static int32_t get_offset_of_U3CpreferredExtensionU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(AssetFileNameExtensionAttribute_t1361241164, ___U3CpreferredExtensionU3Ek__BackingField_0)); } inline String_t* get_U3CpreferredExtensionU3Ek__BackingField_0() const { return ___U3CpreferredExtensionU3Ek__BackingField_0; } inline String_t** get_address_of_U3CpreferredExtensionU3Ek__BackingField_0() { return &___U3CpreferredExtensionU3Ek__BackingField_0; } inline void set_U3CpreferredExtensionU3Ek__BackingField_0(String_t* value) { ___U3CpreferredExtensionU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CpreferredExtensionU3Ek__BackingField_0), value); } inline static int32_t get_offset_of_U3CotherExtensionsU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(AssetFileNameExtensionAttribute_t1361241164, ___U3CotherExtensionsU3Ek__BackingField_1)); } inline RuntimeObject* get_U3CotherExtensionsU3Ek__BackingField_1() const { return ___U3CotherExtensionsU3Ek__BackingField_1; } inline RuntimeObject** get_address_of_U3CotherExtensionsU3Ek__BackingField_1() { return &___U3CotherExtensionsU3Ek__BackingField_1; } inline void set_U3CotherExtensionsU3Ek__BackingField_1(RuntimeObject* value) { ___U3CotherExtensionsU3Ek__BackingField_1 = value; Il2CppCodeGenWriteBarrier((&___U3CotherExtensionsU3Ek__BackingField_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ASSETFILENAMEEXTENSIONATTRIBUTE_T1361241164_H #ifndef ORDERBLOCK_T1585977831_H #define ORDERBLOCK_T1585977831_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.BeforeRenderHelper/OrderBlock struct OrderBlock_t1585977831 { public: // System.Int32 UnityEngine.BeforeRenderHelper/OrderBlock::order int32_t ___order_0; // UnityEngine.Events.UnityAction UnityEngine.BeforeRenderHelper/OrderBlock::callback UnityAction_t3245792599 * ___callback_1; public: inline static int32_t get_offset_of_order_0() { return static_cast<int32_t>(offsetof(OrderBlock_t1585977831, ___order_0)); } inline int32_t get_order_0() const { return ___order_0; } inline int32_t* get_address_of_order_0() { return &___order_0; } inline void set_order_0(int32_t value) { ___order_0 = value; } inline static int32_t get_offset_of_callback_1() { return static_cast<int32_t>(offsetof(OrderBlock_t1585977831, ___callback_1)); } inline UnityAction_t3245792599 * get_callback_1() const { return ___callback_1; } inline UnityAction_t3245792599 ** get_address_of_callback_1() { return &___callback_1; } inline void set_callback_1(UnityAction_t3245792599 * value) { ___callback_1 = value; Il2CppCodeGenWriteBarrier((&___callback_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.BeforeRenderHelper/OrderBlock struct OrderBlock_t1585977831_marshaled_pinvoke { int32_t ___order_0; Il2CppMethodPointer ___callback_1; }; // Native definition for COM marshalling of UnityEngine.BeforeRenderHelper/OrderBlock struct OrderBlock_t1585977831_marshaled_com { int32_t ___order_0; Il2CppMethodPointer ___callback_1; }; #endif // ORDERBLOCK_T1585977831_H #ifndef IGNOREATTRIBUTE_T1982719709_H #define IGNOREATTRIBUTE_T1982719709_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.IgnoreAttribute struct IgnoreAttribute_t1982719709 : public Attribute_t861562559 { public: // System.Boolean UnityEngine.Bindings.IgnoreAttribute::<DoesNotContributeToSize>k__BackingField bool ___U3CDoesNotContributeToSizeU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CDoesNotContributeToSizeU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(IgnoreAttribute_t1982719709, ___U3CDoesNotContributeToSizeU3Ek__BackingField_0)); } inline bool get_U3CDoesNotContributeToSizeU3Ek__BackingField_0() const { return ___U3CDoesNotContributeToSizeU3Ek__BackingField_0; } inline bool* get_address_of_U3CDoesNotContributeToSizeU3Ek__BackingField_0() { return &___U3CDoesNotContributeToSizeU3Ek__BackingField_0; } inline void set_U3CDoesNotContributeToSizeU3Ek__BackingField_0(bool value) { ___U3CDoesNotContributeToSizeU3Ek__BackingField_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // IGNOREATTRIBUTE_T1982719709_H #ifndef NATIVECONDITIONALATTRIBUTE_T2439539374_H #define NATIVECONDITIONALATTRIBUTE_T2439539374_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NativeConditionalAttribute struct NativeConditionalAttribute_t2439539374 : public Attribute_t861562559 { public: // System.String UnityEngine.Bindings.NativeConditionalAttribute::<Condition>k__BackingField String_t* ___U3CConditionU3Ek__BackingField_0; // System.Boolean UnityEngine.Bindings.NativeConditionalAttribute::<Enabled>k__BackingField bool ___U3CEnabledU3Ek__BackingField_1; public: inline static int32_t get_offset_of_U3CConditionU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeConditionalAttribute_t2439539374, ___U3CConditionU3Ek__BackingField_0)); } inline String_t* get_U3CConditionU3Ek__BackingField_0() const { return ___U3CConditionU3Ek__BackingField_0; } inline String_t** get_address_of_U3CConditionU3Ek__BackingField_0() { return &___U3CConditionU3Ek__BackingField_0; } inline void set_U3CConditionU3Ek__BackingField_0(String_t* value) { ___U3CConditionU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CConditionU3Ek__BackingField_0), value); } inline static int32_t get_offset_of_U3CEnabledU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(NativeConditionalAttribute_t2439539374, ___U3CEnabledU3Ek__BackingField_1)); } inline bool get_U3CEnabledU3Ek__BackingField_1() const { return ___U3CEnabledU3Ek__BackingField_1; } inline bool* get_address_of_U3CEnabledU3Ek__BackingField_1() { return &___U3CEnabledU3Ek__BackingField_1; } inline void set_U3CEnabledU3Ek__BackingField_1(bool value) { ___U3CEnabledU3Ek__BackingField_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVECONDITIONALATTRIBUTE_T2439539374_H #ifndef NATIVEHEADERATTRIBUTE_T5261382_H #define NATIVEHEADERATTRIBUTE_T5261382_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NativeHeaderAttribute struct NativeHeaderAttribute_t5261382 : public Attribute_t861562559 { public: // System.String UnityEngine.Bindings.NativeHeaderAttribute::<Header>k__BackingField String_t* ___U3CHeaderU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CHeaderU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeHeaderAttribute_t5261382, ___U3CHeaderU3Ek__BackingField_0)); } inline String_t* get_U3CHeaderU3Ek__BackingField_0() const { return ___U3CHeaderU3Ek__BackingField_0; } inline String_t** get_address_of_U3CHeaderU3Ek__BackingField_0() { return &___U3CHeaderU3Ek__BackingField_0; } inline void set_U3CHeaderU3Ek__BackingField_0(String_t* value) { ___U3CHeaderU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CHeaderU3Ek__BackingField_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVEHEADERATTRIBUTE_T5261382_H #ifndef NATIVEMETHODATTRIBUTE_T4187428193_H #define NATIVEMETHODATTRIBUTE_T4187428193_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NativeMethodAttribute struct NativeMethodAttribute_t4187428193 : public Attribute_t861562559 { public: // System.String UnityEngine.Bindings.NativeMethodAttribute::<Name>k__BackingField String_t* ___U3CNameU3Ek__BackingField_0; // System.Boolean UnityEngine.Bindings.NativeMethodAttribute::<IsThreadSafe>k__BackingField bool ___U3CIsThreadSafeU3Ek__BackingField_1; // System.Boolean UnityEngine.Bindings.NativeMethodAttribute::<IsFreeFunction>k__BackingField bool ___U3CIsFreeFunctionU3Ek__BackingField_2; // System.Boolean UnityEngine.Bindings.NativeMethodAttribute::<ThrowsException>k__BackingField bool ___U3CThrowsExceptionU3Ek__BackingField_3; // System.Boolean UnityEngine.Bindings.NativeMethodAttribute::<HasExplicitThis>k__BackingField bool ___U3CHasExplicitThisU3Ek__BackingField_4; public: inline static int32_t get_offset_of_U3CNameU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeMethodAttribute_t4187428193, ___U3CNameU3Ek__BackingField_0)); } inline String_t* get_U3CNameU3Ek__BackingField_0() const { return ___U3CNameU3Ek__BackingField_0; } inline String_t** get_address_of_U3CNameU3Ek__BackingField_0() { return &___U3CNameU3Ek__BackingField_0; } inline void set_U3CNameU3Ek__BackingField_0(String_t* value) { ___U3CNameU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CNameU3Ek__BackingField_0), value); } inline static int32_t get_offset_of_U3CIsThreadSafeU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(NativeMethodAttribute_t4187428193, ___U3CIsThreadSafeU3Ek__BackingField_1)); } inline bool get_U3CIsThreadSafeU3Ek__BackingField_1() const { return ___U3CIsThreadSafeU3Ek__BackingField_1; } inline bool* get_address_of_U3CIsThreadSafeU3Ek__BackingField_1() { return &___U3CIsThreadSafeU3Ek__BackingField_1; } inline void set_U3CIsThreadSafeU3Ek__BackingField_1(bool value) { ___U3CIsThreadSafeU3Ek__BackingField_1 = value; } inline static int32_t get_offset_of_U3CIsFreeFunctionU3Ek__BackingField_2() { return static_cast<int32_t>(offsetof(NativeMethodAttribute_t4187428193, ___U3CIsFreeFunctionU3Ek__BackingField_2)); } inline bool get_U3CIsFreeFunctionU3Ek__BackingField_2() const { return ___U3CIsFreeFunctionU3Ek__BackingField_2; } inline bool* get_address_of_U3CIsFreeFunctionU3Ek__BackingField_2() { return &___U3CIsFreeFunctionU3Ek__BackingField_2; } inline void set_U3CIsFreeFunctionU3Ek__BackingField_2(bool value) { ___U3CIsFreeFunctionU3Ek__BackingField_2 = value; } inline static int32_t get_offset_of_U3CThrowsExceptionU3Ek__BackingField_3() { return static_cast<int32_t>(offsetof(NativeMethodAttribute_t4187428193, ___U3CThrowsExceptionU3Ek__BackingField_3)); } inline bool get_U3CThrowsExceptionU3Ek__BackingField_3() const { return ___U3CThrowsExceptionU3Ek__BackingField_3; } inline bool* get_address_of_U3CThrowsExceptionU3Ek__BackingField_3() { return &___U3CThrowsExceptionU3Ek__BackingField_3; } inline void set_U3CThrowsExceptionU3Ek__BackingField_3(bool value) { ___U3CThrowsExceptionU3Ek__BackingField_3 = value; } inline static int32_t get_offset_of_U3CHasExplicitThisU3Ek__BackingField_4() { return static_cast<int32_t>(offsetof(NativeMethodAttribute_t4187428193, ___U3CHasExplicitThisU3Ek__BackingField_4)); } inline bool get_U3CHasExplicitThisU3Ek__BackingField_4() const { return ___U3CHasExplicitThisU3Ek__BackingField_4; } inline bool* get_address_of_U3CHasExplicitThisU3Ek__BackingField_4() { return &___U3CHasExplicitThisU3Ek__BackingField_4; } inline void set_U3CHasExplicitThisU3Ek__BackingField_4(bool value) { ___U3CHasExplicitThisU3Ek__BackingField_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVEMETHODATTRIBUTE_T4187428193_H #ifndef NATIVENAMEATTRIBUTE_T3268151526_H #define NATIVENAMEATTRIBUTE_T3268151526_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NativeNameAttribute struct NativeNameAttribute_t3268151526 : public Attribute_t861562559 { public: // System.String UnityEngine.Bindings.NativeNameAttribute::<Name>k__BackingField String_t* ___U3CNameU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CNameU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeNameAttribute_t3268151526, ___U3CNameU3Ek__BackingField_0)); } inline String_t* get_U3CNameU3Ek__BackingField_0() const { return ___U3CNameU3Ek__BackingField_0; } inline String_t** get_address_of_U3CNameU3Ek__BackingField_0() { return &___U3CNameU3Ek__BackingField_0; } inline void set_U3CNameU3Ek__BackingField_0(String_t* value) { ___U3CNameU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CNameU3Ek__BackingField_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVENAMEATTRIBUTE_T3268151526_H #ifndef NATIVETHROWSATTRIBUTE_T1697526064_H #define NATIVETHROWSATTRIBUTE_T1697526064_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NativeThrowsAttribute struct NativeThrowsAttribute_t1697526064 : public Attribute_t861562559 { public: // System.Boolean UnityEngine.Bindings.NativeThrowsAttribute::<ThrowsException>k__BackingField bool ___U3CThrowsExceptionU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CThrowsExceptionU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeThrowsAttribute_t1697526064, ___U3CThrowsExceptionU3Ek__BackingField_0)); } inline bool get_U3CThrowsExceptionU3Ek__BackingField_0() const { return ___U3CThrowsExceptionU3Ek__BackingField_0; } inline bool* get_address_of_U3CThrowsExceptionU3Ek__BackingField_0() { return &___U3CThrowsExceptionU3Ek__BackingField_0; } inline void set_U3CThrowsExceptionU3Ek__BackingField_0(bool value) { ___U3CThrowsExceptionU3Ek__BackingField_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVETHROWSATTRIBUTE_T1697526064_H #ifndef NATIVEWRITABLESELFATTRIBUTE_T3843992162_H #define NATIVEWRITABLESELFATTRIBUTE_T3843992162_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NativeWritableSelfAttribute struct NativeWritableSelfAttribute_t3843992162 : public Attribute_t861562559 { public: // System.Boolean UnityEngine.Bindings.NativeWritableSelfAttribute::<WritableSelf>k__BackingField bool ___U3CWritableSelfU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CWritableSelfU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeWritableSelfAttribute_t3843992162, ___U3CWritableSelfU3Ek__BackingField_0)); } inline bool get_U3CWritableSelfU3Ek__BackingField_0() const { return ___U3CWritableSelfU3Ek__BackingField_0; } inline bool* get_address_of_U3CWritableSelfU3Ek__BackingField_0() { return &___U3CWritableSelfU3Ek__BackingField_0; } inline void set_U3CWritableSelfU3Ek__BackingField_0(bool value) { ___U3CWritableSelfU3Ek__BackingField_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVEWRITABLESELFATTRIBUTE_T3843992162_H #ifndef NOTNULLATTRIBUTE_T1114947401_H #define NOTNULLATTRIBUTE_T1114947401_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NotNullAttribute struct NotNullAttribute_t1114947401 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NOTNULLATTRIBUTE_T1114947401_H #ifndef UNMARSHALLEDATTRIBUTE_T1517743549_H #define UNMARSHALLEDATTRIBUTE_T1517743549_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.UnmarshalledAttribute struct UnmarshalledAttribute_t1517743549 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNMARSHALLEDATTRIBUTE_T1517743549_H #ifndef VISIBLETOOTHERMODULESATTRIBUTE_T1429630568_H #define VISIBLETOOTHERMODULESATTRIBUTE_T1429630568_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.VisibleToOtherModulesAttribute struct VisibleToOtherModulesAttribute_t1429630568 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VISIBLETOOTHERMODULESATTRIBUTE_T1429630568_H #ifndef COLOR_T2555686324_H #define COLOR_T2555686324_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Color struct Color_t2555686324 { public: // System.Single UnityEngine.Color::r float ___r_0; // System.Single UnityEngine.Color::g float ___g_1; // System.Single UnityEngine.Color::b float ___b_2; // System.Single UnityEngine.Color::a float ___a_3; public: inline static int32_t get_offset_of_r_0() { return static_cast<int32_t>(offsetof(Color_t2555686324, ___r_0)); } inline float get_r_0() const { return ___r_0; } inline float* get_address_of_r_0() { return &___r_0; } inline void set_r_0(float value) { ___r_0 = value; } inline static int32_t get_offset_of_g_1() { return static_cast<int32_t>(offsetof(Color_t2555686324, ___g_1)); } inline float get_g_1() const { return ___g_1; } inline float* get_address_of_g_1() { return &___g_1; } inline void set_g_1(float value) { ___g_1 = value; } inline static int32_t get_offset_of_b_2() { return static_cast<int32_t>(offsetof(Color_t2555686324, ___b_2)); } inline float get_b_2() const { return ___b_2; } inline float* get_address_of_b_2() { return &___b_2; } inline void set_b_2(float value) { ___b_2 = value; } inline static int32_t get_offset_of_a_3() { return static_cast<int32_t>(offsetof(Color_t2555686324, ___a_3)); } inline float get_a_3() const { return ___a_3; } inline float* get_address_of_a_3() { return &___a_3; } inline void set_a_3(float value) { ___a_3 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COLOR_T2555686324_H #ifndef COLOR32_T2600501292_H #define COLOR32_T2600501292_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Color32 struct Color32_t2600501292 { public: union { #pragma pack(push, tp, 1) struct { // System.Int32 UnityEngine.Color32::rgba int32_t ___rgba_0; }; #pragma pack(pop, tp) struct { int32_t ___rgba_0_forAlignmentOnly; }; #pragma pack(push, tp, 1) struct { // System.Byte UnityEngine.Color32::r uint8_t ___r_1; }; #pragma pack(pop, tp) struct { uint8_t ___r_1_forAlignmentOnly; }; #pragma pack(push, tp, 1) struct { char ___g_2_OffsetPadding[1]; // System.Byte UnityEngine.Color32::g uint8_t ___g_2; }; #pragma pack(pop, tp) struct { char ___g_2_OffsetPadding_forAlignmentOnly[1]; uint8_t ___g_2_forAlignmentOnly; }; #pragma pack(push, tp, 1) struct { char ___b_3_OffsetPadding[2]; // System.Byte UnityEngine.Color32::b uint8_t ___b_3; }; #pragma pack(pop, tp) struct { char ___b_3_OffsetPadding_forAlignmentOnly[2]; uint8_t ___b_3_forAlignmentOnly; }; #pragma pack(push, tp, 1) struct { char ___a_4_OffsetPadding[3]; // System.Byte UnityEngine.Color32::a uint8_t ___a_4; }; #pragma pack(pop, tp) struct { char ___a_4_OffsetPadding_forAlignmentOnly[3]; uint8_t ___a_4_forAlignmentOnly; }; }; public: inline static int32_t get_offset_of_rgba_0() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___rgba_0)); } inline int32_t get_rgba_0() const { return ___rgba_0; } inline int32_t* get_address_of_rgba_0() { return &___rgba_0; } inline void set_rgba_0(int32_t value) { ___rgba_0 = value; } inline static int32_t get_offset_of_r_1() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___r_1)); } inline uint8_t get_r_1() const { return ___r_1; } inline uint8_t* get_address_of_r_1() { return &___r_1; } inline void set_r_1(uint8_t value) { ___r_1 = value; } inline static int32_t get_offset_of_g_2() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___g_2)); } inline uint8_t get_g_2() const { return ___g_2; } inline uint8_t* get_address_of_g_2() { return &___g_2; } inline void set_g_2(uint8_t value) { ___g_2 = value; } inline static int32_t get_offset_of_b_3() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___b_3)); } inline uint8_t get_b_3() const { return ___b_3; } inline uint8_t* get_address_of_b_3() { return &___b_3; } inline void set_b_3(uint8_t value) { ___b_3 = value; } inline static int32_t get_offset_of_a_4() { return static_cast<int32_t>(offsetof(Color32_t2600501292, ___a_4)); } inline uint8_t get_a_4() const { return ___a_4; } inline uint8_t* get_address_of_a_4() { return &___a_4; } inline void set_a_4(uint8_t value) { ___a_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COLOR32_T2600501292_H #ifndef CONTEXTMENU_T1295656858_H #define CONTEXTMENU_T1295656858_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ContextMenu struct ContextMenu_t1295656858 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONTEXTMENU_T1295656858_H #ifndef CULLINGGROUPEVENT_T1722745023_H #define CULLINGGROUPEVENT_T1722745023_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.CullingGroupEvent struct CullingGroupEvent_t1722745023 { public: // System.Int32 UnityEngine.CullingGroupEvent::m_Index int32_t ___m_Index_0; // System.Byte UnityEngine.CullingGroupEvent::m_PrevState uint8_t ___m_PrevState_1; // System.Byte UnityEngine.CullingGroupEvent::m_ThisState uint8_t ___m_ThisState_2; public: inline static int32_t get_offset_of_m_Index_0() { return static_cast<int32_t>(offsetof(CullingGroupEvent_t1722745023, ___m_Index_0)); } inline int32_t get_m_Index_0() const { return ___m_Index_0; } inline int32_t* get_address_of_m_Index_0() { return &___m_Index_0; } inline void set_m_Index_0(int32_t value) { ___m_Index_0 = value; } inline static int32_t get_offset_of_m_PrevState_1() { return static_cast<int32_t>(offsetof(CullingGroupEvent_t1722745023, ___m_PrevState_1)); } inline uint8_t get_m_PrevState_1() const { return ___m_PrevState_1; } inline uint8_t* get_address_of_m_PrevState_1() { return &___m_PrevState_1; } inline void set_m_PrevState_1(uint8_t value) { ___m_PrevState_1 = value; } inline static int32_t get_offset_of_m_ThisState_2() { return static_cast<int32_t>(offsetof(CullingGroupEvent_t1722745023, ___m_ThisState_2)); } inline uint8_t get_m_ThisState_2() const { return ___m_ThisState_2; } inline uint8_t* get_address_of_m_ThisState_2() { return &___m_ThisState_2; } inline void set_m_ThisState_2(uint8_t value) { ___m_ThisState_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CULLINGGROUPEVENT_T1722745023_H #ifndef DEFAULTEXECUTIONORDER_T3059642329_H #define DEFAULTEXECUTIONORDER_T3059642329_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.DefaultExecutionOrder struct DefaultExecutionOrder_t3059642329 : public Attribute_t861562559 { public: // System.Int32 UnityEngine.DefaultExecutionOrder::<order>k__BackingField int32_t ___U3CorderU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CorderU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(DefaultExecutionOrder_t3059642329, ___U3CorderU3Ek__BackingField_0)); } inline int32_t get_U3CorderU3Ek__BackingField_0() const { return ___U3CorderU3Ek__BackingField_0; } inline int32_t* get_address_of_U3CorderU3Ek__BackingField_0() { return &___U3CorderU3Ek__BackingField_0; } inline void set_U3CorderU3Ek__BackingField_0(int32_t value) { ___U3CorderU3Ek__BackingField_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DEFAULTEXECUTIONORDER_T3059642329_H #ifndef DISALLOWMULTIPLECOMPONENT_T1422053217_H #define DISALLOWMULTIPLECOMPONENT_T1422053217_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.DisallowMultipleComponent struct DisallowMultipleComponent_t1422053217 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DISALLOWMULTIPLECOMPONENT_T1422053217_H #ifndef EXCLUDEFROMPRESETATTRIBUTE_T3751627762_H #define EXCLUDEFROMPRESETATTRIBUTE_T3751627762_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ExcludeFromPresetAttribute struct ExcludeFromPresetAttribute_t3751627762 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EXCLUDEFROMPRESETATTRIBUTE_T3751627762_H #ifndef EXECUTEINEDITMODE_T3727731349_H #define EXECUTEINEDITMODE_T3727731349_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ExecuteInEditMode struct ExecuteInEditMode_t3727731349 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EXECUTEINEDITMODE_T3727731349_H #ifndef KEYFRAME_T4206410242_H #define KEYFRAME_T4206410242_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Keyframe struct Keyframe_t4206410242 { public: // System.Single UnityEngine.Keyframe::m_Time float ___m_Time_0; // System.Single UnityEngine.Keyframe::m_Value float ___m_Value_1; // System.Single UnityEngine.Keyframe::m_InTangent float ___m_InTangent_2; // System.Single UnityEngine.Keyframe::m_OutTangent float ___m_OutTangent_3; // System.Int32 UnityEngine.Keyframe::m_WeightedMode int32_t ___m_WeightedMode_4; // System.Single UnityEngine.Keyframe::m_InWeight float ___m_InWeight_5; // System.Single UnityEngine.Keyframe::m_OutWeight float ___m_OutWeight_6; public: inline static int32_t get_offset_of_m_Time_0() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_Time_0)); } inline float get_m_Time_0() const { return ___m_Time_0; } inline float* get_address_of_m_Time_0() { return &___m_Time_0; } inline void set_m_Time_0(float value) { ___m_Time_0 = value; } inline static int32_t get_offset_of_m_Value_1() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_Value_1)); } inline float get_m_Value_1() const { return ___m_Value_1; } inline float* get_address_of_m_Value_1() { return &___m_Value_1; } inline void set_m_Value_1(float value) { ___m_Value_1 = value; } inline static int32_t get_offset_of_m_InTangent_2() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_InTangent_2)); } inline float get_m_InTangent_2() const { return ___m_InTangent_2; } inline float* get_address_of_m_InTangent_2() { return &___m_InTangent_2; } inline void set_m_InTangent_2(float value) { ___m_InTangent_2 = value; } inline static int32_t get_offset_of_m_OutTangent_3() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_OutTangent_3)); } inline float get_m_OutTangent_3() const { return ___m_OutTangent_3; } inline float* get_address_of_m_OutTangent_3() { return &___m_OutTangent_3; } inline void set_m_OutTangent_3(float value) { ___m_OutTangent_3 = value; } inline static int32_t get_offset_of_m_WeightedMode_4() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_WeightedMode_4)); } inline int32_t get_m_WeightedMode_4() const { return ___m_WeightedMode_4; } inline int32_t* get_address_of_m_WeightedMode_4() { return &___m_WeightedMode_4; } inline void set_m_WeightedMode_4(int32_t value) { ___m_WeightedMode_4 = value; } inline static int32_t get_offset_of_m_InWeight_5() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_InWeight_5)); } inline float get_m_InWeight_5() const { return ___m_InWeight_5; } inline float* get_address_of_m_InWeight_5() { return &___m_InWeight_5; } inline void set_m_InWeight_5(float value) { ___m_InWeight_5 = value; } inline static int32_t get_offset_of_m_OutWeight_6() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_OutWeight_6)); } inline float get_m_OutWeight_6() const { return ___m_OutWeight_6; } inline float* get_address_of_m_OutWeight_6() { return &___m_OutWeight_6; } inline void set_m_OutWeight_6(float value) { ___m_OutWeight_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // KEYFRAME_T4206410242_H #ifndef NATIVECLASSATTRIBUTE_T2601352714_H #define NATIVECLASSATTRIBUTE_T2601352714_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.NativeClassAttribute struct NativeClassAttribute_t2601352714 : public Attribute_t861562559 { public: // System.String UnityEngine.NativeClassAttribute::<QualifiedNativeName>k__BackingField String_t* ___U3CQualifiedNativeNameU3Ek__BackingField_0; // System.String UnityEngine.NativeClassAttribute::<Declaration>k__BackingField String_t* ___U3CDeclarationU3Ek__BackingField_1; public: inline static int32_t get_offset_of_U3CQualifiedNativeNameU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeClassAttribute_t2601352714, ___U3CQualifiedNativeNameU3Ek__BackingField_0)); } inline String_t* get_U3CQualifiedNativeNameU3Ek__BackingField_0() const { return ___U3CQualifiedNativeNameU3Ek__BackingField_0; } inline String_t** get_address_of_U3CQualifiedNativeNameU3Ek__BackingField_0() { return &___U3CQualifiedNativeNameU3Ek__BackingField_0; } inline void set_U3CQualifiedNativeNameU3Ek__BackingField_0(String_t* value) { ___U3CQualifiedNativeNameU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CQualifiedNativeNameU3Ek__BackingField_0), value); } inline static int32_t get_offset_of_U3CDeclarationU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(NativeClassAttribute_t2601352714, ___U3CDeclarationU3Ek__BackingField_1)); } inline String_t* get_U3CDeclarationU3Ek__BackingField_1() const { return ___U3CDeclarationU3Ek__BackingField_1; } inline String_t** get_address_of_U3CDeclarationU3Ek__BackingField_1() { return &___U3CDeclarationU3Ek__BackingField_1; } inline void set_U3CDeclarationU3Ek__BackingField_1(String_t* value) { ___U3CDeclarationU3Ek__BackingField_1 = value; Il2CppCodeGenWriteBarrier((&___U3CDeclarationU3Ek__BackingField_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVECLASSATTRIBUTE_T2601352714_H #ifndef REQUIRECOMPONENT_T3490506609_H #define REQUIRECOMPONENT_T3490506609_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RequireComponent struct RequireComponent_t3490506609 : public Attribute_t861562559 { public: // System.Type UnityEngine.RequireComponent::m_Type0 Type_t * ___m_Type0_0; // System.Type UnityEngine.RequireComponent::m_Type1 Type_t * ___m_Type1_1; // System.Type UnityEngine.RequireComponent::m_Type2 Type_t * ___m_Type2_2; public: inline static int32_t get_offset_of_m_Type0_0() { return static_cast<int32_t>(offsetof(RequireComponent_t3490506609, ___m_Type0_0)); } inline Type_t * get_m_Type0_0() const { return ___m_Type0_0; } inline Type_t ** get_address_of_m_Type0_0() { return &___m_Type0_0; } inline void set_m_Type0_0(Type_t * value) { ___m_Type0_0 = value; Il2CppCodeGenWriteBarrier((&___m_Type0_0), value); } inline static int32_t get_offset_of_m_Type1_1() { return static_cast<int32_t>(offsetof(RequireComponent_t3490506609, ___m_Type1_1)); } inline Type_t * get_m_Type1_1() const { return ___m_Type1_1; } inline Type_t ** get_address_of_m_Type1_1() { return &___m_Type1_1; } inline void set_m_Type1_1(Type_t * value) { ___m_Type1_1 = value; Il2CppCodeGenWriteBarrier((&___m_Type1_1), value); } inline static int32_t get_offset_of_m_Type2_2() { return static_cast<int32_t>(offsetof(RequireComponent_t3490506609, ___m_Type2_2)); } inline Type_t * get_m_Type2_2() const { return ___m_Type2_2; } inline Type_t ** get_address_of_m_Type2_2() { return &___m_Type2_2; } inline void set_m_Type2_2(Type_t * value) { ___m_Type2_2 = value; Il2CppCodeGenWriteBarrier((&___m_Type2_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REQUIRECOMPONENT_T3490506609_H #ifndef GENERATEDBYOLDBINDINGSGENERATORATTRIBUTE_T433318409_H #define GENERATEDBYOLDBINDINGSGENERATORATTRIBUTE_T433318409_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Scripting.GeneratedByOldBindingsGeneratorAttribute struct GeneratedByOldBindingsGeneratorAttribute_t433318409 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // GENERATEDBYOLDBINDINGSGENERATORATTRIBUTE_T433318409_H #ifndef REQUIREDBYNATIVECODEATTRIBUTE_T4130846357_H #define REQUIREDBYNATIVECODEATTRIBUTE_T4130846357_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Scripting.RequiredByNativeCodeAttribute struct RequiredByNativeCodeAttribute_t4130846357 : public Attribute_t861562559 { public: // System.String UnityEngine.Scripting.RequiredByNativeCodeAttribute::<Name>k__BackingField String_t* ___U3CNameU3Ek__BackingField_0; // System.Boolean UnityEngine.Scripting.RequiredByNativeCodeAttribute::<Optional>k__BackingField bool ___U3COptionalU3Ek__BackingField_1; // System.Boolean UnityEngine.Scripting.RequiredByNativeCodeAttribute::<GenerateProxy>k__BackingField bool ___U3CGenerateProxyU3Ek__BackingField_2; public: inline static int32_t get_offset_of_U3CNameU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(RequiredByNativeCodeAttribute_t4130846357, ___U3CNameU3Ek__BackingField_0)); } inline String_t* get_U3CNameU3Ek__BackingField_0() const { return ___U3CNameU3Ek__BackingField_0; } inline String_t** get_address_of_U3CNameU3Ek__BackingField_0() { return &___U3CNameU3Ek__BackingField_0; } inline void set_U3CNameU3Ek__BackingField_0(String_t* value) { ___U3CNameU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CNameU3Ek__BackingField_0), value); } inline static int32_t get_offset_of_U3COptionalU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(RequiredByNativeCodeAttribute_t4130846357, ___U3COptionalU3Ek__BackingField_1)); } inline bool get_U3COptionalU3Ek__BackingField_1() const { return ___U3COptionalU3Ek__BackingField_1; } inline bool* get_address_of_U3COptionalU3Ek__BackingField_1() { return &___U3COptionalU3Ek__BackingField_1; } inline void set_U3COptionalU3Ek__BackingField_1(bool value) { ___U3COptionalU3Ek__BackingField_1 = value; } inline static int32_t get_offset_of_U3CGenerateProxyU3Ek__BackingField_2() { return static_cast<int32_t>(offsetof(RequiredByNativeCodeAttribute_t4130846357, ___U3CGenerateProxyU3Ek__BackingField_2)); } inline bool get_U3CGenerateProxyU3Ek__BackingField_2() const { return ___U3CGenerateProxyU3Ek__BackingField_2; } inline bool* get_address_of_U3CGenerateProxyU3Ek__BackingField_2() { return &___U3CGenerateProxyU3Ek__BackingField_2; } inline void set_U3CGenerateProxyU3Ek__BackingField_2(bool value) { ___U3CGenerateProxyU3Ek__BackingField_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REQUIREDBYNATIVECODEATTRIBUTE_T4130846357_H #ifndef USEDBYNATIVECODEATTRIBUTE_T1703770351_H #define USEDBYNATIVECODEATTRIBUTE_T1703770351_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Scripting.UsedByNativeCodeAttribute struct UsedByNativeCodeAttribute_t1703770351 : public Attribute_t861562559 { public: // System.String UnityEngine.Scripting.UsedByNativeCodeAttribute::<Name>k__BackingField String_t* ___U3CNameU3Ek__BackingField_0; public: inline static int32_t get_offset_of_U3CNameU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(UsedByNativeCodeAttribute_t1703770351, ___U3CNameU3Ek__BackingField_0)); } inline String_t* get_U3CNameU3Ek__BackingField_0() const { return ___U3CNameU3Ek__BackingField_0; } inline String_t** get_address_of_U3CNameU3Ek__BackingField_0() { return &___U3CNameU3Ek__BackingField_0; } inline void set_U3CNameU3Ek__BackingField_0(String_t* value) { ___U3CNameU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CNameU3Ek__BackingField_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // USEDBYNATIVECODEATTRIBUTE_T1703770351_H #ifndef THREADANDSERIALIZATIONSAFEATTRIBUTE_T363116225_H #define THREADANDSERIALIZATIONSAFEATTRIBUTE_T363116225_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ThreadAndSerializationSafeAttribute struct ThreadAndSerializationSafeAttribute_t363116225 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // THREADANDSERIALIZATIONSAFEATTRIBUTE_T363116225_H #ifndef UNITYENGINEMODULEASSEMBLY_T2421846737_H #define UNITYENGINEMODULEASSEMBLY_T2421846737_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.UnityEngineModuleAssembly struct UnityEngineModuleAssembly_t2421846737 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UNITYENGINEMODULEASSEMBLY_T2421846737_H #ifndef VECTOR2_T2156229523_H #define VECTOR2_T2156229523_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector2 struct Vector2_t2156229523 { public: // System.Single UnityEngine.Vector2::x float ___x_0; // System.Single UnityEngine.Vector2::y float ___y_1; public: inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(Vector2_t2156229523, ___x_0)); } inline float get_x_0() const { return ___x_0; } inline float* get_address_of_x_0() { return &___x_0; } inline void set_x_0(float value) { ___x_0 = value; } inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(Vector2_t2156229523, ___y_1)); } inline float get_y_1() const { return ___y_1; } inline float* get_address_of_y_1() { return &___y_1; } inline void set_y_1(float value) { ___y_1 = value; } }; struct Vector2_t2156229523_StaticFields { public: // UnityEngine.Vector2 UnityEngine.Vector2::zeroVector Vector2_t2156229523 ___zeroVector_2; // UnityEngine.Vector2 UnityEngine.Vector2::oneVector Vector2_t2156229523 ___oneVector_3; // UnityEngine.Vector2 UnityEngine.Vector2::upVector Vector2_t2156229523 ___upVector_4; // UnityEngine.Vector2 UnityEngine.Vector2::downVector Vector2_t2156229523 ___downVector_5; // UnityEngine.Vector2 UnityEngine.Vector2::leftVector Vector2_t2156229523 ___leftVector_6; // UnityEngine.Vector2 UnityEngine.Vector2::rightVector Vector2_t2156229523 ___rightVector_7; // UnityEngine.Vector2 UnityEngine.Vector2::positiveInfinityVector Vector2_t2156229523 ___positiveInfinityVector_8; // UnityEngine.Vector2 UnityEngine.Vector2::negativeInfinityVector Vector2_t2156229523 ___negativeInfinityVector_9; public: inline static int32_t get_offset_of_zeroVector_2() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___zeroVector_2)); } inline Vector2_t2156229523 get_zeroVector_2() const { return ___zeroVector_2; } inline Vector2_t2156229523 * get_address_of_zeroVector_2() { return &___zeroVector_2; } inline void set_zeroVector_2(Vector2_t2156229523 value) { ___zeroVector_2 = value; } inline static int32_t get_offset_of_oneVector_3() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___oneVector_3)); } inline Vector2_t2156229523 get_oneVector_3() const { return ___oneVector_3; } inline Vector2_t2156229523 * get_address_of_oneVector_3() { return &___oneVector_3; } inline void set_oneVector_3(Vector2_t2156229523 value) { ___oneVector_3 = value; } inline static int32_t get_offset_of_upVector_4() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___upVector_4)); } inline Vector2_t2156229523 get_upVector_4() const { return ___upVector_4; } inline Vector2_t2156229523 * get_address_of_upVector_4() { return &___upVector_4; } inline void set_upVector_4(Vector2_t2156229523 value) { ___upVector_4 = value; } inline static int32_t get_offset_of_downVector_5() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___downVector_5)); } inline Vector2_t2156229523 get_downVector_5() const { return ___downVector_5; } inline Vector2_t2156229523 * get_address_of_downVector_5() { return &___downVector_5; } inline void set_downVector_5(Vector2_t2156229523 value) { ___downVector_5 = value; } inline static int32_t get_offset_of_leftVector_6() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___leftVector_6)); } inline Vector2_t2156229523 get_leftVector_6() const { return ___leftVector_6; } inline Vector2_t2156229523 * get_address_of_leftVector_6() { return &___leftVector_6; } inline void set_leftVector_6(Vector2_t2156229523 value) { ___leftVector_6 = value; } inline static int32_t get_offset_of_rightVector_7() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___rightVector_7)); } inline Vector2_t2156229523 get_rightVector_7() const { return ___rightVector_7; } inline Vector2_t2156229523 * get_address_of_rightVector_7() { return &___rightVector_7; } inline void set_rightVector_7(Vector2_t2156229523 value) { ___rightVector_7 = value; } inline static int32_t get_offset_of_positiveInfinityVector_8() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___positiveInfinityVector_8)); } inline Vector2_t2156229523 get_positiveInfinityVector_8() const { return ___positiveInfinityVector_8; } inline Vector2_t2156229523 * get_address_of_positiveInfinityVector_8() { return &___positiveInfinityVector_8; } inline void set_positiveInfinityVector_8(Vector2_t2156229523 value) { ___positiveInfinityVector_8 = value; } inline static int32_t get_offset_of_negativeInfinityVector_9() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___negativeInfinityVector_9)); } inline Vector2_t2156229523 get_negativeInfinityVector_9() const { return ___negativeInfinityVector_9; } inline Vector2_t2156229523 * get_address_of_negativeInfinityVector_9() { return &___negativeInfinityVector_9; } inline void set_negativeInfinityVector_9(Vector2_t2156229523 value) { ___negativeInfinityVector_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR2_T2156229523_H #ifndef VECTOR3_T3722313464_H #define VECTOR3_T3722313464_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector3 struct Vector3_t3722313464 { public: // System.Single UnityEngine.Vector3::x float ___x_2; // System.Single UnityEngine.Vector3::y float ___y_3; // System.Single UnityEngine.Vector3::z float ___z_4; public: inline static int32_t get_offset_of_x_2() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___x_2)); } inline float get_x_2() const { return ___x_2; } inline float* get_address_of_x_2() { return &___x_2; } inline void set_x_2(float value) { ___x_2 = value; } inline static int32_t get_offset_of_y_3() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___y_3)); } inline float get_y_3() const { return ___y_3; } inline float* get_address_of_y_3() { return &___y_3; } inline void set_y_3(float value) { ___y_3 = value; } inline static int32_t get_offset_of_z_4() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___z_4)); } inline float get_z_4() const { return ___z_4; } inline float* get_address_of_z_4() { return &___z_4; } inline void set_z_4(float value) { ___z_4 = value; } }; struct Vector3_t3722313464_StaticFields { public: // UnityEngine.Vector3 UnityEngine.Vector3::zeroVector Vector3_t3722313464 ___zeroVector_5; // UnityEngine.Vector3 UnityEngine.Vector3::oneVector Vector3_t3722313464 ___oneVector_6; // UnityEngine.Vector3 UnityEngine.Vector3::upVector Vector3_t3722313464 ___upVector_7; // UnityEngine.Vector3 UnityEngine.Vector3::downVector Vector3_t3722313464 ___downVector_8; // UnityEngine.Vector3 UnityEngine.Vector3::leftVector Vector3_t3722313464 ___leftVector_9; // UnityEngine.Vector3 UnityEngine.Vector3::rightVector Vector3_t3722313464 ___rightVector_10; // UnityEngine.Vector3 UnityEngine.Vector3::forwardVector Vector3_t3722313464 ___forwardVector_11; // UnityEngine.Vector3 UnityEngine.Vector3::backVector Vector3_t3722313464 ___backVector_12; // UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector Vector3_t3722313464 ___positiveInfinityVector_13; // UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector Vector3_t3722313464 ___negativeInfinityVector_14; public: inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___zeroVector_5)); } inline Vector3_t3722313464 get_zeroVector_5() const { return ___zeroVector_5; } inline Vector3_t3722313464 * get_address_of_zeroVector_5() { return &___zeroVector_5; } inline void set_zeroVector_5(Vector3_t3722313464 value) { ___zeroVector_5 = value; } inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___oneVector_6)); } inline Vector3_t3722313464 get_oneVector_6() const { return ___oneVector_6; } inline Vector3_t3722313464 * get_address_of_oneVector_6() { return &___oneVector_6; } inline void set_oneVector_6(Vector3_t3722313464 value) { ___oneVector_6 = value; } inline static int32_t get_offset_of_upVector_7() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___upVector_7)); } inline Vector3_t3722313464 get_upVector_7() const { return ___upVector_7; } inline Vector3_t3722313464 * get_address_of_upVector_7() { return &___upVector_7; } inline void set_upVector_7(Vector3_t3722313464 value) { ___upVector_7 = value; } inline static int32_t get_offset_of_downVector_8() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___downVector_8)); } inline Vector3_t3722313464 get_downVector_8() const { return ___downVector_8; } inline Vector3_t3722313464 * get_address_of_downVector_8() { return &___downVector_8; } inline void set_downVector_8(Vector3_t3722313464 value) { ___downVector_8 = value; } inline static int32_t get_offset_of_leftVector_9() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___leftVector_9)); } inline Vector3_t3722313464 get_leftVector_9() const { return ___leftVector_9; } inline Vector3_t3722313464 * get_address_of_leftVector_9() { return &___leftVector_9; } inline void set_leftVector_9(Vector3_t3722313464 value) { ___leftVector_9 = value; } inline static int32_t get_offset_of_rightVector_10() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___rightVector_10)); } inline Vector3_t3722313464 get_rightVector_10() const { return ___rightVector_10; } inline Vector3_t3722313464 * get_address_of_rightVector_10() { return &___rightVector_10; } inline void set_rightVector_10(Vector3_t3722313464 value) { ___rightVector_10 = value; } inline static int32_t get_offset_of_forwardVector_11() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___forwardVector_11)); } inline Vector3_t3722313464 get_forwardVector_11() const { return ___forwardVector_11; } inline Vector3_t3722313464 * get_address_of_forwardVector_11() { return &___forwardVector_11; } inline void set_forwardVector_11(Vector3_t3722313464 value) { ___forwardVector_11 = value; } inline static int32_t get_offset_of_backVector_12() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___backVector_12)); } inline Vector3_t3722313464 get_backVector_12() const { return ___backVector_12; } inline Vector3_t3722313464 * get_address_of_backVector_12() { return &___backVector_12; } inline void set_backVector_12(Vector3_t3722313464 value) { ___backVector_12 = value; } inline static int32_t get_offset_of_positiveInfinityVector_13() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___positiveInfinityVector_13)); } inline Vector3_t3722313464 get_positiveInfinityVector_13() const { return ___positiveInfinityVector_13; } inline Vector3_t3722313464 * get_address_of_positiveInfinityVector_13() { return &___positiveInfinityVector_13; } inline void set_positiveInfinityVector_13(Vector3_t3722313464 value) { ___positiveInfinityVector_13 = value; } inline static int32_t get_offset_of_negativeInfinityVector_14() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___negativeInfinityVector_14)); } inline Vector3_t3722313464 get_negativeInfinityVector_14() const { return ___negativeInfinityVector_14; } inline Vector3_t3722313464 * get_address_of_negativeInfinityVector_14() { return &___negativeInfinityVector_14; } inline void set_negativeInfinityVector_14(Vector3_t3722313464 value) { ___negativeInfinityVector_14 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR3_T3722313464_H #ifndef WRITABLEATTRIBUTE_T812406054_H #define WRITABLEATTRIBUTE_T812406054_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.WritableAttribute struct WritableAttribute_t812406054 : public Attribute_t861562559 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WRITABLEATTRIBUTE_T812406054_H #ifndef U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255366_H #define U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255366_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <PrivateImplementationDetails> struct U3CPrivateImplementationDetailsU3E_t3057255366 : public RuntimeObject { public: public: }; struct U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields { public: // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=120 <PrivateImplementationDetails>::0AA802CD6847EB893FE786B5EA5168B2FDCD7B93 __StaticArrayInitTypeSizeU3D120_t3297148302 ___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=256 <PrivateImplementationDetails>::0C4110BC17D746F018F47B49E0EB0D6590F69939 __StaticArrayInitTypeSizeU3D256_t1757367634 ___0C4110BC17D746F018F47B49E0EB0D6590F69939_1; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::20733E1283D873EBE47133A95C233E11B76F5F11 __StaticArrayInitTypeSizeU3D1024_t4211899788 ___20733E1283D873EBE47133A95C233E11B76F5F11_2; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E __StaticArrayInitTypeSizeU3D1024_t4211899788 ___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94 __StaticArrayInitTypeSizeU3D1024_t4211899788 ___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::30A0358B25B1372DD598BB4B1AC56AD6B8F08A47 __StaticArrayInitTypeSizeU3D1024_t4211899788 ___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::5B5DF5A459E902D96F7DB0FB235A25346CA85C5D __StaticArrayInitTypeSizeU3D1024_t4211899788 ___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::5BE411F1438EAEF33726D855E99011D5FECDDD4E __StaticArrayInitTypeSizeU3D1024_t4211899788 ___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=256 <PrivateImplementationDetails>::8F22C9ECE1331718CBD268A9BBFD2F5E451441E3 __StaticArrayInitTypeSizeU3D256_t1757367634 ___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53 __StaticArrayInitTypeSizeU3D1024_t4211899788 ___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9; // <PrivateImplementationDetails>/__StaticArrayInitTypeSize=1024 <PrivateImplementationDetails>::AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9 __StaticArrayInitTypeSizeU3D1024_t4211899788 ___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10; public: inline static int32_t get_offset_of_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0)); } inline __StaticArrayInitTypeSizeU3D120_t3297148302 get_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0() const { return ___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0; } inline __StaticArrayInitTypeSizeU3D120_t3297148302 * get_address_of_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0() { return &___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0; } inline void set_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0(__StaticArrayInitTypeSizeU3D120_t3297148302 value) { ___0AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0 = value; } inline static int32_t get_offset_of_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___0C4110BC17D746F018F47B49E0EB0D6590F69939_1)); } inline __StaticArrayInitTypeSizeU3D256_t1757367634 get_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1() const { return ___0C4110BC17D746F018F47B49E0EB0D6590F69939_1; } inline __StaticArrayInitTypeSizeU3D256_t1757367634 * get_address_of_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1() { return &___0C4110BC17D746F018F47B49E0EB0D6590F69939_1; } inline void set_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1(__StaticArrayInitTypeSizeU3D256_t1757367634 value) { ___0C4110BC17D746F018F47B49E0EB0D6590F69939_1 = value; } inline static int32_t get_offset_of_U320733E1283D873EBE47133A95C233E11B76F5F11_2() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___20733E1283D873EBE47133A95C233E11B76F5F11_2)); } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 get_U320733E1283D873EBE47133A95C233E11B76F5F11_2() const { return ___20733E1283D873EBE47133A95C233E11B76F5F11_2; } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 * get_address_of_U320733E1283D873EBE47133A95C233E11B76F5F11_2() { return &___20733E1283D873EBE47133A95C233E11B76F5F11_2; } inline void set_U320733E1283D873EBE47133A95C233E11B76F5F11_2(__StaticArrayInitTypeSizeU3D1024_t4211899788 value) { ___20733E1283D873EBE47133A95C233E11B76F5F11_2 = value; } inline static int32_t get_offset_of_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3)); } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 get_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3() const { return ___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3; } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 * get_address_of_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3() { return &___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3; } inline void set_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3(__StaticArrayInitTypeSizeU3D1024_t4211899788 value) { ___21F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3 = value; } inline static int32_t get_offset_of_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4)); } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 get_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4() const { return ___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4; } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 * get_address_of_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4() { return &___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4; } inline void set_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4(__StaticArrayInitTypeSizeU3D1024_t4211899788 value) { ___23DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4 = value; } inline static int32_t get_offset_of_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5)); } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 get_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5() const { return ___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5; } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 * get_address_of_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5() { return &___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5; } inline void set_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5(__StaticArrayInitTypeSizeU3D1024_t4211899788 value) { ___30A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5 = value; } inline static int32_t get_offset_of_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6)); } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 get_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6() const { return ___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6; } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 * get_address_of_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6() { return &___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6; } inline void set_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6(__StaticArrayInitTypeSizeU3D1024_t4211899788 value) { ___5B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6 = value; } inline static int32_t get_offset_of_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7)); } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 get_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7() const { return ___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7; } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 * get_address_of_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7() { return &___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7; } inline void set_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7(__StaticArrayInitTypeSizeU3D1024_t4211899788 value) { ___5BE411F1438EAEF33726D855E99011D5FECDDD4E_7 = value; } inline static int32_t get_offset_of_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8)); } inline __StaticArrayInitTypeSizeU3D256_t1757367634 get_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8() const { return ___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8; } inline __StaticArrayInitTypeSizeU3D256_t1757367634 * get_address_of_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8() { return &___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8; } inline void set_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8(__StaticArrayInitTypeSizeU3D256_t1757367634 value) { ___8F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8 = value; } inline static int32_t get_offset_of_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9)); } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 get_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9() const { return ___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9; } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 * get_address_of_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9() { return &___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9; } inline void set_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9(__StaticArrayInitTypeSizeU3D1024_t4211899788 value) { ___A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9 = value; } inline static int32_t get_offset_of_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10() { return static_cast<int32_t>(offsetof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields, ___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10)); } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 get_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10() const { return ___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10; } inline __StaticArrayInitTypeSizeU3D1024_t4211899788 * get_address_of_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10() { return &___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10; } inline void set_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10(__StaticArrayInitTypeSizeU3D1024_t4211899788 value) { ___AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CPRIVATEIMPLEMENTATIONDETAILSU3E_T3057255366_H #ifndef DELEGATE_T1188392813_H #define DELEGATE_T1188392813_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Delegate struct Delegate_t1188392813 : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::extra_arg intptr_t ___extra_arg_5; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_6; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_7; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_8; // System.DelegateData System.Delegate::data DelegateData_t1677132599 * ___data_9; // System.Boolean System.Delegate::method_is_virtual bool ___method_is_virtual_10; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((&___m_target_2), value); } inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_extra_arg_5() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___extra_arg_5)); } inline intptr_t get_extra_arg_5() const { return ___extra_arg_5; } inline intptr_t* get_address_of_extra_arg_5() { return &___extra_arg_5; } inline void set_extra_arg_5(intptr_t value) { ___extra_arg_5 = value; } inline static int32_t get_offset_of_method_code_6() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_code_6)); } inline intptr_t get_method_code_6() const { return ___method_code_6; } inline intptr_t* get_address_of_method_code_6() { return &___method_code_6; } inline void set_method_code_6(intptr_t value) { ___method_code_6 = value; } inline static int32_t get_offset_of_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_info_7)); } inline MethodInfo_t * get_method_info_7() const { return ___method_info_7; } inline MethodInfo_t ** get_address_of_method_info_7() { return &___method_info_7; } inline void set_method_info_7(MethodInfo_t * value) { ___method_info_7 = value; Il2CppCodeGenWriteBarrier((&___method_info_7), value); } inline static int32_t get_offset_of_original_method_info_8() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___original_method_info_8)); } inline MethodInfo_t * get_original_method_info_8() const { return ___original_method_info_8; } inline MethodInfo_t ** get_address_of_original_method_info_8() { return &___original_method_info_8; } inline void set_original_method_info_8(MethodInfo_t * value) { ___original_method_info_8 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_8), value); } inline static int32_t get_offset_of_data_9() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___data_9)); } inline DelegateData_t1677132599 * get_data_9() const { return ___data_9; } inline DelegateData_t1677132599 ** get_address_of_data_9() { return &___data_9; } inline void set_data_9(DelegateData_t1677132599 * value) { ___data_9 = value; Il2CppCodeGenWriteBarrier((&___data_9), value); } inline static int32_t get_offset_of_method_is_virtual_10() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_is_virtual_10)); } inline bool get_method_is_virtual_10() const { return ___method_is_virtual_10; } inline bool* get_address_of_method_is_virtual_10() { return &___method_is_virtual_10; } inline void set_method_is_virtual_10(bool value) { ___method_is_virtual_10 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Delegate struct Delegate_t1188392813_marshaled_pinvoke { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t1677132599 * ___data_9; int32_t ___method_is_virtual_10; }; // Native definition for COM marshalling of System.Delegate struct Delegate_t1188392813_marshaled_com { intptr_t ___method_ptr_0; intptr_t ___invoke_impl_1; Il2CppIUnknown* ___m_target_2; intptr_t ___method_3; intptr_t ___delegate_trampoline_4; intptr_t ___extra_arg_5; intptr_t ___method_code_6; MethodInfo_t * ___method_info_7; MethodInfo_t * ___original_method_info_8; DelegateData_t1677132599 * ___data_9; int32_t ___method_is_virtual_10; }; #endif // DELEGATE_T1188392813_H #ifndef ANIMATIONCURVE_T3046754366_H #define ANIMATIONCURVE_T3046754366_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AnimationCurve struct AnimationCurve_t3046754366 : public RuntimeObject { public: // System.IntPtr UnityEngine.AnimationCurve::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(AnimationCurve_t3046754366, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.AnimationCurve struct AnimationCurve_t3046754366_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.AnimationCurve struct AnimationCurve_t3046754366_marshaled_com { intptr_t ___m_Ptr_0; }; #endif // ANIMATIONCURVE_T3046754366_H #ifndef ASYNCOPERATION_T1445031843_H #define ASYNCOPERATION_T1445031843_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AsyncOperation struct AsyncOperation_t1445031843 : public YieldInstruction_t403091072 { public: // System.IntPtr UnityEngine.AsyncOperation::m_Ptr intptr_t ___m_Ptr_0; // System.Action`1<UnityEngine.AsyncOperation> UnityEngine.AsyncOperation::m_completeCallback Action_1_t1617499438 * ___m_completeCallback_1; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(AsyncOperation_t1445031843, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_completeCallback_1() { return static_cast<int32_t>(offsetof(AsyncOperation_t1445031843, ___m_completeCallback_1)); } inline Action_1_t1617499438 * get_m_completeCallback_1() const { return ___m_completeCallback_1; } inline Action_1_t1617499438 ** get_address_of_m_completeCallback_1() { return &___m_completeCallback_1; } inline void set_m_completeCallback_1(Action_1_t1617499438 * value) { ___m_completeCallback_1 = value; Il2CppCodeGenWriteBarrier((&___m_completeCallback_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.AsyncOperation struct AsyncOperation_t1445031843_marshaled_pinvoke : public YieldInstruction_t403091072_marshaled_pinvoke { intptr_t ___m_Ptr_0; Il2CppMethodPointer ___m_completeCallback_1; }; // Native definition for COM marshalling of UnityEngine.AsyncOperation struct AsyncOperation_t1445031843_marshaled_com : public YieldInstruction_t403091072_marshaled_com { intptr_t ___m_Ptr_0; Il2CppMethodPointer ___m_completeCallback_1; }; #endif // ASYNCOPERATION_T1445031843_H #ifndef CODEGENOPTIONS_T498890944_H #define CODEGENOPTIONS_T498890944_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.CodegenOptions struct CodegenOptions_t498890944 { public: // System.Int32 UnityEngine.Bindings.CodegenOptions::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(CodegenOptions_t498890944, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CODEGENOPTIONS_T498890944_H #ifndef FREEFUNCTIONATTRIBUTE_T2020741617_H #define FREEFUNCTIONATTRIBUTE_T2020741617_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.FreeFunctionAttribute struct FreeFunctionAttribute_t2020741617 : public NativeMethodAttribute_t4187428193 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FREEFUNCTIONATTRIBUTE_T2020741617_H #ifndef STATICACCESSORTYPE_T186341701_H #define STATICACCESSORTYPE_T186341701_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.StaticAccessorType struct StaticAccessorType_t186341701 { public: // System.Int32 UnityEngine.Bindings.StaticAccessorType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(StaticAccessorType_t186341701, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STATICACCESSORTYPE_T186341701_H #ifndef TARGETTYPE_T2370014154_H #define TARGETTYPE_T2370014154_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.TargetType struct TargetType_t2370014154 { public: // System.Int32 UnityEngine.Bindings.TargetType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(TargetType_t2370014154, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TARGETTYPE_T2370014154_H #ifndef THREADSAFEATTRIBUTE_T3376653515_H #define THREADSAFEATTRIBUTE_T3376653515_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.ThreadSafeAttribute struct ThreadSafeAttribute_t3376653515 : public NativeMethodAttribute_t4187428193 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // THREADSAFEATTRIBUTE_T3376653515_H #ifndef BOOTCONFIGDATA_T3818279794_H #define BOOTCONFIGDATA_T3818279794_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.BootConfigData struct BootConfigData_t3818279794 : public RuntimeObject { public: // System.IntPtr UnityEngine.BootConfigData::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(BootConfigData_t3818279794, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOTCONFIGDATA_T3818279794_H #ifndef BOUNDS_T2266837910_H #define BOUNDS_T2266837910_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bounds struct Bounds_t2266837910 { public: // UnityEngine.Vector3 UnityEngine.Bounds::m_Center Vector3_t3722313464 ___m_Center_0; // UnityEngine.Vector3 UnityEngine.Bounds::m_Extents Vector3_t3722313464 ___m_Extents_1; public: inline static int32_t get_offset_of_m_Center_0() { return static_cast<int32_t>(offsetof(Bounds_t2266837910, ___m_Center_0)); } inline Vector3_t3722313464 get_m_Center_0() const { return ___m_Center_0; } inline Vector3_t3722313464 * get_address_of_m_Center_0() { return &___m_Center_0; } inline void set_m_Center_0(Vector3_t3722313464 value) { ___m_Center_0 = value; } inline static int32_t get_offset_of_m_Extents_1() { return static_cast<int32_t>(offsetof(Bounds_t2266837910, ___m_Extents_1)); } inline Vector3_t3722313464 get_m_Extents_1() const { return ___m_Extents_1; } inline Vector3_t3722313464 * get_address_of_m_Extents_1() { return &___m_Extents_1; } inline void set_m_Extents_1(Vector3_t3722313464 value) { ___m_Extents_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOUNDS_T2266837910_H #ifndef MONOORSTEREOSCOPICEYE_T647613870_H #define MONOORSTEREOSCOPICEYE_T647613870_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Camera/MonoOrStereoscopicEye struct MonoOrStereoscopicEye_t647613870 { public: // System.Int32 UnityEngine.Camera/MonoOrStereoscopicEye::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(MonoOrStereoscopicEye_t647613870, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MONOORSTEREOSCOPICEYE_T647613870_H #ifndef COROUTINE_T3829159415_H #define COROUTINE_T3829159415_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Coroutine struct Coroutine_t3829159415 : public YieldInstruction_t403091072 { public: // System.IntPtr UnityEngine.Coroutine::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(Coroutine_t3829159415, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Coroutine struct Coroutine_t3829159415_marshaled_pinvoke : public YieldInstruction_t403091072_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.Coroutine struct Coroutine_t3829159415_marshaled_com : public YieldInstruction_t403091072_marshaled_com { intptr_t ___m_Ptr_0; }; #endif // COROUTINE_T3829159415_H #ifndef CULLINGGROUP_T2096318768_H #define CULLINGGROUP_T2096318768_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.CullingGroup struct CullingGroup_t2096318768 : public RuntimeObject { public: // System.IntPtr UnityEngine.CullingGroup::m_Ptr intptr_t ___m_Ptr_0; // UnityEngine.CullingGroup/StateChanged UnityEngine.CullingGroup::m_OnStateChanged StateChanged_t2136737110 * ___m_OnStateChanged_1; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(CullingGroup_t2096318768, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } inline static int32_t get_offset_of_m_OnStateChanged_1() { return static_cast<int32_t>(offsetof(CullingGroup_t2096318768, ___m_OnStateChanged_1)); } inline StateChanged_t2136737110 * get_m_OnStateChanged_1() const { return ___m_OnStateChanged_1; } inline StateChanged_t2136737110 ** get_address_of_m_OnStateChanged_1() { return &___m_OnStateChanged_1; } inline void set_m_OnStateChanged_1(StateChanged_t2136737110 * value) { ___m_OnStateChanged_1 = value; Il2CppCodeGenWriteBarrier((&___m_OnStateChanged_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.CullingGroup struct CullingGroup_t2096318768_marshaled_pinvoke { intptr_t ___m_Ptr_0; Il2CppMethodPointer ___m_OnStateChanged_1; }; // Native definition for COM marshalling of UnityEngine.CullingGroup struct CullingGroup_t2096318768_marshaled_com { intptr_t ___m_Ptr_0; Il2CppMethodPointer ___m_OnStateChanged_1; }; #endif // CULLINGGROUP_T2096318768_H #ifndef SCRIPTABLERENDERCONTEXT_T274343796_H #define SCRIPTABLERENDERCONTEXT_T274343796_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Experimental.Rendering.ScriptableRenderContext struct ScriptableRenderContext_t274343796 { public: // System.IntPtr UnityEngine.Experimental.Rendering.ScriptableRenderContext::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(ScriptableRenderContext_t274343796, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SCRIPTABLERENDERCONTEXT_T274343796_H #ifndef IMECOMPOSITIONMODE_T2677948540_H #define IMECOMPOSITIONMODE_T2677948540_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.IMECompositionMode struct IMECompositionMode_t2677948540 { public: // System.Int32 UnityEngine.IMECompositionMode::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(IMECompositionMode_t2677948540, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // IMECOMPOSITIONMODE_T2677948540_H #ifndef LOGTYPE_T73765434_H #define LOGTYPE_T73765434_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.LogType struct LogType_t73765434 { public: // System.Int32 UnityEngine.LogType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(LogType_t73765434, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LOGTYPE_T73765434_H #ifndef OBJECT_T631007953_H #define OBJECT_T631007953_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Object struct Object_t631007953 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t631007953, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_t631007953_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t631007953_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_t631007953_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_t631007953_marshaled_com { intptr_t ___m_CachedPtr_0; }; #endif // OBJECT_T631007953_H #ifndef RUNTIMEPLATFORM_T4159857903_H #define RUNTIMEPLATFORM_T4159857903_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RuntimePlatform struct RuntimePlatform_t4159857903 { public: // System.Int32 UnityEngine.RuntimePlatform::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(RuntimePlatform_t4159857903, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEPLATFORM_T4159857903_H #ifndef SENDMESSAGEOPTIONS_T3580193095_H #define SENDMESSAGEOPTIONS_T3580193095_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SendMessageOptions struct SendMessageOptions_t3580193095 { public: // System.Int32 UnityEngine.SendMessageOptions::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(SendMessageOptions_t3580193095, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SENDMESSAGEOPTIONS_T3580193095_H #ifndef TOUCHPHASE_T72348083_H #define TOUCHPHASE_T72348083_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TouchPhase struct TouchPhase_t72348083 { public: // System.Int32 UnityEngine.TouchPhase::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(TouchPhase_t72348083, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TOUCHPHASE_T72348083_H #ifndef TOUCHTYPE_T2034578258_H #define TOUCHTYPE_T2034578258_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.TouchType struct TouchType_t2034578258 { public: // System.Int32 UnityEngine.TouchType::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(TouchType_t2034578258, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TOUCHTYPE_T2034578258_H #ifndef MULTICASTDELEGATE_T_H #define MULTICASTDELEGATE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MulticastDelegate struct MulticastDelegate_t : public Delegate_t1188392813 { public: // System.Delegate[] System.MulticastDelegate::delegates DelegateU5BU5D_t1703627840* ___delegates_11; public: inline static int32_t get_offset_of_delegates_11() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___delegates_11)); } inline DelegateU5BU5D_t1703627840* get_delegates_11() const { return ___delegates_11; } inline DelegateU5BU5D_t1703627840** get_address_of_delegates_11() { return &___delegates_11; } inline void set_delegates_11(DelegateU5BU5D_t1703627840* value) { ___delegates_11 = value; Il2CppCodeGenWriteBarrier((&___delegates_11), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_pinvoke : public Delegate_t1188392813_marshaled_pinvoke { DelegateU5BU5D_t1703627840* ___delegates_11; }; // Native definition for COM marshalling of System.MulticastDelegate struct MulticastDelegate_t_marshaled_com : public Delegate_t1188392813_marshaled_com { DelegateU5BU5D_t1703627840* ___delegates_11; }; #endif // MULTICASTDELEGATE_T_H #ifndef NATIVEPROPERTYATTRIBUTE_T1305929258_H #define NATIVEPROPERTYATTRIBUTE_T1305929258_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NativePropertyAttribute struct NativePropertyAttribute_t1305929258 : public NativeMethodAttribute_t4187428193 { public: // UnityEngine.Bindings.TargetType UnityEngine.Bindings.NativePropertyAttribute::<TargetType>k__BackingField int32_t ___U3CTargetTypeU3Ek__BackingField_5; public: inline static int32_t get_offset_of_U3CTargetTypeU3Ek__BackingField_5() { return static_cast<int32_t>(offsetof(NativePropertyAttribute_t1305929258, ___U3CTargetTypeU3Ek__BackingField_5)); } inline int32_t get_U3CTargetTypeU3Ek__BackingField_5() const { return ___U3CTargetTypeU3Ek__BackingField_5; } inline int32_t* get_address_of_U3CTargetTypeU3Ek__BackingField_5() { return &___U3CTargetTypeU3Ek__BackingField_5; } inline void set_U3CTargetTypeU3Ek__BackingField_5(int32_t value) { ___U3CTargetTypeU3Ek__BackingField_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVEPROPERTYATTRIBUTE_T1305929258_H #ifndef NATIVETYPEATTRIBUTE_T2250406315_H #define NATIVETYPEATTRIBUTE_T2250406315_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.NativeTypeAttribute struct NativeTypeAttribute_t2250406315 : public Attribute_t861562559 { public: // System.String UnityEngine.Bindings.NativeTypeAttribute::<Header>k__BackingField String_t* ___U3CHeaderU3Ek__BackingField_0; // System.String UnityEngine.Bindings.NativeTypeAttribute::<IntermediateScriptingStructName>k__BackingField String_t* ___U3CIntermediateScriptingStructNameU3Ek__BackingField_1; // UnityEngine.Bindings.CodegenOptions UnityEngine.Bindings.NativeTypeAttribute::<CodegenOptions>k__BackingField int32_t ___U3CCodegenOptionsU3Ek__BackingField_2; public: inline static int32_t get_offset_of_U3CHeaderU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(NativeTypeAttribute_t2250406315, ___U3CHeaderU3Ek__BackingField_0)); } inline String_t* get_U3CHeaderU3Ek__BackingField_0() const { return ___U3CHeaderU3Ek__BackingField_0; } inline String_t** get_address_of_U3CHeaderU3Ek__BackingField_0() { return &___U3CHeaderU3Ek__BackingField_0; } inline void set_U3CHeaderU3Ek__BackingField_0(String_t* value) { ___U3CHeaderU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CHeaderU3Ek__BackingField_0), value); } inline static int32_t get_offset_of_U3CIntermediateScriptingStructNameU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(NativeTypeAttribute_t2250406315, ___U3CIntermediateScriptingStructNameU3Ek__BackingField_1)); } inline String_t* get_U3CIntermediateScriptingStructNameU3Ek__BackingField_1() const { return ___U3CIntermediateScriptingStructNameU3Ek__BackingField_1; } inline String_t** get_address_of_U3CIntermediateScriptingStructNameU3Ek__BackingField_1() { return &___U3CIntermediateScriptingStructNameU3Ek__BackingField_1; } inline void set_U3CIntermediateScriptingStructNameU3Ek__BackingField_1(String_t* value) { ___U3CIntermediateScriptingStructNameU3Ek__BackingField_1 = value; Il2CppCodeGenWriteBarrier((&___U3CIntermediateScriptingStructNameU3Ek__BackingField_1), value); } inline static int32_t get_offset_of_U3CCodegenOptionsU3Ek__BackingField_2() { return static_cast<int32_t>(offsetof(NativeTypeAttribute_t2250406315, ___U3CCodegenOptionsU3Ek__BackingField_2)); } inline int32_t get_U3CCodegenOptionsU3Ek__BackingField_2() const { return ___U3CCodegenOptionsU3Ek__BackingField_2; } inline int32_t* get_address_of_U3CCodegenOptionsU3Ek__BackingField_2() { return &___U3CCodegenOptionsU3Ek__BackingField_2; } inline void set_U3CCodegenOptionsU3Ek__BackingField_2(int32_t value) { ___U3CCodegenOptionsU3Ek__BackingField_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // NATIVETYPEATTRIBUTE_T2250406315_H #ifndef STATICACCESSORATTRIBUTE_T2432663902_H #define STATICACCESSORATTRIBUTE_T2432663902_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Bindings.StaticAccessorAttribute struct StaticAccessorAttribute_t2432663902 : public Attribute_t861562559 { public: // System.String UnityEngine.Bindings.StaticAccessorAttribute::<Name>k__BackingField String_t* ___U3CNameU3Ek__BackingField_0; // UnityEngine.Bindings.StaticAccessorType UnityEngine.Bindings.StaticAccessorAttribute::<Type>k__BackingField int32_t ___U3CTypeU3Ek__BackingField_1; public: inline static int32_t get_offset_of_U3CNameU3Ek__BackingField_0() { return static_cast<int32_t>(offsetof(StaticAccessorAttribute_t2432663902, ___U3CNameU3Ek__BackingField_0)); } inline String_t* get_U3CNameU3Ek__BackingField_0() const { return ___U3CNameU3Ek__BackingField_0; } inline String_t** get_address_of_U3CNameU3Ek__BackingField_0() { return &___U3CNameU3Ek__BackingField_0; } inline void set_U3CNameU3Ek__BackingField_0(String_t* value) { ___U3CNameU3Ek__BackingField_0 = value; Il2CppCodeGenWriteBarrier((&___U3CNameU3Ek__BackingField_0), value); } inline static int32_t get_offset_of_U3CTypeU3Ek__BackingField_1() { return static_cast<int32_t>(offsetof(StaticAccessorAttribute_t2432663902, ___U3CTypeU3Ek__BackingField_1)); } inline int32_t get_U3CTypeU3Ek__BackingField_1() const { return ___U3CTypeU3Ek__BackingField_1; } inline int32_t* get_address_of_U3CTypeU3Ek__BackingField_1() { return &___U3CTypeU3Ek__BackingField_1; } inline void set_U3CTypeU3Ek__BackingField_1(int32_t value) { ___U3CTypeU3Ek__BackingField_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STATICACCESSORATTRIBUTE_T2432663902_H #ifndef COMPONENT_T1923634451_H #define COMPONENT_T1923634451_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Component struct Component_t1923634451 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMPONENT_T1923634451_H #ifndef LOWERRESBLITTEXTURE_T2609707774_H #define LOWERRESBLITTEXTURE_T2609707774_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.LowerResBlitTexture struct LowerResBlitTexture_t2609707774 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LOWERRESBLITTEXTURE_T2609707774_H #ifndef MATERIAL_T340375123_H #define MATERIAL_T340375123_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Material struct Material_t340375123 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MATERIAL_T340375123_H #ifndef PRELOADDATA_T3191880618_H #define PRELOADDATA_T3191880618_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.PreloadData struct PreloadData_t3191880618 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PRELOADDATA_T3191880618_H #ifndef TEXTURE_T3661962703_H #define TEXTURE_T3661962703_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Texture struct Texture_t3661962703 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTURE_T3661962703_H #ifndef TOUCH_T1921856868_H #define TOUCH_T1921856868_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Touch struct Touch_t1921856868 { public: // System.Int32 UnityEngine.Touch::m_FingerId int32_t ___m_FingerId_0; // UnityEngine.Vector2 UnityEngine.Touch::m_Position Vector2_t2156229523 ___m_Position_1; // UnityEngine.Vector2 UnityEngine.Touch::m_RawPosition Vector2_t2156229523 ___m_RawPosition_2; // UnityEngine.Vector2 UnityEngine.Touch::m_PositionDelta Vector2_t2156229523 ___m_PositionDelta_3; // System.Single UnityEngine.Touch::m_TimeDelta float ___m_TimeDelta_4; // System.Int32 UnityEngine.Touch::m_TapCount int32_t ___m_TapCount_5; // UnityEngine.TouchPhase UnityEngine.Touch::m_Phase int32_t ___m_Phase_6; // UnityEngine.TouchType UnityEngine.Touch::m_Type int32_t ___m_Type_7; // System.Single UnityEngine.Touch::m_Pressure float ___m_Pressure_8; // System.Single UnityEngine.Touch::m_maximumPossiblePressure float ___m_maximumPossiblePressure_9; // System.Single UnityEngine.Touch::m_Radius float ___m_Radius_10; // System.Single UnityEngine.Touch::m_RadiusVariance float ___m_RadiusVariance_11; // System.Single UnityEngine.Touch::m_AltitudeAngle float ___m_AltitudeAngle_12; // System.Single UnityEngine.Touch::m_AzimuthAngle float ___m_AzimuthAngle_13; public: inline static int32_t get_offset_of_m_FingerId_0() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_FingerId_0)); } inline int32_t get_m_FingerId_0() const { return ___m_FingerId_0; } inline int32_t* get_address_of_m_FingerId_0() { return &___m_FingerId_0; } inline void set_m_FingerId_0(int32_t value) { ___m_FingerId_0 = value; } inline static int32_t get_offset_of_m_Position_1() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_Position_1)); } inline Vector2_t2156229523 get_m_Position_1() const { return ___m_Position_1; } inline Vector2_t2156229523 * get_address_of_m_Position_1() { return &___m_Position_1; } inline void set_m_Position_1(Vector2_t2156229523 value) { ___m_Position_1 = value; } inline static int32_t get_offset_of_m_RawPosition_2() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_RawPosition_2)); } inline Vector2_t2156229523 get_m_RawPosition_2() const { return ___m_RawPosition_2; } inline Vector2_t2156229523 * get_address_of_m_RawPosition_2() { return &___m_RawPosition_2; } inline void set_m_RawPosition_2(Vector2_t2156229523 value) { ___m_RawPosition_2 = value; } inline static int32_t get_offset_of_m_PositionDelta_3() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_PositionDelta_3)); } inline Vector2_t2156229523 get_m_PositionDelta_3() const { return ___m_PositionDelta_3; } inline Vector2_t2156229523 * get_address_of_m_PositionDelta_3() { return &___m_PositionDelta_3; } inline void set_m_PositionDelta_3(Vector2_t2156229523 value) { ___m_PositionDelta_3 = value; } inline static int32_t get_offset_of_m_TimeDelta_4() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_TimeDelta_4)); } inline float get_m_TimeDelta_4() const { return ___m_TimeDelta_4; } inline float* get_address_of_m_TimeDelta_4() { return &___m_TimeDelta_4; } inline void set_m_TimeDelta_4(float value) { ___m_TimeDelta_4 = value; } inline static int32_t get_offset_of_m_TapCount_5() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_TapCount_5)); } inline int32_t get_m_TapCount_5() const { return ___m_TapCount_5; } inline int32_t* get_address_of_m_TapCount_5() { return &___m_TapCount_5; } inline void set_m_TapCount_5(int32_t value) { ___m_TapCount_5 = value; } inline static int32_t get_offset_of_m_Phase_6() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_Phase_6)); } inline int32_t get_m_Phase_6() const { return ___m_Phase_6; } inline int32_t* get_address_of_m_Phase_6() { return &___m_Phase_6; } inline void set_m_Phase_6(int32_t value) { ___m_Phase_6 = value; } inline static int32_t get_offset_of_m_Type_7() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_Type_7)); } inline int32_t get_m_Type_7() const { return ___m_Type_7; } inline int32_t* get_address_of_m_Type_7() { return &___m_Type_7; } inline void set_m_Type_7(int32_t value) { ___m_Type_7 = value; } inline static int32_t get_offset_of_m_Pressure_8() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_Pressure_8)); } inline float get_m_Pressure_8() const { return ___m_Pressure_8; } inline float* get_address_of_m_Pressure_8() { return &___m_Pressure_8; } inline void set_m_Pressure_8(float value) { ___m_Pressure_8 = value; } inline static int32_t get_offset_of_m_maximumPossiblePressure_9() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_maximumPossiblePressure_9)); } inline float get_m_maximumPossiblePressure_9() const { return ___m_maximumPossiblePressure_9; } inline float* get_address_of_m_maximumPossiblePressure_9() { return &___m_maximumPossiblePressure_9; } inline void set_m_maximumPossiblePressure_9(float value) { ___m_maximumPossiblePressure_9 = value; } inline static int32_t get_offset_of_m_Radius_10() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_Radius_10)); } inline float get_m_Radius_10() const { return ___m_Radius_10; } inline float* get_address_of_m_Radius_10() { return &___m_Radius_10; } inline void set_m_Radius_10(float value) { ___m_Radius_10 = value; } inline static int32_t get_offset_of_m_RadiusVariance_11() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_RadiusVariance_11)); } inline float get_m_RadiusVariance_11() const { return ___m_RadiusVariance_11; } inline float* get_address_of_m_RadiusVariance_11() { return &___m_RadiusVariance_11; } inline void set_m_RadiusVariance_11(float value) { ___m_RadiusVariance_11 = value; } inline static int32_t get_offset_of_m_AltitudeAngle_12() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_AltitudeAngle_12)); } inline float get_m_AltitudeAngle_12() const { return ___m_AltitudeAngle_12; } inline float* get_address_of_m_AltitudeAngle_12() { return &___m_AltitudeAngle_12; } inline void set_m_AltitudeAngle_12(float value) { ___m_AltitudeAngle_12 = value; } inline static int32_t get_offset_of_m_AzimuthAngle_13() { return static_cast<int32_t>(offsetof(Touch_t1921856868, ___m_AzimuthAngle_13)); } inline float get_m_AzimuthAngle_13() const { return ___m_AzimuthAngle_13; } inline float* get_address_of_m_AzimuthAngle_13() { return &___m_AzimuthAngle_13; } inline void set_m_AzimuthAngle_13(float value) { ___m_AzimuthAngle_13 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TOUCH_T1921856868_H #ifndef LOGCALLBACK_T3588208630_H #define LOGCALLBACK_T3588208630_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Application/LogCallback struct LogCallback_t3588208630 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LOGCALLBACK_T3588208630_H #ifndef LOWMEMORYCALLBACK_T4104246196_H #define LOWMEMORYCALLBACK_T4104246196_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Application/LowMemoryCallback struct LowMemoryCallback_t4104246196 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LOWMEMORYCALLBACK_T4104246196_H #ifndef BEHAVIOUR_T1437897464_H #define BEHAVIOUR_T1437897464_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Behaviour struct Behaviour_t1437897464 : public Component_t1923634451 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BEHAVIOUR_T1437897464_H #ifndef CAMERACALLBACK_T190067161_H #define CAMERACALLBACK_T190067161_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Camera/CameraCallback struct CameraCallback_t190067161 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CAMERACALLBACK_T190067161_H #ifndef CUBEMAP_T1972384409_H #define CUBEMAP_T1972384409_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Cubemap struct Cubemap_t1972384409 : public Texture_t3661962703 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CUBEMAP_T1972384409_H #ifndef RENDERTEXTURE_T2108887433_H #define RENDERTEXTURE_T2108887433_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RenderTexture struct RenderTexture_t2108887433 : public Texture_t3661962703 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RENDERTEXTURE_T2108887433_H #ifndef TEXTURE2D_T3840446185_H #define TEXTURE2D_T3840446185_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Texture2D struct Texture2D_t3840446185 : public Texture_t3661962703 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTURE2D_T3840446185_H #ifndef TEXTURE2DARRAY_T4044506685_H #define TEXTURE2DARRAY_T4044506685_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Texture2DArray struct Texture2DArray_t4044506685 : public Texture_t3661962703 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTURE2DARRAY_T4044506685_H #ifndef TEXTURE3D_T1884131049_H #define TEXTURE3D_T1884131049_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Texture3D struct Texture3D_t1884131049 : public Texture_t3661962703 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TEXTURE3D_T1884131049_H #ifndef CAMERA_T4157153871_H #define CAMERA_T4157153871_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Camera struct Camera_t4157153871 : public Behaviour_t1437897464 { public: public: }; struct Camera_t4157153871_StaticFields { public: // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPreCull CameraCallback_t190067161 * ___onPreCull_4; // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPreRender CameraCallback_t190067161 * ___onPreRender_5; // UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPostRender CameraCallback_t190067161 * ___onPostRender_6; public: inline static int32_t get_offset_of_onPreCull_4() { return static_cast<int32_t>(offsetof(Camera_t4157153871_StaticFields, ___onPreCull_4)); } inline CameraCallback_t190067161 * get_onPreCull_4() const { return ___onPreCull_4; } inline CameraCallback_t190067161 ** get_address_of_onPreCull_4() { return &___onPreCull_4; } inline void set_onPreCull_4(CameraCallback_t190067161 * value) { ___onPreCull_4 = value; Il2CppCodeGenWriteBarrier((&___onPreCull_4), value); } inline static int32_t get_offset_of_onPreRender_5() { return static_cast<int32_t>(offsetof(Camera_t4157153871_StaticFields, ___onPreRender_5)); } inline CameraCallback_t190067161 * get_onPreRender_5() const { return ___onPreRender_5; } inline CameraCallback_t190067161 ** get_address_of_onPreRender_5() { return &___onPreRender_5; } inline void set_onPreRender_5(CameraCallback_t190067161 * value) { ___onPreRender_5 = value; Il2CppCodeGenWriteBarrier((&___onPreRender_5), value); } inline static int32_t get_offset_of_onPostRender_6() { return static_cast<int32_t>(offsetof(Camera_t4157153871_StaticFields, ___onPostRender_6)); } inline CameraCallback_t190067161 * get_onPostRender_6() const { return ___onPostRender_6; } inline CameraCallback_t190067161 ** get_address_of_onPostRender_6() { return &___onPostRender_6; } inline void set_onPostRender_6(CameraCallback_t190067161 * value) { ___onPostRender_6 = value; Il2CppCodeGenWriteBarrier((&___onPostRender_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CAMERA_T4157153871_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3000 = { sizeof (Utilities_t3288484762), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3001 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable3001[2] = { 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3002 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable3002[15] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3003 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable3003[3] = { 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3004 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable3004[4] = { 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3005 = { 0, 0, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3006 = { sizeof (U3CPrivateImplementationDetailsU3E_t3057255366), -1, sizeof(U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3006[11] = { U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U30AA802CD6847EB893FE786B5EA5168B2FDCD7B93_0(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U30C4110BC17D746F018F47B49E0EB0D6590F69939_1(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U320733E1283D873EBE47133A95C233E11B76F5F11_2(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U321F4CBF8283FF1CAEB4A39316A97FC1D6DF1D35E_3(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U323DFDCA6F045D4257BF5AC8CB1CF2EFADAFE9B94_4(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U330A0358B25B1372DD598BB4B1AC56AD6B8F08A47_5(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U35B5DF5A459E902D96F7DB0FB235A25346CA85C5D_6(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U35BE411F1438EAEF33726D855E99011D5FECDDD4E_7(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_U38F22C9ECE1331718CBD268A9BBFD2F5E451441E3_8(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_A02DD1D8604EA8EC2D2BDA717A93A4EE85F13E53_9(), U3CPrivateImplementationDetailsU3E_t3057255366_StaticFields::get_offset_of_AE2F76ECEF8B08F0BC7EA95DCFE945E1727927C9_10(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3007 = { sizeof (__StaticArrayInitTypeSizeU3D120_t3297148302)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D120_t3297148302 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3008 = { sizeof (__StaticArrayInitTypeSizeU3D256_t1757367634)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D256_t1757367634 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3009 = { sizeof (__StaticArrayInitTypeSizeU3D1024_t4211899788)+ sizeof (RuntimeObject), sizeof(__StaticArrayInitTypeSizeU3D1024_t4211899788 ), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3010 = { sizeof (U3CModuleU3E_t692745531), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3011 = { sizeof (UsedByNativeCodeAttribute_t1703770351), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3011[1] = { UsedByNativeCodeAttribute_t1703770351::get_offset_of_U3CNameU3Ek__BackingField_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3012 = { sizeof (RequiredByNativeCodeAttribute_t4130846357), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3012[3] = { RequiredByNativeCodeAttribute_t4130846357::get_offset_of_U3CNameU3Ek__BackingField_0(), RequiredByNativeCodeAttribute_t4130846357::get_offset_of_U3COptionalU3Ek__BackingField_1(), RequiredByNativeCodeAttribute_t4130846357::get_offset_of_U3CGenerateProxyU3Ek__BackingField_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3013 = { sizeof (GeneratedByOldBindingsGeneratorAttribute_t433318409), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3014 = { sizeof (AssetFileNameExtensionAttribute_t1361241164), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3014[2] = { AssetFileNameExtensionAttribute_t1361241164::get_offset_of_U3CpreferredExtensionU3Ek__BackingField_0(), AssetFileNameExtensionAttribute_t1361241164::get_offset_of_U3CotherExtensionsU3Ek__BackingField_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3015 = { sizeof (ThreadAndSerializationSafeAttribute_t363116225), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3016 = { sizeof (WritableAttribute_t812406054), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3017 = { sizeof (UnityEngineModuleAssembly_t2421846737), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3018 = { sizeof (NativeClassAttribute_t2601352714), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3018[2] = { NativeClassAttribute_t2601352714::get_offset_of_U3CQualifiedNativeNameU3Ek__BackingField_0(), NativeClassAttribute_t2601352714::get_offset_of_U3CDeclarationU3Ek__BackingField_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3019 = { sizeof (VisibleToOtherModulesAttribute_t1429630568), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3020 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3021 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3022 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3023 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3024 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3025 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3026 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3027 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3028 = { sizeof (NativeConditionalAttribute_t2439539374), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3028[2] = { NativeConditionalAttribute_t2439539374::get_offset_of_U3CConditionU3Ek__BackingField_0(), NativeConditionalAttribute_t2439539374::get_offset_of_U3CEnabledU3Ek__BackingField_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3029 = { sizeof (NativeHeaderAttribute_t5261382), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3029[1] = { NativeHeaderAttribute_t5261382::get_offset_of_U3CHeaderU3Ek__BackingField_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3030 = { sizeof (NativeNameAttribute_t3268151526), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3030[1] = { NativeNameAttribute_t3268151526::get_offset_of_U3CNameU3Ek__BackingField_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3031 = { sizeof (NativeWritableSelfAttribute_t3843992162), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3031[1] = { NativeWritableSelfAttribute_t3843992162::get_offset_of_U3CWritableSelfU3Ek__BackingField_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3032 = { sizeof (NativeMethodAttribute_t4187428193), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3032[5] = { NativeMethodAttribute_t4187428193::get_offset_of_U3CNameU3Ek__BackingField_0(), NativeMethodAttribute_t4187428193::get_offset_of_U3CIsThreadSafeU3Ek__BackingField_1(), NativeMethodAttribute_t4187428193::get_offset_of_U3CIsFreeFunctionU3Ek__BackingField_2(), NativeMethodAttribute_t4187428193::get_offset_of_U3CThrowsExceptionU3Ek__BackingField_3(), NativeMethodAttribute_t4187428193::get_offset_of_U3CHasExplicitThisU3Ek__BackingField_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3033 = { sizeof (TargetType_t2370014154)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3033[3] = { TargetType_t2370014154::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3034 = { sizeof (NativePropertyAttribute_t1305929258), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3034[1] = { NativePropertyAttribute_t1305929258::get_offset_of_U3CTargetTypeU3Ek__BackingField_5(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3035 = { sizeof (CodegenOptions_t498890944)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3035[4] = { CodegenOptions_t498890944::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3036 = { sizeof (NativeTypeAttribute_t2250406315), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3036[3] = { NativeTypeAttribute_t2250406315::get_offset_of_U3CHeaderU3Ek__BackingField_0(), NativeTypeAttribute_t2250406315::get_offset_of_U3CIntermediateScriptingStructNameU3Ek__BackingField_1(), NativeTypeAttribute_t2250406315::get_offset_of_U3CCodegenOptionsU3Ek__BackingField_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3037 = { sizeof (NotNullAttribute_t1114947401), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3038 = { sizeof (UnmarshalledAttribute_t1517743549), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3039 = { sizeof (FreeFunctionAttribute_t2020741617), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3040 = { sizeof (ThreadSafeAttribute_t3376653515), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3041 = { sizeof (StaticAccessorType_t186341701)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3041[5] = { StaticAccessorType_t186341701::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3042 = { sizeof (StaticAccessorAttribute_t2432663902), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3042[2] = { StaticAccessorAttribute_t2432663902::get_offset_of_U3CNameU3Ek__BackingField_0(), StaticAccessorAttribute_t2432663902::get_offset_of_U3CTypeU3Ek__BackingField_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3043 = { sizeof (NativeThrowsAttribute_t1697526064), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3043[1] = { NativeThrowsAttribute_t1697526064::get_offset_of_U3CThrowsExceptionU3Ek__BackingField_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3044 = { sizeof (IgnoreAttribute_t1982719709), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3044[1] = { IgnoreAttribute_t1982719709::get_offset_of_U3CDoesNotContributeToSizeU3Ek__BackingField_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3045 = { sizeof (UnityString_t1423233093), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3046 = { sizeof (U3CModuleU3E_t692745532), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3047 = { sizeof (Camera_t4157153871), -1, sizeof(Camera_t4157153871_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3047[3] = { Camera_t4157153871_StaticFields::get_offset_of_onPreCull_4(), Camera_t4157153871_StaticFields::get_offset_of_onPreRender_5(), Camera_t4157153871_StaticFields::get_offset_of_onPostRender_6(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3048 = { sizeof (MonoOrStereoscopicEye_t647613870)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3048[4] = { MonoOrStereoscopicEye_t647613870::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3049 = { sizeof (CameraCallback_t190067161), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3050 = { sizeof (NoAllocHelpers_t1437076930), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3051 = { sizeof (TouchPhase_t72348083)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3051[6] = { TouchPhase_t72348083::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3052 = { sizeof (IMECompositionMode_t2677948540)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3052[4] = { IMECompositionMode_t2677948540::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3053 = { sizeof (TouchType_t2034578258)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3053[4] = { TouchType_t2034578258::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3054 = { sizeof (Touch_t1921856868)+ sizeof (RuntimeObject), sizeof(Touch_t1921856868 ), 0, 0 }; extern const int32_t g_FieldOffsetTable3054[14] = { Touch_t1921856868::get_offset_of_m_FingerId_0() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_Position_1() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_RawPosition_2() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_PositionDelta_3() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_TimeDelta_4() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_TapCount_5() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_Phase_6() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_Type_7() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_Pressure_8() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_maximumPossiblePressure_9() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_Radius_10() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_RadiusVariance_11() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_AltitudeAngle_12() + static_cast<int32_t>(sizeof(RuntimeObject)), Touch_t1921856868::get_offset_of_m_AzimuthAngle_13() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3055 = { sizeof (Gyroscope_t3288342876), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3056 = { sizeof (Input_t1431474628), -1, sizeof(Input_t1431474628_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3056[1] = { Input_t1431474628_StaticFields::get_offset_of_m_MainGyro_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3057 = { 0, -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3058 = { sizeof (PlayerConnectionInternal_t3892293164), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3059 = { sizeof (Material_t340375123), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3060 = { sizeof (Texture2D_t3840446185), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3061 = { sizeof (Cubemap_t1972384409), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3062 = { sizeof (Texture3D_t1884131049), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3063 = { sizeof (Texture2DArray_t4044506685), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3064 = { sizeof (RenderTexture_t2108887433), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3065 = { sizeof (ScriptableRenderContext_t274343796)+ sizeof (RuntimeObject), sizeof(ScriptableRenderContext_t274343796 ), 0, 0 }; extern const int32_t g_FieldOffsetTable3065[1] = { ScriptableRenderContext_t274343796::get_offset_of_m_Ptr_0() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3066 = { sizeof (Keyframe_t4206410242)+ sizeof (RuntimeObject), sizeof(Keyframe_t4206410242 ), 0, 0 }; extern const int32_t g_FieldOffsetTable3066[7] = { Keyframe_t4206410242::get_offset_of_m_Time_0() + static_cast<int32_t>(sizeof(RuntimeObject)), Keyframe_t4206410242::get_offset_of_m_Value_1() + static_cast<int32_t>(sizeof(RuntimeObject)), Keyframe_t4206410242::get_offset_of_m_InTangent_2() + static_cast<int32_t>(sizeof(RuntimeObject)), Keyframe_t4206410242::get_offset_of_m_OutTangent_3() + static_cast<int32_t>(sizeof(RuntimeObject)), Keyframe_t4206410242::get_offset_of_m_WeightedMode_4() + static_cast<int32_t>(sizeof(RuntimeObject)), Keyframe_t4206410242::get_offset_of_m_InWeight_5() + static_cast<int32_t>(sizeof(RuntimeObject)), Keyframe_t4206410242::get_offset_of_m_OutWeight_6() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3067 = { sizeof (AnimationCurve_t3046754366), sizeof(AnimationCurve_t3046754366_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable3067[1] = { AnimationCurve_t3046754366::get_offset_of_m_Ptr_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3068 = { sizeof (Application_t1852185770), -1, sizeof(Application_t1852185770_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3068[5] = { Application_t1852185770_StaticFields::get_offset_of_lowMemory_0(), Application_t1852185770_StaticFields::get_offset_of_s_LogCallbackHandler_1(), Application_t1852185770_StaticFields::get_offset_of_s_LogCallbackHandlerThreaded_2(), Application_t1852185770_StaticFields::get_offset_of_wantsToQuit_3(), Application_t1852185770_StaticFields::get_offset_of_quitting_4(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3069 = { sizeof (LowMemoryCallback_t4104246196), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3070 = { sizeof (LogCallback_t3588208630), sizeof(Il2CppMethodPointer), 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3071 = { sizeof (AsyncOperation_t1445031843), sizeof(AsyncOperation_t1445031843_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable3071[2] = { AsyncOperation_t1445031843::get_offset_of_m_Ptr_0(), AsyncOperation_t1445031843::get_offset_of_m_completeCallback_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3072 = { sizeof (AttributeHelperEngine_t2735742303), -1, sizeof(AttributeHelperEngine_t2735742303_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3072[3] = { AttributeHelperEngine_t2735742303_StaticFields::get_offset_of__disallowMultipleComponentArray_0(), AttributeHelperEngine_t2735742303_StaticFields::get_offset_of__executeInEditModeArray_1(), AttributeHelperEngine_t2735742303_StaticFields::get_offset_of__requireComponentArray_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3073 = { sizeof (DisallowMultipleComponent_t1422053217), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3074 = { sizeof (RequireComponent_t3490506609), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3074[3] = { RequireComponent_t3490506609::get_offset_of_m_Type0_0(), RequireComponent_t3490506609::get_offset_of_m_Type1_1(), RequireComponent_t3490506609::get_offset_of_m_Type2_2(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3075 = { sizeof (AddComponentMenu_t415040132), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3075[2] = { AddComponentMenu_t415040132::get_offset_of_m_AddComponentMenu_0(), AddComponentMenu_t415040132::get_offset_of_m_Ordering_1(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3076 = { sizeof (ContextMenu_t1295656858), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3077 = { sizeof (ExecuteInEditMode_t3727731349), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3078 = { sizeof (DefaultExecutionOrder_t3059642329), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3078[1] = { DefaultExecutionOrder_t3059642329::get_offset_of_U3CorderU3Ek__BackingField_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3079 = { sizeof (AssemblyIsEditorAssembly_t3442416807), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3080 = { sizeof (ExcludeFromPresetAttribute_t3751627762), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3081 = { sizeof (SendMessageOptions_t3580193095)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3081[3] = { SendMessageOptions_t3580193095::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3082 = { sizeof (RuntimePlatform_t4159857903)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3082[34] = { RuntimePlatform_t4159857903::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3083 = { sizeof (LogType_t73765434)+ sizeof (RuntimeObject), sizeof(int32_t), 0, 0 }; extern const int32_t g_FieldOffsetTable3083[6] = { LogType_t73765434::get_offset_of_value___2() + static_cast<int32_t>(sizeof(RuntimeObject)), 0, 0, 0, 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3084 = { sizeof (BeforeRenderHelper_t1336903776), -1, sizeof(BeforeRenderHelper_t1336903776_StaticFields), 0 }; extern const int32_t g_FieldOffsetTable3084[1] = { BeforeRenderHelper_t1336903776_StaticFields::get_offset_of_s_OrderBlocks_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3085 = { sizeof (OrderBlock_t1585977831)+ sizeof (RuntimeObject), sizeof(OrderBlock_t1585977831_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable3085[2] = { OrderBlock_t1585977831::get_offset_of_order_0() + static_cast<int32_t>(sizeof(RuntimeObject)), OrderBlock_t1585977831::get_offset_of_callback_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3086 = { sizeof (Behaviour_t1437897464), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3087 = { sizeof (BootConfigData_t3818279794), -1, 0, 0 }; extern const int32_t g_FieldOffsetTable3087[1] = { BootConfigData_t3818279794::get_offset_of_m_Ptr_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3088 = { sizeof (Bounds_t2266837910)+ sizeof (RuntimeObject), sizeof(Bounds_t2266837910 ), 0, 0 }; extern const int32_t g_FieldOffsetTable3088[2] = { Bounds_t2266837910::get_offset_of_m_Center_0() + static_cast<int32_t>(sizeof(RuntimeObject)), Bounds_t2266837910::get_offset_of_m_Extents_1() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3089 = { 0, 0, 0, 0 }; extern const int32_t g_FieldOffsetTable3089[2] = { 0, 0, }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3090 = { sizeof (ClassLibraryInitializer_t2339504045), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3091 = { sizeof (LowerResBlitTexture_t2609707774), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3092 = { sizeof (PreloadData_t3191880618), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3093 = { sizeof (Color_t2555686324)+ sizeof (RuntimeObject), sizeof(Color_t2555686324 ), 0, 0 }; extern const int32_t g_FieldOffsetTable3093[4] = { Color_t2555686324::get_offset_of_r_0() + static_cast<int32_t>(sizeof(RuntimeObject)), Color_t2555686324::get_offset_of_g_1() + static_cast<int32_t>(sizeof(RuntimeObject)), Color_t2555686324::get_offset_of_b_2() + static_cast<int32_t>(sizeof(RuntimeObject)), Color_t2555686324::get_offset_of_a_3() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3094 = { sizeof (Color32_t2600501292)+ sizeof (RuntimeObject), sizeof(Color32_t2600501292 ), 0, 0 }; extern const int32_t g_FieldOffsetTable3094[5] = { Color32_t2600501292::get_offset_of_rgba_0() + static_cast<int32_t>(sizeof(RuntimeObject)), Color32_t2600501292::get_offset_of_r_1() + static_cast<int32_t>(sizeof(RuntimeObject)), Color32_t2600501292::get_offset_of_g_2() + static_cast<int32_t>(sizeof(RuntimeObject)), Color32_t2600501292::get_offset_of_b_3() + static_cast<int32_t>(sizeof(RuntimeObject)), Color32_t2600501292::get_offset_of_a_4() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3095 = { sizeof (Component_t1923634451), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3096 = { sizeof (Coroutine_t3829159415), sizeof(Coroutine_t3829159415_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable3096[1] = { Coroutine_t3829159415::get_offset_of_m_Ptr_0(), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3097 = { sizeof (SetupCoroutine_t2062820429), -1, 0, 0 }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3098 = { sizeof (CullingGroupEvent_t1722745023)+ sizeof (RuntimeObject), sizeof(CullingGroupEvent_t1722745023 ), 0, 0 }; extern const int32_t g_FieldOffsetTable3098[3] = { CullingGroupEvent_t1722745023::get_offset_of_m_Index_0() + static_cast<int32_t>(sizeof(RuntimeObject)), CullingGroupEvent_t1722745023::get_offset_of_m_PrevState_1() + static_cast<int32_t>(sizeof(RuntimeObject)), CullingGroupEvent_t1722745023::get_offset_of_m_ThisState_2() + static_cast<int32_t>(sizeof(RuntimeObject)), }; extern const Il2CppTypeDefinitionSizes g_typeDefinitionSize3099 = { sizeof (CullingGroup_t2096318768), sizeof(CullingGroup_t2096318768_marshaled_pinvoke), 0, 0 }; extern const int32_t g_FieldOffsetTable3099[2] = { CullingGroup_t2096318768::get_offset_of_m_Ptr_0(), CullingGroup_t2096318768::get_offset_of_m_OnStateChanged_1(), }; #ifdef __clang__ #pragma clang diagnostic pop #endif
38.300817
234
0.832548
[ "object" ]
fde08f4c01f615d03dcb85ca8fc402628ee57e35
10,951
hpp
C++
inference-engine/include/ie_locked_memory.hpp
giulio1979/dldt
e7061922066ccefc54c8dae6e3215308ce9559e1
[ "Apache-2.0" ]
1
2021-07-30T17:03:50.000Z
2021-07-30T17:03:50.000Z
inference-engine/include/ie_locked_memory.hpp
Dipet/dldt
b2140c083a068a63591e8c2e9b5f6b240790519d
[ "Apache-2.0" ]
null
null
null
inference-engine/include/ie_locked_memory.hpp
Dipet/dldt
b2140c083a068a63591e8c2e9b5f6b240790519d
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /** * @brief A header file for generic LockedMemory<> and different variations of locks * * @file ie_locked_memory.hpp */ #pragma once #include <iostream> #include <utility> #include "ie_allocator.hpp" namespace InferenceEngine { namespace details { /** * @brief This class is a LockedMemory concept for hardware memory */ template <class T> class LockedMemoryBase { IAllocator* _allocator = nullptr; void* _handle = nullptr; mutable T* _locked = nullptr; LockOp _lockFlag = LOCK_FOR_WRITE; protected: /** * @brief An offset size * * The default value is 0. */ size_t _offset = 0; public: /** * @brief A constructor * * @param ptr Pointer to an IAllocator object * @param handle Handle provided by allocator->Alloc() * @param lockFlag Read/Write type of mapping * @param offsetInBytes Offset in originally locked region */ LockedMemoryBase(IAllocator* ptr, void* handle, LockOp lockFlag, size_t offsetInBytes) : _allocator(ptr), _handle(handle), _lockFlag(lockFlag), _offset(offsetInBytes) {} /** * @brief A copy constructor * * @param that An rvalue reference for the other LockedMemoryBase instance */ LockedMemoryBase(LockedMemoryBase&& that) : _allocator(that._allocator), _handle(that._handle), _lockFlag(that._lockFlag), _offset(that._offset) { that._locked = nullptr; } /** * @brief A virtual destructor */ virtual ~LockedMemoryBase() { if (_locked != nullptr) { _allocator->unlock(_handle); } } protected: /** * @brief Compares referenced values * * @param pointer Pointer to the object to compare with * @return True if all handlers are nullptr or referenced values are equal, false otherwise */ bool isEqualTo(const T* pointer) const { if (pointer == nullptr && (_allocator == nullptr || _handle == nullptr)) { return true; } return dereference() == pointer; } /** * @brief Gets the locked object. * * Locks the handler and casts memory to the object of the given template type. * * @return The pointer to the locked object, nullptr otherwise */ virtual T* dereference() const { if (_locked != nullptr) return _locked; if (_allocator == nullptr) { return nullptr; } if (_handle == nullptr) { return nullptr; } uint8_t* pBytes = reinterpret_cast<uint8_t*>(_allocator->lock(_handle, _lockFlag)); return _locked = reinterpret_cast<T*>(pBytes + _offset); } }; } // namespace details /** * @brief This class represents locked memory for read/write memory */ template <class T> class LockedMemory : public details::LockedMemoryBase<T> { using base = details::LockedMemoryBase<T>; public: /** * @brief A constructor * * @param ptr Pointer to IAllocator object * @param handle Handle provided by allocator * @param offsetInBytes Offset in originally locked region */ LockedMemory(IAllocator* ptr, void* handle, size_t offsetInBytes = 0) : base(ptr, handle, LOCK_FOR_WRITE, offsetInBytes) {} /** * @brief A default copy constructor, accepting rvalue */ LockedMemory(LockedMemory<T>&&) = default; /** * @brief A default copy constructor that accepts rvalue * * Also sets the offset value for the new memory object * * @param that Rvalue reference for the other LockedMemoryBase instance * @param offset Offset value */ LockedMemory(LockedMemory<T>&& that, size_t offset): base(std::move(that)) { base::_offset = offset; } /** * @brief A disabled copy constructor for lvalue */ LockedMemory(const LockedMemory<T>&) = delete; /** * @brief Gets a pointer to the stored object * * Dereferences from the base class. * * @return The pointer to the object of the given template type */ operator T*() { return base::dereference(); } /** * @brief Gets the const pointer to the stored object * * Dereferences from the base class. * @return The const pointer object of the given template type. */ operator const T*() const { return base::dereference(); } /** * @brief Compares stored object with the given one * * @return true if objects are equal, false otherwise */ bool operator==(const T* pointer) const { // special case with nullptr return base::isEqualTo(pointer); } /** * @brief Compares the object with the one stored in the memory. * * @return true if objects are equal, false otherwise */ friend bool operator==(const T* pointer, const LockedMemory<T>& lm) { return lm.operator==(pointer); } /** * @brief Casts stored object to any provided type. * * Uses reinterpret_cast. * * @tparam S Type to be casted to * @return Casted to the given type object */ template <class S, typename = std::enable_if<std::is_pointer<S>::value>> S as() { return reinterpret_cast<S>(base::dereference()); } /** * @brief Casts stored object to any provided type. * * Uses reinterpret_cast. * * @tparam S Type to be casted to * @return Casted to the given type const object */ template <class S, typename = std::enable_if<std::is_pointer<S>::value>> const S as() const { return reinterpret_cast<S>(base::dereference()); } }; /** * @brief This class is for <void*> data and allows casting to any pointers */ template <> class LockedMemory<void> : public details::LockedMemoryBase<void> { using base = details::LockedMemoryBase<void>; public: /** * @brief A constructor * * @param ptr Pointer to IAllocator object * @param handle Handle provided by allocator * @param offsetInBytes Offset in originally locked region */ LockedMemory(IAllocator* ptr, void* handle, size_t offsetInBytes) : base(ptr, handle, LOCK_FOR_WRITE, offsetInBytes) {} /** * @brief A default copy constructor that accepts rvalue */ LockedMemory(LockedMemory<void>&&) = default; /** * @brief A default copy constructor that accepts rvalue * * Also sets the offset value for the new memory object * * @param that Rvalue reference for the other LockedMemoryBase instance * @param offset Offset value */ LockedMemory(LockedMemory<void>&& that, size_t offset): base(std::move(that)) { base::_offset = offset; } /** * @brief A disabled copy constructor for lvalue */ LockedMemory(const LockedMemory<void>&) = delete; /** * @brief Gets the pointer to the stored object of the given template type * * Dereferences from the base class. * * @tparam S Type to be casted to * @return The pointer to the object of the given template type */ template <class S> operator S*() { return reinterpret_cast<S*>(base::dereference()); } /** * @brief Compares stored object with the given one * * @return true if objects are equal, false otherwise */ bool operator==(const void* pointer) const { // special case with nullptr return base::isEqualTo(pointer); } /** * @brief Compares the object with the one stored in the memory * * @return true if objects are equal, false otherwise */ friend bool operator==(const void* pointer, const LockedMemory<void>& lm) { return lm.operator==(pointer); } /** * @brief Casts stored object to any given type * * Uses reinterpret_cast. * * @tparam S Type to be casted to * @return Casted to the given type object */ template <class S, typename = std::enable_if<std::is_pointer<S>::value>> S as() { return reinterpret_cast<S>(dereference()); } /** * @brief Casts stored object to any given type * * Uses reinterpret_cast. * * @tparam S Type to be casted to * @return Casted to the given type const object */ template <class S, typename = std::enable_if<std::is_pointer<S>::value>> const S as() const { return reinterpret_cast<S>(dereference()); } }; /** * @brief This class is for read-only segments */ template <class T> class LockedMemory<const T> : public details::LockedMemoryBase<T> { using base = details::LockedMemoryBase<T>; public: /** * @brief A constructor * * @param ptr Pointer to IAllocator object * @param handle Handle provided by allocator * @param offsetInBytes Offset in originally locked region */ LockedMemory(IAllocator* ptr, void* handle, size_t offset): base(ptr, handle, LOCK_FOR_READ, offset) {} /** * @brief A default copy constructor that accepts rvalue */ LockedMemory(LockedMemory<const T>&&) = default; /** * @brief A default copy constructor that accepts rvalue. * * Also sets the offset value for the new memory object * * @param that Rvalue reference for the other LockedMemoryBase instance * @param offset Offset value */ LockedMemory(LockedMemory<const T>&& that, size_t offset): base(std::move(that)) { base::_offset = offset; } /** * @brief A disabled copy constructor for lvalue */ LockedMemory(const LockedMemory<const T>&) = delete; /** * @brief Gets the const pointer to the stored object * * Dereferences from the base class. * * @return The pointer to the object. */ operator const T*() const { return base::dereference(); } /** * @brief Compares stored object with the given one * * @return true if objects are equal, false otherwise */ bool operator==(const T* pointer) const { // special case with nullptr return base::isEqualTo(pointer); } /** * @brief Compares the object with the one stored in the memory * * @return true if objects are equal, false otherwise */ friend bool operator==(const T* pointer, const LockedMemory<const T>& lm) { return lm.operator==(pointer); } /** * @brief Casts stored object to any given type. * * Uses reinterpret_cast. * * @tparam S Type to be casted to * @return Casted to the given type object */ template <class S, typename = std::enable_if<std::is_pointer<S>::value && std::is_const<S>::value>> S as() const { return reinterpret_cast<S>(base::dereference()); } }; } // namespace InferenceEngine
27.65404
112
0.622592
[ "object" ]
fde4d4790c92efde970ee8d43407dc0b63b4707d
86,582
cxx
C++
src/tools.cxx
naver/tamgu
9532edc82aa90f7610dbd98dc379e0631de4b252
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
192
2019-07-10T15:47:11.000Z
2022-03-10T09:26:31.000Z
src/tools.cxx
naver/tamgu
9532edc82aa90f7610dbd98dc379e0631de4b252
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
5
2019-10-01T13:17:28.000Z
2021-01-05T15:31:39.000Z
src/tools.cxx
naver/tamgu
9532edc82aa90f7610dbd98dc379e0631de4b252
[ "BSD-3-Clause-Clear", "BSD-3-Clause" ]
14
2019-09-23T03:39:59.000Z
2021-09-02T12:20:14.000Z
/* * Tamgu (탐구) * * Copyright 2019-present NAVER Corp. * under BSD 3-clause */ /* --- CONTENTS --- Project : Tamgu (탐구) Version : See tamgu.cxx for the version number filename : tools.cxx Date : 2017/09/01 Purpose : Programmer : Claude ROUX (claude.roux@naverlabs.com) Reviewer : */ #ifdef WIN32 #include "Windows.h" #endif #include "codeparse.h" #include "tamgu.h" #include "compilecode.h" #include "tamgustring.h" #include "tamguvector.h" #include "tamguivector.h" #include "tamgufvector.h" #include "tamgusvector.h" #include "tamguuvector.h" #include "tamgubvector.h" #include "tamgudvector.h" #include "tamgumap.h" #include "tamguprimemap.h" #include "tamguprimemapss.h" #include "tamguversion.h" #include "tamgulvector.h" #include "tamguhvector.h" #include "tamguautomaton.h" #include "tamgulisp.h" #include "x_tokenize.h" #ifdef UNIX #include <unistd.h> #include <dlfcn.h> #include <signal.h> #include <termios.h> #include <sys/time.h> #endif #ifdef WIN32 #include <io.h> #define DUP _dup #define DUP2 _dup2 #define FILENO _fileno #else #define FILENO fileno #define DUP dup #define DUP2 dup2 #endif //--------------------------------------------------------- #ifdef WIN32 bool errorsprintf = false; void wrongSprintf(const wchar_t* expression, const wchar_t* function, const wchar_t* file, unsigned int line, uintptr_t pReserved) { errorsprintf = true; } #endif const char ANTISEP = '\\'; #ifdef WIN32 const char SEP = '\\'; #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #define DELTA_EPOCH_IN_MICROSECS 11644473600000000Ui64 #else #define DELTA_EPOCH_IN_MICROSECS 11644473600000000ULL #endif //Note: copied from: https://stackoverflow.com/questions/10905892/equivalent-of-gettimeday-for-windows long gettimeofday(struct timeval *tv, struct timezone *tz) { FILETIME ft; unsigned __int64 tmpres = 0; if (NULL != tv) { GetSystemTimeAsFileTime(&ft); tmpres |= ft.dwHighDateTime; tmpres <<= 32; tmpres |= ft.dwLowDateTime; /*converting file time to unix epoch*/ tmpres -= DELTA_EPOCH_IN_MICROSECS; tmpres /= 10; /*convert into microseconds*/ tv->tv_sec = (long)(tmpres / 1000000UL); tv->tv_usec = (long)(tmpres % 1000000UL); } return 0; } #endif #ifdef UNIX const char SEP = '/'; #endif //----------------------------------------------------------------------------------- unsigned long long Hashkey(string& s) { return std::use_facet<std::collate<char> >(loc).hash(s.data(), s.data() + s.length()); } unsigned long long Hashkey(wstring& s) { return std::use_facet<std::collate<wchar_t> >(loc).hash(s.data(), s.data() + s.length()); } //----------------------------------------------------------------------------------- char* convertir(char* res) { string conversion = conversion_latin_to_utf8(res); char* r = (char*)malloc(conversion.size() + 1); strcpy(r, STR(conversion)); return r; } //----------------------------------------------------------------------------------- double plustime(timeval& tempsinitial, timeval& tempsfinal) { double init = (((unsigned long)tempsinitial.tv_sec) * 1000 + ((unsigned long)tempsinitial.tv_usec) / 1000.0) + 0.5; double final = (((unsigned long)tempsfinal.tv_sec) * 1000 + ((unsigned long)tempsfinal.tv_usec) / 1000.0) + 0.5; return(final + init); } double minustime(timeval& tempsfinal, timeval& tempsinitial) { double init = (((unsigned long)tempsinitial.tv_sec) * 1000 + ((unsigned long)tempsinitial.tv_usec) / 1000.0); double final = (((unsigned long)tempsfinal.tv_sec) * 1000 + ((unsigned long)tempsfinal.tv_usec) / 1000.0); return(final - init); } long timeminus(double init, timeval& tempsfinal) { double final = (((unsigned long)tempsfinal.tv_sec) * 1000 + ((unsigned long)tempsfinal.tv_usec) / 1000.0); return(final - init); } //--------------------------------------------------------- static bool tamgurestrandom = false; static ThreadLock randomlock; double localrandom(long mx) { if (!mx) mx = 1; static unsigned long x = 123456789; static unsigned long y = 362436069; static unsigned long z = 521288629; static long w = time(0); unsigned long t; if (tamgurestrandom) { w = time(0); tamgurestrandom = false; } Locking _lock(randomlock); t = x ^ (x << 11); x = y; y = z; z = w; w = w ^ (w >> 19) ^ (t ^ (t >> 8)); return abs(w%mx); } double a_localrandom(long mx) { if (!mx) mx = 1; static unsigned long x = 123456789; static unsigned long y = 362436069; static unsigned long z = 521288629; static long w = time(0); unsigned long t; if (tamgurestrandom) { w = time(0); tamgurestrandom = false; } t = x ^ (x << 11); x = y; y = z; z = w; w = w ^ (w >> 19) ^ (t ^ (t >> 8)); return abs(w%mx); } //--------------------------------------------------------- bool IsLong(BLONG v) { if (v < -2147483647 || v > 2147483647) return true; return false; } bool IsShort(BLONG v) { if (v < -32768 || v > 32767) return false; return true; } //--------------------------------------------------------- bool v_comma_split_string(string& thestr, vector<string>& v) { size_t sz = thestr.size() - 1; if (thestr[0] != '[' || thestr[sz] != ']') return false; if (sz == 1) return true; size_t pos; bool comma = true; string value; uchar c, nxt; for (pos = 1; pos < sz; pos++) { c = thestr[pos]; if (c <= 32) continue; if (c == ',') { if (comma) { return false; } comma = true; continue; } if (!comma) return false; comma = false; if (c != '"' && c != 39 && c != '@') return false; if (c == '@') { nxt = '"'; if (thestr[++pos] != '"') { return false; } } else nxt = c; value = ""; pos++; while (pos < sz && thestr[pos] != nxt) value += thestr[pos++]; if (pos == sz) { return false; } if (c == '@') { if (thestr[++pos] != '@') { return false; } } v.push_back(value); } if (comma) { return false; } return true; } bool v_comma_split_string(wstring& thestr, vector<wstring>& v) { size_t sz = thestr.size() - 1; if (thestr[0] != '[' || thestr[sz] != ']') return false; if (sz == 1) return true; size_t pos; bool comma = true; wstring value; wchar_t c, nxt; for (pos = 1; pos < sz; pos++) { c = thestr[pos]; if (c <= 32) continue; if (c == ',') { if (comma) { return false; } comma = true; continue; } if (!comma) return false; comma = false; if (c != '"' && c != 39 && c != '@') { return false; } if (c == '@') { nxt = '"'; if (thestr[++pos] != '"') { return false; } } else nxt = c; value = L""; pos++; while (pos < sz && thestr[pos] != nxt) value += thestr[pos++]; if (pos == sz) { return false; } if (c == '@') { if (thestr[++pos] != '@') { return false; } } v.push_back(value); } if (comma) { return false; } return true; } #define isdigit(c) (c >= '0' && c <= '9') bool v_comma_split_decimal(string& thestr, vector<float>& v) { size_t sz = thestr.size() - 1; if (thestr[0] != '[' || thestr[sz] != ']') return false; if (sz == 1) return true; size_t pos; bool comma = true; float d; short l; uchar c; for (pos = 1; pos < sz; pos++) { c = thestr[pos]; if (c <= 32) continue; if (c == ',') { if (comma) { return false; } comma = true; continue; } if (!comma) return false; comma = false; if (c == '-' || c == '+' || isdigit(c)) { d = conversionfloathexa(STR(thestr)+pos, l); v.push_back(d); pos += l - 1; continue; } return false; } if (comma) { return false; } return true; } bool v_comma_split_float(string& thestr, vector<double>& v) { size_t sz = thestr.size() - 1; if (thestr[0] != '[' || thestr[sz] != ']') return false; if (sz == 1) return true; size_t pos; bool comma = true; double d; short l; uchar c; for (pos = 1; pos < sz; pos++) { c = thestr[pos]; if (c <= 32) continue; if (c == ',') { if (comma) { return false; } comma = true; continue; } if (!comma) return false; comma = false; if (c == '-' || c == '+' || isdigit(c)) { d = conversionfloathexa(STR(thestr)+pos, l); v.push_back(d); pos += l - 1; continue; } return false; } if (comma) { return false; } return true; } bool v_comma_split_int(string& thestr, vector<long>& v) { size_t sz = thestr.size() - 1; if (thestr[0] != '[' || thestr[sz] != ']') return false; if (sz == 1) return true; size_t pos; bool comma = true; long d; short l; uchar c; for (pos = 1; pos < sz; pos++) { c = thestr[pos]; if (c <= 32) continue; if (c == ',') { if (comma) { return false; } comma = true; continue; } if (!comma) return false; comma = false; if (c == '-' || c == '+' || isdigit(c)) { d = conversionfloathexa(STR(thestr)+pos, l); v.push_back(d); pos += l - 1; continue; } return false; } if (comma) { return false; } return true; } bool v_comma_split_long(string& thestr, vector<BLONG>& v) { size_t sz = thestr.size() - 1; if (thestr[0] != '[' || thestr[sz] != ']') return false; if (sz == 1) return true; size_t pos; bool comma = true; BLONG d; short l; uchar c; for (pos = 1; pos < sz; pos++) { c = thestr[pos]; if (c <= 32) continue; if (c == ',') { if (comma) { return false; } comma = true; continue; } if (!comma) return false; comma = false; if (c == '-' || c == '+' || isdigit(c)) { d = conversionfloathexa(STR(thestr)+pos, l); v.push_back(d); pos += l - 1; continue; } return false; } if (comma) { return false; } return true; } bool v_comma_split_byte(string& thestr, vector<uchar>& v) { size_t sz = thestr.size() - 1; if (thestr[0] != '[' || thestr[sz] != ']') return false; if (sz == 1) return true; size_t pos; bool comma = true; uchar d; short l; uchar c; for (pos = 1; pos < sz; pos++) { c = thestr[pos]; if (c <= 32) continue; if (c == ',') { if (comma) { return false; } comma = true; continue; } if (!comma) return false; comma = false; if (c == '-' || c == '+' || isdigit(c)) { d = conversionfloathexa(STR(thestr)+pos, l); v.push_back(d); pos += l - 1; continue; } return false; } if (comma) { return false; } return true; } bool v_comma_split_short(string& thestr, vector<short>& v) { size_t sz = thestr.size() - 1; if (thestr[0] != '[' || thestr[sz] != ']') return false; if (sz == 1) return true; size_t pos; bool comma = true; short d; short l; uchar c; for (pos = 1; pos < sz; pos++) { c = thestr[pos]; if (c <= 32) continue; if (c == ',') { if (comma) { return false; } comma = true; continue; } if (!comma) return false; comma = false; if (c == '-' || c == '+' || isdigit(c)) { d = conversionfloathexa(STR(thestr)+pos, l); v.push_back(d); pos += l - 1; continue; } return false; } if (comma) { return false; } return true; } //--------------------------------------------------------------------------------------------- Tamgu* Mapcompare(Tamgu*a, Tamgu*b, TamguGlobal* global) { if (!b->isMapContainer() || a->Size() != b->Size()) return aFALSE; if (!a->Size()) return aTRUE; Tamgu* key; Tamgu* value; Tamgu* vb; Tamgu* res; Locking _lock((TamguObject*)a); TamguIteration* itr = a->Newiteration(false); for (itr->Begin(); itr->End() != aTRUE; itr->Next()) { value = itr->IteratorValue(); key = itr->IteratorKey(); res = aFALSE; switch (key->Type()) { case a_long: case a_int: vb = b->Value(key->Integer()); if (vb != aNOELEMENT) res = vb->same(value); break; case a_float: vb = b->Value(key->Float()); if (vb != aNOELEMENT) res = vb->same(value); break; default: vb = b->Value(key->String()); if (vb != aNOELEMENT) res = vb->same(value); } vb->Release(); if (res == aFALSE) { itr->Release(); return aFALSE; } } itr->Release(); return aTRUE; } //--------------------------------------------------------------------------- #ifdef WSTRING_IS_UTF16 long checkemoji(wstring& svalue, long i) { if ((svalue[i] & 0xFF00) == 0xD800) { TAMGUCHAR c = getachar(svalue, i); if (((c & 0x1F000) == 0x1F000) && c_is_emoji(c)) { long j = i + 1; c = getachar(svalue, j); while (c_is_emojicomp(c)) { j++; c = getachar(svalue, j); } i = j; } } return i; } Exporting char StringIndexes(wstring& svalue, Tamgu* index, long& ileft, long& iright, short idthread) { wstring sub; Tamgu* left = index; Tamgu* right = NULL; long sz = svalue.size(); //On Windows wstring are encoded in UTF16 //We need to check for large UTF16 characters (on 4 bytes) long pivot = -1; long szchar = size_w(svalue, pivot); bool sleft = false; bool sright = false; bool releft = false; bool reright = false; iright = -1; if (index->isIndex()) { TamguIndex* kind = (TamguIndex*)index; sleft = kind->signleft; sright = kind->signright; if (kind->isConst()) { left = kind->left; right = kind->right; } else { left = kind->left->Eval(aNULL, aNULL, idthread); if (left != kind->left) releft = true; if (kind->interval == true) { right = kind->right->Eval(aNULL, aNULL, idthread); if (right != kind->right) reright = true; } } } if (left->isRegular()) { //this is a regular expression... if (sleft) { //we need the last one... if (!left->searchlast(svalue, ileft, iright)) return 0; } else { if (!left->search(svalue, ileft, iright)) return 0; } } else { if (left->isString()) { left->Setstring(sub, idthread); if (releft) left->Release(); //then we are looking for a substring if (sleft) ileft = s_rfind(svalue, sub, sz); else ileft = s_find(svalue, sub, 0); if (ileft == -1) return 0; iright = ileft + sub.size(); } else { ileft = left->Integer(); if (releft) left->Release(); if (pivot == -1) { if (ileft < 0) ileft += sz; if (ileft >= sz) return 0; } else { //We have to take into account a large UTF16 character if (ileft < 0) ileft += szchar; if (ileft >= szchar) return 0; if (ileft >= pivot) ileft = convertchartoposutf16(svalue, pivot, ileft); } if (ileft < 0) ileft = 0; } } //We return as a non interval if (right == NULL) { if (iright != -1) return 2; if (pivot != -1) { iright = checkemoji(svalue, ileft); if (iright != ileft) return 2; } return 1; } if (right->isRegular()) { //this is a regular expression... long r = iright; if (sright) { //we need the last one... if (!right->searchlast(svalue, r, iright, r)) return 0; } else { if (!right->search(svalue, r, iright, r)) return 0; } if (iright < ileft) return 0; return 2; } if (right->isString()) { right->Setstring(sub, idthread); if (reright) right->Release(); if (sright) { iright = s_rfind(svalue, sub, sz); if (iright < ileft) return 0; } else { if (iright != -1) iright = s_find(svalue, sub, iright); else iright = s_find(svalue, sub, ileft); } if (iright == -1) return 0; iright += sub.size(); return 2; } if (iright == -1) {//absolute position iright = right->Integer(); if (reright) right->Release(); if (iright < 0 || right == aNULL) { iright += szchar; if (iright < 0) return 0; } if (iright >= szchar) iright = sz; else { if (pivot != -1 && pivot < iright) { iright = convertchartoposutf16(svalue, pivot, iright); if (iright < ileft) return 0; } } return 2; } long shift; //this is a shift if (right == aNULL) iright = sz; else { shift = right->Integer(); if (reright) right->Release(); if (iright > pivot) iright = convertpostocharutf16(svalue, pivot, iright) + shift; else iright += shift; if (iright > pivot) //This is position compared to the end of the string //First we need to transform shift in bytes iright = convertchartoposutf16(svalue, pivot, iright); } if (iright >= szchar) iright = sz; else if (iright < ileft) return 0; return 2; } #else //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // UTF32 version //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- long char_to_pos_emoji(wstring& w, long& ileft, long emoji) { //emoji is the position of the first emoji in the string long sz = w.size(); while (emoji != ileft) { if (c_is_emoji(w[emoji])) { emoji++; while (c_is_emojicomp(w[emoji])) { emoji++; ileft++; } } else emoji++; } if (emoji < sz && c_is_emoji(w[emoji])) { emoji++; while (emoji < sz && c_is_emojicomp(w[emoji])) { emoji++; } } else emoji++; return emoji; } Exporting char StringIndexes(wstring& svalue, Tamgu* index, long& ileft, long& iright, short idthread) { wstring sub; Tamgu* left = index; Tamgu* right = NULL; long emoji = -1; long sz = size_c(svalue, emoji); bool sleft = false; bool sright = false; bool releft = false; bool reright = false; iright = -1; if (index->isIndex()) { TamguIndex* kind = (TamguIndex*)index; sleft = kind->signleft; sright = kind->signright; if (kind->isConst()) { left = kind->left; right = kind->right; } else { left = kind->left->Eval(aNULL, aNULL, idthread); if (left != kind->left) releft = true; if (kind->interval == true) { right = kind->right->Eval(aNULL, aNULL, idthread); if (right != kind->right) reright = true; } } } if (left->isRegular()) { //this is a regular expression... if (sleft) { //we need the last one... if (!left->searchlast(svalue, ileft, iright)) return 0; } else { if (!left->search(svalue, ileft, iright)) return 0; } } else { if (left->isString()) { left->Setstring(sub, idthread); if (releft) left->Release(); //then we are looking for a substring if (sleft) ileft = s_rfind(svalue, sub, sz); else ileft = s_find(svalue, sub, 0); if (ileft == -1) return 0; iright = ileft + sub.size(); } else { ileft = left->Integer(); if (releft) left->Release(); if (ileft < 0) ileft += sz; if (ileft >= sz) return 0; if (ileft < 0) ileft = 0; } } //We return as a non interval if (right == NULL) { if (iright != -1) return 2; if (emoji != -1 && ileft >= emoji) { iright = char_to_pos_emoji(svalue, ileft, emoji); return 2; } return 1; } if (right->isRegular()) { //this is a regular expression... long r = iright; if (sright) { //we need the last one... if (!right->searchlast(svalue, r, iright, r)) return 0; } else { if (!right->search(svalue, r, iright, r)) return 0; } if (iright < ileft) return 0; return 2; } if (right->isString()) { right->Setstring(sub, idthread); if (reright) right->Release(); if (sright) { iright = s_rfind(svalue, sub, sz); if (iright < ileft) return 0; } else { if (iright != -1) iright = s_find(svalue, sub, iright); else iright = s_find(svalue, sub, ileft); } if (iright == -1) return 0; iright += sub.size(); return 2; } if (iright == -1) {//absolute position iright = right->Integer(); if (reright) right->Release(); if (iright < 0 || right == aNULL) iright += sz; } else { //this is a shift if (right == aNULL) iright = sz; else iright += right->Integer(); } if (emoji != -1) { if (ileft >= emoji) char_to_pos_emoji(svalue, ileft, emoji); if (iright > sz) iright = sz; if (iright >= emoji) char_to_pos_emoji(svalue, iright, emoji); if (iright < ileft) return 0; return 2; } if (iright > sz) iright = sz; else if (iright < ileft) return 0; return 2; } #endif //--------------------------------------------------------------------------- long char_to_byteposition(unsigned char* contenu, long sz, long i, long charpos) { charpos-=i; long nb; while (charpos > 0 && i < sz) { nb = c_test_utf8(contenu + i); if (nb == 3 && c_is_emoji(contenu,i)) { i++; while (c_is_emojicomp(contenu, i)) { i++; } } else i += nb + 1; charpos--; } return i; } long char_to_byteposition(unsigned char* contenu, long sz, long i, long charpos, long& emoji) { emoji = -1; charpos-=i; long nb; while (charpos > 0 && i < sz) { nb = c_test_utf8(contenu + i); if (nb == 3 && c_is_emoji(contenu,i)) { i++; while (c_is_emojicomp(contenu, i)) { i++; } } else i += nb + 1; charpos--; } if (c_test_utf8(contenu+i) == 3) { long ii = i; if (c_is_emoji(contenu,ii)) { ii++; while (c_is_emojicomp(contenu, ii)) { ii++; emoji = ii; } } } return i; } Exporting char StringIndexes(string& svalue, Tamgu* index, long& ileft, long& iright, short idthread) { string sub; Tamgu* left = index; Tamgu* right = NULL; long sz = -1, szc = -1, pivot = -1, emoji = -1; char utf8 = 0; char clean = 0; bool sleft = false; bool sright = false; iright = -1; if (index->isIndex()) { TamguIndex* kind = (TamguIndex*)index; sleft = kind->signleft; sright = kind->signright; if (kind->isConst()) { left = kind->left; right = kind->right; } else { left = kind->left->Eval(aNULL, aNULL, idthread); if (left != kind->left) clean = 1; if (kind->interval == true) { right = kind->right->Eval(aNULL, aNULL, idthread); if (right != kind->right) clean |= 2; } } } if (left->isRegular()) { //this is a regular expression... if (sleft) { //we need the last one... if (!left->searchlast(svalue, ileft, iright)) return 0; } else { if (!left->search(svalue, ileft, iright)) return 0; } } else { sz = svalue.size(); if (left->isString()) { left->Setstring(sub, idthread); if ((clean & 1)==1) left->Release(); //then we are looking for a substring if (sleft) ileft = s_rfindbyte(svalue, sub, sz); else ileft = s_findbyte(svalue, sub, 0); if (ileft == -1) return 0; iright = ileft + sub.size(); } else { ileft = left->Integer(); if ((clean & 1)==1) left->Release(); //This is a tricky case... ileft is in character position not bytes szc = size_c(USTR(svalue), sz, pivot); if (pivot == -1) utf8 = 1; else utf8 = 2; //to mark that we have computed it... if (ileft <0) { //This a position from the end... //We need to compute the size in characters to the size in bytes... if (utf8 == 2) { ileft += szc; if (ileft < 0) ileft = 0; else { if (ileft >= pivot) // the pivot is the first UTF8 element slot in characters ileft = char_to_byteposition(USTR(svalue), sz, pivot, ileft, emoji); } } else { ileft += sz; if (ileft < 0) ileft = 0; } } else { if (ileft > szc) ileft = sz; else { if (utf8 == 2 && ileft >= pivot) ileft = char_to_byteposition(USTR(svalue), sz, pivot, ileft, emoji); } } } } //We return as a non interval if (right == NULL) { if (iright == -1) { if (ileft < emoji) { iright = emoji; return 2; } return 1; } return 2; } if (right->isRegular()) { //this is a regular expression... long r = iright; if (sright) { //we need the last one... if (!right->searchlast(svalue, r, iright, r)) return 0; } else { if (!right->search(svalue, r, iright, ileft)) return 0; } if (iright < ileft) return 0; return 2; } if (sz == -1) sz = svalue.size(); if (right->isString()) { right->Setstring(sub, idthread); if ((clean & 2)==2) right->Release(); if (sright) { iright = s_rfindbyte(svalue, sub, sz); if (iright < ileft) return 0; } else { if (iright == -1) iright = s_findbyte(svalue, sub, ileft); else iright = s_findbyte(svalue, sub, iright); } if (iright == -1) return 0; iright += sub.size(); return 2; } if (!utf8) { //we need to compute them szc = size_c(USTR(svalue), sz, pivot); if (pivot == -1) utf8 = 1; else utf8 = 2; } //Now we have two cases... //First, this is a pure integer interval, in that case, iright is the absolute position if (iright == -1) { iright = right->Integer(); if ((clean & 2)==2) right->Release(); if (iright < 0 || right == aNULL) { if (utf8 == 2) { //This is position compared to the end of the string iright += szc; if (iright <= 0) return 0; if (iright > pivot) { iright = char_to_byteposition(USTR(svalue), sz, pivot, iright); } } else iright += sz; } else { if (iright > szc) iright = sz; else { if (utf8 == 2 && iright > pivot) { iright = char_to_byteposition(USTR(svalue), sz, pivot, iright); } } } if (iright < ileft) return 0; return 2; } long shift = right->Integer(); if ((clean & 2)==2) right->Release(); if (shift < 0) return 0; if (right == aNULL) iright = sz; else { if (utf8 == 2) { if (iright > pivot) iright = c_bytetocharposition(USTR(svalue), iright)+shift; else iright += shift; if (iright > pivot) { //This is position compared to the end of the string //First we need to transform shift in bytes iright = char_to_byteposition(USTR(svalue), sz, pivot, iright); } } else iright += shift; } if (iright > sz) iright = sz; else if (iright < ileft) return 0; return 2; } Exporting char StringIndexes(uchar* svalue, long sz, Tamgu* index, long& ileft, long& iright, short idthread) { string sub; Tamgu* left = index; Tamgu* right = NULL; long szc = -1, pivot = -1, emoji = -1; char utf8 = 0; char clean = 0; bool sleft = false; bool sright = false; iright = -1; if (index->isIndex()) { TamguIndex* kind = (TamguIndex*)index; sleft = kind->signleft; sright = kind->signright; if (kind->isConst()) { left = kind->left; right = kind->right; } else { left = kind->left->Eval(aNULL, aNULL, idthread); if (left != kind->left) clean = 1; if (kind->interval == true) { right = kind->right->Eval(aNULL, aNULL, idthread); if (right != kind->right) clean |= 2; } } } if (left->isRegular()) { //this is a regular expression... sub = (char*)svalue; if (sleft) { //we need the last one... if (!left->searchlast(sub, ileft, iright)) return 0; } else { if (!left->search(sub, ileft, iright)) return 0; } } else { if (left->isString()) { left->Setstring(sub, idthread); if ((clean & 1)==1) left->Release(); //then we are looking for a substring if (sleft) ileft = s_rfindbyte(svalue, sz, sub, sz); else ileft = s_findbyte(svalue, sz, sub, 0); if (ileft == -1) return 0; iright = ileft + sub.size(); } else { ileft = left->Integer(); if ((clean & 1)==1) left->Release(); //This is a tricky case... ileft is in character position not bytes szc = size_c(svalue, sz, pivot); if (pivot == -1) utf8 = 1; else utf8 = 2; //to mark that we have computed it... if (ileft <0) { //This a position from the end... //We need to compute the size in characters to the size in bytes... if (utf8 == 2) { ileft += szc; if (ileft < 0) ileft = 0; else { if (ileft >= pivot) // the pivot is the first UTF8 element slot in characters ileft = char_to_byteposition(svalue, sz, pivot, ileft, emoji); } } else { ileft += sz; if (ileft < 0) ileft = 0; } } else { if (ileft > szc) ileft = sz; else { if (utf8 == 2 && ileft >= pivot) ileft = char_to_byteposition(svalue, sz, pivot, ileft, emoji); } } } } //We return as a non interval if (right == NULL) { if (iright == -1) { if (ileft < emoji) { iright = emoji; return 2; } return 1; } return 2; } if (right->isRegular()) { //this is a regular expression... long r = iright; sub = (char*)svalue; if (sright) { //we need the last one... if (!right->searchlast(sub, r, iright, r)) return 0; } else { if (!right->search(sub, r, iright, ileft)) return 0; } if (iright < ileft) return 0; return 2; } if (right->isString()) { right->Setstring(sub, idthread); if ((clean & 2)==2) right->Release(); if (sright) { iright = s_rfindbyte(svalue, sz, sub, sz); if (iright < ileft) return 0; } else { if (iright == -1) iright = s_findbyte(svalue, sz, sub, ileft); else iright = s_findbyte(svalue, sz, sub, iright); } if (iright == -1) return 0; iright += sub.size(); return 2; } if (!utf8) { //we need to compute them szc = size_c(svalue, sz, pivot); if (pivot == -1) utf8 = 1; else utf8 = 2; } //Now we have two cases... //First, this is a pure integer interval, in that case, iright is the absolute position if (iright == -1) { iright = right->Integer(); if ((clean & 2)==2) right->Release(); if (iright < 0 || right == aNULL) { if (utf8 == 2) { //This is position compared to the end of the string iright += szc; if (iright <= 0) return 0; if (iright > pivot) { iright = char_to_byteposition(svalue, sz, pivot, iright); } } else iright += sz; } else { if (iright > szc) iright = sz; else { if (utf8 == 2 && iright > pivot) { iright = char_to_byteposition(svalue, sz, pivot, iright); } } } if (iright < ileft) return 0; return 2; } long shift = right->Integer(); if ((clean & 2)==2) right->Release(); if (shift < 0) return 0; if (right == aNULL) iright = sz; else { if (utf8 == 2) { if (iright > pivot) iright = c_bytetocharposition(svalue, iright)+shift; else iright += shift; if (iright > pivot) { //This is position compared to the end of the string //First we need to transform shift in bytes iright = char_to_byteposition(svalue, sz, pivot, iright); } } else iright += shift; } if (iright > sz) iright = sz; else if (iright < ileft) return 0; return 2; } //--------------------------------------------------------- unsigned long StringEditDistance(wstring& value, wstring& s2) { unsigned long s1len, s2len, x, y, lastdiag, olddiag; s1len = value.size(); s2len = s2.size(); size_t* column = new size_t[s1len + 1]; for (y = 1; y <= s1len; y++) column[y] = y; for (x = 1; x <= s2len; x++) { column[0] = x; for (y = 1, lastdiag = x - 1; y <= s1len; y++) { olddiag = column[y]; column[y] = MIN3(column[y] + 1, column[y - 1] + 1, lastdiag + (value[y - 1] == s2[x - 1] ? 0 : 1)); lastdiag = olddiag; } } s2len = column[s1len]; delete[] column; return s2len; } unsigned long StringEditDistance(string& value, string& s2) { unsigned long s1len, s2len, x, y, lastdiag, olddiag; s1len = value.size(); s2len = s2.size(); size_t* column = new size_t[s1len + 1]; for (y = 1; y <= s1len; y++) column[y] = y; for (x = 1; x <= s2len; x++) { column[0] = x; for (y = 1, lastdiag = x - 1; y <= s1len; y++) { olddiag = column[y]; column[y] = MIN3(column[y] + 1, column[y - 1] + 1, lastdiag + (value[y - 1] == s2[x - 1] ? 0 : 1)); lastdiag = olddiag; } } s2len = column[s1len]; delete[] column; return s2len; } string StringXor(string value, string s) { string u; long m = minlocal(s.size(), value.size()); for (long i = 0; i < m; i++) { if (s[i] != value[i]) u += value[i]; } return u; } wstring StringXor(wstring value, wstring s) { wstring u; long m = minlocal(s.size(), value.size()); for (long i = 0; i < m; i++) { if (s[i] != value[i]) u += value[i]; } return u; } string StringAnd(string value, string s) { string u; long m = minlocal(s.size(), value.size()); for (long i = 0; i < m; i++) { if (s[i] == value[i]) u += s[i]; } return u; } wstring StringAnd(wstring value, wstring s) { wstring u; long m = minlocal(s.size(), value.size()); for (long i = 0; i < m; i++) { if (s[i] == value[i]) u += s[i]; } return u; } string StringOr(string value, string s) { return value + s; } wstring StringOr(wstring value, wstring s) { return value + s; } string StringMinus(string v, string sub) { size_t pos = v.find(sub); if (pos == string::npos) return v; size_t nb = sub.size(); //we keep our string up to p sub = v.substr(0, pos); //then we skip the nb characters matching the size of v pos += nb; //then we concatenate with the rest of the string sub += v.substr(pos, v.size() - pos); return sub; } wstring StringMinus(wstring v, wstring sub) { size_t pos = v.find(sub); if (pos == wstring::npos) return v; size_t nb = sub.size(); //we keep our wstring up to p sub = v.substr(0, pos); //then we skip the nb characters matching the size of v pos += nb; //then we concatenate with the rest of the wstring sub += v.substr(pos, v.size() - pos); return sub; } //--------------------------------------------------------- double DoubleAnd(double value, double l) { double64 d(value); double64 dl(value); d.bits &= dl.bits; return d.v; } double DoubleOr(double value, double l) { double64 d(value); double64 dl(value); d.bits |= dl.bits; return d.v; } double DoubleXor(double value, double l) { double64 d(value); double64 dl(value); d.bits ^= dl.bits; return d.v; } double DoubleShiftleft(double value, long l) { double64 d(value); d.bits <<= l; return d.v; } double DoubleShiftright(double value, long l) { double64 d(value); d.bits >>= l; return d.v; } float FloatAnd(float value, float l) { float32 d(value); float32 dl(value); d.bits &= dl.bits; return d.v; } float FloatOr(float value, float l) { float32 d(value); float32 dl(value); d.bits |= dl.bits; return d.v; } float FloatXor(float value, float l) { float32 d(value); float32 dl(value); d.bits ^= dl.bits; return d.v; } float FloatShiftleft(float value, long l) { float32 d(value); d.bits <<= l; return d.v; } float FloatShiftright(float value, long l) { float32 d(value); d.bits >>= l; return d.v; } //--------------------------------------------------------- void convertbytepositiontochar(vector<long>& v, agnostring& s) { vector<long> vres; long i = 0; long r = 0; for (long j = 0; j < v.size(); j++) { c_bytetocharpositionidx(USTR(s), v[j], r, i); vres.push_back(r); } v = vres; } void convertbytepositiontochar(vector<double>& v, agnostring& s) { vector<double> vres; long i = 0; long r = 0; for (long j = 0; j < v.size(); j++) { c_bytetocharpositionidx(USTR(s), v[j], r, i); vres.push_back(r); } v = vres; } //--------------------------------------------------------- void XNBrowse(x_node* xn, Tamgu* kf) { if (xn == NULL) return; Tamguprimemap* kmap = new Tamguprimemap; kf->Push(kmap); if (xn->nodes.size()) { string key = xn->token; if (xn->value != "") key += "_" + xn->value; Tamguvector* kvect = globalTamgu->Providevector(); kmap->Push(key, kvect); for (size_t i = 0; i < xn->nodes.size(); i++) { XNBrowse(xn->nodes[i], kvect); } } else kmap->Push(xn->token, globalTamgu->Providestring(xn->value)); } //--------------------------------------------------------- Exporting Tamgu* Selectaprimemapss(Tamgu* context) { if (context->Type()==Tamguprimemapss::idtype && context->isAffectation()) { context->Clear(); return context; } return new Tamguprimemapss; } Exporting Tamgu* SelectContainer(Tamgu* context, short idthread) { if (context->isContainer()) { if(context->isAffectation()) { context->Clear(); return context; } return context->Newinstance(idthread); } return NULL; } Exporting Tamgu* Selectacontainer(Tamgu* context, short idthread) { if (context->isContainer()) { if (context->isAffectation()) { context->Clear(); return context; } return context->Newinstance(idthread); } return globalTamgu->Providevector(); } Exporting Tamgu* Selectamap(Tamgu* context) { if (context->isMapContainer() && context->isAffectation()) { context->Clear(); return context; } return globalTamgu->Providemap(); } Exporting Tamgu* Selectavector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation()) { context->Clear(); return context; } return globalTamgu->Providevector(); } Exporting Tamgu* SelectaVector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_vector) { context->Clear(); return context; } return globalTamgu->Providevector(); } Exporting Tamgu* Selectasvector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_svector) { context->Clear(); return context; } return globalTamgu->Providesvector(); } Exporting Tamgu* Selectauvector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_uvector) { context->Clear(); return context; } return globalTamgu->Provideuvector(); } Exporting Tamgu* Selectaivector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_ivector) { context->Clear(); return context; } return globalTamgu->Provideivector(); } Exporting Tamgu* Selectahvector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_hvector) { context->Clear(); return context; } return new Tamguhvector; } Exporting Tamgu* Selectalvector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_lvector) { context->Clear(); return context; } return new Tamgulvector; } Exporting Tamgu* Selectadvector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_dvector) { context->Clear(); return context; } return new Tamgudvector; } Exporting Tamgu* Selectafvector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_fvector) { context->Clear(); return context; } return globalTamgu->Providefvector(); } Exporting Tamgu* Selectabvector(Tamgu* context) { if (context->isVectorContainer() && context->isAffectation() && context->Type() == a_bvector) { context->Clear(); return context; } return new Tamgubvector; } //-------------------------------------------------------------------- Exporting Tamgu* TamguGlobal::EvaluateParenthetic(string& s, string& o, string& c, bool comma, bool separator, bool keeprc, vector<string>& rules, short idthread) { x_tokenize xr; bnf_tamgu bnf; threads[idthread].message.str(""); threads[idthread].message.clear(); if (rules.size()==0) xr.load(); else { xr.resetrules(rules); xr.rules = rules; string mess; if (!xr.parseexternalrules(mess)) return globalTamgu->Returnerror(mess, idthread); xr.loaded=true; } if (comma) xr.selectcomma(true); else xr.selectcomma(false); if (keeprc) xr.keeprc(true); else xr.keeprc(false); if (separator) xr.separator(true); else xr.separator(false); xr.tokenize(s); bnf.initialize(&xr); bnf.baseline = linereference; bnf_tamgu* previous = currentbnf; currentbnf = &bnf; string lret; x_node* xn = new x_node; bnf.Y_var_0 = o[0]; bnf.Y_var_1 = c[0]; if (bnf.m_parenthetique(lret, &xn) != 1 || bnf.currentpos != xr.stack.size()) { delete xn; stringstream& message = globalTamgu->threads[0].message; message << "Error while parsing a parenthetic expression at line: " << bnf.lineerror; return globalTamgu->Returnerror(message.str(), idthread); } Tamgu* kret = globalTamgu->Providevector(); TamguCode* code = spaces[0]; code->compilemode = false; try { code->Traverse(xn, kret); } catch (TamguRaiseError* m) { code->compilemode = true; code->global = this; kret->Release(); kret = Returnerror(m->message, idthread); delete m; } code->compilemode = true; currentbnf = previous; delete xn; return kret; } Exporting Tamgu* TamguGlobal::EvaluateTags(string& s, string& o, string& c, bool comma, bool separator, bool keeprc, vector<string>& rules, short idthread){ x_tokenize xr; bnf_tamgu bnf; threads[idthread].message.str(""); threads[idthread].message.clear(); if (rules.size()==0) xr.load(); else { xr.resetrules(rules); xr.rules = rules; string mess; if (!xr.parseexternalrules(mess)) return globalTamgu->Returnerror(mess, idthread); xr.loaded=true; } if (comma) xr.selectcomma(true); else xr.selectcomma(false); if (keeprc) xr.keeprc(true); else xr.keeprc(false); if (separator) xr.separator(true); else xr.separator(false); xr.tokenize(s); bnf.initialize(&xr); bnf.baseline = linereference; bnf_tamgu* previous = currentbnf; currentbnf = &bnf; string lret; x_node* xn = new x_node; bnf.VS_var_2 = o; bnf.VS_var_3 = c; if (bnf.m_tag(lret, &xn) != 1 || bnf.currentpos != xr.stack.size()) { delete xn; stringstream& message = globalTamgu->threads[0].message; message << "Error while parsing a TAG expression at line: " << bnf.lineerror; return globalTamgu->Returnerror(message.str(), idthread); } Tamgu* kret = globalTamgu->Providevector(); TamguCode* code = spaces[0]; code->compilemode = false; try { code->Traverse(xn, kret); } catch (TamguRaiseError* m) { code->compilemode = true; code->global = this; kret->Release(); kret = Returnerror(m->message, idthread); delete m; } code->compilemode = true; currentbnf = previous; delete xn; return kret; } Exporting An_rules* TamguGlobal::EvaluateRules(string& body, short idthread) { x_reading xr; bnf_tamgu bnf; threads[idthread].message.str(""); threads[idthread].message.clear(); bnf.initialize(&xr); bnf.baseline = linereference; bnf_tamgu* previous = currentbnf; xr.tokenize(body); if (xr.size() == 0) { stringstream message; message << "Empry string" << endl; globalTamgu->Returnerror(message.str(), idthread); return NULL; } lineerror = -1; x_node* xn = bnf.x_parsing(&xr, FULL); currentbnf = &bnf; string lret; TamguCode* code = spaces[0]; if (xn == NULL) { stringstream& message = globalTamgu->threads[0].message; globalTamgu->lineerror = bnf.lineerror; code->currentline = globalTamgu->lineerror; message << "Error while parsing string: "; if (bnf.errornumber != -1) message << bnf.x_errormsg(bnf.errornumber); else message << bnf.labelerror; globalTamgu->Returnerror(message.str(), idthread); return NULL; } Tamgu* kret = aNULL; code->compilemode = false; try { kret = code->Traverse(xn, aNULL); } catch (TamguRaiseError* m) { code->compilemode = true; code->global = this; kret->Release(); kret = Returnerror(m->message, idthread); delete m; currentbnf = previous; delete xn; return NULL; } code->compilemode = true; currentbnf = previous; delete xn; return globalTamgu->gTheAnnotationRules; } Exporting Tamgu* TamguGlobal::EvaluateLisp(Tamgu* contextualpattern, string filename, string& body, short idthread) { x_reading xr; bnf_tamgu bnf; threads[idthread].message.str(""); threads[idthread].message.clear(); if (body[0] == '(' && body[1] == ')') { body[0]='/'; body[1]='/'; } xr.lispmode = true; xr.tokenize(body); bnf.initialize(&xr); bnf.baseline = linereference; bnf_tamgu* previous = currentbnf; currentbnf = &bnf; string lret; x_node* xn = new x_node; if (bnf.m_tamgupurelisp(lret, &xn) != 1 || bnf.currentpos != xr.stack.size()) { delete xn; stringstream& message = globalTamgu->threads[0].message; message << "Error while parsing Lisp '"<< filename << "' at line: " << bnf.lineerror; return globalTamgu->Returnerror(message.str(), idthread); } Tamgu* kret = aNULL; TamguCode* code = spaces[0]; code->compilemode = false; Tamgulisp* lst = globalTamgu->Providelisp(); lst->Setreference(); try { kret = code->Traverse(xn, lst); } catch (TamguRaiseError* m) { code->compilemode = true; code->global = this; kret->Release(); kret = Returnerror(m->message, idthread); lst->Release(); delete m; } code->compilemode = true; for (long i = 0; i < lst->values.size(); i++) { if (i) kret->Release(); kret = lst->values[i]->Eval(aEMPTYLISP, aNULL, idthread); } //Specific case for lambdas, we need to protect them... kret->Setreference(); lst->Resetreference(1); kret->Protect(); currentbnf = previous; delete xn; return kret; } //------------ Container evaluation ------------------------------------- void split_container(unsigned char* src, long lensrc, vector<long>&, bool forindent); class TamguJsonCompiler { public: vector<long> pos; string token; unsigned char* src; double v; long line; long i; long r; long sz; long to; short l; uchar c; bool compile(Tamgu* kf, string& s) { pos.clear(); src = USTR(s); sz = s.size(); pos.reserve(sz >> 2); split_container(src, sz, pos, false); r = 1; i = 1; line = 0; sz = pos.size(); if (!buildexpression(kf) || r != pos.size()) return false; return true; } char buildexpression(Tamgu* kf); }; Exporting Tamgu* TamguGlobal::EvaluateVector(string& s, short idthread) { static TamguJsonCompiler jcomp_base; threads[idthread].message.str(""); threads[idthread].message.clear(); if (s[0] != '[') { stringstream msg; msg << "Wrong map definition. Expecting a vector definition"; return globalTamgu->Returnerror(msg.str(), idthread); } Tamgu* kf = globalTamgu->Providevector(); TamguJsonCompiler* jcomp = &jcomp_base; if (idthread) jcomp = new TamguJsonCompiler; if (!jcomp->compile(kf, s)) { if (idthread) delete jcomp; kf->Release(); stringstream msg; msg << "Wrong vector definition. Internal line error: " << jcomp->line; return globalTamgu->Returnerror(msg.str(), idthread); } if (idthread) delete jcomp; return kf; } Exporting Tamgu* TamguGlobal::EvaluateVector(Tamgu* kf, string& s, short idthread) { static TamguJsonCompiler jcomp_base; threads[idthread].message.str(""); threads[idthread].message.clear(); if (s[0] != '[') { stringstream msg; msg << "Wrong map definition. Expecting a vector definition"; return globalTamgu->Returnerror(msg.str(), idthread); } TamguJsonCompiler* jcomp = &jcomp_base; if (idthread) jcomp = new TamguJsonCompiler; if (!jcomp->compile(kf, s)) { if (idthread) delete jcomp; stringstream msg; msg << "Wrong vector definition. Internal line error: " << jcomp->line; return globalTamgu->Returnerror(msg.str(), idthread); } if (idthread) delete jcomp; return kf; } Exporting Tamgu* TamguGlobal::EvaluateMap(Tamgu* kf, string& s, short idthread) { static TamguJsonCompiler jcomp_base; threads[idthread].message.str(""); threads[idthread].message.clear(); if (s[0] != '{') { stringstream msg; msg << "Wrong map definition. Expecting a map definition"; return globalTamgu->Returnerror(msg.str(), idthread); } TamguJsonCompiler* jcomp = &jcomp_base; if (idthread) jcomp = new TamguJsonCompiler; if (!jcomp->compile(kf, s)) { if (idthread) delete jcomp; stringstream msg; msg << "Wrong map definition. Internal line error: " << jcomp->line; return globalTamgu->Returnerror(msg.str(), idthread); } if (idthread) delete jcomp; return kf; } Exporting Tamgu* TamguGlobal::EvaluateMap(string& s, short idthread) { static TamguJsonCompiler jcomp_base; threads[idthread].message.str(""); threads[idthread].message.clear(); if (s[0] != '{') { stringstream msg; msg << "Wrong map definition. Expecting a map definition"; return globalTamgu->Returnerror(msg.str(), idthread); } Tamgu* kf = globalTamgu->Providemap(); TamguJsonCompiler* jcomp = &jcomp_base; if (idthread) jcomp = new TamguJsonCompiler; if (!jcomp->compile(kf, s)) { if (idthread) delete jcomp; kf->Release(); stringstream msg; msg << "Wrong map definition. Internal line error: " << jcomp->line; return globalTamgu->Returnerror(msg.str(), idthread); } if (idthread) delete jcomp; return kf; } Exporting Tamgu* TamguGlobal::EvaluateJSON(string& s, short idthread) { static TamguJsonCompiler jcomp_base; threads[idthread].message.str(""); threads[idthread].message.clear(); Tamgu* kf; if (s[0] == '[') kf = globalTamgu->Providevector(); else if (s[0] == '{') kf = globalTamgu->Providemap(); else { stringstream msg; msg << "Wrong JSON definition. Expecting a map or a vector definition"; return globalTamgu->Returnerror(msg.str(), idthread); } TamguJsonCompiler* jcomp = &jcomp_base; if (idthread) jcomp = new TamguJsonCompiler; if (!jcomp->compile(kf, s)) { if (idthread) delete jcomp; kf->Release(); stringstream msg; msg << "Wrong JSON definition. Internal line error: " << jcomp->line; return globalTamgu->Returnerror(msg.str(), idthread); } if (idthread) delete jcomp; return kf; } void replacemetas(string& sub) { string thestr; long sz = sub.size(); for (long i=0;i<sz;i++) { if (sub[i]=='\\') { switch(sub[++i]) { case 'n': thestr+="\n"; break; case 'r': thestr+="\r"; break; case 't': thestr+="\t"; break; default: thestr+=sub[i]; } } else thestr+=sub[i]; } sub = thestr; } char TamguJsonCompiler::buildexpression(Tamgu* kf) { string key; Tamgu* local; bool checknext = false; char expecting = kf->isMapContainer(); to = 0; while (r < pos.size()) { c = src[i++]; if (c <= 32) { if (c == '\n') line++; continue; } if (c == '@' && src[i] != '"') r++; if (i != pos[r] + 1) { if (checknext) return false; to = i; while (src[to] > 32 && to < pos[r]) to++; c = src[to]; src[to] = 0; if (expecting == 1) key = (char*)src+i-1; else { token = (char*)src+i-1; if (token == "false") local = aFALSE; else if (token == "true") local = aTRUE; else if (token == "null" || token == "nil") local = aNULL; else { local = globalTamgu->Providewithstring(token); } if (expecting) { ((Tamgumap*)kf)->pushone(key, local); expecting = 1; } else ((Tamguvector*)kf)->pushone(local); checknext=true; } src[to] = c; i = to; continue; } r++; switch (c) { case '@': if (checknext) return false; r++; // the " has already been detected above... while (r < sz) { to = pos[r++]; if (src[to-1] != '\\' && src[to] == '"' && src[to+1] == '@') { to = pos[r++]; break; } } c= src[to-1]; src[to-1] = 0; if (expecting == 1) key = (char*)src+i+1; else { if (strchr((char*)src+i, '\\') == NULL) local = globalTamgu->Providestring((char*)src+i); else { token = (char*)src+i; replacemetas(token); local = globalTamgu->Providewithstring(token); } if (expecting) { ((Tamgumap*)kf)->pushone(key, local); expecting = 1; } else ((Tamguvector*)kf)->pushone(local); checknext=true; } src[to-1] = c; i = to + 1; break; case 34: if (checknext) return false; while (r < sz) { to = pos[r++]; if (src[to-1] != '\\' && src[to] == '"') break; } c= src[to]; src[to] = 0; if (expecting == 1) key = (char*)src+i; else { if (strchr((char*)src+i, '\\') == NULL) local = globalTamgu->Providestring((char*)src+i); else { token = (char*)src+i; replacemetas(token); local = globalTamgu->Providewithstring(token); } if (expecting) { ((Tamgumap*)kf)->pushone(key, local); expecting = 1; } else ((Tamguvector*)kf)->pushone(local); checknext=true; } src[to] = c; i = to + 1; break; case 39: if (checknext) return false; while (r < sz) { to = pos[r++]; if (src[to] == '\'') break; } c= src[to]; src[to] = 0; if (expecting == 1) key = (char*)src+i; else { local = globalTamgu->Providestring((char*)src+i); if (expecting) { ((Tamgumap*)kf)->pushone(key, local); expecting = 1; } else ((Tamguvector*)kf)->pushone(local); checknext=true; } src[to] = c; i = to + 1; break; case '+': case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (checknext) return false; v = conversionfloathexa((const char*)src+i-1, l); to = i + l - 1; while (pos[r] < to) r++; c= src[to]; src[to] = 0; if (expecting == 1) key = (char*)src+i; else { if (strchr((char*)src+i, '.')) local = globalTamgu->ProvideConstfloat(v); else local = globalTamgu->ProvideConstint(v); if (expecting) { ((Tamgumap*)kf)->pushone(key, local); expecting = 1; } else ((Tamguvector*)kf)->pushone(local); checknext=true; } src[to] = c; i = to; break; case '{': if (expecting == 1 || checknext) return false; local = globalTamgu->Providemap(); if (src[i] == '}') { r++; i++; } else { if (!buildexpression(local)) { local->Release(); return false; } } if (expecting) { ((Tamgumap*)kf)->pushone(key, local); expecting = 1; } else ((Tamguvector*)kf)->pushone(local); checknext=true; break; case '[': if (expecting == 1 || checknext) return false; local = globalTamgu->Providevector(); if (src[i] == ']') { r++; i++; } else { if (!buildexpression(local)) { local->Release(); return false; } } if (expecting) { ((Tamgumap*)kf)->pushone(key, local); expecting = 1; } else ((Tamguvector*)kf)->pushone(local); checknext=true; break; case '}': return (expecting == 1); case ']': return (!expecting); case ':': if (expecting != 1) return false; expecting = 2; break; case ',': if (!checknext) return false; checknext = false; } } return false; } //-------------------------------------------------------------------- bool WaitingFor(double tm, PauseBack pb, void* data) { double init; double res; timeval tempsfinal; gettimeofday(&tempsfinal, NULL); init = (((unsigned long)tempsfinal.tv_sec) * 1000 + ((unsigned long)tempsfinal.tv_usec) / 1000.0); res = tm * 1000; double diff = 0; while (diff < res) { if (pb(data) == true) return true; gettimeofday(&tempsfinal, NULL); diff = timeminus(init, tempsfinal); } return false; } void Wait(double tm) { double init; double res; timeval tempsfinal; gettimeofday(&tempsfinal, NULL); init = (((unsigned long)tempsfinal.tv_sec) * 1000 + ((unsigned long)tempsfinal.tv_usec) / 1000.0); res = tm * 1000; double diff = 0; while (diff < res) { gettimeofday(&tempsfinal, NULL); diff = timeminus(init, tempsfinal); } } #ifdef WIN32 bool DirectoryCreation(char* noms, long pos) { char* pt = strchr(noms + pos, SEP); while (pt != NULL) { *pt = 0; CreateDirectoryA(noms, NULL); *pt = SEP; pt = strchr(pt + 1, SEP); } bool created = true; if (CreateDirectoryA(noms, NULL) == FALSE) created = false; return created; } #else bool DirectoryCreation(char* noms, long pos) { char* pt = strchr(noms + pos, SEP); while (pt != NULL) { *pt = 0; mkdir(noms, S_IRWXU | S_IRWXG | S_IRWXO); *pt = SEP; pt = strchr(pt + 1, SEP); } bool created = true; if (mkdir(noms, S_IRWXU | S_IRWXG | S_IRWXO) != 0) created = false; return created; } #endif #ifdef APPLE extern "C" { int gethostuuid(uuid_t id, const struct timespec *wait) { return -1; } } #endif //----------------------------------------------------------------------- static FILE* localstreamerr = NULL; static FILE* localstream = NULL; void clear_output() { if (localstream != NULL) { fclose(localstream); localstream = NULL; } if (localstreamerr != NULL) { fclose(localstreamerr); localstreamerr = NULL; } } char redirect_output(string& filename, long output) { if (output == 1) { if (localstream != NULL) return -2; int o = DUP(output); localstream = fopen(STR(filename), "w"); if (localstream == NULL) return -1; DUP2(FILENO(localstream), output); return o; } if (localstreamerr != NULL) return -2; int o = DUP(output); localstreamerr = fopen(STR(filename), "w"); if (localstreamerr == NULL) return -1; DUP2(FILENO(localstreamerr), output); return o; } char restate_output(long o, long output) { if (output == 1) { if (localstream == NULL) return -1; fflush(stdout); fclose(localstream); localstream = NULL; DUP2(o, output); return 0; } if (localstreamerr == NULL) return -1; fflush(stdout); fclose(localstreamerr); localstreamerr = NULL; DUP2(o, output); return 0; } //----------------------------------------------------------------------------- void Flattening(Tamgu* ret, Tamgu* res) { TamguIteration* itr = res->Newiteration(false); Tamgu* kval; for (itr->Begin(); itr->End() != aTRUE; itr->Next()) { kval = itr->IteratorValue(); if (kval->isContainer()) Flattening(ret, kval); else ret->Push(kval); } itr->Release(); } //----------------------------------------------------------------------------- #ifdef WIN32 char* Getenv(char* name) { static char rep[4096]; size_t size = 0; getenv_s(&size, rep, 4096, name); return rep; } #else #define Getenv getenv #endif void FileNameNomalization(char* fileName, char* buffer, long buffersz) { //Tout d'abord on ramene tous les chemins a de l'UNIX long l = strlen(buffer); //On normalise les chemins for (int i = 0; i < l; i++) { if (buffer[i] == ANTISEP) buffer[i] = SEP; } //s'il y a une variable d'environnement char* vari = strchr(buffer, '$'); fileName[0] = 0; while (vari) { char* reper = Getenv(vari + 1); char* pt = strchr(vari + 1, SEP); if (pt != NULL) *pt = 0; //On recopie la partie qui precede la variable long lvar = vari - buffer; long lnom = strlen(fileName); memcpy(fileName + lnom, buffer, lvar); fileName[lvar + lnom] = 0; if (reper != NULL) strcat_s(fileName, buffersz, reper); if (pt != NULL) { *pt = SEP; static char inter[1000]; strcpy_s(inter,1000, pt); strcpy_s(buffer, buffersz, inter); } else buffer[0] = 0; vari = strchr(buffer, '$'); } strcat_s(fileName, buffersz, buffer); char localpath[4096]; #ifdef WIN32 _fullpath(localpath, fileName, 4096); #else realpath(fileName, localpath); #endif strcpy_s(fileName, buffersz, localpath); } string NormalizeFileName(string n) { if (n == "") return ""; char buff[4096]; char name[4096]; strcpy_s(name, 4096, STR(n)); FileNameNomalization(buff, name, 4096); return buff; } Exporting bool TamguGlobal::RecordExternalLibrary(string name, TamguExternalModule module) { if (externalLibraries.find(name) != externalLibraries.end()) return false; if (module == NULL) return true; externalLibraries[name] = module; return true; } //------------------------------------------------------------ uchar Selecttype(Tamgu* context) { if (context->isMapContainer()) return a_map; switch (context->Typevariable()) { case a_ivector: return a_ivector; case a_fvector: return a_fvector; case a_svector: return a_svector; case a_uvector: return a_uvector; case a_vector: return a_vector; case a_string: return a_string; case a_ustring: return a_ustring; case a_dvector: return a_dvector; case a_lvector: return a_lvector; case a_counter: return a_counter; default: if (context->isVectorContainer()) return a_vector; } return 0; } Tamgu* Storealongtype(Tamgu* context, Tamgu* a, short idthread, uchar& addvalue) { switch (addvalue) { case a_vector: context->Push(a); return context; case a_hvector: ((Tamguhvector*)context)->values.push_back(a->Short()); return context; case a_ivector: ((Tamguivector*)context)->values.push_back(a->Integer()); return context; case a_fvector: ((Tamgufvector*)context)->values.push_back(a->Float()); return context; case a_svector: ((Tamgusvector*)context)->values.push_back(a->String()); return context; case a_uvector: ((Tamguuvector*)context)->values.push_back(a->UString()); return context; case a_dvector: ((Tamgudvector*)context)->values.push_back(a->Decimal()); return context; case a_lvector: ((Tamgulvector*)context)->values.push_back(a->Long()); return context; case a_string: ((Tamgustring*)context)->value += a->String(); return context; case a_ustring: ((Tamguustring*)context)->value += a->UString(); return context; case a_map: context->Pushinmap(a, idthread); return context; case a_counter: ((TamguTaskellCounter*)context)->value++; return context; } switch (a->Typevariable()) { case a_short: context = new Tamguhvector; ((Tamguhvector*)context)->values.push_back(a->Short()); addvalue = a_hvector; return context; case a_int: context = globalTamgu->Provideivector(); ((Tamguivector*)context)->values.push_back(a->Integer()); addvalue = a_ivector; return context; case a_long: context = new Tamgulvector; ((Tamgulvector*)context)->values.push_back(a->Long()); addvalue = a_lvector; return context; case a_float: context = globalTamgu->Providefvector(); ((Tamgufvector*)context)->values.push_back(a->Float()); addvalue = a_fvector; return context; case a_string: context = globalTamgu->Providesvector(); ((Tamgusvector*)context)->values.push_back(a->String()); addvalue = a_svector; return context; case a_ustring: context = globalTamgu->Provideuvector(); ((Tamguuvector*)context)->values.push_back(a->UString()); addvalue = a_uvector; return context; case a_decimal: context = new Tamgudvector; ((Tamgudvector*)context)->values.push_back(a->Decimal()); addvalue = a_dvector; return context; default: if (a->isMapContainer()) { context = globalTamgu->Providemap(); context->Pushinmap(a, idthread); addvalue = a_map; } else { context = globalTamgu->Providevector(); context->Push(a); addvalue = a_vector; } } return context; } //------------------------------------------------------------ #ifdef WIN32 bool TamguCode::Loadlibrary(string n, string& library_name) { if (n == "") return false; string name = NormalizeFileName(n); HINSTANCE LoadMe; string lname = name; int pos = lname.find_last_of(SEP); string subname = lname; if (pos != -1) { subname = lname.substr(pos + 1, lname.size() - pos - 1); pos = subname.find("."); if (pos != -1) subname = subname.substr(0, pos); } string moduleinitname = subname; moduleinitname += "_InitialisationModule"; //If it has already been loaded, we return... library_name = lname; TamguExternalModule LibEntryPoint; if (globalTamgu->RecordExternalLibrary(moduleinitname, NULL) == false) { LibEntryPoint = globalTamgu->externalLibraries[moduleinitname]; (*LibEntryPoint)(globalTamgu, TamguVersion()); return true; } LoadMe = LoadLibraryA(STR(lname)); if (LoadMe == 0) { string atanlib; if (Getenv("TAMGULIBS") != NULL) atanlib = Getenv("TAMGULIBS"); else { stringstream message; message << "Please set TAMGULIBS: " << name; throw new TamguRaiseError(message, filename, current_start, current_end); } if (Getenv("PATH") != NULL) { string path = "Path="; path += atanlib; path += ";"; path += Getenv("PATH"); _putenv(STR(path)); } atanlib += "\\"; atanlib += subname; atanlib += ".dll"; atanlib = NormalizeFileName(atanlib); library_name = atanlib; LoadMe = LoadLibraryA(STR(library_name)); } // Check to see if the library was loaded successfully if (LoadMe == 0) { DWORD err = GetLastError(); stringstream message; message << "Cannot load library: " << name; throw new TamguRaiseError(message, filename, current_start, current_end); } LibEntryPoint = (TamguExternalModule)GetProcAddress(LoadMe, STR(moduleinitname)); if (LibEntryPoint == NULL) { stringstream message; message << "No entry point in this library: " << name; throw new TamguRaiseError(message, filename, current_start, current_end); } globalTamgu->RecordExternalLibrary(moduleinitname, LibEntryPoint); if ((*LibEntryPoint)(globalTamgu, TamguVersion()) == false) { stringstream message; message << "Wrong version: " << name; throw new TamguRaiseError(message, filename, current_start, current_end); } return true; } #else #ifdef TAMGUINEEDCLOSELIBS vector<void*> TAMGULIBSTOCLOSE; void TamguCloseLibraries() { for (int x = 0; x<TAMGULIBSTOCLOSE.size(); x++) dlclose(TAMGULIBSTOCLOSE[x]); } #endif bool TamguCode::Loadlibrary(string n, string& library_name) { string name = NormalizeFileName(n); void* LoadMe; char lname[4096]; strcpy_s(lname, 4096, STR(name)); char* error; char* pt = strrchr(lname, '/'); char buff[4096]; bool addso = true; string basename; if (strstr(lname + strlen(lname) - 3, ".so")) addso = false; if (pt != NULL) { if (memcmp(pt + 1, "lib", 3)) { if (addso) sprintf(buff, "lib%s.so", pt + 1); else sprintf(buff, "lib%s", pt + 1); } else { if (addso) sprintf(buff, "%s.so", pt + 1); else strcpy(buff, pt + 1); } basename = buff; strcpy(pt + 1, buff); } else { if (memcmp(lname, "lib", 3)) { if (addso) sprintf(buff, "lib%s.so", lname); else sprintf(buff, "lib%s", lname); } else { if (addso) sprintf(buff, "%s.so", lname); else strcpy(buff, lname); } basename = buff; strcpy(lname, buff); } FileNameNomalization(buff, lname, 4096); strcpy(lname, buff); string subname = basename.substr(3, basename.size() - 6); string moduleinitname = subname; moduleinitname += "_InitialisationModule"; TamguExternalModule LibEntryPoint; library_name = lname; //If it has already been loaded, we return... if (global->RecordExternalLibrary(moduleinitname, NULL) == false) { LibEntryPoint = global->externalLibraries[moduleinitname]; (*LibEntryPoint)(global,TamguVersion()); return true; } LoadMe = dlopen(lname, RTLD_LAZY | RTLD_GLOBAL); string baselib; if (LoadMe == NULL) { string atanlib; if (Getenv("TAMGULIBS") != NULL) atanlib = Getenv("TAMGULIBS"); else { stringstream message; message << "Please set TAMGULIBS: " << name; throw new TamguRaiseError(message, filename, current_start, current_end); } string ldlibpath; if (Getenv("LD_LIBRARY_PATH") != NULL) { ldlibpath = Getenv("LD_LIBRARY_PATH"); ldlibpath = ":" + ldlibpath; } ldlibpath = atanlib + ldlibpath; setenv("LD_LIBRARY_PATH", ldlibpath.c_str(), 1); #ifdef APPLE ldlibpath=""; if (Getenv("DYLD_LIBRARY_PATH") != NULL) { ldlibpath = Getenv("DYLD_LIBRARY_PATH"); ldlibpath = ":" + ldlibpath; } ldlibpath = atanlib + ldlibpath; setenv("DYLD_LIBRARY_PATH", ldlibpath.c_str(), 1); #endif ldlibpath = ""; if (Getenv("PATH") != NULL) { ldlibpath = Getenv("PATH"); ldlibpath = ":" + ldlibpath; } ldlibpath = atanlib + ldlibpath; setenv("PATH", ldlibpath.c_str(), 1); if (atanlib.back() != '/') atanlib += "/"; baselib = atanlib; atanlib += basename; atanlib = NormalizeFileName(atanlib); library_name = atanlib; LoadMe = dlopen(STR(atanlib), RTLD_LAZY | RTLD_GLOBAL); } // Check to see if the library was loaded successfully if (LoadMe == NULL) { //We try without lib in the name baselib += n; if (addso) baselib += ".so"; LoadMe = dlopen(STR(baselib), RTLD_LAZY | RTLD_GLOBAL); } if (LoadMe == NULL) { error = dlerror(); stringstream message; message << error << ": " << lname; throw new TamguRaiseError(message, filename, current_start, current_end); } #ifdef TAMGUINEEDCLOSELIBS TamguLIBSTOCLOSE.push_back(LoadMe); #endif LibEntryPoint = (TamguExternalModule)dlsym(LoadMe, STR(moduleinitname)); if ((error = dlerror()) != NULL) { stringstream message; message << error << ": " << name; throw new TamguRaiseError(message, filename, current_start, current_end); } global->RecordExternalLibrary(moduleinitname, LibEntryPoint); if ((*LibEntryPoint)(global,TamguVersion()) == false) { stringstream message; message << "Wrong version: " << name; throw new TamguRaiseError(message, filename, current_start, current_end); } return true; } #endif
25.578139
164
0.472777
[ "vector", "transform" ]
fde86b6e0b4068db8fcb028a4b1da5cf95c1e2d5
3,164
cpp
C++
quantiphyse_deeds/src/TMI2013/applyWarp.cpp
physimals/quantiphyse-deeds
d4466fabf861d09a65ce155a528087ba28580b67
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
quantiphyse_deeds/src/TMI2013/applyWarp.cpp
physimals/quantiphyse-deeds
d4466fabf861d09a65ce155a528087ba28580b67
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
quantiphyse_deeds/src/TMI2013/applyWarp.cpp
physimals/quantiphyse-deeds
d4466fabf861d09a65ce155a528087ba28580b67
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* Helper-function for deeds if you need to upsample the deformation fields into high-res To compile simple run the following in your Terminal: g++ applyWarp.cpp -arch x86_64 -O3 -o applyWarp ./applyWarp output_vol second_vol.nii in order to upsample the fields and apply this deformation to second_vol.nii this will generate output_vol_second_deformed.nii (output_vol_deformed.nii must still be in same directory as output_vol_flow4D.dat) */ #include <iostream> #include <fstream> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include <vector> #include <algorithm> #include <functional> #include <unistd.h> #include <string.h> #include <sstream> #include <stdarg.h> #include <unistd.h> using namespace std; int image_m=256; //will be set later int image_n=256; int image_o=106; float SSD0; float SSD1; #include "symmetricDiffeomorphic.h" void warpImage(float* warped,float* im1,float* im1b,float* u1,float* v1,float* w1){ int m=image_m; int n=image_n; int o=image_o; int sz=m*n*o; float ssd=0; float ssd0=0; float ssd2=0; interp3(warped,im1,u1,v1,w1,m,n,o,m,n,o,true); for(int i=0;i<m;i++){ for(int j=0;j<n;j++){ for(int k=0;k<o;k++){ ssd+=pow(im1b[i+j*m+k*m*n]-warped[i+j*m+k*m*n],2); ssd0+=pow(im1b[i+j*m+k*m*n]-im1[i+j*m+k*m*n],2); } } } ssd/=m*n*o; ssd0/=m*n*o; SSD0=ssd0; SSD1=ssd; } int main (int argc, char * const argv[]) { char* flowend=new char[50]; strcpy(flowend,"_flow4D.dat"); char* outputflow=new char[200]; strcpy(outputflow,argv[1]); strncat(outputflow,flowend,200); char* defend=new char[50]; strcpy(defend,"_deformed.nii"); char* outputdef=new char[200]; strcpy(outputdef,argv[1]); strncat(outputdef,defend,200); char* secend=new char[50]; strcpy(secend,"_second_deformed.nii"); char* outputs=new char[200]; strcpy(outputs,argv[1]); strncat(outputs,secend,200); float* im1; float* second; int M,N,O; char* header; FILE * pFile; long sizeflow; pFile = fopen(outputflow,"rb"); if (pFile==NULL) perror ("Error opening file"); else { fseek (pFile, 0, SEEK_END); sizeflow=ftell (pFile); fclose (pFile); } sizeflow/=4; float* flow=new float[sizeflow]; readFloat(outputflow,flow,sizeflow); int sz1=sizeflow/3; float* u1=new float[sz1]; float* v1=new float[sz1]; float* w1=new float[sz1]; for(int i=0;i<sz1;i++){ u1[i]=flow[i]; v1[i]=flow[i+sz1]; w1[i]=flow[i+sz1*2]; } readNifti(argv[2],second,M,N,O,header); readNifti(outputdef,im1,M,N,O,header); image_m=M; image_n=N; image_o=O; int m=image_m; int n=image_n; int o=image_o; int sz=m*n*o; int step1=round(pow((float)sz/(float)sz1,0.3333333)); cout<<"grid-step: "<<step1<<"\n"; int m1=m/step1; int n1=n/step1; int o1=o/step1; //flow-fields //u is in x-direction (2nd dimension), v in y-direction (1st dim) and w in z-direction (3rd dim) float* ux=new float[sz]; float* vx=new float[sz]; float* wx=new float[sz]; upsampleDeformations2(ux,vx,wx,u1,v1,w1,m,n,o,m1,n1,o1); float* warped=new float[sz]; warpImage(warped,second,im1,ux,vx,wx); writeNifti(outputs,warped,header,m*n*o); return 0; }
21.972222
97
0.676675
[ "vector" ]
fde96e2b6e0d0a44df3b70971b5636cd353adc24
31,043
hpp
C++
core/x-lib.hpp
AftabHussain/x-stream
01fb3ff0703d18c23047d3c80f68b26f14b2b4fa
[ "Apache-2.0" ]
75
2015-11-06T02:01:16.000Z
2021-02-04T01:51:00.000Z
core/x-lib.hpp
AftabHussain/x-stream
01fb3ff0703d18c23047d3c80f68b26f14b2b4fa
[ "Apache-2.0" ]
7
2016-07-13T13:05:43.000Z
2019-09-23T17:45:05.000Z
core/x-lib.hpp
AftabHussain/x-stream
01fb3ff0703d18c23047d3c80f68b26f14b2b4fa
[ "Apache-2.0" ]
46
2015-08-31T09:41:13.000Z
2020-05-27T07:29:43.000Z
/* * X-Stream * * Copyright 2013 Operating Systems Laboratory EPFL * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _X_LIB_ #define _X_LIB_ #include "disk_io.hpp" #include "../utils/clock_utils.h" #include "../utils/memory_utils.h" #include "../utils/barrier.h" #include<boost/thread.hpp> #include "../utils/barrier.h" #include "../utils/per_cpu_data.hpp" #include "split_stream.hpp" #include "x-ingest.hpp" #include<sys/resource.h> #define OUTBUF_SIZE 8192 namespace x_lib { struct stream_callback_state { bool loopback; bool ingest; unsigned char *state; unsigned long superp; unsigned long partition_id; unsigned char *bufin; // callee can change unsigned long bytes_in; // callee must set unsigned char *bufout; // callee can change unsigned long bytes_out; // callee must set unsigned long bytes_out_max; #ifdef PYTHON_SUPPORT PyObject *pbufin; unsigned long pbufin_offset; PyObject *pbufout; PyObject *pstate; unsigned long pstate_offset; #endif algorithm::per_processor_data *cpu_state; }; struct work_base { virtual void operator() (unsigned long processor_id, configuration *config, x_barrier *sync, algorithm::per_processor_data * cpu_state, unsigned char *outbuf) = 0; }; template<typename A> struct state_iter_work : public work_base { memory_buffer *state_buffer; unsigned long superp; void operator()(unsigned long processor_id, configuration *config, x_barrier *sync, algorithm::per_processor_data *cpu_state, unsigned char *outbuf) { unsigned long partitions_per_cpu = config->cached_partitions / config->processors; unsigned long remainder = config->cached_partitions - partitions_per_cpu * config->processors; unsigned long start = partitions_per_cpu*processor_id; unsigned long count = partitions_per_cpu; if (processor_id == (config->processors - 1)) { count += remainder; } unsigned long i, j, k; for (i = start, j = 0; j < count; i++, j++) { unsigned long vertices = config->state_count(superp, i); for (k = 0; k < vertices; k++) { unsigned char * vertex = &state_buffer->buffer[state_buffer->index[0][i] + k * config->vertex_size]; A::state_iter_callback(superp, i, k, vertex, cpu_state); } } } } __attribute__((__aligned__(64))); template<typename A, typename IN, typename OUT> struct work : public work_base { unsigned long superp; memory_buffer *state; memory_buffer *stream_in; memory_buffer *ingest; memory_buffer *stream_out; filter *input_filter; disk_stream *disk_stream_out; rtc_clock *io_clock; buffer_manager *bufm; bool loopback; bool flush_buffer(unsigned long processor_id, configuration *config, x_barrier *sync, algorithm::per_processor_data *cpu_state) { memory_buffer *loopback_buffer = stream_out; bool empty = false; sync->wait(); if (stream_out->bufsize > 0) { make_index<OUT, map_super_partition_wrap>(stream_out, processor_id, config->super_partitions, sync); if (processor_id == 0) { if (loopback) { // IO only if more than one superpartition if (config->super_partitions > 1) { // Hold on for looping back on current superpartition loopback_buffer->skip_superp = superp; loopback_buffer->set_refcount(loopback_buffer->get_refcount() + 1); io_clock->start(); disk_stream_out->append(stream_out); io_clock->stop(); } } else { io_clock->start(); disk_stream_out->append(stream_out); io_clock->stop(); } stream_out = NULL; } if (loopback) { if (processor_id == 0) { stream_out = bufm->get_buffer(); } sync->wait(); unsigned long loopback_bytes; unsigned char *loopback_src = loopback_buffer->get_substream(processor_id, superp, &loopback_bytes); unsigned long offset_start; unsigned long offset_stop; do { offset_start = stream_out->bufsize; offset_stop = offset_start + loopback_bytes; } while (!__sync_bool_compare_and_swap(&stream_out->bufsize, offset_start, offset_stop)); memcpy(stream_out->buffer + offset_start, loopback_src, loopback_bytes); sync->wait(); make_index<OUT, map_cached_partition_wrap > (stream_out, processor_id, config->cached_partitions, sync); stream_callback_state callback_state; callback_state.superp = superp; callback_state.bytes_out_max = 0; callback_state.cpu_state = cpu_state; callback_state.loopback = true; sync->wait(); stream_out->work_queues->prep_dq(processor_id); sync->wait(); unsigned long partition_id; while ((partition_id = stream_out->work_queues->dq(processor_id)) != ULONG_MAX) { callback_state.state = &state->buffer[state->index[0][partition_id]]; callback_state.partition_id = partition_id; A::partition_pre_callback(superp, partition_id, cpu_state); for (unsigned long i = 0; i < config->processors; i++) { callback_state.bufin = stream_out->get_substream(i, partition_id, &callback_state.bytes_in); callback_state.bufout = NULL; // No output allowed in loopback #ifdef PYTHON_SUPPORT callback_state.pbufin = stream_out->pBuffer; callback_state.pbufin_offset = callback_state.bufin - stream_out->buffer; callback_state.pstate = state->pBuffer; callback_state.pstate_offset = callback_state.state - state->buffer; #endif A::partition_callback(&callback_state); } A::partition_post_callback(superp, partition_id, cpu_state); } sync->wait(); if (processor_id == 0) { loopback_buffer->set_refcount(loopback_buffer->get_refcount() - 1); stream_out->set_refcount(stream_out->get_refcount() - 1); stream_out = NULL; } } if (processor_id == 0) { if (vm["force_buffers"].as<unsigned long>() == 0) { stream_out = bufm->get_buffer(); } else { stream_out = NULL; } } } else { empty = true; } sync->wait(); return empty; } void final_flush(unsigned long processor_id, configuration *config, x_barrier *sync, algorithm::per_processor_data *cpu_state) { bool empty; if (stream_out != NULL) { do { empty = flush_buffer(processor_id, config, sync, cpu_state); } while (!empty && stream_out != NULL); } sync->wait(); if (processor_id == 0 && stream_out != NULL) { stream_out->set_refcount(stream_out->get_refcount() - 1); } } void append_buffer(unsigned char *buffer, unsigned long bytes, unsigned long processor_id, configuration *config, x_barrier *sync, algorithm::per_processor_data *cpu_state) { while (bytes) { unsigned char *base = stream_out->buffer; unsigned long offset_start = stream_out->bufsize; unsigned long space = (MIN(stream_out->bufbytes - offset_start, bytes) / OUT::item_size()) * OUT::item_size(); unsigned long offset_stop = offset_start + space; if (__sync_bool_compare_and_swap(&stream_out->bufsize, offset_start, offset_stop)) { memcpy(base + offset_start, buffer, space); if (space != bytes) { // Need flush (void) flush_buffer(processor_id, config, sync, cpu_state); } bytes -= space; buffer += space; } } } void execute_callback(stream_callback_state *callback, unsigned long processor_id, configuration *config, x_barrier *sync, algorithm::per_processor_data *cpu_state, unsigned char *outbuf) { callback->bufout = outbuf; callback->bytes_out = 0; #ifdef PYTHON_SUPPORT callback->pbufin = stream_in->pBuffer; callback->pbufin_offset = callback->bufin - stream_in->buffer; npy_intp dim[1] = {OUTBUF_SIZE}; callback->pbufout = PyArray_SimpleNewFromData(1, dim, NPY_UINT8, (void *) outbuf); callback->pstate = state->pBuffer; callback->pstate_offset = callback->state - state->buffer; #endif while (callback->bytes_in) { A::partition_callback(callback); if (stream_out != NULL && callback->bytes_out > 0) { append_buffer(outbuf, callback->bytes_out, processor_id, config, sync, cpu_state); callback->bufout = outbuf; callback->bytes_out = 0; } } #ifdef PYTHON_SUPPORT Py_DECREF(callback->pbufout); #endif } void operator()(unsigned long processor_id, configuration *config, x_barrier *sync, algorithm::per_processor_data *cpu_state, unsigned char *outbuf) { if (stream_in == NULL && stream_out == NULL) { A::do_cpu_callback(cpu_state); return; } stream_callback_state callback_state; callback_state.superp = superp; callback_state.bytes_out_max = (OUTBUF_SIZE / OUT::item_size()) * OUT::item_size(); callback_state.cpu_state = cpu_state; callback_state.loopback = false; // Must play ingest first if (ingest != NULL) { sync->wait(); callback_state.ingest = true; make_index<IN, map_super_partition_wrap>(ingest, processor_id, config->super_partitions, sync); unsigned long ingest_bytes; unsigned char *ingest_src = ingest->get_substream(processor_id, superp, &ingest_bytes); unsigned long offset_start; unsigned long offset_stop; do { offset_start = stream_in->bufsize; offset_stop = offset_start + ingest_bytes; } while (!__sync_bool_compare_and_swap(&stream_in->bufsize, offset_start, offset_stop)); memcpy(stream_in->buffer + offset_start, ingest_src, ingest_bytes); sync->wait(); if (processor_id == 0) { BOOST_ASSERT_MSG(stream_in->bufsize == ingest->bufsize, "Error in partitioning ingest !"); ingest = NULL; } } else { callback_state.ingest = false; } if (stream_in != NULL) { make_index<IN, map_cached_partition_wrap > (stream_in, processor_id, config->cached_partitions, sync); } sync->wait(); input_filter->prep_dq(processor_id); sync->wait(); unsigned long partition_id; while ((partition_id = input_filter->dq(processor_id)) != ULONG_MAX) { callback_state.state = &state->buffer[state->index[0][partition_id]]; callback_state.partition_id = partition_id; A::partition_pre_callback(superp, partition_id, cpu_state); if (stream_in != NULL) { for (unsigned long i = 0; i < config->processors; i++) { callback_state.bufin = stream_in->get_substream(i, partition_id, &callback_state.bytes_in); execute_callback(&callback_state, processor_id, config, sync, cpu_state, outbuf); } } else { callback_state.bufin = callback_state.state; callback_state.bytes_in = config->vertex_size * config->state_count(superp, partition_id); execute_callback(&callback_state, processor_id, config, sync, cpu_state, outbuf); } A::partition_post_callback(superp, partition_id, cpu_state); } if (stream_out != NULL) { final_flush(processor_id, config, sync, cpu_state); } } } __attribute__((aligned(64))); class x_thread { public: static x_barrier *sync; struct configuration *config; algorithm::per_processor_data * const cpu_state; const unsigned long processor_id; static volatile bool terminate; static struct work_base * volatile work_to_do; unsigned char *outbuf; x_thread(struct configuration* config_in, unsigned long processor_id_in, algorithm::per_processor_data *cpu_state_in) : config(config_in), cpu_state(cpu_state_in), processor_id(processor_id_in) { if (sync == NULL) { // First object sync = new x_barrier(config->processors); } outbuf = (unsigned char *) map_anon_memory(OUTBUF_SIZE, true, "thread outbuf"); } void operator()() { do { sync->wait(); if (terminate) { break; } else { (*work_to_do)(processor_id, config, sync, cpu_state, outbuf); sync->wait(); // Must synchronize before p0 exits (object is on stack) } } while (processor_id != 0); } friend class stream_IO; } __attribute__((__aligned__(64))); template<typename A> class streamIO { struct configuration *config; disk_stream **streams; memory_buffer **ingest_buffers; buffer_manager *buffers; memory_buffer *state_buffer; x_thread **workers; boost::thread ** thread_array; algorithm::per_processor_data ** cpu_state_array; /* Clock */ rtc_clock io_wait_time; unsigned int vertices_refresh, edges_refresh, updates_refresh; #ifdef PYTHON_SUPPORT //M: has to be called before creating python arrays! It is a macro, it has to be inside an int-returning function int import_numpy_array() { import_array(); return 0; } #endif void make_config() { #ifdef PYTHON_SUPPORT Py_Initialize(); import_numpy_array(); #endif config->memory_buffer_object_size = sizeof (memory_buffer); config->disk_stream_object_size = sizeof (disk_stream); config->ioq_object_size = sizeof (ioq); config->vertex_size = A::vertex_state_bytes(); config->vertex_footprint = config->vertex_size + A::vertex_stream_buffer_bytes(); config->max_streams = A::max_streams(); config->max_buffers = A::max_buffers(); config->init(); if (vm.count("autotune") > 0) { bool success = config->autotune(); if (!success) { BOOST_LOG_TRIVIAL(fatal) << "Auto-tuning failed !"; config->dump_config(); exit(-1); } } else { config->manual(); } config->dump_config(); /* Sanity checks */ check_pow_2(config->super_partitions, "Super partitions must be power of two"); check_pow_2(config->cached_partitions, "Cached partitions must be power of two"); check_pow_2(config->processors, "Processors must be power of two"); } public: streamIO() { vertices_refresh = updates_refresh = edges_refresh = 0; config = new struct configuration(); make_config(); buffers = new buffer_manager(config, config->buffer_size, config->max_buffers); state_buffer = new memory_buffer(config, config->max_state_bufsize()); startup_ioqs(config); streams = new disk_stream *[config->max_streams]; ingest_buffers = new memory_buffer *[config->max_streams]; for (unsigned long i = 0; i < config->max_streams; i++) { streams[i] = NULL; ingest_buffers[i] = 0; } workers = new x_thread* [config->processors]; thread_array = new boost::thread* [config->processors]; cpu_state_array = new algorithm::per_processor_data* [config->processors]; for (unsigned long i = 0; i < config->processors; i++) { cpu_state_array[i] = A::create_per_processor_data(i); workers[i] = new x_thread(config, i, cpu_state_array[i]); if (i > 0) { thread_array[i] = new boost::thread(boost::ref(*workers[i])); } } } const configuration *get_config() { return config; } unsigned long open_stream(const char *stream_name, bool new_file, unsigned long io_queue_number, unsigned long stream_unit, unsigned long override_superp_cnt = ULONG_MAX) { unsigned long stream_id; for (stream_id = 0; stream_id < config->max_streams; stream_id++) { if (streams[stream_id] == NULL) { break; } } if (stream_id == config->max_streams) { BOOST_LOG_TRIVIAL(fatal) << "Exceeded max streams !"; exit(-1); } if (io_queue_number >= config->num_ioqs) { BOOST_LOG_TRIVIAL(fatal) << "Trying to access non-existent disk!"; exit(-1); } streams[stream_id] = new disk_stream(stream_name, new_file, vm.count("compressed_io") > 0, disk_ioq_array[io_queue_number], buffers, override_superp_cnt == ULONG_MAX ? config->super_partitions : override_superp_cnt, stream_unit, config->stream_unit); return stream_id; } void close_stream(unsigned long stream) { streams[stream]->rewind(true); // TBD -- cleanup resources } void state_load(int stream, unsigned long superp) { io_wait_time.start(); state_buffer->wait_uptodate(); // Previous op complete ? state_buffer->bufsize = config->state_bufsize(superp); /*if(vertices_refresh < config->super_partitions){ vertices_refresh++; streams[stream]->refreshRDfd(superp); }*/ //streams[stream]->refreshRDfd(superp); streams[stream]->read_one_shot(state_buffer, superp); state_buffer->wait_uptodate(); io_wait_time.stop(); } void state_prepare(unsigned long superp) { // Make sure state is uptodate state_buffer->wait_uptodate(); /* Setup pmap */ unsigned long v_so_far = 0; for (unsigned long i = 0; i < config->cached_partitions; i++) { //Count entries in the partition state_buffer->index[0][i] = v_so_far; v_so_far += config->vertex_size * config->state_count(superp, i); } } void state_store(int stream, unsigned long superp) { state_buffer->wait_uptodate(); // Previous op complete ? state_buffer->bufsize = config->state_bufsize(superp); io_wait_time.start(); streams[stream]->refreshWRfd(superp); streams[stream]->write_one_shot(state_buffer, superp); state_buffer->wait_uptodate(); //BY JUNYAO: TESTING io_wait_time.stop(); } bool stream_empty(int stream) { return streams[stream]->is_empty(); } void terminate() { workers[0]->terminate = true; (*workers[0])(); for (unsigned long i = 1; i < config->processors; i++) { thread_array[i]->join(); } shutdown_ioqs(); struct rusage ru; (void) getrusage(RUSAGE_SELF, &ru); BOOST_LOG_TRIVIAL(info) << "CORE::RUSAGE::MAX_RSS_KB " << ru.ru_maxrss; BOOST_LOG_TRIVIAL(info) << "CORE::RUSAGE::MINFLT " << ru.ru_minflt; BOOST_LOG_TRIVIAL(info) << "CORE::RUSAGE::MAJFLT " << ru.ru_majflt; BOOST_LOG_TRIVIAL(info) << "CORE::RUSAGE::MAJFLT " << ru.ru_majflt; BOOST_LOG_TRIVIAL(info) << "CORE::RUSAGE::INBLK " << ru.ru_inblock; BOOST_LOG_TRIVIAL(info) << "CORE::RUSAGE::OUBLK " << ru.ru_oublock; BOOST_LOG_TRIVIAL(info) << "CORE::UTILS::BYTES_READ " << stat_bytes_read; BOOST_LOG_TRIVIAL(info) << "CORE::UTILS::BYTES_WRITTEN " << stat_bytes_written; io_wait_time.print("CORE::TIME::IO_WAIT"); if (vm.count("filename")) { io_wait_time.writeToFile(vm["filename"].as<std::string>().c_str(), false); } } void rewind_stream(unsigned long stream) { streams[stream]->rewind(); } void reset_stream(unsigned long stream, unsigned long super_partition) { streams[stream]->reset(super_partition); } template<typename B, typename IN, typename OUT> friend bool do_stream(streamIO<B> *sio, unsigned long superp, unsigned long stream_in, unsigned long stream_out, filter *override_input_filter, bool loopback); template<typename B> friend bool do_cpu(streamIO<B> *sio, unsigned long superp); template<typename B> friend void do_state_iter(streamIO<B> *sio, unsigned long superp); template<typename B> friend bool ingest(streamIO<B> *sio, unsigned long stream_in, ingest_t *ingest_segment); template<typename B> friend void merge_ingest(streamIO<B> *sio, unsigned long stream); }; #define SETUP_STREAMOUT() \ do { \ work_item.bufm = sio->buffers; \ if(stream_out != ULONG_MAX) { \ work_item.stream_out = sio->buffers->get_buffer(); \ work_item.disk_stream_out = sio->streams[stream_out]; \ work_item.io_clock = &sio->io_wait_time; \ } \ else { \ work_item.stream_out = NULL; \ work_item.disk_stream_out = NULL; \ work_item.io_clock = NULL; \ } \ sio->workers[0]->work_to_do = &work_item; \ }while(0) template<typename A, typename IN, typename OUT> static bool do_stream(streamIO<A> *sio, unsigned long superp, unsigned long stream_in, unsigned long stream_out, filter *override_input_filter, bool loopback = false) { struct work<A, IN, OUT> work_item; bool reduce_result; work_item.superp = superp; work_item.state = sio->state_buffer; work_item.loopback = loopback; work_item.ingest = NULL; if (stream_in != ULONG_MAX) { if (sio->ingest_buffers[stream_in] != NULL) { work_item.ingest = sio->ingest_buffers[stream_in]; work_item.stream_in = sio->buffers->get_buffer(); work_item.input_filter = work_item.stream_in->work_queues; SETUP_STREAMOUT(); (*sio->workers[0])(); work_item.stream_in->set_refcount(work_item.stream_in->get_refcount() - 1); } while (!sio->streams[stream_in]->stream_eof(superp)) { sio->io_wait_time.start(); work_item.stream_in = sio->streams[stream_in]->read(superp); sio->io_wait_time.stop(); if (override_input_filter != NULL) { work_item.input_filter = override_input_filter; } else { work_item.input_filter = work_item.stream_in->work_queues; } SETUP_STREAMOUT(); (*sio->workers[0])(); work_item.stream_in->set_refcount(work_item.stream_in->get_refcount() - 1); } } else { BOOST_ASSERT_MSG(override_input_filter != NULL, "Must have input stream or input filter !"); work_item.input_filter = override_input_filter; work_item.stream_in = NULL; work_item.bufm = sio->buffers; BOOST_ASSERT_MSG(stream_out != ULONG_MAX, "Must have input stream or output stream !"); work_item.stream_out = sio->buffers->get_buffer(); work_item.disk_stream_out = sio->streams[stream_out]; work_item.io_clock = &sio->io_wait_time; sio->workers[0]->work_to_do = &work_item; (*sio->workers[0])(); } reduce_result = sio->cpu_state_array[0]->reduce(sio->cpu_state_array, sio->config->processors); return reduce_result; } class DUMMY_IN { public: static unsigned long item_size() { BOOST_ASSERT_MSG(false, "Should not be called !"); return 0; } static unsigned long key(unsigned char *buffer) { BOOST_ASSERT_MSG(false, "Should not be called !"); return 0; } }; class DUMMY_OUT { public: static unsigned long item_size() { BOOST_ASSERT_MSG(false, "Should not be called !"); return 0; } static unsigned long key(unsigned char *buffer) { BOOST_ASSERT_MSG(false, "Should not be called !"); return 0; } }; template<typename A> static bool do_cpu(streamIO<A> *sio, unsigned long superp) { struct work<A, DUMMY_IN, DUMMY_OUT> work_item; work_item.state = NULL; work_item.stream_in = NULL; work_item.ingest = NULL; work_item.stream_out = NULL; sio->workers[0]->work_to_do = &work_item; (*sio->workers[0])(); bool reduce_result = sio->cpu_state_array[0]->reduce(sio->cpu_state_array, sio->config->processors); return reduce_result; } template<typename A> static void do_state_iter(streamIO<A> *sio, unsigned long superp) { state_iter_work<A> work; work.state_buffer = sio->state_buffer; work.superp = superp; sio->workers[0]->work_to_do = &work; (*sio->workers[0])(); } // Returns true on eof template<typename A> static bool ingest(streamIO<A> *sio, unsigned long stream, ingest_t *ingest_segment) { while (ingest_segment->avail == 0 && !ingest_segment->eof); if (ingest_segment->eof) { return true; } memory_buffer *ingest_buffer = sio->buffers->get_buffer(); memcpy(ingest_buffer->buffer, ingest_segment->buffer, ingest_segment->avail); ingest_buffer->bufsize = ingest_segment->avail; ingest_segment->avail = 0; // Signal that the ingest segment is free sio->ingest_buffers[stream] = ingest_buffer; return false; } template<typename A> static void merge_ingest(streamIO<A> *sio, unsigned long stream) { if (sio->ingest_buffers[stream] != NULL) { sio->streams[stream]->ingest(sio->ingest_buffers[stream]); sio->ingest_buffers[stream] = NULL; } } } #endif
40.420573
121
0.532487
[ "object" ]
fdecf634ac272bbba0fbd6f59fe9f8563f57508d
7,753
cc
C++
components/data_reduction_proxy/content/browser/content_lofi_decider.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
components/data_reduction_proxy/content/browser/content_lofi_decider.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
components/data_reduction_proxy/content/browser/content_lofi_decider.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/data_reduction_proxy/content/browser/content_lofi_decider.h" #include <string> #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_headers.h" #include "components/data_reduction_proxy/core/common/data_reduction_proxy_params.h" #include "content/public/browser/resource_request_info.h" #include "content/public/common/previews_state.h" #include "content/public/common/resource_type.h" #include "net/base/load_flags.h" #include "net/http/http_request_headers.h" #include "net/url_request/url_request.h" namespace data_reduction_proxy { ContentLoFiDecider::ContentLoFiDecider() {} ContentLoFiDecider::~ContentLoFiDecider() {} bool ContentLoFiDecider::IsUsingLoFiMode(const net::URLRequest& request) const { const content::ResourceRequestInfo* request_info = content::ResourceRequestInfo::ForRequest(&request); // The Lo-Fi directive should not be added for users in the Lo-Fi field // trial "Control" group. Check that the user is in a group that can get // "q=low". bool lofi_enabled_via_flag_or_field_trial = params::IsLoFiOnViaFlags() || params::IsIncludedInLoFiEnabledFieldTrial(); // Return if the user is using Lo-Fi and not part of the "Control" group. if (request_info) { return (request_info->GetPreviewsState() & content::SERVER_LOFI_ON) && lofi_enabled_via_flag_or_field_trial; } return false; } void ContentLoFiDecider::MaybeSetAcceptTransformHeader( const net::URLRequest& request, bool is_previews_disabled, net::HttpRequestHeaders* headers) const { const content::ResourceRequestInfo* request_info = content::ResourceRequestInfo::ForRequest(&request); if (!request_info) return; // Previews only operate on HTTP. if (!request.url().SchemeIs("http")) return; // Chrome-Proxy-Accept-Transform takes at most one token. if (headers->HasHeader(chrome_proxy_accept_transform_header())) return; content::ResourceType resource_type = request_info->GetResourceType(); if (resource_type == content::RESOURCE_TYPE_MEDIA) { headers->SetHeader(chrome_proxy_accept_transform_header(), compressed_video_directive()); return; } // The Lo-Fi and Lite Page directives should not be added for users in the // Lo-Fi field trial "Control" group. bool lofi_enabled_via_flags_or_field_trial = params::IsLoFiOnViaFlags() || params::IsIncludedInLoFiEnabledFieldTrial(); bool lite_page_enabled_via_flags_or_field_trial = (params::IsLoFiOnViaFlags() && params::AreLitePagesEnabledViaFlags()) || params::IsIncludedInLitePageFieldTrial(); // User does not have previews enabled. if (!lofi_enabled_via_flags_or_field_trial && !lite_page_enabled_via_flags_or_field_trial) { return; } // Previews has been disabled. if (is_previews_disabled) return; // Do not add the Chrome-Proxy-Accept-Transform header when the page load // explicitly forbids previews transformations. if (request_info->GetPreviewsState() & content::PREVIEWS_NO_TRANSFORM) return; // LoFi is not allowed on the main frame, stylesheet, script, font resource, // media, service worker, or CSP report. bool resource_type_supports_empty_image = !(resource_type == content::RESOURCE_TYPE_MAIN_FRAME || resource_type == content::RESOURCE_TYPE_STYLESHEET || resource_type == content::RESOURCE_TYPE_SCRIPT || resource_type == content::RESOURCE_TYPE_FONT_RESOURCE || resource_type == content::RESOURCE_TYPE_MEDIA || resource_type == content::RESOURCE_TYPE_CSP_REPORT); // If in the lite page field trial or the lite page flag is enabled, only add // the "lite-page" directive on main frame requests. Do not add "empty-image" // directives to other requests when Lite Page previews are enabled. // Add the "if-heavy" qualifier to allow the server to provide a preview when // the page is data heavy on if a preview was not otherwise triggered. std::string accept_transform_value; if (lite_page_enabled_via_flags_or_field_trial) { if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME) accept_transform_value = lite_page_directive(); } else if (lofi_enabled_via_flags_or_field_trial) { if (resource_type_supports_empty_image) accept_transform_value = empty_image_directive(); } if (accept_transform_value.empty()) return; if (!(request_info->GetPreviewsState() & content::SERVER_LOFI_ON)) accept_transform_value += base::StringPrintf(";%s", if_heavy_qualifier()); headers->SetHeader(chrome_proxy_accept_transform_header(), accept_transform_value); } bool ContentLoFiDecider::IsSlowPagePreviewRequested( const net::HttpRequestHeaders& headers) const { std::string accept_transform_header_value; if (!headers.GetHeader(chrome_proxy_accept_transform_header(), &accept_transform_header_value)) { return false; } std::vector<std::string> tokens = base::SplitString(base::ToLowerASCII(accept_transform_header_value), ";", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); // A slow page preview is a request for any unqualified transform type. if (tokens.size() != 1) return false; std::string transform_type; base::TrimWhitespaceASCII(tokens[0], base::TRIM_ALL, &transform_type); return (transform_type == lite_page_directive() || transform_type == empty_image_directive()); } bool ContentLoFiDecider::IsLitePagePreviewRequested( const net::HttpRequestHeaders& headers) const { std::string accept_transform_header_value; if (!headers.GetHeader(chrome_proxy_accept_transform_header(), &accept_transform_header_value)) { return false; } std::vector<std::string> tokens = base::SplitString(base::ToLowerASCII(accept_transform_header_value), ";", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL); if (tokens.empty()) return false; std::string transform_type; base::TrimWhitespaceASCII(tokens[0], base::TRIM_ALL, &transform_type); return transform_type == lite_page_directive(); } void ContentLoFiDecider::RemoveAcceptTransformHeader( net::HttpRequestHeaders* headers) const { headers->RemoveHeader(chrome_proxy_accept_transform_header()); } void ContentLoFiDecider::MaybeSetIgnorePreviewsBlacklistDirective( net::HttpRequestHeaders* headers) const { if (!headers || !params::AreLitePagesEnabledViaFlags() || !IsLitePagePreviewRequested(*headers)) { return; } std::string chrome_proxy_header_value; headers->GetHeader(chrome_proxy_header(), &chrome_proxy_header_value); headers->RemoveHeader(chrome_proxy_header()); if (!chrome_proxy_header_value.empty()) chrome_proxy_header_value += ", "; chrome_proxy_header_value += chrome_proxy_lite_page_ignore_blacklist_directive(); headers->SetHeader(chrome_proxy_header(), chrome_proxy_header_value); } bool ContentLoFiDecider::ShouldRecordLoFiUMA( const net::URLRequest& request) const { const content::ResourceRequestInfo* request_info = content::ResourceRequestInfo::ForRequest(&request); // User is not using Lo-Fi. if (!request_info || !(request_info->GetPreviewsState() & content::SERVER_LOFI_ON)) { return false; } return params::IsIncludedInLoFiEnabledFieldTrial() || params::IsIncludedInLoFiControlFieldTrial(); } } // namespace data_reduction_proxy
38.572139
85
0.743454
[ "vector", "transform" ]
fdfd59dec35b948a5967c2d0e95cbb010288af11
9,945
cpp
C++
src/core/datastructures/volume/volume.cpp
Dapid/inviwo
29c33706ca35cf41c5f6e617c99b0691f0f68ede
[ "BSD-2-Clause" ]
null
null
null
src/core/datastructures/volume/volume.cpp
Dapid/inviwo
29c33706ca35cf41c5f6e617c99b0691f0f68ede
[ "BSD-2-Clause" ]
null
null
null
src/core/datastructures/volume/volume.cpp
Dapid/inviwo
29c33706ca35cf41c5f6e617c99b0691f0f68ede
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2021 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include <inviwo/core/datastructures/volume/volume.h> #include <inviwo/core/datastructures/volume/volumeram.h> #include <inviwo/core/util/document.h> #include <fmt/format.h> namespace inviwo { Volume::Volume(size3_t defaultDimensions, const DataFormatBase* defaultFormat, const SwizzleMask& defaultSwizzleMask, InterpolationType interpolation, const Wrapping3D& wrapping) : Data<Volume, VolumeRepresentation>{} , StructuredGridEntity<3>{} , MetaDataOwner{} , HistogramSupplier{} , dataMap_{defaultFormat} , axes{util::defaultAxes<3>()} , defaultDimensions_{defaultDimensions} , defaultDataFormat_{defaultFormat} , defaultSwizzleMask_{defaultSwizzleMask} , defaultInterpolation_{interpolation} , defaultWrapping_{wrapping} {} Volume::Volume(std::shared_ptr<VolumeRepresentation> in) : Data<Volume, VolumeRepresentation>{} , StructuredGridEntity<3>{} , MetaDataOwner{} , HistogramSupplier{} , dataMap_{in->getDataFormat()} , axes{util::defaultAxes<3>()} , defaultDimensions_{in->getDimensions()} , defaultDataFormat_{in->getDataFormat()} , defaultSwizzleMask_{in->getSwizzleMask()} , defaultInterpolation_{in->getInterpolation()} , defaultWrapping_{in->getWrapping()} { addRepresentation(in); } Volume::Volume(const Volume& rhs, NoData) : Data<Volume, VolumeRepresentation>{} , StructuredGridEntity<3>{rhs} , MetaDataOwner{rhs} , HistogramSupplier{} , dataMap_{rhs.dataMap_} , axes{rhs.axes} , defaultDimensions_{rhs.defaultDimensions_} , defaultDataFormat_{rhs.defaultDataFormat_} , defaultSwizzleMask_{rhs.defaultSwizzleMask_} , defaultInterpolation_{rhs.defaultInterpolation_} , defaultWrapping_{rhs.defaultWrapping_} {} Volume* Volume::clone() const { return new Volume(*this); } Volume::~Volume() = default; void Volume::setDimensions(const size3_t& dim) { defaultDimensions_ = dim; if (lastValidRepresentation_) { // Resize last valid representation lastValidRepresentation_->setDimensions(dim); invalidateAllOther(lastValidRepresentation_.get()); } } size3_t Volume::getDimensions() const { if (lastValidRepresentation_) { return lastValidRepresentation_->getDimensions(); } return defaultDimensions_; } void Volume::setDataFormat(const DataFormatBase* format) { defaultDataFormat_ = format; } const DataFormatBase* Volume::getDataFormat() const { if (lastValidRepresentation_) { return lastValidRepresentation_->getDataFormat(); } return defaultDataFormat_; } void Volume::setSwizzleMask(const SwizzleMask& mask) { defaultSwizzleMask_ = mask; if (lastValidRepresentation_) { lastValidRepresentation_->setSwizzleMask(mask); invalidateAllOther(lastValidRepresentation_.get()); } } SwizzleMask Volume::getSwizzleMask() const { if (lastValidRepresentation_) { return lastValidRepresentation_->getSwizzleMask(); } return defaultSwizzleMask_; } void Volume::setInterpolation(InterpolationType interpolation) { defaultInterpolation_ = interpolation; if (lastValidRepresentation_) { lastValidRepresentation_->setInterpolation(interpolation); invalidateAllOther(lastValidRepresentation_.get()); } } InterpolationType Volume::getInterpolation() const { if (lastValidRepresentation_) { return lastValidRepresentation_->getInterpolation(); } return defaultInterpolation_; } void Volume::setWrapping(const Wrapping3D& wrapping) { defaultWrapping_ = wrapping; if (lastValidRepresentation_) { lastValidRepresentation_->setWrapping(wrapping); invalidateAllOther(lastValidRepresentation_.get()); } } Wrapping3D Volume::getWrapping() const { if (lastValidRepresentation_) { return lastValidRepresentation_->getWrapping(); } return defaultWrapping_; } Document Volume::getInfo() const { using P = Document::PathComponent; using H = utildoc::TableBuilder::Header; Document doc; doc.append("b", "Volume", {{"style", "color:white;"}}); utildoc::TableBuilder tb(doc.handle(), P::end()); tb(H("Format"), getDataFormat()->getString()); tb(H("Dimension"), getDimensions()); tb(H("SwizzleMask"), getSwizzleMask()); tb(H("Interpolation"), getInterpolation()); tb(H("Wrapping"), getWrapping()); tb(H("Data Range"), dataMap_.dataRange); tb(H("Value Range"), dataMap_.valueRange); tb(H("Value"), fmt::format("{}{: [}", dataMap_.valueAxis.name, dataMap_.valueAxis.unit)); tb(H("Axis 1"), fmt::format("{}{: [}", axes[0].name, axes[0].unit)); tb(H("Axis 2"), fmt::format("{}{: [}", axes[1].name, axes[1].unit)); tb(H("Axis 3"), fmt::format("{}{: [}", axes[2].name, axes[2].unit)); if (hasRepresentation<VolumeRAM>()) { if (hasHistograms()) { const auto& histograms = getHistograms(); for (size_t i = 0; i < histograms.size(); ++i) { std::stringstream ss; ss << "Channel " << i << " Min: " << histograms[i].stats_.min << " Mean: " << histograms[i].stats_.mean << " Max: " << histograms[i].stats_.max << " Std: " << histograms[i].stats_.standardDeviation; tb(H("Stats"), ss.str()); std::stringstream ss2; ss2 << "(1: " << histograms[i].stats_.percentiles[1] << ", 25: " << histograms[i].stats_.percentiles[25] << ", 50: " << histograms[i].stats_.percentiles[50] << ", 75: " << histograms[i].stats_.percentiles[75] << ", 99: " << histograms[i].stats_.percentiles[99] << ")"; tb(H("Percentiles"), ss2.str()); } } } return doc; } vec3 Volume::getWorldSpaceGradientSpacing() const { mat3 textureToWorld = mat3(getCoordinateTransformer().getTextureToWorldMatrix()); // Basis vectors with a length of one voxel. // Basis vectors may be non-orthogonal auto dimensions = getDimensions(); vec3 a = textureToWorld[0] / static_cast<float>(dimensions[0]); vec3 b = textureToWorld[1] / static_cast<float>(dimensions[1]); vec3 c = textureToWorld[2] / static_cast<float>(dimensions[2]); // Project the voxel basis vectors // onto the world space x/y/z axes, // and choose the longest projected vector // for each axis. // Using the fact that // vec3 x{ 1.f, 0, 0 }; // vec3 y{ 0, 1.f, 0 }; // vec3 z{ 0, 0, 1.f }; // such that // ax' = dot(x, a) = a.x // bx' = dot(x, b) = b.x // cx' = dot(x, c) = c.x // and so on. auto signedMax = [](const float& x1, const float& x2) { return (std::abs(x1) >= std::abs(x2)) ? x1 : x2; }; vec3 ds{signedMax(a.x, signedMax(b.x, c.x)), signedMax(a.y, signedMax(b.y, c.y)), signedMax(a.z, signedMax(b.z, c.z))}; // Return the spacing in world space, // actually given by: // { gradientSpacing.x 0 0 // 0 gradientSpacing.y 0 // 0 0 gradientSpacing.z } return ds; } uvec3 Volume::colorCode = uvec3(188, 101, 101); const std::string Volume::classIdentifier = "org.inviwo.Volume"; const std::string Volume::dataName = "Volume"; const StructuredCameraCoordinateTransformer<3>& Volume::getCoordinateTransformer( const Camera& camera) const { return StructuredGridEntity<3>::getCoordinateTransformer(camera); } std::shared_ptr<HistogramCalculationState> Volume::calculateHistograms(size_t bins) const { getRepresentation<VolumeRAM>(); // make sure lastValidRepresentation_ is VolumeRAM return HistogramSupplier::startCalculation( std::static_pointer_cast<VolumeRAM>(lastValidRepresentation_), dataMap_.dataRange, bins); } template class IVW_CORE_TMPL_INST DataReaderType<Volume>; template class IVW_CORE_TMPL_INST DataWriterType<Volume>; template class IVW_CORE_TMPL_INST DataReaderType<VolumeSequence>; template class IVW_CORE_TMPL_INST DataInport<Volume>; template class IVW_CORE_TMPL_INST DataOutport<Volume>; template class IVW_CORE_TMPL_INST DataInport<VolumeSequence>; template class IVW_CORE_TMPL_INST DataOutport<VolumeSequence>; } // namespace inviwo
38.25
100
0.666063
[ "vector" ]
a90266cdf0a2118d6024867a633d7a4caa54fedb
4,890
cpp
C++
Tools/EditorFramework/Actions/Implementation/AssetActions.cpp
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
null
null
null
Tools/EditorFramework/Actions/Implementation/AssetActions.cpp
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
null
null
null
Tools/EditorFramework/Actions/Implementation/AssetActions.cpp
eltld/ezEngine
3230235249dd2769f166872b753efd6bd8347c98
[ "CC-BY-3.0" ]
1
2020-03-08T04:55:16.000Z
2020-03-08T04:55:16.000Z
#include <PCH.h> #include <EditorFramework/Actions/AssetActions.h> #include <EditorFramework/Assets/AssetDocument.h> #include <EditorFramework/Assets/AssetCurator.h> #include <GuiFoundation/Action/ActionMapManager.h> #include <GuiFoundation/Action/ActionManager.h> ezActionDescriptorHandle ezAssetActions::s_hAssetCategory; ezActionDescriptorHandle ezAssetActions::s_hTransformAsset; ezActionDescriptorHandle ezAssetActions::s_hTransformAllAssets; ezActionDescriptorHandle ezAssetActions::s_hCheckFileSystem; ezActionDescriptorHandle ezAssetActions::s_hWriteLookupTable; ezActionDescriptorHandle ezAssetActions::s_hRetrieveAssetInfo; void ezAssetActions::RegisterActions() { s_hAssetCategory = EZ_REGISTER_CATEGORY("AssetCategory"); s_hTransformAsset = EZ_REGISTER_ACTION_1("TransformAsset", "Transform Asset", ezActionScope::Document, "Assets", "", ezAssetAction, ezAssetAction::ButtonType::TransformAsset); s_hTransformAllAssets = EZ_REGISTER_ACTION_1("TransformAllAssets", "Transform All Assets", ezActionScope::Global, "Assets", "", ezAssetAction, ezAssetAction::ButtonType::TransformAllAssets); s_hCheckFileSystem = EZ_REGISTER_ACTION_1("CheckFilesystem", "Check Filesystem", ezActionScope::Global, "Assets", "", ezAssetAction, ezAssetAction::ButtonType::CheckFileSystem); s_hWriteLookupTable = EZ_REGISTER_ACTION_1("WriteLookupTable", "Write Lookup Table", ezActionScope::Global, "Assets", "", ezAssetAction, ezAssetAction::ButtonType::WriteLookupTable); s_hRetrieveAssetInfo = EZ_REGISTER_ACTION_1("RetrieveAssetInfo", "Retrieve Asset Info", ezActionScope::Document, "Assets", "", ezAssetAction, ezAssetAction::ButtonType::RetrieveAssetInfo); } void ezAssetActions::UnregisterActions() { ezActionManager::UnregisterAction(s_hAssetCategory); ezActionManager::UnregisterAction(s_hTransformAsset); ezActionManager::UnregisterAction(s_hTransformAllAssets); ezActionManager::UnregisterAction(s_hCheckFileSystem); ezActionManager::UnregisterAction(s_hWriteLookupTable); ezActionManager::UnregisterAction(s_hRetrieveAssetInfo); } void ezAssetActions::MapActions(const char* szMapping, bool bDocument) { ezActionMap* pMap = ezActionMapManager::GetActionMap(szMapping); EZ_ASSERT_DEV(pMap != nullptr, "The given mapping ('%s') does not exist, mapping the actions failed!", szMapping); pMap->MapAction(s_hAssetCategory, "", 10.0f); if (bDocument) { pMap->MapAction(s_hTransformAsset, "AssetCategory", 1.0f); pMap->MapAction(s_hRetrieveAssetInfo, "AssetCategory", 2.0f); } else { pMap->MapAction(s_hTransformAllAssets, "AssetCategory", 1.0f); } pMap->MapAction(s_hCheckFileSystem, "AssetCategory", 3.0f); pMap->MapAction(s_hWriteLookupTable, "AssetCategory", 4.0f); } //////////////////////////////////////////////////////////////////////// // ezAssetAction //////////////////////////////////////////////////////////////////////// EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezAssetAction, ezButtonAction, 0, ezRTTINoAllocator); EZ_END_DYNAMIC_REFLECTED_TYPE(); ezAssetAction::ezAssetAction(const ezActionContext& context, const char* szName, ButtonType button) : ezButtonAction(context, szName, false, "") { m_ButtonType = button; switch (m_ButtonType) { case ezAssetAction::ButtonType::TransformAsset: SetIconPath(":/GuiFoundation/Icons/TransformAssets16.png"); break; case ezAssetAction::ButtonType::TransformAllAssets: SetIconPath(":/GuiFoundation/Icons/TransformAllAssets16.png"); break; case ezAssetAction::ButtonType::CheckFileSystem: SetIconPath(":/GuiFoundation/Icons/CheckFileSystem16.png"); break; case ezAssetAction::ButtonType::WriteLookupTable: SetIconPath(":/GuiFoundation/Icons/WriteLookupTable16.png"); break; case ezAssetAction::ButtonType::RetrieveAssetInfo: SetIconPath(":/GuiFoundation/Icons/RetriveAssetInfo16.png"); break; } } ezAssetAction::~ezAssetAction() { } void ezAssetAction::Execute(const ezVariant& value) { switch (m_ButtonType) { case ezAssetAction::ButtonType::TransformAsset: { ezAssetDocument* pDoc = static_cast<ezAssetDocument*>(m_Context.m_pDocument); pDoc->TransformAsset(); ezAssetCurator::GetInstance()->WriteAssetTables(); } break; case ezAssetAction::ButtonType::TransformAllAssets: { ezAssetCurator::GetInstance()->TransformAllAssets(); } break; case ezAssetAction::ButtonType::CheckFileSystem: { ezAssetCurator::GetInstance()->CheckFileSystem(); ezAssetCurator::GetInstance()->WriteAssetTables(); } break; case ezAssetAction::ButtonType::WriteLookupTable: { ezAssetCurator::GetInstance()->WriteAssetTables(); } break; case ezAssetAction::ButtonType::RetrieveAssetInfo: { ezAssetDocument* pDoc = static_cast<ezAssetDocument*>(m_Context.m_pDocument); pDoc->RetrieveAssetInfo(); } break; } }
35.955882
192
0.74908
[ "transform" ]
a902db5f4940a1911d318dc2527f503f7b0cc77c
16,519
cpp
C++
src/CardinalityEstimators.cpp
a-kr/vertica_approx_distinct
f061a5e4c41c85ef4a0b786748c811159be8c31c
[ "MIT" ]
1
2015-02-22T17:27:59.000Z
2015-02-22T17:27:59.000Z
src/CardinalityEstimators.cpp
Babazka/vertica_approx_distinct
f061a5e4c41c85ef4a0b786748c811159be8c31c
[ "MIT" ]
null
null
null
src/CardinalityEstimators.cpp
Babazka/vertica_approx_distinct
f061a5e4c41c85ef4a0b786748c811159be8c31c
[ "MIT" ]
1
2017-11-13T08:12:30.000Z
2017-11-13T08:12:30.000Z
#include <vector> #include <algorithm> #include <stdexcept> #include <queue> #include <cmath> #include <cstdlib> #include <cstring> #include <cstdio> #include <stdint.h> #include "MurmurHash3.h" #include "CardinalityEstimators.h" /******** Utilities *******/ #define UINT64_MAX (18446744073709551615ULL) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) std::string human_readable_size(int bytes) { char buf[20]; int kb = bytes / 1024; int b = bytes % 1024; if (kb == 0) { sprintf(buf, "%d", b); } else if (kb < 1024) { sprintf(buf, "%dK", kb); } else { sprintf(buf, "%.1fM", double(kb) / 1024.0); } return std::string(buf); } void print_binary(uint64_t n) { int i; for (i = 63; i >= 0; i--) { if (n & (1 << i)) { printf("1"); } else { printf("0"); } } printf("\n"); } int constrain_int(int v, int min, int max) { if (v > max) { return max; } else if (v < min) { return min; } return v; } /* Counts the length of the run of `one` bits starting from the least significant bits * TODO: probably can be crazily optimized */ inline int count_run_of_ones(uint64_t val) { int n = 0; while (val) { if (val & 1) { n++; val = val >> 1; } else { break; } } /* HACK: this '+1' should not be here, and compensates for some unknown bug * elsewhere in the code, which I was not able to locate */ return n + 1; } /******** HashingCardinalityEstimator ********/ uint64_t HashingCardinalityEstimator::hash(const char *key) { int key_len = strlen(key); uint64_t h[2]; MurmurHash3_x64_128(key, key_len, 0, &h[0]); return h[0]; } uint64_t HashingCardinalityEstimator::hash(const char *key, int key_len) { uint64_t h[2]; MurmurHash3_x64_128(key, key_len, 0, &h[0]); return h[0]; } /******* LinearProbabilisticCounter ********/ LinearProbabilisticCounter::LinearProbabilisticCounter(int size): _bitset(size, false) { this->size_in_bits = size; } void LinearProbabilisticCounter::increment(const char *key, int len) { if (len == -1) { len = strlen(key); } uint64_t h = this->hash(key, len); uint64_t i = h % this->size_in_bits; this->_bitset[i] = true; } int LinearProbabilisticCounter::count_set_bits() { return (int)std::count( this->_bitset.begin(), this->_bitset.end(), true ); } int LinearProbabilisticCounter::count() { /* -size * ln(unset_bits/size) */ int unset_bits = this->size_in_bits - this->count_set_bits(); if (unset_bits == 0) { return this->size_in_bits; } double ratio = double(unset_bits) / double(this->size_in_bits); return -this->size_in_bits * log(ratio); } std::string LinearProbabilisticCounter::repr() { char buf[100]; int memory = this->size_in_bits / 8; sprintf(buf, "LinearProbabilisticCounter(n=%d, %s bytes)", this->size_in_bits, human_readable_size(memory).c_str()); return std::string(buf); } void LinearProbabilisticCounter::merge_from(ICardinalityEstimator *that) { LinearProbabilisticCounter *other = (LinearProbabilisticCounter *)that; int i; if (this->size_in_bits != other->size_in_bits) { throw std::runtime_error("cannot merge LinearProbabilisticCounters with different parameters"); } for (i = 0; i < this->size_in_bits; i++) { this->_bitset[i] = this->_bitset[i] || other->_bitset[i]; } } ICardinalityEstimator* LinearProbabilisticCounter::clone() { return new LinearProbabilisticCounter(this->size_in_bits); } void LinearProbabilisticCounter::serialize(Serializer *serializer) { serializer->write_int(this->size_in_bits); uint64_t bit_buffer = 0; int bb_i = 0; int bit_i; for (bit_i = 0; bit_i < this->size_in_bits; bit_i++) { bit_buffer |= ((uint64_t)this->_bitset[bit_i] << bb_i); bb_i++; if (unlikely(bb_i >= 64)) { serializer->write_uint64_t(bit_buffer); bit_buffer = 0; bb_i = 0; } } if (bb_i > 0) { serializer->write_uint64_t(bit_buffer); } } void LinearProbabilisticCounter::unserialize(Serializer *serializer) { this->size_in_bits = serializer->read_int(); this->_bitset.resize(this->size_in_bits, false); uint64_t bit_buffer = 0; int bb_i = 64; // to force read on the first iteration int bit_i = 0; for (bit_i = 0; bit_i < this->size_in_bits; bit_i++) { if (unlikely(bb_i >= 64)) { bit_buffer = serializer->read_uint64_t(); bb_i = 0; } this->_bitset[bit_i] = !!(bit_buffer & ((uint64_t)1 << bb_i)); bb_i++; } } /******* KMinValuesCounter ********/ KMinValuesCounter::KMinValuesCounter(int k) : _minimal_values() { this->k = k; } int KMinValuesCounter::get_real_k() { if ((int)this->_minimal_values.size() < this->k) { return this->k; } return this->_minimal_values.size(); } void KMinValuesCounter::increment(const char *key, int len) { if (len == -1) { len = strlen(key); } uint64_t h = this->hash(key, len); if (unlikely((int)this->_minimal_values.size() < this->k)) { this->_minimal_values.push(h); } else if (unlikely(h < this->_minimal_values.top())) { if (likely((int)this->_minimal_values.size() == this->k)) { this->_minimal_values.pop(); this->_minimal_values.push(h); } } } int KMinValuesCounter::count() { /* (k - 1) / kth_min_normalized */ /* == (k - 1) / (kth_min / UINT64_MAX) */ /* == UINT64_MAX * (k - 1) / kth_min */ int k = this->get_real_k(); if (k == 0) { return 0; } return int(UINT64_MAX * double(k - 1) / double(this->_minimal_values.top())); } std::string KMinValuesCounter::repr() { char buf[50]; int memory = sizeof(uint64_t) * this->k; sprintf(buf, "KMinValuesCounter(k=%d, %s bytes)", this->k, human_readable_size(memory).c_str()); return std::string(buf); } /* Caution: this is a destructive merge, i.e. it empties "that" counter */ void KMinValuesCounter::merge_from(ICardinalityEstimator *that) { KMinValuesCounter *other = (KMinValuesCounter *)that; uint64_t v; while (!other->_minimal_values.empty()) { v = other->_minimal_values.top(); other->_minimal_values.pop(); if (v < this->_minimal_values.top()) { if ((int)this->_minimal_values.size() == this->k) { this->_minimal_values.pop(); } this->_minimal_values.push(v); } } } ICardinalityEstimator* KMinValuesCounter::clone() { return new KMinValuesCounter(this->k); } void KMinValuesCounter::serialize(Serializer *serializer) { std::vector<uint64_t> backup_for_queue; serializer->write_int(this->k); serializer->write_int(this->_minimal_values.size()); while (!this->_minimal_values.empty()) { uint64_t v = this->_minimal_values.top(); this->_minimal_values.pop(); backup_for_queue.push_back(v); serializer->write_uint64_t(v); } while (!backup_for_queue.empty()) { uint64_t v = backup_for_queue.back(); backup_for_queue.pop_back(); this->_minimal_values.push(v); } } void KMinValuesCounter::unserialize(Serializer *serializer) { this->k = serializer->read_int(); int n = serializer->read_int(); // strangely enough, priority_queue has no method clear() while (!this->_minimal_values.empty()) { this->_minimal_values.pop(); } for (int i = 0; i < n; i++) { uint64_t v = serializer->read_uint64_t(); //printf("restoring %lu\n", v); this->_minimal_values.push(v); } } /******* HyperLogLogCounter ********/ #define HYPER_LOG_LOG_B_MAX 20 HyperLogLogCounter::HyperLogLogCounter(int b): buckets( int(pow(2, constrain_int(b, 4, HYPER_LOG_LOG_B_MAX))), 0) { this->b = b; this->m = int(pow(2, constrain_int(b, 4, HYPER_LOG_LOG_B_MAX))); this->m_mask = this->m - 1; // 'b' ones } double HyperLogLogCounter::get_alpha() { switch (this->b) { case 4: return 0.673; case 5: return 0.697; case 6: return 0.709; } return 0.7213 / (1.0 + 1.079 / double(1 << this->b)); } void HyperLogLogCounter::increment(const char *key, int len) { if (len == -1) { len = strlen(key); } uint64_t h = this->hash(key, len); int j = h & this->m_mask; uint64_t w = h >> this->b; int run_of_ones = count_run_of_ones(w); this->buckets[j] = (run_of_ones > this->buckets[j]) ? run_of_ones : this->buckets[j]; } int HyperLogLogCounter::count() { /* DV_est = alpha * m^2 * 1/sum( 2^ -register ) */ double estimate = this->get_alpha() * this->m * this->m; double sum = 0.0; int i; for (i = 0; i < this->m; i++) { sum += pow(2, -this->buckets[i]); } estimate = estimate * 1.0 / sum; if (estimate < 2.5 * this->m) { // small range correction int v = this->number_of_zero_buckets(); if (v > 0) { estimate = this->m * log(this->m / double(v)); } } else if (estimate > 1/30.0 * pow(2, 64)) { // large range correction (for hash collisions) // And we use a 64-bit hash... estimate = -pow(2, 64) * log(1.0 - estimate / pow(2, 64)); } return estimate; } int HyperLogLogCounter::number_of_zero_buckets() { return (int)std::count( this->buckets.begin(), this->buckets.end(), 0 ); } std::string HyperLogLogCounter::repr() { char buf[50]; int memory = sizeof(int) * this->m; sprintf(buf, "HyperLogLogCounter(b=%d, m=%d, %s bytes)", this->b, this->m, human_readable_size(memory).c_str()); return std::string(buf); } void HyperLogLogCounter::merge_from(ICardinalityEstimator *that) { HyperLogLogCounter *other = (HyperLogLogCounter *)that; if (this->m != other->m) { throw std::runtime_error("cannot merge HyperLogLogCounters with different parameters"); } int i; for (i = 0; i < this->m; i++) { int my_v = this->buckets[i]; int his_v = other->buckets[i]; this->buckets[i] = (my_v > his_v) ? my_v : his_v; } } ICardinalityEstimator* HyperLogLogCounter::clone() { return new HyperLogLogCounter(this->b); } void HyperLogLogCounter::serialize(Serializer *serializer) { serializer->write_int(this->b); serializer->write_int(this->m); serializer->write_int(this->m_mask); for (int i = 0; i < this->m; i++) { serializer->write_int(this->buckets[i]); } } void HyperLogLogCounter::unserialize(Serializer *serializer) { this->b = serializer->read_int(); this->m = serializer->read_int(); this->m_mask = serializer->read_int(); this->buckets.resize(this->m); for (int i = 0; i < this->m; i++) { int v = serializer->read_int(); this->buckets[i] = v; } } /******* HyperLogLogOwnArrayCounter ********/ HyperLogLogOwnArrayCounter::HyperLogLogOwnArrayCounter(int b, char *storage0, char *storage1) { this->own_buckets_memory = false; this->b = b; this->m = int(pow(2, constrain_int(b, 4, HYPER_LOG_LOG_B_MAX))); this->m_mask = this->m - 1; // 'b' ones if (storage0 && storage1) { this->buckets[0] = (uint32_t *)storage0; this->buckets[1] = (uint32_t *)storage1; } else { this->buckets[0] = new uint32_t[this->m/2]; this->buckets[1] = new uint32_t[this->m/2]; this->own_buckets_memory = true; for (int i = 0; i < this->m/2; i++) { this->buckets[0][i] = 0; this->buckets[1][i] = 0; } } } HyperLogLogOwnArrayCounter::~HyperLogLogOwnArrayCounter() { if (this->own_buckets_memory) { delete this->buckets[0]; delete this->buckets[1]; } } double HyperLogLogOwnArrayCounter::get_alpha() { switch (this->b) { case 4: return 0.673; case 5: return 0.697; case 6: return 0.709; } return 0.7213 / (1.0 + 1.079 / double(1 << this->b)); } /* TODO: move to HLL base class */ void HyperLogLogOwnArrayCounter::increment(const char *key, int len) { if (len == -1) { len = strlen(key); } uint64_t h = this->hash(key, len); int j = h & this->m_mask; int j_bucket = j & 1; j = j >> 1; uint64_t w = h >> this->b; uint32_t run_of_ones = (uint32_t)count_run_of_ones(w); uint32_t old_value = this->buckets[j_bucket][j]; this->buckets[j_bucket][j] = (run_of_ones > old_value) ? run_of_ones : old_value; } int HyperLogLogOwnArrayCounter::count() { /* DV_est = alpha * m^2 * 1/sum( 2^ -register ) */ double estimate = this->get_alpha() * this->m * this->m; double sum = 0.0; int i; for (i = 0; i < this->m/2; i++) { sum += pow(2, -(double)this->buckets[0][i]); sum += pow(2, -(double)this->buckets[1][i]); } estimate = estimate * 1.0 / sum; if (estimate < 2.5 * this->m) { // small range correction int v = this->number_of_zero_buckets(); if (v > 0) { estimate = this->m * log(this->m / double(v)); } } else if (estimate > 1/30.0 * pow(2, 64)) { // large range correction (for hash collisions) // And we use a 64-bit hash... estimate = -pow(2, 64) * log(1.0 - estimate / pow(2, 64)); } return estimate; } int HyperLogLogOwnArrayCounter::number_of_zero_buckets() { int i, count = 0; for (i = 0; i < this->m/2; i++) { if (this->buckets[0][i] == 0) { count++; } if (this->buckets[1][i] == 0) { count++; } } return count; } std::string HyperLogLogOwnArrayCounter::repr() { char buf[100]; int memory = sizeof(this->buckets[0][0]) * this->m; sprintf(buf, "HyperLogLogOwnArrayCounter(b=%d, m=%d, %s bytes)", this->b, this->m, human_readable_size(memory).c_str()); return std::string(buf); } void HyperLogLogOwnArrayCounter::merge_from(ICardinalityEstimator *that) { HyperLogLogOwnArrayCounter *other = (HyperLogLogOwnArrayCounter *)that; if (this->m != other->m) { throw std::runtime_error("cannot merge HyperLogLogOwnArrayCounter with different parameters"); } int i; for (i = 0; i < this->m/2; i++) { uint32_t my_v = this->buckets[0][i]; uint32_t his_v = other->buckets[0][i]; this->buckets[0][i] = (my_v > his_v) ? my_v : his_v; my_v = this->buckets[1][i]; his_v = other->buckets[1][i]; this->buckets[1][i] = (my_v > his_v) ? my_v : his_v; } } ICardinalityEstimator* HyperLogLogOwnArrayCounter::clone() { return new HyperLogLogOwnArrayCounter(this->b, NULL, NULL); } void HyperLogLogOwnArrayCounter::serialize(Serializer *serializer) { serializer->write_int(this->b); serializer->write_int(this->m); serializer->write_int(this->m_mask); for (int i = 0; i < this->m/2; i++) { serializer->write_uint32_t(this->buckets[0][i]); serializer->write_uint32_t(this->buckets[1][i]); } } void HyperLogLogOwnArrayCounter::unserialize(Serializer *serializer) { this->b = serializer->read_int(); this->m = serializer->read_int(); this->m_mask = serializer->read_int(); //this->buckets.resize(this->m); for (int i = 0; i < this->m/2; i++) { uint32_t v = serializer->read_uint32_t(); this->buckets[0][i] = v; v = serializer->read_uint32_t(); this->buckets[1][i] = v; } } /******* DummyCounter ********/ DummyCounter::DummyCounter(int ignored) { this->c = 0; } void DummyCounter::increment(const char *key, int len) { this->c++; } int DummyCounter::count() { return this->c; } std::string DummyCounter::repr() { char buf[50]; int memory = sizeof(int); sprintf(buf, "DummyCounter(%s bytes)", human_readable_size(memory).c_str()); return std::string(buf); } void DummyCounter::merge_from(ICardinalityEstimator *that) { DummyCounter *other = (DummyCounter *)that; this->c += other->c; } ICardinalityEstimator* DummyCounter::clone() { return new DummyCounter(0); } void DummyCounter::serialize(Serializer *serializer) { serializer->write_int(this->c); } void DummyCounter::unserialize(Serializer *serializer) { this->c = serializer->read_int(); }
29.289007
124
0.599007
[ "vector" ]
a9049088d4ebd7453e69832d542ba0cb635c68f1
11,956
cc
C++
src/Net.cc
markh15/zeek
b41cb78f8d6e205d49e175aef2d2279918809cf7
[ "Apache-2.0" ]
null
null
null
src/Net.cc
markh15/zeek
b41cb78f8d6e205d49e175aef2d2279918809cf7
[ "Apache-2.0" ]
null
null
null
src/Net.cc
markh15/zeek
b41cb78f8d6e205d49e175aef2d2279918809cf7
[ "Apache-2.0" ]
null
null
null
// See the file "COPYING" in the main distribution directory for copyright. #include "zeek-config.h" #include "Net.h" #include <sys/types.h> #ifdef TIME_WITH_SYS_TIME # include <sys/time.h> # include <time.h> #else # ifdef HAVE_SYS_TIME_H # include <sys/time.h> # else # include <time.h> # endif #endif #include <errno.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> extern "C" { #include "setsignal.h" }; #include "NetVar.h" #include "Sessions.h" #include "Event.h" #include "Timer.h" #include "ID.h" #include "Reporter.h" #include "Scope.h" #include "Anon.h" #include "iosource/Manager.h" #include "iosource/PktSrc.h" #include "iosource/PktDumper.h" #include "plugin/Manager.h" #include "broker/Manager.h" extern "C" { extern int select(int, fd_set *, fd_set *, fd_set *, struct timeval *); } iosource::PktDumper* pkt_dumper = nullptr; bool reading_live = false; bool reading_traces = false; bool have_pending_timers = false; double pseudo_realtime = 0.0; double network_time = 0.0; // time according to last packet timestamp // (or current time) double processing_start_time = 0.0; // time started working on current pkt double bro_start_time = 0.0; // time Bro started. double bro_start_network_time; // timestamp of first packet double last_watchdog_proc_time = 0.0; // value of above during last watchdog bool terminating = false; // whether we're done reading and finishing up bool is_parsing = false; const zeek::Packet *current_pkt = nullptr; int current_dispatched = 0; double current_timestamp = 0.0; iosource::PktSrc* current_pktsrc = nullptr; iosource::IOSource* current_iosrc = nullptr; std::list<ScannedFile> files_scanned; std::vector<std::string> sig_files; RETSIGTYPE watchdog(int /* signo */) { if ( processing_start_time != 0.0 ) { // The signal arrived while we're processing a packet and/or // its corresponding event queue. Check whether we've been // spending too much time, which we take to mean we've wedged. // Note that it's subtle how exactly to test this. In // processing_start_time we have the timestamp of the packet // we're currently working on. But that *doesn't* mean that // we began work on the packet at that time; we could have // begun at a much later time, depending on how long the // packet filter waited (to fill its buffer) before handing // up this packet. So what we require is that the current // processing_start_time matches the processing_start_time we // observed last time the watchdog went off. If so, then // we've been working on the current packet for at least // watchdog_interval seconds. if ( processing_start_time == last_watchdog_proc_time ) { // snprintf() calls alloc/free routines if you use %f! // We need to avoid doing that given we're in a single // handler and the allocation routines are not // reentrant. double ct = current_time(); int int_ct = int(ct); int frac_ct = int((ct - int_ct) * 1e6); int int_pst = int(processing_start_time); int frac_pst = int((processing_start_time - int_pst) * 1e6); if ( current_pkt ) { if ( ! pkt_dumper ) { // We aren't dumping packets; however, // saving the packet which caused the // watchdog to trigger may be helpful, // so we'll save that one nevertheless. pkt_dumper = iosource_mgr->OpenPktDumper("watchdog-pkt.pcap", false); if ( ! pkt_dumper || pkt_dumper->IsError() ) { zeek::reporter->Error("watchdog: can't open watchdog-pkt.pcap for writing"); pkt_dumper = nullptr; } } if ( pkt_dumper ) pkt_dumper->Dump(current_pkt); } net_get_final_stats(); net_finish(0); zeek::reporter->FatalErrorWithCore( "**watchdog timer expired, t = %d.%06d, start = %d.%06d, dispatched = %d", int_ct, frac_ct, int_pst, frac_pst, current_dispatched); } } last_watchdog_proc_time = processing_start_time; (void) alarm(watchdog_interval); return RETSIGVAL; } void net_update_time(double new_network_time) { network_time = new_network_time; PLUGIN_HOOK_VOID(HOOK_UPDATE_NETWORK_TIME, HookUpdateNetworkTime(new_network_time)); } void net_init(const std::optional<std::string>& interface, const std::optional<std::string>& pcap_input_file, const std::optional<std::string>& pcap_output_file, bool do_watchdog) { if ( pcap_input_file ) { reading_live = pseudo_realtime > 0.0; reading_traces = true; iosource::PktSrc* ps = iosource_mgr->OpenPktSrc(*pcap_input_file, false); assert(ps); if ( ! ps->IsOpen() ) zeek::reporter->FatalError("problem with trace file %s (%s)", pcap_input_file->c_str(), ps->ErrorMsg()); } else if ( interface ) { reading_live = true; reading_traces = false; iosource::PktSrc* ps = iosource_mgr->OpenPktSrc(*interface, true); assert(ps); if ( ! ps->IsOpen() ) zeek::reporter->FatalError("problem with interface %s (%s)", interface->c_str(), ps->ErrorMsg()); } else // have_pending_timers = true, possibly. We don't set // that here, though, because at this point we don't know // whether the user's zeek_init() event will indeed set // a timer. reading_traces = reading_live = false; if ( pcap_output_file ) { const char* writefile = pcap_output_file->data(); pkt_dumper = iosource_mgr->OpenPktDumper(writefile, false); assert(pkt_dumper); if ( ! pkt_dumper->IsOpen() ) zeek::reporter->FatalError("problem opening dump file %s (%s)", writefile, pkt_dumper->ErrorMsg()); if ( const auto& id = zeek::detail::global_scope()->Find("trace_output_file") ) id->SetVal(zeek::make_intrusive<zeek::StringVal>(writefile)); else zeek::reporter->Error("trace_output_file not defined in bro.init"); } zeek::detail::init_ip_addr_anonymizers(); zeek::sessions = new zeek::NetSessions(); if ( do_watchdog ) { // Set up the watchdog to make sure we don't wedge. (void) setsignal(SIGALRM, watchdog); (void) alarm(watchdog_interval); } } void expire_timers(iosource::PktSrc* src_ps) { zeek::detail::SegmentProfiler prof(zeek::detail::segment_logger, "expiring-timers"); current_dispatched += zeek::detail::timer_mgr->Advance(network_time, max_timer_expires - current_dispatched); } void net_packet_dispatch(double t, const zeek::Packet* pkt, iosource::PktSrc* src_ps) { if ( ! bro_start_network_time ) { bro_start_network_time = t; if ( network_time_init ) zeek::event_mgr.Enqueue(network_time_init, zeek::Args{}); } // network_time never goes back. net_update_time(zeek::detail::timer_mgr->Time() < t ? t : zeek::detail::timer_mgr->Time()); current_pktsrc = src_ps; current_iosrc = src_ps; processing_start_time = t; expire_timers(src_ps); zeek::detail::SegmentProfiler* sp = nullptr; if ( load_sample ) { static uint32_t load_freq = 0; if ( load_freq == 0 ) load_freq = uint32_t(0xffffffff) / uint32_t(load_sample_freq); if ( uint32_t(zeek::random_number() & 0xffffffff) < load_freq ) { // Drain the queued timer events so they're not // charged against this sample. zeek::event_mgr.Drain(); zeek::detail::sample_logger = new zeek::detail::SampleLogger(); sp = new zeek::detail::SegmentProfiler(zeek::detail::sample_logger, "load-samp"); } } zeek::sessions->NextPacket(t, pkt); zeek::event_mgr.Drain(); if ( sp ) { delete sp; delete zeek::detail::sample_logger; zeek::detail::sample_logger = nullptr; } processing_start_time = 0.0; // = "we're not processing now" current_dispatched = 0; current_iosrc = nullptr; current_pktsrc = nullptr; } void net_run() { set_processing_status("RUNNING", "net_run"); std::vector<iosource::IOSource*> ready; ready.reserve(iosource_mgr->TotalSize()); while ( iosource_mgr->Size() || (zeek::BifConst::exit_only_after_terminate && ! terminating) ) { iosource_mgr->FindReadySources(&ready); #ifdef DEBUG static int loop_counter = 0; // If no source is ready, we log only every 100th cycle, // starting with the first. if ( ! ready.empty() || loop_counter++ % 100 == 0 ) { DBG_LOG(zeek::DBG_MAINLOOP, "realtime=%.6f ready_count=%zu", current_time(), ready.size()); if ( ! ready.empty() ) loop_counter = 0; } #endif current_iosrc = nullptr; auto communication_enabled = broker_mgr->Active(); if ( ! ready.empty() ) { for ( auto src : ready ) { DBG_LOG(zeek::DBG_MAINLOOP, "processing source %s", src->Tag()); current_iosrc = src; src->Process(); } } else if ( (have_pending_timers || communication_enabled || zeek::BifConst::exit_only_after_terminate) && ! pseudo_realtime ) { // Take advantage of the lull to get up to // date on timers and events. Because we only // have timers as sources, going to sleep here // doesn't risk blocking on other inputs. net_update_time(current_time()); expire_timers(); } zeek::event_mgr.Drain(); processing_start_time = 0.0; // = "we're not processing now" current_dispatched = 0; current_iosrc = nullptr; extern int signal_val; if ( signal_val == SIGTERM || signal_val == SIGINT ) // We received a signal while processing the // current packet and its related events. // Should we put the signal handling into an IOSource? zeek_terminate_loop("received termination signal"); if ( ! reading_traces ) // Check whether we have timers scheduled for // the future on which we need to wait. have_pending_timers = zeek::detail::timer_mgr->Size() > 0; if ( pseudo_realtime && communication_enabled ) { auto have_active_packet_source = false; iosource::PktSrc* ps = iosource_mgr->GetPktSrc(); if ( ps && ps->IsOpen() ) have_active_packet_source = true; if ( ! have_active_packet_source ) // Can turn off pseudo realtime now pseudo_realtime = 0.0; } } // Get the final statistics now, and not when net_finish() is // called, since that might happen quite a bit in the future // due to expiring pending timers, and we don't want to ding // for any packets dropped beyond this point. net_get_final_stats(); } void net_get_final_stats() { iosource::PktSrc* ps = iosource_mgr->GetPktSrc(); if ( ps && ps->IsLive() ) { iosource::PktSrc::Stats s; ps->Statistics(&s); double dropped_pct = s.dropped > 0.0 ? ((double)s.dropped / ((double)s.received + (double)s.dropped)) * 100.0 : 0.0; zeek::reporter->Info("%" PRIu64 " packets received on interface %s, %" PRIu64 " (%.2f%%) dropped", s.received, ps->Path().c_str(), s.dropped, dropped_pct); } } void net_finish(int drain_events) { set_processing_status("TERMINATING", "net_finish"); if ( drain_events ) { if ( zeek::sessions ) zeek::sessions->Drain(); zeek::event_mgr.Drain(); if ( zeek::sessions ) zeek::sessions->Done(); } #ifdef DEBUG extern int reassem_seen_bytes, reassem_copied_bytes; // DEBUG_MSG("Reassembly (TCP and IP/Frag): %d bytes seen, %d bytes copied\n", // reassem_seen_bytes, reassem_copied_bytes); extern int num_packets_held, num_packets_cleaned; // DEBUG_MSG("packets clean up: %d/%d\n", num_packets_cleaned, num_packets_held); #endif } void net_delete() { set_processing_status("TERMINATING", "net_delete"); delete zeek::sessions; for ( int i = 0; i < zeek::detail::NUM_ADDR_ANONYMIZATION_METHODS; ++i ) delete zeek::detail::ip_anonymizer[i]; } int _processing_suspended = 0; void net_suspend_processing() { if ( _processing_suspended == 0 ) zeek::reporter->Info("processing suspended"); ++_processing_suspended; } void net_continue_processing() { if ( _processing_suspended == 1 ) { zeek::reporter->Info("processing continued"); if ( iosource::PktSrc* ps = iosource_mgr->GetPktSrc() ) ps->ContinueAfterSuspend(); } --_processing_suspended; }
27.422018
118
0.684175
[ "vector" ]
a90d9a512a6f48be0c362cec66c96916e94736ec
7,891
cpp
C++
iree/compiler/Dialect/Flow/Utils/DispatchUtils.cpp
xinan-jiang/iree
334aa4a5ac033399255fbd836d4fbe807c741230
[ "Apache-2.0" ]
2
2021-10-03T15:58:09.000Z
2021-11-17T10:34:35.000Z
iree/compiler/Dialect/Flow/Utils/DispatchUtils.cpp
3alireza32109/iree
fd32e47b1695f105d20c06b8b20a29ef65c5e54c
[ "Apache-2.0" ]
null
null
null
iree/compiler/Dialect/Flow/Utils/DispatchUtils.cpp
3alireza32109/iree
fd32e47b1695f105d20c06b8b20a29ef65c5e54c
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 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. #include "iree/compiler/Dialect/Flow/Utils/DispatchUtils.h" #include "iree/compiler/Dialect/Flow/IR/FlowOps.h" #include "iree/compiler/Dialect/Shape/IR/ShapeDialect.h" #include "llvm/ADT/SetVector.h" #include "mlir-hlo/Dialect/mhlo/IR/hlo_ops.h" #include "mlir/Dialect/Linalg/IR/LinalgTypes.h" #include "mlir/Dialect/StandardOps/IR/Ops.h" #include "mlir/Dialect/Tosa/IR/TosaOps.h" #include "mlir/IR/BlockAndValueMapping.h" #include "mlir/IR/Builders.h" namespace mlir { namespace iree_compiler { namespace IREE { namespace Flow { bool isOpOfKnownDialect(Operation *op) { if (!op->getDialect()) return false; // TODO(benvanik): replace with op dispatchability interface to allow dialects // to opt into dispatch. auto dialectNamespace = op->getDialect()->getNamespace(); return dialectNamespace == FlowDialect::getDialectNamespace() || dialectNamespace == linalg::LinalgDialect::getDialectNamespace() || dialectNamespace == mhlo::MhloDialect::getDialectNamespace() || dialectNamespace == mlir::StandardOpsDialect::getDialectNamespace() || dialectNamespace == ShapeDialect::getDialectNamespace() || dialectNamespace == tosa::TosaDialect::getDialectNamespace(); } namespace { // Returns the set of values that must be captured for use by |ops| and the // set of values defined by |ops| that are used outside of the set. LogicalResult analyzeOpRangeValues(ArrayRef<Operation *> ops, llvm::SetVector<Value> *capturedValues, llvm::SetVector<Value> *escapingValues) { llvm::SmallDenseSet<Operation *> opSet; opSet.reserve(ops.size()); opSet.insert(ops.begin(), ops.end()); for (auto *op : ops) { for (auto value : op->getOperands()) { if (!llvm::is_contained(opSet, value.getDefiningOp())) { // Op is using a value not in the ops set, ensure we capture it. capturedValues->insert(value); } } for (auto value : op->getResults()) { for (auto &use : value.getUses()) { if (!llvm::is_contained(opSet, use.getOwner())) { // An op outside of the ops set is using the value, needs to escape. escapingValues->insert(value); continue; } } } } return success(); } } // namespace LogicalResult buildDispatchRegion(Block *parentBlock, Value workload, ArrayRef<Operation *> ops) { // Fused location with all ops. SmallVector<Location, 16> opLocs; for (auto *op : ops) { opLocs.push_back(op->getLoc()); } auto regionLoc = FusedLoc::get(opLocs, workload.getContext()); // Get a list of values that we need to capture and values that escape the // region and need to be returned. llvm::SetVector<Value> capturedValues; llvm::SetVector<Value> escapingValues; if (failed(analyzeOpRangeValues(ops, &capturedValues, &escapingValues))) { return failure(); } SmallVector<Type, 8> escapingTypes; for (auto value : escapingValues) escapingTypes.push_back(value.getType()); // Build the region op and add it to the parent block. OpBuilder parentBuilder = OpBuilder::atBlockEnd(parentBlock); parentBuilder.setInsertionPoint(ops.back()); auto dispatchRegionOp = parentBuilder.create<IREE::Flow::DispatchRegionOp>( regionLoc, escapingTypes, workload, capturedValues.getArrayRef()); // Create the block and setup the arg mapping for captured values. auto *regionBlock = new Block(); dispatchRegionOp.body().push_back(regionBlock); OpBuilder regionBuilder = OpBuilder::atBlockEnd(regionBlock); BlockAndValueMapping mapping; for (auto capturedValue : capturedValues) { auto blockArg = regionBlock->addArgument(capturedValue.getType()); mapping.map(capturedValue, blockArg); } // Clone ops into the new region block. for (auto *op : ops) { // Note that this updates the mapping with the new values (so at the end // we have those new values). regionBuilder.clone(*op, mapping); } // Return results (as we need a terminator in our block). // These are all of the values that escape our region. SmallVector<Value, 8> resultValues; for (auto oldValue : escapingValues) { resultValues.push_back(mapping.lookupOrDefault(oldValue)); } regionBuilder.create<IREE::Flow::ReturnOp>(opLocs.back(), resultValues); // Replace usage of values with the results of the region. for (int i = 0; i < escapingValues.size(); ++i) { escapingValues[i].replaceAllUsesWith(dispatchRegionOp.getResult(i)); } // Remove original ops from the parent region. for (auto it = ops.rbegin(); it != ops.rend(); ++it) { (*it)->erase(); } return success(); } namespace { // Recursively finds all reachable functions from the given |rootFunc| and adds // them to the |reachableFuncs| set. // // Note that indirect calls are not supported, however we don't allow those in // dispatch regions anyway so they should not be present here. LogicalResult findReachableFunctions( FuncOp rootFuncOp, llvm::SetVector<FuncOp> &reachableFuncs, llvm::StringMap<FuncOp> &dispatchableFuncOps) { llvm::SetVector<FuncOp> worklist; worklist.insert(rootFuncOp); while (!worklist.empty()) { auto funcOp = worklist.pop_back_val(); funcOp.walk([&](CallOp callOp) { auto calleeOp = dispatchableFuncOps.find(callOp.callee())->second; if (reachableFuncs.insert(calleeOp)) { worklist.insert(calleeOp); } }); } return success(); } } // namespace ExecutableOp createExecutable(Location loc, StringRef executableName, ArrayRef<FuncOp> funcOps, ModuleOp parentModuleOp, llvm::StringMap<FuncOp> &dispatchableFuncOps) { assert(!funcOps.empty() && "must have at least one entry function"); // Gather all reachable functions. llvm::SetVector<FuncOp> reachableFuncs; for (auto funcOp : funcOps) { findReachableFunctions(funcOp, reachableFuncs, dispatchableFuncOps); } // Create the executable that will contain the outlined region. // NOTE: this will get uniquified if we have multiple in the same block. OpBuilder parentModuleBuilder(&parentModuleOp.getBody()->back()); auto executableOp = parentModuleBuilder.create<IREE::Flow::ExecutableOp>(loc, executableName); // Create the inner ModuleOp that contains the original functions. We need // to provide this shim as some ops (like std.call) look for the // containing module to provide symbol resolution. OpBuilder executableBuilder(executableOp); executableBuilder.setInsertionPointToStart(&executableOp.getBlock()); auto innerModule = executableBuilder.create<ModuleOp>(loc); for (auto funcOp : funcOps) { innerModule.push_back(funcOp); } // Copy all reachable functions into the executable. // Linker passes may dedupe these later on. OpBuilder innerModuleBuilder = OpBuilder::atBlockEnd(innerModule.getBody()); innerModuleBuilder.setInsertionPoint(innerModule.getBody(), ++innerModule.getBody()->begin()); for (auto reachableFunc : reachableFuncs) { innerModuleBuilder.clone(*reachableFunc); } return executableOp; } } // namespace Flow } // namespace IREE } // namespace iree_compiler } // namespace mlir
37.755981
80
0.701179
[ "shape" ]
a90df3de027914ccd9ecec95c0cbf93d1099692c
12,365
hpp
C++
include/lyra/arguments.hpp
vslutov/Lyra
c6fdb1fcad2d97008b2d60a6fd47a39f473926c2
[ "BSL-1.0" ]
null
null
null
include/lyra/arguments.hpp
vslutov/Lyra
c6fdb1fcad2d97008b2d60a6fd47a39f473926c2
[ "BSL-1.0" ]
null
null
null
include/lyra/arguments.hpp
vslutov/Lyra
c6fdb1fcad2d97008b2d60a6fd47a39f473926c2
[ "BSL-1.0" ]
null
null
null
// Copyright 2018-2020 René Ferdinand Rivera Morell // Copyright 2017 Two Blue Cubes Ltd. All rights reserved. // // 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) #ifndef LYRA_ARGUMENTS_HPP #define LYRA_ARGUMENTS_HPP #include "lyra/exe_name.hpp" #include "lyra/parser.hpp" #include <functional> #include <sstream> namespace lyra { /* tag::reference[] [#lyra_arguments] = `lyra::arguments` A Combined parser made up of any number of parsers. Creating and using one of these as a basis one can incrementally compose other parsers into this one. For example: [source] ---- auto p = lyra::arguments(); std::string what; float when = 0; std::string where; p |= lyra::opt(what, "what")["--make-it-so"]("Make it so.").required(); p |= lyra::opt(when. "when")["--time"]("When to do <what>.").optional(); p.add_argument(lyra::opt(where, "where").name("--where") .help("There you are.").optional()); ---- */ // end::reference[] class arguments : public parser { public: // How to evaluate the collection of arguments within the limits of the // cardinality. enum evaluation { // Any of the arguments, in any order, are valid. I.e. an inclusive-or. any = 0, // All arguments, in sequence, matched. I.e. conjunctive-and. sequence = 1 }; arguments() = default; arguments(evaluation e) : eval_mode(e) {} // Copy construction, needs to copy the the composed parsers. arguments(const arguments & other); // Compose a regular parser. arguments & add_argument(parser const & p); arguments & operator|=(parser const & p); // Compose the parsers from another `arguments`. arguments & add_argument(arguments const & other); arguments & operator|=(arguments const & other); // Concat composition. template <typename T> arguments operator|(T const & other) const { return arguments(*this) |= other; } // Parsing mode. arguments & sequential(); arguments & inclusive(); // Access. template <typename T> T & get(size_t i); // Internal.. virtual std::string get_usage_text(const option_style & style) const override { std::ostringstream os; for (auto const & p : parsers) { std::string usage_text = p->get_usage_text(style); if (usage_text.size() > 0) { if (os.tellp() != std::ostringstream::pos_type(0)) os << " "; if (p->is_group()) os << "{ " << usage_text << " }"; else if (p->is_optional()) os << "[" << usage_text << "]"; else os << usage_text; } } return os.str(); } virtual std::string get_description_text(const option_style & style) const override { std::ostringstream os; for (auto const & p : parsers) { if (p->is_group()) continue; auto child_description = p->get_description_text(style); if (!child_description.empty()) os << child_description << "\n"; } return os.str(); } // Return a container of the individual help text for the composed parsers. virtual help_text get_help_text(const option_style & style) const override { help_text text; for (auto const & p : parsers) { if (p->is_group()) text.push_back({ "", "" }); auto child_help = p->get_help_text(style); text.insert(text.end(), child_help.begin(), child_help.end()); } return text; } virtual detail::parser_cardinality cardinality() const override { return { 0, 0 }; } virtual result validate() const override { for (auto const & p : parsers) { auto result = p->validate(); if (!result) return result; } return result::ok(); } parse_result parse(detail::token_iterator const & tokens, const option_style & style) const override { switch (eval_mode) { case any: return parse_any(tokens, style); case sequence: return parse_sequence(tokens, style); } return parse_result::logicError( detail::parse_state(parser_result_type::no_match, tokens), "Unknown evaluation mode; not one of 'any', or 'sequence'."); } parse_result parse_any(detail::token_iterator const & tokens, const option_style & style) const { struct ParserInfo { parser const * parser_p = nullptr; size_t count = 0; }; std::vector<ParserInfo> parser_info(parsers.size()); { size_t i = 0; for (auto const & p : parsers) parser_info[i++].parser_p = p.get(); } auto result = parse_result::ok( detail::parse_state(parser_result_type::no_match, tokens)); while (result.value().remainingTokens()) { bool token_parsed = false; for (auto & parse_info : parser_info) { auto parser_cardinality = parse_info.parser_p->cardinality(); if (parser_cardinality.is_unbounded() || parse_info.count < parser_cardinality.maximum) { auto subparse_result = parse_info.parser_p->parse( result.value().remainingTokens(), style); // It's only an error if this is not a sub-parser. This // makes it such that sub-parsers will report no_match // trigerring consideration of other sub-parser // alternatives. As the whole of the sub-parser is // optional, but not parts of it. if (!subparse_result && !parse_info.parser_p->is_group()) return subparse_result; result = parse_result(subparse_result); if (result.value().type() != parser_result_type::no_match) { token_parsed = true; parse_info.count += 1; break; } } } if (result.value().type() == parser_result_type::short_circuit_all) return result; if (!token_parsed) return parse_result::runtimeError(result.value(), "Unrecognized token: " + result.value().remainingTokens().argument().name); } // Check missing required options. For bounded arguments we check // bound min and max bounds against what we parsed. For the loosest // required arguments we check for only the minimum. As the upper // bound could be infinite. for (auto & parseInfo : parser_info) { auto parser_cardinality = parseInfo.parser_p->cardinality(); if ((parser_cardinality.is_bounded() && (parseInfo.count < parser_cardinality.minimum || parser_cardinality.maximum < parseInfo.count)) || (parser_cardinality.is_required() && (parseInfo.count < parser_cardinality.minimum))) { return parse_result::runtimeError(result.value(), "Expected: " + parseInfo.parser_p->get_usage_text(style)); } } return result; } parse_result parse_sequence(detail::token_iterator const & tokens, const option_style & style) const { struct ParserInfo { parser const * parser_p = nullptr; size_t count = 0; }; std::vector<ParserInfo> parser_info(parsers.size()); { size_t i = 0; for (auto const & p : parsers) parser_info[i++].parser_p = p.get(); } auto result = parse_result::ok( detail::parse_state(parser_result_type::no_match, tokens)); // Sequential parsing means we walk through the given parsers in order // and exhaust the tokens as we go. for (size_t i = 0; i < parsers.size() && result.value().have_tokens(); ++i) { auto & parse_info = parser_info[i]; auto parser_cardinality = parse_info.parser_p->cardinality(); // This is a greedy sequential parsing algo. As it parsers the // current argument as much as possible. while (result.value().have_tokens() && (parser_cardinality.is_unbounded() || parse_info.count < parser_cardinality.maximum)) { result = parse_info.parser_p->parse( result.value().remainingTokens(), style); parser_result_type result_type = result.value().type(); if (!result) { return result; } else if (result_type == parser_result_type::short_circuit_all) { return result; } else if (result_type == parser_result_type::matched) { parse_info.count += 1; } } // Check missing required options immediately as for sequential the // argument is greedy and will fully match here. For bounded // arguments we check bound min and max bounds against what we // parsed. For the loosest required arguments we check for only the // minimum. As the upper bound could be infinite. if ((parser_cardinality.is_bounded() && (parse_info.count < parser_cardinality.minimum || parser_cardinality.maximum < parse_info.count)) || (parser_cardinality.is_required() && (parse_info.count < parser_cardinality.minimum))) { return parse_result::runtimeError(result.value(), "Expected: " + parse_info.parser_p->get_usage_text(style)); } } // The return is just the last state as it contains any remaining tokens // to parse. return result; } virtual std::unique_ptr<parser> clone() const override { return make_clone<arguments>(this); } friend std::ostream & operator<<( std::ostream & os, arguments const & parser) { const option_style & s = parser.opt_style ? *parser.opt_style : option_style::posix(); parser.print_help_text(os, s); return os; } virtual const parser * get_named(const std::string & n) const override { for (auto & p: parsers) { const parser * result = p->get_named(n); if (result) return result; } return nullptr; } protected: std::shared_ptr<option_style> opt_style; private: std::vector<std::unique_ptr<parser>> parsers; evaluation eval_mode = any; }; /* tag::reference[] [#lyra_arguments_ctor] == Construction end::reference[] */ /* tag::reference[] [#lyra_arguments_ctor_default] === Default [source] ---- arguments() = default; ---- Default constructing a `arguments` is the starting point to adding arguments and options for parsing a arguments line. end::reference[] */ /* tag::reference[] [#lyra_arguments_ctor_copy] === Copy [source] ---- arguments::arguments(const arguments& other); ---- end::reference[] */ inline arguments::arguments(const arguments & other) : parser(other) , opt_style(other.opt_style) , eval_mode(other.eval_mode) { for (auto & other_parser : other.parsers) { parsers.push_back(other_parser->clone()); } } /* tag::reference[] [#lyra_arguments_specification] == Specification end::reference[] */ // == /* tag::reference[] [#lyra_arguments_add_argument] === `lyra::arguments::add_argument` [source] ---- arguments& arguments::add_argument(parser const& p); arguments& arguments::operator|=(parser const& p); arguments& arguments::add_argument(arguments const& other); arguments& arguments::operator|=(arguments const& other); ---- Adds the given argument parser to the considered arguments for this `arguments`. Depending on the parser given it will be: directly added as an argument (for `parser`), or add the parsers from another `arguments` to this one. end::reference[] */ inline arguments & arguments::add_argument(parser const & p) { parsers.push_back(p.clone()); return *this; } inline arguments & arguments::operator|=(parser const & p) { return this->add_argument(p); } inline arguments & arguments::add_argument(arguments const & other) { if (other.is_group()) { parsers.push_back(other.clone()); } else { for (auto & p : other.parsers) { parsers.push_back(p->clone()); } } return *this; } inline arguments & arguments::operator|=(arguments const & other) { return this->add_argument(other); } /* tag::reference[] === `lyra::arguments::sequential` [source] ---- arguments & arguments::sequential(); ---- Sets the parsing mode for the arguments to "sequential". When parsing the arguments they will be, greedily, consumed in the order they where added. This is useful for sub-commands and structured command lines. end::reference[] */ inline arguments & arguments::sequential() { eval_mode = sequence; return *this; } /* tag::reference[] === `lyra::arguments::inclusive` [source] ---- arguments & arguments::inclusive(); ---- Sets the parsing mode for the arguments to "inclusively any". This is the default that attempts to match each parsed argument with all the available parsers. This means that there is no ordering enforced. end::reference[] */ inline arguments & arguments::inclusive() { eval_mode = any; return *this; } /* tag::reference[] === `lyra::arguments::get` [source] ---- template <typename T> T & arguments::get(size_t i); ---- Get a modifyable reference to one of the parsers specified. end::reference[] */ template <typename T> T & arguments::get(size_t i) { return static_cast<T &>(*parsers.at(i)); } } // namespace lyra #endif
25.390144
88
0.686292
[ "vector" ]
a911436eeb213a08006e7156e53b5542ecf40c82
1,657
cpp
C++
HackerRank/HackerRank - subset/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
HackerRank/HackerRank - subset/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
HackerRank/HackerRank - subset/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: 2020-07-22 20:41:01 * solution_verdict: Accepted language: C++ * run_time (ms): 2384 memory_used (MB): * problem: https://vjudge.net/problem/HackerRank-subset ****************************************************************************************/ #include<iostream> #include<vector> #include<cstring> #include<map> #include<bitset> #include<assert.h> #include<algorithm> #include<iomanip> #include<cmath> #include<set> #include<queue> #include<unordered_map> #include<random> #include<chrono> #include<stack> #include<deque> #define long long long using namespace std; const int N=1e6; int aa[N+2],bb[N+2],a,b,fr[N+2],dp[N+2]; void cal() { for(int i=1;i<=a;i++)fr[aa[i]]++; for(int i=1;i<=b;i++)fr[bb[i]]--; a=0,b=0; for(int i=0;i<(1<<16);i++)dp[i]=fr[i]; for(int i=0;i<16;i++) { for(int msk=0;msk<(1<<16);msk++) { if(msk&(1<<i)) dp[msk]+=dp[msk^(1<<i)]; } } } const int magic=2000; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n; for(int i=1;i<=n;i++) { string s;int x;cin>>s>>x; if(s=="cnt") { int ans=dp[x]; for(int i=1;i<=a;i++)if((x&aa[i])==aa[i])ans++; for(int i=1;i<=b;i++)if((x&bb[i])==bb[i])ans--; cout<<ans<<"\n"; } else if(s=="add")aa[++a]=x; else bb[++b]=x; if(a+b>=magic)cal(); } return 0; }
26.301587
111
0.441762
[ "vector" ]
a913284365f59361b04a6bedcea86c5594d50272
8,522
cc
C++
third_party/blink/renderer/controller/performance_manager/v8_worker_memory_reporter.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/controller/performance_manager/v8_worker_memory_reporter.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/controller/performance_manager/v8_worker_memory_reporter.cc
mghgroup/Glide-Browser
6a4c1eaa6632ec55014fee87781c6bbbb92a2af5
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2020 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 "third_party/blink/renderer/controller/performance_manager/v8_worker_memory_reporter.h" #include <memory> #include <utility> #include "base/check.h" #include "base/time/time.h" #include "third_party/blink/renderer/core/workers/worker_global_scope.h" #include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h" #include "third_party/blink/renderer/core/workers/worker_thread.h" #include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/blink/renderer/platform/wtf/allocator/allocator.h" #include "third_party/blink/renderer/platform/wtf/cross_thread_copier.h" #include "third_party/blink/renderer/platform/wtf/cross_thread_functional.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace WTF { template <> struct CrossThreadCopier<blink::V8WorkerMemoryReporter::WorkerMemoryUsage> : public CrossThreadCopierPassThrough< blink::V8WorkerMemoryReporter::WorkerMemoryUsage> { STATIC_ONLY(CrossThreadCopier); }; } // namespace WTF namespace blink { const base::TimeDelta V8WorkerMemoryReporter::kTimeout = base::TimeDelta::FromSeconds(60); namespace { // This delegate is provided to v8::Isolate::MeasureMemory API. // V8 calls MeasurementComplete with the measurement result. // // All functions of this delegate are called on the worker thread. class WorkerMeasurementDelegate : public v8::MeasureMemoryDelegate { public: WorkerMeasurementDelegate( base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter, WorkerThread* worker_thread) : worker_memory_reporter_(std::move(worker_memory_reporter)), worker_thread_(worker_thread) { DCHECK(worker_thread_->IsCurrentThread()); } ~WorkerMeasurementDelegate() override; // v8::MeasureMemoryDelegate overrides. bool ShouldMeasure(v8::Local<v8::Context> context) override { return true; } void MeasurementComplete( const std::vector<std::pair<v8::Local<v8::Context>, size_t>>& context_sizes, size_t unattributed_size) override; private: void NotifyMeasurementSuccess( V8WorkerMemoryReporter::WorkerMemoryUsage memory_usage); void NotifyMeasurementFailure(); base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter_; WorkerThread* worker_thread_; bool did_notify_ = false; }; WorkerMeasurementDelegate::~WorkerMeasurementDelegate() { DCHECK(worker_thread_->IsCurrentThread()); if (!did_notify_) { // This may happen if the worker shuts down before completing // memory measurement. NotifyMeasurementFailure(); } } void WorkerMeasurementDelegate::MeasurementComplete( const std::vector<std::pair<v8::Local<v8::Context>, size_t>>& context_sizes, size_t unattributed_size) { DCHECK(worker_thread_->IsCurrentThread()); WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope(); DCHECK(global_scope); DCHECK_LE(context_sizes.size(), 1u); size_t bytes = unattributed_size; for (auto& context_size : context_sizes) { bytes += context_size.second; } NotifyMeasurementSuccess(V8WorkerMemoryReporter::WorkerMemoryUsage{ To<WorkerGlobalScope>(global_scope)->GetWorkerToken(), bytes}); } void WorkerMeasurementDelegate::NotifyMeasurementFailure() { DCHECK(worker_thread_->IsCurrentThread()); DCHECK(!did_notify_); V8WorkerMemoryReporter::NotifyMeasurementFailure(worker_thread_, worker_memory_reporter_); did_notify_ = true; } void WorkerMeasurementDelegate::NotifyMeasurementSuccess( V8WorkerMemoryReporter::WorkerMemoryUsage memory_usage) { DCHECK(worker_thread_->IsCurrentThread()); DCHECK(!did_notify_); V8WorkerMemoryReporter::NotifyMeasurementSuccess( worker_thread_, worker_memory_reporter_, memory_usage); did_notify_ = true; } } // anonymous namespace // static void V8WorkerMemoryReporter::GetMemoryUsage(ResultCallback callback, v8::MeasureMemoryExecution mode) { DCHECK(IsMainThread()); // The private constructor prevents us from using std::make_unique here. std::unique_ptr<V8WorkerMemoryReporter> worker_memory_reporter( new V8WorkerMemoryReporter(std::move(callback))); // Worker tasks get a weak pointer to the instance for passing it back // to the main thread in OnMeasurementSuccess and OnMeasurementFailure. // Worker tasks never dereference the weak pointer. unsigned worker_count = WorkerThread::CallOnAllWorkerThreads( &V8WorkerMemoryReporter::StartMeasurement, TaskType::kInternalDefault, worker_memory_reporter->GetWeakPtr(), mode); if (worker_count == 0) { Thread::Current()->GetTaskRunner()->PostTask( FROM_HERE, WTF::Bind(&V8WorkerMemoryReporter::InvokeCallback, std::move(worker_memory_reporter))); return; } worker_memory_reporter->SetWorkerCount(worker_count); // Transfer the ownership of the instance to the timeout task. Thread::Current()->GetTaskRunner()->PostDelayedTask( FROM_HERE, WTF::Bind(&V8WorkerMemoryReporter::OnTimeout, std::move(worker_memory_reporter)), kTimeout); } // static void V8WorkerMemoryReporter::StartMeasurement( WorkerThread* worker_thread, base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter, v8::MeasureMemoryExecution measurement_mode) { DCHECK(worker_thread->IsCurrentThread()); WorkerOrWorkletGlobalScope* global_scope = worker_thread->GlobalScope(); DCHECK(global_scope); v8::Isolate* isolate = worker_thread->GetIsolate(); if (global_scope->IsWorkerGlobalScope()) { auto delegate = std::make_unique<WorkerMeasurementDelegate>( std::move(worker_memory_reporter), worker_thread); isolate->MeasureMemory(std::move(delegate), measurement_mode); } else { // TODO(ulan): Add support for worklets once we get tokens for them. We // need to careful to not trigger GC on a worklet because usually worklets // are soft real-time and are written to avoid GC. // For now we simply notify a failure so that the main thread doesn't wait // for a response from the worklet. NotifyMeasurementFailure(worker_thread, worker_memory_reporter); } } // static void V8WorkerMemoryReporter::NotifyMeasurementSuccess( WorkerThread* worker_thread, base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter, WorkerMemoryUsage memory_usage) { DCHECK(worker_thread->IsCurrentThread()); PostCrossThreadTask( *Thread::MainThread()->GetTaskRunner(), FROM_HERE, CrossThreadBindOnce(&V8WorkerMemoryReporter::OnMeasurementSuccess, worker_memory_reporter, memory_usage)); } // static void V8WorkerMemoryReporter::NotifyMeasurementFailure( WorkerThread* worker_thread, base::WeakPtr<V8WorkerMemoryReporter> worker_memory_reporter) { DCHECK(worker_thread->IsCurrentThread()); PostCrossThreadTask( *Thread::MainThread()->GetTaskRunner(), FROM_HERE, CrossThreadBindOnce(&V8WorkerMemoryReporter::OnMeasurementFailure, worker_memory_reporter)); } void V8WorkerMemoryReporter::OnMeasurementFailure() { DCHECK(IsMainThread()); if (state_ == State::kDone) return; ++failure_count_; if (success_count_ + failure_count_ == worker_count_) { InvokeCallback(); DCHECK_EQ(state_, State::kDone); } } void V8WorkerMemoryReporter::OnMeasurementSuccess( WorkerMemoryUsage memory_usage) { DCHECK(IsMainThread()); if (state_ == State::kDone) return; result_.workers.emplace_back(memory_usage); ++success_count_; if (success_count_ + failure_count_ == worker_count_) { InvokeCallback(); DCHECK_EQ(state_, State::kDone); } } void V8WorkerMemoryReporter::SetWorkerCount(unsigned worker_count) { DCHECK(IsMainThread()); DCHECK_EQ(0u, worker_count_); worker_count_ = worker_count; } void V8WorkerMemoryReporter::OnTimeout() { DCHECK(IsMainThread()); if (state_ == State::kDone) return; InvokeCallback(); DCHECK_EQ(state_, State::kDone); } void V8WorkerMemoryReporter::InvokeCallback() { DCHECK(IsMainThread()); DCHECK_EQ(state_, State::kWaiting); std::move(callback_).Run(std::move(result_)); state_ = State::kDone; } } // namespace blink
36.732759
96
0.749824
[ "vector" ]
a91b48d6ecc6a1aeed67f38fc94ff29b42081664
7,843
cpp
C++
cnr_velocity_to_torque_controller/src/cnr_velocity_to_torque_controller/cnr_velocity_to_torque_controller.cpp
CNR-STIIMA-IRAS/cnr_ros_controllers
c4bbfa4c2968da49b7b1f17ee91cae23af62e793
[ "BSD-3-Clause" ]
1
2021-04-22T19:53:59.000Z
2021-04-22T19:53:59.000Z
cnr_velocity_to_torque_controller/src/cnr_velocity_to_torque_controller/cnr_velocity_to_torque_controller.cpp
CNR-STIIMA-IRAS/cnr_ros_controllers
c4bbfa4c2968da49b7b1f17ee91cae23af62e793
[ "BSD-3-Clause" ]
1
2022-02-04T16:46:33.000Z
2022-02-04T16:46:33.000Z
cnr_velocity_to_torque_controller/src/cnr_velocity_to_torque_controller/cnr_velocity_to_torque_controller.cpp
CNR-STIIMA-IRAS/cnr_ros_controllers
c4bbfa4c2968da49b7b1f17ee91cae23af62e793
[ "BSD-3-Clause" ]
null
null
null
#include <rosparam_utilities/rosparam_utilities.h> #include <state_space_ros/ros_params.h> #include <cnr_velocity_to_torque_controller/cnr_velocity_to_torque_controller.h> #include <pluginlib/class_list_macros.h> PLUGINLIB_EXPORT_CLASS(cnr::control::VelocityToTorqueController , controller_interface::ControllerBase) namespace cnr { namespace control { //! inline bool VelocityToTorqueController::doInit( ) { CNR_TRACE_START(this->logger()); std::string setpoint_topic_name; if(!this->getControllerNh().getParam("setpoint_topic_name", setpoint_topic_name)) { CNR_ERROR(this->logger(), this->getControllerNamespace() + "/setpoint_topic_name does not exist"); CNR_RETURN_FALSE(this->logger()); } this->template add_subscriber<sensor_msgs::JointState>(setpoint_topic_name,1, boost::bind(&VelocityToTorqueController::callback, this, _1)); m_use_target_torque = false; if(!this->getControllerNh().getParam("use_target_torque", m_use_target_torque)) { CNR_WARN(this->logger(), this->getControllerNamespace() + "/use_target_torque does not exist, set FALSE"); } std::string what; std::string msg; int ok = eigen_control_toolbox::setMatricesFromParam(m_filter,this->getControllerNh(), "vel_filter",msg); if(ok==-1) { CNR_ERROR(this->logger(), this->getControllerNamespace() + "/vel_filter: " << what); return false; } else if(ok==0) { CNR_WARN(this->logger(), this->getControllerNamespace() + "/vel_filter: " << what); } ok = eigen_control_toolbox::setMatricesFromParam(m_target_filter,this->getControllerNh(), "target_vel_filter",msg); if(ok==-1) { CNR_ERROR(this->logger(), this->getControllerNamespace() + "/target_vel_filter: " << what); return false; } else if(ok==0) { CNR_WARN(this->logger(), this->getControllerNamespace() + "/target_vel_filter: " << what); } ok = eigen_control_toolbox::setMatricesFromParam(m_controller,this->getControllerNh(), "controller",msg); if(ok==-1) { CNR_ERROR(this->logger(), this->getControllerNamespace() + "/controller: " << what); return false; } else if(ok==0) { CNR_WARN(this->logger(), this->getControllerNamespace() + "/controller: " << what); } ok = eigen_control_toolbox::setMatricesFromParam(m_integral_controller,this->getControllerNh(),"integral_controller",msg); if(ok==-1) { CNR_ERROR(this->logger(), this->getControllerNamespace() + "/integral_controller: " << what); return -1; } else if(ok==0) { CNR_WARN(this->logger(), this->getControllerNamespace() + "/integral_controller: " << what); } eigen_utils::resize(m_antiwindup_gain , this->nAx(), this->nAx() );eigen_utils::setDiagonal(m_antiwindup_gain, 1); eigen_utils::resize(m_pos_deadband , this->nAx() );eigen_utils::setZero(m_pos_deadband ); eigen_utils::resize(m_vel_cmd , this->nAx() );eigen_utils::setZero(m_vel_cmd ); eigen_utils::resize(m_eff_cmd , this->nAx() );eigen_utils::setZero(m_eff_cmd ); eigen_utils::resize(m_antiwindup , this->nAx() );eigen_utils::setZero(m_antiwindup ); eigen_utils::resize(m_max_effort , this->nAx() );eigen_utils::setZero(m_max_effort ); eigen_utils::resize(m_target_vel , this->nAx() );eigen_utils::setZero(m_target_vel ); eigen_utils::resize(m_target_eff , this->nAx() );eigen_utils::setZero(m_target_eff ); if(!rosparam_utilities::getParam(this->getControllerNh(), "antiwindup_ratio", m_antiwindup_gain, what, &m_antiwindup_gain)) { return false; } if(!rosparam_utilities::getParam(this->getControllerNh(), "maximum_torque", m_max_effort, what, &m_max_effort)) { return false; } m_well_init = true; this->setPriority(this->QD_PRIORITY); return true; } //! inline bool VelocityToTorqueController::doStarting(const ros::Time& /*time*/) { CNR_TRACE_START(this->logger()); m_configured = false; auto fb_vel = this->getPosition(); auto fb_eff = this->getEffort(); m_target_vel = fb_vel; eigen_utils::setZero(m_target_eff); auto init_vel = fb_vel; m_filter.setStateFromLastIO(init_vel, init_vel); init_vel = m_target_vel; m_target_filter.setStateFromLastIO(init_vel, init_vel); auto init_eff = (m_use_target_torque) ? fb_eff - m_target_eff : fb_eff; auto init_error = m_target_filter.y() - m_filter.y(); m_controller.setStateFromLastIO(init_error, init_eff); m_integral_controller.setStateFromLastIO(init_error, init_eff); eigen_utils::setZero(m_antiwindup); CNR_RETURN_TRUE(this->logger()); } //! inline bool VelocityToTorqueController::doStopping(const ros::Time& /*time*/) { CNR_TRACE_START(this->logger()); m_configured = false; eigen_utils::setZero(m_vel_cmd); CNR_RETURN_TRUE(this->logger()); } //! inline bool VelocityToTorqueController::doUpdate(const ros::Time& /*time*/, const ros::Duration& /*period*/) { CNR_TRACE_START_THROTTLE_DEFAULT(this->logger()); try { if (!m_configured) { m_target_vel = this->getVelocity(); eigen_utils::setZero(m_target_eff); } auto filter_output = m_filter.update(this->getVelocity()); auto target_filter_output = (m_configured) ? m_target_filter.update(m_target_vel) : m_target_filter.update(m_target_filter.y()); auto controller_input = target_filter_output - filter_output; //controller error auto controller_output = m_controller.update(controller_input); auto integral_controller_input = controller_input + m_antiwindup_gain * m_antiwindup; //integral controller error auto integral_controller_output = m_integral_controller.update(integral_controller_input); m_vel_cmd = target_filter_output; m_eff_cmd = controller_output + integral_controller_output; if(m_use_target_torque) { m_eff_cmd += m_target_eff; } for(int i=0;i<int(this->nAx());i++) { if (eigen_utils::at(m_eff_cmd,i) > eigen_utils::at(m_max_effort,i) ) { eigen_utils::at(m_antiwindup,i) = eigen_utils::at(m_max_effort,i) - eigen_utils::at(m_eff_cmd,i); eigen_utils::at(m_eff_cmd ,i) = eigen_utils::at(m_max_effort,i); } else if (eigen_utils::at(m_eff_cmd,i) < -eigen_utils::at(m_max_effort,i) ) { eigen_utils::at(m_antiwindup,i) = -eigen_utils::at(m_max_effort,i) - eigen_utils::at(m_eff_cmd,i); eigen_utils::at(m_eff_cmd ,i) = -eigen_utils::at(m_max_effort,i); } else { eigen_utils::setZero(m_antiwindup); } } this->setCommandEffort(m_eff_cmd); } catch (...) { CNR_ERROR(this->logger(), "Something wrong"); eigen_utils::setZero(m_eff_cmd); this->setCommandEffort(m_eff_cmd); } CNR_RETURN_TRUE(this->logger()); } //! inline bool VelocityToTorqueController::extractJoint( const sensor_msgs::JointState& msg, const std::vector<std::string>& names, rosdyn::VectorXd& vel, rosdyn::VectorXd& eff) { if(msg.velocity.size()!=msg.name.size()) { return false; } for(size_t i=0;i<names.size(); i++) { std::vector<std::string>::const_iterator it = std::find(msg.name.begin(), msg.name.end(), names.at(i)); if(it == msg.name.end()) { return false; } size_t iJoint = std::distance(msg.name.begin(), it); eigen_utils::at(vel,i) = msg.velocity.at(iJoint); eigen_utils::at(eff,i) = msg.effort.size() == msg.name.size() ? msg.effort.at(iJoint) : 0 ; } return true; } //! inline void VelocityToTorqueController::callback(const sensor_msgs::JointStateConstPtr& msg) { if (extractJoint(*msg, this->jointNames(), m_target_vel, m_target_eff)) { m_configured = true; } else { CNR_ERROR(this->logger(), this->getControllerNamespace() + " target message dimension is wrong"); } return; } } }
32.27572
125
0.689022
[ "vector" ]
a92256abe65019d0c448eed5c18b1eb8b6649f93
9,066
hpp
C++
include/mamba/core/util.hpp
s-pike/mamba
a7756e6f1c587bad5dc88b29b9b7855a938bae03
[ "BSD-3-Clause" ]
null
null
null
include/mamba/core/util.hpp
s-pike/mamba
a7756e6f1c587bad5dc88b29b9b7855a938bae03
[ "BSD-3-Clause" ]
null
null
null
include/mamba/core/util.hpp
s-pike/mamba
a7756e6f1c587bad5dc88b29b9b7855a938bae03
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, QuantStack and Mamba Contributors // // Distributed under the terms of the BSD 3-Clause License. // // The full license is in the file LICENSE, distributed with this software. #ifndef MAMBA_CORE_UTIL_HPP #define MAMBA_CORE_UTIL_HPP #include <array> #include <iomanip> #include <limits> #include <random> #include <sstream> #include <stdexcept> #include <string> #include <string_view> #include <vector> #include "nlohmann/json.hpp" #include "mamba_fs.hpp" namespace mamba { #if __APPLE__ || __MACH__ static constexpr bool on_win = false; static constexpr bool on_linux = false; static constexpr bool on_mac = true; #elif __linux__ static constexpr bool on_win = false; static constexpr bool on_linux = true; static constexpr bool on_mac = false; #elif _WIN32 static constexpr bool on_win = true; static constexpr bool on_linux = false; static constexpr bool on_mac = false; #else #error "no supported OS detected" #endif class mamba_error : public std::runtime_error { public: using std::runtime_error::runtime_error; }; bool is_package_file(const std::string_view& fn); void to_human_readable_filesize(std::ostream& o, double bytes, std::size_t precision = 0); bool lexists(const fs::path& p); std::vector<fs::path> filter_dir(const fs::path& dir, const std::string& suffix); bool paths_equal(const fs::path& lhs, const fs::path& rhs); std::string read_contents(const fs::path& path, std::ios::openmode mode = std::ios::in | std::ios::binary); std::vector<std::string> read_lines(const fs::path& path); inline void make_executable(const fs::path& p) { fs::permissions(p, fs::perms::owner_all | fs::perms::group_all | fs::perms::others_read | fs::perms::others_exec); } template <typename T = std::mt19937> inline auto random_generator() -> T { auto constexpr seed_bits = sizeof(typename T::result_type) * T::state_size; auto constexpr seed_len = seed_bits / std::numeric_limits<std::seed_seq::result_type>::digits; auto seed = std::array<std::seed_seq::result_type, seed_len>{}; auto dev = std::random_device{}; std::generate_n(begin(seed), seed_len, std::ref(dev)); auto seed_seq = std::seed_seq(begin(seed), end(seed)); return T{ seed_seq }; } inline std::string generate_random_alphanumeric_string(std::size_t len) { static constexpr auto chars = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; thread_local auto rng = random_generator<std::mt19937>(); auto dist = std::uniform_int_distribution{ {}, std::strlen(chars) - 1 }; auto result = std::string(len, '\0'); std::generate_n(begin(result), len, [&]() { return chars[dist(rng)]; }); return result; } class TemporaryDirectory { public: TemporaryDirectory(); ~TemporaryDirectory(); TemporaryDirectory(const TemporaryDirectory&) = delete; TemporaryDirectory& operator=(const TemporaryDirectory&) = delete; TemporaryDirectory& operator=(TemporaryDirectory&&) = default; fs::path& path(); operator fs::path(); private: fs::path m_path; }; class TemporaryFile { public: TemporaryFile(const std::string& prefix = "mambaf", const std::string& suffix = ""); ~TemporaryFile(); TemporaryFile(const TemporaryFile&) = delete; TemporaryFile& operator=(const TemporaryFile&) = delete; TemporaryFile& operator=(TemporaryFile&&) = default; fs::path& path(); operator fs::path(); private: fs::path m_path; }; class LockFile { public: LockFile(const fs::path& path); ~LockFile(); LockFile(const LockFile&) = delete; LockFile& operator=(const LockFile&) = delete; LockFile& operator=(LockFile&&) = default; fs::path& path(); operator fs::path(); private: fs::path m_path; int m_fd; #if defined(__APPLE__) or defined(__linux__) pid_t m_pid; #else int m_pid; #endif }; /************************* * utils for std::string * *************************/ inline const char* check_char(const char* ptr) { return ptr ? ptr : ""; } constexpr const char* WHITESPACES(" \r\n\t\f\v"); bool starts_with(const std::string_view& str, const std::string_view& prefix); bool ends_with(const std::string_view& str, const std::string_view& suffix); bool contains(const std::string_view& str, const std::string_view& sub_str); std::string_view strip(const std::string_view& input); std::string_view lstrip(const std::string_view& input); std::string_view rstrip(const std::string_view& input); std::string_view strip(const std::string_view& input, const std::string_view& chars); std::string_view lstrip(const std::string_view& input, const std::string_view& chars); std::string_view rstrip(const std::string_view& input, const std::string_view& chars); std::vector<std::string> split(const std::string_view& input, const std::string_view& sep, std::size_t max_split = SIZE_MAX); std::vector<std::string> rsplit(const std::string_view& input, const std::string_view& sep, std::size_t max_split = SIZE_MAX); void split_package_extension(const std::string& file, std::string& name, std::string& extension); fs::path strip_package_extension(const std::string& file); template <class S> inline std::string join(const char* j, const S& container) { if (container.empty()) return ""; std::string result = container[0]; for (std::size_t i = 1; i < container.size(); ++i) { result += j; result += container[i]; } return result; } void replace_all(std::string& data, const std::string& search, const std::string& replace); void replace_all(std::wstring& data, const std::wstring& search, const std::wstring& replace); // Note: this function only works for non-unicode! std::string to_upper(const std::string_view& input); std::string to_lower(const std::string_view& input); namespace concat_impl { template <class T> inline void concat_foreach(std::string& result, const T& rhs) { result += rhs; } template <class T, class... Rest> inline void concat_foreach(std::string& result, const T& rhs, const Rest&... rest) { result += rhs; concat_foreach(result, rest...); } struct sizer { inline sizer(const char* s) : size(strlen(s)) { } inline sizer(const char s) : size(1) { } template <class T> inline sizer(T& s) : size(s.size()) { } std::size_t size; }; } // namespace concat_impl template <typename... Args> inline std::string concat(const Args&... args) { size_t len = 0; for (auto s : std::initializer_list<concat_impl::sizer>{ args... }) len += s.size; std::string result; result.reserve(len); concat_impl::concat_foreach(result, args...); return result; } template <class B> inline std::string hex_string(const B& buffer) { std::ostringstream oss; oss << std::hex; for (std::size_t i = 0; i < buffer.size(); ++i) { oss << std::setw(2) << std::setfill('0') << static_cast<int>(buffer[i]); } return oss.str(); } // get the value corresponding to a key in a JSON object and assign it to target // if the key is not found, assign default_value to target template <typename T> void assign_or(const nlohmann::json& j, const char* key, T& target, T default_value) { if (j.contains(key)) target = j[key]; else target = default_value; } std::string quote_for_shell(const std::vector<std::string>& arguments, const std::string& shell = ""); void remove_or_rename(const fs::path& path); // Unindent a string literal std::string unindent(const char* p); std::string prepend(const std::string& p, const char* start, const char* newline = ""); std::string prepend(const char* p, const char* start, const char* newline = ""); } // namespace mamba #endif // MAMBA_UTIL_HPP
30.628378
98
0.588904
[ "object", "vector" ]
a925e6a7723b1a0e4e64ec4883e04bf3f490a03b
4,035
cpp
C++
Core/Code/Testing/mitkPointSetFileIOTest.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
5
2015-05-27T06:57:53.000Z
2020-03-12T21:08:23.000Z
Core/Code/Testing/mitkPointSetFileIOTest.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
4
2020-09-17T16:01:55.000Z
2022-01-18T21:12:10.000Z
Core/Code/Testing/mitkPointSetFileIOTest.cpp
danielknorr/MITK
b1b9780b2a6671d8118313c5ef71e9aa128362be
[ "BSD-3-Clause" ]
2
2016-08-17T12:01:04.000Z
2020-03-12T22:36:36.000Z
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkPointSet.h" #include "mitkTestingMacros.h" #include "mitkFileWriterRegistry.h" #include "mitkIOUtil.h" #include <vector> #include <itksys/SystemTools.hxx> #include <time.h> //unsigned int numberOfTestPointSets = 1; unsigned int numberOfTimeSeries = 5; // create one test PointSet class mitkPointSetFileIOTestClass { public: mitk::PointSet::Pointer m_SavedPointSet; std::string m_FilePath; mitkPointSetFileIOTestClass() { } ~mitkPointSetFileIOTestClass() { if (!m_FilePath.empty()) { std::remove(m_FilePath.c_str()); } } mitk::PointSet::Pointer CreateTestPointSet() { mitk::PointSet::Pointer pointSet = mitk::PointSet::New(); for (unsigned int t = 0; t < numberOfTimeSeries; t++) { unsigned int position(0); mitk::Point3D point; mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); pointSet->SetPoint(position, point, t); mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); ++position; pointSet->SetPoint(position, point, t); mitk::FillVector3D(point, (rand()%1000) /1000.0 , (rand()%1000) /1000.0, (rand()%1000)/1000.0); ++position; pointSet->SetPoint(position, point, t); } m_SavedPointSet = pointSet; return pointSet; } void PointSetCompare(mitk::PointSet::Pointer pointSet2, mitk::PointSet::Pointer pointSet1, bool& /*identical*/) { MITK_TEST_CONDITION(pointSet1->GetSize() == pointSet2->GetSize(), "Testing if PointSet size is correct" ); for (unsigned int t = 0; t < numberOfTimeSeries; t++) { for (unsigned int i = 0; i < (unsigned int) pointSet1->GetSize(t); ++i) { mitk::Point3D p1 = pointSet1->GetPoint(i); mitk::Point3D p2 = pointSet2->GetPoint(i); //test std::cout << "r point: " << p2 << std::endl; std::cout << "w point: " << p1 << std::endl; //test end MITK_TEST_CONDITION((p1[0] - p2[0]) <= 0.0001, "Testing if X coordinates of the Point are at the same Position" ); MITK_TEST_CONDITION((p1[1] - p2[1]) <= 0.0001, "Testing if Y coordinates of the Point are at the same Position" ); MITK_TEST_CONDITION((p1[2] - p2[2]) <= 0.0001, "Testing if Z coordinates of the Point are at the same Position" ); } } } bool PointSetWrite() { try { m_SavedPointSet = NULL; std::ofstream tmpStream; m_FilePath = mitk::IOUtil::CreateTemporaryFile(tmpStream); mitk::IOUtil::Save(CreateTestPointSet(), m_FilePath); } catch (std::exception& /*e*/) { return false; } return true; } void PointSetLoadAndCompareTest() { try { mitk::PointSet::Pointer pointSet = mitk::IOUtil::LoadPointSet(m_FilePath); MITK_TEST_CONDITION(pointSet.IsNotNull(), "Testing if the loaded Data are NULL" ); bool identical(true); PointSetCompare(pointSet.GetPointer(), m_SavedPointSet.GetPointer(), identical); } catch (std::exception& /*e*/) { } } }; //mitkPointSetFileIOTestClass int mitkPointSetFileIOTest(int, char*[]) { MITK_TEST_BEGIN("PointSet"); mitkPointSetFileIOTestClass* test = new mitkPointSetFileIOTestClass(); // write MITK_TEST_CONDITION(test->PointSetWrite(), "Testing if the PointSetWriter writes Data" ); // load - compare test->PointSetLoadAndCompareTest(); //Delete correctly delete test; MITK_TEST_END(); }
25.700637
122
0.628748
[ "vector" ]
a92aa02e511b798582eefc05d4586c835b4a56eb
833
cpp
C++
practica_03/two_values.cpp
ImaMos01/ProgCom2021A
ae1cf91be54fe2f565a5b496575855100e8c5bf3
[ "BSD-3-Clause" ]
null
null
null
practica_03/two_values.cpp
ImaMos01/ProgCom2021A
ae1cf91be54fe2f565a5b496575855100e8c5bf3
[ "BSD-3-Clause" ]
null
null
null
practica_03/two_values.cpp
ImaMos01/ProgCom2021A
ae1cf91be54fe2f565a5b496575855100e8c5bf3
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void TwoValues(vector<pair<int,int>>& nums,int k){ int i = 0, j = n - 1; while (i < j) { // movemos los punteros de izquierda y derecha if(nums[i].first + nums[j].first > k) j--; else if (nums[i].first + nums[j].first < k) i++; else if (nums[i].first + nums[j].first == k) { cout << nums[i].second << " " << nums[j].second; return; } } cout << "IMPOSSIBLE" << endl; } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); vector<pair<int,int>> nums; //implementamos un vector de pares int n=0,x=0,a=0; cin>>n>>x; for(int i=0;i<n;i++){ cin>>a; nums.push_back({a,i+1}); } sort(nums.begin(), nums.end()); //ordenamos el vector TwoValues(nums,x); return 0; }
23.138889
67
0.536615
[ "vector" ]
a92fca16fb5a1c49b6ab3d5af65bd29185a018c3
708
cpp
C++
JZ45.cpp
corn1ng/LeetCode-Solution
e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95
[ "Apache-2.0" ]
6
2017-11-18T02:16:35.000Z
2017-12-17T06:30:40.000Z
JZ45.cpp
corn1ng/LeetCode-Solution
e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95
[ "Apache-2.0" ]
null
null
null
JZ45.cpp
corn1ng/LeetCode-Solution
e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95
[ "Apache-2.0" ]
null
null
null
class Solution { public: static bool compare(string& a,string& b) { string st1 =a+b; string st2 =b+a; return st1<st2; } string PrintMinNumber(vector<int> numbers) { string result; int size =numbers.size(); if(size<=0) return result; vector<string> mystr; for(int i=0;i<numbers.size();i++ ){             string s= to_string(numbers[i]);             mystr.push_back(s);         }         sort(mystr.begin(),mystr.end(),compare); for(int i=0;i<mystr.size();i++){             result.append(mystr[i]);         }         return result; } }; // 三步,一,把每个int 变为string 二,排序,三 ,组合。 // to_string 把int 变为string 类型。
24.413793
48
0.522599
[ "vector" ]
a933c5658dab7c1070bac587798ff33bc4ef0db7
28,778
cpp
C++
IGC/AdaptorCommon/ImplicitArgs.cpp
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
IGC/AdaptorCommon/ImplicitArgs.cpp
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
IGC/AdaptorCommon/ImplicitArgs.cpp
bader/intel-graphics-compiler
04f51dc2f3d5047f334da5cb5eebe568480622f5
[ "MIT" ]
null
null
null
/*========================== begin_copyright_notice ============================ Copyright (c) 2000-2021 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ============================= end_copyright_notice ===========================*/ #include "ImplicitArgs.hpp" #include "Compiler/Optimizer/OpenCLPasses/KernelArgs.hpp" #include "common/LLVMWarningsPush.hpp" #include <llvmWrapper/IR/DerivedTypes.h> #include <llvm/IR/Function.h> #include <llvm/IR/Metadata.h> #include <llvm/IR/Module.h> #include "common/LLVMWarningsPop.hpp" #include "Probe/Assertion.h" using namespace llvm; using namespace IGC; using namespace IGC::IGCMD; ImplicitArg::ImplicitArg( const ArgType& argType, const std::string& name, const ValType valType, WIAnalysis::WIDependancy dependency, unsigned int nbElement, ValAlign align, bool isConstantBuf) : m_argType(argType), m_name(name), m_valType(valType), m_dependency(dependency), m_nbElement(nbElement), m_align(align), m_isConstantBuf(isConstantBuf) { } ImplicitArg::ArgType ImplicitArg::getArgType() const { return m_argType; } const std::string& ImplicitArg::getName() const { return m_name; } Type* ImplicitArg::getLLVMType(LLVMContext& context) const { // Return the appropriate LLVM type, based on the argument value type. // This has two quirks: // 1) Pointer size depends on the data layout. // 2) For non-uniform arguments, m_nbElement should be used to determine // the allocation size, but not to determine the LLVM type, because every // work-item sees a scalar. Type* baseType = nullptr; switch (m_valType) { case BYTE: baseType = Type::getInt8Ty(context); break; case SHORT: baseType = Type::getInt16Ty(context); break; case INT: baseType = Type::getInt32Ty(context); break; case LONG: baseType = Type::getInt64Ty(context); break; case FP32: baseType = Type::getFloatTy(context); break; case CONSTPTR: baseType = Type::getInt8Ty(context)->getPointerTo(ADDRESS_SPACE_CONSTANT); break; case PRIVATEPTR: baseType = Type::getInt8Ty(context)->getPointerTo(ADDRESS_SPACE_PRIVATE); break; case GLOBALPTR: baseType = Type::getInt8Ty(context)->getPointerTo(ADDRESS_SPACE_GLOBAL); break; default: IGC_ASSERT_MESSAGE(0, "Unrecognized implicit argument type"); return nullptr; } if (m_nbElement == 1 || !WIAnalysis::isDepUniform(m_dependency)) { return baseType; } else { return IGCLLVM::FixedVectorType::get(baseType, m_nbElement); } } unsigned int ImplicitArg::getNumberElements() const { return m_nbElement; } VISA_Type ImplicitArg::getVISAType(const DataLayout& DL) const { switch (m_valType) { case BYTE: return VISA_Type::ISA_TYPE_B; case SHORT: return VISA_Type::ISA_TYPE_W; case INT: return VISA_Type::ISA_TYPE_D; case LONG: return VISA_Type::ISA_TYPE_Q; case FP32: return VISA_Type::ISA_TYPE_F; case CONSTPTR: case GLOBALPTR: case PRIVATEPTR: return getPointerSize(DL) == 4 ? VISA_Type::ISA_TYPE_UD : VISA_Type::ISA_TYPE_UQ; default: IGC_ASSERT_MESSAGE(0, "Unrecognized implicit argument type"); break; } return VISA_Type::ISA_TYPE_UD; } unsigned int ImplicitArg::getPointerSize(const DataLayout& DL) const { switch (m_valType) { case CONSTPTR: return DL.getPointerSize(ADDRESS_SPACE_CONSTANT); case PRIVATEPTR: return DL.getPointerSize(ADDRESS_SPACE_PRIVATE); case GLOBALPTR: return DL.getPointerSize(ADDRESS_SPACE_GLOBAL); default: IGC_ASSERT_MESSAGE(0, "Unrecognized pointer type"); break; } return 0; } IGC::e_alignment ImplicitArg::getAlignType(const DataLayout& DL) const { switch (m_align) { case ALIGN_DWORD: return IGC::EALIGN_DWORD; case ALIGN_QWORD: return IGC::EALIGN_QWORD; case ALIGN_GRF: //According to old implementation, EALIGN_GRF = EALIGN_HWORD, the corresponding alignmentSize is 32, so EALIGN_HWORD will not change the old define. return IGC::EALIGN_HWORD; //FIXME: But, the ALIGN_GRF is really GRF aligned? If so, there is bug here. case ALIGN_PTR: return getPointerSize(DL) == 4 ? IGC::EALIGN_DWORD : IGC::EALIGN_QWORD; default: IGC_ASSERT_MESSAGE(0, "Uknown alignment"); break; } return IGC::EALIGN_DWORD; } size_t ImplicitArg::getAlignment(const DataLayout& DL) const { return (size_t) 1 << getAlignType(DL); } WIAnalysis::WIDependancy ImplicitArg::getDependency() const { return m_dependency; } unsigned int ImplicitArg::getAllocateSize(const DataLayout& DL) const { unsigned int elemSize = 0; switch (m_valType) { case BYTE: elemSize = 1; break; case SHORT: elemSize = 2; break; case INT: elemSize = 4; break; case LONG: elemSize = 8; break; case FP32: elemSize = 4; break; case CONSTPTR: case GLOBALPTR: case PRIVATEPTR: elemSize = getPointerSize(DL); break; default: IGC_ASSERT_MESSAGE(0, "Unrecognized implicit argument type"); break; } return m_nbElement * elemSize; } bool ImplicitArg::isConstantBuf() const { return m_isConstantBuf; } bool ImplicitArg::isLocalIDs() const { return (m_argType == ImplicitArg::LOCAL_ID_X || m_argType == ImplicitArg::LOCAL_ID_Y || m_argType == ImplicitArg::LOCAL_ID_Z); } ImplicitArgs::ImplicitArgs(const llvm::Function& func , const MetaDataUtils* pMdUtils) { if (IMPLICIT_ARGS.size() == 0) { IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::R0, "r0", ImplicitArg::INT, WIAnalysis::UNIFORM_THREAD, 8, ImplicitArg::ALIGN_GRF, false)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::PAYLOAD_HEADER, "payloadHeader", ImplicitArg::INT, WIAnalysis::UNIFORM_WORKGROUP, 8, ImplicitArg::ALIGN_GRF, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::WORK_DIM, "workDim", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::NUM_GROUPS, "numWorkGroups", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 3, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::GLOBAL_SIZE, "globalSize", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 3, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::LOCAL_SIZE, "localSize", ImplicitArg::INT, WIAnalysis::UNIFORM_WORKGROUP, 3, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::ENQUEUED_LOCAL_WORK_SIZE, "enqueuedLocalSize", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 3, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::LOCAL_ID_X, "localIdX", ImplicitArg::SHORT, WIAnalysis::RANDOM, 16, ImplicitArg::ALIGN_GRF, false)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::LOCAL_ID_Y, "localIdY", ImplicitArg::SHORT, WIAnalysis::RANDOM, 16, ImplicitArg::ALIGN_GRF, false)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::LOCAL_ID_Z, "localIdZ", ImplicitArg::SHORT, WIAnalysis::RANDOM, 16, ImplicitArg::ALIGN_GRF, false)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::CONSTANT_BASE, "constBase", ImplicitArg::CONSTPTR, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_PTR, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::GLOBAL_BASE, "globalBase", ImplicitArg::GLOBALPTR, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_PTR, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::PRIVATE_BASE, "privateBase", ImplicitArg::PRIVATEPTR, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_PTR, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::PRINTF_BUFFER, "printfBuffer", ImplicitArg::GLOBALPTR, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_PTR, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::BUFFER_OFFSET, "bufferOffset", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::CONSTANT_REG_FP32, "const_reg_fp32", ImplicitArg::FP32, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::CONSTANT_REG_QWORD, "const_reg_qword", ImplicitArg::LONG, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_QWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::CONSTANT_REG_DWORD, "const_reg_dword", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::CONSTANT_REG_WORD, "const_reg_word", ImplicitArg::SHORT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::CONSTANT_REG_BYTE, "const_reg_byte", ImplicitArg::BYTE, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_HEIGHT, "imageHeigt", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_WIDTH, "imageWidth", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_DEPTH, "imageDepth", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_NUM_MIP_LEVELS, "imageNumMipLevels", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_CHANNEL_DATA_TYPE, "imageDataType", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_CHANNEL_ORDER, "imageOrder", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_SRGB_CHANNEL_ORDER, "imageSrgbOrder", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_ARRAY_SIZE, "imageArrSize", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::IMAGE_NUM_SAMPLES, "imageNumSamples", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::SAMPLER_ADDRESS, "smpAddress", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::SAMPLER_NORMALIZED, "smpNormalized", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::SAMPLER_SNAP_WA, "smpSnapWA", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::FLAT_IMAGE_BASEOFFSET, "flatImageBaseoffset", ImplicitArg::LONG, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_QWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::FLAT_IMAGE_HEIGHT, "flatImageHeight", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::FLAT_IMAGE_WIDTH, "flatImageWidth", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::FLAT_IMAGE_PITCH, "flatImagePitch", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::VME_MB_BLOCK_TYPE, "vmeMbBlockType", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::VME_SUBPIXEL_MODE, "vmeSubpixelMode", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::VME_SAD_ADJUST_MODE, "vmeSadAdjustMode", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::VME_SEARCH_PATH_TYPE, "vmeSearchPathType", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::DEVICE_ENQUEUE_DEFAULT_DEVICE_QUEUE, "deviceEnqueueDefaultDeviceQueue", ImplicitArg::GLOBALPTR, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_PTR, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::DEVICE_ENQUEUE_EVENT_POOL, "deviceEnqueueEventPool", ImplicitArg::GLOBALPTR, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_PTR, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::DEVICE_ENQUEUE_MAX_WORKGROUP_SIZE, "deviceEnqueueMaxWorkgroupSize", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::DEVICE_ENQUEUE_PARENT_EVENT, "deviceEnqueueParentEvent", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::DEVICE_ENQUEUE_PREFERED_WORKGROUP_MULTIPLE, "deviceEnqueuePreferedWorkgroupMultiple", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::GET_OBJECT_ID, "deviceEnqueueGetObjectId", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::GET_BLOCK_SIMD_SIZE, "deviceEnqueueGetBlockSimdSize", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::LOCAL_MEMORY_STATELESS_WINDOW_START_ADDRESS, "localMemStatelessWindowStartAddr", ImplicitArg::GLOBALPTR, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_PTR, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::LOCAL_MEMORY_STATELESS_WINDOW_SIZE, "localMemStatelessWindowSize", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::PRIVATE_MEMORY_STATELESS_SIZE, "PrivateMemStatelessSize", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::STAGE_IN_GRID_ORIGIN, "stageInGridOrigin", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 3, ImplicitArg::ALIGN_GRF, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::STAGE_IN_GRID_SIZE, "stageInGridSize", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 3, ImplicitArg::ALIGN_GRF, true)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::SYNC_BUFFER, "syncBuffer", ImplicitArg::GLOBALPTR, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_PTR, false)); IMPLICIT_ARGS.push_back(ImplicitArg(ImplicitArg::BINDLESS_OFFSET, "bindlessOffset", ImplicitArg::INT, WIAnalysis::UNIFORM_GLOBAL, 1, ImplicitArg::ALIGN_DWORD, true)); IGC_ASSERT_MESSAGE((IMPLICIT_ARGS.size() == ImplicitArg::NUM_IMPLICIT_ARGS), "Mismatch in NUM_IMPLICIT_ARGS and IMPLICIT_ARGS vector"); { // Note: the order that implicit args are added here must match the // order of the ImplicitArg::Argtype enum. Let's check that they match: uint32_t CurArgId = ImplicitArg::START_ID; for (auto& Arg : IMPLICIT_ARGS) { IGC_ASSERT_MESSAGE((Arg.getArgType() == CurArgId++), "enum and vector out of sync!"); } } } m_funcInfoMD = pMdUtils->getFunctionsInfoItem(const_cast<llvm::Function*>(&func)); } const ImplicitArg& ImplicitArgs::operator[](unsigned int i) const { IGC_ASSERT_MESSAGE((IMPLICIT_ARGS.size() == ImplicitArg::NUM_IMPLICIT_ARGS), "Mismatch in NUM_IMPLICIT_ARGS and IMPLICIT_ARGS vector"); return IMPLICIT_ARGS[getArgType(i)]; } unsigned int ImplicitArgs::getArgIndex(ImplicitArg::ArgType argType) const { IGC_ASSERT_MESSAGE((this->size() > 0), "There are no implicit arguments!"); // Find the first appearance of the given implicit arg type unsigned int implicitArgIndex = 0; for (implicitArgIndex = 0; implicitArgIndex < this->size(); ++implicitArgIndex) { ImplicitArg::ArgType type = getArgType(implicitArgIndex); if (type == argType) { break; } } IGC_ASSERT_MESSAGE((implicitArgIndex < this->size()), "Implicit argument not found!"); return implicitArgIndex; } bool ImplicitArgs::isImplicitArgExist( const IGCMD::FunctionInfoMetaDataHandle& funcInfo, ImplicitArg::ArgType argType) { bool res = false; // Find the first appearance of the given implicit arg type for (unsigned int implicitArgIndex = 0; implicitArgIndex < funcInfo->size_ImplicitArgInfoList(); ++implicitArgIndex) { ImplicitArg::ArgType type = (ImplicitArg::ArgType) funcInfo->getImplicitArgInfoListItem(implicitArgIndex)->getArgId(); if (type == argType) { res = true; break; } } return res; } bool ImplicitArgs::isImplicitArgExist(ImplicitArg::ArgType argType) const { return isImplicitArgExist(m_funcInfoMD, argType); } bool ImplicitArgs::isImplicitArgExist( llvm::Function& F, ImplicitArg::ArgType argType, const IGCMD::MetaDataUtils* pMdUtils) { return isImplicitArgExist(pMdUtils->getFunctionsInfoItem(&F), argType); } unsigned int ImplicitArgs::getImageArgIndex(ImplicitArg::ArgType argType, const Argument* image) const { IGC_ASSERT_MESSAGE(isImplicitImage(argType), "Non image/sampler implicit arg!"); return getNumberedArgIndex(argType, image->getArgNo()); } unsigned int ImplicitArgs::getNumberedArgIndex(ImplicitArg::ArgType argType, int argNum) const { IGC_ASSERT_MESSAGE((argNum >= 0), "objectNum cannot be less than 0"); for (int i = 0, e = m_funcInfoMD->size_ImplicitArgInfoList() ; i < e; ++i) { ArgInfoMetaDataHandle argInfo = m_funcInfoMD->getImplicitArgInfoListItem(i); if (argInfo->getArgId() == argType && argInfo->getExplicitArgNum() == argNum) { return i; } } IGC_ASSERT_MESSAGE(0, "No implicit argument for the given type & argNum"); return m_funcInfoMD->size_ImplicitArgInfoList(); } void ImplicitArgs::addImplicitArgs(llvm::Function& F, const SmallVectorImpl<ImplicitArg::ArgType>& implicitArgs, const MetaDataUtils* pMdUtils) { // Add implicit args metadata for the given function FunctionInfoMetaDataHandle funcInfo = pMdUtils->getFunctionsInfoItem(&F); for (auto arg : implicitArgs) { if (!isImplicitArgExist(F, arg, pMdUtils)) { ArgInfoMetaDataHandle argMD = ArgInfoMetaDataHandle(ArgInfoMetaData::get()); argMD->setArgId(arg); funcInfo->addImplicitArgInfoListItem(argMD); } } } void ImplicitArgs::addImageArgs(llvm::Function& F, const ImplicitArg::ArgMap& argMap, const MetaDataUtils* pMdUtils) { FunctionInfoMetaDataHandle funcInfo = pMdUtils->getFunctionsInfoItem(&F); for (ImplicitArg::ArgType argType = ImplicitArg::IMAGES_START; argType <= ImplicitArg::IMAGES_END; argType = static_cast<ImplicitArg::ArgType>(argType + 1)) { auto argMapIter = argMap.find(argType); if (argMapIter != argMap.end()) { for (const auto& argI : argMapIter->second) { ArgInfoMetaDataHandle argMD = ArgInfoMetaDataHandle(ArgInfoMetaData::get()); argMD->setArgId(argType); argMD->setExplicitArgNum(argI); funcInfo->addImplicitArgInfoListItem(argMD); } } } } void ImplicitArgs::addStructArgs(llvm::Function& F, const Argument* A, const ImplicitArg::StructArgList& S, const MetaDataUtils* pMdUtils) { FunctionInfoMetaDataHandle funcInfo = pMdUtils->getFunctionsInfoItem(&F); for (const auto& argI : S) { unsigned int id = argI.first; unsigned int offset = argI.second; ArgInfoMetaDataHandle argMD = ArgInfoMetaDataHandle(ArgInfoMetaData::get()); argMD->setExplicitArgNum(A->getArgNo()); argMD->setArgId(id); argMD->setStructArgOffset(offset); funcInfo->addImplicitArgInfoListItem(argMD); } } void ImplicitArgs::addNumberedArgs(llvm::Function& F, const ImplicitArg::ArgMap& argMap, const IGCMD::MetaDataUtils* pMdUtils) { FunctionInfoMetaDataHandle funcInfo = pMdUtils->getFunctionsInfoItem(&F); for (const auto& argPair : argMap) { ImplicitArg::ArgType argId = argPair.first; for (const auto& argNum : argPair.second) { ArgInfoMetaDataHandle argMD(ArgInfoMetaData::get()); argMD->setArgId(argId); argMD->setExplicitArgNum(argNum); funcInfo->addImplicitArgInfoListItem(argMD); } } } // Add one implicit argument for each pointer argument to global or constant buffer. // Note that F is the original input function (ie, without implicit arguments). void ImplicitArgs::addBufferOffsetArgs(llvm::Function& F, const IGCMD::MetaDataUtils* pMdUtils, IGC::ModuleMetaData *modMD) { ImplicitArg::ArgMap OffsetArgs; FunctionInfoMetaDataHandle funcInfoMD = pMdUtils->getFunctionsInfoItem(&F); IGC_ASSERT(modMD->FuncMD.find(&F) != modMD->FuncMD.end()); // StatelessToStatefull optimization is not applied on non-kernel functions. if (!isEntryFunc(pMdUtils, &F)) return; FunctionMetaData* funcMD = &modMD->FuncMD.find(&F)->second; for (const auto& Arg : F.args()) { PointerType* PTy = dyn_cast<PointerType>(Arg.getType()); if (!PTy || (PTy->getPointerAddressSpace() != ADDRESS_SPACE_CONSTANT && PTy->getPointerAddressSpace() != ADDRESS_SPACE_GLOBAL)) { continue; } int argNo = Arg.getArgNo(); std::string argbaseType = ""; if (funcMD->m_OpenCLArgBaseTypes.size() > (unsigned)argNo) argbaseType = funcMD->m_OpenCLArgBaseTypes[argNo]; // Do not generate implicit arg for any image arguments KernelArg::ArgType ImgArgType; if (KernelArg::isImage( &Arg, argbaseType, ImgArgType) || KernelArg::isSampler(&Arg, argbaseType)) { continue; } OffsetArgs[ImplicitArg::BUFFER_OFFSET].insert(argNo); } if (OffsetArgs.size() > 0) { ImplicitArgs::addNumberedArgs(F, OffsetArgs, pMdUtils); } } // Add one implicit argument for each pointer argument to global or constant buffer. // Note that F is the original input function (ie, without implicit arguments). void ImplicitArgs::addBindlessOffsetArgs(llvm::Function& F, const IGCMD::MetaDataUtils* pMdUtils, IGC::ModuleMetaData* modMD) { ImplicitArg::ArgMap OffsetArgs; FunctionInfoMetaDataHandle funcInfoMD = pMdUtils->getFunctionsInfoItem(&F); IGC_ASSERT(modMD->FuncMD.find(&F) != modMD->FuncMD.end()); // StatelessToStatefull optimization is not applied on non-kernel functions. if (!isEntryFunc(pMdUtils, &F)) return; FunctionMetaData* funcMD = &modMD->FuncMD.find(&F)->second; for (const auto& Arg : F.args()) { PointerType* PTy = dyn_cast<PointerType>(Arg.getType()); if (!PTy || (PTy->getPointerAddressSpace() != ADDRESS_SPACE_CONSTANT && PTy->getPointerAddressSpace() != ADDRESS_SPACE_GLOBAL)) { continue; } int argNo = Arg.getArgNo(); std::string argbaseType = ""; if (funcMD->m_OpenCLArgBaseTypes.size() > (unsigned)argNo) argbaseType = funcMD->m_OpenCLArgBaseTypes[argNo]; // Do not generate implicit arg for any image arguments KernelArg::ArgType ImgArgType; if (KernelArg::isImage( &Arg, argbaseType, ImgArgType) || KernelArg::isSampler(&Arg, argbaseType)) { continue; } OffsetArgs[ImplicitArg::BINDLESS_OFFSET].insert(argNo); } if (OffsetArgs.size() > 0) { ImplicitArgs::addNumberedArgs(F, OffsetArgs, pMdUtils); } } unsigned int ImplicitArgs::size() const { return m_funcInfoMD->size_ImplicitArgInfoList(); } bool ImplicitArgs::isImplicitImage(ImplicitArg::ArgType argType) { return (argType >= ImplicitArg::IMAGES_START) && (argType <= ImplicitArg::IMAGES_END); } bool ImplicitArgs::isImplicitStruct(ImplicitArg::ArgType argType) { return (argType >= ImplicitArg::STRUCT_START) && (argType <= ImplicitArg::STRUCT_END); } ImplicitArg::ArgType ImplicitArgs::getArgType(unsigned int index) const { IGC_ASSERT_MESSAGE((index < size()), "Index out of range"); ArgInfoMetaDataHandle argInfo = m_funcInfoMD->getImplicitArgInfoListItem(index); return static_cast<ImplicitArg::ArgType>(argInfo->getArgId()); } int32_t ImplicitArgs::getExplicitArgNum(unsigned int index) const { ArgInfoMetaDataHandle argInfo = m_funcInfoMD->getImplicitArgInfoListItem(index); if (argInfo->isExplicitArgNumHasValue()) { return argInfo->getExplicitArgNum(); } return -1; } int32_t ImplicitArgs::getStructArgOffset(unsigned int index) const { ArgInfoMetaDataHandle argInfo = m_funcInfoMD->getImplicitArgInfoListItem(index); if (argInfo->isStructArgOffsetHasValue()) { return argInfo->getStructArgOffset(); } return -1; } TODO("Refactor code to avoid code triplication for getArgInFunc(), getImplicitArg() and WIFuncResolution::getImplicitArg()") Argument* ImplicitArgs::getArgInFunc(llvm::Function& F, ImplicitArg::ArgType argType) const { IGC_ASSERT_MESSAGE((F.arg_size() >= size()), "Invalid number of argumnents in the function!"); unsigned int argIndex = getArgIndex(argType); unsigned int argIndexInFunc = F.arg_size() - size() + argIndex; return F.arg_begin() + argIndexInFunc; } Argument* ImplicitArgs::getImplicitArg(llvm::Function& F, ImplicitArg::ArgType argType) const { if (!isImplicitArgExist(argType)) return nullptr; unsigned int numImplicitArgs = this->size(); unsigned int implicitArgIndex = this->getArgIndex(argType); unsigned int implicitArgIndexInFunc = F.arg_size() - numImplicitArgs + implicitArgIndex; return F.arg_begin() + implicitArgIndexInFunc; } Argument* ImplicitArgs::getNumberedImplicitArg(llvm::Function& F, ImplicitArg::ArgType argType, int argNum) const { IGC_ASSERT_MESSAGE((F.arg_size() >= size()), "Invalid number of arguments in the function!"); unsigned int numImplicitArgs = size(); unsigned int implicitArgIndex = this->getNumberedArgIndex(argType, argNum); if (implicitArgIndex == numImplicitArgs) return nullptr; unsigned int implicitArgIndexInFunc = F.arg_size() - numImplicitArgs + implicitArgIndex; return F.arg_begin() + implicitArgIndexInFunc; } TODO("The allocation size and alignment of constBase should change according to target bitness...")
44.686335
225
0.712489
[ "vector" ]
a937b6dbf16265d76730befb8d52f0a9fd560669
1,227
cpp
C++
online_judges/cf/contest/1521/b/b.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
2
2018-02-20T14:44:57.000Z
2018-02-20T14:45:03.000Z
online_judges/cf/contest/1521/b/b.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
null
null
null
online_judges/cf/contest/1521/b/b.cpp
miaortizma/competitive-programming
ea5adfc07e49935acfc0697eeb0a12c7dc6cd8cc
[ "MIT" ]
null
null
null
/* Generated by powerful Codeforces Tool * You can download the binary file in here https://github.com/xalanq/cf-tool (Windows, macOS, Linux) * Author: mia_ortizma * Time: 2021-05-07 09:35:02 **/ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef tuple<int, int, int, int> tp; const int MAX_N = 1e5 + 100; int arr[MAX_N]; bool even(int x) { return x % 2 == 0; } int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); int T; cin >> T; while (T--) { int N; cin >> N; for (int i = 1; i <= N; ++i) { cin >> arr[i]; } int min_p = 1; int mn = arr[1]; for (int i = 1; i <= N; ++i) { if (arr[i] < mn) { mn = arr[i]; min_p = i; } } vector<tp> vec; if (min_p != 1) { vec.push_back({ 1, min_p, mn, mn }); } for (int i = 2; i <= N; ++i) { if (even(i)) { vec.push_back({ 1, i, mn, mn + 1 }); } else { vec.push_back({ 1, i, mn, mn }); } } cout << vec.size() << "\n"; for (auto& x : vec) { cout << get<0>(x) << " " << get<1>(x) << " " << get<2>(x) << " " << get<3>(x); cout << "\n"; } } return 0; }
18.044118
101
0.472698
[ "vector" ]
a93e785e7acd918291a6ca17b741b6d2a01d4634
30,756
cpp
C++
src/parallel/InteriorBoundary.cpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
2
2018-07-04T16:44:04.000Z
2021-01-03T07:26:27.000Z
src/parallel/InteriorBoundary.cpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
src/parallel/InteriorBoundary.cpp
spraetor/amdis2
53c45c81a65752a8fafbb54f9ae6724a86639dcd
[ "MIT" ]
null
null
null
/****************************************************************************** * * AMDiS - Adaptive multidimensional simulations * * Copyright (C) 2013 Dresden University of Technology. All Rights Reserved. * Web: https://fusionforge.zih.tu-dresden.de/projects/amdis * * Authors: * Simon Vey, Thomas Witkowski, Andreas Naumann, Simon Praetorius, et al. * * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * * This file is part of AMDiS * * See also license.opensource.txt in the distribution. * ******************************************************************************/ #include "parallel/InteriorBoundary.hpp" #include "parallel/ElementObjectDatabase.hpp" #include "parallel/MeshDistributor.hpp" #include "FiniteElemSpace.h" #include "BasisFunction.h" #include "Serializer.h" #include "VertexVector.h" namespace AMDiS { namespace Parallel { using namespace std; void InteriorBoundary::create(MeshLevelData& levelData, int level, ElementObjectDatabase& elObjDb) { FUNCNAME("InteriorBoundary::create()"); own.clear(); other.clear(); periodic.clear(); macroElIndexMap = elObjDb.getElIndexMap(); Mesh* mesh = elObjDb.getMesh(); TEST_EXIT_DBG(mesh)("Should not happen!\n"); TEST_EXIT_DBG(level < levelData.getNumberOfLevels()) ("Should not happen!\n"); MPI::Intracomm mpiComm = levelData.getMpiComm(level); if (mpiComm == MPI::COMM_SELF) return; // int levelMpiRank = mpiComm.Get_rank(); int globalMpiRank = MPI::COMM_WORLD.Get_rank(); std::set<int> levelRanks = levelData.getLevelRanks(level); // === Create interior boundary data structure. === for (int geoPos = 0; geoPos < mesh->getDim(); geoPos++) { GeoIndex geoIndex = INDEX_OF_DIM(geoPos, mesh->getDim()); elObjDb.resetIterator(); while (elObjDb.iterate(geoIndex)) { flat_map<int, ElementObjectData>& objData = elObjDb.getIterateData(); // Test, if this is a boundary object of this rank. if (!(objData.count(globalMpiRank) && objData.size() > 1)) continue; // Test, if the boundary object defines an interior boundary within the // ranks of the MPI group. If not, go to next element. bool boundaryWithinMpiGroup = false; if (levelData.getNumberOfLevels() == 1) { boundaryWithinMpiGroup = true; } else { TEST_EXIT_DBG(level + 1 < levelData.getNumberOfLevels()) ("Level = %d but number of levels = %d\n", level, levelData.getNumberOfLevels()); for (flat_map<int, ElementObjectData>::iterator it = objData.begin(); it != objData.end(); ++it) { if (!levelData.rankInLevel(it->first, level + 1)) { boundaryWithinMpiGroup = true; break; } } } if (!boundaryWithinMpiGroup) continue; int owner = elObjDb.getIterateOwner(level); ElementObjectData& rankBoundEl = objData[globalMpiRank]; AtomicBoundary bound; bound.maxLevel = elObjDb.getIterateMaxLevel(); bound.rankObj.elIndex = rankBoundEl.elIndex; bound.rankObj.elType = elObjDb.getElementType(rankBoundEl.elIndex); bound.rankObj.subObj = geoIndex; bound.rankObj.ithObj = rankBoundEl.ithObject; if (geoIndex == FACE) { for (int edgeNo = 0; edgeNo < 3; edgeNo++) { Element* el = elObjDb.getElementPtr(bound.rankObj.elIndex, mesh); int edgeOfFace = el->getEdgeOfFace(bound.rankObj.ithObj, edgeNo); bound.rankObj.excludedSubstructures.push_back(make_pair(EDGE, edgeOfFace)); } } if (owner == globalMpiRank) { for (flat_map<int, ElementObjectData>::iterator it2 = objData.begin(); it2 != objData.end(); ++it2) { if (it2->first == globalMpiRank) continue; if (!levelData.rankInLevel(it2->first, level)) continue; bound.neighObj.elIndex = it2->second.elIndex; bound.neighObj.elType = elObjDb.getElementType(it2->second.elIndex); bound.neighObj.subObj = geoIndex; bound.neighObj.ithObj = it2->second.ithObject; bound.type = INTERIOR; int rankInLevel = levelData.mapRank(it2->first, 0, level); AtomicBoundary& b = getNewOwn(rankInLevel); b = bound; if (geoIndex == EDGE) b.neighObj.reverseMode = elObjDb.getEdgeReverseMode(rankBoundEl, it2->second); if (geoIndex == FACE) b.neighObj.reverseMode = elObjDb.getFaceReverseMode(rankBoundEl, it2->second); } } else { TEST_EXIT_DBG(objData.count(owner) == 1) ("Should not happen!\n"); ElementObjectData& ownerBoundEl = objData[owner]; bound.neighObj.elIndex = ownerBoundEl.elIndex; bound.neighObj.elType = -1; bound.neighObj.subObj = geoIndex; bound.neighObj.ithObj = ownerBoundEl.ithObject; bound.type = INTERIOR; int rankInLevel = levelData.mapRank(owner, 0, level); AtomicBoundary& b = getNewOther(rankInLevel); b = bound; if (geoIndex == EDGE) b.rankObj.reverseMode = elObjDb.getEdgeReverseMode(rankBoundEl, ownerBoundEl); if (geoIndex == FACE) b.rankObj.reverseMode = elObjDb.getFaceReverseMode(rankBoundEl, ownerBoundEl); } } } // === Create periodic boundary data structure. === int removePeriodicBoundary = 0; Parameters::get("parallel->remove periodic boundary", removePeriodicBoundary); for (PerBoundMap<DegreeOfFreedom>::iterator it = elObjDb.getPeriodicVertices().begin(); it != elObjDb.getPeriodicVertices().end(); ++it) { if (elObjDb.isInRank(it->first.first, globalMpiRank) == false) continue; ElementObjectData& perDofEl0 = elObjDb.getElementsInRank(it->first.first)[globalMpiRank]; for (flat_map<int, ElementObjectData>::iterator elIt = elObjDb.getElementsInRank(it->first.second).begin(); elIt != elObjDb.getElementsInRank(it->first.second).end(); ++elIt) { int otherElementRank = elIt->first; ElementObjectData& perDofEl1 = elIt->second; AtomicBoundary bound; bound.rankObj.elIndex = perDofEl0.elIndex; bound.rankObj.elType = elObjDb.getElementType(perDofEl0.elIndex); bound.rankObj.subObj = VERTEX; bound.rankObj.ithObj = perDofEl0.ithObject; bound.neighObj.elIndex = perDofEl1.elIndex; bound.neighObj.elType = elObjDb.getElementType(perDofEl1.elIndex); bound.neighObj.subObj = VERTEX; bound.neighObj.ithObj = perDofEl1.ithObject; if (removePeriodicBoundary) { bound.type = INTERIOR; flat_map<int, ElementObjectData> objData = elObjDb.getElementsInRank(it->first.first); objData.insert(elObjDb.getElementsInRank(it->first.second).begin(), elObjDb.getElementsInRank(it->first.second).end()); int owner = std::max(elObjDb.getOwner(it->first.first, level), elObjDb.getOwner(it->first.second, level)); // Consider the following configuration of four elements partitioned // to four ranks: // // |--------|--------|(*) // | /| /| // | 3 / | 0 / | // | / | / | // | / | / | // | / | / | // | / 2 | / 1 | // | / | / | // |/-------|/-------| // // We are in now interested in vertex (*). For the first, rank 1 owns // the interior boundary with rank 0 on this vertex. When we remove // periodic boundaries, which are applied on the left and right outer // boundary, rank 3 becomes the owner of this vertex. Rank 0 and rank 1 // will have an interior boundary with rank 3 on this vertex, but rank // 0 and rank 1 have no more interior boundaries on vertex (*). Thus we // have to search and remove for this scenario. if (owner != globalMpiRank) { removeOwn(bound.rankObj); removeOther(bound.rankObj); } // And than we can add the boundary to either own or other part of the // interior database. if (owner == globalMpiRank) { int rankInLevel = levelData.mapRank(otherElementRank, 0, level); AtomicBoundary& b = getNewOwn(rankInLevel); b = bound; } else { ElementObjectData& ownerBoundEl = objData[owner]; bound.neighObj.elIndex = ownerBoundEl.elIndex; bound.neighObj.elType = -1; bound.neighObj.ithObj = ownerBoundEl.ithObject; int rankInLevel = levelData.mapRank(owner, 0, level); AtomicBoundary& b = getNewOther(rankInLevel); b = bound; } } else { bound.type = it->second; int rankInLevel = levelData.mapRank(otherElementRank, 0, level); AtomicBoundary& b = getNewPeriodic(rankInLevel); b = bound; } } } for (PerBoundMap<DofEdge>::iterator it = elObjDb.getPeriodicEdges().begin(); it != elObjDb.getPeriodicEdges().end(); ++it) { if (elObjDb.isInRank(it->first.first, globalMpiRank) == false) continue; ElementObjectData& perEdgeEl0 = elObjDb.getElementsInRank(it->first.first)[globalMpiRank]; for (flat_map<int, ElementObjectData>::iterator elIt = elObjDb.getElementsInRank(it->first.second).begin(); elIt != elObjDb.getElementsInRank(it->first.second).end(); ++elIt) { int otherElementRank = elIt->first; ElementObjectData& perEdgeEl1 = elIt->second; AtomicBoundary bound; bound.rankObj.elIndex = perEdgeEl0.elIndex; bound.rankObj.elType = elObjDb.getElementType(perEdgeEl0.elIndex); bound.rankObj.subObj = EDGE; bound.rankObj.ithObj = perEdgeEl0.ithObject; bound.neighObj.elIndex = perEdgeEl1.elIndex; bound.neighObj.elType = elObjDb.getElementType(perEdgeEl1.elIndex); bound.neighObj.subObj = EDGE; bound.neighObj.ithObj = perEdgeEl1.ithObject; if (removePeriodicBoundary) { bound.type = INTERIOR; flat_map<int, ElementObjectData> objData = elObjDb.getElementsInRank(it->first.first); objData.insert(elObjDb.getElementsInRank(it->first.second).begin(), elObjDb.getElementsInRank(it->first.second).end()); int owner = std::max(elObjDb.getOwner(it->first.first, level), elObjDb.getOwner(it->first.second, level)); ElementObjectData& rankBoundEl = objData[globalMpiRank]; // See comments in the same part of code for VERTEX if (owner != globalMpiRank) { removeOwn(bound.rankObj); removeOther(bound.rankObj); } if (owner == globalMpiRank) { int rankInLevel = levelData.mapRank(owner, 0, level); AtomicBoundary& b = getNewOwn(rankInLevel); b = bound; } else { int rankInLevel = levelData.mapRank(owner, 0, level); AtomicBoundary& b = getNewOther(rankInLevel); b = bound; ElementObjectData& ownerBoundEl = objData[owner]; b.neighObj.elIndex = ownerBoundEl.elIndex; b.neighObj.elType = -1; b.neighObj.ithObj = ownerBoundEl.ithObject; b.rankObj.reverseMode = elObjDb.getEdgeReverseMode(rankBoundEl, ownerBoundEl); } } else { bound.type = it->second; int rankInLevel = levelData.mapRank(otherElementRank, 0, level); AtomicBoundary& b = getNewPeriodic(rankInLevel); b = bound; if (globalMpiRank > otherElementRank) b.neighObj.reverseMode = elObjDb.getEdgeReverseMode(perEdgeEl0, perEdgeEl1); else b.rankObj.reverseMode = elObjDb.getEdgeReverseMode(perEdgeEl0, perEdgeEl1); } } } for (PerBoundMap<DofFace>::iterator it = elObjDb.getPeriodicFaces().begin(); it != elObjDb.getPeriodicFaces().end(); ++it) { if (elObjDb.isInRank(it->first.first, globalMpiRank) == false) continue; TEST_EXIT_DBG(elObjDb.getElements(it->first.first).size() == 1) ("Should not happen!\n"); TEST_EXIT_DBG(elObjDb.getElements(it->first.second).size() == 1) ("Should not happen!\n"); ElementObjectData& perFaceEl0 = elObjDb.getElementsInRank(it->first.first)[globalMpiRank]; for (flat_map<int, ElementObjectData>::iterator elIt = elObjDb.getElementsInRank(it->first.second).begin(); elIt != elObjDb.getElementsInRank(it->first.second).end(); ++elIt) { int otherElementRank = elIt->first; ElementObjectData& perFaceEl1 = elIt->second; AtomicBoundary bound; bound.rankObj.elIndex = perFaceEl0.elIndex; bound.rankObj.elType = elObjDb.getElementType(perFaceEl0.elIndex); bound.rankObj.subObj = FACE; bound.rankObj.ithObj = perFaceEl0.ithObject; bound.neighObj.elIndex = perFaceEl1.elIndex; bound.neighObj.elType = elObjDb.getElementType(perFaceEl1.elIndex); bound.neighObj.subObj = FACE; bound.neighObj.ithObj = perFaceEl1.ithObject; if (removePeriodicBoundary) { bound.type = INTERIOR; flat_map<int, ElementObjectData> objData = elObjDb.getElementsInRank(it->first.first); objData.insert(elObjDb.getElementsInRank(it->first.second).begin(), elObjDb.getElementsInRank(it->first.second).end()); int owner = std::max(elObjDb.getOwner(it->first.first, level), elObjDb.getOwner(it->first.second, level)); ElementObjectData& rankBoundEl = objData[globalMpiRank]; if (owner == globalMpiRank) { int rankInLevel = levelData.mapRank(otherElementRank, 0, level); AtomicBoundary& b = getNewOwn(rankInLevel); b = bound; } else { int rankInLevel = levelData.mapRank(owner, 0, level); AtomicBoundary& b = getNewOther(rankInLevel); b = bound; ElementObjectData& ownerBoundEl = objData[owner]; b.neighObj.elIndex = ownerBoundEl.elIndex; b.neighObj.elType = -1; b.neighObj.ithObj = ownerBoundEl.ithObject; b.rankObj.reverseMode = elObjDb.getFaceReverseMode(rankBoundEl, ownerBoundEl); } } else { bound.type = it->second; int rankInLevel = levelData.mapRank(otherElementRank, 0, level); AtomicBoundary& b = getNewPeriodic(rankInLevel); b = bound; if (globalMpiRank > otherElementRank) b.neighObj.reverseMode = elObjDb.getFaceReverseMode(perFaceEl0, perFaceEl1); else b.rankObj.reverseMode = elObjDb.getFaceReverseMode(perFaceEl0, perFaceEl1); } } } // === Once we have this information, we must care about the order of the === // === atomic bounds in the three boundary handling object. Eventually === // === all the boundaries have to be in the same order on both ranks that === // === share the bounday. === StdMpi<vector<AtomicBoundary>> stdMpi(mpiComm); stdMpi.send(own); stdMpi.recv(other); stdMpi.startCommunication(); // === The information about all neighbouring boundaries has been === // === received. So the rank tests if its own atomic boundaries are in === // === the same order. If not, the atomic boundaries are swaped to the === // === correct order. === for (RankToBoundMap::iterator rankIt = other.begin(); rankIt != other.end(); ++rankIt) { int rank = rankIt->first; // === We have received from "rank" the ordered list of element === // === indices. Now, we have to sort the corresponding list in this === // === rank to get the same order. === for (unsigned int j = 0; j < rankIt->second.size(); j++) { // If the expected object is not at place, search for it. BoundaryObject& receivedBound = stdMpi.getRecvData()[rank][j].rankObj; if ((rankIt->second)[j].neighObj != receivedBound) { unsigned int k = j + 1; for (; k < rankIt->second.size(); k++) { if ((rankIt->second)[k].neighObj == receivedBound) break; } // The element must always be found, because the list is just in // another order. TEST_EXIT_DBG(k < rankIt->second.size()) ("Cannot find element %d/%d/%d received from rank %d!\n", receivedBound.elIndex, receivedBound.subObj, receivedBound.ithObj, rank); // Swap the current with the found element. AtomicBoundary tmpBound = (rankIt->second)[k]; (rankIt->second)[k] = (rankIt->second)[j]; (rankIt->second)[j] = tmpBound; } } } // === Do the same for the periodic boundaries. === if (periodic.size() > 0) { stdMpi.clear(); RankToBoundMap sendBounds, recvBounds; for (RankToBoundMap::iterator rankIt = periodic.begin(); rankIt != periodic.end(); ++rankIt) { if (rankIt->first == globalMpiRank) continue; if (rankIt->first < globalMpiRank) sendBounds[rankIt->first] = rankIt->second; else recvBounds[rankIt->first] = rankIt->second; } stdMpi.send(sendBounds); stdMpi.recv(recvBounds); stdMpi.startCommunication(); for (RankToBoundMap::iterator rankIt = periodic.begin(); rankIt != periodic.end(); ++rankIt) { if (rankIt->first <= globalMpiRank) continue; for (unsigned int j = 0; j < rankIt->second.size(); j++) { BoundaryObject& recvRankObj = stdMpi.getRecvData()[rankIt->first][j].rankObj; BoundaryObject& recvNeighObj = stdMpi.getRecvData()[rankIt->first][j].neighObj; if (periodic[rankIt->first][j].neighObj != recvRankObj || periodic[rankIt->first][j].rankObj != recvNeighObj) { unsigned int k = j + 1; for (; k < rankIt->second.size(); k++) if (periodic[rankIt->first][k].neighObj == recvRankObj && periodic[rankIt->first][k].rankObj == recvNeighObj) break; // The element must always be found, because the list is just in // another order. TEST_EXIT_DBG(k < rankIt->second.size())("Should never happen!\n"); // Swap the current with the found element. AtomicBoundary tmpBound = (rankIt->second)[k]; (rankIt->second)[k] = (rankIt->second)[j]; (rankIt->second)[j] = tmpBound; } } } } // periodicBoundary.boundary.size() > 0 // === Run verification procedure. === verifyBoundary(); } int InteriorBoundary::getDegreeOwn(BoundaryObject& bObj) { int counter = 0; for (RankToBoundMap::iterator it = own.begin(); it != own.end(); ++it) { for (vector<AtomicBoundary>::iterator bIt = it->second.begin(); bIt != it->second.end(); ++bIt) { if (bIt->rankObj == bObj) { counter++; break; } } } return counter; } void InteriorBoundary::serialize(ostream& out) { serialize(out, own); serialize(out, other); serialize(out, periodic); } void InteriorBoundary::serialize(ostream& out, RankToBoundMap& boundary) { int mSize = boundary.size(); SerUtil::serialize(out, mSize); for (RankToBoundMap::iterator it = boundary.begin(); it != boundary.end(); ++it) { int rank = it->first; int boundSize = it->second.size(); SerUtil::serialize(out, rank); SerUtil::serialize(out, boundSize); for (int i = 0; i < boundSize; i++) { AtomicBoundary& bound = (it->second)[i]; SerUtil::serialize(out, bound.rankObj.elIndex); SerUtil::serialize(out, bound.rankObj.elType); SerUtil::serialize(out, bound.rankObj.subObj); SerUtil::serialize(out, bound.rankObj.ithObj); SerUtil::serialize(out, bound.rankObj.reverseMode); serializeExcludeList(out, bound.rankObj.excludedSubstructures); SerUtil::serialize(out, bound.neighObj.elIndex); SerUtil::serialize(out, bound.neighObj.elType); SerUtil::serialize(out, bound.neighObj.subObj); SerUtil::serialize(out, bound.neighObj.ithObj); SerUtil::serialize(out, bound.neighObj.reverseMode); serializeExcludeList(out, bound.neighObj.excludedSubstructures); SerUtil::serialize(out, bound.type); } } } void InteriorBoundary::deserialize(istream& in, Mesh* mesh) { map<int, Element*> elIndexMap; mesh->getElementIndexMap(elIndexMap); deserialize(in, own, elIndexMap); deserialize(in, other, elIndexMap); deserialize(in, periodic, elIndexMap); } void InteriorBoundary::deserialize(istream& in, RankToBoundMap& boundary, map<int, Element*>& elIndexMap) { FUNCNAME_DBG("InteriorBoundary::deserialize()"); int mSize = 0; SerUtil::deserialize(in, mSize); for (int i = 0; i < mSize; i++) { int rank = 0; int boundSize = 0; SerUtil::deserialize(in, rank); SerUtil::deserialize(in, boundSize); boundary[rank].resize(boundSize); for (int i = 0; i < boundSize; i++) { AtomicBoundary& bound = boundary[rank][i]; SerUtil::deserialize(in, bound.rankObj.elIndex); SerUtil::deserialize(in, bound.rankObj.elType); SerUtil::deserialize(in, bound.rankObj.subObj); SerUtil::deserialize(in, bound.rankObj.ithObj); SerUtil::deserialize(in, bound.rankObj.reverseMode); deserializeExcludeList(in, bound.rankObj.excludedSubstructures); SerUtil::deserialize(in, bound.neighObj.elIndex); SerUtil::deserialize(in, bound.neighObj.elType); SerUtil::deserialize(in, bound.neighObj.subObj); SerUtil::deserialize(in, bound.neighObj.ithObj); SerUtil::deserialize(in, bound.neighObj.reverseMode); deserializeExcludeList(in, bound.neighObj.excludedSubstructures); SerUtil::deserialize(in, bound.type); TEST_EXIT_DBG(elIndexMap.count(bound.rankObj.elIndex) == 1) ("Cannot find element with index %d for deserialization!\n", bound.rankObj.elIndex); TEST_EXIT_DBG(elIndexMap[bound.rankObj.elIndex]->getIndex() == bound.rankObj.elIndex)("Should not happen!\n"); bound.rankObj.el = elIndexMap[bound.rankObj.elIndex]; // For the case of periodic interior boundaries, a rank may have an // boundary with itself. In this case, also the pointer to the neighbour // object must be set correctly. if (elIndexMap.count(bound.neighObj.elIndex)) bound.neighObj.el = elIndexMap[bound.neighObj.elIndex]; else bound.neighObj.el = NULL; } } } void InteriorBoundary::verifyBoundary() { FUNCNAME("InteriorBoundary::verifyBoundary()"); // === Check if no other boundery rank object is also included in own === // === boundary part, which would make no sence. === std::set<BoundaryObject> allOwnBounds; for (map<int, vector<AtomicBoundary>>::iterator it = own.begin(); it != own.end(); ++it) for (vector<AtomicBoundary>::iterator bIt = it->second.begin(); bIt != it->second.end(); ++bIt) allOwnBounds.insert(bIt->rankObj); for (map<int, vector<AtomicBoundary>>::iterator it = other.begin(); it != other.end(); ++it) for (vector<AtomicBoundary>::iterator bIt = it->second.begin(); bIt != it->second.end(); ++bIt) if (allOwnBounds.count(bIt->rankObj)) { ERROR_EXIT("Boundary %d/%d/%d is included in both, own and other interior boundary part!\n", bIt->rankObj.elIndex, bIt->rankObj.subObj, bIt->rankObj.ithObj); } } AtomicBoundary& InteriorBoundary::getNewOwn(int rank) { int size = own[rank].size(); own[rank].resize(size + 1); return own[rank][size]; } AtomicBoundary& InteriorBoundary::getNewOther(int rank) { int size = other[rank].size(); other[rank].resize(size + 1); return other[rank][size]; } AtomicBoundary& InteriorBoundary::getNewPeriodic(int rank) { FUNCNAME("InteriorBoundary::getNewPeriodic()"); int size = periodic[rank].size(); periodic[rank].resize(size + 1); return periodic[rank][size]; } bool InteriorBoundary::checkOther(AtomicBoundary& bound, int rank) { FUNCNAME("InteriorBoundary::checkOther()"); int globalMpiRank = MPI::COMM_WORLD.Get_rank(); TEST_EXIT(rank > globalMpiRank) ("Wrong MPI ranks: %d %d\n", rank, globalMpiRank); bool found = false; if (other.count(rank)) { vector<AtomicBoundary>& otherBounds = other[rank]; for (int i = 0; i < static_cast<int>(otherBounds.size()); i++) { if (otherBounds[i].rankObj == bound.rankObj) { if (otherBounds[i].neighObj != bound.neighObj) { ERROR_EXIT("If this really can happen, I have to thing about this!\n"); } else { found = true; break; } } } } return found; } bool InteriorBoundary::removeOwn(BoundaryObject& bound) { bool removed = false; for (map<int, vector<AtomicBoundary>>::iterator it = own.begin(); it != own.end(); ++it) { for (vector<AtomicBoundary>::iterator bIt = it->second.begin(); bIt != it->second.end(); ++bIt) { if (bIt->rankObj == bound) { it->second.erase(bIt); removed = true; break; } } } return removed; } bool InteriorBoundary::removeOther(BoundaryObject& bound) { bool removed = false; for (map<int, vector<AtomicBoundary>>::iterator it = other.begin(); it != other.end(); ++it) { for (vector<AtomicBoundary>::iterator bIt = it->second.begin(); bIt != it->second.end(); ++bIt) { if (bIt->rankObj == bound) { it->second.erase(bIt); removed = true; break; } } } return removed; } void InteriorBoundary::serializeExcludeList(ostream& out, ExcludeList& list) { int size = list.size(); SerUtil::serialize(out, size); for (int i = 0; i < size; i++) { SerUtil::serialize(out, list[i].first); SerUtil::serialize(out, list[i].second); } } void InteriorBoundary::deserializeExcludeList(istream& in, ExcludeList& list) { int size = 0; SerUtil::deserialize(in, size); list.resize(0); list.reserve(size); for (int i = 0; i < size; i++) { GeoIndex a; int b; SerUtil::deserialize(in, a); SerUtil::deserialize(in, b); list.push_back(make_pair(a, b)); } } void MultiLevelInteriorBoundary::create(MeshLevelData& levelData, ElementObjectDatabase& elObjDb) { levelIntBound.clear(); int nLevel = levelData.getNumberOfLevels(); for (int level = 0; level < nLevel; level++) levelIntBound[level].create(levelData, level, elObjDb); } void MultiLevelInteriorBoundary::serialize(ostream& out) { FUNCNAME("MultiLevelInteriorBoundary::serialize()"); ERROR_EXIT("Not yet implemented!\n"); } void MultiLevelInteriorBoundary::deserialize(istream& in, Mesh* mesh) { FUNCNAME("MultiLevelInteriorBoundary::deserialize()"); ERROR_EXIT("Not yet implemented!\n"); } } }
33.539804
115
0.554266
[ "mesh", "object", "vector" ]
a9401d390c0ad90a10abd6e52045d92fe8cf7d0c
2,162
cpp
C++
CM2005 Object Oriented Programming/Topic 4/4.3.3/CSVReader.cpp
LevDoesCode/UoL
312b2d1096af4925c94b81d656e5d326dbad939e
[ "MIT" ]
null
null
null
CM2005 Object Oriented Programming/Topic 4/4.3.3/CSVReader.cpp
LevDoesCode/UoL
312b2d1096af4925c94b81d656e5d326dbad939e
[ "MIT" ]
null
null
null
CM2005 Object Oriented Programming/Topic 4/4.3.3/CSVReader.cpp
LevDoesCode/UoL
312b2d1096af4925c94b81d656e5d326dbad939e
[ "MIT" ]
null
null
null
#include "CSVReader.h" #include <iostream> #include <fstream> CSVReader::CSVReader() { } std::vector<OrderBookEntry> CSVReader::readCSV(std::string csvFilename) { std::vector<OrderBookEntry> entries; unsigned int errors = 0; std::ifstream csvFile{csvFilename}; std::string line; std::cout << "Loading data..." << std::endl; if (csvFile.is_open()) { while(std::getline(csvFile, line)) { try { OrderBookEntry obe = stringsToOBE(tokenise(line, ',')); entries.push_back(obe); } catch(const std::exception& e) { ++errors; } }// end of while std::cout << "Success! " << entries.size() << " entries found." << std::endl; if(errors > 0) std::cout << errors << " errors found." << std::endl; } return entries; } std::vector<std::string> CSVReader::tokenise(std::string csvLine, char separator) { std::vector<std::string> tokens; signed int start, end; std::string token; start = csvLine.find_first_not_of(separator, 0); do{ end = csvLine.find_first_of(separator, start); if (start == csvLine.length() || start == end) break; if (end >= 0) token = csvLine.substr(start, end - start); else token = csvLine.substr(start, csvLine.length() - start); tokens.push_back(token); start = end + 1; } while(end > 0); return tokens; } OrderBookEntry CSVReader::stringsToOBE(std::vector<std::string> tokens) { double price, amount; if (tokens.size() != 5) // bad { //std::cout << "Bad line " << std::endl; throw std::exception{}; } // we have 5 tokens try { price = std::stod(tokens[3]); amount = std::stod(tokens[4]); } catch(const std::exception& e) { throw; } OrderBookEntry obe{price, amount, tokens[0], tokens[1], OrderBookEntry::stringToOrderBookType(tokens[2])}; return obe; }
25.139535
86
0.530527
[ "vector" ]
a94070f9e8e6df0f58f8df2028a70300c5121db1
388,862
cpp
C++
prebuilt/windows.ui.notifications/_nodert_generated.cpp
MarkTiedemann/win10-toast
1502d7d72dfd1e30f2a0c3fb4e95a0ab7ddb817f
[ "WTFPL" ]
2
2018-05-18T11:08:25.000Z
2019-03-11T14:00:22.000Z
prebuilt/windows.ui.notifications/_nodert_generated.cpp
MarkTiedemann/win10-toast
1502d7d72dfd1e30f2a0c3fb4e95a0ab7ddb817f
[ "WTFPL" ]
null
null
null
prebuilt/windows.ui.notifications/_nodert_generated.cpp
MarkTiedemann/win10-toast
1502d7d72dfd1e30f2a0c3fb4e95a0ab7ddb817f
[ "WTFPL" ]
null
null
null
// Copyright (c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *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 Version 2.0 License for specific language governing permissions and limitations under the License. // TODO: Verify that this is is still needed.. #define NTDDI_VERSION 0x06010000 #include <v8.h> #include "nan.h" #include <string> #include <ppltasks.h> #include "CollectionsConverter.h" #include "CollectionsWrap.h" #include "node-async.h" #include "NodeRtUtils.h" #include "OpaqueWrapper.h" #include "WrapperBase.h" #using <Windows.WinMD> // this undefs fixes the issues of compiling Windows.Data.Json, Windows.Storag.FileProperties, and Windows.Stroage.Search // Some of the node header files brings windows definitions with the same names as some of the WinRT methods #undef DocumentProperties #undef GetObject #undef CreateEvent #undef FindText #undef SendMessage const char* REGISTRATION_TOKEN_MAP_PROPERTY_NAME = "__registrationTokenMap__"; using v8::Array; using v8::String; using v8::Handle; using v8::Value; using v8::Boolean; using v8::Integer; using v8::FunctionTemplate; using v8::Object; using v8::Local; using v8::Function; using v8::Date; using v8::Number; using v8::PropertyAttribute; using v8::Primitive; using Nan::HandleScope; using Nan::Persistent; using Nan::Undefined; using Nan::True; using Nan::False; using Nan::Null; using Nan::MaybeLocal; using Nan::EscapableHandleScope; using Nan::HandleScope; using Nan::TryCatch; using namespace concurrency; namespace NodeRT { namespace Windows { namespace UI { namespace Notifications { v8::Local<v8::Value> WrapShownTileNotification(::Windows::UI::Notifications::ShownTileNotification^ wintRtInstance); ::Windows::UI::Notifications::ShownTileNotification^ UnwrapShownTileNotification(Local<Value> value); v8::Local<v8::Value> WrapNotification(::Windows::UI::Notifications::Notification^ wintRtInstance); ::Windows::UI::Notifications::Notification^ UnwrapNotification(Local<Value> value); v8::Local<v8::Value> WrapNotificationBinding(::Windows::UI::Notifications::NotificationBinding^ wintRtInstance); ::Windows::UI::Notifications::NotificationBinding^ UnwrapNotificationBinding(Local<Value> value); v8::Local<v8::Value> WrapIAdaptiveNotificationContent(::Windows::UI::Notifications::IAdaptiveNotificationContent^ wintRtInstance); ::Windows::UI::Notifications::IAdaptiveNotificationContent^ UnwrapIAdaptiveNotificationContent(Local<Value> value); v8::Local<v8::Value> WrapAdaptiveNotificationText(::Windows::UI::Notifications::AdaptiveNotificationText^ wintRtInstance); ::Windows::UI::Notifications::AdaptiveNotificationText^ UnwrapAdaptiveNotificationText(Local<Value> value); v8::Local<v8::Value> WrapTileUpdater(::Windows::UI::Notifications::TileUpdater^ wintRtInstance); ::Windows::UI::Notifications::TileUpdater^ UnwrapTileUpdater(Local<Value> value); v8::Local<v8::Value> WrapTileUpdateManagerForUser(::Windows::UI::Notifications::TileUpdateManagerForUser^ wintRtInstance); ::Windows::UI::Notifications::TileUpdateManagerForUser^ UnwrapTileUpdateManagerForUser(Local<Value> value); v8::Local<v8::Value> WrapTileNotification(::Windows::UI::Notifications::TileNotification^ wintRtInstance); ::Windows::UI::Notifications::TileNotification^ UnwrapTileNotification(Local<Value> value); v8::Local<v8::Value> WrapScheduledTileNotification(::Windows::UI::Notifications::ScheduledTileNotification^ wintRtInstance); ::Windows::UI::Notifications::ScheduledTileNotification^ UnwrapScheduledTileNotification(Local<Value> value); v8::Local<v8::Value> WrapTileFlyoutUpdater(::Windows::UI::Notifications::TileFlyoutUpdater^ wintRtInstance); ::Windows::UI::Notifications::TileFlyoutUpdater^ UnwrapTileFlyoutUpdater(Local<Value> value); v8::Local<v8::Value> WrapTileFlyoutNotification(::Windows::UI::Notifications::TileFlyoutNotification^ wintRtInstance); ::Windows::UI::Notifications::TileFlyoutNotification^ UnwrapTileFlyoutNotification(Local<Value> value); v8::Local<v8::Value> WrapBadgeUpdater(::Windows::UI::Notifications::BadgeUpdater^ wintRtInstance); ::Windows::UI::Notifications::BadgeUpdater^ UnwrapBadgeUpdater(Local<Value> value); v8::Local<v8::Value> WrapBadgeUpdateManagerForUser(::Windows::UI::Notifications::BadgeUpdateManagerForUser^ wintRtInstance); ::Windows::UI::Notifications::BadgeUpdateManagerForUser^ UnwrapBadgeUpdateManagerForUser(Local<Value> value); v8::Local<v8::Value> WrapBadgeNotification(::Windows::UI::Notifications::BadgeNotification^ wintRtInstance); ::Windows::UI::Notifications::BadgeNotification^ UnwrapBadgeNotification(Local<Value> value); v8::Local<v8::Value> WrapToastNotifier(::Windows::UI::Notifications::ToastNotifier^ wintRtInstance); ::Windows::UI::Notifications::ToastNotifier^ UnwrapToastNotifier(Local<Value> value); v8::Local<v8::Value> WrapToastNotification(::Windows::UI::Notifications::ToastNotification^ wintRtInstance); ::Windows::UI::Notifications::ToastNotification^ UnwrapToastNotification(Local<Value> value); v8::Local<v8::Value> WrapScheduledToastNotification(::Windows::UI::Notifications::ScheduledToastNotification^ wintRtInstance); ::Windows::UI::Notifications::ScheduledToastNotification^ UnwrapScheduledToastNotification(Local<Value> value); v8::Local<v8::Value> WrapToastDismissedEventArgs(::Windows::UI::Notifications::ToastDismissedEventArgs^ wintRtInstance); ::Windows::UI::Notifications::ToastDismissedEventArgs^ UnwrapToastDismissedEventArgs(Local<Value> value); v8::Local<v8::Value> WrapToastFailedEventArgs(::Windows::UI::Notifications::ToastFailedEventArgs^ wintRtInstance); ::Windows::UI::Notifications::ToastFailedEventArgs^ UnwrapToastFailedEventArgs(Local<Value> value); v8::Local<v8::Value> WrapNotificationVisual(::Windows::UI::Notifications::NotificationVisual^ wintRtInstance); ::Windows::UI::Notifications::NotificationVisual^ UnwrapNotificationVisual(Local<Value> value); v8::Local<v8::Value> WrapToastNotificationHistory(::Windows::UI::Notifications::ToastNotificationHistory^ wintRtInstance); ::Windows::UI::Notifications::ToastNotificationHistory^ UnwrapToastNotificationHistory(Local<Value> value); v8::Local<v8::Value> WrapToastNotificationManagerForUser(::Windows::UI::Notifications::ToastNotificationManagerForUser^ wintRtInstance); ::Windows::UI::Notifications::ToastNotificationManagerForUser^ UnwrapToastNotificationManagerForUser(Local<Value> value); v8::Local<v8::Value> WrapUserNotificationChangedEventArgs(::Windows::UI::Notifications::UserNotificationChangedEventArgs^ wintRtInstance); ::Windows::UI::Notifications::UserNotificationChangedEventArgs^ UnwrapUserNotificationChangedEventArgs(Local<Value> value); v8::Local<v8::Value> WrapUserNotification(::Windows::UI::Notifications::UserNotification^ wintRtInstance); ::Windows::UI::Notifications::UserNotification^ UnwrapUserNotification(Local<Value> value); v8::Local<v8::Value> WrapKnownAdaptiveNotificationHints(::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ wintRtInstance); ::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ UnwrapKnownAdaptiveNotificationHints(Local<Value> value); v8::Local<v8::Value> WrapKnownNotificationBindings(::Windows::UI::Notifications::KnownNotificationBindings^ wintRtInstance); ::Windows::UI::Notifications::KnownNotificationBindings^ UnwrapKnownNotificationBindings(Local<Value> value); v8::Local<v8::Value> WrapKnownAdaptiveNotificationTextStyles(::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ wintRtInstance); ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ UnwrapKnownAdaptiveNotificationTextStyles(Local<Value> value); v8::Local<v8::Value> WrapTileUpdateManager(::Windows::UI::Notifications::TileUpdateManager^ wintRtInstance); ::Windows::UI::Notifications::TileUpdateManager^ UnwrapTileUpdateManager(Local<Value> value); v8::Local<v8::Value> WrapBadgeUpdateManager(::Windows::UI::Notifications::BadgeUpdateManager^ wintRtInstance); ::Windows::UI::Notifications::BadgeUpdateManager^ UnwrapBadgeUpdateManager(Local<Value> value); v8::Local<v8::Value> WrapTileFlyoutUpdateManager(::Windows::UI::Notifications::TileFlyoutUpdateManager^ wintRtInstance); ::Windows::UI::Notifications::TileFlyoutUpdateManager^ UnwrapTileFlyoutUpdateManager(Local<Value> value); v8::Local<v8::Value> WrapToastNotificationManager(::Windows::UI::Notifications::ToastNotificationManager^ wintRtInstance); ::Windows::UI::Notifications::ToastNotificationManager^ UnwrapToastNotificationManager(Local<Value> value); v8::Local<v8::Value> WrapToastActivatedEventArgs(::Windows::UI::Notifications::ToastActivatedEventArgs^ wintRtInstance); ::Windows::UI::Notifications::ToastActivatedEventArgs^ UnwrapToastActivatedEventArgs(Local<Value> value); v8::Local<v8::Value> WrapToastNotificationHistoryChangedTriggerDetail(::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ wintRtInstance); ::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ UnwrapToastNotificationHistoryChangedTriggerDetail(Local<Value> value); v8::Local<v8::Value> WrapToastNotificationActionTriggerDetail(::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ wintRtInstance); ::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ UnwrapToastNotificationActionTriggerDetail(Local<Value> value); static void InitNotificationSettingEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("NotificationSetting").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("enabled").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationSetting::Enabled))); Nan::Set(enumObject, Nan::New<String>("disabledForApplication").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationSetting::DisabledForApplication))); Nan::Set(enumObject, Nan::New<String>("disabledForUser").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationSetting::DisabledForUser))); Nan::Set(enumObject, Nan::New<String>("disabledByGroupPolicy").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationSetting::DisabledByGroupPolicy))); Nan::Set(enumObject, Nan::New<String>("disabledByManifest").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationSetting::DisabledByManifest))); } static void InitToastDismissalReasonEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("ToastDismissalReason").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("userCanceled").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastDismissalReason::UserCanceled))); Nan::Set(enumObject, Nan::New<String>("applicationHidden").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastDismissalReason::ApplicationHidden))); Nan::Set(enumObject, Nan::New<String>("timedOut").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastDismissalReason::TimedOut))); } static void InitBadgeTemplateTypeEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("BadgeTemplateType").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("badgeGlyph").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::BadgeTemplateType::BadgeGlyph))); Nan::Set(enumObject, Nan::New<String>("badgeNumber").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::BadgeTemplateType::BadgeNumber))); } static void InitTileFlyoutTemplateTypeEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("TileFlyoutTemplateType").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("tileFlyoutTemplate01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileFlyoutTemplateType::TileFlyoutTemplate01))); } static void InitTileTemplateTypeEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("TileTemplateType").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150Image").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150Image))); Nan::Set(enumObject, Nan::New<String>("tileSquareImage").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquareImage))); Nan::Set(enumObject, Nan::New<String>("tileSquareBlock").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquareBlock))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150Block").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150Block))); Nan::Set(enumObject, Nan::New<String>("tileSquareText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquareText01))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150Text01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150Text01))); Nan::Set(enumObject, Nan::New<String>("tileSquareText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquareText02))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150Text02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150Text02))); Nan::Set(enumObject, Nan::New<String>("tileSquareText03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquareText03))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150Text03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150Text03))); Nan::Set(enumObject, Nan::New<String>("tileSquareText04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquareText04))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150Text04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150Text04))); Nan::Set(enumObject, Nan::New<String>("tileSquarePeekImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquarePeekImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150PeekImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150PeekImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileSquarePeekImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquarePeekImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150PeekImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150PeekImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileSquarePeekImageAndText03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquarePeekImageAndText03))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150PeekImageAndText03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150PeekImageAndText03))); Nan::Set(enumObject, Nan::New<String>("tileSquarePeekImageAndText04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquarePeekImageAndText04))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150PeekImageAndText04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150PeekImageAndText04))); Nan::Set(enumObject, Nan::New<String>("tileWideImage").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideImage))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Image").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Image))); Nan::Set(enumObject, Nan::New<String>("tileWideImageCollection").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideImageCollection))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150ImageCollection").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150ImageCollection))); Nan::Set(enumObject, Nan::New<String>("tileWideImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150ImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150ImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileWideImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150ImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150ImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileWideBlockAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideBlockAndText01))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150BlockAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150BlockAndText01))); Nan::Set(enumObject, Nan::New<String>("tileWideBlockAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideBlockAndText02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150BlockAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150BlockAndText02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImageCollection01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImageCollection01))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImageCollection01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImageCollection01))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImageCollection02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImageCollection02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImageCollection02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImageCollection02))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImageCollection03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImageCollection03))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImageCollection03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImageCollection03))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImageCollection04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImageCollection04))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImageCollection04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImageCollection04))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImageCollection05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImageCollection05))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImageCollection05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImageCollection05))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImageCollection06").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImageCollection06))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImageCollection06").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImageCollection06))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImage01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImage01))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImage01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImage01))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImage02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImage02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImage02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImage02))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImage03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImage03))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImage03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImage03))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImage04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImage04))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImage04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImage04))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImage05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImage05))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImage05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImage05))); Nan::Set(enumObject, Nan::New<String>("tileWidePeekImage06").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWidePeekImage06))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150PeekImage06").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150PeekImage06))); Nan::Set(enumObject, Nan::New<String>("tileWideSmallImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideSmallImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150SmallImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150SmallImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileWideSmallImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideSmallImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150SmallImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150SmallImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileWideSmallImageAndText03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideSmallImageAndText03))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150SmallImageAndText03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150SmallImageAndText03))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150SmallImageAndText04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150SmallImageAndText04))); Nan::Set(enumObject, Nan::New<String>("tileWideSmallImageAndText04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideSmallImageAndText04))); Nan::Set(enumObject, Nan::New<String>("tileWideSmallImageAndText05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideSmallImageAndText05))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150SmallImageAndText05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150SmallImageAndText05))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text01))); Nan::Set(enumObject, Nan::New<String>("tileWideText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText01))); Nan::Set(enumObject, Nan::New<String>("tileWideText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text02))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text03))); Nan::Set(enumObject, Nan::New<String>("tileWideText03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText03))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text04))); Nan::Set(enumObject, Nan::New<String>("tileWideText04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText04))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text05))); Nan::Set(enumObject, Nan::New<String>("tileWideText05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText05))); Nan::Set(enumObject, Nan::New<String>("tileWideText06").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText06))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text06").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text06))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text07").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text07))); Nan::Set(enumObject, Nan::New<String>("tileWideText07").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText07))); Nan::Set(enumObject, Nan::New<String>("tileWideText08").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText08))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text08").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text08))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text09").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text09))); Nan::Set(enumObject, Nan::New<String>("tileWideText09").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText09))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text10").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text10))); Nan::Set(enumObject, Nan::New<String>("tileWideText10").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText10))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150Text11").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150Text11))); Nan::Set(enumObject, Nan::New<String>("tileWideText11").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWideText11))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310BlockAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310BlockAndText01))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310BlockAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310BlockAndText02))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Image").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Image))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310ImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310ImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310ImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310ImageAndText02))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310ImageAndTextOverlay01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310ImageAndTextOverlay01))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310ImageAndTextOverlay02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310ImageAndTextOverlay02))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310ImageAndTextOverlay03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310ImageAndTextOverlay03))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310ImageCollectionAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310ImageCollectionAndText01))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310ImageCollectionAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310ImageCollectionAndText02))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310ImageCollection").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310ImageCollection))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310SmallImagesAndTextList01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310SmallImagesAndTextList01))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310SmallImagesAndTextList02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310SmallImagesAndTextList02))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310SmallImagesAndTextList03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310SmallImagesAndTextList03))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310SmallImagesAndTextList04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310SmallImagesAndTextList04))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text01))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text02))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text03))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text04))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text05))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text06").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text06))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text07").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text07))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text08").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text08))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310TextList01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310TextList01))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310TextList02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310TextList02))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310TextList03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310TextList03))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310SmallImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310SmallImageAndText01))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310SmallImagesAndTextList05").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310SmallImagesAndTextList05))); Nan::Set(enumObject, Nan::New<String>("tileSquare310x310Text09").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare310x310Text09))); Nan::Set(enumObject, Nan::New<String>("tileSquare71x71IconWithBadge").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare71x71IconWithBadge))); Nan::Set(enumObject, Nan::New<String>("tileSquare150x150IconWithBadge").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare150x150IconWithBadge))); Nan::Set(enumObject, Nan::New<String>("tileWide310x150IconWithBadgeAndText").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileWide310x150IconWithBadgeAndText))); Nan::Set(enumObject, Nan::New<String>("tileSquare71x71Image").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileSquare71x71Image))); Nan::Set(enumObject, Nan::New<String>("tileTall150x310Image").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::TileTemplateType::TileTall150x310Image))); } static void InitToastTemplateTypeEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("ToastTemplateType").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("toastImageAndText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastTemplateType::ToastImageAndText01))); Nan::Set(enumObject, Nan::New<String>("toastImageAndText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastTemplateType::ToastImageAndText02))); Nan::Set(enumObject, Nan::New<String>("toastImageAndText03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastTemplateType::ToastImageAndText03))); Nan::Set(enumObject, Nan::New<String>("toastImageAndText04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastTemplateType::ToastImageAndText04))); Nan::Set(enumObject, Nan::New<String>("toastText01").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastTemplateType::ToastText01))); Nan::Set(enumObject, Nan::New<String>("toastText02").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastTemplateType::ToastText02))); Nan::Set(enumObject, Nan::New<String>("toastText03").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastTemplateType::ToastText03))); Nan::Set(enumObject, Nan::New<String>("toastText04").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastTemplateType::ToastText04))); } static void InitPeriodicUpdateRecurrenceEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("PeriodicUpdateRecurrence").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("halfHour").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::PeriodicUpdateRecurrence::HalfHour))); Nan::Set(enumObject, Nan::New<String>("hour").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::PeriodicUpdateRecurrence::Hour))); Nan::Set(enumObject, Nan::New<String>("sixHours").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::PeriodicUpdateRecurrence::SixHours))); Nan::Set(enumObject, Nan::New<String>("twelveHours").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::PeriodicUpdateRecurrence::TwelveHours))); Nan::Set(enumObject, Nan::New<String>("daily").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::PeriodicUpdateRecurrence::Daily))); } static void InitToastHistoryChangedTypeEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("ToastHistoryChangedType").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("cleared").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastHistoryChangedType::Cleared))); Nan::Set(enumObject, Nan::New<String>("removed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastHistoryChangedType::Removed))); Nan::Set(enumObject, Nan::New<String>("expired").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastHistoryChangedType::Expired))); Nan::Set(enumObject, Nan::New<String>("added").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::ToastHistoryChangedType::Added))); } static void InitAdaptiveNotificationContentKindEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("AdaptiveNotificationContentKind").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("text").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::AdaptiveNotificationContentKind::Text))); } static void InitNotificationMirroringEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("NotificationMirroring").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("allowed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationMirroring::Allowed))); Nan::Set(enumObject, Nan::New<String>("disabled").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationMirroring::Disabled))); } static void InitNotificationKindsEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("NotificationKinds").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("unknown").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationKinds::Unknown))); Nan::Set(enumObject, Nan::New<String>("toast").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::NotificationKinds::Toast))); } static void InitUserNotificationChangedKindEnum(const Local<Object> exports) { HandleScope scope; Local<Object> enumObject = Nan::New<Object>(); Nan::Set(exports, Nan::New<String>("UserNotificationChangedKind").ToLocalChecked(), enumObject); Nan::Set(enumObject, Nan::New<String>("added").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::UserNotificationChangedKind::Added))); Nan::Set(enumObject, Nan::New<String>("removed").ToLocalChecked(), Nan::New<Integer>(static_cast<int>(::Windows::UI::Notifications::UserNotificationChangedKind::Removed))); } class ShownTileNotification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ShownTileNotification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("arguments").ToLocalChecked(), ArgumentsGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ShownTileNotification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ShownTileNotification(::Windows::UI::Notifications::ShownTileNotification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ShownTileNotification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ShownTileNotification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ShownTileNotification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ShownTileNotification *wrapperInstance = new ShownTileNotification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ArgumentsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ShownTileNotification^>(info.This())) { return; } ShownTileNotification *wrapper = ShownTileNotification::Unwrap<ShownTileNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Arguments; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ShownTileNotification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapShownTileNotification(::Windows::UI::Notifications::ShownTileNotification^ wintRtInstance); friend ::Windows::UI::Notifications::ShownTileNotification^ UnwrapShownTileNotification(Local<Value> value); }; Persistent<FunctionTemplate> ShownTileNotification::s_constructorTemplate; v8::Local<v8::Value> WrapShownTileNotification(::Windows::UI::Notifications::ShownTileNotification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ShownTileNotification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ShownTileNotification^ UnwrapShownTileNotification(Local<Value> value) { return ShownTileNotification::Unwrap<ShownTileNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitShownTileNotification(Local<Object> exports) { ShownTileNotification::Init(exports); } class Notification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("Notification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("visual").ToLocalChecked(), VisualGetter, VisualSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("expirationTime").ToLocalChecked(), ExpirationTimeGetter, ExpirationTimeSetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("Notification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: Notification(::Windows::UI::Notifications::Notification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::Notification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::Notification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::Notification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 0) { try { winRtInstance = ref new ::Windows::UI::Notifications::Notification(); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); Notification *wrapperInstance = new Notification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void VisualGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::Notification^>(info.This())) { return; } Notification *wrapper = Notification::Unwrap<Notification>(info.This()); try { ::Windows::UI::Notifications::NotificationVisual^ result = wrapper->_instance->Visual; info.GetReturnValue().Set(WrapNotificationVisual(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void VisualSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationVisual^>(value)) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::Notification^>(info.This())) { return; } Notification *wrapper = Notification::Unwrap<Notification>(info.This()); try { ::Windows::UI::Notifications::NotificationVisual^ winRtValue = dynamic_cast<::Windows::UI::Notifications::NotificationVisual^>(NodeRT::Utils::GetObjectInstance(value)); wrapper->_instance->Visual = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ExpirationTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::Notification^>(info.This())) { return; } Notification *wrapper = Notification::Unwrap<Notification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ result = wrapper->_instance->ExpirationTime; info.GetReturnValue().Set(result ? static_cast<Local<Value>>(NodeRT::Utils::DateTimeToJS(result->Value)) : Undefined()); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void ExpirationTimeSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsDate()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::Notification^>(info.This())) { return; } Notification *wrapper = Notification::Unwrap<Notification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ winRtValue = ref new ::Platform::Box<::Windows::Foundation::DateTime>(NodeRT::Utils::DateTimeFromJSDate(value)); wrapper->_instance->ExpirationTime = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } private: ::Windows::UI::Notifications::Notification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapNotification(::Windows::UI::Notifications::Notification^ wintRtInstance); friend ::Windows::UI::Notifications::Notification^ UnwrapNotification(Local<Value> value); }; Persistent<FunctionTemplate> Notification::s_constructorTemplate; v8::Local<v8::Value> WrapNotification(::Windows::UI::Notifications::Notification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(Notification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::Notification^ UnwrapNotification(Local<Value> value) { return Notification::Unwrap<Notification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitNotification(Local<Object> exports) { Notification::Init(exports); } class NotificationBinding : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("NotificationBinding").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "getTextElements", GetTextElements); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("template").ToLocalChecked(), TemplateGetter, TemplateSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("language").ToLocalChecked(), LanguageGetter, LanguageSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("hints").ToLocalChecked(), HintsGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("NotificationBinding").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: NotificationBinding(::Windows::UI::Notifications::NotificationBinding^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::NotificationBinding^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationBinding^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::NotificationBinding^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); NotificationBinding *wrapperInstance = new NotificationBinding(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void GetTextElements(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationBinding^>(info.This())) { return; } NotificationBinding *wrapper = NotificationBinding::Unwrap<NotificationBinding>(info.This()); if (info.Length() == 0) { try { ::Windows::Foundation::Collections::IVectorView<::Windows::UI::Notifications::AdaptiveNotificationText^>^ result; result = wrapper->_instance->GetTextElements(); info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::UI::Notifications::AdaptiveNotificationText^>::CreateVectorViewWrapper(result, [](::Windows::UI::Notifications::AdaptiveNotificationText^ val) -> Local<Value> { return WrapAdaptiveNotificationText(val); }, [](Local<Value> value) -> bool { return NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::AdaptiveNotificationText^>(value); }, [](Local<Value> value) -> ::Windows::UI::Notifications::AdaptiveNotificationText^ { return UnwrapAdaptiveNotificationText(value); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void TemplateGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationBinding^>(info.This())) { return; } NotificationBinding *wrapper = NotificationBinding::Unwrap<NotificationBinding>(info.This()); try { Platform::String^ result = wrapper->_instance->Template; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TemplateSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationBinding^>(info.This())) { return; } NotificationBinding *wrapper = NotificationBinding::Unwrap<NotificationBinding>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Template = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void LanguageGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationBinding^>(info.This())) { return; } NotificationBinding *wrapper = NotificationBinding::Unwrap<NotificationBinding>(info.This()); try { Platform::String^ result = wrapper->_instance->Language; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void LanguageSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationBinding^>(info.This())) { return; } NotificationBinding *wrapper = NotificationBinding::Unwrap<NotificationBinding>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Language = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void HintsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationBinding^>(info.This())) { return; } NotificationBinding *wrapper = NotificationBinding::Unwrap<NotificationBinding>(info.This()); try { ::Windows::Foundation::Collections::IMap<::Platform::String^, ::Platform::String^>^ result = wrapper->_instance->Hints; info.GetReturnValue().Set(NodeRT::Collections::MapWrapper<::Platform::String^,::Platform::String^>::CreateMapWrapper(result, [](::Platform::String^ val) -> Local<Value> { return NodeRT::Utils::NewString(val->Data()); }, [](Local<Value> value) -> bool { return value->IsString(); }, [](Local<Value> value) -> ::Platform::String^ { return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); }, [](::Platform::String^ val) -> Local<Value> { return NodeRT::Utils::NewString(val->Data()); }, [](Local<Value> value) -> bool { return value->IsString(); }, [](Local<Value> value) -> ::Platform::String^ { return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::NotificationBinding^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapNotificationBinding(::Windows::UI::Notifications::NotificationBinding^ wintRtInstance); friend ::Windows::UI::Notifications::NotificationBinding^ UnwrapNotificationBinding(Local<Value> value); }; Persistent<FunctionTemplate> NotificationBinding::s_constructorTemplate; v8::Local<v8::Value> WrapNotificationBinding(::Windows::UI::Notifications::NotificationBinding^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(NotificationBinding::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::NotificationBinding^ UnwrapNotificationBinding(Local<Value> value) { return NotificationBinding::Unwrap<NotificationBinding>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitNotificationBinding(Local<Object> exports) { NotificationBinding::Init(exports); } class IAdaptiveNotificationContent : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("IAdaptiveNotificationContent").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("hints").ToLocalChecked(), HintsGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("kind").ToLocalChecked(), KindGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("IAdaptiveNotificationContent").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: IAdaptiveNotificationContent(::Windows::UI::Notifications::IAdaptiveNotificationContent^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::IAdaptiveNotificationContent^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::IAdaptiveNotificationContent^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::IAdaptiveNotificationContent^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); IAdaptiveNotificationContent *wrapperInstance = new IAdaptiveNotificationContent(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void HintsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::IAdaptiveNotificationContent^>(info.This())) { return; } IAdaptiveNotificationContent *wrapper = IAdaptiveNotificationContent::Unwrap<IAdaptiveNotificationContent>(info.This()); try { ::Windows::Foundation::Collections::IMap<::Platform::String^, ::Platform::String^>^ result = wrapper->_instance->Hints; info.GetReturnValue().Set(NodeRT::Collections::MapWrapper<::Platform::String^,::Platform::String^>::CreateMapWrapper(result, [](::Platform::String^ val) -> Local<Value> { return NodeRT::Utils::NewString(val->Data()); }, [](Local<Value> value) -> bool { return value->IsString(); }, [](Local<Value> value) -> ::Platform::String^ { return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); }, [](::Platform::String^ val) -> Local<Value> { return NodeRT::Utils::NewString(val->Data()); }, [](Local<Value> value) -> bool { return value->IsString(); }, [](Local<Value> value) -> ::Platform::String^ { return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void KindGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::IAdaptiveNotificationContent^>(info.This())) { return; } IAdaptiveNotificationContent *wrapper = IAdaptiveNotificationContent::Unwrap<IAdaptiveNotificationContent>(info.This()); try { ::Windows::UI::Notifications::AdaptiveNotificationContentKind result = wrapper->_instance->Kind; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::IAdaptiveNotificationContent^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapIAdaptiveNotificationContent(::Windows::UI::Notifications::IAdaptiveNotificationContent^ wintRtInstance); friend ::Windows::UI::Notifications::IAdaptiveNotificationContent^ UnwrapIAdaptiveNotificationContent(Local<Value> value); }; Persistent<FunctionTemplate> IAdaptiveNotificationContent::s_constructorTemplate; v8::Local<v8::Value> WrapIAdaptiveNotificationContent(::Windows::UI::Notifications::IAdaptiveNotificationContent^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(IAdaptiveNotificationContent::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::IAdaptiveNotificationContent^ UnwrapIAdaptiveNotificationContent(Local<Value> value) { return IAdaptiveNotificationContent::Unwrap<IAdaptiveNotificationContent>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitIAdaptiveNotificationContent(Local<Object> exports) { IAdaptiveNotificationContent::Init(exports); } class AdaptiveNotificationText : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("AdaptiveNotificationText").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("hints").ToLocalChecked(), HintsGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("kind").ToLocalChecked(), KindGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("text").ToLocalChecked(), TextGetter, TextSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("language").ToLocalChecked(), LanguageGetter, LanguageSetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("AdaptiveNotificationText").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: AdaptiveNotificationText(::Windows::UI::Notifications::AdaptiveNotificationText^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::AdaptiveNotificationText^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::AdaptiveNotificationText^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::AdaptiveNotificationText^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 0) { try { winRtInstance = ref new ::Windows::UI::Notifications::AdaptiveNotificationText(); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); AdaptiveNotificationText *wrapperInstance = new AdaptiveNotificationText(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void HintsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::AdaptiveNotificationText^>(info.This())) { return; } AdaptiveNotificationText *wrapper = AdaptiveNotificationText::Unwrap<AdaptiveNotificationText>(info.This()); try { ::Windows::Foundation::Collections::IMap<::Platform::String^, ::Platform::String^>^ result = wrapper->_instance->Hints; info.GetReturnValue().Set(NodeRT::Collections::MapWrapper<::Platform::String^,::Platform::String^>::CreateMapWrapper(result, [](::Platform::String^ val) -> Local<Value> { return NodeRT::Utils::NewString(val->Data()); }, [](Local<Value> value) -> bool { return value->IsString(); }, [](Local<Value> value) -> ::Platform::String^ { return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); }, [](::Platform::String^ val) -> Local<Value> { return NodeRT::Utils::NewString(val->Data()); }, [](Local<Value> value) -> bool { return value->IsString(); }, [](Local<Value> value) -> ::Platform::String^ { return ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void KindGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::AdaptiveNotificationText^>(info.This())) { return; } AdaptiveNotificationText *wrapper = AdaptiveNotificationText::Unwrap<AdaptiveNotificationText>(info.This()); try { ::Windows::UI::Notifications::AdaptiveNotificationContentKind result = wrapper->_instance->Kind; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TextGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::AdaptiveNotificationText^>(info.This())) { return; } AdaptiveNotificationText *wrapper = AdaptiveNotificationText::Unwrap<AdaptiveNotificationText>(info.This()); try { Platform::String^ result = wrapper->_instance->Text; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TextSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::AdaptiveNotificationText^>(info.This())) { return; } AdaptiveNotificationText *wrapper = AdaptiveNotificationText::Unwrap<AdaptiveNotificationText>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Text = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void LanguageGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::AdaptiveNotificationText^>(info.This())) { return; } AdaptiveNotificationText *wrapper = AdaptiveNotificationText::Unwrap<AdaptiveNotificationText>(info.This()); try { Platform::String^ result = wrapper->_instance->Language; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void LanguageSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::AdaptiveNotificationText^>(info.This())) { return; } AdaptiveNotificationText *wrapper = AdaptiveNotificationText::Unwrap<AdaptiveNotificationText>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Language = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } private: ::Windows::UI::Notifications::AdaptiveNotificationText^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapAdaptiveNotificationText(::Windows::UI::Notifications::AdaptiveNotificationText^ wintRtInstance); friend ::Windows::UI::Notifications::AdaptiveNotificationText^ UnwrapAdaptiveNotificationText(Local<Value> value); }; Persistent<FunctionTemplate> AdaptiveNotificationText::s_constructorTemplate; v8::Local<v8::Value> WrapAdaptiveNotificationText(::Windows::UI::Notifications::AdaptiveNotificationText^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(AdaptiveNotificationText::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::AdaptiveNotificationText^ UnwrapAdaptiveNotificationText(Local<Value> value) { return AdaptiveNotificationText::Unwrap<AdaptiveNotificationText>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitAdaptiveNotificationText(Local<Object> exports) { AdaptiveNotificationText::Init(exports); } class TileUpdater : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("TileUpdater").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "update", Update); Nan::SetPrototypeMethod(localRef, "clear", Clear); Nan::SetPrototypeMethod(localRef, "enableNotificationQueue", EnableNotificationQueue); Nan::SetPrototypeMethod(localRef, "addToSchedule", AddToSchedule); Nan::SetPrototypeMethod(localRef, "removeFromSchedule", RemoveFromSchedule); Nan::SetPrototypeMethod(localRef, "getScheduledTileNotifications", GetScheduledTileNotifications); Nan::SetPrototypeMethod(localRef, "startPeriodicUpdate", StartPeriodicUpdate); Nan::SetPrototypeMethod(localRef, "stopPeriodicUpdate", StopPeriodicUpdate); Nan::SetPrototypeMethod(localRef, "startPeriodicUpdateBatch", StartPeriodicUpdateBatch); Nan::SetPrototypeMethod(localRef, "enableNotificationQueueForSquare150x150", EnableNotificationQueueForSquare150x150); Nan::SetPrototypeMethod(localRef, "enableNotificationQueueForWide310x150", EnableNotificationQueueForWide310x150); Nan::SetPrototypeMethod(localRef, "enableNotificationQueueForSquare310x310", EnableNotificationQueueForSquare310x310); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("setting").ToLocalChecked(), SettingGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("TileUpdater").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: TileUpdater(::Windows::UI::Notifications::TileUpdater^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::TileUpdater^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::TileUpdater^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); TileUpdater *wrapperInstance = new TileUpdater(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void Update(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileNotification^>(info[0])) { try { ::Windows::UI::Notifications::TileNotification^ arg0 = UnwrapTileNotification(info[0]); wrapper->_instance->Update(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void Clear(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 0) { try { wrapper->_instance->Clear(); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void EnableNotificationQueue(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 1 && info[0]->IsBoolean()) { try { bool arg0 = Nan::To<bool>(info[0]).FromMaybe(false); wrapper->_instance->EnableNotificationQueue(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void AddToSchedule(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info[0])) { try { ::Windows::UI::Notifications::ScheduledTileNotification^ arg0 = UnwrapScheduledTileNotification(info[0]); wrapper->_instance->AddToSchedule(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void RemoveFromSchedule(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info[0])) { try { ::Windows::UI::Notifications::ScheduledTileNotification^ arg0 = UnwrapScheduledTileNotification(info[0]); wrapper->_instance->RemoveFromSchedule(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void GetScheduledTileNotifications(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 0) { try { ::Windows::Foundation::Collections::IVectorView<::Windows::UI::Notifications::ScheduledTileNotification^>^ result; result = wrapper->_instance->GetScheduledTileNotifications(); info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::UI::Notifications::ScheduledTileNotification^>::CreateVectorViewWrapper(result, [](::Windows::UI::Notifications::ScheduledTileNotification^ val) -> Local<Value> { return WrapScheduledTileNotification(val); }, [](Local<Value> value) -> bool { return NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(value); }, [](Local<Value> value) -> ::Windows::UI::Notifications::ScheduledTileNotification^ { return UnwrapScheduledTileNotification(value); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void StartPeriodicUpdate(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 2 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[0]) && info[1]->IsInt32()) { try { ::Windows::Foundation::Uri^ arg0 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::UI::Notifications::PeriodicUpdateRecurrence arg1 = static_cast<::Windows::UI::Notifications::PeriodicUpdateRecurrence>(Nan::To<int32_t>(info[1]).FromMaybe(0)); wrapper->_instance->StartPeriodicUpdate(arg0, arg1); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 3 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[0]) && info[1]->IsDate() && info[2]->IsInt32()) { try { ::Windows::Foundation::Uri^ arg0 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::Foundation::DateTime arg1 = NodeRT::Utils::DateTimeFromJSDate(info[1]); ::Windows::UI::Notifications::PeriodicUpdateRecurrence arg2 = static_cast<::Windows::UI::Notifications::PeriodicUpdateRecurrence>(Nan::To<int32_t>(info[2]).FromMaybe(0)); wrapper->_instance->StartPeriodicUpdate(arg0, arg1, arg2); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void StopPeriodicUpdate(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 0) { try { wrapper->_instance->StopPeriodicUpdate(); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void StartPeriodicUpdateBatch(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 2 && (NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^>(info[0]) || info[0]->IsArray()) && info[1]->IsInt32()) { try { ::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^ arg0 = [] (v8::Local<v8::Value> value) -> ::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^ { if (value->IsArray()) { return NodeRT::Collections::JsArrayToWinrtVector<::Windows::Foundation::Uri^>(value.As<Array>(), [](Local<Value> value) -> bool { return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(value); }, [](Local<Value> value) -> ::Windows::Foundation::Uri^ { return dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(value)); } ); } else { return dynamic_cast<::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^>(NodeRT::Utils::GetObjectInstance(value)); } } (info[0]); ::Windows::UI::Notifications::PeriodicUpdateRecurrence arg1 = static_cast<::Windows::UI::Notifications::PeriodicUpdateRecurrence>(Nan::To<int32_t>(info[1]).FromMaybe(0)); wrapper->_instance->StartPeriodicUpdateBatch(arg0, arg1); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 3 && (NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^>(info[0]) || info[0]->IsArray()) && info[1]->IsDate() && info[2]->IsInt32()) { try { ::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^ arg0 = [] (v8::Local<v8::Value> value) -> ::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^ { if (value->IsArray()) { return NodeRT::Collections::JsArrayToWinrtVector<::Windows::Foundation::Uri^>(value.As<Array>(), [](Local<Value> value) -> bool { return NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(value); }, [](Local<Value> value) -> ::Windows::Foundation::Uri^ { return dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(value)); } ); } else { return dynamic_cast<::Windows::Foundation::Collections::IIterable<::Windows::Foundation::Uri^>^>(NodeRT::Utils::GetObjectInstance(value)); } } (info[0]); ::Windows::Foundation::DateTime arg1 = NodeRT::Utils::DateTimeFromJSDate(info[1]); ::Windows::UI::Notifications::PeriodicUpdateRecurrence arg2 = static_cast<::Windows::UI::Notifications::PeriodicUpdateRecurrence>(Nan::To<int32_t>(info[2]).FromMaybe(0)); wrapper->_instance->StartPeriodicUpdateBatch(arg0, arg1, arg2); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void EnableNotificationQueueForSquare150x150(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 1 && info[0]->IsBoolean()) { try { bool arg0 = Nan::To<bool>(info[0]).FromMaybe(false); wrapper->_instance->EnableNotificationQueueForSquare150x150(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void EnableNotificationQueueForWide310x150(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 1 && info[0]->IsBoolean()) { try { bool arg0 = Nan::To<bool>(info[0]).FromMaybe(false); wrapper->_instance->EnableNotificationQueueForWide310x150(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void EnableNotificationQueueForSquare310x310(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); if (info.Length() == 1 && info[0]->IsBoolean()) { try { bool arg0 = Nan::To<bool>(info[0]).FromMaybe(false); wrapper->_instance->EnableNotificationQueueForSquare310x310(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void SettingGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdater^>(info.This())) { return; } TileUpdater *wrapper = TileUpdater::Unwrap<TileUpdater>(info.This()); try { ::Windows::UI::Notifications::NotificationSetting result = wrapper->_instance->Setting; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::TileUpdater^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapTileUpdater(::Windows::UI::Notifications::TileUpdater^ wintRtInstance); friend ::Windows::UI::Notifications::TileUpdater^ UnwrapTileUpdater(Local<Value> value); }; Persistent<FunctionTemplate> TileUpdater::s_constructorTemplate; v8::Local<v8::Value> WrapTileUpdater(::Windows::UI::Notifications::TileUpdater^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(TileUpdater::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::TileUpdater^ UnwrapTileUpdater(Local<Value> value) { return TileUpdater::Unwrap<TileUpdater>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitTileUpdater(Local<Object> exports) { TileUpdater::Init(exports); } class TileUpdateManagerForUser : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("TileUpdateManagerForUser").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "createTileUpdaterForApplicationForUser", CreateTileUpdaterForApplicationForUser); Nan::SetPrototypeMethod(localRef, "createTileUpdaterForApplication", CreateTileUpdaterForApplication); Nan::SetPrototypeMethod(localRef, "createTileUpdaterForSecondaryTile", CreateTileUpdaterForSecondaryTile); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("user").ToLocalChecked(), UserGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("TileUpdateManagerForUser").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: TileUpdateManagerForUser(::Windows::UI::Notifications::TileUpdateManagerForUser^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::TileUpdateManagerForUser^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdateManagerForUser^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::TileUpdateManagerForUser^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); TileUpdateManagerForUser *wrapperInstance = new TileUpdateManagerForUser(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void CreateTileUpdaterForApplicationForUser(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdateManagerForUser^>(info.This())) { return; } TileUpdateManagerForUser *wrapper = TileUpdateManagerForUser::Unwrap<TileUpdateManagerForUser>(info.This()); if (info.Length() == 0) { try { ::Windows::UI::Notifications::TileUpdater^ result; result = wrapper->_instance->CreateTileUpdaterForApplicationForUser(); info.GetReturnValue().Set(WrapTileUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateTileUpdaterForApplication(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdateManagerForUser^>(info.This())) { return; } TileUpdateManagerForUser *wrapper = TileUpdateManagerForUser::Unwrap<TileUpdateManagerForUser>(info.This()); if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::TileUpdater^ result; result = wrapper->_instance->CreateTileUpdaterForApplication(arg0); info.GetReturnValue().Set(WrapTileUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateTileUpdaterForSecondaryTile(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdateManagerForUser^>(info.This())) { return; } TileUpdateManagerForUser *wrapper = TileUpdateManagerForUser::Unwrap<TileUpdateManagerForUser>(info.This()); if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::TileUpdater^ result; result = wrapper->_instance->CreateTileUpdaterForSecondaryTile(arg0); info.GetReturnValue().Set(WrapTileUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void UserGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdateManagerForUser^>(info.This())) { return; } TileUpdateManagerForUser *wrapper = TileUpdateManagerForUser::Unwrap<TileUpdateManagerForUser>(info.This()); try { ::Windows::System::User^ result = wrapper->_instance->User; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.System", "User", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::TileUpdateManagerForUser^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapTileUpdateManagerForUser(::Windows::UI::Notifications::TileUpdateManagerForUser^ wintRtInstance); friend ::Windows::UI::Notifications::TileUpdateManagerForUser^ UnwrapTileUpdateManagerForUser(Local<Value> value); }; Persistent<FunctionTemplate> TileUpdateManagerForUser::s_constructorTemplate; v8::Local<v8::Value> WrapTileUpdateManagerForUser(::Windows::UI::Notifications::TileUpdateManagerForUser^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(TileUpdateManagerForUser::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::TileUpdateManagerForUser^ UnwrapTileUpdateManagerForUser(Local<Value> value) { return TileUpdateManagerForUser::Unwrap<TileUpdateManagerForUser>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitTileUpdateManagerForUser(Local<Object> exports) { TileUpdateManagerForUser::Init(exports); } class TileNotification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("TileNotification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("tag").ToLocalChecked(), TagGetter, TagSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("expirationTime").ToLocalChecked(), ExpirationTimeGetter, ExpirationTimeSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("content").ToLocalChecked(), ContentGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("TileNotification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: TileNotification(::Windows::UI::Notifications::TileNotification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::TileNotification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileNotification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::TileNotification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Xml::Dom::XmlDocument^>(info[0])) { try { ::Windows::Data::Xml::Dom::XmlDocument^ arg0 = dynamic_cast<::Windows::Data::Xml::Dom::XmlDocument^>(NodeRT::Utils::GetObjectInstance(info[0])); winRtInstance = ref new ::Windows::UI::Notifications::TileNotification(arg0); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); TileNotification *wrapperInstance = new TileNotification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void TagGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileNotification^>(info.This())) { return; } TileNotification *wrapper = TileNotification::Unwrap<TileNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Tag; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TagSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileNotification^>(info.This())) { return; } TileNotification *wrapper = TileNotification::Unwrap<TileNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Tag = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ExpirationTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileNotification^>(info.This())) { return; } TileNotification *wrapper = TileNotification::Unwrap<TileNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ result = wrapper->_instance->ExpirationTime; info.GetReturnValue().Set(result ? static_cast<Local<Value>>(NodeRT::Utils::DateTimeToJS(result->Value)) : Undefined()); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void ExpirationTimeSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsDate()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileNotification^>(info.This())) { return; } TileNotification *wrapper = TileNotification::Unwrap<TileNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ winRtValue = ref new ::Platform::Box<::Windows::Foundation::DateTime>(NodeRT::Utils::DateTimeFromJSDate(value)); wrapper->_instance->ExpirationTime = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ContentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileNotification^>(info.This())) { return; } TileNotification *wrapper = TileNotification::Unwrap<TileNotification>(info.This()); try { ::Windows::Data::Xml::Dom::XmlDocument^ result = wrapper->_instance->Content; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::TileNotification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapTileNotification(::Windows::UI::Notifications::TileNotification^ wintRtInstance); friend ::Windows::UI::Notifications::TileNotification^ UnwrapTileNotification(Local<Value> value); }; Persistent<FunctionTemplate> TileNotification::s_constructorTemplate; v8::Local<v8::Value> WrapTileNotification(::Windows::UI::Notifications::TileNotification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(TileNotification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::TileNotification^ UnwrapTileNotification(Local<Value> value) { return TileNotification::Unwrap<TileNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitTileNotification(Local<Object> exports) { TileNotification::Init(exports); } class ScheduledTileNotification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ScheduledTileNotification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("tag").ToLocalChecked(), TagGetter, TagSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("id").ToLocalChecked(), IdGetter, IdSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("expirationTime").ToLocalChecked(), ExpirationTimeGetter, ExpirationTimeSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("content").ToLocalChecked(), ContentGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("deliveryTime").ToLocalChecked(), DeliveryTimeGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ScheduledTileNotification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ScheduledTileNotification(::Windows::UI::Notifications::ScheduledTileNotification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ScheduledTileNotification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ScheduledTileNotification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 2 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Xml::Dom::XmlDocument^>(info[0]) && info[1]->IsDate()) { try { ::Windows::Data::Xml::Dom::XmlDocument^ arg0 = dynamic_cast<::Windows::Data::Xml::Dom::XmlDocument^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::Foundation::DateTime arg1 = NodeRT::Utils::DateTimeFromJSDate(info[1]); winRtInstance = ref new ::Windows::UI::Notifications::ScheduledTileNotification(arg0,arg1); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ScheduledTileNotification *wrapperInstance = new ScheduledTileNotification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void TagGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info.This())) { return; } ScheduledTileNotification *wrapper = ScheduledTileNotification::Unwrap<ScheduledTileNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Tag; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TagSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info.This())) { return; } ScheduledTileNotification *wrapper = ScheduledTileNotification::Unwrap<ScheduledTileNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Tag = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void IdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info.This())) { return; } ScheduledTileNotification *wrapper = ScheduledTileNotification::Unwrap<ScheduledTileNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Id; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void IdSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info.This())) { return; } ScheduledTileNotification *wrapper = ScheduledTileNotification::Unwrap<ScheduledTileNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Id = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ExpirationTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info.This())) { return; } ScheduledTileNotification *wrapper = ScheduledTileNotification::Unwrap<ScheduledTileNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ result = wrapper->_instance->ExpirationTime; info.GetReturnValue().Set(result ? static_cast<Local<Value>>(NodeRT::Utils::DateTimeToJS(result->Value)) : Undefined()); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void ExpirationTimeSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsDate()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info.This())) { return; } ScheduledTileNotification *wrapper = ScheduledTileNotification::Unwrap<ScheduledTileNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ winRtValue = ref new ::Platform::Box<::Windows::Foundation::DateTime>(NodeRT::Utils::DateTimeFromJSDate(value)); wrapper->_instance->ExpirationTime = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ContentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info.This())) { return; } ScheduledTileNotification *wrapper = ScheduledTileNotification::Unwrap<ScheduledTileNotification>(info.This()); try { ::Windows::Data::Xml::Dom::XmlDocument^ result = wrapper->_instance->Content; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void DeliveryTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledTileNotification^>(info.This())) { return; } ScheduledTileNotification *wrapper = ScheduledTileNotification::Unwrap<ScheduledTileNotification>(info.This()); try { ::Windows::Foundation::DateTime result = wrapper->_instance->DeliveryTime; info.GetReturnValue().Set(NodeRT::Utils::DateTimeToJS(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ScheduledTileNotification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapScheduledTileNotification(::Windows::UI::Notifications::ScheduledTileNotification^ wintRtInstance); friend ::Windows::UI::Notifications::ScheduledTileNotification^ UnwrapScheduledTileNotification(Local<Value> value); }; Persistent<FunctionTemplate> ScheduledTileNotification::s_constructorTemplate; v8::Local<v8::Value> WrapScheduledTileNotification(::Windows::UI::Notifications::ScheduledTileNotification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ScheduledTileNotification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ScheduledTileNotification^ UnwrapScheduledTileNotification(Local<Value> value) { return ScheduledTileNotification::Unwrap<ScheduledTileNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitScheduledTileNotification(Local<Object> exports) { ScheduledTileNotification::Init(exports); } class TileFlyoutUpdater : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("TileFlyoutUpdater").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "update", Update); Nan::SetPrototypeMethod(localRef, "clear", Clear); Nan::SetPrototypeMethod(localRef, "startPeriodicUpdate", StartPeriodicUpdate); Nan::SetPrototypeMethod(localRef, "stopPeriodicUpdate", StopPeriodicUpdate); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("setting").ToLocalChecked(), SettingGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("TileFlyoutUpdater").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: TileFlyoutUpdater(::Windows::UI::Notifications::TileFlyoutUpdater^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::TileFlyoutUpdater^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutUpdater^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::TileFlyoutUpdater^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); TileFlyoutUpdater *wrapperInstance = new TileFlyoutUpdater(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void Update(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutUpdater^>(info.This())) { return; } TileFlyoutUpdater *wrapper = TileFlyoutUpdater::Unwrap<TileFlyoutUpdater>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutNotification^>(info[0])) { try { ::Windows::UI::Notifications::TileFlyoutNotification^ arg0 = UnwrapTileFlyoutNotification(info[0]); wrapper->_instance->Update(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void Clear(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutUpdater^>(info.This())) { return; } TileFlyoutUpdater *wrapper = TileFlyoutUpdater::Unwrap<TileFlyoutUpdater>(info.This()); if (info.Length() == 0) { try { wrapper->_instance->Clear(); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void StartPeriodicUpdate(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutUpdater^>(info.This())) { return; } TileFlyoutUpdater *wrapper = TileFlyoutUpdater::Unwrap<TileFlyoutUpdater>(info.This()); if (info.Length() == 2 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[0]) && info[1]->IsInt32()) { try { ::Windows::Foundation::Uri^ arg0 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::UI::Notifications::PeriodicUpdateRecurrence arg1 = static_cast<::Windows::UI::Notifications::PeriodicUpdateRecurrence>(Nan::To<int32_t>(info[1]).FromMaybe(0)); wrapper->_instance->StartPeriodicUpdate(arg0, arg1); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 3 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[0]) && info[1]->IsDate() && info[2]->IsInt32()) { try { ::Windows::Foundation::Uri^ arg0 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::Foundation::DateTime arg1 = NodeRT::Utils::DateTimeFromJSDate(info[1]); ::Windows::UI::Notifications::PeriodicUpdateRecurrence arg2 = static_cast<::Windows::UI::Notifications::PeriodicUpdateRecurrence>(Nan::To<int32_t>(info[2]).FromMaybe(0)); wrapper->_instance->StartPeriodicUpdate(arg0, arg1, arg2); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void StopPeriodicUpdate(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutUpdater^>(info.This())) { return; } TileFlyoutUpdater *wrapper = TileFlyoutUpdater::Unwrap<TileFlyoutUpdater>(info.This()); if (info.Length() == 0) { try { wrapper->_instance->StopPeriodicUpdate(); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void SettingGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutUpdater^>(info.This())) { return; } TileFlyoutUpdater *wrapper = TileFlyoutUpdater::Unwrap<TileFlyoutUpdater>(info.This()); try { ::Windows::UI::Notifications::NotificationSetting result = wrapper->_instance->Setting; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::TileFlyoutUpdater^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapTileFlyoutUpdater(::Windows::UI::Notifications::TileFlyoutUpdater^ wintRtInstance); friend ::Windows::UI::Notifications::TileFlyoutUpdater^ UnwrapTileFlyoutUpdater(Local<Value> value); }; Persistent<FunctionTemplate> TileFlyoutUpdater::s_constructorTemplate; v8::Local<v8::Value> WrapTileFlyoutUpdater(::Windows::UI::Notifications::TileFlyoutUpdater^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(TileFlyoutUpdater::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::TileFlyoutUpdater^ UnwrapTileFlyoutUpdater(Local<Value> value) { return TileFlyoutUpdater::Unwrap<TileFlyoutUpdater>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitTileFlyoutUpdater(Local<Object> exports) { TileFlyoutUpdater::Init(exports); } class TileFlyoutNotification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("TileFlyoutNotification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("expirationTime").ToLocalChecked(), ExpirationTimeGetter, ExpirationTimeSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("content").ToLocalChecked(), ContentGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("TileFlyoutNotification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: TileFlyoutNotification(::Windows::UI::Notifications::TileFlyoutNotification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::TileFlyoutNotification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutNotification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::TileFlyoutNotification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Xml::Dom::XmlDocument^>(info[0])) { try { ::Windows::Data::Xml::Dom::XmlDocument^ arg0 = dynamic_cast<::Windows::Data::Xml::Dom::XmlDocument^>(NodeRT::Utils::GetObjectInstance(info[0])); winRtInstance = ref new ::Windows::UI::Notifications::TileFlyoutNotification(arg0); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); TileFlyoutNotification *wrapperInstance = new TileFlyoutNotification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ExpirationTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutNotification^>(info.This())) { return; } TileFlyoutNotification *wrapper = TileFlyoutNotification::Unwrap<TileFlyoutNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ result = wrapper->_instance->ExpirationTime; info.GetReturnValue().Set(result ? static_cast<Local<Value>>(NodeRT::Utils::DateTimeToJS(result->Value)) : Undefined()); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void ExpirationTimeSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsDate()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutNotification^>(info.This())) { return; } TileFlyoutNotification *wrapper = TileFlyoutNotification::Unwrap<TileFlyoutNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ winRtValue = ref new ::Platform::Box<::Windows::Foundation::DateTime>(NodeRT::Utils::DateTimeFromJSDate(value)); wrapper->_instance->ExpirationTime = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ContentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutNotification^>(info.This())) { return; } TileFlyoutNotification *wrapper = TileFlyoutNotification::Unwrap<TileFlyoutNotification>(info.This()); try { ::Windows::Data::Xml::Dom::XmlDocument^ result = wrapper->_instance->Content; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::TileFlyoutNotification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapTileFlyoutNotification(::Windows::UI::Notifications::TileFlyoutNotification^ wintRtInstance); friend ::Windows::UI::Notifications::TileFlyoutNotification^ UnwrapTileFlyoutNotification(Local<Value> value); }; Persistent<FunctionTemplate> TileFlyoutNotification::s_constructorTemplate; v8::Local<v8::Value> WrapTileFlyoutNotification(::Windows::UI::Notifications::TileFlyoutNotification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(TileFlyoutNotification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::TileFlyoutNotification^ UnwrapTileFlyoutNotification(Local<Value> value) { return TileFlyoutNotification::Unwrap<TileFlyoutNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitTileFlyoutNotification(Local<Object> exports) { TileFlyoutNotification::Init(exports); } class BadgeUpdater : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("BadgeUpdater").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "update", Update); Nan::SetPrototypeMethod(localRef, "clear", Clear); Nan::SetPrototypeMethod(localRef, "startPeriodicUpdate", StartPeriodicUpdate); Nan::SetPrototypeMethod(localRef, "stopPeriodicUpdate", StopPeriodicUpdate); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("BadgeUpdater").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: BadgeUpdater(::Windows::UI::Notifications::BadgeUpdater^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::BadgeUpdater^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdater^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::BadgeUpdater^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); BadgeUpdater *wrapperInstance = new BadgeUpdater(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void Update(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdater^>(info.This())) { return; } BadgeUpdater *wrapper = BadgeUpdater::Unwrap<BadgeUpdater>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeNotification^>(info[0])) { try { ::Windows::UI::Notifications::BadgeNotification^ arg0 = UnwrapBadgeNotification(info[0]); wrapper->_instance->Update(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void Clear(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdater^>(info.This())) { return; } BadgeUpdater *wrapper = BadgeUpdater::Unwrap<BadgeUpdater>(info.This()); if (info.Length() == 0) { try { wrapper->_instance->Clear(); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void StartPeriodicUpdate(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdater^>(info.This())) { return; } BadgeUpdater *wrapper = BadgeUpdater::Unwrap<BadgeUpdater>(info.This()); if (info.Length() == 2 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[0]) && info[1]->IsInt32()) { try { ::Windows::Foundation::Uri^ arg0 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::UI::Notifications::PeriodicUpdateRecurrence arg1 = static_cast<::Windows::UI::Notifications::PeriodicUpdateRecurrence>(Nan::To<int32_t>(info[1]).FromMaybe(0)); wrapper->_instance->StartPeriodicUpdate(arg0, arg1); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 3 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Foundation::Uri^>(info[0]) && info[1]->IsDate() && info[2]->IsInt32()) { try { ::Windows::Foundation::Uri^ arg0 = dynamic_cast<::Windows::Foundation::Uri^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::Foundation::DateTime arg1 = NodeRT::Utils::DateTimeFromJSDate(info[1]); ::Windows::UI::Notifications::PeriodicUpdateRecurrence arg2 = static_cast<::Windows::UI::Notifications::PeriodicUpdateRecurrence>(Nan::To<int32_t>(info[2]).FromMaybe(0)); wrapper->_instance->StartPeriodicUpdate(arg0, arg1, arg2); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void StopPeriodicUpdate(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdater^>(info.This())) { return; } BadgeUpdater *wrapper = BadgeUpdater::Unwrap<BadgeUpdater>(info.This()); if (info.Length() == 0) { try { wrapper->_instance->StopPeriodicUpdate(); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } private: ::Windows::UI::Notifications::BadgeUpdater^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapBadgeUpdater(::Windows::UI::Notifications::BadgeUpdater^ wintRtInstance); friend ::Windows::UI::Notifications::BadgeUpdater^ UnwrapBadgeUpdater(Local<Value> value); }; Persistent<FunctionTemplate> BadgeUpdater::s_constructorTemplate; v8::Local<v8::Value> WrapBadgeUpdater(::Windows::UI::Notifications::BadgeUpdater^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(BadgeUpdater::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::BadgeUpdater^ UnwrapBadgeUpdater(Local<Value> value) { return BadgeUpdater::Unwrap<BadgeUpdater>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitBadgeUpdater(Local<Object> exports) { BadgeUpdater::Init(exports); } class BadgeUpdateManagerForUser : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("BadgeUpdateManagerForUser").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "createBadgeUpdaterForApplication", CreateBadgeUpdaterForApplication); Nan::SetPrototypeMethod(localRef, "createBadgeUpdaterForSecondaryTile", CreateBadgeUpdaterForSecondaryTile); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("user").ToLocalChecked(), UserGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("BadgeUpdateManagerForUser").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: BadgeUpdateManagerForUser(::Windows::UI::Notifications::BadgeUpdateManagerForUser^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::BadgeUpdateManagerForUser^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdateManagerForUser^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::BadgeUpdateManagerForUser^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); BadgeUpdateManagerForUser *wrapperInstance = new BadgeUpdateManagerForUser(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void CreateBadgeUpdaterForApplication(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdateManagerForUser^>(info.This())) { return; } BadgeUpdateManagerForUser *wrapper = BadgeUpdateManagerForUser::Unwrap<BadgeUpdateManagerForUser>(info.This()); if (info.Length() == 0) { try { ::Windows::UI::Notifications::BadgeUpdater^ result; result = wrapper->_instance->CreateBadgeUpdaterForApplication(); info.GetReturnValue().Set(WrapBadgeUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::BadgeUpdater^ result; result = wrapper->_instance->CreateBadgeUpdaterForApplication(arg0); info.GetReturnValue().Set(WrapBadgeUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateBadgeUpdaterForSecondaryTile(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdateManagerForUser^>(info.This())) { return; } BadgeUpdateManagerForUser *wrapper = BadgeUpdateManagerForUser::Unwrap<BadgeUpdateManagerForUser>(info.This()); if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::BadgeUpdater^ result; result = wrapper->_instance->CreateBadgeUpdaterForSecondaryTile(arg0); info.GetReturnValue().Set(WrapBadgeUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void UserGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdateManagerForUser^>(info.This())) { return; } BadgeUpdateManagerForUser *wrapper = BadgeUpdateManagerForUser::Unwrap<BadgeUpdateManagerForUser>(info.This()); try { ::Windows::System::User^ result = wrapper->_instance->User; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.System", "User", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::BadgeUpdateManagerForUser^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapBadgeUpdateManagerForUser(::Windows::UI::Notifications::BadgeUpdateManagerForUser^ wintRtInstance); friend ::Windows::UI::Notifications::BadgeUpdateManagerForUser^ UnwrapBadgeUpdateManagerForUser(Local<Value> value); }; Persistent<FunctionTemplate> BadgeUpdateManagerForUser::s_constructorTemplate; v8::Local<v8::Value> WrapBadgeUpdateManagerForUser(::Windows::UI::Notifications::BadgeUpdateManagerForUser^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(BadgeUpdateManagerForUser::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::BadgeUpdateManagerForUser^ UnwrapBadgeUpdateManagerForUser(Local<Value> value) { return BadgeUpdateManagerForUser::Unwrap<BadgeUpdateManagerForUser>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitBadgeUpdateManagerForUser(Local<Object> exports) { BadgeUpdateManagerForUser::Init(exports); } class BadgeNotification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("BadgeNotification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("expirationTime").ToLocalChecked(), ExpirationTimeGetter, ExpirationTimeSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("content").ToLocalChecked(), ContentGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("BadgeNotification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: BadgeNotification(::Windows::UI::Notifications::BadgeNotification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::BadgeNotification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeNotification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::BadgeNotification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Xml::Dom::XmlDocument^>(info[0])) { try { ::Windows::Data::Xml::Dom::XmlDocument^ arg0 = dynamic_cast<::Windows::Data::Xml::Dom::XmlDocument^>(NodeRT::Utils::GetObjectInstance(info[0])); winRtInstance = ref new ::Windows::UI::Notifications::BadgeNotification(arg0); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); BadgeNotification *wrapperInstance = new BadgeNotification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ExpirationTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeNotification^>(info.This())) { return; } BadgeNotification *wrapper = BadgeNotification::Unwrap<BadgeNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ result = wrapper->_instance->ExpirationTime; info.GetReturnValue().Set(result ? static_cast<Local<Value>>(NodeRT::Utils::DateTimeToJS(result->Value)) : Undefined()); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void ExpirationTimeSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsDate()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeNotification^>(info.This())) { return; } BadgeNotification *wrapper = BadgeNotification::Unwrap<BadgeNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ winRtValue = ref new ::Platform::Box<::Windows::Foundation::DateTime>(NodeRT::Utils::DateTimeFromJSDate(value)); wrapper->_instance->ExpirationTime = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ContentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeNotification^>(info.This())) { return; } BadgeNotification *wrapper = BadgeNotification::Unwrap<BadgeNotification>(info.This()); try { ::Windows::Data::Xml::Dom::XmlDocument^ result = wrapper->_instance->Content; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::BadgeNotification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapBadgeNotification(::Windows::UI::Notifications::BadgeNotification^ wintRtInstance); friend ::Windows::UI::Notifications::BadgeNotification^ UnwrapBadgeNotification(Local<Value> value); }; Persistent<FunctionTemplate> BadgeNotification::s_constructorTemplate; v8::Local<v8::Value> WrapBadgeNotification(::Windows::UI::Notifications::BadgeNotification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(BadgeNotification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::BadgeNotification^ UnwrapBadgeNotification(Local<Value> value) { return BadgeNotification::Unwrap<BadgeNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitBadgeNotification(Local<Object> exports) { BadgeNotification::Init(exports); } class ToastNotifier : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastNotifier").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "show", Show); Nan::SetPrototypeMethod(localRef, "hide", Hide); Nan::SetPrototypeMethod(localRef, "addToSchedule", AddToSchedule); Nan::SetPrototypeMethod(localRef, "removeFromSchedule", RemoveFromSchedule); Nan::SetPrototypeMethod(localRef, "getScheduledToastNotifications", GetScheduledToastNotifications); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("setting").ToLocalChecked(), SettingGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastNotifier").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastNotifier(::Windows::UI::Notifications::ToastNotifier^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastNotifier^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotifier^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastNotifier^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastNotifier *wrapperInstance = new ToastNotifier(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void Show(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotifier^>(info.This())) { return; } ToastNotifier *wrapper = ToastNotifier::Unwrap<ToastNotifier>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info[0])) { try { ::Windows::UI::Notifications::ToastNotification^ arg0 = UnwrapToastNotification(info[0]); wrapper->_instance->Show(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void Hide(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotifier^>(info.This())) { return; } ToastNotifier *wrapper = ToastNotifier::Unwrap<ToastNotifier>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info[0])) { try { ::Windows::UI::Notifications::ToastNotification^ arg0 = UnwrapToastNotification(info[0]); wrapper->_instance->Hide(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void AddToSchedule(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotifier^>(info.This())) { return; } ToastNotifier *wrapper = ToastNotifier::Unwrap<ToastNotifier>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info[0])) { try { ::Windows::UI::Notifications::ScheduledToastNotification^ arg0 = UnwrapScheduledToastNotification(info[0]); wrapper->_instance->AddToSchedule(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void RemoveFromSchedule(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotifier^>(info.This())) { return; } ToastNotifier *wrapper = ToastNotifier::Unwrap<ToastNotifier>(info.This()); if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info[0])) { try { ::Windows::UI::Notifications::ScheduledToastNotification^ arg0 = UnwrapScheduledToastNotification(info[0]); wrapper->_instance->RemoveFromSchedule(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void GetScheduledToastNotifications(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotifier^>(info.This())) { return; } ToastNotifier *wrapper = ToastNotifier::Unwrap<ToastNotifier>(info.This()); if (info.Length() == 0) { try { ::Windows::Foundation::Collections::IVectorView<::Windows::UI::Notifications::ScheduledToastNotification^>^ result; result = wrapper->_instance->GetScheduledToastNotifications(); info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::UI::Notifications::ScheduledToastNotification^>::CreateVectorViewWrapper(result, [](::Windows::UI::Notifications::ScheduledToastNotification^ val) -> Local<Value> { return WrapScheduledToastNotification(val); }, [](Local<Value> value) -> bool { return NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(value); }, [](Local<Value> value) -> ::Windows::UI::Notifications::ScheduledToastNotification^ { return UnwrapScheduledToastNotification(value); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void SettingGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotifier^>(info.This())) { return; } ToastNotifier *wrapper = ToastNotifier::Unwrap<ToastNotifier>(info.This()); try { ::Windows::UI::Notifications::NotificationSetting result = wrapper->_instance->Setting; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ToastNotifier^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastNotifier(::Windows::UI::Notifications::ToastNotifier^ wintRtInstance); friend ::Windows::UI::Notifications::ToastNotifier^ UnwrapToastNotifier(Local<Value> value); }; Persistent<FunctionTemplate> ToastNotifier::s_constructorTemplate; v8::Local<v8::Value> WrapToastNotifier(::Windows::UI::Notifications::ToastNotifier^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastNotifier::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastNotifier^ UnwrapToastNotifier(Local<Value> value) { return ToastNotifier::Unwrap<ToastNotifier>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastNotifier(Local<Object> exports) { ToastNotifier::Init(exports); } class ToastNotification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastNotification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef,"addListener", AddListener); Nan::SetPrototypeMethod(localRef,"on", AddListener); Nan::SetPrototypeMethod(localRef,"removeListener", RemoveListener); Nan::SetPrototypeMethod(localRef, "off", RemoveListener); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("expirationTime").ToLocalChecked(), ExpirationTimeGetter, ExpirationTimeSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("content").ToLocalChecked(), ContentGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("tag").ToLocalChecked(), TagGetter, TagSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("suppressPopup").ToLocalChecked(), SuppressPopupGetter, SuppressPopupSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("group").ToLocalChecked(), GroupGetter, GroupSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("remoteId").ToLocalChecked(), RemoteIdGetter, RemoteIdSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("notificationMirroring").ToLocalChecked(), NotificationMirroringGetter, NotificationMirroringSetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastNotification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastNotification(::Windows::UI::Notifications::ToastNotification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastNotification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastNotification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Xml::Dom::XmlDocument^>(info[0])) { try { ::Windows::Data::Xml::Dom::XmlDocument^ arg0 = dynamic_cast<::Windows::Data::Xml::Dom::XmlDocument^>(NodeRT::Utils::GetObjectInstance(info[0])); winRtInstance = ref new ::Windows::UI::Notifications::ToastNotification(arg0); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastNotification *wrapperInstance = new ToastNotification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ExpirationTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ result = wrapper->_instance->ExpirationTime; info.GetReturnValue().Set(result ? static_cast<Local<Value>>(NodeRT::Utils::DateTimeToJS(result->Value)) : Undefined()); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void ExpirationTimeSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsDate()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::DateTime>^ winRtValue = ref new ::Platform::Box<::Windows::Foundation::DateTime>(NodeRT::Utils::DateTimeFromJSDate(value)); wrapper->_instance->ExpirationTime = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ContentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { ::Windows::Data::Xml::Dom::XmlDocument^ result = wrapper->_instance->Content; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TagGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Tag; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TagSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Tag = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void SuppressPopupGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { bool result = wrapper->_instance->SuppressPopup; info.GetReturnValue().Set(Nan::New<Boolean>(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SuppressPopupSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsBoolean()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { bool winRtValue = Nan::To<bool>(value).FromMaybe(false); wrapper->_instance->SuppressPopup = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void GroupGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Group; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void GroupSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Group = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void RemoteIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->RemoteId; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void RemoteIdSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->RemoteId = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void NotificationMirroringGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { ::Windows::UI::Notifications::NotificationMirroring result = wrapper->_instance->NotificationMirroring; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void NotificationMirroringSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsInt32()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { ::Windows::UI::Notifications::NotificationMirroring winRtValue = static_cast<::Windows::UI::Notifications::NotificationMirroring>(Nan::To<int32_t>(value).FromMaybe(0)); wrapper->_instance->NotificationMirroring = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void AddListener(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected arguments are eventName(string),callback(function)"))); return; } String::Value eventName(info[0]); auto str = *eventName; Local<Function> callback = info[1].As<Function>(); ::Windows::Foundation::EventRegistrationToken registrationToken; if (NodeRT::Utils::CaseInsenstiveEquals(L"activated", str)) { if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed"))); return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Persistent<Object>* perstPtr = new Persistent<Object>(); perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback)); std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr, [] (Persistent<Object> *ptr ) { NodeUtils::Async::RunOnMain([ptr]() { ptr->Reset(); delete ptr; }); }); registrationToken = wrapper->_instance->Activated::add( ref new ::Windows::Foundation::TypedEventHandler<::Windows::UI::Notifications::ToastNotification^, ::Platform::Object^>( [callbackObjPtr](::Windows::UI::Notifications::ToastNotification^ arg0, ::Platform::Object^ arg1) { NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() { HandleScope scope; TryCatch tryCatch; Local<Value> error; Local<Value> wrappedArg0 = WrapToastNotification(arg0); Local<Value> wrappedArg1 = CreateOpaqueWrapper(arg1); if (tryCatch.HasCaught()) { error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked(); } else { error = Undefined(); } if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined(); if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined(); Local<Value> args[] = { wrappedArg0, wrappedArg1 }; Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr); NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args); }); }) ); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (NodeRT::Utils::CaseInsenstiveEquals(L"dismissed", str)) { if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed"))); return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Persistent<Object>* perstPtr = new Persistent<Object>(); perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback)); std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr, [] (Persistent<Object> *ptr ) { NodeUtils::Async::RunOnMain([ptr]() { ptr->Reset(); delete ptr; }); }); registrationToken = wrapper->_instance->Dismissed::add( ref new ::Windows::Foundation::TypedEventHandler<::Windows::UI::Notifications::ToastNotification^, ::Windows::UI::Notifications::ToastDismissedEventArgs^>( [callbackObjPtr](::Windows::UI::Notifications::ToastNotification^ arg0, ::Windows::UI::Notifications::ToastDismissedEventArgs^ arg1) { NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() { HandleScope scope; TryCatch tryCatch; Local<Value> error; Local<Value> wrappedArg0 = WrapToastNotification(arg0); Local<Value> wrappedArg1 = WrapToastDismissedEventArgs(arg1); if (tryCatch.HasCaught()) { error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked(); } else { error = Undefined(); } if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined(); if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined(); Local<Value> args[] = { wrappedArg0, wrappedArg1 }; Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr); NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args); }); }) ); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (NodeRT::Utils::CaseInsenstiveEquals(L"failed", str)) { if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed"))); return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); try { Persistent<Object>* perstPtr = new Persistent<Object>(); perstPtr->Reset(NodeRT::Utils::CreateCallbackObjectInDomain(callback)); std::shared_ptr<Persistent<Object>> callbackObjPtr(perstPtr, [] (Persistent<Object> *ptr ) { NodeUtils::Async::RunOnMain([ptr]() { ptr->Reset(); delete ptr; }); }); registrationToken = wrapper->_instance->Failed::add( ref new ::Windows::Foundation::TypedEventHandler<::Windows::UI::Notifications::ToastNotification^, ::Windows::UI::Notifications::ToastFailedEventArgs^>( [callbackObjPtr](::Windows::UI::Notifications::ToastNotification^ arg0, ::Windows::UI::Notifications::ToastFailedEventArgs^ arg1) { NodeUtils::Async::RunOnMain([callbackObjPtr , arg0, arg1]() { HandleScope scope; TryCatch tryCatch; Local<Value> error; Local<Value> wrappedArg0 = WrapToastNotification(arg0); Local<Value> wrappedArg1 = WrapToastFailedEventArgs(arg1); if (tryCatch.HasCaught()) { error = Nan::To<Object>(tryCatch.Exception()).ToLocalChecked(); } else { error = Undefined(); } if (wrappedArg0.IsEmpty()) wrappedArg0 = Undefined(); if (wrappedArg1.IsEmpty()) wrappedArg1 = Undefined(); Local<Value> args[] = { wrappedArg0, wrappedArg1 }; Local<Object> callbackObjLocalRef = Nan::New<Object>(*callbackObjPtr); NodeRT::Utils::CallCallbackInDomain(callbackObjLocalRef, _countof(args), args); }); }) ); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(String::Concat(NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>()))); return; } Local<Value> tokenMapVal = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked()); Local<Object> tokenMap; if (tokenMapVal.IsEmpty() || Nan::Equals(tokenMapVal, Undefined()).FromMaybe(false)) { tokenMap = Nan::New<Object>(); NodeRT::Utils::SetHiddenValueWithObject(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked(), tokenMap); } else { tokenMap = Nan::To<Object>(tokenMapVal).ToLocalChecked(); } Nan::Set(tokenMap, info[0], CreateOpaqueWrapper(::Windows::Foundation::PropertyValue::CreateInt64(registrationToken.Value))); } static void RemoveListener(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() < 2 || !info[0]->IsString() || !info[1]->IsFunction()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"wrong arguments, expected a string and a callback"))); return; } String::Value eventName(info[0]); auto str = *eventName; if ((NodeRT::Utils::CaseInsenstiveEquals(L"activated", str)) &&(NodeRT::Utils::CaseInsenstiveEquals(L"dismissed", str)) &&(NodeRT::Utils::CaseInsenstiveEquals(L"failed", str))) { Nan::ThrowError(Nan::Error(String::Concat(NodeRT::Utils::NewString(L"given event name isn't supported: "), info[0].As<String>()))); return; } Local<Function> callback = info[1].As<Function>(); Local<Value> tokenMap = NodeRT::Utils::GetHiddenValue(callback, Nan::New<String>(REGISTRATION_TOKEN_MAP_PROPERTY_NAME).ToLocalChecked()); if (tokenMap.IsEmpty() || Nan::Equals(tokenMap, Undefined()).FromMaybe(false)) { return; } Local<Value> opaqueWrapperObj = Nan::Get(Nan::To<Object>(tokenMap).ToLocalChecked(), info[0]).ToLocalChecked(); if (opaqueWrapperObj.IsEmpty() || Nan::Equals(opaqueWrapperObj,Undefined()).FromMaybe(false)) { return; } OpaqueWrapper *opaqueWrapper = OpaqueWrapper::Unwrap<OpaqueWrapper>(opaqueWrapperObj.As<Object>()); long long tokenValue = (long long) opaqueWrapper->GetObjectInstance(); ::Windows::Foundation::EventRegistrationToken registrationToken; registrationToken.Value = tokenValue; try { if (NodeRT::Utils::CaseInsenstiveEquals(L"activated", str)) { if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed"))); return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); wrapper->_instance->Activated::remove(registrationToken); } else if (NodeRT::Utils::CaseInsenstiveEquals(L"dismissed", str)) { if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed"))); return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); wrapper->_instance->Dismissed::remove(registrationToken); } else if (NodeRT::Utils::CaseInsenstiveEquals(L"failed", str)) { if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(info.This())) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"The caller of this method isn't of the expected type or internal WinRt object was disposed"))); return; } ToastNotification *wrapper = ToastNotification::Unwrap<ToastNotification>(info.This()); wrapper->_instance->Failed::remove(registrationToken); } } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } Nan::Delete(Nan::To<Object>(tokenMap).ToLocalChecked(), Nan::To<String>(info[0]).ToLocalChecked()); } private: ::Windows::UI::Notifications::ToastNotification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastNotification(::Windows::UI::Notifications::ToastNotification^ wintRtInstance); friend ::Windows::UI::Notifications::ToastNotification^ UnwrapToastNotification(Local<Value> value); }; Persistent<FunctionTemplate> ToastNotification::s_constructorTemplate; v8::Local<v8::Value> WrapToastNotification(::Windows::UI::Notifications::ToastNotification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastNotification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastNotification^ UnwrapToastNotification(Local<Value> value) { return ToastNotification::Unwrap<ToastNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastNotification(Local<Object> exports) { ToastNotification::Init(exports); } class ScheduledToastNotification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ScheduledToastNotification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("id").ToLocalChecked(), IdGetter, IdSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("content").ToLocalChecked(), ContentGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("deliveryTime").ToLocalChecked(), DeliveryTimeGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("maximumSnoozeCount").ToLocalChecked(), MaximumSnoozeCountGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("snoozeInterval").ToLocalChecked(), SnoozeIntervalGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("tag").ToLocalChecked(), TagGetter, TagSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("suppressPopup").ToLocalChecked(), SuppressPopupGetter, SuppressPopupSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("group").ToLocalChecked(), GroupGetter, GroupSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("remoteId").ToLocalChecked(), RemoteIdGetter, RemoteIdSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("notificationMirroring").ToLocalChecked(), NotificationMirroringGetter, NotificationMirroringSetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ScheduledToastNotification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ScheduledToastNotification(::Windows::UI::Notifications::ScheduledToastNotification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ScheduledToastNotification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ScheduledToastNotification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 2 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Xml::Dom::XmlDocument^>(info[0]) && info[1]->IsDate()) { try { ::Windows::Data::Xml::Dom::XmlDocument^ arg0 = dynamic_cast<::Windows::Data::Xml::Dom::XmlDocument^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::Foundation::DateTime arg1 = NodeRT::Utils::DateTimeFromJSDate(info[1]); winRtInstance = ref new ::Windows::UI::Notifications::ScheduledToastNotification(arg0,arg1); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 4 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::Data::Xml::Dom::XmlDocument^>(info[0]) && info[1]->IsDate() && info[2]->IsNumber() && info[3]->IsUint32()) { try { ::Windows::Data::Xml::Dom::XmlDocument^ arg0 = dynamic_cast<::Windows::Data::Xml::Dom::XmlDocument^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::Foundation::DateTime arg1 = NodeRT::Utils::DateTimeFromJSDate(info[1]); ::Windows::Foundation::TimeSpan arg2 = NodeRT::Utils::TimeSpanFromMilli(Nan::To<int64_t>(info[2]).FromMaybe(0)); unsigned int arg3 = static_cast<unsigned int>(Nan::To<uint32_t>(info[3]).FromMaybe(0)); winRtInstance = ref new ::Windows::UI::Notifications::ScheduledToastNotification(arg0,arg1,arg2,arg3); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ScheduledToastNotification *wrapperInstance = new ScheduledToastNotification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void IdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Id; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void IdSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Id = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void ContentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { ::Windows::Data::Xml::Dom::XmlDocument^ result = wrapper->_instance->Content; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void DeliveryTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { ::Windows::Foundation::DateTime result = wrapper->_instance->DeliveryTime; info.GetReturnValue().Set(NodeRT::Utils::DateTimeToJS(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void MaximumSnoozeCountGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { unsigned int result = wrapper->_instance->MaximumSnoozeCount; info.GetReturnValue().Set(Nan::New<Integer>(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SnoozeIntervalGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { ::Platform::IBox<::Windows::Foundation::TimeSpan>^ result = wrapper->_instance->SnoozeInterval; info.GetReturnValue().Set(result ? static_cast<Local<Value>>(Nan::New<Number>(result->Value.Duration/10000.0)) : Undefined()); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TagGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Tag; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TagSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Tag = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void SuppressPopupGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { bool result = wrapper->_instance->SuppressPopup; info.GetReturnValue().Set(Nan::New<Boolean>(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SuppressPopupSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsBoolean()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { bool winRtValue = Nan::To<bool>(value).FromMaybe(false); wrapper->_instance->SuppressPopup = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void GroupGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->Group; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void GroupSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Group = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void RemoteIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { Platform::String^ result = wrapper->_instance->RemoteId; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void RemoteIdSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->RemoteId = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void NotificationMirroringGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { ::Windows::UI::Notifications::NotificationMirroring result = wrapper->_instance->NotificationMirroring; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void NotificationMirroringSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsInt32()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ScheduledToastNotification^>(info.This())) { return; } ScheduledToastNotification *wrapper = ScheduledToastNotification::Unwrap<ScheduledToastNotification>(info.This()); try { ::Windows::UI::Notifications::NotificationMirroring winRtValue = static_cast<::Windows::UI::Notifications::NotificationMirroring>(Nan::To<int32_t>(value).FromMaybe(0)); wrapper->_instance->NotificationMirroring = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } private: ::Windows::UI::Notifications::ScheduledToastNotification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapScheduledToastNotification(::Windows::UI::Notifications::ScheduledToastNotification^ wintRtInstance); friend ::Windows::UI::Notifications::ScheduledToastNotification^ UnwrapScheduledToastNotification(Local<Value> value); }; Persistent<FunctionTemplate> ScheduledToastNotification::s_constructorTemplate; v8::Local<v8::Value> WrapScheduledToastNotification(::Windows::UI::Notifications::ScheduledToastNotification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ScheduledToastNotification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ScheduledToastNotification^ UnwrapScheduledToastNotification(Local<Value> value) { return ScheduledToastNotification::Unwrap<ScheduledToastNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitScheduledToastNotification(Local<Object> exports) { ScheduledToastNotification::Init(exports); } class ToastDismissedEventArgs : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastDismissedEventArgs").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("reason").ToLocalChecked(), ReasonGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastDismissedEventArgs").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastDismissedEventArgs(::Windows::UI::Notifications::ToastDismissedEventArgs^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastDismissedEventArgs^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastDismissedEventArgs^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastDismissedEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastDismissedEventArgs *wrapperInstance = new ToastDismissedEventArgs(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ReasonGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastDismissedEventArgs^>(info.This())) { return; } ToastDismissedEventArgs *wrapper = ToastDismissedEventArgs::Unwrap<ToastDismissedEventArgs>(info.This()); try { ::Windows::UI::Notifications::ToastDismissalReason result = wrapper->_instance->Reason; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ToastDismissedEventArgs^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastDismissedEventArgs(::Windows::UI::Notifications::ToastDismissedEventArgs^ wintRtInstance); friend ::Windows::UI::Notifications::ToastDismissedEventArgs^ UnwrapToastDismissedEventArgs(Local<Value> value); }; Persistent<FunctionTemplate> ToastDismissedEventArgs::s_constructorTemplate; v8::Local<v8::Value> WrapToastDismissedEventArgs(::Windows::UI::Notifications::ToastDismissedEventArgs^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastDismissedEventArgs::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastDismissedEventArgs^ UnwrapToastDismissedEventArgs(Local<Value> value) { return ToastDismissedEventArgs::Unwrap<ToastDismissedEventArgs>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastDismissedEventArgs(Local<Object> exports) { ToastDismissedEventArgs::Init(exports); } class ToastFailedEventArgs : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastFailedEventArgs").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("errorCode").ToLocalChecked(), ErrorCodeGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastFailedEventArgs").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastFailedEventArgs(::Windows::UI::Notifications::ToastFailedEventArgs^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastFailedEventArgs^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastFailedEventArgs^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastFailedEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastFailedEventArgs *wrapperInstance = new ToastFailedEventArgs(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ErrorCodeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastFailedEventArgs^>(info.This())) { return; } ToastFailedEventArgs *wrapper = ToastFailedEventArgs::Unwrap<ToastFailedEventArgs>(info.This()); try { ::Windows::Foundation::HResult result = wrapper->_instance->ErrorCode; info.GetReturnValue().Set(Nan::New<Integer>(result.Value)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ToastFailedEventArgs^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastFailedEventArgs(::Windows::UI::Notifications::ToastFailedEventArgs^ wintRtInstance); friend ::Windows::UI::Notifications::ToastFailedEventArgs^ UnwrapToastFailedEventArgs(Local<Value> value); }; Persistent<FunctionTemplate> ToastFailedEventArgs::s_constructorTemplate; v8::Local<v8::Value> WrapToastFailedEventArgs(::Windows::UI::Notifications::ToastFailedEventArgs^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastFailedEventArgs::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastFailedEventArgs^ UnwrapToastFailedEventArgs(Local<Value> value) { return ToastFailedEventArgs::Unwrap<ToastFailedEventArgs>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastFailedEventArgs(Local<Object> exports) { ToastFailedEventArgs::Init(exports); } class NotificationVisual : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("NotificationVisual").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "getBinding", GetBinding); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("language").ToLocalChecked(), LanguageGetter, LanguageSetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("bindings").ToLocalChecked(), BindingsGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("NotificationVisual").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: NotificationVisual(::Windows::UI::Notifications::NotificationVisual^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::NotificationVisual^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationVisual^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::NotificationVisual^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); NotificationVisual *wrapperInstance = new NotificationVisual(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void GetBinding(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationVisual^>(info.This())) { return; } NotificationVisual *wrapper = NotificationVisual::Unwrap<NotificationVisual>(info.This()); if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::NotificationBinding^ result; result = wrapper->_instance->GetBinding(arg0); info.GetReturnValue().Set(WrapNotificationBinding(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void LanguageGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationVisual^>(info.This())) { return; } NotificationVisual *wrapper = NotificationVisual::Unwrap<NotificationVisual>(info.This()); try { Platform::String^ result = wrapper->_instance->Language; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void LanguageSetter(Local<String> property, Local<Value> value, const Nan::PropertyCallbackInfo<void> &info) { HandleScope scope; if (!value->IsString()) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Value to set is of unexpected type"))); return; } if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationVisual^>(info.This())) { return; } NotificationVisual *wrapper = NotificationVisual::Unwrap<NotificationVisual>(info.This()); try { Platform::String^ winRtValue = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(value))); wrapper->_instance->Language = winRtValue; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); } } static void BindingsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationVisual^>(info.This())) { return; } NotificationVisual *wrapper = NotificationVisual::Unwrap<NotificationVisual>(info.This()); try { ::Windows::Foundation::Collections::IVector<::Windows::UI::Notifications::NotificationBinding^>^ result = wrapper->_instance->Bindings; info.GetReturnValue().Set(NodeRT::Collections::VectorWrapper<::Windows::UI::Notifications::NotificationBinding^>::CreateVectorWrapper(result, [](::Windows::UI::Notifications::NotificationBinding^ val) -> Local<Value> { return WrapNotificationBinding(val); }, [](Local<Value> value) -> bool { return NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::NotificationBinding^>(value); }, [](Local<Value> value) -> ::Windows::UI::Notifications::NotificationBinding^ { return UnwrapNotificationBinding(value); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::NotificationVisual^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapNotificationVisual(::Windows::UI::Notifications::NotificationVisual^ wintRtInstance); friend ::Windows::UI::Notifications::NotificationVisual^ UnwrapNotificationVisual(Local<Value> value); }; Persistent<FunctionTemplate> NotificationVisual::s_constructorTemplate; v8::Local<v8::Value> WrapNotificationVisual(::Windows::UI::Notifications::NotificationVisual^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(NotificationVisual::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::NotificationVisual^ UnwrapNotificationVisual(Local<Value> value) { return NotificationVisual::Unwrap<NotificationVisual>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitNotificationVisual(Local<Object> exports) { NotificationVisual::Init(exports); } class ToastNotificationHistory : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastNotificationHistory").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "removeGroup", RemoveGroup); Nan::SetPrototypeMethod(localRef, "remove", Remove); Nan::SetPrototypeMethod(localRef, "clear", Clear); Nan::SetPrototypeMethod(localRef, "getHistory", GetHistory); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastNotificationHistory").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastNotificationHistory(::Windows::UI::Notifications::ToastNotificationHistory^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastNotificationHistory^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationHistory^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastNotificationHistory^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastNotificationHistory *wrapperInstance = new ToastNotificationHistory(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void RemoveGroup(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationHistory^>(info.This())) { return; } ToastNotificationHistory *wrapper = ToastNotificationHistory::Unwrap<ToastNotificationHistory>(info.This()); if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); wrapper->_instance->RemoveGroup(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 2 && info[0]->IsString() && info[1]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[1]))); wrapper->_instance->RemoveGroup(arg0, arg1); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void Remove(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationHistory^>(info.This())) { return; } ToastNotificationHistory *wrapper = ToastNotificationHistory::Unwrap<ToastNotificationHistory>(info.This()); if (info.Length() == 3 && info[0]->IsString() && info[1]->IsString() && info[2]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[1]))); Platform::String^ arg2 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[2]))); wrapper->_instance->Remove(arg0, arg1, arg2); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 2 && info[0]->IsString() && info[1]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); Platform::String^ arg1 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[1]))); wrapper->_instance->Remove(arg0, arg1); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); wrapper->_instance->Remove(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void Clear(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationHistory^>(info.This())) { return; } ToastNotificationHistory *wrapper = ToastNotificationHistory::Unwrap<ToastNotificationHistory>(info.This()); if (info.Length() == 0) { try { wrapper->_instance->Clear(); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); wrapper->_instance->Clear(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void GetHistory(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationHistory^>(info.This())) { return; } ToastNotificationHistory *wrapper = ToastNotificationHistory::Unwrap<ToastNotificationHistory>(info.This()); if (info.Length() == 0) { try { ::Windows::Foundation::Collections::IVectorView<::Windows::UI::Notifications::ToastNotification^>^ result; result = wrapper->_instance->GetHistory(); info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::UI::Notifications::ToastNotification^>::CreateVectorViewWrapper(result, [](::Windows::UI::Notifications::ToastNotification^ val) -> Local<Value> { return WrapToastNotification(val); }, [](Local<Value> value) -> bool { return NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(value); }, [](Local<Value> value) -> ::Windows::UI::Notifications::ToastNotification^ { return UnwrapToastNotification(value); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::Foundation::Collections::IVectorView<::Windows::UI::Notifications::ToastNotification^>^ result; result = wrapper->_instance->GetHistory(arg0); info.GetReturnValue().Set(NodeRT::Collections::VectorViewWrapper<::Windows::UI::Notifications::ToastNotification^>::CreateVectorViewWrapper(result, [](::Windows::UI::Notifications::ToastNotification^ val) -> Local<Value> { return WrapToastNotification(val); }, [](Local<Value> value) -> bool { return NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotification^>(value); }, [](Local<Value> value) -> ::Windows::UI::Notifications::ToastNotification^ { return UnwrapToastNotification(value); } )); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } private: ::Windows::UI::Notifications::ToastNotificationHistory^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastNotificationHistory(::Windows::UI::Notifications::ToastNotificationHistory^ wintRtInstance); friend ::Windows::UI::Notifications::ToastNotificationHistory^ UnwrapToastNotificationHistory(Local<Value> value); }; Persistent<FunctionTemplate> ToastNotificationHistory::s_constructorTemplate; v8::Local<v8::Value> WrapToastNotificationHistory(::Windows::UI::Notifications::ToastNotificationHistory^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastNotificationHistory::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastNotificationHistory^ UnwrapToastNotificationHistory(Local<Value> value) { return ToastNotificationHistory::Unwrap<ToastNotificationHistory>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastNotificationHistory(Local<Object> exports) { ToastNotificationHistory::Init(exports); } class ToastNotificationManagerForUser : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastNotificationManagerForUser").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(localRef, "createToastNotifier", CreateToastNotifier); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("history").ToLocalChecked(), HistoryGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("user").ToLocalChecked(), UserGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastNotificationManagerForUser").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastNotificationManagerForUser(::Windows::UI::Notifications::ToastNotificationManagerForUser^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastNotificationManagerForUser^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationManagerForUser^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastNotificationManagerForUser^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastNotificationManagerForUser *wrapperInstance = new ToastNotificationManagerForUser(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void CreateToastNotifier(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationManagerForUser^>(info.This())) { return; } ToastNotificationManagerForUser *wrapper = ToastNotificationManagerForUser::Unwrap<ToastNotificationManagerForUser>(info.This()); if (info.Length() == 0) { try { ::Windows::UI::Notifications::ToastNotifier^ result; result = wrapper->_instance->CreateToastNotifier(); info.GetReturnValue().Set(WrapToastNotifier(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::ToastNotifier^ result; result = wrapper->_instance->CreateToastNotifier(arg0); info.GetReturnValue().Set(WrapToastNotifier(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void HistoryGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationManagerForUser^>(info.This())) { return; } ToastNotificationManagerForUser *wrapper = ToastNotificationManagerForUser::Unwrap<ToastNotificationManagerForUser>(info.This()); try { ::Windows::UI::Notifications::ToastNotificationHistory^ result = wrapper->_instance->History; info.GetReturnValue().Set(WrapToastNotificationHistory(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void UserGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationManagerForUser^>(info.This())) { return; } ToastNotificationManagerForUser *wrapper = ToastNotificationManagerForUser::Unwrap<ToastNotificationManagerForUser>(info.This()); try { ::Windows::System::User^ result = wrapper->_instance->User; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.System", "User", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ToastNotificationManagerForUser^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastNotificationManagerForUser(::Windows::UI::Notifications::ToastNotificationManagerForUser^ wintRtInstance); friend ::Windows::UI::Notifications::ToastNotificationManagerForUser^ UnwrapToastNotificationManagerForUser(Local<Value> value); }; Persistent<FunctionTemplate> ToastNotificationManagerForUser::s_constructorTemplate; v8::Local<v8::Value> WrapToastNotificationManagerForUser(::Windows::UI::Notifications::ToastNotificationManagerForUser^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastNotificationManagerForUser::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastNotificationManagerForUser^ UnwrapToastNotificationManagerForUser(Local<Value> value) { return ToastNotificationManagerForUser::Unwrap<ToastNotificationManagerForUser>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastNotificationManagerForUser(Local<Object> exports) { ToastNotificationManagerForUser::Init(exports); } class UserNotificationChangedEventArgs : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("UserNotificationChangedEventArgs").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("changeKind").ToLocalChecked(), ChangeKindGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("userNotificationId").ToLocalChecked(), UserNotificationIdGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("UserNotificationChangedEventArgs").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: UserNotificationChangedEventArgs(::Windows::UI::Notifications::UserNotificationChangedEventArgs^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::UserNotificationChangedEventArgs^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::UserNotificationChangedEventArgs^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::UserNotificationChangedEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); UserNotificationChangedEventArgs *wrapperInstance = new UserNotificationChangedEventArgs(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ChangeKindGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::UserNotificationChangedEventArgs^>(info.This())) { return; } UserNotificationChangedEventArgs *wrapper = UserNotificationChangedEventArgs::Unwrap<UserNotificationChangedEventArgs>(info.This()); try { ::Windows::UI::Notifications::UserNotificationChangedKind result = wrapper->_instance->ChangeKind; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void UserNotificationIdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::UserNotificationChangedEventArgs^>(info.This())) { return; } UserNotificationChangedEventArgs *wrapper = UserNotificationChangedEventArgs::Unwrap<UserNotificationChangedEventArgs>(info.This()); try { unsigned int result = wrapper->_instance->UserNotificationId; info.GetReturnValue().Set(Nan::New<Integer>(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::UserNotificationChangedEventArgs^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapUserNotificationChangedEventArgs(::Windows::UI::Notifications::UserNotificationChangedEventArgs^ wintRtInstance); friend ::Windows::UI::Notifications::UserNotificationChangedEventArgs^ UnwrapUserNotificationChangedEventArgs(Local<Value> value); }; Persistent<FunctionTemplate> UserNotificationChangedEventArgs::s_constructorTemplate; v8::Local<v8::Value> WrapUserNotificationChangedEventArgs(::Windows::UI::Notifications::UserNotificationChangedEventArgs^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(UserNotificationChangedEventArgs::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::UserNotificationChangedEventArgs^ UnwrapUserNotificationChangedEventArgs(Local<Value> value) { return UserNotificationChangedEventArgs::Unwrap<UserNotificationChangedEventArgs>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitUserNotificationChangedEventArgs(Local<Object> exports) { UserNotificationChangedEventArgs::Init(exports); } class UserNotification : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("UserNotification").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("appInfo").ToLocalChecked(), AppInfoGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("creationTime").ToLocalChecked(), CreationTimeGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("id").ToLocalChecked(), IdGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("notification").ToLocalChecked(), NotificationGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("UserNotification").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: UserNotification(::Windows::UI::Notifications::UserNotification^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::UserNotification^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::UserNotification^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::UserNotification^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); UserNotification *wrapperInstance = new UserNotification(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void AppInfoGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::UserNotification^>(info.This())) { return; } UserNotification *wrapper = UserNotification::Unwrap<UserNotification>(info.This()); try { ::Windows::ApplicationModel::AppInfo^ result = wrapper->_instance->AppInfo; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.ApplicationModel", "AppInfo", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void CreationTimeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::UserNotification^>(info.This())) { return; } UserNotification *wrapper = UserNotification::Unwrap<UserNotification>(info.This()); try { ::Windows::Foundation::DateTime result = wrapper->_instance->CreationTime; info.GetReturnValue().Set(NodeRT::Utils::DateTimeToJS(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void IdGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::UserNotification^>(info.This())) { return; } UserNotification *wrapper = UserNotification::Unwrap<UserNotification>(info.This()); try { unsigned int result = wrapper->_instance->Id; info.GetReturnValue().Set(Nan::New<Integer>(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void NotificationGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::UserNotification^>(info.This())) { return; } UserNotification *wrapper = UserNotification::Unwrap<UserNotification>(info.This()); try { ::Windows::UI::Notifications::Notification^ result = wrapper->_instance->Notification; info.GetReturnValue().Set(WrapNotification(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::UserNotification^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapUserNotification(::Windows::UI::Notifications::UserNotification^ wintRtInstance); friend ::Windows::UI::Notifications::UserNotification^ UnwrapUserNotification(Local<Value> value); }; Persistent<FunctionTemplate> UserNotification::s_constructorTemplate; v8::Local<v8::Value> WrapUserNotification(::Windows::UI::Notifications::UserNotification^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(UserNotification::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::UserNotification^ UnwrapUserNotification(Local<Value> value) { return UserNotification::Unwrap<UserNotification>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitUserNotification(Local<Object> exports) { UserNotification::Init(exports); } class KnownAdaptiveNotificationHints : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("KnownAdaptiveNotificationHints").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::SetAccessor(constructor, Nan::New<String>("align").ToLocalChecked(), AlignGetter); Nan::SetAccessor(constructor, Nan::New<String>("maxLines").ToLocalChecked(), MaxLinesGetter); Nan::SetAccessor(constructor, Nan::New<String>("minLines").ToLocalChecked(), MinLinesGetter); Nan::SetAccessor(constructor, Nan::New<String>("style").ToLocalChecked(), StyleGetter); Nan::SetAccessor(constructor, Nan::New<String>("textStacking").ToLocalChecked(), TextStackingGetter); Nan::SetAccessor(constructor, Nan::New<String>("wrap").ToLocalChecked(), WrapGetter); Nan::Set(exports, Nan::New<String>("KnownAdaptiveNotificationHints").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: KnownAdaptiveNotificationHints(::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::KnownAdaptiveNotificationHints^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::KnownAdaptiveNotificationHints^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); KnownAdaptiveNotificationHints *wrapperInstance = new KnownAdaptiveNotificationHints(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void AlignGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationHints::Align; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void MaxLinesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationHints::MaxLines; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void MinLinesGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationHints::MinLines; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void StyleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationHints::Style; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TextStackingGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationHints::TextStacking; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void WrapGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationHints::Wrap; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapKnownAdaptiveNotificationHints(::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ wintRtInstance); friend ::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ UnwrapKnownAdaptiveNotificationHints(Local<Value> value); }; Persistent<FunctionTemplate> KnownAdaptiveNotificationHints::s_constructorTemplate; v8::Local<v8::Value> WrapKnownAdaptiveNotificationHints(::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(KnownAdaptiveNotificationHints::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::KnownAdaptiveNotificationHints^ UnwrapKnownAdaptiveNotificationHints(Local<Value> value) { return KnownAdaptiveNotificationHints::Unwrap<KnownAdaptiveNotificationHints>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitKnownAdaptiveNotificationHints(Local<Object> exports) { KnownAdaptiveNotificationHints::Init(exports); } class KnownNotificationBindings : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("KnownNotificationBindings").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::SetAccessor(constructor, Nan::New<String>("toastGeneric").ToLocalChecked(), ToastGenericGetter); Nan::Set(exports, Nan::New<String>("KnownNotificationBindings").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: KnownNotificationBindings(::Windows::UI::Notifications::KnownNotificationBindings^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::KnownNotificationBindings^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::KnownNotificationBindings^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::KnownNotificationBindings^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); KnownNotificationBindings *wrapperInstance = new KnownNotificationBindings(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ToastGenericGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownNotificationBindings::ToastGeneric; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::KnownNotificationBindings^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapKnownNotificationBindings(::Windows::UI::Notifications::KnownNotificationBindings^ wintRtInstance); friend ::Windows::UI::Notifications::KnownNotificationBindings^ UnwrapKnownNotificationBindings(Local<Value> value); }; Persistent<FunctionTemplate> KnownNotificationBindings::s_constructorTemplate; v8::Local<v8::Value> WrapKnownNotificationBindings(::Windows::UI::Notifications::KnownNotificationBindings^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(KnownNotificationBindings::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::KnownNotificationBindings^ UnwrapKnownNotificationBindings(Local<Value> value) { return KnownNotificationBindings::Unwrap<KnownNotificationBindings>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitKnownNotificationBindings(Local<Object> exports) { KnownNotificationBindings::Init(exports); } class KnownAdaptiveNotificationTextStyles : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("KnownAdaptiveNotificationTextStyles").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::SetAccessor(constructor, Nan::New<String>("base").ToLocalChecked(), BaseGetter); Nan::SetAccessor(constructor, Nan::New<String>("baseSubtle").ToLocalChecked(), BaseSubtleGetter); Nan::SetAccessor(constructor, Nan::New<String>("body").ToLocalChecked(), BodyGetter); Nan::SetAccessor(constructor, Nan::New<String>("bodySubtle").ToLocalChecked(), BodySubtleGetter); Nan::SetAccessor(constructor, Nan::New<String>("caption").ToLocalChecked(), CaptionGetter); Nan::SetAccessor(constructor, Nan::New<String>("captionSubtle").ToLocalChecked(), CaptionSubtleGetter); Nan::SetAccessor(constructor, Nan::New<String>("header").ToLocalChecked(), HeaderGetter); Nan::SetAccessor(constructor, Nan::New<String>("headerNumeral").ToLocalChecked(), HeaderNumeralGetter); Nan::SetAccessor(constructor, Nan::New<String>("headerNumeralSubtle").ToLocalChecked(), HeaderNumeralSubtleGetter); Nan::SetAccessor(constructor, Nan::New<String>("headerSubtle").ToLocalChecked(), HeaderSubtleGetter); Nan::SetAccessor(constructor, Nan::New<String>("subheader").ToLocalChecked(), SubheaderGetter); Nan::SetAccessor(constructor, Nan::New<String>("subheaderNumeral").ToLocalChecked(), SubheaderNumeralGetter); Nan::SetAccessor(constructor, Nan::New<String>("subheaderNumeralSubtle").ToLocalChecked(), SubheaderNumeralSubtleGetter); Nan::SetAccessor(constructor, Nan::New<String>("subheaderSubtle").ToLocalChecked(), SubheaderSubtleGetter); Nan::SetAccessor(constructor, Nan::New<String>("subtitle").ToLocalChecked(), SubtitleGetter); Nan::SetAccessor(constructor, Nan::New<String>("subtitleSubtle").ToLocalChecked(), SubtitleSubtleGetter); Nan::SetAccessor(constructor, Nan::New<String>("title").ToLocalChecked(), TitleGetter); Nan::SetAccessor(constructor, Nan::New<String>("titleNumeral").ToLocalChecked(), TitleNumeralGetter); Nan::SetAccessor(constructor, Nan::New<String>("titleSubtle").ToLocalChecked(), TitleSubtleGetter); Nan::Set(exports, Nan::New<String>("KnownAdaptiveNotificationTextStyles").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: KnownAdaptiveNotificationTextStyles(::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); KnownAdaptiveNotificationTextStyles *wrapperInstance = new KnownAdaptiveNotificationTextStyles(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void BaseGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::Base; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void BaseSubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::BaseSubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void BodyGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::Body; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void BodySubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::BodySubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void CaptionGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::Caption; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void CaptionSubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::CaptionSubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void HeaderGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::Header; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void HeaderNumeralGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::HeaderNumeral; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void HeaderNumeralSubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::HeaderNumeralSubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void HeaderSubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::HeaderSubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SubheaderGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::Subheader; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SubheaderNumeralGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::SubheaderNumeral; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SubheaderNumeralSubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::SubheaderNumeralSubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SubheaderSubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::SubheaderSubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SubtitleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::Subtitle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void SubtitleSubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::SubtitleSubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TitleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::Title; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TitleNumeralGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::TitleNumeral; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void TitleSubtleGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { Platform::String^ result = ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles::TitleSubtle; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapKnownAdaptiveNotificationTextStyles(::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ wintRtInstance); friend ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ UnwrapKnownAdaptiveNotificationTextStyles(Local<Value> value); }; Persistent<FunctionTemplate> KnownAdaptiveNotificationTextStyles::s_constructorTemplate; v8::Local<v8::Value> WrapKnownAdaptiveNotificationTextStyles(::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(KnownAdaptiveNotificationTextStyles::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::KnownAdaptiveNotificationTextStyles^ UnwrapKnownAdaptiveNotificationTextStyles(Local<Value> value) { return KnownAdaptiveNotificationTextStyles::Unwrap<KnownAdaptiveNotificationTextStyles>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitKnownAdaptiveNotificationTextStyles(Local<Object> exports) { KnownAdaptiveNotificationTextStyles::Init(exports); } class TileUpdateManager : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("TileUpdateManager").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::SetMethod(constructor, "getForUser", GetForUser); Nan::SetMethod(constructor, "createTileUpdaterForApplication", CreateTileUpdaterForApplication); Nan::SetMethod(constructor, "createTileUpdaterForSecondaryTile", CreateTileUpdaterForSecondaryTile); Nan::SetMethod(constructor, "getTemplateContent", GetTemplateContent); Nan::Set(exports, Nan::New<String>("TileUpdateManager").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: TileUpdateManager(::Windows::UI::Notifications::TileUpdateManager^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::TileUpdateManager^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileUpdateManager^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::TileUpdateManager^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); TileUpdateManager *wrapperInstance = new TileUpdateManager(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void GetForUser(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::User^>(info[0])) { try { ::Windows::System::User^ arg0 = dynamic_cast<::Windows::System::User^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::UI::Notifications::TileUpdateManagerForUser^ result; result = ::Windows::UI::Notifications::TileUpdateManager::GetForUser(arg0); info.GetReturnValue().Set(WrapTileUpdateManagerForUser(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateTileUpdaterForApplication(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 0) { try { ::Windows::UI::Notifications::TileUpdater^ result; result = ::Windows::UI::Notifications::TileUpdateManager::CreateTileUpdaterForApplication(); info.GetReturnValue().Set(WrapTileUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::TileUpdater^ result; result = ::Windows::UI::Notifications::TileUpdateManager::CreateTileUpdaterForApplication(arg0); info.GetReturnValue().Set(WrapTileUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateTileUpdaterForSecondaryTile(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::TileUpdater^ result; result = ::Windows::UI::Notifications::TileUpdateManager::CreateTileUpdaterForSecondaryTile(arg0); info.GetReturnValue().Set(WrapTileUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void GetTemplateContent(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && info[0]->IsInt32()) { try { ::Windows::UI::Notifications::TileTemplateType arg0 = static_cast<::Windows::UI::Notifications::TileTemplateType>(Nan::To<int32_t>(info[0]).FromMaybe(0)); ::Windows::Data::Xml::Dom::XmlDocument^ result; result = ::Windows::UI::Notifications::TileUpdateManager::GetTemplateContent(arg0); info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } private: ::Windows::UI::Notifications::TileUpdateManager^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapTileUpdateManager(::Windows::UI::Notifications::TileUpdateManager^ wintRtInstance); friend ::Windows::UI::Notifications::TileUpdateManager^ UnwrapTileUpdateManager(Local<Value> value); }; Persistent<FunctionTemplate> TileUpdateManager::s_constructorTemplate; v8::Local<v8::Value> WrapTileUpdateManager(::Windows::UI::Notifications::TileUpdateManager^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(TileUpdateManager::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::TileUpdateManager^ UnwrapTileUpdateManager(Local<Value> value) { return TileUpdateManager::Unwrap<TileUpdateManager>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitTileUpdateManager(Local<Object> exports) { TileUpdateManager::Init(exports); } class BadgeUpdateManager : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("BadgeUpdateManager").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::SetMethod(constructor, "getForUser", GetForUser); Nan::SetMethod(constructor, "createBadgeUpdaterForApplication", CreateBadgeUpdaterForApplication); Nan::SetMethod(constructor, "createBadgeUpdaterForSecondaryTile", CreateBadgeUpdaterForSecondaryTile); Nan::SetMethod(constructor, "getTemplateContent", GetTemplateContent); Nan::Set(exports, Nan::New<String>("BadgeUpdateManager").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: BadgeUpdateManager(::Windows::UI::Notifications::BadgeUpdateManager^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::BadgeUpdateManager^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::BadgeUpdateManager^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::BadgeUpdateManager^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); BadgeUpdateManager *wrapperInstance = new BadgeUpdateManager(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void GetForUser(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::User^>(info[0])) { try { ::Windows::System::User^ arg0 = dynamic_cast<::Windows::System::User^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::UI::Notifications::BadgeUpdateManagerForUser^ result; result = ::Windows::UI::Notifications::BadgeUpdateManager::GetForUser(arg0); info.GetReturnValue().Set(WrapBadgeUpdateManagerForUser(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateBadgeUpdaterForApplication(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 0) { try { ::Windows::UI::Notifications::BadgeUpdater^ result; result = ::Windows::UI::Notifications::BadgeUpdateManager::CreateBadgeUpdaterForApplication(); info.GetReturnValue().Set(WrapBadgeUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::BadgeUpdater^ result; result = ::Windows::UI::Notifications::BadgeUpdateManager::CreateBadgeUpdaterForApplication(arg0); info.GetReturnValue().Set(WrapBadgeUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateBadgeUpdaterForSecondaryTile(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::BadgeUpdater^ result; result = ::Windows::UI::Notifications::BadgeUpdateManager::CreateBadgeUpdaterForSecondaryTile(arg0); info.GetReturnValue().Set(WrapBadgeUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void GetTemplateContent(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && info[0]->IsInt32()) { try { ::Windows::UI::Notifications::BadgeTemplateType arg0 = static_cast<::Windows::UI::Notifications::BadgeTemplateType>(Nan::To<int32_t>(info[0]).FromMaybe(0)); ::Windows::Data::Xml::Dom::XmlDocument^ result; result = ::Windows::UI::Notifications::BadgeUpdateManager::GetTemplateContent(arg0); info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } private: ::Windows::UI::Notifications::BadgeUpdateManager^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapBadgeUpdateManager(::Windows::UI::Notifications::BadgeUpdateManager^ wintRtInstance); friend ::Windows::UI::Notifications::BadgeUpdateManager^ UnwrapBadgeUpdateManager(Local<Value> value); }; Persistent<FunctionTemplate> BadgeUpdateManager::s_constructorTemplate; v8::Local<v8::Value> WrapBadgeUpdateManager(::Windows::UI::Notifications::BadgeUpdateManager^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(BadgeUpdateManager::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::BadgeUpdateManager^ UnwrapBadgeUpdateManager(Local<Value> value) { return BadgeUpdateManager::Unwrap<BadgeUpdateManager>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitBadgeUpdateManager(Local<Object> exports) { BadgeUpdateManager::Init(exports); } class TileFlyoutUpdateManager : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("TileFlyoutUpdateManager").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::SetMethod(constructor, "createTileFlyoutUpdaterForApplication", CreateTileFlyoutUpdaterForApplication); Nan::SetMethod(constructor, "createTileFlyoutUpdaterForSecondaryTile", CreateTileFlyoutUpdaterForSecondaryTile); Nan::SetMethod(constructor, "getTemplateContent", GetTemplateContent); Nan::Set(exports, Nan::New<String>("TileFlyoutUpdateManager").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: TileFlyoutUpdateManager(::Windows::UI::Notifications::TileFlyoutUpdateManager^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::TileFlyoutUpdateManager^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::TileFlyoutUpdateManager^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::TileFlyoutUpdateManager^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); TileFlyoutUpdateManager *wrapperInstance = new TileFlyoutUpdateManager(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void CreateTileFlyoutUpdaterForApplication(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 0) { try { ::Windows::UI::Notifications::TileFlyoutUpdater^ result; result = ::Windows::UI::Notifications::TileFlyoutUpdateManager::CreateTileFlyoutUpdaterForApplication(); info.GetReturnValue().Set(WrapTileFlyoutUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::TileFlyoutUpdater^ result; result = ::Windows::UI::Notifications::TileFlyoutUpdateManager::CreateTileFlyoutUpdaterForApplication(arg0); info.GetReturnValue().Set(WrapTileFlyoutUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateTileFlyoutUpdaterForSecondaryTile(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::TileFlyoutUpdater^ result; result = ::Windows::UI::Notifications::TileFlyoutUpdateManager::CreateTileFlyoutUpdaterForSecondaryTile(arg0); info.GetReturnValue().Set(WrapTileFlyoutUpdater(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void GetTemplateContent(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && info[0]->IsInt32()) { try { ::Windows::UI::Notifications::TileFlyoutTemplateType arg0 = static_cast<::Windows::UI::Notifications::TileFlyoutTemplateType>(Nan::To<int32_t>(info[0]).FromMaybe(0)); ::Windows::Data::Xml::Dom::XmlDocument^ result; result = ::Windows::UI::Notifications::TileFlyoutUpdateManager::GetTemplateContent(arg0); info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } private: ::Windows::UI::Notifications::TileFlyoutUpdateManager^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapTileFlyoutUpdateManager(::Windows::UI::Notifications::TileFlyoutUpdateManager^ wintRtInstance); friend ::Windows::UI::Notifications::TileFlyoutUpdateManager^ UnwrapTileFlyoutUpdateManager(Local<Value> value); }; Persistent<FunctionTemplate> TileFlyoutUpdateManager::s_constructorTemplate; v8::Local<v8::Value> WrapTileFlyoutUpdateManager(::Windows::UI::Notifications::TileFlyoutUpdateManager^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(TileFlyoutUpdateManager::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::TileFlyoutUpdateManager^ UnwrapTileFlyoutUpdateManager(Local<Value> value) { return TileFlyoutUpdateManager::Unwrap<TileFlyoutUpdateManager>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitTileFlyoutUpdateManager(Local<Object> exports) { TileFlyoutUpdateManager::Init(exports); } class ToastNotificationManager : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastNotificationManager").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::SetMethod(constructor, "getForUser", GetForUser); Nan::SetMethod(constructor, "configureNotificationMirroring", ConfigureNotificationMirroring); Nan::SetMethod(constructor, "createToastNotifier", CreateToastNotifier); Nan::SetMethod(constructor, "getTemplateContent", GetTemplateContent); Nan::SetAccessor(constructor, Nan::New<String>("history").ToLocalChecked(), HistoryGetter); Nan::Set(exports, Nan::New<String>("ToastNotificationManager").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastNotificationManager(::Windows::UI::Notifications::ToastNotificationManager^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastNotificationManager^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationManager^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastNotificationManager^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastNotificationManager *wrapperInstance = new ToastNotificationManager(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void GetForUser(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && NodeRT::Utils::IsWinRtWrapperOf<::Windows::System::User^>(info[0])) { try { ::Windows::System::User^ arg0 = dynamic_cast<::Windows::System::User^>(NodeRT::Utils::GetObjectInstance(info[0])); ::Windows::UI::Notifications::ToastNotificationManagerForUser^ result; result = ::Windows::UI::Notifications::ToastNotificationManager::GetForUser(arg0); info.GetReturnValue().Set(WrapToastNotificationManagerForUser(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void ConfigureNotificationMirroring(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && info[0]->IsInt32()) { try { ::Windows::UI::Notifications::NotificationMirroring arg0 = static_cast<::Windows::UI::Notifications::NotificationMirroring>(Nan::To<int32_t>(info[0]).FromMaybe(0)); ::Windows::UI::Notifications::ToastNotificationManager::ConfigureNotificationMirroring(arg0); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void CreateToastNotifier(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 0) { try { ::Windows::UI::Notifications::ToastNotifier^ result; result = ::Windows::UI::Notifications::ToastNotificationManager::CreateToastNotifier(); info.GetReturnValue().Set(WrapToastNotifier(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else if (info.Length() == 1 && info[0]->IsString()) { try { Platform::String^ arg0 = ref new Platform::String(NodeRT::Utils::StringToWchar(v8::String::Value(info[0]))); ::Windows::UI::Notifications::ToastNotifier^ result; result = ::Windows::UI::Notifications::ToastNotificationManager::CreateToastNotifier(arg0); info.GetReturnValue().Set(WrapToastNotifier(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void GetTemplateContent(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; if (info.Length() == 1 && info[0]->IsInt32()) { try { ::Windows::UI::Notifications::ToastTemplateType arg0 = static_cast<::Windows::UI::Notifications::ToastTemplateType>(Nan::To<int32_t>(info[0]).FromMaybe(0)); ::Windows::Data::Xml::Dom::XmlDocument^ result; result = ::Windows::UI::Notifications::ToastNotificationManager::GetTemplateContent(arg0); info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Data.Xml.Dom", "XmlDocument", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Bad arguments: no suitable overload found"))); return; } } static void HistoryGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; try { ::Windows::UI::Notifications::ToastNotificationHistory^ result = ::Windows::UI::Notifications::ToastNotificationManager::History; info.GetReturnValue().Set(WrapToastNotificationHistory(result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ToastNotificationManager^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastNotificationManager(::Windows::UI::Notifications::ToastNotificationManager^ wintRtInstance); friend ::Windows::UI::Notifications::ToastNotificationManager^ UnwrapToastNotificationManager(Local<Value> value); }; Persistent<FunctionTemplate> ToastNotificationManager::s_constructorTemplate; v8::Local<v8::Value> WrapToastNotificationManager(::Windows::UI::Notifications::ToastNotificationManager^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastNotificationManager::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastNotificationManager^ UnwrapToastNotificationManager(Local<Value> value) { return ToastNotificationManager::Unwrap<ToastNotificationManager>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastNotificationManager(Local<Object> exports) { ToastNotificationManager::Init(exports); } class ToastActivatedEventArgs : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastActivatedEventArgs").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("arguments").ToLocalChecked(), ArgumentsGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastActivatedEventArgs").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastActivatedEventArgs(::Windows::UI::Notifications::ToastActivatedEventArgs^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastActivatedEventArgs^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastActivatedEventArgs^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastActivatedEventArgs^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastActivatedEventArgs *wrapperInstance = new ToastActivatedEventArgs(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ArgumentsGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastActivatedEventArgs^>(info.This())) { return; } ToastActivatedEventArgs *wrapper = ToastActivatedEventArgs::Unwrap<ToastActivatedEventArgs>(info.This()); try { Platform::String^ result = wrapper->_instance->Arguments; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ToastActivatedEventArgs^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastActivatedEventArgs(::Windows::UI::Notifications::ToastActivatedEventArgs^ wintRtInstance); friend ::Windows::UI::Notifications::ToastActivatedEventArgs^ UnwrapToastActivatedEventArgs(Local<Value> value); }; Persistent<FunctionTemplate> ToastActivatedEventArgs::s_constructorTemplate; v8::Local<v8::Value> WrapToastActivatedEventArgs(::Windows::UI::Notifications::ToastActivatedEventArgs^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastActivatedEventArgs::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastActivatedEventArgs^ UnwrapToastActivatedEventArgs(Local<Value> value) { return ToastActivatedEventArgs::Unwrap<ToastActivatedEventArgs>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastActivatedEventArgs(Local<Object> exports) { ToastActivatedEventArgs::Init(exports); } class ToastNotificationHistoryChangedTriggerDetail : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastNotificationHistoryChangedTriggerDetail").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("changeType").ToLocalChecked(), ChangeTypeGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastNotificationHistoryChangedTriggerDetail").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastNotificationHistoryChangedTriggerDetail(::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastNotificationHistoryChangedTriggerDetail *wrapperInstance = new ToastNotificationHistoryChangedTriggerDetail(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ChangeTypeGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^>(info.This())) { return; } ToastNotificationHistoryChangedTriggerDetail *wrapper = ToastNotificationHistoryChangedTriggerDetail::Unwrap<ToastNotificationHistoryChangedTriggerDetail>(info.This()); try { ::Windows::UI::Notifications::ToastHistoryChangedType result = wrapper->_instance->ChangeType; info.GetReturnValue().Set(Nan::New<Integer>(static_cast<int>(result))); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastNotificationHistoryChangedTriggerDetail(::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ wintRtInstance); friend ::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ UnwrapToastNotificationHistoryChangedTriggerDetail(Local<Value> value); }; Persistent<FunctionTemplate> ToastNotificationHistoryChangedTriggerDetail::s_constructorTemplate; v8::Local<v8::Value> WrapToastNotificationHistoryChangedTriggerDetail(::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastNotificationHistoryChangedTriggerDetail::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastNotificationHistoryChangedTriggerDetail^ UnwrapToastNotificationHistoryChangedTriggerDetail(Local<Value> value) { return ToastNotificationHistoryChangedTriggerDetail::Unwrap<ToastNotificationHistoryChangedTriggerDetail>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastNotificationHistoryChangedTriggerDetail(Local<Object> exports) { ToastNotificationHistoryChangedTriggerDetail::Init(exports); } class ToastNotificationActionTriggerDetail : public WrapperBase { public: static void Init(const Local<Object> exports) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(New); s_constructorTemplate.Reset(localRef); localRef->SetClassName(Nan::New<String>("ToastNotificationActionTriggerDetail").ToLocalChecked()); localRef->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("argument").ToLocalChecked(), ArgumentGetter); Nan::SetAccessor(localRef->PrototypeTemplate(), Nan::New<String>("userInput").ToLocalChecked(), UserInputGetter); Local<Object> constructor = Nan::To<Object>(Nan::GetFunction(localRef).ToLocalChecked()).ToLocalChecked(); Nan::Set(exports, Nan::New<String>("ToastNotificationActionTriggerDetail").ToLocalChecked(), constructor); } virtual ::Platform::Object^ GetObjectInstance() const override { return _instance; } private: ToastNotificationActionTriggerDetail(::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ instance) { _instance = instance; } static void New(Nan::NAN_METHOD_ARGS_TYPE info) { HandleScope scope; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(s_constructorTemplate); // in case the constructor was called without the new operator if (!localRef->HasInstance(info.This())) { if (info.Length() > 0) { std::unique_ptr<Local<Value> []> constructorArgs(new Local<Value>[info.Length()]); Local<Value> *argsPtr = constructorArgs.get(); for (int i = 0; i < info.Length(); i++) { argsPtr[i] = info[i]; } info.GetReturnValue().Set(Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), constructorArgs.get()).ToLocalChecked()); return; } else { MaybeLocal<Value> res = Nan::CallAsConstructor(Nan::GetFunction(localRef).ToLocalChecked(), info.Length(), nullptr); if (res.IsEmpty()) { return; } info.GetReturnValue().Set(res.ToLocalChecked()); return; } } ::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ winRtInstance; if (info.Length() == 1 && OpaqueWrapper::IsOpaqueWrapper(info[0]) && NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^>(info[0])) { try { winRtInstance = (::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^) NodeRT::Utils::GetObjectInstance(info[0]); } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } else { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"Invalid arguments, no suitable constructor found"))); return; } NodeRT::Utils::SetHiddenValue(info.This(), Nan::New<String>("__winRtInstance__").ToLocalChecked(), True()); ToastNotificationActionTriggerDetail *wrapperInstance = new ToastNotificationActionTriggerDetail(winRtInstance); wrapperInstance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } static void ArgumentGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^>(info.This())) { return; } ToastNotificationActionTriggerDetail *wrapper = ToastNotificationActionTriggerDetail::Unwrap<ToastNotificationActionTriggerDetail>(info.This()); try { Platform::String^ result = wrapper->_instance->Argument; info.GetReturnValue().Set(NodeRT::Utils::NewString(result->Data())); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } static void UserInputGetter(Local<String> property, const Nan::PropertyCallbackInfo<v8::Value> &info) { HandleScope scope; if (!NodeRT::Utils::IsWinRtWrapperOf<::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^>(info.This())) { return; } ToastNotificationActionTriggerDetail *wrapper = ToastNotificationActionTriggerDetail::Unwrap<ToastNotificationActionTriggerDetail>(info.This()); try { ::Windows::Foundation::Collections::ValueSet^ result = wrapper->_instance->UserInput; info.GetReturnValue().Set(NodeRT::Utils::CreateExternalWinRTObject("Windows.Foundation.Collections", "ValueSet", result)); return; } catch (Platform::Exception ^exception) { NodeRT::Utils::ThrowWinRtExceptionInJs(exception); return; } } private: ::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ _instance; static Persistent<FunctionTemplate> s_constructorTemplate; friend v8::Local<v8::Value> WrapToastNotificationActionTriggerDetail(::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ wintRtInstance); friend ::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ UnwrapToastNotificationActionTriggerDetail(Local<Value> value); }; Persistent<FunctionTemplate> ToastNotificationActionTriggerDetail::s_constructorTemplate; v8::Local<v8::Value> WrapToastNotificationActionTriggerDetail(::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ winRtInstance) { EscapableHandleScope scope; if (winRtInstance == nullptr) { return scope.Escape(Undefined()); } Local<Value> opaqueWrapper = CreateOpaqueWrapper(winRtInstance); Local<Value> args[] = {opaqueWrapper}; Local<FunctionTemplate> localRef = Nan::New<FunctionTemplate>(ToastNotificationActionTriggerDetail::s_constructorTemplate); return scope.Escape(Nan::NewInstance(Nan::GetFunction(localRef).ToLocalChecked(),_countof(args), args).ToLocalChecked()); } ::Windows::UI::Notifications::ToastNotificationActionTriggerDetail^ UnwrapToastNotificationActionTriggerDetail(Local<Value> value) { return ToastNotificationActionTriggerDetail::Unwrap<ToastNotificationActionTriggerDetail>(Nan::To<Object>(value).ToLocalChecked())->_instance; } void InitToastNotificationActionTriggerDetail(Local<Object> exports) { ToastNotificationActionTriggerDetail::Init(exports); } } } } } NAN_MODULE_INIT(init) { if (FAILED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))) { Nan::ThrowError(Nan::Error(NodeRT::Utils::NewString(L"error in CoInitializeEx()"))); return; } NodeRT::Windows::UI::Notifications::InitNotificationSettingEnum(target); NodeRT::Windows::UI::Notifications::InitToastDismissalReasonEnum(target); NodeRT::Windows::UI::Notifications::InitBadgeTemplateTypeEnum(target); NodeRT::Windows::UI::Notifications::InitTileFlyoutTemplateTypeEnum(target); NodeRT::Windows::UI::Notifications::InitTileTemplateTypeEnum(target); NodeRT::Windows::UI::Notifications::InitToastTemplateTypeEnum(target); NodeRT::Windows::UI::Notifications::InitPeriodicUpdateRecurrenceEnum(target); NodeRT::Windows::UI::Notifications::InitToastHistoryChangedTypeEnum(target); NodeRT::Windows::UI::Notifications::InitAdaptiveNotificationContentKindEnum(target); NodeRT::Windows::UI::Notifications::InitNotificationMirroringEnum(target); NodeRT::Windows::UI::Notifications::InitNotificationKindsEnum(target); NodeRT::Windows::UI::Notifications::InitUserNotificationChangedKindEnum(target); NodeRT::Windows::UI::Notifications::InitShownTileNotification(target); NodeRT::Windows::UI::Notifications::InitNotification(target); NodeRT::Windows::UI::Notifications::InitNotificationBinding(target); NodeRT::Windows::UI::Notifications::InitIAdaptiveNotificationContent(target); NodeRT::Windows::UI::Notifications::InitAdaptiveNotificationText(target); NodeRT::Windows::UI::Notifications::InitTileUpdater(target); NodeRT::Windows::UI::Notifications::InitTileUpdateManagerForUser(target); NodeRT::Windows::UI::Notifications::InitTileNotification(target); NodeRT::Windows::UI::Notifications::InitScheduledTileNotification(target); NodeRT::Windows::UI::Notifications::InitTileFlyoutUpdater(target); NodeRT::Windows::UI::Notifications::InitTileFlyoutNotification(target); NodeRT::Windows::UI::Notifications::InitBadgeUpdater(target); NodeRT::Windows::UI::Notifications::InitBadgeUpdateManagerForUser(target); NodeRT::Windows::UI::Notifications::InitBadgeNotification(target); NodeRT::Windows::UI::Notifications::InitToastNotifier(target); NodeRT::Windows::UI::Notifications::InitToastNotification(target); NodeRT::Windows::UI::Notifications::InitScheduledToastNotification(target); NodeRT::Windows::UI::Notifications::InitToastDismissedEventArgs(target); NodeRT::Windows::UI::Notifications::InitToastFailedEventArgs(target); NodeRT::Windows::UI::Notifications::InitNotificationVisual(target); NodeRT::Windows::UI::Notifications::InitToastNotificationHistory(target); NodeRT::Windows::UI::Notifications::InitToastNotificationManagerForUser(target); NodeRT::Windows::UI::Notifications::InitUserNotificationChangedEventArgs(target); NodeRT::Windows::UI::Notifications::InitUserNotification(target); NodeRT::Windows::UI::Notifications::InitKnownAdaptiveNotificationHints(target); NodeRT::Windows::UI::Notifications::InitKnownNotificationBindings(target); NodeRT::Windows::UI::Notifications::InitKnownAdaptiveNotificationTextStyles(target); NodeRT::Windows::UI::Notifications::InitTileUpdateManager(target); NodeRT::Windows::UI::Notifications::InitBadgeUpdateManager(target); NodeRT::Windows::UI::Notifications::InitTileFlyoutUpdateManager(target); NodeRT::Windows::UI::Notifications::InitToastNotificationManager(target); NodeRT::Windows::UI::Notifications::InitToastActivatedEventArgs(target); NodeRT::Windows::UI::Notifications::InitToastNotificationHistoryChangedTriggerDetail(target); NodeRT::Windows::UI::Notifications::InitToastNotificationActionTriggerDetail(target); NodeRT::Utils::RegisterNameSpace("Windows.UI.Notifications", target); } NODE_MODULE(binding, init)
36.709336
266
0.657056
[ "object" ]
a9431e7855beccb76f59f883e0f8f84ce0e51994
1,936
cpp
C++
src/stats/http/Connection.cpp
neogenie/iqlogger
7a3866046dd30282a35ce954dc4fd301452aa924
[ "Apache-2.0" ]
1
2020-08-17T12:22:36.000Z
2020-08-17T12:22:36.000Z
src/stats/http/Connection.cpp
neogenie/iqlogger
7a3866046dd30282a35ce954dc4fd301452aa924
[ "Apache-2.0" ]
null
null
null
src/stats/http/Connection.cpp
neogenie/iqlogger
7a3866046dd30282a35ce954dc4fd301452aa924
[ "Apache-2.0" ]
null
null
null
// // Connection.cpp // ~~~~~~~~~~~~~~~~ // // Copyright (C) 2018 IQOption Software, Inc. // // #include <utility> #include <vector> #include "Connection.h" #include "ConnectionManager.h" #include "RequestHandler.h" using namespace iqlogger::stats::http; Connection::Connection(boost::asio::io_service& io_service, ConnectionManager& manager, RequestHandler& handler) : m_socket(io_service), m_connectionManager(manager), m_requestHandler(handler) {} void Connection::start() { do_read(); } void Connection::stop() { m_socket.close(); } void Connection::do_read() { auto self(shared_from_this()); m_socket.async_read_some( boost::asio::buffer(m_buffer), [this, self](boost::system::error_code ec, std::size_t bytes_transferred) { if (!ec) { RequestParser::result_type result; std::tie(result, std::ignore) = m_request_parser.parse(m_request, m_buffer.data(), m_buffer.data() + bytes_transferred); if (result == RequestParser::result_type::good) { m_requestHandler.handle_request(m_request, m_reply); do_write(); } else if (result == RequestParser::result_type::bad) { m_reply = Reply::stock_reply(Reply::status_type::bad_request); do_write(); } else { do_read(); } } else if (ec != boost::asio::error::operation_aborted) { m_connectionManager.stop(shared_from_this()); } }); } void Connection::do_write() { auto self(shared_from_this()); boost::asio::async_write(m_socket, m_reply.to_buffers(), [this, self](boost::system::error_code ec, std::size_t) { if (!ec) { boost::system::error_code ignored_ec; m_socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } if (ec != boost::asio::error::operation_aborted) { m_connectionManager.stop(shared_from_this()); } }); }
28.057971
116
0.63843
[ "vector" ]
a9502b4931dad7b20d0584bf683743f33cc692a1
7,274
cpp
C++
src/Orbit/Graphics/Debug/DebugManager.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
41
2018-08-02T06:28:07.000Z
2022-01-20T01:23:42.000Z
src/Orbit/Graphics/Debug/DebugManager.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
4
2020-02-11T22:10:31.000Z
2020-07-06T19:36:09.000Z
src/Orbit/Graphics/Debug/DebugManager.cpp
Gaztin/Orb
4589f3f0165d287482ab4b367f02633ea4e7c9a5
[ "Zlib" ]
4
2018-11-18T10:19:57.000Z
2021-07-14T02:58:40.000Z
/* * Copyright (c) 2020 Sebastian Kylander https://gaztin.com/ * * This software is provided 'as-is', without any express or implied warranty. In no event will * the authors be held liable for any damages arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, including commercial * applications, and to alter it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the * original software. If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as * being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "DebugManager.h" #include "Orbit/Core/Utility/Color.h" #include "Orbit/Graphics/Geometry/MeshFactory.h" #include "Orbit/Graphics/Renderer/DefaultRenderer.h" #include "Orbit/Graphics/Renderer/RenderCommand.h" #include "Orbit/Math/Matrix/Matrix4.h" #include "Orbit/Math/Vector/Vector4.h" #include "Orbit/Core/IO/Log.h" ORB_NAMESPACE_BEGIN struct DebugVertex { Vector4 position; Color color; }; constexpr std::string_view shader_source = R"( #if defined( HLSL ) cbuffer VertexUniforms { matrix u_view_projection; }; struct VertexData { float4 position : POSITION; float4 color : COLOR; }; struct PixelData { float4 position : SV_POSITION; float4 color : COLOR; }; PixelData VSMain( VertexData input ) { PixelData output; output.position = mul( input.position, u_view_projection ); output.color = input.color; return output; } float4 PSMain( PixelData input ) : SV_TARGET { return input.color; } #elif defined( GLSL ) // HLSL #if defined( VERTEX ) ORB_CONSTANTS_BEGIN( VertexUniforms ) ORB_CONSTANT( mat4, u_view_projection ); ORB_CONSTANTS_END ORB_ATTRIBUTE( 0 ) vec4 a_position; ORB_ATTRIBUTE( 1 ) vec4 a_color; ORB_VARYING vec4 v_position; ORB_VARYING vec4 v_color; void main() { v_position = u_view_projection * a_position; v_color = a_color; gl_Position = v_position; } #elif defined( FRAGMENT ) // VERTEX ORB_VARYING vec4 v_position; ORB_VARYING vec4 v_color; void main() { ORB_SET_OUT_COLOR( v_color ); } #endif // FRAGMENT #endif // GLSL )"; static VertexLayout vertex_layout { VertexComponent::Position, VertexComponent::Color, }; DebugManager::DebugManager( void ) : shader_ ( shader_source, vertex_layout ) , line_segments_ { } , spheres_ { } , lines_vertex_buffer_ ( nullptr, 0, vertex_layout.GetStride(), false ) , spheres_vertex_buffer_( nullptr, 0, vertex_layout.GetStride(), false ) , sphere_geometry_ ( MeshFactory::GetInstance().CreateGeometryFromShape( ShapeType::Sphere, vertex_layout, MeshFactory::DetailLevel::Low ) ) { } void DebugManager::PushLineSegment( const LineSegment& line_segment, Color color, double duration ) { DebugLineSegment obj; obj.birth = Clock::now(); obj.death = obj.birth + std::chrono::duration_cast< Clock::duration >( std::chrono::duration< double >( duration ) ); obj.color = color; obj.line_segment = line_segment; line_segments_.emplace_back( std::move( obj ) ); } void DebugManager::PushSphere( Vector3 center, Color color, double duration ) { DebugSphere obj; obj.birth = Clock::now(); obj.death = obj.birth + std::chrono::duration_cast< Clock::duration >( std::chrono::duration< double >( duration ) ); obj.color = color; obj.position = center; spheres_.emplace_back( std::move( obj ) ); } void DebugManager::Render( IRenderer& renderer, const Matrix4& view_projection ) { auto now = Clock::now(); shader_.SetVertexUniform( "u_view_projection", &view_projection, sizeof( Matrix4 ) ); if( !line_segments_.empty() ) { lines_vertex_buffer_.Update( nullptr, line_segments_.size() * 2 ); DebugVertex* dst = static_cast< DebugVertex* >( lines_vertex_buffer_.Map() ); for( const DebugLineSegment& obj : line_segments_ ) { Color color = obj.color; color.a = CalcAlphaForObject( obj, now ); dst->position = Vector4( obj.line_segment.start, 1.0f ); dst->color = color; ++dst; dst->position = Vector4( obj.line_segment.end, 1.0f ); dst->color = color; ++dst; } lines_vertex_buffer_.Unmap(); // Create render command RenderCommand command; command.shader = shader_; command.vertex_buffer = lines_vertex_buffer_; command.topology = Topology::Lines; renderer.PushCommand( std::move( command ) ); } if( !spheres_.empty() ) { spheres_vertex_buffer_.Update( nullptr, spheres_.size() * sphere_geometry_.GetFaceCount() * 6 ); DebugVertex* dst = static_cast< DebugVertex* >( spheres_vertex_buffer_.Map() ); for( const DebugSphere& obj : spheres_ ) { Color color = obj.color; color.a = CalcAlphaForObject( obj, now ); for( Face face : sphere_geometry_.GetFaces() ) { Vertex v1 = sphere_geometry_.GetVertex( face.indices[ 0 ] ); Vertex v2 = sphere_geometry_.GetVertex( face.indices[ 1 ] ); Vertex v3 = sphere_geometry_.GetVertex( face.indices[ 2 ] ); v1.position += Vector4( obj.position, 0.0f ); v2.position += Vector4( obj.position, 0.0f ); v3.position += Vector4( obj.position, 0.0f ); dst->position = v1.position; dst->color = color; ++dst; dst->position = v2.position; dst->color = color; ++dst; dst->position = v1.position; dst->color = color; ++dst; dst->position = v3.position; dst->color = color; ++dst; dst->position = v2.position; dst->color = color; ++dst; dst->position = v3.position; dst->color = color; ++dst; } } spheres_vertex_buffer_.Unmap(); // Create render command RenderCommand render_command; render_command.shader = shader_; render_command.vertex_buffer = spheres_vertex_buffer_; render_command.topology = Topology::Lines; renderer.PushCommand( std::move( render_command ) ); } } void DebugManager::Flush( void ) { auto now = Clock::now(); for( LineSegmentVector::iterator it = line_segments_.begin(); it != line_segments_.end(); ) { auto time_left = ( it->death - now ); if( time_left < time_left.zero() ) it = line_segments_.erase( it ); else it++; } for( SphereVector::iterator it = spheres_.begin(); it != spheres_.end(); ) { auto time_left = ( it->death - now ); if( time_left < time_left.zero() ) it = spheres_.erase( it ); else it++; } } float DebugManager::CalcAlphaForObject( const DebugObjectBase& object, Clock::time_point now ) { // Single-frame objects should always be visible if( object.birth == object.death ) return 1.0f; float time_alive = std::chrono::duration_cast< std::chrono::duration< float > >( now - object.birth ).count(); float time_left_to_live = std::chrono::duration_cast< std::chrono::duration< float > >( object.death - now ).count(); return ( time_left_to_live / std::min( time_alive + time_left_to_live, 1.0f ) ); } ORB_NAMESPACE_END
26.742647
146
0.689167
[ "geometry", "render", "object", "vector" ]
a950630ea7f0c8488b93b9948b31a9adb03c1bff
9,211
cxx
C++
smtk/extension/paraview/widgets/plugin/pqConePropertyWidget.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
40
2015-02-21T19:55:54.000Z
2022-01-06T13:13:05.000Z
smtk/extension/paraview/widgets/plugin/pqConePropertyWidget.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
127
2015-01-15T20:55:45.000Z
2021-08-19T17:34:15.000Z
smtk/extension/paraview/widgets/plugin/pqConePropertyWidget.cxx
jcfr/SMTK
0069ea37f8f71a440b8f10a157b84a56ca004551
[ "BSD-3-Clause-Clear" ]
27
2015-03-04T14:17:51.000Z
2021-12-23T01:05:42.000Z
//========================================================================= // Copyright (c) Kitware, Inc. // All rights reserved. // See LICENSE.txt for details. // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notice for more information. //========================================================================= #include "smtk/extension/paraview/widgets/plugin/pqConePropertyWidget.h" #include "smtk/extension/paraview/widgets/plugin/ui_pqConePropertyWidget.h" #include "smtk/extension/paraview/widgets/pqPointPickingVisibilityHelper.h" #include "pqCoreUtilities.h" #include "pqPointPickingHelper.h" #include "vtkSMNewWidgetRepresentationProxy.h" #include "vtkSMProperty.h" #include "vtkSMPropertyGroup.h" #include "vtkSMPropertyHelper.h" #include "vtkCommand.h" #include "vtkMath.h" #include "vtkVector.h" #include "vtkVectorOperators.h" class pqConePropertyWidget::Internals { public: Internals() : BottomRadiusName("Bottom radius") { } Ui::ConePropertyWidget Ui; bool PickPoint1{ true }; std::string BottomRadiusName; }; pqConePropertyWidget::pqConePropertyWidget( vtkSMProxy* smproxy, vtkSMPropertyGroup* smgroup, QWidget* parentObj) : Superclass("representations", "ConeWidgetRepresentation", smproxy, smgroup, parentObj) , m_p(new pqConePropertyWidget::Internals()) { Ui::ConePropertyWidget& ui = m_p->Ui; ui.setupUi(this); auto* topRad = smgroup->GetProperty("TopRadius"); if (!topRad) { // Only show a single radius when both must be identical. ui.radius2->hide(); ui.labelRadius2->hide(); ui.labelRadius1->setText("Radius"); ui.show3DWidget->setText("Show cylinder"); ui.cylindrical->hide(); // We are forced into cylinder model auto* cyl = smgroup->GetProperty("Cylindrical"); if (cyl) { int on = 1; vtkSMPropertyHelper(cyl).Set(&on, 1); } } // link show3DWidget checkbox this->connect(ui.show3DWidget, SIGNAL(toggled(bool)), SLOT(setWidgetVisible(bool))); ui.show3DWidget->connect(this, SIGNAL(widgetVisibilityToggled(bool)), SLOT(setChecked(bool))); this->setWidgetVisible(ui.show3DWidget->isChecked()); // link show3DWidget checkbox this->connect(ui.cylindrical, SIGNAL(toggled(bool)), SLOT(setCylindrical(bool))); // ui.cylindrical->connect(this, SIGNAL(widgetVisibilityToggled(bool)), SLOT(setChecked(bool))); this->setCylindrical(ui.cylindrical->isChecked()); #ifdef Q_OS_MAC ui.pickLabel->setText(ui.pickLabel->text().replace("Ctrl", "Cmd")); #endif if (vtkSMProperty* p1 = smgroup->GetProperty("BottomPoint")) { ui.labelPoint1->setText(tr(p1->GetXMLLabel())); this->addPropertyLink(ui.point1X, "text2", SIGNAL(textChangedAndEditingFinished()), p1, 0); this->addPropertyLink(ui.point1Y, "text2", SIGNAL(textChangedAndEditingFinished()), p1, 1); this->addPropertyLink(ui.point1Z, "text2", SIGNAL(textChangedAndEditingFinished()), p1, 2); ui.labelPoint1->setText(p1->GetXMLLabel()); } else { qCritical("Missing required property for function 'BottomPoint'."); } if (vtkSMProperty* p2 = smgroup->GetProperty("TopPoint")) { ui.labelPoint2->setText(tr(p2->GetXMLLabel())); this->addPropertyLink(ui.point2X, "text2", SIGNAL(textChangedAndEditingFinished()), p2, 0); this->addPropertyLink(ui.point2Y, "text2", SIGNAL(textChangedAndEditingFinished()), p2, 1); this->addPropertyLink(ui.point2Z, "text2", SIGNAL(textChangedAndEditingFinished()), p2, 2); ui.labelPoint2->setText(p2->GetXMLLabel()); } else { qCritical("Missing required property for function 'TopPoint'."); } if (vtkSMProperty* r1 = smgroup->GetProperty("BottomRadius")) { ui.labelRadius1->setText(tr(r1->GetXMLLabel())); this->addPropertyLink(ui.radius1, "text2", SIGNAL(textChangedAndEditingFinished()), r1, 0); } else { qCritical("Missing required property for function 'BottomRadius'."); } if (vtkSMProperty* r2 = smgroup->GetProperty("TopRadius")) { ui.labelRadius2->setText(tr(r2->GetXMLLabel())); this->addPropertyLink(ui.radius2, "text2", SIGNAL(textChangedAndEditingFinished()), r2, 0); } else { qCritical("Missing required property for function 'TopRadius'."); } pqPointPickingHelper* pickHelper = new pqPointPickingHelper(QKeySequence(tr("P")), false, this); pickHelper->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); this->connect( pickHelper, SIGNAL(pick(double, double, double)), SLOT(pick(double, double, double))); pqPointPickingVisibilityHelper<pqPointPickingHelper>{ *this, *pickHelper }; pqPointPickingHelper* pickHelper2 = new pqPointPickingHelper(QKeySequence(tr("Ctrl+P")), true, this); pickHelper2->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); this->connect( pickHelper2, SIGNAL(pick(double, double, double)), SLOT(pick(double, double, double))); pqPointPickingVisibilityHelper<pqPointPickingHelper>{ *this, *pickHelper2 }; pqPointPickingHelper* pickHelper3 = new pqPointPickingHelper(QKeySequence(tr("1")), false, this); pickHelper3->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); this->connect( pickHelper3, SIGNAL(pick(double, double, double)), SLOT(pickPoint1(double, double, double))); pqPointPickingVisibilityHelper<pqPointPickingHelper>{ *this, *pickHelper3 }; pqPointPickingHelper* pickHelper4 = new pqPointPickingHelper(QKeySequence(tr("Ctrl+1")), true, this); pickHelper4->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); this->connect( pickHelper4, SIGNAL(pick(double, double, double)), SLOT(pickPoint1(double, double, double))); pqPointPickingVisibilityHelper<pqPointPickingHelper>{ *this, *pickHelper4 }; pqPointPickingHelper* pickHelper5 = new pqPointPickingHelper(QKeySequence(tr("2")), false, this); pickHelper5->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); this->connect( pickHelper5, SIGNAL(pick(double, double, double)), SLOT(pickPoint2(double, double, double))); pqPointPickingVisibilityHelper<pqPointPickingHelper>{ *this, *pickHelper5 }; pqPointPickingHelper* pickHelper6 = new pqPointPickingHelper(QKeySequence(tr("Ctrl+2")), true, this); pickHelper6->connect(this, SIGNAL(viewChanged(pqView*)), SLOT(setView(pqView*))); this->connect( pickHelper6, SIGNAL(pick(double, double, double)), SLOT(pickPoint2(double, double, double))); pqPointPickingVisibilityHelper<pqPointPickingHelper>{ *this, *pickHelper6 }; pqCoreUtilities::connect( this->widgetProxy(), vtkCommand::PropertyModifiedEvent, this, SLOT(updateInformationLabels())); this->updateInformationLabels(); } pqConePropertyWidget::~pqConePropertyWidget() = default; void pqConePropertyWidget::pick(double wx, double wy, double wz) { if (m_p->PickPoint1) { this->pickPoint1(wx, wy, wz); } else { this->pickPoint2(wx, wy, wz); } m_p->PickPoint1 = !m_p->PickPoint1; } void pqConePropertyWidget::pickPoint1(double wx, double wy, double wz) { double position[3] = { wx, wy, wz }; vtkSMNewWidgetRepresentationProxy* wdgProxy = this->widgetProxy(); vtkSMPropertyHelper(wdgProxy, "BottomPoint").Set(position, 3); wdgProxy->UpdateVTKObjects(); emit this->changeAvailable(); this->render(); } void pqConePropertyWidget::pickPoint2(double wx, double wy, double wz) { double position[3] = { wx, wy, wz }; vtkSMNewWidgetRepresentationProxy* wdgProxy = this->widgetProxy(); vtkSMPropertyHelper(wdgProxy, "TopPoint").Set(position, 3); wdgProxy->UpdateVTKObjects(); emit this->changeAvailable(); this->render(); } void pqConePropertyWidget::setCylindrical(bool isCylinder) { int cyl = isCylinder ? 1 : 0; vtkSMNewWidgetRepresentationProxy* wdgProxy = this->widgetProxy(); vtkSMPropertyHelper(wdgProxy, "Cylindrical").Set(&cyl, 1); if (isCylinder) { m_p->BottomRadiusName = m_p->Ui.labelRadius1->text().toStdString(); m_p->Ui.radius2->hide(); m_p->Ui.labelRadius2->hide(); m_p->Ui.labelRadius1->setText("Radius"); m_p->Ui.show3DWidget->setText("Show cylinder"); } else { m_p->Ui.radius2->show(); m_p->Ui.labelRadius2->show(); m_p->Ui.labelRadius1->setText(m_p->BottomRadiusName.c_str()); m_p->Ui.show3DWidget->setText("Show cone"); } wdgProxy->UpdateVTKObjects(); emit this->changeAvailable(); this->render(); } void pqConePropertyWidget::setForceCylindrical(bool isCylinder) { m_p->Ui.cylindrical->setChecked(isCylinder); if (isCylinder) { m_p->Ui.cylindrical->hide(); } else { m_p->Ui.cylindrical->show(); } this->setCylindrical(isCylinder); } void pqConePropertyWidget::updateInformationLabels() { Ui::ConePropertyWidget& ui = m_p->Ui; vtkVector3d p1, p2; vtkSMProxy* wproxy = this->widgetProxy(); vtkSMPropertyHelper(wproxy, "BottomPoint").Get(p1.GetData(), 3); vtkSMPropertyHelper(wproxy, "TopPoint").Get(p2.GetData(), 3); double distance = (p2 - p1).Norm(); ui.labelLength->setText(QString("<b>Length:</b> <i>%1</i> ").arg(distance)); } void pqConePropertyWidget::placeWidget() { // Nothing to do? }
35.156489
99
0.709478
[ "render", "model" ]
a9511bca5454700d607eaf2b8d059edcfc5c27cd
33,091
cpp
C++
libs/openFrameworks/gl/ofGLRenderer.cpp
creatologist/openFrameworks0084
aa74f188f105b62fbcecb7baf2b41d56d97cf7bc
[ "MIT" ]
3
2017-12-27T23:02:50.000Z
2018-10-14T00:50:49.000Z
libs/openFrameworks/gl/ofGLRenderer.cpp
creatologist/openFrameworks0084
aa74f188f105b62fbcecb7baf2b41d56d97cf7bc
[ "MIT" ]
null
null
null
libs/openFrameworks/gl/ofGLRenderer.cpp
creatologist/openFrameworks0084
aa74f188f105b62fbcecb7baf2b41d56d97cf7bc
[ "MIT" ]
null
null
null
#include "ofGLRenderer.h" #include "ofMesh.h" #include "ofPath.h" #include "ofGraphics.h" #include "ofAppRunner.h" #include "ofMesh.h" #include "of3dPrimitives.h" #include "ofBitmapFont.h" #include "ofGLUtils.h" #include "ofImage.h" #include "ofFbo.h" const string ofGLRenderer::TYPE="GL"; //---------------------------------------------------------- ofGLRenderer::ofGLRenderer(bool useShapeColor) :matrixStack(*ofGetWindowPtr()){ bBackgroundAuto = true; linePoints.resize(2); rectPoints.resize(4); triPoints.resize(3); fillFlag = OF_FILLED; bSmoothHinted = false; rectMode = OF_RECTMODE_CORNER; } //---------------------------------------------------------- void ofGLRenderer::update(){ matrixStack.setRenderSurface(*ofGetWindowPtr()); } //---------------------------------------------------------- void ofGLRenderer::draw(ofMesh & vertexData, bool useColors, bool useTextures, bool useNormals){ if(vertexData.getNumVertices()){ glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &vertexData.getVerticesPointer()->x); } if(vertexData.getNumNormals() && useNormals){ glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, sizeof(ofVec3f), &vertexData.getNormalsPointer()->x); } if(vertexData.getNumColors() && useColors){ glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), &vertexData.getColorsPointer()->r); } if(vertexData.getNumTexCoords() && useTextures){ glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, sizeof(ofVec2f), &vertexData.getTexCoordsPointer()->x); } if(vertexData.getNumIndices()){ #ifdef TARGET_OPENGLES glDrawElements(ofGetGLPrimitiveMode(vertexData.getMode()), vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer()); #else glDrawElements(ofGetGLPrimitiveMode(vertexData.getMode()), vertexData.getNumIndices(),GL_UNSIGNED_INT,vertexData.getIndexPointer()); #endif }else{ glDrawArrays(ofGetGLPrimitiveMode(vertexData.getMode()), 0, vertexData.getNumVertices()); } if(vertexData.getNumColors() && useColors){ glDisableClientState(GL_COLOR_ARRAY); } if(vertexData.getNumNormals() && useNormals){ glDisableClientState(GL_NORMAL_ARRAY); } if(vertexData.getNumTexCoords() && useTextures){ glDisableClientState(GL_TEXTURE_COORD_ARRAY); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofMesh & vertexData, ofPolyRenderMode renderType, bool useColors, bool useTextures, bool useNormals){ if (bSmoothHinted) startSmoothing(); #ifndef TARGET_OPENGLES glPushAttrib(GL_POLYGON_BIT); glPolygonMode(GL_FRONT_AND_BACK, ofGetGLPolyMode(renderType)); draw(vertexData,useColors,useTextures,useNormals); glPopAttrib(); //TODO: GLES doesnt support polygon mode, add renderType to gl renderer? #else if(vertexData.getNumVertices()){ glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), vertexData.getVerticesPointer()); } if(vertexData.getNumNormals() && useNormals){ glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, 0, vertexData.getNormalsPointer()); } if(vertexData.getNumColors() && useColors){ glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4,GL_FLOAT, sizeof(ofFloatColor), vertexData.getColorsPointer()); } if(vertexData.getNumTexCoords() && useTextures){ glEnableClientState(GL_TEXTURE_COORD_ARRAY); glTexCoordPointer(2, GL_FLOAT, 0, vertexData.getTexCoordsPointer()); } GLenum drawMode; switch(renderType){ case OF_MESH_POINTS: drawMode = GL_POINTS; break; case OF_MESH_WIREFRAME: drawMode = GL_LINES; break; case OF_MESH_FILL: drawMode = ofGetGLPrimitiveMode(vertexData.getMode()); break; default: drawMode = ofGetGLPrimitiveMode(vertexData.getMode()); break; } if(vertexData.getNumIndices()){ glDrawElements(drawMode, vertexData.getNumIndices(),GL_UNSIGNED_SHORT,vertexData.getIndexPointer()); }else{ glDrawArrays(drawMode, 0, vertexData.getNumVertices()); } if(vertexData.getNumColors() && useColors){ glDisableClientState(GL_COLOR_ARRAY); } if(vertexData.getNumNormals() && useNormals){ glDisableClientState(GL_NORMAL_ARRAY); } if(vertexData.getNumTexCoords() && useTextures){ glDisableClientState(GL_TEXTURE_COORD_ARRAY); } #endif if (bSmoothHinted) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::draw( of3dPrimitive& model, ofPolyRenderMode renderType) { // FIXME: we don't need this anymore since GL_NORMALIZE is enabled on lighting // leaving it comented just in case. it's also safe to remove this method completely // from the renderers hierarchy /*bool normalsEnabled = glIsEnabled( GL_NORMALIZE ); if(model.hasScaling() && model.hasNormalsEnabled()) { if(!normalsEnabled) glEnable( GL_NORMALIZE ); }*/ model.getMesh().draw(renderType); /*if(model.hasScaling() && model.hasNormalsEnabled()) { if(!normalsEnabled) glDisable( GL_NORMALIZE ); }*/ } //---------------------------------------------------------- void ofGLRenderer::draw(ofPolyline & poly){ if(!poly.getVertices().empty()) { // use smoothness, if requested: if (bSmoothHinted) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &poly.getVertices()[0].x); glDrawArrays(poly.isClosed()?GL_LINE_LOOP:GL_LINE_STRIP, 0, poly.size()); // use smoothness, if requested: if (bSmoothHinted) endSmoothing(); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofPath & shape){ ofColor prevColor; if(shape.getUseShapeColor()){ prevColor = ofGetStyle().color; } if(shape.isFilled()){ ofMesh & mesh = shape.getTessellation(); if(shape.getUseShapeColor()){ setColor( shape.getFillColor(),shape.getFillColor().a); } draw(mesh); } if(shape.hasOutline()){ float lineWidth = ofGetStyle().lineWidth; if(shape.getUseShapeColor()){ setColor( shape.getStrokeColor(), shape.getStrokeColor().a); } setLineWidth( shape.getStrokeWidth() ); vector<ofPolyline> & outlines = shape.getOutline(); for(int i=0; i<(int)outlines.size(); i++) draw(outlines[i]); setLineWidth(lineWidth); } if(shape.getUseShapeColor()){ setColor(prevColor); } } //---------------------------------------------------------- void ofGLRenderer::draw(ofImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning("ofGLRenderer") << "drawing an unallocated texture"; } } } //---------------------------------------------------------- void ofGLRenderer::draw(ofFloatImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning("ofGLRenderer") << "draw(): texture is not allocated"; } } } //---------------------------------------------------------- void ofGLRenderer::draw(ofShortImage & image, float x, float y, float z, float w, float h, float sx, float sy, float sw, float sh){ if(image.isUsingTexture()){ ofTexture& tex = image.getTextureReference(); if(tex.bAllocated()) { tex.drawSubsection(x,y,z,w,h,sx,sy,sw,sh); } else { ofLogWarning("ofGLRenderer") << "draw(): texture is not allocated"; } } } //---------------------------------------------------------- void ofGLRenderer::setCurrentFBO(ofFbo * fbo){ if(fbo!=NULL){ ofMatrix4x4 m; glGetFloatv(GL_PROJECTION_MATRIX,m.getPtr()); m = m*matrixStack.getOrientationMatrixInverse(); ofMatrixMode currentMode = matrixStack.getCurrentMatrixMode(); matrixStack.matrixMode(OF_MATRIX_PROJECTION); matrixStack.loadMatrix(m.getPtr()); matrixStack.setRenderSurface(*fbo); glMatrixMode(GL_PROJECTION); glLoadMatrixf(matrixStack.getProjectionMatrix().getPtr()); matrixMode(currentMode); }else{ matrixStack.setRenderSurface(*ofGetWindowPtr()); } } //---------------------------------------------------------- void ofGLRenderer::pushView() { getCurrentViewport(); ofMatrix4x4 m; ofMatrixMode matrixMode = matrixStack.getCurrentMatrixMode(); glGetFloatv(GL_PROJECTION_MATRIX,m.getPtr()); matrixStack.matrixMode(OF_MATRIX_PROJECTION); matrixStack.loadMatrix(m.getPtr()); glGetFloatv(GL_MODELVIEW_MATRIX,m.getPtr()); matrixStack.matrixMode(OF_MATRIX_MODELVIEW); matrixStack.loadMatrix(m.getPtr()); matrixStack.matrixMode(matrixMode); matrixStack.pushView(); } //---------------------------------------------------------- void ofGLRenderer::popView() { matrixStack.popView(); ofMatrix4x4 m; ofMatrixMode currentMode = matrixStack.getCurrentMatrixMode(); matrixMode(OF_MATRIX_PROJECTION); loadMatrix(matrixStack.getProjectionMatrix()); matrixMode(OF_MATRIX_MODELVIEW); loadMatrix(matrixStack.getModelViewMatrix()); matrixMode(currentMode); viewport(matrixStack.getCurrentViewport()); } //---------------------------------------------------------- void ofGLRenderer::viewport(ofRectangle viewport_){ viewport(viewport_.x, viewport_.y, viewport_.width, viewport_.height, isVFlipped()); } //---------------------------------------------------------- void ofGLRenderer::viewport(float x, float y, float width, float height, bool vflip) { matrixStack.viewport(x,y,width,height,vflip); ofRectangle nativeViewport = matrixStack.getNativeViewport(); glViewport(nativeViewport.x,nativeViewport.y,nativeViewport.width,nativeViewport.height); } //---------------------------------------------------------- ofRectangle ofGLRenderer::getCurrentViewport(){ getNativeViewport(); return matrixStack.getCurrentViewport(); } //---------------------------------------------------------- ofRectangle ofGLRenderer::getNativeViewport(){ GLint viewport[4]; // Where The Viewport Values Will Be Stored glGetIntegerv(GL_VIEWPORT, viewport); ofRectangle nativeViewport(viewport[0], viewport[1], viewport[2], viewport[3]); matrixStack.nativeViewport(nativeViewport); return nativeViewport; } //---------------------------------------------------------- int ofGLRenderer::getViewportWidth(){ return getCurrentViewport().width; } //---------------------------------------------------------- int ofGLRenderer::getViewportHeight(){ return getCurrentViewport().height; } //---------------------------------------------------------- void ofGLRenderer::setCoordHandedness(ofHandednessType handedness) { } //---------------------------------------------------------- ofHandednessType ofGLRenderer::getCoordHandedness() { return matrixStack.getHandedness(); } //---------------------------------------------------------- void ofGLRenderer::setOrientation(ofOrientation orientation, bool vFlip){ matrixStack.setOrientation(orientation,vFlip); } //---------------------------------------------------------- bool ofGLRenderer::isVFlipped() const{ return matrixStack.isVFlipped(); } //---------------------------------------------------------- bool ofGLRenderer::texturesNeedVFlip() const{ return matrixStack.customMatrixNeedsFlip(); } //---------------------------------------------------------- void ofGLRenderer::setupScreenPerspective(float width, float height, float fov, float nearDist, float farDist) { float viewW, viewH; if(width<0 || height<0){ ofRectangle currentViewport = getCurrentViewport(); viewW = currentViewport.width; viewH = currentViewport.height; }else{ viewW = width; viewH = height; } float eyeX = viewW / 2; float eyeY = viewH / 2; float halfFov = PI * fov / 360; float theTan = tanf(halfFov); float dist = eyeY / theTan; float aspect = (float) viewW / viewH; if(nearDist == 0) nearDist = dist / 10.0f; if(farDist == 0) farDist = dist * 10.0f; matrixMode(OF_MATRIX_PROJECTION); ofMatrix4x4 persp; persp.makePerspectiveMatrix(fov, aspect, nearDist, farDist); loadMatrix( persp ); matrixMode(OF_MATRIX_MODELVIEW); ofMatrix4x4 lookAt; lookAt.makeLookAtViewMatrix( ofVec3f(eyeX, eyeY, dist), ofVec3f(eyeX, eyeY, 0), ofVec3f(0, 1, 0) ); loadMatrix(lookAt); } //---------------------------------------------------------- void ofGLRenderer::setupScreenOrtho(float width, float height, float nearDist, float farDist) { float viewW, viewH; if(width<0 || height<0){ ofRectangle currentViewport = getCurrentViewport(); viewW = currentViewport.width; viewH = currentViewport.height; }else{ viewW = width; viewH = height; } ofMatrix4x4 ortho; ortho = ofMatrix4x4::newOrthoMatrix(0, viewW, 0, viewH, nearDist, farDist); matrixMode(OF_MATRIX_PROJECTION); loadMatrix(ortho); // make ortho our new projection matrix. matrixMode(OF_MATRIX_MODELVIEW); loadIdentityMatrix(); } //---------------------------------------------------------- //Resets openGL parameters back to OF defaults void ofGLRenderer::setupGraphicDefaults(){ glEnableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_COLOR_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } //---------------------------------------------------------- void ofGLRenderer::setupScreen(){ setupScreenPerspective(); // assume defaults } //---------------------------------------------------------- void ofGLRenderer::setCircleResolution(int res){ if((int)circlePolyline.size()!=res+1){ circlePolyline.clear(); circlePolyline.arc(0,0,0,1,1,0,360,res); circlePoints.resize(circlePolyline.size()); } } //our openGL wrappers //---------------------------------------------------------- void ofGLRenderer::pushMatrix(){ glPushMatrix(); } //---------------------------------------------------------- void ofGLRenderer::popMatrix(){ glPopMatrix(); } //---------------------------------------------------------- void ofGLRenderer::translate(const ofPoint& p){ glTranslatef(p.x, p.y, p.z); } //---------------------------------------------------------- void ofGLRenderer::translate(float x, float y, float z){ glTranslatef(x, y, z); } //---------------------------------------------------------- void ofGLRenderer::scale(float xAmnt, float yAmnt, float zAmnt){ glScalef(xAmnt, yAmnt, zAmnt); } //---------------------------------------------------------- void ofGLRenderer::rotate(float degrees, float vecX, float vecY, float vecZ){ glRotatef(degrees, vecX, vecY, vecZ); } //---------------------------------------------------------- void ofGLRenderer::rotateX(float degrees){ glRotatef(degrees, 1, 0, 0); } //---------------------------------------------------------- void ofGLRenderer::rotateY(float degrees){ glRotatef(degrees, 0, 1, 0); } //---------------------------------------------------------- void ofGLRenderer::rotateZ(float degrees){ glRotatef(degrees, 0, 0, 1); } //same as ofRotateZ //---------------------------------------------------------- void ofGLRenderer::rotate(float degrees){ glRotatef(degrees, 0, 0, 1); } //---------------------------------------------------------- void ofGLRenderer::matrixMode(ofMatrixMode mode){ glMatrixMode(GL_MODELVIEW+mode); matrixStack.matrixMode(mode); } //---------------------------------------------------------- void ofGLRenderer::loadIdentityMatrix (void){ loadMatrix(ofMatrix4x4::newIdentityMatrix()); } //---------------------------------------------------------- void ofGLRenderer::loadMatrix (const ofMatrix4x4 & m){ loadMatrix( m.getPtr() ); } //---------------------------------------------------------- void ofGLRenderer::loadMatrix (const float *m){ if(matrixStack.getCurrentMatrixMode()==OF_MATRIX_PROJECTION){ matrixStack.loadMatrix(m); glLoadMatrixf(matrixStack.getProjectionMatrix().getPtr()); }else{ glLoadMatrixf(m); } } //---------------------------------------------------------- /** @brief Queries the current OpenGL matrix state * @detail Returns the specified matrix as held by the renderer's current matrix stack. * * You can query one of the following: * * [OF_MATRIX_MODELVIEW | OF_MATRIX_PROJECTION | OF_MATRIX_TEXTURE] * * Each query will return the state of the matrix * as it was uploaded to the shader currently bound. * * @param matrixMode_ Which matrix mode to query */ ofMatrix4x4 ofGLRenderer::getCurrentMatrix(ofMatrixMode matrixMode_) const { ofMatrix4x4 mat; switch (matrixMode_) { case OF_MATRIX_MODELVIEW: glGetFloatv(GL_MODELVIEW_MATRIX, mat.getPtr()); break; case OF_MATRIX_PROJECTION: glGetFloatv(GL_PROJECTION_MATRIX, mat.getPtr()); break; case OF_MATRIX_TEXTURE: glGetFloatv(GL_TEXTURE_MATRIX, mat.getPtr()); break; default: ofLogWarning() << "Invalid getCurrentMatrix query"; mat = ofMatrix4x4(); break; } return mat; } //---------------------------------------------------------- ofMatrix4x4 ofGLRenderer::getCurrentOrientationMatrix() const { return matrixStack.getOrientationMatrix(); } //---------------------------------------------------------- void ofGLRenderer::multMatrix (const ofMatrix4x4 & m){ multMatrix( m.getPtr() ); } //---------------------------------------------------------- void ofGLRenderer::multMatrix (const float *m){ if(matrixStack.getCurrentMatrixMode()==OF_MATRIX_PROJECTION){ ofMatrix4x4 current; glGetFloatv(GL_PROJECTION_MATRIX,current.getPtr()); if(matrixStack.customMatrixNeedsFlip()){ current.scale(1,-1,1); } matrixStack.loadMatrix(current.getPtr()); matrixStack.multMatrix(m); glLoadMatrixf(matrixStack.getProjectionMatrix().getPtr()); }else{ glMultMatrixf(m); } } //---------------------------------------------------------- void ofGLRenderer::setColor(const ofColor & color){ setColor(color.r,color.g,color.b,color.a); } //---------------------------------------------------------- void ofGLRenderer::setColor(const ofColor & color, int _a){ setColor(color.r,color.g,color.b,_a); } //---------------------------------------------------------- void ofGLRenderer::setColor(int _r, int _g, int _b){ glColor4f(_r/255.f,_g/255.f,_b/255.f,1.f); } //---------------------------------------------------------- void ofGLRenderer::setColor(int _r, int _g, int _b, int _a){ glColor4f(_r/255.f,_g/255.f,_b/255.f,_a/255.f); } //---------------------------------------------------------- void ofGLRenderer::setColor(int gray){ setColor(gray, gray, gray); } //---------------------------------------------------------- void ofGLRenderer::setHexColor(int hexColor){ int r = (hexColor >> 16) & 0xff; int g = (hexColor >> 8) & 0xff; int b = (hexColor >> 0) & 0xff; setColor(r,g,b); } //---------------------------------------------------------- void ofGLRenderer::clear(float r, float g, float b, float a) { glClearColor(r / 255., g / 255., b / 255., a / 255.); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //---------------------------------------------------------- void ofGLRenderer::clear(float brightness, float a) { clear(brightness, brightness, brightness, a); } //---------------------------------------------------------- void ofGLRenderer::clearAlpha() { glColorMask(0, 0, 0, 1); glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glColorMask(1, 1, 1, 1); } //---------------------------------------------------------- void ofGLRenderer::setBackgroundAuto(bool bAuto){ bBackgroundAuto = bAuto; } //---------------------------------------------------------- bool ofGLRenderer::bClearBg(){ return bBackgroundAuto; } //---------------------------------------------------------- ofFloatColor & ofGLRenderer::getBgColor(){ return bgColor; } //---------------------------------------------------------- void ofGLRenderer::background(const ofColor & c){ bgColor = c; glClearColor(bgColor[0],bgColor[1],bgColor[2], bgColor[3]); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } //---------------------------------------------------------- void ofGLRenderer::background(float brightness) { background(brightness); } //---------------------------------------------------------- void ofGLRenderer::background(int hexColor, float _a){ background ( (hexColor >> 16) & 0xff, (hexColor >> 8) & 0xff, (hexColor >> 0) & 0xff, _a); } //---------------------------------------------------------- void ofGLRenderer::background(int r, int g, int b, int a){ background(ofColor(r,g,b,a)); } //---------------------------------------------------------- void ofGLRenderer::setFillMode(ofFillFlag fill){ fillFlag = fill; } //---------------------------------------------------------- ofFillFlag ofGLRenderer::getFillMode(){ return fillFlag; } //---------------------------------------------------------- void ofGLRenderer::setRectMode(ofRectMode mode){ rectMode = mode; } //---------------------------------------------------------- ofRectMode ofGLRenderer::getRectMode(){ return rectMode; } //---------------------------------------------------------- void ofGLRenderer::setLineWidth(float lineWidth){ glLineWidth(lineWidth); } //---------------------------------------------------------- void ofGLRenderer::setDepthTest(bool depthTest){ if(depthTest) { glEnable(GL_DEPTH_TEST); } else { glDisable(GL_DEPTH_TEST); } } //---------------------------------------------------------- void ofGLRenderer::setLineSmoothing(bool smooth){ bSmoothHinted = smooth; } //---------------------------------------------------------- void ofGLRenderer::startSmoothing(){ #ifndef TARGET_OPENGLES glPushAttrib(GL_COLOR_BUFFER_BIT | GL_ENABLE_BIT); #endif glHint(GL_LINE_SMOOTH_HINT, GL_NICEST); glEnable(GL_LINE_SMOOTH); //why do we need this? glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } //---------------------------------------------------------- void ofGLRenderer::endSmoothing(){ #ifndef TARGET_OPENGLES glPopAttrib(); #endif } //---------------------------------------------------------- void ofGLRenderer::setBlendMode(ofBlendMode blendMode){ switch (blendMode){ case OF_BLENDMODE_DISABLED: glDisable(GL_BLEND); break; case OF_BLENDMODE_ALPHA:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); break; } case OF_BLENDMODE_ADD:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; } case OF_BLENDMODE_MULTIPLY:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_DST_COLOR, GL_ONE_MINUS_SRC_ALPHA /* GL_ZERO or GL_ONE_MINUS_SRC_ALPHA */); break; } case OF_BLENDMODE_SCREEN:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_ADD); #endif glBlendFunc(GL_ONE_MINUS_DST_COLOR, GL_ONE); break; } case OF_BLENDMODE_SUBTRACT:{ glEnable(GL_BLEND); #ifndef TARGET_OPENGLES glBlendEquation(GL_FUNC_REVERSE_SUBTRACT); #else ofLogWarning("ofGLRenderer") << "OF_BLENDMODE_SUBTRACT not currently supported on OpenGL ES"; #endif glBlendFunc(GL_SRC_ALPHA, GL_ONE); break; } default: break; } } //---------------------------------------------------------- void ofGLRenderer::enablePointSprites(){ #ifdef TARGET_OPENGLES glEnable(GL_POINT_SPRITE_OES); glTexEnvi(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE); // does look like this needs to be enabled in ES because // it is always eneabled... //glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #else glEnable(GL_POINT_SPRITE); glTexEnvi(GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE); glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); #endif } //---------------------------------------------------------- void ofGLRenderer::disablePointSprites(){ #ifdef TARGET_OPENGLES glDisable(GL_POINT_SPRITE_OES); #else glDisable(GL_POINT_SPRITE); #endif } //---------------------------------------------------------- void ofGLRenderer::enableAntiAliasing(){ glEnable(GL_MULTISAMPLE); } //---------------------------------------------------------- void ofGLRenderer::disableAntiAliasing(){ glDisable(GL_MULTISAMPLE); } //---------------------------------------------------------- void ofGLRenderer::drawLine(float x1, float y1, float z1, float x2, float y2, float z2){ linePoints[0].set(x1,y1,z1); linePoints[1].set(x2,y2,z2); // use smoothness, if requested: if (bSmoothHinted) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &linePoints[0].x); glDrawArrays(GL_LINES, 0, 2); // use smoothness, if requested: if (bSmoothHinted) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawRectangle(float x, float y, float z,float w, float h){ if (rectMode == OF_RECTMODE_CORNER){ rectPoints[0].set(x,y,z); rectPoints[1].set(x+w, y, z); rectPoints[2].set(x+w, y+h, z); rectPoints[3].set(x, y+h, z); }else{ rectPoints[0].set(x-w/2.0f, y-h/2.0f, z); rectPoints[1].set(x+w/2.0f, y-h/2.0f, z); rectPoints[2].set(x+w/2.0f, y+h/2.0f, z); rectPoints[3].set(x-w/2.0f, y+h/2.0f, z); } // use smoothness, if requested: if (bSmoothHinted && fillFlag == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &rectPoints[0].x); glDrawArrays((fillFlag == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_LOOP, 0, 4); // use smoothness, if requested: if (bSmoothHinted && fillFlag == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawTriangle(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3){ triPoints[0].set(x1,y1,z1); triPoints[1].set(x2,y2,z2); triPoints[2].set(x3,y3,z3); // use smoothness, if requested: if (bSmoothHinted && fillFlag == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &triPoints[0].x); glDrawArrays((fillFlag == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_LOOP, 0, 3); // use smoothness, if requested: if (bSmoothHinted && fillFlag == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawCircle(float x, float y, float z, float radius){ vector<ofPoint> & circleCache = circlePolyline.getVertices(); for(int i=0;i<(int)circleCache.size();i++){ circlePoints[i].set(radius*circleCache[i].x+x,radius*circleCache[i].y+y,z); } // use smoothness, if requested: if (bSmoothHinted && fillFlag == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &circlePoints[0].x); glDrawArrays((fillFlag == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_STRIP, 0, circlePoints.size()); // use smoothness, if requested: if (bSmoothHinted && fillFlag == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawEllipse(float x, float y, float z, float width, float height){ float radiusX = width*0.5; float radiusY = height*0.5; vector<ofPoint> & circleCache = circlePolyline.getVertices(); for(int i=0;i<(int)circleCache.size();i++){ circlePoints[i].set(radiusX*circlePolyline[i].x+x,radiusY*circlePolyline[i].y+y,z); } // use smoothness, if requested: if (bSmoothHinted && fillFlag == OF_OUTLINE) startSmoothing(); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(ofVec3f), &circlePoints[0].x); glDrawArrays((fillFlag == OF_FILLED) ? GL_TRIANGLE_FAN : GL_LINE_STRIP, 0, circlePoints.size()); // use smoothness, if requested: if (bSmoothHinted && fillFlag == OF_OUTLINE) endSmoothing(); } //---------------------------------------------------------- void ofGLRenderer::drawString(string textString, float x, float y, float z, ofDrawBitmapMode mode){ // remember the current blend mode so that we can restore it at the end of this method. GLint blend_src, blend_dst; glGetIntegerv( GL_BLEND_SRC, &blend_src ); glGetIntegerv( GL_BLEND_DST, &blend_dst ); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); int len = (int)textString.length(); float fontSize = 8.0f; float lineHeight = fontSize*1.7f; int newLineDirection = 1.0f; if(!ofIsVFlipped()){ newLineDirection = -1; // this would align multiline texts to the last line when vflip is disabled //int lines = ofStringTimesInString(textString,"\n"); //y = lines*lineHeight; } float sx = 0; float sy = -fontSize; /////////////////////////// // APPLY TRANSFORM / VIEW /////////////////////////// // bool hasModelView = false; bool hasProjection = false; bool hasViewport = false; ofRectangle rViewport; switch (mode) { case OF_BITMAPMODE_SIMPLE: sx += x; sy += y; break; case OF_BITMAPMODE_SCREEN: hasViewport = true; pushView(); rViewport = ofGetWindowRect(); viewport(rViewport); matrixMode(OF_MATRIX_PROJECTION); loadIdentityMatrix(); matrixMode(OF_MATRIX_MODELVIEW); loadIdentityMatrix(); translate(-1, 1, 0); scale(2/rViewport.width, -2/rViewport.height, 1); translate(x, y, 0); break; case OF_BITMAPMODE_VIEWPORT: rViewport = getCurrentViewport(); hasProjection = true; matrixMode(OF_MATRIX_PROJECTION); pushMatrix(); loadIdentityMatrix(); hasModelView = true; matrixMode(OF_MATRIX_MODELVIEW); pushMatrix(); loadIdentityMatrix(); translate(-1, 1, 0); scale(2/rViewport.width, -2/rViewport.height, 1); translate(x, y, 0); break; case OF_BITMAPMODE_MODEL: hasModelView = true; matrixMode(OF_MATRIX_MODELVIEW); pushMatrix(); translate(x, y, z); break; case OF_BITMAPMODE_MODEL_BILLBOARD: { //our aim here is to draw to screen //at the viewport position related //to the world position x,y,z // tig: we want to get the signed normalised screen coordinates (-1,+1) of our point (x,y,z) // that's projection * modelview * point in GLSL multiplication order // then doing the good old (v + 1.0) / 2. to get unsigned normalized screen (0,1) coordinates. // we then multiply x by width and y by height to get window coordinates. // previous implementations used gluProject, which made it incompatible with GLES (and the future) // https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/gluProject.3.html // // this could probably be backported to the GL2 Renderer =) rViewport = getCurrentViewport(); ofMatrix4x4 modelview, projection; glGetFloatv(GL_MODELVIEW_MATRIX, modelview.getPtr()); glGetFloatv(GL_PROJECTION_MATRIX, projection.getPtr()); ofVec3f dScreen = ofVec3f(x,y,z) * modelview * projection * matrixStack.getOrientationMatrixInverse(); dScreen += ofVec3f(1.0) ; dScreen *= 0.5; dScreen.x += rViewport.x; dScreen.x *= rViewport.width; dScreen.y += rViewport.y; dScreen.y *= rViewport.height; if (dScreen.z >= 1) return; hasProjection = true; matrixMode(OF_MATRIX_PROJECTION); pushMatrix(); loadIdentityMatrix(); hasModelView = true; matrixMode(OF_MATRIX_MODELVIEW); pushMatrix(); loadIdentityMatrix(); translate(-1, -1, 0); scale(2/rViewport.width, 2/rViewport.height, 1); translate(dScreen.x, dScreen.y, 0); } break; default: break; } // /////////////////////////// // tig: we switch over to our built-in bitmapstring shader // to render text. This gives us more flexibility & control // and does not mess/interfere with client side shaders. // (c) enable texture once before we start drawing each char (no point turning it on and off constantly) //We do this because its way faster ofDrawBitmapCharacterStart(textString.size()); int column = 0; for(int c = 0; c < len; c++){ if(textString[c] == '\n'){ sy += lineHeight*newLineDirection; if(mode == OF_BITMAPMODE_SIMPLE) { sx = x; } else { sx = 0; } column = 0; } else if (textString[c] == '\t'){ //move the cursor to the position of the next tab //8 is the default tab spacing in osx terminal and windows command line int out = column + 8 - (column % 8); sx += fontSize * (out-column); column = out; } else if (textString[c] >= 32){ // < 32 = control characters - don't draw // solves a bug with control characters // getting drawn when they ought to not be ofDrawBitmapCharacter(textString[c], (int)sx, (int)sy); sx += fontSize; column++; } } //We do this because its way faster ofDrawBitmapCharacterEnd(); if (hasModelView) popMatrix(); if (hasProjection) { matrixMode(OF_MATRIX_PROJECTION); popMatrix(); matrixMode(OF_MATRIX_MODELVIEW); } if (hasViewport) popView(); // restore blendmode glBlendFunc(blend_src, blend_dst); } void ofGLRenderer::enableTextureTarget(int textureTarget){ glEnable(textureTarget); } void ofGLRenderer::disableTextureTarget(int textureTarget){ glDisable(textureTarget); }
28.900437
136
0.618174
[ "mesh", "render", "shape", "vector", "model", "transform" ]
a953e3c6704f29e717aab1146e4e9db1b4aeca84
1,227
hpp
C++
third_party/boost/simd/function/maxnum.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
third_party/boost/simd/function/maxnum.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/function/maxnum.hpp
SylvainCorlay/pythran
908ec070d837baf77d828d01c3e35e2f4bfa2bfa
[ "BSD-3-Clause" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_MAXNUM_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_MAXNUM_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-ieee This function object returns the largest of two floating point arguments, treating NaNs as missing data (between a NaN and a numeric value, the numeric value is chosen). @par Header <boost/simd/function/maxnum.hpp> @par Decorators - std_ for floating entries calls the stdlibc++ function std::fmax. @see max, maxnummag, maxmag @par Example: @snippet maxnum.cpp maxnum @par Possible output: @snippet maxnum.txt maxnum **/ Value maxnum(Value const& x, Value const& y); } } #endif #include <boost/simd/function/scalar/maxnum.hpp> #include <boost/simd/function/simd/maxnum.hpp> #endif
25.040816
100
0.603097
[ "object" ]
a9590506db4542b7b3d87550b8fa3d2d478b5cea
1,850
cpp
C++
cpp_module_08/ex01/span.cpp
AbderrSfa/cpp_modules
2465e31853af87f9bf9faba57ac0470b43918607
[ "Apache-2.0" ]
1
2021-11-05T13:46:36.000Z
2021-11-05T13:46:36.000Z
cpp_module_08/ex01/span.cpp
AbderrSfa/cpp_modules
2465e31853af87f9bf9faba57ac0470b43918607
[ "Apache-2.0" ]
null
null
null
cpp_module_08/ex01/span.cpp
AbderrSfa/cpp_modules
2465e31853af87f9bf9faba57ac0470b43918607
[ "Apache-2.0" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* span.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: asfaihi <asfaihi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/25 13:18:08 by asfaihi #+# #+# */ /* Updated: 2021/11/27 09:54:08 by asfaihi ### ########.fr */ /* */ /* ************************************************************************** */ #include "span.hpp" Span::Span(unsigned int N) : _N(N) {} Span::Span(Span const & src) { *this = src; } Span::~Span() {} Span & Span::operator=(Span const & rhs) { if (this == &rhs) return (*this); this->_N = rhs._N; this->_vect = rhs._vect; return (*this); } void Span::addNumber(int num) { if (this->_vect.size() == this->_N) throw ContainerFull(); this->_vect.push_back(num); } int Span::shortestSpan( void ) { if (this->_vect.size() <= 1) throw NotEnoughNumbers(); std::vector<int> sorted = this->_vect; std::sort(sorted.begin(), sorted.end()); int ret = INT_MAX; for (size_t i = 0; i < sorted.size() - 1; i++) if (sorted.at(i + 1) - sorted.at(i) < ret) ret = sorted.at(i + 1) - sorted.at(i); return (ret); } int Span::longestSpan( void ) { if (this->_vect.size() <= 1) throw NotEnoughNumbers(); return (*max_element(this->_vect.begin(), this->_vect.end()) - *min_element(this->_vect.begin(), this->_vect.end())); }
35.576923
80
0.368108
[ "vector" ]
a95d9d9975e950cf03cd7de6644c46432a121cb6
116,407
cpp
C++
src/kits/tracker/ContainerWindow.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
1
2021-08-31T01:47:13.000Z
2021-08-31T01:47:13.000Z
src/kits/tracker/ContainerWindow.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
null
null
null
src/kits/tracker/ContainerWindow.cpp
axeld/haiku
e3becd53eef5c093ee8c8f32bab51d40b0f2b8d4
[ "MIT" ]
3
2018-12-17T13:07:38.000Z
2021-09-08T13:07:31.000Z
/* Open Tracker License Terms and Conditions Copyright (c) 1991-2000, Be Incorporated. 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 applies to all licensees and 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 TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL BE INCORPORATED 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. Except as contained in this notice, the name of Be Incorporated shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Be Incorporated. Tracker(TM), Be(R), BeOS(R), and BeIA(TM) are trademarks or registered trademarks of Be Incorporated in the United States and other countries. Other brand product names are registered trademarks or trademarks of their respective holders. All rights reserved. */ #include "ContainerWindow.h" #include <Alert.h> #include <Application.h> #include <AppFileInfo.h> #include <Catalog.h> #include <ControlLook.h> #include <Debug.h> #include <Directory.h> #include <Entry.h> #include <FindDirectory.h> #include <GridView.h> #include <GroupLayout.h> #include <Keymap.h> #include <Locale.h> #include <MenuItem.h> #include <MenuBar.h> #include <NodeMonitor.h> #include <Path.h> #include <PopUpMenu.h> #include <Roster.h> #include <Screen.h> #include <UnicodeChar.h> #include <Volume.h> #include <VolumeRoster.h> #include <WindowPrivate.h> #include <fs_attr.h> #include <image.h> #include <strings.h> #include <stdlib.h> #include <algorithm> #include <memory> #include "Attributes.h" #include "AttributeStream.h" #include "AutoLock.h" #include "BackgroundImage.h" #include "Commands.h" #include "CountView.h" #include "DeskWindow.h" #include "FavoritesMenu.h" #include "FindPanel.h" #include "FSClipboard.h" #include "FSUndoRedo.h" #include "FSUtils.h" #include "IconMenuItem.h" #include "OpenWithWindow.h" #include "MimeTypes.h" #include "MountMenu.h" #include "Navigator.h" #include "NavMenu.h" #include "PoseView.h" #include "QueryContainerWindow.h" #include "SelectionWindow.h" #include "TitleView.h" #include "Tracker.h" #include "TrackerSettings.h" #include "Thread.h" #include "TemplatesMenu.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ContainerWindow" #ifdef _IMPEXP_BE _IMPEXP_BE #endif void do_minimize_team(BRect zoomRect, team_id team, bool zoom); // Amount you have to move the mouse before a drag starts const float kDragSlop = 3.0f; namespace BPrivate { class DraggableContainerIcon : public BView { public: DraggableContainerIcon(); virtual void MouseDown(BPoint where); virtual void MouseUp(BPoint); virtual void MouseMoved(BPoint point, uint32, const BMessage*); virtual void Draw(BRect updateRect); private: uint32 fDragButton; BPoint fClickPoint; bool fDragStarted; }; } // namespace BPrivate struct AddOneAddonParams { BObjectList<BMenuItem>* primaryList; BObjectList<BMenuItem>* secondaryList; }; struct StaggerOneParams { bool rectFromParent; }; const int32 kWindowStaggerBy = 17; BRect BContainerWindow::sNewWindRect(85, 50, 548, 280); LockingList<AddonShortcut>* BContainerWindow::fAddonsList = new LockingList<struct AddonShortcut>(10, true); namespace BPrivate { filter_result ActivateWindowFilter(BMessage*, BHandler** target, BMessageFilter*) { BView* view = dynamic_cast<BView*>(*target); // activate the window if no PoseView or DraggableContainerIcon had been // pressed (those will activate the window themselves, if necessary) if (view != NULL && dynamic_cast<BPoseView*>(view) == NULL && dynamic_cast<DraggableContainerIcon*>(view) == NULL && view->Window() != NULL) { view->Window()->Activate(true); } return B_DISPATCH_MESSAGE; } int CompareLabels(const BMenuItem* item1, const BMenuItem* item2) { return strcasecmp(item1->Label(), item2->Label()); } } // namespace BPrivate static bool AddOneAddon(const Model* model, const char* name, uint32 shortcut, uint32 modifiers, bool primary, void* context) { AddOneAddonParams* params = (AddOneAddonParams*)context; BMessage* message = new BMessage(kLoadAddOn); message->AddRef("refs", model->EntryRef()); ModelMenuItem* item = new ModelMenuItem(model, name, message, (char)shortcut, modifiers); if (primary) params->primaryList->AddItem(item); else params->secondaryList->AddItem(item); return false; } static int32 AddOnThread(BMessage* refsMessage, entry_ref addonRef, entry_ref directoryRef) { std::auto_ptr<BMessage> refsMessagePtr(refsMessage); BEntry entry(&addonRef); BPath path; status_t result = entry.InitCheck(); if (result == B_OK) result = entry.GetPath(&path); if (result == B_OK) { image_id addonImage = load_add_on(path.Path()); if (addonImage >= 0) { void (*processRefs)(entry_ref, BMessage*, void*); result = get_image_symbol(addonImage, "process_refs", 2, (void**)&processRefs); if (result >= 0) { // call add-on code (*processRefs)(directoryRef, refsMessagePtr.get(), NULL); unload_add_on(addonImage); return B_OK; } else PRINT(("couldn't find process_refs\n")); unload_add_on(addonImage); } else result = addonImage; } BString buffer(B_TRANSLATE("Error %error loading Add-On %name.")); buffer.ReplaceFirst("%error", strerror(result)); buffer.ReplaceFirst("%name", addonRef.name); BAlert* alert = new BAlert("", buffer.String(), B_TRANSLATE("Cancel"), 0, 0, B_WIDTH_AS_USUAL, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); return result; } static bool NodeHasSavedState(const BNode* node) { attr_info info; return node->GetAttrInfo(kAttrWindowFrame, &info) == B_OK; } static bool OffsetFrameOne(const char* DEBUG_ONLY(name), uint32, off_t, void* castToRect, void* castToParams) { ASSERT(strcmp(name, kAttrWindowFrame) == 0); StaggerOneParams* params = (StaggerOneParams*)castToParams; if (!params->rectFromParent) return false; if (!castToRect) return false; ((BRect*)castToRect)->OffsetBy(kWindowStaggerBy, kWindowStaggerBy); return true; } static void AddMimeTypeString(BStringList& list, Model* model) { if (model == NULL) return; const char* modelMimeType = model->MimeType(); if (modelMimeType == NULL || *modelMimeType == '\0') return; BString type = BString(modelMimeType); if (list.HasString(type, true)) return; list.Add(type); } // #pragma mark - DraggableContainerIcon DraggableContainerIcon::DraggableContainerIcon() : BView("DraggableContainerIcon", B_WILL_DRAW), fDragButton(0), fDragStarted(false) { } void DraggableContainerIcon::MouseDown(BPoint where) { // we only like container windows BContainerWindow* window = dynamic_cast<BContainerWindow*>(Window()); ThrowOnAssert(window != NULL); // we don't like the Trash icon (because it cannot be moved) if (window->IsTrash() || window->IsPrintersDir()) return; uint32 buttons; window->CurrentMessage()->FindInt32("buttons", (int32*)&buttons); if (IconCache::sIconCache->IconHitTest(where, window->TargetModel(), kNormalIcon, B_MINI_ICON)) { // The click hit the icon, initiate a drag fDragButton = buttons & (B_PRIMARY_MOUSE_BUTTON | B_SECONDARY_MOUSE_BUTTON); fDragStarted = false; fClickPoint = where; } else fDragButton = 0; if (!fDragButton) Window()->Activate(true); } void DraggableContainerIcon::MouseUp(BPoint) { if (!fDragStarted) Window()->Activate(true); fDragButton = 0; fDragStarted = false; } void DraggableContainerIcon::MouseMoved(BPoint where, uint32, const BMessage*) { if (fDragButton == 0 || fDragStarted || (abs((int32)(where.x - fClickPoint.x)) <= kDragSlop && abs((int32)(where.y - fClickPoint.y)) <= kDragSlop)) return; BContainerWindow* window = static_cast<BContainerWindow*>(Window()); // we can only get here in a BContainerWindow Model* model = window->TargetModel(); // Find the required height BFont font; GetFont(&font); font_height fontHeight; font.GetHeight(&fontHeight); float height = ceilf(fontHeight.ascent + fontHeight.descent + fontHeight.leading + 2 + Bounds().Height() + 8); BRect rect(0, 0, std::max(Bounds().Width(), font.StringWidth(model->Name()) + 4), height); BBitmap* dragBitmap = new BBitmap(rect, B_RGBA32, true); dragBitmap->Lock(); BView* view = new BView(dragBitmap->Bounds(), "", B_FOLLOW_NONE, 0); dragBitmap->AddChild(view); view->SetOrigin(0, 0); BRect clipRect(view->Bounds()); BRegion newClip; newClip.Set(clipRect); view->ConstrainClippingRegion(&newClip); // Transparent draw magic view->SetHighColor(0, 0, 0, 0); view->FillRect(view->Bounds()); view->SetDrawingMode(B_OP_ALPHA); rgb_color textColor = ui_color(B_PANEL_TEXT_COLOR); textColor.alpha = 128; // set the level of transparency by value view->SetHighColor(textColor); view->SetBlendingMode(B_CONSTANT_ALPHA, B_ALPHA_COMPOSITE); // Draw the icon float hIconOffset = (rect.Width() - Bounds().Width()) / 2; IconCache::sIconCache->Draw(model, view, BPoint(hIconOffset, 0), kNormalIcon, B_MINI_ICON, true); // See if we need to truncate the string BString nameString = model->Name(); if (view->StringWidth(model->Name()) > rect.Width()) view->TruncateString(&nameString, B_TRUNCATE_END, rect.Width() - 5); // Draw the label float leftText = (view->StringWidth(nameString.String()) - Bounds().Width()) / 2; view->MovePenTo(BPoint(hIconOffset - leftText + 2, Bounds().Height() + (fontHeight.ascent + 2))); view->DrawString(nameString.String()); view->Sync(); dragBitmap->Unlock(); BMessage message(B_SIMPLE_DATA); message.AddRef("refs", model->EntryRef()); message.AddPoint("click_pt", fClickPoint); BPoint tmpLoc; uint32 button; GetMouse(&tmpLoc, &button); if (button) message.AddInt32("buttons", (int32)button); if ((button & B_PRIMARY_MOUSE_BUTTON) != 0) { // add an action specifier to the message, so that it is not copied message.AddInt32("be:actions", (modifiers() & B_OPTION_KEY) != 0 ? B_COPY_TARGET : B_MOVE_TARGET); } fDragStarted = true; fDragButton = 0; DragMessage(&message, dragBitmap, B_OP_ALPHA, BPoint(fClickPoint.x + hIconOffset, fClickPoint.y), this); } void DraggableContainerIcon::Draw(BRect updateRect) { BContainerWindow* window = dynamic_cast<BContainerWindow*>(Window()); ThrowOnAssert(window != NULL); BRect rect(Bounds()); rgb_color base = ui_color(B_MENU_BACKGROUND_COLOR); be_control_look->DrawBorder(this, rect, updateRect, base, B_PLAIN_BORDER, 0, BControlLook::B_BOTTOM_BORDER); be_control_look->DrawMenuBarBackground(this, rect, updateRect, base, 0, BControlLook::B_ALL_BORDERS & ~BControlLook::B_LEFT_BORDER); // Draw the icon, straddling the border SetDrawingMode(B_OP_ALPHA); SetBlendingMode(B_PIXEL_ALPHA, B_ALPHA_OVERLAY); float iconOffsetX = (Bounds().Width() - B_MINI_ICON) / 2; float iconOffsetY = (Bounds().Height() - B_MINI_ICON) / 2; IconCache::sIconCache->Draw(window->TargetModel(), this, BPoint(iconOffsetX, iconOffsetY), kNormalIcon, B_MINI_ICON, true); } // #pragma mark - BContainerWindow BContainerWindow::BContainerWindow(LockingList<BWindow>* list, uint32 containerWindowFlags, window_look look, window_feel feel, uint32 flags, uint32 workspace, bool useLayouts, bool isDeskWindow) : BWindow(InitialWindowRect(feel), "TrackerWindow", look, feel, flags, workspace), fUseLayouts(useLayouts), fMenuContainer(NULL), fPoseContainer(NULL), fBorderedView(NULL), fVScrollBarContainer(NULL), fCountContainer(NULL), fFileContextMenu(NULL), fWindowContextMenu(NULL), fDropContextMenu(NULL), fVolumeContextMenu(NULL), fTrashContextMenu(NULL), fDragContextMenu(NULL), fMoveToItem(NULL), fCopyToItem(NULL), fCreateLinkItem(NULL), fOpenWithItem(NULL), fNavigationItem(NULL), fMenuBar(NULL), fDraggableIcon(NULL), fNavigator(NULL), fPoseView(NULL), fWindowList(list), fAttrMenu(NULL), fWindowMenu(NULL), fFileMenu(NULL), fArrangeByMenu(NULL), fSelectionWindow(NULL), fTaskLoop(NULL), fIsTrash(false), fInTrash(false), fIsPrinters(false), fIsDesktop(isDeskWindow), fContainerWindowFlags(containerWindowFlags), fBackgroundImage(NULL), fSavedZoomRect(0, 0, -1, -1), fContextMenu(NULL), fDragMessage(NULL), fCachedTypesList(NULL), fStateNeedsSaving(false), fSaveStateIsEnabled(true), fIsWatchingPath(false) { InitIconPreloader(); if (list != NULL) { ASSERT(list->IsLocked()); list->AddItem(this); } if (useLayouts) { SetFlags(Flags() | B_AUTO_UPDATE_SIZE_LIMITS); fRootLayout = new BGroupLayout(B_VERTICAL, 0); fRootLayout->SetInsets(0); SetLayout(fRootLayout); fRootLayout->Owner()->AdoptSystemColors(); if (!fIsDesktop) { fMenuContainer = new BGroupView(B_HORIZONTAL, 0); fRootLayout->AddView(fMenuContainer); fPoseContainer = new BGridView(0.0, 0.0); fRootLayout->AddView(fPoseContainer); fBorderedView = new BorderedView; fPoseContainer->GridLayout()->AddView(fBorderedView, 0, 1); fCountContainer = new BGroupView(B_HORIZONTAL, 0); fPoseContainer->GridLayout()->AddView(fCountContainer, 0, 2); } } AddCommonFilter(new BMessageFilter(B_MOUSE_DOWN, ActivateWindowFilter)); Run(); // watch out for settings changes TTracker* tracker = dynamic_cast<TTracker*>(be_app); if (tracker != NULL && tracker->Lock()) { tracker->StartWatching(this, kWindowsShowFullPathChanged); tracker->StartWatching(this, kSingleWindowBrowseChanged); tracker->StartWatching(this, kShowNavigatorChanged); tracker->StartWatching(this, kDontMoveFilesToTrashChanged); tracker->Unlock(); } // ToDo: remove me once we have undo/redo menu items // (that is, move them to AddShortcuts()) AddShortcut('Z', B_COMMAND_KEY, new BMessage(B_UNDO), this); AddShortcut('Z', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(B_REDO), this); } BContainerWindow::~BContainerWindow() { ASSERT(IsLocked()); // stop the watchers TTracker* tracker = dynamic_cast<TTracker*>(be_app); if (tracker != NULL && tracker->Lock()) { tracker->StopWatching(this, kWindowsShowFullPathChanged); tracker->StopWatching(this, kSingleWindowBrowseChanged); tracker->StopWatching(this, kShowNavigatorChanged); tracker->StopWatching(this, kDontMoveFilesToTrashChanged); tracker->Unlock(); } delete fTaskLoop; delete fBackgroundImage; delete fDragMessage; delete fCachedTypesList; if (fSelectionWindow != NULL && fSelectionWindow->Lock()) fSelectionWindow->Quit(); } BRect BContainerWindow::InitialWindowRect(window_feel feel) { if (feel != kDesktopWindowFeel) return sNewWindRect; // do not offset desktop window BRect result = sNewWindRect; result.OffsetTo(0, 0); return result; } void BContainerWindow::Minimize(bool minimize) { if (minimize && (modifiers() & B_OPTION_KEY) != 0) do_minimize_team(BRect(0, 0, 0, 0), be_app->Team(), true); else _inherited::Minimize(minimize); } bool BContainerWindow::QuitRequested() { // this is a response to the DeskBar sending us a B_QUIT, when it really // means to say close all your windows. It might be better to have it // send a kCloseAllWindows message and have windowless apps stay running, // which is what we will do for the Tracker if (CurrentMessage() != NULL && ((CurrentMessage()->FindInt32("modifiers") & B_CONTROL_KEY)) != 0) { be_app->PostMessage(kCloseAllWindows); } Hide(); // this will close the window instantly, even if // the file system is very busy right now return true; } void BContainerWindow::Quit() { // get rid of context menus if (fNavigationItem) { BMenu* menu = fNavigationItem->Menu(); if (menu != NULL) menu->RemoveItem(fNavigationItem); delete fNavigationItem; fNavigationItem = NULL; } if (fOpenWithItem != NULL && fOpenWithItem->Menu() == NULL) { delete fOpenWithItem; fOpenWithItem = NULL; } if (fMoveToItem != NULL && fMoveToItem->Menu() == NULL) { delete fMoveToItem; fMoveToItem = NULL; } if (fCopyToItem != NULL && fCopyToItem->Menu() == NULL) { delete fCopyToItem; fCopyToItem = NULL; } if (fCreateLinkItem != NULL && fCreateLinkItem->Menu() == NULL) { delete fCreateLinkItem; fCreateLinkItem = NULL; } if (fAttrMenu != NULL && fAttrMenu->Supermenu() == NULL) { delete fAttrMenu; fAttrMenu = NULL; } delete fFileContextMenu; fFileContextMenu = NULL; delete fWindowContextMenu; fWindowContextMenu = NULL; delete fDropContextMenu; fDropContextMenu = NULL; delete fVolumeContextMenu; fVolumeContextMenu = NULL; delete fDragContextMenu; fDragContextMenu = NULL; int32 windowCount = 0; // This is a deadlock code sequence - need to change this // to acquire the window list while this container window is unlocked if (fWindowList != NULL) { AutoLock<LockingList<BWindow> > lock(fWindowList); if (lock.IsLocked()) { fWindowList->RemoveItem(this, false); windowCount = fWindowList->CountItems(); } } if (StateNeedsSaving()) SaveState(); if (fWindowList != NULL && windowCount == 0) be_app->PostMessage(B_QUIT_REQUESTED); _inherited::Quit(); } BPoseView* BContainerWindow::NewPoseView(Model* model, uint32 viewMode) { return new BPoseView(model, viewMode); } void BContainerWindow::UpdateIfTrash(Model* model) { BEntry entry(model->EntryRef()); if (entry.InitCheck() == B_OK) { fIsTrash = model->IsTrash(); fInTrash = FSInTrashDir(model->EntryRef()); fIsPrinters = FSIsPrintersDir(&entry); } } void BContainerWindow::CreatePoseView(Model* model) { UpdateIfTrash(model); fPoseView = NewPoseView(model, kListMode); fBorderedView->GroupLayout()->AddView(fPoseView); fBorderedView->GroupLayout()->SetInsets(1, 0, 1, 1); fBorderedView->EnableBorderHighlight(false); TrackerSettings settings; if (settings.SingleWindowBrowse() && model->IsDirectory() && !fPoseView->IsFilePanel()) { fNavigator = new BNavigator(model); fPoseContainer->GridLayout()->AddView(fNavigator, 0, 0, 2); if (!settings.ShowNavigator()) fNavigator->Hide(); } SetPathWatchingEnabled(settings.ShowNavigator() || settings.ShowFullPathInTitleBar()); } void BContainerWindow::AddContextMenus() { // create context sensitive menus fFileContextMenu = new BPopUpMenu("FileContext", false, false); fFileContextMenu->SetFont(be_plain_font); AddFileContextMenus(fFileContextMenu); fVolumeContextMenu = new BPopUpMenu("VolumeContext", false, false); fVolumeContextMenu->SetFont(be_plain_font); AddVolumeContextMenus(fVolumeContextMenu); fWindowContextMenu = new BPopUpMenu("WindowContext", false, false); fWindowContextMenu->SetFont(be_plain_font); AddWindowContextMenus(fWindowContextMenu); fDropContextMenu = new BPopUpMenu("DropContext", false, false); fDropContextMenu->SetFont(be_plain_font); AddDropContextMenus(fDropContextMenu); fDragContextMenu = new BSlowContextMenu("DragContext"); // will get added and built dynamically in ShowContextMenu fTrashContextMenu = new BPopUpMenu("TrashContext", false, false); fTrashContextMenu->SetFont(be_plain_font); AddTrashContextMenus(fTrashContextMenu); } void BContainerWindow::RepopulateMenus() { // Avoid these menus to be destroyed: if (fMoveToItem && fMoveToItem->Menu()) fMoveToItem->Menu()->RemoveItem(fMoveToItem); if (fCopyToItem && fCopyToItem->Menu()) fCopyToItem->Menu()->RemoveItem(fCopyToItem); if (fCreateLinkItem && fCreateLinkItem->Menu()) fCreateLinkItem->Menu()->RemoveItem(fCreateLinkItem); if (fOpenWithItem && fOpenWithItem->Menu()) { fOpenWithItem->Menu()->RemoveItem(fOpenWithItem); delete fOpenWithItem; fOpenWithItem = NULL; } if (fNavigationItem) { BMenu* menu = fNavigationItem->Menu(); if (menu) { menu->RemoveItem(fNavigationItem); BMenuItem* item = menu->RemoveItem((int32)0); ASSERT(item != fNavigationItem); delete item; } } delete fFileContextMenu; fFileContextMenu = new BPopUpMenu("FileContext", false, false); fFileContextMenu->SetFont(be_plain_font); AddFileContextMenus(fFileContextMenu); delete fWindowContextMenu; fWindowContextMenu = new BPopUpMenu("WindowContext", false, false); fWindowContextMenu->SetFont(be_plain_font); AddWindowContextMenus(fWindowContextMenu); if (fMenuBar != NULL) { fMenuBar->RemoveItem(fFileMenu); delete fFileMenu; fFileMenu = new BMenu(B_TRANSLATE("File")); AddFileMenu(fFileMenu); fMenuBar->AddItem(fFileMenu); fMenuBar->RemoveItem(fWindowMenu); delete fWindowMenu; fWindowMenu = new BMenu(B_TRANSLATE("Window")); fMenuBar->AddItem(fWindowMenu); AddWindowMenu(fWindowMenu); // just create the attribute, decide to add it later fMenuBar->RemoveItem(fAttrMenu); delete fAttrMenu; fAttrMenu = new BMenu(B_TRANSLATE("Attributes")); NewAttributeMenu(fAttrMenu); if (PoseView()->ViewMode() == kListMode) ShowAttributeMenu(); PopulateArrangeByMenu(fArrangeByMenu); int32 selectCount = PoseView()->SelectionList()->CountItems(); SetupOpenWithMenu(fFileMenu); SetupMoveCopyMenus(selectCount ? PoseView()->SelectionList() ->FirstItem()->TargetModel()->EntryRef() : NULL, fFileMenu); } } void BContainerWindow::Init(const BMessage* message) { BEntry entry; ASSERT(fPoseView != NULL); if (fPoseView == NULL) return; // deal with new unconfigured folders if (NeedsDefaultStateSetup()) SetUpDefaultState(); if (ShouldAddScrollBars()) fPoseView->AddScrollBars(); fMoveToItem = new BMenuItem(new BNavMenu(B_TRANSLATE("Move to"), kMoveSelectionTo, this)); fCopyToItem = new BMenuItem(new BNavMenu(B_TRANSLATE("Copy to"), kCopySelectionTo, this)); fCreateLinkItem = new BMenuItem(new BNavMenu(B_TRANSLATE("Create link"), kCreateLink, this), new BMessage(kCreateLink)); TrackerSettings settings; if (ShouldAddMenus()) { fMenuBar = new BMenuBar("MenuBar"); fMenuContainer->GroupLayout()->AddView(fMenuBar); AddMenus(); if (!TargetModel()->IsRoot() && !IsTrash()) _AddFolderIcon(); } else { // add equivalents of the menu shortcuts to the menuless // desktop window AddShortcuts(); } AddContextMenus(); AddShortcut('T', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(kDelete), PoseView()); AddShortcut('K', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(kCleanupAll), PoseView()); AddShortcut('Q', B_COMMAND_KEY | B_OPTION_KEY | B_SHIFT_KEY | B_CONTROL_KEY, new BMessage(kQuitTracker)); AddShortcut(B_DOWN_ARROW, B_COMMAND_KEY, new BMessage(kOpenSelection), PoseView()); SetSingleWindowBrowseShortcuts(settings.SingleWindowBrowse()); #if DEBUG // add some debugging shortcuts AddShortcut('D', B_COMMAND_KEY | B_CONTROL_KEY, new BMessage('dbug'), PoseView()); AddShortcut('C', B_COMMAND_KEY | B_CONTROL_KEY, new BMessage('dpcc'), PoseView()); AddShortcut('F', B_COMMAND_KEY | B_CONTROL_KEY, new BMessage('dpfl'), PoseView()); AddShortcut('F', B_COMMAND_KEY | B_CONTROL_KEY | B_OPTION_KEY, new BMessage('dpfL'), PoseView()); #endif BKeymap keymap; keymap.SetToCurrent(); BObjectList<const char> unmodified(3, true); if (keymap.GetModifiedCharacters("+", B_SHIFT_KEY, 0, &unmodified) == B_OK) { int32 count = unmodified.CountItems(); for (int32 i = 0; i < count; i++) { uint32 key = BUnicodeChar::FromUTF8(unmodified.ItemAt(i)); if (!HasShortcut(key, 0)) { // Add semantic zoom in shortcut, bug #6692 BMessage* increaseSize = new BMessage(kIconMode); increaseSize->AddInt32("scale", 1); AddShortcut(key, B_COMMAND_KEY, increaseSize, PoseView()); } } } unmodified.MakeEmpty(); if (message != NULL) RestoreState(*message); else RestoreState(); if (ShouldAddMenus() && PoseView()->ViewMode() == kListMode) { // for now only show attributes in list view // eventually enable attribute menu to allow users to select // using different attributes as titles in icon view modes ShowAttributeMenu(); } MarkAttributeMenu(fAttrMenu); CheckScreenIntersect(); if (fBackgroundImage != NULL && !fIsDesktop && PoseView()->ViewMode() != kListMode) { fBackgroundImage->Show(PoseView(), current_workspace()); } Show(); // done showing, turn the B_NO_WORKSPACE_ACTIVATION flag off; // it was on to prevent workspace jerking during boot SetFlags(Flags() & ~B_NO_WORKSPACE_ACTIVATION); } void BContainerWindow::InitLayout() { fBorderedView->GroupLayout()->AddView(0, fPoseView->TitleView()); BLayoutItem* item = fCountContainer->GroupLayout()->AddView( fPoseView->CountView()); item->SetExplicitMinSize(BSize(kCountViewWidth, B_H_SCROLL_BAR_HEIGHT)); item->SetExplicitMaxSize(BSize(kCountViewWidth, B_SIZE_UNSET)); // Eliminate the extra borders fMenuContainer->GroupLayout()->SetInsets(0, 0, -1, 0); fPoseContainer->GridLayout()->SetInsets(-1, 0, -1, -1); fCountContainer->GroupLayout()->SetInsets(0, -1, 0, 0); if (fPoseView->VScrollBar() != NULL) { fVScrollBarContainer = new BGroupView(B_VERTICAL, 0); fVScrollBarContainer->GroupLayout()->AddView(fPoseView->VScrollBar()); fVScrollBarContainer->GroupLayout()->SetInsets(-1, -1, 0, 0); fPoseContainer->GridLayout()->AddView(fVScrollBarContainer, 1, 1); } if (fPoseView->HScrollBar() != NULL) { BGroupView* hScrollBarContainer = new BGroupView(B_VERTICAL, 0); hScrollBarContainer->GroupLayout()->AddView(fPoseView->HScrollBar()); hScrollBarContainer->GroupLayout()->SetInsets(0, -1, 0, -1); fCountContainer->GroupLayout()->AddView(hScrollBarContainer); } } void BContainerWindow::RestoreState() { UpdateTitle(); WindowStateNodeOpener opener(this, false); RestoreWindowState(opener.StreamNode()); fPoseView->Init(opener.StreamNode()); RestoreStateCommon(); } void BContainerWindow::RestoreState(const BMessage &message) { UpdateTitle(); RestoreWindowState(message); fPoseView->Init(message); RestoreStateCommon(); } void BContainerWindow::RestoreStateCommon() { if (!fIsDesktop && fUseLayouts) InitLayout(); if (BootedInSafeMode()) // don't pick up backgrounds in safe mode return; WindowStateNodeOpener opener(this, false); if (!TargetModel()->IsRoot() && opener.Node() != NULL) { // don't pick up background image for root disks // to do this, would have to have a unique attribute for the // disks window that doesn't collide with the desktop // for R4 this was not done to make things simpler // the default image will still work though fBackgroundImage = BackgroundImage::GetBackgroundImage( opener.Node(), fIsDesktop); // look for background image info in the window's node } BNode defaultingNode; if (fBackgroundImage == NULL && !fIsDesktop && DefaultStateSourceNode(kDefaultFolderTemplate, &defaultingNode)) { // look for background image info in the source for defaults fBackgroundImage = BackgroundImage::GetBackgroundImage(&defaultingNode, fIsDesktop); } } void BContainerWindow::UpdateTitle() { // set title to full path, if necessary if (TrackerSettings().ShowFullPathInTitleBar()) { // use the Entry's full path BPath path; TargetModel()->GetPath(&path); SetTitle(path.Path()); } else { // use the default look SetTitle(TargetModel()->Name()); } if (Navigator() != NULL) { Navigator()->UpdateLocation(PoseView()->TargetModel(), kActionUpdatePath); } } void BContainerWindow::UpdateBackgroundImage() { if (BootedInSafeMode()) return; WindowStateNodeOpener opener(this, false); if (!TargetModel()->IsRoot() && opener.Node() != NULL) { fBackgroundImage = BackgroundImage::Refresh(fBackgroundImage, opener.Node(), fIsDesktop, PoseView()); } // look for background image info in the window's node BNode defaultingNode; if (!fBackgroundImage && !fIsDesktop && DefaultStateSourceNode(kDefaultFolderTemplate, &defaultingNode)) { // look for background image info in the source for defaults fBackgroundImage = BackgroundImage::Refresh(fBackgroundImage, &defaultingNode, fIsDesktop, PoseView()); } } void BContainerWindow::FrameResized(float, float) { if (PoseView() != NULL && !fIsDesktop) { BRect extent = PoseView()->Extent(); float offsetX = extent.left - PoseView()->Bounds().left; float offsetY = extent.top - PoseView()->Bounds().top; // scroll when the size augmented, there is a negative offset // and we have resized over the bottom right corner of the extent BPoint scroll(B_ORIGIN); if (offsetX < 0 && PoseView()->Bounds().right > extent.right && Bounds().Width() > fPreviousBounds.Width()) { scroll.x = std::max(fPreviousBounds.Width() - Bounds().Width(), offsetX); } if (offsetY < 0 && PoseView()->Bounds().bottom > extent.bottom && Bounds().Height() > fPreviousBounds.Height()) { scroll.y = std::max(fPreviousBounds.Height() - Bounds().Height(), offsetY); } if (scroll != B_ORIGIN) PoseView()->ScrollBy(scroll.x, scroll.y); PoseView()->UpdateScrollRange(); PoseView()->ResetPosePlacementHint(); } fPreviousBounds = Bounds(); fStateNeedsSaving = true; } void BContainerWindow::FrameMoved(BPoint) { fStateNeedsSaving = true; } void BContainerWindow::WorkspacesChanged(uint32, uint32) { fStateNeedsSaving = true; } void BContainerWindow::ViewModeChanged(uint32 oldMode, uint32 newMode) { if (fBackgroundImage == NULL) return; if (newMode == kListMode) fBackgroundImage->Remove(); else if (oldMode == kListMode) fBackgroundImage->Show(PoseView(), current_workspace()); } void BContainerWindow::CheckScreenIntersect() { BScreen screen(this); BRect screenFrame(screen.Frame()); BRect frame(Frame()); if (sNewWindRect.bottom > screenFrame.bottom) sNewWindRect.OffsetTo(85, 50); if (sNewWindRect.right > screenFrame.right) sNewWindRect.OffsetTo(85, 50); if (!frame.Intersects(screenFrame)) MoveTo(sNewWindRect.LeftTop()); } void BContainerWindow::SaveState(bool hide) { if (SaveStateIsEnabled()) { WindowStateNodeOpener opener(this, true); if (opener.StreamNode() != NULL) SaveWindowState(opener.StreamNode()); if (hide) Hide(); if (opener.StreamNode()) fPoseView->SaveState(opener.StreamNode()); fStateNeedsSaving = false; } } void BContainerWindow::SaveState(BMessage& message) const { if (SaveStateIsEnabled()) { SaveWindowState(message); fPoseView->SaveState(message); } } bool BContainerWindow::StateNeedsSaving() const { return fPoseView != NULL && (fStateNeedsSaving || fPoseView->StateNeedsSaving()); } status_t BContainerWindow::GetLayoutState(BNode* node, BMessage* message) { if (node == NULL || message == NULL) return B_BAD_VALUE; status_t result = node->InitCheck(); if (result != B_OK) return result; // ToDo: get rid of this, use AttrStream instead node->RewindAttrs(); char attrName[256]; while (node->GetNextAttrName(attrName) == B_OK) { attr_info info; if (node->GetAttrInfo(attrName, &info) != B_OK) continue; // filter out attributes that are not related to window position // and column resizing // more can be added as needed if (strcmp(attrName, kAttrWindowFrame) != 0 && strcmp(attrName, kAttrColumns) != 0 && strcmp(attrName, kAttrViewState) != 0 && strcmp(attrName, kAttrColumnsForeign) != 0 && strcmp(attrName, kAttrViewStateForeign) != 0) { continue; } char* buffer = new char[info.size]; if (node->ReadAttr(attrName, info.type, 0, buffer, (size_t)info.size) == info.size) { message->AddData(attrName, info.type, buffer, (ssize_t)info.size); } delete[] buffer; } return B_OK; } status_t BContainerWindow::SetLayoutState(BNode* node, const BMessage* message) { status_t result = node->InitCheck(); if (result != B_OK) return result; for (int32 globalIndex = 0; ;) { #if B_BEOS_VERSION_DANO const char* name; #else char* name; #endif type_code type; int32 count; status_t result = message->GetInfo(B_ANY_TYPE, globalIndex, &name, &type, &count); if (result != B_OK) break; for (int32 index = 0; index < count; index++) { const void* buffer; ssize_t size; result = message->FindData(name, type, index, &buffer, &size); if (result != B_OK) { PRINT(("error reading %s \n", name)); return result; } if (node->WriteAttr(name, type, 0, buffer, (size_t)size) != size) { PRINT(("error writing %s \n", name)); return result; } globalIndex++; } } return B_OK; } bool BContainerWindow::ShouldAddMenus() const { return true; } bool BContainerWindow::ShouldAddScrollBars() const { return true; } Model* BContainerWindow::TargetModel() const { return fPoseView->TargetModel(); } void BContainerWindow::SelectionChanged() { } void BContainerWindow::Zoom(BPoint, float, float) { BRect oldZoomRect(fSavedZoomRect); fSavedZoomRect = Frame(); ResizeToFit(); if (fSavedZoomRect == Frame() && oldZoomRect.IsValid()) ResizeTo(oldZoomRect.Width(), oldZoomRect.Height()); } void BContainerWindow::ResizeToFit() { BScreen screen(this); BRect screenFrame(screen.Frame()); screenFrame.InsetBy(5, 5); BMessage decoratorSettings; GetDecoratorSettings(&decoratorSettings); float tabHeight = 15; BRect tabRect; if (decoratorSettings.FindRect("tab frame", &tabRect) == B_OK) tabHeight = tabRect.Height(); screenFrame.top += tabHeight; BRect frame(Frame()); float widthDiff = frame.Width() - PoseView()->Frame().Width(); float heightDiff = frame.Height() - PoseView()->Frame().Height(); // move frame left top on screen BPoint leftTop(frame.LeftTop()); leftTop.ConstrainTo(screenFrame); frame.OffsetTo(leftTop); // resize to extent size BRect extent(PoseView()->Extent()); frame.right = frame.left + extent.Width() + widthDiff; frame.bottom = frame.top + extent.Height() + heightDiff; // make sure entire window fits on screen frame = frame & screenFrame; ResizeTo(frame.Width(), frame.Height()); MoveTo(frame.LeftTop()); PoseView()->DisableScrollBars(); // scroll if there is an offset PoseView()->ScrollBy( extent.left - PoseView()->Bounds().left, extent.top - PoseView()->Bounds().top); PoseView()->UpdateScrollRange(); PoseView()->EnableScrollBars(); } void BContainerWindow::MessageReceived(BMessage* message) { switch (message->what) { case B_CUT: case B_COPY: case B_PASTE: case kCutMoreSelectionToClipboard: case kCopyMoreSelectionToClipboard: case kPasteLinksFromClipboard: { BView* view = CurrentFocus(); if (dynamic_cast<BTextView*>(view) == NULL) { // The selected item is not a BTextView, so forward the // message to the PoseView. if (fPoseView != NULL) fPoseView->MessageReceived(message); } else { // Since we catch the generic clipboard shortcuts in a way that // means the BTextView will never get them, we must // manually forward them ourselves. // // However, we have to take care to not forward the custom // clipboard messages, else we would wind up in infinite // recursion. if (message->what == B_CUT || message->what == B_COPY || message->what == B_PASTE) { view->MessageReceived(message); } } break; } case B_UNDO: { BView* view = CurrentFocus(); if (dynamic_cast<BTextView*>(view) == NULL) { FSUndo(); } else { view->MessageReceived(message); } break; } case B_REDO: { BView* view = CurrentFocus(); if (dynamic_cast<BTextView*>(view) == NULL) { FSRedo(); } else { view->MessageReceived(message); } break; } case kNewFolder: PostMessage(message, PoseView()); break; case kRestoreState: if (message->HasMessage("state")) { BMessage state; message->FindMessage("state", &state); Init(&state); } else Init(); break; case kResizeToFit: ResizeToFit(); break; case kLoadAddOn: LoadAddOn(message); break; case kCopySelectionTo: { entry_ref ref; if (message->FindRef("refs", &ref) != B_OK) break; BRoster().AddToRecentFolders(&ref); Model model(&ref); if (model.InitCheck() != B_OK) break; if (*model.NodeRef() == *TargetModel()->NodeRef()) PoseView()->DuplicateSelection(); else PoseView()->MoveSelectionInto(&model, this, true); break; } case kMoveSelectionTo: { entry_ref ref; if (message->FindRef("refs", &ref) != B_OK) break; BRoster().AddToRecentFolders(&ref); Model model(&ref); if (model.InitCheck() != B_OK) break; PoseView()->MoveSelectionInto(&model, this, false, true); break; } case kCreateLink: case kCreateRelativeLink: { entry_ref ref; if (message->FindRef("refs", &ref) == B_OK) { BRoster().AddToRecentFolders(&ref); Model model(&ref); if (model.InitCheck() != B_OK) break; PoseView()->MoveSelectionInto(&model, this, false, false, message->what == kCreateLink, message->what == kCreateRelativeLink); } else if (!TargetModel()->IsQuery() && !TargetModel()->IsVirtualDirectory()) { // no destination specified, create link in same dir as item PoseView()->MoveSelectionInto(TargetModel(), this, false, false, message->what == kCreateLink, message->what == kCreateRelativeLink); } break; } case kShowSelectionWindow: ShowSelectionWindow(); break; case kSelectMatchingEntries: PoseView()->SelectMatchingEntries(message); break; case kFindButton: (new FindWindow())->Show(); break; case kQuitTracker: be_app->PostMessage(B_QUIT_REQUESTED); break; case kRestoreBackgroundImage: UpdateBackgroundImage(); break; case kSwitchDirectory: { entry_ref ref; if (message->FindRef("refs", &ref) == B_OK) { BEntry entry; if (entry.SetTo(&ref) == B_OK) { if (StateNeedsSaving()) SaveState(false); bool wasInTrash = IsTrash() || InTrash(); bool isRoot = PoseView()->TargetModel()->IsRoot(); // Switch dir and apply new state WindowStateNodeOpener opener(this, false); opener.SetTo(&entry, false); // Update PoseView PoseView()->SwitchDir(&ref, opener.StreamNode()); fIsTrash = FSIsTrashDir(&entry); fInTrash = FSInTrashDir(&ref); if (wasInTrash ^ (IsTrash() || InTrash()) || isRoot != PoseView()->TargetModel()->IsRoot()) RepopulateMenus(); if (Navigator() != NULL) { // update Navigation bar int32 action = kActionSet; if (message->FindInt32("action", &action) != B_OK) { // Design problem? Why does FindInt32 touch // 'action' at all if he can't find it?? action = kActionSet; } Navigator()->UpdateLocation(PoseView()->TargetModel(), action); } TrackerSettings settings; if (settings.ShowNavigator() || settings.ShowFullPathInTitleBar()) { SetPathWatchingEnabled(true); } SetSingleWindowBrowseShortcuts( settings.SingleWindowBrowse()); // Update draggable folder icon if (fMenuBar != NULL) { if (!TargetModel()->IsRoot() && !IsTrash()) { // Folder icon should be visible, but in single // window navigation, it might not be. if (fDraggableIcon != NULL) { IconCache::sIconCache->IconChanged( TargetModel()); fDraggableIcon->Invalidate(); } else _AddFolderIcon(); } else if (fDraggableIcon != NULL) fDraggableIcon->RemoveSelf(); } // Update window title UpdateTitle(); } } break; } case B_REFS_RECEIVED: if (Dragging()) { // ref in this message is the target, // the end point of the drag entry_ref ref; if (message->FindRef("refs", &ref) == B_OK) { fWaitingForRefs = false; BEntry entry(&ref, true); // don't copy to printers dir if (!FSIsPrintersDir(&entry)) { if (entry.InitCheck() == B_OK && entry.IsDirectory()) { Model targetModel(&entry, true, false); BPoint dropPoint; uint32 buttons; PoseView()->GetMouse(&dropPoint, &buttons, true); PoseView()->HandleDropCommon(fDragMessage, &targetModel, NULL, PoseView(), dropPoint); } } } DragStop(); } break; case B_OBSERVER_NOTICE_CHANGE: { int32 observerWhat; if (message->FindInt32("be:observe_change_what", &observerWhat) == B_OK) { TrackerSettings settings; switch (observerWhat) { case kWindowsShowFullPathChanged: UpdateTitle(); if (!IsPathWatchingEnabled() && settings.ShowFullPathInTitleBar()) { SetPathWatchingEnabled(true); } if (IsPathWatchingEnabled() && !(settings.ShowNavigator() || settings.ShowFullPathInTitleBar())) { SetPathWatchingEnabled(false); } break; case kSingleWindowBrowseChanged: if (settings.SingleWindowBrowse() && !Navigator() && TargetModel()->IsDirectory() && !PoseView()->IsFilePanel() && !PoseView()->IsDesktopWindow()) { fNavigator = new BNavigator(TargetModel()); fPoseContainer->GridLayout()->AddView(fNavigator, 0, 0, 2); fNavigator->Hide(); SetPathWatchingEnabled(settings.ShowNavigator() || settings.ShowFullPathInTitleBar()); } if (!settings.SingleWindowBrowse() && !fIsDesktop && TargetModel()->IsDesktop()) { // Close the "Desktop" window, but not the Desktop this->Quit(); } SetSingleWindowBrowseShortcuts( settings.SingleWindowBrowse()); break; case kShowNavigatorChanged: ShowNavigator(settings.ShowNavigator()); if (!IsPathWatchingEnabled() && settings.ShowNavigator()) { SetPathWatchingEnabled(true); } if (IsPathWatchingEnabled() && !(settings.ShowNavigator() || settings.ShowFullPathInTitleBar())) { SetPathWatchingEnabled(false); } SetSingleWindowBrowseShortcuts( settings.SingleWindowBrowse()); break; case kDontMoveFilesToTrashChanged: { bool dontMoveToTrash = settings.DontMoveFilesToTrash(); BMenuItem* item = fFileContextMenu->FindItem(kMoveToTrash); if (item != NULL) { item->SetLabel(dontMoveToTrash ? B_TRANSLATE("Delete") : B_TRANSLATE("Move to Trash")); } // Deskbar doesn't have a menu bar, so check if // there is fMenuBar if (fMenuBar && fFileMenu) { item = fFileMenu->FindItem(kMoveToTrash); if (item != NULL) { item->SetLabel(dontMoveToTrash ? B_TRANSLATE("Delete") : B_TRANSLATE("Move to Trash")); } } UpdateIfNeeded(); break; } default: _inherited::MessageReceived(message); break; } } break; } case B_NODE_MONITOR: UpdateTitle(); break; default: _inherited::MessageReceived(message); break; } } void BContainerWindow::SetCutItem(BMenu* menu) { BMenuItem* item; if ((item = menu->FindItem(B_CUT)) == NULL && (item = menu->FindItem(kCutMoreSelectionToClipboard)) == NULL) return; item->SetEnabled(PoseView()->SelectionList()->CountItems() > 0 || PoseView() != CurrentFocus()); if (modifiers() & B_SHIFT_KEY) { item->SetLabel(B_TRANSLATE("Cut more")); item->SetShortcut('X', B_COMMAND_KEY | B_SHIFT_KEY); item->SetMessage(new BMessage(kCutMoreSelectionToClipboard)); } else { item->SetLabel(B_TRANSLATE("Cut")); item->SetShortcut('X', B_COMMAND_KEY); item->SetMessage(new BMessage(B_CUT)); } } void BContainerWindow::SetCopyItem(BMenu* menu) { BMenuItem* item; if ((item = menu->FindItem(B_COPY)) == NULL && (item = menu->FindItem(kCopyMoreSelectionToClipboard)) == NULL) { return; } item->SetEnabled(PoseView()->SelectionList()->CountItems() > 0 || PoseView() != CurrentFocus()); if (modifiers() & B_SHIFT_KEY) { item->SetLabel(B_TRANSLATE("Copy more")); item->SetShortcut('C', B_COMMAND_KEY | B_SHIFT_KEY); item->SetMessage(new BMessage(kCopyMoreSelectionToClipboard)); } else { item->SetLabel(B_TRANSLATE("Copy")); item->SetShortcut('C', B_COMMAND_KEY); item->SetMessage(new BMessage(B_COPY)); } } void BContainerWindow::SetPasteItem(BMenu* menu) { BMenuItem* item; if ((item = menu->FindItem(B_PASTE)) == NULL && (item = menu->FindItem(kPasteLinksFromClipboard)) == NULL) { return; } item->SetEnabled(FSClipboardHasRefs() || PoseView() != CurrentFocus()); if (modifiers() & B_SHIFT_KEY) { item->SetLabel(B_TRANSLATE("Paste links")); item->SetShortcut('V', B_COMMAND_KEY | B_SHIFT_KEY); item->SetMessage(new BMessage(kPasteLinksFromClipboard)); } else { item->SetLabel(B_TRANSLATE("Paste")); item->SetShortcut('V', B_COMMAND_KEY); item->SetMessage(new BMessage(B_PASTE)); } } void BContainerWindow::SetArrangeMenu(BMenu* menu) { BMenuItem* item; if ((item = menu->FindItem(kCleanup)) == NULL && (item = menu->FindItem(kCleanupAll)) == NULL) { return; } item->Menu()->SetEnabled(PoseView()->CountItems() > 0 && (PoseView()->ViewMode() != kListMode)); BMenu* arrangeMenu; if (modifiers() & B_SHIFT_KEY) { item->SetLabel(B_TRANSLATE("Clean up all")); item->SetShortcut('K', B_COMMAND_KEY | B_SHIFT_KEY); item->SetMessage(new BMessage(kCleanupAll)); arrangeMenu = item->Menu(); } else { item->SetLabel(B_TRANSLATE("Clean up")); item->SetShortcut('K', B_COMMAND_KEY); item->SetMessage(new BMessage(kCleanup)); arrangeMenu = item->Menu(); } MarkArrangeByMenu(arrangeMenu); } void BContainerWindow::SetCloseItem(BMenu* menu) { BMenuItem* item; if ((item = menu->FindItem(B_QUIT_REQUESTED)) == NULL && (item = menu->FindItem(kCloseAllWindows)) == NULL) { return; } if (modifiers() & B_SHIFT_KEY) { item->SetLabel(B_TRANSLATE("Close all")); item->SetShortcut('W', B_COMMAND_KEY | B_SHIFT_KEY); item->SetTarget(be_app); item->SetMessage(new BMessage(kCloseAllWindows)); } else { item->SetLabel(B_TRANSLATE("Close")); item->SetShortcut('W', B_COMMAND_KEY); item->SetTarget(this); item->SetMessage(new BMessage(B_QUIT_REQUESTED)); } } bool BContainerWindow::IsShowing(const node_ref* node) const { return PoseView()->Represents(node); } bool BContainerWindow::IsShowing(const entry_ref* entry) const { return PoseView()->Represents(entry); } void BContainerWindow::AddMenus() { fFileMenu = new BMenu(B_TRANSLATE("File")); AddFileMenu(fFileMenu); fMenuBar->AddItem(fFileMenu); fWindowMenu = new BMenu(B_TRANSLATE("Window")); fMenuBar->AddItem(fWindowMenu); AddWindowMenu(fWindowMenu); // just create the attribute, decide to add it later fAttrMenu = new BMenu(B_TRANSLATE("Attributes")); NewAttributeMenu(fAttrMenu); PopulateArrangeByMenu(fArrangeByMenu); } void BContainerWindow::AddFileMenu(BMenu* menu) { if (!PoseView()->IsFilePanel()) { menu->AddItem(new BMenuItem(B_TRANSLATE("Find" B_UTF8_ELLIPSIS), new BMessage(kFindButton), 'F')); } if (!TargetModel()->IsQuery() && !TargetModel()->IsVirtualDirectory() && !IsTrash() && !IsPrintersDir() && !TargetModel()->IsRoot()) { if (!PoseView()->IsFilePanel()) { TemplatesMenu* templatesMenu = new TemplatesMenu(PoseView(), B_TRANSLATE("New")); menu->AddItem(templatesMenu); templatesMenu->SetTargetForItems(PoseView()); } else { menu->AddItem(new BMenuItem(B_TRANSLATE("New folder"), new BMessage(kNewFolder), 'N')); } } menu->AddSeparatorItem(); menu->AddItem(new BMenuItem(B_TRANSLATE("Open"), new BMessage(kOpenSelection), 'O')); menu->AddItem(new BMenuItem(B_TRANSLATE("Get info"), new BMessage(kGetInfo), 'I')); menu->AddItem(new BMenuItem(B_TRANSLATE("Edit name"), new BMessage(kEditItem), 'E')); if (IsTrash() || InTrash()) { menu->AddItem(new BMenuItem(B_TRANSLATE("Restore"), new BMessage(kRestoreFromTrash))); if (IsTrash()) { // add as first item in menu menu->AddItem(new BMenuItem(B_TRANSLATE("Empty Trash"), new BMessage(kEmptyTrash)), 0); menu->AddItem(new BSeparatorItem(), 1); } } else if (IsPrintersDir()) { menu->AddItem(new BMenuItem(B_TRANSLATE("Add printer" B_UTF8_ELLIPSIS), new BMessage(kAddPrinter), 'N'), 0); menu->AddItem(new BSeparatorItem(), 1); menu->AddItem(new BMenuItem(B_TRANSLATE("Make active printer"), new BMessage(kMakeActivePrinter))); } else if (TargetModel()->IsRoot()) { BMenuItem* item = new BMenuItem(B_TRANSLATE("Unmount"), new BMessage(kUnmountVolume), 'U'); item->SetEnabled(false); menu->AddItem(item); menu->AddItem(new BMenuItem( B_TRANSLATE("Mount settings" B_UTF8_ELLIPSIS), new BMessage(kRunAutomounterSettings))); } else { menu->AddItem(new BMenuItem(B_TRANSLATE("Duplicate"), new BMessage(kDuplicateSelection), 'D')); menu->AddItem(new BMenuItem(TrackerSettings().DontMoveFilesToTrash() ? B_TRANSLATE("Delete") : B_TRANSLATE("Move to Trash"), new BMessage(kMoveToTrash), 'T')); menu->AddSeparatorItem(); // The "Move To", "Copy To", "Create Link" menus are inserted // at this place, have a look at: // BContainerWindow::SetupMoveCopyMenus() } BMenuItem* cutItem = NULL; BMenuItem* copyItem = NULL; BMenuItem* pasteItem = NULL; if (!IsPrintersDir()) { menu->AddSeparatorItem(); if (!TargetModel()->IsRoot()) { cutItem = new(std::nothrow) BMenuItem(B_TRANSLATE("Cut"), new BMessage(B_CUT), 'X'); menu->AddItem(cutItem); copyItem = new(std::nothrow) BMenuItem(B_TRANSLATE("Copy"), new BMessage(B_COPY), 'C'); menu->AddItem(copyItem); pasteItem = new(std::nothrow) BMenuItem(B_TRANSLATE("Paste"), new BMessage(B_PASTE), 'V'); menu->AddItem(pasteItem); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem(B_TRANSLATE("Identify"), new BMessage(kIdentifyEntry))); } BMenu* addOnMenuItem = new BMenu(B_TRANSLATE("Add-ons")); addOnMenuItem->SetFont(be_plain_font); menu->AddItem(addOnMenuItem); } menu->SetTargetForItems(PoseView()); if (cutItem != NULL) cutItem->SetTarget(this); if (copyItem != NULL) copyItem->SetTarget(this); if (pasteItem != NULL) pasteItem->SetTarget(this); } void BContainerWindow::AddWindowMenu(BMenu* menu) { BMenuItem* item; BMenu* iconSizeMenu = new BMenu(B_TRANSLATE("Icon view")); BMessage* message = new BMessage(kIconMode); message->AddInt32("size", 32); item = new BMenuItem(B_TRANSLATE("32 x 32"), message); item->SetTarget(PoseView()); iconSizeMenu->AddItem(item); message = new BMessage(kIconMode); message->AddInt32("size", 40); item = new BMenuItem(B_TRANSLATE("40 x 40"), message); item->SetTarget(PoseView()); iconSizeMenu->AddItem(item); message = new BMessage(kIconMode); message->AddInt32("size", 48); item = new BMenuItem(B_TRANSLATE("48 x 48"), message); item->SetTarget(PoseView()); iconSizeMenu->AddItem(item); message = new BMessage(kIconMode); message->AddInt32("size", 64); item = new BMenuItem(B_TRANSLATE("64 x 64"), message); item->SetTarget(PoseView()); iconSizeMenu->AddItem(item); message = new BMessage(kIconMode); message->AddInt32("size", 96); item = new BMenuItem(B_TRANSLATE("96 x 96"), message); item->SetTarget(PoseView()); iconSizeMenu->AddItem(item); message = new BMessage(kIconMode); message->AddInt32("size", 128); item = new BMenuItem(B_TRANSLATE("128 x 128"), message); item->SetTarget(PoseView()); iconSizeMenu->AddItem(item); iconSizeMenu->AddSeparatorItem(); message = new BMessage(kIconMode); message->AddInt32("scale", 0); item = new BMenuItem(B_TRANSLATE("Decrease size"), message, '-'); item->SetTarget(PoseView()); iconSizeMenu->AddItem(item); message = new BMessage(kIconMode); message->AddInt32("scale", 1); item = new BMenuItem(B_TRANSLATE("Increase size"), message, '+'); item->SetTarget(PoseView()); iconSizeMenu->AddItem(item); // A sub menu where the super item can be invoked. menu->AddItem(iconSizeMenu); iconSizeMenu->Superitem()->SetShortcut('1', B_COMMAND_KEY); iconSizeMenu->Superitem()->SetMessage(new BMessage(kIconMode)); iconSizeMenu->Superitem()->SetTarget(PoseView()); item = new BMenuItem(B_TRANSLATE("Mini icon view"), new BMessage(kMiniIconMode), '2'); item->SetTarget(PoseView()); menu->AddItem(item); BMenu* listViewMenu = new BMenu(B_TRANSLATE("List view")); message = new BMessage(kListMode); message->AddInt32("icon_size", B_MINI_ICON); item = new BMenuItem(listViewMenu, message); item->SetShortcut('3', B_COMMAND_KEY); item->SetTarget(PoseView()); menu->AddItem(item); message = new BMessage(kListMode); message->AddInt32("icon_size", B_MINI_ICON); item = new BMenuItem(B_TRANSLATE("Mini"), message); item->SetTarget(PoseView()); listViewMenu->AddItem(item); message = new BMessage(kListMode); message->AddInt32("icon_size", B_LARGE_ICON); item = new BMenuItem(B_TRANSLATE("Large"), message); item->SetTarget(PoseView()); listViewMenu->AddItem(item); listViewMenu->SetTargetForItems(PoseView()); menu->AddSeparatorItem(); item = new BMenuItem(B_TRANSLATE("Resize to fit"), new BMessage(kResizeToFit), 'Y'); item->SetTarget(this); menu->AddItem(item); fArrangeByMenu = new BMenu(B_TRANSLATE("Arrange by")); menu->AddItem(fArrangeByMenu); item = new BMenuItem(B_TRANSLATE("Select" B_UTF8_ELLIPSIS), new BMessage(kShowSelectionWindow), 'A', B_SHIFT_KEY); item->SetTarget(PoseView()); menu->AddItem(item); item = new BMenuItem(B_TRANSLATE("Select all"), new BMessage(B_SELECT_ALL), 'A'); item->SetTarget(PoseView()); menu->AddItem(item); item = new BMenuItem(B_TRANSLATE("Invert selection"), new BMessage(kInvertSelection), 'S'); item->SetTarget(PoseView()); menu->AddItem(item); if (!IsTrash()) { item = new BMenuItem(B_TRANSLATE("Open parent"), new BMessage(kOpenParentDir), B_UP_ARROW); item->SetTarget(PoseView()); menu->AddItem(item); } item = new BMenuItem(B_TRANSLATE("Close"), new BMessage(B_QUIT_REQUESTED), 'W'); item->SetTarget(this); menu->AddItem(item); item = new BMenuItem(B_TRANSLATE("Close all in workspace"), new BMessage(kCloseAllInWorkspace), 'Q'); item->SetTarget(be_app); menu->AddItem(item); menu->AddSeparatorItem(); item = new BMenuItem(B_TRANSLATE("Preferences" B_UTF8_ELLIPSIS), new BMessage(kShowSettingsWindow)); item->SetTarget(be_app); menu->AddItem(item); } void BContainerWindow::AddShortcuts() { // add equivalents of the menu shortcuts to the menuless desktop window ASSERT(!IsTrash()); ASSERT(!PoseView()->IsFilePanel()); ASSERT(!TargetModel()->IsQuery()); ASSERT(!TargetModel()->IsVirtualDirectory()); AddShortcut('X', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(kCutMoreSelectionToClipboard), this); AddShortcut('C', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(kCopyMoreSelectionToClipboard), this); AddShortcut('F', B_COMMAND_KEY, new BMessage(kFindButton), PoseView()); AddShortcut('N', B_COMMAND_KEY, new BMessage(kNewFolder), PoseView()); AddShortcut('O', B_COMMAND_KEY, new BMessage(kOpenSelection), PoseView()); AddShortcut('I', B_COMMAND_KEY, new BMessage(kGetInfo), PoseView()); AddShortcut('E', B_COMMAND_KEY, new BMessage(kEditItem), PoseView()); AddShortcut('D', B_COMMAND_KEY, new BMessage(kDuplicateSelection), PoseView()); AddShortcut('T', B_COMMAND_KEY, new BMessage(kMoveToTrash), PoseView()); AddShortcut('K', B_COMMAND_KEY, new BMessage(kCleanup), PoseView()); AddShortcut('A', B_COMMAND_KEY, new BMessage(B_SELECT_ALL), PoseView()); AddShortcut('S', B_COMMAND_KEY, new BMessage(kInvertSelection), PoseView()); AddShortcut('A', B_COMMAND_KEY | B_SHIFT_KEY, new BMessage(kShowSelectionWindow), PoseView()); AddShortcut('G', B_COMMAND_KEY, new BMessage(kEditQuery), PoseView()); // it is ok to add a global Edit query shortcut here, PoseView will // filter out cases where selected pose is not a query AddShortcut('U', B_COMMAND_KEY, new BMessage(kUnmountVolume), PoseView()); AddShortcut(B_UP_ARROW, B_COMMAND_KEY, new BMessage(kOpenParentDir), PoseView()); AddShortcut('O', B_COMMAND_KEY | B_CONTROL_KEY, new BMessage(kOpenSelectionWith), PoseView()); BMessage* decreaseSize = new BMessage(kIconMode); decreaseSize->AddInt32("scale", 0); AddShortcut('-', B_COMMAND_KEY, decreaseSize, PoseView()); BMessage* increaseSize = new BMessage(kIconMode); increaseSize->AddInt32("scale", 1); AddShortcut('+', B_COMMAND_KEY, increaseSize, PoseView()); } void BContainerWindow::MenusBeginning() { if (fMenuBar == NULL) return; if (CurrentMessage() != NULL && CurrentMessage()->what == B_MOUSE_DOWN) { // don't commit active pose if only a keyboard shortcut is // invoked - this would prevent Cut/Copy/Paste from working fPoseView->CommitActivePose(); } // File menu int32 selectCount = PoseView()->SelectionList()->CountItems(); SetupOpenWithMenu(fFileMenu); SetupMoveCopyMenus(selectCount ? PoseView()->SelectionList()->FirstItem()->TargetModel()->EntryRef() : NULL, fFileMenu); if (TargetModel()->IsRoot()) { BVolume boot; BVolumeRoster().GetBootVolume(&boot); bool ejectableVolumeSelected = false; int32 count = PoseView()->SelectionList()->CountItems(); for (int32 index = 0; index < count; index++) { Model* model = PoseView()->SelectionList()->ItemAt(index)->TargetModel(); if (model->IsVolume()) { BVolume volume; volume.SetTo(model->NodeRef()->device); if (volume != boot) { ejectableVolumeSelected = true; break; } } } BMenuItem* item = fMenuBar->FindItem(kUnmountVolume); if (item != NULL) item->SetEnabled(ejectableVolumeSelected); } UpdateMenu(fMenuBar, kMenuBarContext); AddMimeTypesToMenu(fAttrMenu); if (IsPrintersDir()) { EnableNamedMenuItem(fFileMenu, B_TRANSLATE("Make active printer"), selectCount == 1); } } void BContainerWindow::MenusEnded() { // when we're done we want to clear nav menus for next time DeleteSubmenu(fNavigationItem); DeleteSubmenu(fMoveToItem); DeleteSubmenu(fCopyToItem); DeleteSubmenu(fCreateLinkItem); DeleteSubmenu(fOpenWithItem); } void BContainerWindow::SetupNavigationMenu(const entry_ref* ref, BMenu* parent) { // start by removing nav item (and separator) from old menu if (fNavigationItem != NULL) { BMenu* menu = fNavigationItem->Menu(); if (menu != NULL) { menu->RemoveItem(fNavigationItem); BMenuItem* item = menu->RemoveItem((int32)0); ASSERT(item != fNavigationItem); delete item; } } // if we weren't passed a ref then we're navigating this window if (ref == NULL) ref = TargetModel()->EntryRef(); BEntry entry; if (entry.SetTo(ref) != B_OK) return; // only navigate directories and queries (check for symlink here) Model model(&entry); entry_ref resolvedRef; if (model.InitCheck() != B_OK || (!model.IsContainer() && !model.IsSymLink())) { return; } if (model.IsSymLink()) { if (entry.SetTo(model.EntryRef(), true) != B_OK) return; Model resolvedModel(&entry); if (resolvedModel.InitCheck() != B_OK || !resolvedModel.IsContainer()) return; entry.GetRef(&resolvedRef); ref = &resolvedRef; } if (fNavigationItem == NULL) { fNavigationItem = new ModelMenuItem(&model, new BNavMenu(model.Name(), B_REFS_RECEIVED, be_app, this)); } // setup a navigation menu item which will dynamically load items // as menu items are traversed BNavMenu* navMenu = dynamic_cast<BNavMenu*>(fNavigationItem->Submenu()); navMenu->SetNavDir(ref); fNavigationItem->SetLabel(model.Name()); fNavigationItem->SetEntry(&entry); parent->AddItem(fNavigationItem, 0); parent->AddItem(new BSeparatorItem(), 1); BMessage* message = new BMessage(B_REFS_RECEIVED); message->AddRef("refs", ref); fNavigationItem->SetMessage(message); fNavigationItem->SetTarget(be_app); if (!Dragging()) parent->SetTrackingHook(NULL, NULL); } void BContainerWindow::SetUpEditQueryItem(BMenu* menu) { ASSERT(menu); // File menu int32 selectCount = PoseView()->SelectionList()->CountItems(); // add Edit query if appropriate bool queryInSelection = false; if (selectCount && selectCount < 100) { // only do this for a limited number of selected poses // if any queries selected, add an edit query menu item for (int32 index = 0; index < selectCount; index++) { BPose* pose = PoseView()->SelectionList()->ItemAt(index); Model model(pose->TargetModel()->EntryRef(), true); if (model.InitCheck() != B_OK) continue; if (model.IsQuery() || model.IsQueryTemplate()) { queryInSelection = true; break; } } } bool poseViewIsQuery = TargetModel()->IsQuery(); // if the view is a query pose view, add edit query menu item BMenuItem* item = menu->FindItem(kEditQuery); if (!poseViewIsQuery && !queryInSelection && item != NULL) item->Menu()->RemoveItem(item); else if ((poseViewIsQuery || queryInSelection) && item == NULL) { // add edit query item after Open item = menu->FindItem(kOpenSelection); if (item) { int32 itemIndex = item->Menu()->IndexOf(item); BMenuItem* query = new BMenuItem(B_TRANSLATE("Edit query"), new BMessage(kEditQuery), 'G'); item->Menu()->AddItem(query, itemIndex + 1); query->SetTarget(PoseView()); } } } void BContainerWindow::SetupOpenWithMenu(BMenu* parent) { // start by removing nav item (and separator) from old menu if (fOpenWithItem) { BMenu* menu = fOpenWithItem->Menu(); if (menu != NULL) menu->RemoveItem(fOpenWithItem); delete fOpenWithItem; fOpenWithItem = 0; } if (PoseView()->SelectionList()->CountItems() == 0) { // no selection, nothing to open return; } if (TargetModel()->IsRoot()) { // don't add ourselves if we are root return; } // ToDo: // check if only item in selection list is the root // and do not add if true // add after "Open" BMenuItem* item = parent->FindItem(kOpenSelection); int32 count = PoseView()->SelectionList()->CountItems(); if (count == 0) return; // build a list of all refs to open BMessage message(B_REFS_RECEIVED); for (int32 index = 0; index < count; index++) { BPose* pose = PoseView()->SelectionList()->ItemAt(index); message.AddRef("refs", pose->TargetModel()->EntryRef()); } // add Tracker token so that refs received recipients can script us message.AddMessenger("TrackerViewToken", BMessenger(PoseView())); int32 index = item->Menu()->IndexOf(item); fOpenWithItem = new BMenuItem( new OpenWithMenu(B_TRANSLATE("Open with" B_UTF8_ELLIPSIS), &message, this, be_app), new BMessage(kOpenSelectionWith)); fOpenWithItem->SetTarget(PoseView()); fOpenWithItem->SetShortcut('O', B_COMMAND_KEY | B_CONTROL_KEY); item->Menu()->AddItem(fOpenWithItem, index + 1); } void BContainerWindow::PopulateMoveCopyNavMenu(BNavMenu* navMenu, uint32 what, const entry_ref* ref, bool addLocalOnly) { BVolume volume; BVolumeRoster volumeRoster; BDirectory directory; BEntry entry; BPath path; Model model; dev_t device = ref->device; int32 volumeCount = 0; navMenu->RemoveItems(0, navMenu->CountItems(), true); // count persistent writable volumes volumeRoster.Rewind(); while (volumeRoster.GetNextVolume(&volume) == B_OK) if (!volume.IsReadOnly() && volume.IsPersistent()) volumeCount++; // add the current folder if (entry.SetTo(ref) == B_OK && entry.GetParent(&entry) == B_OK && model.SetTo(&entry) == B_OK) { BNavMenu* menu = new BNavMenu(B_TRANSLATE("Current folder"), what, this); menu->SetNavDir(model.EntryRef()); menu->SetShowParent(true); BMenuItem* item = new SpecialModelMenuItem(&model,menu); item->SetMessage(new BMessage((uint32)what)); navMenu->AddItem(item); } // add the recent folder menu // the "Tracker" settings directory is only used to get its icon if (find_directory(B_USER_SETTINGS_DIRECTORY, &path) == B_OK) { path.Append("Tracker"); if (entry.SetTo(path.Path()) == B_OK && model.SetTo(&entry) == B_OK) { BMenu* menu = new RecentsMenu(B_TRANSLATE("Recent folders"), kRecentFolders, what, this); BMenuItem* item = new SpecialModelMenuItem(&model,menu); item->SetMessage(new BMessage((uint32)what)); navMenu->AddItem(item); } } // add Desktop FSGetBootDeskDir(&directory); if (directory.InitCheck() == B_OK && directory.GetEntry(&entry) == B_OK && model.SetTo(&entry) == B_OK) navMenu->AddNavDir(&model, what, this, true); // ask NavMenu to populate submenu for us // add the home dir if (find_directory(B_USER_DIRECTORY, &path) == B_OK && entry.SetTo(path.Path()) == B_OK && model.SetTo(&entry) == B_OK) navMenu->AddNavDir(&model, what, this, true); navMenu->AddSeparatorItem(); // either add all mounted volumes (for copy), or all the top-level // directories from the same device (for move) // ToDo: can be changed if cross-device moves are implemented if (addLocalOnly || volumeCount < 2) { // add volume this item lives on if (volume.SetTo(device) == B_OK && volume.GetRootDirectory(&directory) == B_OK && directory.GetEntry(&entry) == B_OK && model.SetTo(&entry) == B_OK) { navMenu->AddNavDir(&model, what, this, false); // do not have submenu populated navMenu->SetNavDir(model.EntryRef()); } } else { // add all persistent writable volumes volumeRoster.Rewind(); while (volumeRoster.GetNextVolume(&volume) == B_OK) { if (volume.IsReadOnly() || !volume.IsPersistent()) continue; // add root dir if (volume.GetRootDirectory(&directory) == B_OK && directory.GetEntry(&entry) == B_OK && model.SetTo(&entry) == B_OK) { navMenu->AddNavDir(&model, what, this, true); // ask NavMenu to populate submenu for us } } } } void BContainerWindow::SetupMoveCopyMenus(const entry_ref* item_ref, BMenu* parent) { if (IsTrash() || InTrash() || IsPrintersDir() || !fMoveToItem || !fCopyToItem || !fCreateLinkItem || TargetModel()->IsRoot()) { return; } // Grab the modifiers state since we use it twice uint32 modifierKeys = modifiers(); // re-parent items to this menu since they're shared int32 index; BMenuItem* trash = parent->FindItem(kMoveToTrash); if (trash) index = parent->IndexOf(trash) + 2; else index = 0; if (fMoveToItem->Menu() != parent) { if (fMoveToItem->Menu()) fMoveToItem->Menu()->RemoveItem(fMoveToItem); parent->AddItem(fMoveToItem, index++); } if (fCopyToItem->Menu() != parent) { if (fCopyToItem->Menu()) fCopyToItem->Menu()->RemoveItem(fCopyToItem); parent->AddItem(fCopyToItem, index++); } if (fCreateLinkItem->Menu() != parent) { if (fCreateLinkItem->Menu()) fCreateLinkItem->Menu()->RemoveItem(fCreateLinkItem); parent->AddItem(fCreateLinkItem, index); } // Set the "Create Link" item label here so it // appears correctly when menus are disabled, too. if (modifierKeys & B_SHIFT_KEY) fCreateLinkItem->SetLabel(B_TRANSLATE("Create relative link")); else fCreateLinkItem->SetLabel(B_TRANSLATE("Create link")); // only enable once the menus are built fMoveToItem->SetEnabled(false); fCopyToItem->SetEnabled(false); fCreateLinkItem->SetEnabled(false); // get ref for item which is selected BEntry entry; if (entry.SetTo(item_ref) != B_OK) return; Model tempModel(&entry); if (tempModel.InitCheck() != B_OK) return; if (tempModel.IsRoot() || tempModel.IsVolume()) return; // configure "Move to" menu item PopulateMoveCopyNavMenu(dynamic_cast<BNavMenu*>(fMoveToItem->Submenu()), kMoveSelectionTo, item_ref, true); // configure "Copy to" menu item // add all mounted volumes (except the one this item lives on) PopulateMoveCopyNavMenu(dynamic_cast<BNavMenu*>(fCopyToItem->Submenu()), kCopySelectionTo, item_ref, false); // Set "Create Link" menu item message and // add all mounted volumes (except the one this item lives on) if (modifierKeys & B_SHIFT_KEY) { fCreateLinkItem->SetMessage(new BMessage(kCreateRelativeLink)); PopulateMoveCopyNavMenu(dynamic_cast<BNavMenu*> (fCreateLinkItem->Submenu()), kCreateRelativeLink, item_ref, false); } else { fCreateLinkItem->SetMessage(new BMessage(kCreateLink)); PopulateMoveCopyNavMenu(dynamic_cast<BNavMenu*> (fCreateLinkItem->Submenu()), kCreateLink, item_ref, false); } fMoveToItem->SetEnabled(true); fCopyToItem->SetEnabled(true); fCreateLinkItem->SetEnabled(true); // Set the "Identify" item label BMenuItem* identifyItem = parent->FindItem(kIdentifyEntry); if (identifyItem != NULL) { if (modifierKeys & B_SHIFT_KEY) { identifyItem->SetLabel(B_TRANSLATE("Force identify")); identifyItem->Message()->ReplaceBool("force", true); } else { identifyItem->SetLabel(B_TRANSLATE("Identify")); identifyItem->Message()->ReplaceBool("force", false); } } } uint32 BContainerWindow::ShowDropContextMenu(BPoint loc) { BPoint global(loc); PoseView()->ConvertToScreen(&global); PoseView()->CommitActivePose(); // Change the "Create Link" item - allow user to // create relative links with the Shift key down. BMenuItem* item = fDropContextMenu->FindItem(kCreateLink); if (item == NULL) item = fDropContextMenu->FindItem(kCreateRelativeLink); if (item && (modifiers() & B_SHIFT_KEY)) { item->SetLabel(B_TRANSLATE("Create relative link here")); item->SetMessage(new BMessage(kCreateRelativeLink)); } else if (item) { item->SetLabel(B_TRANSLATE("Create link here")); item->SetMessage(new BMessage(kCreateLink)); } item = fDropContextMenu->Go(global, true, true); if (item) return item->Command(); return 0; } void BContainerWindow::ShowContextMenu(BPoint loc, const entry_ref* ref, BView*) { ASSERT(IsLocked()); BPoint global(loc); PoseView()->ConvertToScreen(&global); PoseView()->CommitActivePose(); if (ref != NULL) { // clicked on a pose, show file or volume context menu Model model(ref); if (model.IsTrash()) { if (fTrashContextMenu->Window() || Dragging()) return; DeleteSubmenu(fNavigationItem); // selected item was trash, show the trash context menu instead EnableNamedMenuItem(fTrashContextMenu, kEmptyTrash, static_cast<TTracker*>(be_app)->TrashFull()); SetupNavigationMenu(ref, fTrashContextMenu); fTrashContextMenu->Go(global, true, true, true); } else { bool showAsVolume = false; bool filePanel = PoseView()->IsFilePanel(); if (Dragging()) { fContextMenu = NULL; BEntry entry; model.GetEntry(&entry); // only show for directories (directory, volume, root) // // don't show a popup for the trash or printers // trash is handled in DeskWindow // // since this menu is opened asynchronously // we need to make sure we don't open it more // than once, the IsShowing flag is set in // SlowContextPopup::AttachedToWindow and // reset in DetachedFromWindow // see the notes in SlowContextPopup::AttachedToWindow if (!FSIsPrintersDir(&entry) && !fDragContextMenu->IsShowing()) { //printf("ShowContextMenu - target is %s %i\n", // ref->name, IsShowing(ref)); fDragContextMenu->ClearMenu(); // in case the ref is a symlink, resolve it // only pop open for directories BEntry resolvedEntry(ref, true); if (!resolvedEntry.IsDirectory()) return; entry_ref resolvedRef; resolvedEntry.GetRef(&resolvedRef); // use the resolved ref for the menu fDragContextMenu->SetNavDir(&resolvedRef); fDragContextMenu->SetTypesList(fCachedTypesList); fDragContextMenu->SetTarget(BMessenger(this)); BPoseView* poseView = PoseView(); if (poseView != NULL) { BMessenger target(poseView); fDragContextMenu->InitTrackingHook( &BPoseView::MenuTrackingHook, &target, fDragMessage); } // this is now asynchronous so that we don't // deadlock in Window::Quit, fDragContextMenu->Go(global, true, false, true); } return; } else if (TargetModel()->IsRoot() || model.IsVolume()) { fContextMenu = fVolumeContextMenu; showAsVolume = true; } else fContextMenu = fFileContextMenu; // clean up items from last context menu if (fContextMenu != NULL) { if (fContextMenu->Window()) return; else MenusEnded(); if (model.InitCheck() == B_OK) { // ??? Do I need this ??? if (showAsVolume) { // non-volume enable/disable copy, move, identify EnableNamedMenuItem(fContextMenu, kDuplicateSelection, false); EnableNamedMenuItem(fContextMenu, kMoveToTrash, false); EnableNamedMenuItem(fContextMenu, kIdentifyEntry, false); // volume model, enable/disable the Unmount item bool ejectableVolumeSelected = false; BVolume boot; BVolumeRoster().GetBootVolume(&boot); BVolume volume; volume.SetTo(model.NodeRef()->device); if (volume != boot) ejectableVolumeSelected = true; EnableNamedMenuItem(fContextMenu, B_TRANSLATE("Unmount"), ejectableVolumeSelected); } } SetupNavigationMenu(ref, fContextMenu); if (!showAsVolume && !filePanel) { SetupMoveCopyMenus(ref, fContextMenu); SetupOpenWithMenu(fContextMenu); } UpdateMenu(fContextMenu, kPosePopUpContext); fContextMenu->Go(global, true, true, true); } } } else if (fWindowContextMenu != NULL) { if (fWindowContextMenu->Window()) return; // Repopulate desktop menu if IsDesktop if (fIsDesktop) RepopulateMenus(); MenusEnded(); // clicked on a window, show window context menu SetupNavigationMenu(ref, fWindowContextMenu); UpdateMenu(fWindowContextMenu, kWindowPopUpContext); fWindowContextMenu->Go(global, true, true, true); } fContextMenu = NULL; } void BContainerWindow::AddFileContextMenus(BMenu* menu) { menu->AddItem(new BMenuItem(B_TRANSLATE("Open"), new BMessage(kOpenSelection), 'O')); menu->AddItem(new BMenuItem(B_TRANSLATE("Get info"), new BMessage(kGetInfo), 'I')); menu->AddItem(new BMenuItem(B_TRANSLATE("Edit name"), new BMessage(kEditItem), 'E')); if (!IsTrash() && !InTrash() && !IsPrintersDir()) { menu->AddItem(new BMenuItem(B_TRANSLATE("Duplicate"), new BMessage(kDuplicateSelection), 'D')); } if (!IsTrash() && !InTrash()) { menu->AddItem(new BMenuItem(TrackerSettings().DontMoveFilesToTrash() ? B_TRANSLATE("Delete") : B_TRANSLATE("Move to Trash"), new BMessage(kMoveToTrash), 'T')); if (!IsPrintersDir()) { // add separator for copy to/move to items (navigation items) menu->AddSeparatorItem(); } } else { menu->AddItem(new BMenuItem(B_TRANSLATE("Delete"), new BMessage(kDelete), 0)); menu->AddItem(new BMenuItem(B_TRANSLATE("Restore"), new BMessage(kRestoreFromTrash), 0)); } #ifdef CUT_COPY_PASTE_IN_CONTEXT_MENU menu->AddSeparatorItem(); BMenuItem* cutItem = new BMenuItem(B_TRANSLATE("Cut"), new BMessage(B_CUT), 'X'); menu->AddItem(cutItem); BMenuItem* copyItem = new BMenuItem(B_TRANSLATE("Copy"), new BMessage(B_COPY), 'C'); menu->AddItem(copyItem); #endif menu->AddSeparatorItem(); BMessage* message = new BMessage(kIdentifyEntry); message->AddBool("force", false); menu->AddItem(new BMenuItem(B_TRANSLATE("Identify"), message)); BMenu* addOnMenuItem = new BMenu(B_TRANSLATE("Add-ons")); addOnMenuItem->SetFont(be_plain_font); menu->AddItem(addOnMenuItem); // set targets as needed menu->SetTargetForItems(PoseView()); #ifdef CUT_COPY_PASTE_IN_CONTEXT_MENU cutItem->SetTarget(this); copyItem->SetTarget(this); #endif } void BContainerWindow::AddVolumeContextMenus(BMenu* menu) { menu->AddItem(new BMenuItem(B_TRANSLATE("Open"), new BMessage(kOpenSelection), 'O')); menu->AddItem(new BMenuItem(B_TRANSLATE("Get info"), new BMessage(kGetInfo), 'I')); menu->AddItem(new BMenuItem(B_TRANSLATE("Edit name"), new BMessage(kEditItem), 'E')); menu->AddSeparatorItem(); menu->AddItem(new MountMenu(B_TRANSLATE("Mount"))); BMenuItem* item = new BMenuItem(B_TRANSLATE("Unmount"), new BMessage(kUnmountVolume), 'U'); item->SetEnabled(false); menu->AddItem(item); menu->AddSeparatorItem(); menu->AddItem(new BMenu(B_TRANSLATE("Add-ons"))); menu->SetTargetForItems(PoseView()); } void BContainerWindow::AddWindowContextMenus(BMenu* menu) { // create context sensitive menu for empty area of window // since we check view mode before display, this should be a radio // mode menu Model* targetModel = TargetModel(); ASSERT(targetModel != NULL); bool needSeparator = true; if (IsTrash()) { menu->AddItem(new BMenuItem(B_TRANSLATE("Empty Trash"), new BMessage(kEmptyTrash))); } else if (IsPrintersDir()) { menu->AddItem(new BMenuItem(B_TRANSLATE("Add printer" B_UTF8_ELLIPSIS), new BMessage(kAddPrinter), 'N')); } else if (InTrash() || targetModel->IsRoot()) { needSeparator = false; } else { TemplatesMenu* templatesMenu = new TemplatesMenu(PoseView(), B_TRANSLATE("New")); menu->AddItem(templatesMenu); templatesMenu->SetTargetForItems(PoseView()); templatesMenu->SetFont(be_plain_font); } if (needSeparator) menu->AddSeparatorItem(); #ifdef CUT_COPY_PASTE_IN_CONTEXT_MENU BMenuItem* pasteItem = new BMenuItem("Paste", new BMessage(B_PASTE), 'V'); menu->AddItem(pasteItem); menu->AddSeparatorItem(); #endif BMenu* arrangeBy = new BMenu(B_TRANSLATE("Arrange by")); PopulateArrangeByMenu(arrangeBy); menu->AddItem(arrangeBy); menu->AddItem(new BMenuItem(B_TRANSLATE("Select" B_UTF8_ELLIPSIS), new BMessage(kShowSelectionWindow), 'A', B_SHIFT_KEY)); menu->AddItem(new BMenuItem(B_TRANSLATE("Select all"), new BMessage(B_SELECT_ALL), 'A')); if (!IsTrash()) { menu->AddItem(new BMenuItem(B_TRANSLATE("Open parent"), new BMessage(kOpenParentDir), B_UP_ARROW)); } if (targetModel->IsRoot()) { menu->AddSeparatorItem(); menu->AddItem(new MountMenu(B_TRANSLATE("Mount"))); } menu->AddSeparatorItem(); BMenu* addOnMenuItem = new BMenu(B_TRANSLATE("Add-ons")); addOnMenuItem->SetFont(be_plain_font); menu->AddItem(addOnMenuItem); #if DEBUG menu->AddSeparatorItem(); BMenuItem* testing = new BMenuItem("Test icon cache", new BMessage(kTestIconCache)); menu->AddItem(testing); #endif // target items as needed menu->SetTargetForItems(PoseView()); #ifdef CUT_COPY_PASTE_IN_CONTEXT_MENU pasteItem->SetTarget(this); #endif } void BContainerWindow::AddDropContextMenus(BMenu* menu) { menu->AddItem(new BMenuItem(B_TRANSLATE("Create link here"), new BMessage(kCreateLink))); menu->AddItem(new BMenuItem(B_TRANSLATE("Move here"), new BMessage(kMoveSelectionTo))); menu->AddItem(new BMenuItem(B_TRANSLATE("Copy here"), new BMessage(kCopySelectionTo))); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem(B_TRANSLATE("Cancel"), new BMessage(kCancelButton))); } void BContainerWindow::AddTrashContextMenus(BMenu* menu) { // setup special trash context menu menu->AddItem(new BMenuItem(B_TRANSLATE("Empty Trash"), new BMessage(kEmptyTrash))); menu->AddItem(new BMenuItem(B_TRANSLATE("Open"), new BMessage(kOpenSelection), 'O')); menu->AddItem(new BMenuItem(B_TRANSLATE("Get info"), new BMessage(kGetInfo), 'I')); menu->SetTargetForItems(PoseView()); } void BContainerWindow::EachAddon(bool (*eachAddon)(const Model*, const char*, uint32 shortcut, uint32 modifiers, bool primary, void* context), void* passThru, BStringList& mimeTypes) { AutoLock<LockingList<AddonShortcut> > lock(fAddonsList); if (lock.IsLocked()) { for (int i = fAddonsList->CountItems() - 1; i >= 0; i--) { struct AddonShortcut* item = fAddonsList->ItemAt(i); bool primary = false; if (mimeTypes.CountStrings() > 0) { BFile file(item->model->EntryRef(), B_READ_ONLY); if (file.InitCheck() == B_OK) { BAppFileInfo info(&file); if (info.InitCheck() == B_OK) { bool secondary = true; // does this add-on has types set at all? BMessage message; if (info.GetSupportedTypes(&message) == B_OK) { type_code typeCode; int32 count; if (message.GetInfo("types", &typeCode, &count) == B_OK) { secondary = false; } } // check all supported types if it has some set if (!secondary) { for (int32 i = mimeTypes.CountStrings(); !primary && i-- > 0;) { BString type = mimeTypes.StringAt(i); if (info.IsSupportedType(type.String())) { BMimeType mimeType(type.String()); if (info.Supports(&mimeType)) primary = true; else secondary = true; } } } if (!secondary && !primary) continue; } } } ((eachAddon)(item->model, item->model->Name(), item->key, item->modifiers, primary, passThru)); } } } void BContainerWindow::BuildMimeTypeList(BStringList& mimeTypes) { int32 count = PoseView()->SelectionList()->CountItems(); if (count <= 0) { // just add the type of the current directory AddMimeTypeString(mimeTypes, TargetModel()); } else { _UpdateSelectionMIMEInfo(); for (int32 index = 0; index < count; index++) { BPose* pose = PoseView()->SelectionList()->ItemAt(index); AddMimeTypeString(mimeTypes, pose->TargetModel()); // If it's a symlink, resolves it and add the Target's MimeType if (pose->TargetModel()->IsSymLink()) { Model* resolved = new Model( pose->TargetModel()->EntryRef(), true, true); if (resolved->InitCheck() == B_OK) AddMimeTypeString(mimeTypes, resolved); delete resolved; } } } } void BContainerWindow::BuildAddOnMenu(BMenu* menu) { BMenuItem* item = menu->FindItem(B_TRANSLATE("Add-ons")); if (menu->IndexOf(item) == 0) { // the folder of the context menu seems to be named "Add-Ons" // so we just take the last menu item, which is correct if not // build with debug option item = menu->ItemAt(menu->CountItems() - 1); } if (item == NULL) return; BFont font; menu->GetFont(&font); menu = item->Submenu(); if (menu == NULL) return; menu->SetFont(&font); // found the addons menu, empty it first for (;;) { item = menu->RemoveItem((int32)0); if (!item) break; delete item; } BObjectList<BMenuItem> primaryList; BObjectList<BMenuItem> secondaryList; BStringList mimeTypes(10); BuildMimeTypeList(mimeTypes); AddOneAddonParams params; params.primaryList = &primaryList; params.secondaryList = &secondaryList; // build a list of the MIME types of the selected items EachAddon(AddOneAddon, &params, mimeTypes); primaryList.SortItems(CompareLabels); secondaryList.SortItems(CompareLabels); int32 count = primaryList.CountItems(); for (int32 index = 0; index < count; index++) menu->AddItem(primaryList.ItemAt(index)); if (count > 0) menu->AddSeparatorItem(); count = secondaryList.CountItems(); for (int32 index = 0; index < count; index++) menu->AddItem(secondaryList.ItemAt(index)); menu->SetTargetForItems(this); } void BContainerWindow::UpdateMenu(BMenu* menu, UpdateMenuContext context) { const int32 selectCount = PoseView()->SelectionList()->CountItems(); const int32 count = PoseView()->CountItems(); if (context == kMenuBarContext) { EnableNamedMenuItem(menu, kOpenSelection, selectCount > 0); EnableNamedMenuItem(menu, kGetInfo, selectCount > 0); EnableNamedMenuItem(menu, kIdentifyEntry, selectCount > 0); EnableNamedMenuItem(menu, kMoveToTrash, selectCount > 0); EnableNamedMenuItem(menu, kRestoreFromTrash, selectCount > 0); EnableNamedMenuItem(menu, kDelete, selectCount > 0); EnableNamedMenuItem(menu, kDuplicateSelection, selectCount > 0); } Model* selectedModel = NULL; if (selectCount == 1) { selectedModel = PoseView()->SelectionList()->FirstItem()-> TargetModel(); } if (context == kMenuBarContext || context == kPosePopUpContext) { SetUpEditQueryItem(menu); EnableNamedMenuItem(menu, kEditItem, selectCount == 1 && (context == kPosePopUpContext || !PoseView()->ActivePose()) && selectedModel != NULL && !selectedModel->IsDesktop() && !selectedModel->IsRoot() && !selectedModel->IsTrash() && !selectedModel->HasLocalizedName()); SetCutItem(menu); SetCopyItem(menu); SetPasteItem(menu); } if (context == kMenuBarContext || context == kWindowPopUpContext) { uint32 viewMode = PoseView()->ViewMode(); BMenu* iconSizeMenu = NULL; if (BMenuItem* item = menu->FindItem(kIconMode)) iconSizeMenu = item->Submenu(); if (iconSizeMenu != NULL) { if (viewMode == kIconMode) { int32 iconSize = PoseView()->IconSizeInt(); BMenuItem* item = iconSizeMenu->ItemAt(0); for (int32 i = 0; (item = iconSizeMenu->ItemAt(i)) != NULL; i++) { BMessage* message = item->Message(); if (message == NULL) { item->SetMarked(false); continue; } int32 size; if (message->FindInt32("size", &size) != B_OK) size = -1; item->SetMarked(iconSize == size); } } else { BMenuItem* item; for (int32 i = 0; (item = iconSizeMenu->ItemAt(i)) != NULL; i++) item->SetMarked(false); } } BMenu* listSizeMenu = NULL; if (BMenuItem* item = menu->FindItem(kListMode)) listSizeMenu = item->Submenu(); if (listSizeMenu != NULL) { if (viewMode == kListMode) { int32 iconSize = PoseView()->IconSizeInt(); BMenuItem* item = listSizeMenu->ItemAt(0); for (int32 i = 0; (item = listSizeMenu->ItemAt(i)) != NULL; i++) { BMessage* message = item->Message(); if (message == NULL) { item->SetMarked(false); continue; } int32 size; if (message->FindInt32("icon_size", &size) != B_OK) size = -1; item->SetMarked(iconSize == size); } } else { BMenuItem* item; for (int32 i = 0; (item = listSizeMenu->ItemAt(i)) != NULL; i++) item->SetMarked(false); } } MarkNamedMenuItem(menu, kIconMode, viewMode == kIconMode); MarkNamedMenuItem(menu, kListMode, viewMode == kListMode); MarkNamedMenuItem(menu, kMiniIconMode, viewMode == kMiniIconMode); SetCloseItem(menu); SetArrangeMenu(menu); SetPasteItem(menu); BEntry entry(TargetModel()->EntryRef()); BDirectory parent; entry_ref ref; BEntry root("/"); bool parentIsRoot = (entry.GetParent(&parent) == B_OK && parent.GetEntry(&entry) == B_OK && entry.GetRef(&ref) == B_OK && entry == root); EnableNamedMenuItem(menu, kOpenParentDir, !TargetModel()->IsDesktop() && !TargetModel()->IsRoot() && (!parentIsRoot || TrackerSettings().SingleWindowBrowse() || TrackerSettings().ShowDisksIcon() || (modifiers() & B_CONTROL_KEY) != 0)); EnableNamedMenuItem(menu, kEmptyTrash, count > 0); EnableNamedMenuItem(menu, B_SELECT_ALL, count > 0); BMenuItem* item = menu->FindItem(B_TRANSLATE("New")); if (item != NULL) { TemplatesMenu* templatesMenu = dynamic_cast<TemplatesMenu*>( item->Submenu()); if (templatesMenu != NULL) templatesMenu->UpdateMenuState(); } } BuildAddOnMenu(menu); } void BContainerWindow::LoadAddOn(BMessage* message) { UpdateIfNeeded(); entry_ref addonRef; status_t result = message->FindRef("refs", &addonRef); if (result != B_OK) { BString buffer(B_TRANSLATE("Error %error loading add-On %name.")); buffer.ReplaceFirst("%error", strerror(result)); buffer.ReplaceFirst("%name", addonRef.name); BAlert* alert = new BAlert("", buffer.String(), B_TRANSLATE("Cancel"), 0, 0, B_WIDTH_AS_USUAL, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); return; } // add selected refs to message BMessage* refs = new BMessage(B_REFS_RECEIVED); BObjectList<BPose>* selectionList = PoseView()->SelectionList(); int32 index = 0; BPose* pose; while ((pose = selectionList->ItemAt(index++)) != NULL) refs->AddRef("refs", pose->TargetModel()->EntryRef()); refs->AddMessenger("TrackerViewToken", BMessenger(PoseView())); LaunchInNewThread("Add-on", B_NORMAL_PRIORITY, &AddOnThread, refs, addonRef, *TargetModel()->EntryRef()); } void BContainerWindow::_UpdateSelectionMIMEInfo() { BPose* pose; int32 index = 0; while ((pose = PoseView()->SelectionList()->ItemAt(index++)) != NULL) { BString mimeType(pose->TargetModel()->MimeType()); if (!mimeType.Length() || mimeType.ICompare(B_FILE_MIMETYPE) == 0) { pose->TargetModel()->Mimeset(true); if (pose->TargetModel()->IsSymLink()) { Model* resolved = new Model(pose->TargetModel()->EntryRef(), true, true); if (resolved->InitCheck() == B_OK) { mimeType.SetTo(resolved->MimeType()); if (!mimeType.Length() || mimeType.ICompare(B_FILE_MIMETYPE) == 0) { resolved->Mimeset(true); } } delete resolved; } } } } void BContainerWindow::_AddFolderIcon() { if (fMenuBar == NULL) { // We don't want to add the icon if there's no menubar return; } float iconSize = fMenuBar->Bounds().Height() - 2; if (iconSize < 16) iconSize = 16; fDraggableIcon = new(std::nothrow) DraggableContainerIcon(); if (fDraggableIcon != NULL) { BLayoutItem* item = fMenuContainer->GroupLayout()->AddView( fDraggableIcon); item->SetExplicitMinSize(BSize(iconSize + 5, iconSize)); item->SetExplicitMaxSize(BSize(iconSize + 5, item->MaxSize().Height())); fMenuBar->SetBorders( BControlLook::B_ALL_BORDERS & ~BControlLook::B_RIGHT_BORDER); } } BMenuItem* BContainerWindow::NewAttributeMenuItem(const char* label, const char* name, int32 type, float width, int32 align, bool editable, bool statField) { return NewAttributeMenuItem(label, name, type, NULL, width, align, editable, statField); } BMenuItem* BContainerWindow::NewAttributeMenuItem(const char* label, const char* name, int32 type, const char* displayAs, float width, int32 align, bool editable, bool statField) { BMessage* message = new BMessage(kAttributeItem); message->AddString("attr_name", name); message->AddInt32("attr_type", type); message->AddInt32("attr_hash", (int32)AttrHashString(name, (uint32)type)); message->AddFloat("attr_width", width); message->AddInt32("attr_align", align); if (displayAs != NULL) message->AddString("attr_display_as", displayAs); message->AddBool("attr_editable", editable); message->AddBool("attr_statfield", statField); BMenuItem* menuItem = new BMenuItem(label, message); menuItem->SetTarget(PoseView()); return menuItem; } void BContainerWindow::NewAttributeMenu(BMenu* menu) { ASSERT(PoseView()); BMenuItem* item; menu->AddItem(item = new BMenuItem(B_TRANSLATE("Copy layout"), new BMessage(kCopyAttributes))); item->SetTarget(PoseView()); menu->AddItem(item = new BMenuItem(B_TRANSLATE("Paste layout"), new BMessage(kPasteAttributes))); item->SetTarget(PoseView()); menu->AddSeparatorItem(); menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Name"), kAttrStatName, B_STRING_TYPE, 145, B_ALIGN_LEFT, true, true)); if (gLocalizedNamePreferred) { menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Real name"), kAttrRealName, B_STRING_TYPE, 145, B_ALIGN_LEFT, true, true)); } menu->AddItem(NewAttributeMenuItem (B_TRANSLATE("Size"), kAttrStatSize, B_OFF_T_TYPE, 80, B_ALIGN_RIGHT, false, true)); menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Modified"), kAttrStatModified, B_TIME_TYPE, 150, B_ALIGN_LEFT, false, true)); menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Created"), kAttrStatCreated, B_TIME_TYPE, 150, B_ALIGN_LEFT, false, true)); menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Kind"), kAttrMIMEType, B_MIME_STRING_TYPE, 145, B_ALIGN_LEFT, false, false)); if (IsTrash() || InTrash()) { menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Original name"), kAttrOriginalPath, B_STRING_TYPE, 225, B_ALIGN_LEFT, false, false)); } else { menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Location"), kAttrPath, B_STRING_TYPE, 225, B_ALIGN_LEFT, false, false)); } #ifdef OWNER_GROUP_ATTRIBUTES menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Owner"), kAttrStatOwner, B_STRING_TYPE, 60, B_ALIGN_LEFT, false, true)); menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Group"), kAttrStatGroup, B_STRING_TYPE, 60, B_ALIGN_LEFT, false, true)); #endif menu->AddItem(NewAttributeMenuItem(B_TRANSLATE("Permissions"), kAttrStatMode, B_STRING_TYPE, 80, B_ALIGN_LEFT, false, true)); } void BContainerWindow::ShowAttributeMenu() { ASSERT(fAttrMenu); fMenuBar->AddItem(fAttrMenu); } void BContainerWindow::HideAttributeMenu() { ASSERT(fAttrMenu); fMenuBar->RemoveItem(fAttrMenu); } void BContainerWindow::MarkAttributeMenu() { MarkAttributeMenu(fAttrMenu); } void BContainerWindow::MarkAttributeMenu(BMenu* menu) { if (!menu) return; int32 count = menu->CountItems(); for (int32 index = 0; index < count; index++) { BMenuItem* item = menu->ItemAt(index); int32 attrHash; if (item->Message()) { if (item->Message()->FindInt32("attr_hash", &attrHash) == B_OK) item->SetMarked(PoseView()->ColumnFor((uint32)attrHash) != 0); else item->SetMarked(false); } BMenu* submenu = item->Submenu(); if (submenu) { int32 count2 = submenu->CountItems(); for (int32 subindex = 0; subindex < count2; subindex++) { item = submenu->ItemAt(subindex); if (item->Message()) { if (item->Message()->FindInt32("attr_hash", &attrHash) == B_OK) { item->SetMarked(PoseView()->ColumnFor((uint32)attrHash) != 0); } else item->SetMarked(false); } } } } } void BContainerWindow::MarkArrangeByMenu(BMenu* menu) { if (!menu) return; int32 count = menu->CountItems(); for (int32 index = 0; index < count; index++) { BMenuItem* item = menu->ItemAt(index); if (item->Message()) { uint32 attrHash; if (item->Message()->FindInt32("attr_hash", (int32*)&attrHash) == B_OK) { item->SetMarked(PoseView()->PrimarySort() == attrHash); } else if (item->Command() == kArrangeReverseOrder) item->SetMarked(PoseView()->ReverseSort()); } } } void BContainerWindow::AddMimeTypesToMenu() { AddMimeTypesToMenu(fAttrMenu); } // Adds a menu for a specific MIME type if it doesn't exist already. // Returns the menu, if it existed or not. BMenu* BContainerWindow::AddMimeMenu(const BMimeType& mimeType, bool isSuperType, BMenu* menu, int32 start) { AutoLock<BLooper> _(menu->Looper()); if (!mimeType.IsValid()) return NULL; // Check if we already have an entry for this MIME type in the menu. for (int32 i = start; BMenuItem* item = menu->ItemAt(i); i++) { BMessage* message = item->Message(); if (message == NULL) continue; const char* type; if (message->FindString("mimetype", &type) == B_OK && !strcmp(mimeType.Type(), type)) { return item->Submenu(); } } BMessage attrInfo; char description[B_MIME_TYPE_LENGTH]; const char* label = mimeType.Type(); if (!mimeType.IsInstalled()) return NULL; // only add things to menu which have "user-visible" data if (mimeType.GetAttrInfo(&attrInfo) != B_OK) return NULL; if (mimeType.GetShortDescription(description) == B_OK && description[0]) label = description; // go through each field in meta mime and add it to a menu BMenu* mimeMenu = NULL; if (isSuperType) { // If it is a supertype, we create the menu anyway as it may have // submenus later on. mimeMenu = new BMenu(label); BFont font; menu->GetFont(&font); mimeMenu->SetFont(&font); } int32 index = -1; const char* publicName; while (attrInfo.FindString("attr:public_name", ++index, &publicName) == B_OK) { if (!attrInfo.FindBool("attr:viewable", index)) { // don't add if attribute not viewable continue; } int32 type; int32 align; int32 width; bool editable; const char* attrName; if (attrInfo.FindString("attr:name", index, &attrName) != B_OK || attrInfo.FindInt32("attr:type", index, &type) != B_OK || attrInfo.FindBool("attr:editable", index, &editable) != B_OK || attrInfo.FindInt32("attr:width", index, &width) != B_OK || attrInfo.FindInt32("attr:alignment", index, &align) != B_OK) continue; BString displayAs; attrInfo.FindString("attr:display_as", index, &displayAs); if (mimeMenu == NULL) { // do a lazy allocation of the menu mimeMenu = new BMenu(label); BFont font; menu->GetFont(&font); mimeMenu->SetFont(&font); } mimeMenu->AddItem(NewAttributeMenuItem(publicName, attrName, type, displayAs.String(), width, align, editable, false)); } if (mimeMenu == NULL) return NULL; BMessage* message = new BMessage(kMIMETypeItem); message->AddString("mimetype", mimeType.Type()); menu->AddItem(new IconMenuItem(mimeMenu, message, mimeType.Type())); return mimeMenu; } void BContainerWindow::AddMimeTypesToMenu(BMenu* menu) { if (!menu) return; // Remove old mime type menus int32 start = menu->CountItems(); while (start > 0 && menu->ItemAt(start - 1)->Submenu() != NULL) { delete menu->RemoveItem(start - 1); start--; } // Add a separator item if there is none yet if (start > 0 && dynamic_cast<BSeparatorItem*>(menu->ItemAt(start - 1)) == NULL) menu->AddSeparatorItem(); // Add MIME type in case we're a default query type window BPath path; if (TargetModel() != NULL) { TargetModel()->GetPath(&path); if (path.InitCheck() == B_OK && strstr(path.Path(), "/" kQueryTemplates "/") != NULL) { // demangle MIME type name BString name(TargetModel()->Name()); name.ReplaceFirst('_', '/'); PoseView()->AddMimeType(name.String()); } } // Add MIME type menus int32 typeCount = PoseView()->CountMimeTypes(); for (int32 index = 0; index < typeCount; index++) { BMimeType mimeType(PoseView()->MimeTypeAt(index)); if (mimeType.InitCheck() == B_OK) { BMimeType superType; mimeType.GetSupertype(&superType); if (superType.InitCheck() == B_OK) { BMenu* superMenu = AddMimeMenu(superType, true, menu, start); if (superMenu != NULL) { // We have a supertype menu. AddMimeMenu(mimeType, false, superMenu, 0); } } } } // remove empty super menus, promote sub-types if needed for (int32 index = 0; index < typeCount; index++) { BMimeType mimeType(PoseView()->MimeTypeAt(index)); BMimeType superType; mimeType.GetSupertype(&superType); BMenu* superMenu = AddMimeMenu(superType, true, menu, start); if (superMenu == NULL) continue; int32 itemsFound = 0; int32 menusFound = 0; for (int32 i = 0; BMenuItem* item = superMenu->ItemAt(i); i++) { if (item->Submenu() != NULL) menusFound++; else itemsFound++; } if (itemsFound == 0) { if (menusFound != 0) { // promote types to the top level while (BMenuItem* item = superMenu->RemoveItem((int32)0)) { menu->AddItem(item); } } menu->RemoveItem(superMenu->Superitem()); delete superMenu->Superitem(); } } // remove separator if it's the only item in menu BMenuItem* item = menu->ItemAt(menu->CountItems() - 1); if (dynamic_cast<BSeparatorItem*>(item) != NULL) { menu->RemoveItem(item); delete item; } MarkAttributeMenu(menu); } BHandler* BContainerWindow::ResolveSpecifier(BMessage* message, int32 index, BMessage* specifier, int32 form, const char* property) { if (strcmp(property, "Poses") == 0) { // PRINT(("BContainerWindow::ResolveSpecifier %s\n", property)); message->PopSpecifier(); return PoseView(); } return _inherited::ResolveSpecifier(message, index, specifier, form, property); } PiggybackTaskLoop* BContainerWindow::DelayedTaskLoop() { if (!fTaskLoop) fTaskLoop = new PiggybackTaskLoop; return fTaskLoop; } bool BContainerWindow::NeedsDefaultStateSetup() { if (TargetModel() == NULL) return false; if (TargetModel()->IsRoot()) { // don't try to set up anything if we are root return false; } WindowStateNodeOpener opener(this, false); if (opener.StreamNode() == NULL) { // can't read state, give up return false; } return !NodeHasSavedState(opener.Node()); } bool BContainerWindow::DefaultStateSourceNode(const char* name, BNode* result, bool createNew, bool createFolder) { //PRINT(("looking for default state in tracker settings dir\n")); BPath settingsPath; if (FSFindTrackerSettingsDir(&settingsPath) != B_OK) return false; BDirectory dir(settingsPath.Path()); BPath path(settingsPath); path.Append(name); if (!BEntry(path.Path()).Exists()) { if (!createNew) return false; BPath tmpPath(settingsPath); for (;;) { // deal with several levels of folders const char* nextSlash = strchr(name, '/'); if (!nextSlash) break; BString tmp; tmp.SetTo(name, nextSlash - name); tmpPath.Append(tmp.String()); mkdir(tmpPath.Path(), 0777); name = nextSlash + 1; if (!name[0]) { // can't deal with a slash at end return false; } } if (createFolder) { if (mkdir(path.Path(), 0777) < 0) return false; } else { BFile file; if (dir.CreateFile(name, &file) != B_OK) return false; } } //PRINT(("using default state from %s\n", path.Path())); result->SetTo(path.Path()); return result->InitCheck() == B_OK; } void BContainerWindow::SetUpDefaultState() { BNode defaultingNode; // this is where we'll ulitimately get the state from bool gotDefaultingNode = 0; bool shouldStagger = false; ASSERT(TargetModel() != NULL); PRINT(("folder %s does not have any saved state\n", TargetModel()->Name())); WindowStateNodeOpener opener(this, true); // this is our destination node, whatever it is for this window if (opener.StreamNode() == NULL) return; if (!TargetModel()->IsRoot()) { BDirectory deskDir; FSGetDeskDir(&deskDir); // try copying state from our parent directory, unless it is the // desktop folder BEntry entry(TargetModel()->EntryRef()); BNode parent; if (FSGetParentVirtualDirectoryAware(entry, parent) == B_OK && parent != deskDir) { PRINT(("looking at parent for state\n")); if (NodeHasSavedState(&parent)) { PRINT(("got state from parent\n")); defaultingNode = parent; gotDefaultingNode = true; // when getting state from parent, stagger the window shouldStagger = true; } } } if (!gotDefaultingNode // parent didn't have any state, use the template directory from // tracker settings folder for what our state should be // For simplicity we are not picking up the most recent // changes that didn't get committed if home is still open in // a window, that's probably not a problem; would be OK if state // got committed after every change && !DefaultStateSourceNode(kDefaultFolderTemplate, &defaultingNode, true)) { return; } if (fIsDesktop) { // don't copy over the attributes if we are the Desktop return; } // copy over the attributes // set up a filter of the attributes we want copied const char* allowAttrs[] = { kAttrWindowFrame, kAttrWindowWorkspace, kAttrViewState, kAttrViewStateForeign, kAttrColumns, kAttrColumnsForeign, 0 }; // copy over attributes that apply; transform them properly, stripping // parts that do not apply, adding a window stagger, etc. StaggerOneParams params; params.rectFromParent = shouldStagger; SelectiveAttributeTransformer frameOffsetter(kAttrWindowFrame, OffsetFrameOne, &params); SelectiveAttributeTransformer scrollOriginCleaner(kAttrViewState, ClearViewOriginOne, &params); // do it AttributeStreamMemoryNode memoryNode; NamesToAcceptAttrFilter filter(allowAttrs); AttributeStreamFileNode fileNode(&defaultingNode); *opener.StreamNode() << scrollOriginCleaner << frameOffsetter << memoryNode << filter << fileNode; } void BContainerWindow::RestoreWindowState(AttributeStreamNode* node) { if (node == NULL || fIsDesktop) { // don't restore any window state if we are the Desktop return; } const char* rectAttributeName; const char* workspaceAttributeName; if (TargetModel()->IsRoot()) { rectAttributeName = kAttrDisksFrame; workspaceAttributeName = kAttrDisksWorkspace; } else { rectAttributeName = kAttrWindowFrame; workspaceAttributeName = kAttrWindowWorkspace; } BRect frame(Frame()); if (node->Read(rectAttributeName, 0, B_RECT_TYPE, sizeof(BRect), &frame) == sizeof(BRect)) { MoveTo(frame.LeftTop()); ResizeTo(frame.Width(), frame.Height()); } else sNewWindRect.OffsetBy(kWindowStaggerBy, kWindowStaggerBy); fPreviousBounds = Bounds(); uint32 workspace; if (((fContainerWindowFlags & kRestoreWorkspace) != 0) && node->Read(workspaceAttributeName, 0, B_INT32_TYPE, sizeof(uint32), &workspace) == sizeof(uint32)) SetWorkspaces(workspace); if ((fContainerWindowFlags & kIsHidden) != 0) Minimize(true); // restore window decor settings int32 size = node->Contains(kAttrWindowDecor, B_RAW_TYPE); if (size > 0) { char buffer[size]; if (((fContainerWindowFlags & kRestoreDecor) != 0) && node->Read(kAttrWindowDecor, 0, B_RAW_TYPE, size, buffer) == size) { BMessage decorSettings; if (decorSettings.Unflatten(buffer) == B_OK) SetDecoratorSettings(decorSettings); } } } void BContainerWindow::RestoreWindowState(const BMessage& message) { if (fIsDesktop) { // don't restore any window state if we are the Desktop return; } const char* rectAttributeName; const char* workspaceAttributeName; if (TargetModel()->IsRoot()) { rectAttributeName = kAttrDisksFrame; workspaceAttributeName = kAttrDisksWorkspace; } else { rectAttributeName = kAttrWindowFrame; workspaceAttributeName = kAttrWindowWorkspace; } BRect frame(Frame()); if (message.FindRect(rectAttributeName, &frame) == B_OK) { MoveTo(frame.LeftTop()); ResizeTo(frame.Width(), frame.Height()); } else sNewWindRect.OffsetBy(kWindowStaggerBy, kWindowStaggerBy); uint32 workspace; if ((fContainerWindowFlags & kRestoreWorkspace) && message.FindInt32(workspaceAttributeName, (int32*)&workspace) == B_OK) { SetWorkspaces(workspace); } if (fContainerWindowFlags & kIsHidden) Minimize(true); // restore window decor settings BMessage decorSettings; if ((fContainerWindowFlags & kRestoreDecor) && message.FindMessage(kAttrWindowDecor, &decorSettings) == B_OK) { SetDecoratorSettings(decorSettings); } } void BContainerWindow::SaveWindowState(AttributeStreamNode* node) { if (fIsDesktop) { // don't save window state if we are the Desktop return; } ASSERT(node != NULL); const char* rectAttributeName; const char* workspaceAttributeName; if (TargetModel() != NULL && TargetModel()->IsRoot()) { rectAttributeName = kAttrDisksFrame; workspaceAttributeName = kAttrDisksWorkspace; } else { rectAttributeName = kAttrWindowFrame; workspaceAttributeName = kAttrWindowWorkspace; } // node is null if it already got deleted BRect frame(Frame()); node->Write(rectAttributeName, 0, B_RECT_TYPE, sizeof(BRect), &frame); uint32 workspaces = Workspaces(); node->Write(workspaceAttributeName, 0, B_INT32_TYPE, sizeof(uint32), &workspaces); BMessage decorSettings; if (GetDecoratorSettings(&decorSettings) == B_OK) { int32 size = decorSettings.FlattenedSize(); char buffer[size]; if (decorSettings.Flatten(buffer, size) == B_OK) { node->Write(kAttrWindowDecor, 0, B_RAW_TYPE, size, buffer); } } } void BContainerWindow::SaveWindowState(BMessage& message) const { const char* rectAttributeName; const char* workspaceAttributeName; if (TargetModel() != NULL && TargetModel()->IsRoot()) { rectAttributeName = kAttrDisksFrame; workspaceAttributeName = kAttrDisksWorkspace; } else { rectAttributeName = kAttrWindowFrame; workspaceAttributeName = kAttrWindowWorkspace; } // node is null if it already got deleted BRect frame(Frame()); message.AddRect(rectAttributeName, frame); message.AddInt32(workspaceAttributeName, (int32)Workspaces()); BMessage decorSettings; if (GetDecoratorSettings(&decorSettings) == B_OK) { message.AddMessage(kAttrWindowDecor, &decorSettings); } } status_t BContainerWindow::DragStart(const BMessage* dragMessage) { if (dragMessage == NULL) return B_ERROR; // if already dragging, or // if all the refs match if (Dragging() && SpringLoadedFolderCompareMessages(dragMessage, fDragMessage)) { return B_OK; } // cache the current drag message // build a list of the mimetypes in the message SpringLoadedFolderCacheDragData(dragMessage, &fDragMessage, &fCachedTypesList); fWaitingForRefs = true; return B_OK; } void BContainerWindow::DragStop() { delete fDragMessage; fDragMessage = NULL; delete fCachedTypesList; fCachedTypesList = NULL; fWaitingForRefs = false; } void BContainerWindow::ShowSelectionWindow() { if (fSelectionWindow == NULL) { fSelectionWindow = new SelectionWindow(this); fSelectionWindow->Show(); } else if (fSelectionWindow->Lock()) { // The window is already there, just bring it close fSelectionWindow->MoveCloseToMouse(); if (fSelectionWindow->IsHidden()) fSelectionWindow->Show(); fSelectionWindow->Unlock(); } } void BContainerWindow::ShowNavigator(bool show) { if (PoseView()->IsDesktopWindow() || !TargetModel()->IsDirectory() || fPoseView->IsFilePanel()) { return; } if (show) { if (Navigator() && !Navigator()->IsHidden()) return; if (Navigator() == NULL) { fNavigator = new BNavigator(TargetModel()); fPoseContainer->GridLayout()->AddView(fNavigator, 0, 0, 2); } if (Navigator()->IsHidden()) Navigator()->Show(); if (PoseView()->VScrollBar()) PoseView()->UpdateScrollRange(); } else { if (!Navigator() || Navigator()->IsHidden()) return; if (PoseView()->VScrollBar()) PoseView()->UpdateScrollRange(); fNavigator->Hide(); } } void BContainerWindow::SetSingleWindowBrowseShortcuts(bool enabled) { if (PoseView()->IsDesktopWindow()) return; if (enabled) { if (!Navigator()) return; RemoveShortcut(B_DOWN_ARROW, B_COMMAND_KEY | B_OPTION_KEY); RemoveShortcut(B_UP_ARROW, B_COMMAND_KEY); RemoveShortcut(B_UP_ARROW, B_COMMAND_KEY | B_OPTION_KEY); AddShortcut(B_LEFT_ARROW, B_COMMAND_KEY, new BMessage(kNavigatorCommandBackward), Navigator()); AddShortcut(B_RIGHT_ARROW, B_COMMAND_KEY, new BMessage(kNavigatorCommandForward), Navigator()); AddShortcut(B_UP_ARROW, B_COMMAND_KEY, new BMessage(kNavigatorCommandUp), Navigator()); AddShortcut(B_LEFT_ARROW, B_OPTION_KEY | B_COMMAND_KEY, new BMessage(kNavigatorCommandBackward), Navigator()); AddShortcut(B_RIGHT_ARROW, B_OPTION_KEY | B_COMMAND_KEY, new BMessage(kNavigatorCommandForward), Navigator()); AddShortcut(B_UP_ARROW, B_OPTION_KEY | B_COMMAND_KEY, new BMessage(kNavigatorCommandUp), Navigator()); AddShortcut(B_DOWN_ARROW, B_OPTION_KEY | B_COMMAND_KEY, new BMessage(kOpenSelection), PoseView()); AddShortcut('L', B_COMMAND_KEY, new BMessage(kNavigatorCommandSetFocus), Navigator()); } else { RemoveShortcut(B_LEFT_ARROW, B_COMMAND_KEY); RemoveShortcut(B_RIGHT_ARROW, B_COMMAND_KEY); RemoveShortcut(B_UP_ARROW, B_COMMAND_KEY); // This is added again, below, with a new meaning. RemoveShortcut(B_LEFT_ARROW, B_OPTION_KEY | B_COMMAND_KEY); RemoveShortcut(B_RIGHT_ARROW, B_OPTION_KEY | B_COMMAND_KEY); RemoveShortcut(B_UP_ARROW, B_OPTION_KEY | B_COMMAND_KEY); RemoveShortcut(B_DOWN_ARROW, B_COMMAND_KEY | B_OPTION_KEY); // This also changes meaning, added again below. AddShortcut(B_DOWN_ARROW, B_COMMAND_KEY | B_OPTION_KEY, new BMessage(kOpenSelection), PoseView()); AddShortcut(B_UP_ARROW, B_COMMAND_KEY, new BMessage(kOpenParentDir), PoseView()); // We change the meaning from kNavigatorCommandUp // to kOpenParentDir. AddShortcut(B_UP_ARROW, B_COMMAND_KEY | B_OPTION_KEY, new BMessage(kOpenParentDir), PoseView()); // command + option results in closing the parent window RemoveShortcut('L', B_COMMAND_KEY); } } void BContainerWindow::SetPathWatchingEnabled(bool enable) { if (IsPathWatchingEnabled()) { stop_watching(this); fIsWatchingPath = false; } if (enable) { if (TargetModel() != NULL) { BEntry entry; TargetModel()->GetEntry(&entry); status_t err; do { err = entry.GetParent(&entry); if (err != B_OK) break; char name[B_FILE_NAME_LENGTH]; entry.GetName(name); if (strcmp(name, "/") == 0) break; node_ref ref; entry.GetNodeRef(&ref); watch_node(&ref, B_WATCH_NAME, this); } while (err == B_OK); fIsWatchingPath = err == B_OK; } else fIsWatchingPath = false; } } void BContainerWindow::PulseTaskLoop() { if (fTaskLoop) fTaskLoop->PulseMe(); } void BContainerWindow::PopulateArrangeByMenu(BMenu* menu) { if (!fAttrMenu || !menu) return; // empty fArrangeByMenu... BMenuItem* item; while ((item = menu->RemoveItem((int32)0)) != NULL) delete item; int32 itemCount = fAttrMenu->CountItems(); for (int32 i = 0; i < itemCount; i++) { item = fAttrMenu->ItemAt(i); if (item->Command() == kAttributeItem) { BMessage* message = new BMessage(*(item->Message())); message->what = kArrangeBy; BMenuItem* newItem = new BMenuItem(item->Label(), message); newItem->SetTarget(PoseView()); menu->AddItem(newItem); } } menu->AddSeparatorItem(); item = new BMenuItem(B_TRANSLATE("Reverse order"), new BMessage(kArrangeReverseOrder)); item->SetTarget(PoseView()); menu->AddItem(item); menu->AddSeparatorItem(); item = new BMenuItem(B_TRANSLATE("Clean up"), new BMessage(kCleanup), 'K'); item->SetTarget(PoseView()); menu->AddItem(item); } // #pragma mark - WindowStateNodeOpener WindowStateNodeOpener::WindowStateNodeOpener(BContainerWindow* window, bool forWriting) : fModelOpener(NULL), fNode(NULL), fStreamNode(NULL) { if (window->TargetModel() && window->TargetModel()->IsRoot()) { BDirectory dir; if (FSGetDeskDir(&dir) == B_OK) { fNode = new BDirectory(dir); fStreamNode = new AttributeStreamFileNode(fNode); } } else if (window->TargetModel()){ fModelOpener = new ModelNodeLazyOpener(window->TargetModel(), forWriting, false); if (fModelOpener->IsOpen(forWriting)) { fStreamNode = new AttributeStreamFileNode( fModelOpener->TargetModel()->Node()); } } } WindowStateNodeOpener::~WindowStateNodeOpener() { delete fModelOpener; delete fNode; delete fStreamNode; } void WindowStateNodeOpener::SetTo(const BDirectory* node) { delete fModelOpener; delete fNode; delete fStreamNode; fModelOpener = NULL; fNode = new BDirectory(*node); fStreamNode = new AttributeStreamFileNode(fNode); } void WindowStateNodeOpener::SetTo(const BEntry* entry, bool forWriting) { delete fModelOpener; delete fNode; delete fStreamNode; fModelOpener = NULL; fNode = new BFile(entry, (uint32)(forWriting ? O_RDWR : O_RDONLY)); fStreamNode = new AttributeStreamFileNode(fNode); } void WindowStateNodeOpener::SetTo(Model* model, bool forWriting) { delete fModelOpener; delete fNode; delete fStreamNode; fNode = NULL; fStreamNode = NULL; fModelOpener = new ModelNodeLazyOpener(model, forWriting, false); if (fModelOpener->IsOpen(forWriting)) { fStreamNode = new AttributeStreamFileNode( fModelOpener->TargetModel()->Node()); } } AttributeStreamNode* WindowStateNodeOpener::StreamNode() const { return fStreamNode; } BNode* WindowStateNodeOpener::Node() const { if (!fStreamNode) return NULL; if (fNode) return fNode; return fModelOpener->TargetModel()->Node(); } // #pragma mark - BorderedView BorderedView::BorderedView() : BGroupView(B_VERTICAL, 0), fEnableBorderHighlight(true) { GroupLayout()->SetInsets(1); } void BorderedView::WindowActivated(bool active) { BContainerWindow* window = dynamic_cast<BContainerWindow*>(Window()); if (window == NULL) return; if (window->PoseView()->IsFocus()) PoseViewFocused(active); // Update border color } void BorderedView::EnableBorderHighlight(bool enable) { fEnableBorderHighlight = enable; PoseViewFocused(false); } void BorderedView::PoseViewFocused(bool focused) { BContainerWindow* window = dynamic_cast<BContainerWindow*>(Window()); if (window == NULL) return; color_which base = B_DOCUMENT_BACKGROUND_COLOR; float tint = B_DARKEN_2_TINT; if (focused && window->IsActive() && fEnableBorderHighlight) { base = B_KEYBOARD_NAVIGATION_COLOR; tint = B_NO_TINT; } BScrollBar* hScrollBar = window->PoseView()->HScrollBar(); if (hScrollBar != NULL) hScrollBar->SetBorderHighlighted(focused); BScrollBar* vScrollBar = window->PoseView()->VScrollBar(); if (vScrollBar != NULL) vScrollBar->SetBorderHighlighted(focused); SetViewUIColor(base, tint); Invalidate(); } void BorderedView::Pulse() { BContainerWindow* window = dynamic_cast<BContainerWindow*>(Window()); if (window != NULL) window->PulseTaskLoop(); }
26.164756
82
0.702965
[ "model", "transform" ]
a95f319b31b8e2bb363a117d8df09d3959f27841
30,794
cpp
C++
test/range/test-member_view.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
test/range/test-member_view.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
test/range/test-member_view.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
/* Copyright 2012-2015 Rogier van Dalen. 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 This tests range/member_view.hpp. In the process, this also tests aspects of range/core.hpp. It is therefore quite thorough. */ #define BOOST_TEST_MODULE test_range_member_view #include "utility/test/boost_unit_test.hpp" #include "range/member_view.hpp" #include <type_traits> #include <string> #include "meta/vector.hpp" #include "rime/check/check_equal.hpp" BOOST_AUTO_TEST_SUITE(test_range_member_view) struct structure { int i; double d; char const c; structure (char c) : c (c) {} std::string get_string() const { return "hello"; } char get_char() { return c; } }; int & get_int (structure & s) { return s.i; } double get_double (structure const & s) { return s.d; } double && move_double (structure && s) { return std::move (s.d); } BOOST_AUTO_TEST_CASE (test_range_member_view) { using range::view; using range::empty; using range::size; using range::first; using range::drop; using range::chop; using range::chop_in_place; using range::at; using range::at_c; using range::second; using range::third; using range::front; using range::back; structure s ('a'); s.i = 4; s.d = 3.5; structure s2 (char (234)); s2.i = 123; s2.d = 432.1; typedef range::member_extractor <int structure::*, &structure::i> member_i; typedef range::member_extractor <double structure::*, &structure::d> member_d; typedef range::member_extractor <char const (structure::*), &structure::c> member_c; { typedef range::member_view <structure &, meta::vector<>> empty_view_type; empty_view_type empty_view (s); static_assert ( !std::is_convertible <structure &, empty_view_type>::value, "member_view should be only explicitly is_convertible."); static_assert (std::is_same <typename range::result_of < range::callable::default_direction (empty_view_type)>::type, direction::front>::value, ""); auto d = range::default_direction (empty_view); static_assert (std::is_same <decltype (d), direction::front>::value, ""); static_assert (!range::is_homogeneous <empty_view_type>::value, ""); static_assert (!range::is_homogeneous < empty_view_type, direction::back>::value, ""); // view. static_assert (range::has <range::callable::view ( empty_view_type const)>::value, ""); static_assert (!range::has <range::callable::view ( int, empty_view_type const)>::value, ""); static_assert (range::has <range::callable::view ( empty_view_type &, direction::front)>::value, ""); static_assert (range::has <range::callable::view ( empty_view_type const &, direction::back)>::value, ""); // view_once. static_assert (range::has <range::callable::view_once ( empty_view_type const)>::value, ""); static_assert (!range::has <range::callable::view_once ( int, empty_view_type const)>::value, ""); static_assert (range::has <range::callable::view_once ( empty_view_type &, direction::front)>::value, ""); static_assert (range::has <range::callable::view_once ( empty_view_type const &, direction::back)>::value, ""); // empty. static_assert (range::has <range::callable::empty ( empty_view_type const)>::value, ""); static_assert (range::has <range::callable::empty ( empty_view_type &, direction::front)>::value, ""); static_assert (range::has <range::callable::empty ( empty_view_type const &, direction::back)>::value, ""); // size. static_assert (range::has <range::callable::size ( empty_view_type const)>::value, ""); static_assert (range::has <range::callable::size ( empty_view_type const &, direction::front &)>::value, ""); static_assert (range::has <range::callable::size ( empty_view_type, direction::back const &)>::value, ""); // empty. RIME_CHECK_EQUAL (empty (empty_view_type (s)), rime::true_); RIME_CHECK_EQUAL (empty (view (empty_view_type (s), front)), rime::true_); RIME_CHECK_EQUAL (empty (empty_view, front), rime::true_); RIME_CHECK_EQUAL (empty (empty_view, direction::back()), rime::true_); BOOST_MPL_ASSERT (( range::always_empty <empty_view_type, direction::front>)); BOOST_MPL_ASSERT (( range::always_empty <empty_view_type, direction::back>)); // size. RIME_CHECK_EQUAL (size (empty_view), rime::size_t <0>()); RIME_CHECK_EQUAL (size (empty_view, front), rime::size_t <0>()); RIME_CHECK_EQUAL (size (empty_view_type (s), back), rime::size_t <0>()); // first. static_assert (!range::has <range::callable::first ( empty_view_type)>::value, ""); static_assert (!range::has <range::callable::first ( direction::front, empty_view_type)>::value, ""); static_assert (!range::has <range::callable::first ( direction::back, empty_view_type)>::value, ""); // drop. static_assert (!range::has <range::callable::drop ( empty_view_type)>::value, ""); static_assert (!range::has <range::callable::drop ( direction::front, empty_view_type)>::value, ""); static_assert (!range::has <range::callable::drop ( direction::back, empty_view_type)>::value, ""); // at. static_assert (!range::has <range::callable::at ( empty_view_type)>::value, ""); static_assert (!range::has <range::callable::at ( direction::front, empty_view_type)>::value, ""); static_assert (!range::has <range::callable::at ( direction::back, empty_view_type)>::value, ""); // drop of size 0 is available. static_assert (range::has <range::callable::drop ( empty_view_type, rime::size_t <0>)>::value, ""); static_assert (range::has <range::callable::drop ( empty_view_type, std::integral_constant <std::size_t, 0>, direction::front)>::value, ""); static_assert (range::has <range::callable::drop ( empty_view_type, rime::size_t <0>, direction::back)>::value, ""); static_assert (!range::has <range::callable::drop ( empty_view_type, rime::size_t <1>)>::value, ""); static_assert (!range::has <range::callable::drop ( empty_view_type, rime::size_t <1>, direction::front)>::value, ""); static_assert (!range::has <range::callable::drop ( empty_view_type, rime::size_t <1>, direction::back)>::value, ""); static_assert (!range::has <range::callable::drop ( empty_view_type, rime::size_t <2>)>::value, ""); static_assert (!range::has <range::callable::drop ( empty_view_type, std::integral_constant <std::size_t, 3>, direction::front)>::value, ""); static_assert (!range::has <range::callable::drop ( empty_view_type, rime::size_t <3>, direction::back)>::value, ""); // chop. static_assert (!range::has <range::callable::chop ( empty_view_type)>::value, ""); static_assert (!range::has <range::callable::chop ( empty_view_type, direction::front)>::value, ""); static_assert (!range::has <range::callable::chop ( empty_view_type, direction::back)>::value, ""); // chop_in_place: not a homogeneous range. static_assert (!range::has <range::callable::chop_in_place ( empty_view_type)>::value, ""); static_assert (!range::has <range::callable::chop_in_place ( empty_view_type, direction::front)>::value, ""); static_assert (!range::has <range::callable::chop_in_place ( empty_view_type, direction::back)>::value, ""); // View must be assignable. empty_view = empty_view_type (s2); RIME_CHECK_EQUAL (empty (empty_view), rime::true_); // Original container, s, has not changed. BOOST_CHECK_EQUAL (s.i, 4); } { typedef range::member_view <structure const &, meta::vector <member_i>> int_view_type; typedef range::member_view <structure const &, meta::vector<>> empty_view_type; int_view_type int_view (s); // empty. static_assert (range::has <range::callable::empty ( int_view_type)>::value, ""); static_assert (range::has <range::callable::empty ( int_view_type, direction::front)>::value, ""); RIME_CHECK_EQUAL (range::empty (int_view), rime::false_); RIME_CHECK_EQUAL (range::empty (int_view, front), rime::false_); BOOST_MPL_ASSERT (( range::never_empty <int_view_type, direction::front>)); BOOST_MPL_ASSERT (( range::never_empty <int_view_type, direction::back>)); // size. static_assert (range::has <range::callable::size ( int_view_type)>::value, ""); static_assert (range::has <range::callable::size ( int_view_type, direction::back)>::value, ""); BOOST_MPL_ASSERT ((std::is_same <range::result_of < range::callable::size (int_view_type)>::type, rime::size_t <1>>)); BOOST_MPL_ASSERT ((std::is_same < range::result_of < range::callable::size (int_view_type, direction::back)>::type, rime::size_t <1>>)); // first. static_assert (range::has <range::callable::first ( int_view_type)>::value, ""); static_assert (range::has <range::callable::first ( int_view_type, direction::front)>::value, ""); static_assert (range::has <range::callable::first ( int_view_type, direction::back)>::value, ""); BOOST_MPL_ASSERT ((std::is_same < range::result_of <range::callable::first ( int_view_type const)>::type, int const &>)); BOOST_MPL_ASSERT ((std::is_same < range::result_of <range::callable::first ( int_view_type, direction::back)>::type, int const &>)); static_assert (!range::is_homogeneous <int_view_type>::value, ""); static_assert (!range::is_homogeneous < int_view_type, direction::back>::value, ""); // drop. static_assert (range::has <range::callable::drop ( int_view_type)>::value, ""); static_assert (range::has <range::callable::drop ( int_view_type, rime::int_<1>, direction::front)>::value, ""); BOOST_MPL_ASSERT ((std::is_same < range::result_of <range::callable::drop ( int_view_type)>::type, empty_view_type>)); BOOST_MPL_ASSERT ((std::is_same < range::result_of <range::callable::drop ( int_view_type, direction::back)>::type, empty_view_type>)); static_assert (!range::has <range::callable::drop ( int_view_type, rime::int_<2>, direction::back)>::value, ""); static_assert (!range::has <range::callable::drop ( int_view_type, int, direction::back)>::value, ""); static_assert (!range::has <range::callable::drop ( int_view_type, std::size_t, direction::back)>::value, ""); // chop. static_assert (range::has <range::callable::chop ( int_view_type)>::value, ""); static_assert (range::has <range::callable::chop ( int_view_type, direction::front)>::value, ""); static_assert (range::has <range::callable::chop ( int_view_type, direction::back)>::value, ""); BOOST_MPL_ASSERT ((std::is_same <range::result_of < range::callable::chop (int_view_type)>::type, range::chopped <int const &, empty_view_type>>)); BOOST_MPL_ASSERT ((std::is_same <range::result_of < range::callable::chop (int_view_type, direction::front)>::type, range::chopped <int const &, empty_view_type>>)); BOOST_MPL_ASSERT ((std::is_same <range::result_of < range::callable::chop (int_view_type, direction::back)>::type, range::chopped <int const &, empty_view_type>>)); // chop_in_place: not a homogeneous range. static_assert (!range::has <range::callable::chop_in_place ( int_view_type)>::value, ""); static_assert (!range::has <range::callable::chop_in_place ( int_view_type, direction::front)>::value, ""); static_assert (!range::has <range::callable::chop_in_place ( int_view_type, direction::back)>::value, ""); // at: the implementation is based on drop and first. static_assert (range::has <range::callable::at ( int_view_type, rime::size_t <0>)>::value, ""); static_assert (range::has <range::callable::at ( int_view_type, rime::size_t <0>, direction::front)>::value, ""); static_assert (range::has <range::callable::at ( int_view_type, rime::size_t <0>, direction::back)>::value, ""); static_assert (!range::has <range::callable::at ( int_view_type, rime::size_t <1>)>::value, ""); static_assert (!range::has <range::callable::at ( int_view_type, rime::size_t <1>, direction::front)>::value, ""); static_assert (!range::has <range::callable::at ( int_view_type, rime::size_t <1>, direction::back)>::value, ""); BOOST_MPL_ASSERT ((std::is_same < range::result_of <range::callable::at ( int_view_type const, rime::size_t <0>)>::type, int const &>)); BOOST_MPL_ASSERT ((std::is_same < range::result_of <range::callable::at ( int_view_type, rime::size_t <0>, direction::back)>::type, int const &>)); BOOST_CHECK_EQUAL (at (int_view, rime::size_t <0>()), 4); BOOST_CHECK_EQUAL (at (int_view, rime::size_t <0>(), back), 4); BOOST_CHECK_EQUAL (at_c <0> (int_view), 4); BOOST_CHECK_EQUAL (at_c <0> (int_view, back), 4); // Run-time behaviour. auto empty_1 = drop (int_view); auto empty_2 = drop (int_view, back); auto first_and_empty_1 = chop (int_view); auto first_and_empty_2 = chop (int_view, back); RIME_CHECK_EQUAL (empty (int_view), rime::false_); RIME_CHECK_EQUAL (empty (int_view, front), rime::false_); RIME_CHECK_EQUAL (empty (view (int_view, front), back), rime::false_); RIME_CHECK_EQUAL (size (int_view), rime::size_t <1>()); RIME_CHECK_EQUAL (size (int_view, front), rime::size_t <1>()); RIME_CHECK_EQUAL (size (int_view, back), rime::size_t <1>()); BOOST_CHECK_EQUAL (first (int_view), 4); BOOST_CHECK_EQUAL (first (int_view, back), 4); BOOST_CHECK_EQUAL (first_and_empty_1.first(), 4); BOOST_CHECK_EQUAL (first_and_empty_2.first(), 4); RIME_CHECK_EQUAL (empty (empty_1), rime::true_); RIME_CHECK_EQUAL (empty (empty_1, front), rime::true_); RIME_CHECK_EQUAL (size (empty_1), rime::size_t <0>()); RIME_CHECK_EQUAL (size (empty_1, back), rime::size_t <0>()); RIME_CHECK_EQUAL (empty (empty_2), rime::true_); RIME_CHECK_EQUAL (empty (empty_2, back), rime::true_); RIME_CHECK_EQUAL (size (empty_2), rime::size_t <0>()); RIME_CHECK_EQUAL (size (empty_2, front), rime::size_t <0>()); // chopped ranges. RIME_CHECK_EQUAL (empty (first_and_empty_1.rest()), rime::true_); RIME_CHECK_EQUAL (empty (first_and_empty_1.rest(), front), rime::true_); RIME_CHECK_EQUAL (size (first_and_empty_1.rest()), rime::size_t <0>()); RIME_CHECK_EQUAL (size (first_and_empty_1.rest(), back), rime::size_t <0>()); RIME_CHECK_EQUAL (empty (first_and_empty_2.rest()), rime::true_); RIME_CHECK_EQUAL (empty (first_and_empty_2.rest(), back), rime::true_); RIME_CHECK_EQUAL (size (first_and_empty_2.rest()), rime::size_t <0>()); RIME_CHECK_EQUAL (size (first_and_empty_2.rest(), front), rime::size_t <0>()); // View must be assignable. int_view = int_view_type (s2); RIME_CHECK_EQUAL (empty (int_view), rime::false_); // Original container, s, has not changed. BOOST_CHECK_EQUAL (s.i, 4); BOOST_CHECK_EQUAL (first (int_view), 123); BOOST_CHECK_EQUAL (at (int_view, rime::size_t <0>()), 123); } { typedef range::member_view <structure &, meta::vector <member_i, member_d, member_c>> three_view_type; three_view_type three_view (s); static_assert (!range::is_homogeneous <three_view_type>::value, ""); static_assert (!range::is_homogeneous < three_view_type &, direction::back>::value, ""); static_assert (!range::is_homogeneous < three_view_type const, direction::front>::value, ""); static_assert (range::has <range::callable::empty ( three_view_type)>::value, ""); static_assert (range::has <range::callable::empty ( three_view_type, direction::front)>::value, ""); static_assert (range::has <range::callable::size ( three_view_type)>::value, ""); static_assert (range::has <range::callable::size ( three_view_type, direction::back)>::value, ""); static_assert (range::has <range::callable::first ( three_view_type)>::value, ""); static_assert (range::has <range::callable::first ( three_view_type, direction::front)>::value, ""); static_assert (range::has <range::callable::first ( three_view_type, direction::back)>::value, ""); static_assert (range::has <range::callable::drop ( three_view_type)>::value, ""); static_assert (range::has <range::callable::drop ( three_view_type, rime::int_<1>, direction::front)>::value, ""); static_assert (range::has <range::callable::drop ( three_view_type, boost::mpl::int_<2>, direction::back)>::value, ""); static_assert (range::has <range::callable::drop ( three_view_type, std::integral_constant <std::size_t, 3>, direction::back)>::value, ""); static_assert (!range::has <range::callable::drop ( three_view_type, rime::int_<4>, direction::back)>::value, ""); static_assert (!range::has <range::callable::drop ( three_view_type, int, direction::back)>::value, ""); static_assert (!range::has <range::callable::drop ( three_view_type, std::size_t, direction::back)>::value, ""); static_assert (range::has <range::callable::chop ( three_view_type)>::value, ""); static_assert (range::has <range::callable::chop ( three_view_type, direction::front)>::value, ""); static_assert (range::has <range::callable::chop ( three_view_type, direction::back)>::value, ""); static_assert (!range::has <range::callable::chop_in_place ( three_view_type)>::value, ""); static_assert (!range::has <range::callable::chop_in_place ( three_view_type, direction::front)>::value, ""); static_assert (!range::has <range::callable::chop_in_place ( three_view_type, direction::back)>::value, ""); RIME_CHECK_EQUAL (empty (three_view), rime::false_); RIME_CHECK_EQUAL (empty (three_view, front), rime::false_); RIME_CHECK_EQUAL (empty (three_view, back), rime::false_); BOOST_MPL_ASSERT (( range::never_empty <three_view_type, direction::front>)); BOOST_MPL_ASSERT (( range::never_empty <three_view_type, direction::back>)); RIME_CHECK_EQUAL (size (three_view), rime::size_t <3>()); RIME_CHECK_EQUAL (size (three_view, front), rime::size_t <3>()); RIME_CHECK_EQUAL (size (three_view, back), rime::size_t <3>()); BOOST_CHECK_EQUAL (first (three_view), 4); BOOST_CHECK_EQUAL (first (three_view, back), 'a'); BOOST_CHECK_EQUAL (first (drop (three_view, back)), 4); BOOST_CHECK_EQUAL (first (drop (three_view, rime::int_<2>(), back)), 4); BOOST_CHECK_EQUAL (first (drop (three_view, front), back), 'a'); RIME_CHECK_EQUAL (chop (three_view).first(), 4); RIME_CHECK_EQUAL (chop (three_view, back).first(), 'a'); // Access second element. RIME_CHECK_EQUAL (empty (drop (three_view)), rime::false_); RIME_CHECK_EQUAL (empty (drop (three_view, front)), rime::false_); RIME_CHECK_EQUAL (empty (drop (view (three_view, front), back)), rime::false_); RIME_CHECK_EQUAL (size (drop (three_view)), rime::size_t <2>()); RIME_CHECK_EQUAL (size (drop (three_view), front), rime::size_t <2>()); RIME_CHECK_EQUAL (size (drop (three_view), back), rime::size_t <2>()); RIME_CHECK_EQUAL (size (drop (three_view, front)), rime::size_t <2>()); RIME_CHECK_EQUAL (size (drop (three_view, front), front), rime::size_t <2>()); RIME_CHECK_EQUAL (size (drop (three_view, front), back), rime::size_t <2>()); BOOST_CHECK_EQUAL (first (drop (three_view)), 3.5); BOOST_CHECK_EQUAL (first (drop (three_view, front)), 3.5); BOOST_CHECK_EQUAL ( first (drop (three_view, std::integral_constant <int, 1>())), 3.5); BOOST_CHECK_EQUAL (first (drop (three_view, rime::int_ <1>(), front)), 3.5); RIME_CHECK_EQUAL (size (chop (three_view).rest()), rime::size_t <2>()); BOOST_CHECK_EQUAL (first (chop (three_view).rest()), 3.5); RIME_CHECK_EQUAL (size (chop (three_view, back).rest()), rime::size_t <2>()); BOOST_CHECK_EQUAL (first (chop (three_view, back).rest(), back), 3.5); // Access second element of the three_view reduced to two elements RIME_CHECK_EQUAL (empty (drop (drop (three_view, back))), rime::false_); BOOST_CHECK_EQUAL (first (drop (drop (three_view, back))), 3.5); BOOST_CHECK_EQUAL (first (drop (drop (three_view, back), front)), 3.5); BOOST_CHECK_EQUAL (first (drop ( drop (three_view, back), rime::int_ <1>())), 3.5); BOOST_CHECK_EQUAL (first (drop ( drop (three_view, back), rime::int_ <1>(), front)), 3.5); // Third element. RIME_CHECK_EQUAL (empty (drop (drop (three_view))), rime::false_); BOOST_CHECK_EQUAL (first (drop (drop (three_view))), 'a'); BOOST_CHECK_EQUAL (first (drop (drop (three_view), front)), 'a'); BOOST_CHECK_EQUAL (first (drop (three_view, rime::int_ <2>())), 'a'); BOOST_CHECK_EQUAL (first (drop (three_view, rime::int_ <2>(), front)), 'a'); // at (d,n,r) is a shorthand for first (d, drop (d, n, r)). static_assert (range::has <range::callable::at ( three_view_type, rime::size_t <0>)>::value, ""); static_assert (range::has <range::callable::at ( three_view_type, rime::size_t <1>)>::value, ""); static_assert (range::has <range::callable::at ( three_view_type, rime::size_t <2>)>::value, ""); static_assert (!range::has <range::callable::at ( three_view_type, rime::size_t <3>)>::value, ""); BOOST_CHECK_EQUAL (at (three_view, rime::size_t <0>()), 4); BOOST_CHECK_EQUAL (at (three_view, rime::size_t <1>()), 3.5); BOOST_CHECK_EQUAL (at (three_view, rime::size_t <2>()), 'a'); BOOST_CHECK_EQUAL (at (three_view, rime::size_t <0>(), front), 4); BOOST_CHECK_EQUAL ( at (three_view, std::integral_constant <size_t, 1>(), front), 3.5); BOOST_CHECK_EQUAL (at (three_view, rime::size_t <2>(), front), 'a'); BOOST_CHECK_EQUAL (at (three_view, rime::size_t <0>(), back), 'a'); BOOST_CHECK_EQUAL (at (three_view, rime::size_t <1>(), back), 3.5); BOOST_CHECK_EQUAL (at (three_view, boost::mpl::size_t <2>(), back), 4); BOOST_CHECK_EQUAL (at_c <0> (three_view), 4); BOOST_CHECK_EQUAL (at_c <1> (three_view), 3.5); BOOST_CHECK_EQUAL (at_c <2> (three_view), 'a'); BOOST_CHECK_EQUAL (at_c <0> (three_view, back), 'a'); BOOST_CHECK_EQUAL (at_c <1> (three_view, back), 3.5); BOOST_CHECK_EQUAL (at_c <2> (three_view, back), 4); BOOST_CHECK_EQUAL (second (three_view), 3.5); BOOST_CHECK_EQUAL (third (three_view), 'a'); BOOST_CHECK_EQUAL (second (three_view, back), 3.5); BOOST_CHECK_EQUAL (third (three_view, back), 4); rime::int_<2> two; // Three drops from whichever direction and the range is empty. RIME_CHECK_EQUAL (empty (drop (drop (drop (three_view)))), rime::true_); RIME_CHECK_EQUAL (empty (drop (drop (drop (three_view), back))), rime::true_); RIME_CHECK_EQUAL (empty (drop (drop (drop (three_view)), back)), rime::true_); RIME_CHECK_EQUAL (empty (drop (drop ( view (three_view, back), rime::int_<2>()))), rime::true_); RIME_CHECK_EQUAL (empty (drop (drop (three_view, two, back))), rime::true_); RIME_CHECK_EQUAL (empty (drop (drop (three_view, two), back)), rime::true_); RIME_CHECK_EQUAL (empty (drop (drop (three_view), rime::int_<2>(), back)), rime::true_); first (three_view) = 6; BOOST_CHECK_EQUAL (s.i, 6); first (drop (three_view)) = 98.7; BOOST_CHECK_EQUAL (s.d, 98.7); // View must be assignable. three_view = three_view_type (s2); RIME_CHECK_EQUAL (empty (three_view), rime::false_); // Original container, s, has not changed. BOOST_CHECK_EQUAL (s.i, 6); BOOST_CHECK_EQUAL (first (three_view), 123); BOOST_CHECK_EQUAL (first (drop (three_view)), 432.1); BOOST_CHECK_EQUAL (first (three_view, back), char (234)); } // Rvalue reference to the structure. { typedef range::member_view <structure &&, meta::vector <member_i, member_d, member_c>> three_view_type; three_view_type three_view (std::move (s)); BOOST_MPL_ASSERT ((std::is_same < decltype (first (three_view)), int &&>)); BOOST_MPL_ASSERT ((std::is_same < decltype (at_c <1> (three_view)), double &&>)); BOOST_MPL_ASSERT ((std::is_same < decltype (second (three_view)), double &&>)); BOOST_MPL_ASSERT ((std::is_same < decltype (at_c <2> (three_view)), char const &&>)); BOOST_MPL_ASSERT ((std::is_same < decltype (third (three_view)), char const &&>)); BOOST_CHECK_EQUAL (first (three_view), 6); BOOST_CHECK_EQUAL (at_c <1> (three_view), 98.7); BOOST_CHECK_EQUAL (at_c <2> (three_view), 'a'); } { // Check that member_view can be constructed only from member_view's // with a superset of extractors. typedef range::member_view <structure &, meta::vector<>> empty_view_type; typedef range::member_view <structure &, meta::vector <member_i>> int_view_type; typedef range::member_view <structure &, meta::vector <member_i, member_d, member_c>> three_view_type; BOOST_MPL_ASSERT (( std::is_convertible <int_view_type, empty_view_type>)); BOOST_MPL_ASSERT (( std::is_convertible <three_view_type, empty_view_type>)); BOOST_MPL_ASSERT (( std::is_convertible <three_view_type, int_view_type>)); BOOST_MPL_ASSERT_NOT (( std::is_convertible <empty_view_type, int_view_type>)); BOOST_MPL_ASSERT_NOT (( std::is_convertible <empty_view_type, three_view_type>)); BOOST_MPL_ASSERT_NOT (( std::is_convertible <int_view_type, three_view_type>)); } } BOOST_AUTO_TEST_CASE (test_range_functions) { using range::view; using range::empty; using range::size; using range::first; using range::at_c; using range::drop; using range::front; using range::back; typedef range::member_extractor <int structure::*, &structure::i> member_i; typedef range::member_extractor <std::string (structure::*)() const, &structure::get_string> member_s; typedef range::member_extractor <char (structure::*)(), &structure::get_char> member_c; typedef range::member_extractor <int & (*) (structure &), &get_int> member_i_2; typedef range::member_extractor <double (*) (structure const &), &get_double> member_d_2; structure s ('b'); s.i = 678; s.d = 890.1; { typedef range::member_view <structure &, meta::vector <member_i, member_s, member_c, member_i_2, member_d_2>> view_type; view_type structure_view (s); BOOST_CHECK_EQUAL (first (structure_view), 678); BOOST_CHECK_EQUAL (at_c <1> (structure_view), "hello"); BOOST_CHECK_EQUAL (at_c <2> (structure_view), 'b'); BOOST_CHECK_EQUAL (at_c <3> (structure_view), 678); at_c <3>(structure_view) = 3; BOOST_CHECK_EQUAL (s.i, 3); BOOST_CHECK_EQUAL (at_c <4> (structure_view), 890.1); } { // Rvalue reference. typedef range::member_extractor <double && (*) (structure &&), &move_double> member_d_move; typedef range::member_view <structure &&, meta::vector <member_d_move, member_s>> view_type; view_type structure_view (std::move (s)); BOOST_MPL_ASSERT ((std::is_same < decltype (first (structure_view)), double &&>)); BOOST_CHECK_EQUAL (first (structure_view), 890.1); // Use nonconst function. BOOST_CHECK_EQUAL (at_c <1> (structure_view), "hello"); } } BOOST_AUTO_TEST_SUITE_END()
44.564399
80
0.603819
[ "vector" ]
a964e24596eaf9771d60b31122bb08301bd1c607
592
hpp
C++
src/pass/shape_inference_interface.hpp
chentong319/ONNF
5357fc1421333391522fe694612bacd3e00da953
[ "Apache-2.0" ]
25
2019-12-24T09:22:09.000Z
2021-09-09T17:10:09.000Z
src/pass/shape_inference_interface.hpp
chentong319/ONNF
5357fc1421333391522fe694612bacd3e00da953
[ "Apache-2.0" ]
69
2019-12-24T06:24:38.000Z
2020-03-16T14:42:53.000Z
src/pass/shape_inference_interface.hpp
chentong319/ONNF
5357fc1421333391522fe694612bacd3e00da953
[ "Apache-2.0" ]
10
2019-12-24T01:41:42.000Z
2021-09-09T17:11:31.000Z
//===- shape_inference_interface.hpp - Definition for ShapeInference --------=// // // Copyright 2019 The IBM Research Authors. // // ============================================================================= // // This file contains the declarations of the shape inference interfaces defined // in ShapeInferenceInterface.td. // //===----------------------------------------------------------------------===// #pragma once #include "mlir/IR/OpDefinition.h" namespace mlir { /// Include the auto-generated declarations. #include "src/shape_inference.hpp.inc" } // end namespace mlir
26.909091
80
0.530405
[ "shape" ]
a96570633a6fbfd9f0e2ba932677d0182a2b173b
9,282
cpp
C++
Plugins/PLRendererOpenGL/src/Linux/ContextLinux.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Plugins/PLRendererOpenGL/src/Linux/ContextLinux.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Plugins/PLRendererOpenGL/src/Linux/ContextLinux.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: ContextLinux.h * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLCore/Log/Log.h> #include <PLCore/Container/Array.h> #include <PLRenderer/Renderer/Types.h> #include "PLRendererOpenGL/Renderer.h" #include "PLRendererOpenGL/Extensions.h" #include "PLRendererOpenGL/Linux/SurfaceWindowLinux.h" #include "PLRendererOpenGL/Linux/ContextLinux.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; namespace PLRendererOpenGL { //[-------------------------------------------------------] //[ Public methods ] //[-------------------------------------------------------] /** * @brief * Constructor */ ContextLinux::ContextLinux(Renderer &cRenderer) : Context(), m_pRenderer(&cRenderer), m_pDisplay(nullptr), m_hDummyNativeWindow(NULL_HANDLE), m_pDummyVisualInfo(nullptr), m_hDummyWindowRenderContext(nullptr) { // Get X server display connection m_pDisplay = XOpenDisplay(nullptr); if (m_pDisplay) { // Get an appropriate visual int nAttributeList[] = { GLX_RGBA, GLX_DOUBLEBUFFER, GLX_RED_SIZE, 4, GLX_GREEN_SIZE, 4, GLX_BLUE_SIZE, 4, GLX_DEPTH_SIZE, 16, 0 }; // = "None" m_pDummyVisualInfo = glXChooseVisual(m_pDisplay, DefaultScreen(m_pDisplay), nAttributeList); if (m_pDummyVisualInfo) { // Create a GLX context m_hDummyWindowRenderContext = glXCreateContext(m_pDisplay, m_pDummyVisualInfo, 0, GL_TRUE); if (m_hDummyWindowRenderContext) { // Create a color map XSetWindowAttributes sSetWindowAttributes; sSetWindowAttributes.colormap = XCreateColormap(m_pDisplay, RootWindow(m_pDisplay, m_pDummyVisualInfo->screen), m_pDummyVisualInfo->visual, AllocNone); // Create a window sSetWindowAttributes.border_pixel = 0; sSetWindowAttributes.event_mask = 0; m_hDummyNativeWindow = XCreateWindow(m_pDisplay, RootWindow(m_pDisplay, m_pDummyVisualInfo->screen), 0, 0, 300, 300, 0, m_pDummyVisualInfo->depth, InputOutput, m_pDummyVisualInfo->visual, CWBorderPixel|CWColormap|CWEventMask, &sSetWindowAttributes); if (m_hDummyNativeWindow) { // Make the internal dummy to the current render target MakeDummyCurrent(); // Initialize the OpenGL extensions GetExtensions().Init(); } else { // Error, failed to create dummy window! } } else { // Error, failed to create a GLX context! } } else { // Error, failed to get an appropriate visual! } } else { // Error, failed to get display! } } /** * @brief * Destructor */ ContextLinux::~ContextLinux() { // Is there a valid X server display connection? if (m_pDisplay) { // Is the render context of the OpenGL dummy window is the currently active OpenGL render context? if (glXGetCurrentContext() == m_hDummyWindowRenderContext) glXMakeCurrent(m_pDisplay, 0L, nullptr); // Destroy the GLX context of the OpenGL dummy window if (m_hDummyWindowRenderContext != nullptr) glXDestroyContext(m_pDisplay, m_hDummyWindowRenderContext); // Destroy the dummy native window if (m_hDummyNativeWindow) XDestroyWindow(m_pDisplay, m_hDummyNativeWindow); if (m_pDummyVisualInfo) XFree(m_pDummyVisualInfo); // Close the X server display connection XCloseDisplay(m_pDisplay); } } /** * @brief * Returns the X server display connection */ Display *ContextLinux::GetDisplay() const { return m_pDisplay; } /** * @brief * Returns the primary render context */ GLXContext ContextLinux::GetRenderContext() const { return m_hDummyWindowRenderContext; } //[-------------------------------------------------------] //[ Public virtual Context methods ] //[-------------------------------------------------------] bool ContextLinux::IsValid() const { return (m_pDisplay != nullptr && m_hDummyNativeWindow != NULL_HANDLE && m_pDummyVisualInfo != nullptr && m_hDummyWindowRenderContext != nullptr); } void ContextLinux::MakeDummyCurrent() const { // [TODO] What the... - usually we need to make a OpenGL context to the current one in order to call OpenGL commands, but if we uncomment the following, it doesn't work?! glXMakeCurrent(m_pDisplay, m_hDummyNativeWindow, m_hDummyWindowRenderContext); } bool ContextLinux::QueryDisplayModes(Array<const PLRenderer::DisplayMode*> &lstDisplayModeList) { bool bResult = false; // Error by default // Clear old list of display modes for (uint32 i=0; i<lstDisplayModeList.GetNumOfElements(); i++) delete lstDisplayModeList[i]; lstDisplayModeList.Clear(); // Get list of display modes PL_LOG(Info, "Query available display modes") // Get XRR screen configuration (don't forget "XRRFreeScreenConfigInfo()" if you no longer need it) const int nScreen = XDefaultScreen(m_pDisplay); XRRScreenConfiguration *pXRRScreenConfiguration = XRRGetScreenInfo(m_pDisplay, RootWindow(m_pDisplay, nScreen)); // Get specific configuration information out of our screen configuration int nNumOfModes = 0; XRRScreenSize *pXRRScreenSize = XRRConfigSizes(pXRRScreenConfiguration, &nNumOfModes); // Loop through all modes for (int nMode=0; nMode<nNumOfModes; nMode++) { // First at all, we're only interested in some of the settings - as a result, we really should check if there's // already a display mode within our list with the interesting settings of the current found display mode bool bNewMode = true; for (uint32 i=0; i<lstDisplayModeList.GetNumOfElements(); i++) { const PLRenderer::DisplayMode *pDisplayMode = lstDisplayModeList[i]; if (pDisplayMode->vSize.x == pXRRScreenSize[nMode].width && pDisplayMode->vSize.y == pXRRScreenSize[nMode].height) { // We already have such a display mode within our list! bNewMode = false; // Get us out of this loop right now! i = lstDisplayModeList.GetNumOfElements(); } } if (bNewMode) { // Get required information PLRenderer::DisplayMode *pDisplayMode = new PLRenderer::DisplayMode; pDisplayMode->vSize.x = pXRRScreenSize[nMode].width; pDisplayMode->vSize.y = pXRRScreenSize[nMode].height; pDisplayMode->nColorBits = XDefaultDepth(m_pDisplay, nScreen); // [TODO] Under Linux there is currently no real 32 bit visual (RGBA) // only 24 bit (RGB) which is equal to 32 bit in RGB (without alpha value) if (pDisplayMode->nColorBits == 24) pDisplayMode->nColorBits = 32; pDisplayMode->nFrequency = 0; // Give out a log message String sTemp; if (pDisplayMode->nFrequency) { sTemp = String::Format("Found: %dx%dx%d %d Hz", pDisplayMode->vSize.x, pDisplayMode->vSize.y, pDisplayMode->nColorBits, pDisplayMode->nFrequency); } else { sTemp = String::Format("Found: %dx%dx%d", pDisplayMode->vSize.x, pDisplayMode->vSize.y, pDisplayMode->nColorBits); } // Add found display mode to list PL_LOG(Info, sTemp) lstDisplayModeList.Add(pDisplayMode); } } // Was at least one display mode found? if (lstDisplayModeList.GetNumOfElements()) bResult = true; // Success! :D else PL_LOG(Error, "No available & supported display modes found!") // Free XRR screen configuration XRRFreeScreenConfigInfo(pXRRScreenConfiguration); // Done return bResult; } PLRenderer::SurfaceWindow *ContextLinux::CreateSurfaceWindow(PLRenderer::SurfaceWindowHandler &cHandler, handle nNativeWindowHandle, const PLRenderer::DisplayMode &sDisplayMode, bool bFullscreen) { return new SurfaceWindowLinux(cHandler, nNativeWindowHandle, sDisplayMode, bFullscreen); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLRendererOpenGL
36.98008
195
0.665051
[ "render" ]
a9692affe256e72b6c807c93bbfa76263c0278a1
9,440
cpp
C++
libcxx/test/libcxx/debug/containers/sequence_container_iterators.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/libcxx/debug/containers/sequence_container_iterators.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/libcxx/debug/containers/sequence_container_iterators.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++11, c++14 // UNSUPPORTED: libcxx-no-debug-mode, c++03, windows // ADDITIONAL_COMPILE_FLAGS: -D_LIBCPP_DEBUG=1 // test container debugging #include <forward_list> #include <list> #include <vector> #include <deque> #include "check_assertion.h" #include "container_debug_tests.h" #include "test_macros.h" using namespace IteratorDebugChecks; template <class Container, ContainerType CT> struct SequenceContainerChecks : BasicContainerChecks<Container, CT> { using Base = BasicContainerChecks<Container, CT>; using value_type = typename Container::value_type; using allocator_type = typename Container::allocator_type; using iterator = typename Container::iterator; using const_iterator = typename Container::const_iterator; using Base::makeContainer; using Base::makeValueType; public: static void run() { Base::run(); SanityTest(); FrontOnEmptyContainer(); if constexpr(CT != CT_ForwardList) { AssignInvalidates(); BackOnEmptyContainer(); InsertIterValue(); InsertIterSizeValue(); InsertIterIterIter(); EmplaceIterValue(); EraseIterIter(); } else { SpliceFirstElemAfter(); } if constexpr (CT == CT_Vector || CT == CT_Deque || CT == CT_List) { PopBack(); } if constexpr (CT == CT_List || CT == CT_Deque) { PopFront(); // FIXME: Run with forward list as well } if constexpr (CT == CT_List || CT == CT_ForwardList) { RemoveFirstElem(); } if constexpr (CT == CT_List) { SpliceFirstElem(); SpliceSameContainer(); } } private: static void SanityTest() { // sanity test Container C = {1, 1, 1, 1}; ::DoNotOptimize(&C); } static void RemoveFirstElem() { // See llvm.org/PR35564 // remove(<first-elem>) { Container C = makeContainer(1); auto FirstVal = *(C.begin()); C.remove(FirstVal); assert(C.empty()); } { Container C = {1, 1, 1, 1}; auto FirstVal = *(C.begin()); C.remove(FirstVal); assert(C.empty()); } } static void SpliceFirstElem() { // See llvm.org/PR35564 // splice(<first-elem>) { Container C = makeContainer(1); Container C2; C2.splice(C2.end(), C, C.begin(), ++C.begin()); } { Container C = makeContainer(1); Container C2; C2.splice(C2.end(), C, C.begin()); } } static void SpliceSameContainer() { // splice(<same-container>) Container C = {1, 1}; C.splice(C.end(), C, C.begin()); } static void SpliceFirstElemAfter() { // See llvm.org/PR35564 // splice(<first-elem>) { Container C = makeContainer(1); Container C2; C2.splice_after(C2.begin(), C, C.begin(), ++C.begin()); } { Container C = makeContainer(1); Container C2; C2.splice_after(C2.begin(), C, C.begin()); } } static void AssignInvalidates() { // assign(Size, Value) Container C(allocator_type{}); iterator it1, it2, it3; auto reset = [&]() { C = makeContainer(3); it1 = C.begin(); it2 = ++C.begin(); it3 = C.end(); }; auto check = [&]() { EXPECT_DEATH( C.erase(it1) ); EXPECT_DEATH( C.erase(it2) ); EXPECT_DEATH( C.erase(it3, C.end()) ); }; reset(); C.assign(2, makeValueType(4)); check(); reset(); // assign(Iter, Iter) std::vector<value_type> V = { makeValueType(1), makeValueType(2), makeValueType(3) }; C.assign(V.begin(), V.end()); check(); reset(); // assign(initializer_list) C.assign({makeValueType(1), makeValueType(2), makeValueType(3)}); check(); } static void BackOnEmptyContainer() { // testing back on empty Container C = makeContainer(1); Container const& CC = C; (void)C.back(); (void)CC.back(); C.clear(); EXPECT_DEATH( C.back() ); EXPECT_DEATH( CC.back() ); } static void FrontOnEmptyContainer() { // testing front on empty Container C = makeContainer(1); Container const& CC = C; (void)C.front(); (void)CC.front(); C.clear(); EXPECT_DEATH( C.front() ); EXPECT_DEATH( CC.front() ); } static void EraseIterIter() { // testing erase iter iter invalidation Container C1 = makeContainer(3); iterator it1 = C1.begin(); iterator it1_next = ++C1.begin(); iterator it1_after_next = ++C1.begin(); ++it1_after_next; iterator it1_back = --C1.end(); assert(it1_next != it1_back); if (CT == CT_Vector) { EXPECT_DEATH( C1.erase(it1_next, it1) ); // bad range } C1.erase(it1, it1_after_next); EXPECT_DEATH( C1.erase(it1) ); EXPECT_DEATH( C1.erase(it1_next) ); if (CT == CT_List) { C1.erase(it1_back); } else { EXPECT_DEATH( C1.erase(it1_back) ); } } static void PopBack() { // testing pop_back() invalidation Container C1 = makeContainer(2); iterator it1 = C1.end(); --it1; C1.pop_back(); EXPECT_DEATH( C1.erase(it1) ); C1.erase(C1.begin()); assert(C1.size() == 0); EXPECT_DEATH( C1.pop_back() ); } static void PopFront() { // testing pop_front() invalidation Container C1 = makeContainer(2); iterator it1 = C1.begin(); C1.pop_front(); EXPECT_DEATH( C1.erase(it1) ); C1.erase(C1.begin()); assert(C1.size() == 0); EXPECT_DEATH( C1.pop_front() ); } static void InsertIterValue() { // testing insert(iter, value) Container C1 = makeContainer(2); iterator it1 = C1.begin(); iterator it1_next = it1; ++it1_next; Container C2 = C1; const value_type value = makeValueType(3); value_type rvalue = makeValueType(3); EXPECT_DEATH( C2.insert(it1, value) ); // wrong container EXPECT_DEATH( C2.insert(it1, std::move(rvalue)) ); // wrong container C1.insert(it1_next, value); if (CT == CT_List) { C1.insert(it1_next, value); C1.insert(it1, value); C1.insert(it1_next, std::move(rvalue)); C1.insert(it1, std::move(rvalue)); } else { EXPECT_DEATH( C1.insert(it1_next, value) ); // invalidated iterator EXPECT_DEATH( C1.insert(it1, value) ); // invalidated iterator EXPECT_DEATH( C1.insert(it1_next, std::move(rvalue)) ); // invalidated iterator EXPECT_DEATH( C1.insert(it1, std::move(rvalue)) ); // invalidated iterator } } static void EmplaceIterValue() { // testing emplace(iter, value) Container C1 = makeContainer(2); iterator it1 = C1.begin(); iterator it1_next = it1; ++it1_next; Container C2 = C1; const value_type value = makeValueType(3); EXPECT_DEATH( C2.emplace(it1, value) ); // wrong container EXPECT_DEATH( C2.emplace(it1, makeValueType(4)) ); // wrong container C1.emplace(it1_next, value); if (CT == CT_List) { C1.emplace(it1_next, value); C1.emplace(it1, value); } else { EXPECT_DEATH( C1.emplace(it1_next, value) ); // invalidated iterator EXPECT_DEATH( C1.emplace(it1, value) ); // invalidated iterator } } static void InsertIterSizeValue() { // testing insert(iter, size, value) Container C1 = makeContainer(2); iterator it1 = C1.begin(); iterator it1_next = it1; ++it1_next; Container C2 = C1; const value_type value = makeValueType(3); EXPECT_DEATH( C2.insert(it1, 1, value) ); // wrong container C1.insert(it1_next, 2, value); if (CT == CT_List) { C1.insert(it1_next, 3, value); C1.insert(it1, 1, value); } else { EXPECT_DEATH( C1.insert(it1_next, 1, value) ); // invalidated iterator EXPECT_DEATH( C1.insert(it1, 1, value) ); // invalidated iterator } } static void InsertIterIterIter() { // testing insert(iter, iter, iter) Container C1 = makeContainer(2); iterator it1 = C1.begin(); iterator it1_next = it1; ++it1_next; Container C2 = C1; std::vector<value_type> V = { makeValueType(1), makeValueType(2), makeValueType(3) }; EXPECT_DEATH( C2.insert(it1, V.begin(), V.end()) ); // wrong container C1.insert(it1_next, V.begin(), V.end()); if (CT == CT_List) { C1.insert(it1_next, V.begin(), V.end()); C1.insert(it1, V.begin(), V.end()); } else { EXPECT_DEATH( C1.insert(it1_next, V.begin(), V.end()) ); // invalidated iterator EXPECT_DEATH( C1.insert(it1, V.begin(), V.end()) ); // invalidated iterator } } }; int main(int, char**) { using Alloc = test_allocator<int>; { SequenceContainerChecks<std::list<int, Alloc>, CT_List>::run(); SequenceContainerChecks<std::vector<int, Alloc>, CT_Vector>::run(); } // FIXME these containers don't support iterator debugging if ((false)) { SequenceContainerChecks< std::vector<bool, test_allocator<bool>>, CT_VectorBool>::run(); SequenceContainerChecks< std::forward_list<int, Alloc>, CT_ForwardList>::run(); SequenceContainerChecks< std::deque<int, Alloc>, CT_Deque>::run(); } return 0; }
28.095238
86
0.600847
[ "vector" ]
a96bb1baabad1fc6010888681e646dc4ad323502
895
cpp
C++
host/display/cubic_rate_filter.cpp
wmax351/airball-embedded
204189922415b0f3cbef5dda14fa137e3c806a7d
[ "MIT" ]
null
null
null
host/display/cubic_rate_filter.cpp
wmax351/airball-embedded
204189922415b0f3cbef5dda14fa137e3c806a7d
[ "MIT" ]
null
null
null
host/display/cubic_rate_filter.cpp
wmax351/airball-embedded
204189922415b0f3cbef5dda14fa137e3c806a7d
[ "MIT" ]
null
null
null
#include <complex> #include "cubic_rate_filter.h" #include "polyfit.h" namespace airball { cubic_rate_filter::cubic_rate_filter(int size) { set_size(size); } int cubic_rate_filter::size() const { return values_y_.size(); } void cubic_rate_filter::set_size(int size) { values_y_.resize(size, 0); } void cubic_rate_filter::put(double y) { values_y_.pop_back(); values_y_.insert(values_y_.begin(), y); compute_rate(); } double cubic_rate_filter::get_rate() { return rate_; } void cubic_rate_filter::compute_rate() { std::vector<double> coeff; std::vector<double> values_x; for (int i = 0; i < values_y_.size(); i++) { values_x.insert(values_x.begin(), (double) i); } polyfit(values_x, values_y_, coeff, 3); const double x = values_x[0]; rate_ = 0; for (int i = 1; i < coeff.size(); i++) { rate_ += coeff[i] * ((double) i) * std::pow(x, i - 1); } } }
20.340909
58
0.664804
[ "vector" ]
a96c3e4547e10c44bd24ffb503c6cb713e486a48
5,143
cc
C++
src/lib/dns/tests/rdata_dhcid_unittest.cc
svenauhagen/kea
8a575ad46dee1487364fad394e7a325337200839
[ "Apache-2.0" ]
273
2015-01-22T14:14:42.000Z
2022-03-13T10:27:44.000Z
src/lib/dns/tests/rdata_dhcid_unittest.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
104
2015-01-16T16:37:06.000Z
2021-08-08T19:38:45.000Z
src/lib/dns/tests/rdata_dhcid_unittest.cc
jxiaobin/kea
1987a50a458921f9e5ac84cb612782c07f3b601d
[ "Apache-2.0" ]
133
2015-02-21T14:06:39.000Z
2022-02-27T08:56:40.000Z
// Copyright (C) 2011-2015 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <exceptions/exceptions.h> #include <util/buffer.h> #include <dns/rdataclass.h> #include <util/encode/base64.h> #include <gtest/gtest.h> #include <dns/tests/unittest_util.h> #include <dns/tests/rdata_unittest.h> #include <util/unittests/wiredata.h> using namespace std; using namespace isc; using namespace isc::dns; using namespace isc::util; using namespace isc::util::encode; using namespace isc::dns::rdata; using isc::UnitTestUtil; using isc::util::unittests::matchWireData; namespace { class Rdata_DHCID_Test : public RdataTest { protected: Rdata_DHCID_Test() : dhcid_txt("0LIg0LvQtdGB0YMg0YDQvtC00LjQu9Cw0YHRjCDRkdC70L7Rh9C60LA="), rdata_dhcid(dhcid_txt) {} void checkFromText_None(const string& rdata_str) { checkFromText<in::DHCID, isc::Exception, isc::Exception>( rdata_str, rdata_dhcid, false, false); } void checkFromText_BadValue(const string& rdata_str) { checkFromText<in::DHCID, BadValue, BadValue>( rdata_str, rdata_dhcid, true, true); } void checkFromText_LexerError(const string& rdata_str) { checkFromText <in::DHCID, InvalidRdataText, MasterLexer::LexerError>( rdata_str, rdata_dhcid, true, true); } void checkFromText_BadString(const string& rdata_str) { checkFromText <in::DHCID, InvalidRdataText, isc::Exception>( rdata_str, rdata_dhcid, true, false); } const string dhcid_txt; const in::DHCID rdata_dhcid; }; TEST_F(Rdata_DHCID_Test, fromText) { EXPECT_EQ(dhcid_txt, rdata_dhcid.toText()); // Space in digest data is OK checkFromText_None( "0LIg0LvQtdGB0YMg 0YDQvtC00LjQu9Cw 0YHRjCDRkdC70L7R h9C60LA="); // Multi-line digest data is OK, if enclosed in parentheses checkFromText_None( "( 0LIg0LvQtdGB0YMg0YDQvtC00LjQu9Cw\n0YHRjCDRkdC70L7R h9C60LA= )"); // Trailing garbage. This should cause only the string constructor // to fail, but the lexer constructor must be able to continue // parsing from it. checkFromText_BadString( "0LIg0LvQtdGB0YMg0YDQvtC00LjQu9Cw0YHRjCDRkdC70L7Rh9C60LA=" " ; comment\n" "AAIBY2/AuCccgoJbsaxcQc9TUapptP69lOjxfNuVAA2kjEA="); } TEST_F(Rdata_DHCID_Test, badText) { // missing digest data checkFromText_LexerError(""); // invalid base64 checkFromText_BadValue("EEeeeeeeEEEeeeeeeGaaahAAAAAAAAHHHHHHHHHHH!="); // unterminated multi-line base64 checkFromText_LexerError( "( 0LIg0LvQtdGB0YMg0YDQvtC00LjQu9Cw\n0YHRjCDRkdC70L7R h9C60LA="); } TEST_F(Rdata_DHCID_Test, copy) { const in::DHCID rdata_dhcid2(rdata_dhcid); EXPECT_EQ(0, rdata_dhcid.compare(rdata_dhcid2)); } TEST_F(Rdata_DHCID_Test, createFromWire) { EXPECT_EQ(0, rdata_dhcid.compare( *rdataFactoryFromFile(RRType("DHCID"), RRClass("IN"), "rdata_dhcid_fromWire"))); InputBuffer buffer(NULL, 0); EXPECT_THROW(in::DHCID(buffer, 0), InvalidRdataLength); // TBD: more tests } TEST_F(Rdata_DHCID_Test, createFromLexer) { EXPECT_EQ(0, rdata_dhcid.compare( *test::createRdataUsingLexer(RRType::DHCID(), RRClass::IN(), dhcid_txt))); } TEST_F(Rdata_DHCID_Test, toWireRenderer) { rdata_dhcid.toWire(renderer); vector<unsigned char> data; UnitTestUtil::readWireData("rdata_dhcid_toWire", data); matchWireData(&data[0], data.size(), renderer.getData(), renderer.getLength()); } TEST_F(Rdata_DHCID_Test, toWireBuffer) { rdata_dhcid.toWire(obuffer); vector<unsigned char> data; UnitTestUtil::readWireData("rdata_dhcid_toWire", data); matchWireData(&data[0], data.size(), obuffer.getData(), obuffer.getLength()); } TEST_F(Rdata_DHCID_Test, toText) { EXPECT_EQ(dhcid_txt, rdata_dhcid.toText()); } TEST_F(Rdata_DHCID_Test, getDHCIDDigest) { const string dhcid_txt1(encodeBase64(rdata_dhcid.getDigest())); EXPECT_EQ(dhcid_txt, dhcid_txt1); } TEST_F(Rdata_DHCID_Test, compare) { // trivial case: self equivalence // cppcheck-suppress uselessCallsCompare EXPECT_EQ(0, rdata_dhcid.compare(rdata_dhcid)); in::DHCID rdata_dhcid1("0YLQvtC/0L7Qu9GPINC00LLQsCDRgNGD0LHQu9GP"); in::DHCID rdata_dhcid2("0YLQvtC/0L7Qu9GPINGC0YDQuCDRgNGD0LHQu9GP"); in::DHCID rdata_dhcid3("0YLQvtC/0L7Qu9GPINGH0LXRgtGL0YDQtSDRgNGD0LHQu9GP"); EXPECT_LT(rdata_dhcid1.compare(rdata_dhcid2), 0); EXPECT_GT(rdata_dhcid2.compare(rdata_dhcid1), 0); EXPECT_LT(rdata_dhcid2.compare(rdata_dhcid3), 0); EXPECT_GT(rdata_dhcid3.compare(rdata_dhcid2), 0); // comparison attempt between incompatible RR types should be rejected EXPECT_THROW(rdata_dhcid.compare(*rdata_nomatch), bad_cast); } }
30.981928
79
0.700175
[ "vector" ]
a96d9214572fbcb5661a097a7289261a4e066d88
6,142
cpp
C++
src/utils/SkLayer.cpp
coltorchen/android-skia
91bb0c6f4224715ab78e3f64ba471a42d5d5a307
[ "BSD-3-Clause" ]
39
2015-12-12T23:40:51.000Z
2021-11-01T06:04:55.000Z
src/utils/SkLayer.cpp
coltorchen/android-skia
91bb0c6f4224715ab78e3f64ba471a42d5d5a307
[ "BSD-3-Clause" ]
2
2017-07-25T09:37:22.000Z
2017-08-04T07:18:56.000Z
src/utils/SkLayer.cpp
coltorchen/android-skia
91bb0c6f4224715ab78e3f64ba471a42d5d5a307
[ "BSD-3-Clause" ]
30
2015-02-28T12:23:06.000Z
2021-11-01T06:04:57.000Z
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkLayer.h" #include "SkCanvas.h" //#define DEBUG_DRAW_LAYER_BOUNDS //#define DEBUG_TRACK_NEW_DELETE #ifdef DEBUG_TRACK_NEW_DELETE static int gLayerAllocCount; #endif SK_DEFINE_INST_COUNT(SkLayer) /////////////////////////////////////////////////////////////////////////////// SkLayer::SkLayer() { fParent = NULL; m_opacity = SK_Scalar1; m_size.set(0, 0); m_position.set(0, 0); m_anchorPoint.set(SK_ScalarHalf, SK_ScalarHalf); fMatrix.reset(); fChildrenMatrix.reset(); fFlags = 0; #ifdef DEBUG_TRACK_NEW_DELETE gLayerAllocCount += 1; SkDebugf("SkLayer new: %d\n", gLayerAllocCount); #endif } SkLayer::SkLayer(const SkLayer& src) { fParent = NULL; m_opacity = src.m_opacity; m_size = src.m_size; m_position = src.m_position; m_anchorPoint = src.m_anchorPoint; fMatrix = src.fMatrix; fChildrenMatrix = src.fChildrenMatrix; fFlags = src.fFlags; #ifdef DEBUG_TRACK_NEW_DELETE gLayerAllocCount += 1; SkDebugf("SkLayer copy: %d\n", gLayerAllocCount); #endif } SkLayer::~SkLayer() { this->removeChildren(); #ifdef DEBUG_TRACK_NEW_DELETE gLayerAllocCount -= 1; SkDebugf("SkLayer delete: %d\n", gLayerAllocCount); #endif } /////////////////////////////////////////////////////////////////////////////// bool SkLayer::isInheritFromRootTransform() const { return (fFlags & kInheritFromRootTransform_Flag) != 0; } void SkLayer::setInheritFromRootTransform(bool doInherit) { if (doInherit) { fFlags |= kInheritFromRootTransform_Flag; } else { fFlags &= ~kInheritFromRootTransform_Flag; } } void SkLayer::setMatrix(const SkMatrix& matrix) { fMatrix = matrix; } void SkLayer::setChildrenMatrix(const SkMatrix& matrix) { fChildrenMatrix = matrix; } /////////////////////////////////////////////////////////////////////////////// int SkLayer::countChildren() const { return m_children.count(); } SkLayer* SkLayer::getChild(int index) const { if ((unsigned)index < (unsigned)m_children.count()) { SkASSERT(m_children[index]->fParent == this); return m_children[index]; } return NULL; } SkLayer* SkLayer::addChild(SkLayer* child) { SkASSERT(this != child); child->ref(); child->detachFromParent(); SkASSERT(child->fParent == NULL); child->fParent = this; *m_children.append() = child; return child; } void SkLayer::detachFromParent() { if (fParent) { int index = fParent->m_children.find(this); SkASSERT(index >= 0); fParent->m_children.remove(index); fParent = NULL; this->unref(); // this call might delete us } } void SkLayer::removeChildren() { int count = m_children.count(); for (int i = 0; i < count; i++) { SkLayer* child = m_children[i]; SkASSERT(child->fParent == this); child->fParent = NULL; // in case it has more than one owner child->unref(); } m_children.reset(); } SkLayer* SkLayer::getRootLayer() const { const SkLayer* root = this; while (root->fParent != NULL) { root = root->fParent; } return const_cast<SkLayer*>(root); } /////////////////////////////////////////////////////////////////////////////// void SkLayer::getLocalTransform(SkMatrix* matrix) const { matrix->setTranslate(m_position.fX, m_position.fY); SkScalar tx = SkScalarMul(m_anchorPoint.fX, m_size.width()); SkScalar ty = SkScalarMul(m_anchorPoint.fY, m_size.height()); matrix->preTranslate(tx, ty); matrix->preConcat(this->getMatrix()); matrix->preTranslate(-tx, -ty); } void SkLayer::localToGlobal(SkMatrix* matrix) const { this->getLocalTransform(matrix); if (this->isInheritFromRootTransform()) { matrix->postConcat(this->getRootLayer()->getMatrix()); return; } const SkLayer* layer = this; while (layer->fParent != NULL) { layer = layer->fParent; SkMatrix tmp; layer->getLocalTransform(&tmp); tmp.preConcat(layer->getChildrenMatrix()); matrix->postConcat(tmp); } } /////////////////////////////////////////////////////////////////////////////// void SkLayer::onDraw(SkCanvas*, SkScalar opacity) { // SkDebugf("----- no onDraw for %p\n", this); } #include "SkString.h" void SkLayer::draw(SkCanvas* canvas, SkScalar opacity) { #if 0 SkString str1, str2; // this->getMatrix().toDumpString(&str1); // this->getChildrenMatrix().toDumpString(&str2); SkDebugf("--- drawlayer %p opacity %g size [%g %g] pos [%g %g] matrix %s children %s\n", this, opacity * this->getOpacity(), m_size.width(), m_size.height(), m_position.fX, m_position.fY, str1.c_str(), str2.c_str()); #endif opacity = SkScalarMul(opacity, this->getOpacity()); if (opacity <= 0) { // SkDebugf("---- abort drawing %p opacity %g\n", this, opacity); return; } SkAutoCanvasRestore acr(canvas, true); // apply our local transform { SkMatrix tmp; this->getLocalTransform(&tmp); if (this->isInheritFromRootTransform()) { // should we also apply the root's childrenMatrix? canvas->setMatrix(getRootLayer()->getMatrix()); } canvas->concat(tmp); } this->onDraw(canvas, opacity); #ifdef DEBUG_DRAW_LAYER_BOUNDS { SkRect r = SkRect::MakeSize(this->getSize()); SkPaint p; p.setAntiAlias(true); p.setStyle(SkPaint::kStroke_Style); p.setStrokeWidth(SkIntToScalar(2)); p.setColor(0xFFFF44DD); canvas->drawRect(r, p); canvas->drawLine(r.fLeft, r.fTop, r.fRight, r.fBottom, p); canvas->drawLine(r.fLeft, r.fBottom, r.fRight, r.fTop, p); } #endif int count = this->countChildren(); if (count > 0) { canvas->concat(this->getChildrenMatrix()); for (int i = 0; i < count; i++) { this->getChild(i)->draw(canvas, opacity); } } }
26.360515
92
0.594106
[ "transform" ]
a973424def22fbd3948443432db80f101bdba217
6,134
cpp
C++
object_transform.cpp
githaff/vectograph
15f7add7d57610aa2dce0de6d6199895d9434db3
[ "BSD-2-Clause" ]
null
null
null
object_transform.cpp
githaff/vectograph
15f7add7d57610aa2dce0de6d6199895d9434db3
[ "BSD-2-Clause" ]
null
null
null
object_transform.cpp
githaff/vectograph
15f7add7d57610aa2dce0de6d6199895d9434db3
[ "BSD-2-Clause" ]
null
null
null
#include "svgobjects.h" //------------------перевод объектов в формат сцены----------------// void fillVector2DFromString(QVector<QPointF>& v,QString& s) { auto list = s.split(QRegExp("\\D+")); //убрать все возможные пробелы list.removeAll(""); v.reserve( ( list.size() / 2 ) + 1); for(int i = 0;i < list.size();i += 2) { QPoint p(list[i].toDouble(),list[i + 1].toDouble()); v.push_back(p); } } QColor color(QString& color) { return (!color.isEmpty()) ? QColor(color) : Qt::black; } double realDefaults(double attr) {//параметры по умолчанию //при незаданных параметрах //берутся равные 1 //пример: толщина линии return ( attr == 0 ) ? 1 : attr; } double opacity(double op) {//по умолчанию = 1 //в отличие от других параметров return ( op == 0 ) ? 1 : op; } void Object::setItemAttributes(QGraphicsItem* item) { //разрешить перемещение объекта по сцене //выделять объект при его выборе item->setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsSelectable); //прозрачность элемента item->setOpacity( opacity (_fillOpacity) ); } void Object::setShapeItemAttributes(QAbstractGraphicsShapeItem* item) { setItemAttributes(item); QPen pen; //цвет обводки pen.setColor(QColor(_stroke )); //толщина обводки pen.setWidthF(realDefaults(_strokeWidth)); //цвет обводки item->setPen(pen); item->setBrush(QColor(_fill)); } void Ellipse::transformToScene() { setShapeItemAttributes(this); double x = _cx - _rx; double y = _cy - _ry; double width = _rx * 2; double height = _ry * 2; setRect(x,y,width,height); } void Circle::transformToScene() { setShapeItemAttributes(this); double x = _cx - _r; double y = _cy - _r; double diameter = _r * 2; setRect(x,y,diameter,diameter); } void Rectangle::transformToScene() { setShapeItemAttributes(this); setRect(_x,_y,_width,_height); } void Line::transformToScene() { setItemAttributes(this); QPen pen; pen.setColor(QColor(_stroke )); //толщина обводки pen.setWidthF(realDefaults(_strokeWidth)); //цвет обводки setPen(pen); setLine(_x1,_y1,_x2,_y2); } void Polyline::transformToScene() { setShapeItemAttributes(this); QPainterPath path; //начинаем рисовать с 1-вой точки path.moveTo(_points[0]); for(auto &p : _points) path.lineTo(p); setPath(path); } void Polygon::transformToScene() { setShapeItemAttributes(this); setPolygon(QPolygonF(_points)); } void Text::transformToScene() { setItemAttributes(this); setPlainText(_text); //сделать текст редактируемым setTextInteractionFlags(Qt::TextEditorInteraction); setPos(_x,_y); } //--------------------------перевод объектов в формат svg------------// void Object::getItemAttributes(QGraphicsItem *item) { //прозрачность _fillOpacity = item->opacity(); } void Object::getShapeItemAttributes(QAbstractGraphicsShapeItem *item) { getItemAttributes(item); QPen pen = item->pen(); QColor penColor = pen.color(); //обводка по умолчанию чёрная //не нужно записывать if(penColor != Qt::black) _stroke = penColor.name(); _strokeWidth = pen.widthF(); //по умолч. цвет заливки белый QBrush brush = item->brush(); QColor brushColor = brush.color(); if(brushColor != Qt::white) _fill = brushColor.name(); } void Ellipse::transformToSvg() { getShapeItemAttributes(this); QRectF rectangle = rect(); QPointF point = QGraphicsItem::mapToScene(rectangle.x(),rectangle.y()); double width = rectangle.width(); double height = rectangle.height(); double x = point.x(); double y = point.y(); _rx = width / 2; _cx = x + _rx; _ry = height / 2; _cy = y + _ry; } void Circle::transformToSvg() { /* double x = _cx - _r; double y = _cy - _r; double diameter = _r * 2; */ getShapeItemAttributes(this); QRectF rectangle = rect(); QPointF point = QGraphicsItem::mapToScene(rectangle.x(),rectangle.y()); double diametr = rectangle.width(); double x = point.x(); double y = point.y(); _r = diametr / 2; _cx = x + _r; _cy = y + _r; } void Rectangle::transformToSvg() { getShapeItemAttributes(this); QRectF rectangle = rect(); QPointF point = QGraphicsItem::mapToScene(rectangle.x(),rectangle.y()); _x = point.x(); _y = point.y(); _width = rectangle.width(); _height = rectangle.height(); } void Line::transformToSvg() { getItemAttributes(this); QPen _pen = pen(); QColor penColor = _pen.color(); _stroke = penColor.name(); _strokeWidth = _pen.widthF(); QLineF _line = line(); QPointF p1 = QGraphicsItem::mapToScene(_line.x1(),_line.y1()); QPointF p2 = QGraphicsItem::mapToScene(_line.x2(),_line.y2()); _x1 = p1.x(); _y1 = p1.y(); _x2 = p2.x(); _y2 = p2.y(); } size_t Polyline::vertcesBegin(QPainterPath& path) { //находим начало обхода точек полилинии for(int i = path.elementCount() - 1;i >= 0;i--) { if(path.elementAt(i).isMoveTo()) return i; } return 0; } void Polyline::verticesFromScene() { QPainterPath path = shape(); size_t vertBeg = vertcesBegin(path); int newSize = path.elementCount() - vertBeg; if( newSize != _points.size()) _points.resize(newSize); size_t j = 0; for(int i = vertBeg;i < path.elementCount();i ++) _points[j++] = QGraphicsItem::mapToScene(path.elementAt(i).x,path.elementAt(i).y); } void Polyline::transformToSvg() { getShapeItemAttributes(this); //записать массив точек verticesFromScene(); } void Polygon::transformToSvg() { getShapeItemAttributes(this); //массив точек //полигон = QVector<QPointF> QPolygonF pol = polygon(); for(int i = 0;i < pol.size();i++) _points[i] = QGraphicsItem::mapToScene( pol.at(i) ); } void Text::transformToSvg() { getItemAttributes(this); QPointF position = scenePos(); _x = position.x(); _y = position.y(); _text = toPlainText(); }
21.447552
91
0.631725
[ "object", "shape" ]
a975d5c1a4d19e3ed6cec7d21ece36c094dddfbf
44,174
cpp
C++
drivers/spi/bcm2836/device.cpp
christopherco/rpi-iotcore
2cf15e428e743dd7f7742f7511725741640c5be3
[ "MIT" ]
89
2018-12-22T15:34:45.000Z
2021-12-16T20:07:29.000Z
drivers/spi/bcm2836/device.cpp
christopherco/rpi-iotcore
2cf15e428e743dd7f7742f7511725741640c5be3
[ "MIT" ]
31
2021-01-10T16:04:10.000Z
2022-03-12T08:04:21.000Z
drivers/spi/bcm2836/device.cpp
christopherco/rpi-iotcore
2cf15e428e743dd7f7742f7511725741640c5be3
[ "MIT" ]
42
2016-02-18T21:55:54.000Z
2018-11-27T07:12:01.000Z
/*++ Copyright (c) Microsoft Corporation. All rights reserved. Module Name: device.cpp Abstract: This module contains WDF device initialization and SPB callback functions for the controller driver. Environment: kernel-mode only Revision History: --*/ #include "internal.h" #include "device.h" #include "controller.h" #include "device.tmh" ///////////////////////////////////////////////// // // WDF and SPB DDI callbacks. // ///////////////////////////////////////////////// _Use_decl_annotations_ NTSTATUS OnPrepareHardware( WDFDEVICE FxDevice, WDFCMRESLIST FxResourcesRaw, WDFCMRESLIST FxResourcesTranslated ) /*++ Routine Description: This routine maps the hardware resources to the SPB controller register structure. Arguments: FxDevice - a handle to the framework device object FxResourcesRaw - list of translated hardware resources that the PnP manager has assigned to the device FxResourcesTranslated - list of raw hardware resources that the PnP manager has assigned to the device Return Value: Status --*/ { FuncEntry(TRACE_FLAG_WDFLOADING); PPBC_DEVICE pDevice = GetDeviceContext(FxDevice); NT_ASSERT(pDevice != NULL); ULONG irqCount = 0; NTSTATUS status = STATUS_SUCCESS; UNREFERENCED_PARAMETER(FxResourcesRaw); // // Get the register base for the SPI controller. // { ULONG resourceCount = WdfCmResourceListGetCount(FxResourcesTranslated); for (ULONG i = 0; i < resourceCount; i++) { PCM_PARTIAL_RESOURCE_DESCRIPTOR res; res = WdfCmResourceListGetDescriptor(FxResourcesTranslated, i); if (res->Type == CmResourceTypeMemory) { if (pDevice->pSPIRegisters != NULL) { status = STATUS_DEVICE_CONFIGURATION_ERROR; Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_WDFLOADING, "Error multiple memory regions assigned (PA:%I64x, length:%d) for WDFDEVICE %p - %!STATUS!", res->u.Memory.Start.QuadPart, res->u.Memory.Length, pDevice->FxDevice, status); goto exit; } if (res->u.Memory.Length < sizeof(BCM_SPI_REGISTERS)) { status = STATUS_DEVICE_CONFIGURATION_ERROR; Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_WDFLOADING, "Error memory region too small (PA:%I64x, length:%d) for WDFDEVICE %p - %!STATUS!", res->u.Memory.Start.QuadPart, res->u.Memory.Length, pDevice->FxDevice, status); goto exit; } pDevice->pSPIRegisters = #if (NTDDI_VERSION > NTDDI_WINBLUE) (PBCM_SPI_REGISTERS)MmMapIoSpaceEx( res->u.Memory.Start, res->u.Memory.Length, PAGE_READWRITE | PAGE_NOCACHE); #else (PBCM_SPI_REGISTERS)MmMapIoSpace( res->u.Memory.Start, res->u.Memory.Length, MmNonCached); #endif if (pDevice->pSPIRegisters == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_WDFLOADING, "Error mapping controller registers (PA:%I64x, length:%d) for WDFDEVICE %p - %!STATUS!", res->u.Memory.Start.QuadPart, res->u.Memory.Length, pDevice->FxDevice, status); goto exit; } pDevice->SPIRegistersCb = res->u.Memory.Length; pDevice->pSPIRegistersPhysicalAddress = res->u.Memory.Start; Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_WDFLOADING, "SPI controller @ paddr %I64x vaddr @ %p for WDFDEVICE %p", pDevice->pSPIRegistersPhysicalAddress.QuadPart, pDevice->pSPIRegisters, pDevice->FxDevice); } else if (res->Type == CmResourceTypeInterrupt) { irqCount++; } } } if (irqCount != 1) { status = STATUS_DEVICE_CONFIGURATION_ERROR; Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_WDFLOADING, "Error number of assigned interrupts incorrect (%d instead of 1) for WDFDEVICE %p - %!STATUS!", irqCount, pDevice->FxDevice, status); goto exit; } if (pDevice->pSPIRegisters == NULL) { status = STATUS_DEVICE_CONFIGURATION_ERROR; Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_WDFLOADING, "Error memory region missing for WDFDEVICE %p - %!STATUS!", pDevice->FxDevice, status); goto exit; } exit: if (!NT_SUCCESS(status)) { // make sure memory is unmapped in case of failure OnReleaseHardware(FxDevice, FxResourcesTranslated); } FuncExit(TRACE_FLAG_WDFLOADING); return status; } _Use_decl_annotations_ NTSTATUS OnReleaseHardware( WDFDEVICE FxDevice, WDFCMRESLIST FxResourcesTranslated ) /*++ Routine Description: This routine unmaps the SPB controller register structure. Arguments: FxDevice - a handle to the framework device object FxResourcesRaw - list of translated hardware resources that the PnP manager has assigned to the device FxResourcesTranslated - list of raw hardware resources that the PnP manager has assigned to the device Return Value: Status --*/ { FuncEntry(TRACE_FLAG_WDFLOADING); PPBC_DEVICE pDevice = GetDeviceContext(FxDevice); NT_ASSERT(pDevice != NULL); NTSTATUS status = STATUS_SUCCESS; UNREFERENCED_PARAMETER(FxResourcesTranslated); if (pDevice->pSPIRegisters != NULL) { MmUnmapIoSpace(pDevice->pSPIRegisters, pDevice->SPIRegistersCb); pDevice->pSPIRegisters = NULL; pDevice->SPIRegistersCb = 0; } FuncExit(TRACE_FLAG_WDFLOADING); return status; } _Use_decl_annotations_ NTSTATUS OnD0Entry( WDFDEVICE FxDevice, WDF_POWER_DEVICE_STATE FxPreviousState ) /*++ Routine Description: This routine allocates objects needed by the driver and initializes the controller hardware. Arguments: FxDevice - a handle to the framework device object FxPreviousState - previous power state Return Value: Status --*/ { FuncEntry(TRACE_FLAG_WDFLOADING); PPBC_DEVICE pDevice = GetDeviceContext(FxDevice); NT_ASSERT(pDevice != NULL); UNREFERENCED_PARAMETER(FxPreviousState); // // Initialize controller. // pDevice->pCurrentTarget = NULL; pDevice->Locked = FALSE; ControllerInitialize(pDevice); FuncExit(TRACE_FLAG_WDFLOADING); return STATUS_SUCCESS; } _Use_decl_annotations_ NTSTATUS OnD0Exit( WDFDEVICE FxDevice, WDF_POWER_DEVICE_STATE FxPreviousState ) /*++ Routine Description: This routine destroys objects needed by the driver and uninitializes the controller hardware. Arguments: FxDevice - a handle to the framework device object FxPreviousState - previous power state Return Value: Status --*/ { FuncEntry(TRACE_FLAG_WDFLOADING); PPBC_DEVICE pDevice = GetDeviceContext(FxDevice); NT_ASSERT(pDevice != NULL); NTSTATUS status = STATUS_SUCCESS; UNREFERENCED_PARAMETER(FxPreviousState); // // Uninitialize controller. // ControllerUninitialize(pDevice); pDevice->pCurrentTarget = NULL; pDevice->Locked = FALSE; FuncExit(TRACE_FLAG_WDFLOADING); return status; } _Use_decl_annotations_ NTSTATUS OnSelfManagedIoInit( WDFDEVICE FxDevice ) /*++ Routine Description: Initializes and starts the device's self-managed I/O operations. Arguments: FxDevice - a handle to the framework device object Return Value: None --*/ { FuncEntry(TRACE_FLAG_WDFLOADING); PPBC_DEVICE pDevice = GetDeviceContext(FxDevice); NTSTATUS status; // // Register for monitor power setting callback. This will be // used to dynamically set the idle timeout delay according // to the monitor power state. // NT_ASSERT(pDevice->pMonitorPowerSettingHandle == NULL); status = PoRegisterPowerSettingCallback( WdfDeviceWdmGetDeviceObject(pDevice->FxDevice), &GUID_MONITOR_POWER_ON, OnMonitorPowerSettingCallback, pDevice->FxDevice, &pDevice->pMonitorPowerSettingHandle); if (!NT_SUCCESS(status)) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_WDFLOADING, "Failed to register monitor power setting callback - %!STATUS!", status); goto exit; } exit: FuncExit(TRACE_FLAG_WDFLOADING); return status; } _Use_decl_annotations_ VOID OnSelfManagedIoCleanup( WDFDEVICE FxDevice ) /*++ Routine Description: Cleanup for the device's self-managed I/O operations. Arguments: FxDevice - a handle to the framework device object Return Value: None --*/ { FuncEntry(TRACE_FLAG_WDFLOADING); PPBC_DEVICE pDevice = GetDeviceContext(FxDevice); // // Unregister for monitor power setting callback. // if (pDevice->pMonitorPowerSettingHandle != NULL) { PoUnregisterPowerSettingCallback(pDevice->pMonitorPowerSettingHandle); pDevice->pMonitorPowerSettingHandle = NULL; } FuncExit(TRACE_FLAG_WDFLOADING); } _Use_decl_annotations_ NTSTATUS OnMonitorPowerSettingCallback( LPCGUID SettingGuid, PVOID Value, ULONG ValueLength, PVOID Context ) /*++ Routine Description: This routine updates the idle timeout delay according to the current monitor power setting. Arguments: SettingGuid - the setting GUID Value - pointer to the new value of the power setting that changed ValueLength - value of type ULONG that specifies the size, in bytes, of the new power setting value Context - the WDFDEVICE pointer context Return Value: Status --*/ { FuncEntry(TRACE_FLAG_WDFLOADING); UNREFERENCED_PARAMETER(ValueLength); WDFDEVICE Device; WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS idleSettings; BOOLEAN isMonitorOff; NTSTATUS status = STATUS_SUCCESS; if (Context == NULL) { status = STATUS_INVALID_PARAMETER; Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_WDFLOADING, "%!FUNC! parameter Context is NULL - %!STATUS!", status); goto exit; } Device = (WDFDEVICE)Context; // // We only expect GUID_MONITOR_POWER_ON notifications // in this callback, but let's check just to be sure. // if (IsEqualGUID(*SettingGuid, GUID_MONITOR_POWER_ON)) { NT_ASSERT(Value != NULL); NT_ASSERT(ValueLength == sizeof(ULONG)); // // Determine power setting. // isMonitorOff = ((*(PULONG)Value) == MONITOR_POWER_OFF); // // Update the idle timeout delay. // WDF_DEVICE_POWER_POLICY_IDLE_SETTINGS_INIT( &idleSettings, IdleCannotWakeFromS0); idleSettings.IdleTimeoutType = SystemManagedIdleTimeoutWithHint; if (isMonitorOff) { idleSettings.IdleTimeout = IDLE_TIMEOUT_MONITOR_OFF; } else { idleSettings.IdleTimeout = IDLE_TIMEOUT_MONITOR_ON; } status = WdfDeviceAssignS0IdleSettings( Device, &idleSettings); if (!NT_SUCCESS(status)) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_WDFLOADING, "Failed to assign S0 idle settings - %!STATUS!", status); goto exit; } } exit: FuncExit(TRACE_FLAG_WDFLOADING); return status; } _Use_decl_annotations_ NTSTATUS OnTargetConnect( WDFDEVICE SpbController, SPBTARGET SpbTarget ) /*++ Routine Description: This routine is invoked whenever a peripheral driver opens a target. It retrieves target-specific settings from the Resource Hub and saves them in the target's context. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbTarget - a handle to the SPBTARGET object Return Value: Status --*/ { FuncEntry(TRACE_FLAG_SPBDDI); PPBC_DEVICE pDevice = GetDeviceContext(SpbController); PPBC_TARGET pTarget = GetTargetContext(SpbTarget); NT_ASSERT(pDevice != NULL); NT_ASSERT(pTarget != NULL); NTSTATUS status = STATUS_SUCCESS; // // Get target connection parameters. // SPB_CONNECTION_PARAMETERS params; SPB_CONNECTION_PARAMETERS_INIT(&params); SpbTargetGetConnectionParameters(SpbTarget, &params); // // Retrieve target settings. // status = PbcTargetGetSettings(pDevice, params.ConnectionParameters, &pTarget->Settings ); // // fail on unsupported target settings // if (pTarget->Settings.DataBitLength != BCM_SPI_DATA_BIT_LENGTH_SUPPORTED || pTarget->Settings.DeviceSelection >= BCM_SPI_CS_SUPPORTED || (pTarget->Settings.GeneralFlags & SPI_SLV_BIT) != 0 || (pTarget->Settings.TypeSpecificFlags & SPI_WIREMODE_BIT) != 0 ) { status = STATUS_INVALID_PARAMETER; } // // Initialize target context. // if (NT_SUCCESS(status)) { pTarget->SpbTarget = SpbTarget; pTarget->pCurrentRequest = NULL; Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_SPBDDI, "Connected to SPBTARGET %p at device 0x%lx from WDFDEVICE %p", pTarget->SpbTarget, pTarget->Settings.DeviceSelection, pDevice->FxDevice); } FuncExit(TRACE_FLAG_SPBDDI); return status; } _Use_decl_annotations_ VOID OnControllerLock( WDFDEVICE SpbController, SPBTARGET SpbTarget, SPBREQUEST SpbRequest ) /*++ Routine Description: This routine is invoked whenever the controller is to be locked for a single target. The request is only completed if there is an error configuring the transfer. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbTarget - a handle to the SPBTARGET object SpbRequest - a handle to the SPBREQUEST object Return Value: None. The request is completed synchronously. --*/ { FuncEntry(TRACE_FLAG_SPBDDI); PPBC_DEVICE pDevice = GetDeviceContext(SpbController); PPBC_TARGET pTarget = GetTargetContext(SpbTarget); NT_ASSERT(pDevice != NULL); NT_ASSERT(pTarget != NULL); // // Acquire the device lock. // WdfSpinLockAcquire(pDevice->Lock); // // Assign current target. // NT_ASSERT(pDevice->pCurrentTarget == NULL); NT_ASSERT(!pDevice->Locked); pDevice->pCurrentTarget = pTarget; pDevice->Locked = TRUE; WdfSpinLockRelease(pDevice->Lock); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_SPBDDI, "Controller locked for SPBTARGET %p at device 0x%lx (WDFDEVICE %p)", pTarget->SpbTarget, pTarget->Settings.DeviceSelection, pDevice->FxDevice); // // Complete lock request. // SpbRequestComplete(SpbRequest, STATUS_SUCCESS); FuncExit(TRACE_FLAG_SPBDDI); } _Use_decl_annotations_ VOID OnControllerUnlock( WDFDEVICE SpbController, SPBTARGET SpbTarget, SPBREQUEST SpbRequest ) /*++ Routine Description: This routine is invoked whenever the controller is to be unlocked for a single target. The request is only completed if there is an error configuring the transfer. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbTarget - a handle to the SPBTARGET object SpbRequest - a handle to the SPBREQUEST object Return Value: None. The request is completed asynchronously. --*/ { FuncEntry(TRACE_FLAG_SPBDDI); PPBC_DEVICE pDevice = GetDeviceContext(SpbController); PPBC_TARGET pTarget = GetTargetContext(SpbTarget); NT_ASSERT(pDevice != NULL); NT_ASSERT(pTarget != NULL); // // Acquire the device lock. // WdfSpinLockAcquire(pDevice->Lock); ControllerUnlockTransfer(pDevice); // // Remove current target. // NT_ASSERT(pDevice->pCurrentTarget == pTarget); NT_ASSERT(pDevice->Locked); pDevice->pCurrentTarget = NULL; pDevice->Locked = FALSE; WdfSpinLockRelease(pDevice->Lock); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_SPBDDI, "Controller unlocked for SPBTARGET %p at device 0x%lx (WDFDEVICE %p)", pTarget->SpbTarget, pTarget->Settings.DeviceSelection, pDevice->FxDevice); // // Complete lock request. // SpbRequestComplete(SpbRequest, STATUS_SUCCESS); FuncExit(TRACE_FLAG_SPBDDI); } _Use_decl_annotations_ VOID OnRead( WDFDEVICE SpbController, SPBTARGET SpbTarget, SPBREQUEST SpbRequest, size_t Length ) /*++ Routine Description: This routine sets up a read from the target device using the supplied buffers. The request is only completed if there is an error configuring the transfer. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbTarget - a handle to the SPBTARGET object SpbRequest - a handle to the SPBREQUEST object Length - the number of bytes to read from the target Return Value: None. The request is completed asynchronously. --*/ { FuncEntry(TRACE_FLAG_SPBDDI); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_SPBDDI, "Received read request %p of length %Iu for SPBTARGET %p (WDFDEVICE %p)", SpbRequest, Length, SpbTarget, SpbController); OnNonSequenceRequest( SpbController, SpbTarget, SpbRequest, Length); FuncExit(TRACE_FLAG_SPBDDI); } _Use_decl_annotations_ VOID OnWrite( WDFDEVICE SpbController, SPBTARGET SpbTarget, SPBREQUEST SpbRequest, size_t Length ) /*++ Routine Description: This routine sets up a write to the target device using the supplied buffers. The request is only completed if there is an error configuring the transfer. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbTarget - a handle to the SPBTARGET object SpbRequest - a handle to the SPBREQUEST object Length - the number of bytes to write to the target Return Value: None. The request is completed asynchronously. --*/ { FuncEntry(TRACE_FLAG_SPBDDI); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_SPBDDI, "Received write request %p of length %Iu for SPBTARGET %p (WDFDEVICE %p)", SpbRequest, Length, SpbTarget, SpbController); OnNonSequenceRequest( SpbController, SpbTarget, SpbRequest, Length); FuncExit(TRACE_FLAG_SPBDDI); } _Use_decl_annotations_ VOID OnNonSequenceRequest( WDFDEVICE SpbController, SPBTARGET SpbTarget, SPBREQUEST SpbRequest, size_t Length ) /*++ Routine Description: This is a helper routine used to configure the request context and controller hardware for a non- sequence SPB request. It validates parameters and retrieves the transfer buffer as necessary. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbTarget - a handle to the SPBTARGET object SpbRequest - a handle to the SPBREQUEST object Length - the number of bytes to write/read to/from the target Return Value: None. The request is completed asynchronously. --*/ { FuncEntry(TRACE_FLAG_TRANSFER); PPBC_DEVICE pDevice = GetDeviceContext(SpbController); PPBC_TARGET pTarget = GetTargetContext(SpbTarget); PPBC_REQUEST pRequest = GetRequestContext(SpbRequest); UNREFERENCED_PARAMETER(Length); NTSTATUS status; // // Get the request parameters. // SPB_REQUEST_PARAMETERS params; SPB_REQUEST_PARAMETERS_INIT(&params); SpbRequestGetParameters(SpbRequest, &params); // // Initialize request context with info that persist // the lifetime of the request // pRequest->SpbRequest = SpbRequest; pRequest->Type = params.Type; pRequest->CurrentTransferSequencePosition = params.Position; pRequest->TransferCount = 1; pRequest->CurrentTransferIndex = 0; pRequest->TotalInformation = 0; pRequest->RequestLength = params.Length; status = OnRequest(pDevice, pTarget, pRequest); if (!NT_SUCCESS(status)) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Error configuring non-sequence, completing SPBREQUEST %p synchronously - %!STATUS!", pRequest->SpbRequest, status); SpbRequestComplete( pRequest->SpbRequest, status); } FuncExit(TRACE_FLAG_TRANSFER); } _Use_decl_annotations_ VOID OnSequenceRequest( WDFDEVICE SpbController, SPBTARGET SpbTarget, SPBREQUEST SpbRequest, ULONG /*TransferCount*/ ) /*++ Routine Description: This routine sets up a sequence of reads and writes. It validates parameters as necessary. The request is only completed if there is an error configuring the transfer. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbTarget - a handle to the SPBTARGET object SpbRequest - a handle to the SPBREQUEST object TransferCount - number of individual transfers in the sequence Return Value: None. The request is completed asynchronously. --*/ { FuncEntry(TRACE_FLAG_SPBDDI); PPBC_DEVICE pDevice = GetDeviceContext(SpbController); PPBC_TARGET pTarget = GetTargetContext(SpbTarget); PPBC_REQUEST pRequest = GetRequestContext(SpbRequest); NTSTATUS status = STATUS_SUCCESS; // // Get request parameters. // SPB_REQUEST_PARAMETERS params; SPB_REQUEST_PARAMETERS_INIT(&params); SpbRequestGetParameters(SpbRequest, &params); // // Initialize request context. // pRequest->SpbRequest = SpbRequest; pRequest->Type = params.Type; pRequest->CurrentTransferSequencePosition = params.Position; pRequest->CurrentTransferIndex = 0; pRequest->TotalInformation = 0; pRequest->RequestLength = params.Length; pRequest->TransferCount = params.SequenceTransferCount; // // Special handling for fullduplex transfer // if (params.Type == SpbRequestTypeOther) { // // Fullduplex request is a special kind of sequence request // It comes as sequence of write then read transfer and SPB // assign to it different rquest type // if (pRequest->TransferCount != 2) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Full-duplex request should specify only 2 transfers, %lu specified. SPBREQUEST %p (SPBTARGET %p)", pRequest->TransferCount, pRequest->SpbRequest, SpbTarget); status = STATUS_INVALID_PARAMETER; goto exit; } pRequest->TransferCount = 1; // // check for supported fullduplex sequences and the lock / unlock case // if (!pDevice->Locked) { NT_ASSERT(params.Position == SpbRequestSequencePositionSingle); } else { NT_ASSERT(params.Position == SpbRequestSequencePositionFirst || params.Position == SpbRequestSequencePositionContinue); } status = PbcRequestSetNthTransferInfo(pRequest, 1); if (!NT_SUCCESS(status)) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Error configuring full-duplex request context for SPBREQUEST %p (SPBTARGET %p) - %!STATUS!", pRequest->SpbRequest, SpbTarget, status); goto exit; } if (pRequest->CurrentTransferDirection != SpbTransferDirectionFromDevice) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Full-duplex request 2nd transfer should be a read transfer. SPBREQUEST %p (SPBTARGET %p)", pRequest->SpbRequest, SpbTarget); status = STATUS_INVALID_PARAMETER; goto exit; } if (pRequest->CurrentTransferDelayInUs > 0) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Full-duplex request SPBREQUEST %p should have zero delay specified (SPBTARGET %p)", pRequest->SpbRequest, SpbTarget); status = STATUS_INVALID_PARAMETER; goto exit; } Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_SPBDDI, "Received full-duplex for SPBTARGET %p (WDFDEVICE %p)", SpbTarget, SpbController); } else { NT_ASSERT(params.Position == SpbRequestSequencePositionSingle); NT_ASSERT(params.Type == SpbRequestTypeSequence); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_SPBDDI, "Received sequence request with transfer count %d for SPBTARGET %p (WDFDEVICE %p)", pRequest->TransferCount, SpbTarget, SpbController); } // // Configure the request. // // // Get length and MDL for first transfer in the request // it will be the write request if request is fullduplex // status = PbcRequestSetNthTransferInfo(pRequest, 0); if (!NT_SUCCESS(status)) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Error configuring request context for SPBREQUEST %p (SPBTARGET %p) - %!STATUS!", pRequest->SpbRequest, SpbTarget, status); goto exit; } if (pRequest->Type == SpbRequestTypeOther) { if (pRequest->CurrentTransferDirection != SpbTransferDirectionToDevice) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Full-duplex request 1st transfer should be a write transfer. SPBREQUEST %p (SPBTARGET %p)", pRequest->SpbRequest, SpbTarget); status = STATUS_INVALID_PARAMETER; goto exit; } if (pRequest->CurrentTransferDelayInUs > 0) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Full-duplex request SPBREQUEST %p should have zero delay specified (SPBTARGET %p)", pRequest->SpbRequest, SpbTarget); status = STATUS_INVALID_PARAMETER; goto exit; } NT_ASSERT(pRequest->CurrentTransferDirection == SpbTransferDirectionToDevice); pRequest->CurrentTransferDirection = SpbTransferDirectionNone; // // fullduplex request actual transfer length .ie the amount of bytes that goes // over the wires is the max of write and read transfers supplied by SPB // pRequest->RequestLength = max( pRequest->CurrentTransferWriteLength, pRequest->CurrentTransferReadLength); } status = OnRequest(pDevice, pTarget, pRequest); exit: if (!NT_SUCCESS(status)) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Error configuring sequence, completing SPBREQUEST %p synchronously - %!STATUS!", pRequest->SpbRequest, status); SpbRequestComplete( pRequest->SpbRequest, status); } FuncExit(TRACE_FLAG_SPBDDI); } _Use_decl_annotations_ VOID OnOtherInCallerContext( WDFDEVICE SpbController, WDFREQUEST FxRequest ) /*++ Routine Description: This routine preprocesses custom IO requests before the framework places them in an IO queue. For requests using the SPB transfer list format, it calls SpbRequestCaptureIoOtherTransferList to capture the client's buffers. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbRequest - a handle to the SPBREQUEST object Return Value: None. The request is either completed or enqueued asynchronously. --*/ { FuncEntry(TRACE_FLAG_SPBDDI); NTSTATUS status = STATUS_SUCCESS; // // Check for custom IOCTLs that this driver handles. If // unrecognized mark as STATUS_NOT_SUPPORTED and complete. // WDF_REQUEST_PARAMETERS fxParams; WDF_REQUEST_PARAMETERS_INIT(&fxParams); WdfRequestGetParameters(FxRequest, &fxParams); if ((fxParams.Type != WdfRequestTypeDeviceControl) && (fxParams.Type != WdfRequestTypeDeviceControlInternal)) { status = STATUS_NOT_SUPPORTED; Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "FxRequest %p is of unsupported request type - %!STATUS!", FxRequest, status ); goto exit; } SpbIoctl controlCode; controlCode = (SpbIoctl) fxParams.Parameters.DeviceIoControl.IoControlCode; switch (controlCode) { case IOCTL_SPB_FULL_DUPLEX: break; default: status = STATUS_NOT_SUPPORTED; goto exit; } // // For custom IOCTLs that use the SPB transfer list format // (i.e. sequence formatting), call SpbRequestCaptureIoOtherTransferList // so that the driver can leverage other SPB DDIs for this request. // status = SpbRequestCaptureIoOtherTransferList((SPBREQUEST)FxRequest); if (!NT_SUCCESS(status)) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_SPBDDI, "Failed to capture transfer list for custom SpbRequest %p - %!STATUS!", FxRequest, status ); goto exit; } // // Preprocessing has succeeded, enqueue the request. // status = WdfDeviceEnqueueRequest(SpbController, FxRequest); if (!NT_SUCCESS(status)) { goto exit; } exit: if (!NT_SUCCESS(status)) { WdfRequestComplete(FxRequest, status); } FuncExit(TRACE_FLAG_SPBDDI); } _Use_decl_annotations_ VOID OnOther( WDFDEVICE SpbController, SPBTARGET SpbTarget, SPBREQUEST SpbRequest, size_t OutputBufferLength, size_t InputBufferLength, ULONG IoControlCode ) /*++ Routine Description: This routine processes custom IO requests that are not natively supported by the SPB framework extension. For requests using the SPB transfer list format, SpbRequestCaptureIoOtherTransferList must have been called in the driver's OnOtherInCallerContext routine. Arguments: SpbController - a handle to the framework device object representing an SPB controller SpbTarget - a handle to the SPBTARGET object SpbRequest - a handle to the SPBREQUEST object OutputBufferLength - the request's output buffer length InputBufferLength - the requests input buffer length IoControlCode - the device IO control code Return Value: None. The request is completed asynchronously. --*/ { FuncEntry(TRACE_FLAG_SPBDDI); NTSTATUS status = STATUS_SUCCESS; UNREFERENCED_PARAMETER(OutputBufferLength); UNREFERENCED_PARAMETER(InputBufferLength); if (IoControlCode == IOCTL_SPB_FULL_DUPLEX) { OnSequenceRequest( SpbController, SpbTarget, SpbRequest, 2 // FullDuplex is formatted as 1 write follwed by 1 read transfer ); } else { status = STATUS_NOT_SUPPORTED; } if (!NT_SUCCESS(status)) { SpbRequestComplete(SpbRequest, status); } FuncExit(TRACE_FLAG_SPBDDI); } ///////////////////////////////////////////////// // // PBC functions. // ///////////////////////////////////////////////// _Use_decl_annotations_ NTSTATUS PbcTargetGetSettings( PPBC_DEVICE pDevice, PVOID ConnectionParameters, PPBC_TARGET_SETTINGS pSettings ) /*++ Routine Description: This routine populates the target's settings. Arguments: pDevice - a pointer to the PBC device context ConnectionParameters - a pointer to a blob containing the connection parameters Settings - a pointer the the target's settings Return Value: Status --*/ { FuncEntry(TRACE_FLAG_PBCLOADING); UNREFERENCED_PARAMETER(pDevice); NT_ASSERT(ConnectionParameters != nullptr); NT_ASSERT(pSettings != nullptr); PRH_QUERY_CONNECTION_PROPERTIES_OUTPUT_BUFFER connection; PPNP_SERIAL_BUS_DESCRIPTOR descriptor; PPNP_SPI_SERIAL_BUS_DESCRIPTOR spiDescriptor; connection = (PRH_QUERY_CONNECTION_PROPERTIES_OUTPUT_BUFFER) ConnectionParameters; if (connection->PropertiesLength < sizeof(PNP_SPI_SERIAL_BUS_DESCRIPTOR)) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_PBCLOADING, "Invalid connection properties (length = %lu, expected = %Iu)", connection->PropertiesLength, sizeof(PNP_SPI_SERIAL_BUS_DESCRIPTOR)); return STATUS_INVALID_PARAMETER; } descriptor = (PPNP_SERIAL_BUS_DESCRIPTOR) connection->ConnectionProperties; if (descriptor->SerialBusType != SPI_SERIAL_BUS_TYPE) { Trace( TRACE_LEVEL_ERROR, TRACE_FLAG_PBCLOADING, "Bus type %c not supported, only SPI", descriptor->SerialBusType); return STATUS_INVALID_PARAMETER; } spiDescriptor = (PPNP_SPI_SERIAL_BUS_DESCRIPTOR) connection->ConnectionProperties; Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_PBCLOADING, "SPI Connection Descriptor %p ConnectionSpeed:%lu ", spiDescriptor, spiDescriptor->ConnectionSpeed ); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_PBCLOADING, " Phase:%u Polarity:%u DeviceSelection:0x%hx", spiDescriptor->Phase, spiDescriptor->Polarity, spiDescriptor->DeviceSelection ); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_PBCLOADING, " WireMode:%u wires DevicePolarity:%u ", (descriptor->TypeSpecificFlags & SPI_WIREMODE_BIT) ? 3 : 4, (descriptor->TypeSpecificFlags & SPI_DEVICEPOLARITY_BIT) ? 1 : 0 ); // Target settings for transaction pSettings->TypeSpecificFlags = descriptor->TypeSpecificFlags; pSettings->GeneralFlags = descriptor->GeneralFlags; pSettings->ConnectionSpeed = spiDescriptor->ConnectionSpeed; pSettings->DataBitLength = spiDescriptor->DataBitLength; pSettings->Phase = spiDescriptor->Phase; pSettings->Polarity = spiDescriptor->Polarity; pSettings->DeviceSelection = spiDescriptor->DeviceSelection; FuncExit(TRACE_FLAG_PBCLOADING); return STATUS_SUCCESS; } _Use_decl_annotations_ NTSTATUS PbcRequestSetNthTransferInfo( PPBC_REQUEST pRequest, ULONG TransferIndex ) /*++ Routine Description: This is a helper routine used to configure the request context and controller hardware for a transfer within a sequence. It validates parameters and retrieves the transfer buffer as necessary. Arguments: pRequest - a pointer to the PBC request context Index - index of the transfer within the sequence Return Value: STATUS --*/ { FuncEntry(TRACE_FLAG_TRANSFER); NT_ASSERT(pRequest != NULL); NTSTATUS status = STATUS_SUCCESS; // // Get transfer parameters for index. // SPB_TRANSFER_DESCRIPTOR descriptor; PMDL pMdl; SPB_TRANSFER_DESCRIPTOR_INIT(&descriptor); SpbRequestGetTransferParameters( pRequest->SpbRequest, TransferIndex, &descriptor, &pMdl); NT_ASSERT(pMdl != NULL); // // Configure request context. // pRequest->CurrentTransferInformation = 0; pRequest->CurrentTransferDirection = descriptor.Direction; pRequest->CurrentTransferDelayInUs = descriptor.DelayInUs; // // This method is called twice in preparation for the fullduplex // transfer in which both write and read transfer info is fetched. // For other types, this method is called once after each transfer // if (pRequest->Type != SpbRequestTypeOther) { pRequest->CurrentTransferReadLength = 0; pRequest->CurrentTransferWriteLength = 0; } if (pRequest->CurrentTransferDirection == SpbTransferDirectionFromDevice) { pRequest->pCurrentTransferReadMdlChain = pMdl; pRequest->CurrentTransferReadLength = descriptor.TransferLength; } else if (pRequest->CurrentTransferDirection == SpbTransferDirectionToDevice) { pRequest->pCurrentTransferWriteMdlChain = pMdl; pRequest->CurrentTransferWriteLength = descriptor.TransferLength; } else { NT_ASSERT(!"Transfer should either To or From device"); } // // Update sequence position if request is type sequence. // if (pRequest->Type == SpbRequestTypeSequence) { if (pRequest->TransferCount == 1) { pRequest->CurrentTransferSequencePosition = SpbRequestSequencePositionSingle; } else if (TransferIndex == 0) { pRequest->CurrentTransferSequencePosition = SpbRequestSequencePositionFirst; } else if (TransferIndex == (pRequest->TransferCount - 1)) { pRequest->CurrentTransferSequencePosition = SpbRequestSequencePositionLast; } else { pRequest->CurrentTransferSequencePosition = SpbRequestSequencePositionContinue; } } FuncExit(TRACE_FLAG_TRANSFER); return status; } _Use_decl_annotations_ NTSTATUS OnRequest( PPBC_DEVICE pDevice, PPBC_TARGET pTarget, PPBC_REQUEST pRequest ) { NTSTATUS status = STATUS_SUCCESS; WdfSpinLockAcquire(pDevice->Lock); // // Update device and target contexts. // if (pDevice->Locked) { NT_ASSERT(pDevice->pCurrentTarget == pTarget); } else { NT_ASSERT(pDevice->pCurrentTarget == NULL); pDevice->pCurrentTarget = pTarget; } NT_ASSERT(pTarget->pCurrentRequest == NULL); pTarget->pCurrentRequest = pRequest; (void)KeSetEvent( &pDevice->TransferThreadWakeEvt, 0, FALSE); WdfSpinLockRelease(pDevice->Lock); return status; } _Use_decl_annotations_ VOID OnRequestPollMode( PPBC_DEVICE pDevice ) { PPBC_REQUEST pRequest = pDevice->pCurrentTarget->pCurrentRequest; #if DBG ULONGLONG requestTimeNoDelayUs = ControllerEstimateRequestCompletionTimeUs(pDevice->pCurrentTarget, pRequest, false); ULONGLONG requestTimeWithDelayUs = ControllerEstimateRequestCompletionTimeUs(pDevice->pCurrentTarget, pRequest, true); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_TRANSFER, "Controller estimated request time to be %I64u us for %Iu bytes, with %I64u us spent in delays (SPBREQUEST %p, WDFDEVICE %p)", requestTimeWithDelayUs, pRequest->RequestLength, requestTimeWithDelayUs - requestTimeNoDelayUs, pRequest->SpbRequest, pDevice->FxDevice); #endif // // Configure controller HW if necessary and kick-off transfer // if (pRequest->CurrentTransferSequencePosition == SpbRequestSequencePositionSingle || pRequest->CurrentTransferSequencePosition == SpbRequestSequencePositionFirst) { ControllerConfigForTargetAndActivate(pDevice); } NTSTATUS status = STATUS_SUCCESS; bool bIsRequestComplete = false; // // Fulduplex request despite consisting of 2 transfers write followed // by read, we treat the request as 1 transfer in which write and read // transfers happen at the same time in fullduplex manner. // if (pRequest->Type == SpbRequestTypeOther) { status = ControllerDoOneTransferPollMode(pDevice, pRequest); bIsRequestComplete = ControllerCompleteTransfer(pDevice, pRequest, status); NT_ASSERT(bIsRequestComplete); } else { do { status = PbcRequestSetNthTransferInfo(pRequest, pRequest->CurrentTransferIndex); if (NT_SUCCESS(status)) { status = ControllerDoOneTransferPollMode(pDevice, pRequest); } bIsRequestComplete = ControllerCompleteTransfer(pDevice, pRequest, status); } while (!bIsRequestComplete); } } _Use_decl_annotations_ VOID TransferPollModeThread( PVOID StartContext ) { FuncEntry(TRACE_FLAG_TRANSFER); PPBC_DEVICE pDevice = GetDeviceContext((WDFDEVICE)StartContext); // // Set thread affinity mask to allow rescheduling the current thread // on any processor but CPU0. Purpose is to move polling to any thread // other than the system main thread on which interupts are being // handled to make polling smooth and uninterruptable as possible // NT_ASSERTMSG("IRQL unexpected", KeGetCurrentIrql() < DISPATCH_LEVEL); ULONG numCpus = KeQueryActiveProcessorCountEx(ALL_PROCESSOR_GROUPS); ULONG noCpu0AffinityMask = (~(ULONG(~0x0) << numCpus) & ULONG(~0x1)); KAFFINITY callerAffinity = KeSetSystemAffinityThreadEx(KAFFINITY(noCpu0AffinityMask)); NT_ASSERTMSG("Affinity not set as asked", KeGetCurrentProcessorNumberEx(NULL) != 0); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_TRANSFER, "Transfer poll mode thread started on processor %u. WDFDEVICE %p", KeGetCurrentProcessorNumberEx(NULL), pDevice->FxDevice); NTSTATUS status; for (;;) { // // Wait until waken up to either shutdown or // handle a request transfer // status = KeWaitForSingleObject( &pDevice->TransferThreadWakeEvt, Executive, KernelMode, FALSE, nullptr); NT_ASSERTMSG( "KeWaitForSingleObject non-success wake reason is not possible", status == STATUS_SUCCESS); if (InterlockedOr(&pDevice->TransferThreadShutdown, 0)) break; OnRequestPollMode(pDevice); } KeRevertToUserAffinityThreadEx(callerAffinity); Trace( TRACE_LEVEL_INFORMATION, TRACE_FLAG_TRANSFER, "Transfer poll mode thread shutting down. WDFDEVICE %p", pDevice->FxDevice); FuncExit(TRACE_FLAG_TRANSFER); }
24.761211
134
0.636211
[ "object" ]
a97d7a37987a367ffa704f43b3f3747add7c4e1c
16,129
cpp
C++
OrbitCore/OrbitProcess.cpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
null
null
null
OrbitCore/OrbitProcess.cpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
null
null
null
OrbitCore/OrbitProcess.cpp
ehei1/orbit
f990a7f9abb7d330e93d0d20018a62869890f04e
[ "BSD-2-Clause" ]
null
null
null
//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include "Core.h" #include "OrbitProcess.h" #include "OrbitModule.h" #include "SymbolUtils.h" #include "Pdb.h" #include "Path.h" #include "OrbitType.h" #include "OrbitSession.h" #include "OrbitThread.h" #include "Injection.h" #include "ScopeTimer.h" #include "Serialization.h" #include <tlhelp32.h> //----------------------------------------------------------------------------- Process::Process() : m_ID(0) , m_Handle(0) , m_Is64Bit(false) , m_CpuUsage(0) , m_DebugInfoLoaded(false) , m_IsRemote(false) , m_IsElevated(false) { } //----------------------------------------------------------------------------- Process::Process(DWORD a_ID) : m_ID(a_ID) , m_LastUserTime({0}) , m_LastKernTime({0}) , m_CpuUsage(0.f) , m_Is64Bit(false) , m_DebugInfoLoaded(false) , m_IsElevated(false) { Init(); } //----------------------------------------------------------------------------- Process::~Process() { if( m_DebugInfoLoaded ) { OrbitSymCleanup( m_Handle ); } } //----------------------------------------------------------------------------- void Process::Init() { m_Handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, m_ID); m_Is64Bit = ProcessUtils::Is64Bit(m_Handle); m_IsElevated = IsElevated( m_Handle ); m_UpdateCpuTimer.Start(); } //----------------------------------------------------------------------------- void Process::LoadDebugInfo() { if( !m_DebugInfoLoaded ) { if( m_Handle == nullptr ) { m_Handle = GetCurrentProcess(); } // Initialize dbghelp //SymInit(m_Handle); // Load module information /*wstring symbolPath = Path::GetDirectory(this->GetFullName()).c_str(); SymSetSearchPath(m_Handle, symbolPath.c_str());*/ // List threads //EnumerateThreads(); m_DebugInfoLoaded = true; } } //----------------------------------------------------------------------------- void Process::SetID( DWORD a_ID ) { m_ID = a_ID; Init(); } //----------------------------------------------------------------------------- void Process::ListModules() { SCOPE_TIMER_LOG( L"ListModules" ); ClearTransients(); SymUtils::ListModules( m_Handle, m_Modules ); for( auto & pair : m_Modules ) { shared_ptr<Module> & module = pair.second; std::wstring name = ToLower( module->m_Name ); m_NameToModuleMap[name] = module; module->LoadDebugInfo(); } } //----------------------------------------------------------------------------- void Process::ClearTransients() { m_Functions.clear(); m_Types.clear(); m_Globals.clear(); m_WatchedVariables.clear(); m_NameToModuleMap.clear(); } //----------------------------------------------------------------------------- void Process::EnumerateThreads() { m_Threads.clear(); m_ThreadIds.clear(); // https://blogs.msdn.microsoft.com/oldnewthing/20060223-14/?p=32173/ HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, m_ID); if (h != INVALID_HANDLE_VALUE) { THREADENTRY32 te; te.dwSize = sizeof(te); if (Thread32First(h, &te)) { do { if (te.dwSize >= FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(te.th32OwnerProcessID)) { HANDLE thandle; { thandle = OpenThread(THREAD_ALL_ACCESS, FALSE, te.th32ThreadID); } if (thandle == NULL) { //ORBIT_LOG(GetLastErrorAsString()); continue; } if (te.th32OwnerProcessID == m_ID) { std::shared_ptr<Thread> thread = std::make_shared<Thread>(); thread->m_Handle = thandle; thread->m_TID = te.th32ThreadID; m_Threads.push_back( thread ); } } te.dwSize = sizeof(te); } while (Thread32Next(h, &te)); } CloseHandle(h); } for (std::shared_ptr<Thread> & thread : m_Threads) { m_ThreadIds.insert(thread->m_TID); } } //----------------------------------------------------------------------------- void Process::UpdateCpuTime() { FILETIME creationTime; FILETIME exitTime; FILETIME kernTime; FILETIME userTime; double elapsedMillis = m_UpdateCpuTimer.QueryMillis(); m_UpdateCpuTimer.Start(); if( GetProcessTimes( m_Handle, &creationTime, &exitTime, &kernTime, &userTime ) ) { unsigned numCores = std::thread::hardware_concurrency(); LONGLONG kernMs = FileTimeDiffInMillis( m_LastKernTime, kernTime ); LONGLONG userMs = FileTimeDiffInMillis( m_LastUserTime, userTime ); m_LastKernTime = kernTime; m_LastUserTime = userTime; m_CpuUsage = ( 100.0 * double( kernMs + userMs ) / elapsedMillis ) / numCores; } } //----------------------------------------------------------------------------- void Process::UpdateThreadUsage() { for( auto & thread : m_Threads ) { thread->UpdateUsage(); } } //----------------------------------------------------------------------------- void Process::SortThreadsByUsage() { std::sort( m_Threads.begin() , m_Threads.end() , [](std::shared_ptr<Thread> & a_T0, std::shared_ptr<Thread> & a_T1) { return a_T1->m_Usage.Latest() < a_T0->m_Usage.Latest(); } ); } //----------------------------------------------------------------------------- void Process::SortThreadsById() { std::sort( m_Threads.begin() , m_Threads.end() , [](std::shared_ptr<Thread> & a_T1, std::shared_ptr<Thread> & a_T0) { return a_T1->m_TID < a_T0->m_TID; } ); } //----------------------------------------------------------------------------- std::shared_ptr<Module> Process::FindModule( const std::wstring & a_ModuleName ) { std::wstring moduleName = ToLower( Path::GetFileNameNoExt( a_ModuleName ) ); for( auto & it : m_Modules ) { std::shared_ptr<Module> & module = it.second; if( ToLower( Path::GetFileNameNoExt( module->m_Name ) ) == moduleName ) { return module; } } return nullptr; } //----------------------------------------------------------------------------- Function* Process::GetFunctionFromAddress( DWORD64 a_Address, bool a_IsExact ) { DWORD64 address = (DWORD64)a_Address; auto & it = m_Modules.upper_bound( address ); if( !m_Modules.empty() && it != m_Modules.begin() ) { --it; std::shared_ptr<Module> & module = it->second; if( address < module->m_AddressEnd ) { if( module->m_Pdb != nullptr ) { if( a_IsExact ) { return module->m_Pdb->GetFunctionFromExactAddress( a_Address ); } else { return module->m_Pdb->GetFunctionFromProgramCounter( a_Address ); } } } } return nullptr; } //----------------------------------------------------------------------------- shared_ptr<Module> Process::GetModuleFromAddress( DWORD64 a_Address ) { DWORD64 address = (DWORD64)a_Address; auto & it = m_Modules.upper_bound(address); if (!m_Modules.empty() && it != m_Modules.begin()) { --it; std::shared_ptr<Module> module = it->second; return module; } return nullptr; } //----------------------------------------------------------------------------- std::shared_ptr<OrbitDiaSymbol> Process::SymbolFromAddress( DWORD64 a_Address ) { shared_ptr<Module> module = GetModuleFromAddress( a_Address ); if( module && module->m_Pdb ) { return module->m_Pdb->SymbolFromAddress( a_Address ); } return make_shared<OrbitDiaSymbol>(); } //----------------------------------------------------------------------------- bool Process::LineInfoFromAddress( DWORD64 a_Address, LineInfo & o_LineInfo ) { shared_ptr<Module> module = GetModuleFromAddress( a_Address ); if( module && module->m_Pdb ) { return module->m_Pdb->LineInfoFromAddress( a_Address, o_LineInfo ); } return false; } //----------------------------------------------------------------------------- void Process::LoadSession( const Session & a_Session ) { } //----------------------------------------------------------------------------- void Process::SaveSession() { } //----------------------------------------------------------------------------- void Process::RefreshWatchedVariables() { for( std::shared_ptr<Variable> var : m_WatchedVariables ) { var->SyncValue(); } } //----------------------------------------------------------------------------- void Process::ClearWatchedVariables() { m_WatchedVariables.clear(); } //----------------------------------------------------------------------------- void Process::AddType(Type & a_Type) { bool isPtr = a_Type.m_Name.find(L"Pointer to") != std::string::npos; if (!isPtr) { unsigned long long typeHash = a_Type.Hash(); auto it = m_UniqueTypeHash.insert(typeHash); if (it.second == true) { m_Types.push_back(&a_Type); } } } //----------------------------------------------------------------------------- void Process::AddModule( shared_ptr<Module> & a_Module ) { m_Modules[a_Module->m_AddressStart] = a_Module; } //----------------------------------------------------------------------------- void Process::FindPdbs( const std::vector< std::wstring > & a_SearchLocations ) { std::unordered_map< std::wstring, std::vector<std::wstring> > nameToPaths; // Populate list of all available pdb files for( const std::wstring & dir : a_SearchLocations ) { std::vector< std::wstring > pdbFiles = Path::ListFiles( dir, L".pdb" ); for( const std::wstring & pdb : pdbFiles ) { wstring pdbLower = Path::GetFileName( ToLower( pdb ) ); nameToPaths[pdbLower].push_back( pdb ); } } // Find matching pdb for( auto & modulePair : m_Modules ) { std::shared_ptr<Module> module = modulePair.second; if( !module->m_FoundPdb ) { std::wstring moduleName = ToLower( module->m_Name ); std::wstring pdbName = Path::StripExtension( moduleName ) + L".pdb"; const std::vector< std::wstring > & pdbs = nameToPaths[pdbName]; for( const wstring & pdb : pdbs ) { module->m_PdbName = pdb; module->m_FoundPdb = true; module->LoadDebugInfo(); std::wstring signature = s2ws( GuidToString( module->m_Pdb->GetGuid() ) ); if( Contains( module->m_DebugSignature, signature ) ) { // Found matching pdb module->m_PdbSize = ::tr2::sys::file_size( module->m_PdbName ); break; } else { module->m_FoundPdb = false; } } } } } //----------------------------------------------------------------------------- bool Process::IsElevated( HANDLE a_Process ) { bool fRet = false; HANDLE hToken = NULL; if( OpenProcessToken( a_Process, TOKEN_QUERY, &hToken ) ) { TOKEN_ELEVATION Elevation; DWORD cbSize = sizeof( TOKEN_ELEVATION ); if( GetTokenInformation( hToken, TokenElevation, &Elevation, sizeof( Elevation ), &cbSize ) ) { fRet = Elevation.TokenIsElevated != 0; } } if( hToken ) { CloseHandle( hToken ); } return fRet; } //----------------------------------------------------------------------------- bool Process::SetPrivilege( LPCTSTR a_Name, bool a_Enable ) { HANDLE hToken; if( !OpenProcessToken( GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken ) ) { ORBIT_ERROR; PRINT_VAR( GetLastErrorAsString() ); } TOKEN_PRIVILEGES tp; LUID luid; if( !LookupPrivilegeValue(NULL, a_Name, &luid ) ) { ORBIT_ERROR; PRINT( "LookupPrivilegeValue error: " ); PRINT_VAR( GetLastErrorAsString() ); return false; } tp.PrivilegeCount = 1; tp.Privileges[0].Luid = luid; tp.Privileges[0].Attributes = a_Enable ? SE_PRIVILEGE_ENABLED : 0; if( !AdjustTokenPrivileges( hToken, FALSE, &tp, sizeof( TOKEN_PRIVILEGES ), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL ) ) { ORBIT_ERROR; PRINT( "AdjustTokenPrivileges error: " ); PRINT_VAR( GetLastErrorAsString() ); return false; } if( GetLastError() == ERROR_NOT_ALL_ASSIGNED ) { PRINT( "The token does not have the specified privilege. \n" ); return false; } return true; } //----------------------------------------------------------------------------- DWORD64 Process::GetOutputDebugStringAddress() { auto it = m_NameToModuleMap.find( L"kernelbase.dll" ); if( it != m_NameToModuleMap.end() ) { shared_ptr<Module> module = it->second; auto remoteAddr = Injection::GetRemoteProcAddress( GetHandle(), module->m_ModuleHandle, "OutputDebugStringA" ); return (DWORD64)remoteAddr; } return 0; } //----------------------------------------------------------------------------- DWORD64 Process::GetRaiseExceptionAddress() { auto it = m_NameToModuleMap.find( L"kernelbase.dll" ); if (it != m_NameToModuleMap.end()) { shared_ptr<Module> module = it->second; auto remoteAddr = Injection::GetRemoteProcAddress(GetHandle(), module->m_ModuleHandle, "RaiseException"); return (DWORD64)remoteAddr; } return 0; } //----------------------------------------------------------------------------- void Process::FindCoreFunctions() { return; SCOPE_TIMER_LOG(L"FindCoreFunctions"); const auto prio = oqpi::task_priority::normal; auto numWorkers = oqpi_tk::scheduler().workersCount( prio ); //int numWorkers = oqpi::thread::hardware_concurrency(); oqpi_tk::parallel_for( "FindAllocFreeFunctions", (int32_t)m_Functions.size(), [&]( int32_t a_BlockIndex, int32_t a_ElementIndex ) { Function* func = m_Functions[a_ElementIndex]; const std::wstring & name = func->Lower(); if( Contains( name, L"operator new" ) || Contains( name, L"FMallocBinned::Malloc" ) ) { func->Select(); func->m_OrbitType = Function::ALLOC; } else if( Contains( name, L"operator delete" ) || name == L"FMallocBinned::Free" ) { func->Select(); func->m_OrbitType = Function::FREE; } else if( Contains( name, L"realloc" ) ) { func->Select(); func->m_OrbitType = Function::REALLOC; } } ); } //----------------------------------------------------------------------------- ORBIT_SERIALIZE( Process, 0 ) { ORBIT_NVP_VAL( 0, m_Name ); ORBIT_NVP_VAL( 0, m_FullName ); ORBIT_NVP_VAL( 0, m_ID ); ORBIT_NVP_VAL( 0, m_IsElevated ); ORBIT_NVP_VAL( 0, m_CpuUsage ); ORBIT_NVP_VAL( 0, m_Is64Bit ); ORBIT_NVP_VAL( 0, m_DebugInfoLoaded ); ORBIT_NVP_VAL( 0, m_IsRemote ); ORBIT_NVP_VAL( 0, m_Modules ); ORBIT_NVP_VAL( 0, m_NameToModuleMap ); ORBIT_NVP_VAL( 0, m_ThreadIds ); }
29.594495
133
0.483911
[ "vector" ]
a9800c3f52ec187dbae1387dbb2fde39b9c95ec0
1,129
cpp
C++
python_bindings/src/PyStage.cpp
benoitsteiner/Halide
9cbab04189ebb5fb264b9defcc812144ad934a3f
[ "Apache-2.0" ]
null
null
null
python_bindings/src/PyStage.cpp
benoitsteiner/Halide
9cbab04189ebb5fb264b9defcc812144ad934a3f
[ "Apache-2.0" ]
null
null
null
python_bindings/src/PyStage.cpp
benoitsteiner/Halide
9cbab04189ebb5fb264b9defcc812144ad934a3f
[ "Apache-2.0" ]
3
2020-03-27T02:05:13.000Z
2021-01-06T03:05:29.000Z
#include "PyStage.h" #include "PyScheduleMethods.h" namespace Halide { namespace PythonBindings { void define_stage(py::module &m) { auto stage_class = py::class_<Stage>(m, "Stage") .def("dump_argument_list", &Stage::dump_argument_list) .def("name", &Stage::name) .def("rfactor", (Func(Stage::*)(std::vector<std::pair<RVar, Var>>)) & Stage::rfactor, py::arg("preserved")) .def("rfactor", (Func(Stage::*)(RVar, Var)) & Stage::rfactor, py::arg("r"), py::arg("v")) // These two variants of compute_with are specific to Stage .def("compute_with", (Stage & (Stage::*)(LoopLevel, const std::vector<std::pair<VarOrRVar, LoopAlignStrategy>> &)) & Stage::compute_with, py::arg("loop_level"), py::arg("align")) .def("compute_with", (Stage & (Stage::*)(LoopLevel, LoopAlignStrategy)) & Stage::compute_with, py::arg("loop_level"), py::arg("align") = LoopAlignStrategy::Auto); add_schedule_methods(stage_class); } } // namespace PythonBindings } // namespace Halide
38.931034
149
0.59256
[ "vector" ]
a98242a4b7b3356d36616c054bf17b5dce319f58
1,661
hpp
C++
include/commonroad/types.hpp
arminstr/commonroad_objects_ros
7fbc3f27801bc7803bb4932fa247a348d2b14a83
[ "MIT" ]
1
2021-06-02T15:39:03.000Z
2021-06-02T15:39:03.000Z
include/commonroad/types.hpp
arminstr/commonroad_objects_ros
7fbc3f27801bc7803bb4932fa247a348d2b14a83
[ "MIT" ]
null
null
null
include/commonroad/types.hpp
arminstr/commonroad_objects_ros
7fbc3f27801bc7803bb4932fa247a348d2b14a83
[ "MIT" ]
null
null
null
#pragma once #include <cmath> #include <limits> #include <memory> #include <string> #include <unordered_map> #include <vector> namespace commonroad { enum class ObstacleRole : unsigned int { DYNAMIC, STATIC }; enum class ObstacleType : unsigned int { CAR, TRAM }; enum class ObstacleGeometry : unsigned int { RECTANGLE, CIRCLE }; struct Orientation { double exact; }; struct Time { int exact; }; struct Velocity { double exact; }; struct Acceleration { double exact; }; struct YawRate { double exact; }; struct SlipAngle { double exact; }; struct Point { double x; double y; }; struct Position { Point point; }; struct ObstacleShape { ObstacleGeometry geometry; double length; double width; }; struct ObstacleState { Position position; Orientation orientation; Time time; Velocity velocity; Acceleration acceleration; }; struct ObstacleInitialState : public ObstacleState{}; struct ProblemInitialState { Position position; Orientation orientation; Time time; Velocity velocity; YawRate yawRate; SlipAngle slipAngle; }; struct GoalPosition { int laneletRef; }; struct GoalTime { int intervalStart; int intervalEnd; }; struct GoalState { GoalPosition position; GoalTime time; }; struct ObstacleInformation { int id; ObstacleRole role; ObstacleType type; ObstacleShape shape; ObstacleInitialState initialState; std::vector<ObstacleState> trajectory; }; struct PlanningProblem { int id; ProblemInitialState initialState; GoalState goalState; }; struct CommonRoadData { std::vector<ObstacleInformation> obstacles; PlanningProblem planningProblem; }; }
11.864286
53
0.728477
[ "geometry", "shape", "vector" ]
a98707125842d7f6c7dafdebca110634a0772754
13,953
cpp
C++
inference_helper/inference_helper_snpe.cpp
Rexiome/InferenceHelper
7c975cf9d32016aa6bfceabf6922fe6d808dc5eb
[ "Apache-2.0" ]
119
2020-12-27T14:25:19.000Z
2022-03-30T09:52:34.000Z
inference_helper/inference_helper_snpe.cpp
yang0000qi/InferenceHelper
c5763bba9bc71ab1d0d70df6240ed66635dc2159
[ "Apache-2.0" ]
21
2020-12-27T10:22:01.000Z
2022-03-20T10:47:10.000Z
inference_helper/inference_helper_snpe.cpp
yang0000qi/InferenceHelper
c5763bba9bc71ab1d0d70df6240ed66635dc2159
[ "Apache-2.0" ]
19
2020-12-27T20:54:02.000Z
2022-03-22T09:00:57.000Z
/* Copyright 2021 iwatake2222 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 ***/ /* for general */ #include <cstdint> #include <cstdlib> #include <cmath> #include <cstring> #include <string> #include <vector> #include <array> #include <algorithm> #include <chrono> #include <unordered_map> /* for SNPE lib */ #include "SNPE/SNPE.hpp" #include "SNPE/SNPEFactory.hpp" #include "SNPE/SNPEBuilder.hpp" #include "DlSystem/DlError.hpp" #include "DlSystem/RuntimeList.hpp" #include "DlSystem/UserBufferMap.hpp" #include "DlSystem/UDLFunc.hpp" #include "DlSystem/IUserBuffer.hpp" #include "DlContainer/IDlContainer.hpp" #include "DiagLog/IDiagLog.hpp" #include "DlSystem/ITensor.hpp" #include "DlSystem/StringList.hpp" #include "DlSystem/TensorMap.hpp" #include "DlSystem/TensorShape.hpp" #include "DlSystem/IUserBufferFactory.hpp" /* for SNPE helper func */ #include "udlExample.hpp" #include "CreateUserBuffer.hpp" /* for My modules */ #include "inference_helper_log.h" #include "inference_helper_snpe.h" /*** Macro ***/ #define TAG "InferenceHelperSnpe" #define PRINT(...) INFERENCE_HELPER_LOG_PRINT(TAG, __VA_ARGS__) #define PRINT_E(...) INFERENCE_HELPER_LOG_PRINT_E(TAG, __VA_ARGS__) /*** Function ***/ InferenceHelperSnpe::InferenceHelperSnpe() { num_threads_ = 1; input_map_.reset(new zdl::DlSystem::UserBufferMap()); output_map_.reset(new zdl::DlSystem::UserBufferMap()); } InferenceHelperSnpe::~InferenceHelperSnpe() { } int32_t InferenceHelperSnpe::SetNumThreads(const int32_t num_threads) { num_threads_ = num_threads; return kRetOk; } int32_t InferenceHelperSnpe::SetCustomOps(const std::vector<std::pair<const char*, const void*>>& custom_ops) { PRINT("[WARNING] This method is not supported\n"); return kRetOk; } int32_t InferenceHelperSnpe::Initialize(const std::string& model_filename, std::vector<InputTensorInfo>& input_tensor_info_list, std::vector<OutputTensorInfo>& output_tensor_info_list) { /* Settings for SNPE */ int32_t user_buffer_source_type = CPUBUFFER; int32_t buffer_type = USERBUFFER_FLOAT; int32_t bit_width = 0; switch (input_tensor_info_list[0].tensor_type) { case InputTensorInfo::kTensorTypeFp32: buffer_type = USERBUFFER_FLOAT; break; case InputTensorInfo::kTensorTypeUint8: buffer_type = USERBUFFER_TF8; bit_width = 8; break; default: PRINT_E("Unsupported tensor type\n"); return kRetErr; } bool use_user_supplied_buffers = (buffer_type == USERBUFFER_FLOAT || buffer_type == USERBUFFER_TF8 || buffer_type == USERBUFFER_TF16); /* Create network */ snpe_ = CreateSnpe(model_filename, use_user_supplied_buffers); if (!snpe_) { PRINT_E("Failed to create SNPE\n"); return kRetErr; } GetAllTensorInfo(snpe_, input_tensor_info_list, output_tensor_info_list); /* Allocate buffer memory for input/output */ if (use_user_supplied_buffers) { if (buffer_type == USERBUFFER_TF8 || buffer_type == USERBUFFER_TF16) { PRINT_E("Not tested\n"); createOutputBufferMap(*output_map_, application_output_buffers_, snpe_user_output_buffers_, snpe_, true, bit_width); createInputBufferMap(*input_map_, application_input_buffers_, snpe_user_input_buffers_, snpe_, true, bit_width); } else if (buffer_type == USERBUFFER_FLOAT) { createOutputBufferMap(*output_map_, application_output_buffers_, snpe_user_output_buffers_, snpe_, false, bit_width); if (user_buffer_source_type == CPUBUFFER) { createInputBufferMap(*input_map_, application_input_buffers_, snpe_user_input_buffers_, snpe_, false, bit_width); } else { PRINT_E("Not supported\n"); return kRetErr; } } } else { PRINT_E("Not supported\n"); return kRetErr; } /* Convert normalize parameter to speed up */ for (auto& input_tensor_info : input_tensor_info_list) { ConvertNormalizeParameters(input_tensor_info); } return kRetOk; }; int32_t InferenceHelperSnpe::Finalize(void) { return kRetErr; } int32_t InferenceHelperSnpe::PreProcess(const std::vector<InputTensorInfo>& input_tensor_info_list) { if (!snpe_ || !input_map_ || !output_map_) { PRINT_E("Interpreter is not built yet\n"); return kRetErr; } for (const auto& input_tensor_info : input_tensor_info_list) { const int32_t img_width = input_tensor_info.GetWidth(); const int32_t img_height = input_tensor_info.GetHeight(); const int32_t img_channel = input_tensor_info.GetChannel(); if (input_tensor_info.data_type == InputTensorInfo::kDataTypeImage) { if ((input_tensor_info.image_info.width != input_tensor_info.image_info.crop_width) || (input_tensor_info.image_info.height != input_tensor_info.image_info.crop_height)) { PRINT_E("Crop is not supported\n"); return kRetErr; } if ((input_tensor_info.image_info.crop_width != img_width) || (input_tensor_info.image_info.crop_height != img_height)) { PRINT_E("Resize is not supported\n"); return kRetErr; } if (input_tensor_info.image_info.channel != img_channel) { PRINT_E("Color conversion is not supported\n"); return kRetErr; } /* Normalize image (NHWC to NHWC)*/ uint8_t* src = static_cast<uint8_t*>(input_tensor_info.data); if (input_tensor_info.tensor_type == TensorInfo::kTensorTypeUint8) { PRINT_E("kTensorTypeUint8 is not supported\n"); } else if (input_tensor_info.tensor_type == TensorInfo::kTensorTypeFp32) { float* dst = reinterpret_cast<float*> (&application_input_buffers_.at(input_tensor_info.name)[0]); #pragma omp parallel for num_threads(num_threads_) for (int32_t i = 0; i < img_width * img_height; i++) { for (int32_t c = 0; c < img_channel; c++) { #if 1 dst[i * img_channel + c] = (src[i * img_channel + c] - input_tensor_info.normalize.mean[c]) * input_tensor_info.normalize.norm[c]; #else dst[i * img_channel + c] = (src[i * img_channel + c] / 255.0f - input_tensor_info.normalize.mean[c]) / input_tensor_info.normalize.norm[c]; #endif } } } else { PRINT_E("Unsupported tensor_type (%d)\n", input_tensor_info.tensor_type); return kRetErr; } } else if ( (input_tensor_info.data_type == InputTensorInfo::kDataTypeBlobNhwc) || (input_tensor_info.data_type == InputTensorInfo::kDataTypeBlobNchw) ){ PRINT_E("kDataTypeBlobNhwc (kDataTypeBlobNchw) is not supported\n"); return kRetErr; } else { PRINT_E("Unsupported data type (%d)\n", input_tensor_info.data_type); return kRetErr; } } return kRetOk; } int32_t InferenceHelperSnpe::Process(std::vector<OutputTensorInfo>& output_tensor_info_list) { if (!snpe_ || !input_map_ || !output_map_) { PRINT_E("Interpreter is not built yet\n"); return kRetErr; } bool exec_status = snpe_->execute(*input_map_, *output_map_); if (exec_status == false) { PRINT_E("Error while executing the network.\n"); return kRetErr; } for (auto& output_tensor_info : output_tensor_info_list) { output_tensor_info.data = application_output_buffers_.at(output_tensor_info.name).data(); } return kRetOk; } static zdl::DlSystem::RuntimeList GetSystemAvailability(void) { zdl::DlSystem::Version_t version = zdl::SNPE::SNPEFactory::getLibraryVersion(); PRINT("SNPE Version: %s\n", version.asString().c_str()); zdl::DlSystem::RuntimeList runtime_list; zdl::DlSystem::Runtime_t runtime = zdl::DlSystem::Runtime_t::DSP_FIXED8_TF; if (zdl::SNPE::SNPEFactory::isRuntimeAvailable(runtime) == false) { PRINT_E("DSP is not available. Falling back to GPU.\n"); runtime = zdl::DlSystem::Runtime_t::GPU_FLOAT32_16_HYBRID; if (zdl::SNPE::SNPEFactory::isRuntimeAvailable(runtime) == false) { PRINT_E("GPU is not available. Falling back to CPU.\n"); runtime = zdl::DlSystem::Runtime_t::CPU_FLOAT32; } } runtime_list.add(runtime); return runtime_list; } std::unique_ptr<zdl::SNPE::SNPE> InferenceHelperSnpe::CreateSnpe(const std::string& model_filename, bool use_user_supplied_buffers) { zdl::DlSystem::RuntimeList runtime_list = GetSystemAvailability(); std::unique_ptr<zdl::DlContainer::IDlContainer> container = zdl::DlContainer::IDlContainer::open(zdl::DlSystem::String(model_filename.c_str())); if (container == nullptr) { PRINT_E("Error while opening the container file.\n"); return nullptr; } zdl::DlSystem::UDLFactoryFunc udl_func = UdlExample::MyUDLFactory; zdl::DlSystem::UDLBundle udl_bundle; udl_bundle.cookie = (void*)0xdeadbeaf, udl_bundle.func = udl_func; // 0xdeadbeaf to test cookie zdl::DlSystem::PlatformConfig platform_config; zdl::SNPE::SNPEBuilder snpe_builder(container.get()); std::unique_ptr<zdl::SNPE::SNPE> snpe = snpe_builder.setOutputLayers({}) .setRuntimeProcessorOrder(runtime_list) .setUdlBundle(udl_bundle) .setUseUserSuppliedBuffers(use_user_supplied_buffers) .setPlatformConfig(platform_config) .setInitCacheMode(false) .build(); if (snpe == nullptr) { PRINT_E("Error while building SNPE object.\n"); return nullptr; } auto logger_opt = snpe->getDiagLogInterface(); if (!logger_opt) { PRINT_E("SNPE failed to obtain logging interface.\n"); } auto logger = *logger_opt; auto opts = logger->getOptions(); opts.LogFileDirectory = model_filename + "_log/"; if(!logger->setOptions(opts)) { PRINT_E("Failed to set options\n"); return nullptr; } if (!logger->start()) { PRINT_E("Failed to start logger\n"); return nullptr; } return snpe; } int32_t InferenceHelperSnpe::GetTensorInfo(std::unique_ptr<zdl::SNPE::SNPE> const& snpe, const std::string& name, std::vector<int32_t>& dims) { auto buffer_attributes_opt = snpe->getInputOutputBufferAttributes(name.c_str()); if (!buffer_attributes_opt) { PRINT_E("Error obtaining attributes for input tensor. %s\n", name.c_str()); return kRetErr; } zdl::DlSystem::TensorShape tensor_shape = buffer_attributes_opt->getDims(); dims.clear(); for (int32_t d = 0; d < tensor_shape.rank(); d++) { dims.push_back(static_cast<int32_t>(tensor_shape.getDimensions()[d])); } return kRetOk; } int32_t InferenceHelperSnpe::GetAllTensorInfo(std::unique_ptr<zdl::SNPE::SNPE> const& snpe, std::vector<InputTensorInfo>& input_tensor_info_list, std::vector<OutputTensorInfo>& output_tensor_info_list) { for (auto& input_tensor_info : input_tensor_info_list) { std::vector<int32_t> dims; if (GetTensorInfo(snpe, input_tensor_info.name, dims) != 0) { return kRetErr; } if (dims.size() == 0 && input_tensor_info.tensor_dims.size() == 0) { PRINT_E("Tensor is undefined\n"); return kRetErr; } else if (dims.size() == 0 && input_tensor_info.tensor_dims.size() > 0) { // do nothing } else if (dims.size() > 0 && input_tensor_info.tensor_dims.size() == 0) { input_tensor_info.tensor_dims = dims; } else { for (int32_t d = 0; d < dims.size(); d++) { if (dims[d] != input_tensor_info.tensor_dims[d]) { PRINT_E("%s: Dim size doesn't match: %d vs %d\n", input_tensor_info.name.c_str(), dims[d], input_tensor_info.tensor_dims[d]); return kRetErr; } } } } for (auto& output_tensor_info : output_tensor_info_list) { std::vector<int32_t> dims; if (GetTensorInfo(snpe, output_tensor_info.name, dims) != 0) { return kRetErr; } if (dims.size() == 0 && output_tensor_info.tensor_dims.size() == 0) { PRINT_E("Tensor is undefined\n"); return kRetErr; } else if (dims.size() == 0 && output_tensor_info.tensor_dims.size() > 0) { // do nothing } else if (dims.size() > 0 && output_tensor_info.tensor_dims.size() == 0) { output_tensor_info.tensor_dims = dims; } else { for (int32_t d = 0; d < dims.size(); d++) { if (dims[d] != output_tensor_info.tensor_dims[d]) { PRINT_E("%s: Dim size doesn't match: %d vs %d\n", output_tensor_info.name.c_str(), dims[d], output_tensor_info.tensor_dims[d]); return kRetErr; } } } } return kRetOk; }
39.304225
202
0.638859
[ "object", "vector" ]
a987cddac29b6e3402c8cd56f2e6bf8b97352ff3
28,688
cc
C++
src/cxx/mr/libmr2d/MR_CDecomp.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
src/cxx/mr/libmr2d/MR_CDecomp.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
src/cxx/mr/libmr2d/MR_CDecomp.cc
sfarrens/cosmostat
a475315cda06dca346095a1e83cb6ad23979acae
[ "MIT" ]
null
null
null
// pyramidal median transform with integer // #include "NR.h" #include "IM_Obj.h" #include "IM_Math.h" #include "IM_IO.h" #include "IM_BIO.h" #include "MR_Obj.h" #include "IM_CompTool.h" #include "IM_Noise.h" #include "MR_Noise.h" #include "MR_Comp.h" #include "IM_Lut.h" #include "IM_Comp.h" extern float PasCodeur; /* CCD gain */ extern float SigmaGauss; /* CCD read-out noise standard deviation */ extern float MeanGauss; /* CCD read-out noise mean */ extern float BadPixalVal; extern Bool BadPixel; Bool InputFromStdin = False; static Iint ImagInt; static IOInfoData InfoData; /***************************************************/ // Decompression part /***************************************************/ void MR_CompData::read_tinfo() { extern softinfo Soft; short ValIdent[3]; fread(ValIdent, sizeof(short), 3, InFile); // cout << "V1 = " << ValIdent[0] << endl; // cout << "V2 = " << ValIdent[1] << endl; // cout << "V3 = " << ValIdent[2] << endl; float SoftVersion; SoftVersion = readfloat (InFile); if (SoftVersion > Soft.release()) { cerr << "Warning: the image has been compressed with a more recent version " << endl; cerr << " than the decompression program version. " << endl; cerr << " You should update the decompression program." << endl; } Comp_Method = (type_comp) readint (InFile); switch (Comp_Method) { case COMP_HAAR: Transform = TO_HAAR; break; case COMP_MALLAT: Transform = TO_MALLAT; if (SoftVersion > 2) { type_sb_filter TF; sb_type_norm TN; TF = (type_sb_filter) readint(InFile); TN = (sb_type_norm) readint(InFile); if (readint(InFile) == 1) UseLiftingInsteadOfFilter = True; else UseLiftingInsteadOfFilter = False; if (readint(InFile) == 1) UnifQuant = True; else UnifQuant = False; } break; case COMP_FEAUVEAU: Transform = TO_FEAUVEAU;break; case COMP_MIN_MAX: Transform = TM_MIN_MAX; break; case COMP_MRMEDIAN: Transform = TM_PYR_MEDIAN; break; case COMP_WT_PMT: Transform = TM_TO_PYR; break; case COMP_O_MRMEDIAN: Transform = TM_PYR_MEDIAN; break; case COMP_O_MIN_MAX: Transform = TM_MIN_MAX;break; case COMP_O_MORPHO: case COMP_MORPHO: break; case COMP_INT_LIFTING: LiftingTrans = (type_lift) readint (InFile); Transform = TO_LIFTING; break; default: break; } Nbr_Plan = readint (InFile); if (SoftVersion > 1.) { L_Nl = readint (InFile); L_Nc = readint (InFile); KeepResi = readint (InFile); } if (Resol >= Nbr_Plan) Resol = Nbr_Plan-1; IntTrans = work_with_int(Comp_Method); NoiseThresholding = noise_threshold(Comp_Method); FormatInput = (type_format) readint (InFile); // test for compatibility software version if (SoftVersion > 1.) { int NCol = readint (InFile); if (NCol > 0) { cbyte *r = new cbyte[NCol]; cbyte *g = new cbyte[NCol]; cbyte *b = new cbyte[NCol]; fread(r, 1, NCol, InFile); fread(g, 1, NCol, InFile); fread(b, 1, NCol, InFile); IO_RGB.alloc(NCol,r,g,b); } } NbrImag = readint (InFile); if (NbrImag > 1) { cout << "Error: multichannel data cannot be decompressed by this program ... " << endl; exit(-1); } TypeQuant = (type_quant) readint (InFile); TypeCoder = (type_coding) readint (InFile); Stat_Noise = (type_noise) readint (InFile); if (Stat_Noise == NOISE_POISSON) { PasCodeur = readfloat(InFile); SigmaGauss = readfloat(InFile); MeanGauss = readfloat(InFile); } if (readint (InFile) == 1) { UseBlock = True; // NbrImag = readint (InFile); NbrBlock = readint (InFile); BlockSize = readint (InFile); BlockOverlap= readint (InFile); } if (readint (InFile) == 1) { BadPixel = True; BadPixalVal = readfloat (InFile); MinDat = readfloat (InFile); MaxDat = readfloat (InFile); } if (Verbose == True) { cerr << endl; cerr << Soft.banner() << endl; cerr << StringComp(Comp_Method) << endl << endl; cerr << "Input File = " << File_Name_Transform << endl; cerr << "Output File = " << File_Name_Imag << endl; if (NbrBlock > 1) cerr << "Number of blocks = " << NbrBlock << endl; if (NbrBlock > 1) cerr << "block size = " << BlockSize << endl; if (NbrBlock > 1) cerr << "block overlapping = " << BlockOverlap<< endl; if (Resol >= 0) cerr << "Resolution = " << Resol << endl; if (BadPixel == True) { cerr << "MinDat = " << MinDat << endl; cerr << "MaxDat = " << MaxDat << endl; } } } /*****************************************************************/ void MR_CompData::header_resol() { if (Resol > 0) { for (int k = 0; k < Resol; k++) { Header.cdeltx *= 2.; Header.cdelty *= 2.; Header.crpixx /= 2.; Header.crpixy /= 2.; Header.width = (Header.width+1)/2; Header.height = (Header.height+1)/2; } Header.npix = Header.width*Header.height; } } /*****************************************************************/ void MR_CompData::read_header() { initfield(&Header); ReadHd = readint (InFile); // cout << "ReadHd = " << ReadHd << endl; if (ReadHd > 0) { int Sname; char *Buff; char *Buff_Head; if (ReadHd > 1) { Buff_Head = new char [ReadHd]; fread((char *) Buff_Head, sizeof(char), ReadHd, InFile); Header.fitshead = Buff_Head; Header.fitsheadsize = ReadHd; } else Header.fitshead = NULL; Sname = readint (InFile); Buff = new char [Sname+1]; fread(Buff, sizeof(char), Sname, InFile); Buff[Sname] = '\0'; Header.origin = Buff; strcpy(Header.rident, Cmd); Header.bitpix = readint (InFile); Header.bytepix = readint (InFile); Header.naxis = 2; Header.width = readint (InFile); Header.height = readint (InFile); Header.crpixx = (double) readfloat (InFile); Header.crpixy = (double) readfloat (InFile); Header.crvalx = (double) readfloat (InFile); Header.crvaly = (double) readfloat (InFile); Header.cdeltx = (double) readfloat (InFile); Header.cdelty = (double) readfloat (InFile); Header.crotax = (double) readfloat (InFile); Header.crotay = (double) readfloat (InFile); Header.bscale = (double) readfloat (InFile); Header.bzero = (double) readfloat (InFile); Header.ngamma = (double) readfloat (InFile); Header.epoch = (double) readfloat (InFile); Header.pixscale = (double) readfloat (InFile); strcpy(Header.ident, Header.origin); Sname = readint (InFile); Buff = new char [Sname+1]; fread(Buff, sizeof(char), Sname, InFile); Buff[Sname] = '\0'; strcpy(Header.ctypex, Buff); Sname = readint (InFile); Buff = new char [Sname+1]; fread(Buff, sizeof(char), Sname, InFile); Buff[Sname] = '\0'; strcpy(Header.ctypey,Buff); header_resol(); Header.npix = Header.width*Header.height; if (Verbose == True) { cerr << "cmd = " << Header.origin << endl; cerr << "bitpix = " << Header.bitpix; cerr << " bytepix = " << Header.bytepix << endl; cerr << "width = " << Header.width; cerr << " height = " << Header.height << endl; if ((Header.crpixx > 0) && (Header.crpixy > 0)) { cerr << "crpixx = " << Header.crpixx; cerr << " crpixy = " << Header.crpixy << endl; } if ((Header.crvalx > 0) && (Header.crvaly> 0)) { cerr << "crvalx = " << Header.crvalx; cerr << " crvaly = " << Header.crvaly << endl; } if ((Header.cdeltx > 0) && (Header.cdelty > 0)) { cerr << "cdeltx = " << Header.cdeltx; cerr << " cdelty = " << Header.cdelty << endl; } if ((Header.crotax> 0) || (Header.crotay > 0)) { cerr << "crotax = " << Header.crotax; cerr << " crotay = " << Header.crotay << endl; } cerr << "bscale = " << Header.bscale; cerr << " bzero = " << Header.bzero << endl; if (Header.ngamma> 0) cerr << "ngamma = " << Header.ngamma << endl; if (Header.epoch> 0) cerr << "epoch = " << Header.epoch << endl; if (Header.pixscale> 0) cerr << "pixscale = " << Header.pixscale << endl; if (strlen(Header.ctypex) > 0) cerr << "ctypex = " << Header.ctypex; if (strlen(Header.ctypey) > 0) cerr << " ctypey = " << Header.ctypex << endl << endl; } } if (IntTrans == True) { if (readint (InFile) == 0) NoBscale= False; else NoBscale = True; } if ((Comp_Method == COMP_O_MORPHO) || (Comp_Method == COMP_MORPHO)) { Elstr_Size = readint (InFile); Elstr_Shape = readint (InFile); } if (Verbose == True) { if (NoBscale == True) cerr << "Bscaling not applied " << endl; if ((Comp_Method == COMP_O_MORPHO) || (Comp_Method == COMP_MORPHO)) { cerr << "Struct. element size = " << Elstr_Size << endl; if (Elstr_Shape == 0) cerr << "Struct. element = square " << endl; else cerr << "Struct. element = circle " << endl; } } // modify the fits structure following user request type_format FormatData = io_which_format(File_Name_Imag); if (FormatData == F_UNKNOWN) { if (FormatInput != F_UNKNOWN) io_set_format(FormatInput); else FormatInput = FormatData; } // in case of fits format, set the output type of data if ((OutputType == 'i') && (ReadHd > 0)) { Header.bitpix = 32; Header.bytepix = 4; } else if ((OutputType == 's') && (ReadHd > 0)) { Header.bitpix = 16; Header.bytepix = 2; } else if ((OutputType == 'f') && (ReadHd > 0)) { Header.bitpix = -32; Header.bytepix = 4; } } /****************************************************************/ void MR_CompData::decode_data() { int i, NScale,Nli,Nci; // cout << "DEC" << Comp_Method << endl; switch (Comp_Method) { case COMP_HAAR: case COMP_MALLAT: case COMP_FEAUVEAU: case COMP_MIN_MAX: case COMP_WT_PMT: // if (Comp_Method != COMP_HAAR) IterRec = 0; if ((Comp_Method == COMP_MALLAT) && (UseLiftingInsteadOfFilter == True)) lifting_decompress(*BDat, Resol,InFile,Nli,Nci,Verbose); else { if (Resol == -1) mr_buddecompress(*BDat, Transform, 0,InFile,Nli,Nci,IterRec,Verbose); else mr_buddecompress(*BDat, Transform, Resol,InFile,Nli,Nci,IterRec,Verbose); Nl = BDat->nl(); Nc = BDat->nc(); // Haar scaling function is not normalized by 1. // It means that pixels values of the image at a lower // resolution are higher than the original image // ===> we do a renormalization if ((Resol > 0) && (Comp_Method == COMP_HAAR)) { float Coef = 1.; for (i=0; i < Resol; i++) Coef *= 2.; for (i=0; i < Dat.nl()*Dat.nc(); i++) (*BDat)(i) /= Coef; } } break; case COMP_MRMEDIAN: if (Resol == -1) mr_decompress (*BDat,0,InFile,Nli,Nci,Verbose); else mr_decompress (*BDat,Resol,InFile,Nli,Nci,Verbose); Nl = BDat->nl(); Nc = BDat->nc(); break; case COMP_O_MRMEDIAN: if (Resol == -1) mri_decompress (&BIDat,&Nl,&Nc,& NScale,0,InFile,Nli,Nci,Verbose); else mri_decompress (&BIDat,&Nl,&Nc,&NScale, Resol,InFile,Nli,Nci,Verbose); ImagInt.alloc(BIDat,Nl,Nc); break; case COMP_MORPHO: morpho_decompress (*BDat, N_Iter,InFile, Elstr_Size,Elstr_Shape,Verbose); Nl = Dat.nl(); Nc = Dat.nc(); Nli = Nl; Nci = Nc; break; case COMP_O_MIN_MAX: { Iint GDat; if (Resol == -1) mr_i_ortho_decompress (GDat,0, NScale, InFile,Nli,Nci,Verbose); else mr_i_ortho_decompress (GDat, Resol, NScale, InFile,Nli,Nci,Verbose); Nl = GDat.nl(); Nc = GDat.nc(); /* image reconstruction */ ImagInt.alloc(Nl,Nc,"rec"); inverse_transform_g (GDat, ImagInt, NScale-1); BIDat = ImagInt.buffer(); } break; case COMP_INT_LIFTING: { // cout << "lift" << endl; if (Resol == -1) mr_i_ortho_decompress (ImagInt,0, NScale, InFile, Nli,Nci,Verbose); else mr_i_ortho_decompress (ImagInt, Resol, NScale, InFile, Nli,Nci,Verbose); Nl = ImagInt.nl(); Nc = ImagInt.nc(); Lifting Clift1D(LiftingTrans); Ortho_2D_WT WT2D(Clift1D); WT2D.recons(ImagInt, NScale); BIDat = ImagInt.buffer(); } break; case COMP_O_MORPHO: Nl =readint(InFile); /* x size of image */ Nc =readint(InFile); /* y size of image */ ImagInt.alloc(Nl,Nc,"ImagInt"); BIDat= ImagInt.buffer(); morphoi_decompress (BIDat, N_Iter, Nl, Nc, InFile,Elstr_Size,Elstr_Shape,Verbose); Nli = Nl; Nci = Nc; break; default: cerr << "Error: unknown compression method ... " << endl; exit(-1); break; } // inverse transform if ((Stat_Noise == NOISE_POISSON) && (Comp_Method != COMP_O_MIN_MAX) && (Comp_Method != COMP_INT_LIFTING)) { if (IntTrans == False) noise_inverse_poisson_transform (*BDat, *BDat); else noise_inverse_poisson_transform (BIDat, BIDat, Nl, Nc); } // if it is not a block compression, the original image size is // equal to Nli,Nci if (NbrBlock <= 1) { L_Nl = Nli; L_Nc = Nci; } } /***************************************************************/ void MR_CompData::read_noise_info() { KeepResi = readint(InFile); Noise_Ima = readfloat(InFile); } /*****************************************************************/ void MR_CompData::decode_residu() { float Sigmaf; int i,j,k=0; if (IntTrans == False) { if ((Resol==-1) && (KeepResi!=0)) { decode(InFile, &IResidual, &Nl, &Nc, &Sigmaf); // if (Verbose == True) cerr << "Sigma residu = " << Sigmaf << endl; for (i = 0; i < Nl; i++) for (j = 0; j < Nc; j++) (*BDat)(i,j) += IResidual[k++] * Sigmaf; } else if (SimuNoise == True) { if (Stat_Noise == NOISE_POISSON) noise_poisson_transform (*BDat, *BDat); *BDat +=im_noise(Noise_Ima, BDat->nl(), BDat->nc()); if (Stat_Noise == NOISE_POISSON) noise_inverse_poisson_transform (*BDat, *BDat); else noise_inverse_poisson_transform (BIDat, BIDat, Nl, Nc); } } else { if ((Resol==-1) && (KeepResi!=0)) { decode(InFile, &IResidual, &Nl, &Nc, &Sigmaf); // if (Verbose == True) cerr << "Sigma residu = " << Sigmaf << endl; for (i = 0; i < Nl*Nc; i++) BIDat[i] += (int) (IResidual[i] * Sigmaf); } else if (SimuNoise == True) { Ifloat DatN(Nl,Nc,"im_noise"); for (i = 0; i < Nl*Nc; i++) DatN(i) = BIDat[i]; if (Stat_Noise == NOISE_POISSON) noise_poisson_transform (DatN, DatN); DatN += im_noise(Noise_Ima, Nl, Nc); if (Stat_Noise == NOISE_POISSON) noise_inverse_poisson_transform (DatN, DatN); for (i = 0; i < Nl*Nc; i++) BIDat[i] = quant(DatN(i), 1.); } } } /*****************************************************************/ void MR_CompData::put_block(int NumBlock) { int Depi, Depj; Depj = TabBlockDepNc[NumBlock]; Depi = TabBlockDepNl[NumBlock]; if (IntTrans == False) { io_write_block_ima(File_Name_Imag, *BDat, Depi, Depj, InfoData, NoBscale); } else { io_write_block_ima(File_Name_Imag, ImagInt, Depi, Depj, InfoData, NoBscale); } } /*****************************************************************/ void MR_CompData::dec_data() { int i; // BSCALE operation and send to the output the result if (IntTrans == False) { if (NoBscale == True) for (i=0; i < Dat.nl()*Dat.nc(); i++) Dat(i) = Dat(i) * Header.bscale + Header.bzero; } else { Dat.resize(Nl,Nc); if (NoBscale == True) { for (i=0; i < Nl*Nc; i++) Dat(i) = IDat[i] * Header.bscale + Header.bzero; } else for (i=0; i < Nl*Nc; i++) Dat(i) = IDat[i]; } // if bad pixels must be be replaced, do it. if ((BadPixel == True) && (Resol < 0)) { for (i=0; i < Dat.nl()*Dat.nc(); i++) { if (Dat(i)-Noise_Ima*5 < MinDat) Dat(i) = BadPixalVal; else if (Dat(i)+Noise_Ima*5 > MaxDat) Dat(i) = BadPixalVal; } } } /*****************************************************************/ void MR_CompData::write() { // write to ouput file the decompressed data // cout << "ReadHd = " << ReadHd << endl; if (ReadHd > 0) io_write_ima_float(File_Name_Imag, Dat, &Header); else io_write_ima_float(File_Name_Imag, Dat); } /*****************************************************************/ void MR_CompData::set_block_info_data() { int i; int Nli=L_Nl,Nci=L_Nc; // cerr << "set_block_info_data: L_Nl " << L_Nl << " L_Nc = " << L_Nc << endl; // cerr << "StringTransform = " << StringTransform(Transform) << endl; if (BlockSize < 0) BlockSize = MAX(Nli,Nci); set_tabblock(); // find final image size if (Resol > 0) { // BlockSize = BlockSize >> Resol; int Depi=0; int Depj=0; Nli = 0; Nci = 0; for (i = 0; i < NbrBlock; i++) { TabBlockNl[i] = size_ima_resol(Resol, TabBlockNl[i]); TabBlockNc[i] = size_ima_resol(Resol, TabBlockNc[i]); if (i < NbrBlocNc) Nci += TabBlockNc[i]; if (i % NbrBlocNc == 0) { Depj = 0; Nli += TabBlockNl[i]; if (i!= 0) Depi += TabBlockNl[i-1]; } TabBlockDepNl[i] = Depi; TabBlockDepNc[i] = Depj; Depj += TabBlockNc[i]; // cerr << "Block " << i+1 << ": " << TabBlockNl[i] << "x" << TabBlockNc[i] << // " DepNl = " << TabBlockDepNl[i] << " DepNc = " << TabBlockDepNc[i] << endl; } Header.width = Nci; Header.height = Nli; Header.npix = Nci*Nli; } // cout << "FINAL Image Size= " << Nli << "x" << Nci << endl; InfoData.Nl = Nli; InfoData.Nc = Nci; InfoData.Format = FormatInput; InfoData.Nima = 1; if (ReadHd > 0) InfoData.PtrFits = &Header; else { InfoData.PtrFits = new fitsstruct; init_fits_struct(InfoData.PtrFits, Nli, Nci); } if (InfoData.Format == F_GIF) InfoData.PtrGif = new PICINFO; InfoData.put_info(File_Name_Imag); if (IntTrans == False) BDat = new Ifloat; } /*****************************************************************/ void MR_CompData::decompress() { int i; long BufSize; // intialize the decompression init_decompress(); if ((Resol > 0) && ( (Comp_Method == COMP_MORPHO) || (Comp_Method == COMP_O_MORPHO))) { cerr << "Error: morphology based method is not compatible with -r option ... " << endl; exit(-1); } // decompress all blocks if (UseBlock == True) // (NbrBlock > 1) { L_Nl = readint(InFile); L_Nc = readint(InFile); if (Verbose == True) cerr << "Compressed image size: Nl = " << L_Nl << " Nc = " << L_Nc << endl; set_block_info_data(); // decode each block for (i =0; i < NbrBlock; i++) { BufSize = readint(InFile); if (Verbose == True) { cerr << "Block " << i+1 << ": " << TabBlockNl[i] << "x" << TabBlockNc[i] << " Size = " << BufSize << endl; } decode_data(); // cout << "skip to next block" << endl; if (Resol > 0) { int NB_seek = number_band_per_resol(Transform)* Resol; // cout << " NB_seek = " << NB_seek << endl; seek_band(NB_seek); } // cout << "decode noise" << endl; if (NoiseThresholding == True) { // read info parameters read_noise_info(); if (Resol < 0) { decode_residu(); if ((IntTrans == True) && (IResidual != NULL)) i_free(IResidual); } else if (KeepResi) { // cout << "fseek noise" << endl; seek_band(1); } } // cout << "put_block" << endl; put_block(i); if (IntTrans == True) ImagInt.free(); else (*BDat).free(); } io_close_block_ima(File_Name_Imag, InfoData); } else { BDat = &Dat; decode_data(); IDat = BIDat; // decode noise if all scale are decompressed (Resol == -1) if ((NoiseThresholding == True) && (Resol < 0)) { read_noise_info(); decode_residu(); } dec_data(); } if ((NoiseThresholding == True) && (Verbose == True) && (Stat_Noise == NOISE_GAUSSIAN) && (Resol < 0) ) { fprintf(stderr, "Sigma estimated noise = %f\n", Noise_Ima); } if ((InFile != NULL) && (InFile != stdin)) fclose (InFile); } /*****************************************************************/ void MR_CompData::init_decompress() { if (InputFromStdin == False) { InFile = fopen (File_Name_Transform, "rb"); if (InFile == NULL) { cerr << "Error: cannot open input file: "<<File_Name_Transform<< endl; exit(0); } } else InFile = stdin; read_tinfo(); read_header(); } /*****************************************************************/ void MR_CompData::decompress(int NB) { int i, NumBlock=NB-1; init_decompress(); long BufSize; if ((NumBlock<0) || (NumBlock >= NbrBlock)) NumBlock = 0; // skip the first blocks seek_block(NumBlock); // read the total size if (UseBlock == True) // (NbrBlock > 1) BufSize = readint(InFile); BDat = &Dat; decode_data(); IDat = BIDat; //L_Nl = Nl; //L_Nc = Nc; // Modify the fits header if (NbrBlock > 1) { Header.width = Nc; Header.height = Nl; Header.npix = Nc*Nl; int Nx = TabBlockDepNc[NumBlock]; int Ny = TabBlockDepNl[NumBlock]; if ((Resol > 0) && (ReadHd > 0)) { for (i = 0; i < Resol; i++) { Nx = (Nx+1) / 2; Ny = (Ny+1) / 2; } } Header.crpixx -= Nx; Header.crpixy -= Ny; } if (Verbose == True) cerr << "Block " << NumBlock+1 << ": " << Nl << "x" << Nc << endl; // decode noise if ((NoiseThresholding == True) && (Resol < 0)) { read_noise_info(); decode_residu(); } if ((NoiseThresholding == True) && (Verbose == True) && (Stat_Noise == NOISE_GAUSSIAN) && (Resol < 0) ) fprintf(stderr, "Sigma estimated noise = %f\n", Noise_Ima); dec_data(); if (InFile != NULL) fclose (InFile); } /***************************************************/ void MR_CompData::get_resol(int RN, int &SizeBufResol, char * & BuffResol, int NB) { int i,NumBlock=NB-1; int NbrSkipResol; long BufSize; int ResolNumber=RN; init_decompress(); if (ResolNumber >= Nbr_Plan) ResolNumber = Nbr_Plan-1; // test compression method: must be based on multiresolution. if ((Comp_Method == COMP_MORPHO) || (Comp_Method == COMP_O_MORPHO)) { cerr << "Error: this compression method is not multiresolution based. " << endl; exit(-1); } seek_block(NumBlock); if (UseBlock == True) // (NbrBlock > 1) BufSize = readint(InFile); // read the original block image size Nl =readint( InFile); Nc =readint( InFile); // read the number of scales Nbr_Plan=readint( InFile); // calculate the number of resolution to skip NbrSkipResol = Nbr_Plan - ResolNumber - 1; if (NbrSkipResol >= Nbr_Plan) { seek_resol(Nbr_Plan); read_noise_info(); if (Verbose == True) cerr << "Noise ima = " << Noise_Ima << endl; // test if the residu is stored if ((ResolNumber==-1) && (KeepResi!=0)) { SizeBufResol = readint(InFile); if (Verbose == True) cerr << "Size residual = " << SizeBufResol << endl; BuffResol = new char [SizeBufResol]; fread((void *) BuffResol, sizeof(char), SizeBufResol, InFile); } else { cerr << "Error: no residual part in the compressed file ... " << endl; exit(-1); } } else { seek_resol(NbrSkipResol); // read the number of bands (contained in a single resolution) to read int NbrB; if (NbrSkipResol == 0) NbrB = 1; else NbrB = number_band_per_resol(Transform); // read the bands SizeBufResol = 0; long SizeOneBand; for (i=0; i < NbrB; i++) { char *PtrBuff; SizeOneBand = readint(InFile); if (Verbose == True) cerr << "Resol " << ResolNumber << " Band " << i+1 << " Size = " << SizeOneBand << endl; if (SizeBufResol == 0) BuffResol = new char [SizeOneBand]; else BuffResol = (char *) realloc(BuffResol, SizeBufResol+SizeOneBand); PtrBuff = BuffResol; PtrBuff += SizeBufResol; SizeBufResol += SizeOneBand; fread((void *) PtrBuff, sizeof(char), SizeOneBand, InFile); } } if (InFile != NULL) fclose (InFile); } /***************************************************/ // seek the first N blocks void MR_CompData::seek_block(int NumBlock) { long BufSize; int i; if (UseBlock == True) // (NbrBlock > 1) { L_Nl = readint(InFile); L_Nc = readint(InFile); set_tabblock(); } // skip the first blocks i =0; while ((i < NumBlock) && (i < NbrBlock)) { BufSize = readint(InFile); if ( fseek(InFile, BufSize, SEEK_CUR) < 0) { cerr << "Error in fseek: request shift is " << BufSize << endl; exit(-1); } i++; } } /***************************************************/ void MR_CompData::seek_resol(int NbrSkipResol) { int NumberBand_per_Resol = number_band_per_resol(Transform); int NbrSkipBand = NumberBand_per_Resol*(NbrSkipResol-1)+1; // cout << "NumberBand_per_Resol = " << NumberBand_per_Resol << endl; // cout << "NbrSkipBand = " <<NbrSkipBand<< endl; // cout << "NbrSkipResol= " <<NbrSkipResol<< endl; seek_band(NbrSkipBand); } /***************************************************/ void MR_CompData::seek_band(int NbrSkipBand) { long BufSize; // skip the resolutions if (NbrSkipBand > 3*Nbr_Plan+1) { cerr << "Error: the number of band to skip is too high ... " << endl; cerr << " NbrSkipBand = " << NbrSkipBand << " Nbr_Plan = " << Nbr_Plan << endl; exit(-1); } for (int r=0; r < NbrSkipBand; r++) { BufSize = readint(InFile); // cout << "size skip " << BufSize << endl; if (fseek(InFile, BufSize, SEEK_CUR)) { cerr << "Error in fseek: request shift is " << BufSize << endl; exit(-1); } } } /***************************************************/
29.790239
103
0.507948
[ "transform" ]
a98c806c53804edef055f133b546133c45f0aa4f
27,159
cpp
C++
test/correctness/reduction_non_rectangular.cpp
mbrukman/Halide
8a08a705044c2da42581f1255ccae9e34030f703
[ "MIT" ]
2
2018-12-27T17:46:11.000Z
2019-04-19T23:01:35.000Z
test/correctness/reduction_non_rectangular.cpp
mbrukman/Halide
8a08a705044c2da42581f1255ccae9e34030f703
[ "MIT" ]
1
2018-10-05T03:40:57.000Z
2018-10-05T03:40:57.000Z
test/correctness/reduction_non_rectangular.cpp
mbrukman/Halide
8a08a705044c2da42581f1255ccae9e34030f703
[ "MIT" ]
1
2021-04-30T05:14:03.000Z
2021-04-30T05:14:03.000Z
#include <stdio.h> #include "Halide.h" using namespace Halide; // A trace that checks for vector and scalar stores int buffer_index = 0; bool run_tracer = false; int niters_expected = 0; int niters = 0; int intermediate_bound_depend_on_output_trace(void *user_context, const halide_trace_event_t *e) { std::string buffer_name = "g_" + std::to_string(buffer_index); if (std::string(e->func) == buffer_name) { if (e->event == halide_trace_produce) { run_tracer = true; } else if (e->event == halide_trace_consume) { run_tracer = false; } if (run_tracer && (e->event == halide_trace_store)) { if (!((e->coordinates[0] < e->coordinates[1]) && (e->coordinates[0] >= 0) && (e->coordinates[0] <= 199) && (e->coordinates[1] >= 0) && (e->coordinates[1] <= 199))) { printf("Bounds on store of g were supposed to be x < y and x=[0, 99] and y=[0, 99]\n" "Instead they are: %d %d\n", e->coordinates[0], e->coordinates[1]); exit(-1); } niters++; } } return 0; } int func_call_bound_trace(void *user_context, const halide_trace_event_t *e) { std::string buffer_name = "g_" + std::to_string(buffer_index); if (std::string(e->func) == buffer_name) { if (e->event == halide_trace_produce) { run_tracer = true; } else if (e->event == halide_trace_consume) { run_tracer = false; } if (run_tracer && (e->event == halide_trace_store)) { if (!((e->coordinates[0] >= 10) && (e->coordinates[0] <= 109))) { printf("Bounds on store of g were supposed to be x=[10, 109]\n" "Instead it is: %d\n", e->coordinates[0]); exit(-1); } niters++; } } return 0; } int box_bound_trace(void *user_context, const halide_trace_event_t *e) { std::string buffer_name = "g_" + std::to_string(buffer_index); if (std::string(e->func) == buffer_name) { if (e->event == halide_trace_produce) { run_tracer = true; } else if (e->event == halide_trace_consume) { run_tracer = false; } if (run_tracer && (e->event == halide_trace_store)) { if (!((e->coordinates[0] >= 0) && (e->coordinates[0] <= 99) && (e->coordinates[1] >= 0) && (e->coordinates[1] <= 99))) { printf("Bounds on store of g were supposed to be x < y and x=[0, 99] and y=[0, 99]\n" "Instead they are: %d %d\n", e->coordinates[0], e->coordinates[1]); exit(-1); } niters++; } } return 0; } int equality_inequality_bound_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)); Var x("x"), y("y"); f(x, y) = x + y; RDom r(0, 100, 0, 100); r.where(r.x < r.y); r.where(!(r.x != 10)); f(r.x, r.y) += 1; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((x == 10) && (0 <= y && y <= 99)) { correct += (x < y) ? 1 : 0; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } return 0; } int split_fuse_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)); Var x("x"), y("y"); f(x, y) = x + y; RDom r(0, 100, 0, 100); r.where(r.x < r.y); f(r.x, r.y) += 1; RVar rx_outer, rx_inner, r_fused; f.update().reorder(r.y, r.x); f.update().split(r.x, rx_outer, rx_inner, 4); f.update().fuse(rx_inner, r.y, r_fused); Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct += (x < y) ? 1 : 0; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } return 0; } int free_variable_bound_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)); Var x("x"), y("y"), z("z"); f(x, y, z) = x + y + z; RDom r(0, 100, 0, 100, "r"); r.where(r.x < r.y + z); f(r.x, r.y, z) += 1; Buffer<int> im = f.realize(200, 200, 200); for (int z = 0; z < im.channels(); z++) { for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y + z; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct += (x < y + z) ? 1 : 0; } if (im(x, y, z) != correct) { printf("im(%d, %d, %d) = %d instead of %d\n", x, y, z, im(x, y, z), correct); return -1; } } } } return 0; } int func_call_inside_bound_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)); Var x("x"), y("y"); g(x) = x; f(x, y) = x + y; RDom r(0, 100, 0, 100, "r"); r.where(r.x < g(r.y+10)); f(r.x, r.y) += 1; // Expect g to be computed over x=[10, 109]. g.compute_root(); f.set_custom_trace(&func_call_bound_trace); g.trace_stores(); g.trace_realizations(); run_tracer = false; niters_expected = 100; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct += (x < y+10) ? 1 : 0; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } if (niters_expected != niters) { printf("func_call_inside_bound_test : Expect niters on g to be %d but got %d instead\n", niters_expected, niters); return -1; } return 0; } int func_call_inside_bound_inline_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)); Func h("h_" + std::to_string(index)); Var x("x"), y("y"); g(x) = x; h(x) = 2*x; f(x, y) = x + y; RDom r(0, 100, 0, 100, "r"); r.where(r.x < g(r.y) + h(r.x)); f(r.x, r.y) += 1; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct += (x < y + 2*x) ? 1 : 0; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } return 0; } int two_linear_bounds_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)); Var x("x"), y("y"); g(x, y) = x + y; f(x, y) = x + y; RDom r(0, 100, 0, 100); r.where(2*r.x + 30 < r.y); r.where(r.y >= 100 - r.x); f(r.x, r.y) += 2*g(r.x, r.y); // Expect g to be computed over x=[0,99] and y=[1,99]. g.compute_root(); f.set_custom_trace(&box_bound_trace); g.trace_stores(); g.trace_realizations(); run_tracer = false; // The first condition means r.x. can be at most 34 (2*34 + 30 = // 98 < 99). The second condition means r.x must be at least 1, // so there are 34 legal values for r.x. The second condition // also means that r.y is at least 100 - 34 and at most 99, so // there are also 34 legal values of it. We only actually iterate // over a triangle within this box, but Halide takes bounding // boxes for bounds relationships. niters_expected = 34 * 34; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct = ((2*x + 30 < y) && (y >= 100 - x)) ? 3*correct : correct; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } if (niters_expected != niters) { printf("two_linear_bounds_test : Expect niters on g to be %d but got %d instead\n", niters_expected, niters); return -1; } return 0; } int circle_bound_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)); Var x("x"), y("y"); g(x, y) = x; f(x, y) = x + y; // Iterate over circle with radius of 10 RDom r(0, 100, 0, 100); r.where(r.x*r.x + r.y*r.y <= 100); f(r.x, r.y) += g(r.x, r.y); // Expect g to be still computed over x=[0,99] and y=[0,99]. The predicate // guard for the non-linear term will be left as is in the inner loop of f, // i.e. f loop will still iterate over x=[0,99] and y=[0,99]. g.compute_at(f, r.y); f.set_custom_trace(&box_bound_trace); g.trace_stores(); g.trace_realizations(); run_tracer = false; niters_expected = 100*100; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct += (x*x + y*y <= 100) ? x : 0; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } return 0; } int intermediate_computed_if_param_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)); Var x("x"), y("y"); Param<int> p; g(x, y) = x + y; f(x, y) = x + y; RDom r(0, 100, 0, 100); r.where(p > 3); f(r.x, r.y) += 2*g(r.x, r.y); // Expect g to be only computed over x=[0,99] and y=[0,99] if param is bigger // than 3. g.compute_root(); f.set_custom_trace(&box_bound_trace); g.trace_stores(); g.trace_realizations(); { printf("....Set p to 5, expect g to be computed\n"); p.set(5); run_tracer = false; niters_expected = 100*100; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct = 3*correct; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } if (niters_expected != niters) { printf("intermediate_computed_if_param_test : Expect niters on g to be %d but got %d instead\n", niters_expected, niters); return -1; } } { printf("....Set p to 0, expect g to be not computed\n"); p.set(0); run_tracer = false; niters_expected = 0; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } if (niters_expected != niters) { printf("intermediate_computed_if_param_test : Expect niters on g to be %d but got %d instead\n", niters_expected, niters); return -1; } } return 0; } int intermediate_bound_depend_on_output_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)); Var x("x"), y("y"); g(x, y) = x; f(x, y) = x + y; RDom r(0, 200, 0, 200); r.where(r.x < r.y); f(r.x, r.y) = g(r.x, r.y); // Expect bound of g on r.x to be directly dependent on the simplified // bound of f on r.x, which should have been r.x = [0, r.y) in this case g.compute_at(f, r.y); f.set_custom_trace(&intermediate_bound_depend_on_output_trace); g.trace_stores(); g.trace_realizations(); run_tracer = false; niters_expected = 200*199/2; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 199) && (0 <= y && y <= 199)) { if (x < y) { correct = x; } } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } if (niters_expected != niters) { printf("intermediate_bound_depend_on_output_test: Expect niters on g to be %d but got %d instead\n", niters_expected, niters); return -1; } return 0; } int tile_intermediate_bound_depend_on_output_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)); Var x("x"), y("y"); g(x, y) = x; f(x, y) = x + y; RDom r(0, 200, 0, 200, "r"); r.where(r.x < r.y); f(r.x, r.y) += g(r.x, r.y); RVar rxi("rxi"), ryi("ryi"); f.update(0).tile(r.x, r.y, rxi, ryi, 8, 8); f.update(0).reorder(rxi, ryi, r.x, r.y); // Expect bound of g on r.x to be directly dependent on the simplified // bound of f on r.x, which should have been r.x = [0, r.y) in this case g.compute_at(f, ryi); f.set_custom_trace(&intermediate_bound_depend_on_output_trace); g.trace_stores(); g.trace_realizations(); run_tracer = false; niters_expected = 200*199/2; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 199) && (0 <= y && y <= 199)) { correct += (x < y) ? x : 0; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } if (niters_expected != niters) { printf("intermediate_bound_depend_on_output_test: Expect niters on g to be %d but got %d instead\n", niters_expected, niters); return -1; } return 0; } int self_reference_bound_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)); Var x("x"), y("y"); f(x, y) = x + y; g(x, y) = 10; RDom r1(0, 100, 0, 100, "r1"); r1.where(f(r1.x, r1.y) >= 40); r1.where(f(r1.x, r1.y) != 50); f(r1.x, r1.y) += 1; f.compute_root(); RDom r2(0, 50, 0, 50, "r2"); r2.where(f(r2.x, r2.y) < 30); g(r2.x, r2.y) += f(r2.x, r2.y); Buffer<int> im1 = f.realize(200, 200); for (int y = 0; y < im1.height(); y++) { for (int x = 0; x < im1.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct += ((correct >= 40) && (correct != 50)) ? 1 : 0; } if (im1(x, y) != correct) { printf("im1(%d, %d) = %d instead of %d\n", x, y, im1(x, y), correct); return -1; } } } Buffer<int> im2 = g.realize(200, 200); for (int y = 0; y < im2.height(); y++) { for (int x = 0; x < im2.width(); x++) { int correct = 10; if ((0 <= x && x <= 49) && (0 <= y && y <= 49)) { correct += (im1(x, y) < 30) ? im1(x, y) : 0; } if (im2(x, y) != correct) { printf("im2(%d, %d) = %d instead of %d\n", x, y, im2(x, y), correct); return -1; } } } return 0; } int random_float_bound_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)); Var x("x"), y("y"); Expr e1 = random_float() < 0.5f; f(x, y) = Tuple(e1, x + y); RDom r(0, 100, 0, 100); r.where(f(r.x, r.y)[0]); f(r.x, r.y) = Tuple(f(r.x, r.y)[0], f(r.x, r.y)[1] + 10); Realization res = f.realize(200, 200); assert(res.size() == 2); Buffer<bool> im0 = res[0]; Buffer<int> im1 = res[1]; int n_true = 0; for (int y = 0; y < im1.height(); y++) { for (int x = 0; x < im1.width(); x++) { n_true += im0(x, y); int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct += im0(x, y) ? 10 : 0; } if (im1(x, y) != correct) { printf("im1(%d, %d) = %d instead of %d\n", x, y, im1(x, y), correct); return -1; } } } if (!(19000 <= n_true && n_true <= 21000)) { printf("Expected n_true to be between 19000 and 21000; got %d instead\n", n_true); return -1; } return 0; } int newton_method_test() { Func inverse; Var x; // Negating the bits of a float is a piecewise linear approximation to inverting it inverse(x) = {-0.25f * reinterpret<float>(~(reinterpret<uint32_t>(cast<float>(x+1)))), 0}; const int max_iters = 10; RDom r(0, max_iters); Expr not_converged = abs(inverse(x)[0] * (x+1) - 1) > 0.001f; r.where(not_converged); // Compute the inverse of x using Newton's method, and count the // number of iterations required to reach convergence inverse(x) = {inverse(x)[0] * (2 - (x+1) * inverse(x)[0]), r+1}; { Realization r = inverse.realize(128); Buffer<float> r0 = r[0]; Buffer<int> r1 = r[1]; for (int i = 0; i < r0.width(); i++) { float x = (i+1); float prod = x * r0(i); int num_iters = r1(i); if (num_iters == max_iters) { printf("Newton's method didn't converge!\n"); return -1; } if (std::abs(prod - 1) > 0.001) { printf("Newton's method converged without producing the correct inverse:\n" "%f * %f = %f (%d iterations)\n", x, r0(i), prod, r1(i)); return -1; } } } return 0; } int init_on_gpu_update_on_cpu_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)); Var x("x"), y("y"); f(x, y) = x + y; RDom r(0, 100, 0, 100); r.where(r.x < r.y); r.where(!(r.x != 10)); f(r.x, r.y) += 3; Var xi("xi"), yi("yi"); f.gpu_tile(x, y, xi, yi, 4, 4); Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((x == 10) && (0 <= y && y <= 99)) { correct += (x < y) ? 3 : 0; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } return 0; } int init_on_cpu_update_on_gpu_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)); Var x("x"), y("y"); f(x, y) = x + y; RDom r(0, 100, 0, 100); r.where(!(r.x != 10)); r.where(r.x < r.y); f(r.x, r.y) += 3; RVar rxi("rxi"), ryi("ryi"); f.update(0).gpu_tile(r.x, r.y, r.x, r.y, rxi, ryi, 4, 4); Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((x == 10) && (0 <= y && y <= 99)) { correct += (x < y) ? 3 : 0; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } return 0; } int gpu_intermediate_computed_if_param_test(int index) { buffer_index = index; Func f("f_" + std::to_string(index)), g("g_" + std::to_string(index)), h("h_" + std::to_string(index)); Var x("x"), y("y"); Param<int> p; g(x, y) = x + y; h(x, y) = 10; f(x, y) = x + y; RDom r1(0, 100, 0, 100); r1.where(p > 3); f(r1.x, r1.y) += 2*g(r1.x, r1.y); RDom r2(0, 100, 0, 100); r2.where(p <= 3); f(r2.x, r2.y) += h(r2.x, r2.y) + g(r2.x, r2.y); RVar r1xi("r1xi"), r1yi("r1yi"); f.update(0).specialize(p >= 2).gpu_tile(r1.x, r1.y, r1xi, r1yi, 4, 4); g.compute_root(); h.compute_root(); Var xi("xi"), yi("yi"); h.gpu_tile(x, y, xi, yi, 8, 8); { printf("....Set p to 5, expect g to be computed\n"); p.set(5); run_tracer = false; niters_expected = 100*100; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct = 3*correct; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } } { printf("....Set p to 0, expect g to be not computed\n"); p.set(0); run_tracer = false; niters_expected = 0; niters = 0; Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = x + y; if ((0 <= x && x <= 99) && (0 <= y && y <= 99)) { correct += 10 + correct; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } } return 0; } int vectorize_predicated_rvar_test() { Func f("f"); Var x("x"), y("y"); f(x, y) = 0; Expr w = (f.output_buffer().width()/2)*2; Expr h = (f.output_buffer().height()/2)*2; RDom r(1, w - 2, 1, h - 2); r.where((r.x + r.y) % 2 == 0); f(r.x, r.y) += 10; f.update(0).unroll(r.x, 2) .allow_race_conditions().vectorize(r.x, 8); Buffer<int> im = f.realize(200, 200); for (int y = 0; y < im.height(); y++) { for (int x = 0; x < im.width(); x++) { int correct = 0; if ((1 <= x && x < im.width() - 1) && (1 <= y && y < im.height() - 1) && ((x + y) % 2 == 0)) { correct += 10; } if (im(x, y) != correct) { printf("im(%d, %d) = %d instead of %d\n", x, y, im(x, y), correct); return -1; } } } return 0; } int main(int argc, char **argv) { printf("Running equality inequality bound test\n"); if (equality_inequality_bound_test(0) != 0) { return -1; } printf("Running split fuse test\n"); if (split_fuse_test(1) != 0) { return -1; } printf("Running bound depend on free variable test\n"); if (free_variable_bound_test(2) != 0) { return -1; } printf("Running function call inside bound test\n"); if (func_call_inside_bound_test(3) != 0) { return -1; } printf("Running function call inside bound inline test\n"); if (func_call_inside_bound_inline_test(4) != 0) { return -1; } printf("Running two linear bounds test\n"); if (two_linear_bounds_test(5) != 0) { return -1; } printf("Running circular bound test\n"); if (circle_bound_test(6) != 0) { return -1; } printf("Running intermediate only computed if param is bigger than certain value test\n"); if (intermediate_computed_if_param_test(7) != 0) { return -1; } printf("Running tile intermediate stage depend on output bound test\n"); if (tile_intermediate_bound_depend_on_output_test(8) != 0) { return -1; } printf("Running intermediate stage depend on output bound\n"); if (intermediate_bound_depend_on_output_test(9) != 0) { return -1; } printf("Running self reference bound test\n"); if (self_reference_bound_test(10) != 0) { return -1; } printf("Running random float bound test\n"); if (random_float_bound_test(11) != 0) { return -1; } printf("Running newton's method test\n"); if (newton_method_test() != 0) { return -1; } printf("Running vectorize predicated rvar test\n"); if (vectorize_predicated_rvar_test() != 0) { return -1; } // Run GPU tests now if there is support for GPU. if (!get_jit_target_from_environment().has_gpu_feature()) { printf("Not running test because no gpu feature enabled in target.\n"); printf("Success!\n"); return 0; } printf("Running initialization on gpu and update on cpu test\n"); if (init_on_gpu_update_on_cpu_test(12) != 0) { return -1; } printf("Running initialization on cpu and update on gpu test\n"); if (init_on_cpu_update_on_gpu_test(13) != 0) { return -1; } printf("Running gpu intermediate only computed if param is bigger than certain value test\n"); if (gpu_intermediate_computed_if_param_test(14) != 0) { return -1; } printf("Success!\n"); return 0; }
29.584967
108
0.461762
[ "vector" ]
817aa496e361eb631fad1842f8548ca64ee16aba
14,874
cpp
C++
third_party/maya/lib/usdMaya/meshUtil.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
6
2018-08-26T13:27:22.000Z
2021-08-14T23:57:38.000Z
third_party/maya/lib/usdMaya/meshUtil.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
1
2021-08-14T23:57:51.000Z
2021-08-14T23:57:51.000Z
third_party/maya/lib/usdMaya/meshUtil.cpp
navefx/YuksUSD
56c2e1def36ee07121f4ecb349c1626472b3c338
[ "AML" ]
4
2018-06-14T18:14:59.000Z
2021-09-13T22:20:50.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "pxr/pxr.h" #include "usdMaya/meshUtil.h" #include "pxr/base/gf/vec3f.h" #include "pxr/base/tf/staticTokens.h" #include "pxr/base/tf/token.h" #include "pxr/base/vt/array.h" #include "pxr/usd/usdGeom/mesh.h" #include <maya/MFloatVector.h> #include <maya/MFloatVectorArray.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnStringData.h> #include <maya/MFnTypedAttribute.h> #include <maya/MGlobal.h> #include <maya/MItMeshFaceVertex.h> #include <maya/MPlug.h> #include <maya/MStatus.h> PXR_NAMESPACE_OPEN_SCOPE TF_DEFINE_PUBLIC_TOKENS(PxrUsdMayaMeshColorSetTokens, PXRUSDMAYA_MESH_COLOR_SET_TOKENS); // These tokens are supported Maya attributes used for Mesh surfaces TF_DEFINE_PRIVATE_TOKENS( _meshTokens, // we capitalize this because it doesn't correspond to an actual attribute (USD_EmitNormals) // This is a value for face varying interpolate boundary from OpenSubdiv 2 // that we translate to face varying linear interpolation for OpenSubdiv 3. (alwaysSharp) ); // These tokens are supported Maya attributes used for SDiv surfaces TF_DEFINE_PRIVATE_TOKENS( _subdivTokens, (USD_subdivisionScheme) (USD_interpolateBoundary) (USD_faceVaryingLinearInterpolation) // This token is deprecated as it is from OpenSubdiv 2 and the USD // schema now conforms to OpenSubdiv 3, but we continue to look for it // and translate to the equivalent new value for backwards compatibility. (USD_faceVaryingInterpolateBoundary) ); // This can be customized for specific pipelines. bool PxrUsdMayaMeshUtil::getEmitNormals( const MFnMesh& mesh, const TfToken& subdivScheme) { MPlug plug = mesh.findPlug(MString(_meshTokens->USD_EmitNormals.GetText())); if (!plug.isNull()) { return plug.asBool(); } // We only emit normals by default if it wasn't explicitly set (above) and // the subdiv scheme is "polygonal". note, we currently only ever call this // function with subdivScheme == none... return subdivScheme == UsdGeomTokens->none; } TfToken PxrUsdMayaMeshUtil::setEmitNormals( const UsdGeomMesh& primSchema, MFnMesh& meshFn, TfToken defaultValue) { MStatus status; TfToken normalInterp = defaultValue; //primSchema.GetSubdivisionSchemeAttr().Get(&subdScheme, UsdTimeCode::Default()); //primSchema.GetNormalsAttr().Set(meshNormals, UsdTimeCode::Default()); normalInterp = primSchema.GetNormalsInterpolation(); // If normals are not present, don't create the attribute if (normalInterp == UsdGeomTokens->faceVarying) { MFnNumericAttribute nAttr; MObject attr = nAttr.create(_meshTokens->USD_EmitNormals.GetText(), "", MFnNumericData::kBoolean, 1, &status); if (status == MS::kSuccess) { meshFn.addAttribute(attr); } } return normalInterp; } bool PxrUsdMayaMeshUtil::GetMeshNormals( const MFnMesh& mesh, VtArray<GfVec3f>* normalsArray, TfToken* interpolation) { MStatus status; // Sanity check first to make sure we can get this mesh's normals. int numNormals = mesh.numNormals(&status); if (status != MS::kSuccess || numNormals == 0) { return false; } // Using itFV.getNormal() does not always give us the right answer, so // instead we have to use itFV.normalId() and use that to index into the // normals. MFloatVectorArray mayaNormals; status = mesh.getNormals(mayaNormals); if (status != MS::kSuccess) { return false; } const unsigned int numFaceVertices = mesh.numFaceVertices(&status); if (status != MS::kSuccess) { return false; } normalsArray->resize(numFaceVertices); *interpolation = UsdGeomTokens->faceVarying; MItMeshFaceVertex itFV(mesh.object()); unsigned int fvi = 0; for (itFV.reset(); !itFV.isDone(); itFV.next(), ++fvi) { int normalId = itFV.normalId(); if (normalId < 0 || static_cast<size_t>(normalId) >= mayaNormals.length()) { return false; } MFloatVector normal = mayaNormals[normalId]; (*normalsArray)[fvi][0] = normal[0]; (*normalsArray)[fvi][1] = normal[1]; (*normalsArray)[fvi][2] = normal[2]; } return true; } // This can be customized for specific pipelines. // We first look for the USD string attribute, and if not present we look for // the RenderMan for Maya int attribute. // XXX Maybe we should come up with a OSD centric nomenclature ?? TfToken PxrUsdMayaMeshUtil::getSubdivScheme( const MFnMesh& mesh, const TfToken& defaultValue) { TfToken schemeToken = defaultValue; MPlug plug = mesh.findPlug(MString(_subdivTokens->USD_subdivisionScheme.GetText())); if (!plug.isNull()) { schemeToken = TfToken(plug.asString().asChar()); } else { plug = mesh.findPlug(MString("rman__torattr___subdivScheme")); if (!plug.isNull()) { switch (plug.asInt()) { case 0: schemeToken = UsdGeomTokens->catmullClark; break; case 1: schemeToken = UsdGeomTokens->loop; break; default: break; } } } if (schemeToken.IsEmpty()) { return defaultValue; } else if (schemeToken != UsdGeomTokens->none && schemeToken != UsdGeomTokens->catmullClark && schemeToken != UsdGeomTokens->loop && schemeToken != UsdGeomTokens->bilinear) { MGlobal::displayError("Unsupported subdivision scheme: " + MString(schemeToken.GetText()) + " on mesh: " + MString(mesh.fullPathName()) + ". Defaulting to: " + MString(defaultValue.GetText())); return defaultValue; } return schemeToken; } // This can be customized for specific pipelines. // We first look for the USD string attribute, and if not present we look for // the RenderMan for Maya int attribute. // XXX Maybe we should come up with a OSD centric nomenclature ?? TfToken PxrUsdMayaMeshUtil::getSubdivInterpBoundary( const MFnMesh& mesh, const TfToken& defaultValue) { TfToken interpBoundaryToken = defaultValue; MPlug plug = mesh.findPlug(MString(_subdivTokens->USD_interpolateBoundary.GetText())); if (!plug.isNull()) { interpBoundaryToken = TfToken(plug.asString().asChar()); } else { plug = mesh.findPlug(MString("rman__torattr___subdivInterp")); if (!plug.isNull()) { switch (plug.asInt()) { case 0: interpBoundaryToken = UsdGeomTokens->none; break; case 1: interpBoundaryToken = UsdGeomTokens->edgeAndCorner; break; case 2: interpBoundaryToken = UsdGeomTokens->edgeOnly; break; default: break; } } } if (interpBoundaryToken.IsEmpty()) { return defaultValue; } else if (interpBoundaryToken != UsdGeomTokens->none && interpBoundaryToken != UsdGeomTokens->edgeAndCorner && interpBoundaryToken != UsdGeomTokens->edgeOnly) { MGlobal::displayError("Unsupported interpolate boundary setting: " + MString(interpBoundaryToken.GetText()) + " on mesh: " + MString(mesh.fullPathName()) + ". Defaulting to: " + MString(defaultValue.GetText())); return defaultValue; } return interpBoundaryToken; } // XXX: Note that this function is not exposed publicly since the USD schema // has been updated to conform to OpenSubdiv 3. We still look for this attribute // on Maya nodes specifying this value from OpenSubdiv 2, but we translate the // value to OpenSubdiv 3. This is to support legacy assets authored against // OpenSubdiv 2. static TfToken _getSubdivFVInterpBoundary(const MFnMesh& mesh) { TfToken sdFVInterpBound; MPlug plug = mesh.findPlug(MString(_subdivTokens->USD_faceVaryingInterpolateBoundary.GetText())); if (!plug.isNull()) { sdFVInterpBound = TfToken(plug.asString().asChar()); // Translate OSD2 values to OSD3. if (sdFVInterpBound == UsdGeomTokens->bilinear) { sdFVInterpBound = UsdGeomTokens->all; } else if (sdFVInterpBound == UsdGeomTokens->edgeAndCorner) { sdFVInterpBound = UsdGeomTokens->cornersPlus1; } else if (sdFVInterpBound == _meshTokens->alwaysSharp) { sdFVInterpBound = UsdGeomTokens->boundaries; } else if (sdFVInterpBound == UsdGeomTokens->edgeOnly) { sdFVInterpBound = UsdGeomTokens->none; } } else { plug = mesh.findPlug(MString("rman__torattr___subdivFacevaryingInterp")); if (!plug.isNull()) { switch(plug.asInt()) { case 0: sdFVInterpBound = UsdGeomTokens->all; break; case 1: sdFVInterpBound = UsdGeomTokens->cornersPlus1; break; case 2: sdFVInterpBound = UsdGeomTokens->none; break; case 3: sdFVInterpBound = UsdGeomTokens->boundaries; break; default: break; } } } return sdFVInterpBound; } TfToken PxrUsdMayaMeshUtil::getSubdivFVLinearInterpolation(const MFnMesh& mesh) { TfToken sdFVLinearInterpolation; MPlug plug = mesh.findPlug(MString(_subdivTokens->USD_faceVaryingLinearInterpolation.GetText())); if (!plug.isNull()) { sdFVLinearInterpolation = TfToken(plug.asString().asChar()); } else { // If the OpenSubdiv 3-style face varying linear interpolation value // wasn't specified, fall back to the old OpenSubdiv 2-style face // varying interpolate boundary value if we have that. sdFVLinearInterpolation = _getSubdivFVInterpBoundary(mesh); } if (!sdFVLinearInterpolation.IsEmpty() && sdFVLinearInterpolation != UsdGeomTokens->all && sdFVLinearInterpolation != UsdGeomTokens->none && sdFVLinearInterpolation != UsdGeomTokens->boundaries && sdFVLinearInterpolation != UsdGeomTokens->cornersOnly && sdFVLinearInterpolation != UsdGeomTokens->cornersPlus1 && sdFVLinearInterpolation != UsdGeomTokens->cornersPlus2) { MGlobal::displayError("Unsupported Face Varying Linear Interpolation Attribute: " + MString(sdFVLinearInterpolation.GetText()) + " on mesh: " + MString(mesh.fullPathName())); sdFVLinearInterpolation = TfToken(); } return sdFVLinearInterpolation; } TfToken PxrUsdMayaMeshUtil::setSubdivScheme(const UsdGeomMesh &primSchema, MFnMesh &meshFn, TfToken defaultValue) { MStatus status; // Determine if PolyMesh or SubdivMesh TfToken subdScheme; primSchema.GetSubdivisionSchemeAttr().Get(&subdScheme, UsdTimeCode::Default()); // If retrieved scheme is default, don't create the attribute if (subdScheme != defaultValue) { MFnTypedAttribute stringAttr; MFnStringData stringData; MObject stringVal = stringData.create(subdScheme.GetText()); MObject attr = stringAttr.create(_subdivTokens->USD_subdivisionScheme.GetText(), "", MFnData::kString, stringVal, &status); if (status == MS::kSuccess) { meshFn.addAttribute(attr); } } return subdScheme; } TfToken PxrUsdMayaMeshUtil::setSubdivInterpBoundary(const UsdGeomMesh &primSchema, MFnMesh &meshFn, TfToken defaultValue) { MStatus status; TfToken interpBoundary; primSchema.GetInterpolateBoundaryAttr().Get(&interpBoundary, UsdTimeCode::Default()); // XXXX THIS IS FOR OPENSUBDIV IN MAYA ? if (interpBoundary != UsdGeomTokens->none) { MPlug boundRulePlug = meshFn.findPlug("boundaryRule", &status); if (status == MS::kSuccess) { int value=0; if(interpBoundary == UsdGeomTokens->edgeAndCorner) value=1; else if(interpBoundary == UsdGeomTokens->edgeOnly) value=2; boundRulePlug.setValue(value); } } if (interpBoundary != defaultValue) { MFnTypedAttribute stringAttr; MFnStringData stringData; MObject stringVal = stringData.create(interpBoundary.GetText()); MObject attr = stringAttr.create(_subdivTokens->USD_interpolateBoundary.GetText(), "", MFnData::kString, stringVal, &status); if (status == MS::kSuccess) { meshFn.addAttribute(attr); } } return interpBoundary; } TfToken PxrUsdMayaMeshUtil::setSubdivFVLinearInterpolation(const UsdGeomMesh &primSchema, MFnMesh &meshFn) { MStatus status; TfToken fvLinearInterpolation; auto fvLinearInterpolationAttr = primSchema.GetFaceVaryingLinearInterpolationAttr(); fvLinearInterpolationAttr.Get(&fvLinearInterpolation); if (fvLinearInterpolation != UsdGeomTokens->cornersPlus1) { MFnTypedAttribute stringAttr; MFnStringData stringData; MObject stringVal = stringData.create(fvLinearInterpolation.GetText()); MObject attr = stringAttr.create(_subdivTokens->USD_faceVaryingInterpolateBoundary.GetText(), "", MFnData::kString, stringVal, &status); if (status == MS::kSuccess) { meshFn.addAttribute(attr); } } return fvLinearInterpolation; } PXR_NAMESPACE_CLOSE_SCOPE
35.754808
121
0.65396
[ "mesh", "object" ]
817e0fe3e7db9e0e737dc572dd6268fc009dbba9
8,408
cpp
C++
src/nemo/nemo_neuro_system/neurosynaptic_cores/NemoCoreScheduler.cpp
markplagge/NeMo2
36ec62acc8e4dc8f06ea1ced6997c587895cb6e9
[ "BSD-3-Clause" ]
null
null
null
src/nemo/nemo_neuro_system/neurosynaptic_cores/NemoCoreScheduler.cpp
markplagge/NeMo2
36ec62acc8e4dc8f06ea1ced6997c587895cb6e9
[ "BSD-3-Clause" ]
29
2020-05-29T16:22:16.000Z
2020-07-06T13:45:03.000Z
src/nemo/nemo_neuro_system/neurosynaptic_cores/NemoCoreScheduler.cpp
markplagge/NeMo2
36ec62acc8e4dc8f06ea1ced6997c587895cb6e9
[ "BSD-3-Clause" ]
1
2020-06-28T22:06:23.000Z
2020-06-28T22:06:23.000Z
// // Created by Mark Plagge on 6/18/20. // #include "NemoCoreScheduler.h" #include <json.hpp> namespace nemo { namespace neuro_system { void NemoCoreScheduler::forward_scheduler_event(tw_bf* bf, nemo::nemo_message* m, tw_lp* lp) { //Scheduler events are only once per global tick //first queue up next scheduler event static int did_init = 0; if (global_config->do_neuro_os) { //First schedule the next tick of the neuro_os_scheduler auto sched_time = JITTER(lp->rng) + 1; struct tw_event* os_tick = tw_event_new(lp->gid, sched_time, my_lp); nemo_message* msg = (nemo_message*)tw_event_data(os_tick); msg->message_type = NOS_TICK; msg->random_call_count = lp->rng->count; tw_event_send(os_tick); //update state this->current_neuro_tick = floor(tw_now(lp)); //Now run the scheduler iteration code which handles scheduling processes. scheduler_iteration(); }else if (!did_init){ did_init = 1; //no scheduler. Just run the model at position 0 auto model_file = model_files[0]; auto num_needed_cores = model_file.get_num_needed_cores(); for(int i = 0; i < num_needed_cores; i ++){ send_process_states(i, 0); } for (int i = 0; i < g_tw_ts_end; ++i) { send_input_spikes(0,i); } } //check the current list of processes: } void NemoCoreScheduler::send_process_states(int dest_core, int model_id){ auto model_file = model_files[model_id]; struct tw_event* set_state = tw_event_new(get_gid_from_core_local(dest_core,0),JITTER(my_lp->rng),my_lp); auto msg = (nemo_message*) tw_event_data(set_state); msg->message_type = NOS_LOAD_MODEL; msg->debug_time = tw_now(my_lp); msg->model_id = model_id; auto core_dat = model_files[model_id].get_core_settings(model_id); char * core_dat_s = const_cast<char*>(core_dat.c_str()); msg->update_message = core_dat_s; //memcpy(msg->update_message,core_dat_s,core_dat.size()); tw_event_send(set_state); } void NemoCoreScheduler::reverse_scheduler_event(tw_bf* bf, nemo::nemo_message* m, tw_lp* lp) { } void NemoCoreScheduler::set_task_list(const std::vector<nemo::config::ScheduledTask>& new_task_list) { for (const auto& task : new_task_list) { auto task_ptr = std::make_shared<nemo::config::ScheduledTask>(std::move(task)); task_list.push_back(task_ptr); } } void NemoCoreScheduler::init_process_models() { int model_counter = 0; auto l_task_list = global_config->scheduler_inputs; auto l_model_list = global_config->models; /** @todo: Could do this in parallel - if IO is not the bottleneck, but using modern json for the file parse is - Could also switch to RapidJSON */ /** @remark If time permits investigate OMP init or maybe switching to RAPIDJSON */ std::map<int, config::NemoModel> models; int max_models = -1; if (!global_config->do_neuro_os){ max_models = 1; } for (const auto& model : l_model_list) { /**@todo: handle unlimited runs */ if (max_models > 0 and max_models <= model_counter){ break; } bool does_model_have_known_runtime = true; auto model_id = model.id; models.emplace(model_id, model); if (model.model_file_path.length() != 0) { if (g_tw_mynode == 0) tw_printf(TW_LOC, "Loading Model #%i: %s \n", model_counter, model.model_file_path.c_str()); auto model_file = ModelFile(model.model_file_path); if (g_tw_mynode == 0) tw_printf(TW_LOC, "Loading Spike #%i: %s \n", model_counter, model.spike_file_path.c_str()); auto spike_file = SpikeFile(model.spike_file_path); model_files.push_back(model_file); spike_files.push_back(spike_file); } else { tw_printf(TW_LOC, "Loading benchmark model %s \n", model.benchmark_model_name.c_str()); ModelFile mf; SpikeFile sf; model_files.push_back(mf); spike_files.push_back(sf); } model_counter += 1; } this->set_models(models); this->set_task_list(l_task_list); int task_counter = 0; int max_start_time = 0; int run_time_ttl = 0; //queue up a message to test for end-times for (const auto& task : task_list) { task_counter += 1; auto start_time = task->start_time; auto task_id = task->task_id; auto proc = std::make_shared<neuro_os::sim_proc::SimProc>(); auto model = this->models[task_id]; proc->needed_cores = model.needed_cores; proc->PID = model.id; proc->needed_run_time = model.requested_time; proc->scheduled_start_time = start_time; process_queue.enqueue(proc); if (max_start_time < proc->scheduled_start_time) { max_start_time = proc->scheduled_start_time; } run_time_ttl += proc->needed_run_time; } std::cout << "Models loaded: " << model_counter << "\n" << task_counter << " tasks. \n"; auto sched_time = JITTER(my_lp->rng) + run_time_ttl + max_start_time; struct tw_event* os_tick = tw_event_new(my_lp->gid, sched_time, my_lp); nemo_message* msg = (nemo_message*)tw_event_data(os_tick); msg->message_type = NOS_STATUS; msg->debug_time = tw_now(my_lp); msg->random_call_count = my_lp->rng->count; tw_event_send(os_tick); } void NemoCoreScheduler::check_waiting_procs() { } void NemoCoreScheduler::set_models(const std::map<int, nemo::config::NemoModel>& models) { NemoCoreScheduler::models = models; } std::vector<std::shared_ptr<SimProcess>> NemoCoreScheduler::get_removable_processes() { auto assigned_processes = this->core_process_map.get_all_assigned_processes(); for (int i = 0; i < assigned_processes.size() ; ++i) { auto proc = assigned_processes[i]; if(proc->current_state == neuro_os::sim_proc::COMPLETE){ auto pid = proc->get_pid(); } } } int NemoCoreScheduler::remove_assigned_done_processes() { } void NemoCoreScheduler::scheduler_iteration(){ //1. set process queue time: this->process_queue.system_tick(); current_scheduler_time ++; //2. get_working_cores: auto working_cores = core_process_map.get_working_cores(); //3. get processes assigned to cores: auto assigned_procs = core_process_map.get_all_assigned_processes(); //4. Check each assigned process if it should be removed from assigned processes //(Process is completed then remove it, or if using some other scheduler system mark it too) } void NemoCoreScheduler::send_input_spikes(int model_id,double time_t) { auto time = floor(time_t); auto spike_r = spike_files[model_id].get_spikes_at_time(time); for (const auto& spk : spike_r) { auto dest = get_gid_from_core_local(spk.dest_core,spk.dest_axon); auto dest_t = JITTER(this->my_lp->rng) + spk.time; struct tw_event* os_input_spike_evt = tw_event_new(dest,dest_t,this->my_lp); nemo_message *msg = (nemo_message*) tw_event_data(os_input_spike_evt); msg->dest_axon = spk.dest_axon; msg->message_type = NEURON_SPIKE; //add random call count msg->intended_neuro_tick = spk.time; msg->source_core = -1; tw_event_send(os_input_spike_evt); } } void sched_core_init(NemoCoreScheduler* s, tw_lp* lp) { new (s) NemoCoreScheduler(); //Make sure we are running on PE 0 if (g_tw_mynode != 0) { tw_error(TW_LOC, "Neuromorphic scheduler core was init'ed from non 0 pe: PEID: %i", g_tw_mynode); } s->my_lp = lp; auto sched_time = JITTER(lp->rng) + 1; struct tw_event* os_tick = tw_event_new(lp->gid, sched_time, lp); auto* msg = (nemo_message*)tw_event_data(os_tick); msg->message_type = NOS_TICK; msg->debug_time = tw_now(lp); msg->random_call_count = lp->rng->count; tw_event_send(os_tick); s->init_process_models(); } void sched_pre_run(NemoCoreScheduler* s, tw_lp* lp) { } /** * on forward events call the parent class * @param s * @param bf * @param m * @param lp */ void sched_forward_event(NemoCoreScheduler* s, tw_bf* bf, nemo::nemo_message* m, tw_lp* lp) { s->forward_scheduler_event(bf, m, lp); } void sched_reverse_event(NemoCoreScheduler* s, tw_bf* bf, nemo::nemo_message* m, tw_lp* lp) { s->reverse_scheduler_event(bf, m, lp); } void sched_core_commit(NemoCoreScheduler* s, tw_bf* bf, nemo::nemo_message* m, tw_lp* lp) { s->core_commit(bf, m, lp); } void sched_core_finish(NemoCoreScheduler* s, tw_lp* lp) { s->core_finish(lp); } }// namespace neuro_system }// namespace nemo
34.600823
150
0.694933
[ "vector", "model" ]
817e8dddbc56f28955b7f1cd819ecc8c6fa9708c
1,387
cpp
C++
src/ivoc/graphvec.cpp
matz-e/nrn
8570e8e3814e7351e0b3884a150b758c27bb0dd7
[ "BSD-3-Clause" ]
1
2018-07-05T14:42:23.000Z
2018-07-05T14:42:23.000Z
src/ivoc/graphvec.cpp
matz-e/nrn
8570e8e3814e7351e0b3884a150b758c27bb0dd7
[ "BSD-3-Clause" ]
null
null
null
src/ivoc/graphvec.cpp
matz-e/nrn
8570e8e3814e7351e0b3884a150b758c27bb0dd7
[ "BSD-3-Clause" ]
null
null
null
#include <../../nrnconf.h> #if HAVE_IV // to end of file #define USEGNU 1 #include "graph.h" #include "ivoc.h" #if USEGNU #include "oc2iv.h" #include "ivocvect.h" extern "C" { extern Object** (*nrnpy_gui_helper_)(const char* name, Object* obj); extern double (*nrnpy_object_to_double_)(Object*); } Object** DataVec::new_vect(GLabel* gl) const { int i, cnt; Vect* vec; cnt = count(); vec = new Vect(cnt); for (i=0; i < cnt; ++i) { (*vec)[i] = get_val(i); } if (gl) { vec->label(gl->text()); } Object** obp = vec->temp_objvar(); hoc_obj_ref(*obp); return obp; } double gr_getline(void* v) { TRY_GUI_REDIRECT_ACTUAL_DOUBLE("Graph.getline", v); Graph* g = (Graph*)v; GlyphIndex i, cnt; cnt = g->count(); i = (int)chkarg(1, -1, cnt); if (i < 0 || i > cnt-1) { i = -1; } Vect* x = vector_arg(2); Vect* y = vector_arg(3); for (i += 1; i < cnt; ++i) { GraphItem* gi = (GraphItem*)g->component(i); if (gi->is_polyline()) { GPolyLine* gpl = (GPolyLine*)gi->body(); long size = gpl->x_data()->count(); x->resize(size); y->resize(size); for (long j=0; j < size; ++j) { x->elem(j) = gpl->x(j); y->elem(j) = gpl->y(j); } if (gpl->label()) { y->label(gpl->label()->text()); } return (double)i; } } return -1.; } #else void DataVec::new_vect(Object**, DataVec*) { hoc_execerror("No Vector class", 0); } #endif #endif
19
69
0.58111
[ "object", "vector" ]
818071abd7b98c1bfbe8ad7ac9a142dbf0eebba4
38,250
cpp
C++
libs/intrusive/test/unordered_multiset_test.cpp
Abce/boost
2d7491a27211aa5defab113f8e2d657c3d85ca93
[ "BSL-1.0" ]
null
null
null
libs/intrusive/test/unordered_multiset_test.cpp
Abce/boost
2d7491a27211aa5defab113f8e2d657c3d85ca93
[ "BSL-1.0" ]
null
null
null
libs/intrusive/test/unordered_multiset_test.cpp
Abce/boost
2d7491a27211aa5defab113f8e2d657c3d85ca93
[ "BSL-1.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // // (C) Copyright Olaf Krzikalla 2004-2006. // (C) Copyright Ion Gaztanaga 2006-2013. // // 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) // // See http://www.boost.org/libs/intrusive for documentation. // ///////////////////////////////////////////////////////////////////////////// #include <boost/intrusive/unordered_set.hpp> #include <boost/intrusive/pointer_traits.hpp> #include <boost/intrusive/detail/iterator.hpp> #include "itestvalue.hpp" #include "smart_ptr.hpp" #include "common_functors.hpp" #include <vector> #include <algorithm> //std::sort #include <set> #include <boost/detail/lightweight_test.hpp> #include "test_macros.hpp" #include "test_container.hpp" namespace boost { namespace intrusive { namespace test { #if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES) template<class T, class O1, class O2, class O3, class O4, class O5, class O6> #else template<class T, class ...Options> #endif struct is_unordered<boost::intrusive::unordered_multiset<T, #if !defined (BOOST_INTRUSIVE_VARIADIC_TEMPLATES) O1, O2, O3, O4, O5, O6 #else Options... #endif > > { static const bool value = true; }; }}} using namespace boost::intrusive; struct my_tag; template<class VoidPointer> struct hooks { typedef unordered_set_base_hook<void_pointer<VoidPointer> > base_hook_type; typedef unordered_set_base_hook < link_mode<auto_unlink> , void_pointer<VoidPointer> , tag<my_tag> , store_hash<true> > auto_base_hook_type; typedef unordered_set_member_hook < void_pointer<VoidPointer> , optimize_multikey<true> > member_hook_type; typedef unordered_set_member_hook < link_mode<auto_unlink>, void_pointer<VoidPointer> , store_hash<true> , optimize_multikey<true> > auto_member_hook_type; typedef nonhook_node_member< unordered_node_traits< VoidPointer, true, true >, unordered_algorithms > nonhook_node_member_type; }; static const std::size_t BucketSize = 8; template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> struct test_unordered_multiset { typedef typename ValueTraits::value_type value_type; static void test_all (std::vector<value_type>& values); static void test_sort(std::vector<value_type>& values); static void test_insert(std::vector<value_type>& values); static void test_swap(std::vector<value_type>& values); static void test_rehash(std::vector<value_type>& values, detail::true_); static void test_rehash(std::vector<value_type>& values, detail::false_); static void test_find(std::vector<value_type>& values); static void test_impl(); static void test_clone(std::vector<value_type>& values); }; template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>:: test_all (std::vector<typename ValueTraits::value_type>& values) { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset < value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; { typedef typename unordered_multiset_type::bucket_traits bucket_traits; typename unordered_multiset_type::bucket_type buckets [BucketSize]; unordered_multiset_type testset (bucket_traits(pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets[0]), BucketSize)); testset.insert(values.begin(), values.end()); test::test_container(testset); testset.clear(); testset.insert(values.begin(), values.end()); test::test_common_unordered_and_associative_container(testset, values); testset.clear(); testset.insert(values.begin(), values.end()); test::test_unordered_associative_container(testset, values); testset.clear(); testset.insert(values.begin(), values.end()); test::test_non_unique_container(testset, values); } test_sort(values); test_insert(values); test_swap(values); test_rehash(values, detail::bool_<Incremental>()); test_find(values); test_impl(); test_clone(values); } //test case due to an error in tree implementation: template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental> ::test_impl() { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset <value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; typedef typename unordered_multiset_type::bucket_traits bucket_traits; std::vector<value_type> values (5); for (int i = 0; i < 5; ++i) values[i].value_ = i; typename unordered_multiset_type::bucket_type buckets [BucketSize]; unordered_multiset_type testset(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets[0]), BucketSize)); for (int i = 0; i < 5; ++i) testset.insert (values[i]); testset.erase (testset.iterator_to (values[0])); testset.erase (testset.iterator_to (values[1])); testset.insert (values[1]); testset.erase (testset.iterator_to (values[2])); testset.erase (testset.iterator_to (values[3])); } //test: constructor, iterator, clear, reverse_iterator, front, back, size: template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental> ::test_sort(std::vector<typename ValueTraits::value_type>& values) { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset <value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; typedef typename unordered_multiset_type::bucket_traits bucket_traits; typename unordered_multiset_type::bucket_type buckets [BucketSize]; unordered_multiset_type testset1 (values.begin(), values.end(), bucket_traits (pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets[0]), BucketSize)); if(Incremental){ { int init_values [] = { 4, 5, 1, 2, 2, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } } else{ { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } } testset1.clear(); BOOST_TEST (testset1.empty()); } //test: insert, const_iterator, const_reverse_iterator, erase, iterator_to: template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental> ::test_insert(std::vector<typename ValueTraits::value_type>& values) { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset <value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; typedef typename unordered_multiset_type::bucket_traits bucket_traits; typedef typename unordered_multiset_type::iterator iterator; { typename unordered_multiset_type::bucket_type buckets [BucketSize]; unordered_multiset_type testset(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets[0]), BucketSize)); testset.insert(&values[0] + 2, &values[0] + 5); const unordered_multiset_type& const_testset = testset; if(Incremental){ { { int init_values [] = { 4, 5, 1 }; TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); } typename unordered_multiset_type::iterator i = testset.begin(); BOOST_TEST (i->value_ == 4); i = testset.insert (values[0]); BOOST_TEST (&*i == &values[0]); i = testset.iterator_to (values[2]); BOOST_TEST (&*i == &values[2]); testset.erase(i); { int init_values [] = { 5, 1, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); } testset.clear(); testset.insert(&values[0], &values[0] + values.size()); { int init_values [] = { 4, 5, 1, 2, 2, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); } BOOST_TEST (testset.erase(1) == 1); BOOST_TEST (testset.erase(2) == 2); BOOST_TEST (testset.erase(3) == 1); BOOST_TEST (testset.erase(4) == 1); BOOST_TEST (testset.erase(5) == 1); BOOST_TEST (testset.empty() == true); //Now with a single bucket typename unordered_multiset_type::bucket_type single_bucket[1]; unordered_multiset_type testset2(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(single_bucket[0]), 1)); testset2.insert(&values[0], &values[0] + values.size()); BOOST_TEST (testset2.erase(5) == 1); BOOST_TEST (testset2.erase(2) == 2); BOOST_TEST (testset2.erase(1) == 1); BOOST_TEST (testset2.erase(4) == 1); BOOST_TEST (testset2.erase(3) == 1); BOOST_TEST (testset2.empty() == true); } } else{ { { int init_values [] = { 1, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); } typename unordered_multiset_type::iterator i = testset.begin(); BOOST_TEST (i->value_ == 1); i = testset.insert (values[0]); BOOST_TEST (&*i == &values[0]); i = testset.iterator_to (values[2]); BOOST_TEST (&*i == &values[2]); testset.erase(i); { int init_values [] = { 1, 3, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); } testset.clear(); testset.insert(&values[0], &values[0] + values.size()); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); } BOOST_TEST (testset.erase(1) == 1); BOOST_TEST (testset.erase(2) == 2); BOOST_TEST (testset.erase(3) == 1); BOOST_TEST (testset.erase(4) == 1); BOOST_TEST (testset.erase(5) == 1); BOOST_TEST (testset.empty() == true); //Now with a single bucket typename unordered_multiset_type::bucket_type single_bucket[1]; unordered_multiset_type testset2(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(single_bucket[0]), 1)); testset2.insert(&values[0], &values[0] + values.size()); BOOST_TEST (testset2.erase(5) == 1); BOOST_TEST (testset2.erase(2) == 2); BOOST_TEST (testset2.erase(1) == 1); BOOST_TEST (testset2.erase(4) == 1); BOOST_TEST (testset2.erase(3) == 1); BOOST_TEST (testset2.empty() == true); } } { //Now erase just one per loop const int random_init[] = { 3, 2, 4, 1, 5, 2, 2 }; const unsigned int random_size = sizeof(random_init)/sizeof(random_init[0]); typename unordered_multiset_type::bucket_type single_bucket[1]; for(unsigned int i = 0, max = random_size; i != max; ++i){ std::vector<typename ValueTraits::value_type> data (random_size); for (unsigned int j = 0; j < random_size; ++j) data[j].value_ = random_init[j]; unordered_multiset_type testset_new(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(single_bucket[0]), 1)); testset_new.insert(&data[0], &data[0]+max); testset_new.erase(testset_new.iterator_to(data[i])); BOOST_TEST (testset_new.size() == (max -1)); } } } { typename unordered_multiset_type::bucket_type buckets [BucketSize]; const unsigned int NumBucketSize = BucketSize; const unsigned int LoadFactor = 3; const unsigned int NumIterations = NumBucketSize*LoadFactor; std::vector<value_type> random_init(NumIterations);//Preserve memory std::vector<value_type> set_tester; set_tester.reserve(NumIterations); //Initialize values for (unsigned int i = 0; i < NumIterations; ++i){ random_init[i].value_ = i*2;//(i/LoadFactor)*LoadFactor; } for(unsigned int initial_pos = 0; initial_pos != (NumIterations+1); ++initial_pos){ for(unsigned int final_pos = initial_pos; final_pos != (NumIterations+1); ++final_pos){ //Create intrusive container inserting values unordered_multiset_type testset ( &random_init[0] , &random_init[0] + random_init.size() , bucket_traits(pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets[0]), NumBucketSize)); BOOST_TEST (testset.size() == random_init.size()); //Obtain the iterator range to erase iterator it_beg_pos = testset.begin(); for(unsigned int it_beg_pos_num = 0; it_beg_pos_num != initial_pos; ++it_beg_pos_num){ ++it_beg_pos; } iterator it_end_pos(it_beg_pos); for(unsigned int it_end_pos_num = 0; it_end_pos_num != (final_pos - initial_pos); ++it_end_pos_num){ ++it_end_pos; } //Erase the same values in both the intrusive and original vector std::size_t erased_cnt = boost::intrusive::iterator_distance(it_beg_pos, it_end_pos); //Erase values from the intrusive container testset.erase(it_beg_pos, it_end_pos); BOOST_TEST (testset.size() == (random_init.size()-(final_pos - initial_pos))); //Now test... BOOST_TEST ((random_init.size() - erased_cnt) == testset.size()); //Create an ordered copy of the intrusive container set_tester.insert(set_tester.end(), testset.begin(), testset.end()); std::sort(set_tester.begin(), set_tester.end()); { typename std::vector<value_type>::iterator it = set_tester.begin(), itend = set_tester.end(); typename std::vector<value_type>::iterator random_init_it(random_init.begin()); for( ; it != itend; ++it){ while(!random_init_it->is_linked()) ++random_init_it; BOOST_TEST(*it == *random_init_it); ++random_init_it; } } set_tester.clear(); } } } } //test: insert (seq-version), swap, erase (seq-version), size: template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>:: test_swap(std::vector<typename ValueTraits::value_type>& values) { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset <value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; typedef typename unordered_multiset_type::bucket_traits bucket_traits; typename unordered_multiset_type::bucket_type buckets [BucketSize]; typename unordered_multiset_type::bucket_type buckets2 [BucketSize]; unordered_multiset_type testset1(&values[0], &values[0] + 2, bucket_traits(pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets[0]), BucketSize)); unordered_multiset_type testset2(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets2[0]), BucketSize)); testset2.insert (&values[0] + 2, &values[0] + 6); testset1.swap (testset2); if(Incremental){ { int init_values [] = { 4, 5, 1, 2 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } { int init_values [] = { 2, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset2.begin() ); } testset1.erase (testset1.iterator_to(values[4]), testset1.end()); BOOST_TEST (testset1.size() == 1); // BOOST_TEST (&testset1.front() == &values[3]); BOOST_TEST (&*testset1.begin() == &values[2]); } else{ { int init_values [] = { 1, 2, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } { int init_values [] = { 2, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset2.begin() ); } testset1.erase (testset1.iterator_to(values[5]), testset1.end()); BOOST_TEST (testset1.size() == 1); // BOOST_TEST (&testset1.front() == &values[3]); BOOST_TEST (&*testset1.begin() == &values[3]); } } //test: rehash: template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental> ::test_rehash(std::vector<typename ValueTraits::value_type>& values, detail::true_) { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset <value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; typedef typename unordered_multiset_type::bucket_traits bucket_traits; //Build a uset typename unordered_multiset_type::bucket_type buckets1 [BucketSize]; typename unordered_multiset_type::bucket_type buckets2 [BucketSize*2]; unordered_multiset_type testset1(&values[0], &values[0] + values.size(), bucket_traits(pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), BucketSize)); //Test current state BOOST_TEST(testset1.split_count() == BucketSize/2); { int init_values [] = { 4, 5, 1, 2, 2, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Incremental rehash step BOOST_TEST (testset1.incremental_rehash() == true); BOOST_TEST(testset1.split_count() == (BucketSize/2+1)); { int init_values [] = { 5, 1, 2, 2, 3, 4 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Rest of incremental rehashes should lead to the same sequence for(std::size_t split_bucket = testset1.split_count(); split_bucket != BucketSize; ++split_bucket){ BOOST_TEST (testset1.incremental_rehash() == true); BOOST_TEST(testset1.split_count() == (split_bucket+1)); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } } //This incremental rehash should fail because we've reached the end of the bucket array BOOST_TEST (testset1.incremental_rehash() == false); BOOST_TEST(testset1.split_count() == BucketSize); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } // //Try incremental hashing specifying a new bucket traits pointing to the same array // //This incremental rehash should fail because the new size is not twice the original BOOST_TEST(testset1.incremental_rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), BucketSize)) == false); BOOST_TEST(testset1.split_count() == BucketSize); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } // //Try incremental hashing specifying a new bucket traits pointing to the same array // //This incremental rehash should fail because the new size is not twice the original BOOST_TEST(testset1.incremental_rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets2[0]), BucketSize)) == false); BOOST_TEST(testset1.split_count() == BucketSize); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //This incremental rehash should success because the new size is twice the original //and split_count is the same as the old bucket count BOOST_TEST(testset1.incremental_rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets2[0]), BucketSize*2)) == true); BOOST_TEST(testset1.split_count() == BucketSize); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //This incremental rehash should also success because the new size is half the original //and split_count is the same as the new bucket count BOOST_TEST(testset1.incremental_rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), BucketSize)) == true); BOOST_TEST(testset1.split_count() == BucketSize); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Full shrink rehash testset1.rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), 4)); BOOST_TEST (testset1.size() == values.size()); BOOST_TEST (testset1.incremental_rehash() == false); { int init_values [] = { 4, 5, 1, 2, 2, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Full shrink rehash again testset1.rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), 2)); BOOST_TEST (testset1.size() == values.size()); BOOST_TEST (testset1.incremental_rehash() == false); { int init_values [] = { 2, 2, 4, 3, 5, 1 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Full growing rehash testset1.rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), BucketSize)); BOOST_TEST (testset1.size() == values.size()); BOOST_TEST (testset1.incremental_rehash() == false); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Incremental rehash shrinking //First incremental rehashes should lead to the same sequence for(std::size_t split_bucket = testset1.split_count(); split_bucket > 6; --split_bucket){ BOOST_TEST (testset1.incremental_rehash(false) == true); BOOST_TEST(testset1.split_count() == (split_bucket-1)); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } } //Incremental rehash step BOOST_TEST (testset1.incremental_rehash(false) == true); BOOST_TEST(testset1.split_count() == (BucketSize/2+1)); { int init_values [] = { 5, 1, 2, 2, 3, 4 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Incremental rehash step 2 BOOST_TEST (testset1.incremental_rehash(false) == true); BOOST_TEST(testset1.split_count() == (BucketSize/2)); { int init_values [] = { 4, 5, 1, 2, 2, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //This incremental rehash should fail because we've reached the half of the bucket array BOOST_TEST(testset1.incremental_rehash(false) == false); BOOST_TEST(testset1.split_count() == BucketSize/2); { int init_values [] = { 4, 5, 1, 2, 2, 3 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } } template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental> ::test_rehash(std::vector<typename ValueTraits::value_type>& values, detail::false_) { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset <value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; typedef typename unordered_multiset_type::bucket_traits bucket_traits; typename unordered_multiset_type::bucket_type buckets1 [BucketSize]; typename unordered_multiset_type::bucket_type buckets2 [2]; typename unordered_multiset_type::bucket_type buckets3 [BucketSize*2]; unordered_multiset_type testset1(&values[0], &values[0] + 6, bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), BucketSize)); BOOST_TEST (testset1.size() == values.size()); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } testset1.rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets2[0]), 2)); BOOST_TEST (testset1.size() == values.size()); { int init_values [] = { 4, 2, 2, 5, 3, 1 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } testset1.rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets3[0]), BucketSize*2)); BOOST_TEST (testset1.size() == values.size()); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Now rehash reducing the buckets testset1.rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets3[0]), 2)); BOOST_TEST (testset1.size() == values.size()); { int init_values [] = { 4, 2, 2, 5, 3, 1 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } //Now rehash increasing the buckets testset1.rehash(bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets3[0]), BucketSize*2)); BOOST_TEST (testset1.size() == values.size()); { int init_values [] = { 1, 2, 2, 3, 4, 5 }; TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); } } //test: find, equal_range (lower_bound, upper_bound): template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental>:: test_find(std::vector<typename ValueTraits::value_type>& values) { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset <value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; typedef typename unordered_multiset_type::bucket_traits bucket_traits; typename unordered_multiset_type::bucket_type buckets[BucketSize]; unordered_multiset_type testset(values.begin(), values.end(), bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets[0]), BucketSize)); typedef typename unordered_multiset_type::iterator iterator; value_type cmp_val; cmp_val.value_ = 2; iterator i = testset.find (cmp_val); BOOST_TEST (i->value_ == 2); BOOST_TEST ((++i)->value_ == 2); std::pair<iterator,iterator> range = testset.equal_range (cmp_val); BOOST_TEST (range.first->value_ == 2); BOOST_TEST (range.second->value_ == 3); BOOST_TEST (boost::intrusive::iterator_distance (range.first, range.second) == 2); cmp_val.value_ = 7; BOOST_TEST (testset.find (cmp_val) == testset.end()); } template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental> void test_unordered_multiset<ValueTraits, CacheBegin, CompareHash, Incremental> ::test_clone(std::vector<typename ValueTraits::value_type>& values) { typedef typename ValueTraits::value_type value_type; typedef unordered_multiset <value_type , value_traits<ValueTraits> , constant_time_size<value_type::constant_time_size> , cache_begin<CacheBegin> , compare_hash<CompareHash> , incremental<Incremental> > unordered_multiset_type; typedef typename unordered_multiset_type::bucket_traits bucket_traits; { //Test with equal bucket arrays typename unordered_multiset_type::bucket_type buckets1 [BucketSize]; typename unordered_multiset_type::bucket_type buckets2 [BucketSize]; unordered_multiset_type testset1 (values.begin(), values.end(), bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), BucketSize)); unordered_multiset_type testset2 (bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets2[0]), BucketSize)); testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>()); //Ordering is not guarantee in the cloning so insert data in a set and test std::multiset<typename ValueTraits::value_type> src(testset1.begin(), testset1.end()); std::multiset<typename ValueTraits::value_type> dst(testset2.begin(), testset2.end()); BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin())); testset2.clear_and_dispose(test::delete_disposer<value_type>()); BOOST_TEST (testset2.empty()); } { //Test with bigger source bucket arrays typename unordered_multiset_type::bucket_type buckets1 [BucketSize*2]; typename unordered_multiset_type::bucket_type buckets2 [BucketSize]; unordered_multiset_type testset1 (values.begin(), values.end(), bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), BucketSize*2)); unordered_multiset_type testset2 (bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets2[0]), BucketSize)); testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>()); //Ordering is not guarantee in the cloning so insert data in a set and test std::multiset<typename ValueTraits::value_type> src(testset1.begin(), testset1.end()); std::multiset<typename ValueTraits::value_type> dst(testset2.begin(), testset2.end()); BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin())); testset2.clear_and_dispose(test::delete_disposer<value_type>()); BOOST_TEST (testset2.empty()); } { //Test with smaller source bucket arrays typename unordered_multiset_type::bucket_type buckets1 [BucketSize]; typename unordered_multiset_type::bucket_type buckets2 [BucketSize*2]; unordered_multiset_type testset1 (values.begin(), values.end(), bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets1[0]), BucketSize)); unordered_multiset_type testset2 (bucket_traits( pointer_traits<typename unordered_multiset_type::bucket_ptr>:: pointer_to(buckets2[0]), BucketSize*2)); testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>()); //Ordering is not guaranteed in the cloning so insert data in a set and test std::multiset<typename ValueTraits::value_type> src(testset1.begin(), testset1.end()); std::multiset<typename ValueTraits::value_type> dst(testset2.begin(), testset2.end()); BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin())); testset2.clear_and_dispose(test::delete_disposer<value_type>()); BOOST_TEST (testset2.empty()); } } template<class VoidPointer, bool constant_time_size, bool Incremental> class test_main_template { public: int operator()() { typedef testvalue<hooks<VoidPointer> , constant_time_size> value_type; static const int random_init[6] = { 3, 2, 4, 1, 5, 2 }; std::vector<testvalue<hooks<VoidPointer> , constant_time_size> > data (6); for (int i = 0; i < 6; ++i) data[i].value_ = random_init[i]; test_unordered_multiset < typename detail::get_base_value_traits < value_type , typename hooks<VoidPointer>::base_hook_type >::type , true , false , Incremental >::test_all(data); test_unordered_multiset < typename detail::get_member_value_traits < member_hook< value_type , typename hooks<VoidPointer>::member_hook_type , &value_type::node_ > >::type , false , false , Incremental >::test_all(data); test_unordered_multiset < nonhook_node_member_value_traits< value_type, typename hooks<VoidPointer>::nonhook_node_member_type, &value_type::nhn_member_, safe_link >, false, false, Incremental >::test_all(data); return 0; } }; template<class VoidPointer, bool Incremental> class test_main_template<VoidPointer, false, Incremental> { public: int operator()() { typedef testvalue<hooks<VoidPointer> , false> value_type; static const int random_init[6] = { 3, 2, 4, 1, 5, 2 }; std::vector<testvalue<hooks<VoidPointer> , false> > data (6); for (int i = 0; i < 6; ++i) data[i].value_ = random_init[i]; test_unordered_multiset < typename detail::get_base_value_traits < value_type , typename hooks<VoidPointer>::base_hook_type >::type , false , false , Incremental >::test_all(data); test_unordered_multiset < typename detail::get_member_value_traits < member_hook< value_type , typename hooks<VoidPointer>::member_hook_type , &value_type::node_ > >::type , true , false , Incremental >::test_all(data); test_unordered_multiset < typename detail::get_base_value_traits < value_type , typename hooks<VoidPointer>::auto_base_hook_type >::type , false , false , Incremental >::test_all(data); test_unordered_multiset < typename detail::get_member_value_traits < member_hook< value_type , typename hooks<VoidPointer>::auto_member_hook_type , &value_type::auto_node_ > >::type , false , true , Incremental >::test_all(data); return 0; } }; int main() { test_main_template<void*, false, true>()(); test_main_template<smart_ptr<void>, false, true>()(); test_main_template<void*, true, true>()(); test_main_template<smart_ptr<void>, true, true>()(); test_main_template<void*, false, false>()(); test_main_template<smart_ptr<void>, false, false>()(); test_main_template<void*, true, true>()(); test_main_template<smart_ptr<void>, true, false>()(); return boost::report_errors(); }
43.814433
121
0.633203
[ "vector" ]
8182ad8f54c0b9709df0199bb5a03c5f0df0bed1
9,129
cpp
C++
core/channel/async_push_channel_unittest.cpp
OwenDeng1993/Husky
61ba0e8fc2a0ab025e89307de07a1c6833227857
[ "Apache-2.0" ]
117
2016-08-31T04:05:08.000Z
2021-12-18T15:05:38.000Z
core/channel/async_push_channel_unittest.cpp
OwenDeng1993/Husky
61ba0e8fc2a0ab025e89307de07a1c6833227857
[ "Apache-2.0" ]
223
2016-09-12T05:32:44.000Z
2020-05-22T02:51:21.000Z
core/channel/async_push_channel_unittest.cpp
OwenDeng1993/Husky
61ba0e8fc2a0ab025e89307de07a1c6833227857
[ "Apache-2.0" ]
77
2016-08-31T04:02:57.000Z
2020-04-08T09:23:46.000Z
#include "core/channel/async_push_channel.hpp" #include <string> #include <thread> #include <vector> #include "gtest/gtest.h" #include "base/log.hpp" #include "base/serialization.hpp" #include "core/channel/migrate_channel.hpp" #include "core/hash_ring.hpp" #include "core/mailbox.hpp" #include "core/objlist.hpp" #include "core/worker_info.hpp" namespace husky { namespace { class TestAsyncPushChannel : public testing::Test { public: TestAsyncPushChannel() {} ~TestAsyncPushChannel() {} protected: void SetUp() {} void TearDown() {} }; class Obj { public: using KeyT = int; KeyT key; const KeyT& id() const { return key; } Obj() {} explicit Obj(const KeyT& k) : key(k) {} }; // Create AsyncPushChannel without setting template <typename MsgT, typename DstObjT> AsyncPushChannel<MsgT, DstObjT> create_async_push_channel(ObjList<DstObjT>& obj_list) { AsyncPushChannel<MsgT, DstObjT> async_push_channel(&obj_list); return async_push_channel; } // Create MigrateChannel without setting template <typename ObjT> MigrateChannel<ObjT> create_migrate_channel(ObjList<ObjT>& src_list, ObjList<ObjT>& dst_list) { MigrateChannel<ObjT> migrate_channel(&src_list, &dst_list); return migrate_channel; } TEST_F(TestAsyncPushChannel, Create) { // Mailbox Setup zmq::context_t zmq_context; MailboxEventLoop el(&zmq_context); el.set_process_id(0); CentralRecver recver(&zmq_context, "inproc://test"); LocalMailbox mailbox(&zmq_context); mailbox.set_thread_id(0); el.register_mailbox(mailbox); // WorkerInfo Setup WorkerInfo workerinfo; workerinfo.add_worker(0, 0, 0); workerinfo.set_process_id(0); // ObjList Setup ObjList<Obj> obj_list; // PushChannel auto async_push_channel = create_async_push_channel<int>(obj_list); async_push_channel.setup(0, 0, workerinfo, &mailbox); } TEST_F(TestAsyncPushChannel, PushSingle) { // Mailbox Setup zmq::context_t zmq_context; MailboxEventLoop el(&zmq_context); el.set_process_id(0); CentralRecver recver(&zmq_context, "inproc://test"); LocalMailbox mailbox(&zmq_context); mailbox.set_thread_id(0); el.register_mailbox(mailbox); // WorkerInfo Setup WorkerInfo workerinfo; workerinfo.add_worker(0, 0, 0); workerinfo.set_process_id(0); // ObjList Setup ObjList<Obj> obj_list; // PushChannel auto async_push_channel = create_async_push_channel<int>(obj_list); async_push_channel.setup(0, 0, workerinfo, &mailbox); // push async_push_channel.push(123, 10); // send 123 to 10 async_push_channel.out(); // get async_push_channel.prepare_messages_test(); Obj& obj = obj_list.get_data()[0]; EXPECT_EQ(obj.id(), 10); auto msgs = async_push_channel.get(obj); EXPECT_EQ(msgs.size(), 1); EXPECT_EQ(msgs[0], 123); } TEST_F(TestAsyncPushChannel, PushMultipleTime) { // Mailbox Setup zmq::context_t zmq_context; MailboxEventLoop el(&zmq_context); el.set_process_id(0); CentralRecver recver(&zmq_context, "inproc://test"); LocalMailbox mailbox(&zmq_context); mailbox.set_thread_id(0); el.register_mailbox(mailbox); // ObjList Setup ObjList<Obj> obj_list; // WorkerInfo Setup WorkerInfo workerinfo; workerinfo.add_worker(0, 0, 0); workerinfo.set_process_id(0); // PushChannel auto async_push_channel = create_async_push_channel<int>(obj_list); async_push_channel.setup(0, 0, workerinfo, &mailbox); // push to two dst async_push_channel.push(123, 10); // send 123 to 10 async_push_channel.push(32, 3); async_push_channel.push(4, 10); async_push_channel.push(532, 3); async_push_channel.push(56, 10); async_push_channel.out(); // get while (1) { if (mailbox.poll_non_block(async_push_channel.get_channel_id(), async_push_channel.get_progress())) { auto bin = mailbox.recv(async_push_channel.get_channel_id(), async_push_channel.get_progress()); async_push_channel.in(bin); } int count = 0; for (auto& obj : obj_list.get_data()) for (auto& msg : async_push_channel.get(obj)) count += 1; if (count == 5) // Total 5 msgs break; } EXPECT_EQ(obj_list.get_size(), 2); } TEST_F(TestAsyncPushChannel, IncProgress) { // Mailbox Setup zmq::context_t zmq_context; MailboxEventLoop el(&zmq_context); el.set_process_id(0); CentralRecver recver(&zmq_context, "inproc://test"); LocalMailbox mailbox(&zmq_context); mailbox.set_thread_id(0); el.register_mailbox(mailbox); // WorkerInfo Setup WorkerInfo workerinfo; workerinfo.add_worker(0, 0, 0); workerinfo.set_process_id(0); // ObjList Setup ObjList<Obj> obj_list; // PushChannel // Round 1 auto async_push_channel = create_async_push_channel<int>(obj_list); async_push_channel.setup(0, 0, workerinfo, &mailbox); // push async_push_channel.push(123, 10); // send 123 to 10 async_push_channel.out(); // get async_push_channel.prepare_messages_test(); Obj& obj = obj_list.get_data()[0]; EXPECT_EQ(obj.id(), 10); auto msgs = async_push_channel.get(obj); EXPECT_EQ(msgs.size(), 1); EXPECT_EQ(msgs[0], 123); // Round 2 async_push_channel.push(456, 10); // send 123 to 10 async_push_channel.out(); async_push_channel.prepare_messages_test(); EXPECT_EQ(obj.id(), 10); msgs = async_push_channel.get(obj); EXPECT_EQ(msgs.size(), 1); EXPECT_EQ(msgs[0], 456); } TEST_F(TestAsyncPushChannel, MultiThread) { // Mailbox Setup zmq::context_t zmq_context; MailboxEventLoop el(&zmq_context); el.set_process_id(0); CentralRecver recver(&zmq_context, "inproc://test"); // Mailbox_0 LocalMailbox mailbox_0(&zmq_context); mailbox_0.set_thread_id(0); el.register_mailbox(mailbox_0); // Mailbox_1 LocalMailbox mailbox_1(&zmq_context); mailbox_1.set_thread_id(1); el.register_mailbox(mailbox_1); // WorkerInfo Setup WorkerInfo workerinfo; workerinfo.add_worker(0, 0, 0); workerinfo.add_worker(0, 1, 1); workerinfo.set_process_id(0); std::thread th1 = std::thread([&]() { ObjList<Obj> obj_list; obj_list.add_object(Obj(100)); obj_list.add_object(Obj(18)); obj_list.add_object(Obj(57)); // Globalize auto migrate_channel = create_migrate_channel(obj_list, obj_list); migrate_channel.setup(0, 0, workerinfo, &mailbox_0); for (auto& obj : obj_list.get_data()) { int dst_thread_id = workerinfo.get_hash_ring().hash_lookup(obj.id()); if (dst_thread_id != 0) { migrate_channel.migrate(obj, dst_thread_id); } } obj_list.deletion_finalize(); migrate_channel.out(); migrate_channel.prepare_immigrants(); obj_list.sort(); // Push auto async_push_channel = create_async_push_channel<int>(obj_list); async_push_channel.setup(0, 0, workerinfo, &mailbox_0); async_push_channel.push(123, 1); async_push_channel.push(123, 1342148); async_push_channel.push(123, 5); async_push_channel.push(123, 100); async_push_channel.push(123, 18); async_push_channel.push(123, 57); async_push_channel.out(); async_push_channel.prepare_messages_test(); for (auto& obj : obj_list.get_data()) { auto& msgs = async_push_channel.get(obj); EXPECT_EQ(msgs.size(), 2); } }); std::thread th2 = std::thread([&]() { ObjList<Obj> obj_list; obj_list.add_object(Obj(1)); obj_list.add_object(Obj(1342148)); obj_list.add_object(Obj(5)); // GLobalize auto migrate_channel = create_migrate_channel(obj_list, obj_list); migrate_channel.setup(1, 1, workerinfo, &mailbox_1); for (auto& obj : obj_list.get_data()) { int dst_thread_id = workerinfo.get_hash_ring().hash_lookup(obj.id()); if (dst_thread_id != 1) { migrate_channel.migrate(obj, dst_thread_id); } } obj_list.deletion_finalize(); migrate_channel.out(); migrate_channel.prepare_immigrants(); obj_list.sort(); // Push auto async_push_channel = create_async_push_channel<int>(obj_list); async_push_channel.setup(1, 1, workerinfo, &mailbox_1); async_push_channel.push(123, 1); async_push_channel.push(123, 1342148); async_push_channel.push(123, 5); async_push_channel.push(123, 100); async_push_channel.push(123, 18); async_push_channel.push(123, 57); async_push_channel.out(); async_push_channel.prepare_messages_test(); for (auto& obj : obj_list.get_data()) { auto& msgs = async_push_channel.get(obj); EXPECT_EQ(msgs.size(), 2); } }); th1.join(); th2.join(); } } // namespace } // namespace husky
29.931148
109
0.660751
[ "vector" ]
81849120ad63bb97ffdda8f49a3a2dabd5739cb3
1,323
cpp
C++
CToC++/CToC++/Tools/TestTool.cpp
UCliwenbin/AlgorithmCPP
3cb4a6a9510682b5d4dc956826d263ab778a2a00
[ "MIT" ]
1
2021-02-25T08:00:43.000Z
2021-02-25T08:00:43.000Z
CToC++/CToC++/Tools/TestTool.cpp
UCliwenbin/AlgorithmCPP
3cb4a6a9510682b5d4dc956826d263ab778a2a00
[ "MIT" ]
null
null
null
CToC++/CToC++/Tools/TestTool.cpp
UCliwenbin/AlgorithmCPP
3cb4a6a9510682b5d4dc956826d263ab778a2a00
[ "MIT" ]
null
null
null
// // TestTool.cpp // CToC++ // // Created by mac on 2020/4/22. // Copyright © 2020 lwb. All rights reserved. // #include "TestTool.hpp" #include <ctime> #include <sys/timeb.h> #include <memory> //计算算法执行时间的程序 void testAlgorithm(ExecuteAlgorithm method) { struct timeb startTime , endTime; ftime(&startTime); method(); ftime(&endTime); cout << "算法执行时间:" << (endTime.time-startTime.time)*1000 + (endTime.millitm - startTime.millitm) << "毫秒" << endl; } //随机生成K个数据的数组(0~1000) void generateRandArray(vector<int> &arr,int k,int maxValue) { cout<<"数据样本为:"<<endl; for (int i = 0; i < k; i++) { int value = rand()%maxValue; cout<<value<<' '; arr.push_back(value); } cout<<endl; } void splitString(string& s, vector<string>& v,string& c) { string::size_type pos1, pos2; pos2 = s.find(c); pos1 = 0; while(string::npos != pos2) { v.push_back(s.substr(pos1, pos2-pos1)); pos1 = pos2 + c.size(); pos2 = s.find(c, pos1); } if(pos1 != s.length()) v.push_back(s.substr(pos1)); } void printFormateMatrix(vector<vector<int>> &matrix) { for (int i = 0; i < matrix.size(); i++) { for (int j = 0; j < matrix[0].size(); j++) { cout<<matrix[i][j]<<" "; } cout<<endl; } }
23.210526
116
0.56387
[ "vector" ]
818c22f0dbe7eaa8f7163a7488773277e483fb5e
6,646
cpp
C++
src/demos/multicore/demo_MCORE_friction.cpp
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
1,383
2015-02-04T14:17:40.000Z
2022-03-30T04:58:16.000Z
src/demos/multicore/demo_MCORE_friction.cpp
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
245
2015-01-11T15:30:51.000Z
2022-03-30T21:28:54.000Z
src/demos/multicore/demo_MCORE_friction.cpp
Benatti1991/chrono
d927a7fae8ed2f4e6695cacaef28c605fcd9ffaf
[ "BSD-3-Clause" ]
351
2015-02-04T14:17:47.000Z
2022-03-30T04:42:52.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban, Victor Bertolazzo // ============================================================================= // // Chrono::Multicore test program using NSC method for rolling frictional contact. // // The global reference frame has Z up. // // ============================================================================= #include "chrono/ChConfig.h" #include "chrono/utils/ChUtilsCreators.h" #include "chrono_multicore/physics/ChSystemMulticore.h" #include "chrono_multicore/solver/ChIterativeSolverMulticore.h" #include "chrono_opengl/ChOpenGLWindow.h" using namespace chrono; using namespace chrono::collision; // -------------------------------------------------------------------------- int main(int argc, char** argv) { GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n"; // Parameters double radius = 0.5; double time_step = 0.01; uint max_iteration_normal = 0; uint max_iteration_sliding = 0; uint max_iteration_spinning = 100; uint max_iteration_bilateral = 0; // Create the multicore system ChSystemMulticoreNSC system; system.Set_G_acc(ChVector<>(0, -9.81, 0)); // Set number of threads system.SetNumThreads(1); // Set solver settings system.ChangeSolverType(SolverType::APGD); system.GetSettings()->solver.solver_mode = SolverMode::SPINNING; system.GetSettings()->solver.max_iteration_normal = max_iteration_normal; system.GetSettings()->solver.max_iteration_sliding = max_iteration_sliding; system.GetSettings()->solver.max_iteration_spinning = max_iteration_spinning; system.GetSettings()->solver.max_iteration_bilateral = max_iteration_bilateral; system.GetSettings()->solver.alpha = 0; system.GetSettings()->solver.contact_recovery_speed = 1e32; system.GetSettings()->solver.use_full_inertia_tensor = false; system.GetSettings()->solver.tolerance = 0; system.GetSettings()->collision.collision_envelope = 0.1 * radius; system.GetSettings()->collision.narrowphase_algorithm = ChNarrowphase::Algorithm::HYBRID; system.GetSettings()->collision.bins_per_axis = vec3(10, 10, 10); // Create the container body auto container = std::shared_ptr<ChBody>(system.NewBody()); system.Add(container); container->SetPos(ChVector<>(0, 0, 0)); container->SetBodyFixed(true); container->SetIdentifier(-1); container->SetCollide(true); // Set rolling and friction coefficients for the container. // By default, the composite material will use the minimum value for an interacting collision pair. auto bin_mat = chrono_types::make_shared<ChMaterialSurfaceNSC>(); bin_mat->SetFriction(0.6f); bin_mat->SetRollingFriction(1); bin_mat->SetSpinningFriction(1); container->GetCollisionModel()->ClearModel(); utils::AddBoxGeometry(container.get(), bin_mat, ChVector<>(20, 1, 20) / 2.0, ChVector<>(0, -1, 0)); utils::AddBoxGeometry(container.get(), bin_mat, ChVector<>(1, 2, 20.99) / 2.0, ChVector<>(-10, 0, 0)); utils::AddBoxGeometry(container.get(), bin_mat, ChVector<>(1, 2, 20.99) / 2.0, ChVector<>(10, 0, 0)); utils::AddBoxGeometry(container.get(), bin_mat, ChVector<>(20.99, 2, 1) / 2.0, ChVector<>(0, 0, -10)); utils::AddBoxGeometry(container.get(), bin_mat, ChVector<>(20.99, 2, 1) / 2.0, ChVector<>(0, 0, 10)); container->GetCollisionModel()->BuildModel(); // Create some spheres that roll horizontally, with increasing rolling friction values double density = 1000; double mass = density * (4.0 / 3.0) * CH_C_PI * pow(radius, 3); double inertia = (2.0 / 5.0) * mass * pow(radius, 2); double initial_angspeed = 10; double initial_linspeed = initial_angspeed * radius; for (int bi = 0; bi < 10; bi++) { auto mat = chrono_types::make_shared<ChMaterialSurfaceNSC>(); mat->SetFriction(0.4f); mat->SetRollingFriction(((float)bi / 10) * 0.05f); auto ball = std::shared_ptr<ChBody>(system.NewBody()); ball->SetIdentifier(bi); ball->SetMass(mass); ball->SetInertiaXX(ChVector<>(inertia)); // Initial position and velocity ball->SetPos(ChVector<>(-7, radius - 0.5, -5 + bi * radius * 2.5)); ball->SetPos_dt(ChVector<>(initial_linspeed, 0, 0)); ball->SetWvel_par(ChVector<>(0, 0, -initial_angspeed)); // Contact geometry ball->SetCollide(true); ball->GetCollisionModel()->ClearModel(); utils::AddSphereGeometry(ball.get(), mat, radius); ball->GetCollisionModel()->BuildModel(); // Add to the system system.Add(ball); } // Create some spheres that spin in place, with increasing spinning friction values for (int bi = 0; bi < 10; bi++) { auto mat = chrono_types::make_shared<ChMaterialSurfaceNSC>(); mat->SetFriction(0.4f); mat->SetSpinningFriction(((float)bi / 10) * 0.02f); auto ball = std::shared_ptr<ChBody>(system.NewBody()); ball->SetIdentifier(bi); ball->SetMass(mass); ball->SetInertiaXX(ChVector<>(inertia)); // Initial position and velocity ball->SetPos(ChVector<>(-8, 1 + radius - 0.5, -5 + bi * radius * 2.5)); ball->SetPos_dt(ChVector<>(0, 0, 0)); ball->SetWvel_par(ChVector<>(0, 20, 0)); // Contact geometry ball->SetCollide(true); ball->GetCollisionModel()->ClearModel(); utils::AddSphereGeometry(ball.get(), mat, radius); ball->GetCollisionModel()->BuildModel(); // Add to the system system.Add(ball); } // Create the visualization window opengl::ChOpenGLWindow& gl_window = opengl::ChOpenGLWindow::getInstance(); gl_window.Initialize(1280, 720, "Settling test", &system); gl_window.SetCamera(ChVector<>(10, 10, 20), ChVector<>(0, 0, 0), ChVector<>(0, 1, 0), 0.05f); gl_window.SetRenderMode(opengl::WIREFRAME); // Simulate system while (gl_window.Active()) { system.DoStepDynamics(time_step); gl_window.Render(); ////std::cout << "num contacts: " << system.GetNcontacts() << "\n\n"; } return 0; }
39.796407
106
0.626994
[ "geometry", "render" ]