hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
40aa23d314b53734894c6c1d441a15e4f1712af5
1,290
hpp
C++
libs/core/include/fcppt/container/find_opt_iterator.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/container/find_opt_iterator.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/container/find_opt_iterator.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_CONTAINER_FIND_OPT_ITERATOR_HPP_INCLUDED #define FCPPT_CONTAINER_FIND_OPT_ITERATOR_HPP_INCLUDED #include <fcppt/container/to_iterator_type.hpp> #include <fcppt/optional/object_impl.hpp> namespace fcppt { namespace container { /** \brief Returns an iterator from a find operation or an empty optional. Searches for \a _key in the associative container \a _container. If \a _key is found, its iterator is returned. Otherwise, the empty optional is returned. \ingroup fcpptcontainer \tparam Container Must be an associative container. \tparam Key Must be a key that can be searched for. */ template< typename Container, typename Key > fcppt::optional::object< fcppt::container::to_iterator_type< Container > > find_opt_iterator( Container &_container, Key const &_key ) { auto const it( _container.find( _key ) ); typedef fcppt::optional::object< fcppt::container::to_iterator_type< Container > > result_type; return it != _container.end() ? result_type( it ) : result_type() ; } } } #endif
16.973684
78
0.727132
pmiddend
40ac7c0d929478f10e0c34c5f3f4ae75897ec363
2,894
cpp
C++
platformio/ethernet_client/src/main.cpp
amdxyz/aiolib
90d6541b0945680d61d070109f8bcc468902af38
[ "MIT" ]
1
2020-05-24T10:33:14.000Z
2020-05-24T10:33:14.000Z
platformio/ethernet_client/src/main.cpp
amdxyz/aiolib
90d6541b0945680d61d070109f8bcc468902af38
[ "MIT" ]
1
2019-02-20T19:33:08.000Z
2019-02-20T19:36:19.000Z
platformio/ethernet_client/src/main.cpp
amdx/aiolib
90d6541b0945680d61d070109f8bcc468902af38
[ "MIT" ]
null
null
null
/** * AMDX AIO arduino library * * Copyright (C) 2019-2020 Archimedes Exhibitions GmbH * All rights reserved. * * MIT License * * 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. */ // Tests the onboard W5500 ethernet controller on the AIO XL #include <Arduino.h> #include <Ethernet.h> #include <AIO.h> using namespace AIO; const uint8_t MAX_CHUNK_SIZE = 128; uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; EthernetClient client; void fetch_page(const char* host) { uint8_t chunk[MAX_CHUNK_SIZE]; Serial.print(F(">>> Connecting to: ")); Serial.println(host); if (client.connect(host, 80)) { client.write("HEAD / HTTP/1.1\nHost:"); client.write(host); client.write("\nConnection: close\n\n"); Serial.println(F(">>> Retrieving data:")); while (1) { int length = client.read(chunk, MAX_CHUNK_SIZE); if (length > 0) { Serial.write(chunk, length); } else if (!client.connected()) { Serial.println(); Serial.println(F(">>> Head fetched")); break; } } } else { Serial.println(F("*** Cannot connect to the remote end")); } } void setup() { // Open serial communications and wait for port to open: Serial.begin(115200); Serial.print(F("Initializing..")); Ethernet.init(ETH_CS_PIN); Ethernet.begin(mac, IPAddress(0, 0, 0, 0)); Serial.println("done."); Serial.print(F("Waiting for link..")); while (Ethernet.linkStatus() != LinkON) { delay(500); Serial.print("."); } Serial.println(F("link is up.")); Serial.print(F("Requesting IP via DHCP..")); // Initialize the ethernet library Ethernet.begin(mac); Serial.println(F("done.")); fetch_page("www.google.com"); } void loop() { }
28.94
93
0.651348
amdxyz
40afa021be7ce8ce58c26ee44ba6500f1a43ba20
1,034
cpp
C++
DISCSHOP.cpp
Yash1256/Codechef-Solutions
8aa93379ba543fdcf82b3b1f94d71f6f698b6161
[ "MIT" ]
1
2020-04-30T10:43:16.000Z
2020-04-30T10:43:16.000Z
DISCSHOP.cpp
Yash1256/Codechef-Solutions
8aa93379ba543fdcf82b3b1f94d71f6f698b6161
[ "MIT" ]
null
null
null
DISCSHOP.cpp
Yash1256/Codechef-Solutions
8aa93379ba543fdcf82b3b1f94d71f6f698b6161
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fastio \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0); #define pb push_back #define ll long long #define mp make_pair #define f first #define s second #define tc \ int t = 1; \ cin >> t; \ while (t--) using namespace std; void solve(int N) { int no_of_digits = floor(log10(N) + 1) - 1; int mini = N % (int)pow(10, no_of_digits); int num = mini, i = 0; while (1) { int left_limit = floor(N / pow(10, no_of_digits - i)); //cout<<"left_limit"<<left_limit<<endl; num = num % (int)pow(10, no_of_digits - i - 1); int req_num = left_limit * pow(10, no_of_digits - 1 - i) + num; i += 1; //cout<<mini<<" "<<req_num<<endl; mini = (mini < req_num) ? mini : req_num; if (i == no_of_digits) break; } cout << mini << endl; } int main() { fastio; tc { int N; cin >> N; solve(N); } return 0; }
22.478261
71
0.501934
Yash1256
40b2611eae038d213c5ccfa342d44e5e7b9e2868
593
cpp
C++
MoravaEngine/src/H2M/Core/HashH2M.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
null
null
null
MoravaEngine/src/H2M/Core/HashH2M.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
null
null
null
MoravaEngine/src/H2M/Core/HashH2M.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
1
2022-01-05T03:51:02.000Z
2022-01-05T03:51:02.000Z
/** * @package H2M (Hazel to Morava) * @author Yan Chernikov (TheCherno) * @licence Apache License 2.0 */ #include "HashH2M.h" namespace H2M { uint32_t HashH2M::GenerateFNVHash(const char* str) { constexpr uint32_t FNV_PRIME = 16777619u; constexpr uint32_t OFFSET_BASIS = 2166136261u; const size_t length = strlen(str) + 1; uint32_t hash = OFFSET_BASIS; for (size_t i = 0; i < length; ++i) { hash ^= *str++; hash *= FNV_PRIME; } return hash; } uint32_t HashH2M::GenerateFNVHash(const std::string& string) { return GenerateFNVHash(string.c_str()); } }
17.441176
61
0.671164
imgui-works
40b523f52870cab0904b80949e7e892cc5c49cde
395
cpp
C++
test/chapter_09_data_serialization/problem_077_printing_a_list_of_movies_to_a_pdf.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
test/chapter_09_data_serialization/problem_077_printing_a_list_of_movies_to_a_pdf.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
test/chapter_09_data_serialization/problem_077_printing_a_list_of_movies_to_a_pdf.cpp
rturrado/TheModernCppChallenge
648284fb417b6aaa43c21ea2b12a5a21c8cb9269
[ "MIT" ]
null
null
null
#include "chapter_09_data_serialization/problem_077_printing_a_list_of_movies_to_a_pdf.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <sstream> // ostringstream TEST(problem_77_main, DISABLED_output) { std::ostringstream oss{}; problem_77_main(oss); EXPECT_THAT(oss.str(), ::testing::ContainsRegex( "Writing PDF out to: .*/list_of_movies.pdf\n" )); }
24.6875
89
0.726582
rturrado
40b5ce5cc77231d5ef5716675374b11c6290e415
5,517
hpp
C++
renderboi/core/shader/shader_program.hpp
deqyra/GLSandbox
40d641ebbf6af694e8640a584d283876d128748c
[ "MIT" ]
null
null
null
renderboi/core/shader/shader_program.hpp
deqyra/GLSandbox
40d641ebbf6af694e8640a584d283876d128748c
[ "MIT" ]
null
null
null
renderboi/core/shader/shader_program.hpp
deqyra/GLSandbox
40d641ebbf6af694e8640a584d283876d128748c
[ "MIT" ]
null
null
null
#ifndef RENDERBOI__CORE__SHADER__SHADER_PROGRAM_HPP #define RENDERBOI__CORE__SHADER__SHADER_PROGRAM_HPP #include <glad/gl.h> #include <glm/glm.hpp> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <unordered_map> #include "shader_feature.hpp" #include "../material.hpp" namespace Renderboi { class ShaderBuilder; /// @brief Handler for a shader program resource on the GPU. class ShaderProgram { friend ShaderBuilder; private: /// @param location Location of the shader program resource on the GPU. /// @param supportedFeatures Array of literals describing features which /// the shader program supports. ShaderProgram(const unsigned int location, const std::vector<ShaderFeature> supportedFeatures); /// @brief The location of the shader resource on the GPU. unsigned int _location; /// @brief Array of literals describing features which the shader /// program supports. std::vector<ShaderFeature> _supportedFeatures; /// @brief Structure mapping uniform locations against their name, and /// then against the location of the program they belong to. static std::unordered_map<unsigned int, std::unordered_map<std::string, unsigned int>> _uniformLocations; /// @brief Structure mapping how many shader instances are referencing a /// shader resource on the GPU. static std::unordered_map<unsigned int, unsigned int> _locationRefCounts; /// @brief Free resources upon destroying an instance. void _cleanup(); public: ShaderProgram(const ShaderProgram& other); ~ShaderProgram(); ShaderProgram& operator=(const ShaderProgram& other); /// @brief Get location of the shader program on the GPU. /// /// @return The location of the shader program on the GPU. unsigned int location() const; /// @brief Enable the shader on the GPU. void use() const; /// @brief Get the GPU location of a named uniform in the program. /// /// @param name The name of the uniform to locate in the program. /// /// @return The GPU location of a named uniform in the shader program. unsigned int getUniformLocation(const std::string& name) const; /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type bool. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setBool(const std::string& name, const bool value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type int. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setInt(const std::string& name, const int value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type unsigned int. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setUint(const std::string& name, const unsigned int value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type float. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setFloat(const std::string& name, const float value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type 3-by-3 float matrix. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. /// @param transpose Whether or not to transpose the matrix before /// sending. void setMat3f(const std::string& name, const glm::mat3& value, const bool transpose = false); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type 4-by-4 float matrix. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. /// @param transpose Whether or not to transpose the matrix before /// sending. void setMat4f(const std::string& name, const glm::mat4& value, const bool transpose = false); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type 3-dimensional float vector. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setVec3f(const std::string& name, const glm::vec3& value); /// @brief Set the value of a named uniform in the program. /// Use for uniforms of type material. /// /// @param name The name of the uniform whose value to set. /// @param value The value to set the uniform at. void setMaterial(const std::string& name, const Material& value); /// @brief Get the features which this shader program supports. /// /// @return A const reference to an array of literals describing which /// features the shader program supports. const std::vector<ShaderFeature>& getSupportedFeatures() const; /// @brief Tells whether this shader supports a certain feature. /// /// @param feature Literal describing the feature to check on. /// /// @return Whether or not the feature is supported. bool supports(const ShaderFeature feature) const; }; }//namespace Renderboi #endif//RENDERBOI__CORE__SHADER__SHADER_PROGRAM_HPP
37.277027
109
0.684249
deqyra
40b67ac7c887ead0be8f471a144aaca2fc328515
2,482
cpp
C++
src/core/module/notification.cpp
webosce/sam
bddc1e646d729920350f69e44105e02d1c5422d4
[ "Apache-2.0" ]
null
null
null
src/core/module/notification.cpp
webosce/sam
bddc1e646d729920350f69e44105e02d1c5422d4
[ "Apache-2.0" ]
null
null
null
src/core/module/notification.cpp
webosce/sam
bddc1e646d729920350f69e44105e02d1c5422d4
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2012-2018 LG Electronics, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #include "core/module/notification.h" #include "core/base/jutil.h" #include "core/base/logging.h" #include "core/base/lsutils.h" #include "core/base/utils.h" ResBundleAdaptor::ResBundleAdaptor() {} ResBundleAdaptor::~ResBundleAdaptor() {} std::string ResBundleAdaptor::getLocString(const std::string& key) { return m_resBundle->getLocString(key); } void ResBundleAdaptor::setLocale(const std::string& locale) { if(locale.empty()) { LOG_DEBUG("locale is empty"); return; } m_resFile = "cppstrings.json"; m_resPath = "/usr/share/localization/sam"; m_resBundle = std::make_shared<ResBundle>(locale, m_resFile, m_resPath); LOG_DEBUG("Locale is set as %s", locale.c_str()); } ToastHelper::ToastHelper() {} ToastHelper::~ToastHelper() {} bool ToastHelper::createToast(pbnjson::JValue msg) { LSErrorSafe lserror; if(msg.isNull()) { LOG_WARNING(MSGID_NOTIFICATION, 0, "msg is empty"); return false; } /* if(!LSCallOneReply(MemMgrService::instance().getPrivateHandle(), "palm://com.webos.notification/createToast", JUtil::jsonToString(msg).c_str(), toastLsCallBack, NULL, NULL, &lserror)) { LOG_WARNING(MSGID_NOTIFICATION_FAIL, 1, PMLOGKS("NOTI_MSG", JUtil::jsonToString(msg).c_str()), "NOTI send failed"); return false; } */ return true; } bool ToastHelper::toastLsCallBack(LSHandle *sh, LSMessage *message, void *user_data) { pbnjson::JValue json = JUtil::parse(LSMessageGetPayload(message), std::string("")); if(json.isNull()) return true; bool returnValue = json["returnValue"].asBool(); if(!returnValue) { LOG_WARNING(MSGID_NOTIFICATION_FAIL, 0, "Notification return failed from Noti-Service"); } return true; }
26.126316
123
0.6805
webosce
40b8975c587a48e3dba4fdac3d02bd47e37f9d9f
1,899
cpp
C++
src/libraries/postProcessing/functionObjects/utilities/residuals/residualsTemplates.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/postProcessing/functionObjects/utilities/residuals/residualsTemplates.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/postProcessing/functionObjects/utilities/residuals/residualsTemplates.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2015 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of Caelus. Caelus 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. Caelus 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 Caelus. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "residuals.hpp" #include "volFields.hpp" #include "dictionary.hpp" #include "Time.hpp" #include "ListOps.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // template<class Type> void CML::residuals::writeResidual ( const word& fieldName ) { typedef GeometricField<Type, fvPatchField, volMesh> fieldType; if (obr_.foundObject<fieldType>(fieldName)) { const fieldType& field = obr_.lookupObject<fieldType>(fieldName); const fvMesh& mesh = field.mesh(); const CML::dictionary& solverDict = mesh.solverPerformanceDict(); if (solverDict.found(fieldName)) { const List<solverPerformance> sp(solverDict.lookup(fieldName)); const scalar residual = sp.first().initialResidual(); file() << token::TAB << residual; } } } // ************************************************************************* //
34.527273
79
0.549236
MrAwesomeRocks
40ba3dfb4bb2d2840d3ec34bebf40ea22b63f6e4
10,597
cc
C++
net/spdy/spdy_protocol_test.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
2
2017-09-02T19:08:28.000Z
2021-11-15T15:15:14.000Z
net/spdy/spdy_protocol_test.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
null
null
null
net/spdy/spdy_protocol_test.cc
Gitman1989/chromium
2b1cceae1075ef012fb225deec8b4c8bbe4bc897
[ "BSD-3-Clause" ]
1
2020-04-13T05:45:10.000Z
2020-04-13T05:45:10.000Z
// Copyright (c) 2010 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 "net/spdy/spdy_protocol.h" #include "base/scoped_ptr.h" #include "net/spdy/spdy_bitmasks.h" #include "net/spdy/spdy_framer.h" #include "testing/platform_test.h" using spdy::CONTROL_FLAG_FIN; using spdy::CONTROL_FLAG_NONE; using spdy::GOAWAY; using spdy::HEADERS; using spdy::NOOP; using spdy::PING; using spdy::RST_STREAM; using spdy::SETTINGS; using spdy::SYN_REPLY; using spdy::SYN_STREAM; using spdy::WINDOW_UPDATE; using spdy::FlagsAndLength; using spdy::SpdyControlFrame; using spdy::SpdyControlType; using spdy::SpdyDataFrame; using spdy::SpdyFrame; using spdy::SpdyFramer; using spdy::SpdyHeaderBlock; using spdy::SpdyGoAwayControlFrame; using spdy::SpdyRstStreamControlFrame; using spdy::SpdySettings; using spdy::SpdySettingsControlFrame; using spdy::SpdyStatusCodes; using spdy::SpdySynReplyControlFrame; using spdy::SpdySynStreamControlFrame; using spdy::SpdyWindowUpdateControlFrame; using spdy::SettingsFlagsAndId; using spdy::kLengthMask; using spdy::kSpdyProtocolVersion; using spdy::kStreamIdMask; namespace { // Test our protocol constants TEST(SpdyProtocolTest, ProtocolConstants) { EXPECT_EQ(8u, SpdyFrame::size()); EXPECT_EQ(8u, SpdyDataFrame::size()); EXPECT_EQ(8u, SpdyControlFrame::size()); EXPECT_EQ(18u, SpdySynStreamControlFrame::size()); EXPECT_EQ(14u, SpdySynReplyControlFrame::size()); EXPECT_EQ(16u, SpdyRstStreamControlFrame::size()); EXPECT_EQ(12u, SpdyGoAwayControlFrame::size()); EXPECT_EQ(12u, SpdySettingsControlFrame::size()); EXPECT_EQ(16u, SpdyWindowUpdateControlFrame::size()); EXPECT_EQ(4u, sizeof(FlagsAndLength)); EXPECT_EQ(1, SYN_STREAM); EXPECT_EQ(2, SYN_REPLY); EXPECT_EQ(3, RST_STREAM); EXPECT_EQ(4, SETTINGS); EXPECT_EQ(5, NOOP); EXPECT_EQ(6, PING); EXPECT_EQ(7, GOAWAY); EXPECT_EQ(8, HEADERS); EXPECT_EQ(9, WINDOW_UPDATE); } // Test some of the protocol helper functions TEST(SpdyProtocolTest, FrameStructs) { SpdyFrame frame(SpdyFrame::size()); frame.set_length(12345); frame.set_flags(10); EXPECT_EQ(12345u, frame.length()); EXPECT_EQ(10u, frame.flags()); EXPECT_FALSE(frame.is_control_frame()); frame.set_length(0); frame.set_flags(10); EXPECT_EQ(0u, frame.length()); EXPECT_EQ(10u, frame.flags()); EXPECT_FALSE(frame.is_control_frame()); } TEST(SpdyProtocolTest, DataFrameStructs) { SpdyDataFrame data_frame; data_frame.set_stream_id(12345); EXPECT_EQ(12345u, data_frame.stream_id()); } TEST(SpdyProtocolTest, ControlFrameStructs) { SpdyFramer framer; SpdyHeaderBlock headers; scoped_ptr<SpdySynStreamControlFrame> syn_frame( framer.CreateSynStream(123, 456, 2, CONTROL_FLAG_FIN, false, &headers)); EXPECT_EQ(kSpdyProtocolVersion, syn_frame->version()); EXPECT_TRUE(syn_frame->is_control_frame()); EXPECT_EQ(SYN_STREAM, syn_frame->type()); EXPECT_EQ(123u, syn_frame->stream_id()); EXPECT_EQ(456u, syn_frame->associated_stream_id()); EXPECT_EQ(2u, syn_frame->priority()); EXPECT_EQ(2, syn_frame->header_block_len()); EXPECT_EQ(1u, syn_frame->flags()); syn_frame->set_associated_stream_id(999u); EXPECT_EQ(123u, syn_frame->stream_id()); EXPECT_EQ(999u, syn_frame->associated_stream_id()); scoped_ptr<SpdySynReplyControlFrame> syn_reply( framer.CreateSynReply(123, CONTROL_FLAG_NONE, false, &headers)); EXPECT_EQ(kSpdyProtocolVersion, syn_reply->version()); EXPECT_TRUE(syn_reply->is_control_frame()); EXPECT_EQ(SYN_REPLY, syn_reply->type()); EXPECT_EQ(123u, syn_reply->stream_id()); EXPECT_EQ(2, syn_reply->header_block_len()); EXPECT_EQ(0, syn_reply->flags()); scoped_ptr<SpdyRstStreamControlFrame> rst_frame( framer.CreateRstStream(123, spdy::PROTOCOL_ERROR)); EXPECT_EQ(kSpdyProtocolVersion, rst_frame->version()); EXPECT_TRUE(rst_frame->is_control_frame()); EXPECT_EQ(RST_STREAM, rst_frame->type()); EXPECT_EQ(123u, rst_frame->stream_id()); EXPECT_EQ(spdy::PROTOCOL_ERROR, rst_frame->status()); rst_frame->set_status(spdy::INVALID_STREAM); EXPECT_EQ(spdy::INVALID_STREAM, rst_frame->status()); EXPECT_EQ(0, rst_frame->flags()); scoped_ptr<SpdyGoAwayControlFrame> goaway_frame( framer.CreateGoAway(123)); EXPECT_EQ(kSpdyProtocolVersion, goaway_frame->version()); EXPECT_TRUE(goaway_frame->is_control_frame()); EXPECT_EQ(GOAWAY, goaway_frame->type()); EXPECT_EQ(123u, goaway_frame->last_accepted_stream_id()); scoped_ptr<SpdyWindowUpdateControlFrame> window_update_frame( framer.CreateWindowUpdate(123, 456)); EXPECT_EQ(kSpdyProtocolVersion, window_update_frame->version()); EXPECT_TRUE(window_update_frame->is_control_frame()); EXPECT_EQ(WINDOW_UPDATE, window_update_frame->type()); EXPECT_EQ(123u, window_update_frame->stream_id()); EXPECT_EQ(456u, window_update_frame->delta_window_size()); } TEST(SpdyProtocolTest, TestDataFrame) { SpdyDataFrame frame; // Set the stream ID to various values. frame.set_stream_id(0); EXPECT_EQ(0u, frame.stream_id()); EXPECT_FALSE(frame.is_control_frame()); frame.set_stream_id(~0 & kStreamIdMask); EXPECT_EQ(~0 & kStreamIdMask, frame.stream_id()); EXPECT_FALSE(frame.is_control_frame()); // Set length to various values. Make sure that when you set_length(x), // length() == x. Also make sure the flags are unaltered. memset(frame.data(), '1', SpdyDataFrame::size()); int8 flags = frame.flags(); frame.set_length(0); EXPECT_EQ(0u, frame.length()); EXPECT_EQ(flags, frame.flags()); frame.set_length(kLengthMask); EXPECT_EQ(kLengthMask, frame.length()); EXPECT_EQ(flags, frame.flags()); frame.set_length(5u); EXPECT_EQ(5u, frame.length()); EXPECT_EQ(flags, frame.flags()); // Set flags to various values. Make sure that when you set_flags(x), // flags() == x. Also make sure the length is unaltered. memset(frame.data(), '1', SpdyDataFrame::size()); uint32 length = frame.length(); frame.set_flags(0u); EXPECT_EQ(0u, frame.flags()); EXPECT_EQ(length, frame.length()); int8 all_flags = ~0; frame.set_flags(all_flags); flags = frame.flags(); EXPECT_EQ(all_flags, flags); EXPECT_EQ(length, frame.length()); frame.set_flags(5u); EXPECT_EQ(5u, frame.flags()); EXPECT_EQ(length, frame.length()); } // Test various types of SETTINGS frames. TEST(SpdyProtocolTest, TestSpdySettingsFrame) { SpdyFramer framer; // Create a settings frame with no settings. SpdySettings settings; scoped_ptr<SpdySettingsControlFrame> settings_frame( framer.CreateSettings(settings)); EXPECT_EQ(kSpdyProtocolVersion, settings_frame->version()); EXPECT_TRUE(settings_frame->is_control_frame()); EXPECT_EQ(SETTINGS, settings_frame->type()); EXPECT_EQ(0u, settings_frame->num_entries()); // We'll add several different ID/Flag combinations and then verify // that they encode and decode properly. SettingsFlagsAndId ids[] = { 0x00000000, 0xffffffff, 0xff000001, 0x01000002, }; for (size_t index = 0; index < arraysize(ids); ++index) { settings.insert(settings.end(), std::make_pair(ids[index], index)); settings_frame.reset(framer.CreateSettings(settings)); EXPECT_EQ(kSpdyProtocolVersion, settings_frame->version()); EXPECT_TRUE(settings_frame->is_control_frame()); EXPECT_EQ(SETTINGS, settings_frame->type()); EXPECT_EQ(index + 1, settings_frame->num_entries()); SpdySettings parsed_settings; EXPECT_TRUE(framer.ParseSettings(settings_frame.get(), &parsed_settings)); EXPECT_EQ(parsed_settings.size(), settings.size()); SpdySettings::const_iterator it = parsed_settings.begin(); int pos = 0; while (it != parsed_settings.end()) { SettingsFlagsAndId parsed = it->first; uint32 value = it->second; EXPECT_EQ(parsed.flags(), ids[pos].flags()); EXPECT_EQ(parsed.id(), ids[pos].id()); EXPECT_EQ(value, static_cast<uint32>(pos)); ++it; ++pos; } } } // Make sure that overflows both die in debug mode, and do not cause problems // in opt mode. Note: The EXPECT_DEBUG_DEATH call does not work on Win32 yet, // so we comment it out. TEST(SpdyProtocolDeathTest, TestDataFrame) { SpdyDataFrame frame; frame.set_stream_id(0); // TODO(mbelshe): implement EXPECT_DEBUG_DEATH on windows. #ifndef WIN32 EXPECT_DEBUG_DEATH(frame.set_stream_id(~0), ""); #endif EXPECT_FALSE(frame.is_control_frame()); frame.set_flags(0); #ifndef WIN32 EXPECT_DEBUG_DEATH(frame.set_length(~0), ""); #endif EXPECT_EQ(0, frame.flags()); } TEST(SpdyProtocolDeathTest, TestSpdyControlFrameStreamId) { SpdyControlFrame frame_store(SpdySynStreamControlFrame::size()); memset(frame_store.data(), '1', SpdyControlFrame::size()); SpdySynStreamControlFrame* frame = reinterpret_cast<SpdySynStreamControlFrame*>(&frame_store); // Set the stream ID to various values. frame->set_stream_id(0); EXPECT_EQ(0u, frame->stream_id()); EXPECT_FALSE(frame->is_control_frame()); frame->set_stream_id(kStreamIdMask); EXPECT_EQ(kStreamIdMask, frame->stream_id()); EXPECT_FALSE(frame->is_control_frame()); } TEST(SpdyProtocolDeathTest, TestSpdyControlFrameVersion) { const unsigned int kVersionMask = 0x7fff; SpdyControlFrame frame(SpdySynStreamControlFrame::size()); memset(frame.data(), '1', SpdyControlFrame::size()); // Set the version to various values, and make sure it does not affect the // type. frame.set_type(SYN_STREAM); frame.set_version(0); EXPECT_EQ(0, frame.version()); EXPECT_TRUE(frame.is_control_frame()); EXPECT_EQ(SYN_STREAM, frame.type()); SpdySynStreamControlFrame* syn_stream = reinterpret_cast<SpdySynStreamControlFrame*>(&frame); syn_stream->set_stream_id(~0 & kVersionMask); EXPECT_EQ(~0 & kVersionMask, syn_stream->stream_id()); EXPECT_TRUE(frame.is_control_frame()); EXPECT_EQ(SYN_STREAM, frame.type()); } TEST(SpdyProtocolDeathTest, TestSpdyControlFrameType) { SpdyControlFrame frame(SpdyControlFrame::size()); memset(frame.data(), 255, SpdyControlFrame::size()); // type() should be out of bounds. EXPECT_FALSE(frame.AppearsToBeAValidControlFrame()); uint16 version = frame.version(); for (int i = SYN_STREAM; i <= spdy::NOOP; ++i) { frame.set_type(static_cast<SpdyControlType>(i)); EXPECT_EQ(i, static_cast<int>(frame.type())); EXPECT_TRUE(frame.AppearsToBeAValidControlFrame()); // Make sure setting type does not alter the version block. EXPECT_EQ(version, frame.version()); EXPECT_TRUE(frame.is_control_frame()); } } } // namespace
34.294498
79
0.742191
Gitman1989
40bc04f1652ef79cb3a294bcbe6b12ca0d240779
175
cpp
C++
FrameLib_Max_Objects/IO/fl.source~.cpp
AlexHarker/FrameLib
04b9882561c83d3240c6cb07f14861244d1d6272
[ "BSD-3-Clause" ]
33
2017-08-13T00:02:41.000Z
2022-03-10T23:02:17.000Z
FrameLib_Max_Objects/IO/fl.source~.cpp
AlexHarker/FrameLib
04b9882561c83d3240c6cb07f14861244d1d6272
[ "BSD-3-Clause" ]
60
2018-02-01T23:33:36.000Z
2022-03-23T23:25:13.000Z
FrameLib_Max_Objects/IO/fl.source~.cpp
AlexHarker/FrameLib
04b9882561c83d3240c6cb07f14861244d1d6272
[ "BSD-3-Clause" ]
8
2018-02-01T20:18:46.000Z
2020-07-03T12:53:04.000Z
#include "FrameLib_Source.h" #include "FrameLib_MaxClass.h" extern "C" int C74_EXPORT main(void) { FrameLib_MaxClass_Expand<FrameLib_Source>::makeClass("fl.source~"); }
19.444444
71
0.754286
AlexHarker
8ad653610f9deded27ac62e1d95fcf2b6797912c
2,290
cpp
C++
src/Group.cpp
gicmo/nix
17a5b90e6c12a22e921c181b79eb2a3db1bf61af
[ "BSD-3-Clause" ]
53
2015-02-10T01:04:34.000Z
2021-04-24T14:26:04.000Z
src/Group.cpp
tapaswenipathak/nix
4565c2d7b363f27cac88932b35c085ee8fe975a1
[ "BSD-3-Clause" ]
262
2015-01-09T13:24:21.000Z
2021-07-02T13:45:31.000Z
src/Group.cpp
gicmo/nix
17a5b90e6c12a22e921c181b79eb2a3db1bf61af
[ "BSD-3-Clause" ]
34
2015-03-27T16:41:14.000Z
2020-03-27T06:47:59.000Z
// Copyright (c) 2013, German Neuroinformatics Node (G-Node) // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted under the terms of the BSD License. See // LICENSE file in the root of the Project. #include <nix/Group.hpp> #include <nix/util/util.hpp> using namespace nix; template<typename T> void Group::replaceEntities(const std::vector<T> &entities) { base::IGroup *ig = backend(); ObjectType ot = objectToType<T>::value; while (ig->entityCount(ot) > 0) { ig->removeEntity(ig->getEntity<typename objectToType<T>::backendType>(0)); } for (const auto &e : entities) { ig->addEntity(e); } } void Group::dataArrays(const std::vector<DataArray> &data_arrays) { replaceEntities(data_arrays); } std::vector<DataArray> Group::dataArrays(const util::Filter<DataArray>::type &filter) const { auto f = [this] (size_t i) { return getDataArray(i); }; return getEntities<DataArray>(f, dataArrayCount(), filter); } void Group::dataFrames(const std::vector<DataFrame> &data_frames) { replaceEntities(data_frames); } std::vector<DataFrame> Group::dataFrames(const util::Filter<DataFrame>::type &filter) const { auto f = [this] (size_t i) { return getDataFrame(i); }; return getEntities<DataFrame>(f, dataFrameCount(), filter); } void Group::tags(const std::vector<Tag> &tags) { replaceEntities(tags); } std::vector<Tag> Group::tags(const util::Filter<Tag>::type &filter) const { auto f = [this] (size_t i) { return getTag(i); }; return getEntities<Tag>(f, tagCount(), filter); } std::vector<MultiTag> Group::multiTags(const util::Filter<MultiTag>::type &filter) const { auto f = [this] (size_t i) { return getMultiTag(i); }; return getEntities<MultiTag>(f, multiTagCount(), filter); } void Group::multiTags(const std::vector<MultiTag> &tags) { replaceEntities(tags); } std::ostream& nix::operator<<(std::ostream &out, const Group &ent) { out << "Group: {name = " << ent.name(); out << ", type = " << ent.type(); out << ", id = " << ent.id() << "}"; return out; }
27.590361
93
0.625328
gicmo
8ad874790cc7b81859edcf2349de3491b20944b5
1,749
hpp
C++
test/unit/search/helper.hpp
remyschwab/seqan3
f10e557b61428ff7faac8b10f18b9087d1ff2663
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/search/helper.hpp
remyschwab/seqan3
f10e557b61428ff7faac8b10f18b9087d1ff2663
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
test/unit/search/helper.hpp
remyschwab/seqan3
f10e557b61428ff7faac8b10f18b9087d1ff2663
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2021, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2021, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- #pragma once #include <algorithm> #include <iterator> #include <vector> #include <seqan3/core/debug_stream/debug_stream_type.hpp> #include <seqan3/search/fm_index/bi_fm_index_cursor.hpp> #include <seqan3/search/fm_index/fm_index_cursor.hpp> #include <seqan3/utility/views/to.hpp> namespace seqan3 { template <typename char_t, typename index_t> inline debug_stream_type<char_t> & operator<<(debug_stream_type<char_t> & s, seqan3::fm_index_cursor<index_t> const &) { return s << ("fm_index_cursor"); } template <typename char_t, typename index_t> inline debug_stream_type<char_t> & operator<<(debug_stream_type<char_t> & s, seqan3::bi_fm_index_cursor<index_t> const &) { return s << ("bi_fm_index_cursor"); } template <typename result_range_t> std::vector<std::ranges::range_value_t<result_range_t>> uniquify(result_range_t && result_range) { auto unique_res = result_range | views::to<std::vector>; std::sort(unique_res.begin(), unique_res.end()); unique_res.erase(std::unique(unique_res.begin(), unique_res.end()), unique_res.end()); return unique_res; } } // namespace std
38.866667
104
0.6255
remyschwab
8adb3d3bdbc6a4910d3a2ee786967bd5609a6321
929
cpp
C++
sycl/test/basic_tests/implicit_conversion_error.cpp
elizabethandrews/llvm
308498236c1c4778fdcba0bfbb556adf8aa333ea
[ "Apache-2.0" ]
null
null
null
sycl/test/basic_tests/implicit_conversion_error.cpp
elizabethandrews/llvm
308498236c1c4778fdcba0bfbb556adf8aa333ea
[ "Apache-2.0" ]
6
2021-02-04T21:32:09.000Z
2021-02-08T09:31:15.000Z
sycl/test/basic_tests/implicit_conversion_error.cpp
elizabethandrews/llvm
308498236c1c4778fdcba0bfbb556adf8aa333ea
[ "Apache-2.0" ]
1
2021-11-23T17:16:34.000Z
2021-11-23T17:16:34.000Z
// RUN: %clangxx -fsyntax-only -Xclang -verify %s -I %sycl_include -Xclang -verify-ignore-unexpected=note,warning //==-- implicit_conversion_error.cpp - Unintended implicit conversion check --==// // // 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 // //===-----------------------------------------------------------------------===// #include <CL/sycl.hpp> int main() { cl::sycl::queue q; cl::sycl::context cxt = q.get_context(); cl::sycl::device dev = q.get_device(); cl::sycl::context cxt2{dev}; cl::sycl::context cxt3 = dev; // expected-error {{no viable conversion from 'cl::sycl::device' to 'cl::sycl::context'}} cl::sycl::queue q2{dev}; cl::sycl::queue q3 = dev; // expected-error {{no viable conversion from 'cl::sycl::device' to 'cl::sycl::queue'}} }
42.227273
121
0.628633
elizabethandrews
8adeaae052d54d6102b799e4873e2616fbd2af6b
1,296
cpp
C++
experiment_setup/slave_node/hpc_sample_tool_savitor/src/sample.cpp
Rasoul-Jahanshahi/Hardware_Performance_Counters_Can_Detect_Malware_Myth_or_Fact
1d0322784d2371411c5362651a099763d4776a39
[ "MIT" ]
18
2018-05-10T18:50:06.000Z
2022-01-11T17:11:34.000Z
experiment_setup/slave_node/hpc_sample_tool_savitor/src/sample.cpp
Rasoul-Jahanshahi/Hardware_Performance_Counters_Can_Detect_Malware_Myth_or_Fact
1d0322784d2371411c5362651a099763d4776a39
[ "MIT" ]
24
2018-06-14T17:54:17.000Z
2022-03-11T23:21:29.000Z
experiment_setup/slave_node/hpc_sample_tool_savitor/src/sample.cpp
Rasoul-Jahanshahi/Hardware_Performance_Counters_Can_Detect_Malware_Myth_or_Fact
1d0322784d2371411c5362651a099763d4776a39
[ "MIT" ]
4
2019-04-02T16:04:34.000Z
2022-01-10T11:44:43.000Z
#include "../include/stdafx.h" unsigned __int64 * profile::sample_profile(unsigned int event_count) { switch(event_count) { case 1: fnGetEventCount(Core, 0, &pAllEventCount[0]); break; case 2: fnGetEventCount(Core, 0, &pAllEventCount[0]); fnGetEventCount(Core, 1, &pAllEventCount[1]); break; case 3: fnGetEventCount(Core, 0, &pAllEventCount[0]); fnGetEventCount(Core, 1, &pAllEventCount[1]); fnGetEventCount(Core, 2, &pAllEventCount[2]); break; case 4: fnGetEventCount(Core, 0, &pAllEventCount[0]); fnGetEventCount(Core, 1, &pAllEventCount[1]); fnGetEventCount(Core, 2, &pAllEventCount[2]); fnGetEventCount(Core, 3, &pAllEventCount[3]); break; break; case 5: fnGetEventCount(Core, 0, &pAllEventCount[0]); fnGetEventCount(Core, 1, &pAllEventCount[1]); fnGetEventCount(Core, 2, &pAllEventCount[2]); fnGetEventCount(Core, 3, &pAllEventCount[3]); fnGetEventCount(Core, 4, &pAllEventCount[4]); break; break; case 6: fnGetEventCount(Core, 0, &pAllEventCount[0]); fnGetEventCount(Core, 1, &pAllEventCount[1]); fnGetEventCount(Core, 2, &pAllEventCount[2]); fnGetEventCount(Core, 3, &pAllEventCount[3]); fnGetEventCount(Core, 4, &pAllEventCount[4]); fnGetEventCount(Core, 5, &pAllEventCount[5]); break; } return pAllEventCount; }
27.574468
68
0.710648
Rasoul-Jahanshahi
8adefb8961b214b786de58988af91b0c84172789
1,103
cpp
C++
src/ast/rewriter/label_rewriter.cpp
jar-ben/z3
7baa4f88b0cb4458461596d147e1f71853d77126
[ "MIT" ]
7,746
2015-03-26T18:59:33.000Z
2022-03-31T15:34:48.000Z
src/ast/rewriter/label_rewriter.cpp
jar-ben/z3
7baa4f88b0cb4458461596d147e1f71853d77126
[ "MIT" ]
5,162
2015-03-27T01:12:48.000Z
2022-03-31T14:56:16.000Z
src/ast/rewriter/label_rewriter.cpp
jar-ben/z3
7baa4f88b0cb4458461596d147e1f71853d77126
[ "MIT" ]
1,529
2015-03-26T18:45:30.000Z
2022-03-31T15:35:16.000Z
/*++ Copyright (c) 2015 Microsoft Corporation Module Name: label_rewriter.cpp Abstract: Basic rewriting rules for removing labels. Author: Nikolaj Bjorner (nbjorner) 2015-19-10 Notes: --*/ #include "ast/rewriter/rewriter.h" #include "ast/rewriter/rewriter_def.h" #include "ast/rewriter/label_rewriter.h" label_rewriter::label_rewriter(ast_manager & m) : m_label_fid(m.get_label_family_id()), m_rwr(m, false, *this) {} label_rewriter::~label_rewriter() {} br_status label_rewriter::reduce_app( func_decl * f, unsigned num, expr * const * args, expr_ref & result, proof_ref & result_pr) { if (is_decl_of(f, m_label_fid, OP_LABEL)) { SASSERT(num == 1); result = args[0]; return BR_DONE; } return BR_FAILED; } void label_rewriter::remove_labels(expr_ref& fml, proof_ref& pr) { ast_manager& m = fml.get_manager(); expr_ref tmp(m); m_rwr(fml, tmp); if (pr && fml != tmp) { pr = m.mk_modus_ponens(pr, m.mk_rewrite(fml, tmp)); } fml = tmp; } //template class rewriter_tpl<label_rewriter>;
20.425926
73
0.658205
jar-ben
8ae376ff7484994fb0d118556b27921a69aad370
535
cpp
C++
demo/main.cpp
SSBMTonberry/emusound
3f07b3af1158277cacaf63d78c47f47aeb18723d
[ "BSD-2-Clause" ]
4
2020-07-22T07:26:18.000Z
2020-09-01T22:10:21.000Z
demo/main.cpp
SSBMTonberry/emusound
3f07b3af1158277cacaf63d78c47f47aeb18723d
[ "BSD-2-Clause" ]
1
2020-08-21T06:43:04.000Z
2020-08-30T12:28:08.000Z
demo/main.cpp
SSBMTonberry/emusound
3f07b3af1158277cacaf63d78c47f47aeb18723d
[ "BSD-2-Clause" ]
null
null
null
// // Created by robin on 19.01.2020. // #include "ProgramManager.h" int emuprogramExample(int argc, char** argv) { std::string title = "emusound demo"; sf::ContextSettings settings; settings.antialiasingLevel = 0; esnddemo::ProgramManager program(title, sf::Vector2i(400 * 4, 240 * 4), sf::Vector2i(400, 240), sf::Style::Titlebar, settings); //program.setZoomValue(1.f); program.initialize(); program.run(); return 0; } int main(int argc, char** argv) { return emuprogramExample(argc, argv); }
22.291667
131
0.66729
SSBMTonberry
8ae52f3cde59794915f589b495859af442b3ea62
9,126
cpp
C++
Managment/src/slam_client.cpp
cxdcxd/sepanta3
a65a3415f046631ac4d6b91f9342966b0c030226
[ "MIT" ]
1
2018-09-11T18:40:25.000Z
2018-09-11T18:40:25.000Z
ROS/Managment/src/slam_client.cpp
cxdcxd/NAVbot
8068e7ca596708f1fbfc63b1f6f944b85dee0953
[ "MIT" ]
null
null
null
ROS/Managment/src/slam_client.cpp
cxdcxd/NAVbot
8068e7ca596708f1fbfc63b1f6f944b85dee0953
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <move_base_msgs/MoveBaseAction.h> #include <actionlib/client/simple_action_client.h> #include <tf/transform_broadcaster.h> #include <stdio.h> #include <boost/thread.hpp> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <actionlib/client/simple_action_client.h> #include <actionlib/client/terminal_state.h> #include <sepanta_msgs/command.h> #include <sepanta_msgs/omnidata.h> #include <sepanta_msgs/sepantaAction.h> //movex movey turngl turngllocal actions #include <sepanta_msgs/slamactionAction.h> //slam action #include <std_msgs/Int32.h> #include <std_msgs/Bool.h> //#include <std_msgs/Bool.h> #include "sepanta_msgs/stop.h" typedef actionlib::SimpleActionClient<sepanta_msgs::slamactionAction> SLAMClient; typedef actionlib::SimpleActionClient<sepanta_msgs::sepantaAction> SepantaClient; ros::ServiceClient serviceclient_odometryslam; ros::ServiceClient serviceclient_facestop; ros::ServiceClient serviceclient_manualauto; ros::ServiceClient serviceclient_map; SLAMClient *globalSLAM; SepantaClient *globalSepanta; bool App_exit = false; ros::Publisher chatter_pub[20]; using namespace std; bool flag1 = false; bool flag2 = false; int old = 0; std::string service_command = ""; std::string service_id = ""; int service_value = 0 ; void goWithOdometry(string mode,int value) { ROS_INFO("Going %s with odometry...", mode.c_str()); sepanta_msgs::sepantaGoal interfacegoal; interfacegoal.type = mode; interfacegoal.value = value; actionlib::SimpleClientGoalState state = globalSepanta->sendGoalAndWait(interfacegoal, ros::Duration(1000), ros::Duration(1000)); if (state == actionlib::SimpleClientGoalState::PREEMPTED) { ROS_INFO("ODOMETRY PREEMPTED"); } if (state == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("ODOMETRY SUCCEEDED"); } if (state == actionlib::SimpleClientGoalState::ABORTED) { ROS_INFO("ODOMETRY ABORTED"); } } void goWithSlam(string where) { ROS_INFO("Going %s with slam...", where.c_str()); sepanta_msgs::slamactionGoal interfacegoal; interfacegoal.x = 0; interfacegoal.y = 0; interfacegoal.yaw = 0; interfacegoal.ID = where; ROS_INFO("goal sent to slam... waiting for reach there."); cout << where << endl; actionlib::SimpleClientGoalState state = globalSLAM->sendGoalAndWait(interfacegoal, ros::Duration(1000), ros::Duration(1000)); if (state == actionlib::SimpleClientGoalState::PREEMPTED) { ROS_INFO("SLAM PREEMPTED"); } if (state == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("SLAM SUCCEEDED"); } if (state == actionlib::SimpleClientGoalState::ABORTED) { ROS_INFO("SLAM ABORTED"); } } void service_thread2() { while ( App_exit == false && ros::ok()) { if (service_command == "gotocancle") { ROS_INFO("GOTOCANCLE"); globalSLAM->cancelGoal(); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "odometrycancle") { ROS_INFO("ODOMETRYCANCLE"); globalSepanta->cancelGoal(); service_command = ""; service_id = ""; service_value = 0; } boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } } void service_thread() { while ( App_exit == false && ros::ok()) { if (service_command == "goto") { ROS_INFO("GET GOTO"); goWithSlam(service_id); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "movex") { ROS_INFO("MOVEX"); goWithOdometry(service_command,service_value); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "movey") { ROS_INFO("MOVEY"); goWithOdometry(service_command,service_value); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "turngl") { ROS_INFO("TURNGL"); goWithOdometry(service_command,service_value); service_command = ""; service_id = ""; service_value = 0; } else if (service_command == "turngllocal") { ROS_INFO("TURNGLLOCAL"); goWithOdometry(service_command,service_value); service_command = ""; service_id = ""; service_value = 0; } boost::this_thread::sleep(boost::posix_time::milliseconds(100)); } } bool checkcommand(sepanta_msgs::command::Request &req,sepanta_msgs::command::Response &res) { std::string str = req.command; std::string id = req.id; int value = req.value; ROS_INFO("Service Request...."); service_command = str; service_id = id; service_value = value; res.result = "done"; return true; } void omnidrive(int x,int y,int w) { sepanta_msgs::omnidata msg_data; msg_data.d0 = x; msg_data.d1 = y; msg_data.d2 = w; chatter_pub[0].publish(msg_data); } void calibration_test() { return; cout << "calib start start" << endl; boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); //reset_position(); omnidrive(0, 0, 30); boost::this_thread::sleep(boost::posix_time::milliseconds(10000)); omnidrive(0, 0, 0); boost::this_thread::sleep(boost::posix_time::milliseconds(5000)); cout << "back" << endl; omnidrive(0, 0, -30); boost::this_thread::sleep(boost::posix_time::milliseconds(10000)); omnidrive(0, 0, 0); boost::this_thread::sleep(boost::posix_time::milliseconds(5000)); cout << "finish" << endl; // cout << position[0] << " , " << position[1] << " , " << position[2] << " , " << delta<< endl; } void checkkeypad(const std_msgs::Int32::ConstPtr &topicMsg) { int value = topicMsg->data ; //ROS_INFO("%d",value); if ( value != old) { ROS_INFO("%d",value); old = value; if(value==3) { omnidrive(0,0,0); // std_msgs::Bool msg; // msg.data = true; // chatter_pub[2].publish(msg); } if(value== 7) { omnidrive(200,0,0); } if(value==8) { omnidrive(-200,0,0); } if(value==9) { omnidrive(0,200,0); } if(value==10) { omnidrive(0,-200,0); } if(value==5) { omnidrive(0,0,220); } if(value==6) { omnidrive(0,0,-220); } //================ if ( value == 1) { //manual mode start // sepanta_msgs::stop srv_stop; // srv_stop.request.command = "Manual"; // serviceclient_manualauto.call(srv_stop); } if ( value == 4) { //slam mode start //sepanta_msgs::stop srv_stop; //srv_stop.request.command = "Slam"; //serviceclient_manualauto.call(srv_stop); } if ( value == 2) { //manual reached //sepanta_msgs::stop srv_stop; //srv_stop.request.command = "ManualReached"; //serviceclient_manualauto.call(srv_stop); // std_msgs::Bool msg; // msg.data = false; // chatter_pub[2].publish(msg); } } } int main(int argc, char** argv) { ros::init(argc, argv, "navigation_client"); ros::Time::init(); cout << "SEPANTA SLAM CLIENTS SERVICES STARTED DONE (93/04/05)" << endl; ros::NodeHandle n_service; ros::ServiceServer service_command = n_service.advertiseService("AUTROBOTINSRV_command", checkcommand); ros::NodeHandle node_handles[15]; chatter_pub[0] = node_handles[0].advertise<sepanta_msgs::omnidata>("AUTROBOTIN_omnidrive", 10); chatter_pub[1] = node_handles[1].advertise<std_msgs::Bool>("AUTROBOTIN_greenlight", 10); chatter_pub[2] = node_handles[2].advertise<std_msgs::Bool>("AUTROBOTIN_redlight", 10); ros::Subscriber sub_handles[1]; sub_handles[0] = node_handles[1].subscribe("AUTROBOTOUT_keypad", 10, checkkeypad); ros::NodeHandle n_client1; serviceclient_facestop = n_client1.serviceClient<sepanta_msgs::stop>("speechOrFace_Stop"); ros::NodeHandle n_client2; serviceclient_manualauto = n_client2.serviceClient<sepanta_msgs::stop>("manualOrAuto"); SLAMClient slamAction("slam_action", true); globalSLAM = &slamAction ; slamAction.waitForServer(); ROS_INFO("connected to slam server"); //=========================================== SepantaClient sepantaAction("sepanta_action", true); globalSepanta = &sepantaAction ; sepantaAction.waitForServer(); ROS_INFO("connected to sepanta server"); ros::Rate ros_rate(20); boost::thread _thread_logic(&calibration_test); boost::thread _thread_serevice(&service_thread); boost::thread _thread_serevice2(&service_thread2); while(ros::ok()) { ros::spinOnce(); ros_rate.sleep(); } App_exit = true; _thread_logic.interrupt(); _thread_logic.join(); _thread_serevice.interrupt(); _thread_serevice.join(); _thread_serevice2.interrupt(); _thread_serevice2.join(); return 0; }
23.952756
133
0.636862
cxdcxd
8ae5f6927c5f8ab729c252d6ea0ce8d9aad3c9a4
11,131
cpp
C++
python/remote_file_operation/download.cpp
colin-zhou/mrfs
12b8ed1f06bb1a8ed0637a3ee78231c5f8eec6d1
[ "MIT" ]
8
2017-12-23T10:40:57.000Z
2021-05-04T06:56:03.000Z
python/remote_file_operation/download.cpp
colin-zhou/mrfs
12b8ed1f06bb1a8ed0637a3ee78231c5f8eec6d1
[ "MIT" ]
null
null
null
python/remote_file_operation/download.cpp
colin-zhou/mrfs
12b8ed1f06bb1a8ed0637a3ee78231c5f8eec6d1
[ "MIT" ]
1
2019-01-29T06:39:04.000Z
2019-01-29T06:39:04.000Z
#include <Python.h> #include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <errno.h> #include "download.h" static task_repository tr; static pthread_t dl_thread; static int c_sem_key = sem_key_start; static int dl_thread_status = FAIL; static int create_semid() { int sem_id; do { sem_id = semget((key_t)c_sem_key, 1, 0666 | IPC_CREAT); c_sem_key += 1; if (c_sem_key == MAX_SEM) { c_sem_key = sem_key_start; } } while (sem_id == -1); return sem_id; } static int set_semvalue(int sem_id) { union semun sem_union; sem_union.val = 0; if (semctl(sem_id, 0, SETVAL, sem_union) == -1) { fprintf(stderr, "set semvalue error %s\n", strerror(errno)); return FAIL; } return SUCCESS; } static int del_semvalue(int sem_id) { printf("free the semaphore sem_id = %d \n", sem_id); union semun sem_union; if (semctl(sem_id, 0, IPC_RMID, sem_union) == -1) { fprintf(stderr, "del semvalue error %s\n", strerror(errno)); return FAIL; } return SUCCESS; } static int semaphore_p(int sem_id) { printf("p operation %d\n", sem_id); struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = -1; sem_b.sem_flg = SEM_UNDO; if (semop(sem_id, &sem_b, 1) == -1) { fprintf(stderr, "semaphore p operation error %s\n", strerror(errno)); return FAIL; } return SUCCESS; } static int semaphore_v(int sem_id) { printf("v operation %d\n", sem_id); struct sembuf sem_b; sem_b.sem_num = 0; sem_b.sem_op = 1; sem_b.sem_flg = SEM_UNDO; if (semop(sem_id, &sem_b, 1) == -1) { fprintf(stderr, "semaphore v operation error %d %s\n", sem_id, strerror(errno)); return FAIL; } return SUCCESS; } static int check_rf_params(remote_file_t *rf) { if (rf->host == NULL || rf->path_file == NULL) { fprintf(stderr, "remote file params error\n"); return FAIL; } return SUCCESS; } static int check_lf_params(local_file_t *lf) { if (lf->path_file == NULL) { fprintf(stderr, "local file params error\n"); return FAIL; } return SUCCESS; } static int check_ssh_conn_params(ssh_conn_params_t *ssh) { if(ssh->host == NULL || ssh->port == NULL || ssh->user == NULL || ssh->password == NULL) { fprintf(stderr, "ssh connection parameters error\n"); return FAIL; } return SUCCESS; } static void pthread_cleanup_func(void *args) { dl_thread_status = FAIL; } int download_file(remote_file_t *rf, local_file_t *lf) { int ret = FAIL; int cpos, sem_id; // check the parameters if (!check_lf_params(lf) || !check_rf_params(rf)) { return FAIL; } // check the dl_thread if (dl_thread_status == FAIL) { fprintf(stderr, "Download thread is not alive\n"); return FAIL; } // write the task to buffer if it could pthread_mutex_lock(&tr.mtx); // buffer is full (preparing for process) then wait here while (tr.write_position + 1 % repository_size == tr.read_position) { pthread_cond_wait(&tr.repo_not_full, &tr.mtx); } (tr.params_buffer)[tr.write_position].type = CMD_DOWNLOAD; (tr.params_buffer)[tr.write_position].rf = rf; (tr.params_buffer)[tr.write_position].lf = lf; (tr.params_buffer)[tr.write_position].sshp = NULL; (tr.params_buffer)[tr.write_position].ret_msg = UNKNOWN; sem_id = create_semid(); (tr.params_buffer)[tr.write_position].sem_id = sem_id; cpos = tr.write_position; (tr.write_position)++; if (tr.write_position == repository_size) { tr.write_position = 0; } // inform the process thread to process it pthread_cond_signal(&tr.repo_not_empty); pthread_mutex_unlock(&tr.mtx); // wait until the task is finished printf("sem_id = %d ---- %d\n",sem_id, c_sem_key); if (set_semvalue(sem_id) == SUCCESS && semaphore_p(sem_id) == SUCCESS) { ret = (tr.params_buffer)[cpos].ret_msg; del_semvalue(sem_id); } else { while(1) { if (tr.params_buffer[cpos].ret_msg != UNKNOWN) { ret = tr.params_buffer[cpos].ret_msg; break; } } } return ret; } int init_ssh_connection(ssh_conn_params_t *ssh) { int ret = FAIL; int cpos, sem_id; // check the parameters if (!check_ssh_conn_params(ssh)) { return FAIL; } // check the dl_thread if (dl_thread_status == FAIL) { fprintf(stderr, "Download thread is not alive\n"); return FAIL; } pthread_mutex_lock(&tr.mtx); // buffer is full (preparing for process) then wait here while (tr.write_position + 1 % repository_size == tr.read_position) { pthread_cond_wait(&tr.repo_not_full, &tr.mtx); } tr.params_buffer[tr.write_position].type = CMD_INIT; tr.params_buffer[tr.write_position].rf = NULL; tr.params_buffer[tr.write_position].lf = NULL; tr.params_buffer[tr.write_position].sshp = ssh; tr.params_buffer[tr.write_position].ret_msg = UNKNOWN; sem_id = create_semid(); (tr.params_buffer)[tr.write_position].sem_id = sem_id; cpos = tr.write_position; (tr.write_position)++; if (tr.write_position == repository_size) { tr.write_position = 0; } // inform the process thread to process it pthread_cond_signal(&tr.repo_not_empty); pthread_mutex_unlock(&tr.mtx); printf("sem_id = %d ---- %d\n",sem_id, c_sem_key); // semaphore method to wait process ret if (set_semvalue(sem_id) == SUCCESS && semaphore_p(sem_id) == SUCCESS) { ret = (tr.params_buffer)[cpos].ret_msg; del_semvalue(sem_id); } else { while(1) { if (tr.params_buffer[cpos].ret_msg != UNKNOWN) { ret = tr.params_buffer[cpos].ret_msg; break; } } } } // TODO: // 1. #include improve // 3. thread alive check static void * download_thread(void *pVoid) { // initial the py environment PyObject *pName, *pModule, *pDict, *pFunc_download, *pFunc_init; PyObject *pArgs, *pRet; int error_flag = 0; do { Py_Initialize(); if (!Py_IsInitialized()) { error_flag = 1; break; } PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('./')"); pName = PyString_FromString("remote_file_operation"); if (pName == NULL) { error_flag = 1; break; } pModule = PyImport_Import(pName); if (pModule == NULL) { error_flag = 1; break; } pDict = PyModule_GetDict(pModule); if (pDict == NULL) { error_flag = 1; break; } pFunc_download = PyDict_GetItemString(pDict, "download_file"); if (pFunc_download == NULL || !PyCallable_Check(pFunc_download)) { error_flag = 1; break; } pFunc_init = PyDict_GetItemString(pDict, "conn_server"); if (pFunc_init == NULL || !PyCallable_Check(pFunc_init)) { error_flag = 1; break; } } while(0); if (error_flag) { goto PY_ERROR; } // initial the tr message tr.read_position = 0; tr.write_position = 0; dl_thread_status = SUCCESS; // main loop wait for signal to process the tasks while (1) { int ret, type, sem_id; pthread_mutex_lock(&tr.mtx); // wait till the buffer is not empty while (tr.write_position == tr.read_position) { pthread_cond_wait(&tr.repo_not_empty, &tr.mtx); } type = (tr.params_buffer)[tr.read_position].type; // consume the resource according the type msg and // write back the process result if (type == CMD_DOWNLOAD) { // parse the arguments remote_file_t *rf = ((tr.params_buffer)[tr.read_position]).rf; local_file_t *lf = ((tr.params_buffer)[tr.read_position]).lf; sem_id = ((tr.params_buffer)[tr.read_position]).sem_id; pArgs = PyTuple_New(3); // string presented as a raw byte string PyObject *host = PyString_FromString(rf->host); PyObject *r_path_file = PyString_FromString(rf->path_file); PyObject *l_path_file = PyString_FromString(lf->path_file); if (host==NULL || r_path_file == NULL || l_path_file==NULL) { error_flag = 1; pthread_mutex_unlock(&tr.mtx); break; } PyTuple_SetItem(pArgs, 0, host); PyTuple_SetItem(pArgs, 1, r_path_file); PyTuple_SetItem(pArgs, 2, l_path_file); pRet = PyObject_CallObject(pFunc_download, pArgs); if (pArgs != NULL) { Py_DECREF(pArgs); } if (pRet == NULL) { error_flag = 1; pthread_mutex_unlock(&tr.mtx); break; } ret = PyInt_AsLong(pRet); } else { ssh_conn_params_t *sshp = ((tr.params_buffer)[tr.read_position]).sshp; sem_id = ((tr.params_buffer)[tr.read_position]).sem_id; pArgs = PyTuple_New(4); PyObject *host = PyString_FromString(sshp->host); PyObject *user = PyString_FromString(sshp->user); PyObject *password = PyString_FromString(sshp->password); PyObject *port = PyInt_FromLong(atoi(sshp->port)); PyTuple_SetItem(pArgs, 0, host); PyTuple_SetItem(pArgs, 1, user); PyTuple_SetItem(pArgs, 2, password); PyTuple_SetItem(pArgs, 3, port); pRet = PyObject_CallObject(pFunc_init, pArgs); if (pArgs != NULL) { Py_DECREF(pArgs); } if (pRet == NULL) { error_flag = 1; break; } ret = PyInt_AsLong(pRet); } (tr.params_buffer)[tr.read_position].ret_msg = ret; (tr.read_position)++; if (tr.read_position >= repository_size) { tr.read_position = 0; } pthread_cond_broadcast(&tr.repo_not_full); pthread_mutex_unlock(&tr.mtx); if (semaphore_v(sem_id) == FAIL) { break; } } // free the py environment PY_ERROR: printf("the value of error_flag = %d\n", error_flag); if (pModule) { Py_DECREF(pModule); } if (pName) { Py_DECREF(pName); } if (error_flag == 1) { PyErr_Print(); } Py_Finalize(); dl_thread_status = FAIL; fprintf(stderr, "Child thread in C finished. \n"); pthread_exit(NULL); } int start_download_thread() { pthread_create(&dl_thread, NULL, download_thread, NULL); pthread_detach(dl_thread); sleep(1); return 0; }
29.215223
88
0.583955
colin-zhou
8ae63d490cda9c5c36b938df14957f23e053c408
99,673
cpp
C++
compiler/src/cpp_synth.cpp
mdegirolami/stay
b47676e5340c2bbd93fe97d52a12a895a3492b22
[ "BSD-3-Clause" ]
null
null
null
compiler/src/cpp_synth.cpp
mdegirolami/stay
b47676e5340c2bbd93fe97d52a12a895a3492b22
[ "BSD-3-Clause" ]
null
null
null
compiler/src/cpp_synth.cpp
mdegirolami/stay
b47676e5340c2bbd93fe97d52a12a895a3492b22
[ "BSD-3-Clause" ]
null
null
null
#include <assert.h> #include <string.h> #include <stdio.h> #include <vector> #include <cinttypes> #include "cpp_synth.h" #include "FileName.h" #include "helpers.h" #include "builtin_functions.h" namespace SingNames { static const int KForcedPriority = 100; // i.e. requires no protection and never overrides order. (uses brackets) //static const int KLiteralPriority = 0; // a single literal numeral, can be converted changing the suffix static const int KLeafPriority = 1; // a single item, not a literal numeral static const int KCastPriority = 3; bool IsFloatFormat(const char *num); void CppSynth::Synthetize(string *cppfile, string *hppfile, PackageManager *packages, Options *options, int pkg_index, bool *empty_cpp) { string text; int num_levels, num_items; *cppfile = ""; *hppfile = ""; const Package *pkg = packages->getPkg(pkg_index); pkmgr_ = packages; root_ = (AstFile*)pkg->GetRoot(); indent_ = 0; split_level_ = 0xff; exp_level = 0; synth_options_ = options->GetSynthOptions(); debug_ = options->IsDebugBuild(); // HPP file ///////////////// formatter_.Reset(); formatter_.SetMaxLineLen(synth_options_->max_linelen_); formatter_.SetRemarks(&root_->remarks_[0], root_->remarks_.size()); file_str_ = hppfile; text = "#pragma once"; Write(&text, false); EmptyLine(); // headers text = "#include <sing.h>"; Write(&text, false); WriteHeaders(DependencyUsage::PUBLIC); EmptyLine(); // open the namespace num_levels = WriteNamespaceOpening(); // all public declarations by cathegory WriteClassForwardDeclarations(true); WriteTypeDefinitions(true); WritePrototypes(true); WriteExternalDeclarations(); WriteNamespaceClosing(num_levels); if (options->GenerateHOnly()) { *empty_cpp = true; return; } // CPP file ///////////////// formatter_.Reset(); formatter_.SetRemarks(&root_->remarks_[0], root_->remarks_.size()); file_str_ = cppfile; string fullname = pkg->getFullPath(); FileName::SplitFullName(nullptr, &text, nullptr, &fullname); text.insert(0, "#include \""); text += ".h\""; Write(&text, false); num_items = WriteHeaders(DependencyUsage::PRIVATE); EmptyLine(); // open the namespace num_levels = WriteNamespaceOpening(); // all public declarations by cathegory WriteClassForwardDeclarations(false); num_items += WriteTypeDefinitions(false); WritePrototypes(false); num_items += WriteVariablesDefinitions(); num_items += WriteClassIdsDefinitions(); num_items += WriteConstructors(); num_items += WriteFunctions(); WriteNamespaceClosing(num_levels); *empty_cpp = num_items == 0; } void CppSynth::SynthVar(VarDeclaration *declaration) { string text, typedecl, initer; if (!declaration->HasOneOfFlags(VF_ISLOCAL) && (!declaration->IsPublic() || declaration->HasOneOfFlags(VF_IMPLEMENTED_AS_CONSTINT)) ) { text = "static "; } if (declaration->initer_ != nullptr) { SynthIniterCore(&initer, declaration->GetTypeSpec(), declaration->initer_); } else if (declaration->HasOneOfFlags(VF_ISLOCAL)) { SynthZeroIniter(&initer, declaration->GetTypeSpec()); } if (declaration->HasOneOfFlags(VF_ISPOINTED)) { bool init_on_second_row = declaration->initer_ != nullptr && declaration->initer_->GetType() == ANT_INITER; init_on_second_row = init_on_second_row || initer[0] == '{'; text += "std::shared_ptr<"; if (declaration->HasOneOfFlags(VF_READONLY)) { text += "const "; } SynthTypeSpecification(&typedecl, declaration->GetTypeSpec()); text += typedecl; text += "> "; text += declaration->name_; text += " = std::make_shared<"; text += typedecl; if (initer.length() > 0 && !init_on_second_row) { text += ">("; text += initer; text += ")"; } else { text += ">()"; } Write(&text); if (initer.length() > 0 && init_on_second_row) { text = "*"; text += declaration->name_; text += " = "; text += initer; Write(&text); } } else { if (declaration->HasOneOfFlags(VF_READONLY)) { text += "const "; } typedecl = declaration->name_; IAstTypeNode *tnode = declaration->GetTypeSpec(); SynthTypeSpecification(&typedecl, tnode); text += typedecl; if (initer.length() > 0) { text += " = "; text += initer; } Write(&text); } } void CppSynth::SynthType(TypeDeclaration *declaration) { switch (declaration->type_spec_->GetType()) { case ANT_CLASS_TYPE: SynthClassDeclaration(declaration->name_.c_str(), (AstClassType*)declaration->type_spec_); break; case ANT_INTERFACE_TYPE: SynthInterfaceDeclaration(declaration->name_.c_str(), (AstInterfaceType*)declaration->type_spec_); break; case ANT_ENUM_TYPE: SynthEnumDeclaration(declaration->name_.c_str(), (AstEnumType*)declaration->type_spec_); break; default: { string text(declaration->name_); SynthTypeSpecification(&text, declaration->type_spec_); text.insert(0, "typedef "); Write(&text); break; } } } void CppSynth::SynthFunc(FuncDeclaration *declaration) { string text, typedecl; EmptyLine(); if (declaration->is_class_member_) { AstClassType *ctype = GetLocalClassTypeDeclaration(declaration->classname_.c_str()); if (ctype != nullptr && ctype->has_constructor && !ctype->constructor_written) { ctype->SetConstructorDone(); SynthConstructor(&declaration->classname_, ctype); } EmptyLine(); if (declaration->name_ == "finalize") { text = declaration->classname_ + "::~" + declaration->classname_ + "()"; } else { text = declaration->classname_ + "::" + declaration->name_; SynthFuncTypeSpecification(&text, declaration->function_type_, false); if (!declaration->is_muting_) { text += " const"; } } } else { text = declaration->name_; SynthFuncTypeSpecification(&text, declaration->function_type_, false); if (!declaration->IsPublic()) { text.insert(0, "static "); } } SynthFunOpenBrace(text); return_type_ = declaration->function_type_->return_type_; function_name_ = declaration->name_; if (debug_) { WriteArgumentsGuards(declaration->function_type_); } SynthBlock(declaration->block_); } void CppSynth::SynthFunOpenBrace(string &text) { if (!synth_options_->newline_before_function_bracket_) { text += " {"; } Write(&text, false); if (synth_options_->newline_before_function_bracket_) { text = "{"; Write(&text, false); } } void CppSynth::SynthConstructor(string *classname, AstClassType *ctype) { string initer, text; EmptyLine(); text = *classname + "::" + *classname + "()"; SynthFunOpenBrace(text); ++indent_; for (int ii = 0; ii < ctype->member_vars_.size(); ++ii) { VarDeclaration *vdecl = ctype->member_vars_[ii]; initer = ""; if (vdecl->initer_ != nullptr) { SynthIniterCore(&initer, vdecl->GetTypeSpec(), vdecl->initer_); } else { SynthZeroIniter(&initer, vdecl->GetTypeSpec()); } if (initer.length() > 0) { text = ""; AppendMemberName(&text, vdecl); text += " = "; text += initer; Write(&text); } } --indent_; text = "}"; Write(&text, false); } void CppSynth::SynthTypeSpecification(string *dst, IAstTypeNode *type_spec) { switch (type_spec->GetType()) { case ANT_BASE_TYPE: { const char *name = GetBaseTypeName(((AstBaseType*)type_spec)->base_type_); PrependWithSeparator(dst, name); } break; case ANT_NAMED_TYPE: { AstNamedType *node = (AstNamedType*)type_spec; if (node->next_component != nullptr) { string full; GetFullExternName(&full, node->pkg_index_, node->next_component->name_.c_str()); PrependWithSeparator(dst, full.c_str()); } else if (node->pkg_index_ > 0) { string full; GetFullExternName(&full, node->pkg_index_, node->name_.c_str()); PrependWithSeparator(dst, full.c_str()); } else { PrependWithSeparator(dst, node->name_.c_str()); } } break; case ANT_ARRAY_TYPE: SynthArrayTypeSpecification(dst, (AstArrayType*)type_spec); break; case ANT_MAP_TYPE: { AstMapType *node = (AstMapType*)type_spec; string fulldecl, the_type; fulldecl = "sing::map<"; SynthTypeSpecification(&the_type, node->key_type_); fulldecl += the_type; fulldecl += ", "; the_type = ""; SynthTypeSpecification(&the_type, node->returned_type_); fulldecl += the_type; fulldecl += ">"; PrependWithSeparator(dst, fulldecl.c_str()); } break; case ANT_POINTER_TYPE: { AstPointerType *node = (AstPointerType*)type_spec; string fulldecl, the_type; fulldecl = "std::"; if (node->isweak_) { fulldecl += "weak_ptr<"; } else { fulldecl += "shared_ptr<"; } if (node->isconst_) fulldecl += "const "; SynthTypeSpecification(&the_type, node->pointed_type_); fulldecl += the_type; fulldecl += ">"; PrependWithSeparator(dst, fulldecl.c_str()); } break; case ANT_FUNC_TYPE: dst->insert(0, "(*"); *dst += ")"; SynthFuncTypeSpecification(dst, (AstFuncType*)type_spec, false); break; case ANT_ENUM_TYPE: { AstEnumType *node = (AstEnumType*)type_spec; int pkg_idx = node->GetPositionRecord()->package_idx; if (pkg_idx > 0) { string full; GetFullExternName(&full, pkg_idx, node->name_.c_str()); PrependWithSeparator(dst, full.c_str()); } else { PrependWithSeparator(dst, node->name_.c_str()); } } break; case ANT_CLASS_TYPE: { // this is possible only locally, else the class is referred as a named type. AstClassType *node = (AstClassType*)type_spec; PrependWithSeparator(dst, node->name_.c_str()); } } } void CppSynth::SynthFuncTypeSpecification(string *dst, AstFuncType *type_spec, bool prototype) { int ii; --split_level_; *dst += "("; AddSplitMarker(dst); if (type_spec->arguments_.size() > 0) { string the_type; int last_uninited; for (last_uninited = type_spec->arguments_.size() - 1; last_uninited >= 0; --last_uninited) { if (type_spec->arguments_[last_uninited]->initer_ == NULL) break; } for (ii = 0; ii < (int)type_spec->arguments_.size(); ++ii) { // collect info VarDeclaration *arg = type_spec->arguments_[ii]; ParmPassingMethod mode = GetParameterPassingMethod(arg->GetTypeSpec(), arg->HasOneOfFlags(VF_READONLY)); // sinth the parm if (mode == PPM_INPUT_STRING) { the_type = "char *"; the_type += arg->name_; } else { if (mode == PPM_POINTER) { the_type = "*"; the_type += arg->name_; } else if (mode == PPM_CONSTREF) { the_type = "&"; the_type += arg->name_; } else { // PPM_VALUE the_type = arg->name_; } SynthTypeSpecification(&the_type, arg->GetTypeSpec()); } // add to dst if (ii != 0) { *dst += ", "; AddSplitMarker(dst); } if (arg->HasOneOfFlags(VF_READONLY) && mode != PPM_VALUE) { *dst += "const "; } if (ii > last_uninited && prototype) { SynthIniter(&the_type, arg->GetTypeSpec(), arg->initer_); } *dst += the_type; } if (type_spec->varargs_) { *dst += ", "; } } if (type_spec->varargs_) { *dst += "..."; } *dst += ')'; SynthTypeSpecification(dst, type_spec->return_type_); ++split_level_; } void CppSynth::SynthArrayTypeSpecification(string *dst, AstArrayType *type_spec) { string the_type, decl; if (type_spec->is_dynamic_) { decl = "std::vector<"; } else { decl = "sing::array<"; } SynthTypeSpecification(&the_type, type_spec->element_type_); decl += the_type; if (!type_spec->is_dynamic_) { // i.e.: is sing::array if (type_spec->expression_ != nullptr) { string exp; decl += ", "; int priority = SynthExpression(&exp, type_spec->expression_); if (type_spec->expression_->GetAttr()->IsEnum()) { priority = AddCast(&exp, priority, "size_t"); } Protect(&exp, priority, GetBinopCppPriority(TOKEN_SHR)); // because SHR gets confused with the end of the template parameters list '>' decl += exp; } else { // length determined based on the initializer char buffer[32]; sprintf(buffer, ", %" PRIu64, (uint64_t)type_spec->dimension_); decl += buffer; } } decl += ">"; PrependWithSeparator(dst, decl.c_str()); } void CppSynth::SynthClassDeclaration(const char *name, AstClassType *type_spec) { bool has_base = type_spec->member_interfaces_.size() > 0; SynthClassHeader(name, &type_spec->member_interfaces_, false); // collect some info bool supports_typeswitch = type_spec->member_interfaces_.size() > 0; bool has_private = false; bool has_public_var = false; bool needs_constructor = false; for (int ii = 0; ii < type_spec->member_vars_.size(); ++ii) { VarDeclaration *vdecl = type_spec->member_vars_[ii]; if (!vdecl->IsPublic()) { has_private = true; } else { has_public_var = true; } if (vdecl->initer_ != nullptr || vdecl->GetTypeSpec()->NeedsZeroIniter()) { needs_constructor = true; } } for (int ii = 0; ii < type_spec->member_functions_.size() && !has_private; ++ii) { if (!type_spec->member_functions_[ii]->IsPublic()) { has_private = true; } } // for later use !! if (needs_constructor) { type_spec->SetNeedsConstructor(); } string text = "public:"; Write(&text, false); // the functions ++indent_; // constructor if (needs_constructor) { text = name; text += "()"; Write(&text); } // destructor if (type_spec->has_destructor) { text = name; if (has_base) { text.insert(0, "virtual ~"); text += "()"; } else { text.insert(0, "~"); text += "()"; } Write(&text); // if has a destructor, copying is unsafe !! /* text = name; text += "(const "; text += name; text += " &) = delete"; Write(&text); text = name; text += " &operator=(const "; text += name; text += " &) = delete"; Write(&text); */ } // get__id (if inherits from an interface) if (supports_typeswitch) { if (synth_options_->use_override_) { text = "virtual void *get__id() const override { return(&id__); }"; } else { text = "virtual void *get__id() const { return(&id__); }"; } Write(&text); } // user defined int num_functions = SynthClassMemberFunctions(&type_spec->member_functions_, &type_spec->fn_implementors_, type_spec->first_hinherited_member_, true, false); if (num_functions > 0 && (supports_typeswitch || has_public_var)) { EmptyLine(); } // the variables if (supports_typeswitch) { text = "static char id__"; Write(&text); } SynthClassMemberVariables(&type_spec->member_vars_, true); --indent_; if (has_private) { EmptyLine(); string text = "private:"; Write(&text, false); ++indent_; num_functions = SynthClassMemberFunctions(&type_spec->member_functions_, &type_spec->fn_implementors_, type_spec->first_hinherited_member_, false, false); if (num_functions > 0) { EmptyLine(); } SynthClassMemberVariables(&type_spec->member_vars_, false); --indent_; } // close the declaration text = "}"; Write(&text); } void CppSynth::SynthClassHeader(const char *name, vector<AstNamedType*> *bases, bool is_interface) { string text = "class "; text += name; if (!is_interface && synth_options_->use_final_) { text += " final"; } int num_bases = bases->size(); if (num_bases > 0) { string basename; text += " :"; for (int ii = 0; ii < num_bases; ++ii) { basename = ""; SynthTypeSpecification(&basename, (*bases)[ii]); text += " public "; text += basename; if (ii < num_bases - 1) { text += ","; } } } text += " {"; Write(&text, false); } int CppSynth::SynthClassMemberFunctions(vector<FuncDeclaration*> *declarations, vector<string> *implementors, int first_hinerited, bool public_members, bool is_interface) { string text; int num_functions = 0; int top = declarations->size(); // on interfaces there is no need to declare inherited functions if (is_interface) { top = first_hinerited; } for (int ii = 0; ii < top; ++ii) { // filter out FuncDeclaration *func = (*declarations)[ii]; if (func->IsPublic() != public_members) continue; if (func->name_ == "finalize") continue; // declared elsewhere // setup for comments formatter_.SetNodePos(func); // synth ! AstFuncType *ftype = func->function_type_; assert(ftype != nullptr); text = func->name_; SynthFuncTypeSpecification(&text, ftype, true); if (is_interface || ii >= first_hinerited) { text.insert(0, "virtual "); } if (!func->is_muting_) { text += " const"; } if (!is_interface && ii >= first_hinerited && synth_options_->use_override_) { text += " override"; } if (is_interface) { text += " = 0"; } else if ((*implementors)[ii] != "") { SynthFunOpenBrace(text); ++indent_; bool voidfun = ftype->ReturnsVoid(); if (!voidfun) { text = "return("; } else { text = ""; } text +=synth_options_->member_prefix_ + (*implementors)[ii] + synth_options_->member_suffix_ + "." + func->name_ + "("; --split_level_; for (int ii = 0; ii < ftype->arguments_.size(); ++ii) { text += ftype->arguments_[ii]->name_; if (ii < ftype->arguments_.size() - 1) { text += ", "; AddSplitMarker(&text); } } ++split_level_; text += ")"; if (!voidfun) { text += ")"; } Write(&text); --indent_; text = "}"; } Write(&text); ++num_functions; } return(num_functions); } void CppSynth::SynthClassMemberVariables(vector<VarDeclaration*> *d_vector, bool public_members) { string text; int top = d_vector->size(); for (int ii = 0; ii < top; ++ii) { VarDeclaration *declaration = (*d_vector)[ii]; if (declaration->IsPublic() != public_members) continue; formatter_.SetNodePos(declaration); text = ""; AppendMemberName(&text, declaration); SynthTypeSpecification(&text, declaration->GetTypeSpec()); Write(&text); } } void CppSynth::SynthInterfaceDeclaration(const char *name, AstInterfaceType *type_spec) { SynthClassHeader(name, &type_spec->ancestors_, true); string text = "public:"; Write(&text, false); // the functions ++indent_; // virtual destructor and typeswitch support (if not inherited) if (type_spec->ancestors_.size() == 0) { text = "virtual ~"; text += name; text += "() {}"; Write(&text, false); text = "virtual void *get__id() const = 0"; Write(&text); } SynthClassMemberFunctions(&type_spec->members_, nullptr, type_spec->first_hinherited_member_, true, true); --indent_; // close the declaration text = "}"; Write(&text); } void CppSynth::SynthEnumDeclaration(const char *name, AstEnumType *type_spec) { --split_level_; string text = "enum class "; text += name; text += " {"; AddSplitMarker(&text); for (int ii = 0; ii < type_spec->items_.size(); ++ii) { text += type_spec->items_[ii]; if (type_spec->initers_[ii] != nullptr) { string exp; SynthExpression(&exp, type_spec->initers_[ii]); text += " = "; text += exp; } if (ii < type_spec->items_.size() - 1) { text += ", "; AddSplitMarker(&text); } } text += "}"; Write(&text); ++split_level_; } void CppSynth::SynthIniter(string *dst, IAstTypeNode *type_spec, IAstNode *initer) { *dst += " = "; SynthIniterCore(dst, type_spec, initer); } void CppSynth::SynthIniterCore(string *dst, IAstTypeNode *type_spec, IAstNode *initer) { while (type_spec != nullptr && type_spec->GetType() == ANT_NAMED_TYPE) { type_spec = ((AstNamedType*)type_spec)->wp_decl_->type_spec_; } if (initer->GetType() == ANT_INITER) { AstIniter *ast_initer = (AstIniter*)initer; int ii; int oldrow = initer->GetPositionRecord()->start_row; *dst += '{'; if (type_spec->GetType() == ANT_ARRAY_TYPE) { AstArrayType *arraytype = (AstArrayType*)type_spec; for (ii = 0; ii < (int)ast_initer->elements_.size(); ++ii) { IAstNode *element = ast_initer->elements_[ii]; oldrow = AddForcedSplit(dst, element, oldrow); SynthIniterCore(dst, arraytype->element_type_, element); if (ii != (int)ast_initer->elements_.size() - 1) { *dst += ", "; } } } else if (type_spec->GetType() == ANT_MAP_TYPE) { AstMapType *maptype = (AstMapType*)type_spec; IAstNode **element = &ast_initer->elements_[0]; for (ii = (int)ast_initer->elements_.size() >> 1; ii > 0; --ii) { oldrow = AddForcedSplit(dst, element[0], oldrow); *dst += "{"; SynthIniterCore(dst, maptype->key_type_, element[0]); *dst += ", "; SynthIniterCore(dst, maptype->returned_type_, element[1]); *dst += "}"; if (ii != 1) { *dst += ", "; } element += 2; } } if (initer->GetPositionRecord()->last_row > oldrow) { *dst += 0xff; } *dst += '}'; } else { string exp; SynthFullExpression(type_spec, &exp, (IAstExpNode*)initer); *dst += exp; } } void CppSynth::SynthZeroIniter(string *dst, IAstTypeNode *type_spec) { *dst = ""; switch (type_spec->GetType()) { case ANT_BASE_TYPE: switch (((AstBaseType*)type_spec)->base_type_) { default: *dst = "0"; break; case TOKEN_COMPLEX64: case TOKEN_COMPLEX128: case TOKEN_STRING: break; case TOKEN_BOOL: *dst = "false"; break; } break; case ANT_NAMED_TYPE: SynthZeroIniter(dst, ((AstNamedType*)type_spec)->wp_decl_->type_spec_); break; case ANT_FUNC_TYPE: *dst = "nullptr"; break; case ANT_ENUM_TYPE: { AstEnumType *etype = (AstEnumType*)type_spec; *dst = etype->name_ + "::" + etype->items_[0]; int pkg_idx = etype->GetPositionRecord()->package_idx; if (pkg_idx > 0) { string partial = *dst; GetFullExternName(dst, pkg_idx, partial.c_str()); } } break; case ANT_ARRAY_TYPE: if (!((AstArrayType*)type_spec)->is_dynamic_) { SynthZeroIniter(dst, ((AstArrayType*)type_spec)->element_type_); if ((*dst)[0] != 0) { dst->insert(0, "{"); *dst += "}"; } } break; default: break; } } void CppSynth::SynthBlock(AstBlock *block, bool write_closing_bracket) { int ii; AstNodeType oldtype = ANT_BLOCK; // init so that SynthStatementOrAutoVar doesn't place an empty line. ++indent_; for (ii = 0; ii < (int)block->block_items_.size(); ++ii) { SynthStatementOrAutoVar(block->block_items_[ii], &oldtype); } --indent_; if (write_closing_bracket) { string text = "}"; Write(&text, false); } } void CppSynth::SynthStatementOrAutoVar(IAstNode *node, AstNodeType *oldtype) { string text; AstNodeType type; type = node->GetType(); formatter_.SetNodePos(node, type != ANT_VAR && type != ANT_BLOCK); // place an empty line before the first non-var statement following one or more var declarations // if (oldtype != nullptr) { // if (type != ANT_VAR && *oldtype == ANT_VAR) { // EmptyLine(); // } // *oldtype = type; // } switch (type) { case ANT_VAR: SynthVar((VarDeclaration*)node); break; case ANT_UPDATE: SynthUpdateStatement((AstUpdate*)node); break; case ANT_INCDEC: SynthIncDec((AstIncDec*)node); break; case ANT_SWAP: SynthSwap((AstSwap*)node); break; case ANT_WHILE: SynthWhile((AstWhile*)node); break; case ANT_IF: SynthIf((AstIf*)node); break; case ANT_FOR: SynthFor((AstFor*)node); break; case ANT_SIMPLE: SynthSimpleStatement((AstSimpleStatement*)node); break; case ANT_RETURN: SynthReturn((AstReturn*)node); break; case ANT_TRY: SynthTry((AstTry*)node); break; case ANT_FUNCALL: text = ""; SynthFunCall(&text, (AstFunCall*)node); Write(&text, true); break; case ANT_SWITCH: SynthSwitch((AstSwitch*)node); break; case ANT_TYPESWITCH: SynthTypeSwitch((AstTypeSwitch*)node); break; case ANT_BLOCK: text = "{"; Write(&text, false); SynthBlock((AstBlock*)node); break; } } void CppSynth::SynthUpdateStatement(AstUpdate *node) { string full; string expression; const ExpressionAttributes *left_attr = node->left_term_->GetAttr(); const ExpressionAttributes *right_attr = node->right_term_->GetAttr(); // copying a static vector to a dynamic one ? if (left_attr->IsArray() && ((AstArrayType*)left_attr->GetTypeTree())->is_dynamic_ && !((AstArrayType*)right_attr->GetTypeTree())->is_dynamic_) { --split_level_; SynthExpression(&expression, node->left_term_); full = "sing::copy_array_to_vec("; AddSplitMarker(&full); full += expression; expression = ""; SynthExpression(&expression, node->right_term_); full += ", "; AddSplitMarker(&full); full += expression; full += ")"; ++split_level_; } else if (left_attr->IsWeakPointer() && right_attr->IsLiteralNull()) { int priority = SynthExpression(&full, node->left_term_); Protect(&full, priority, GetBinopCppPriority(TOKEN_DOT)); full += ".reset()"; } else { SynthExpression(&full, node->left_term_); full += ' '; full += Lexer::GetTokenString(node->operation_); full += ' '; SynthFullExpression(left_attr, &expression, node->right_term_); full += expression; } Write(&full); } void CppSynth::SynthIncDec(AstIncDec *node) { int priority; string text; priority = SynthExpression(&text, node->left_term_); Protect(&text, priority, GetUnopCppPriority(node->operation_)); text.insert(0, Lexer::GetTokenString(node->operation_)); Write(&text); } void CppSynth::SynthSwap(AstSwap *node) { string text, expression; --split_level_; text = "std::swap("; AddSplitMarker(&text); SynthExpression(&expression, node->left_term_); text += expression; text += ", "; AddSplitMarker(&text); expression = ""; SynthExpression(&expression, node->right_term_); text += expression; text += ")"; Write(&text); ++split_level_; } void CppSynth::SynthWhile(AstWhile *node) { string text; SynthExpression(&text, node->expression_); text.insert(0, "while ("); text += ") {"; Write(&text, false); SynthBlock(node->block_); } void CppSynth::SynthIf(AstIf *node) { string text; int ii; // check: types compatibility (annotate the node). SynthExpression(&text, node->expressions_[0]); text.insert(0, "if ("); text += ") {"; Write(&text, false); SynthBlock(node->blocks_[0], false); for (ii = 1; ii < (int)node->expressions_.size(); ++ii) { text = ""; SynthExpression(&text, node->expressions_[ii]); text.insert(0, "} else if ("); text += ") {"; Write(&text, false); SynthBlock(node->blocks_[ii], false); } if (node->default_block_ != NULL) { text = "} else {"; Write(&text, false); SynthBlock(node->default_block_, false); } text = "}"; Write(&text, false); } void CppSynth::SynthSwitch(AstSwitch *node) { string text; --split_level_; SynthExpression(&text, node->switch_value_); text.insert(0, "switch ("); text += ") {"; Write(&text, false); int cases = 0; for (int ii = 0; ii < (int)node->statements_.size(); ++ii) { int top_case = node->statement_top_case_[ii]; if (top_case == cases) { text = "default:"; Write(&text, false); } else { while (cases < top_case) { IAstExpNode *clause = node->case_values_[cases]; if (clause != nullptr) { SynthExpression(&text, clause); text.insert(0, "case "); text += ": "; Write(&text, false); } ++cases; } } IAstNode *statement = node->statements_[ii]; ++indent_; if (statement != nullptr) { SynthStatementOrAutoVar(statement, nullptr); } text = "break"; Write(&text); --indent_; } text = "}"; ++split_level_; Write(&text, false); } void CppSynth::SynthTypeSwitch(AstTypeSwitch *node) { string text, switch_exp, tocompare, tempbuf; int exppri = SynthExpression(&switch_exp, node->expression_); tocompare = switch_exp; if (node->on_interface_ptr_) { Protect(&tocompare, exppri, GetUnopCppPriority(TOKEN_MPY)); tocompare.insert(0, "(*"); tocompare += ").get__id() == &"; } else { Protect(&tocompare, exppri, GetBinopCppPriority(TOKEN_DOT)); tocompare += ".get__id() == &"; } if (node->on_interface_ptr_) { text = "if (!"; text += switch_exp; // no need to protect: a leftvalue doesn't include binops. text += ") {"; Write(&text, false); } for (int ii = 0; ii < node->case_types_.size(); ++ii) { IAstTypeNode *clause = node->case_types_[ii]; IAstNode *statement = node->case_statements_[ii]; bool needs_reference = node->uses_reference_[ii]; string clause_typename; if (clause == nullptr) { if (statement != nullptr) { assert(ii != 0); text = "} else {"; Write(&text, false); } } else { if (ii == 0 && !node->on_interface_ptr_) { text = "if ("; } else { text = "} else if ("; } text += tocompare; if (node->on_interface_ptr_) { IAstTypeNode *solved = SolveTypedefs(clause); if (solved->GetType() == ANT_POINTER_TYPE) { SynthTypeSpecification(&clause_typename, ((AstPointerType*)solved)->pointed_type_); } } else { SynthTypeSpecification(&clause_typename, clause); } text += clause_typename; text += "::id__) {"; Write(&text, false); } if (statement != nullptr) { ++indent_; // init the reference if (needs_reference) { if (node->on_interface_ptr_) { // es: std::shared_ptr<Derived> localname(p04, (Derived*)p04.get()); text = "std::shared_ptr<"; text += clause_typename; text += "> "; text += node->reference_->name_; text += "("; text += switch_exp; text += ", ("; text += clause_typename; text += "*)"; tempbuf = switch_exp; Protect(&tempbuf, exppri, GetBinopCppPriority(TOKEN_DOT)); text += tempbuf; text += ".get())"; } else { // es: Derived &localname = *(Derived *)&inparm; text = clause_typename; text += " &"; text += node->reference_->name_; text += " = *("; text += clause_typename; text += " *)&"; text += switch_exp; } Write(&text); } // this is all about avoiding double {} if (statement->GetType() == ANT_BLOCK) { --indent_; SynthBlock((AstBlock*)statement, false); ++indent_; } else { SynthStatementOrAutoVar(statement, nullptr); } --indent_; } } text = "}"; Write(&text, false); } void CppSynth::SynthFor(AstFor *node) { string text; // declare or init the index // (can't do in the init clause of the for because it is a declaration, not a statement !! if (node->index_ != nullptr) { if (!node->index_referenced_) { text = "int64_t "; text += node->index_->name_; } else { text = node->index_->name_; } if (node->set_ != nullptr) { text += " = -1"; } else { text += " = 0"; } Write(&text); } if (node->set_ != nullptr) { SynthForEachOnDyna(node); } else { SynthForIntRange(node); } } void CppSynth::SynthForEachOnDyna(AstFor *node) { string expression, text; text = "for(auto &"; text += node->iterator_->name_; text += " : "; SynthExpression(&expression, node->set_); text += expression; text += ") {"; Write(&text, false); if (debug_) { ++indent_; WriteReferenceGuard(node->iterator_->name_.c_str(), true); --indent_; } if (node->index_ != nullptr) { ++indent_; text = "++"; text += node->index_->name_; Write(&text); --indent_; } SynthBlock(node->block_); } void CppSynth::SynthForIntRange(AstFor *node) { string text, aux, top_exp; const ExpressionAttributes *attr_low = node->low_->GetAttr(); const ExpressionAttributes *attr_high = node->high_->GetAttr(); bool use_top_var = !attr_high->HasKnownValue(); bool use_step_var = (node->step_value_ == 0); // is 0 when unknown at compile time (not literal) assert(node->iterator_->GetTypeSpec()->GetType() == ANT_BASE_TYPE); bool using_64_bits = ((AstBaseType*)node->iterator_->GetTypeSpec())->base_type_ == TOKEN_INT64; --split_level_; text = "for("; AddSplitMarker(&text); // declaration of iterator aux = node->iterator_->name_; SynthTypeSpecification(&aux, node->iterator_->GetTypeSpec()); text += aux; text += " = "; SynthExpressionAndCastToInt(&aux, node->low_, using_64_bits); text += aux; // init clause includes declaration of high/step backing variables, index and interator if (use_top_var) { text += ", "; text += node->iterator_->name_; text += "__top = "; SynthExpressionAndCastToInt(&aux, node->high_, using_64_bits); text += aux; } if (use_step_var) { text += ", "; text += node->iterator_->name_; text += "__step = "; SynthExpressionAndCastToInt(&aux, node->step_, using_64_bits); text += aux; } text += "; "; AddSplitMarker(&text); // end of loop clause. if (use_top_var) { top_exp = node->iterator_->name_; top_exp += "__top"; } else { SynthExpressionAndCastToInt(&top_exp, node->high_, using_64_bits); } if (use_step_var) { text += node->iterator_->name_; text += "__step > 0 ? ("; text += node->iterator_->name_; text += " < "; text += top_exp; text += ") : ("; text += node->iterator_->name_; text += " > "; text += top_exp; text += "); "; } else { text += node->iterator_->name_; text += node->step_value_ > 0 ? " < " : " > "; text += top_exp; text += "; "; } AddSplitMarker(&text); // increment clause if (node->step_value_ == 1) { text += "++"; text += node->iterator_->name_; } else if (node->step_value_ == -1) { text += "--"; text += node->iterator_->name_; } else { text += node->iterator_->name_; text += " += "; if (use_step_var) { text += node->iterator_->name_; text += "__step"; } else { SynthExpressionAndCastToInt(&aux, node->step_, using_64_bits); text += aux; } } if (node->index_ != NULL) { text += ", ++"; text += node->index_->name_; } // close and write down text += ") {"; Write(&text, false); ++split_level_; SynthBlock(node->block_); } void CppSynth::SynthExpressionAndCastToInt(string *dst, IAstExpNode *node, bool use_int64) { int priority; *dst = ""; priority = SynthExpression(dst, node); Token target = use_int64 ? TOKEN_INT64 : TOKEN_INT32; CastIfNeededTo(target, node->GetAttr()->GetAutoBaseType(), dst, priority, false); } void CppSynth::SynthSimpleStatement(AstSimpleStatement *node) { // check: is in an inner block who is continuable/breakable ? string text = Lexer::GetTokenString(node->subtype_); Write(&text); } void CppSynth::SynthReturn(AstReturn *node) { string text; if (node->retvalue_ != nullptr) { SynthFullExpression(return_type_, &text, node->retvalue_); text.insert(0, "return ("); text += ")"; } else { text = "return"; } Write(&text); } void CppSynth::SynthTry(AstTry *node) { string text; bool not_optimization = false; if (node->tried_->GetType() == ANT_UNOP) { AstUnop *op = (AstUnop*)node->tried_; if (op->subtype_ == TOKEN_LOGICAL_NOT) { SynthExpression(&text, op->operand_); not_optimization = true; } } if (!not_optimization) { int priority = SynthExpression(&text, node->tried_); Protect(&text, priority, GetUnopCppPriority(TOKEN_LOGICAL_NOT)); text.insert(0, "!"); } text.insert(0, "if ("); text += ") return(false)"; Write(&text); } // // Adds a final conversion in view of the assignment. Sing allows some numeric conversions c++ doesn't: // - If the value is a compile time constant and fits the target value. // - if the conversion is not narrowing but the target is a complex and the source is not a value of same precision. // // You DONT' need SynthFullExpression() if: // - the espression is strictly constant (recognized as such by legacy C compilers), currently: // - enum case initers // - array size // - left terms (or in general if the value is not the source for a write) // - values that are known not being numerics (es. typeswitch expression) // - values that are required to be integers (not automatically downcasted, even if constant: indices) // - consider SynthExpressionAndCastToInt() for values that are known to be signed ints; // int CppSynth::SynthFullExpression(const IAstTypeNode *type_spec, string *dst, IAstExpNode *node) { int priority; priority = SynthExpression(dst, node); if (type_spec != nullptr) { type_spec = SolveTypedefs(type_spec); if (type_spec->GetType() == ANT_POINTER_TYPE && !((AstPointerType*)type_spec)->isweak_ && node->GetAttr()->IsWeakPointer()) { int newpriority = GetBinopCppPriority(TOKEN_DOT); Protect(dst, priority, newpriority); priority = newpriority; *dst += ".lock()"; } else { Token base = GetBaseType(type_spec); if (base != TOKENS_COUNT) { priority = CastIfNeededTo(base, node->GetAttr()->GetAutoBaseType(), dst, priority, false); } } } return(priority); } int CppSynth::SynthFullExpression(const ExpressionAttributes *attr, string *dst, IAstExpNode *node) { int priority; priority = SynthExpression(dst, node); if (attr != nullptr) { if (attr->IsStrongPointer() && node->GetAttr()->IsWeakPointer()) { int newpriority = GetBinopCppPriority(TOKEN_DOT); Protect(dst, priority, newpriority); priority = newpriority; *dst += ".lock()"; } else { Token target_type = attr->GetAutoBaseType(); if (target_type != TOKENS_COUNT) { priority = CastIfNeededTo(target_type, node->GetAttr()->GetAutoBaseType(), dst, priority, false); } } } return(priority); } // TODO: split on more lines int CppSynth::SynthExpression(string *dst, IAstExpNode *node) { int priority = 0; switch (node->GetType()) { case ANT_INDEXING: priority = SynthIndices(dst, (AstIndexing*)node); break; case ANT_FUNCALL: priority = SynthFunCall(dst, (AstFunCall*) node); break; case ANT_BINOP: priority = SynthBinop(dst, (AstBinop*)node); break; case ANT_UNOP: priority = SynthUnop(dst, (AstUnop*)node); break; case ANT_EXP_LEAF: priority = SynthLeaf(dst, (AstExpressionLeaf*)node); break; } return(priority); } int CppSynth::SynthIndices(string *dst, AstIndexing *node) { string expression; int priority; int exp_pri = SynthExpression(dst, node->indexed_term_); int index_pri = SynthExpression(&expression, node->lower_value_); if (node->lower_value_->GetAttr()->IsEnum()) { AddCast(&expression, index_pri, "size_t"); } if (debug_) { priority = GetUnopCppPriority(TOKEN_DOT); Protect(dst, exp_pri, priority); *dst += ".at("; *dst += expression; *dst += ')'; } else { priority = GetUnopCppPriority(TOKEN_SQUARE_OPEN); Protect(dst, exp_pri, priority); *dst += '['; *dst += expression; *dst += ']'; } return(priority); } int CppSynth::SynthFunCall(string *dst, AstFunCall *node) { int ii, priority; int numargs = (int)node->arguments_.size(); string expression; bool builtin = false; if (node->left_term_->GetType() == ANT_BINOP) { AstBinop *bnode = (AstBinop*)node->left_term_; builtin = bnode->builtin_ != nullptr; } --split_level_; priority = SynthExpression(dst, node->left_term_); if (builtin) { // fun call alredy synthesized in SynthDotOp() but is missing the arguments dst->erase(dst->length() - 1); // just delete ')' - reopen the arg list bool has_already_args = (*dst)[dst->length() - 1] != '('; if (has_already_args && numargs > 0) { // separate the two groups *dst += ", "; } if (has_already_args || numargs > 0) { AddSplitMarker(dst); // has at least an arg. } } else { Protect(dst, priority, GetUnopCppPriority(TOKEN_ROUND_OPEN)); *dst += '('; if (numargs > 0) { AddSplitMarker(dst); // has at least an arg. } } for (ii = 0; ii < numargs; ++ii) { VarDeclaration *var = node->func_type_->arguments_[ii]; IAstExpNode *expression_node = node->arguments_[ii]->expression_; expression = ""; int priority = SynthFullExpression(var->GetTypeSpec(), &expression, expression_node); ParmPassingMethod ppm = GetParameterPassingMethod(var->GetTypeSpec(), var->HasOneOfFlags(VF_READONLY)); if (ppm == PPM_POINTER) { // passed by pointer: get the address (or simplify *this) //if (expression[0] == '*') { // note: can't do this if * is to access an item pointed by a shared pointer. if (expression == "*this") { expression.erase(0, 1); } else if (expression != "nullptr") { // note: optouts can be set to nullptr. expression.insert(0, "&"); } } else if (ppm == PPM_INPUT_STRING && !IsInputArg(expression_node) && !IsLiteralString(expression_node)) { Protect(&expression, priority, GetBinopCppPriority(TOKEN_DOT)); expression += ".c_str()"; } if (ii != 0) { *dst += ", "; AddSplitMarker(dst); } *dst += expression; } *dst += ')'; ++split_level_; return(GetUnopCppPriority(TOKEN_ROUND_OPEN)); } int CppSynth::SynthBinop(string *dst, AstBinop *node) { int priority = 0; switch (node->subtype_) { case TOKEN_DOT: priority = SynthDotOperator(dst, node); break; case TOKEN_POWER: priority = SynthPowerOperator(dst, node); break; case TOKEN_MPY: case TOKEN_DIVIDE: case TOKEN_PLUS: case TOKEN_MINUS: case TOKEN_MOD: case TOKEN_SHR: case TOKEN_AND: case TOKEN_SHL: case TOKEN_OR: case TOKEN_XOR: case TOKEN_MIN: case TOKEN_MAX: --split_level_; priority = SynthMathOperator(dst, node); ++split_level_; break; case TOKEN_ANGLE_OPEN_LT: case TOKEN_ANGLE_CLOSE_GT: case TOKEN_GTE: case TOKEN_LTE: case TOKEN_DIFFERENT: case TOKEN_EQUAL: --split_level_; priority = SynthRelationalOperator(dst, node); ++split_level_; break; case TOKEN_LOGICAL_AND: case TOKEN_LOGICAL_OR: --split_level_; priority = SynthLogicalOperator(dst, node); ++split_level_; break; default: // ops !! assert(false); break; } return(priority); } int CppSynth::SynthDotOperator(string *dst, AstBinop *node) { int priority = GetBinopCppPriority(TOKEN_DOT); assert(node->operand_right_->GetType() == ANT_EXP_LEAF); AstExpressionLeaf* right_leaf = (AstExpressionLeaf*)node->operand_right_; // is a package resolution operator or 'this' ? int pkg_index = -1; if (node->operand_left_->GetType() == ANT_EXP_LEAF) { AstExpressionLeaf* left_leaf = (AstExpressionLeaf*)node->operand_left_; pkg_index = left_leaf->pkg_index_; if (pkg_index >= 0) { GetFullExternName(dst, pkg_index, right_leaf->value_.c_str()); return(KLeafPriority); } else if (left_leaf->subtype_ == TOKEN_THIS) { if (!right_leaf->unambiguous_member_access) { *dst = "this->"; } AppendMemberName(dst, right_leaf->wp_decl_); return(priority); } } priority = SynthExpression(dst, node->operand_left_); const ExpressionAttributes *left_attr = node->operand_left_->GetAttr(); if (left_attr->IsEnum()) { *dst += "::"; *dst += right_leaf->value_; priority = KLeafPriority; } else if (node->builtin_ != nullptr) { if (left_attr->IsPointer()) { Protect(dst, priority, GetUnopCppPriority(TOKEN_MPY)); dst->insert(0, "*"); priority = GetUnopCppPriority(TOKEN_MPY); } BInSynthMode builtin_mode = GetBuiltinSynthMode(node->builtin_signature_); switch (builtin_mode) { case BInSynthMode::sing: dst->insert(0, "("); dst->insert(0, right_leaf->value_); dst->insert(0, "sing::"); (*dst) += ")"; priority = GetUnopCppPriority(TOKEN_ROUND_OPEN); break; case BInSynthMode::std: dst->insert(0, "("); dst->insert(0, right_leaf->value_); dst->insert(0, "std::"); (*dst) += ")"; priority = GetUnopCppPriority(TOKEN_ROUND_OPEN); break; case BInSynthMode::cast: case BInSynthMode::plain: { dst->insert(0, "("); dst->insert(0, right_leaf->value_); if (root_->namespace_.length() > 0) { dst->insert(0, "::"); } (*dst) += ")"; priority = GetUnopCppPriority(TOKEN_ROUND_OPEN); Token base_type = node->operand_left_->GetAttr()->GetAutoBaseType(); if (base_type != TOKEN_FLOAT64 && builtin_mode != BInSynthMode::plain) { priority = AddCast(dst, priority, GetBaseTypeName(base_type)); } } break; case BInSynthMode::member: default: Protect(dst, priority, GetBinopCppPriority(TOKEN_DOT)); (*dst) += "."; (*dst) += right_leaf->value_; (*dst) += "()"; priority = GetUnopCppPriority(TOKEN_ROUND_OPEN); break; } } else { if (left_attr->IsPointer()) { Protect(dst, priority, GetUnopCppPriority(TOKEN_MPY)); dst->insert(0, "(*"); *dst += ")."; } else { // ANT_CLASS_TYPE Protect(dst, priority, GetBinopCppPriority(TOKEN_DOT)); *dst += "."; } AppendMemberName(dst, right_leaf->wp_decl_); priority = GetBinopCppPriority(TOKEN_DOT); } return(priority); } int CppSynth::SynthPowerOperator(string *dst, AstBinop *node) { string right; int priority = GetBinopCppPriority(node->subtype_); int left_priority = SynthExpression(dst, node->operand_left_); int right_priority = SynthExpression(&right, node->operand_right_); const ExpressionAttributes *left_attr = node->operand_left_->GetAttr(); const ExpressionAttributes *right_attr = node->operand_right_->GetAttr(); const ExpressionAttributes *result_attr = node->GetAttr(); const NumericValue *right_value = right_attr->GetValue(); Token left_type = left_attr->GetAutoBaseType(); Token right_type = right_attr->GetAutoBaseType(); Token result_type = result_attr->GetAutoBaseType(); // pow2 ? if (right_attr->HasKnownValue() && !right_value->IsComplex() && right_value->GetDouble() == 2) { if (left_type != result_type) { left_priority = AddCast(dst, left_priority, GetBaseTypeName(result_type)); } dst->insert(0, "sing::pow2("); *dst += ")"; return(priority); } else { if (ExpressionAttributes::BinopRequiresNumericConversion(left_attr, right_attr, TOKEN_POWER)) { assert(false); // since we do no authomatic conversion if (left_type != result_type) { left_priority = AddCast(dst, left_priority, GetBaseTypeName(result_type)); } if (right_type != result_type) { right_priority = AddCast(&right, right_priority, GetBaseTypeName(result_type)); } } else { left_priority = PromoteToInt32(left_type, dst, left_priority); } if (result_attr->IsInteger()) { dst->insert(0, "sing::pow("); } else { dst->insert(0, "std::pow("); } *dst += ", "; *dst += right; *dst += ")"; } return(priority); } int CppSynth::SynthMathOperator(string *dst, AstBinop *node) { string right; const ExpressionAttributes *left_attr = node->operand_left_->GetAttr(); const ExpressionAttributes *right_attr = node->operand_right_->GetAttr(); const ExpressionAttributes *result_attr = node->GetAttr(); Token left_type = left_attr->GetAutoBaseType(); Token right_type = right_attr->GetAutoBaseType(); Token result_type = result_attr->GetAutoBaseType(); if (node->subtype_ == TOKEN_PLUS && left_type == TOKEN_STRING && right_type == TOKEN_STRING) { string format, parms; ProcessStringSumOperand(&format, &parms, node->operand_left_); ProcessStringSumOperand(&format, &parms, node->operand_right_); bool left_is_literal = IsLiteralString(node->operand_left_); bool right_is_literal = IsLiteralString(node->operand_right_); bool left_is_const_char = left_is_literal || IsInputArg(node->operand_left_); bool right_is_const_char = right_is_literal || IsInputArg(node->operand_right_); if (format != "%s%s" || left_is_const_char && right_is_const_char) { if (left_is_literal && right_is_literal) { *dst += ((AstExpressionLeaf*)node->operand_left_)->value_; *dst += ' '; *dst += ((AstExpressionLeaf*)node->operand_right_)->value_; return(KForcedPriority); } else { *dst = "sing::s_format(\""; *dst += format; *dst += "\""; *dst += parms; *dst += ")"; return(KForcedPriority); } } // else can simply use the + operator. } int priority = GetBinopCppPriority(node->subtype_); int left_priority = SynthExpression(dst, node->operand_left_); int right_priority = SynthExpression(&right, node->operand_right_); if (ExpressionAttributes::BinopRequiresNumericConversion(left_attr, right_attr, node->subtype_)) { assert(false); // since we do no authomatic conversion if (left_type != result_type) { left_priority = CastIfNeededTo(result_type, left_type, dst, left_priority, false); } if (right_type != result_type) { right_priority = CastIfNeededTo(result_type, right_type, &right, right_priority, false); } } // add brackets if needed Protect(dst, left_priority, priority); Protect(&right, right_priority, priority, true); // sinthesize the operation if (node->subtype_ == TOKEN_MIN || node->subtype_ == TOKEN_MAX) { if (node->subtype_ == TOKEN_MIN) { dst->insert(0, "std::min("); } else { dst->insert(0, "std::max("); } *dst += ", "; AddSplitMarker(dst); *dst += right; *dst += ')'; } else { if (node->subtype_ == TOKEN_XOR) { *dst += " ^ "; } else { *dst += ' '; *dst += Lexer::GetTokenString(node->subtype_); *dst += ' '; } AddSplitMarker(dst); *dst += right; } return(priority); } int CppSynth::SynthRelationalOperator(string *dst, AstBinop *node) { return(SynthRelationalOperator3(dst, node->subtype_, node->operand_left_, node->operand_right_)); } int CppSynth::SynthRelationalOperator3(string *dst, Token subtype, IAstExpNode *operand_left, IAstExpNode *operand_right) { string right; int priority = GetBinopCppPriority(subtype); int left_priority = SynthExpression(dst, operand_left); int right_priority = SynthExpression(&right, operand_right); const ExpressionAttributes *left_attr = operand_left->GetAttr(); const ExpressionAttributes *right_attr = operand_right->GetAttr(); Token left_type = left_attr->GetAutoBaseType(); Token right_type = right_attr->GetAutoBaseType(); if (left_attr->IsInteger() && right_attr->IsInteger()) { // use special function in case of signed-unsigned comparison bool left_is_uint64 = left_type == TOKEN_UINT64; bool right_is_uint64 = right_type == TOKEN_UINT64; bool left_is_int64 = left_type == TOKEN_INT64; bool right_is_int64 = right_type == TOKEN_INT64; bool left_is_uint32 = left_type == TOKEN_UINT32; bool right_is_uint32 = right_type == TOKEN_UINT32; bool left_is_int32 = left_type == TOKEN_INT32 || left_attr->RequiresPromotion(); bool right_is_int32 = right_type == TOKEN_INT32 || right_attr->RequiresPromotion(); bool use_function = left_is_uint64 && right_is_int64 || left_is_uint64 && right_is_int32 || left_is_uint32 && right_is_int32; bool use_function_swap = right_is_uint64 && left_is_int64 || right_is_uint64 && left_is_int32 || right_is_uint32 && left_is_int32; if (use_function) { switch (subtype) { case TOKEN_ANGLE_OPEN_LT: dst->insert(0, "sing::isless("); break; case TOKEN_ANGLE_CLOSE_GT: dst->insert(0, "sing::ismore("); break; case TOKEN_GTE: dst->insert(0, "sing::ismore_eq("); break; case TOKEN_LTE: dst->insert(0, "sing::isless_eq("); break; case TOKEN_DIFFERENT: dst->insert(0, "!sing::iseq("); break; case TOKEN_EQUAL: dst->insert(0, "sing::iseq("); break; } *dst += ", "; AddSplitMarker(dst); *dst += right; *dst += ")"; return(subtype == TOKEN_DIFFERENT ? GetUnopCppPriority(TOKEN_LOGICAL_NOT) : KForcedPriority); } if (use_function_swap) { switch (subtype) { case TOKEN_ANGLE_OPEN_LT: right.insert(0, "sing::ismore("); break; case TOKEN_ANGLE_CLOSE_GT: right.insert(0, "sing::isless("); break; case TOKEN_GTE: right.insert(0, "sing::isless_eq("); break; case TOKEN_LTE: right.insert(0, "sing::ismore_eq("); break; case TOKEN_DIFFERENT: right.insert(0, "!sing::iseq("); break; case TOKEN_EQUAL: right.insert(0, "sing::iseq("); break; } right += ", "; AddSplitMarker(&right); dst->insert(0, right); *dst += ")"; return(subtype == TOKEN_DIFFERENT ? GetUnopCppPriority(TOKEN_LOGICAL_NOT) : KForcedPriority); } } else if (left_attr->IsNumber()) { CastForRelational(left_type, right_type, dst, &right, &left_priority, &right_priority); } else if (left_attr->IsString() && right_attr->IsString()) { if (IsLiteralString(operand_left) || IsInputArg(operand_left)) { if (IsLiteralString(operand_right) || IsInputArg(operand_right)) { dst->insert(0, "::strcmp("); *dst += ", "; *dst += right; *dst += ") "; *dst += Lexer::GetTokenString(subtype); *dst += " 0"; return(priority); } } } // add brackets if needed Protect(dst, left_priority, priority); Protect(&right, right_priority, priority, true); // sinthesize the operation *dst += ' '; *dst += Lexer::GetTokenString(subtype); *dst += ' '; AddSplitMarker(dst); *dst += right; return(priority); } int CppSynth::SynthLogicalOperator(string *dst, AstBinop *node) { string right; int priority = GetBinopCppPriority(node->subtype_); int left_priority = SynthExpression(dst, node->operand_left_); int right_priority = SynthExpression(&right, node->operand_right_); // add brackets if needed Protect(dst, left_priority, priority); Protect(&right, right_priority, priority, true); // sinthesize the operation *dst += ' '; *dst += Lexer::GetTokenString(node->subtype_); *dst += ' '; AddSplitMarker(dst); *dst += right; return(priority); } int CppSynth::SynthUnop(string *dst, AstUnop *node) { int exp_priority, priority; if (node->subtype_ == TOKEN_SIZEOF) { priority = KForcedPriority; } else { priority = 3; } if (node->operand_ != nullptr) { exp_priority = SynthExpression(dst, node->operand_); } switch (node->subtype_) { case TOKEN_SIZEOF: if (node->type_ != NULL) { SynthTypeSpecification(dst, node->type_); } dst->insert(0, "sizeof("); *dst += ')'; break; case TOKEN_MINUS: Protect(dst, exp_priority, priority); dst->insert(0, "-"); break; case TOKEN_NOT: Protect(dst, exp_priority, priority); dst->insert(0, "~"); break; case TOKEN_AND: Protect(dst, exp_priority, priority); if ((*dst)[0] == '*') { dst->erase(0, 1); } else { dst->insert(0, "&"); } break; case TOKEN_MPY: Protect(dst, exp_priority, priority); if ((*dst)[0] == '&') { dst->erase(0, 1); } else { dst->insert(0, "*"); } break; case TOKEN_PLUS: case TOKEN_LOGICAL_NOT: Protect(dst, exp_priority, priority); dst->insert(0, Lexer::GetTokenString(node->subtype_)); break; case TOKEN_INT8: case TOKEN_INT16: case TOKEN_INT32: case TOKEN_INT64: case TOKEN_UINT8: case TOKEN_UINT16: case TOKEN_UINT32: case TOKEN_UINT64: case TOKEN_FLOAT32: case TOKEN_FLOAT64: priority = SynthCastToScalar(dst, node, exp_priority); break; case TOKEN_COMPLEX64: case TOKEN_COMPLEX128: priority = SynthCastToComplex(dst, node, exp_priority); break; case TOKEN_STRING: priority = SynthCastToString(dst, node); break; case TOKEN_DEF: priority = GetBinopCppPriority(TOKEN_EQUAL); dst->erase(0, 1); // legal args of def are variables requiring indirection: delete '*' // Protect(dst, exp_priority, priority); // no need - exp can only be a single name *dst += " != nullptr"; break; } return(priority); } int CppSynth::SynthCastToScalar(string *dst, AstUnop *node, int priority) { const ExpressionAttributes *src_attr; bool explicit_cast = true; src_attr = node->operand_->GetAttr(); if (src_attr->HasComplexType()) { Protect(dst, priority, GetBinopCppPriority(TOKEN_DOT)); *dst += ".real()"; priority = GetBinopCppPriority(TOKEN_DOT); if (src_attr->GetAutoBaseType() == TOKEN_COMPLEX64) { explicit_cast = node->subtype_ != TOKEN_FLOAT32; } else { explicit_cast = node->subtype_ != TOKEN_FLOAT64; } } else if (src_attr->IsString()) { switch (node->subtype_) { case TOKEN_INT8: case TOKEN_INT16: case TOKEN_INT32: case TOKEN_INT64: dst->insert(0, "sing::string2int("); *dst += ")"; priority = KForcedPriority; explicit_cast = node->subtype_ != TOKEN_INT64; break; case TOKEN_UINT8: case TOKEN_UINT16: case TOKEN_UINT32: case TOKEN_UINT64: dst->insert(0, "sing::string2uint("); *dst += ")"; priority = KForcedPriority; explicit_cast = node->subtype_ != TOKEN_UINT64; break; case TOKEN_FLOAT32: case TOKEN_FLOAT64: dst->insert(0, "sing::string2double("); *dst += ")"; priority = KForcedPriority; explicit_cast = node->subtype_ != TOKEN_FLOAT64; break; } } if (explicit_cast) { priority = AddCast(dst, priority, GetBaseTypeName(node->subtype_)); } return(priority); } int CppSynth::SynthCastToComplex(string *dst, AstUnop *node, int priority) { const ExpressionAttributes *src_attr; src_attr = node->operand_->GetAttr(); if (src_attr->HasComplexType()) { Token src_type = src_attr->GetAutoBaseType(); if (src_attr->GetAutoBaseType() == TOKEN_COMPLEX64 && node->subtype_ == TOKEN_COMPLEX128) { dst->insert(0, "sing::c_f2d("); } else if (src_attr->GetAutoBaseType() == TOKEN_COMPLEX128 && node->subtype_ == TOKEN_COMPLEX64) { dst->insert(0, "sing::c_d2f("); } *dst += ")"; } else if (src_attr->IsString()) { if (node->subtype_ == TOKEN_COMPLEX128) { dst->insert(0, "sing::string2complex128("); } else { dst->insert(0, "sing::string2complex64("); } *dst += ")"; priority = KForcedPriority; } else { Token src_type = src_attr->GetAutoBaseType(); if (node->subtype_ == TOKEN_COMPLEX128) { if (src_type == TOKEN_INT64 || src_type == TOKEN_UINT64) { priority = AddCast(dst, priority, "double"); } priority = AddCast(dst, priority, "std::complex<double>"); } else { if (src_type == TOKEN_INT64 || src_type == TOKEN_UINT64 || src_type == TOKEN_INT32 || src_type == TOKEN_UINT32) { priority = AddCast(dst, priority, "float"); } priority = AddCast(dst, priority, "std::complex<float>"); } } return(priority); } int CppSynth::SynthCastToString(string *dst, AstUnop *node) { bool use_sing_fun = false; if (node->operand_ != nullptr) { const ExpressionAttributes *attr = node->operand_->GetAttr(); use_sing_fun = attr->IsComplex() || attr->IsBool(); } if (use_sing_fun) { dst->insert(0, "sing::to_string("); } else { dst->insert(0, "std::to_string("); } *dst += ")"; return(KForcedPriority); } void CppSynth::ProcessStringSumOperand(string *format, string *parms, IAstExpNode *node) { string operand; if (node->GetType() == ANT_UNOP && ((AstUnop*)node)->subtype_ == TOKEN_STRING) { // CASE 1: a conversion. generate a type specifier based on the underlying type IAstExpNode *child = ((AstUnop*)node)->operand_; Token basetype = child->GetAttr()->GetAutoBaseType(); switch (basetype) { case TOKEN_INT8: case TOKEN_INT16: case TOKEN_INT32: *format += "%d"; break; case TOKEN_INT64: *format += "%lld"; break; case TOKEN_UINT8: case TOKEN_UINT16: case TOKEN_UINT32: *format += "%u"; break; case TOKEN_UINT64: *format += "%llu"; break; case TOKEN_FLOAT32: case TOKEN_FLOAT64: *format += "%f"; break; case TOKEN_COMPLEX64: case TOKEN_COMPLEX128: *format += "%s"; break; case TOKEN_BOOL: *format += "%s"; break; case TOKEN_STRING: *format += "%s"; break; default: assert(false); } int priority = SynthExpression(&operand, child); if (basetype == TOKEN_COMPLEX64 || basetype == TOKEN_COMPLEX128) { operand.insert(0, "sing::to_string("); operand += ").c_str()"; } else if (basetype == TOKEN_BOOL) { if (operand == "true" || operand == "false") { operand.insert(0, "\""); operand += "\""; } else { operand += " ? \"true\" : \"false\""; } } } else { if (node->GetType() == ANT_BINOP) { IAstExpNode *node_left = ((AstBinop*)node)->operand_left_; IAstExpNode *node_right = ((AstBinop*)node)->operand_right_; Token left_type = node_left->GetAttr()->GetAutoBaseType(); Token right_type = node_right->GetAttr()->GetAutoBaseType(); if (((AstBinop*)node)->subtype_ == TOKEN_PLUS && (left_type == TOKEN_STRING || right_type == TOKEN_STRING)) { // CASE 2: a sum of strings. recur ProcessStringSumOperand(format, parms, node_left); ProcessStringSumOperand(format, parms, node_right); return; } assert(false); } // CASE 3: leaf string const ExpressionAttributes *attr = node->GetAttr(); *format += "%s"; int priority = SynthExpression(&operand, node); if (!IsLiteralString(node) && !IsInputArg(node)) { Protect(&operand, priority, GetBinopCppPriority(TOKEN_DOT)); operand += ".c_str()"; } } *parms += ", "; AddSplitMarker(parms); *parms += operand; } int CppSynth::SynthLeaf(string *dst, AstExpressionLeaf *node) { int priority = KLeafPriority; switch (node->subtype_) { case TOKEN_NULL: *dst = "nullptr"; break; case TOKEN_FALSE: case TOKEN_TRUE: *dst = Lexer::GetTokenString(node->subtype_); break; case TOKEN_LITERAL_STRING: *dst = node->value_; break; case TOKEN_INT32: priority = GetRealPartOfIntegerLiteral(dst, node, 32); break; case TOKEN_INT64: priority = GetRealPartOfIntegerLiteral(dst, node, 64); *dst += "LL"; break; case TOKEN_UINT32: GetRealPartOfUnsignedLiteral(dst, node); *dst += "U"; break; case TOKEN_UINT64: GetRealPartOfUnsignedLiteral(dst, node); *dst += "LLU"; break; case TOKEN_FLOAT32: priority = GetRealPartOfFloatLiteral(dst, node); *dst += "f"; break; case TOKEN_FLOAT64: priority = GetRealPartOfFloatLiteral(dst, node); break; case TOKEN_COMPLEX64: SynthComplex64(dst, node); break; case TOKEN_COMPLEX128: SynthComplex128(dst, node); break; case TOKEN_LITERAL_UINT: *dst = node->value_; dst->erase_occurrencies_of('_'); break; case TOKEN_LITERAL_FLOAT: *dst = node->value_; *dst += "f"; dst->erase_occurrencies_of('_'); break; case TOKEN_LITERAL_IMG: GetImgPartOfLiteral(dst, node->value_.c_str(), false, false); dst->insert(0, "std::complex<float>(0.0f, "); *dst += ')'; break; case TOKEN_THIS: *dst = "*this"; priority = GetUnopCppPriority(TOKEN_MPY); break; case TOKEN_NAME: { IAstDeclarationNode *decl = node->wp_decl_; bool needs_dereferencing = false; if (decl->GetType() == ANT_VAR) { needs_dereferencing = VarNeedsDereference((VarDeclaration*)decl); } if (needs_dereferencing) { *dst = "*"; *dst += node->value_; priority = GetUnopCppPriority(TOKEN_MPY); } else { *dst = node->value_; } } break; } return(priority); } void CppSynth::SynthComplex64(string *dst, AstExpressionLeaf *node) { GetRealPartOfFloatLiteral(dst, node); dst->insert(0, "std::complex<float>("); if (node->img_value_ == "") { *dst += "f, 0.0f)"; } else { string img; GetImgPartOfLiteral(&img, node->img_value_.c_str(), false, node->img_is_negated_); *dst += "f, "; *dst += img; *dst += ')'; } } void CppSynth::SynthComplex128(string *dst, AstExpressionLeaf *node) { GetRealPartOfFloatLiteral(dst, node); dst->insert(0, "std::complex<double>("); if (node->img_value_ == "") { *dst += ", 0.0)"; } else { string img; GetImgPartOfLiteral(&img, node->img_value_.c_str(), node->subtype_ == TOKEN_COMPLEX128, node->img_is_negated_); *dst += ", "; *dst += img; *dst += ')'; } } int CppSynth::GetRealPartOfIntegerLiteral(string *dst, AstExpressionLeaf *node, int nbits) { int64_t value; int priority = KLeafPriority; node->GetAttr()->GetSignedIntegerValue(&value); if (node->real_is_int_) { // keep the original format (es. hex..) *dst = node->value_; dst->erase_occurrencies_of('_'); if (node->real_is_negated_) { dst->insert(0, "-"); } } else { char buffer[100]; // must have an integer value. Use it and discard the original floating point representation. sprintf(buffer, "%" PRId64, value); *dst = buffer; } if (nbits == 32 && value == -(int64_t)0x80000000) { dst->insert(0, "(int32_t)"); *dst += "LL"; priority = KCastPriority; } else if ((*dst)[0] == '-') { priority = GetUnopCppPriority(TOKEN_MINUS); } return(priority); } void CppSynth::GetRealPartOfUnsignedLiteral(string *dst, AstExpressionLeaf *node) { if (node->real_is_int_) { // keep the original format (es. hex..) *dst = node->value_; dst->erase_occurrencies_of('_'); } else { uint64_t value; char buffer[100]; // must have an integer value. Use it and discard the original floating point representation. value = node->GetAttr()->GetUnsignedValue(); sprintf(buffer, "%" PRIu64, value); *dst = buffer; } } int CppSynth::GetRealPartOfFloatLiteral(string *dst, AstExpressionLeaf *node) { if (IsFloatFormat(node->value_.c_str())) { *dst = node->value_; dst->erase_occurrencies_of('_'); if (node->real_is_negated_) { dst->insert(0, "-"); } } else { int64_t value; char buffer[100]; // must have an integer value. Use it and convert to a floating point representation. value = (int64_t)node->GetAttr()->GetDoubleValue(); sprintf(buffer, "%" PRId64 ".0", value); *dst = buffer; } if ((*dst)[0] == '-') { return(GetUnopCppPriority(TOKEN_MINUS)); } return(KLeafPriority); } void CppSynth::GetImgPartOfLiteral(string *dst, const char *src, bool is_double, bool is_negated) { *dst = src; dst->erase_occurrencies_of('_'); dst->erase(dst->length() - 1); // erase 'i' if (!IsFloatFormat(src)) { *dst += ".0"; } if (!is_double) { *dst += "f"; } if (is_negated) { dst->insert(0, "-"); } } bool IsFloatFormat(const char *num) { return (strchr(num, 'e') != nullptr || strchr(num, 'E') != nullptr || strchr(num, '.') != nullptr); } void CppSynth::Write(string *text, bool add_semicolon) { if (add_semicolon) { *text += ';'; } // adds indentation and line feed, // if appropriate splits the line at the split markers, // adds comments formatter_.Format(text, indent_); const char *bufout = formatter_.GetString(); int length = formatter_.GetLength(); *file_str_ += bufout; } void CppSynth::AddSplitMarker(string *dst) { *dst += MAX(split_level_, 0xf8); } int CppSynth::AddForcedSplit(string *dst, IAstNode *node1, int row) { int newrow = node1->GetPositionRecord()->start_row; if (newrow != row) { *dst += 0xff; } return(newrow); } void CppSynth::EmptyLine(void) { formatter_.AddLineBreak(); } const char *CppSynth::GetBaseTypeName(Token token) { switch (token) { case TOKEN_INT8: return("int8_t"); case TOKEN_INT16: return("int16_t"); case TOKEN_INT32: return("int32_t"); case TOKEN_INT64: return("int64_t"); case TOKEN_UINT8: return("uint8_t"); case TOKEN_UINT16: return("uint16_t"); case TOKEN_UINT32: return("uint32_t"); case TOKEN_UINT64: return("uint64_t"); case TOKEN_FLOAT32: return("float"); case TOKEN_FLOAT64: return("double"); case TOKEN_COMPLEX64: return("std::complex<float>"); case TOKEN_COMPLEX128: return("std::complex<double>"); case TOKEN_STRING: return("std::string"); case TOKEN_BOOL: return("bool"); case TOKEN_VOID: return("void"); } return(""); } int CppSynth::GetBinopCppPriority(Token token) { switch (token) { case TOKEN_POWER: case TOKEN_MIN: case TOKEN_MAX: return(KForcedPriority); // means "doesn't require parenthesys/doesn't take precedence over childrens." case TOKEN_DOT: return(2); case TOKEN_MPY: case TOKEN_DIVIDE: case TOKEN_MOD: return(5); case TOKEN_SHR: case TOKEN_SHL: return(7); case TOKEN_AND: return(11); case TOKEN_PLUS: case TOKEN_MINUS: return(6); case TOKEN_OR: return(13); case TOKEN_XOR: return(12); case TOKEN_ANGLE_OPEN_LT: case TOKEN_ANGLE_CLOSE_GT: case TOKEN_GTE: case TOKEN_LTE: return(9); case TOKEN_DIFFERENT: case TOKEN_EQUAL: return(10); case TOKEN_LOGICAL_AND: return(14); case TOKEN_LOGICAL_OR: return(15); default: assert(false); break; } return(KForcedPriority); } int CppSynth::GetUnopCppPriority(Token token) { switch (token) { case TOKEN_SQUARE_OPEN: // subscript case TOKEN_ROUND_OPEN: // function call case TOKEN_INC: case TOKEN_DEC: case TOKEN_DOT: return(2); case TOKEN_SIZEOF: return(KForcedPriority); case TOKEN_MINUS: case TOKEN_PLUS: case TOKEN_NOT: // bitwise not case TOKEN_AND: // address case TOKEN_LOGICAL_NOT: case TOKEN_MPY: // dereference default: // casts break; } return(3); } bool CppSynth::VarNeedsDereference(VarDeclaration *var) { if (var->HasOneOfFlags(VF_ISPOINTED)) return(true); if (var->HasOneOfFlags(VF_ISARG)) { // output and not a vector return(GetParameterPassingMethod(var->GetTypeSpec(), var->HasOneOfFlags(VF_READONLY)) == PPM_POINTER); } return(false); } void CppSynth::PrependWithSeparator(string *dst, const char *src) { if (dst->length() == 0) { *dst = src; } else { dst->insert(0, src); dst->insert(strlen(src), " "); } } int CppSynth::AddCast(string *dst, int priority, const char *cast_type) { char prefix[100]; if (cast_type == nullptr || cast_type[0] == 0) { return(priority); } if (priority > KCastPriority) { sprintf(prefix, "(%s)(", cast_type); dst->insert(0, prefix); *dst += ")"; } else { sprintf(prefix, "(%s)", cast_type); dst->insert(0, prefix); } return(KCastPriority); } void CppSynth::CutDecimalPortionAndSuffix(string *dst) { int cut_point = dst->find('.'); if (cut_point != string::npos) { dst->erase(cut_point); return; } // if '.' was not found this could be an integer with an 'll' suffix CutSuffix(dst); } void CppSynth::CutSuffix(string *dst) { int ii; for (ii = dst->length() - 1; ii > 0 && dst->c_str()[ii] == 'l'; --ii); dst->erase(ii + 1); } // // casts numerics if c++ doesn't automatically cast to target // int CppSynth::CastIfNeededTo(Token target, Token src_type, string *dst, int priority, bool for_power_op) { if (target == src_type || target == TOKEN_BOOL || target == TOKEN_STRING || target == TOKENS_COUNT) { return(priority); } if (target == TOKEN_COMPLEX128) { if (src_type == TOKEN_COMPLEX64) { dst->insert(0, "sing::c_f2d("); *dst += ")"; return(KForcedPriority); } else if (src_type != TOKEN_COMPLEX128 && src_type != TOKEN_FLOAT64) { priority = AddCast(dst, priority, "double"); } return(priority); } if (target == TOKEN_COMPLEX64) { if (src_type == TOKEN_COMPLEX128) { dst->insert(0, "sing::c_d2f("); *dst += ")"; return(KForcedPriority); } else if (src_type != TOKEN_COMPLEX64 && src_type != TOKEN_FLOAT32) { priority = AddCast(dst, priority, "float"); } return(priority); } // the target is scalar if (src_type == TOKEN_COMPLEX128 || src_type == TOKEN_COMPLEX64) { Protect(dst, priority, GetBinopCppPriority(TOKEN_DOT)); *dst += ".real()"; priority = GetBinopCppPriority(TOKEN_DOT); src_type = (src_type == TOKEN_COMPLEX128) ? TOKEN_FLOAT64 : TOKEN_FLOAT32; } if (ExpressionAttributes::CanAssignWithoutLoss(target, src_type)) { return(priority); } priority = AddCast(dst, priority, GetBaseTypeName(target)); return(priority); } void CppSynth::CastForRelational(Token left_type, Token right_type, string *left, string *right, int *priority_left, int *priority_right) { // complex comparison if (left_type == TOKEN_COMPLEX128 || right_type == TOKEN_COMPLEX128 || left_type == TOKEN_COMPLEX64 && right_type == TOKEN_FLOAT64 || right_type == TOKEN_COMPLEX64 && left_type == TOKEN_FLOAT64) { *priority_left = CastIfNeededTo(TOKEN_COMPLEX128, left_type, left, *priority_left, false); *priority_right = CastIfNeededTo(TOKEN_COMPLEX128, right_type, right, *priority_right, false); } else if (left_type == TOKEN_COMPLEX64 || right_type == TOKEN_COMPLEX64) { *priority_left = CastIfNeededTo(TOKEN_COMPLEX64, left_type, left, *priority_left, false); *priority_right = CastIfNeededTo(TOKEN_COMPLEX64, right_type, right, *priority_right, false); } else if (left_type == TOKEN_FLOAT64 || right_type == TOKEN_FLOAT64) { *priority_left = CastIfNeededTo(TOKEN_FLOAT64, left_type, left, *priority_left, false); *priority_right = CastIfNeededTo(TOKEN_FLOAT64, right_type, right, *priority_right, false); } else { // we are sure than not both the values are integers, so we know that at least one is float *priority_left = CastIfNeededTo(TOKEN_FLOAT32, left_type, left, *priority_left, false); *priority_right = CastIfNeededTo(TOKEN_FLOAT32, right_type, right, *priority_right, false); } } int CppSynth::PromoteToInt32(Token target, string *dst, int priority) { switch (target) { case TOKEN_INT16: case TOKEN_INT8: case TOKEN_UINT16: case TOKEN_UINT8: return(AddCast(dst, priority, "int32_t")); default: break; } return(priority); } // adds brackets if adding the next operator would invert the priority // to be done to operands after casts and before operation void CppSynth::Protect(string *dst, int priority, int next_priority, bool is_right_term) { // a function-like operator: needs no protection and causes no inversion if (priority == KForcedPriority || next_priority == KForcedPriority) return; // protect the priority of this branch from adjacent operators // note: if two binary operators have same priority, use brackets if right-associativity is required if (next_priority < priority || is_right_term && priority > 3 && next_priority == priority) { dst->insert(0, "("); *dst += ')'; } } bool CppSynth::IsPOD(IAstTypeNode *node) { bool ispod = true; switch (node->GetType()) { case ANT_BASE_TYPE: switch (((AstBaseType*)node)->base_type_) { case TOKEN_COMPLEX64: case TOKEN_COMPLEX128: case TOKEN_STRING: ispod = false; default: break; } break; case ANT_NAMED_TYPE: ispod = IsPOD(((AstNamedType*)node)->wp_decl_->type_spec_); break; case ANT_ARRAY_TYPE: case ANT_MAP_TYPE: case ANT_POINTER_TYPE: ispod = false; break; case ANT_FUNC_TYPE: case ANT_ENUM_TYPE: default: break; } return(ispod); } Token CppSynth::GetBaseType(const IAstTypeNode *node) { switch (node->GetType()) { case ANT_BASE_TYPE: return(((AstBaseType*)node)->base_type_); case ANT_NAMED_TYPE: return(GetBaseType(((AstNamedType*)node)->wp_decl_->type_spec_)); default: break; } return(TOKENS_COUNT); } void CppSynth::GetFullExternName(string *full, int pkg_index, const char *local_name) { const Package *pkg = pkmgr_->getPkg(pkg_index); assert(pkg != nullptr); if (pkg != nullptr) { const string *nspace = &pkg->GetRoot()->namespace_; if (root_->namespace_ != *nspace) { const char *src = nspace->c_str(); (*full) = ""; for (int ii = 0; ii < (int)nspace->length(); ++ii) { if (src[ii] != '.') { (*full) += src[ii]; } else { (*full) += "::"; } } (*full) += "::"; (*full) += local_name; } else { (*full) = local_name; } } else { (*full) = local_name; } } bool CppSynth::IsLiteralString(IAstExpNode *node) { if (node->GetType() == ANT_EXP_LEAF) { AstExpressionLeaf *leaf = (AstExpressionLeaf*)node; return (leaf->subtype_ == TOKEN_LITERAL_STRING); } else if (node->GetType() == ANT_BINOP) { AstBinop *op = (AstBinop*)node; return(IsLiteralString(op->operand_left_) && IsLiteralString(op->operand_right_)); } return(false); } bool CppSynth::IsInputArg(IAstExpNode *node) { if (node->GetType() == ANT_EXP_LEAF) { AstExpressionLeaf *leaf = (AstExpressionLeaf*)node; if (leaf->subtype_ == TOKEN_NAME) { IAstDeclarationNode *decl = leaf->wp_decl_; if (decl != nullptr && decl->GetType() == ANT_VAR) { VarDeclaration *var = (VarDeclaration*)decl; return(var->HasAllFlags(VF_ISARG | VF_READONLY)); } } } return(false); } int CppSynth::WriteHeaders(DependencyUsage usage) { string text; int num_items = 0; for (int ii = 0; ii < (int)root_->dependencies_.size(); ++ii) { AstDependency *dependency = root_->dependencies_[ii]; if (dependency->GetUsage() == usage) { text = dependency->package_dir_.c_str(); FileName::ExtensionSet(&text, "h"); text.insert(0, "#include \""); text += "\""; formatter_.SetNodePos(dependency); Write(&text, false); ++num_items; } } return(num_items); } int CppSynth::WriteNamespaceOpening(void) { int num_levels = 0; const char *scan = root_->namespace_.c_str(); if (*scan != 0) { string text; while (*scan != 0) { text = "namespace "; while (*scan != '.' && *scan != 0) { text += *scan++; } text += " {"; Write(&text, false); while (*scan == '.') ++scan; ++num_levels; } } if (num_levels > 0) { EmptyLine(); } return(num_levels); } void CppSynth::WriteNamespaceClosing(int num_levels) { if (num_levels > 0) { EmptyLine(); string closing; for (int ii = 0; ii < num_levels; ++ii) { closing = "} // namespace"; Write(&closing, false); } } } void CppSynth::WriteClassForwardDeclarations(bool public_defs) { bool empty_section = true; string text; ForwardReferenceType reftype = public_defs ? FRT_PUBLIC : FRT_PRIVATE; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_TYPE) { TypeDeclaration *tdecl = (TypeDeclaration*)declaration; if (tdecl->forward_referral_ != reftype) continue; text = "class "; text += tdecl->name_; Write(&text); empty_section = false; } } if (!empty_section) { EmptyLine(); } } int CppSynth::WriteTypeDefinitions(bool public_defs) { int num_items = 0; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->IsPublic() != public_defs) continue; switch (declaration->GetType()) { case ANT_VAR: { VarDeclaration *var = (VarDeclaration*)declaration; if (var->HasOneOfFlags(VF_IMPLEMENTED_AS_CONSTINT)) { formatter_.SetNodePos(var); SynthVar(var); ++num_items; } } break; case ANT_TYPE: formatter_.SetNodePos(declaration); SynthType((TypeDeclaration*)declaration); ++num_items; break; default: break; } } if (num_items > 0) { EmptyLine(); } return(num_items); } void CppSynth::WritePrototypes(bool public_defs) { bool empty_section = true; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->IsPublic() != public_defs) continue; if (declaration->GetType() == ANT_FUNC) { FuncDeclaration *func = (FuncDeclaration*)declaration; if (!func->is_class_member_) { if (func->block_ == nullptr) { formatter_.SetNodePos(declaration); } text = func->name_; SynthFuncTypeSpecification(&text, func->function_type_, true); if (!public_defs) { text.insert(0, "static "); } Write(&text); empty_section = false; } } } if (!empty_section) { EmptyLine(); } } void CppSynth::WriteExternalDeclarations(void) { bool empty_section = true; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (!declaration->IsPublic()) continue; if (declaration->GetType() == ANT_VAR) { VarDeclaration *var = (VarDeclaration*)declaration; if (!var->HasOneOfFlags(VF_IMPLEMENTED_AS_CONSTINT)) { text = var->name_; SynthTypeSpecification(&text, var->GetTypeSpec()); text.insert(0, "extern const "); Write(&text); empty_section = false; } } } if (!empty_section) { EmptyLine(); } } int CppSynth::WriteVariablesDefinitions(void) { int num_items = 0; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_VAR) { VarDeclaration *var = (VarDeclaration*)declaration; if (!var->HasOneOfFlags(VF_IMPLEMENTED_AS_CONSTINT)) { formatter_.SetNodePos(declaration); SynthVar((VarDeclaration*)declaration); ++num_items; } } } if (num_items > 0) { EmptyLine(); } return(num_items); } int CppSynth::WriteClassIdsDefinitions(void) { int num_items = 0; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_TYPE) { TypeDeclaration *tdecl = (TypeDeclaration*)declaration; bool towrite = false; // if has base classes, downcast is possible. if (tdecl->type_spec_->GetType() == ANT_CLASS_TYPE) { AstClassType *ctype = (AstClassType*)tdecl->type_spec_; towrite = ctype->member_interfaces_.size() > 0; } if (towrite) { text = "char "; text += tdecl->name_; text += "::id__"; Write(&text); ++num_items; } } } if (num_items > 0) { EmptyLine(); } return(num_items); } int CppSynth::WriteConstructors(void) { int num_items = 0; string text; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_TYPE) { TypeDeclaration *tdecl = (TypeDeclaration*)declaration; if (tdecl->type_spec_->GetType() == ANT_CLASS_TYPE) { AstClassType *ctype = (AstClassType*)tdecl->type_spec_; // note: if the class has functions, the constructor is placed just before the first of them if (ctype->has_constructor && !ctype->constructor_written && ctype->member_functions_.size() == 0) { ++num_items; SynthConstructor(&tdecl->name_, ctype); } } } } if (num_items > 0) { EmptyLine(); } return(num_items); } int CppSynth::WriteFunctions(void) { string text; int num_items = 0; for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_FUNC) { formatter_.SetNodePos(declaration); SynthFunc((FuncDeclaration*)declaration); ++num_items; } } return(num_items); } void CppSynth::WriteReferenceGuard(const char *ref_name, bool isref) { char buf[20]; sprintf(buf, "%d", refguard_name_++); string text = "sing::Ref r"; text += buf; text += "__(\""; text += ref_name; text += " in "; text += function_name_; text += "\", "; if (isref) text += '&'; text += ref_name; text += ")"; Write(&text); } void CppSynth::WriteArgumentsGuards(AstFuncType *type_spec) { ++indent_; refguard_name_ = 0; for (int ii = 0; ii < (int)type_spec->arguments_.size(); ++ii) { VarDeclaration *arg = type_spec->arguments_[ii]; ParmPassingMethod mode = GetParameterPassingMethod(arg->GetTypeSpec(), arg->HasOneOfFlags(VF_READONLY)); if (mode != PPM_VALUE) { WriteReferenceGuard(arg->name_.c_str(), mode == PPM_CONSTREF); } } --indent_; } AstClassType *CppSynth::GetLocalClassTypeDeclaration(const char *classname) { for (int ii = 0; ii < (int)root_->declarations_.size(); ++ii) { IAstDeclarationNode *declaration = root_->declarations_[ii]; if (declaration->GetType() == ANT_TYPE) { TypeDeclaration *tdecl = (TypeDeclaration*)declaration; if (tdecl->name_ == classname) { IAstTypeNode *ntype = tdecl->type_spec_; if (ntype != nullptr && ntype->GetType() == ANT_CLASS_TYPE) { return((AstClassType*)ntype); } return(nullptr); } } } return(nullptr); } void CppSynth::AppendMemberName(string *dst, IAstDeclarationNode *src) { assert(src != nullptr); if (src == nullptr) return; if (src->GetType() == ANT_VAR) { VarDeclaration *var = (VarDeclaration*)src; *dst += synth_options_->member_prefix_; *dst += var->name_; *dst += synth_options_->member_suffix_; } else if (src->GetType() == ANT_FUNC) { FuncDeclaration *fun = (FuncDeclaration*)src; *dst += fun->name_; } else { assert(false); } } void CppSynth::SynthDFile(FILE *dfd, const Package *package, const char *target_name) { fprintf(dfd, "%s:", target_name); const vector<AstDependency*> *vdep = &package->GetRoot()->dependencies_; for (int ii = 0; ii < vdep->size(); ++ii) { AstDependency *dep = (*vdep)[ii]; if (ii == vdep->size() - 1) { fprintf(dfd, " %s", dep->full_package_path_.c_str()); } else { fprintf(dfd, " %s \\\n", dep->full_package_path_.c_str()); } } } void CppSynth::SynthMapFile(FILE *mfd) { fprintf(mfd, "prefix = %s\r\n", synth_options_->member_prefix_.c_str()); fprintf(mfd, "suffix = %s\r\n", synth_options_->member_suffix_.c_str()); const vector<line_nums> *lines = formatter_.GetLines(); int top = lines->size() - 1; if (top < 0) { fprintf(mfd, "top_lines = 0, 0\r\n"); } else { fprintf(mfd, "top_lines = %d, %d\r\n", (*lines)[top].sing_line, (*lines)[top].cpp_line); fprintf(mfd, "lines:\r\n"); for (int ii = 0; ii <= top; ++ii) { fprintf(mfd, "%d, %d\r\n", (*lines)[ii].sing_line, (*lines)[ii].cpp_line); } } } } // namespace
31.32401
149
0.558466
mdegirolami
8ae721269e40b7d5ffeeaed58bf0df78f43da481
1,365
cpp
C++
src/endgame.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
1
2021-11-19T02:56:04.000Z
2021-11-19T02:56:04.000Z
src/endgame.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
null
null
null
src/endgame.cpp
joestilin/Trading-Game
d795d375d4d9063703b7b4ca0a6ca420bd4a9c06
[ "MIT" ]
null
null
null
#include "endgame.h" EndGame::EndGame() { } void EndGame::Run(State &state, Controller &controller, Renderer &renderer, TradeLog &tradelog, std::size_t &target_frame_duration){ // timing variables Uint32 title_timestamp = SDL_GetTicks(); Uint32 start = SDL_GetTicks(); Uint32 frame_start; Uint32 frame_end; Uint32 frame_duration; int frame_count = 0; // enable text input SDL_StartTextInput(); // display the end page for total_duration unless the player quits while (SDL_GetTicks() - start < total_duration && state != QUIT) { frame_start = SDL_GetTicks(); controller.HandleEndGameInput(state); Update(); renderer.RenderEndGame(tradelog, state); // end of frame timing frame_end = SDL_GetTicks(); frame_count++; frame_duration = frame_end - frame_start; // calculate frames per second if (frame_end - title_timestamp > 1000) { renderer.UpdateWindow_Title(frame_count); frame_count = 0; title_timestamp = frame_end; } // throttle the loop to target frame rate if (frame_duration < target_frame_duration) { SDL_Delay(target_frame_duration - frame_duration); } } } void EndGame::Update() { // future features }
27.3
76
0.625641
joestilin
8ae8ad8c155112d2466e1d49ce25a1a5357a158d
27,127
cpp
C++
source/adios2/engine/ssc/SscHelper.cpp
fengggli/ADIOS2
d0909894aaa36e24a253b16a62f371b500ff85a7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/adios2/engine/ssc/SscHelper.cpp
fengggli/ADIOS2
d0909894aaa36e24a253b16a62f371b500ff85a7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
source/adios2/engine/ssc/SscHelper.cpp
fengggli/ADIOS2
d0909894aaa36e24a253b16a62f371b500ff85a7
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * SscHelper.cpp * * Created on: Sep 30, 2019 * Author: Jason Wang */ #include "SscHelper.h" #include "adios2/common/ADIOSMacros.h" #include "adios2/helper/adiosFunctions.h" #include "adios2/helper/adiosType.h" #include <iostream> #include <numeric> namespace adios2 { namespace core { namespace engine { namespace ssc { size_t GetTypeSize(DataType type) { if (type == DataType::None) { helper::Throw<std::runtime_error>("Engine", "SscHelper", "GetTypeSize", "unknown data type"); } #define declare_type(T) \ else if (type == helper::GetDataType<T>()) { return sizeof(T); } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type else { helper::Throw<std::runtime_error>("Engine", "SscHelper", "GetTypeSize", "unknown data type"); } return 0; } size_t TotalDataSize(const Dims &dims, DataType type, const ShapeID &shapeId) { if (shapeId == ShapeID::GlobalArray || shapeId == ShapeID::LocalArray) { return std::accumulate(dims.begin(), dims.end(), GetTypeSize(type), std::multiplies<size_t>()); } else if (shapeId == ShapeID::GlobalValue || shapeId == ShapeID::LocalValue) { return GetTypeSize(type); } helper::Throw<std::runtime_error>("Engine", "SscHelper", "TotalDataSize", "ShapeID not supported"); return 0; } size_t TotalDataSize(const BlockVec &bv) { size_t s = 0; for (const auto &b : bv) { if (b.type == DataType::String) { s += b.bufferCount; } else { s += TotalDataSize(b.count, b.type, b.shapeId); } } return s; } RankPosMap CalculateOverlap(BlockVecVec &globalVecVec, const BlockVec &localVec) { RankPosMap ret; int rank = 0; for (auto &rankBlockVec : globalVecVec) { for (auto &gBlock : rankBlockVec) { for (auto &lBlock : localVec) { if (lBlock.name == gBlock.name) { if (gBlock.shapeId == ShapeID::GlobalValue) { ret[rank].first = 0; } else if (gBlock.shapeId == ShapeID::GlobalArray) { bool hasOverlap = true; for (size_t i = 0; i < gBlock.start.size(); ++i) { if (gBlock.start[i] + gBlock.count[i] <= lBlock.start[i] || lBlock.start[i] + lBlock.count[i] <= gBlock.start[i]) { hasOverlap = false; break; } } if (hasOverlap) { ret[rank].first = 0; } } else if (gBlock.shapeId == ShapeID::LocalValue) { } else if (gBlock.shapeId == ShapeID::LocalArray) { } } } } ++rank; } return ret; } void SerializeVariables(const BlockVec &input, Buffer &output, const int rank) { for (const auto &b : input) { uint64_t pos = output.value<uint64_t>(); output.resize(pos + 1024); output.value<uint8_t>(pos) = static_cast<uint8_t>(b.shapeId); ++pos; output.value<int>(pos) = rank; pos += 4; output.value(pos) = static_cast<uint8_t>(b.name.size()); ++pos; std::memcpy(output.data(pos), b.name.data(), b.name.size()); pos += b.name.size(); output.value(pos) = static_cast<uint8_t>(b.type); ++pos; output.value(pos) = static_cast<uint8_t>(b.shape.size()); ++pos; for (const auto &s : b.shape) { output.value<uint64_t>(pos) = s; pos += 8; } for (const auto &s : b.start) { output.value<uint64_t>(pos) = s; pos += 8; } for (const auto &s : b.count) { output.value<uint64_t>(pos) = s; pos += 8; } output.value<uint64_t>(pos) = b.bufferStart; pos += 8; output.value<uint64_t>(pos) = b.bufferCount; pos += 8; output.value(pos) = static_cast<uint8_t>(b.value.size()); ++pos; std::memcpy(output.data(pos), b.value.data(), b.value.size()); pos += b.value.size(); output.value<uint64_t>() = pos; } } void SerializeAttributes(IO &input, Buffer &output) { const auto &attributeMap = input.GetAttributes(); for (const auto &attributePair : attributeMap) { uint64_t pos = output.value<uint64_t>(); output.resize(pos + 1024); if (attributePair.second->m_Type == DataType::String) { const auto &attribute = input.InquireAttribute<std::string>(attributePair.first); output[pos] = 66; ++pos; output[pos] = static_cast<uint8_t>(attribute->m_Type); ++pos; output[pos] = static_cast<uint8_t>(attribute->m_Name.size()); ++pos; std::memcpy(output.data(pos), attribute->m_Name.data(), attribute->m_Name.size()); pos += attribute->m_Name.size(); output.value<uint64_t>(pos) = attribute->m_DataSingleValue.size(); pos += 8; std::memcpy(output.data(pos), attribute->m_DataSingleValue.data(), attribute->m_DataSingleValue.size()); pos += attribute->m_DataSingleValue.size(); } #define declare_type(T) \ else if (attributePair.second->m_Type == helper::GetDataType<T>()) \ { \ const auto &attribute = \ input.InquireAttribute<T>(attributePair.first); \ output[pos] = 66; \ ++pos; \ output[pos] = static_cast<uint8_t>(attribute->m_Type); \ ++pos; \ output[pos] = static_cast<uint8_t>(attribute->m_Name.size()); \ ++pos; \ std::memcpy(output.data(pos), attribute->m_Name.data(), \ attribute->m_Name.size()); \ pos += attribute->m_Name.size(); \ if (attribute->m_IsSingleValue) \ { \ output.value<uint64_t>(pos) = sizeof(T); \ pos += 8; \ output.value<T>(pos) = attribute->m_DataSingleValue; \ pos += sizeof(T); \ } \ else \ { \ uint64_t size = sizeof(T) * attribute->m_DataArray.size(); \ output.value<uint64_t>(pos) = size; \ pos += 8; \ std::memcpy(output.data(pos), attribute->m_DataArray.data(), \ size); \ pos += size; \ } \ } ADIOS2_FOREACH_ATTRIBUTE_STDTYPE_1ARG(declare_type) #undef declare_type output.value<uint64_t>() = pos; } } void Deserialize(const Buffer &input, BlockVecVec &output, IO &io, const bool regVars, const bool regAttrs) { for (auto &i : output) { i.clear(); } uint64_t pos = 2; uint64_t blockSize = input.value<uint64_t>(pos); pos += 8; while (pos < blockSize) { uint8_t shapeId = input[pos]; ++pos; if (shapeId == 66) { const DataType type = static_cast<DataType>(input[pos]); ++pos; uint8_t nameSize = input[pos]; ++pos; std::vector<char> namev(nameSize); std::memcpy(namev.data(), input.data(pos), nameSize); std::string name = std::string(namev.begin(), namev.end()); pos += nameSize; uint64_t size = input.value<uint64_t>(pos); pos += 8; if (regAttrs) { const auto &attributes = io.GetAttributes(); auto it = attributes.find(name); if (it == attributes.end()) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (type == DataType::String) { io.DefineAttribute<std::string>( name, std::string(input.data<char>(pos), size)); } #define declare_type(T) \ else if (type == helper::GetDataType<T>()) \ { \ if (size == sizeof(T)) \ { \ io.DefineAttribute<T>(name, input.value<T>(pos)); \ } \ else \ { \ io.DefineAttribute<T>(name, input.data<T>(pos), size / sizeof(T)); \ } \ } ADIOS2_FOREACH_ATTRIBUTE_STDTYPE_1ARG(declare_type) #undef declare_type else { helper::Throw<std::runtime_error>( "Engine", "SscHelper", "Deserialize", "unknown attribute data type"); } } } pos += size; } else { int rank = input.value<int>(pos); pos += 4; output[rank].emplace_back(); auto &b = output[rank].back(); b.shapeId = static_cast<ShapeID>(shapeId); uint8_t nameSize = input[pos]; ++pos; std::vector<char> name(nameSize); std::memcpy(name.data(), input.data(pos), nameSize); b.name = std::string(name.begin(), name.end()); pos += nameSize; b.type = static_cast<DataType>(input[pos]); ++pos; uint8_t shapeSize = input[pos]; ++pos; b.shape.resize(shapeSize); b.start.resize(shapeSize); b.count.resize(shapeSize); std::memcpy(b.shape.data(), input.data(pos), 8 * shapeSize); pos += 8 * shapeSize; std::memcpy(b.start.data(), input.data(pos), 8 * shapeSize); pos += 8 * shapeSize; std::memcpy(b.count.data(), input.data(pos), 8 * shapeSize); pos += 8 * shapeSize; b.bufferStart = input.value<uint64_t>(pos); pos += 8; b.bufferCount = input.value<uint64_t>(pos); pos += 8; uint8_t valueSize = input[pos]; pos++; b.value.resize(valueSize); if (valueSize > 0) { std::memcpy(b.value.data(), input.data() + pos, valueSize); pos += valueSize; } if (regVars) { if (b.type == DataType::None) { helper::Throw<std::runtime_error>( "Engine", "SscHelper", "Deserialize", "unknown variable data type"); } #define declare_type(T) \ else if (b.type == helper::GetDataType<T>()) \ { \ auto v = io.InquireVariable<T>(b.name); \ if (!v) \ { \ Dims vStart = b.start; \ Dims vShape = b.shape; \ if (io.m_ArrayOrder != ArrayOrdering::RowMajor) \ { \ std::reverse(vStart.begin(), vStart.end()); \ std::reverse(vShape.begin(), vShape.end()); \ } \ if (b.shapeId == ShapeID::GlobalValue) \ { \ io.DefineVariable<T>(b.name); \ } \ else if (b.shapeId == ShapeID::GlobalArray) \ { \ io.DefineVariable<T>(b.name, vShape, vStart, vShape); \ } \ else if (b.shapeId == ShapeID::LocalValue) \ { \ io.DefineVariable<T>(b.name, {adios2::LocalValueDim}); \ } \ else if (b.shapeId == ShapeID::LocalArray) \ { \ io.DefineVariable<T>(b.name, {}, {}, vShape); \ } \ } \ } ADIOS2_FOREACH_STDTYPE_1ARG(declare_type) #undef declare_type else { helper::Throw<std::runtime_error>( "Engine", "SscHelper", "Deserialize", "unknown variable data type"); } } } } } void AggregateMetadata(const Buffer &localBuffer, Buffer &globalBuffer, MPI_Comm comm, const bool finalStep, const bool locked) { int mpiSize; MPI_Comm_size(comm, &mpiSize); int localSize = static_cast<int>(localBuffer.value<uint64_t>()) - 8; std::vector<int> localSizes(mpiSize); MPI_Gather(&localSize, 1, MPI_INT, localSizes.data(), 1, MPI_INT, 0, comm); int globalSize = std::accumulate(localSizes.begin(), localSizes.end(), 0); globalBuffer.resize(globalSize + 10); std::vector<int> displs(mpiSize); for (size_t i = 1; i < static_cast<size_t>(mpiSize); ++i) { displs[i] = displs[i - 1] + localSizes[i - 1]; } MPI_Gatherv(localBuffer.data() + 8, localSize, MPI_CHAR, globalBuffer.data() + 10, localSizes.data(), displs.data(), MPI_CHAR, 0, comm); globalBuffer[0] = finalStep; globalBuffer[1] = locked; globalBuffer.value<uint64_t>(2) = globalSize; } void BroadcastMetadata(Buffer &globalBuffer, const int root, MPI_Comm comm) { int globalBufferSize = static_cast<int>(globalBuffer.size()); MPI_Bcast(&globalBufferSize, 1, MPI_INT, root, comm); if (globalBuffer.size() < static_cast<size_t>(globalBufferSize)) { globalBuffer.resize(globalBufferSize); } MPI_Bcast(globalBuffer.data(), globalBufferSize, MPI_CHAR, root, comm); } bool AreSameDims(const Dims &a, const Dims &b) { if (a.size() != b.size()) { return false; } for (size_t i = 0; i < a.size(); ++i) { if (a[i] != b[i]) { return false; } } return true; } void MPI_Gatherv64(const void *sendbuf, uint64_t sendcount, MPI_Datatype sendtype, void *recvbuf, const uint64_t *recvcounts, const uint64_t *displs, MPI_Datatype recvtype, int root, MPI_Comm comm, const int chunksize) { int mpiSize; int mpiRank; MPI_Comm_size(comm, &mpiSize); MPI_Comm_rank(comm, &mpiRank); int recvTypeSize; int sendTypeSize; MPI_Type_size(recvtype, &recvTypeSize); MPI_Type_size(sendtype, &sendTypeSize); std::vector<MPI_Request> requests; if (mpiRank == root) { for (int i = 0; i < mpiSize; ++i) { uint64_t recvcount = recvcounts[i]; while (recvcount > 0) { requests.emplace_back(); if (recvcount > static_cast<uint64_t>(chunksize)) { MPI_Irecv(reinterpret_cast<char *>(recvbuf) + (displs[i] + recvcounts[i] - recvcount) * recvTypeSize, chunksize, recvtype, i, 0, comm, &requests.back()); recvcount -= static_cast<uint64_t>(chunksize); } else { MPI_Irecv(reinterpret_cast<char *>(recvbuf) + (displs[i] + recvcounts[i] - recvcount) * recvTypeSize, static_cast<int>(recvcount), recvtype, i, 0, comm, &requests.back()); recvcount = 0; } } } } uint64_t sendcountvar = sendcount; while (sendcountvar > 0) { requests.emplace_back(); if (sendcountvar > static_cast<uint64_t>(chunksize)) { MPI_Isend(reinterpret_cast<const char *>(sendbuf) + (sendcount - sendcountvar) * sendTypeSize, chunksize, sendtype, root, 0, comm, &requests.back()); sendcountvar -= static_cast<uint64_t>(chunksize); } else { MPI_Isend(reinterpret_cast<const char *>(sendbuf) + (sendcount - sendcountvar) * sendTypeSize, static_cast<int>(sendcountvar), sendtype, root, 0, comm, &requests.back()); sendcountvar = 0; } } MPI_Waitall(static_cast<int>(requests.size()), requests.data(), MPI_STATUSES_IGNORE); } void MPI_Gatherv64OneSidedPull(const void *sendbuf, uint64_t sendcount, MPI_Datatype sendtype, void *recvbuf, const uint64_t *recvcounts, const uint64_t *displs, MPI_Datatype recvtype, int root, MPI_Comm comm, const int chunksize) { int mpiSize; int mpiRank; MPI_Comm_size(comm, &mpiSize); MPI_Comm_rank(comm, &mpiRank); int recvTypeSize; int sendTypeSize; MPI_Type_size(recvtype, &recvTypeSize); MPI_Type_size(sendtype, &sendTypeSize); MPI_Win win; MPI_Win_create(const_cast<void *>(sendbuf), sendcount * sendTypeSize, sendTypeSize, MPI_INFO_NULL, comm, &win); if (mpiRank == root) { for (int i = 0; i < mpiSize; ++i) { uint64_t recvcount = recvcounts[i]; while (recvcount > 0) { if (recvcount > static_cast<uint64_t>(chunksize)) { MPI_Get(reinterpret_cast<char *>(recvbuf) + (displs[i] + recvcounts[i] - recvcount) * recvTypeSize, chunksize, recvtype, i, recvcounts[i] - recvcount, chunksize, recvtype, win); recvcount -= static_cast<uint64_t>(chunksize); } else { MPI_Get(reinterpret_cast<char *>(recvbuf) + (displs[i] + recvcounts[i] - recvcount) * recvTypeSize, static_cast<int>(recvcount), recvtype, i, recvcounts[i] - recvcount, static_cast<int>(recvcount), recvtype, win); recvcount = 0; } } } } MPI_Win_free(&win); } void MPI_Gatherv64OneSidedPush(const void *sendbuf, uint64_t sendcount, MPI_Datatype sendtype, void *recvbuf, const uint64_t *recvcounts, const uint64_t *displs, MPI_Datatype recvtype, int root, MPI_Comm comm, const int chunksize) { int mpiSize; int mpiRank; MPI_Comm_size(comm, &mpiSize); MPI_Comm_rank(comm, &mpiRank); int recvTypeSize; int sendTypeSize; MPI_Type_size(recvtype, &recvTypeSize); MPI_Type_size(sendtype, &sendTypeSize); uint64_t recvsize = displs[mpiSize - 1] + recvcounts[mpiSize - 1]; MPI_Win win; MPI_Win_create(recvbuf, recvsize * recvTypeSize, recvTypeSize, MPI_INFO_NULL, comm, &win); uint64_t sendcountvar = sendcount; while (sendcountvar > 0) { if (sendcountvar > static_cast<uint64_t>(chunksize)) { MPI_Put(reinterpret_cast<const char *>(sendbuf) + (sendcount - sendcountvar) * sendTypeSize, chunksize, sendtype, root, displs[mpiRank] + sendcount - sendcountvar, chunksize, sendtype, win); sendcountvar -= static_cast<uint64_t>(chunksize); } else { MPI_Put(reinterpret_cast<const char *>(sendbuf) + (sendcount - sendcountvar) * sendTypeSize, static_cast<int>(sendcountvar), sendtype, root, displs[mpiRank] + sendcount - sendcountvar, static_cast<int>(sendcountvar), sendtype, win); sendcountvar = 0; } } MPI_Win_free(&win); } void PrintDims(const Dims &dims, const std::string &label) { std::cout << label; for (const auto &i : dims) { std::cout << i << ", "; } std::cout << std::endl; } void PrintBlock(const BlockInfo &b, const std::string &label) { std::cout << label << std::endl; std::cout << b.name << std::endl; std::cout << " DataType : " << b.type << std::endl; PrintDims(b.shape, " Shape : "); PrintDims(b.start, " Start : "); PrintDims(b.count, " Count : "); std::cout << " Position Start : " << b.bufferStart << std::endl; std::cout << " Position Count : " << b.bufferCount << std::endl; } void PrintBlockVec(const BlockVec &bv, const std::string &label) { std::cout << label << std::endl; for (const auto &i : bv) { std::cout << i.name << std::endl; std::cout << " DataType : " << i.type << std::endl; PrintDims(i.shape, " Shape : "); PrintDims(i.start, " Start : "); PrintDims(i.count, " Count : "); std::cout << " Position Start : " << i.bufferStart << std::endl; std::cout << " Position Count : " << i.bufferCount << std::endl; } } void PrintBlockVecVec(const BlockVecVec &bvv, const std::string &label) { std::cout << label << std::endl; size_t rank = 0; for (const auto &bv : bvv) { std::cout << "Rank " << rank << std::endl; for (const auto &i : bv) { std::cout << " " << i.name << std::endl; std::cout << " DataType : " << i.type << std::endl; PrintDims(i.shape, " Shape : "); PrintDims(i.start, " Start : "); PrintDims(i.count, " Count : "); std::cout << " Position Start : " << i.bufferStart << std::endl; std::cout << " Position Count : " << i.bufferCount << std::endl; } ++rank; } } void PrintRankPosMap(const RankPosMap &m, const std::string &label) { std::cout << label << std::endl; for (const auto &rank : m) { std::cout << "Rank = " << rank.first << ", bufferStart = " << rank.second.first << ", bufferCount = " << rank.second.second << std::endl; } } void PrintMpiInfo(const MpiInfo &writersInfo, const MpiInfo &readersInfo) { int s = 0; for (size_t i = 0; i < writersInfo.size(); ++i) { std::cout << "App " << s << " Writer App " << i << " Wrold Ranks : "; for (size_t j = 0; j < writersInfo[i].size(); ++j) { std::cout << writersInfo[i][j] << " "; } std::cout << std::endl; ++s; } for (size_t i = 0; i < readersInfo.size(); ++i) { std::cout << "App " << s << " Reader App " << i << " Wrold Ranks : "; for (size_t j = 0; j < readersInfo[i].size(); ++j) { std::cout << readersInfo[i][j] << " "; } std::cout << std::endl; ++s; } std::cout << std::endl; } } // end namespace ssc } // end namespace engine } // end namespace core } // end namespace adios2
35.740448
80
0.430752
fengggli
8aec6d4b0dbb0d87b0e22e71cd47b612af21bd4c
3,803
cpp
C++
test/testMat.cpp
anazli/raymann
425c908f275309da4dc1f77fe6ea0a27ec9e30f8
[ "BSD-2-Clause" ]
null
null
null
test/testMat.cpp
anazli/raymann
425c908f275309da4dc1f77fe6ea0a27ec9e30f8
[ "BSD-2-Clause" ]
null
null
null
test/testMat.cpp
anazli/raymann
425c908f275309da4dc1f77fe6ea0a27ec9e30f8
[ "BSD-2-Clause" ]
null
null
null
#include "geometry/sphere.h" #include "gtest/gtest.h" #include "tools/tools.h" using namespace testing; class TMat : public Test { public: Sphere *s; PointLight light; }; TEST_F(TMat, createsDefaultLight) { ASSERT_TRUE(light.position() == Point3f()); ASSERT_TRUE(light.intensity() == Vec3f()); } TEST_F(TMat, createsNewLight1) { light.setPosition(Point3f(1.0f, 2.0f, 3.0f)); light.setIntensity(Vec3f(0.1f, 0.1f, 0.3f)); ASSERT_EQ(light.position().x(), 1.0f); ASSERT_EQ(light.position().y(), 2.0f); ASSERT_EQ(light.position().z(), 3.0f); ASSERT_EQ(light.intensity().x(), 0.1f); ASSERT_EQ(light.intensity().y(), 0.1f); ASSERT_EQ(light.intensity().z(), 0.3f); } TEST_F(TMat, createsNewLight2) { light = PointLight(Point3f(0.1f, -4.0f, -0.4f), Vec3f(1.0f, 4.0f, 0.0f)); ASSERT_EQ(light.position().x(), 0.1f); ASSERT_EQ(light.position().y(), -4.0f); ASSERT_EQ(light.position().z(), -0.4f); ASSERT_EQ(light.intensity().x(), 1.0f); ASSERT_EQ(light.intensity().y(), 4.0f); ASSERT_EQ(light.intensity().z(), 0.0f); } TEST_F(TMat, lightsWithEyeBetweenLightAndSurface) { //---------------------------------- // As it is in Material->lighting //---------------------------------- Vec3f eye(0.0f, 0.0f, -1.0f); light = PointLight(Point3f(0.0f, 0.0f, -10.0f), Vec3f(1.0f, 1.0f, 1.0f)); Point3f p(0.0f, 0.0f, 0.0f); Vec3f m_color(1.0f, 1.0f, 1.0f); Vec3f effective_color = m_color * light.intensity(); Vec3f lightv = (light.position() - p).normalize(); float m_ambient = 0.1f; float m_diffuse = 0.9f; float m_specular = 0.9f; float m_shininess = 200.0f; Vec3f norm(0.0f, 0.0f, -1.0f); // norm == this->normal(p) Vec3f ret_ambient = effective_color * m_ambient; Vec3f ret_diffuse; Vec3f ret_specular; float light_normal = dot(lightv, norm); if (light_normal >= 0.0f) { ret_diffuse = effective_color * m_diffuse * light_normal; Vec3f reflectv = reflect(-lightv, norm); float reflect_dot_eye = dot(reflectv, eye); if (reflect_dot_eye > 0.0f) { float factor = pow(reflect_dot_eye, m_shininess); ret_specular = light.intensity() * m_specular * factor; } } Vec3f result = ret_ambient + ret_diffuse + ret_specular; ASSERT_EQ(result.x(), 1.9f); ASSERT_EQ(result.y(), 1.9f); ASSERT_EQ(result.z(), 1.9f); ASSERT_TRUE(result == Vec3f(1.9f, 1.9f, 1.9f)); } TEST_F(TMat, lightingWithSurfaceInShadow) { //------------------------------------------------------ // As it is in Material->lighting | Update (With shadow) //------------------------------------------------------ bool in_shadow = true; Vec3f eye(0.0f, 0.0f, -1.0f); light = PointLight(Point3f(0.0f, 0.0f, -10.0f), Vec3f(1.0f, 1.0f, 1.0f)); Point3f p(0.0f, 0.0f, 0.0f); Vec3f m_color(1.0f, 1.0f, 1.0f); Vec3f effective_color = m_color * light.intensity(); Vec3f lightv = (light.position() - p).normalize(); float m_ambient = 0.1f; float m_diffuse = 0.9f; float m_specular = 0.9f; float m_shininess = 200.0f; Vec3f norm(0.0f, 0.0f, -1.0f); // norm == this->normal(p) Vec3f ret_ambient = effective_color * m_ambient; Vec3f ret_diffuse; Vec3f ret_specular; if (!in_shadow) { float light_normal = dot(lightv, norm); if (light_normal >= 0.0f) { ret_diffuse = effective_color * m_diffuse * light_normal; Vec3f reflectv = reflect(-lightv, norm); float reflect_dot_eye = dot(reflectv, eye); if (reflect_dot_eye > 0.0f) { float factor = pow(reflect_dot_eye, m_shininess); ret_specular = light.intensity() * m_specular * factor; } } } Vec3f result = ret_ambient + ret_diffuse + ret_specular; ASSERT_EQ(result.x(), 0.1f); ASSERT_EQ(result.y(), 0.1f); ASSERT_EQ(result.z(), 0.1f); ASSERT_TRUE(result == Vec3f(0.1f, 0.1f, 0.1f)); }
29.944882
75
0.621615
anazli
8af1470d873f6e93e7b56a678c6e338261466f82
19,514
cpp
C++
src/other/openscenegraph/src/osgPlugins/freetype/FreeTypeFont.cpp
Zitara/BRLCAD
620449d036e38bd52257f6b5b10daa55d9284900
[ "BSD-4-Clause", "BSD-3-Clause" ]
1
2019-10-23T16:17:49.000Z
2019-10-23T16:17:49.000Z
src/other/openscenegraph/src/osgPlugins/freetype/FreeTypeFont.cpp
pombredanne/sf.net-brlcad
fb56f37c201b51241e8f3aa7b979436856f43b8c
[ "BSD-4-Clause", "BSD-3-Clause" ]
null
null
null
src/other/openscenegraph/src/osgPlugins/freetype/FreeTypeFont.cpp
pombredanne/sf.net-brlcad
fb56f37c201b51241e8f3aa7b979436856f43b8c
[ "BSD-4-Clause", "BSD-3-Clause" ]
1
2018-12-21T21:09:47.000Z
2018-12-21T21:09:47.000Z
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include "FreeTypeFont.h" #include "FreeTypeLibrary.h" #include <ft2build.h> #include FT_FREETYPE_H #include FT_OUTLINE_H #include FT_BBOX_H #include <osg/Notify> #include <osg/io_utils> #include <osgDB/WriteFile> namespace FreeType { struct Char3DInfo { Char3DInfo(int numSteps): _verts( new osg::Vec3Array ), _geometry( new osg::Geometry ), _numSteps(numSteps), _maxY(-FLT_MAX), _maxX(-FLT_MAX), _minX(FLT_MAX), _minY(FLT_MAX), _coord_scale(1.0/64.0) { _geometry->setVertexArray(_verts.get()); } ~Char3DInfo() { } void completeCurrentPrimitiveSet() { if (_currentPrimitiveSet.valid() && _currentPrimitiveSet->size()>1) { _geometry->addPrimitiveSet( _currentPrimitiveSet.get() ); } _currentPrimitiveSet = 0; } osg::Geometry* get() { completeCurrentPrimitiveSet(); return _geometry.get(); } void addVertex(osg::Vec3 pos) { _previous = pos; pos *= _coord_scale; if (!_verts->empty() && _verts->back()==pos) { // OSG_NOTICE<<"addVertex("<<pos<<") duplicate, ignoring"<<std::endl; return; } if (!_currentPrimitiveSet) { _currentPrimitiveSet = new osg::DrawElementsUShort( osg::PrimitiveSet::POLYGON); _currentPrimitiveSet->setName("boundary"); } if (!(_currentPrimitiveSet->empty()) && (*_verts)[(*_currentPrimitiveSet)[0]] == pos) { _currentPrimitiveSet->push_back( (*_currentPrimitiveSet)[0] ); } else { _currentPrimitiveSet->push_back( _verts->size() ); _verts->push_back( pos ); setMinMax(pos); } } void moveTo(const osg::Vec2& pos) { completeCurrentPrimitiveSet(); addVertex( osg::Vec3(pos.x(),pos.y(),0) ); } void lineTo(const osg::Vec2& pos) { addVertex( osg::Vec3(pos.x(),pos.y(),0) ); } void conicTo(const osg::Vec2& control, const osg::Vec2& pos) { osg::Vec3 p0 = _previous; osg::Vec3 p1 = osg::Vec3(control.x(),control.y(),0); osg::Vec3 p2 = osg::Vec3(pos.x(),pos.y(),0); double dt = 1.0/_numSteps; double u=0; for (int i=0; i<=_numSteps; ++i) { double w = 1; double bs = 1.0/( (1-u)*(1-u)+2*(1-u)*u*w +u*u ); osg::Vec3 p = (p0*((1-u)*(1-u)) + p1*(2*(1-u)*u*w) + p2*(u*u))*bs; addVertex( p ); u += dt; } } void cubicTo(const osg::Vec2& control1, const osg::Vec2& control2, const osg::Vec2& pos) { osg::Vec3 p0 = _previous; osg::Vec3 p1 = osg::Vec3(control1.x(),control1.y(),0); osg::Vec3 p2 = osg::Vec3(control2.x(),control2.y(),0); osg::Vec3 p3 = osg::Vec3(pos.x(),pos.y(),0); double cx = 3*(p1.x() - p0.x()); double bx = 3*(p2.x() - p1.x()) - cx; double ax = p3.x() - p0.x() - cx - bx; double cy = 3*(p1.y() - p0.y()); double by = 3*(p2.y() - p1.y()) - cy; double ay = p3.y() - p0.y() - cy - by; double dt = 1.0/_numSteps; double u=0; for (int i=0; i<=_numSteps; ++i) { osg::Vec3 p = osg::Vec3( ax*u*u*u + bx*u*u + cx*u + p0.x(),ay*u*u*u + by*u*u + cy*u + p0.y(),0 ); addVertex( p ); u += dt; } } void setMinMax(const osg::Vec3& pos) { _maxY = std::max(_maxY, (double) pos.y()); _minY = std::min(_minY, (double) pos.y()); _maxX = std::max(_maxX, (double) pos.x()); _minX = std::min(_minX, (double) pos.x()); } osg::ref_ptr<osg::Vec3Array> _verts; osg::ref_ptr<osg::DrawElementsUShort> _currentPrimitiveSet; osg::ref_ptr<osg::Geometry> _geometry; osg::Vec3 _previous; int _numSteps; double _maxY; double _maxX; double _minX; double _minY; double _coord_scale; }; int moveTo( const FT_Vector* to, void* user ) { Char3DInfo* char3d = (Char3DInfo*)user; char3d->moveTo( osg::Vec2(to->x,to->y) ); return 0; } int lineTo( const FT_Vector* to, void* user ) { Char3DInfo* char3d = (Char3DInfo*)user; char3d->lineTo( osg::Vec2(to->x,to->y) ); return 0; } int conicTo( const FT_Vector* control,const FT_Vector* to, void* user ) { Char3DInfo* char3d = (Char3DInfo*)user; char3d->conicTo( osg::Vec2(control->x,control->y), osg::Vec2(to->x,to->y) ); return 0; } int cubicTo( const FT_Vector* control1,const FT_Vector* control2,const FT_Vector* to, void* user ) { Char3DInfo* char3d = (Char3DInfo*)user; char3d->cubicTo( osg::Vec2(control1->x,control1->y), osg::Vec2(control2->x,control2->y), osg::Vec2(to->x,to->y) ); return 0; } } FreeTypeFont::FreeTypeFont(const std::string& filename, FT_Face face, unsigned int flags): _currentRes(osgText::FontResolution(0,0)), _filename(filename), _buffer(0), _face(face), _flags(flags) { init(); } FreeTypeFont::FreeTypeFont(FT_Byte* buffer, FT_Face face, unsigned int flags): _currentRes(osgText::FontResolution(0,0)), _filename(""), _buffer(buffer), _face(face), _flags(flags) { init(); } FreeTypeFont::~FreeTypeFont() { if(_face) { FreeTypeLibrary* freeTypeLibrary = FreeTypeLibrary::instance(); if (freeTypeLibrary) { // remove myself from the local registry to ensure that // not dangling pointers remain freeTypeLibrary->removeFontImplmentation(this); // free the freetype font face itself FT_Done_Face(_face); _face = 0; // release memory held for FT_Face to work if (_buffer) { delete [] _buffer; _buffer = 0; } } } } void FreeTypeFont::init() { FT_Error _error; _error = FT_Set_Pixel_Sizes(_face, 32, 32); if (_error) { OSG_NOTICE << "FreeTypeFont3D: set pixel sizes failed ..." << std::endl; return; } _currentRes.first = 32; _currentRes.second = 32; } void FreeTypeFont::setFontResolution(const osgText::FontResolution& fontSize) { if (fontSize==_currentRes) return; int width = fontSize.first; int height = fontSize.second; int maxAxis = std::max(width, height); int margin = _facade->getGlyphImageMargin() + (int)((float)maxAxis * _facade->getGlyphImageMarginRatio()); if ((unsigned int)(width+2*margin) > _facade->getTextureWidthHint() || (unsigned int)(width+2*margin) > _facade->getTextureHeightHint()) { OSG_WARN<<"Warning: FreeTypeFont::setSize("<<width<<","<<height<<") sizes too large,"<<std::endl; width = _facade->getTextureWidthHint()-2*margin; height = _facade->getTextureHeightHint()-2*margin; OSG_WARN<<" sizes capped ("<<width<<","<<height<<") to fit int current glyph texture size."<<std::endl; } FT_Error error = FT_Set_Pixel_Sizes( _face, /* handle to face object */ width, /* pixel_width */ height ); /* pixel_height */ if (error) { OSG_WARN<<"FT_Set_Pixel_Sizes() - error 0x"<<std::hex<<error<<std::dec<<std::endl; } else { _currentRes = fontSize; } } osgText::Glyph* FreeTypeFont::getGlyph(const osgText::FontResolution& fontRes, unsigned int charcode) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(FreeTypeLibrary::instance()->getMutex()); setFontResolution(fontRes); float coord_scale = getCoordScale(); // // GT: fix for symbol fonts (i.e. the Webdings font) as the wrong character are being // returned, for symbol fonts in windows (FT_ENCONDING_MS_SYMBOL in freetype) the correct // values are from 0xF000 to 0xF0FF not from 0x000 to 0x00FF (0 to 255) as you would expect. // Microsoft uses a private field for its symbol fonts // unsigned int charindex = charcode; if (_face->charmap != NULL) { if (_face->charmap->encoding == FT_ENCODING_MS_SYMBOL) { charindex |= 0xF000; } } FT_Error error = FT_Load_Char( _face, charindex, FT_LOAD_RENDER|FT_LOAD_NO_BITMAP|_flags ); if (error) { OSG_WARN << "FT_Load_Char(...) error 0x"<<std::hex<<error<<std::dec<<std::endl; return 0; } FT_GlyphSlot glyphslot = _face->glyph; int pitch = glyphslot->bitmap.pitch; unsigned char* buffer = glyphslot->bitmap.buffer; unsigned int sourceWidth = glyphslot->bitmap.width;; unsigned int sourceHeight = glyphslot->bitmap.rows; unsigned int width = sourceWidth; unsigned int height = sourceHeight; osg::ref_ptr<osgText::Glyph> glyph = new osgText::Glyph(_facade, charcode); unsigned int dataSize = width*height; unsigned char* data = new unsigned char[dataSize]; // clear the image to zeros. for(unsigned char* p=data;p<data+dataSize;) { *p++ = 0; } glyph->setImage(width,height,1, GL_ALPHA, GL_ALPHA,GL_UNSIGNED_BYTE, data, osg::Image::USE_NEW_DELETE, 1); glyph->setInternalTextureFormat(GL_ALPHA); // copy image across to osgText::Glyph image. switch(glyphslot->bitmap.pixel_mode) { case FT_PIXEL_MODE_MONO: for(int r=sourceHeight-1;r>=0;--r) { unsigned char* ptr = buffer+r*pitch; for(unsigned int c=0;c<sourceWidth;++c) { (*data++)= (ptr[c >> 3] & (1 << (~c & 7))) ? 255 : 0; } } break; case FT_PIXEL_MODE_GRAY: for(int r=sourceHeight-1;r>=0;--r) { unsigned char* ptr = buffer+r*pitch; for(unsigned int c=0;c<sourceWidth;++c,++ptr) { (*data++)=*ptr; } } break; default: OSG_WARN << "FT_Load_Char(...) returned bitmap with unknown pixel_mode " << glyphslot->bitmap.pixel_mode << std::endl; } FT_Glyph_Metrics* metrics = &(_face->glyph->metrics); glyph->setWidth((float)metrics->width * coord_scale); glyph->setHeight((float)metrics->height * coord_scale); glyph->setHorizontalBearing(osg::Vec2((float)metrics->horiBearingX * coord_scale,(float)(metrics->horiBearingY-metrics->height) * coord_scale)); // bottom left. glyph->setHorizontalAdvance((float)metrics->horiAdvance * coord_scale); glyph->setVerticalBearing(osg::Vec2((float)metrics->vertBearingX * coord_scale,(float)(metrics->vertBearingY-metrics->height) * coord_scale)); // top middle. glyph->setVerticalAdvance((float)metrics->vertAdvance * coord_scale); #if 0 OSG_NOTICE<<"getGlyph("<<charcode<<", "<<char(charcode)<<") _face="<<_face<<", _filename="<<_filename<<std::endl; OSG_NOTICE<<" height="<<glyph->getHeight()<<std::endl; OSG_NOTICE<<" width="<<glyph->getWidth()<<std::endl; OSG_NOTICE<<" horizontalBearing="<<glyph->getHorizontalBearing()<<std::endl; OSG_NOTICE<<" horizontalAdvance="<<glyph->getHorizontalAdvance()<<std::endl; OSG_NOTICE<<" verticalBearing="<<glyph->getHorizontalBearing()<<std::endl; OSG_NOTICE<<" verticalAdvance="<<glyph->getVerticalAdvance()<<std::endl; OSG_NOTICE<<" coord_scale = "<<coord_scale<<std::endl; OSG_NOTICE<<" _face->units_per_EM = "<<_face->units_per_EM<<", scale="<<1.0f/float(_face->units_per_EM)<<std::endl; #endif // cout << " in getGlyph() implementation="<<this<<" "<<_filename<<" facade="<<_facade<<endl; return glyph.release(); } osgText::Glyph3D * FreeTypeFont::getGlyph3D(unsigned int charcode) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(FreeTypeLibrary::instance()->getMutex()); // // GT: fix for symbol fonts (i.e. the Webdings font) as the wrong character are being // returned, for symbol fonts in windows (FT_ENCONDING_MS_SYMBOL in freetype) the correct // values are from 0xF000 to 0xF0FF not from 0x000 to 0x00FF (0 to 255) as you would expect. // Microsoft uses a private field for its symbol fonts // unsigned int charindex = charcode; if (_face->charmap != NULL) { if (_face->charmap->encoding == FT_ENCODING_MS_SYMBOL) { charindex |= 0xF000; } } FT_Error error = FT_Load_Char( _face, charindex, FT_LOAD_DEFAULT|_flags ); if (error) { OSG_WARN << "FT_Load_Char(...) error 0x"<<std::hex<<error<<std::dec<<std::endl; return 0; } if (_face->glyph->format != FT_GLYPH_FORMAT_OUTLINE) { OSG_WARN << "FreeTypeFont3D::getGlyph : not a vector font" << std::endl; return 0; } float coord_scale = getCoordScale(); // ** init FreeType to describe the glyph FreeType::Char3DInfo char3d(_facade->getNumberCurveSamples()); char3d._coord_scale = coord_scale; FT_Outline outline = _face->glyph->outline; FT_Outline_Funcs funcs; funcs.conic_to = (FT_Outline_ConicToFunc)&FreeType::conicTo; funcs.line_to = (FT_Outline_LineToFunc)&FreeType::lineTo; funcs.cubic_to = (FT_Outline_CubicToFunc)&FreeType::cubicTo; funcs.move_to = (FT_Outline_MoveToFunc)&FreeType::moveTo; funcs.shift = 0; funcs.delta = 0; // ** record description FT_Error _error = FT_Outline_Decompose(&outline, &funcs, &char3d); if (_error) { OSG_WARN << "FreeTypeFont3D::getGlyph : - outline decompose failed ..." << std::endl; return 0; } // ** create geometry for each part of the glyph osg::ref_ptr<osg::Geometry> frontGeo(new osg::Geometry); osg::ref_ptr<osg::Vec3Array> rawVertices = new osg::Vec3Array(*(char3d._verts)); osg::Geometry::PrimitiveSetList rawPrimitives; for(osg::Geometry::PrimitiveSetList::iterator itr = char3d.get()->getPrimitiveSetList().begin(); itr != char3d.get()->getPrimitiveSetList().end(); ++itr) { rawPrimitives.push_back(dynamic_cast<osg::PrimitiveSet*>((*itr)->clone(osg::CopyOp::DEEP_COPY_ALL))); } // ** save vertices and PrimitiveSetList of each face in the Glyph3D PrimitiveSet face list osg::ref_ptr<osgText::Glyph3D> glyph = new osgText::Glyph3D(_facade, charcode); // copy the raw primitive set list before we tessellate it. glyph->getRawFacePrimitiveSetList() = rawPrimitives; glyph->setRawVertexArray(rawVertices.get()); FT_Glyph_Metrics* metrics = &(_face->glyph->metrics); glyph->setWidth((float)metrics->width * coord_scale); glyph->setHeight((float)metrics->height * coord_scale); glyph->setHorizontalBearing(osg::Vec2((float)metrics->horiBearingX * coord_scale,(float)(metrics->horiBearingY-metrics->height) * coord_scale)); // bottom left. glyph->setHorizontalAdvance((float)metrics->horiAdvance * coord_scale); glyph->setVerticalBearing(osg::Vec2((float)metrics->vertBearingX * coord_scale,(float)(metrics->vertBearingY-metrics->height) * coord_scale)); // top middle. glyph->setVerticalAdvance((float)metrics->vertAdvance * coord_scale); #if 0 OSG_NOTICE<<"getGlyph3D("<<charcode<<", "<<char(charcode)<<")"<<std::endl; OSG_NOTICE<<" height="<<glyph->getHeight()<<std::endl; OSG_NOTICE<<" width="<<glyph->getWidth()<<std::endl; OSG_NOTICE<<" horizontalBearing="<<glyph->getHorizontalBearing()<<std::endl; OSG_NOTICE<<" horizontalAdvance="<<glyph->getHorizontalAdvance()<<std::endl; OSG_NOTICE<<" verticalBearing="<<glyph->getHorizontalBearing()<<std::endl; OSG_NOTICE<<" verticalAdvance="<<glyph->getVerticalAdvance()<<std::endl; #endif FT_BBox ftbb; FT_Outline_Get_BBox(&outline, &ftbb); osg::BoundingBox bb(float(ftbb.xMin) * coord_scale, float(ftbb.yMin) * coord_scale, 0.0f, float(ftbb.xMax) * coord_scale, float(ftbb.yMax) * coord_scale, 0.0f); glyph->setBoundingBox(bb); return glyph.release(); } osg::Vec2 FreeTypeFont::getKerning(unsigned int leftcharcode,unsigned int rightcharcode, osgText::KerningType kerningType) { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(FreeTypeLibrary::instance()->getMutex()); if (!FT_HAS_KERNING(_face) || (kerningType == osgText::KERNING_NONE)) return osg::Vec2(0.0f,0.0f); FT_Kerning_Mode mode = (kerningType==osgText::KERNING_DEFAULT) ? ft_kerning_default : ft_kerning_unfitted; // convert character code to glyph index FT_UInt left = FT_Get_Char_Index( _face, leftcharcode ); FT_UInt right = FT_Get_Char_Index( _face, rightcharcode ); // get the kerning distances. FT_Vector kerning; FT_Error error = FT_Get_Kerning( _face, // handle to face object left, // left glyph index right, // right glyph index mode, // kerning mode &kerning ); // target vector if (error) { OSG_WARN << "FT_Get_Kerning(...) returned error code " <<std::hex<<error<<std::dec<< std::endl; return osg::Vec2(0.0f,0.0f); } float coord_scale = getCoordScale(); return osg::Vec2((float)kerning.x*coord_scale,(float)kerning.y*coord_scale); } bool FreeTypeFont::hasVertical() const { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(FreeTypeLibrary::instance()->getMutex()); return FT_HAS_VERTICAL(_face)!=0; } bool FreeTypeFont::getVerticalSize(float & ascender, float & descender) const { OpenThreads::ScopedLock<OpenThreads::Mutex> lock(FreeTypeLibrary::instance()->getMutex()); #if 0 if(_face->units_per_EM != 0) { float coord_scale = 1.0f/static_cast<float>(_face->units_per_EM); ascender = static_cast<float>(_face->ascender) * coord_scale; descender = static_cast<float>(_face->descender) * coord_scale; return true; } else { return false; } #else float coord_scale = getCoordScale(); ascender = static_cast<float>(_face->ascender) * coord_scale; descender = static_cast<float>(_face->descender) * coord_scale; return true; #endif } float FreeTypeFont::getCoordScale() const { //float coord_scale = _freetype_scale/64.0f; //float coord_scale = 1.0f/64.0f; float coord_scale = 1.0f/(float(_currentRes.second)*64.0f); return coord_scale; }
33.300341
164
0.606283
Zitara
8af1b5bd6347590cd332381fda6ab6b0d40f2900
1,507
cpp
C++
COM Interfaces/IDispatch.cpp
ntclark/PDFium-Control
4d1f41a7a48205ea26fb46dac59fec16c53df2ef
[ "BSD-3-Clause" ]
2
2019-02-21T06:25:03.000Z
2019-06-23T04:49:14.000Z
COM Interfaces/IDispatch.cpp
ntclark/PDFium-Control
4d1f41a7a48205ea26fb46dac59fec16c53df2ef
[ "BSD-3-Clause" ]
1
2020-08-29T03:02:46.000Z
2020-08-29T03:02:46.000Z
COM Interfaces/IDispatch.cpp
ntclark/PDFium-Control
4d1f41a7a48205ea26fb46dac59fec16c53df2ef
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017, 2018, 2019 InnoVisioNate Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "PDFiumControl.h" // IDispatch STDMETHODIMP PDFiumControl::GetTypeInfoCount(UINT * pctinfo) { *pctinfo = 1; return S_OK; } long __stdcall PDFiumControl::GetTypeInfo(UINT itinfo,LCID lcid,ITypeInfo **pptinfo) { *pptinfo = NULL; if ( itinfo != 0 ) return DISP_E_BADINDEX; if ( ! pITypeInfo_IPDFiumControl ) { } *pptinfo = pITypeInfo_IPDFiumControl; pITypeInfo_IPDFiumControl -> AddRef(); return S_OK; } STDMETHODIMP PDFiumControl::GetIDsOfNames(REFIID riid,OLECHAR** rgszNames,UINT cNames,LCID lcid, DISPID* rgdispid) { return DispGetIDsOfNames(pITypeInfo_IPDFiumControl, rgszNames, cNames, rgdispid); } STDMETHODIMP PDFiumControl::Invoke(DISPID dispidMember, REFIID riid, LCID lcid, WORD wFlags,DISPPARAMS FAR* pdispparams, VARIANT FAR* pvarResult, EXCEPINFO FAR* pexcepinfo, UINT FAR* puArgErr) { IDispatch *ppv; QueryInterface(IID_IDispatch,reinterpret_cast<void**>(&ppv)); HRESULT hr = pITypeInfo_IPDFiumControl -> Invoke(ppv,dispidMember,wFlags,pdispparams,pvarResult,pexcepinfo,puArgErr); ppv -> Release(); return hr; }
30.755102
138
0.629064
ntclark
8af345c62166da543e44498f6c87fae58444f925
72
cpp
C++
src/native/WeChatHelper/WeChatHelper27278/WeChatHelper27278.cpp
xundididi/weicai-scraper
e0e0931f769814e04e8e3f8d7c670675f420b980
[ "MIT" ]
71
2019-11-30T08:37:15.000Z
2022-02-09T02:33:08.000Z
src/native/WeChatHelper/WeChatHelper27278/WeChatHelper27278.cpp
adams549659584/weicai-scraper
e0e0931f769814e04e8e3f8d7c670675f420b980
[ "MIT" ]
9
2020-03-04T08:18:46.000Z
2021-05-10T22:38:05.000Z
src/native/WeChatHelper/WeChatHelper27278/WeChatHelper27278.cpp
adams549659584/weicai-scraper
e0e0931f769814e04e8e3f8d7c670675f420b980
[ "MIT" ]
37
2019-12-12T11:22:30.000Z
2021-11-10T14:42:15.000Z
// WeChatHelper27278.cpp : 定义 DLL 应用程序的导出函数。 // #include "stdafx.h"
10.285714
45
0.666667
xundididi
8af8630a3bf0fa2e294f240b467fec98c75f9582
628
cpp
C++
Readme_Engine/PanelConsole.cpp
dafral/Readme_Engine
b815e1a29bfdf5e1acc9ff133d406ac9f12085d4
[ "MIT" ]
null
null
null
Readme_Engine/PanelConsole.cpp
dafral/Readme_Engine
b815e1a29bfdf5e1acc9ff133d406ac9f12085d4
[ "MIT" ]
null
null
null
Readme_Engine/PanelConsole.cpp
dafral/Readme_Engine
b815e1a29bfdf5e1acc9ff133d406ac9f12085d4
[ "MIT" ]
null
null
null
#include "PanelConsole.h" #include "Application.h" PanelConsole::PanelConsole(bool active = true) : Panel(active) {} PanelConsole::~PanelConsole() {} void PanelConsole::Draw() { ImGui::SetNextWindowPos(ImVec2(x, y)); ImGui::SetNextWindowSize(ImVec2(w, h)); ImGui::Begin("Console", &active); ImGui::Text(App->text.begin()); ImGui::End(); } void PanelConsole::ConsoleText(const char* log) { App->text.append(log); App->text.append("\n"); } void PanelConsole::AdjustPanel() { h = 300; w = App->window->GetWidth() / 2; x = (App->window->GetWidth() / 2) - (w / 2); y = App->window->GetHeight() - (MARGIN_Y + h); }
19.625
62
0.654459
dafral
8af8ce245411708801abe5cde44f4273199529df
3,738
cpp
C++
Samples/UWP/D3D12PipelineStateCache/src/MemoryMappedFile.cpp
mvisic/DirectX-Graphics-Samples
5055b4f062bbc2e5f746cca377f5760c394bc2d6
[ "MIT" ]
2
2020-09-24T09:31:52.000Z
2021-01-04T08:10:02.000Z
Samples/UWP/D3D12PipelineStateCache/src/MemoryMappedFile.cpp
mvisic/DirectX-Graphics-Samples
5055b4f062bbc2e5f746cca377f5760c394bc2d6
[ "MIT" ]
null
null
null
Samples/UWP/D3D12PipelineStateCache/src/MemoryMappedFile.cpp
mvisic/DirectX-Graphics-Samples
5055b4f062bbc2e5f746cca377f5760c394bc2d6
[ "MIT" ]
2
2020-09-24T09:31:56.000Z
2022-01-14T01:03:06.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "stdafx.h" #include "MemoryMappedFile.h" MemoryMappedFile::MemoryMappedFile() : m_mapFile(INVALID_HANDLE_VALUE), m_file(INVALID_HANDLE_VALUE), m_mapAddress(nullptr), m_currentFileSize(0) { } MemoryMappedFile::~MemoryMappedFile() { } void MemoryMappedFile::Init(std::wstring filename, UINT fileSize) { m_filename = filename; WIN32_FIND_DATA findFileData; HANDLE handle = FindFirstFileEx(filename.c_str(), FindExInfoBasic, &findFileData, FindExSearchNameMatch, nullptr, 0); bool found = handle != INVALID_HANDLE_VALUE; if (found) { FindClose(handle); } m_file = CreateFile2( filename.c_str(), GENERIC_READ | GENERIC_WRITE, 0, (found) ? OPEN_EXISTING : CREATE_NEW, nullptr); if (m_file == INVALID_HANDLE_VALUE) { std::cerr << (L"m_file is invalid. Error %ld.\n", GetLastError()); std::cerr << (L"Target file is %s\n", filename.c_str()); return; } LARGE_INTEGER realFileSize = {}; BOOL flag = GetFileSizeEx(m_file, &realFileSize); if (!flag) { std::cerr << (L"\nError %ld occurred in GetFileSizeEx!", GetLastError()); assert(false); return; } assert(realFileSize.HighPart == 0); m_currentFileSize = realFileSize.LowPart; if (m_currentFileSize == 0) { // File mapping files with a size of 0 produces an error. m_currentFileSize = DefaultFileSize; } else if(fileSize > m_currentFileSize) { // Grow to the specified size. m_currentFileSize = fileSize; } m_mapFile = CreateFileMapping(m_file, nullptr, PAGE_READWRITE, 0, m_currentFileSize, nullptr); if (m_mapFile == nullptr) { std::cerr << (L"m_mapFile is NULL: last error: %d\n", GetLastError()); assert(false); return; } m_mapAddress = MapViewOfFile(m_mapFile, FILE_MAP_ALL_ACCESS, 0, 0, m_currentFileSize); if (m_mapAddress == nullptr) { std::cerr << (L"m_mapAddress is NULL: last error: %d\n", GetLastError()); assert(false); return; } } void MemoryMappedFile::Destroy(bool deleteFile) { if (m_mapAddress) { BOOL flag = UnmapViewOfFile(m_mapAddress); if (!flag) { std::cerr << (L"\nError %ld occurred unmapping the view!", GetLastError()); assert(false); } m_mapAddress = nullptr; flag = CloseHandle(m_mapFile); // Close the file mapping object. if (!flag) { std::cerr << (L"\nError %ld occurred closing the mapping object!", GetLastError()); assert(false); } flag = CloseHandle(m_file); // Close the file itself. if (!flag) { std::cerr << (L"\nError %ld occurred closing the file!", GetLastError()); assert(false); } } if (deleteFile) { DeleteFile(m_filename.c_str()); } } void MemoryMappedFile::GrowMapping(UINT size) { // Add space for the extra size at the beginning of the file. size += sizeof(UINT); // Check the size. if (size <= m_currentFileSize) { // Don't shrink. return; } // Flush. BOOL flag = FlushViewOfFile(m_mapAddress, 0); if (!flag) { std::cerr << (L"\nError %ld occurred flushing the mapping object!", GetLastError()); assert(false); } // Close the current mapping. Destroy(false); // Update the size and create a new mapping. m_currentFileSize = size; Init(m_filename, m_currentFileSize); }
24.116129
119
0.644195
mvisic
8afb1742942826175b02014cfc8a551f07d540d2
736
hpp
C++
include/amtrs/.inc/io-size.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
1
2019-12-10T02:12:49.000Z
2019-12-10T02:12:49.000Z
include/amtrs/.inc/io-size.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
include/amtrs/.inc/io-size.hpp
isaponsoft/libamtrs
5adf821ee15592fc3280985658ca8a4b175ffcaa
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. * * Use of this source code is governed by a BSD-style license that * * can be found in the LICENSE file. */ #ifndef __libamtrs__io__size__hpp #define __libamtrs__io__size__hpp AMTRS_IO_NAMESPACE_BEGIN template<class In> uintmax_t size(In& _in) { return io_traits_t<In>{}.size(_in); } template<class CharT, class Traits> uintmax_t size(std::basic_istream<CharT, Traits>& _in) { _in.clear(); seek(_in, 0, std::ios::end); auto endPos = _in.tellg(); _in.clear(); seek(_in, 0, std::ios::beg); auto begPos = _in.tellg(); _in.clear(); return static_cast<uintmax_t>(endPos - begPos); } AMTRS_IO_NAMESPACE_END #endif
21.028571
72
0.686141
isaponsoft
8afcb7a84d82e8b57abbb6f1696651e331212a3e
1,354
cc
C++
src/Code.cc
GuessEver/grun-core
4250e00393251ee3a07124a9945cf1835f96922b
[ "MIT" ]
2
2017-05-06T10:02:13.000Z
2019-12-09T12:58:01.000Z
src/Code.cc
GuessEver/grun-core
4250e00393251ee3a07124a9945cf1835f96922b
[ "MIT" ]
null
null
null
src/Code.cc
GuessEver/grun-core
4250e00393251ee3a07124a9945cf1835f96922b
[ "MIT" ]
1
2018-10-09T11:17:57.000Z
2018-10-09T11:17:57.000Z
// // Created by guessever on 5/3/17. // #include <string.h> #include "Code.h" #include "Grun.h" /** * get extension from filename * @param filename * @return extension */ const char *getExtension(const char *filename) { long len = strlen(filename) - 1; for (long i = 0; filename[i]; i++) { if (filename[i] == '.') { len = i; } } return filename + len + 1; } /** * initialize data * @param path */ Code::Code(const char *path) { this->path = path; const char *ext = getExtension(this->path); if (!strcmp(ext, "pas")) { this->language = Pascal; this->extension = "pas"; } else if (!strcmp(ext, "c")) { this->language = C; this->extension = "c"; } else if (!strcmp(ext, "cc") || !strcmp(ext, "cxx") || !strcmp(ext, "cpp")) { this->language = CC; this->extension = "cc"; } else if (!strcmp(ext, "java")) { this->language = Java; this->extension = "java"; } else if (!strcmp(ext, "py")) { this->language = Python; this->extension = "py"; } else if (!strcmp(ext, "lua")) { this->language = Lua; this->extension = "lua"; } this->filename2 = "Main"; char *tmp = new char[255]; sprintf(tmp, "%s.%s", this->filename2, this->extension); this->filename = tmp; }
24.178571
82
0.526588
GuessEver
c10007ec3dce74631d45a270634358bcd3f2dc29
665
cpp
C++
Week-3/Day-16-checkValidString.cpp
utkarshavardhana/30-day-leetcoding-challenge
a47b14f74f28961a032d1f00ce710ea3dcb0d910
[ "MIT" ]
2
2020-05-02T04:21:56.000Z
2020-05-14T04:19:47.000Z
Week-3/Day-16-checkValidString.cpp
utkarshavardhana/30-day-leetcoding-challenge
a47b14f74f28961a032d1f00ce710ea3dcb0d910
[ "MIT" ]
null
null
null
Week-3/Day-16-checkValidString.cpp
utkarshavardhana/30-day-leetcoding-challenge
a47b14f74f28961a032d1f00ce710ea3dcb0d910
[ "MIT" ]
null
null
null
class Solution { public: bool checkValidString(string s) { stack<int> st, st1; int i(0); for(const auto &c: s) { if(c == '(') st.push(i); else if(c == '*') st1.push(i); else { if(st.empty() && st1.empty()) return false; else { if(!st.empty()) st.pop(); else st1.pop(); } } i++; } while(!st.empty()) { if(!st1.empty() && st.top() < st1.top()) st.pop(), st1.pop(); else return false; } return true; } };
25.576923
74
0.350376
utkarshavardhana
c1038a684e9e79e241ee1aaac41bcd566f98a22f
314
cpp
C++
usaco/milkpails.cpp
datpq/competitive-programming
ed5733cc55fa4167c4a2e828894b044ea600dcac
[ "MIT" ]
1
2022-02-24T21:35:18.000Z
2022-02-24T21:35:18.000Z
usaco/milkpails.cpp
datpq/competitive-programming
ed5733cc55fa4167c4a2e828894b044ea600dcac
[ "MIT" ]
null
null
null
usaco/milkpails.cpp
datpq/competitive-programming
ed5733cc55fa4167c4a2e828894b044ea600dcac
[ "MIT" ]
1
2022-02-12T14:40:21.000Z
2022-02-12T14:40:21.000Z
#include <fstream> using namespace std; int main() { ifstream ifs("pails.in"); ofstream ofs("pails.out"); int x, y, m; ifs >> x >> y >> m; int ans = m; for (int i = 0; i <= (m / x); i++) { int remainder = m - (i * x); ans = min(ans, remainder % y); if (ans == 0) break; } ofs << (m - ans) << endl; }
19.625
37
0.515924
datpq
c10505d2cd710a8e041e77fb1120b415f6102343
1,674
hpp
C++
IgzModelConverterGUI/3rd_party/PreCore/datas/Matrix44.hpp
AdventureT/IgzModelConverter
7b213d0dd32f04bc01524587a4fa357d204e1c04
[ "MIT" ]
9
2019-10-11T18:12:15.000Z
2022-03-26T23:57:05.000Z
IgzModelConverterGUI/3rd_party/PreCore/datas/Matrix44.hpp
AdventureT/IgzModelConverter
7b213d0dd32f04bc01524587a4fa357d204e1c04
[ "MIT" ]
2
2021-07-29T11:29:30.000Z
2021-12-12T20:40:08.000Z
IgzModelConverterGUI/3rd_party/PreCore/datas/Matrix44.hpp
AdventureT/IgzModelConverter
7b213d0dd32f04bc01524587a4fa357d204e1c04
[ "MIT" ]
1
2020-10-01T23:00:28.000Z
2020-10-01T23:00:28.000Z
/* esMatrix44 class is a simple affine matrix 4x4 more info in README for PreCore Project Copyright 2018-2019 Lukas Cone Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include "VectorsSimd.hpp" class esMatrix44 { public: Vector4A16 r1, r2, r3, r4; esMatrix44(); esMatrix44(const Vector4A16 &row1, const Vector4A16 &row2, const Vector4A16 &row3) : r1(row1), r2(row2), r3(row3) {} esMatrix44(const Vector4A16 &row1, const Vector4A16 &row2, const Vector4A16 &row3, const Vector4A16 &row4) : r1(row1), r2(row2), r3(row3), r4(row4) {} esMatrix44(const Vector4A16 &quat); esMatrix44(const Vector4A16 *rows) : r1(rows[0]), r2(rows[1]), r3(rows[2]), r4(rows[3]) {} void MakeIdentity(); void Decompose(Vector4A16 &position, Vector4A16 &rotation, Vector4A16 &scale) const; void Compose(const Vector4A16 &position, const Vector4A16 &rotation, const Vector4A16 &scale); Vector4A16 RotatePoint(const Vector4A16 &input) const; void FromQuat(const Vector4A16 &q); Vector4A16 ToQuat() const; };
38.045455
80
0.676225
AdventureT
c10709bbee231e2759696c8e0449154f77cc4fee
18,464
cpp
C++
FireRender.Maya.Src/AnimationExporter.cpp
Speedwag00n/RadeonProRenderMayaPlugin
a6560354aeeccc9f1a31a321fb04cb372e220a3b
[ "Apache-2.0" ]
null
null
null
FireRender.Maya.Src/AnimationExporter.cpp
Speedwag00n/RadeonProRenderMayaPlugin
a6560354aeeccc9f1a31a321fb04cb372e220a3b
[ "Apache-2.0" ]
1
2021-04-03T09:39:16.000Z
2021-04-03T09:39:16.000Z
FireRender.Maya.Src/AnimationExporter.cpp
Speedwag00n/RadeonProRenderMayaPlugin
a6560354aeeccc9f1a31a321fb04cb372e220a3b
[ "Apache-2.0" ]
null
null
null
#include "AnimationExporter.h" #include "RprLoadStore.h" #include <maya/MItDag.h> #include <maya/MGlobal.h> #include <maya/MDagPath.h> #include <maya/MAnimUtil.h> #include <maya/MTime.h> #include <maya/MQuaternion.h> #include <maya/MFnTransform.h> #include <maya/MSelectionList.h> #include <maya/MFnMatrixData.h> #include <maya/MPlugArray.h> #include <maya/MAnimControl.h> const int COMPONENT_COUNT_ROTATION = 4; const int COMPONENT_COUNT_TRANSLATION = 3; const int COMPONENT_COUNT_SCALE = 3; const int INPUT_PLUG_COUNT = 3; AnimationExporter::AnimationExporter(bool gltfExport) : m_IsGLTFExport(gltfExport), m_progressBars(nullptr) { if (m_IsGLTFExport) { m_runtimeMoveTypeTranslation = RPRGLTF_ANIMATION_MOVEMENTTYPE_TRANSLATION; m_runtimeMoveTypeRotation = RPRGLTF_ANIMATION_MOVEMENTTYPE_ROTATION; m_runtimeMoveTypeScale = RPRGLTF_ANIMATION_MOVEMENTTYPE_SCALE; m_pFunc_AddExtraCamera = rprGLTF_AddExtraCamera; m_pFunc_AssignCameraToGroup = rprGLTF_AssignCameraToGroup; m_pFunc_AddExtraShapeParameter = rprGLTF_AddExtraShapeParameter; m_pFunc_AssignLightToGroup = rprGLTF_AssignLightToGroup; m_pFunc_AssignShapeToGroup = rprGLTF_AssignShapeToGroup; m_pFunc_SetTransformGroup = rprGLTF_SetTransformGroup; m_pFunc_AssignParentGroupToGroup = rprGLTF_AssignParentGroupToGroup; m_pFunc_AddAnimationTrackToRPR = &AnimationExporter::AddAnimationToGLTFRPR; } else { m_runtimeMoveTypeTranslation = RPRS_ANIMATION_MOVEMENTTYPE_TRANSLATION; m_runtimeMoveTypeRotation = RPRS_ANIMATION_MOVEMENTTYPE_ROTATION; m_runtimeMoveTypeScale = RPRS_ANIMATION_MOVEMENTTYPE_SCALE; m_pFunc_AddExtraCamera = rprsAddExtraCamera; m_pFunc_AddExtraShapeParameter = rprsAddExtraShapeParameter; m_pFunc_AssignLightToGroup = rprsAssignLightToGroup; m_pFunc_AssignCameraToGroup = rprsAssignCameraToGroup; m_pFunc_AssignShapeToGroup = rprsAssignShapeToGroup; m_pFunc_SetTransformGroup = rprsSetTransformGroup; m_pFunc_AssignParentGroupToGroup = rprsAssignParentGroupToGroup; m_pFunc_AddAnimationTrackToRPR = &AnimationExporter::AddAnimationToRPRS; } } void AnimationExporter::Export(FireRenderContext& context, MDagPathArray* renderableCamera) { m_dataHolder.animationDataVector.clear(); m_dataHolder.cameraVector.clear(); m_dataHolder.inputRenderableCameras = renderableCamera; AddAnimations(m_dataHolder, context); } MString AnimationExporter::GetGroupNameForDagPath(MDagPath dagPath, int pop) { if (pop > 0) { dagPath.pop(); } if (dagPath.node().hasFn(MFn::kTransform)) { return dagPath.fullPathName(); } else { // if dagPath points to shape, we need to do pop 1 to get path poiting to transform dagPath.pop(); return dagPath.fullPathName(); } } void FillArrayWithMMatrixData(std::array<float, 16>& arr, const MMatrix& matrix) { for (int i = 0; i < 4; i++) for (int j = 0; j < 4; j++) { arr[i * 4 + j] = (float)matrix(i, j); } } void FillArrayWithScaledMMatrixData(std::array<float, 16>& arr, float coeff = 0.01f) { MMatrix matrix; matrix[0][0] = coeff; matrix[1][1] = coeff; matrix[2][2] = coeff; FillArrayWithMMatrixData(arr, matrix); } void AnimationExporter::AssignCameras(DataHolderStruct& dataHolder, FireRenderContext& context) { MDagPathArray& renderableCameras = *dataHolder.inputRenderableCameras; MDagPath mainCameraPath = context.camera().DagPath(); for (unsigned int i = 0; i < renderableCameras.length(); i++) { MDagPath dagPath = renderableCameras[i]; MMatrix camIdentityMatrix; rpr_camera rprCamera; MString camGroupName = GetGroupNameForDagPath(dagPath); if (mainCameraPath.fullPathName() != dagPath.fullPathName()) { frw::Camera extraCamera = context.GetContext().CreateCamera(); dataHolder.cameraVector.push_back(extraCamera); rprCamera = extraCamera.Handle(); int cameraType = FireRenderGlobals::kCameraDefault; FireMaya::translateCamera(extraCamera, dagPath.node(), camIdentityMatrix, true, (float)context.width() / context.height(), true, cameraType); if (m_pFunc_AddExtraCamera != nullptr) { m_pFunc_AddExtraCamera(rprCamera); } } else { rprCamera = context.camera().data().Handle(); SetCameraLookatForMatrix(rprCamera, camIdentityMatrix); } // set gltf/rprs group name for camera m_pFunc_AssignCameraToGroup(rprCamera, camGroupName.asChar()); } } int getUVLightGroup(const MDagPath& inDagPath) { MDagPath dagPath = inDagPath; while (dagPath.transform() != MObject()) { MFnTransform transform(dagPath.transform()); MPlug plug = transform.findPlug("lightmapUVGroup"); if (!plug.isNull()) { return plug.asInt(); } dagPath.pop(); } return -1; } void AnimationExporter::assignMesh(FireRenderMesh* pMesh, const MString& groupName, const MDagPath& dagPath) { for (auto& element : pMesh->Elements()) { int res = m_pFunc_AssignShapeToGroup(element.shape.Handle(), groupName.asChar()); assert(res == RPR_SUCCESS); //Reset transform for shape since we already have transformation in parent groups std::array<float, 16> arr; FillArrayWithScaledMMatrixData(arr); element.shape.SetTransform(arr.data()); int lightGroup = getUVLightGroup(dagPath); if (lightGroup >= 0) { if (m_pFunc_AddExtraShapeParameter != nullptr) { m_pFunc_AddExtraShapeParameter(element.shape.Handle(), "lightmapUVGroup", lightGroup); } } } } void AnimationExporter::assignLight(FireRenderLight* pLight, const MString& groupName) { // this function was not included in dylib for some reason #ifdef _WIN32 m_pFunc_AssignLightToGroup(pLight->data().light.Handle(), groupName.asChar()); #endif //Reset transform for shape since we already have transformation in parent groups std::array<float, 16> arr; FillArrayWithScaledMMatrixData(arr); pLight->GetFrLight().light.SetTransform(arr.data()); } void AnimationExporter::AssignMeshesAndLights(FireRenderContext& context) { FireRenderContext::FireRenderObjectMap& sceneObjects = context.GetSceneObjects(); // set gltf/rprs group name for meshes for (FireRenderContext::FireRenderObjectMap::iterator it = sceneObjects.begin(); it != sceneObjects.end(); ++it) { FireRenderNode* pNode = dynamic_cast<FireRenderNode*>(it->second.get()); if (pNode == nullptr) { continue; } MDagPath dagPath = pNode->DagPath(); if (!IsNeedToSetANameForTransform(dagPath)) { continue; } MString groupName = GetGroupNameForDagPath(dagPath); FireRenderMesh* pMesh = dynamic_cast<FireRenderMesh*>(pNode); FireRenderLight* pLight = dynamic_cast<FireRenderLight*>(pNode); if (pMesh != nullptr) { assignMesh(pMesh, groupName, dagPath); } else if (pLight != nullptr && !pLight->data().isAreaLight) { assignLight(pLight, groupName); } } } void AnimationExporter::AddAnimations(DataHolderStruct& dataHolder, FireRenderContext& context) { AssignCameras(dataHolder, context); AssignMeshesAndLights(context); AnimateGroups(dataHolder.animationDataVector); } bool AnimationExporter::IsNeedToSetANameForTransform(const MDagPath& dagPath) { MObject transform = dagPath.transform(); MFnDagNode transformDagNode(transform); if (transformDagNode.childCount() == 0) { // skip transform if it has no children return false; } return true; } void AnimationExporter::SetTransformationForNode(MObject transform, const char* groupName) { MFnDependencyNode fnTransform(transform); MPlug matrixPlug = fnTransform.findPlug("matrix"); MMatrix newMatrix; MObject val; matrixPlug.getValue(val); newMatrix = MFnMatrixData(val).matrix(); MTransformationMatrix transformMatrix(newMatrix); std::array<float, 10> arr; MVector vecTranslation = transformMatrix.getTranslation(MSpace::kTransform); MQuaternion rotation = transformMatrix.rotation(); double scale[3]; transformMatrix.getScale(scale, MSpace::kTransform); //cm to m float coeff = 0.01f; vecTranslation *= coeff; int index = 0; for (int i = 0; i < 3; i++) { arr[index++] = (float)vecTranslation[i]; } for (int i = 0; i < 4; i++) { arr[index++] = (float)rotation[i]; } for (int i = 0; i < 3; i++) { arr[index++] = (float)scale[i]; } m_pFunc_SetTransformGroup(groupName, arr.data()); } void AnimationExporter::AnimateGroups(AnimationDataHolderVector& dataHolder) { MStatus status; std::vector<MDagPath> groupDagPathVector; MItDag itDag(MItDag::kDepthFirst, MFn::kDagNode, &status); if (MStatus::kSuccess != status) MGlobal::displayError("MItDag::MItDag iteration not possible?!"); for (; !itDag.isDone(); itDag.next()) { MDagPath dagPath; itDag.getPath(dagPath); if (!dagPath.node().hasFn(MFn::kTransform)) { continue; } if (!IsNeedToSetANameForTransform(dagPath)) { continue; } groupDagPathVector.push_back(dagPath); } MDagPath dagPath; for (size_t i = 0; i < groupDagPathVector.size(); ++i) { dagPath = groupDagPathVector[i]; MObject transform = dagPath.transform(); MString transformGroupName = GetGroupNameForDagPath(dagPath); SetTransformationForNode(transform, transformGroupName.asChar()); MString parentOfTransformGroupName = ""; // if non-root transform if (dagPath.length() > 1) { parentOfTransformGroupName = GetGroupNameForDagPath(dagPath, 1); } m_pFunc_AssignParentGroupToGroup(transformGroupName.asChar(), parentOfTransformGroupName.asChar()); MSelectionList selList; selList.add(transform); if (!MAnimUtil::isAnimated(selList)) { // skip transform if it is not animated continue; } ApplyAnimationForTransform(dagPath, dataHolder); ReportProgress((int)(100 * (i + 1) / groupDagPathVector.size())); } } MString AnimationExporter::GetAttributeNameById(int id) { if (id == m_runtimeMoveTypeTranslation) { return "translate"; } else if (id == m_runtimeMoveTypeRotation) { return "rotate"; } else if (id == m_runtimeMoveTypeScale) { return "scale"; } assert(false); return ""; } int AnimationExporter::GetOutputComponentCount(int attrId) { if (attrId == m_runtimeMoveTypeTranslation) { return COMPONENT_COUNT_TRANSLATION; } else if (attrId == m_runtimeMoveTypeRotation) { return COMPONENT_COUNT_SCALE; } else if (attrId == m_runtimeMoveTypeScale) { return COMPONENT_COUNT_ROTATION; } assert(false); return 0; } void AnimationExporter::AddTimesFromCurve(const MFnAnimCurve& curve, TimeKeySet& outUniqueTimeKeySet, int attributeId) { int keyCount = curve.numKeys(); MTime startTime = MAnimControl::animationStartTime(); MTime endTime = MAnimControl::animationEndTime(); for (int keyIndex = 0; keyIndex < keyCount; ++keyIndex) { MTime time = curve.time(keyIndex); if ((time < startTime) || (time > endTime)) { continue; } AddOneTimePoint(time, curve, outUniqueTimeKeySet, attributeId, keyIndex); } // Add auto point for the start and end animation point AddOneTimePoint(startTime, curve, outUniqueTimeKeySet, attributeId, 0); AddOneTimePoint(endTime, curve, outUniqueTimeKeySet, attributeId, keyCount - 1); } void AnimationExporter::AddOneTimePoint(const MTime time, const MFnAnimCurve& curve, TimeKeySet& outUniqueTimeKeySet, int attributeId, int keyIndex) { TimeKeyStruct timeKey(time, attributeId); TimeKeySet::iterator it = outUniqueTimeKeySet.find(timeKey); if (it != outUniqueTimeKeySet.end()) { it->AddNewAttribute(attributeId); } else { it = outUniqueTimeKeySet.insert(timeKey).first; } // if we process rotation attribute we should as translation as well because in some complex rotations translation might be changed as well if (attributeId == m_runtimeMoveTypeRotation) { it->AddNewAttribute(m_runtimeMoveTypeTranslation); } // keys autogeneration for rotation if ((attributeId == m_runtimeMoveTypeRotation) && (keyIndex > 0)) { double maxValue = curve.value(keyIndex); double minValue = curve.value(keyIndex - 1); double step = M_PI / 2; double currentValue = minValue + step; MTime prevTime = curve.time(keyIndex - 1); MTime maxTime = time; while (currentValue < maxValue) { MTime additionalTimePoint = prevTime + (maxTime - prevTime) * (currentValue - minValue) / (maxValue - minValue); outUniqueTimeKeySet.insert(TimeKeyStruct(additionalTimePoint, attributeId)); currentValue += step; } } } inline float AnimationExporter::GetValueForTime(const MPlug& plug, const MFnAnimCurve& curve, const MTime& time) { if (!curve.object().isNull()) { return (float)curve.evaluate(time); } else { return plug.asFloat(); } } void AnimationExporter::AddAnimationToGLTFRPR(AnimationDataHolderStruct& gltfDataHolderStruct, int attrId) { size_t keyCount = gltfDataHolderStruct.m_timePoints.size(); rprgltf_animation gltfAnimData; gltfAnimData.structSize = sizeof(gltfAnimData); // RPR GLTF takes char* that's why const cast is needed gltfAnimData.groupName = const_cast<char*>(gltfDataHolderStruct.groupName.asChar()); gltfAnimData.movementType = attrId; gltfAnimData.interpolationType = 0; gltfAnimData.nbTimeKeys = (unsigned int)keyCount; gltfAnimData.nbTransformValues = (unsigned int)keyCount; gltfAnimData.timeKeys = gltfDataHolderStruct.m_timePoints.data(); gltfAnimData.transformValues = gltfDataHolderStruct.m_values.data(); int res = rprGLTF_AddAnimation(&gltfAnimData); if (res != RPR_SUCCESS) { MGlobal::displayError("rprGLTF_AddAnimation returned error: "); } } void AnimationExporter::AddAnimationToRPRS(AnimationDataHolderStruct& dataHolderStruct, int attrId) { size_t keyCount = dataHolderStruct.m_timePoints.size(); rprs_animation rprsAnimData; rprsAnimData.structSize = sizeof(rprsAnimData); // RPRs takes char* that's why const cast is needed rprsAnimData.groupName = const_cast<char*>(dataHolderStruct.groupName.asChar()); rprsAnimData.movementType = attrId; rprsAnimData.interpolationType = 0; rprsAnimData.nbTimeKeys = (unsigned int)keyCount; rprsAnimData.nbTransformValues = (unsigned int)keyCount; rprsAnimData.timeKeys = dataHolderStruct.m_timePoints.data(); rprsAnimData.transformValues = dataHolderStruct.m_values.data(); int res = rprsAddAnimation(&rprsAnimData); if (res != RPR_SUCCESS) { MGlobal::displayError("rprGLTF_AddAnimation returned error: "); } } void AnimationExporter::ApplyAnimationForTransform(const MDagPath& dagPath, AnimationDataHolderVector& dataHolder) { // do not change order const int attrCount = 3; int attrIds[attrCount] = { m_runtimeMoveTypeTranslation, m_runtimeMoveTypeRotation, m_runtimeMoveTypeScale }; MString groupName = GetGroupNameForDagPath(dagPath); MFnDependencyNode depNodeTransform(dagPath.transform()); MFnTransform fnTransform(dagPath.transform()); const int inputPlugCount = INPUT_PLUG_COUNT; // it is always x, y, z as inputs MStatus status; MFnAnimCurve tempCurve; TimeKeySet uniqueTimeKeys; // Gather Unique key points MString componentNames[inputPlugCount] = { "X", "Y", "Z" }; for (int attributeId : attrIds) { MString attributeName = GetAttributeNameById(attributeId); MPlugArray plugArray; for (int i = 0; i < inputPlugCount; ++i) { MString plugName = attributeName + componentNames[i]; MPlug plug = depNodeTransform.findPlug(plugName, false, &status); if (status != MStatus::kSuccess || plug.isNull()) { MGlobal::displayError("GLTF/RPRS export error: Necessary plug not found: " + plugName); continue; } plugArray.append(plug); MObjectArray curveObj; if (MAnimUtil::findAnimation(plug, curveObj, &status)) { tempCurve.setObject(curveObj[0]); AddTimesFromCurve(tempCurve, uniqueTimeKeys, attributeId); } } } MPlug matrixPlug = depNodeTransform.findPlug("matrix", &status); size_t keyCount = uniqueTimeKeys.size(); // this is just for progress reporting size_t dataChunkIndex = 0; // Export necessary attributes for (int attributeId : attrIds) { dataHolder.emplace(dataHolder.end()); AnimationDataHolderStruct& dataHolderStruct = dataHolder.back(); for (TimeKeySet::iterator it = uniqueTimeKeys.begin(); it != uniqueTimeKeys.end(); it++) { dataChunkIndex++; if (!it->DoesAttributeIdPresent(attributeId)) { continue; } MTime time = it->GetTime(); MDGContext dgContext(time); MMatrix newMatrix; MObject val; matrixPlug.getValue(val, dgContext); newMatrix = MFnMatrixData(val).matrix(); MTransformationMatrix transformMatrix(newMatrix); dataHolderStruct.m_timePoints.push_back((float)it->GetTime().as(MTime::Unit::kSeconds)); if (attributeId == m_runtimeMoveTypeTranslation) { MVector vec1 = transformMatrix.getTranslation(MSpace::kTransform); //cm to m float coeff = 0.01f; dataHolderStruct.m_values.push_back((float)vec1.x * coeff); dataHolderStruct.m_values.push_back((float)vec1.y * coeff); dataHolderStruct.m_values.push_back((float)vec1.z * coeff); } else if (attributeId == m_runtimeMoveTypeRotation) { MQuaternion rotation = transformMatrix.rotation(); dataHolderStruct.m_values.push_back((float)rotation.x); dataHolderStruct.m_values.push_back((float)rotation.y); dataHolderStruct.m_values.push_back((float)rotation.z); dataHolderStruct.m_values.push_back((float)rotation.w); } else if (attributeId == m_runtimeMoveTypeScale) { double scale[3]; transformMatrix.getScale(scale, MSpace::kTransform); dataHolderStruct.m_values.push_back((float)scale[0]); dataHolderStruct.m_values.push_back((float)scale[1]); dataHolderStruct.m_values.push_back((float)scale[2]); } if (m_progressBars != nullptr && m_progressBars->isCancelled()) { throw ExportCancelledException(); } if (dataChunkIndex % 100 == 0) { ReportDataChunk(dataChunkIndex, attrCount * uniqueTimeKeys.size()); } } dataHolderStruct.groupName = groupName; if (dataHolderStruct.m_timePoints.size() > 0) { (this->*m_pFunc_AddAnimationTrackToRPR)(dataHolderStruct, attributeId); } } } void AnimationExporter::ReportDataChunk(size_t dataChunkIndex, size_t count) { std::ostringstream stream; stream << "Preparing Animation...current object: " << dataChunkIndex << " / " << count; if (m_progressBars != nullptr) { m_progressBars->SetTextAboveProgress(stream.str(), true); } } void AnimationExporter::ReportProgress(int progress) { if (m_progressBars != nullptr) { m_progressBars->update(progress); } } void AnimationExporter::ReportGLTFExportError(MString strPath) { MGlobal::displayError("GLTF/RPRs export error: cannot get animation for transform: " + strPath); }
26.528736
148
0.747455
Speedwag00n
c10bc8063d8b22b7096bbed7bbb9aff6dc1b138d
54,855
cpp
C++
tf2_src/engine/vengineserver_impl.cpp
IamIndeedGamingAsHardAsICan03489/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/engine/vengineserver_impl.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/engine/vengineserver_impl.cpp
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $Workfile: $ // $NoKeywords: $ //===========================================================================// #include "server_pch.h" #include "tier0/valve_minmax_off.h" #include <algorithm> #include "tier0/valve_minmax_on.h" #include "vengineserver_impl.h" #include "vox.h" #include "sound.h" #include "gl_model_private.h" #include "host_saverestore.h" #include "world.h" #include "l_studio.h" #include "decal.h" #include "sys_dll.h" #include "sv_log.h" #include "sv_main.h" #include "tier1/strtools.h" #include "collisionutils.h" #include "staticpropmgr.h" #include "string_t.h" #include "vstdlib/random.h" #include "EngineSoundInternal.h" #include "dt_send_eng.h" #include "PlayerState.h" #include "irecipientfilter.h" #include "sv_user.h" #include "server_class.h" #include "cdll_engine_int.h" #include "enginesingleuserfilter.h" #include "ispatialpartitioninternal.h" #include "con_nprint.h" #include "tmessage.h" #include "iscratchpad3d.h" #include "pr_edict.h" #include "networkstringtableserver.h" #include "networkstringtable.h" #include "LocalNetworkBackdoor.h" #include "host_phonehome.h" #include "matchmaking.h" #include "sv_plugin.h" #include "sv_steamauth.h" #include "replay_internal.h" #include "replayserver.h" #include "replay/iserverengine.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define MAX_MESSAGE_SIZE 2500 #define MAX_TOTAL_ENT_LEAFS 128 void SV_DetermineMulticastRecipients( bool usepas, const Vector& origin, CBitVec< ABSOLUTE_PLAYER_LIMIT >& playerbits ); int MapList_ListMaps( const char *pszSubString, bool listobsolete, bool verbose, int maxcount, int maxitemlength, char maplist[][ 64 ] ); extern CNetworkStringTableContainer *networkStringTableContainerServer; CSharedEdictChangeInfo g_SharedEdictChangeInfo; CSharedEdictChangeInfo *g_pSharedChangeInfo = &g_SharedEdictChangeInfo; IAchievementMgr *g_pAchievementMgr = NULL; CGamestatsData *g_pGamestatsData = NULL; void InvalidateSharedEdictChangeInfos() { if ( g_SharedEdictChangeInfo.m_iSerialNumber == 0xFFFF ) { // Reset all edicts to 0. g_SharedEdictChangeInfo.m_iSerialNumber = 1; for ( int i=0; i < sv.num_edicts; i++ ) sv.edicts[i].SetChangeInfoSerialNumber( 0 ); } else { g_SharedEdictChangeInfo.m_iSerialNumber++; } g_SharedEdictChangeInfo.m_nChangeInfos = 0; } // ---------------------------------------------------------------------- // // Globals. // ---------------------------------------------------------------------- // struct MsgData { MsgData() { Reset(); // link buffers to messages entityMsg.m_DataOut.StartWriting( entitydata, sizeof(entitydata) ); entityMsg.m_DataOut.SetDebugName( "s_MsgData.entityMsg.m_DataOut" ); userMsg.m_DataOut.StartWriting( userdata, sizeof(userdata) ); userMsg.m_DataOut.SetDebugName( "s_MsgData.userMsg.m_DataOut" ); } void Reset() { filter = NULL; reliable = false; subtype = 0; started = false; usermessagesize = -1; usermessagename = NULL; currentMsg = NULL; } byte userdata[ PAD_NUMBER( MAX_USER_MSG_DATA, 4 ) ]; // buffer for outgoing user messages byte entitydata[ PAD_NUMBER( MAX_ENTITY_MSG_DATA, 4 ) ]; // buffer for outgoing entity messages IRecipientFilter *filter; // clients who get this message bool reliable; INetMessage *currentMsg; // pointer to entityMsg or userMessage int subtype; // usermessage index bool started; // IS THERE A MESSAGE IN THE PROCESS OF BEING SENT? int usermessagesize; char const *usermessagename; SVC_EntityMessage entityMsg; SVC_UserMessage userMsg; }; static MsgData s_MsgData; void SeedRandomNumberGenerator( bool random_invariant ) { if (!random_invariant) { long iSeed; g_pVCR->Hook_Time( &iSeed ); float flAppTime = Plat_FloatTime(); ThreadId_t threadId = ThreadGetCurrentId(); iSeed ^= (*((int *)&flAppTime)); iSeed ^= threadId; RandomSeed( iSeed ); } else { // Make those random numbers the same every time! RandomSeed( 0 ); } } // ---------------------------------------------------------------------- // // Static helpers. // ---------------------------------------------------------------------- // static void PR_CheckEmptyString (const char *s) { if (s[0] <= ' ') Host_Error ("Bad string: %s", s); } // Average a list a vertices to find an approximate "center" static void CenterVerts( Vector verts[], int vertCount, Vector& center ) { int i; float scale; if ( vertCount ) { Vector edge0, edge1, normal; VectorCopy( vec3_origin, center ); // sum up verts for ( i = 0; i < vertCount; i++ ) { VectorAdd( center, verts[i], center ); } scale = 1.0f / (float)vertCount; VectorScale( center, scale, center ); // divide by vertCount // Compute 2 poly edges VectorSubtract( verts[1], verts[0], edge0 ); VectorSubtract( verts[vertCount-1], verts[0], edge1 ); // cross for normal CrossProduct( edge0, edge1, normal ); // Find the component of center that is outside of the plane scale = DotProduct( center, normal ) - DotProduct( verts[0], normal ); // subtract it off VectorMA( center, scale, normal, center ); // center is in the plane now } } // Copy the list of verts from an msurface_t int a linear array static void SurfaceToVerts( model_t *model, SurfaceHandle_t surfID, Vector verts[], int *vertCount ) { if ( *vertCount > MSurf_VertCount( surfID ) ) *vertCount = MSurf_VertCount( surfID ); // Build the list of verts from 0 to n for ( int i = 0; i < *vertCount; i++ ) { int vertIndex = model->brush.pShared->vertindices[ MSurf_FirstVertIndex( surfID ) + i ]; Vector& vert = model->brush.pShared->vertexes[ vertIndex ].position; VectorCopy( vert, verts[i] ); } // vert[0] is the first and last vert, there is no copy } // Calculate the surface area of an arbitrary msurface_t polygon (convex with collinear verts) static float SurfaceArea( model_t *model, SurfaceHandle_t surfID ) { Vector center, verts[32]; int vertCount = 32; float area; int i; // Compute a "center" point and fan SurfaceToVerts( model, surfID, verts, &vertCount ); CenterVerts( verts, vertCount, center ); area = 0; // For a triangle of the center and each edge for ( i = 0; i < vertCount; i++ ) { Vector edge0, edge1, out; int next; next = (i+1)%vertCount; VectorSubtract( verts[i], center, edge0 ); // 0.5 * edge cross edge (0.5 is done once at the end) VectorSubtract( verts[next], center, edge1 ); CrossProduct( edge0, edge1, out ); area += VectorLength( out ); } return area * 0.5; // 0.5 here } // Average the list of vertices to find an approximate "center" static void SurfaceCenter( model_t *model, SurfaceHandle_t surfID, Vector& center ) { Vector verts[32]; // We limit faces to 32 verts elsewhere in the engine int vertCount = 32; SurfaceToVerts( model, surfID, verts, &vertCount ); CenterVerts( verts, vertCount, center ); } static bool ValidCmd( const char *pCmd ) { int len; len = strlen(pCmd); // Valid commands all have a ';' or newline '\n' as their last character if ( len && (pCmd[len-1] == '\n' || pCmd[len-1] == ';') ) return true; return false; } // ---------------------------------------------------------------------- // // CVEngineServer // ---------------------------------------------------------------------- // class CVEngineServer : public IVEngineServer { public: virtual void ChangeLevel( const char* s1, const char* s2) { if ( !s1 ) { Sys_Error( "CVEngineServer::Changelevel with NULL s1\n" ); } char cmd[ 256 ]; char s1Escaped[ sizeof( cmd ) ]; char s2Escaped[ sizeof( cmd ) ]; if ( !Cbuf_EscapeCommandArg( s1, s1Escaped, sizeof( s1Escaped ) ) || ( s2 && !Cbuf_EscapeCommandArg( s2, s2Escaped, sizeof( s2Escaped ) ))) { Warning( "Illegal map name in ChangeLevel\n" ); return; } int cmdLen = 0; if ( !s2 ) // no indication of where they are coming from; so just do a standard old changelevel { cmdLen = Q_snprintf( cmd, sizeof( cmd ), "changelevel %s\n", s1Escaped ); } else { cmdLen = Q_snprintf( cmd, sizeof( cmd ), "changelevel2 %s %s\n", s1Escaped, s2Escaped ); } if ( !cmdLen || cmdLen >= sizeof( cmd ) ) { Warning( "Paramter overflow in ChangeLevel\n" ); return; } Cbuf_AddText( cmd ); } virtual int IsMapValid( const char *filename ) { return modelloader->Map_IsValid( filename ); } virtual bool IsDedicatedServer( void ) { return sv.IsDedicated(); } virtual int IsInEditMode( void ) { #ifdef SWDS return false; #else return g_bInEditMode; #endif } virtual int IsInCommentaryMode( void ) { #ifdef SWDS return false; #else return g_bInCommentaryMode; #endif } virtual void NotifyEdictFlagsChange( int iEdict ) { if ( g_pLocalNetworkBackdoor ) g_pLocalNetworkBackdoor->NotifyEdictFlagsChange( iEdict ); } virtual const CCheckTransmitInfo* GetPrevCheckTransmitInfo( edict_t *pPlayerEdict ) { int entnum = NUM_FOR_EDICT( pPlayerEdict ); if ( entnum < 1 || entnum > sv.GetClientCount() ) { Error( "Invalid client specified in GetPrevCheckTransmitInfo\n" ); return NULL; } CGameClient *client = sv.Client( entnum-1 ); return client->GetPrevPackInfo(); } virtual int PrecacheDecal( const char *name, bool preload /*=false*/ ) { PR_CheckEmptyString( name ); int i = SV_FindOrAddDecal( name, preload ); if ( i >= 0 ) { return i; } Host_Error( "CVEngineServer::PrecacheDecal: '%s' overflow, too many decals", name ); return 0; } virtual int PrecacheModel( const char *s, bool preload /*= false*/ ) { PR_CheckEmptyString (s); int i = SV_FindOrAddModel( s, preload ); if ( i >= 0 ) { return i; } Host_Error( "CVEngineServer::PrecacheModel: '%s' overflow, too many models", s ); return 0; } virtual int PrecacheGeneric(const char *s, bool preload /*= false*/ ) { int i; PR_CheckEmptyString (s); i = SV_FindOrAddGeneric( s, preload ); if (i >= 0) { return i; } Host_Error ("CVEngineServer::PrecacheGeneric: '%s' overflow", s); return 0; } virtual bool IsModelPrecached( char const *s ) const { int idx = SV_ModelIndex( s ); return idx != -1 ? true : false; } virtual bool IsDecalPrecached( char const *s ) const { int idx = SV_DecalIndex( s ); return idx != -1 ? true : false; } virtual bool IsGenericPrecached( char const *s ) const { int idx = SV_GenericIndex( s ); return idx != -1 ? true : false; } virtual void ForceExactFile( const char *s ) { Warning( "ForceExactFile no longer supported. Use sv_pure instead. (%s)\n", s ); } virtual void ForceModelBounds( const char *s, const Vector &mins, const Vector &maxs ) { PR_CheckEmptyString( s ); SV_ForceModelBounds( s, mins, maxs ); } virtual void ForceSimpleMaterial( const char *s ) { PR_CheckEmptyString( s ); SV_ForceSimpleMaterial( s ); } virtual bool IsInternalBuild( void ) { return !phonehome->IsExternalBuild(); } //----------------------------------------------------------------------------- // Purpose: Precache a sentence file (parse on server, send to client) // Input : *s - file name //----------------------------------------------------------------------------- virtual int PrecacheSentenceFile( const char *s, bool preload /*= false*/ ) { // UNDONE: Set up preload flag // UNDONE: Send this data to the client to support multiple sentence files VOX_ReadSentenceFile( s ); return 0; } //----------------------------------------------------------------------------- // Purpose: Retrieves the pvs for an origin into the specified array // Input : *org - origin // outputpvslength - size of outputpvs array in bytes // *outputpvs - If null, then return value is the needed length // Output : int - length of pvs array used ( in bytes ) //----------------------------------------------------------------------------- virtual int GetClusterForOrigin( const Vector& org ) { return CM_LeafCluster( CM_PointLeafnum( org ) ); } virtual int GetPVSForCluster( int clusterIndex, int outputpvslength, unsigned char *outputpvs ) { int length = (CM_NumClusters()+7)>>3; if ( outputpvs ) { if ( outputpvslength < length ) { Sys_Error( "GetPVSForOrigin called with inusfficient sized pvs array, need %i bytes!", length ); return length; } CM_Vis( outputpvs, outputpvslength, clusterIndex, DVIS_PVS ); } return length; } //----------------------------------------------------------------------------- // Purpose: Test origin against pvs array retreived from GetPVSForOrigin // Input : *org - origin to chec // checkpvslength - length of pvs array // *checkpvs - // Output : bool - true if entity is visible //----------------------------------------------------------------------------- virtual bool CheckOriginInPVS( const Vector& org, const unsigned char *checkpvs, int checkpvssize ) { int clusterIndex = CM_LeafCluster( CM_PointLeafnum( org ) ); if ( clusterIndex < 0 ) return false; int offset = clusterIndex>>3; if ( offset > checkpvssize ) { Sys_Error( "CheckOriginInPVS: cluster would read past end of pvs data (%i:%i)\n", offset, checkpvssize ); return false; } if ( !(checkpvs[offset] & (1<<(clusterIndex&7)) ) ) { return false; } return true; } //----------------------------------------------------------------------------- // Purpose: Test origin against pvs array retreived from GetPVSForOrigin // Input : *org - origin to chec // checkpvslength - length of pvs array // *checkpvs - // Output : bool - true if entity is visible //----------------------------------------------------------------------------- virtual bool CheckBoxInPVS( const Vector& mins, const Vector& maxs, const unsigned char *checkpvs, int checkpvssize ) { if ( !CM_BoxVisible( mins, maxs, checkpvs, checkpvssize ) ) { return false; } return true; } virtual int GetPlayerUserId( const edict_t *e ) { if ( !sv.IsActive() || !e) return -1; for ( int i = 0; i < sv.GetClientCount(); i++ ) { CGameClient *pClient = sv.Client(i); if ( pClient->edict == e ) { return pClient->m_UserID; } } // Couldn't find it return -1; } virtual const char *GetPlayerNetworkIDString( const edict_t *e ) { if ( !sv.IsActive() || !e) return NULL; for ( int i = 0; i < sv.GetClientCount(); i++ ) { CGameClient *pGameClient = sv.Client(i); if ( pGameClient->edict == e ) { return pGameClient->GetNetworkIDString(); } } // Couldn't find it return NULL; } virtual bool IsPlayerNameLocked( const edict_t *pEdict ) { if ( !sv.IsActive() || !pEdict ) return false; for ( int i = 0; i < sv.GetClientCount(); i++ ) { CGameClient *pClient = sv.Client( i ); if ( pClient->edict == pEdict ) { return pClient->IsPlayerNameLocked(); } } return false; } virtual bool CanPlayerChangeName( const edict_t *pEdict ) { if ( !sv.IsActive() || !pEdict ) return false; for ( int i = 0; i < sv.GetClientCount(); i++ ) { CGameClient *pClient = sv.Client( i ); if ( pClient->edict == pEdict ) { return ( !pClient->IsPlayerNameLocked() && !pClient->IsNameChangeOnCooldown() ); } } return false; } // See header comment. This is the canonical map lookup spot, and a superset of the server gameDLL's // CanProvideLevel/PrepareLevelResources virtual eFindMapResult FindMap( /* in/out */ char *pMapName, int nMapNameMax ) { char szOriginalName[256] = { 0 }; V_strncpy( szOriginalName, pMapName, sizeof( szOriginalName ) ); IServerGameDLL::eCanProvideLevelResult eCanGameDLLProvide = IServerGameDLL::eCanProvideLevel_CannotProvide; if ( g_iServerGameDLLVersion >= 10 ) { eCanGameDLLProvide = serverGameDLL->CanProvideLevel( pMapName, nMapNameMax ); } if ( eCanGameDLLProvide == IServerGameDLL::eCanProvideLevel_Possibly ) { return eFindMap_PossiblyAvailable; } else if ( eCanGameDLLProvide == IServerGameDLL::eCanProvideLevel_CanProvide ) { // See if the game dll fixed up the map name return ( V_strcmp( szOriginalName, pMapName ) == 0 ) ? eFindMap_Found : eFindMap_NonCanonical; } AssertMsg( eCanGameDLLProvide == IServerGameDLL::eCanProvideLevel_CannotProvide, "Unhandled enum member" ); char szDiskName[MAX_PATH] = { 0 }; // Check if we can directly use this as a map Host_DefaultMapFileName( pMapName, szDiskName, sizeof( szDiskName ) ); if ( *szDiskName && modelloader->Map_IsValid( szDiskName, true ) ) { return eFindMap_Found; } // Fuzzy match in map list and check file char match[1][64] = { {0} }; if ( MapList_ListMaps( pMapName, false, false, 1, sizeof( match[0] ), match ) && *(match[0]) ) { Host_DefaultMapFileName( match[0], szDiskName, sizeof( szDiskName ) ); if ( modelloader->Map_IsValid( szDiskName, true ) ) { V_strncpy( pMapName, match[0], nMapNameMax ); return eFindMap_FuzzyMatch; } } return eFindMap_NotFound; } virtual int IndexOfEdict(const edict_t *pEdict) { if ( !pEdict ) { return 0; } int index = (int) ( pEdict - sv.edicts ); if ( index < 0 || index > sv.max_edicts ) { Sys_Error( "Bad entity in IndexOfEdict() index %i pEdict %p sv.edicts %p\n", index, pEdict, sv.edicts ); } return index; } // Returns a pointer to an entity from an index, but only if the entity // is a valid DLL entity (ie. has an attached class) virtual edict_t* PEntityOfEntIndex(int iEntIndex) { if ( iEntIndex >= 0 && iEntIndex < sv.max_edicts ) { edict_t *pEdict = EDICT_NUM( iEntIndex ); if ( !pEdict->IsFree() ) { return pEdict; } } return NULL; } virtual int GetEntityCount( void ) { return sv.num_edicts - sv.free_edicts; } virtual INetChannelInfo* GetPlayerNetInfo( int playerIndex ) { if ( playerIndex < 1 || playerIndex > sv.GetClientCount() ) return NULL; CGameClient *client = sv.Client( playerIndex - 1 ); return client->m_NetChannel; } virtual edict_t* CreateEdict( int iForceEdictIndex ) { edict_t *pedict = ED_Alloc( iForceEdictIndex ); if ( g_pServerPluginHandler ) { g_pServerPluginHandler->OnEdictAllocated( pedict ); } return pedict; } virtual void RemoveEdict(edict_t* ed) { if ( g_pServerPluginHandler ) { g_pServerPluginHandler->OnEdictFreed( ed ); } ED_Free(ed); } // // Request engine to allocate "cb" bytes on the entity's private data pointer. // virtual void *PvAllocEntPrivateData( long cb ) { return calloc( 1, cb ); } // // Release the private data memory, if any. // virtual void FreeEntPrivateData( void *pEntity ) { #if defined( _DEBUG ) && defined( WIN32 ) // set the memory to a known value int size = _msize( pEntity ); memset( pEntity, 0xDD, size ); #endif if ( pEntity ) { free( pEntity ); } } virtual void *SaveAllocMemory( size_t num, size_t size ) { #ifndef SWDS return ::SaveAllocMemory(num, size); #else return NULL; #endif } virtual void SaveFreeMemory( void *pSaveMem ) { #ifndef SWDS ::SaveFreeMemory(pSaveMem); #endif } /* ================= EmitAmbientSound ================= */ virtual void EmitAmbientSound( int entindex, const Vector& pos, const char *samp, float vol, soundlevel_t soundlevel, int fFlags, int pitch, float soundtime /*=0.0f*/ ) { SoundInfo_t sound; sound.SetDefault(); sound.nEntityIndex = entindex; sound.fVolume = vol; sound.Soundlevel = soundlevel; sound.nFlags = fFlags; sound.nPitch = pitch; sound.nChannel = CHAN_STATIC; sound.vOrigin = pos; sound.bIsAmbient = true; ASSERT_COORD( sound.vOrigin ); // set sound delay if ( soundtime != 0.0f ) { sound.fDelay = soundtime - sv.GetTime(); sound.nFlags |= SND_DELAY; } // if this is a sentence, get sentence number if ( TestSoundChar(samp, CHAR_SENTENCE) ) { sound.bIsSentence = true; sound.nSoundNum = Q_atoi( PSkipSoundChars(samp) ); if ( sound.nSoundNum >= VOX_SentenceCount() ) { ConMsg("EmitAmbientSound: invalid sentence number: %s", PSkipSoundChars(samp)); return; } } else { // check to see if samp was properly precached sound.bIsSentence = false; sound.nSoundNum = SV_SoundIndex( samp ); if (sound.nSoundNum <= 0) { ConMsg ("EmitAmbientSound: sound not precached: %s\n", samp); return; } } if ( (fFlags & SND_SPAWNING) && sv.allowsignonwrites ) { SVC_Sounds sndmsg; char buffer[32]; sndmsg.m_DataOut.StartWriting(buffer, sizeof(buffer) ); sndmsg.m_nNumSounds = 1; sndmsg.m_bReliableSound = true; SoundInfo_t defaultSound; defaultSound.SetDefault(); sound.WriteDelta( &defaultSound, sndmsg.m_DataOut ); // write into signon buffer if ( !sndmsg.WriteToBuffer( sv.m_Signon ) ) { Sys_Error( "EmitAmbientSound: Init message would overflow signon buffer!\n" ); return; } } else { if ( fFlags & SND_SPAWNING ) { DevMsg("EmitAmbientSound: warning, broadcasting sound labled as SND_SPAWNING.\n" ); } // send sound to all active players CEngineRecipientFilter filter; filter.AddAllPlayers(); filter.MakeReliable(); sv.BroadcastSound( sound, filter ); } } virtual void FadeClientVolume(const edict_t *clientent, float fadePercent, float fadeOutSeconds, float holdTime, float fadeInSeconds) { int entnum = NUM_FOR_EDICT(clientent); if (entnum < 1 || entnum > sv.GetClientCount() ) { ConMsg ("tried to DLL_FadeClientVolume a non-client\n"); return; } IClient *client = sv.Client(entnum-1); NET_StringCmd sndMsg( va("soundfade %.1f %.1f %.1f %.1f", fadePercent, holdTime, fadeOutSeconds, fadeInSeconds ) ); client->SendNetMsg( sndMsg ); } //----------------------------------------------------------------------------- // // Sentence API // //----------------------------------------------------------------------------- virtual int SentenceGroupPick( int groupIndex, char *name, int nameLen ) { if ( !name ) { Sys_Error( "SentenceGroupPick with NULL name\n" ); } Assert( nameLen > 0 ); return VOX_GroupPick( groupIndex, name, nameLen ); } virtual int SentenceGroupPickSequential( int groupIndex, char *name, int nameLen, int sentenceIndex, int reset ) { if ( !name ) { Sys_Error( "SentenceGroupPickSequential with NULL name\n" ); } Assert( nameLen > 0 ); return VOX_GroupPickSequential( groupIndex, name, nameLen, sentenceIndex, reset ); } virtual int SentenceIndexFromName( const char *pSentenceName ) { if ( !pSentenceName ) { Sys_Error( "SentenceIndexFromName with NULL pSentenceName\n" ); } int sentenceIndex = -1; VOX_LookupString( pSentenceName, &sentenceIndex ); return sentenceIndex; } virtual const char *SentenceNameFromIndex( int sentenceIndex ) { return VOX_SentenceNameFromIndex( sentenceIndex ); } virtual int SentenceGroupIndexFromName( const char *pGroupName ) { if ( !pGroupName ) { Sys_Error( "SentenceGroupIndexFromName with NULL pGroupName\n" ); } return VOX_GroupIndexFromName( pGroupName ); } virtual const char *SentenceGroupNameFromIndex( int groupIndex ) { return VOX_GroupNameFromIndex( groupIndex ); } virtual float SentenceLength( int sentenceIndex ) { return VOX_SentenceLength( sentenceIndex ); } //----------------------------------------------------------------------------- virtual int CheckHeadnodeVisible( int nodenum, const byte *visbits, int vissize ) { return CM_HeadnodeVisible(nodenum, visbits, vissize ); } /* ================= ServerCommand Sends text to servers execution buffer localcmd (string) ================= */ virtual void ServerCommand( const char *str ) { if ( !str ) { Sys_Error( "ServerCommand with NULL string\n" ); } if ( ValidCmd( str ) ) { Cbuf_AddText( str ); } else { ConMsg( "Error, bad server command %s\n", str ); } } /* ================= ServerExecute Executes all commands in server buffer localcmd (string) ================= */ virtual void ServerExecute( void ) { Cbuf_Execute(); } /* ================= ClientCommand Sends text over to the client's execution buffer stuffcmd (clientent, value) ================= */ virtual void ClientCommand(edict_t* pEdict, const char* szFmt, ...) { va_list argptr; static char szOut[1024]; va_start(argptr, szFmt); Q_vsnprintf(szOut, sizeof( szOut ), szFmt, argptr); va_end(argptr); if ( szOut[0] == 0 ) { Warning( "ClientCommand, 0 length string supplied.\n" ); return; } int entnum = NUM_FOR_EDICT( pEdict ); if ( ( entnum < 1 ) || ( entnum > sv.GetClientCount() ) ) { ConMsg("\n!!!\n\nStuffCmd: Some entity tried to stuff '%s' to console buffer of entity %i when maxclients was set to %i, ignoring\n\n", szOut, entnum, sv.GetMaxClients() ); return; } NET_StringCmd string( szOut ); sv.GetClient(entnum-1)->SendNetMsg( string ); } // Send a client command keyvalues // keyvalues are deleted inside the function virtual void ClientCommandKeyValues( edict_t *pEdict, KeyValues *pCommand ) { if ( !pCommand ) return; int entnum = NUM_FOR_EDICT( pEdict ); if ( ( entnum < 1 ) || ( entnum > sv.GetClientCount() ) ) { ConMsg("\n!!!\n\nClientCommandKeyValues: Some entity tried to stuff '%s' to console buffer of entity %i when maxclients was set to %i, ignoring\n\n", pCommand->GetName(), entnum, sv.GetMaxClients() ); return; } SVC_CmdKeyValues cmd( pCommand ); sv.GetClient(entnum-1)->SendNetMsg( cmd ); } /* =============== LightStyle void(float style, string value) lightstyle =============== */ virtual void LightStyle(int style, const char* val) { if ( !val ) { Sys_Error( "LightStyle with NULL value!\n" ); } // change the string in string table INetworkStringTable *stringTable = sv.GetLightStyleTable(); stringTable->SetStringUserData( style, Q_strlen(val)+1, val ); } virtual void StaticDecal( const Vector& origin, int decalIndex, int entityIndex, int modelIndex, bool lowpriority ) { SVC_BSPDecal decal; decal.m_Pos = origin; decal.m_nDecalTextureIndex = decalIndex; decal.m_nEntityIndex = entityIndex; decal.m_nModelIndex = modelIndex; decal.m_bLowPriority = lowpriority; if ( sv.allowsignonwrites ) { decal.WriteToBuffer( sv.m_Signon ); } else { sv.BroadcastMessage( decal, false, true ); } } void Message_DetermineMulticastRecipients( bool usepas, const Vector& origin, CBitVec< ABSOLUTE_PLAYER_LIMIT >& playerbits ) { SV_DetermineMulticastRecipients( usepas, origin, playerbits ); } /* =============================================================================== MESSAGE WRITING =============================================================================== */ virtual bf_write *EntityMessageBegin( int ent_index, ServerClass * ent_class, bool reliable ) { if ( s_MsgData.started ) { Sys_Error( "EntityMessageBegin: New message started before matching call to EndMessage.\n " ); return NULL; } s_MsgData.Reset(); Assert( ent_class ); s_MsgData.filter = NULL; s_MsgData.reliable = reliable; s_MsgData.started = true; s_MsgData.currentMsg = &s_MsgData.entityMsg; s_MsgData.entityMsg.m_nEntityIndex = ent_index; s_MsgData.entityMsg.m_nClassID = ent_class->m_ClassID; s_MsgData.entityMsg.m_DataOut.Reset(); return &s_MsgData.entityMsg.m_DataOut; } virtual bf_write *UserMessageBegin( IRecipientFilter *filter, int msg_index ) { if ( s_MsgData.started ) { Sys_Error( "UserMessageBegin: New message started before matching call to EndMessage.\n " ); return NULL; } s_MsgData.Reset(); Assert( filter ); s_MsgData.filter = filter; s_MsgData.reliable = filter->IsReliable(); s_MsgData.started = true; s_MsgData.currentMsg = &s_MsgData.userMsg; s_MsgData.userMsg.m_nMsgType = msg_index; s_MsgData.userMsg.m_DataOut.Reset(); return &s_MsgData.userMsg.m_DataOut; } // Validates user message type and checks to see if it's variable length // returns true if variable length int Message_CheckMessageLength() { if ( s_MsgData.currentMsg == &s_MsgData.userMsg ) { char msgname[ 256 ]; int msgsize = -1; int msgtype = s_MsgData.userMsg.m_nMsgType; if ( !serverGameDLL->GetUserMessageInfo( msgtype, msgname, sizeof(msgname), msgsize ) ) { Warning( "Unable to find user message for index %i\n", msgtype ); return -1; } int bytesWritten = s_MsgData.userMsg.m_DataOut.GetNumBytesWritten(); if ( msgsize == -1 ) { if ( bytesWritten > MAX_USER_MSG_DATA ) { Warning( "DLL_MessageEnd: Refusing to send user message %s of %i bytes to client, user message size limit is %i bytes\n", msgname, bytesWritten, MAX_USER_MSG_DATA ); return -1; } } else if ( msgsize != bytesWritten ) { Warning( "User Msg '%s': %d bytes written, expected %d\n", msgname, bytesWritten, msgsize ); return -1; } return bytesWritten; // all checks passed, estimated final length } if ( s_MsgData.currentMsg == &s_MsgData.entityMsg ) { int bytesWritten = s_MsgData.entityMsg.m_DataOut.GetNumBytesWritten(); if ( bytesWritten > MAX_ENTITY_MSG_DATA ) // TODO use a define or so { Warning( "Entity Message to %i, %i bytes written (max is %d)\n", s_MsgData.entityMsg.m_nEntityIndex, bytesWritten, MAX_ENTITY_MSG_DATA ); return -1; } return bytesWritten; // all checks passed, estimated final length } Warning( "MessageEnd unknown message type.\n" ); return -1; } virtual void MessageEnd( void ) { if ( !s_MsgData.started ) { Sys_Error( "MESSAGE_END called with no active message\n" ); return; } int length = Message_CheckMessageLength(); // check to see if it's a valid message if ( length < 0 ) { s_MsgData.Reset(); // clear message data return; } if ( s_MsgData.filter ) { // send entity/user messages only to full connected clients in filter sv.BroadcastMessage( *s_MsgData.currentMsg, *s_MsgData.filter ); } else { // send entity messages to all full connected clients sv.BroadcastMessage( *s_MsgData.currentMsg, true, s_MsgData.reliable ); } s_MsgData.Reset(); // clear message data } /* single print to a specific client */ virtual void ClientPrintf( edict_t *pEdict, const char *szMsg ) { int entnum = NUM_FOR_EDICT( pEdict ); if (entnum < 1 || entnum > sv.GetClientCount() ) { ConMsg ("tried to sprint to a non-client\n"); return; } sv.Client(entnum-1)->ClientPrintf( "%s", szMsg ); } #ifdef SWDS void Con_NPrintf( int pos, const char *fmt, ... ) { } void Con_NXPrintf( const struct con_nprint_s *info, const char *fmt, ... ) { } #else void Con_NPrintf( int pos, const char *fmt, ... ) { if ( IsDedicatedServer() ) return; va_list argptr; char text[4096]; va_start (argptr, fmt); Q_vsnprintf(text, sizeof( text ), fmt, argptr); va_end (argptr); ::Con_NPrintf( pos, "%s", text ); } void Con_NXPrintf( const struct con_nprint_s *info, const char *fmt, ... ) { if ( IsDedicatedServer() ) return; va_list argptr; char text[4096]; va_start (argptr, fmt); Q_vsnprintf(text, sizeof( text ), fmt, argptr); va_end (argptr); ::Con_NXPrintf( info, "%s", text ); } #endif virtual void SetView(const edict_t *clientent, const edict_t *viewent) { int clientnum = NUM_FOR_EDICT( clientent ); if (clientnum < 1 || clientnum > sv.GetClientCount() ) Host_Error ("DLL_SetView: not a client"); CGameClient *client = sv.Client(clientnum-1); client->m_pViewEntity = viewent; SVC_SetView view( NUM_FOR_EDICT(viewent) ); client->SendNetMsg( view ); } virtual float Time(void) { return Sys_FloatTime(); } virtual void CrosshairAngle(const edict_t *clientent, float pitch, float yaw) { int clientnum = NUM_FOR_EDICT( clientent ); if (clientnum < 1 || clientnum > sv.GetClientCount() ) Host_Error ("DLL_Crosshairangle: not a client"); IClient *client = sv.Client(clientnum-1); if (pitch > 180) pitch -= 360; if (pitch < -180) pitch += 360; if (yaw > 180) yaw -= 360; if (yaw < -180) yaw += 360; SVC_CrosshairAngle crossHairMsg; crossHairMsg.m_Angle.x = pitch; crossHairMsg.m_Angle.y = yaw; crossHairMsg.m_Angle.y = 0; client->SendNetMsg( crossHairMsg ); } virtual void GetGameDir( char *szGetGameDir, int maxlength ) { COM_GetGameDir(szGetGameDir, maxlength ); } virtual int CompareFileTime( const char *filename1, const char *filename2, int *iCompare) { return COM_CompareFileTime(filename1, filename2, iCompare); } virtual bool LockNetworkStringTables( bool lock ) { return networkStringTableContainerServer->Lock( lock ); } // For use with FAKE CLIENTS virtual edict_t* CreateFakeClient( const char *netname ) { CGameClient *fcl = static_cast<CGameClient*>( sv.CreateFakeClient( netname ) ); if ( !fcl ) { // server is full return NULL; } return fcl->edict; } // For use with FAKE CLIENTS virtual edict_t* CreateFakeClientEx( const char *netname, bool bReportFakeClient /*= true*/ ) { sv.SetReportNewFakeClients( bReportFakeClient ); edict_t *ret = CreateFakeClient( netname ); sv.SetReportNewFakeClients( true ); // Leave this set as true so other callers of sv.CreateFakeClient behave correctly. return ret; } // Get a keyvalue for s specified client virtual const char *GetClientConVarValue( int clientIndex, const char *name ) { if ( clientIndex < 1 || clientIndex > sv.GetClientCount() ) { DevMsg( 1, "GetClientConVarValue: player invalid index %i\n", clientIndex ); return ""; } return sv.GetClient( clientIndex - 1 )->GetUserSetting( name ); } virtual const char *ParseFile(const char *data, char *token, int maxlen) { return ::COM_ParseFile(data, token, maxlen ); } virtual bool CopyFile( const char *source, const char *destination ) { return ::COM_CopyFile( source, destination ); } virtual void AddOriginToPVS( const Vector& origin ) { ::SV_AddOriginToPVS(origin); } virtual void ResetPVS( byte* pvs, int pvssize ) { ::SV_ResetPVS( pvs, pvssize ); } virtual void SetAreaPortalState( int portalNumber, int isOpen ) { CM_SetAreaPortalState(portalNumber, isOpen); } virtual void SetAreaPortalStates( const int *portalNumbers, const int *isOpen, int nPortals ) { CM_SetAreaPortalStates( portalNumbers, isOpen, nPortals ); } virtual void DrawMapToScratchPad( IScratchPad3D *pPad, unsigned long iFlags ) { worldbrushdata_t *pData = host_state.worldmodel->brush.pShared; if ( !pData ) return; SurfaceHandle_t surfID = SurfaceHandleFromIndex( host_state.worldmodel->brush.firstmodelsurface, pData ); for (int i=0; i< host_state.worldmodel->brush.nummodelsurfaces; ++i, ++surfID) { // Don't bother with nodraw surfaces if( MSurf_Flags( surfID ) & SURFDRAW_NODRAW ) continue; CSPVertList vertList; for ( int iVert=0; iVert < MSurf_VertCount( surfID ); iVert++ ) { int iWorldVert = pData->vertindices[surfID->firstvertindex + iVert]; const Vector &vPos = pData->vertexes[iWorldVert].position; vertList.m_Verts.AddToTail( CSPVert( vPos ) ); } pPad->DrawPolygon( vertList ); } } const CBitVec<MAX_EDICTS>* GetEntityTransmitBitsForClient( int iClientIndex ) { if ( iClientIndex < 0 || iClientIndex >= sv.GetClientCount() ) { Assert( false ); return NULL; } CGameClient *pClient = sv.Client( iClientIndex ); CClientFrame *deltaFrame = pClient->GetClientFrame( pClient->m_nDeltaTick ); if ( !deltaFrame ) return NULL; return &deltaFrame->transmit_entity; } virtual bool IsPaused() { return sv.IsPaused(); } virtual void SetFakeClientConVarValue( edict_t *pEntity, const char *pCvarName, const char *value ) { int clientnum = NUM_FOR_EDICT( pEntity ); if (clientnum < 1 || clientnum > sv.GetClientCount() ) Host_Error ("DLL_SetView: not a client"); CGameClient *client = sv.Client(clientnum-1); if ( client->IsFakeClient() ) { client->SetUserCVar( pCvarName, value ); client->m_bConVarsChanged = true; } } virtual CSharedEdictChangeInfo* GetSharedEdictChangeInfo() { return &g_SharedEdictChangeInfo; } virtual IChangeInfoAccessor *GetChangeAccessor( const edict_t *pEdict ) { return &sv.edictchangeinfo[ NUM_FOR_EDICT( pEdict ) ]; } virtual QueryCvarCookie_t StartQueryCvarValue( edict_t *pPlayerEntity, const char *pCvarName ) { int clientnum = NUM_FOR_EDICT( pPlayerEntity ); if (clientnum < 1 || clientnum > sv.GetClientCount() ) Host_Error( "StartQueryCvarValue: not a client" ); CGameClient *client = sv.Client( clientnum-1 ); return SendCvarValueQueryToClient( client, pCvarName, false ); } // Name of most recently load .sav file virtual char const *GetMostRecentlyLoadedFileName() { #if !defined( SWDS ) return saverestore->GetMostRecentlyLoadedFileName(); #else return ""; #endif } virtual char const *GetSaveFileName() { #if !defined( SWDS ) return saverestore->GetSaveFileName(); #else return ""; #endif } // Tells the engine we can immdiately re-use all edict indices // even though we may not have waited enough time virtual void AllowImmediateEdictReuse( ) { ED_AllowImmediateReuse(); } virtual void MultiplayerEndGame() { #if !defined( SWDS ) g_pMatchmaking->EndGame(); #endif } virtual void ChangeTeam( const char *pTeamName ) { #if !defined( SWDS ) g_pMatchmaking->ChangeTeam( pTeamName ); #endif } virtual void SetAchievementMgr( IAchievementMgr *pAchievementMgr ) { g_pAchievementMgr = pAchievementMgr; } virtual IAchievementMgr *GetAchievementMgr() { return g_pAchievementMgr; } virtual int GetAppID() { return GetSteamAppID(); } virtual bool IsLowViolence(); /* ================= InsertServerCommand Sends text to servers execution buffer localcmd (string) ================= */ virtual void InsertServerCommand( const char *str ) { if ( !str ) { Sys_Error( "InsertServerCommand with NULL string\n" ); } if ( ValidCmd( str ) ) { Cbuf_InsertText( str ); } else { ConMsg( "Error, bad server command %s (InsertServerCommand)\n", str ); } } bool GetPlayerInfo( int ent_num, player_info_t *pinfo ) { // Entity numbers are offset by 1 from the player numbers return sv.GetPlayerInfo( (ent_num-1), pinfo ); } bool IsClientFullyAuthenticated( edict_t *pEdict ) { int entnum = NUM_FOR_EDICT( pEdict ); if (entnum < 1 || entnum > sv.GetClientCount() ) return false; // Entity numbers are offset by 1 from the player numbers CGameClient *client = sv.Client(entnum-1); if ( client ) return client->IsFullyAuthenticated(); return false; } void SetDedicatedServerBenchmarkMode( bool bBenchmarkMode ) { g_bDedicatedServerBenchmarkMode = bBenchmarkMode; if ( bBenchmarkMode ) { extern ConVar sv_stressbots; sv_stressbots.SetValue( (int)1 ); } } // Returns the SteamID of the game server const CSteamID *GetGameServerSteamID() { if ( !Steam3Server().GetGSSteamID().IsValid() ) return NULL; return &Steam3Server().GetGSSteamID(); } // Returns the SteamID of the specified player. It'll be NULL if the player hasn't authenticated yet. const CSteamID *GetClientSteamID( edict_t *pPlayerEdict ) { int entnum = NUM_FOR_EDICT( pPlayerEdict ); return GetClientSteamIDByPlayerIndex( entnum ); } const CSteamID *GetClientSteamIDByPlayerIndex( int entnum ) { if (entnum < 1 || entnum > sv.GetClientCount() ) return NULL; // Entity numbers are offset by 1 from the player numbers CGameClient *client = sv.Client(entnum-1); if ( !client ) return NULL; // Make sure they are connected and Steam ID is valid if ( !client->IsConnected() || !client->m_SteamID.IsValid() ) return NULL; return &client->m_SteamID; } void SetGamestatsData( CGamestatsData *pGamestatsData ) { g_pGamestatsData = pGamestatsData; } CGamestatsData *GetGamestatsData() { return g_pGamestatsData; } virtual IReplaySystem *GetReplay() { return g_pReplay; } virtual int GetClusterCount() { CCollisionBSPData *pBSPData = GetCollisionBSPData(); if ( pBSPData && pBSPData->map_vis ) return pBSPData->map_vis->numclusters; return 0; } virtual int GetAllClusterBounds( bbox_t *pBBoxList, int maxBBox ) { CCollisionBSPData *pBSPData = GetCollisionBSPData(); if ( pBSPData && pBSPData->map_vis && host_state.worldbrush ) { // clamp to max clusters in the map if ( maxBBox > pBSPData->map_vis->numclusters ) { maxBBox = pBSPData->map_vis->numclusters; } // reset all of the bboxes for ( int i = 0; i < maxBBox; i++ ) { ClearBounds( pBBoxList[i].mins, pBBoxList[i].maxs ); } // add each leaf's bounds to the bounds for that cluster for ( int i = 0; i < host_state.worldbrush->numleafs; i++ ) { mleaf_t *pLeaf = &host_state.worldbrush->leafs[i]; // skip solid leaves and leaves with cluster < 0 if ( !(pLeaf->contents & CONTENTS_SOLID) && pLeaf->cluster >= 0 && pLeaf->cluster < maxBBox ) { Vector mins, maxs; mins = pLeaf->m_vecCenter - pLeaf->m_vecHalfDiagonal; maxs = pLeaf->m_vecCenter + pLeaf->m_vecHalfDiagonal; AddPointToBounds( mins, pBBoxList[pLeaf->cluster].mins, pBBoxList[pLeaf->cluster].maxs ); AddPointToBounds( maxs, pBBoxList[pLeaf->cluster].mins, pBBoxList[pLeaf->cluster].maxs ); } } return pBSPData->map_vis->numclusters; } return 0; } virtual int GetServerVersion() const OVERRIDE { return GetSteamInfIDVersionInfo().ServerVersion; } virtual float GetServerTime() const OVERRIDE { return sv.GetTime(); } virtual IServer *GetIServer() OVERRIDE { return (IServer *)&sv; } virtual void SetPausedForced( bool bPaused, float flDuration /*= -1.f*/ ) OVERRIDE { sv.SetPausedForced( bPaused, flDuration ); } private: // Purpose: Sends a temp entity to the client ( follows the format of the original MESSAGE_BEGIN stuff from HL1 virtual void PlaybackTempEntity( IRecipientFilter& filter, float delay, const void *pSender, const SendTable *pST, int classID ); virtual int CheckAreasConnected( int area1, int area2 ); virtual int GetArea( const Vector& origin ); virtual void GetAreaBits( int area, unsigned char *bits, int buflen ); virtual bool GetAreaPortalPlane( Vector const &vViewOrigin, int portalKey, VPlane *pPlane ); virtual client_textmessage_t *TextMessageGet( const char *pName ); virtual void LogPrint(const char * msg); virtual bool LoadGameState( char const *pMapName, bool createPlayers ); virtual void LoadAdjacentEnts( const char *pOldLevel, const char *pLandmarkName ); virtual void ClearSaveDir(); virtual void ClearSaveDirAfterClientLoad(); virtual const char* GetMapEntitiesString(); virtual void BuildEntityClusterList( edict_t *pEdict, PVSInfo_t *pPVSInfo ); virtual void CleanUpEntityClusterList( PVSInfo_t *pPVSInfo ); virtual void SolidMoved( edict_t *pSolidEnt, ICollideable *pSolidCollide, const Vector* pPrevAbsOrigin, bool accurateBboxTriggerChecks ); virtual void TriggerMoved( edict_t *pTriggerEnt, bool accurateBboxTriggerChecks ); virtual ISpatialPartition *CreateSpatialPartition( const Vector& worldmin, const Vector& worldmax ) { return ::CreateSpatialPartition( worldmin, worldmax ); } virtual void DestroySpatialPartition( ISpatialPartition *pPartition ) { ::DestroySpatialPartition( pPartition ); } }; // Backwards-compat shim that inherits newest then provides overrides for the legacy behavior class CVEngineServer22 : public CVEngineServer { virtual int IsMapValid( const char *filename ) OVERRIDE { // For users of the older interface, preserve here the old modelloader behavior of wrapping maps/%.bsp around // the filename. This went away in newer interfaces since maps can now live in other places. char szWrappedName[MAX_PATH] = { 0 }; V_snprintf( szWrappedName, sizeof( szWrappedName ), "maps/%s.bsp", filename ); return modelloader->Map_IsValid( szWrappedName ); } }; //----------------------------------------------------------------------------- // Expose CVEngineServer to the game DLL. //----------------------------------------------------------------------------- static CVEngineServer g_VEngineServer; static CVEngineServer22 g_VEngineServer22; // INTERFACEVERSION_VENGINESERVER_VERSION_21 is compatible with 22 latest since we only added virtuals to the end, so expose that as well. EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CVEngineServer, IVEngineServer021, INTERFACEVERSION_VENGINESERVER_VERSION_21, g_VEngineServer22 ); EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CVEngineServer, IVEngineServer022, INTERFACEVERSION_VENGINESERVER_VERSION_22, g_VEngineServer22 ); EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CVEngineServer, IVEngineServer, INTERFACEVERSION_VENGINESERVER, g_VEngineServer ); // When bumping the version to this interface, check that our assumption is still valid and expose the older version in the same way COMPILE_TIME_ASSERT( INTERFACEVERSION_VENGINESERVER_INT == 23 ); //----------------------------------------------------------------------------- // Expose CVEngineServer to the engine. //----------------------------------------------------------------------------- IVEngineServer *g_pVEngineServer = &g_VEngineServer; //----------------------------------------------------------------------------- // Used to allocate pvs infos //----------------------------------------------------------------------------- static CUtlMemoryPool s_PVSInfoAllocator( 128, 128 * 64, CUtlMemoryPool::GROW_SLOW, "pvsinfopool", 128 ); //----------------------------------------------------------------------------- // Purpose: Sends a temp entity to the client ( follows the format of the original MESSAGE_BEGIN stuff from HL1 // Input : msg_dest - // delay - // *origin - // *recipient - // *pSender - // *pST - // classID - //----------------------------------------------------------------------------- void CVEngineServer::PlaybackTempEntity( IRecipientFilter& filter, float delay, const void *pSender, const SendTable *pST, int classID ) { VPROF( "PlaybackTempEntity" ); // don't add more events to a snapshot than a client can receive if ( sv.m_TempEntities.Count() >= ((1<<CEventInfo::EVENT_INDEX_BITS)-1) ) { // remove oldest effect delete sv.m_TempEntities[0]; sv.m_TempEntities.Remove( 0 ); } // Make this start at 1 classID = classID + 1; // Encode now! ALIGN4 unsigned char data[ CEventInfo::MAX_EVENT_DATA ] ALIGN4_POST; bf_write buffer( "PlaybackTempEntity", data, sizeof(data) ); // write all properties, if init or reliable message delta against zero values if( !SendTable_Encode( pST, pSender, &buffer, classID, NULL, false ) ) { Host_Error( "PlaybackTempEntity: SendTable_Encode returned false (ent %d), overflow? %i\n", classID, buffer.IsOverflowed() ? 1 : 0 ); return; } // create CEventInfo: CEventInfo *newEvent = new CEventInfo; //copy client filter newEvent->filter.AddPlayersFromFilter( &filter ); newEvent->classID = classID; newEvent->pSendTable= pST; newEvent->fire_delay= delay; newEvent->bits = buffer.GetNumBitsWritten(); int size = Bits2Bytes( buffer.GetNumBitsWritten() ); newEvent->pData = new byte[size]; Q_memcpy( newEvent->pData, data, size ); // add to list sv.m_TempEntities[sv.m_TempEntities.AddToTail()] = newEvent; } int CVEngineServer::CheckAreasConnected( int area1, int area2 ) { return CM_AreasConnected(area1, area2); } //----------------------------------------------------------------------------- // Purpose: // Input : *origin - // *bits - // Output : void //----------------------------------------------------------------------------- int CVEngineServer::GetArea( const Vector& origin ) { return CM_LeafArea( CM_PointLeafnum( origin ) ); } void CVEngineServer::GetAreaBits( int area, unsigned char *bits, int buflen ) { CM_WriteAreaBits( bits, buflen, area ); } bool CVEngineServer::GetAreaPortalPlane( Vector const &vViewOrigin, int portalKey, VPlane *pPlane ) { return CM_GetAreaPortalPlane( vViewOrigin, portalKey, pPlane ); } client_textmessage_t *CVEngineServer::TextMessageGet( const char *pName ) { return ::TextMessageGet( pName ); } void CVEngineServer::LogPrint(const char * msg) { g_Log.Print( msg ); } // HACKHACK: Save/restore wrapper - Move this to a different interface bool CVEngineServer::LoadGameState( char const *pMapName, bool createPlayers ) { #ifndef SWDS return saverestore->LoadGameState( pMapName, createPlayers ) != 0; #else return 0; #endif } void CVEngineServer::LoadAdjacentEnts( const char *pOldLevel, const char *pLandmarkName ) { #ifndef SWDS saverestore->LoadAdjacentEnts( pOldLevel, pLandmarkName ); #endif } void CVEngineServer::ClearSaveDir() { #ifndef SWDS saverestore->ClearSaveDir(); #endif } void CVEngineServer::ClearSaveDirAfterClientLoad() { #ifndef SWDS saverestore->RequestClearSaveDir(); #endif } const char* CVEngineServer::GetMapEntitiesString() { return CM_EntityString(); } //----------------------------------------------------------------------------- // Builds PVS information for an entity //----------------------------------------------------------------------------- inline bool SortClusterLessFunc( const int &left, const int &right ) { return left < right; } void CVEngineServer::BuildEntityClusterList( edict_t *pEdict, PVSInfo_t *pPVSInfo ) { int i, j; int topnode; int leafCount; int leafs[MAX_TOTAL_ENT_LEAFS], clusters[MAX_TOTAL_ENT_LEAFS]; int area; CleanUpEntityClusterList( pPVSInfo ); pPVSInfo->m_pClusters = 0; pPVSInfo->m_nClusterCount = 0; pPVSInfo->m_nAreaNum = 0; pPVSInfo->m_nAreaNum2 = 0; if ( !pEdict ) return; ICollideable *pCollideable = pEdict->GetCollideable(); Assert( pCollideable ); if ( !pCollideable ) return; topnode = -1; //get all leafs, including solids Vector vecWorldMins, vecWorldMaxs; pCollideable->WorldSpaceSurroundingBounds( &vecWorldMins, &vecWorldMaxs ); leafCount = CM_BoxLeafnums( vecWorldMins, vecWorldMaxs, leafs, MAX_TOTAL_ENT_LEAFS, &topnode ); // set areas for ( i = 0; i < leafCount; i++ ) { clusters[i] = CM_LeafCluster( leafs[i] ); area = CM_LeafArea( leafs[i] ); if ( area == 0 ) continue; // doors may legally straggle two areas, // but nothing should ever need more than that if ( pPVSInfo->m_nAreaNum && pPVSInfo->m_nAreaNum != area ) { if ( pPVSInfo->m_nAreaNum2 && pPVSInfo->m_nAreaNum2 != area && sv.IsLoading() ) { ConDMsg ("Object touching 3 areas at %f %f %f\n", vecWorldMins[0], vecWorldMins[1], vecWorldMins[2]); } pPVSInfo->m_nAreaNum2 = area; } else { pPVSInfo->m_nAreaNum = area; } } Vector center = (vecWorldMins+vecWorldMaxs) * 0.5f; // calc center pPVSInfo->m_nHeadNode = topnode; // save headnode // save origin pPVSInfo->m_vCenter[0] = center[0]; pPVSInfo->m_vCenter[1] = center[1]; pPVSInfo->m_vCenter[2] = center[2]; if ( leafCount >= MAX_TOTAL_ENT_LEAFS ) { // assume we missed some leafs, and mark by headnode pPVSInfo->m_nClusterCount = -1; return; } pPVSInfo->m_pClusters = pPVSInfo->m_pClustersInline; if ( leafCount >= 16 ) { std::make_heap( clusters, clusters + leafCount, SortClusterLessFunc ); std::sort_heap( clusters, clusters + leafCount, SortClusterLessFunc ); for ( i = 0; i < leafCount; i++ ) { if ( clusters[i] == -1 ) continue; // not a visible leaf if ( ( i > 0 ) && ( clusters[i] == clusters[i-1] ) ) continue; if ( pPVSInfo->m_nClusterCount == MAX_FAST_ENT_CLUSTERS ) { unsigned short *pClusters = (unsigned short *)s_PVSInfoAllocator.Alloc(); memcpy( pClusters, pPVSInfo->m_pClusters, MAX_FAST_ENT_CLUSTERS * sizeof(unsigned short) ); pPVSInfo->m_pClusters = pClusters; } else if ( pPVSInfo->m_nClusterCount == MAX_ENT_CLUSTERS ) { // assume we missed some leafs, and mark by headnode s_PVSInfoAllocator.Free( pPVSInfo->m_pClusters ); pPVSInfo->m_pClusters = 0; pPVSInfo->m_nClusterCount = -1; break; } pPVSInfo->m_pClusters[pPVSInfo->m_nClusterCount++] = (short)clusters[i]; } return; } for ( i = 0; i < leafCount; i++ ) { if ( clusters[i] == -1 ) continue; // not a visible leaf for ( j = 0; j < i; j++ ) { if ( clusters[j] == clusters[i] ) break; } if ( j != i ) continue; if ( pPVSInfo->m_nClusterCount == MAX_FAST_ENT_CLUSTERS ) { unsigned short *pClusters = (unsigned short*)s_PVSInfoAllocator.Alloc(); memcpy( pClusters, pPVSInfo->m_pClusters, MAX_FAST_ENT_CLUSTERS * sizeof(unsigned short) ); pPVSInfo->m_pClusters = pClusters; } else if ( pPVSInfo->m_nClusterCount == MAX_ENT_CLUSTERS ) { // assume we missed some leafs, and mark by headnode s_PVSInfoAllocator.Free( pPVSInfo->m_pClusters ); pPVSInfo->m_pClusters = 0; pPVSInfo->m_nClusterCount = -1; break; } pPVSInfo->m_pClusters[pPVSInfo->m_nClusterCount++] = (short)clusters[i]; } } //----------------------------------------------------------------------------- // Cleans up the cluster list //----------------------------------------------------------------------------- void CVEngineServer::CleanUpEntityClusterList( PVSInfo_t *pPVSInfo ) { if ( pPVSInfo->m_nClusterCount > MAX_FAST_ENT_CLUSTERS ) { s_PVSInfoAllocator.Free( pPVSInfo->m_pClusters ); pPVSInfo->m_pClusters = 0; pPVSInfo->m_nClusterCount = 0; } } //----------------------------------------------------------------------------- // Adds a handle to the list of entities to update when a partition query occurs //----------------------------------------------------------------------------- void CVEngineServer::SolidMoved( edict_t *pSolidEnt, ICollideable *pSolidCollide, const Vector* pPrevAbsOrigin, bool accurateBboxTriggerChecks ) { SV_SolidMoved( pSolidEnt, pSolidCollide, pPrevAbsOrigin, accurateBboxTriggerChecks ); } void CVEngineServer::TriggerMoved( edict_t *pTriggerEnt, bool accurateBboxTriggerChecks ) { SV_TriggerMoved( pTriggerEnt, accurateBboxTriggerChecks ); } //----------------------------------------------------------------------------- // Called by the server to determine violence settings. //----------------------------------------------------------------------------- bool CVEngineServer::IsLowViolence() { return g_bLowViolence; }
26.071768
159
0.652338
IamIndeedGamingAsHardAsICan03489
c10c7a43c480235d208526c1abf035cec9f8a363
62
cpp
C++
source/lib.cpp
vsdmars/sing
6c84c4c92c446b119291d205a50df450ae994326
[ "Unlicense" ]
null
null
null
source/lib.cpp
vsdmars/sing
6c84c4c92c446b119291d205a50df450ae994326
[ "Unlicense" ]
null
null
null
source/lib.cpp
vsdmars/sing
6c84c4c92c446b119291d205a50df450ae994326
[ "Unlicense" ]
null
null
null
#include "lib.hpp" library::library() : name("sing") { }
8.857143
18
0.564516
vsdmars
c10d66994ef114033e8fe779172cf9ddc10c4bdc
566
hh
C++
src/proof-fwd.hh
ciaranm/certified-constraint-solver
986b0149341474f911977f3093b1224ada90f605
[ "MIT" ]
null
null
null
src/proof-fwd.hh
ciaranm/certified-constraint-solver
986b0149341474f911977f3093b1224ada90f605
[ "MIT" ]
null
null
null
src/proof-fwd.hh
ciaranm/certified-constraint-solver
986b0149341474f911977f3093b1224ada90f605
[ "MIT" ]
1
2019-08-21T03:29:11.000Z
2019-08-21T03:29:11.000Z
/* vim: set sw=4 sts=4 et foldmethod=syntax : */ #ifndef CERTIFIED_CONSTRAINT_SOLVER_GUARD_SRC_PROOF_FWD_HH #define CERTIFIED_CONSTRAINT_SOLVER_GUARD_SRC_PROOF_FWD_HH 1 #include "strong_typedef.hpp" #include <string> struct Proof; using UnderlyingVariableID = jss::strong_typedef<struct UnderlyingVariableIDTag, std::string, jss::strong_typedef_properties::streamable>; using ProofLineNumber = jss::strong_typedef<struct ProofLineNumberTag, int, jss::strong_typedef_properties::comparable, jss::strong_typedef_properties::streamable>; #endif
29.789474
93
0.803887
ciaranm
c10f3febab8b3be2d570fec9be19669791f9ceb8
7,311
cpp
C++
tests/Unit/IO/Observers/Test_ReductionObserver.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
tests/Unit/IO/Observers/Test_ReductionObserver.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
tests/Unit/IO/Observers/Test_ReductionObserver.cpp
marissawalker/spectre
afc8205e2f697de5e8e4f05e881499e05c9fd8a0
[ "MIT" ]
null
null
null
// Distributed under the MIT License. // See LICENSE.txt for details. #include "tests/Unit/TestingFramework.hpp" #include <cstddef> #include <functional> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> #include "DataStructures/Matrix.hpp" #include "Domain/ElementId.hpp" #include "Domain/ElementIndex.hpp" #include "IO/H5/AccessType.hpp" #include "IO/H5/Dat.hpp" #include "IO/H5/File.hpp" #include "IO/Observer/Actions.hpp" // IWYU pragma: keep #include "IO/Observer/ArrayComponentId.hpp" #include "IO/Observer/Initialize.hpp" // IWYU pragma: keep #include "IO/Observer/ObservationId.hpp" #include "IO/Observer/ObserverComponent.hpp" // IWYU pragma: keep #include "IO/Observer/ReductionActions.hpp" // IWYU pragma: keep #include "IO/Observer/Tags.hpp" // IWYU pragma: keep #include "IO/Observer/TypeOfObservation.hpp" #include "Parallel/ArrayIndex.hpp" #include "Parallel/Reduction.hpp" #include "Utilities/FileSystem.hpp" #include "Utilities/Functional.hpp" #include "Utilities/Numeric.hpp" #include "Utilities/TaggedTuple.hpp" #include "tests/Unit/ActionTesting.hpp" #include "tests/Unit/IO/Observers/ObserverHelpers.hpp" // NOLINTNEXTLINE(google-build-using-namespace) using namespace TestObservers_detail; SPECTRE_TEST_CASE("Unit.IO.Observers.ReductionObserver", "[Unit][Observers]") { using TupleOfMockDistributedObjects = typename ActionTesting::MockRuntimeSystem< Metavariables>::TupleOfMockDistributedObjects; using obs_component = observer_component<Metavariables>; using obs_writer = observer_writer_component<Metavariables>; using element_comp = element_component<Metavariables>; using MockRuntimeSystem = ActionTesting::MockRuntimeSystem<Metavariables>; using ObserverMockDistributedObjectsTag = typename MockRuntimeSystem::template MockDistributedObjectsTag< obs_component>; using WriterMockDistributedObjectsTag = typename MockRuntimeSystem::template MockDistributedObjectsTag< obs_writer>; using ElementMockDistributedObjectsTag = typename MockRuntimeSystem::template MockDistributedObjectsTag< element_comp>; TupleOfMockDistributedObjects dist_objects{}; tuples::get<ObserverMockDistributedObjectsTag>(dist_objects) .emplace(0, ActionTesting::MockDistributedObject<obs_component>{}); tuples::get<WriterMockDistributedObjectsTag>(dist_objects) .emplace(0, ActionTesting::MockDistributedObject<obs_writer>{}); // Specific IDs have no significance, just need different IDs. const std::vector<ElementId<2>> element_ids{{1, {{{1, 0}, {1, 0}}}}, {1, {{{1, 1}, {1, 0}}}}, {1, {{{1, 0}, {2, 3}}}}, {1, {{{1, 0}, {5, 4}}}}, {0, {{{1, 0}, {1, 0}}}}}; for (const auto& id : element_ids) { tuples::get<ElementMockDistributedObjectsTag>(dist_objects) .emplace(ElementIndex<2>{id}, ActionTesting::MockDistributedObject<element_comp>{}); } tuples::TaggedTuple<observers::OptionTags::ReductionFileName, observers::OptionTags::VolumeFileName> cache_data{}; const auto& output_file_prefix = tuples::get<observers::OptionTags::ReductionFileName>(cache_data) = "./Unit.IO.Observers.ReductionObserver"; ActionTesting::MockRuntimeSystem<Metavariables> runner{ cache_data, std::move(dist_objects)}; runner.simple_action<obs_component, observers::Actions::Initialize<Metavariables>>(0); runner.simple_action<obs_writer, observers::Actions::InitializeWriter<Metavariables>>(0); // Register elements for (const auto& id : element_ids) { runner.simple_action<element_comp, observers::Actions::RegisterWithObservers< observers::TypeOfObservation::Reduction>>(id, 0); // Invoke the simple_action RegisterSenderWithSelf that was called on the // observer component by the RegisterWithObservers action. runner.invoke_queued_simple_action<obs_component>(0); } const std::string h5_file_name = output_file_prefix + ".h5"; if (file_system::check_if_file_exists(h5_file_name)) { file_system::rm(h5_file_name, true); } using Redum = Parallel::ReductionDatum<double, funcl::Plus<>, funcl::Sqrt<funcl::Divides<>>, std::index_sequence<1>>; using ReData = Parallel::ReductionData< Parallel::ReductionDatum<double, funcl::AssertEqual<>>, Parallel::ReductionDatum<size_t, funcl::Plus<>>, Redum, Redum>; const auto make_fake_reduction_data = []( const observers::ArrayComponentId& id, const double time) noexcept { const auto hashed_id = static_cast<double>(std::hash<observers::ArrayComponentId>{}(id)); constexpr size_t number_of_grid_points = 4; const double error0 = 1.0e-10 * hashed_id + time; const double error1 = 1.0e-12 * hashed_id + 2 * time; return ReData{time, number_of_grid_points, error0, error1}; }; const TimeId time(3); const std::vector<std::string> legend{"Time", "NumberOfPoints", "Error0", "Error1"}; // Test passing reduction data. for (const auto& id : element_ids) { const observers::ArrayComponentId array_id( std::add_pointer_t<element_comp>{nullptr}, Parallel::ArrayIndex<ElementIndex<2>>{ElementIndex<2>{id}}); auto reduction_data_fakes = make_fake_reduction_data(array_id, time.value()); runner.simple_action<obs_component, observers::Actions::ContributeReductionData>( 0, observers::ObservationId(time), legend, std::move(reduction_data_fakes)); } // Invke the threaded action 'WriteReductionData' to write reduction data to // disk. runner.invoke_queued_threaded_action<obs_writer>(0); // Check that the H5 file was written correctly. { const auto file = h5::H5File<h5::AccessType::ReadOnly>(h5_file_name); const auto& dat_file = file.get<h5::Dat>("/element_data"); const Matrix written_data = dat_file.get_data(); const auto& written_legend = dat_file.get_legend(); CHECK(written_legend == legend); const auto expected = alg::accumulate( element_ids, ReData(time.value(), 0, 0.0, 0.0), [&time, &make_fake_reduction_data ]( ReData state, const ElementId<2>& id) noexcept { const observers::ArrayComponentId array_id( std::add_pointer_t<element_comp>{nullptr}, Parallel::ArrayIndex<ElementIndex<2>>{ElementIndex<2>{id}}); return state.combine( make_fake_reduction_data(array_id, time.value())); }) .finalize() .data(); CHECK(std::get<0>(expected) == written_data(0, 0)); CHECK(std::get<1>(expected) == written_data(0, 1)); CHECK(std::get<2>(expected) == written_data(0, 2)); CHECK(std::get<3>(expected) == written_data(0, 3)); } if (file_system::check_if_file_exists(h5_file_name)) { file_system::rm(h5_file_name, true); } }
42.754386
79
0.669265
marissawalker
c10f5d63b52f31b478175dc4b2ca9d9766a6f40c
689
cpp
C++
Program's_Contributed_By_Contributors/C++_Programs/naive_pattern_searching.cpp
PrajaktaSathe/Hacktoberfest2k21
4f256b4010f96220ee02804a683f379bcd023b15
[ "MIT" ]
null
null
null
Program's_Contributed_By_Contributors/C++_Programs/naive_pattern_searching.cpp
PrajaktaSathe/Hacktoberfest2k21
4f256b4010f96220ee02804a683f379bcd023b15
[ "MIT" ]
null
null
null
Program's_Contributed_By_Contributors/C++_Programs/naive_pattern_searching.cpp
PrajaktaSathe/Hacktoberfest2k21
4f256b4010f96220ee02804a683f379bcd023b15
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void patternSearch(char* pattern, char* string) { int m = strlen(pattern); int n = strlen(string); for (int i = 0; i <= n - m; i++) { int j; for (j = 0; j < m; j++) if (string[i + j] != pattern[j]) break; if (j == m) //returning the index where "AN" occurs in "I AM SHUBHANGI. AN AVID READER WHO LIKES TO LISTEN TO MUSIC." cout << "'AN' occurs in 'I AM SHUBHANGI. AN AVID READER WHO LIKES TO LISTEN TO MUSIC.' at : " << i << endl; } } int main() { char string[] = "I AM SHUBHANGI. AN AVID READER WHO LIKES TO LISTEN TO MUSIC."; char pattern[] = "AN"; patternSearch(pattern, string); return 0; }
23.758621
113
0.597968
PrajaktaSathe
c11010af02593b88ba905329c825b2e7d2a93b6d
2,406
cpp
C++
src/welcome_scene.cpp
toivjon/sdl2-pong
edf08a56d54759ae5074d52a8e9a81b746c02561
[ "MIT" ]
null
null
null
src/welcome_scene.cpp
toivjon/sdl2-pong
edf08a56d54759ae5074d52a8e9a81b746c02561
[ "MIT" ]
null
null
null
src/welcome_scene.cpp
toivjon/sdl2-pong
edf08a56d54759ae5074d52a8e9a81b746c02561
[ "MIT" ]
null
null
null
#include "welcome_scene.h" #include "court_scene.h" #include "game.h" #include <SDL.h> using namespace pong; WelcomeScene::WelcomeScene(Game& game) : mGame(game), mTopicTexture(nullptr), mLeftPlayerInstructions(nullptr), mRightPlayerInstructions(nullptr), mContinueInstructions(nullptr) { mTopicTexture = mGame.createText("SDL2 PONG"); mLeftPlayerInstructions = mGame.createText("Controls for the left player: W and S"); mRightPlayerInstructions = mGame.createText("Controls for the right player: UP-ARROW and DOWN-ARROW"); mContinueInstructions = mGame.createText("Press [ENTER] to start the match"); } WelcomeScene::~WelcomeScene() { SDL_DestroyTexture(mTopicTexture); SDL_DestroyTexture(mLeftPlayerInstructions); SDL_DestroyTexture(mRightPlayerInstructions); SDL_DestroyTexture(mContinueInstructions); } void WelcomeScene::onDraw(SDL_Renderer& renderer) { // draw the topic of the game. SDL_Rect rect {0, 100, 0, 0}; SDL_QueryTexture(mTopicTexture, nullptr, nullptr, &rect.w, &rect.h); rect.x = (400 - (rect.w / 2)); SDL_RenderCopy(&renderer, mTopicTexture, nullptr, &rect); // draw the left player control instructions. SDL_QueryTexture(mLeftPlayerInstructions, nullptr, nullptr, &rect.w, &rect.h); rect.x = (400 - (rect.w / 2)); rect.y = 200; SDL_RenderCopy(&renderer, mLeftPlayerInstructions, nullptr, &rect); // draw the right player control instructions. SDL_QueryTexture(mRightPlayerInstructions, nullptr, nullptr, &rect.w, &rect.h); rect.x = (400 - (rect.w / 2)); rect.y = 250; SDL_RenderCopy(&renderer, mRightPlayerInstructions, nullptr, &rect); // draw the instructions how to continue to court scene. SDL_QueryTexture(mContinueInstructions, nullptr, nullptr, &rect.w, &rect.h); rect.x = (400 - (rect.w / 2)); rect.y = 400; SDL_RenderCopy(&renderer, mContinueInstructions, nullptr, &rect); } void WelcomeScene::onUpdate() { // ... } void WelcomeScene::onEnter() { // ... } void WelcomeScene::onExit() { // ... } void WelcomeScene::onKeyDown(SDL_KeyboardEvent& event) { // ... } void WelcomeScene::onKeyUp(SDL_KeyboardEvent& event) { // move player into the court scene to start the match. switch (event.keysym.sym) { case SDLK_RETURN: mGame.setScene(std::make_shared<CourtScene>(mGame)); break; } }
28.305882
105
0.694929
toivjon
c11212d3c2d37107460132461fe8ccafe5860c13
139
cpp
C++
engine/src/SimpleGame.cpp
irishpatrick/sdl-game
23ff8330fe2aaa765119df40d62e50570f606f07
[ "MIT-0", "MIT" ]
null
null
null
engine/src/SimpleGame.cpp
irishpatrick/sdl-game
23ff8330fe2aaa765119df40d62e50570f606f07
[ "MIT-0", "MIT" ]
null
null
null
engine/src/SimpleGame.cpp
irishpatrick/sdl-game
23ff8330fe2aaa765119df40d62e50570f606f07
[ "MIT-0", "MIT" ]
null
null
null
#include "SimpleGame.hpp" namespace engine { SimpleGame::SimpleGame() : Game() { } SimpleGame::~SimpleGame() { } }
9.266667
35
0.568345
irishpatrick
c112b01ba361511903c19175435682942f98407f
346,839
cc
C++
project4/mariadb/server/sql/sql_table.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
11
2017-10-28T08:41:08.000Z
2021-06-24T07:24:21.000Z
project4/mariadb/server/sql/sql_table.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
null
null
null
project4/mariadb/server/sql/sql_table.cc
jiunbae/ITE4065
3b9fcf9317e93ca7c829f1438b85f0f5ea2885db
[ "MIT" ]
4
2017-09-07T09:33:26.000Z
2021-02-19T07:45:08.000Z
/* Copyright (c) 2000, 2016, Oracle and/or its affiliates. Copyright (c) 2010, 2017, MariaDB Corporation. 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /* drop and alter of tables */ #include <my_global.h> #include "sql_priv.h" #include "unireg.h" #include "debug_sync.h" #include "sql_table.h" #include "sql_parse.h" // test_if_data_home_dir #include "sql_cache.h" // query_cache_* #include "sql_base.h" // lock_table_names #include "lock.h" // mysql_unlock_tables #include "strfunc.h" // find_type2, find_set #include "sql_truncate.h" // regenerate_locked_table #include "sql_partition.h" // mem_alloc_error, // generate_partition_syntax, // partition_info // NOT_A_PARTITION_ID #include "sql_db.h" // load_db_opt_by_name #include "sql_time.h" // make_truncated_value_warning #include "records.h" // init_read_record, end_read_record #include "filesort.h" // filesort_free_buffers #include "sql_select.h" // setup_order #include "sql_handler.h" // mysql_ha_rm_tables #include "discover.h" // readfrm #include "my_pthread.h" // pthread_mutex_t #include "log_event.h" // Query_log_event #include "sql_statistics.h" #include <hash.h> #include <myisam.h> #include <my_dir.h> #include "create_options.h" #include "sp_head.h" #include "sp.h" #include "sql_trigger.h" #include "sql_parse.h" #include "sql_show.h" #include "transaction.h" #include "sql_audit.h" #ifdef __WIN__ #include <io.h> #endif const char *primary_key_name="PRIMARY"; static bool check_if_keyname_exists(const char *name,KEY *start, KEY *end); static char *make_unique_key_name(THD *thd, const char *field_name, KEY *start, KEY *end); static void make_unique_constraint_name(THD *thd, LEX_STRING *name, List<Virtual_column_info> *vcol, uint *nr); static int copy_data_between_tables(THD *thd, TABLE *from,TABLE *to, List<Create_field> &create, bool ignore, uint order_num, ORDER *order, ha_rows *copied,ha_rows *deleted, Alter_info::enum_enable_or_disable keys_onoff, Alter_table_ctx *alter_ctx); static bool prepare_blob_field(THD *thd, Column_definition *sql_field); static int mysql_prepare_create_table(THD *, HA_CREATE_INFO *, Alter_info *, uint *, handler *, KEY **, uint *, int); static uint blob_length_by_type(enum_field_types type); /** @brief Helper function for explain_filename @param thd Thread handle @param to_p Explained name in system_charset_info @param end_p End of the to_p buffer @param name Name to be converted @param name_len Length of the name, in bytes */ static char* add_identifier(THD* thd, char *to_p, const char * end_p, const char* name, uint name_len) { uint res; uint errors; const char *conv_name, *conv_name_end; char tmp_name[FN_REFLEN]; char conv_string[FN_REFLEN]; int quote; DBUG_ENTER("add_identifier"); if (!name[name_len]) conv_name= name; else { strnmov(tmp_name, name, name_len); tmp_name[name_len]= 0; conv_name= tmp_name; } res= strconvert(&my_charset_filename, conv_name, name_len, system_charset_info, conv_string, FN_REFLEN, &errors); if (!res || errors) { DBUG_PRINT("error", ("strconvert of '%s' failed with %u (errors: %u)", conv_name, res, errors)); conv_name= name; conv_name_end= name + name_len; } else { DBUG_PRINT("info", ("conv '%s' -> '%s'", conv_name, conv_string)); conv_name= conv_string; conv_name_end= conv_string + res; } quote = thd ? get_quote_char_for_identifier(thd, conv_name, res - 1) : '`'; if (quote != EOF && (end_p - to_p > 2)) { *(to_p++)= (char) quote; while (*conv_name && (end_p - to_p - 1) > 0) { int length= my_charlen(system_charset_info, conv_name, conv_name_end); if (length <= 0) length= 1; if (length == 1 && *conv_name == (char) quote) { if ((end_p - to_p) < 3) break; *(to_p++)= (char) quote; *(to_p++)= *(conv_name++); } else if (((long) length) < (end_p - to_p)) { to_p= strnmov(to_p, conv_name, length); conv_name+= length; } else break; /* string already filled */ } if (end_p > to_p) { *(to_p++)= (char) quote; if (end_p > to_p) *to_p= 0; /* terminate by NUL, but do not include it in the count */ } } else to_p= strnmov(to_p, conv_name, end_p - to_p); DBUG_RETURN(to_p); } /** @brief Explain a path name by split it to database, table etc. @details Break down the path name to its logic parts (database, table, partition, subpartition). filename_to_tablename cannot be used on partitions, due to the #P# part. There can be up to 6 '#', #P# for partition, #SP# for subpartition and #TMP# or #REN# for temporary or renamed partitions. This should be used when something should be presented to a user in a diagnostic, error etc. when it would be useful to know what a particular file [and directory] means. Such as SHOW ENGINE STATUS, error messages etc. Examples: t1#P#p1 table t1 partition p1 t1#P#p1#SP#sp1 table t1 partition p1 subpartition sp1 t1#P#p1#SP#sp1#TMP# table t1 partition p1 subpartition sp1 temporary t1#P#p1#SP#sp1#REN# table t1 partition p1 subpartition sp1 renamed @param thd Thread handle @param from Path name in my_charset_filename Null terminated in my_charset_filename, normalized to use '/' as directory separation character. @param to Explained name in system_charset_info @param to_length Size of to buffer @param explain_mode Requested output format. EXPLAIN_ALL_VERBOSE -> [Database `db`, ]Table `tbl`[,[ Temporary| Renamed] Partition `p` [, Subpartition `sp`]] EXPLAIN_PARTITIONS_VERBOSE -> `db`.`tbl` [[ Temporary| Renamed] Partition `p` [, Subpartition `sp`]] EXPLAIN_PARTITIONS_AS_COMMENT -> `db`.`tbl` |* [,[ Temporary| Renamed] Partition `p` [, Subpartition `sp`]] *| (| is really a /, and it is all in one line) @retval Length of returned string */ uint explain_filename(THD* thd, const char *from, char *to, uint to_length, enum_explain_filename_mode explain_mode) { char *to_p= to; char *end_p= to_p + to_length; const char *db_name= NULL; int db_name_len= 0; const char *table_name; int table_name_len= 0; const char *part_name= NULL; int part_name_len= 0; const char *subpart_name= NULL; int subpart_name_len= 0; uint part_type= NORMAL_PART_NAME; const char *tmp_p; DBUG_ENTER("explain_filename"); DBUG_PRINT("enter", ("from '%s'", from)); tmp_p= from; table_name= from; /* If '/' then take last directory part as database. '/' is the directory separator, not FN_LIB_CHAR */ while ((tmp_p= strchr(tmp_p, '/'))) { db_name= table_name; /* calculate the length */ db_name_len= (int)(tmp_p - db_name); tmp_p++; table_name= tmp_p; } tmp_p= table_name; /* Look if there are partition tokens in the table name. */ while ((tmp_p= strchr(tmp_p, '#'))) { tmp_p++; switch (tmp_p[0]) { case 'P': case 'p': if (tmp_p[1] == '#') { part_name= tmp_p + 2; tmp_p+= 2; } break; case 'S': case 's': if ((tmp_p[1] == 'P' || tmp_p[1] == 'p') && tmp_p[2] == '#') { part_name_len= (int)(tmp_p - part_name - 1); subpart_name= tmp_p + 3; tmp_p+= 3; } break; case 'T': case 't': if ((tmp_p[1] == 'M' || tmp_p[1] == 'm') && (tmp_p[2] == 'P' || tmp_p[2] == 'p') && tmp_p[3] == '#' && !tmp_p[4]) { part_type= TEMP_PART_NAME; tmp_p+= 4; } break; case 'R': case 'r': if ((tmp_p[1] == 'E' || tmp_p[1] == 'e') && (tmp_p[2] == 'N' || tmp_p[2] == 'n') && tmp_p[3] == '#' && !tmp_p[4]) { part_type= RENAMED_PART_NAME; tmp_p+= 4; } break; default: /* Not partition name part. */ ; } } if (part_name) { table_name_len= (int)(part_name - table_name - 3); if (subpart_name) subpart_name_len= strlen(subpart_name); else part_name_len= strlen(part_name); if (part_type != NORMAL_PART_NAME) { if (subpart_name) subpart_name_len-= 5; else part_name_len-= 5; } } else table_name_len= strlen(table_name); if (db_name) { if (explain_mode == EXPLAIN_ALL_VERBOSE) { to_p= strnmov(to_p, ER_THD_OR_DEFAULT(thd, ER_DATABASE_NAME), end_p - to_p); *(to_p++)= ' '; to_p= add_identifier(thd, to_p, end_p, db_name, db_name_len); to_p= strnmov(to_p, ", ", end_p - to_p); } else { to_p= add_identifier(thd, to_p, end_p, db_name, db_name_len); to_p= strnmov(to_p, ".", end_p - to_p); } } if (explain_mode == EXPLAIN_ALL_VERBOSE) { to_p= strnmov(to_p, ER_THD_OR_DEFAULT(thd, ER_TABLE_NAME), end_p - to_p); *(to_p++)= ' '; to_p= add_identifier(thd, to_p, end_p, table_name, table_name_len); } else to_p= add_identifier(thd, to_p, end_p, table_name, table_name_len); if (part_name) { if (explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT) to_p= strnmov(to_p, " /* ", end_p - to_p); else if (explain_mode == EXPLAIN_PARTITIONS_VERBOSE) to_p= strnmov(to_p, " ", end_p - to_p); else to_p= strnmov(to_p, ", ", end_p - to_p); if (part_type != NORMAL_PART_NAME) { if (part_type == TEMP_PART_NAME) to_p= strnmov(to_p, ER_THD_OR_DEFAULT(thd, ER_TEMPORARY_NAME), end_p - to_p); else to_p= strnmov(to_p, ER_THD_OR_DEFAULT(thd, ER_RENAMED_NAME), end_p - to_p); to_p= strnmov(to_p, " ", end_p - to_p); } to_p= strnmov(to_p, ER_THD_OR_DEFAULT(thd, ER_PARTITION_NAME), end_p - to_p); *(to_p++)= ' '; to_p= add_identifier(thd, to_p, end_p, part_name, part_name_len); if (subpart_name) { to_p= strnmov(to_p, ", ", end_p - to_p); to_p= strnmov(to_p, ER_THD_OR_DEFAULT(thd, ER_SUBPARTITION_NAME), end_p - to_p); *(to_p++)= ' '; to_p= add_identifier(thd, to_p, end_p, subpart_name, subpart_name_len); } if (explain_mode == EXPLAIN_PARTITIONS_AS_COMMENT) to_p= strnmov(to_p, " */", end_p - to_p); } DBUG_PRINT("exit", ("to '%s'", to)); DBUG_RETURN((uint)(to_p - to)); } /* Translate a file name to a table name (WL #1324). SYNOPSIS filename_to_tablename() from The file name in my_charset_filename. to OUT The table name in system_charset_info. to_length The size of the table name buffer. RETURN Table name length. */ uint filename_to_tablename(const char *from, char *to, uint to_length, bool stay_quiet) { uint errors; size_t res; DBUG_ENTER("filename_to_tablename"); DBUG_PRINT("enter", ("from '%s'", from)); res= strconvert(&my_charset_filename, from, FN_REFLEN, system_charset_info, to, to_length, &errors); if (errors) // Old 5.0 name { res= (strxnmov(to, to_length, MYSQL50_TABLE_NAME_PREFIX, from, NullS) - to); if (!stay_quiet) sql_print_error("Invalid (old?) table or database name '%s'", from); } DBUG_PRINT("exit", ("to '%s'", to)); DBUG_RETURN(res); } /** Check if given string begins with "#mysql50#" prefix @param name string to check cut @retval FALSE no prefix found @retval TRUE prefix found */ bool check_mysql50_prefix(const char *name) { return (name[0] == '#' && !strncmp(name, MYSQL50_TABLE_NAME_PREFIX, MYSQL50_TABLE_NAME_PREFIX_LENGTH)); } /** Check if given string begins with "#mysql50#" prefix, cut it if so. @param from string to check and cut @param to[out] buffer for result string @param to_length its size @retval 0 no prefix found @retval non-0 result string length */ uint check_n_cut_mysql50_prefix(const char *from, char *to, uint to_length) { if (check_mysql50_prefix(from)) return (uint) (strmake(to, from + MYSQL50_TABLE_NAME_PREFIX_LENGTH, to_length - 1) - to); return 0; } /* Translate a table name to a file name (WL #1324). SYNOPSIS tablename_to_filename() from The table name in system_charset_info. to OUT The file name in my_charset_filename. to_length The size of the file name buffer. RETURN File name length. */ uint tablename_to_filename(const char *from, char *to, uint to_length) { uint errors, length; DBUG_ENTER("tablename_to_filename"); DBUG_PRINT("enter", ("from '%s'", from)); if ((length= check_n_cut_mysql50_prefix(from, to, to_length))) { /* Check if the name supplied is a valid mysql 5.0 name and make the name a zero length string if it's not. Note that just returning zero length is not enough : a lot of places don't check the return value and expect a zero terminated string. */ if (check_table_name(to, length, TRUE)) { to[0]= 0; length= 0; } DBUG_RETURN(length); } length= strconvert(system_charset_info, from, FN_REFLEN, &my_charset_filename, to, to_length, &errors); if (check_if_legal_tablename(to) && length + 4 < to_length) { memcpy(to + length, "@@@", 4); length+= 3; } DBUG_PRINT("exit", ("to '%s'", to)); DBUG_RETURN(length); } /* Creates path to a file: mysql_data_dir/db/table.ext SYNOPSIS build_table_filename() buff Where to write result in my_charset_filename. This may be the same as table_name. bufflen buff size db Database name in system_charset_info. table_name Table name in system_charset_info. ext File extension. flags FN_FROM_IS_TMP or FN_TO_IS_TMP or FN_IS_TMP table_name is temporary, do not change. NOTES Uses database and table name, and extension to create a file name in mysql_data_dir. Database and table names are converted from system_charset_info into "fscs". Unless flags indicate a temporary table name. 'db' is always converted. 'ext' is not converted. The conversion suppression is required for ALTER TABLE. This statement creates intermediate tables. These are regular (non-temporary) tables with a temporary name. Their path names must be derivable from the table name. So we cannot use build_tmptable_filename() for them. RETURN path length */ uint build_table_filename(char *buff, size_t bufflen, const char *db, const char *table_name, const char *ext, uint flags) { char dbbuff[FN_REFLEN]; char tbbuff[FN_REFLEN]; DBUG_ENTER("build_table_filename"); DBUG_PRINT("enter", ("db: '%s' table_name: '%s' ext: '%s' flags: %x", db, table_name, ext, flags)); if (flags & FN_IS_TMP) // FN_FROM_IS_TMP | FN_TO_IS_TMP strmake(tbbuff, table_name, sizeof(tbbuff)-1); else (void) tablename_to_filename(table_name, tbbuff, sizeof(tbbuff)); (void) tablename_to_filename(db, dbbuff, sizeof(dbbuff)); char *end = buff + bufflen; /* Don't add FN_ROOTDIR if mysql_data_home already includes it */ char *pos = strnmov(buff, mysql_data_home, bufflen); size_t rootdir_len= strlen(FN_ROOTDIR); if (pos - rootdir_len >= buff && memcmp(pos - rootdir_len, FN_ROOTDIR, rootdir_len) != 0) pos= strnmov(pos, FN_ROOTDIR, end - pos); pos= strxnmov(pos, end - pos, dbbuff, FN_ROOTDIR, NullS); #ifdef USE_SYMDIR if (!(flags & SKIP_SYMDIR_ACCESS)) { unpack_dirname(buff, buff); pos= strend(buff); } #endif pos= strxnmov(pos, end - pos, tbbuff, ext, NullS); DBUG_PRINT("exit", ("buff: '%s'", buff)); DBUG_RETURN((uint)(pos - buff)); } /** Create path to a temporary table mysql_tmpdir/#sql1234_12_1 (i.e. to its .FRM file but without an extension). @param thd The thread handle. @param buff Where to write result in my_charset_filename. @param bufflen buff size @note Uses current_pid, thread_id, and tmp_table counter to create a file name in mysql_tmpdir. @return Path length. */ uint build_tmptable_filename(THD* thd, char *buff, size_t bufflen) { DBUG_ENTER("build_tmptable_filename"); char *p= strnmov(buff, mysql_tmpdir, bufflen); my_snprintf(p, bufflen - (p - buff), "/%s%lx_%llx_%x", tmp_file_prefix, current_pid, thd->thread_id, thd->tmp_table++); if (lower_case_table_names) { /* Convert all except tmpdir to lower case */ my_casedn_str(files_charset_info, p); } size_t length= unpack_filename(buff, buff); DBUG_PRINT("exit", ("buff: '%s'", buff)); DBUG_RETURN(length); } /* -------------------------------------------------------------------------- MODULE: DDL log ----------------- This module is used to ensure that we can recover from crashes that occur in the middle of a meta-data operation in MySQL. E.g. DROP TABLE t1, t2; We need to ensure that both t1 and t2 are dropped and not only t1 and also that each table drop is entirely done and not "half-baked". To support this we create log entries for each meta-data statement in the ddl log while we are executing. These entries are dropped when the operation is completed. At recovery those entries that were not completed will be executed. There is only one ddl log in the system and it is protected by a mutex and there is a global struct that contains information about its current state. History: First version written in 2006 by Mikael Ronstrom -------------------------------------------------------------------------- */ struct st_global_ddl_log { /* We need to adjust buffer size to be able to handle downgrades/upgrades where IO_SIZE has changed. We'll set the buffer size such that we can handle that the buffer size was upto 4 times bigger in the version that wrote the DDL log. */ char file_entry_buf[4*IO_SIZE]; char file_name_str[FN_REFLEN]; char *file_name; DDL_LOG_MEMORY_ENTRY *first_free; DDL_LOG_MEMORY_ENTRY *first_used; uint num_entries; File file_id; uint name_len; uint io_size; bool inited; bool do_release; bool recovery_phase; st_global_ddl_log() : inited(false), do_release(false) {} }; st_global_ddl_log global_ddl_log; mysql_mutex_t LOCK_gdl; #define DDL_LOG_ENTRY_TYPE_POS 0 #define DDL_LOG_ACTION_TYPE_POS 1 #define DDL_LOG_PHASE_POS 2 #define DDL_LOG_NEXT_ENTRY_POS 4 #define DDL_LOG_NAME_POS 8 #define DDL_LOG_NUM_ENTRY_POS 0 #define DDL_LOG_NAME_LEN_POS 4 #define DDL_LOG_IO_SIZE_POS 8 /** Read one entry from ddl log file. @param entry_no Entry number to read @return Operation status @retval true Error @retval false Success */ static bool read_ddl_log_file_entry(uint entry_no) { bool error= FALSE; File file_id= global_ddl_log.file_id; uchar *file_entry_buf= (uchar*)global_ddl_log.file_entry_buf; size_t io_size= global_ddl_log.io_size; DBUG_ENTER("read_ddl_log_file_entry"); mysql_mutex_assert_owner(&LOCK_gdl); if (mysql_file_pread(file_id, file_entry_buf, io_size, io_size * entry_no, MYF(MY_WME)) != io_size) error= TRUE; DBUG_RETURN(error); } /** Write one entry to ddl log file. @param entry_no Entry number to write @return Operation status @retval true Error @retval false Success */ static bool write_ddl_log_file_entry(uint entry_no) { bool error= FALSE; File file_id= global_ddl_log.file_id; uchar *file_entry_buf= (uchar*)global_ddl_log.file_entry_buf; DBUG_ENTER("write_ddl_log_file_entry"); mysql_mutex_assert_owner(&LOCK_gdl); if (mysql_file_pwrite(file_id, file_entry_buf, IO_SIZE, IO_SIZE * entry_no, MYF(MY_WME)) != IO_SIZE) error= TRUE; DBUG_RETURN(error); } /** Sync the ddl log file. @return Operation status @retval FALSE Success @retval TRUE Error */ static bool sync_ddl_log_file() { DBUG_ENTER("sync_ddl_log_file"); DBUG_RETURN(mysql_file_sync(global_ddl_log.file_id, MYF(MY_WME))); } /** Write ddl log header. @return Operation status @retval TRUE Error @retval FALSE Success */ static bool write_ddl_log_header() { uint16 const_var; DBUG_ENTER("write_ddl_log_header"); int4store(&global_ddl_log.file_entry_buf[DDL_LOG_NUM_ENTRY_POS], global_ddl_log.num_entries); const_var= FN_REFLEN; int4store(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_LEN_POS], (ulong) const_var); const_var= IO_SIZE; int4store(&global_ddl_log.file_entry_buf[DDL_LOG_IO_SIZE_POS], (ulong) const_var); if (write_ddl_log_file_entry(0UL)) { sql_print_error("Error writing ddl log header"); DBUG_RETURN(TRUE); } DBUG_RETURN(sync_ddl_log_file()); } /** Create ddl log file name. @param file_name Filename setup */ static inline void create_ddl_log_file_name(char *file_name) { strxmov(file_name, mysql_data_home, "/", "ddl_log.log", NullS); } /** Read header of ddl log file. When we read the ddl log header we get information about maximum sizes of names in the ddl log and we also get information about the number of entries in the ddl log. @return Last entry in ddl log (0 if no entries) */ static uint read_ddl_log_header() { uchar *file_entry_buf= (uchar*)global_ddl_log.file_entry_buf; char file_name[FN_REFLEN]; uint entry_no; bool successful_open= FALSE; DBUG_ENTER("read_ddl_log_header"); mysql_mutex_init(key_LOCK_gdl, &LOCK_gdl, MY_MUTEX_INIT_SLOW); mysql_mutex_lock(&LOCK_gdl); create_ddl_log_file_name(file_name); if ((global_ddl_log.file_id= mysql_file_open(key_file_global_ddl_log, file_name, O_RDWR | O_BINARY, MYF(0))) >= 0) { if (read_ddl_log_file_entry(0UL)) { /* Write message into error log */ sql_print_error("Failed to read ddl log file in recovery"); } else successful_open= TRUE; } if (successful_open) { entry_no= uint4korr(&file_entry_buf[DDL_LOG_NUM_ENTRY_POS]); global_ddl_log.name_len= uint4korr(&file_entry_buf[DDL_LOG_NAME_LEN_POS]); global_ddl_log.io_size= uint4korr(&file_entry_buf[DDL_LOG_IO_SIZE_POS]); DBUG_ASSERT(global_ddl_log.io_size <= sizeof(global_ddl_log.file_entry_buf)); } else { entry_no= 0; } global_ddl_log.first_free= NULL; global_ddl_log.first_used= NULL; global_ddl_log.num_entries= 0; global_ddl_log.do_release= true; mysql_mutex_unlock(&LOCK_gdl); DBUG_RETURN(entry_no); } /** Convert from ddl_log_entry struct to file_entry_buf binary blob. @param ddl_log_entry filled in ddl_log_entry struct. */ static void set_global_from_ddl_log_entry(const DDL_LOG_ENTRY *ddl_log_entry) { mysql_mutex_assert_owner(&LOCK_gdl); global_ddl_log.file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= (char)DDL_LOG_ENTRY_CODE; global_ddl_log.file_entry_buf[DDL_LOG_ACTION_TYPE_POS]= (char)ddl_log_entry->action_type; global_ddl_log.file_entry_buf[DDL_LOG_PHASE_POS]= 0; int4store(&global_ddl_log.file_entry_buf[DDL_LOG_NEXT_ENTRY_POS], ddl_log_entry->next_entry); DBUG_ASSERT(strlen(ddl_log_entry->name) < FN_REFLEN); strmake(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS], ddl_log_entry->name, FN_REFLEN - 1); if (ddl_log_entry->action_type == DDL_LOG_RENAME_ACTION || ddl_log_entry->action_type == DDL_LOG_REPLACE_ACTION || ddl_log_entry->action_type == DDL_LOG_EXCHANGE_ACTION) { DBUG_ASSERT(strlen(ddl_log_entry->from_name) < FN_REFLEN); strmake(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + FN_REFLEN], ddl_log_entry->from_name, FN_REFLEN - 1); } else global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + FN_REFLEN]= 0; DBUG_ASSERT(strlen(ddl_log_entry->handler_name) < FN_REFLEN); strmake(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + (2*FN_REFLEN)], ddl_log_entry->handler_name, FN_REFLEN - 1); if (ddl_log_entry->action_type == DDL_LOG_EXCHANGE_ACTION) { DBUG_ASSERT(strlen(ddl_log_entry->tmp_name) < FN_REFLEN); strmake(&global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + (3*FN_REFLEN)], ddl_log_entry->tmp_name, FN_REFLEN - 1); } else global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + (3*FN_REFLEN)]= 0; } /** Convert from file_entry_buf binary blob to ddl_log_entry struct. @param[out] ddl_log_entry struct to fill in. @note Strings (names) are pointing to the global_ddl_log structure, so LOCK_gdl needs to be hold until they are read or copied. */ static void set_ddl_log_entry_from_global(DDL_LOG_ENTRY *ddl_log_entry, const uint read_entry) { char *file_entry_buf= (char*) global_ddl_log.file_entry_buf; uint inx; uchar single_char; mysql_mutex_assert_owner(&LOCK_gdl); ddl_log_entry->entry_pos= read_entry; single_char= file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]; ddl_log_entry->entry_type= (enum ddl_log_entry_code)single_char; single_char= file_entry_buf[DDL_LOG_ACTION_TYPE_POS]; ddl_log_entry->action_type= (enum ddl_log_action_code)single_char; ddl_log_entry->phase= file_entry_buf[DDL_LOG_PHASE_POS]; ddl_log_entry->next_entry= uint4korr(&file_entry_buf[DDL_LOG_NEXT_ENTRY_POS]); ddl_log_entry->name= &file_entry_buf[DDL_LOG_NAME_POS]; inx= DDL_LOG_NAME_POS + global_ddl_log.name_len; ddl_log_entry->from_name= &file_entry_buf[inx]; inx+= global_ddl_log.name_len; ddl_log_entry->handler_name= &file_entry_buf[inx]; if (ddl_log_entry->action_type == DDL_LOG_EXCHANGE_ACTION) { inx+= global_ddl_log.name_len; ddl_log_entry->tmp_name= &file_entry_buf[inx]; } else ddl_log_entry->tmp_name= NULL; } /** Read a ddl log entry. Read a specified entry in the ddl log. @param read_entry Number of entry to read @param[out] entry_info Information from entry @return Operation status @retval TRUE Error @retval FALSE Success */ static bool read_ddl_log_entry(uint read_entry, DDL_LOG_ENTRY *ddl_log_entry) { DBUG_ENTER("read_ddl_log_entry"); if (read_ddl_log_file_entry(read_entry)) { DBUG_RETURN(TRUE); } set_ddl_log_entry_from_global(ddl_log_entry, read_entry); DBUG_RETURN(FALSE); } /** Initialise ddl log. Write the header of the ddl log file and length of names. Also set number of entries to zero. @return Operation status @retval TRUE Error @retval FALSE Success */ static bool init_ddl_log() { char file_name[FN_REFLEN]; DBUG_ENTER("init_ddl_log"); if (global_ddl_log.inited) goto end; global_ddl_log.io_size= IO_SIZE; global_ddl_log.name_len= FN_REFLEN; create_ddl_log_file_name(file_name); if ((global_ddl_log.file_id= mysql_file_create(key_file_global_ddl_log, file_name, CREATE_MODE, O_RDWR | O_TRUNC | O_BINARY, MYF(MY_WME))) < 0) { /* Couldn't create ddl log file, this is serious error */ sql_print_error("Failed to open ddl log file"); DBUG_RETURN(TRUE); } global_ddl_log.inited= TRUE; if (write_ddl_log_header()) { (void) mysql_file_close(global_ddl_log.file_id, MYF(MY_WME)); global_ddl_log.inited= FALSE; DBUG_RETURN(TRUE); } end: DBUG_RETURN(FALSE); } /** Sync ddl log file. @return Operation status @retval TRUE Error @retval FALSE Success */ static bool sync_ddl_log_no_lock() { DBUG_ENTER("sync_ddl_log_no_lock"); mysql_mutex_assert_owner(&LOCK_gdl); if ((!global_ddl_log.recovery_phase) && init_ddl_log()) { DBUG_RETURN(TRUE); } DBUG_RETURN(sync_ddl_log_file()); } /** @brief Deactivate an individual entry. @details For complex rename operations we need to deactivate individual entries. During replace operations where we start with an existing table called t1 and a replacement table called t1#temp or something else and where we want to delete t1 and rename t1#temp to t1 this is not possible to do in a safe manner unless the ddl log is informed of the phases in the change. Delete actions are 1-phase actions that can be ignored immediately after being executed. Rename actions from x to y is also a 1-phase action since there is no interaction with any other handlers named x and y. Replace action where drop y and x -> y happens needs to be a two-phase action. Thus the first phase will drop y and the second phase will rename x -> y. @param entry_no Entry position of record to change @return Operation status @retval TRUE Error @retval FALSE Success */ static bool deactivate_ddl_log_entry_no_lock(uint entry_no) { uchar *file_entry_buf= (uchar*)global_ddl_log.file_entry_buf; DBUG_ENTER("deactivate_ddl_log_entry_no_lock"); mysql_mutex_assert_owner(&LOCK_gdl); if (!read_ddl_log_file_entry(entry_no)) { if (file_entry_buf[DDL_LOG_ENTRY_TYPE_POS] == DDL_LOG_ENTRY_CODE) { /* Log entry, if complete mark it done (IGNORE). Otherwise increase the phase by one. */ if (file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_DELETE_ACTION || file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_RENAME_ACTION || (file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_REPLACE_ACTION && file_entry_buf[DDL_LOG_PHASE_POS] == 1) || (file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_EXCHANGE_ACTION && file_entry_buf[DDL_LOG_PHASE_POS] >= EXCH_PHASE_TEMP_TO_FROM)) file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= DDL_IGNORE_LOG_ENTRY_CODE; else if (file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_REPLACE_ACTION) { DBUG_ASSERT(file_entry_buf[DDL_LOG_PHASE_POS] == 0); file_entry_buf[DDL_LOG_PHASE_POS]= 1; } else if (file_entry_buf[DDL_LOG_ACTION_TYPE_POS] == DDL_LOG_EXCHANGE_ACTION) { DBUG_ASSERT(file_entry_buf[DDL_LOG_PHASE_POS] <= EXCH_PHASE_FROM_TO_NAME); file_entry_buf[DDL_LOG_PHASE_POS]++; } else { DBUG_ASSERT(0); } if (write_ddl_log_file_entry(entry_no)) { sql_print_error("Error in deactivating log entry. Position = %u", entry_no); DBUG_RETURN(TRUE); } } } else { sql_print_error("Failed in reading entry before deactivating it"); DBUG_RETURN(TRUE); } DBUG_RETURN(FALSE); } /** Execute one action in a ddl log entry @param ddl_log_entry Information in action entry to execute @return Operation status @retval TRUE Error @retval FALSE Success */ static int execute_ddl_log_action(THD *thd, DDL_LOG_ENTRY *ddl_log_entry) { bool frm_action= FALSE; LEX_STRING handler_name; handler *file= NULL; MEM_ROOT mem_root; int error= TRUE; char to_path[FN_REFLEN]; char from_path[FN_REFLEN]; #ifdef WITH_PARTITION_STORAGE_ENGINE char *par_ext= (char*)".par"; #endif handlerton *hton; DBUG_ENTER("execute_ddl_log_action"); mysql_mutex_assert_owner(&LOCK_gdl); if (ddl_log_entry->entry_type == DDL_IGNORE_LOG_ENTRY_CODE) { DBUG_RETURN(FALSE); } DBUG_PRINT("ddl_log", ("execute type %c next %u name '%s' from_name '%s' handler '%s'" " tmp_name '%s'", ddl_log_entry->action_type, ddl_log_entry->next_entry, ddl_log_entry->name, ddl_log_entry->from_name, ddl_log_entry->handler_name, ddl_log_entry->tmp_name)); handler_name.str= (char*)ddl_log_entry->handler_name; handler_name.length= strlen(ddl_log_entry->handler_name); init_sql_alloc(&mem_root, TABLE_ALLOC_BLOCK_SIZE, 0, MYF(MY_THREAD_SPECIFIC)); if (!strcmp(ddl_log_entry->handler_name, reg_ext)) frm_action= TRUE; else { plugin_ref plugin= ha_resolve_by_name(thd, &handler_name, false); if (!plugin) { my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), ddl_log_entry->handler_name); goto error; } hton= plugin_data(plugin, handlerton*); file= get_new_handler((TABLE_SHARE*)0, &mem_root, hton); if (!file) { mem_alloc_error(sizeof(handler)); goto error; } } switch (ddl_log_entry->action_type) { case DDL_LOG_REPLACE_ACTION: case DDL_LOG_DELETE_ACTION: { if (ddl_log_entry->phase == 0) { if (frm_action) { strxmov(to_path, ddl_log_entry->name, reg_ext, NullS); if ((error= mysql_file_delete(key_file_frm, to_path, MYF(MY_WME)))) { if (my_errno != ENOENT) break; } #ifdef WITH_PARTITION_STORAGE_ENGINE strxmov(to_path, ddl_log_entry->name, par_ext, NullS); (void) mysql_file_delete(key_file_partition, to_path, MYF(MY_WME)); #endif } else { if ((error= file->ha_delete_table(ddl_log_entry->name))) { if (error != ENOENT && error != HA_ERR_NO_SUCH_TABLE) break; } } if ((deactivate_ddl_log_entry_no_lock(ddl_log_entry->entry_pos))) break; (void) sync_ddl_log_no_lock(); error= FALSE; if (ddl_log_entry->action_type == DDL_LOG_DELETE_ACTION) break; } DBUG_ASSERT(ddl_log_entry->action_type == DDL_LOG_REPLACE_ACTION); /* Fall through and perform the rename action of the replace action. We have already indicated the success of the delete action in the log entry by stepping up the phase. */ } /* fall through */ case DDL_LOG_RENAME_ACTION: { error= TRUE; if (frm_action) { strxmov(to_path, ddl_log_entry->name, reg_ext, NullS); strxmov(from_path, ddl_log_entry->from_name, reg_ext, NullS); if (mysql_file_rename(key_file_frm, from_path, to_path, MYF(MY_WME))) break; #ifdef WITH_PARTITION_STORAGE_ENGINE strxmov(to_path, ddl_log_entry->name, par_ext, NullS); strxmov(from_path, ddl_log_entry->from_name, par_ext, NullS); (void) mysql_file_rename(key_file_partition, from_path, to_path, MYF(MY_WME)); #endif } else { if (file->ha_rename_table(ddl_log_entry->from_name, ddl_log_entry->name)) break; } if ((deactivate_ddl_log_entry_no_lock(ddl_log_entry->entry_pos))) break; (void) sync_ddl_log_no_lock(); error= FALSE; break; } case DDL_LOG_EXCHANGE_ACTION: { /* We hold LOCK_gdl, so we can alter global_ddl_log.file_entry_buf */ char *file_entry_buf= (char*)&global_ddl_log.file_entry_buf; /* not yet implemented for frm */ DBUG_ASSERT(!frm_action); /* Using a case-switch here to revert all currently done phases, since it will fall through until the first phase is undone. */ switch (ddl_log_entry->phase) { case EXCH_PHASE_TEMP_TO_FROM: /* tmp_name -> from_name possibly done */ (void) file->ha_rename_table(ddl_log_entry->from_name, ddl_log_entry->tmp_name); /* decrease the phase and sync */ file_entry_buf[DDL_LOG_PHASE_POS]--; if (write_ddl_log_file_entry(ddl_log_entry->entry_pos)) break; if (sync_ddl_log_no_lock()) break; /* fall through */ case EXCH_PHASE_FROM_TO_NAME: /* from_name -> name possibly done */ (void) file->ha_rename_table(ddl_log_entry->name, ddl_log_entry->from_name); /* decrease the phase and sync */ file_entry_buf[DDL_LOG_PHASE_POS]--; if (write_ddl_log_file_entry(ddl_log_entry->entry_pos)) break; if (sync_ddl_log_no_lock()) break; /* fall through */ case EXCH_PHASE_NAME_TO_TEMP: /* name -> tmp_name possibly done */ (void) file->ha_rename_table(ddl_log_entry->tmp_name, ddl_log_entry->name); /* disable the entry and sync */ file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= DDL_IGNORE_LOG_ENTRY_CODE; if (write_ddl_log_file_entry(ddl_log_entry->entry_pos)) break; if (sync_ddl_log_no_lock()) break; error= FALSE; break; default: DBUG_ASSERT(0); break; } break; } default: DBUG_ASSERT(0); break; } delete file; error: free_root(&mem_root, MYF(0)); DBUG_RETURN(error); } /** Get a free entry in the ddl log @param[out] active_entry A ddl log memory entry returned @return Operation status @retval TRUE Error @retval FALSE Success */ static bool get_free_ddl_log_entry(DDL_LOG_MEMORY_ENTRY **active_entry, bool *write_header) { DDL_LOG_MEMORY_ENTRY *used_entry; DDL_LOG_MEMORY_ENTRY *first_used= global_ddl_log.first_used; DBUG_ENTER("get_free_ddl_log_entry"); if (global_ddl_log.first_free == NULL) { if (!(used_entry= (DDL_LOG_MEMORY_ENTRY*)my_malloc( sizeof(DDL_LOG_MEMORY_ENTRY), MYF(MY_WME)))) { sql_print_error("Failed to allocate memory for ddl log free list"); DBUG_RETURN(TRUE); } global_ddl_log.num_entries++; used_entry->entry_pos= global_ddl_log.num_entries; *write_header= TRUE; } else { used_entry= global_ddl_log.first_free; global_ddl_log.first_free= used_entry->next_log_entry; *write_header= FALSE; } /* Move from free list to used list */ used_entry->next_log_entry= first_used; used_entry->prev_log_entry= NULL; used_entry->next_active_log_entry= NULL; global_ddl_log.first_used= used_entry; if (first_used) first_used->prev_log_entry= used_entry; *active_entry= used_entry; DBUG_RETURN(FALSE); } /** Execute one entry in the ddl log. Executing an entry means executing a linked list of actions. @param first_entry Reference to first action in entry @return Operation status @retval TRUE Error @retval FALSE Success */ static bool execute_ddl_log_entry_no_lock(THD *thd, uint first_entry) { DDL_LOG_ENTRY ddl_log_entry; uint read_entry= first_entry; DBUG_ENTER("execute_ddl_log_entry_no_lock"); mysql_mutex_assert_owner(&LOCK_gdl); do { if (read_ddl_log_entry(read_entry, &ddl_log_entry)) { /* Write to error log and continue with next log entry */ sql_print_error("Failed to read entry = %u from ddl log", read_entry); break; } DBUG_ASSERT(ddl_log_entry.entry_type == DDL_LOG_ENTRY_CODE || ddl_log_entry.entry_type == DDL_IGNORE_LOG_ENTRY_CODE); if (execute_ddl_log_action(thd, &ddl_log_entry)) { /* Write to error log and continue with next log entry */ sql_print_error("Failed to execute action for entry = %u from ddl log", read_entry); break; } read_entry= ddl_log_entry.next_entry; } while (read_entry); DBUG_RETURN(FALSE); } /* External interface methods for the DDL log Module --------------------------------------------------- */ /** Write a ddl log entry. A careful write of the ddl log is performed to ensure that we can handle crashes occurring during CREATE and ALTER TABLE processing. @param ddl_log_entry Information about log entry @param[out] entry_written Entry information written into @return Operation status @retval TRUE Error @retval FALSE Success */ bool write_ddl_log_entry(DDL_LOG_ENTRY *ddl_log_entry, DDL_LOG_MEMORY_ENTRY **active_entry) { bool error, write_header; DBUG_ENTER("write_ddl_log_entry"); mysql_mutex_assert_owner(&LOCK_gdl); if (init_ddl_log()) { DBUG_RETURN(TRUE); } set_global_from_ddl_log_entry(ddl_log_entry); if (get_free_ddl_log_entry(active_entry, &write_header)) { DBUG_RETURN(TRUE); } error= FALSE; DBUG_PRINT("ddl_log", ("write type %c next %u name '%s' from_name '%s' handler '%s'" " tmp_name '%s'", (char) global_ddl_log.file_entry_buf[DDL_LOG_ACTION_TYPE_POS], ddl_log_entry->next_entry, (char*) &global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS], (char*) &global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + FN_REFLEN], (char*) &global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + (2*FN_REFLEN)], (char*) &global_ddl_log.file_entry_buf[DDL_LOG_NAME_POS + (3*FN_REFLEN)])); if (write_ddl_log_file_entry((*active_entry)->entry_pos)) { error= TRUE; sql_print_error("Failed to write entry_no = %u", (*active_entry)->entry_pos); } if (write_header && !error) { (void) sync_ddl_log_no_lock(); if (write_ddl_log_header()) error= TRUE; } if (error) release_ddl_log_memory_entry(*active_entry); DBUG_RETURN(error); } /** @brief Write final entry in the ddl log. @details This is the last write in the ddl log. The previous log entries have already been written but not yet synched to disk. We write a couple of log entries that describes action to perform. This entries are set-up in a linked list, however only when a first execute entry is put as the first entry these will be executed. This routine writes this first. @param first_entry First entry in linked list of entries to execute, if 0 = NULL it means that the entry is removed and the entries are put into the free list. @param complete Flag indicating we are simply writing info about that entry has been completed @param[in,out] active_entry Entry to execute, 0 = NULL if the entry is written first time and needs to be returned. In this case the entry written is returned in this parameter @return Operation status @retval TRUE Error @retval FALSE Success */ bool write_execute_ddl_log_entry(uint first_entry, bool complete, DDL_LOG_MEMORY_ENTRY **active_entry) { bool write_header= FALSE; char *file_entry_buf= (char*)global_ddl_log.file_entry_buf; DBUG_ENTER("write_execute_ddl_log_entry"); mysql_mutex_assert_owner(&LOCK_gdl); if (init_ddl_log()) { DBUG_RETURN(TRUE); } if (!complete) { /* We haven't synched the log entries yet, we synch them now before writing the execute entry. If complete is true we haven't written any log entries before, we are only here to write the execute entry to indicate it is done. */ (void) sync_ddl_log_no_lock(); file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= (char)DDL_LOG_EXECUTE_CODE; } else file_entry_buf[DDL_LOG_ENTRY_TYPE_POS]= (char)DDL_IGNORE_LOG_ENTRY_CODE; file_entry_buf[DDL_LOG_ACTION_TYPE_POS]= 0; /* Ignored for execute entries */ file_entry_buf[DDL_LOG_PHASE_POS]= 0; int4store(&file_entry_buf[DDL_LOG_NEXT_ENTRY_POS], first_entry); file_entry_buf[DDL_LOG_NAME_POS]= 0; file_entry_buf[DDL_LOG_NAME_POS + FN_REFLEN]= 0; file_entry_buf[DDL_LOG_NAME_POS + 2*FN_REFLEN]= 0; if (!(*active_entry)) { if (get_free_ddl_log_entry(active_entry, &write_header)) { DBUG_RETURN(TRUE); } write_header= TRUE; } if (write_ddl_log_file_entry((*active_entry)->entry_pos)) { sql_print_error("Error writing execute entry in ddl log"); release_ddl_log_memory_entry(*active_entry); DBUG_RETURN(TRUE); } (void) sync_ddl_log_no_lock(); if (write_header) { if (write_ddl_log_header()) { release_ddl_log_memory_entry(*active_entry); DBUG_RETURN(TRUE); } } DBUG_RETURN(FALSE); } /** Deactivate an individual entry. @details see deactivate_ddl_log_entry_no_lock. @param entry_no Entry position of record to change @return Operation status @retval TRUE Error @retval FALSE Success */ bool deactivate_ddl_log_entry(uint entry_no) { bool error; DBUG_ENTER("deactivate_ddl_log_entry"); mysql_mutex_lock(&LOCK_gdl); error= deactivate_ddl_log_entry_no_lock(entry_no); mysql_mutex_unlock(&LOCK_gdl); DBUG_RETURN(error); } /** Sync ddl log file. @return Operation status @retval TRUE Error @retval FALSE Success */ bool sync_ddl_log() { bool error; DBUG_ENTER("sync_ddl_log"); mysql_mutex_lock(&LOCK_gdl); error= sync_ddl_log_no_lock(); mysql_mutex_unlock(&LOCK_gdl); DBUG_RETURN(error); } /** Release a log memory entry. @param log_memory_entry Log memory entry to release */ void release_ddl_log_memory_entry(DDL_LOG_MEMORY_ENTRY *log_entry) { DDL_LOG_MEMORY_ENTRY *first_free= global_ddl_log.first_free; DDL_LOG_MEMORY_ENTRY *next_log_entry= log_entry->next_log_entry; DDL_LOG_MEMORY_ENTRY *prev_log_entry= log_entry->prev_log_entry; DBUG_ENTER("release_ddl_log_memory_entry"); mysql_mutex_assert_owner(&LOCK_gdl); global_ddl_log.first_free= log_entry; log_entry->next_log_entry= first_free; if (prev_log_entry) prev_log_entry->next_log_entry= next_log_entry; else global_ddl_log.first_used= next_log_entry; if (next_log_entry) next_log_entry->prev_log_entry= prev_log_entry; DBUG_VOID_RETURN; } /** Execute one entry in the ddl log. Executing an entry means executing a linked list of actions. @param first_entry Reference to first action in entry @return Operation status @retval TRUE Error @retval FALSE Success */ bool execute_ddl_log_entry(THD *thd, uint first_entry) { bool error; DBUG_ENTER("execute_ddl_log_entry"); mysql_mutex_lock(&LOCK_gdl); error= execute_ddl_log_entry_no_lock(thd, first_entry); mysql_mutex_unlock(&LOCK_gdl); DBUG_RETURN(error); } /** Close the ddl log. */ static void close_ddl_log() { DBUG_ENTER("close_ddl_log"); if (global_ddl_log.file_id >= 0) { (void) mysql_file_close(global_ddl_log.file_id, MYF(MY_WME)); global_ddl_log.file_id= (File) -1; } DBUG_VOID_RETURN; } /** Execute the ddl log at recovery of MySQL Server. */ void execute_ddl_log_recovery() { uint num_entries, i; THD *thd; DDL_LOG_ENTRY ddl_log_entry; char file_name[FN_REFLEN]; static char recover_query_string[]= "INTERNAL DDL LOG RECOVER IN PROGRESS"; DBUG_ENTER("execute_ddl_log_recovery"); /* Initialise global_ddl_log struct */ bzero(global_ddl_log.file_entry_buf, sizeof(global_ddl_log.file_entry_buf)); global_ddl_log.inited= FALSE; global_ddl_log.recovery_phase= TRUE; global_ddl_log.io_size= IO_SIZE; global_ddl_log.file_id= (File) -1; /* To be able to run this from boot, we allocate a temporary THD */ if (!(thd=new THD(0))) DBUG_VOID_RETURN; thd->thread_stack= (char*) &thd; thd->store_globals(); thd->set_query(recover_query_string, strlen(recover_query_string)); /* this also initialize LOCK_gdl */ num_entries= read_ddl_log_header(); mysql_mutex_lock(&LOCK_gdl); for (i= 1; i < num_entries + 1; i++) { if (read_ddl_log_entry(i, &ddl_log_entry)) { sql_print_error("Failed to read entry no = %u from ddl log", i); continue; } if (ddl_log_entry.entry_type == DDL_LOG_EXECUTE_CODE) { if (execute_ddl_log_entry_no_lock(thd, ddl_log_entry.next_entry)) { /* Real unpleasant scenario but we continue anyways. */ continue; } } } close_ddl_log(); create_ddl_log_file_name(file_name); (void) mysql_file_delete(key_file_global_ddl_log, file_name, MYF(0)); global_ddl_log.recovery_phase= FALSE; mysql_mutex_unlock(&LOCK_gdl); thd->reset_query(); delete thd; DBUG_VOID_RETURN; } /** Release all memory allocated to the ddl log. */ void release_ddl_log() { DDL_LOG_MEMORY_ENTRY *free_list; DDL_LOG_MEMORY_ENTRY *used_list; DBUG_ENTER("release_ddl_log"); if (!global_ddl_log.do_release) DBUG_VOID_RETURN; mysql_mutex_lock(&LOCK_gdl); free_list= global_ddl_log.first_free; used_list= global_ddl_log.first_used; while (used_list) { DDL_LOG_MEMORY_ENTRY *tmp= used_list->next_log_entry; my_free(used_list); used_list= tmp; } while (free_list) { DDL_LOG_MEMORY_ENTRY *tmp= free_list->next_log_entry; my_free(free_list); free_list= tmp; } close_ddl_log(); global_ddl_log.inited= 0; mysql_mutex_unlock(&LOCK_gdl); mysql_mutex_destroy(&LOCK_gdl); global_ddl_log.do_release= false; DBUG_VOID_RETURN; } /* --------------------------------------------------------------------------- END MODULE DDL log -------------------- --------------------------------------------------------------------------- */ /** @brief construct a temporary shadow file name. @details Make a shadow file name used by ALTER TABLE to construct the modified table (with keeping the original). The modified table is then moved back as original table. The name must start with the temp file prefix so it gets filtered out by table files listing routines. @param[out] buff buffer to receive the constructed name @param bufflen size of buff @param lpt alter table data structure @retval path length */ uint build_table_shadow_filename(char *buff, size_t bufflen, ALTER_PARTITION_PARAM_TYPE *lpt) { char tmp_name[FN_REFLEN]; my_snprintf (tmp_name, sizeof (tmp_name), "%s-%s", tmp_file_prefix, lpt->table_name); return build_table_filename(buff, bufflen, lpt->db, tmp_name, "", FN_IS_TMP); } /* SYNOPSIS mysql_write_frm() lpt Struct carrying many parameters needed for this method flags Flags as defined below WFRM_INITIAL_WRITE If set we need to prepare table before creating the frm file WFRM_INSTALL_SHADOW If set we should install the new frm WFRM_KEEP_SHARE If set we know that the share is to be retained and thus we should ensure share object is correct, if not set we don't set the new partition syntax string since we know the share object is destroyed. WFRM_PACK_FRM If set we should pack the frm file and delete the frm file RETURN VALUES TRUE Error FALSE Success DESCRIPTION A support method that creates a new frm file and in this process it regenerates the partition data. It works fine also for non-partitioned tables since it only handles partitioned data if it exists. */ bool mysql_write_frm(ALTER_PARTITION_PARAM_TYPE *lpt, uint flags) { /* Prepare table to prepare for writing a new frm file where the partitions in add/drop state have temporarily changed their state We set tmp_table to avoid get errors on naming of primary key index. */ int error= 0; char path[FN_REFLEN+1]; char shadow_path[FN_REFLEN+1]; char shadow_frm_name[FN_REFLEN+1]; char frm_name[FN_REFLEN+1]; #ifdef WITH_PARTITION_STORAGE_ENGINE char *part_syntax_buf; uint syntax_len; #endif DBUG_ENTER("mysql_write_frm"); /* Build shadow frm file name */ build_table_shadow_filename(shadow_path, sizeof(shadow_path) - 1, lpt); strxmov(shadow_frm_name, shadow_path, reg_ext, NullS); if (flags & WFRM_WRITE_SHADOW) { if (mysql_prepare_create_table(lpt->thd, lpt->create_info, lpt->alter_info, &lpt->db_options, lpt->table->file, &lpt->key_info_buffer, &lpt->key_count, C_ALTER_TABLE)) { DBUG_RETURN(TRUE); } #ifdef WITH_PARTITION_STORAGE_ENGINE { partition_info *part_info= lpt->table->part_info; if (part_info) { if (!(part_syntax_buf= generate_partition_syntax(lpt->thd, part_info, &syntax_len, TRUE, lpt->create_info, lpt->alter_info))) { DBUG_RETURN(TRUE); } part_info->part_info_string= part_syntax_buf; part_info->part_info_len= syntax_len; } } #endif /* Write shadow frm file */ lpt->create_info->table_options= lpt->db_options; LEX_CUSTRING frm= build_frm_image(lpt->thd, lpt->table_name, lpt->create_info, lpt->alter_info->create_list, lpt->key_count, lpt->key_info_buffer, lpt->table->file); if (!frm.str) { error= 1; goto end; } int error= writefrm(shadow_path, lpt->db, lpt->table_name, lpt->create_info->tmp_table(), frm.str, frm.length); my_free(const_cast<uchar*>(frm.str)); if (error || lpt->table->file->ha_create_partitioning_metadata(shadow_path, NULL, CHF_CREATE_FLAG)) { mysql_file_delete(key_file_frm, shadow_frm_name, MYF(0)); error= 1; goto end; } } if (flags & WFRM_INSTALL_SHADOW) { #ifdef WITH_PARTITION_STORAGE_ENGINE partition_info *part_info= lpt->part_info; #endif /* Build frm file name */ build_table_filename(path, sizeof(path) - 1, lpt->db, lpt->table_name, "", 0); strxnmov(frm_name, sizeof(frm_name), path, reg_ext, NullS); /* When we are changing to use new frm file we need to ensure that we don't collide with another thread in process to open the frm file. We start by deleting the .frm file and possible .par file. Then we write to the DDL log that we have completed the delete phase by increasing the phase of the log entry. Next step is to rename the new .frm file and the new .par file to the real name. After completing this we write a new phase to the log entry that will deactivate it. */ if (mysql_file_delete(key_file_frm, frm_name, MYF(MY_WME)) || #ifdef WITH_PARTITION_STORAGE_ENGINE lpt->table->file->ha_create_partitioning_metadata(path, shadow_path, CHF_DELETE_FLAG) || deactivate_ddl_log_entry(part_info->frm_log_entry->entry_pos) || (sync_ddl_log(), FALSE) || mysql_file_rename(key_file_frm, shadow_frm_name, frm_name, MYF(MY_WME)) || lpt->table->file->ha_create_partitioning_metadata(path, shadow_path, CHF_RENAME_FLAG)) #else mysql_file_rename(key_file_frm, shadow_frm_name, frm_name, MYF(MY_WME))) #endif { error= 1; goto err; } #ifdef WITH_PARTITION_STORAGE_ENGINE if (part_info && (flags & WFRM_KEEP_SHARE)) { TABLE_SHARE *share= lpt->table->s; char *tmp_part_syntax_str; if (!(part_syntax_buf= generate_partition_syntax(lpt->thd, part_info, &syntax_len, TRUE, lpt->create_info, lpt->alter_info))) { error= 1; goto err; } if (share->partition_info_buffer_size < syntax_len + 1) { share->partition_info_buffer_size= syntax_len+1; if (!(tmp_part_syntax_str= (char*) strmake_root(&share->mem_root, part_syntax_buf, syntax_len))) { error= 1; goto err; } share->partition_info_str= tmp_part_syntax_str; } else memcpy((char*) share->partition_info_str, part_syntax_buf, syntax_len + 1); share->partition_info_str_len= part_info->part_info_len= syntax_len; part_info->part_info_string= part_syntax_buf; } #endif err: #ifdef WITH_PARTITION_STORAGE_ENGINE deactivate_ddl_log_entry(part_info->frm_log_entry->entry_pos); part_info->frm_log_entry= NULL; (void) sync_ddl_log(); #endif ; } end: DBUG_RETURN(error); } /* SYNOPSIS write_bin_log() thd Thread object clear_error is clear_error to be called query Query to log query_length Length of query is_trans if the event changes either a trans or non-trans engine. RETURN VALUES NONE DESCRIPTION Write the binlog if open, routine used in multiple places in this file */ int write_bin_log(THD *thd, bool clear_error, char const *query, ulong query_length, bool is_trans) { int error= 0; if (mysql_bin_log.is_open()) { int errcode= 0; thd_proc_info(thd, "Writing to binlog"); if (clear_error) thd->clear_error(); else errcode= query_error_code(thd, TRUE); error= thd->binlog_query(THD::STMT_QUERY_TYPE, query, query_length, is_trans, FALSE, FALSE, errcode); thd_proc_info(thd, 0); } return error; } /* delete (drop) tables. SYNOPSIS mysql_rm_table() thd Thread handle tables List of tables to delete if_exists If 1, don't give error if one table doesn't exists NOTES Will delete all tables that can be deleted and give a compact error messages for tables that could not be deleted. If a table is in use, we will wait for all users to free the table before dropping it Wait if global_read_lock (FLUSH TABLES WITH READ LOCK) is set, but not if under LOCK TABLES. RETURN FALSE OK. In this case ok packet is sent to user TRUE Error */ bool mysql_rm_table(THD *thd,TABLE_LIST *tables, my_bool if_exists, my_bool drop_temporary) { bool error; Drop_table_error_handler err_handler; TABLE_LIST *table; DBUG_ENTER("mysql_rm_table"); /* Disable drop of enabled log tables, must be done before name locking */ for (table= tables; table; table= table->next_local) { if (check_if_log_table(table, TRUE, "DROP")) DBUG_RETURN(true); } if (!drop_temporary) { if (!in_bootstrap) { for (table= tables; table; table= table->next_local) { LEX_STRING db_name= { table->db, table->db_length }; LEX_STRING table_name= { table->table_name, table->table_name_length }; if (table->open_type == OT_BASE_ONLY || !thd->find_temporary_table(table)) (void) delete_statistics_for_table(thd, &db_name, &table_name); } } if (!thd->locked_tables_mode) { if (lock_table_names(thd, tables, NULL, thd->variables.lock_wait_timeout, 0)) DBUG_RETURN(true); } else { for (table= tables; table; table= table->next_local) { if (is_temporary_table(table)) { /* A temporary table. Don't try to find a corresponding MDL lock or assign it to table->mdl_request.ticket. There can't be metadata locks for temporary tables: they are local to the session. Later in this function we release the MDL lock only if table->mdl_requeset.ticket is not NULL. Thus here we ensure that we won't release the metadata lock on the base table locked with LOCK TABLES as a side effect of temporary table drop. */ DBUG_ASSERT(table->mdl_request.ticket == NULL); } else { /* Not a temporary table. Since 'tables' list can't contain duplicates (this is ensured by parser) it is safe to cache pointer to the TABLE instances in its elements. */ table->table= find_table_for_mdl_upgrade(thd, table->db, table->table_name, false); if (!table->table) DBUG_RETURN(true); table->mdl_request.ticket= table->table->mdl_ticket; } } } } /* mark for close and remove all cached entries */ thd->push_internal_handler(&err_handler); error= mysql_rm_table_no_locks(thd, tables, if_exists, drop_temporary, false, false, false); thd->pop_internal_handler(); if (error) DBUG_RETURN(TRUE); my_ok(thd); DBUG_RETURN(FALSE); } /** Find the comment in the query. That's auxiliary function to be used handling DROP TABLE [comment]. @param thd Thread handler @param comment_pos How many characters to skip before the comment. Can be either 9 for DROP TABLE or 17 for DROP TABLE IF EXISTS @param comment_start returns the beginning of the comment if found. @retval 0 no comment found @retval >0 the lenght of the comment found */ static uint32 comment_length(THD *thd, uint32 comment_pos, const char **comment_start) { /* We use uchar * here to make array indexing portable */ const uchar *query= (uchar*) thd->query(); const uchar *query_end= (uchar*) query + thd->query_length(); const uchar *const state_map= thd->charset()->state_map; for (; query < query_end; query++) { if (state_map[static_cast<uchar>(*query)] == MY_LEX_SKIP) continue; if (comment_pos-- == 0) break; } if (query > query_end - 3 /* comment can't be shorter than 4 */ || state_map[static_cast<uchar>(*query)] != MY_LEX_LONG_COMMENT || query[1] != '*') return 0; *comment_start= (char*) query; for (query+= 3; query < query_end; query++) { if (query[-1] == '*' && query[0] == '/') return (uint32)((char*) query - *comment_start + 1); } return 0; } /** Execute the drop of a normal or temporary table. @param thd Thread handler @param tables Tables to drop @param if_exists If set, don't give an error if table doesn't exists. In this case we give an warning of level 'NOTE' @param drop_temporary Only drop temporary tables @param drop_view Allow to delete VIEW .frm @param dont_log_query Don't write query to log files. This will also not generate warnings if the handler files doesn't exists @param dont_free_locks Don't do automatic UNLOCK TABLE if no more locked tables @retval 0 ok @retval 1 Error @retval -1 Thread was killed @note This function assumes that metadata locks have already been taken. It is also assumed that the tables have been removed from TDC. @note This function assumes that temporary tables to be dropped have been pre-opened using corresponding table list elements. @todo When logging to the binary log, we should log tmp_tables and transactional tables as separate statements if we are in a transaction; This is needed to get these tables into the cached binary log that is only written on COMMIT. The current code only writes DROP statements that only uses temporary tables to the cache binary log. This should be ok on most cases, but not all. */ int mysql_rm_table_no_locks(THD *thd, TABLE_LIST *tables, bool if_exists, bool drop_temporary, bool drop_view, bool dont_log_query, bool dont_free_locks) { TABLE_LIST *table; char path[FN_REFLEN + 1], wrong_tables_buff[160], *alias= NULL; String wrong_tables(wrong_tables_buff, sizeof(wrong_tables_buff)-1, system_charset_info); uint path_length= 0, errors= 0; int error= 0; int non_temp_tables_count= 0; bool non_tmp_error= 0; bool trans_tmp_table_deleted= 0, non_trans_tmp_table_deleted= 0; bool non_tmp_table_deleted= 0; bool is_drop_tmp_if_exists_added= 0; bool was_view= 0; String built_query; String built_trans_tmp_query, built_non_trans_tmp_query; DBUG_ENTER("mysql_rm_table_no_locks"); wrong_tables.length(0); /* Prepares the drop statements that will be written into the binary log as follows: 1 - If we are not processing a "DROP TEMPORARY" it prepares a "DROP". 2 - A "DROP" may result in a "DROP TEMPORARY" but the opposite is not true. 3 - If the current format is row, the IF EXISTS token needs to be appended because one does not know if CREATE TEMPORARY was previously written to the binary log. 4 - Add the IF_EXISTS token if necessary, i.e. if_exists is TRUE. 5 - For temporary tables, there is a need to differentiate tables in transactional and non-transactional storage engines. For that, reason, two types of drop statements are prepared. The need to different the type of tables when dropping a temporary table stems from the fact that such drop does not commit an ongoing transaction and changes to non-transactional tables must be written ahead of the transaction in some circumstances. 6- Slave SQL thread ignores all replicate-* filter rules for temporary tables with 'IF EXISTS' clause. (See sql/sql_parse.cc: mysql_execute_command() for details). These commands will be binlogged as they are, even if the default database (from USE `db`) is not present on the Slave. This can cause point in time recovery failures later when user uses the slave's binlog to re-apply. Hence at the time of binary logging, these commands will be written with fully qualified table names and use `db` will be suppressed. */ if (!dont_log_query) { if (!drop_temporary) { const char *comment_start; uint32 comment_len; built_query.set_charset(thd->charset()); if (if_exists) built_query.append("DROP TABLE IF EXISTS "); else built_query.append("DROP TABLE "); if ((comment_len= comment_length(thd, if_exists ? 17:9, &comment_start))) { built_query.append(comment_start, comment_len); built_query.append(" "); } } if (thd->is_current_stmt_binlog_format_row() || if_exists) { is_drop_tmp_if_exists_added= true; built_trans_tmp_query.set_charset(system_charset_info); built_trans_tmp_query.append("DROP TEMPORARY TABLE IF EXISTS "); built_non_trans_tmp_query.set_charset(system_charset_info); built_non_trans_tmp_query.append("DROP TEMPORARY TABLE IF EXISTS "); } else { built_trans_tmp_query.set_charset(system_charset_info); built_trans_tmp_query.append("DROP TEMPORARY TABLE "); built_non_trans_tmp_query.set_charset(system_charset_info); built_non_trans_tmp_query.append("DROP TEMPORARY TABLE "); } } for (table= tables; table; table= table->next_local) { bool is_trans= 0; bool table_creation_was_logged= 1; char *db=table->db; size_t db_length= table->db_length; handlerton *table_type= 0; DBUG_PRINT("table", ("table_l: '%s'.'%s' table: %p s: %p", table->db, table->table_name, table->table, table->table ? table->table->s : NULL)); /* If we are in locked tables mode and are dropping a temporary table, the ticket should be NULL to ensure that we don't release a lock on a base table later. */ DBUG_ASSERT(!(thd->locked_tables_mode && table->open_type != OT_BASE_ONLY && thd->find_temporary_table(table) && table->mdl_request.ticket != NULL)); if (table->open_type == OT_BASE_ONLY || !is_temporary_table(table)) error= 1; else { table_creation_was_logged= table->table->s->table_creation_was_logged; if (thd->drop_temporary_table(table->table, &is_trans, true)) { error= 1; goto err; } error= 0; table->table= 0; } if ((drop_temporary && if_exists) || !error) { /* This handles the case of temporary tables. We have the following cases: . "DROP TEMPORARY" was executed and a temporary table was affected (i.e. drop_temporary && !error) or the if_exists was specified (i.e. drop_temporary && if_exists). . "DROP" was executed but a temporary table was affected (.i.e !error). */ if (!dont_log_query && table_creation_was_logged) { /* If there is an error, we don't know the type of the engine at this point. So, we keep it in the trx-cache. */ is_trans= error ? TRUE : is_trans; if (is_trans) trans_tmp_table_deleted= TRUE; else non_trans_tmp_table_deleted= TRUE; String *built_ptr_query= (is_trans ? &built_trans_tmp_query : &built_non_trans_tmp_query); /* Write the database name if it is not the current one or if thd->db is NULL or 'IF EXISTS' clause is present in 'DROP TEMPORARY' query. */ if (thd->db == NULL || strcmp(db,thd->db) != 0 || is_drop_tmp_if_exists_added ) { append_identifier(thd, built_ptr_query, db, db_length); built_ptr_query->append("."); } append_identifier(thd, built_ptr_query, table->table_name, table->table_name_length); built_ptr_query->append(","); } /* This means that a temporary table was droped and as such there is no need to proceed with the code that tries to drop a regular table. */ if (!error) continue; } else if (!drop_temporary) { non_temp_tables_count++; DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE, table->db, table->table_name, MDL_SHARED)); alias= (lower_case_table_names == 2) ? table->alias : table->table_name; /* remove .frm file and engine files */ path_length= build_table_filename(path, sizeof(path) - 1, db, alias, reg_ext, 0); /* This handles the case where a "DROP" was executed and a regular table "may be" dropped as drop_temporary is FALSE and error is TRUE. If the error was FALSE a temporary table was dropped and regardless of the status of drop_temporary a "DROP TEMPORARY" must be used. */ if (!dont_log_query) { /* Note that unless if_exists is TRUE or a temporary table was deleted, there is no means to know if the statement should be written to the binary log. See further information on this variable in what follows. */ non_tmp_table_deleted= (if_exists ? TRUE : non_tmp_table_deleted); /* Don't write the database name if it is the current one (or if thd->db is NULL). */ if (thd->db == NULL || strcmp(db,thd->db) != 0) { append_identifier(thd, &built_query, db, db_length); built_query.append("."); } append_identifier(thd, &built_query, table->table_name, table->table_name_length); built_query.append(","); } } DEBUG_SYNC(thd, "rm_table_no_locks_before_delete_table"); error= 0; if (drop_temporary || (ha_table_exists(thd, db, alias, &table_type) == 0 && table_type == 0) || (!drop_view && (was_view= (table_type == view_pseudo_hton)))) { /* One of the following cases happened: . "DROP TEMPORARY" but a temporary table was not found. . "DROP" but table was not found . "DROP TABLE" statement, but it's a view. */ if (if_exists) { char buff[FN_REFLEN]; String tbl_name(buff, sizeof(buff), system_charset_info); tbl_name.length(0); tbl_name.append(db); tbl_name.append('.'); tbl_name.append(table->table_name); push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_BAD_TABLE_ERROR, ER_THD(thd, ER_BAD_TABLE_ERROR), tbl_name.c_ptr_safe()); } else { non_tmp_error = (drop_temporary ? non_tmp_error : TRUE); error= 1; } } else { char *end; /* It could happen that table's share in the table definition cache is the only thing that keeps the engine plugin loaded (if it is uninstalled and waits for the ref counter to drop to 0). In this case, the tdc_remove_table() below will release and unload the plugin. And ha_delete_table() will get a dangling pointer. Let's lock the plugin till the end of the statement. */ if (table_type && table_type != view_pseudo_hton) ha_lock_engine(thd, table_type); if (thd->locked_tables_mode == LTM_LOCK_TABLES || thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) { if (wait_while_table_is_used(thd, table->table, HA_EXTRA_NOT_USED)) { error= -1; goto err; } /* the following internally does TDC_RT_REMOVE_ALL */ close_all_tables_for_name(thd, table->table->s, HA_EXTRA_PREPARE_FOR_DROP, NULL); table->table= 0; } else tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table->db, table->table_name, false); /* Check that we have an exclusive lock on the table to be dropped. */ DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE, table->db, table->table_name, MDL_EXCLUSIVE)); // Remove extension for delete *(end= path + path_length - reg_ext_length)= '\0'; error= ha_delete_table(thd, table_type, path, db, table->table_name, !dont_log_query); if (!error) { int frm_delete_error, trigger_drop_error= 0; /* Delete the table definition file */ strmov(end,reg_ext); if (table_type && table_type != view_pseudo_hton && table_type->discover_table) { /* Table type is using discovery and may not need a .frm file. Delete it silently if it exists */ (void) mysql_file_delete(key_file_frm, path, MYF(0)); frm_delete_error= 0; } else frm_delete_error= mysql_file_delete(key_file_frm, path, MYF(MY_WME)); if (frm_delete_error) frm_delete_error= my_errno; else { non_tmp_table_deleted= TRUE; trigger_drop_error= Table_triggers_list::drop_all_triggers(thd, db, table->table_name); } if (trigger_drop_error || (frm_delete_error && frm_delete_error != ENOENT)) error= 1; else if (frm_delete_error && if_exists) thd->clear_error(); } non_tmp_error|= MY_TEST(error); } if (error) { if (wrong_tables.length()) wrong_tables.append(','); wrong_tables.append(db); wrong_tables.append('.'); wrong_tables.append(table->table_name); errors++; } else { PSI_CALL_drop_table_share(false, table->db, table->db_length, table->table_name, table->table_name_length); mysql_audit_drop_table(thd, table); } DBUG_PRINT("table", ("table: %p s: %p", table->table, table->table ? table->table->s : NULL)); } DEBUG_SYNC(thd, "rm_table_no_locks_before_binlog"); thd->thread_specific_used|= (trans_tmp_table_deleted || non_trans_tmp_table_deleted); error= 0; err: if (wrong_tables.length()) { DBUG_ASSERT(errors); if (errors == 1 && was_view) my_error(ER_IT_IS_A_VIEW, MYF(0), wrong_tables.c_ptr_safe()); else if (errors > 1 || !thd->is_error()) my_error(ER_BAD_TABLE_ERROR, MYF(0), wrong_tables.c_ptr_safe()); error= 1; } /* We are always logging drop of temporary tables. The reason is to handle the following case: - Use statement based replication - CREATE TEMPORARY TABLE foo (logged) - set row based replication - DROP TEMPORAY TABLE foo (needs to be logged) This should be fixed so that we remember if creation of the temporary table was logged and only log it if the creation was logged. */ if (non_trans_tmp_table_deleted || trans_tmp_table_deleted || non_tmp_table_deleted) { if (non_trans_tmp_table_deleted || trans_tmp_table_deleted) thd->transaction.stmt.mark_dropped_temp_table(); query_cache_invalidate3(thd, tables, 0); if (!dont_log_query && mysql_bin_log.is_open()) { if (non_trans_tmp_table_deleted) { /* Chop of the last comma */ built_non_trans_tmp_query.chop(); built_non_trans_tmp_query.append(" /* generated by server */"); #ifdef WITH_WSREP thd->wsrep_skip_wsrep_GTID = true; #endif /* WITH_WSREP */ error |= thd->binlog_query(THD::STMT_QUERY_TYPE, built_non_trans_tmp_query.ptr(), built_non_trans_tmp_query.length(), FALSE, FALSE, is_drop_tmp_if_exists_added, 0); } if (trans_tmp_table_deleted) { /* Chop of the last comma */ built_trans_tmp_query.chop(); built_trans_tmp_query.append(" /* generated by server */"); #ifdef WITH_WSREP thd->wsrep_skip_wsrep_GTID = true; #endif /* WITH_WSREP */ error |= thd->binlog_query(THD::STMT_QUERY_TYPE, built_trans_tmp_query.ptr(), built_trans_tmp_query.length(), TRUE, FALSE, is_drop_tmp_if_exists_added, 0); } if (non_tmp_table_deleted) { /* Chop of the last comma */ built_query.chop(); built_query.append(" /* generated by server */"); int error_code = non_tmp_error ? thd->get_stmt_da()->sql_errno() : 0; #ifdef WITH_WSREP thd->wsrep_skip_wsrep_GTID = false; #endif /* WITH_WSREP */ error |= thd->binlog_query(THD::STMT_QUERY_TYPE, built_query.ptr(), built_query.length(), TRUE, FALSE, FALSE, error_code); } } } if (!drop_temporary) { /* Under LOCK TABLES we should release meta-data locks on the tables which were dropped. Leave LOCK TABLES mode if we managed to drop all tables which were locked. Additional check for 'non_temp_tables_count' is to avoid leaving LOCK TABLES mode if we have dropped only temporary tables. */ if (thd->locked_tables_mode) { if (thd->lock && thd->lock->table_count == 0 && non_temp_tables_count > 0 && !dont_free_locks) { thd->locked_tables_list.unlock_locked_tables(thd); goto end; } for (table= tables; table; table= table->next_local) { /* Drop locks for all successfully dropped tables. */ if (table->table == NULL && table->mdl_request.ticket) { /* Under LOCK TABLES we may have several instances of table open and locked and therefore have to remove several metadata lock requests associated with them. */ thd->mdl_context.release_all_locks_for_name(table->mdl_request.ticket); } } } /* Rely on the caller to implicitly commit the transaction and release metadata locks. */ } end: #ifdef WITH_WSREP thd->wsrep_skip_wsrep_GTID = false; #endif /* WITH_WSREP */ DBUG_RETURN(error); } /** Log the drop of a table. @param thd Thread handler @param db_name Database name @param table_name Table name @param temporary_table 1 if table was a temporary table This code is only used in the case of failed CREATE OR REPLACE TABLE when the original table was dropped but we could not create the new one. */ bool log_drop_table(THD *thd, const char *db_name, size_t db_name_length, const char *table_name, size_t table_name_length, bool temporary_table) { char buff[NAME_LEN*2 + 80]; String query(buff, sizeof(buff), system_charset_info); bool error; DBUG_ENTER("log_drop_table"); if (!mysql_bin_log.is_open()) DBUG_RETURN(0); query.length(0); query.append(STRING_WITH_LEN("DROP ")); if (temporary_table) query.append(STRING_WITH_LEN("TEMPORARY ")); query.append(STRING_WITH_LEN("TABLE IF EXISTS ")); append_identifier(thd, &query, db_name, db_name_length); query.append("."); append_identifier(thd, &query, table_name, table_name_length); query.append(STRING_WITH_LEN("/* Generated to handle " "failed CREATE OR REPLACE */")); error= thd->binlog_query(THD::STMT_QUERY_TYPE, query.ptr(), query.length(), FALSE, FALSE, temporary_table, 0); DBUG_RETURN(error); } /** Quickly remove a table. @param thd Thread context. @param base The handlerton handle. @param db The database name. @param table_name The table name. @param flags Flags for build_table_filename() as well as describing if handler files / .FRM should be deleted as well. @return False in case of success, True otherwise. */ bool quick_rm_table(THD *thd, handlerton *base, const char *db, const char *table_name, uint flags, const char *table_path) { char path[FN_REFLEN + 1]; bool error= 0; DBUG_ENTER("quick_rm_table"); size_t path_length= table_path ? (strxnmov(path, sizeof(path) - 1, table_path, reg_ext, NullS) - path) : build_table_filename(path, sizeof(path)-1, db, table_name, reg_ext, flags); if (mysql_file_delete(key_file_frm, path, MYF(0))) error= 1; /* purecov: inspected */ path[path_length - reg_ext_length]= '\0'; // Remove reg_ext if (flags & NO_HA_TABLE) { handler *file= get_new_handler((TABLE_SHARE*) 0, thd->mem_root, base); if (!file) DBUG_RETURN(true); (void) file->ha_create_partitioning_metadata(path, NULL, CHF_DELETE_FLAG); delete file; } if (!(flags & (FRM_ONLY|NO_HA_TABLE))) error|= ha_delete_table(current_thd, base, path, db, table_name, 0); if (likely(error == 0)) { PSI_CALL_drop_table_share(flags & FN_IS_TMP, db, strlen(db), table_name, strlen(table_name)); } DBUG_RETURN(error); } /* Sort keys in the following order: - PRIMARY KEY - UNIQUE keys where all column are NOT NULL - UNIQUE keys that don't contain partial segments - Other UNIQUE keys - Normal keys - Fulltext keys This will make checking for duplicated keys faster and ensure that PRIMARY keys are prioritized. */ static int sort_keys(KEY *a, KEY *b) { ulong a_flags= a->flags, b_flags= b->flags; if (a_flags & HA_NOSAME) { if (!(b_flags & HA_NOSAME)) return -1; if ((a_flags ^ b_flags) & HA_NULL_PART_KEY) { /* Sort NOT NULL keys before other keys */ return (a_flags & HA_NULL_PART_KEY) ? 1 : -1; } if (a->name == primary_key_name) return -1; if (b->name == primary_key_name) return 1; /* Sort keys don't containing partial segments before others */ if ((a_flags ^ b_flags) & HA_KEY_HAS_PART_KEY_SEG) return (a_flags & HA_KEY_HAS_PART_KEY_SEG) ? 1 : -1; } else if (b_flags & HA_NOSAME) return 1; // Prefer b if ((a_flags ^ b_flags) & HA_FULLTEXT) { return (a_flags & HA_FULLTEXT) ? 1 : -1; } /* Prefer original key order. usable_key_parts contains here the original key position. */ return ((a->usable_key_parts < b->usable_key_parts) ? -1 : (a->usable_key_parts > b->usable_key_parts) ? 1 : 0); } /* Check TYPELIB (set or enum) for duplicates SYNOPSIS check_duplicates_in_interval() set_or_name "SET" or "ENUM" string for warning message name name of the checked column typelib list of values for the column dup_val_count returns count of duplicate elements DESCRIPTION This function prints an warning for each value in list which has some duplicates on its right RETURN VALUES 0 ok 1 Error */ bool check_duplicates_in_interval(const char *set_or_name, const char *name, TYPELIB *typelib, CHARSET_INFO *cs, unsigned int *dup_val_count) { TYPELIB tmp= *typelib; const char **cur_value= typelib->type_names; unsigned int *cur_length= typelib->type_lengths; *dup_val_count= 0; for ( ; tmp.count > 1; cur_value++, cur_length++) { tmp.type_names++; tmp.type_lengths++; tmp.count--; if (find_type2(&tmp, (const char*)*cur_value, *cur_length, cs)) { THD *thd= current_thd; ErrConvString err(*cur_value, *cur_length, cs); if (current_thd->is_strict_mode()) { my_error(ER_DUPLICATED_VALUE_IN_TYPE, MYF(0), name, err.ptr(), set_or_name); return 1; } push_warning_printf(thd,Sql_condition::WARN_LEVEL_NOTE, ER_DUPLICATED_VALUE_IN_TYPE, ER_THD(thd, ER_DUPLICATED_VALUE_IN_TYPE), name, err.ptr(), set_or_name); (*dup_val_count)++; } } return 0; } /* Check TYPELIB (set or enum) max and total lengths SYNOPSIS calculate_interval_lengths() cs charset+collation pair of the interval typelib list of values for the column max_length length of the longest item tot_length sum of the item lengths DESCRIPTION After this function call: - ENUM uses max_length - SET uses tot_length. RETURN VALUES void */ void calculate_interval_lengths(CHARSET_INFO *cs, TYPELIB *interval, uint32 *max_length, uint32 *tot_length) { const char **pos; uint *len; *max_length= *tot_length= 0; for (pos= interval->type_names, len= interval->type_lengths; *pos ; pos++, len++) { size_t length= cs->cset->numchars(cs, *pos, *pos + *len); *tot_length+= length; set_if_bigger(*max_length, (uint32)length); } } /* Prepare a create_table instance for packing SYNOPSIS prepare_create_field() sql_field field to prepare for packing blob_columns count for BLOBs table_flags table flags DESCRIPTION This function prepares a Create_field instance. Fields such as pack_flag are valid after this call. RETURN VALUES 0 ok 1 Error */ int prepare_create_field(Column_definition *sql_field, uint *blob_columns, ulonglong table_flags) { uint dup_val_count; uint decimals= sql_field->decimals; DBUG_ENTER("prepare_create_field"); /* This code came from mysql_prepare_create_table. Indent preserved to make patching easier */ DBUG_ASSERT(sql_field->charset); switch (sql_field->sql_type) { case MYSQL_TYPE_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_LONG_BLOB: sql_field->pack_flag=FIELDFLAG_BLOB | pack_length_to_packflag(sql_field->pack_length - portable_sizeof_char_ptr); if (sql_field->charset->state & MY_CS_BINSORT) sql_field->pack_flag|=FIELDFLAG_BINARY; sql_field->length=8; // Unireg field length (*blob_columns)++; break; case MYSQL_TYPE_GEOMETRY: #ifdef HAVE_SPATIAL if (!(table_flags & HA_CAN_GEOMETRY)) { my_error(ER_CHECK_NOT_IMPLEMENTED, MYF(0), "GEOMETRY"); DBUG_RETURN(1); } sql_field->pack_flag=FIELDFLAG_GEOM | pack_length_to_packflag(sql_field->pack_length - portable_sizeof_char_ptr); if (sql_field->charset->state & MY_CS_BINSORT) sql_field->pack_flag|=FIELDFLAG_BINARY; sql_field->length=8; // Unireg field length (*blob_columns)++; break; #else my_error(ER_FEATURE_DISABLED, MYF(0), sym_group_geom.name, sym_group_geom.needed_define); DBUG_RETURN(1); #endif /*HAVE_SPATIAL*/ case MYSQL_TYPE_VARCHAR: #ifndef QQ_ALL_HANDLERS_SUPPORT_VARCHAR if (table_flags & HA_NO_VARCHAR) { /* convert VARCHAR to CHAR because handler is not yet up to date */ sql_field->sql_type= MYSQL_TYPE_VAR_STRING; sql_field->pack_length= calc_pack_length(sql_field->sql_type, (uint) sql_field->length); if ((sql_field->length / sql_field->charset->mbmaxlen) > MAX_FIELD_CHARLENGTH) { my_error(ER_TOO_BIG_FIELDLENGTH, MYF(0), sql_field->field_name, static_cast<ulong>(MAX_FIELD_CHARLENGTH)); DBUG_RETURN(1); } } #endif /* fall through */ case MYSQL_TYPE_STRING: sql_field->pack_flag=0; if (sql_field->charset->state & MY_CS_BINSORT) sql_field->pack_flag|=FIELDFLAG_BINARY; break; case MYSQL_TYPE_ENUM: sql_field->pack_flag=pack_length_to_packflag(sql_field->pack_length) | FIELDFLAG_INTERVAL; if (sql_field->charset->state & MY_CS_BINSORT) sql_field->pack_flag|=FIELDFLAG_BINARY; if (check_duplicates_in_interval("ENUM",sql_field->field_name, sql_field->interval, sql_field->charset, &dup_val_count)) DBUG_RETURN(1); break; case MYSQL_TYPE_SET: sql_field->pack_flag=pack_length_to_packflag(sql_field->pack_length) | FIELDFLAG_BITFIELD; if (sql_field->charset->state & MY_CS_BINSORT) sql_field->pack_flag|=FIELDFLAG_BINARY; if (check_duplicates_in_interval("SET",sql_field->field_name, sql_field->interval, sql_field->charset, &dup_val_count)) DBUG_RETURN(1); /* Check that count of unique members is not more then 64 */ if (sql_field->interval->count - dup_val_count > sizeof(longlong)*8) { my_error(ER_TOO_BIG_SET, MYF(0), sql_field->field_name); DBUG_RETURN(1); } break; case MYSQL_TYPE_DATE: // Rest of string types case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_TIME: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TIME2: case MYSQL_TYPE_DATETIME2: case MYSQL_TYPE_NULL: sql_field->pack_flag=f_settype((uint) sql_field->sql_type); break; case MYSQL_TYPE_BIT: /* We have sql_field->pack_flag already set here, see mysql_prepare_create_table(). */ break; case MYSQL_TYPE_NEWDECIMAL: sql_field->pack_flag=(FIELDFLAG_NUMBER | (sql_field->flags & UNSIGNED_FLAG ? 0 : FIELDFLAG_DECIMAL) | (sql_field->flags & ZEROFILL_FLAG ? FIELDFLAG_ZEROFILL : 0) | (decimals << FIELDFLAG_DEC_SHIFT)); break; case MYSQL_TYPE_FLOAT: case MYSQL_TYPE_DOUBLE: /* User specified FLOAT() or DOUBLE() without precision. Change to FLOATING_POINT_DECIMALS to keep things compatible with earlier MariaDB versions. */ if (decimals >= FLOATING_POINT_DECIMALS) decimals= FLOATING_POINT_DECIMALS; /* fall through */ case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_TIMESTAMP2: default: sql_field->pack_flag=(FIELDFLAG_NUMBER | (sql_field->flags & UNSIGNED_FLAG ? 0 : FIELDFLAG_DECIMAL) | (sql_field->flags & ZEROFILL_FLAG ? FIELDFLAG_ZEROFILL : 0) | f_settype((uint) sql_field->sql_type) | (decimals << FIELDFLAG_DEC_SHIFT)); break; } if (!(sql_field->flags & NOT_NULL_FLAG) || (sql_field->vcol_info)) /* Make virtual columns allow NULL values */ sql_field->pack_flag|= FIELDFLAG_MAYBE_NULL; if (sql_field->flags & NO_DEFAULT_VALUE_FLAG) sql_field->pack_flag|= FIELDFLAG_NO_DEFAULT; DBUG_RETURN(0); } /* Get character set from field object generated by parser using default values when not set. SYNOPSIS get_sql_field_charset() sql_field The sql_field object create_info Info generated by parser RETURN VALUES cs Character set */ CHARSET_INFO* get_sql_field_charset(Create_field *sql_field, HA_CREATE_INFO *create_info) { CHARSET_INFO *cs= sql_field->charset; if (!cs) cs= create_info->default_table_charset; /* table_charset is set only in ALTER TABLE t1 CONVERT TO CHARACTER SET csname if we want change character set for all varchar/char columns. But the table charset must not affect the BLOB fields, so don't allow to change my_charset_bin to somethig else. */ if (create_info->table_charset && cs != &my_charset_bin) cs= create_info->table_charset; return cs; } /** Modifies the first column definition whose SQL type is TIMESTAMP by adding the features DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP. If the first TIMESTAMP column appears to be nullable, or to have an explicit default, or to be a virtual column, then no promition is done. @param column_definitions The list of column definitions, in the physical order in which they appear in the table. */ void promote_first_timestamp_column(List<Create_field> *column_definitions) { List_iterator_fast<Create_field> it(*column_definitions); Create_field *column_definition; while ((column_definition= it++) != NULL) { if (is_timestamp_type(column_definition->sql_type) || // TIMESTAMP column_definition->unireg_check == Field::TIMESTAMP_OLD_FIELD) // Legacy { if ((column_definition->flags & NOT_NULL_FLAG) != 0 && // NOT NULL, column_definition->default_value == NULL && // no constant default, column_definition->unireg_check == Field::NONE && // no function default column_definition->vcol_info == NULL) { DBUG_PRINT("info", ("First TIMESTAMP column '%s' was promoted to " "DEFAULT CURRENT_TIMESTAMP ON UPDATE " "CURRENT_TIMESTAMP", column_definition->field_name )); column_definition->unireg_check= Field::TIMESTAMP_DNUN_FIELD; } return; } } } /** Check if there is a duplicate key. Report a warning for every duplicate key. @param thd Thread context. @param key Key to be checked. @param key_info Key meta-data info. @param key_list List of existing keys. */ static void check_duplicate_key(THD *thd, Key *key, KEY *key_info, List<Key> *key_list) { /* We only check for duplicate indexes if it is requested and the key is not auto-generated. Check is requested if the key was explicitly created or altered by the user (unless it's a foreign key). */ if (!key->key_create_info.check_for_duplicate_indexes || key->generated) return; List_iterator_fast<Key> key_list_iterator(*key_list); List_iterator_fast<Key_part_spec> key_column_iterator(key->columns); Key *k; while ((k= key_list_iterator++)) { // Looking for a similar key... if (k == key) break; if (k->generated || (key->type != k->type) || (key->key_create_info.algorithm != k->key_create_info.algorithm) || (key->columns.elements != k->columns.elements)) { // Keys are different. continue; } /* Keys 'key' and 'k' might be identical. Check that the keys have identical columns in the same order. */ List_iterator_fast<Key_part_spec> k_column_iterator(k->columns); bool all_columns_are_identical= true; key_column_iterator.rewind(); for (uint i= 0; i < key->columns.elements; ++i) { Key_part_spec *c1= key_column_iterator++; Key_part_spec *c2= k_column_iterator++; DBUG_ASSERT(c1 && c2); if (my_strcasecmp(system_charset_info, c1->field_name.str, c2->field_name.str) || (c1->length != c2->length)) { all_columns_are_identical= false; break; } } // Report a warning if we have two identical keys. if (all_columns_are_identical) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_DUP_INDEX, ER_THD(thd, ER_DUP_INDEX), key_info->name); break; } } } /* Preparation for table creation SYNOPSIS mysql_prepare_create_table() thd Thread object. create_info Create information (like MAX_ROWS). alter_info List of columns and indexes to create db_options INOUT Table options (like HA_OPTION_PACK_RECORD). file The handler for the new table. key_info_buffer OUT An array of KEY structs for the indexes. key_count OUT The number of elements in the array. create_table_mode C_ORDINARY_CREATE, C_ALTER_TABLE, C_CREATE_SELECT, C_ASSISTED_DISCOVERY DESCRIPTION Prepares the table and key structures for table creation. NOTES sets create_info->varchar if the table has a varchar RETURN VALUES FALSE OK TRUE error */ static int mysql_prepare_create_table(THD *thd, HA_CREATE_INFO *create_info, Alter_info *alter_info, uint *db_options, handler *file, KEY **key_info_buffer, uint *key_count, int create_table_mode) { const char *key_name; Create_field *sql_field,*dup_field; uint field,null_fields,blob_columns,max_key_length; ulong record_offset= 0; KEY *key_info; KEY_PART_INFO *key_part_info; int field_no,dup_no; int select_field_pos,auto_increment=0; List_iterator_fast<Create_field> it(alter_info->create_list); List_iterator<Create_field> it2(alter_info->create_list); uint total_uneven_bit_length= 0; int select_field_count= C_CREATE_SELECT(create_table_mode); bool tmp_table= create_table_mode == C_ALTER_TABLE; DBUG_ENTER("mysql_prepare_create_table"); LEX_STRING* connect_string = &create_info->connect_string; if (connect_string->length != 0 && connect_string->length > CONNECT_STRING_MAXLEN && (system_charset_info->cset->charpos(system_charset_info, connect_string->str, (connect_string->str + connect_string->length), CONNECT_STRING_MAXLEN) < connect_string->length)) { my_error(ER_WRONG_STRING_LENGTH, MYF(0), connect_string->str, "CONNECTION", CONNECT_STRING_MAXLEN); DBUG_RETURN(TRUE); } select_field_pos= alter_info->create_list.elements - select_field_count; null_fields=blob_columns=0; create_info->varchar= 0; max_key_length= file->max_key_length(); for (field_no=0; (sql_field=it++) ; field_no++) { CHARSET_INFO *save_cs; /* Initialize length from its original value (number of characters), which was set in the parser. This is necessary if we're executing a prepared statement for the second time. */ sql_field->length= sql_field->char_length; /* Set field charset. */ save_cs= sql_field->charset= get_sql_field_charset(sql_field, create_info); if ((sql_field->flags & BINCMP_FLAG) && !(sql_field->charset= find_bin_collation(sql_field->charset))) DBUG_RETURN(TRUE); if (sql_field->sql_type == MYSQL_TYPE_SET || sql_field->sql_type == MYSQL_TYPE_ENUM) { uint32 dummy; CHARSET_INFO *cs= sql_field->charset; TYPELIB *interval= sql_field->interval; /* Create typelib from interval_list, and if necessary convert strings from client character set to the column character set. */ if (!interval) { /* Create the typelib in runtime memory - we will free the occupied memory at the same time when we free this sql_field -- at the end of execution. */ interval= sql_field->interval= typelib(thd->mem_root, sql_field->interval_list); List_iterator<String> int_it(sql_field->interval_list); String conv, *tmp; char comma_buf[5]; /* 5 bytes for 'filename' charset */ DBUG_ASSERT(sizeof(comma_buf) >= cs->mbmaxlen); int comma_length= cs->cset->wc_mb(cs, ',', (uchar*) comma_buf, (uchar*) comma_buf + sizeof(comma_buf)); DBUG_ASSERT(comma_length > 0); for (uint i= 0; (tmp= int_it++); i++) { size_t lengthsp; if (String::needs_conversion(tmp->length(), tmp->charset(), cs, &dummy)) { uint cnv_errs; conv.copy(tmp->ptr(), tmp->length(), tmp->charset(), cs, &cnv_errs); interval->type_names[i]= strmake_root(thd->mem_root, conv.ptr(), conv.length()); interval->type_lengths[i]= conv.length(); } // Strip trailing spaces. lengthsp= cs->cset->lengthsp(cs, interval->type_names[i], interval->type_lengths[i]); interval->type_lengths[i]= lengthsp; ((uchar *)interval->type_names[i])[lengthsp]= '\0'; if (sql_field->sql_type == MYSQL_TYPE_SET) { if (cs->coll->instr(cs, interval->type_names[i], interval->type_lengths[i], comma_buf, comma_length, NULL, 0)) { ErrConvString err(tmp->ptr(), tmp->length(), cs); my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "set", err.ptr()); DBUG_RETURN(TRUE); } } } sql_field->interval_list.empty(); // Don't need interval_list anymore } if (sql_field->sql_type == MYSQL_TYPE_SET) { uint32 field_length; calculate_interval_lengths(cs, interval, &dummy, &field_length); sql_field->length= field_length + (interval->count - 1); } else /* MYSQL_TYPE_ENUM */ { uint32 field_length; DBUG_ASSERT(sql_field->sql_type == MYSQL_TYPE_ENUM); calculate_interval_lengths(cs, interval, &field_length, &dummy); sql_field->length= field_length; } set_if_smaller(sql_field->length, MAX_FIELD_WIDTH-1); } if (sql_field->sql_type == MYSQL_TYPE_BIT) { sql_field->pack_flag= FIELDFLAG_NUMBER; if (file->ha_table_flags() & HA_CAN_BIT_FIELD) total_uneven_bit_length+= sql_field->length & 7; else sql_field->pack_flag|= FIELDFLAG_TREAT_BIT_AS_CHAR; } sql_field->create_length_to_internal_length(); if (prepare_blob_field(thd, sql_field)) DBUG_RETURN(TRUE); /* Convert the default value from client character set into the column character set if necessary. We can only do this for constants as we have not yet run fix_fields. */ if (sql_field->default_value && sql_field->default_value->expr->basic_const_item() && save_cs != sql_field->default_value->expr->collation.collation && (sql_field->sql_type == MYSQL_TYPE_VAR_STRING || sql_field->sql_type == MYSQL_TYPE_STRING || sql_field->sql_type == MYSQL_TYPE_SET || sql_field->sql_type == MYSQL_TYPE_TINY_BLOB || sql_field->sql_type == MYSQL_TYPE_MEDIUM_BLOB || sql_field->sql_type == MYSQL_TYPE_LONG_BLOB || sql_field->sql_type == MYSQL_TYPE_BLOB || sql_field->sql_type == MYSQL_TYPE_ENUM)) { Item *item; if (!(item= sql_field->default_value->expr-> safe_charset_converter(thd, save_cs))) { /* Could not convert */ my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); DBUG_RETURN(TRUE); } /* Fix for prepare statement */ thd->change_item_tree(&sql_field->default_value->expr, item); } if (sql_field->default_value && sql_field->default_value->expr->basic_const_item() && (sql_field->sql_type == MYSQL_TYPE_SET || sql_field->sql_type == MYSQL_TYPE_ENUM)) { StringBuffer<MAX_FIELD_WIDTH> str; String *def= sql_field->default_value->expr->val_str(&str); bool not_found; if (def == NULL) /* SQL "NULL" maps to NULL */ { not_found= sql_field->flags & NOT_NULL_FLAG; } else { not_found= false; if (sql_field->sql_type == MYSQL_TYPE_SET) { char *not_used; uint not_used2; find_set(sql_field->interval, def->ptr(), def->length(), sql_field->charset, &not_used, &not_used2, &not_found); } else /* MYSQL_TYPE_ENUM */ { def->length(sql_field->charset->cset->lengthsp(sql_field->charset, def->ptr(), def->length())); not_found= !find_type2(sql_field->interval, def->ptr(), def->length(), sql_field->charset); } } if (not_found) { my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); DBUG_RETURN(TRUE); } } if (!(sql_field->flags & NOT_NULL_FLAG)) null_fields++; if (check_column_name(sql_field->field_name)) { my_error(ER_WRONG_COLUMN_NAME, MYF(0), sql_field->field_name); DBUG_RETURN(TRUE); } /* Check if we have used the same field name before */ for (dup_no=0; (dup_field=it2++) != sql_field; dup_no++) { if (my_strcasecmp(system_charset_info, sql_field->field_name, dup_field->field_name) == 0) { /* If this was a CREATE ... SELECT statement, accept a field redefinition if we are changing a field in the SELECT part */ if (field_no < select_field_pos || dup_no >= select_field_pos) { my_error(ER_DUP_FIELDNAME, MYF(0), sql_field->field_name); DBUG_RETURN(TRUE); } else { /* Field redefined */ /* If we are replacing a BIT field, revert the increment of total_uneven_bit_length that was done above. */ if (sql_field->sql_type == MYSQL_TYPE_BIT && file->ha_table_flags() & HA_CAN_BIT_FIELD) total_uneven_bit_length-= sql_field->length & 7; sql_field->default_value= dup_field->default_value; sql_field->sql_type= dup_field->sql_type; /* If we are replacing a field with a BIT field, we need to initialize pack_flag. Note that we do not need to increment total_uneven_bit_length here as this dup_field has already been processed. */ if (sql_field->sql_type == MYSQL_TYPE_BIT) { sql_field->pack_flag= FIELDFLAG_NUMBER; if (!(file->ha_table_flags() & HA_CAN_BIT_FIELD)) sql_field->pack_flag|= FIELDFLAG_TREAT_BIT_AS_CHAR; } sql_field->charset= (dup_field->charset ? dup_field->charset : create_info->default_table_charset); sql_field->length= dup_field->char_length; sql_field->pack_length= dup_field->pack_length; sql_field->key_length= dup_field->key_length; sql_field->decimals= dup_field->decimals; sql_field->unireg_check= dup_field->unireg_check; /* We're making one field from two, the result field will have dup_field->flags as flags. If we've incremented null_fields because of sql_field->flags, decrement it back. */ if (!(sql_field->flags & NOT_NULL_FLAG)) null_fields--; sql_field->flags= dup_field->flags; sql_field->create_length_to_internal_length(); sql_field->interval= dup_field->interval; sql_field->vcol_info= dup_field->vcol_info; it2.remove(); // Remove first (create) definition select_field_pos--; break; } } } /* Don't pack rows in old tables if the user has requested this */ if ((sql_field->flags & BLOB_FLAG) || (sql_field->sql_type == MYSQL_TYPE_VARCHAR && create_info->row_type != ROW_TYPE_FIXED)) (*db_options)|= HA_OPTION_PACK_RECORD; it2.rewind(); } /* record_offset will be increased with 'length-of-null-bits' later */ record_offset= 0; null_fields+= total_uneven_bit_length; it.rewind(); while ((sql_field=it++)) { DBUG_ASSERT(sql_field->charset != 0); if (prepare_create_field(sql_field, &blob_columns, file->ha_table_flags())) DBUG_RETURN(TRUE); if (sql_field->sql_type == MYSQL_TYPE_VARCHAR) create_info->varchar= TRUE; sql_field->offset= record_offset; if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER) auto_increment++; if (parse_option_list(thd, create_info->db_type, &sql_field->option_struct, &sql_field->option_list, create_info->db_type->field_options, FALSE, thd->mem_root)) DBUG_RETURN(TRUE); /* For now skip fields that are not physically stored in the database (virtual fields) and update their offset later (see the next loop). */ if (sql_field->stored_in_db()) record_offset+= sql_field->pack_length; } /* Update virtual fields' offset*/ it.rewind(); while ((sql_field=it++)) { if (!sql_field->stored_in_db()) { sql_field->offset= record_offset; record_offset+= sql_field->pack_length; } } if (auto_increment > 1) { my_message(ER_WRONG_AUTO_KEY, ER_THD(thd, ER_WRONG_AUTO_KEY), MYF(0)); DBUG_RETURN(TRUE); } if (auto_increment && (file->ha_table_flags() & HA_NO_AUTO_INCREMENT)) { my_error(ER_TABLE_CANT_HANDLE_AUTO_INCREMENT, MYF(0), file->table_type()); DBUG_RETURN(TRUE); } if (blob_columns && (file->ha_table_flags() & HA_NO_BLOBS)) { my_error(ER_TABLE_CANT_HANDLE_BLOB, MYF(0), file->table_type()); DBUG_RETURN(TRUE); } /* CREATE TABLE[with auto_increment column] SELECT is unsafe as the rows inserted in the created table depends on the order of the rows fetched from the select tables. This order may differ on master and slave. We therefore mark it as unsafe. */ if (select_field_count > 0 && auto_increment) thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_CREATE_SELECT_AUTOINC); /* Create keys */ List_iterator<Key> key_iterator(alter_info->key_list); List_iterator<Key> key_iterator2(alter_info->key_list); uint key_parts=0, fk_key_count=0; bool primary_key=0,unique_key=0; Key *key, *key2; uint tmp, key_number; /* special marker for keys to be ignored */ static char ignore_key[1]; /* Calculate number of key segements */ *key_count= 0; while ((key=key_iterator++)) { DBUG_PRINT("info", ("key name: '%s' type: %d", key->name.str ? key->name.str : "(none)" , key->type)); if (key->type == Key::FOREIGN_KEY) { fk_key_count++; if (((Foreign_key *)key)->validate(alter_info->create_list)) DBUG_RETURN(TRUE); Foreign_key *fk_key= (Foreign_key*) key; if (fk_key->ref_columns.elements && fk_key->ref_columns.elements != fk_key->columns.elements) { my_error(ER_WRONG_FK_DEF, MYF(0), (fk_key->name.str ? fk_key->name.str : "foreign key without name"), ER_THD(thd, ER_KEY_REF_DO_NOT_MATCH_TABLE_REF)); DBUG_RETURN(TRUE); } continue; } (*key_count)++; tmp=file->max_key_parts(); if (key->columns.elements > tmp) { my_error(ER_TOO_MANY_KEY_PARTS,MYF(0),tmp); DBUG_RETURN(TRUE); } if (check_ident_length(&key->name)) DBUG_RETURN(TRUE); key_iterator2.rewind (); if (key->type != Key::FOREIGN_KEY) { while ((key2 = key_iterator2++) != key) { /* foreign_key_prefix(key, key2) returns 0 if key or key2, or both, is 'generated', and a generated key is a prefix of the other key. Then we do not need the generated shorter key. */ if ((key2->type != Key::FOREIGN_KEY && key2->name.str != ignore_key && !foreign_key_prefix(key, key2))) { /* TODO: issue warning message */ /* mark that the generated key should be ignored */ if (!key2->generated || (key->generated && key->columns.elements < key2->columns.elements)) key->name.str= ignore_key; else { key2->name.str= ignore_key; key_parts-= key2->columns.elements; (*key_count)--; } break; } } } if (key->name.str != ignore_key) key_parts+=key->columns.elements; else (*key_count)--; if (key->name.str && !tmp_table && (key->type != Key::PRIMARY) && !my_strcasecmp(system_charset_info, key->name.str, primary_key_name)) { my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key->name.str); DBUG_RETURN(TRUE); } } tmp=file->max_keys(); if (*key_count > tmp) { my_error(ER_TOO_MANY_KEYS,MYF(0),tmp); DBUG_RETURN(TRUE); } (*key_info_buffer)= key_info= (KEY*) thd->calloc(sizeof(KEY) * (*key_count)); key_part_info=(KEY_PART_INFO*) thd->calloc(sizeof(KEY_PART_INFO)*key_parts); if (!*key_info_buffer || ! key_part_info) DBUG_RETURN(TRUE); // Out of memory key_iterator.rewind(); key_number=0; for (; (key=key_iterator++) ; key_number++) { uint key_length=0; Key_part_spec *column; if (key->name.str == ignore_key) { /* ignore redundant keys */ do key=key_iterator++; while (key && key->name.str == ignore_key); if (!key) break; } switch (key->type) { case Key::MULTIPLE: key_info->flags= 0; break; case Key::FULLTEXT: key_info->flags= HA_FULLTEXT; if ((key_info->parser_name= &key->key_create_info.parser_name)->str) key_info->flags|= HA_USES_PARSER; else key_info->parser_name= 0; break; case Key::SPATIAL: #ifdef HAVE_SPATIAL key_info->flags= HA_SPATIAL; break; #else my_error(ER_FEATURE_DISABLED, MYF(0), sym_group_geom.name, sym_group_geom.needed_define); DBUG_RETURN(TRUE); #endif case Key::FOREIGN_KEY: key_number--; // Skip this key continue; default: key_info->flags = HA_NOSAME; break; } if (key->generated) key_info->flags|= HA_GENERATED_KEY; key_info->user_defined_key_parts=(uint8) key->columns.elements; key_info->key_part=key_part_info; key_info->usable_key_parts= key_number; key_info->algorithm= key->key_create_info.algorithm; key_info->option_list= key->option_list; if (parse_option_list(thd, create_info->db_type, &key_info->option_struct, &key_info->option_list, create_info->db_type->index_options, FALSE, thd->mem_root)) DBUG_RETURN(TRUE); if (key->type == Key::FULLTEXT) { if (!(file->ha_table_flags() & HA_CAN_FULLTEXT)) { my_error(ER_TABLE_CANT_HANDLE_FT, MYF(0), file->table_type()); DBUG_RETURN(TRUE); } } /* Make SPATIAL to be RTREE by default SPATIAL only on BLOB or at least BINARY, this actually should be replaced by special GEOM type in near future when new frm file is ready checking for proper key parts number: */ /* TODO: Add proper checks if handler supports key_type and algorithm */ if (key_info->flags & HA_SPATIAL) { if (!(file->ha_table_flags() & HA_CAN_RTREEKEYS)) { my_error(ER_TABLE_CANT_HANDLE_SPKEYS, MYF(0), file->table_type()); DBUG_RETURN(TRUE); } if (key_info->user_defined_key_parts != 1) { my_error(ER_WRONG_ARGUMENTS, MYF(0), "SPATIAL INDEX"); DBUG_RETURN(TRUE); } } else if (key_info->algorithm == HA_KEY_ALG_RTREE) { #ifdef HAVE_RTREE_KEYS if ((key_info->user_defined_key_parts & 1) == 1) { my_error(ER_WRONG_ARGUMENTS, MYF(0), "RTREE INDEX"); DBUG_RETURN(TRUE); } /* TODO: To be deleted */ my_error(ER_NOT_SUPPORTED_YET, MYF(0), "RTREE INDEX"); DBUG_RETURN(TRUE); #else my_error(ER_FEATURE_DISABLED, MYF(0), sym_group_rtree.name, sym_group_rtree.needed_define); DBUG_RETURN(TRUE); #endif } /* Take block size from key part or table part */ /* TODO: Add warning if block size changes. We can't do it here, as this may depend on the size of the key */ key_info->block_size= (key->key_create_info.block_size ? key->key_create_info.block_size : create_info->key_block_size); if (key_info->block_size) key_info->flags|= HA_USES_BLOCK_SIZE; List_iterator<Key_part_spec> cols(key->columns), cols2(key->columns); CHARSET_INFO *ft_key_charset=0; // for FULLTEXT for (uint column_nr=0 ; (column=cols++) ; column_nr++) { Key_part_spec *dup_column; it.rewind(); field=0; while ((sql_field=it++) && my_strcasecmp(system_charset_info, column->field_name.str, sql_field->field_name)) field++; if (!sql_field) { my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), column->field_name.str); DBUG_RETURN(TRUE); } while ((dup_column= cols2++) != column) { if (!my_strcasecmp(system_charset_info, column->field_name.str, dup_column->field_name.str)) { my_error(ER_DUP_FIELDNAME, MYF(0), column->field_name.str); DBUG_RETURN(TRUE); } } cols2.rewind(); if (key->type == Key::FULLTEXT) { if ((sql_field->sql_type != MYSQL_TYPE_STRING && sql_field->sql_type != MYSQL_TYPE_VARCHAR && !f_is_blob(sql_field->pack_flag)) || sql_field->charset == &my_charset_bin || sql_field->charset->mbminlen > 1 || // ucs2 doesn't work yet (ft_key_charset && sql_field->charset != ft_key_charset)) { my_error(ER_BAD_FT_COLUMN, MYF(0), column->field_name.str); DBUG_RETURN(-1); } ft_key_charset=sql_field->charset; /* for fulltext keys keyseg length is 1 for blobs (it's ignored in ft code anyway, and 0 (set to column width later) for char's. it has to be correct col width for char's, as char data are not prefixed with length (unlike blobs, where ft code takes data length from a data prefix, ignoring column->length). */ column->length= MY_TEST(f_is_blob(sql_field->pack_flag)); } else { column->length*= sql_field->charset->mbmaxlen; if (key->type == Key::SPATIAL) { if (column->length) { my_error(ER_WRONG_SUB_KEY, MYF(0)); DBUG_RETURN(TRUE); } if (!f_is_geom(sql_field->pack_flag)) { my_error(ER_WRONG_ARGUMENTS, MYF(0), "SPATIAL INDEX"); DBUG_RETURN(TRUE); } } if (f_is_blob(sql_field->pack_flag) || (f_is_geom(sql_field->pack_flag) && key->type != Key::SPATIAL)) { if (!(file->ha_table_flags() & HA_CAN_INDEX_BLOBS)) { my_error(ER_BLOB_USED_AS_KEY, MYF(0), column->field_name.str, file->table_type()); DBUG_RETURN(TRUE); } if (f_is_geom(sql_field->pack_flag) && sql_field->geom_type == Field::GEOM_POINT) column->length= MAX_LEN_GEOM_POINT_FIELD; if (!column->length) { my_error(ER_BLOB_KEY_WITHOUT_LENGTH, MYF(0), column->field_name.str); DBUG_RETURN(TRUE); } } #ifdef HAVE_SPATIAL if (key->type == Key::SPATIAL) { if (!column->length) { /* 4 is: (Xmin,Xmax,Ymin,Ymax), this is for 2D case Lately we'll extend this code to support more dimensions */ column->length= 4*sizeof(double); } } #endif if (sql_field->vcol_info) { if (key->type == Key::PRIMARY) { my_error(ER_PRIMARY_KEY_BASED_ON_GENERATED_COLUMN, MYF(0)); DBUG_RETURN(TRUE); } if (sql_field->vcol_info->flags & VCOL_NOT_STRICTLY_DETERMINISTIC) { /* use check_expression() to report an error */ check_expression(sql_field->vcol_info, sql_field->field_name, VCOL_GENERATED_STORED); DBUG_ASSERT(thd->is_error()); DBUG_RETURN(TRUE); } } if (!(sql_field->flags & NOT_NULL_FLAG)) { if (key->type == Key::PRIMARY) { /* Implicitly set primary key fields to NOT NULL for ISO conf. */ sql_field->flags|= NOT_NULL_FLAG; sql_field->pack_flag&= ~FIELDFLAG_MAYBE_NULL; null_fields--; } else { key_info->flags|= HA_NULL_PART_KEY; if (!(file->ha_table_flags() & HA_NULL_IN_KEY)) { my_error(ER_NULL_COLUMN_IN_INDEX, MYF(0), column->field_name.str); DBUG_RETURN(TRUE); } if (key->type == Key::SPATIAL) { my_message(ER_SPATIAL_CANT_HAVE_NULL, ER_THD(thd, ER_SPATIAL_CANT_HAVE_NULL), MYF(0)); DBUG_RETURN(TRUE); } } } if (MTYP_TYPENR(sql_field->unireg_check) == Field::NEXT_NUMBER) { if (column_nr == 0 || (file->ha_table_flags() & HA_AUTO_PART_KEY)) auto_increment--; // Field is used } } key_part_info->fieldnr= field; key_part_info->offset= (uint16) sql_field->offset; key_part_info->key_type=sql_field->pack_flag; uint key_part_length= sql_field->key_length; if (column->length) { if (f_is_blob(sql_field->pack_flag)) { key_part_length= MY_MIN(column->length, blob_length_by_type(sql_field->sql_type) * sql_field->charset->mbmaxlen); if (key_part_length > max_key_length || key_part_length > file->max_key_part_length()) { key_part_length= MY_MIN(max_key_length, file->max_key_part_length()); if (key->type == Key::MULTIPLE) { /* not a critical problem */ push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_TOO_LONG_KEY, ER_THD(thd, ER_TOO_LONG_KEY), key_part_length); /* Align key length to multibyte char boundary */ key_part_length-= key_part_length % sql_field->charset->mbmaxlen; } else { my_error(ER_TOO_LONG_KEY, MYF(0), key_part_length); DBUG_RETURN(TRUE); } } } // Catch invalid use of partial keys else if (!f_is_geom(sql_field->pack_flag) && // is the key partial? column->length != key_part_length && // is prefix length bigger than field length? (column->length > key_part_length || // can the field have a partial key? !Field::type_can_have_key_part (sql_field->sql_type) || // a packed field can't be used in a partial key f_is_packed(sql_field->pack_flag) || // does the storage engine allow prefixed search? ((file->ha_table_flags() & HA_NO_PREFIX_CHAR_KEYS) && // and is this a 'unique' key? (key_info->flags & HA_NOSAME)))) { my_message(ER_WRONG_SUB_KEY, ER_THD(thd, ER_WRONG_SUB_KEY), MYF(0)); DBUG_RETURN(TRUE); } else if (!(file->ha_table_flags() & HA_NO_PREFIX_CHAR_KEYS)) key_part_length= column->length; } else if (key_part_length == 0 && (sql_field->flags & NOT_NULL_FLAG)) { my_error(ER_WRONG_KEY_COLUMN, MYF(0), file->table_type(), column->field_name.str); DBUG_RETURN(TRUE); } if (key_part_length > file->max_key_part_length() && key->type != Key::FULLTEXT) { key_part_length= file->max_key_part_length(); if (key->type == Key::MULTIPLE) { /* not a critical problem */ push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_TOO_LONG_KEY, ER_THD(thd, ER_TOO_LONG_KEY), key_part_length); /* Align key length to multibyte char boundary */ key_part_length-= key_part_length % sql_field->charset->mbmaxlen; } else { my_error(ER_TOO_LONG_KEY, MYF(0), key_part_length); DBUG_RETURN(TRUE); } } key_part_info->length= (uint16) key_part_length; /* Use packed keys for long strings on the first column */ if (!((*db_options) & HA_OPTION_NO_PACK_KEYS) && !((create_info->table_options & HA_OPTION_NO_PACK_KEYS)) && (key_part_length >= KEY_DEFAULT_PACK_LENGTH && (sql_field->sql_type == MYSQL_TYPE_STRING || sql_field->sql_type == MYSQL_TYPE_VARCHAR || sql_field->pack_flag & FIELDFLAG_BLOB))) { if ((column_nr == 0 && (sql_field->pack_flag & FIELDFLAG_BLOB)) || sql_field->sql_type == MYSQL_TYPE_VARCHAR) key_info->flags|= HA_BINARY_PACK_KEY | HA_VAR_LENGTH_KEY; else key_info->flags|= HA_PACK_KEY; } /* Check if the key segment is partial, set the key flag accordingly */ if (key_part_length != sql_field->key_length) key_info->flags|= HA_KEY_HAS_PART_KEY_SEG; key_length+= key_part_length; key_part_info++; /* Create the key name based on the first column (if not given) */ if (column_nr == 0) { if (key->type == Key::PRIMARY) { if (primary_key) { my_message(ER_MULTIPLE_PRI_KEY, ER_THD(thd, ER_MULTIPLE_PRI_KEY), MYF(0)); DBUG_RETURN(TRUE); } key_name=primary_key_name; primary_key=1; } else if (!(key_name= key->name.str)) key_name=make_unique_key_name(thd, sql_field->field_name, *key_info_buffer, key_info); if (check_if_keyname_exists(key_name, *key_info_buffer, key_info)) { my_error(ER_DUP_KEYNAME, MYF(0), key_name); DBUG_RETURN(TRUE); } key_info->name=(char*) key_name; } } if (!key_info->name || check_column_name(key_info->name)) { my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key_info->name); DBUG_RETURN(TRUE); } if (key->type == Key::UNIQUE && !(key_info->flags & HA_NULL_PART_KEY)) unique_key=1; key_info->key_length=(uint16) key_length; if (key_length > max_key_length && key->type != Key::FULLTEXT) { my_error(ER_TOO_LONG_KEY,MYF(0),max_key_length); DBUG_RETURN(TRUE); } if (validate_comment_length(thd, &key->key_create_info.comment, INDEX_COMMENT_MAXLEN, ER_TOO_LONG_INDEX_COMMENT, key_info->name)) DBUG_RETURN(TRUE); key_info->comment.length= key->key_create_info.comment.length; if (key_info->comment.length > 0) { key_info->flags|= HA_USES_COMMENT; key_info->comment.str= key->key_create_info.comment.str; } // Check if a duplicate index is defined. check_duplicate_key(thd, key, key_info, &alter_info->key_list); key_info++; } if (!unique_key && !primary_key && (file->ha_table_flags() & HA_REQUIRE_PRIMARY_KEY)) { my_message(ER_REQUIRES_PRIMARY_KEY, ER_THD(thd, ER_REQUIRES_PRIMARY_KEY), MYF(0)); DBUG_RETURN(TRUE); } if (auto_increment > 0) { my_message(ER_WRONG_AUTO_KEY, ER_THD(thd, ER_WRONG_AUTO_KEY), MYF(0)); DBUG_RETURN(TRUE); } /* Sort keys in optimized order */ my_qsort((uchar*) *key_info_buffer, *key_count, sizeof(KEY), (qsort_cmp) sort_keys); create_info->null_bits= null_fields; /* Check fields. */ it.rewind(); while ((sql_field=it++)) { Field::utype type= (Field::utype) MTYP_TYPENR(sql_field->unireg_check); /* Set NO_DEFAULT_VALUE_FLAG if this field doesn't have a default value and it is NOT NULL, not an AUTO_INCREMENT field, not a TIMESTAMP and not updated trough a NOW() function. */ if (!sql_field->default_value && !sql_field->has_default_function() && (sql_field->flags & NOT_NULL_FLAG) && (!is_timestamp_type(sql_field->sql_type) || opt_explicit_defaults_for_timestamp)) { sql_field->flags|= NO_DEFAULT_VALUE_FLAG; sql_field->pack_flag|= FIELDFLAG_NO_DEFAULT; } if (thd->variables.sql_mode & MODE_NO_ZERO_DATE && !sql_field->default_value && !sql_field->vcol_info && is_timestamp_type(sql_field->sql_type) && !opt_explicit_defaults_for_timestamp && (sql_field->flags & NOT_NULL_FLAG) && (type == Field::NONE || type == Field::TIMESTAMP_UN_FIELD)) { /* An error should be reported if: - NO_ZERO_DATE SQL mode is active; - there is no explicit DEFAULT clause (default column value); - this is a TIMESTAMP column; - the column is not NULL; - this is not the DEFAULT CURRENT_TIMESTAMP column. In other words, an error should be reported if - NO_ZERO_DATE SQL mode is active; - the column definition is equivalent to 'column_name TIMESTAMP DEFAULT 0'. */ my_error(ER_INVALID_DEFAULT, MYF(0), sql_field->field_name); DBUG_RETURN(TRUE); } } /* Check table level constraints */ create_info->check_constraint_list= &alter_info->check_constraint_list; { uint nr= 1; List_iterator_fast<Virtual_column_info> c_it(alter_info->check_constraint_list); Virtual_column_info *check; while ((check= c_it++)) { if (!check->name.length) make_unique_constraint_name(thd, &check->name, &alter_info->check_constraint_list, &nr); { /* Check that there's no repeating constraint names. */ List_iterator_fast<Virtual_column_info> dup_it(alter_info->check_constraint_list); Virtual_column_info *dup_check; while ((dup_check= dup_it++) && dup_check != check) { if (check->name.length == dup_check->name.length && my_strcasecmp(system_charset_info, check->name.str, dup_check->name.str) == 0) { my_error(ER_DUP_CONSTRAINT_NAME, MYF(0), "CHECK", check->name.str); DBUG_RETURN(TRUE); } } } if (check_string_char_length(&check->name, 0, NAME_CHAR_LEN, system_charset_info, 1)) { my_error(ER_TOO_LONG_IDENT, MYF(0), check->name.str); DBUG_RETURN(TRUE); } if (check_expression(check, check->name.str, VCOL_CHECK_TABLE)) DBUG_RETURN(TRUE); } } /* Give warnings for not supported table options */ #if defined(WITH_ARIA_STORAGE_ENGINE) extern handlerton *maria_hton; if (file->ht != maria_hton) #endif if (create_info->transactional) push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_ILLEGAL_HA_CREATE_OPTION, ER_THD(thd, ER_ILLEGAL_HA_CREATE_OPTION), file->engine_name()->str, "TRANSACTIONAL=1"); if (parse_option_list(thd, file->partition_ht(), &create_info->option_struct, &create_info->option_list, file->partition_ht()->table_options, FALSE, thd->mem_root)) DBUG_RETURN(TRUE); DBUG_RETURN(FALSE); } /** check comment length of table, column, index and partition If comment lenght is more than the standard length truncate it and store the comment lenght upto the standard comment length size @param thd Thread handle @param[in,out] comment Comment @param max_len Maximum allowed comment length @param err_code Error message @param name Name of commented object @return Operation status @retval true Error found @retval false On Success */ bool validate_comment_length(THD *thd, LEX_STRING *comment, size_t max_len, uint err_code, const char *name) { DBUG_ENTER("validate_comment_length"); uint tmp_len= my_charpos(system_charset_info, comment->str, comment->str + comment->length, max_len); if (tmp_len < comment->length) { if (thd->is_strict_mode()) { my_error(err_code, MYF(0), name, static_cast<ulong>(max_len)); DBUG_RETURN(true); } push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, err_code, ER_THD(thd, err_code), name, static_cast<ulong>(max_len)); comment->length= tmp_len; } DBUG_RETURN(false); } /* Set table default charset, if not set SYNOPSIS set_table_default_charset() create_info Table create information DESCRIPTION If the table character set was not given explicitly, let's fetch the database default character set and apply it to the table. */ static void set_table_default_charset(THD *thd, HA_CREATE_INFO *create_info, char *db) { /* If the table character set was not given explicitly, let's fetch the database default character set and apply it to the table. */ if (!create_info->default_table_charset) { Schema_specification_st db_info; load_db_opt_by_name(thd, db, &db_info); create_info->default_table_charset= db_info.default_table_charset; } } /* Extend long VARCHAR fields to blob & prepare field if it's a blob SYNOPSIS prepare_blob_field() sql_field Field to check RETURN 0 ok 1 Error (sql_field can't be converted to blob) In this case the error is given */ static bool prepare_blob_field(THD *thd, Column_definition *sql_field) { DBUG_ENTER("prepare_blob_field"); if (sql_field->length > MAX_FIELD_VARCHARLENGTH && !(sql_field->flags & BLOB_FLAG)) { /* Convert long VARCHAR columns to TEXT or BLOB */ char warn_buff[MYSQL_ERRMSG_SIZE]; if (thd->is_strict_mode()) { my_error(ER_TOO_BIG_FIELDLENGTH, MYF(0), sql_field->field_name, static_cast<ulong>(MAX_FIELD_VARCHARLENGTH / sql_field->charset->mbmaxlen)); DBUG_RETURN(1); } sql_field->sql_type= MYSQL_TYPE_BLOB; sql_field->flags|= BLOB_FLAG; my_snprintf(warn_buff, sizeof(warn_buff), ER_THD(thd, ER_AUTO_CONVERT), sql_field->field_name, (sql_field->charset == &my_charset_bin) ? "VARBINARY" : "VARCHAR", (sql_field->charset == &my_charset_bin) ? "BLOB" : "TEXT"); push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_AUTO_CONVERT, warn_buff); } if ((sql_field->flags & BLOB_FLAG) && sql_field->length) { if (sql_field->sql_type == FIELD_TYPE_BLOB || sql_field->sql_type == FIELD_TYPE_TINY_BLOB || sql_field->sql_type == FIELD_TYPE_MEDIUM_BLOB) { /* The user has given a length to the blob column */ sql_field->sql_type= get_blob_type_from_length((ulong)sql_field->length); sql_field->pack_length= calc_pack_length(sql_field->sql_type, 0); } sql_field->length= 0; } DBUG_RETURN(0); } /* Preparation of Create_field for SP function return values. Based on code used in the inner loop of mysql_prepare_create_table() above. SYNOPSIS sp_prepare_create_field() thd Thread object sql_field Field to prepare DESCRIPTION Prepares the field structures for field creation. */ void sp_prepare_create_field(THD *thd, Column_definition *sql_field) { if (sql_field->sql_type == MYSQL_TYPE_SET || sql_field->sql_type == MYSQL_TYPE_ENUM) { uint32 field_length, dummy; if (sql_field->sql_type == MYSQL_TYPE_SET) { calculate_interval_lengths(sql_field->charset, sql_field->interval, &dummy, &field_length); sql_field->length= field_length + (sql_field->interval->count - 1); } else /* MYSQL_TYPE_ENUM */ { calculate_interval_lengths(sql_field->charset, sql_field->interval, &field_length, &dummy); sql_field->length= field_length; } set_if_smaller(sql_field->length, MAX_FIELD_WIDTH-1); } if (sql_field->sql_type == MYSQL_TYPE_BIT) { sql_field->pack_flag= FIELDFLAG_NUMBER | FIELDFLAG_TREAT_BIT_AS_CHAR; } sql_field->create_length_to_internal_length(); DBUG_ASSERT(sql_field->default_value == 0); /* Can't go wrong as sql_field->def is not defined */ (void) prepare_blob_field(thd, sql_field); } handler *mysql_create_frm_image(THD *thd, const char *db, const char *table_name, HA_CREATE_INFO *create_info, Alter_info *alter_info, int create_table_mode, KEY **key_info, uint *key_count, LEX_CUSTRING *frm) { uint db_options; handler *file; DBUG_ENTER("mysql_create_frm_image"); if (!alter_info->create_list.elements) { my_error(ER_TABLE_MUST_HAVE_COLUMNS, MYF(0)); DBUG_RETURN(NULL); } set_table_default_charset(thd, create_info, (char*) db); db_options= create_info->table_options; if (create_info->row_type == ROW_TYPE_DYNAMIC || create_info->row_type == ROW_TYPE_PAGE) db_options|= HA_OPTION_PACK_RECORD; if (!(file= get_new_handler((TABLE_SHARE*) 0, thd->mem_root, create_info->db_type))) { mem_alloc_error(sizeof(handler)); DBUG_RETURN(NULL); } #ifdef WITH_PARTITION_STORAGE_ENGINE partition_info *part_info= thd->work_part_info; if (!part_info && create_info->db_type->partition_flags && (create_info->db_type->partition_flags() & HA_USE_AUTO_PARTITION)) { /* Table is not defined as a partitioned table but the engine handles all tables as partitioned. The handler will set up the partition info object with the default settings. */ thd->work_part_info= part_info= new partition_info(); if (!part_info) { mem_alloc_error(sizeof(partition_info)); goto err; } file->set_auto_partitions(part_info); part_info->default_engine_type= create_info->db_type; part_info->is_auto_partitioned= TRUE; } if (part_info) { /* The table has been specified as a partitioned table. If this is part of an ALTER TABLE the handler will be the partition handler but we need to specify the default handler to use for partitions also in the call to check_partition_info. We transport this information in the default_db_type variable, it is either DB_TYPE_DEFAULT or the engine set in the ALTER TABLE command. */ handlerton *part_engine_type= create_info->db_type; char *part_syntax_buf; uint syntax_len; handlerton *engine_type; List_iterator<partition_element> part_it(part_info->partitions); partition_element *part_elem; while ((part_elem= part_it++)) { if (part_elem->part_comment) { LEX_STRING comment= { part_elem->part_comment, strlen(part_elem->part_comment) }; if (validate_comment_length(thd, &comment, TABLE_PARTITION_COMMENT_MAXLEN, ER_TOO_LONG_TABLE_PARTITION_COMMENT, part_elem->partition_name)) DBUG_RETURN(NULL); part_elem->part_comment[comment.length]= '\0'; } if (part_elem->subpartitions.elements) { List_iterator<partition_element> sub_it(part_elem->subpartitions); partition_element *subpart_elem; while ((subpart_elem= sub_it++)) { if (subpart_elem->part_comment) { LEX_STRING comment= { subpart_elem->part_comment, strlen(subpart_elem->part_comment) }; if (validate_comment_length(thd, &comment, TABLE_PARTITION_COMMENT_MAXLEN, ER_TOO_LONG_TABLE_PARTITION_COMMENT, subpart_elem->partition_name)) DBUG_RETURN(NULL); subpart_elem->part_comment[comment.length]= '\0'; } } } } if (create_info->tmp_table()) { my_error(ER_PARTITION_NO_TEMPORARY, MYF(0)); goto err; } if ((part_engine_type == partition_hton) && part_info->default_engine_type) { /* This only happens at ALTER TABLE. default_engine_type was assigned from the engine set in the ALTER TABLE command. */ ; } else { if (create_info->used_fields & HA_CREATE_USED_ENGINE) { part_info->default_engine_type= create_info->db_type; } else { if (part_info->default_engine_type == NULL) { part_info->default_engine_type= ha_default_handlerton(thd); } } } DBUG_PRINT("info", ("db_type = %s create_info->db_type = %s", ha_resolve_storage_engine_name(part_info->default_engine_type), ha_resolve_storage_engine_name(create_info->db_type))); if (part_info->check_partition_info(thd, &engine_type, file, create_info, FALSE)) goto err; part_info->default_engine_type= engine_type; /* We reverse the partitioning parser and generate a standard format for syntax stored in frm file. */ sql_mode_t old_mode= thd->variables.sql_mode; thd->variables.sql_mode &= ~MODE_ANSI_QUOTES; part_syntax_buf= generate_partition_syntax(thd, part_info, &syntax_len, true, create_info, alter_info); thd->variables.sql_mode= old_mode; if (!part_syntax_buf) goto err; part_info->part_info_string= part_syntax_buf; part_info->part_info_len= syntax_len; if ((!(engine_type->partition_flags && engine_type->partition_flags() & HA_CAN_PARTITION)) || create_info->db_type == partition_hton) { /* The handler assigned to the table cannot handle partitioning. Assign the partition handler as the handler of the table. */ DBUG_PRINT("info", ("db_type: %s", ha_resolve_storage_engine_name(create_info->db_type))); delete file; create_info->db_type= partition_hton; if (!(file= get_ha_partition(part_info))) DBUG_RETURN(NULL); /* If we have default number of partitions or subpartitions we might require to set-up the part_info object such that it creates a proper .par file. The current part_info object is only used to create the frm-file and .par-file. */ if (part_info->use_default_num_partitions && part_info->num_parts && (int)part_info->num_parts != file->get_default_no_partitions(create_info)) { uint i; List_iterator<partition_element> part_it(part_info->partitions); part_it++; DBUG_ASSERT(thd->lex->sql_command != SQLCOM_CREATE_TABLE); for (i= 1; i < part_info->partitions.elements; i++) (part_it++)->part_state= PART_TO_BE_DROPPED; } else if (part_info->is_sub_partitioned() && part_info->use_default_num_subpartitions && part_info->num_subparts && (int)part_info->num_subparts != file->get_default_no_partitions(create_info)) { DBUG_ASSERT(thd->lex->sql_command != SQLCOM_CREATE_TABLE); part_info->num_subparts= file->get_default_no_partitions(create_info); } } else if (create_info->db_type != engine_type) { /* We come here when we don't use a partitioned handler. Since we use a partitioned table it must be "native partitioned". We have switched engine from defaults, most likely only specified engines in partition clauses. */ delete file; if (!(file= get_new_handler((TABLE_SHARE*) 0, thd->mem_root, engine_type))) { mem_alloc_error(sizeof(handler)); DBUG_RETURN(NULL); } } } /* Unless table's storage engine supports partitioning natively don't allow foreign keys on partitioned tables (they won't work work even with InnoDB beneath of partitioning engine). If storage engine handles partitioning natively (like NDB) foreign keys support is possible, so we let the engine decide. */ if (create_info->db_type == partition_hton) { List_iterator_fast<Key> key_iterator(alter_info->key_list); Key *key; while ((key= key_iterator++)) { if (key->type == Key::FOREIGN_KEY) { my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0)); goto err; } } } #endif if (mysql_prepare_create_table(thd, create_info, alter_info, &db_options, file, key_info, key_count, create_table_mode)) goto err; create_info->table_options=db_options; *frm= build_frm_image(thd, table_name, create_info, alter_info->create_list, *key_count, *key_info, file); if (frm->str) DBUG_RETURN(file); err: delete file; DBUG_RETURN(NULL); } /** Create a table @param thd Thread object @param orig_db Database for error messages @param orig_table_name Table name for error messages (it's different from table_name for ALTER TABLE) @param db Database @param table_name Table name @param path Path to table (i.e. to its .FRM file without the extension). @param create_info Create information (like MAX_ROWS) @param alter_info Description of fields and keys for new table @param create_table_mode C_ORDINARY_CREATE, C_ALTER_TABLE, C_ASSISTED_DISCOVERY or any positive number (for C_CREATE_SELECT). @param[out] is_trans Identifies the type of engine where the table was created: either trans or non-trans. @param[out] key_info Array of KEY objects describing keys in table which was created. @param[out] key_count Number of keys in table which was created. If one creates a temporary table, its is automatically opened and its TABLE_SHARE is added to THD::all_temp_tables list. Note that this function assumes that caller already have taken exclusive metadata lock on table being created or used some other way to ensure that concurrent operations won't intervene. mysql_create_table() is a wrapper that can be used for this. @retval 0 OK @retval 1 error @retval -1 table existed but IF EXISTS was used */ static int create_table_impl(THD *thd, const char *orig_db, const char *orig_table_name, const char *db, const char *table_name, const char *path, const DDL_options_st options, HA_CREATE_INFO *create_info, Alter_info *alter_info, int create_table_mode, bool *is_trans, KEY **key_info, uint *key_count, LEX_CUSTRING *frm) { const char *alias; handler *file= 0; int error= 1; bool frm_only= create_table_mode == C_ALTER_TABLE_FRM_ONLY; bool internal_tmp_table= create_table_mode == C_ALTER_TABLE || frm_only; DBUG_ENTER("mysql_create_table_no_lock"); DBUG_PRINT("enter", ("db: '%s' table: '%s' tmp: %d path: %s", db, table_name, internal_tmp_table, path)); if (thd->variables.sql_mode & MODE_NO_DIR_IN_CREATE) { if (create_info->data_file_name) push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, WARN_OPTION_IGNORED, ER_THD(thd, WARN_OPTION_IGNORED), "DATA DIRECTORY"); if (create_info->index_file_name) push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, WARN_OPTION_IGNORED, ER_THD(thd, WARN_OPTION_IGNORED), "INDEX DIRECTORY"); create_info->data_file_name= create_info->index_file_name= 0; } else if (error_if_data_home_dir(create_info->data_file_name, "DATA DIRECTORY") || error_if_data_home_dir(create_info->index_file_name, "INDEX DIRECTORY")|| check_partition_dirs(thd->lex->part_info)) goto err; alias= table_case_name(create_info, table_name); /* Check if table exists */ if (create_info->tmp_table()) { /* If a table exists, it must have been pre-opened. Try looking for one in-use in THD::all_temp_tables list of TABLE_SHAREs. */ TABLE *tmp_table= thd->find_temporary_table(db, table_name); if (tmp_table) { bool table_creation_was_logged= tmp_table->s->table_creation_was_logged; if (options.or_replace()) { /* We are using CREATE OR REPLACE on an existing temporary table Remove the old table so that we can re-create it. */ if (thd->drop_temporary_table(tmp_table, NULL, true)) goto err; } else if (options.if_not_exists()) goto warn; else { my_error(ER_TABLE_EXISTS_ERROR, MYF(0), alias); goto err; } /* We have to log this query, even if it failed later to ensure the drop is done. */ if (table_creation_was_logged) { thd->variables.option_bits|= OPTION_KEEP_LOG; thd->log_current_statement= 1; create_info->table_was_deleted= 1; } } } else { if (!internal_tmp_table && ha_table_exists(thd, db, table_name)) { if (options.or_replace()) { TABLE_LIST table_list; table_list.init_one_table(db, strlen(db), table_name, strlen(table_name), table_name, TL_WRITE_ALLOW_WRITE); table_list.table= create_info->table; if (check_if_log_table(&table_list, TRUE, "CREATE OR REPLACE")) goto err; /* Rollback the empty transaction started in mysql_create_table() call to open_and_lock_tables() when we are using LOCK TABLES. */ (void) trans_rollback_stmt(thd); /* Remove normal table without logging. Keep tables locked */ if (mysql_rm_table_no_locks(thd, &table_list, 0, 0, 0, 1, 1)) goto err; /* We have to log this query, even if it failed later to ensure the drop is done. */ thd->variables.option_bits|= OPTION_KEEP_LOG; thd->log_current_statement= 1; create_info->table_was_deleted= 1; DBUG_EXECUTE_IF("send_kill_after_delete", thd->set_killed(KILL_QUERY); ); /* Restart statement transactions for the case of CREATE ... SELECT. */ if (thd->lex->select_lex.item_list.elements && restart_trans_for_tables(thd, thd->lex->query_tables)) goto err; } else if (options.if_not_exists()) goto warn; else { my_error(ER_TABLE_EXISTS_ERROR, MYF(0), table_name); goto err; } } } THD_STAGE_INFO(thd, stage_creating_table); if (check_engine(thd, orig_db, orig_table_name, create_info)) goto err; if (create_table_mode == C_ASSISTED_DISCOVERY) { /* check that it's used correctly */ DBUG_ASSERT(alter_info->create_list.elements == 0); DBUG_ASSERT(alter_info->key_list.elements == 0); TABLE_SHARE share; handlerton *hton= create_info->db_type; int ha_err; Field *no_fields= 0; if (!hton->discover_table_structure) { my_error(ER_TABLE_MUST_HAVE_COLUMNS, MYF(0)); goto err; } init_tmp_table_share(thd, &share, db, 0, table_name, path); /* prepare everything for discovery */ share.field= &no_fields; share.db_plugin= ha_lock_engine(thd, hton); share.option_list= create_info->option_list; share.connect_string= create_info->connect_string; if (parse_engine_table_options(thd, hton, &share)) goto err; ha_err= hton->discover_table_structure(hton, thd, &share, create_info); /* if discovery failed, the plugin will be auto-unlocked, as it was locked on the THD, see above. if discovery succeeded, the plugin was replaced by a globally locked plugin, that will be unlocked by free_table_share() */ if (ha_err) share.db_plugin= 0; // will be auto-freed, locked above on the THD free_table_share(&share); if (ha_err) { my_error(ER_GET_ERRNO, MYF(0), ha_err, hton_name(hton)->str); goto err; } } else { file= mysql_create_frm_image(thd, orig_db, orig_table_name, create_info, alter_info, create_table_mode, key_info, key_count, frm); if (!file) goto err; if (rea_create_table(thd, frm, path, db, table_name, create_info, file, frm_only)) goto err; } create_info->table= 0; if (!frm_only && create_info->tmp_table()) { TABLE *table= thd->create_and_open_tmp_table(create_info->db_type, frm, path, db, table_name, true); if (!table) { (void) thd->rm_temporary_table(create_info->db_type, path); goto err; } if (is_trans != NULL) *is_trans= table->file->has_transactions(); thd->thread_specific_used= TRUE; create_info->table= table; // Store pointer to table } #ifdef WITH_PARTITION_STORAGE_ENGINE else if (thd->work_part_info && frm_only) { /* For partitioned tables we can't find some problems with table until table is opened. Therefore in order to disallow creation of corrupted tables we have to try to open table as the part of its creation process. In cases when both .FRM and SE part of table are created table is implicitly open in ha_create_table() call. In cases when we create .FRM without SE part we have to open table explicitly. */ TABLE table; TABLE_SHARE share; init_tmp_table_share(thd, &share, db, 0, table_name, path); bool result= (open_table_def(thd, &share, GTS_TABLE) || open_table_from_share(thd, &share, "", 0, (uint) READ_ALL, 0, &table, true)); if (!result) (void) closefrm(&table); free_table_share(&share); if (result) { char frm_name[FN_REFLEN]; strxnmov(frm_name, sizeof(frm_name), path, reg_ext, NullS); (void) mysql_file_delete(key_file_frm, frm_name, MYF(0)); (void) file->ha_create_partitioning_metadata(path, NULL, CHF_DELETE_FLAG); goto err; } } #endif error= 0; err: THD_STAGE_INFO(thd, stage_after_create); delete file; DBUG_PRINT("exit", ("return: %d", error)); DBUG_RETURN(error); warn: error= -1; push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_TABLE_EXISTS_ERROR, ER_THD(thd, ER_TABLE_EXISTS_ERROR), alias); goto err; } /** Simple wrapper around create_table_impl() to be used in various version of CREATE TABLE statement. */ int mysql_create_table_no_lock(THD *thd, const char *db, const char *table_name, Table_specification_st *create_info, Alter_info *alter_info, bool *is_trans, int create_table_mode) { KEY *not_used_1; uint not_used_2; int res; char path[FN_REFLEN + 1]; LEX_CUSTRING frm= {0,0}; if (create_info->tmp_table()) build_tmptable_filename(thd, path, sizeof(path)); else { int length; const char *alias= table_case_name(create_info, table_name); length= build_table_filename(path, sizeof(path) - 1, db, alias, "", 0); // Check if we hit FN_REFLEN bytes along with file extension. if (length+reg_ext_length > FN_REFLEN) { my_error(ER_IDENT_CAUSES_TOO_LONG_PATH, MYF(0), sizeof(path)-1, path); return true; } } res= create_table_impl(thd, db, table_name, db, table_name, path, *create_info, create_info, alter_info, create_table_mode, is_trans, &not_used_1, &not_used_2, &frm); my_free(const_cast<uchar*>(frm.str)); return res; } /** Implementation of SQLCOM_CREATE_TABLE. Take the metadata locks (including a shared lock on the affected schema) and create the table. Is written to be called from mysql_execute_command(), to which it delegates the common parts with other commands (i.e. implicit commit before and after, close of thread tables. */ bool mysql_create_table(THD *thd, TABLE_LIST *create_table, Table_specification_st *create_info, Alter_info *alter_info) { const char *db= create_table->db; const char *table_name= create_table->table_name; bool is_trans= FALSE; bool result; int create_table_mode; TABLE_LIST *pos_in_locked_tables= 0; MDL_ticket *mdl_ticket= 0; DBUG_ENTER("mysql_create_table"); DBUG_ASSERT(create_table == thd->lex->query_tables); /* Copy temporarily the statement flags to thd for lock_table_names() */ uint save_thd_create_info_options= thd->lex->create_info.options; thd->lex->create_info.options|= create_info->options; /* Open or obtain an exclusive metadata lock on table being created */ result= open_and_lock_tables(thd, *create_info, create_table, FALSE, 0); thd->lex->create_info.options= save_thd_create_info_options; if (result) { /* is_error() may be 0 if table existed and we generated a warning */ DBUG_RETURN(thd->is_error()); } /* The following is needed only in case of lock tables */ if ((create_info->table= create_table->table)) { pos_in_locked_tables= create_info->table->pos_in_locked_tables; mdl_ticket= create_table->table->mdl_ticket; } /* Got lock. */ DEBUG_SYNC(thd, "locked_table_name"); if (alter_info->create_list.elements || alter_info->key_list.elements) create_table_mode= C_ORDINARY_CREATE; else create_table_mode= C_ASSISTED_DISCOVERY; if (!opt_explicit_defaults_for_timestamp) promote_first_timestamp_column(&alter_info->create_list); if (mysql_create_table_no_lock(thd, db, table_name, create_info, alter_info, &is_trans, create_table_mode) > 0) { result= 1; goto err; } /* Check if we are doing CREATE OR REPLACE TABLE under LOCK TABLES on a non temporary table */ if (thd->locked_tables_mode && pos_in_locked_tables && create_info->or_replace()) { /* Add back the deleted table and re-created table as a locked table This should always work as we have a meta lock on the table. */ thd->locked_tables_list.add_back_last_deleted_lock(pos_in_locked_tables); if (thd->locked_tables_list.reopen_tables(thd)) { thd->locked_tables_list.unlink_all_closed_tables(thd, NULL, 0); result= 1; } else { TABLE *table= pos_in_locked_tables->table; table->mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE); } } err: /* In RBR we don't need to log CREATE TEMPORARY TABLE */ if (thd->is_current_stmt_binlog_format_row() && create_info->tmp_table()) DBUG_RETURN(result); if (create_info->tmp_table()) thd->transaction.stmt.mark_created_temp_table(); /* Write log if no error or if we already deleted a table */ if (!result || thd->log_current_statement) { if (result && create_info->table_was_deleted) { /* Possible locked table was dropped. We should remove meta data locks associated with it and do UNLOCK_TABLES if no more locked tables. */ thd->locked_tables_list.unlock_locked_table(thd, mdl_ticket); } else if (!result && create_info->tmp_table() && create_info->table) { /* Remember that tmp table creation was logged so that we know if we should log a delete of it. */ create_info->table->s->table_creation_was_logged= 1; } if (write_bin_log(thd, result ? FALSE : TRUE, thd->query(), thd->query_length(), is_trans)) result= 1; } DBUG_RETURN(result); } /* ** Give the key name after the first field with an optional '_#' after **/ static bool check_if_keyname_exists(const char *name, KEY *start, KEY *end) { for (KEY *key=start ; key != end ; key++) if (!my_strcasecmp(system_charset_info,name,key->name)) return 1; return 0; } static char * make_unique_key_name(THD *thd, const char *field_name,KEY *start,KEY *end) { char buff[MAX_FIELD_NAME],*buff_end; if (!check_if_keyname_exists(field_name,start,end) && my_strcasecmp(system_charset_info,field_name,primary_key_name)) return (char*) field_name; // Use fieldname buff_end=strmake(buff,field_name, sizeof(buff)-4); /* Only 3 chars + '\0' left, so need to limit to 2 digit This is ok as we can't have more than 100 keys anyway */ for (uint i=2 ; i< 100; i++) { *buff_end= '_'; int10_to_str(i, buff_end+1, 10); if (!check_if_keyname_exists(buff,start,end)) return thd->strdup(buff); } return (char*) "not_specified"; // Should never happen } /** Make an unique name for constraints without a name */ static void make_unique_constraint_name(THD *thd, LEX_STRING *name, List<Virtual_column_info> *vcol, uint *nr) { char buff[MAX_FIELD_NAME], *end; List_iterator_fast<Virtual_column_info> it(*vcol); end=strmov(buff, "CONSTRAINT_"); for (;;) { Virtual_column_info *check; char *real_end= int10_to_str((*nr)++, end, 10); it.rewind(); while ((check= it++)) { if (check->name.str && !my_strcasecmp(system_charset_info, buff, check->name.str)) break; } if (!check) // Found unique name { name->length= (size_t) (real_end - buff); name->str= thd->strmake(buff, name->length); return; } } } /**************************************************************************** ** Alter a table definition ****************************************************************************/ /** Rename a table. @param base The handlerton handle. @param old_db The old database name. @param old_name The old table name. @param new_db The new database name. @param new_name The new table name. @param flags flags FN_FROM_IS_TMP old_name is temporary. FN_TO_IS_TMP new_name is temporary. NO_FRM_RENAME Don't rename the FRM file but only the table in the storage engine. NO_HA_TABLE Don't rename table in engine. NO_FK_CHECKS Don't check FK constraints during rename. @return false OK @return true Error */ bool mysql_rename_table(handlerton *base, const char *old_db, const char *old_name, const char *new_db, const char *new_name, uint flags) { THD *thd= current_thd; char from[FN_REFLEN + 1], to[FN_REFLEN + 1], lc_from[FN_REFLEN + 1], lc_to[FN_REFLEN + 1]; char *from_base= from, *to_base= to; char tmp_name[SAFE_NAME_LEN+1], tmp_db_name[SAFE_NAME_LEN+1]; handler *file; int error=0; ulonglong save_bits= thd->variables.option_bits; int length; DBUG_ENTER("mysql_rename_table"); DBUG_ASSERT(base); DBUG_PRINT("enter", ("old: '%s'.'%s' new: '%s'.'%s'", old_db, old_name, new_db, new_name)); // Temporarily disable foreign key checks if (flags & NO_FK_CHECKS) thd->variables.option_bits|= OPTION_NO_FOREIGN_KEY_CHECKS; file= get_new_handler((TABLE_SHARE*) 0, thd->mem_root, base); build_table_filename(from, sizeof(from) - 1, old_db, old_name, "", flags & FN_FROM_IS_TMP); length= build_table_filename(to, sizeof(to) - 1, new_db, new_name, "", flags & FN_TO_IS_TMP); // Check if we hit FN_REFLEN bytes along with file extension. if (length+reg_ext_length > FN_REFLEN) { my_error(ER_IDENT_CAUSES_TOO_LONG_PATH, MYF(0), sizeof(to)-1, to); DBUG_RETURN(TRUE); } /* If lower_case_table_names == 2 (case-preserving but case-insensitive file system) and the storage is not HA_FILE_BASED, we need to provide a lowercase file name, but we leave the .frm in mixed case. */ if (lower_case_table_names == 2 && file && !(file->ha_table_flags() & HA_FILE_BASED)) { strmov(tmp_name, old_name); my_casedn_str(files_charset_info, tmp_name); strmov(tmp_db_name, old_db); my_casedn_str(files_charset_info, tmp_db_name); build_table_filename(lc_from, sizeof(lc_from) - 1, tmp_db_name, tmp_name, "", flags & FN_FROM_IS_TMP); from_base= lc_from; strmov(tmp_name, new_name); my_casedn_str(files_charset_info, tmp_name); strmov(tmp_db_name, new_db); my_casedn_str(files_charset_info, tmp_db_name); build_table_filename(lc_to, sizeof(lc_to) - 1, tmp_db_name, tmp_name, "", flags & FN_TO_IS_TMP); to_base= lc_to; } if (flags & NO_HA_TABLE) { if (rename_file_ext(from,to,reg_ext)) error= my_errno; (void) file->ha_create_partitioning_metadata(to, from, CHF_RENAME_FLAG); } else if (!file || !(error=file->ha_rename_table(from_base, to_base))) { if (!(flags & NO_FRM_RENAME) && rename_file_ext(from,to,reg_ext)) { error=my_errno; if (file) { if (error == ENOENT) error= 0; // this is ok if file->ha_rename_table() succeeded else file->ha_rename_table(to_base, from_base); // Restore old file name } } } delete file; if (error == HA_ERR_WRONG_COMMAND) my_error(ER_NOT_SUPPORTED_YET, MYF(0), "ALTER TABLE"); else if (error) my_error(ER_ERROR_ON_RENAME, MYF(0), from, to, error); else if (!(flags & FN_IS_TMP)) mysql_audit_rename_table(thd, old_db, old_name, new_db, new_name); /* Remove the old table share from the pfs table share array. The new table share will be created when the renamed table is first accessed. */ if (likely(error == 0)) { PSI_CALL_drop_table_share(flags & FN_FROM_IS_TMP, old_db, strlen(old_db), old_name, strlen(old_name)); } // Restore options bits to the original value thd->variables.option_bits= save_bits; DBUG_RETURN(error != 0); } /* Create a table identical to the specified table SYNOPSIS mysql_create_like_table() thd Thread object table Table list element for target table src_table Table list element for source table create_info Create info RETURN VALUES FALSE OK TRUE error */ bool mysql_create_like_table(THD* thd, TABLE_LIST* table, TABLE_LIST* src_table, Table_specification_st *create_info) { Table_specification_st local_create_info; TABLE_LIST *pos_in_locked_tables= 0; Alter_info local_alter_info; Alter_table_ctx local_alter_ctx; // Not used bool res= TRUE; bool is_trans= FALSE; bool do_logging= FALSE; uint not_used; int create_res; DBUG_ENTER("mysql_create_like_table"); #ifdef WITH_WSREP if (WSREP_ON && !thd->wsrep_applier && wsrep_create_like_table(thd, table, src_table, create_info)) DBUG_RETURN(res); #endif /* We the open source table to get its description in HA_CREATE_INFO and Alter_info objects. This also acquires a shared metadata lock on this table which ensures that no concurrent DDL operation will mess with it. Also in case when we create non-temporary table open_tables() call obtains an exclusive metadata lock on target table ensuring that we can safely perform table creation. Thus by holding both these locks we ensure that our statement is properly isolated from all concurrent operations which matter. */ /* Copy temporarily the statement flags to thd for lock_table_names() */ // QQ: is this really needed??? uint save_thd_create_info_options= thd->lex->create_info.options; thd->lex->create_info.options|= create_info->options; res= open_tables(thd, &thd->lex->query_tables, &not_used, 0); thd->lex->create_info.options= save_thd_create_info_options; if (res) { /* is_error() may be 0 if table existed and we generated a warning */ res= thd->is_error(); goto err; } /* Ensure we don't try to create something from which we select from */ if (create_info->or_replace() && !create_info->tmp_table()) { TABLE_LIST *duplicate; if ((duplicate= unique_table(thd, table, src_table, 0))) { update_non_unique_table_error(src_table, "CREATE", duplicate); goto err; } } src_table->table->use_all_columns(); DEBUG_SYNC(thd, "create_table_like_after_open"); /* Fill Table_specification_st and Alter_info with the source table description. Set OR REPLACE and IF NOT EXISTS option as in the CREATE TABLE LIKE statement. */ local_create_info.init(create_info->create_like_options()); local_create_info.db_type= src_table->table->s->db_type(); local_create_info.row_type= src_table->table->s->row_type; if (mysql_prepare_alter_table(thd, src_table->table, &local_create_info, &local_alter_info, &local_alter_ctx)) goto err; #ifdef WITH_PARTITION_STORAGE_ENGINE /* Partition info is not handled by mysql_prepare_alter_table() call. */ if (src_table->table->part_info) thd->work_part_info= src_table->table->part_info->get_clone(thd); #endif /* Adjust description of source table before using it for creation of target table. Similarly to SHOW CREATE TABLE we ignore MAX_ROWS attribute of temporary table which represents I_S table. */ if (src_table->schema_table) local_create_info.max_rows= 0; /* Replace type of source table with one specified in the statement. */ local_create_info.options&= ~HA_LEX_CREATE_TMP_TABLE; local_create_info.options|= create_info->tmp_table(); /* Reset auto-increment counter for the new table. */ local_create_info.auto_increment_value= 0; /* Do not inherit values of DATA and INDEX DIRECTORY options from the original table. This is documented behavior. */ local_create_info.data_file_name= local_create_info.index_file_name= NULL; /* The following is needed only in case of lock tables */ if ((local_create_info.table= thd->lex->query_tables->table)) pos_in_locked_tables= local_create_info.table->pos_in_locked_tables; res= ((create_res= mysql_create_table_no_lock(thd, table->db, table->table_name, &local_create_info, &local_alter_info, &is_trans, C_ORDINARY_CREATE)) > 0); /* Remember to log if we deleted something */ do_logging= thd->log_current_statement; if (res) goto err; /* Check if we are doing CREATE OR REPLACE TABLE under LOCK TABLES on a non temporary table */ if (thd->locked_tables_mode && pos_in_locked_tables && create_info->or_replace()) { /* Add back the deleted table and re-created table as a locked table This should always work as we have a meta lock on the table. */ thd->locked_tables_list.add_back_last_deleted_lock(pos_in_locked_tables); if (thd->locked_tables_list.reopen_tables(thd)) { thd->locked_tables_list.unlink_all_closed_tables(thd, NULL, 0); res= 1; // We got an error } else { /* Get pointer to the newly opened table. We need this to ensure we don't reopen the table when doing statment logging below. */ table->table= pos_in_locked_tables->table; table->table->mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE); } } else { /* Ensure that we have an exclusive lock on target table if we are creating non-temporary table. */ DBUG_ASSERT((create_info->tmp_table()) || thd->mdl_context.is_lock_owner(MDL_key::TABLE, table->db, table->table_name, MDL_EXCLUSIVE)); } DEBUG_SYNC(thd, "create_table_like_before_binlog"); /* We have to write the query before we unlock the tables. */ if (thd->is_current_stmt_binlog_disabled()) goto err; if (thd->is_current_stmt_binlog_format_row()) { /* Since temporary tables are not replicated under row-based replication, CREATE TABLE ... LIKE ... needs special treatement. We have four cases to consider, according to the following decision table: ==== ========= ========= ============================== Case Target Source Write to binary log ==== ========= ========= ============================== 1 normal normal Original statement 2 normal temporary Generated statement if the table was created. 3 temporary normal Nothing 4 temporary temporary Nothing ==== ========= ========= ============================== */ if (!(create_info->tmp_table())) { if (src_table->table->s->tmp_table) // Case 2 { char buf[2048]; String query(buf, sizeof(buf), system_charset_info); query.length(0); // Have to zero it since constructor doesn't Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN | MYSQL_OPEN_IGNORE_KILLED); bool new_table= FALSE; // Whether newly created table is open. if (create_res != 0) { /* Table or view with same name already existed and we where using IF EXISTS. Continue without logging anything. */ do_logging= 0; goto err; } if (!table->table) { TABLE_LIST::enum_open_strategy save_open_strategy; int open_res; /* Force the newly created table to be opened */ save_open_strategy= table->open_strategy; table->open_strategy= TABLE_LIST::OPEN_NORMAL; /* In order for show_create_table() to work we need to open destination table if it is not already open (i.e. if it has not existed before). We don't need acquire metadata lock in order to do this as we already hold exclusive lock on this table. The table will be closed by close_thread_table() at the end of this branch. */ open_res= open_table(thd, table, &ot_ctx); /* Restore */ table->open_strategy= save_open_strategy; if (open_res) { res= 1; goto err; } new_table= TRUE; } /* We have to re-test if the table was a view as the view may not have been opened until just above. */ if (!table->view) { /* After opening a MERGE table add the children to the query list of tables, so that children tables info can be used on "CREATE TABLE" statement generation by the binary log. Note that placeholders don't have the handler open. */ if (table->table->file->extra(HA_EXTRA_ADD_CHILDREN_LIST)) goto err; /* As the reference table is temporary and may not exist on slave, we must force the ENGINE to be present into CREATE TABLE. */ create_info->used_fields|= HA_CREATE_USED_ENGINE; int result __attribute__((unused))= show_create_table(thd, table, &query, create_info, WITH_DB_NAME); DBUG_ASSERT(result == 0); // show_create_table() always return 0 do_logging= FALSE; if (write_bin_log(thd, TRUE, query.ptr(), query.length())) { res= 1; do_logging= 0; goto err; } if (new_table) { DBUG_ASSERT(thd->open_tables == table->table); /* When opening the table, we ignored the locked tables (MYSQL_OPEN_GET_NEW_TABLE). Now we can close the table without risking to close some locked table. */ close_thread_table(thd, &thd->open_tables); } } } else // Case 1 do_logging= TRUE; } /* Case 3 and 4 does nothing under RBR */ } else { DBUG_PRINT("info", ("res: %d tmp_table: %d create_info->table: %p", res, create_info->tmp_table(), local_create_info.table)); if (create_info->tmp_table()) { thd->transaction.stmt.mark_created_temp_table(); if (!res && local_create_info.table) { /* Remember that tmp table creation was logged so that we know if we should log a delete of it. */ local_create_info.table->s->table_creation_was_logged= 1; } } do_logging= TRUE; } err: if (do_logging) { if (res && create_info->table_was_deleted) { /* Table was not deleted. Original table was deleted. We have to log it. */ log_drop_table(thd, table->db, table->db_length, table->table_name, table->table_name_length, create_info->tmp_table()); } else if (write_bin_log(thd, res ? FALSE : TRUE, thd->query(), thd->query_length(), is_trans)) res= 1; } DBUG_RETURN(res); } /* table_list should contain just one table */ int mysql_discard_or_import_tablespace(THD *thd, TABLE_LIST *table_list, bool discard) { Alter_table_prelocking_strategy alter_prelocking_strategy; int error; DBUG_ENTER("mysql_discard_or_import_tablespace"); mysql_audit_alter_table(thd, table_list); /* Note that DISCARD/IMPORT TABLESPACE always is the only operation in an ALTER TABLE */ THD_STAGE_INFO(thd, stage_discard_or_import_tablespace); /* We set this flag so that ha_innobase::open and ::external_lock() do not complain when we lock the table */ thd->tablespace_op= TRUE; /* Adjust values of table-level and metadata which was set in parser for the case general ALTER TABLE. */ table_list->mdl_request.set_type(MDL_EXCLUSIVE); table_list->lock_type= TL_WRITE; /* Do not open views. */ table_list->required_type= FRMTYPE_TABLE; if (open_and_lock_tables(thd, table_list, FALSE, 0, &alter_prelocking_strategy)) { thd->tablespace_op=FALSE; DBUG_RETURN(-1); } error= table_list->table->file->ha_discard_or_import_tablespace(discard); THD_STAGE_INFO(thd, stage_end); if (error) goto err; /* The 0 in the call below means 'not in a transaction', which means immediate invalidation; that is probably what we wish here */ query_cache_invalidate3(thd, table_list, 0); /* The ALTER TABLE is always in its own transaction */ error= trans_commit_stmt(thd); if (trans_commit_implicit(thd)) error=1; if (error) goto err; error= write_bin_log(thd, FALSE, thd->query(), thd->query_length()); err: thd->tablespace_op=FALSE; if (error == 0) { my_ok(thd); DBUG_RETURN(0); } table_list->table->file->print_error(error, MYF(0)); DBUG_RETURN(-1); } /** Check if key is a candidate key, i.e. a unique index with no index fields partial or nullable. */ static bool is_candidate_key(KEY *key) { KEY_PART_INFO *key_part; KEY_PART_INFO *key_part_end= key->key_part + key->user_defined_key_parts; if (!(key->flags & HA_NOSAME) || (key->flags & HA_NULL_PART_KEY)) return false; for (key_part= key->key_part; key_part < key_part_end; key_part++) { if (key_part->key_part_flag & HA_PART_KEY_SEG) return false; } return true; } /* Preparation for table creation SYNOPSIS handle_if_exists_option() thd Thread object. table The altered table. alter_info List of columns and indexes to create DESCRIPTION Looks for the IF [NOT] EXISTS options, checks the states and remove items from the list if existing found. RETURN VALUES NONE */ static void handle_if_exists_options(THD *thd, TABLE *table, Alter_info *alter_info) { Field **f_ptr; DBUG_ENTER("handle_if_exists_option"); /* Handle ADD COLUMN IF NOT EXISTS. */ { List_iterator<Create_field> it(alter_info->create_list); Create_field *sql_field; while ((sql_field=it++)) { if (!sql_field->create_if_not_exists || sql_field->change) continue; /* If there is a field with the same name in the table already, remove the sql_field from the list. */ for (f_ptr=table->field; *f_ptr; f_ptr++) { if (my_strcasecmp(system_charset_info, sql_field->field_name, (*f_ptr)->field_name) == 0) goto drop_create_field; } { /* If in the ADD list there is a field with the same name, remove the sql_field from the list. */ List_iterator<Create_field> chk_it(alter_info->create_list); Create_field *chk_field; while ((chk_field= chk_it++) && chk_field != sql_field) { if (my_strcasecmp(system_charset_info, sql_field->field_name, chk_field->field_name) == 0) goto drop_create_field; } } continue; drop_create_field: push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_DUP_FIELDNAME, ER_THD(thd, ER_DUP_FIELDNAME), sql_field->field_name); it.remove(); if (alter_info->create_list.is_empty()) { alter_info->flags&= ~Alter_info::ALTER_ADD_COLUMN; if (alter_info->key_list.is_empty()) alter_info->flags&= ~(Alter_info::ALTER_ADD_INDEX | Alter_info::ADD_FOREIGN_KEY); } } } /* Handle MODIFY COLUMN IF EXISTS. */ { List_iterator<Create_field> it(alter_info->create_list); Create_field *sql_field; while ((sql_field=it++)) { if (!sql_field->create_if_not_exists || !sql_field->change) continue; /* If there is NO field with the same name in the table already, remove the sql_field from the list. */ for (f_ptr=table->field; *f_ptr; f_ptr++) { if (my_strcasecmp(system_charset_info, sql_field->change, (*f_ptr)->field_name) == 0) { break; } } if (*f_ptr == NULL) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_BAD_FIELD_ERROR, ER_THD(thd, ER_BAD_FIELD_ERROR), sql_field->change, table->s->table_name.str); it.remove(); if (alter_info->create_list.is_empty()) { alter_info->flags&= ~(Alter_info::ALTER_ADD_COLUMN | Alter_info::ALTER_CHANGE_COLUMN); if (alter_info->key_list.is_empty()) alter_info->flags&= ~Alter_info::ALTER_ADD_INDEX; } } } } /* Handle DROP COLUMN/KEY IF EXISTS. */ { List_iterator<Alter_drop> drop_it(alter_info->drop_list); Alter_drop *drop; bool remove_drop; while ((drop= drop_it++)) { if (!drop->drop_if_exists) continue; remove_drop= TRUE; if (drop->type == Alter_drop::COLUMN) { /* If there is NO field with that name in the table, remove the 'drop' from the list. */ for (f_ptr=table->field; *f_ptr; f_ptr++) { if (my_strcasecmp(system_charset_info, drop->name, (*f_ptr)->field_name) == 0) { remove_drop= FALSE; break; } } } else if (drop->type == Alter_drop::CHECK_CONSTRAINT) { for (uint i=table->s->field_check_constraints; i < table->s->table_check_constraints; i++) { if (my_strcasecmp(system_charset_info, drop->name, table->check_constraints[i]->name.str) == 0) { remove_drop= FALSE; break; } } } else /* Alter_drop::KEY and Alter_drop::FOREIGN_KEY */ { uint n_key; if (drop->type != Alter_drop::FOREIGN_KEY) { for (n_key=0; n_key < table->s->keys; n_key++) { if (my_strcasecmp(system_charset_info, drop->name, table->key_info[n_key].name) == 0) { remove_drop= FALSE; break; } } } else { List <FOREIGN_KEY_INFO> fk_child_key_list; FOREIGN_KEY_INFO *f_key; table->file->get_foreign_key_list(thd, &fk_child_key_list); List_iterator<FOREIGN_KEY_INFO> fk_key_it(fk_child_key_list); while ((f_key= fk_key_it++)) { if (my_strcasecmp(system_charset_info, f_key->foreign_id->str, drop->name) == 0) { remove_drop= FALSE; break; } } } } if (!remove_drop) { /* Check if the name appears twice in the DROP list. */ List_iterator<Alter_drop> chk_it(alter_info->drop_list); Alter_drop *chk_drop; while ((chk_drop= chk_it++) && chk_drop != drop) { if (drop->type == chk_drop->type && my_strcasecmp(system_charset_info, drop->name, chk_drop->name) == 0) { remove_drop= TRUE; break; } } } if (remove_drop) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_CANT_DROP_FIELD_OR_KEY, ER_THD(thd, ER_CANT_DROP_FIELD_OR_KEY), drop->type_name(), drop->name); drop_it.remove(); if (alter_info->drop_list.is_empty()) alter_info->flags&= ~(Alter_info::ALTER_DROP_COLUMN | Alter_info::ALTER_DROP_INDEX | Alter_info::DROP_FOREIGN_KEY); } } } /* ALTER TABLE ADD KEY IF NOT EXISTS */ /* ALTER TABLE ADD FOREIGN KEY IF NOT EXISTS */ { Key *key; List_iterator<Key> key_it(alter_info->key_list); uint n_key; const char *keyname= NULL; while ((key=key_it++)) { if (!key->if_not_exists() && !key->or_replace()) continue; /* Check if the table already has a PRIMARY KEY */ bool dup_primary_key= key->type == Key::PRIMARY && table->s->primary_key != MAX_KEY; if (dup_primary_key) goto remove_key; /* If the name of the key is not specified, */ /* let us check the name of the first key part. */ if ((keyname= key->name.str) == NULL) { if (key->type == Key::PRIMARY) keyname= primary_key_name; else { List_iterator<Key_part_spec> part_it(key->columns); Key_part_spec *kp; if ((kp= part_it++)) keyname= kp->field_name.str; if (keyname == NULL) continue; } } if (key->type != Key::FOREIGN_KEY) { for (n_key=0; n_key < table->s->keys; n_key++) { if (my_strcasecmp(system_charset_info, keyname, table->key_info[n_key].name) == 0) { goto remove_key; } } } else { List <FOREIGN_KEY_INFO> fk_child_key_list; FOREIGN_KEY_INFO *f_key; table->file->get_foreign_key_list(thd, &fk_child_key_list); List_iterator<FOREIGN_KEY_INFO> fk_key_it(fk_child_key_list); while ((f_key= fk_key_it++)) { if (my_strcasecmp(system_charset_info, f_key->foreign_id->str, keyname) == 0) goto remove_key; } } { Key *chk_key; List_iterator<Key> chk_it(alter_info->key_list); const char *chkname; while ((chk_key=chk_it++) && chk_key != key) { if ((chkname= chk_key->name.str) == NULL) { List_iterator<Key_part_spec> part_it(chk_key->columns); Key_part_spec *kp; if ((kp= part_it++)) chkname= kp->field_name.str; if (keyname == NULL) continue; } if (key->type == chk_key->type && my_strcasecmp(system_charset_info, keyname, chkname) == 0) goto remove_key; } } continue; remove_key: if (key->if_not_exists()) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_DUP_KEYNAME, ER_THD(thd, dup_primary_key ? ER_MULTIPLE_PRI_KEY : ER_DUP_KEYNAME), keyname); key_it.remove(); if (key->type == Key::FOREIGN_KEY) { /* ADD FOREIGN KEY appends two items. */ key_it.remove(); } if (alter_info->key_list.is_empty()) alter_info->flags&= ~(Alter_info::ALTER_ADD_INDEX | Alter_info::ADD_FOREIGN_KEY); } else { DBUG_ASSERT(key->or_replace()); Alter_drop::drop_type type= (key->type == Key::FOREIGN_KEY) ? Alter_drop::FOREIGN_KEY : Alter_drop::KEY; Alter_drop *ad= new Alter_drop(type, key->name.str, FALSE); if (ad != NULL) { // Adding the index into the drop list for replacing alter_info->flags |= Alter_info::ALTER_DROP_INDEX; alter_info->drop_list.push_back(ad, thd->mem_root); } } } } #ifdef WITH_PARTITION_STORAGE_ENGINE partition_info *tab_part_info= table->part_info; if (tab_part_info) { /* ALTER TABLE ADD PARTITION IF NOT EXISTS */ if ((alter_info->flags & Alter_info::ALTER_ADD_PARTITION) && thd->lex->create_info.if_not_exists()) { partition_info *alt_part_info= thd->lex->part_info; if (alt_part_info) { List_iterator<partition_element> new_part_it(alt_part_info->partitions); partition_element *pe; while ((pe= new_part_it++)) { if (!tab_part_info->has_unique_name(pe)) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_SAME_NAME_PARTITION, ER_THD(thd, ER_SAME_NAME_PARTITION), pe->partition_name); alter_info->flags&= ~Alter_info::ALTER_ADD_PARTITION; thd->lex->part_info= NULL; break; } } } } /* ALTER TABLE DROP PARTITION IF EXISTS */ if ((alter_info->flags & Alter_info::ALTER_DROP_PARTITION) && thd->lex->if_exists()) { List_iterator<char> names_it(alter_info->partition_names); char *name; while ((name= names_it++)) { List_iterator<partition_element> part_it(tab_part_info->partitions); partition_element *part_elem; while ((part_elem= part_it++)) { if (my_strcasecmp(system_charset_info, part_elem->partition_name, name) == 0) break; } if (!part_elem) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_DROP_PARTITION_NON_EXISTENT, ER_THD(thd, ER_DROP_PARTITION_NON_EXISTENT), "DROP"); names_it.remove(); } } if (alter_info->partition_names.elements == 0) alter_info->flags&= ~Alter_info::ALTER_DROP_PARTITION; } } #endif /*WITH_PARTITION_STORAGE_ENGINE*/ /* ADD CONSTRAINT IF NOT EXISTS. */ { List_iterator<Virtual_column_info> it(alter_info->check_constraint_list); Virtual_column_info *check; TABLE_SHARE *share= table->s; uint c; while ((check=it++)) { if (!(check->flags & Alter_info::CHECK_CONSTRAINT_IF_NOT_EXISTS) && check->name.length) continue; check->flags= 0; for (c= share->field_check_constraints; c < share->table_check_constraints ; c++) { Virtual_column_info *dup= table->check_constraints[c]; if (dup->name.length == check->name.length && my_strcasecmp(system_charset_info, check->name.str, dup->name.str) == 0) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_DUP_CONSTRAINT_NAME, ER_THD(thd, ER_DUP_CONSTRAINT_NAME), "CHECK", check->name.str); it.remove(); if (alter_info->check_constraint_list.elements == 0) alter_info->flags&= ~Alter_info::ALTER_ADD_CHECK_CONSTRAINT; break; } } } } DBUG_VOID_RETURN; } /** Get Create_field object for newly created table by field index. @param alter_info Alter_info describing newly created table. @param idx Field index. */ static Create_field *get_field_by_index(Alter_info *alter_info, uint idx) { List_iterator_fast<Create_field> field_it(alter_info->create_list); uint field_idx= 0; Create_field *field; while ((field= field_it++) && field_idx < idx) { field_idx++; } return field; } static int compare_uint(const uint *s, const uint *t) { return (*s < *t) ? -1 : ((*s > *t) ? 1 : 0); } /** Compare original and new versions of a table and fill Alter_inplace_info describing differences between those versions. @param thd Thread @param table The original table. @param varchar Indicates that new definition has new VARCHAR column. @param[in/out] ha_alter_info Data structure which already contains basic information about create options, field and keys for the new version of table and which should be completed with more detailed information needed for in-place ALTER. First argument 'table' contains information of the original table, which includes all corresponding parts that the new table has in arguments create_list, key_list and create_info. Compare the changes between the original and new table definitions. The result of this comparison is then passed to SE which determines whether it can carry out these changes in-place. Mark any changes detected in the ha_alter_flags. We generally try to specify handler flags only if there are real changes. But in cases when it is cumbersome to determine if some attribute has really changed we might choose to set flag pessimistically, for example, relying on parser output only. If there are no data changes, but index changes, 'index_drop_buffer' and/or 'index_add_buffer' are populated with offsets into table->key_info or key_info_buffer respectively for the indexes that need to be dropped and/or (re-)created. Note that this function assumes that it is OK to change Alter_info and HA_CREATE_INFO which it gets. It is caller who is responsible for creating copies for this structures if he needs them unchanged. @retval true error @retval false success */ static bool fill_alter_inplace_info(THD *thd, TABLE *table, bool varchar, Alter_inplace_info *ha_alter_info) { Field **f_ptr, *field; List_iterator_fast<Create_field> new_field_it; Create_field *new_field; KEY_PART_INFO *key_part, *new_part; KEY_PART_INFO *end; uint candidate_key_count= 0; Alter_info *alter_info= ha_alter_info->alter_info; DBUG_ENTER("fill_alter_inplace_info"); /* Allocate result buffers. */ if (! (ha_alter_info->index_drop_buffer= (KEY**) thd->alloc(sizeof(KEY*) * table->s->keys)) || ! (ha_alter_info->index_add_buffer= (uint*) thd->alloc(sizeof(uint) * alter_info->key_list.elements))) DBUG_RETURN(true); /* Comparing new and old default values of column is cumbersome. So instead of using such a comparison for detecting if default has really changed we rely on flags set by parser to get an approximate value for storage engine flag. */ if (alter_info->flags & (Alter_info::ALTER_CHANGE_COLUMN | Alter_info::ALTER_CHANGE_COLUMN_DEFAULT)) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_DEFAULT; if (alter_info->flags & Alter_info::ADD_FOREIGN_KEY) ha_alter_info->handler_flags|= Alter_inplace_info::ADD_FOREIGN_KEY; if (alter_info->flags & Alter_info::DROP_FOREIGN_KEY) ha_alter_info->handler_flags|= Alter_inplace_info::DROP_FOREIGN_KEY; if (alter_info->flags & Alter_info::ALTER_OPTIONS) ha_alter_info->handler_flags|= Alter_inplace_info::CHANGE_CREATE_OPTION; if (alter_info->flags & Alter_info::ALTER_RENAME) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_RENAME; /* Check partition changes */ if (alter_info->flags & Alter_info::ALTER_ADD_PARTITION) ha_alter_info->handler_flags|= Alter_inplace_info::ADD_PARTITION; if (alter_info->flags & Alter_info::ALTER_DROP_PARTITION) ha_alter_info->handler_flags|= Alter_inplace_info::DROP_PARTITION; if (alter_info->flags & Alter_info::ALTER_PARTITION) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_PARTITION; if (alter_info->flags & Alter_info::ALTER_COALESCE_PARTITION) ha_alter_info->handler_flags|= Alter_inplace_info::COALESCE_PARTITION; if (alter_info->flags & Alter_info::ALTER_REORGANIZE_PARTITION) ha_alter_info->handler_flags|= Alter_inplace_info::REORGANIZE_PARTITION; if (alter_info->flags & Alter_info::ALTER_TABLE_REORG) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_TABLE_REORG; if (alter_info->flags & Alter_info::ALTER_REMOVE_PARTITIONING) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_REMOVE_PARTITIONING; if (alter_info->flags & Alter_info::ALTER_ALL_PARTITION) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_ALL_PARTITION; /* Check for: ALTER TABLE FORCE, ALTER TABLE ENGINE and OPTIMIZE TABLE. */ if (alter_info->flags & Alter_info::ALTER_RECREATE) ha_alter_info->handler_flags|= Alter_inplace_info::RECREATE_TABLE; if (alter_info->flags & Alter_info::ALTER_ADD_CHECK_CONSTRAINT) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_ADD_CHECK_CONSTRAINT; if (alter_info->flags & Alter_info::ALTER_DROP_CHECK_CONSTRAINT) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_DROP_CHECK_CONSTRAINT; /* If we altering table with old VARCHAR fields we will be automatically upgrading VARCHAR column types. */ if (table->s->frm_version < FRM_VER_TRUE_VARCHAR && varchar) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_STORED_COLUMN_TYPE; /* Go through fields in old version of table and detect changes to them. We don't want to rely solely on Alter_info flags for this since: a) new definition of column can be fully identical to the old one despite the fact that this column is mentioned in MODIFY clause. b) even if new column type differs from its old column from metadata point of view, it might be identical from storage engine point of view (e.g. when ENUM('a','b') is changed to ENUM('a','b',c')). c) flags passed to storage engine contain more detailed information about nature of changes than those provided from parser. */ bool maybe_alter_vcol= false; uint field_stored_index= 0; for (f_ptr= table->field; (field= *f_ptr); f_ptr++, field_stored_index+= field->stored_in_db()) { /* Clear marker for renamed or dropped field which we are going to set later. */ field->flags&= ~(FIELD_IS_RENAMED | FIELD_IS_DROPPED); /* Use transformed info to evaluate flags for storage engine. */ uint new_field_index= 0, new_field_stored_index= 0; new_field_it.init(alter_info->create_list); while ((new_field= new_field_it++)) { if (new_field->field == field) break; new_field_index++; new_field_stored_index+= new_field->stored_in_db(); } if (new_field) { /* Field is not dropped. Evaluate changes bitmap for it. */ /* Check if type of column has changed to some incompatible type. */ uint is_equal= field->is_equal(new_field); switch (is_equal) { case IS_EQUAL_NO: /* New column type is incompatible with old one. */ if (field->stored_in_db()) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_STORED_COLUMN_TYPE; else ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_VIRTUAL_COLUMN_TYPE; if (table->s->tmp_table == NO_TMP_TABLE) { delete_statistics_for_column(thd, table, field); KEY *key_info= table->key_info; for (uint i=0; i < table->s->keys; i++, key_info++) { if (field->part_of_key.is_set(i)) { uint key_parts= table->actual_n_key_parts(key_info); for (uint j= 0; j < key_parts; j++) { if (key_info->key_part[j].fieldnr-1 == field->field_index) { delete_statistics_for_index(thd, table, key_info, j >= key_info->user_defined_key_parts); break; } } } } } break; case IS_EQUAL_YES: /* New column is the same as the old one or the fully compatible with it (for example, ENUM('a','b') was changed to ENUM('a','b','c')). Such a change if any can ALWAYS be carried out by simply updating data-dictionary without even informing storage engine. No flag is set in this case. */ break; case IS_EQUAL_PACK_LENGTH: /* New column type differs from the old one, but has compatible packed data representation. Depending on storage engine, such a change can be carried out by simply updating data dictionary without changing actual data (for example, VARCHAR(300) is changed to VARCHAR(400)). */ ha_alter_info->handler_flags|= Alter_inplace_info:: ALTER_COLUMN_EQUAL_PACK_LENGTH; break; default: DBUG_ASSERT(0); /* Safety. */ ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_STORED_COLUMN_TYPE; } if (field->vcol_info || new_field->vcol_info) { /* base <-> virtual or stored <-> virtual */ if (field->stored_in_db() != new_field->stored_in_db()) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_STORED_COLUMN_TYPE | Alter_inplace_info::ALTER_VIRTUAL_COLUMN_TYPE; if (field->vcol_info && new_field->vcol_info) { bool value_changes= is_equal == IS_EQUAL_NO; Alter_inplace_info::HA_ALTER_FLAGS alter_expr; if (field->stored_in_db()) alter_expr= Alter_inplace_info::ALTER_STORED_GCOL_EXPR; else alter_expr= Alter_inplace_info::ALTER_VIRTUAL_GCOL_EXPR; if (!field->vcol_info->is_equal(new_field->vcol_info)) { ha_alter_info->handler_flags|= alter_expr; value_changes= true; } if ((ha_alter_info->handler_flags & Alter_inplace_info::ALTER_COLUMN_DEFAULT) && !(ha_alter_info->handler_flags & alter_expr)) { /* a DEFAULT value of a some column was changed. see if this vcol uses DEFAULT() function. The check is kind of expensive, so don't do it if ALTER_COLUMN_VCOL is already set. */ if (field->vcol_info->expr->walk( &Item::check_func_default_processor, 0, 0)) { ha_alter_info->handler_flags|= alter_expr; value_changes= true; } } if (field->vcol_info->is_in_partitioning_expr() || field->flags & PART_KEY_FLAG) { if (value_changes) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_VCOL; else maybe_alter_vcol= true; } } else /* base <-> stored */ ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_STORED_COLUMN_TYPE; } /* Check if field was renamed */ if (my_strcasecmp(system_charset_info, field->field_name, new_field->field_name)) { field->flags|= FIELD_IS_RENAMED; ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_NAME; rename_column_in_stat_tables(thd, table, field, new_field->field_name); } /* Check that NULL behavior is same for old and new fields */ if ((new_field->flags & NOT_NULL_FLAG) != (uint) (field->flags & NOT_NULL_FLAG)) { if (new_field->flags & NOT_NULL_FLAG) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_NOT_NULLABLE; else ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_NULLABLE; } /* We do not detect changes to default values in this loop. See comment above for more details. */ /* Detect changes in column order. */ if (field->stored_in_db()) { if (field_stored_index != new_field_stored_index) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_STORED_COLUMN_ORDER; } else { if (field->field_index != new_field_index) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_VIRTUAL_COLUMN_ORDER; } /* Detect changes in storage type of column */ if (new_field->field_storage_type() != field->field_storage_type()) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_STORAGE_TYPE; /* Detect changes in column format of column */ if (new_field->column_format() != field->column_format()) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_COLUMN_FORMAT; if (engine_options_differ(field->option_struct, new_field->option_struct, table->file->ht->field_options)) { ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_OPTION; ha_alter_info->create_info->fields_option_struct[f_ptr - table->field]= new_field->option_struct; } } else { // Field is not present in new version of table and therefore was dropped. field->flags|= FIELD_IS_DROPPED; if (field->stored_in_db()) ha_alter_info->handler_flags|= Alter_inplace_info::DROP_STORED_COLUMN; else ha_alter_info->handler_flags|= Alter_inplace_info::DROP_VIRTUAL_COLUMN; } } if (maybe_alter_vcol) { /* What if one of the normal columns was altered and it was part of the some virtual column expression? Currently we don't detect this correctly (FIXME), so let's just say that a vcol *might* be affected if any other column was altered. */ if (ha_alter_info->handler_flags & ( Alter_inplace_info::ALTER_STORED_COLUMN_TYPE | Alter_inplace_info::ALTER_VIRTUAL_COLUMN_TYPE | Alter_inplace_info::ALTER_COLUMN_NOT_NULLABLE | Alter_inplace_info::ALTER_COLUMN_OPTION )) ha_alter_info->handler_flags|= Alter_inplace_info::ALTER_COLUMN_VCOL; } new_field_it.init(alter_info->create_list); while ((new_field= new_field_it++)) { if (! new_field->field) { // Field is not present in old version of table and therefore was added. if (new_field->vcol_info) if (new_field->stored_in_db()) ha_alter_info->handler_flags|= Alter_inplace_info::ADD_STORED_GENERATED_COLUMN; else ha_alter_info->handler_flags|= Alter_inplace_info::ADD_VIRTUAL_COLUMN; else ha_alter_info->handler_flags|= Alter_inplace_info::ADD_STORED_BASE_COLUMN; } } /* Go through keys and check if the original ones are compatible with new table. */ KEY *table_key; KEY *table_key_end= table->key_info + table->s->keys; KEY *new_key; KEY *new_key_end= ha_alter_info->key_info_buffer + ha_alter_info->key_count; DBUG_PRINT("info", ("index count old: %d new: %d", table->s->keys, ha_alter_info->key_count)); /* Step through all keys of the old table and search matching new keys. */ ha_alter_info->index_drop_count= 0; ha_alter_info->index_add_count= 0; for (table_key= table->key_info; table_key < table_key_end; table_key++) { /* Search a new key with the same name. */ for (new_key= ha_alter_info->key_info_buffer; new_key < new_key_end; new_key++) { if (! strcmp(table_key->name, new_key->name)) break; } if (new_key >= new_key_end) { /* Key not found. Add the key to the drop buffer. */ ha_alter_info->index_drop_buffer [ha_alter_info->index_drop_count++]= table_key; DBUG_PRINT("info", ("index dropped: '%s'", table_key->name)); continue; } /* Check that the key types are compatible between old and new tables. */ if ((table_key->algorithm != new_key->algorithm) || ((table_key->flags & HA_KEYFLAG_MASK) != (new_key->flags & HA_KEYFLAG_MASK)) || (table_key->user_defined_key_parts != new_key->user_defined_key_parts)) goto index_changed; if (table_key->block_size != new_key->block_size) goto index_changed; if (engine_options_differ(table_key->option_struct, new_key->option_struct, table->file->ht->index_options)) goto index_changed; /* Check that the key parts remain compatible between the old and new tables. */ end= table_key->key_part + table_key->user_defined_key_parts; for (key_part= table_key->key_part, new_part= new_key->key_part; key_part < end; key_part++, new_part++) { /* Key definition has changed if we are using a different field or if the used key part length is different. It makes sense to check lengths first as in case when fields differ it is likely that lengths differ too and checking fields is more expensive in general case. */ if (key_part->length != new_part->length) goto index_changed; new_field= get_field_by_index(alter_info, new_part->fieldnr); /* For prefix keys KEY_PART_INFO::field points to cloned Field object with adjusted length. So below we have to check field indexes instead of simply comparing pointers to Field objects. */ if (! new_field->field || new_field->field->field_index != key_part->fieldnr - 1) goto index_changed; } /* Check that key comment is not changed. */ if (table_key->comment.length != new_key->comment.length || (table_key->comment.length && memcmp(table_key->comment.str, new_key->comment.str, table_key->comment.length) != 0)) goto index_changed; continue; index_changed: /* Key modified. Add the key / key offset to both buffers. */ ha_alter_info->index_drop_buffer [ha_alter_info->index_drop_count++]= table_key; ha_alter_info->index_add_buffer [ha_alter_info->index_add_count++]= (uint)(new_key - ha_alter_info->key_info_buffer); /* Mark all old fields which are used in newly created index. */ DBUG_PRINT("info", ("index changed: '%s'", table_key->name)); } /*end of for (; table_key < table_key_end;) */ /* Step through all keys of the new table and find matching old keys. */ for (new_key= ha_alter_info->key_info_buffer; new_key < new_key_end; new_key++) { /* Search an old key with the same name. */ for (table_key= table->key_info; table_key < table_key_end; table_key++) { if (! strcmp(table_key->name, new_key->name)) break; } if (table_key >= table_key_end) { /* Key not found. Add the offset of the key to the add buffer. */ ha_alter_info->index_add_buffer [ha_alter_info->index_add_count++]= (uint)(new_key - ha_alter_info->key_info_buffer); DBUG_PRINT("info", ("index added: '%s'", new_key->name)); } else ha_alter_info->create_info->indexes_option_struct[table_key - table->key_info]= new_key->option_struct; } /* Sort index_add_buffer according to how key_info_buffer is sorted. I.e. with primary keys first - see sort_keys(). */ my_qsort(ha_alter_info->index_add_buffer, ha_alter_info->index_add_count, sizeof(uint), (qsort_cmp) compare_uint); /* Now let us calculate flags for storage engine API. */ /* Count all existing candidate keys. */ for (table_key= table->key_info; table_key < table_key_end; table_key++) { /* Check if key is a candidate key, This key is either already primary key or could be promoted to primary key if the original primary key is dropped. In MySQL one is allowed to create primary key with partial fields (i.e. primary key which is not considered candidate). For simplicity we count such key as a candidate key here. */ if (((uint) (table_key - table->key_info) == table->s->primary_key) || is_candidate_key(table_key)) candidate_key_count++; } /* Figure out what kind of indexes we are dropping. */ KEY **dropped_key; KEY **dropped_key_end= ha_alter_info->index_drop_buffer + ha_alter_info->index_drop_count; for (dropped_key= ha_alter_info->index_drop_buffer; dropped_key < dropped_key_end; dropped_key++) { table_key= *dropped_key; if (table_key->flags & HA_NOSAME) { /* Unique key. Check for PRIMARY KEY. Also see comment about primary and candidate keys above. */ if ((uint) (table_key - table->key_info) == table->s->primary_key) { ha_alter_info->handler_flags|= Alter_inplace_info::DROP_PK_INDEX; candidate_key_count--; } else { ha_alter_info->handler_flags|= Alter_inplace_info::DROP_UNIQUE_INDEX; if (is_candidate_key(table_key)) candidate_key_count--; } } else ha_alter_info->handler_flags|= Alter_inplace_info::DROP_INDEX; } /* Now figure out what kind of indexes we are adding. */ for (uint add_key_idx= 0; add_key_idx < ha_alter_info->index_add_count; add_key_idx++) { new_key= ha_alter_info->key_info_buffer + ha_alter_info->index_add_buffer[add_key_idx]; if (new_key->flags & HA_NOSAME) { bool is_pk= !my_strcasecmp(system_charset_info, new_key->name, primary_key_name); if ((!(new_key->flags & HA_KEY_HAS_PART_KEY_SEG) && !(new_key->flags & HA_NULL_PART_KEY)) || is_pk) { /* Candidate key or primary key! */ if (candidate_key_count == 0 || is_pk) ha_alter_info->handler_flags|= Alter_inplace_info::ADD_PK_INDEX; else ha_alter_info->handler_flags|= Alter_inplace_info::ADD_UNIQUE_INDEX; candidate_key_count++; } else { ha_alter_info->handler_flags|= Alter_inplace_info::ADD_UNIQUE_INDEX; } } else ha_alter_info->handler_flags|= Alter_inplace_info::ADD_INDEX; } DBUG_RETURN(false); } /** Mark fields participating in newly added indexes in TABLE object which corresponds to new version of altered table. @param ha_alter_info Alter_inplace_info describing in-place ALTER. @param altered_table TABLE object for new version of TABLE in which fields should be marked. */ static void update_altered_table(const Alter_inplace_info &ha_alter_info, TABLE *altered_table) { uint field_idx, add_key_idx; KEY *key; KEY_PART_INFO *end, *key_part; /* Clear marker for all fields, as we are going to set it only for fields which participate in new indexes. */ for (field_idx= 0; field_idx < altered_table->s->fields; ++field_idx) altered_table->field[field_idx]->flags&= ~FIELD_IN_ADD_INDEX; /* Go through array of newly added indexes and mark fields participating in them. */ for (add_key_idx= 0; add_key_idx < ha_alter_info.index_add_count; add_key_idx++) { key= ha_alter_info.key_info_buffer + ha_alter_info.index_add_buffer[add_key_idx]; end= key->key_part + key->user_defined_key_parts; for (key_part= key->key_part; key_part < end; key_part++) altered_table->field[key_part->fieldnr]->flags|= FIELD_IN_ADD_INDEX; } } /** Compare two tables to see if their metadata are compatible. One table specified by a TABLE instance, the other using Alter_info and HA_CREATE_INFO. @param[in] table The first table. @param[in] alter_info Alter options, fields and keys for the second table. @param[in] create_info Create options for the second table. @param[out] metadata_equal Result of comparison. @retval true error @retval false success */ bool mysql_compare_tables(TABLE *table, Alter_info *alter_info, HA_CREATE_INFO *create_info, bool *metadata_equal) { DBUG_ENTER("mysql_compare_tables"); uint changes= IS_EQUAL_NO; uint key_count; List_iterator_fast<Create_field> tmp_new_field_it; THD *thd= table->in_use; *metadata_equal= false; /* Create a copy of alter_info. To compare definitions, we need to "prepare" the definition - transform it from parser output to a format that describes the table layout (all column defaults are initialized, duplicate columns are removed). This is done by mysql_prepare_create_table. Unfortunately, mysql_prepare_create_table performs its transformations "in-place", that is, modifies the argument. Since we would like to keep mysql_compare_tables() idempotent (not altering any of the arguments) we create a copy of alter_info here and pass it to mysql_prepare_create_table, then use the result to compare the tables, and then destroy the copy. */ Alter_info tmp_alter_info(*alter_info, thd->mem_root); uint db_options= 0; /* not used */ KEY *key_info_buffer= NULL; /* Create the prepared information. */ int create_table_mode= table->s->tmp_table == NO_TMP_TABLE ? C_ORDINARY_CREATE : C_ALTER_TABLE; if (mysql_prepare_create_table(thd, create_info, &tmp_alter_info, &db_options, table->file, &key_info_buffer, &key_count, create_table_mode)) DBUG_RETURN(1); /* Some very basic checks. */ if (table->s->fields != alter_info->create_list.elements || table->s->db_type() != create_info->db_type || table->s->tmp_table || (table->s->row_type != create_info->row_type)) DBUG_RETURN(false); /* Go through fields and check if they are compatible. */ tmp_new_field_it.init(tmp_alter_info.create_list); for (Field **f_ptr= table->field; *f_ptr; f_ptr++) { Field *field= *f_ptr; Create_field *tmp_new_field= tmp_new_field_it++; /* Check that NULL behavior is the same. */ if ((tmp_new_field->flags & NOT_NULL_FLAG) != (uint) (field->flags & NOT_NULL_FLAG)) DBUG_RETURN(false); /* mysql_prepare_alter_table() clears HA_OPTION_PACK_RECORD bit when preparing description of existing table. In ALTER TABLE it is later updated to correct value by create_table_impl() call. So to get correct value of this bit in this function we have to mimic behavior of create_table_impl(). */ if (create_info->row_type == ROW_TYPE_DYNAMIC || create_info->row_type == ROW_TYPE_PAGE || (tmp_new_field->flags & BLOB_FLAG) || (tmp_new_field->sql_type == MYSQL_TYPE_VARCHAR && create_info->row_type != ROW_TYPE_FIXED)) create_info->table_options|= HA_OPTION_PACK_RECORD; /* Check if field was renamed */ if (my_strcasecmp(system_charset_info, field->field_name, tmp_new_field->field_name)) DBUG_RETURN(false); /* Evaluate changes bitmap and send to check_if_incompatible_data() */ uint field_changes= field->is_equal(tmp_new_field); if (field_changes != IS_EQUAL_YES) DBUG_RETURN(false); changes|= field_changes; } /* Check if changes are compatible with current handler. */ if (table->file->check_if_incompatible_data(create_info, changes)) DBUG_RETURN(false); /* Go through keys and check if they are compatible. */ KEY *table_key; KEY *table_key_end= table->key_info + table->s->keys; KEY *new_key; KEY *new_key_end= key_info_buffer + key_count; /* Step through all keys of the first table and search matching keys. */ for (table_key= table->key_info; table_key < table_key_end; table_key++) { /* Search a key with the same name. */ for (new_key= key_info_buffer; new_key < new_key_end; new_key++) { if (! strcmp(table_key->name, new_key->name)) break; } if (new_key >= new_key_end) DBUG_RETURN(false); /* Check that the key types are compatible. */ if ((table_key->algorithm != new_key->algorithm) || ((table_key->flags & HA_KEYFLAG_MASK) != (new_key->flags & HA_KEYFLAG_MASK)) || (table_key->user_defined_key_parts != new_key->user_defined_key_parts)) DBUG_RETURN(false); /* Check that the key parts remain compatible. */ KEY_PART_INFO *table_part; KEY_PART_INFO *table_part_end= table_key->key_part + table_key->user_defined_key_parts; KEY_PART_INFO *new_part; for (table_part= table_key->key_part, new_part= new_key->key_part; table_part < table_part_end; table_part++, new_part++) { /* Key definition is different if we are using a different field or if the used key part length is different. We know that the fields are equal. Comparing field numbers is sufficient. */ if ((table_part->length != new_part->length) || (table_part->fieldnr - 1 != new_part->fieldnr)) DBUG_RETURN(false); } } /* Step through all keys of the second table and find matching keys. */ for (new_key= key_info_buffer; new_key < new_key_end; new_key++) { /* Search a key with the same name. */ for (table_key= table->key_info; table_key < table_key_end; table_key++) { if (! strcmp(table_key->name, new_key->name)) break; } if (table_key >= table_key_end) DBUG_RETURN(false); } *metadata_equal= true; // Tables are compatible DBUG_RETURN(false); } /* Manages enabling/disabling of indexes for ALTER TABLE SYNOPSIS alter_table_manage_keys() table Target table indexes_were_disabled Whether the indexes of the from table were disabled keys_onoff ENABLE | DISABLE | LEAVE_AS_IS RETURN VALUES FALSE OK TRUE Error */ static bool alter_table_manage_keys(TABLE *table, int indexes_were_disabled, Alter_info::enum_enable_or_disable keys_onoff) { int error= 0; DBUG_ENTER("alter_table_manage_keys"); DBUG_PRINT("enter", ("table=%p were_disabled=%d on_off=%d", table, indexes_were_disabled, keys_onoff)); switch (keys_onoff) { case Alter_info::ENABLE: DEBUG_SYNC(table->in_use, "alter_table_enable_indexes"); error= table->file->ha_enable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE); break; case Alter_info::LEAVE_AS_IS: if (!indexes_were_disabled) break; /* fall through */ case Alter_info::DISABLE: error= table->file->ha_disable_indexes(HA_KEY_SWITCH_NONUNIQ_SAVE); } if (error == HA_ERR_WRONG_COMMAND) { THD *thd= table->in_use; push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_ILLEGAL_HA, ER_THD(thd, ER_ILLEGAL_HA), table->file->table_type(), table->s->db.str, table->s->table_name.str); error= 0; } else if (error) table->file->print_error(error, MYF(0)); DBUG_RETURN(error); } /** Check if the pending ALTER TABLE operations support the in-place algorithm based on restrictions in the SQL layer or given the nature of the operations themselves. If in-place isn't supported, it won't be necessary to check with the storage engine. @param table The original TABLE. @param create_info Information from the parsing phase about new table properties. @param alter_info Data related to detected changes. @return false In-place is possible, check with storage engine. @return true Incompatible operations, must use table copy. */ static bool is_inplace_alter_impossible(TABLE *table, HA_CREATE_INFO *create_info, const Alter_info *alter_info) { DBUG_ENTER("is_inplace_alter_impossible"); /* At the moment we can't handle altering temporary tables without a copy. */ if (table->s->tmp_table) DBUG_RETURN(true); /* For the ALTER TABLE tbl_name ORDER BY ... we always use copy algorithm. In theory, this operation can be done in-place by some engine, but since a) no current engine does this and b) our current API lacks infrastructure for passing information about table ordering to storage engine we simply always do copy now. ENABLE/DISABLE KEYS is a MyISAM/Heap specific operation that is not supported for in-place in combination with other operations. Alone, it will be done by simple_rename_or_index_change(). */ if (alter_info->flags & (Alter_info::ALTER_ORDER | Alter_info::ALTER_KEYS_ONOFF)) DBUG_RETURN(true); /* If the table engine is changed explicitly (using ENGINE clause) or implicitly (e.g. when non-partitioned table becomes partitioned) a regular alter table (copy) needs to be performed. */ if (create_info->db_type != table->s->db_type()) DBUG_RETURN(true); /* There was a bug prior to mysql-4.0.25. Number of null fields was calculated incorrectly. As a result frm and data files gets out of sync after fast alter table. There is no way to determine by which mysql version (in 4.0 and 4.1 branches) table was created, thus we disable fast alter table for all tables created by mysql versions prior to 5.0 branch. See BUG#6236. */ if (!table->s->mysql_version) DBUG_RETURN(true); /* If we are using a MySQL 5.7 table with virtual fields, ALTER TABLE must recreate the table as we need to rewrite generated fields */ if (table->s->mysql_version > 50700 && table->s->mysql_version < 100000 && table->s->virtual_fields) DBUG_RETURN(TRUE); DBUG_RETURN(false); } /** Perform in-place alter table. @param thd Thread handle. @param table_list TABLE_LIST for the table to change. @param table The original TABLE. @param altered_table TABLE object for new version of the table. @param ha_alter_info Structure describing ALTER TABLE to be carried out and serving as a storage place for data used during different phases. @param inplace_supported Enum describing the locking requirements. @param target_mdl_request Metadata request/lock on the target table name. @param alter_ctx ALTER TABLE runtime context. @retval true Error @retval false Success @note If mysql_alter_table does not need to copy the table, it is either an alter table where the storage engine does not need to know about the change, only the frm will change, or the storage engine supports performing the alter table operation directly, in-place without mysql having to copy the table. @note This function frees the TABLE object associated with the new version of the table and removes the .FRM file for it in case of both success and failure. */ static bool mysql_inplace_alter_table(THD *thd, TABLE_LIST *table_list, TABLE *table, TABLE *altered_table, Alter_inplace_info *ha_alter_info, enum_alter_inplace_result inplace_supported, MDL_request *target_mdl_request, Alter_table_ctx *alter_ctx) { Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN | MYSQL_OPEN_IGNORE_KILLED); handlerton *db_type= table->s->db_type(); MDL_ticket *mdl_ticket= table->mdl_ticket; HA_CREATE_INFO *create_info= ha_alter_info->create_info; Alter_info *alter_info= ha_alter_info->alter_info; bool reopen_tables= false; bool res; DBUG_ENTER("mysql_inplace_alter_table"); /* Upgrade to EXCLUSIVE lock if: - This is requested by the storage engine - Or the storage engine needs exclusive lock for just the prepare phase - Or requested by the user Note that we handle situation when storage engine needs exclusive lock for prepare phase under LOCK TABLES in the same way as when exclusive lock is required for duration of the whole statement. */ if (inplace_supported == HA_ALTER_INPLACE_EXCLUSIVE_LOCK || ((inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE || inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE) && (thd->locked_tables_mode == LTM_LOCK_TABLES || thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)) || alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE) { if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN)) goto cleanup; /* Get rid of all TABLE instances belonging to this thread except one to be used for in-place ALTER TABLE. This is mostly needed to satisfy InnoDB assumptions/asserts. */ close_all_tables_for_name(thd, table->s, alter_ctx->is_table_renamed() ? HA_EXTRA_PREPARE_FOR_RENAME : HA_EXTRA_NOT_USED, table); /* If we are under LOCK TABLES we will need to reopen tables which we just have closed in case of error. */ reopen_tables= true; } else if (inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE || inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE) { /* Storage engine has requested exclusive lock only for prepare phase and we are not under LOCK TABLES. Don't mark TABLE_SHARE as old in this case, as this won't allow opening of table by other threads during main phase of in-place ALTER TABLE. */ if (thd->mdl_context.upgrade_shared_lock(table->mdl_ticket, MDL_EXCLUSIVE, thd->variables.lock_wait_timeout)) goto cleanup; tdc_remove_table(thd, TDC_RT_REMOVE_NOT_OWN_KEEP_SHARE, table->s->db.str, table->s->table_name.str, false); } /* Upgrade to SHARED_NO_WRITE lock if: - The storage engine needs writes blocked for the whole duration - Or this is requested by the user Note that under LOCK TABLES, we will already have SHARED_NO_READ_WRITE. */ if ((inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK || alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_SHARED) && thd->mdl_context.upgrade_shared_lock(table->mdl_ticket, MDL_SHARED_NO_WRITE, thd->variables.lock_wait_timeout)) { goto cleanup; } // It's now safe to take the table level lock. if (lock_tables(thd, table_list, alter_ctx->tables_opened, 0)) goto cleanup; DEBUG_SYNC(thd, "alter_table_inplace_after_lock_upgrade"); THD_STAGE_INFO(thd, stage_alter_inplace_prepare); switch (inplace_supported) { case HA_ALTER_ERROR: case HA_ALTER_INPLACE_NOT_SUPPORTED: DBUG_ASSERT(0); // fall through case HA_ALTER_INPLACE_NO_LOCK: case HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE: switch (alter_info->requested_lock) { case Alter_info::ALTER_TABLE_LOCK_DEFAULT: case Alter_info::ALTER_TABLE_LOCK_NONE: ha_alter_info->online= true; break; case Alter_info::ALTER_TABLE_LOCK_SHARED: case Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE: break; } break; case HA_ALTER_INPLACE_EXCLUSIVE_LOCK: case HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE: case HA_ALTER_INPLACE_SHARED_LOCK: break; } if (table->file->ha_prepare_inplace_alter_table(altered_table, ha_alter_info)) { goto rollback; } /* Downgrade the lock if storage engine has told us that exclusive lock was necessary only for prepare phase (unless we are not under LOCK TABLES) and user has not explicitly requested exclusive lock. */ if ((inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE || inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE) && !(thd->locked_tables_mode == LTM_LOCK_TABLES || thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) && (alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE)) { /* If storage engine or user requested shared lock downgrade to SNW. */ if (inplace_supported == HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE || alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_SHARED) table->mdl_ticket->downgrade_lock(MDL_SHARED_NO_WRITE); else { DBUG_ASSERT(inplace_supported == HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE); table->mdl_ticket->downgrade_lock(MDL_SHARED_UPGRADABLE); } } DEBUG_SYNC(thd, "alter_table_inplace_after_lock_downgrade"); THD_STAGE_INFO(thd, stage_alter_inplace); /* We can abort alter table for any table type */ thd->abort_on_warning= !ha_alter_info->ignore && thd->is_strict_mode(); res= table->file->ha_inplace_alter_table(altered_table, ha_alter_info); thd->abort_on_warning= false; if (res) goto rollback; // Upgrade to EXCLUSIVE before commit. if (wait_while_table_is_used(thd, table, HA_EXTRA_PREPARE_FOR_RENAME)) goto rollback; /* If we are killed after this point, we should ignore and continue. We have mostly completed the operation at this point, there should be no long waits left. */ DBUG_EXECUTE_IF("alter_table_rollback_new_index", { table->file->ha_commit_inplace_alter_table(altered_table, ha_alter_info, false); my_error(ER_UNKNOWN_ERROR, MYF(0)); goto cleanup; }); DEBUG_SYNC(thd, "alter_table_inplace_before_commit"); THD_STAGE_INFO(thd, stage_alter_inplace_commit); if (table->file->ha_commit_inplace_alter_table(altered_table, ha_alter_info, true)) { goto rollback; } close_all_tables_for_name(thd, table->s, alter_ctx->is_table_renamed() ? HA_EXTRA_PREPARE_FOR_RENAME : HA_EXTRA_NOT_USED, NULL); table_list->table= table= NULL; thd->drop_temporary_table(altered_table, NULL, false); /* Replace the old .FRM with the new .FRM, but keep the old name for now. Rename to the new name (if needed) will be handled separately below. */ if (mysql_rename_table(db_type, alter_ctx->new_db, alter_ctx->tmp_name, alter_ctx->db, alter_ctx->alias, FN_FROM_IS_TMP | NO_HA_TABLE)) { // Since changes were done in-place, we can't revert them. (void) quick_rm_table(thd, db_type, alter_ctx->new_db, alter_ctx->tmp_name, FN_IS_TMP | NO_HA_TABLE); DBUG_RETURN(true); } table_list->mdl_request.ticket= mdl_ticket; if (open_table(thd, table_list, &ot_ctx)) DBUG_RETURN(true); /* Tell the handler that the changed frm is on disk and table has been re-opened */ table_list->table->file->ha_notify_table_changed(); /* We might be going to reopen table down on the road, so we have to restore state of the TABLE object which we used for obtaining of handler object to make it usable for later reopening. */ close_thread_table(thd, &thd->open_tables); table_list->table= NULL; // Rename altered table if requested. if (alter_ctx->is_table_renamed()) { // Remove TABLE and TABLE_SHARE for old name from TDC. tdc_remove_table(thd, TDC_RT_REMOVE_ALL, alter_ctx->db, alter_ctx->table_name, false); if (mysql_rename_table(db_type, alter_ctx->db, alter_ctx->table_name, alter_ctx->new_db, alter_ctx->new_alias, 0)) { /* If the rename fails we will still have a working table with the old name, but with other changes applied. */ DBUG_RETURN(true); } if (Table_triggers_list::change_table_name(thd, alter_ctx->db, alter_ctx->alias, alter_ctx->table_name, alter_ctx->new_db, alter_ctx->new_alias)) { /* If the rename of trigger files fails, try to rename the table back so we at least have matching table and trigger files. */ (void) mysql_rename_table(db_type, alter_ctx->new_db, alter_ctx->new_alias, alter_ctx->db, alter_ctx->alias, NO_FK_CHECKS); DBUG_RETURN(true); } rename_table_in_stat_tables(thd, alter_ctx->db,alter_ctx->alias, alter_ctx->new_db, alter_ctx->new_alias); } DBUG_RETURN(false); rollback: table->file->ha_commit_inplace_alter_table(altered_table, ha_alter_info, false); cleanup: if (reopen_tables) { /* Close the only table instance which is still around. */ close_all_tables_for_name(thd, table->s, alter_ctx->is_table_renamed() ? HA_EXTRA_PREPARE_FOR_RENAME : HA_EXTRA_NOT_USED, NULL); if (thd->locked_tables_list.reopen_tables(thd)) thd->locked_tables_list.unlink_all_closed_tables(thd, NULL, 0); /* QQ; do something about metadata locks ? */ } thd->drop_temporary_table(altered_table, NULL, false); // Delete temporary .frm/.par (void) quick_rm_table(thd, create_info->db_type, alter_ctx->new_db, alter_ctx->tmp_name, FN_IS_TMP | NO_HA_TABLE); DBUG_RETURN(true); } /** maximum possible length for certain blob types. @param[in] type Blob type (e.g. MYSQL_TYPE_TINY_BLOB) @return length */ static uint blob_length_by_type(enum_field_types type) { switch (type) { case MYSQL_TYPE_TINY_BLOB: return 255; case MYSQL_TYPE_BLOB: return 65535; case MYSQL_TYPE_MEDIUM_BLOB: return 16777215; case MYSQL_TYPE_LONG_BLOB: return 4294967295U; default: DBUG_ASSERT(0); // we should never go here return 0; } } /** Prepare column and key definitions for CREATE TABLE in ALTER TABLE. This function transforms parse output of ALTER TABLE - lists of columns and keys to add, drop or modify into, essentially, CREATE TABLE definition - a list of columns and keys of the new table. While doing so, it also performs some (bug not all) semantic checks. This function is invoked when we know that we're going to perform ALTER TABLE via a temporary table -- i.e. in-place ALTER TABLE is not possible, perhaps because the ALTER statement contains instructions that require change in table data, not only in table definition or indexes. @param[in,out] thd thread handle. Used as a memory pool and source of environment information. @param[in] table the source table, open and locked Used as an interface to the storage engine to acquire additional information about the original table. @param[in,out] create_info A blob with CREATE/ALTER TABLE parameters @param[in,out] alter_info Another blob with ALTER/CREATE parameters. Originally create_info was used only in CREATE TABLE and alter_info only in ALTER TABLE. But since ALTER might end-up doing CREATE, this distinction is gone and we just carry around two structures. @param[in,out] alter_ctx Runtime context for ALTER TABLE. @return Fills various create_info members based on information retrieved from the storage engine. Sets create_info->varchar if the table has a VARCHAR column. Prepares alter_info->create_list and alter_info->key_list with columns and keys of the new table. @retval TRUE error, out of memory or a semantical error in ALTER TABLE instructions @retval FALSE success */ bool mysql_prepare_alter_table(THD *thd, TABLE *table, HA_CREATE_INFO *create_info, Alter_info *alter_info, Alter_table_ctx *alter_ctx) { /* New column definitions are added here */ List<Create_field> new_create_list; /* New key definitions are added here */ List<Key> new_key_list; List_iterator<Alter_drop> drop_it(alter_info->drop_list); List_iterator<Create_field> def_it(alter_info->create_list); List_iterator<Alter_column> alter_it(alter_info->alter_list); List_iterator<Key> key_it(alter_info->key_list); List_iterator<Create_field> find_it(new_create_list); List_iterator<Create_field> field_it(new_create_list); List<Key_part_spec> key_parts; List<Virtual_column_info> new_constraint_list; uint db_create_options= (table->s->db_create_options & ~(HA_OPTION_PACK_RECORD)); uint used_fields; KEY *key_info=table->key_info; bool rc= TRUE; bool modified_primary_key= FALSE; Create_field *def; Field **f_ptr,*field; MY_BITMAP *dropped_fields= NULL; // if it's NULL - no dropped fields DBUG_ENTER("mysql_prepare_alter_table"); /* Merge incompatible changes flag in case of upgrade of a table from an old MariaDB or MySQL version. This ensures that we don't try to do an online alter table if field packing or character set changes are required. */ create_info->used_fields|= table->s->incompatible_version; used_fields= create_info->used_fields; create_info->varchar= FALSE; /* Let new create options override the old ones */ if (!(used_fields & HA_CREATE_USED_MIN_ROWS)) create_info->min_rows= table->s->min_rows; if (!(used_fields & HA_CREATE_USED_MAX_ROWS)) create_info->max_rows= table->s->max_rows; if (!(used_fields & HA_CREATE_USED_AVG_ROW_LENGTH)) create_info->avg_row_length= table->s->avg_row_length; if (!(used_fields & HA_CREATE_USED_DEFAULT_CHARSET)) create_info->default_table_charset= table->s->table_charset; if (!(used_fields & HA_CREATE_USED_AUTO) && table->found_next_number_field) { /* Table has an autoincrement, copy value to new table */ table->file->info(HA_STATUS_AUTO); create_info->auto_increment_value= table->file->stats.auto_increment_value; } if (!(used_fields & HA_CREATE_USED_KEY_BLOCK_SIZE)) create_info->key_block_size= table->s->key_block_size; if (!(used_fields & HA_CREATE_USED_STATS_SAMPLE_PAGES)) create_info->stats_sample_pages= table->s->stats_sample_pages; if (!(used_fields & HA_CREATE_USED_STATS_AUTO_RECALC)) create_info->stats_auto_recalc= table->s->stats_auto_recalc; if (!(used_fields & HA_CREATE_USED_TRANSACTIONAL)) create_info->transactional= table->s->transactional; if (!(used_fields & HA_CREATE_USED_CONNECTION)) create_info->connect_string= table->s->connect_string; restore_record(table, s->default_values); // Empty record for DEFAULT if ((create_info->fields_option_struct= (ha_field_option_struct**) thd->calloc(sizeof(void*) * table->s->fields)) == NULL || (create_info->indexes_option_struct= (ha_index_option_struct**) thd->calloc(sizeof(void*) * table->s->keys)) == NULL) DBUG_RETURN(1); create_info->option_list= merge_engine_table_options(table->s->option_list, create_info->option_list, thd->mem_root); /* First collect all fields from table which isn't in drop_list */ bitmap_clear_all(&table->tmp_set); for (f_ptr=table->field ; (field= *f_ptr) ; f_ptr++) { Alter_drop *drop; if (field->type() == MYSQL_TYPE_VARCHAR) create_info->varchar= TRUE; /* Check if field should be dropped */ drop_it.rewind(); while ((drop=drop_it++)) { if (drop->type == Alter_drop::COLUMN && !my_strcasecmp(system_charset_info, field->field_name, drop->name)) break; } if (drop) { /* Reset auto_increment value if it was dropped */ if (MTYP_TYPENR(field->unireg_check) == Field::NEXT_NUMBER && !(used_fields & HA_CREATE_USED_AUTO)) { create_info->auto_increment_value=0; create_info->used_fields|=HA_CREATE_USED_AUTO; } if (table->s->tmp_table == NO_TMP_TABLE) (void) delete_statistics_for_column(thd, table, field); drop_it.remove(); dropped_fields= &table->tmp_set; bitmap_set_bit(dropped_fields, field->field_index); continue; } /* Check if field is changed */ def_it.rewind(); while ((def=def_it++)) { if (def->change && !my_strcasecmp(system_charset_info,field->field_name, def->change)) break; } if (def) { // Field is changed def->field=field; /* Add column being updated to the list of new columns. Note that columns with AFTER clauses are added to the end of the list for now. Their positions will be corrected later. */ new_create_list.push_back(def, thd->mem_root); if (field->stored_in_db() != def->stored_in_db()) { my_error(ER_UNSUPPORTED_ACTION_ON_GENERATED_COLUMN, MYF(0)); goto err; } if (!def->after) { /* If this ALTER TABLE doesn't have an AFTER clause for the modified column then remove this column from the list of columns to be processed. So later we can iterate over the columns remaining in this list and process modified columns with AFTER clause or add new columns. */ def_it.remove(); } } else { /* This field was not dropped and not changed, add it to the list for the new table. */ def= new (thd->mem_root) Create_field(thd, field, field); new_create_list.push_back(def, thd->mem_root); alter_it.rewind(); // Change default if ALTER Alter_column *alter; while ((alter=alter_it++)) { if (!my_strcasecmp(system_charset_info,field->field_name, alter->name)) break; } if (alter) { if ((def->default_value= alter->default_value)) def->flags&= ~NO_DEFAULT_VALUE_FLAG; else def->flags|= NO_DEFAULT_VALUE_FLAG; alter_it.remove(); } } } def_it.rewind(); while ((def=def_it++)) // Add new columns { if (def->change && ! def->field) { /* Check if there is modify for newly added field. */ Create_field *find; find_it.rewind(); while((find=find_it++)) { if (!my_strcasecmp(system_charset_info,find->field_name, def->field_name)) break; } if (find && !find->field) find_it.remove(); else { my_error(ER_BAD_FIELD_ERROR, MYF(0), def->change, table->s->table_name.str); goto err; } } /* Check that the DATE/DATETIME not null field we are going to add is either has a default value or the '0000-00-00' is allowed by the set sql mode. If the '0000-00-00' value isn't allowed then raise the error_if_not_empty flag to allow ALTER TABLE only if the table to be altered is empty. */ if ((def->sql_type == MYSQL_TYPE_DATE || def->sql_type == MYSQL_TYPE_NEWDATE || def->sql_type == MYSQL_TYPE_DATETIME || def->sql_type == MYSQL_TYPE_DATETIME2) && !alter_ctx->datetime_field && !(~def->flags & (NO_DEFAULT_VALUE_FLAG | NOT_NULL_FLAG)) && thd->variables.sql_mode & MODE_NO_ZERO_DATE) { alter_ctx->datetime_field= def; alter_ctx->error_if_not_empty= TRUE; } if (!def->after) new_create_list.push_back(def, thd->mem_root); else { Create_field *find; if (def->change) { find_it.rewind(); /* For columns being modified with AFTER clause we should first remove these columns from the list and then add them back at their correct positions. */ while ((find=find_it++)) { /* Create_fields representing changed columns are added directly from Alter_info::create_list to new_create_list. We can therefore safely use pointer equality rather than name matching here. This prevents removing the wrong column in case of column rename. */ if (find == def) { find_it.remove(); break; } } } if (def->after == first_keyword) new_create_list.push_front(def, thd->mem_root); else { find_it.rewind(); while ((find=find_it++)) { if (!my_strcasecmp(system_charset_info, def->after, find->field_name)) break; } if (!find) { my_error(ER_BAD_FIELD_ERROR, MYF(0), def->after, table->s->table_name.str); goto err; } find_it.after(def); // Put column after this } } /* Check if there is alter for newly added field. */ alter_it.rewind(); Alter_column *alter; while ((alter=alter_it++)) { if (!my_strcasecmp(system_charset_info,def->field_name, alter->name)) break; } if (alter) { if (def->sql_type == MYSQL_TYPE_BLOB) { my_error(ER_BLOB_CANT_HAVE_DEFAULT, MYF(0), def->change); goto err; } if ((def->default_value= alter->default_value)) // Use new default def->flags&= ~NO_DEFAULT_VALUE_FLAG; else def->flags|= NO_DEFAULT_VALUE_FLAG; alter_it.remove(); } } if (alter_info->alter_list.elements) { my_error(ER_BAD_FIELD_ERROR, MYF(0), alter_info->alter_list.head()->name, table->s->table_name.str); goto err; } if (!new_create_list.elements) { my_message(ER_CANT_REMOVE_ALL_FIELDS, ER_THD(thd, ER_CANT_REMOVE_ALL_FIELDS), MYF(0)); goto err; } /* Collect all keys which isn't in drop list. Add only those for which some fields exists. */ for (uint i=0 ; i < table->s->keys ; i++,key_info++) { char *key_name= key_info->name; Alter_drop *drop; drop_it.rewind(); while ((drop=drop_it++)) { if (drop->type == Alter_drop::KEY && !my_strcasecmp(system_charset_info,key_name, drop->name)) break; } if (drop) { if (table->s->tmp_table == NO_TMP_TABLE) { (void) delete_statistics_for_index(thd, table, key_info, FALSE); if (i == table->s->primary_key) { KEY *tab_key_info= table->key_info; for (uint j=0; j < table->s->keys; j++, tab_key_info++) { if (tab_key_info->user_defined_key_parts != tab_key_info->ext_key_parts) (void) delete_statistics_for_index(thd, table, tab_key_info, TRUE); } } } drop_it.remove(); continue; } const char *dropped_key_part= NULL; KEY_PART_INFO *key_part= key_info->key_part; key_parts.empty(); bool delete_index_stat= FALSE; for (uint j=0 ; j < key_info->user_defined_key_parts ; j++,key_part++) { if (!key_part->field) continue; // Wrong field (from UNIREG) const char *key_part_name=key_part->field->field_name; Create_field *cfield; uint key_part_length; field_it.rewind(); while ((cfield=field_it++)) { if (cfield->change) { if (!my_strcasecmp(system_charset_info, key_part_name, cfield->change)) break; } else if (!my_strcasecmp(system_charset_info, key_part_name, cfield->field_name)) break; } if (!cfield) { if (table->s->primary_key == i) modified_primary_key= TRUE; delete_index_stat= TRUE; dropped_key_part= key_part_name; continue; // Field is removed } key_part_length= key_part->length; if (cfield->field) // Not new field { /* If the field can't have only a part used in a key according to its new type, or should not be used partially according to its previous type, or the field length is less than the key part length, unset the key part length. We also unset the key part length if it is the same as the old field's length, so the whole new field will be used. BLOBs may have cfield->length == 0, which is why we test it before checking whether cfield->length < key_part_length (in chars). In case of TEXTs we check the data type maximum length *in bytes* to key part length measured *in characters* (i.e. key_part_length devided to mbmaxlen). This is because it's OK to have: CREATE TABLE t1 (a tinytext, key(a(254)) character set utf8); In case of this example: - data type maximum length is 255. - key_part_length is 1016 (=254*4, where 4 is mbmaxlen) */ if (!Field::type_can_have_key_part(cfield->field->type()) || !Field::type_can_have_key_part(cfield->sql_type) || /* spatial keys can't have sub-key length */ (key_info->flags & HA_SPATIAL) || (cfield->field->field_length == key_part_length && !f_is_blob(key_part->key_type)) || (cfield->length && (((cfield->sql_type >= MYSQL_TYPE_TINY_BLOB && cfield->sql_type <= MYSQL_TYPE_BLOB) ? blob_length_by_type(cfield->sql_type) : cfield->length) < key_part_length / key_part->field->charset()->mbmaxlen))) key_part_length= 0; // Use whole field } key_part_length /= key_part->field->charset()->mbmaxlen; key_parts.push_back(new Key_part_spec(cfield->field_name, strlen(cfield->field_name), key_part_length), thd->mem_root); } if (table->s->tmp_table == NO_TMP_TABLE) { if (delete_index_stat) (void) delete_statistics_for_index(thd, table, key_info, FALSE); else if (modified_primary_key && key_info->user_defined_key_parts != key_info->ext_key_parts) (void) delete_statistics_for_index(thd, table, key_info, TRUE); } if (key_parts.elements) { KEY_CREATE_INFO key_create_info; Key *key; enum Key::Keytype key_type; bzero((char*) &key_create_info, sizeof(key_create_info)); key_create_info.algorithm= key_info->algorithm; if (key_info->flags & HA_USES_BLOCK_SIZE) key_create_info.block_size= key_info->block_size; if (key_info->flags & HA_USES_PARSER) key_create_info.parser_name= *plugin_name(key_info->parser); if (key_info->flags & HA_USES_COMMENT) key_create_info.comment= key_info->comment; /* We're refreshing an already existing index. Since the index is not modified, there is no need to check for duplicate indexes again. */ key_create_info.check_for_duplicate_indexes= false; if (key_info->flags & HA_SPATIAL) key_type= Key::SPATIAL; else if (key_info->flags & HA_NOSAME) { if (! my_strcasecmp(system_charset_info, key_name, primary_key_name)) key_type= Key::PRIMARY; else key_type= Key::UNIQUE; if (dropped_key_part) { my_error(ER_KEY_COLUMN_DOES_NOT_EXITS, MYF(0), dropped_key_part); goto err; } } else if (key_info->flags & HA_FULLTEXT) key_type= Key::FULLTEXT; else key_type= Key::MULTIPLE; key= new Key(key_type, key_name, strlen(key_name), &key_create_info, MY_TEST(key_info->flags & HA_GENERATED_KEY), key_parts, key_info->option_list, DDL_options()); new_key_list.push_back(key, thd->mem_root); } } { Key *key; while ((key=key_it++)) // Add new keys { if (key->type == Key::FOREIGN_KEY && ((Foreign_key *)key)->validate(new_create_list)) goto err; new_key_list.push_back(key, thd->mem_root); if (key->name.str && !my_strcasecmp(system_charset_info, key->name.str, primary_key_name)) { my_error(ER_WRONG_NAME_FOR_INDEX, MYF(0), key->name.str); goto err; } } } /* Add all table level constraints which are not in the drop list */ if (table->s->table_check_constraints) { TABLE_SHARE *share= table->s; for (uint i= share->field_check_constraints; i < share->table_check_constraints ; i++) { Virtual_column_info *check= table->check_constraints[i]; Alter_drop *drop; drop_it.rewind(); while ((drop=drop_it++)) { if (drop->type == Alter_drop::CHECK_CONSTRAINT && !my_strcasecmp(system_charset_info, check->name.str, drop->name)) { drop_it.remove(); break; } } /* see if the constraint depends on *only* on dropped fields */ if (!drop && dropped_fields) { table->default_column_bitmaps(); bitmap_clear_all(table->read_set); check->expr->walk(&Item::register_field_in_read_map, 1, 0); if (bitmap_is_subset(table->read_set, dropped_fields)) drop= (Alter_drop*)1; else if (bitmap_is_overlapping(dropped_fields, table->read_set)) { bitmap_intersect(table->read_set, dropped_fields); uint field_nr= bitmap_get_first_set(table->read_set); my_error(ER_BAD_FIELD_ERROR, MYF(0), table->field[field_nr]->field_name, "CHECK"); goto err; } } if (!drop) new_constraint_list.push_back(check, thd->mem_root); } } /* Add new constraints */ new_constraint_list.append(&alter_info->check_constraint_list); if (alter_info->drop_list.elements) { Alter_drop *drop; drop_it.rewind(); while ((drop=drop_it++)) { switch (drop->type) { case Alter_drop::KEY: case Alter_drop::COLUMN: case Alter_drop::CHECK_CONSTRAINT: my_error(ER_CANT_DROP_FIELD_OR_KEY, MYF(0), drop->type_name(), alter_info->drop_list.head()->name); goto err; case Alter_drop::FOREIGN_KEY: // Leave the DROP FOREIGN KEY names in the alter_info->drop_list. break; } } } if (!create_info->comment.str) { create_info->comment.str= table->s->comment.str; create_info->comment.length= table->s->comment.length; } table->file->update_create_info(create_info); if ((create_info->table_options & (HA_OPTION_PACK_KEYS | HA_OPTION_NO_PACK_KEYS)) || (used_fields & HA_CREATE_USED_PACK_KEYS)) db_create_options&= ~(HA_OPTION_PACK_KEYS | HA_OPTION_NO_PACK_KEYS); if ((create_info->table_options & (HA_OPTION_STATS_PERSISTENT | HA_OPTION_NO_STATS_PERSISTENT)) || (used_fields & HA_CREATE_USED_STATS_PERSISTENT)) db_create_options&= ~(HA_OPTION_STATS_PERSISTENT | HA_OPTION_NO_STATS_PERSISTENT); if (create_info->table_options & (HA_OPTION_CHECKSUM | HA_OPTION_NO_CHECKSUM)) db_create_options&= ~(HA_OPTION_CHECKSUM | HA_OPTION_NO_CHECKSUM); if (create_info->table_options & (HA_OPTION_DELAY_KEY_WRITE | HA_OPTION_NO_DELAY_KEY_WRITE)) db_create_options&= ~(HA_OPTION_DELAY_KEY_WRITE | HA_OPTION_NO_DELAY_KEY_WRITE); create_info->table_options|= db_create_options; if (table->s->tmp_table) create_info->options|=HA_LEX_CREATE_TMP_TABLE; rc= FALSE; alter_info->create_list.swap(new_create_list); alter_info->key_list.swap(new_key_list); alter_info->check_constraint_list.swap(new_constraint_list); err: DBUG_RETURN(rc); } /** Get Create_field object for newly created table by its name in the old version of table. @param alter_info Alter_info describing newly created table. @param old_name Name of field in old table. @returns Pointer to Create_field object, NULL - if field is not present in new version of table. */ static Create_field *get_field_by_old_name(Alter_info *alter_info, const char *old_name) { List_iterator_fast<Create_field> new_field_it(alter_info->create_list); Create_field *new_field; while ((new_field= new_field_it++)) { if (new_field->field && (my_strcasecmp(system_charset_info, new_field->field->field_name, old_name) == 0)) break; } return new_field; } /** Type of change to foreign key column, */ enum fk_column_change_type { FK_COLUMN_NO_CHANGE, FK_COLUMN_DATA_CHANGE, FK_COLUMN_RENAMED, FK_COLUMN_DROPPED }; /** Check that ALTER TABLE's changes on columns of a foreign key are allowed. @param[in] thd Thread context. @param[in] alter_info Alter_info describing changes to be done by ALTER TABLE. @param[in] fk_columns List of columns of the foreign key to check. @param[out] bad_column_name Name of field on which ALTER TABLE tries to do prohibited operation. @note This function takes into account value of @@foreign_key_checks setting. @retval FK_COLUMN_NO_CHANGE No significant changes are to be done on foreign key columns. @retval FK_COLUMN_DATA_CHANGE ALTER TABLE might result in value change in foreign key column (and foreign_key_checks is on). @retval FK_COLUMN_RENAMED Foreign key column is renamed. @retval FK_COLUMN_DROPPED Foreign key column is dropped. */ static enum fk_column_change_type fk_check_column_changes(THD *thd, Alter_info *alter_info, List<LEX_STRING> &fk_columns, const char **bad_column_name) { List_iterator_fast<LEX_STRING> column_it(fk_columns); LEX_STRING *column; *bad_column_name= NULL; while ((column= column_it++)) { Create_field *new_field= get_field_by_old_name(alter_info, column->str); if (new_field) { Field *old_field= new_field->field; if (my_strcasecmp(system_charset_info, old_field->field_name, new_field->field_name)) { /* Copy algorithm doesn't support proper renaming of columns in the foreign key yet. At the moment we lack API which will tell SE that foreign keys should be updated to use new name of column like it happens in case of in-place algorithm. */ *bad_column_name= column->str; return FK_COLUMN_RENAMED; } if ((old_field->is_equal(new_field) == IS_EQUAL_NO) || ((new_field->flags & NOT_NULL_FLAG) && !(old_field->flags & NOT_NULL_FLAG))) { if (!(thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS)) { /* Column in a FK has changed significantly. Unless foreign_key_checks are off we prohibit this since this means values in this column might be changed by ALTER and thus referential integrity might be broken, */ *bad_column_name= column->str; return FK_COLUMN_DATA_CHANGE; } } } else { /* Column in FK was dropped. Most likely this will break integrity constraints of InnoDB data-dictionary (and thus InnoDB will emit an error), so we prohibit this right away even if foreign_key_checks are off. This also includes a rare case when another field replaces field being dropped since it is easy to break referential integrity in this case. */ *bad_column_name= column->str; return FK_COLUMN_DROPPED; } } return FK_COLUMN_NO_CHANGE; } /** Check if ALTER TABLE we are about to execute using COPY algorithm is not supported as it might break referential integrity. @note If foreign_key_checks is disabled (=0), we allow to break referential integrity. But we still disallow some operations like dropping or renaming columns in foreign key since they are likely to break consistency of InnoDB data-dictionary and thus will end-up in error anyway. @param[in] thd Thread context. @param[in] table Table to be altered. @param[in] alter_info Lists of fields, keys to be changed, added or dropped. @param[out] alter_ctx ALTER TABLE runtime context. Alter_table_ctx::fk_error_if_delete flag is set if deletion during alter can break foreign key integrity. @retval false Success. @retval true Error, ALTER - tries to do change which is not compatible with foreign key definitions on the table. */ static bool fk_prepare_copy_alter_table(THD *thd, TABLE *table, Alter_info *alter_info, Alter_table_ctx *alter_ctx) { List <FOREIGN_KEY_INFO> fk_parent_key_list; List <FOREIGN_KEY_INFO> fk_child_key_list; FOREIGN_KEY_INFO *f_key; DBUG_ENTER("fk_prepare_copy_alter_table"); table->file->get_parent_foreign_key_list(thd, &fk_parent_key_list); /* OOM when building list. */ if (thd->is_error()) DBUG_RETURN(true); /* Remove from the list all foreign keys in which table participates as parent which are to be dropped by this ALTER TABLE. This is possible when a foreign key has the same table as child and parent. */ List_iterator<FOREIGN_KEY_INFO> fk_parent_key_it(fk_parent_key_list); while ((f_key= fk_parent_key_it++)) { Alter_drop *drop; List_iterator_fast<Alter_drop> drop_it(alter_info->drop_list); while ((drop= drop_it++)) { /* InnoDB treats foreign key names in case-insensitive fashion. So we do it here too. For database and table name type of comparison used depends on lower-case-table-names setting. For l_c_t_n = 0 we use case-sensitive comparison, for l_c_t_n > 0 modes case-insensitive comparison is used. */ if ((drop->type == Alter_drop::FOREIGN_KEY) && (my_strcasecmp(system_charset_info, f_key->foreign_id->str, drop->name) == 0) && (my_strcasecmp(table_alias_charset, f_key->foreign_db->str, table->s->db.str) == 0) && (my_strcasecmp(table_alias_charset, f_key->foreign_table->str, table->s->table_name.str) == 0)) fk_parent_key_it.remove(); } } /* If there are FKs in which this table is parent which were not dropped we need to prevent ALTER deleting rows from the table, as it might break referential integrity. OTOH it is OK to do so if foreign_key_checks are disabled. */ if (!fk_parent_key_list.is_empty() && !(thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS)) alter_ctx->set_fk_error_if_delete_row(fk_parent_key_list.head()); fk_parent_key_it.rewind(); while ((f_key= fk_parent_key_it++)) { enum fk_column_change_type changes; const char *bad_column_name; changes= fk_check_column_changes(thd, alter_info, f_key->referenced_fields, &bad_column_name); switch(changes) { case FK_COLUMN_NO_CHANGE: /* No significant changes. We can proceed with ALTER! */ break; case FK_COLUMN_DATA_CHANGE: { char buff[NAME_LEN*2+2]; strxnmov(buff, sizeof(buff)-1, f_key->foreign_db->str, ".", f_key->foreign_table->str, NullS); my_error(ER_FK_COLUMN_CANNOT_CHANGE_CHILD, MYF(0), bad_column_name, f_key->foreign_id->str, buff); DBUG_RETURN(true); } case FK_COLUMN_RENAMED: my_error(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0), "ALGORITHM=COPY", ER_THD(thd, ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME), "ALGORITHM=INPLACE"); DBUG_RETURN(true); case FK_COLUMN_DROPPED: { StringBuffer<NAME_LEN*2+2> buff(system_charset_info); LEX_STRING *db= f_key->foreign_db, *tbl= f_key->foreign_table; append_identifier(thd, &buff, db->str, db->length); buff.append('.'); append_identifier(thd, &buff, tbl->str,tbl->length); my_error(ER_FK_COLUMN_CANNOT_DROP_CHILD, MYF(0), bad_column_name, f_key->foreign_id->str, buff.c_ptr()); DBUG_RETURN(true); } default: DBUG_ASSERT(0); } } table->file->get_foreign_key_list(thd, &fk_child_key_list); /* OOM when building list. */ if (thd->is_error()) DBUG_RETURN(true); /* Remove from the list all foreign keys which are to be dropped by this ALTER TABLE. */ List_iterator<FOREIGN_KEY_INFO> fk_key_it(fk_child_key_list); while ((f_key= fk_key_it++)) { Alter_drop *drop; List_iterator_fast<Alter_drop> drop_it(alter_info->drop_list); while ((drop= drop_it++)) { /* Names of foreign keys in InnoDB are case-insensitive. */ if ((drop->type == Alter_drop::FOREIGN_KEY) && (my_strcasecmp(system_charset_info, f_key->foreign_id->str, drop->name) == 0)) fk_key_it.remove(); } } fk_key_it.rewind(); while ((f_key= fk_key_it++)) { enum fk_column_change_type changes; const char *bad_column_name; changes= fk_check_column_changes(thd, alter_info, f_key->foreign_fields, &bad_column_name); switch(changes) { case FK_COLUMN_NO_CHANGE: /* No significant changes. We can proceed with ALTER! */ break; case FK_COLUMN_DATA_CHANGE: my_error(ER_FK_COLUMN_CANNOT_CHANGE, MYF(0), bad_column_name, f_key->foreign_id->str); DBUG_RETURN(true); case FK_COLUMN_RENAMED: my_error(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0), "ALGORITHM=COPY", ER_THD(thd, ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_FK_RENAME), "ALGORITHM=INPLACE"); DBUG_RETURN(true); case FK_COLUMN_DROPPED: my_error(ER_FK_COLUMN_CANNOT_DROP, MYF(0), bad_column_name, f_key->foreign_id->str); DBUG_RETURN(true); default: DBUG_ASSERT(0); } } DBUG_RETURN(false); } /** Rename temporary table and/or turn indexes on/off without touching .FRM. Its a variant of simple_rename_or_index_change() to be used exclusively for temporary tables. @param thd Thread handler @param table_list TABLE_LIST for the table to change @param keys_onoff ENABLE or DISABLE KEYS? @param alter_ctx ALTER TABLE runtime context. @return Operation status @retval false Success @retval true Failure */ static bool simple_tmp_rename_or_index_change(THD *thd, TABLE_LIST *table_list, Alter_info::enum_enable_or_disable keys_onoff, Alter_table_ctx *alter_ctx) { DBUG_ENTER("simple_tmp_rename_or_index_change"); TABLE *table= table_list->table; bool error= false; DBUG_ASSERT(table->s->tmp_table); if (keys_onoff != Alter_info::LEAVE_AS_IS) { THD_STAGE_INFO(thd, stage_manage_keys); error= alter_table_manage_keys(table, table->file->indexes_are_disabled(), keys_onoff); } if (!error && alter_ctx->is_table_renamed()) { THD_STAGE_INFO(thd, stage_rename); /* If THD::rename_temporary_table() fails, there is no need to rename it back to the original name (unlike the case for non-temporary tables), as it was an allocation error and the table was not renamed. */ error= thd->rename_temporary_table(table, alter_ctx->new_db, alter_ctx->new_alias); } if (!error) { int res= 0; /* We do not replicate alter table statement on temporary tables under ROW-based replication. */ if (!thd->is_current_stmt_binlog_format_row()) { res= write_bin_log(thd, true, thd->query(), thd->query_length()); } if (res != 0) error= true; else my_ok(thd); } DBUG_RETURN(error); } /** Rename table and/or turn indexes on/off without touching .FRM @param thd Thread handler @param table_list TABLE_LIST for the table to change @param keys_onoff ENABLE or DISABLE KEYS? @param alter_ctx ALTER TABLE runtime context. @return Operation status @retval false Success @retval true Failure */ static bool simple_rename_or_index_change(THD *thd, TABLE_LIST *table_list, Alter_info::enum_enable_or_disable keys_onoff, Alter_table_ctx *alter_ctx) { TABLE *table= table_list->table; MDL_ticket *mdl_ticket= table->mdl_ticket; int error= 0; enum ha_extra_function extra_func= thd->locked_tables_mode ? HA_EXTRA_NOT_USED : HA_EXTRA_FORCE_REOPEN; DBUG_ENTER("simple_rename_or_index_change"); if (keys_onoff != Alter_info::LEAVE_AS_IS) { if (wait_while_table_is_used(thd, table, extra_func)) DBUG_RETURN(true); // It's now safe to take the table level lock. if (lock_tables(thd, table_list, alter_ctx->tables_opened, 0)) DBUG_RETURN(true); THD_STAGE_INFO(thd, stage_manage_keys); error= alter_table_manage_keys(table, table->file->indexes_are_disabled(), keys_onoff); } if (!error && alter_ctx->is_table_renamed()) { THD_STAGE_INFO(thd, stage_rename); handlerton *old_db_type= table->s->db_type(); /* Then do a 'simple' rename of the table. First we need to close all instances of 'source' table. Note that if wait_while_table_is_used() returns error here (i.e. if this thread was killed) then it must be that previous step of simple rename did nothing and therefore we can safely return without additional clean-up. */ if (wait_while_table_is_used(thd, table, extra_func)) DBUG_RETURN(true); close_all_tables_for_name(thd, table->s, HA_EXTRA_PREPARE_FOR_RENAME, NULL); LEX_STRING old_db_name= { alter_ctx->db, strlen(alter_ctx->db) }; LEX_STRING old_table_name= { alter_ctx->table_name, strlen(alter_ctx->table_name) }; LEX_STRING new_db_name= { alter_ctx->new_db, strlen(alter_ctx->new_db) }; LEX_STRING new_table_name= { alter_ctx->new_alias, strlen(alter_ctx->new_alias) }; (void) rename_table_in_stat_tables(thd, &old_db_name, &old_table_name, &new_db_name, &new_table_name); if (mysql_rename_table(old_db_type, alter_ctx->db, alter_ctx->table_name, alter_ctx->new_db, alter_ctx->new_alias, 0)) error= -1; else if (Table_triggers_list::change_table_name(thd, alter_ctx->db, alter_ctx->alias, alter_ctx->table_name, alter_ctx->new_db, alter_ctx->new_alias)) { (void) mysql_rename_table(old_db_type, alter_ctx->new_db, alter_ctx->new_alias, alter_ctx->db, alter_ctx->table_name, NO_FK_CHECKS); error= -1; } } if (!error) { error= write_bin_log(thd, TRUE, thd->query(), thd->query_length()); if (!error) my_ok(thd); } table_list->table= NULL; // For query cache query_cache_invalidate3(thd, table_list, 0); if ((thd->locked_tables_mode == LTM_LOCK_TABLES || thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)) { /* Under LOCK TABLES we should adjust meta-data locks before finishing statement. Otherwise we can rely on them being released along with the implicit commit. */ if (alter_ctx->is_table_renamed()) thd->mdl_context.release_all_locks_for_name(mdl_ticket); else mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE); } DBUG_RETURN(error != 0); } /** Alter table @param thd Thread handle @param new_db If there is a RENAME clause @param new_name If there is a RENAME clause @param create_info Information from the parsing phase about new table properties. @param table_list The table to change. @param alter_info Lists of fields, keys to be changed, added or dropped. @param order_num How many ORDER BY fields has been specified. @param order List of fields to ORDER BY. @param ignore Whether we have ALTER IGNORE TABLE @retval true Error @retval false Success This is a veery long function and is everything but the kitchen sink :) It is used to alter a table and not only by ALTER TABLE but also CREATE|DROP INDEX are mapped on this function. When the ALTER TABLE statement just does a RENAME or ENABLE|DISABLE KEYS, or both, then this function short cuts its operation by renaming the table and/or enabling/disabling the keys. In this case, the FRM is not changed, directly by mysql_alter_table. However, if there is a RENAME + change of a field, or an index, the short cut is not used. See how `create_list` is used to generate the new FRM regarding the structure of the fields. The same is done for the indices of the table. Altering a table can be done in two ways. The table can be modified directly using an in-place algorithm, or the changes can be done using an intermediate temporary table (copy). In-place is the preferred algorithm as it avoids copying table data. The storage engine selects which algorithm to use in check_if_supported_inplace_alter() based on information about the table changes from fill_alter_inplace_info(). */ bool mysql_alter_table(THD *thd,char *new_db, char *new_name, HA_CREATE_INFO *create_info, TABLE_LIST *table_list, Alter_info *alter_info, uint order_num, ORDER *order, bool ignore) { DBUG_ENTER("mysql_alter_table"); /* Check if we attempt to alter mysql.slow_log or mysql.general_log table and return an error if it is the case. TODO: this design is obsolete and will be removed. */ int table_kind= check_if_log_table(table_list, FALSE, NullS); if (table_kind) { /* Disable alter of enabled log tables */ if (logger.is_log_table_enabled(table_kind)) { my_error(ER_BAD_LOG_STATEMENT, MYF(0), "ALTER"); DBUG_RETURN(true); } /* Disable alter of log tables to unsupported engine */ if ((create_info->used_fields & HA_CREATE_USED_ENGINE) && (!create_info->db_type || /* unknown engine */ !(create_info->db_type->flags & HTON_SUPPORT_LOG_TABLES))) { my_error(ER_UNSUPORTED_LOG_ENGINE, MYF(0), hton_name(create_info->db_type)->str); DBUG_RETURN(true); } #ifdef WITH_PARTITION_STORAGE_ENGINE if (alter_info->flags & Alter_info::ALTER_PARTITION) { my_error(ER_WRONG_USAGE, MYF(0), "PARTITION", "log table"); DBUG_RETURN(true); } #endif } THD_STAGE_INFO(thd, stage_init); /* Code below can handle only base tables so ensure that we won't open a view. Note that RENAME TABLE the only ALTER clause which is supported for views has been already processed. */ table_list->required_type= FRMTYPE_TABLE; Alter_table_prelocking_strategy alter_prelocking_strategy; DEBUG_SYNC(thd, "alter_table_before_open_tables"); uint tables_opened; thd->open_options|= HA_OPEN_FOR_ALTER; bool error= open_tables(thd, &table_list, &tables_opened, 0, &alter_prelocking_strategy); thd->open_options&= ~HA_OPEN_FOR_ALTER; DEBUG_SYNC(thd, "alter_opened_table"); #ifdef WITH_WSREP DBUG_EXECUTE_IF("sync.alter_opened_table", { const char act[]= "now " "wait_for signal.alter_opened_table"; DBUG_ASSERT(!debug_sync_set_action(thd, STRING_WITH_LEN(act))); };); #endif // WITH_WSREP if (error) DBUG_RETURN(true); TABLE *table= table_list->table; table->use_all_columns(); MDL_ticket *mdl_ticket= table->mdl_ticket; /* Prohibit changing of the UNION list of a non-temporary MERGE table under LOCK tables. It would be quite difficult to reuse a shrinked set of tables from the old table or to open a new TABLE object for an extended list and verify that they belong to locked tables. */ if ((thd->locked_tables_mode == LTM_LOCK_TABLES || thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) && (create_info->used_fields & HA_CREATE_USED_UNION) && (table->s->tmp_table == NO_TMP_TABLE)) { my_error(ER_LOCK_OR_ACTIVE_TRANSACTION, MYF(0)); DBUG_RETURN(true); } Alter_table_ctx alter_ctx(thd, table_list, tables_opened, new_db, new_name); MDL_request target_mdl_request; /* Check that we are not trying to rename to an existing table */ if (alter_ctx.is_table_renamed()) { if (table->s->tmp_table != NO_TMP_TABLE) { /* Check whether a temporary table exists with same requested new name. If such table exists, there must be a corresponding TABLE_SHARE in THD::all_temp_tables list. */ if (thd->find_tmp_table_share(alter_ctx.new_db, alter_ctx.new_name)) { my_error(ER_TABLE_EXISTS_ERROR, MYF(0), alter_ctx.new_alias); DBUG_RETURN(true); } } else { MDL_request_list mdl_requests; MDL_request target_db_mdl_request; target_mdl_request.init(MDL_key::TABLE, alter_ctx.new_db, alter_ctx.new_name, MDL_EXCLUSIVE, MDL_TRANSACTION); mdl_requests.push_front(&target_mdl_request); /* If we are moving the table to a different database, we also need IX lock on the database name so that the target database is protected by MDL while the table is moved. */ if (alter_ctx.is_database_changed()) { target_db_mdl_request.init(MDL_key::SCHEMA, alter_ctx.new_db, "", MDL_INTENTION_EXCLUSIVE, MDL_TRANSACTION); mdl_requests.push_front(&target_db_mdl_request); } /* Global intention exclusive lock must have been already acquired when table to be altered was open, so there is no need to do it here. */ DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE)); if (thd->mdl_context.acquire_locks(&mdl_requests, thd->variables.lock_wait_timeout)) DBUG_RETURN(true); DEBUG_SYNC(thd, "locked_table_name"); /* Table maybe does not exist, but we got an exclusive lock on the name, now we can safely try to find out for sure. */ if (ha_table_exists(thd, alter_ctx.new_db, alter_ctx.new_name, 0)) { /* Table will be closed in do_command() */ my_error(ER_TABLE_EXISTS_ERROR, MYF(0), alter_ctx.new_alias); DBUG_RETURN(true); } } } if (!create_info->db_type) { #ifdef WITH_PARTITION_STORAGE_ENGINE if (table->part_info && create_info->used_fields & HA_CREATE_USED_ENGINE) { /* This case happens when the user specified ENGINE = x where x is a non-existing storage engine We set create_info->db_type to default_engine_type to ensure we don't change underlying engine type due to a erroneously given engine name. */ create_info->db_type= table->part_info->default_engine_type; } else #endif create_info->db_type= table->s->db_type(); } if (check_engine(thd, alter_ctx.new_db, alter_ctx.new_name, create_info)) DBUG_RETURN(true); if ((create_info->db_type != table->s->db_type() || alter_info->flags & Alter_info::ALTER_PARTITION) && !table->file->can_switch_engines()) { my_error(ER_ROW_IS_REFERENCED, MYF(0)); DBUG_RETURN(true); } /* If foreign key is added then check permission to access parent table. In function "check_fk_parent_table_access", create_info->db_type is used to identify whether engine supports FK constraint or not. Since create_info->db_type is set here, check to parent table access is delayed till this point for the alter operation. */ if ((alter_info->flags & Alter_info::ADD_FOREIGN_KEY) && check_fk_parent_table_access(thd, create_info, alter_info, new_db)) DBUG_RETURN(true); /* If this is an ALTER TABLE and no explicit row type specified reuse the table's row type. Note: this is the same as if the row type was specified explicitly. */ if (create_info->row_type == ROW_TYPE_NOT_USED) { /* ALTER TABLE without explicit row type */ create_info->row_type= table->s->row_type; } else { /* ALTER TABLE with specific row type */ create_info->used_fields |= HA_CREATE_USED_ROW_FORMAT; } DBUG_PRINT("info", ("old type: %s new type: %s", ha_resolve_storage_engine_name(table->s->db_type()), ha_resolve_storage_engine_name(create_info->db_type))); if (ha_check_storage_engine_flag(table->s->db_type(), HTON_ALTER_NOT_SUPPORTED)) { DBUG_PRINT("info", ("doesn't support alter")); my_error(ER_ILLEGAL_HA, MYF(0), hton_name(table->s->db_type())->str, alter_ctx.db, alter_ctx.table_name); DBUG_RETURN(true); } if (ha_check_storage_engine_flag(create_info->db_type, HTON_ALTER_NOT_SUPPORTED)) { DBUG_PRINT("info", ("doesn't support alter")); my_error(ER_ILLEGAL_HA, MYF(0), hton_name(create_info->db_type)->str, alter_ctx.new_db, alter_ctx.new_name); DBUG_RETURN(true); } if (table->s->tmp_table == NO_TMP_TABLE) mysql_audit_alter_table(thd, table_list); THD_STAGE_INFO(thd, stage_setup); handle_if_exists_options(thd, table, alter_info); /* Look if we have to do anything at all. ALTER can become NOOP after handling the IF (NOT) EXISTS options. */ if (alter_info->flags == 0) { my_snprintf(alter_ctx.tmp_name, sizeof(alter_ctx.tmp_name), ER_THD(thd, ER_INSERT_INFO), 0L, 0L, thd->get_stmt_da()->current_statement_warn_count()); my_ok(thd, 0L, 0L, alter_ctx.tmp_name); /* We don't replicate alter table statement on temporary tables */ if (table->s->tmp_table == NO_TMP_TABLE || !thd->is_current_stmt_binlog_format_row()) { if (write_bin_log(thd, true, thd->query(), thd->query_length())) DBUG_RETURN(true); } DBUG_RETURN(false); } /* Test if we are only doing RENAME or KEYS ON/OFF. This works as we are testing if flags == 0 above. */ if (!(alter_info->flags & ~(Alter_info::ALTER_RENAME | Alter_info::ALTER_KEYS_ONOFF)) && alter_info->requested_algorithm != Alter_info::ALTER_TABLE_ALGORITHM_COPY) // No need to touch frm. { bool res; if (!table->s->tmp_table) { // This requires X-lock, no other lock levels supported. if (alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_DEFAULT && alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE) { my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0), "LOCK=NONE/SHARED", "LOCK=EXCLUSIVE"); DBUG_RETURN(true); } res= simple_rename_or_index_change(thd, table_list, alter_info->keys_onoff, &alter_ctx); } else { res= simple_tmp_rename_or_index_change(thd, table_list, alter_info->keys_onoff, &alter_ctx); } DBUG_RETURN(res); } /* We have to do full alter table. */ #ifdef WITH_PARTITION_STORAGE_ENGINE bool partition_changed= false; bool fast_alter_partition= false; { if (prep_alter_part_table(thd, table, alter_info, create_info, &alter_ctx, &partition_changed, &fast_alter_partition)) { DBUG_RETURN(true); } } #endif if (mysql_prepare_alter_table(thd, table, create_info, alter_info, &alter_ctx)) { DBUG_RETURN(true); } set_table_default_charset(thd, create_info, alter_ctx.db); if (!opt_explicit_defaults_for_timestamp) promote_first_timestamp_column(&alter_info->create_list); #ifdef WITH_PARTITION_STORAGE_ENGINE if (fast_alter_partition) { /* ALGORITHM and LOCK clauses are generally not allowed by the parser for operations related to partitioning. The exceptions are ALTER_PARTITION and ALTER_REMOVE_PARTITIONING. For consistency, we report ER_ALTER_OPERATION_NOT_SUPPORTED here. */ if (alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_DEFAULT) { my_error(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0), "LOCK=NONE/SHARED/EXCLUSIVE", ER_THD(thd, ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION), "LOCK=DEFAULT"); DBUG_RETURN(true); } else if (alter_info->requested_algorithm != Alter_info::ALTER_TABLE_ALGORITHM_DEFAULT) { my_error(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0), "ALGORITHM=COPY/INPLACE", ER_THD(thd, ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_PARTITION), "ALGORITHM=DEFAULT"); DBUG_RETURN(true); } /* Upgrade from MDL_SHARED_UPGRADABLE to MDL_SHARED_NO_WRITE. Afterwards it's safe to take the table level lock. */ if (thd->mdl_context.upgrade_shared_lock(mdl_ticket, MDL_SHARED_NO_WRITE, thd->variables.lock_wait_timeout) || lock_tables(thd, table_list, alter_ctx.tables_opened, 0)) { DBUG_RETURN(true); } // In-place execution of ALTER TABLE for partitioning. DBUG_RETURN(fast_alter_partition_table(thd, table, alter_info, create_info, table_list, alter_ctx.db, alter_ctx.table_name)); } #endif /* Use copy algorithm if: - old_alter_table system variable is set without in-place requested using the ALGORITHM clause. - Or if in-place is impossible for given operation. - Changes to partitioning which were not handled by fast_alter_part_table() needs to be handled using table copying algorithm unless the engine supports auto-partitioning as such engines can do some changes using in-place API. */ if ((thd->variables.old_alter_table && alter_info->requested_algorithm != Alter_info::ALTER_TABLE_ALGORITHM_INPLACE) || is_inplace_alter_impossible(table, create_info, alter_info) || IF_PARTITIONING((partition_changed && !(table->s->db_type()->partition_flags() & HA_USE_AUTO_PARTITION)), 0)) { if (alter_info->requested_algorithm == Alter_info::ALTER_TABLE_ALGORITHM_INPLACE) { my_error(ER_ALTER_OPERATION_NOT_SUPPORTED, MYF(0), "ALGORITHM=INPLACE", "ALGORITHM=COPY"); DBUG_RETURN(true); } alter_info->requested_algorithm= Alter_info::ALTER_TABLE_ALGORITHM_COPY; } /* ALTER TABLE ... ENGINE to the same engine is a common way to request table rebuild. Set ALTER_RECREATE flag to force table rebuild. */ if (create_info->db_type == table->s->db_type() && create_info->used_fields & HA_CREATE_USED_ENGINE) alter_info->flags|= Alter_info::ALTER_RECREATE; /* If the old table had partitions and we are doing ALTER TABLE ... engine= <new_engine>, the new table must preserve the original partitioning. This means that the new engine is still the partitioning engine, not the engine specified in the parser. This is discovered in prep_alter_part_table, which in such case updates create_info->db_type. It's therefore important that the assignment below is done after prep_alter_part_table. */ handlerton *new_db_type= create_info->db_type; handlerton *old_db_type= table->s->db_type(); TABLE *new_table= NULL; ha_rows copied=0,deleted=0; /* Handling of symlinked tables: If no rename: Create new data file and index file on the same disk as the old data and index files. Copy data. Rename new data file over old data file and new index file over old index file. Symlinks are not changed. If rename: Create new data file and index file on the same disk as the old data and index files. Create also symlinks to point at the new tables. Copy data. At end, rename intermediate tables, and symlinks to intermediate table, to final table name. Remove old table and old symlinks If rename is made to another database: Create new tables in new database. Copy data. Remove old table and symlinks. */ char index_file[FN_REFLEN], data_file[FN_REFLEN]; if (!alter_ctx.is_database_changed()) { if (create_info->index_file_name) { /* Fix index_file_name to have 'tmp_name' as basename */ strmov(index_file, alter_ctx.tmp_name); create_info->index_file_name=fn_same(index_file, create_info->index_file_name, 1); } if (create_info->data_file_name) { /* Fix data_file_name to have 'tmp_name' as basename */ strmov(data_file, alter_ctx.tmp_name); create_info->data_file_name=fn_same(data_file, create_info->data_file_name, 1); } } else { /* Ignore symlink if db is changed. */ create_info->data_file_name=create_info->index_file_name=0; } DEBUG_SYNC(thd, "alter_table_before_create_table_no_lock"); /* We can abort alter table for any table type */ thd->abort_on_warning= !ignore && thd->is_strict_mode(); /* Create .FRM for new version of table with a temporary name. We don't log the statement, it will be logged later. Keep information about keys in newly created table as it will be used later to construct Alter_inplace_info object and by fill_alter_inplace_info() call. */ KEY *key_info; uint key_count; /* Remember if the new definition has new VARCHAR column; create_info->varchar will be reset in create_table_impl()/ mysql_prepare_create_table(). */ bool varchar= create_info->varchar; LEX_CUSTRING frm= {0,0}; tmp_disable_binlog(thd); create_info->options|=HA_CREATE_TMP_ALTER; error= create_table_impl(thd, alter_ctx.db, alter_ctx.table_name, alter_ctx.new_db, alter_ctx.tmp_name, alter_ctx.get_tmp_path(), thd->lex->create_info, create_info, alter_info, C_ALTER_TABLE_FRM_ONLY, NULL, &key_info, &key_count, &frm); reenable_binlog(thd); thd->abort_on_warning= false; if (error) { my_free(const_cast<uchar*>(frm.str)); DBUG_RETURN(true); } /* Remember that we have not created table in storage engine yet. */ bool no_ha_table= true; if (alter_info->requested_algorithm != Alter_info::ALTER_TABLE_ALGORITHM_COPY) { Alter_inplace_info ha_alter_info(create_info, alter_info, key_info, key_count, IF_PARTITIONING(thd->work_part_info, NULL), ignore); TABLE *altered_table= NULL; bool use_inplace= true; /* Fill the Alter_inplace_info structure. */ if (fill_alter_inplace_info(thd, table, varchar, &ha_alter_info)) goto err_new_table_cleanup; if (ha_alter_info.handler_flags == 0) { /* No-op ALTER, no need to call handler API functions. If this code path is entered for an ALTER statement that should not be a real no-op, new handler flags should be added and fill_alter_inplace_info() adjusted. Note that we can end up here if an ALTER statement has clauses that cancel each other out (e.g. ADD/DROP identically index). Also note that we ignore the LOCK clause here. TODO don't create the frm in the first place */ const char *path= alter_ctx.get_tmp_path(); table->file->ha_create_partitioning_metadata(path, NULL, CHF_DELETE_FLAG); deletefrm(path); my_free(const_cast<uchar*>(frm.str)); goto end_inplace; } // We assume that the table is non-temporary. DBUG_ASSERT(!table->s->tmp_table); if (!(altered_table= thd->create_and_open_tmp_table(new_db_type, &frm, alter_ctx.get_tmp_path(), alter_ctx.new_db, alter_ctx.tmp_name, false))) goto err_new_table_cleanup; /* Set markers for fields in TABLE object for altered table. */ update_altered_table(ha_alter_info, altered_table); /* Mark all columns in 'altered_table' as used to allow usage of its record[0] buffer and Field objects during in-place ALTER TABLE. */ altered_table->column_bitmaps_set_no_signal(&altered_table->s->all_set, &altered_table->s->all_set); restore_record(altered_table, s->default_values); // Create empty record /* Check that we can call default functions with default field values */ altered_table->reset_default_fields(); if (altered_table->default_field && altered_table->update_default_fields(0, 1)) goto err_new_table_cleanup; // Ask storage engine whether to use copy or in-place enum_alter_inplace_result inplace_supported= table->file->check_if_supported_inplace_alter(altered_table, &ha_alter_info); switch (inplace_supported) { case HA_ALTER_INPLACE_EXCLUSIVE_LOCK: // If SHARED lock and no particular algorithm was requested, use COPY. if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_SHARED && alter_info->requested_algorithm == Alter_info::ALTER_TABLE_ALGORITHM_DEFAULT) { use_inplace= false; } // Otherwise, if weaker lock was requested, report errror. else if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_NONE || alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_SHARED) { ha_alter_info.report_unsupported_error("LOCK=NONE/SHARED", "LOCK=EXCLUSIVE"); thd->drop_temporary_table(altered_table, NULL, false); goto err_new_table_cleanup; } break; case HA_ALTER_INPLACE_SHARED_LOCK_AFTER_PREPARE: case HA_ALTER_INPLACE_SHARED_LOCK: // If weaker lock was requested, report errror. if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_NONE) { ha_alter_info.report_unsupported_error("LOCK=NONE", "LOCK=SHARED"); thd->drop_temporary_table(altered_table, NULL, false); goto err_new_table_cleanup; } break; case HA_ALTER_INPLACE_NO_LOCK_AFTER_PREPARE: case HA_ALTER_INPLACE_NO_LOCK: break; case HA_ALTER_INPLACE_NOT_SUPPORTED: // If INPLACE was requested, report error. if (alter_info->requested_algorithm == Alter_info::ALTER_TABLE_ALGORITHM_INPLACE) { ha_alter_info.report_unsupported_error("ALGORITHM=INPLACE", "ALGORITHM=COPY"); thd->drop_temporary_table(altered_table, NULL, false); goto err_new_table_cleanup; } // COPY with LOCK=NONE is not supported, no point in trying. if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_NONE) { ha_alter_info.report_unsupported_error("LOCK=NONE", "LOCK=SHARED"); thd->drop_temporary_table(altered_table, NULL, false); goto err_new_table_cleanup; } // Otherwise use COPY use_inplace= false; break; case HA_ALTER_ERROR: default: thd->drop_temporary_table(altered_table, NULL, false); goto err_new_table_cleanup; } if (use_inplace) { table->s->frm_image= &frm; int res= mysql_inplace_alter_table(thd, table_list, table, altered_table, &ha_alter_info, inplace_supported, &target_mdl_request, &alter_ctx); my_free(const_cast<uchar*>(frm.str)); if (res) DBUG_RETURN(true); goto end_inplace; } else { thd->drop_temporary_table(altered_table, NULL, false); } } /* ALTER TABLE using copy algorithm. */ /* Check if ALTER TABLE is compatible with foreign key definitions. */ if (fk_prepare_copy_alter_table(thd, table, alter_info, &alter_ctx)) goto err_new_table_cleanup; if (!table->s->tmp_table) { // COPY algorithm doesn't work with concurrent writes. if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_NONE) { my_error(ER_ALTER_OPERATION_NOT_SUPPORTED_REASON, MYF(0), "LOCK=NONE", ER_THD(thd, ER_ALTER_OPERATION_NOT_SUPPORTED_REASON_COPY), "LOCK=SHARED"); goto err_new_table_cleanup; } // If EXCLUSIVE lock is requested, upgrade already. if (alter_info->requested_lock == Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE && wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN)) goto err_new_table_cleanup; /* Otherwise upgrade to SHARED_NO_WRITE. Note that under LOCK TABLES, we will already have SHARED_NO_READ_WRITE. */ if (alter_info->requested_lock != Alter_info::ALTER_TABLE_LOCK_EXCLUSIVE && thd->mdl_context.upgrade_shared_lock(mdl_ticket, MDL_SHARED_NO_WRITE, thd->variables.lock_wait_timeout)) goto err_new_table_cleanup; DEBUG_SYNC(thd, "alter_table_copy_after_lock_upgrade"); } // It's now safe to take the table level lock. if (lock_tables(thd, table_list, alter_ctx.tables_opened, 0)) goto err_new_table_cleanup; if (ha_create_table(thd, alter_ctx.get_tmp_path(), alter_ctx.new_db, alter_ctx.tmp_name, create_info, &frm)) goto err_new_table_cleanup; /* Mark that we have created table in storage engine. */ no_ha_table= false; if (create_info->tmp_table()) { TABLE *tmp_table= thd->create_and_open_tmp_table(new_db_type, &frm, alter_ctx.get_tmp_path(), alter_ctx.new_db, alter_ctx.tmp_name, true); if (!tmp_table) { goto err_new_table_cleanup; } /* in case of alter temp table send the tracker in OK packet */ SESSION_TRACKER_CHANGED(thd, SESSION_STATE_CHANGE_TRACKER, NULL); } /* Open the table since we need to copy the data. */ if (table->s->tmp_table != NO_TMP_TABLE) { TABLE_LIST tbl; tbl.init_one_table(alter_ctx.new_db, strlen(alter_ctx.new_db), alter_ctx.tmp_name, strlen(alter_ctx.tmp_name), alter_ctx.tmp_name, TL_READ_NO_INSERT); /* Table can be found in the list of open tables in THD::all_temp_tables list. */ tbl.table= thd->find_temporary_table(&tbl); new_table= tbl.table; } else { /* table is a normal table: Create temporary table in same directory. Open our intermediate table. */ new_table= thd->create_and_open_tmp_table(new_db_type, &frm, alter_ctx.get_tmp_path(), alter_ctx.new_db, alter_ctx.tmp_name, true); } if (!new_table) goto err_new_table_cleanup; /* Note: In case of MERGE table, we do not attach children. We do not copy data for MERGE tables. Only the children have data. */ /* Copy the data if necessary. */ thd->count_cuted_fields= CHECK_FIELD_WARN; // calc cuted fields thd->cuted_fields=0L; /* We do not copy data for MERGE tables. Only the children have data. MERGE tables have HA_NO_COPY_ON_ALTER set. */ if (!(new_table->file->ha_table_flags() & HA_NO_COPY_ON_ALTER)) { new_table->next_number_field=new_table->found_next_number_field; THD_STAGE_INFO(thd, stage_copy_to_tmp_table); DBUG_EXECUTE_IF("abort_copy_table", { my_error(ER_LOCK_WAIT_TIMEOUT, MYF(0)); goto err_new_table_cleanup; }); if (copy_data_between_tables(thd, table, new_table, alter_info->create_list, ignore, order_num, order, &copied, &deleted, alter_info->keys_onoff, &alter_ctx)) goto err_new_table_cleanup; } else { if (!table->s->tmp_table && wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN)) goto err_new_table_cleanup; THD_STAGE_INFO(thd, stage_manage_keys); alter_table_manage_keys(table, table->file->indexes_are_disabled(), alter_info->keys_onoff); if (trans_commit_stmt(thd) || trans_commit_implicit(thd)) goto err_new_table_cleanup; } thd->count_cuted_fields= CHECK_FIELD_IGNORE; if (table->s->tmp_table != NO_TMP_TABLE) { /* Close lock if this is a transactional table */ if (thd->lock) { if (thd->locked_tables_mode != LTM_LOCK_TABLES && thd->locked_tables_mode != LTM_PRELOCKED_UNDER_LOCK_TABLES) { mysql_unlock_tables(thd, thd->lock); thd->lock= NULL; } else { /* If LOCK TABLES list is not empty and contains this table, unlock the table and remove the table from this list. */ mysql_lock_remove(thd, thd->lock, table); } } new_table->s->table_creation_was_logged= table->s->table_creation_was_logged; /* Remove link to old table and rename the new one */ thd->drop_temporary_table(table, NULL, true); /* Should pass the 'new_name' as we store table name in the cache */ if (thd->rename_temporary_table(new_table, alter_ctx.new_db, alter_ctx.new_name)) goto err_new_table_cleanup; /* We don't replicate alter table statement on temporary tables */ if (!thd->is_current_stmt_binlog_format_row() && write_bin_log(thd, true, thd->query(), thd->query_length())) DBUG_RETURN(true); my_free(const_cast<uchar*>(frm.str)); goto end_temporary; } /* Close the intermediate table that will be the new table, but do not delete it! Even though MERGE tables do not have their children attached here it is safe to call THD::drop_temporary_table(). */ thd->drop_temporary_table(new_table, NULL, false); new_table= NULL; DEBUG_SYNC(thd, "alter_table_before_rename_result_table"); /* Data is copied. Now we: 1) Wait until all other threads will stop using old version of table by upgrading shared metadata lock to exclusive one. 2) Close instances of table open by this thread and replace them with placeholders to simplify reopen process. 3) Rename the old table to a temp name, rename the new one to the old name. 4) If we are under LOCK TABLES and don't do ALTER TABLE ... RENAME we reopen new version of table. 5) Write statement to the binary log. 6) If we are under LOCK TABLES and do ALTER TABLE ... RENAME we remove placeholders and release metadata locks. 7) If we are not not under LOCK TABLES we rely on the caller (mysql_execute_command()) to release metadata locks. */ THD_STAGE_INFO(thd, stage_rename_result_table); if (wait_while_table_is_used(thd, table, HA_EXTRA_PREPARE_FOR_RENAME)) goto err_new_table_cleanup; close_all_tables_for_name(thd, table->s, alter_ctx.is_table_renamed() ? HA_EXTRA_PREPARE_FOR_RENAME: HA_EXTRA_NOT_USED, NULL); table_list->table= table= NULL; /* Safety */ my_free(const_cast<uchar*>(frm.str)); /* Rename the old table to temporary name to have a backup in case anything goes wrong while renaming the new table. */ char backup_name[32]; my_snprintf(backup_name, sizeof(backup_name), "%s2-%lx-%lx", tmp_file_prefix, current_pid, thd->thread_id); if (lower_case_table_names) my_casedn_str(files_charset_info, backup_name); if (mysql_rename_table(old_db_type, alter_ctx.db, alter_ctx.table_name, alter_ctx.db, backup_name, FN_TO_IS_TMP)) { // Rename to temporary name failed, delete the new table, abort ALTER. (void) quick_rm_table(thd, new_db_type, alter_ctx.new_db, alter_ctx.tmp_name, FN_IS_TMP); goto err_with_mdl; } // Rename the new table to the correct name. if (mysql_rename_table(new_db_type, alter_ctx.new_db, alter_ctx.tmp_name, alter_ctx.new_db, alter_ctx.new_alias, FN_FROM_IS_TMP)) { // Rename failed, delete the temporary table. (void) quick_rm_table(thd, new_db_type, alter_ctx.new_db, alter_ctx.tmp_name, FN_IS_TMP); // Restore the backup of the original table to the old name. (void) mysql_rename_table(old_db_type, alter_ctx.db, backup_name, alter_ctx.db, alter_ctx.alias, FN_FROM_IS_TMP | NO_FK_CHECKS); goto err_with_mdl; } // Check if we renamed the table and if so update trigger files. if (alter_ctx.is_table_renamed()) { if (Table_triggers_list::change_table_name(thd, alter_ctx.db, alter_ctx.alias, alter_ctx.table_name, alter_ctx.new_db, alter_ctx.new_alias)) { // Rename succeeded, delete the new table. (void) quick_rm_table(thd, new_db_type, alter_ctx.new_db, alter_ctx.new_alias, 0); // Restore the backup of the original table to the old name. (void) mysql_rename_table(old_db_type, alter_ctx.db, backup_name, alter_ctx.db, alter_ctx.alias, FN_FROM_IS_TMP | NO_FK_CHECKS); goto err_with_mdl; } rename_table_in_stat_tables(thd, alter_ctx.db,alter_ctx.alias, alter_ctx.new_db, alter_ctx.new_alias); } // ALTER TABLE succeeded, delete the backup of the old table. if (quick_rm_table(thd, old_db_type, alter_ctx.db, backup_name, FN_IS_TMP)) { /* The fact that deletion of the backup failed is not critical error, but still worth reporting as it might indicate serious problem with server. */ goto err_with_mdl_after_alter; } end_inplace: if (thd->locked_tables_list.reopen_tables(thd)) goto err_with_mdl_after_alter; THD_STAGE_INFO(thd, stage_end); DEBUG_SYNC(thd, "alter_table_before_main_binlog"); DBUG_ASSERT(!(mysql_bin_log.is_open() && thd->is_current_stmt_binlog_format_row() && (create_info->tmp_table()))); if (write_bin_log(thd, true, thd->query(), thd->query_length())) DBUG_RETURN(true); table_list->table= NULL; // For query cache query_cache_invalidate3(thd, table_list, false); if (thd->locked_tables_mode == LTM_LOCK_TABLES || thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES) { if (alter_ctx.is_table_renamed()) thd->mdl_context.release_all_locks_for_name(mdl_ticket); else mdl_ticket->downgrade_lock(MDL_SHARED_NO_READ_WRITE); } end_temporary: my_snprintf(alter_ctx.tmp_name, sizeof(alter_ctx.tmp_name), ER_THD(thd, ER_INSERT_INFO), (ulong) (copied + deleted), (ulong) deleted, (ulong) thd->get_stmt_da()->current_statement_warn_count()); my_ok(thd, copied + deleted, 0L, alter_ctx.tmp_name); DBUG_RETURN(false); err_new_table_cleanup: my_free(const_cast<uchar*>(frm.str)); if (new_table) { thd->drop_temporary_table(new_table, NULL, true); } else (void) quick_rm_table(thd, new_db_type, alter_ctx.new_db, alter_ctx.tmp_name, (FN_IS_TMP | (no_ha_table ? NO_HA_TABLE : 0)), alter_ctx.get_tmp_path()); /* No default value was provided for a DATE/DATETIME field, the current sql_mode doesn't allow the '0000-00-00' value and the table to be altered isn't empty. Report error here. */ if (alter_ctx.error_if_not_empty && thd->get_stmt_da()->current_row_for_warning()) { const char *f_val= 0; enum enum_mysql_timestamp_type t_type= MYSQL_TIMESTAMP_DATE; switch (alter_ctx.datetime_field->sql_type) { case MYSQL_TYPE_DATE: case MYSQL_TYPE_NEWDATE: f_val= "0000-00-00"; t_type= MYSQL_TIMESTAMP_DATE; break; case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_DATETIME2: f_val= "0000-00-00 00:00:00"; t_type= MYSQL_TIMESTAMP_DATETIME; break; default: /* Shouldn't get here. */ DBUG_ASSERT(0); } bool save_abort_on_warning= thd->abort_on_warning; thd->abort_on_warning= true; make_truncated_value_warning(thd, Sql_condition::WARN_LEVEL_WARN, f_val, strlength(f_val), t_type, alter_ctx.datetime_field->field_name); thd->abort_on_warning= save_abort_on_warning; } DBUG_RETURN(true); err_with_mdl_after_alter: /* the table was altered. binlog the operation */ DBUG_ASSERT(!(mysql_bin_log.is_open() && thd->is_current_stmt_binlog_format_row() && (create_info->tmp_table()))); write_bin_log(thd, true, thd->query(), thd->query_length()); err_with_mdl: /* An error happened while we were holding exclusive name metadata lock on table being altered. To be safe under LOCK TABLES we should remove all references to the altered table from the list of locked tables and release the exclusive metadata lock. */ thd->locked_tables_list.unlink_all_closed_tables(thd, NULL, 0); thd->mdl_context.release_all_locks_for_name(mdl_ticket); DBUG_RETURN(true); } /** Prepare the transaction for the alter table's copy phase. */ bool mysql_trans_prepare_alter_copy_data(THD *thd) { DBUG_ENTER("mysql_trans_prepare_alter_copy_data"); /* Turn off recovery logging since rollback of an alter table is to delete the new table so there is no need to log the changes to it. This needs to be done before external_lock. */ if (ha_enable_transaction(thd, FALSE)) DBUG_RETURN(TRUE); DBUG_RETURN(FALSE); } /** Commit the copy phase of the alter table. */ bool mysql_trans_commit_alter_copy_data(THD *thd) { bool error= FALSE; uint save_unsafe_rollback_flags; DBUG_ENTER("mysql_trans_commit_alter_copy_data"); /* Save flags as transcommit_implicit_are_deleting_them */ save_unsafe_rollback_flags= thd->transaction.stmt.m_unsafe_rollback_flags; if (ha_enable_transaction(thd, TRUE)) DBUG_RETURN(TRUE); /* Ensure that the new table is saved properly to disk before installing the new .frm. And that InnoDB's internal latches are released, to avoid deadlock when waiting on other instances of the table before rename (Bug#54747). */ if (trans_commit_stmt(thd)) error= TRUE; if (trans_commit_implicit(thd)) error= TRUE; thd->transaction.stmt.m_unsafe_rollback_flags= save_unsafe_rollback_flags; DBUG_RETURN(error); } static int copy_data_between_tables(THD *thd, TABLE *from, TABLE *to, List<Create_field> &create, bool ignore, uint order_num, ORDER *order, ha_rows *copied, ha_rows *deleted, Alter_info::enum_enable_or_disable keys_onoff, Alter_table_ctx *alter_ctx) { int error= 1; Copy_field *copy= NULL, *copy_end; ha_rows found_count= 0, delete_count= 0; SORT_INFO *file_sort= 0; READ_RECORD info; TABLE_LIST tables; List<Item> fields; List<Item> all_fields; bool auto_increment_field_copied= 0; bool init_read_record_done= 0; sql_mode_t save_sql_mode= thd->variables.sql_mode; ulonglong prev_insert_id, time_to_report_progress; Field **dfield_ptr= to->default_field; DBUG_ENTER("copy_data_between_tables"); /* Two or 3 stages; Sorting, copying data and update indexes */ thd_progress_init(thd, 2 + MY_TEST(order)); if (mysql_trans_prepare_alter_copy_data(thd)) DBUG_RETURN(-1); if (!(copy= new Copy_field[to->s->fields])) DBUG_RETURN(-1); /* purecov: inspected */ /* We need external lock before we can disable/enable keys */ if (to->file->ha_external_lock(thd, F_WRLCK)) DBUG_RETURN(-1); alter_table_manage_keys(to, from->file->indexes_are_disabled(), keys_onoff); /* We can abort alter table for any table type */ thd->abort_on_warning= !ignore && thd->is_strict_mode(); from->file->info(HA_STATUS_VARIABLE); to->file->ha_start_bulk_insert(from->file->stats.records, ignore ? 0 : HA_CREATE_UNIQUE_INDEX_BY_SORT); List_iterator<Create_field> it(create); Create_field *def; copy_end=copy; to->s->default_fields= 0; for (Field **ptr=to->field ; *ptr ; ptr++) { def=it++; if (def->field) { if (*ptr == to->next_number_field) { auto_increment_field_copied= TRUE; /* If we are going to copy contents of one auto_increment column to another auto_increment column it is sensible to preserve zeroes. This condition also covers case when we are don't actually alter auto_increment column. */ if (def->field == from->found_next_number_field) thd->variables.sql_mode|= MODE_NO_AUTO_VALUE_ON_ZERO; } (copy_end++)->set(*ptr,def->field,0); } else { /* Update the set of auto-update fields to contain only the new fields added to the table. Only these fields should be updated automatically. Old fields keep their current values, and therefore should not be present in the set of autoupdate fields. */ if ((*ptr)->default_value) { *(dfield_ptr++)= *ptr; ++to->s->default_fields; } } } if (dfield_ptr) *dfield_ptr= NULL; if (order) { if (to->s->primary_key != MAX_KEY && to->file->ha_table_flags() & HA_TABLE_SCAN_ON_INDEX) { char warn_buff[MYSQL_ERRMSG_SIZE]; my_snprintf(warn_buff, sizeof(warn_buff), "ORDER BY ignored as there is a user-defined clustered index" " in the table '%-.192s'", from->s->table_name.str); push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, warn_buff); } else { bzero((char *) &tables, sizeof(tables)); tables.table= from; tables.alias= tables.table_name= from->s->table_name.str; tables.db= from->s->db.str; THD_STAGE_INFO(thd, stage_sorting); Filesort_tracker dummy_tracker(false); Filesort fsort(order, HA_POS_ERROR, true, NULL); if (thd->lex->select_lex.setup_ref_array(thd, order_num) || setup_order(thd, thd->lex->select_lex.ref_pointer_array, &tables, fields, all_fields, order)) goto err; if (!(file_sort= filesort(thd, from, &fsort, &dummy_tracker))) goto err; } thd_progress_next_stage(thd); } THD_STAGE_INFO(thd, stage_copy_to_tmp_table); /* Tell handler that we have values for all columns in the to table */ to->use_all_columns(); /* Add virtual columns to vcol_set to ensure they are updated */ if (to->vfield) to->mark_virtual_columns_for_write(TRUE); if (init_read_record(&info, thd, from, (SQL_SELECT *) 0, file_sort, 1, 1, FALSE)) goto err; init_read_record_done= 1; if (ignore && !alter_ctx->fk_error_if_delete_row) to->file->extra(HA_EXTRA_IGNORE_DUP_KEY); thd->get_stmt_da()->reset_current_row_for_warning(); restore_record(to, s->default_values); // Create empty record to->reset_default_fields(); thd->progress.max_counter= from->file->records(); time_to_report_progress= MY_HOW_OFTEN_TO_WRITE/10; while (!(error=info.read_record(&info))) { if (thd->killed) { thd->send_kill_message(); error= 1; break; } if (++thd->progress.counter >= time_to_report_progress) { time_to_report_progress+= MY_HOW_OFTEN_TO_WRITE/10; thd_progress_report(thd, thd->progress.counter, thd->progress.max_counter); } /* Return error if source table isn't empty. */ if (alter_ctx->error_if_not_empty) { error= 1; break; } if (to->next_number_field) { if (auto_increment_field_copied) to->auto_increment_field_not_null= TRUE; else to->next_number_field->reset(); } for (Copy_field *copy_ptr=copy ; copy_ptr != copy_end ; copy_ptr++) { copy_ptr->do_copy(copy_ptr); } prev_insert_id= to->file->next_insert_id; if (to->default_field) to->update_default_fields(0, ignore); if (to->vfield) to->update_virtual_fields(to->file, VCOL_UPDATE_FOR_WRITE); /* This will set thd->is_error() if fatal failure */ if (to->verify_constraints(ignore) == VIEW_CHECK_SKIP) continue; if (thd->is_error()) { error= 1; break; } error=to->file->ha_write_row(to->record[0]); to->auto_increment_field_not_null= FALSE; if (error) { if (to->file->is_fatal_error(error, HA_CHECK_DUP)) { /* Not a duplicate key error. */ to->file->print_error(error, MYF(0)); error= 1; break; } else { /* Duplicate key error. */ if (alter_ctx->fk_error_if_delete_row) { /* We are trying to omit a row from the table which serves as parent in a foreign key. This might have broken referential integrity so emit an error. Note that we can't ignore this error even if we are executing ALTER IGNORE TABLE. IGNORE allows to skip rows, but doesn't allow to break unique or foreign key constraints, */ my_error(ER_FK_CANNOT_DELETE_PARENT, MYF(0), alter_ctx->fk_error_id, alter_ctx->fk_error_table); break; } if (ignore) { /* This ALTER IGNORE TABLE. Simply skip row and continue. */ to->file->restore_auto_increment(prev_insert_id); delete_count++; } else { /* Ordinary ALTER TABLE. Report duplicate key error. */ uint key_nr= to->file->get_dup_key(error); if ((int) key_nr >= 0) { const char *err_msg= ER_THD(thd, ER_DUP_ENTRY_WITH_KEY_NAME); if (key_nr == 0 && (to->key_info[0].key_part[0].field->flags & AUTO_INCREMENT_FLAG)) err_msg= ER_THD(thd, ER_DUP_ENTRY_AUTOINCREMENT_CASE); print_keydup_error(to, key_nr == MAX_KEY ? NULL : &to->key_info[key_nr], err_msg, MYF(0)); } else to->file->print_error(error, MYF(0)); break; } } } else found_count++; thd->get_stmt_da()->inc_current_row_for_warning(); } THD_STAGE_INFO(thd, stage_enabling_keys); thd_progress_next_stage(thd); if (error > 0 && !from->s->tmp_table) { /* We are going to drop the temporary table */ to->file->extra(HA_EXTRA_PREPARE_FOR_DROP); } if (to->file->ha_end_bulk_insert() && error <= 0) { /* Give error, if not already given */ if (!thd->is_error()) to->file->print_error(my_errno,MYF(0)); error= 1; } to->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY); if (mysql_trans_commit_alter_copy_data(thd)) error= 1; err: /* Free resources */ if (init_read_record_done) end_read_record(&info); delete [] copy; delete file_sort; thd->variables.sql_mode= save_sql_mode; thd->abort_on_warning= 0; *copied= found_count; *deleted=delete_count; to->file->ha_release_auto_increment(); if (to->file->ha_external_lock(thd,F_UNLCK)) error=1; if (error < 0 && !from->s->tmp_table && to->file->extra(HA_EXTRA_PREPARE_FOR_RENAME)) error= 1; thd_progress_end(thd); DBUG_RETURN(error > 0 ? -1 : 0); } /* Recreates one table by calling mysql_alter_table(). SYNOPSIS mysql_recreate_table() thd Thread handler table_list Table to recreate table_copy Recreate the table by using ALTER TABLE COPY algorithm RETURN Like mysql_alter_table(). */ bool mysql_recreate_table(THD *thd, TABLE_LIST *table_list, bool table_copy) { HA_CREATE_INFO create_info; Alter_info alter_info; TABLE_LIST *next_table= table_list->next_global; DBUG_ENTER("mysql_recreate_table"); /* Set lock type which is appropriate for ALTER TABLE. */ table_list->lock_type= TL_READ_NO_INSERT; /* Same applies to MDL request. */ table_list->mdl_request.set_type(MDL_SHARED_NO_WRITE); /* hide following tables from open_tables() */ table_list->next_global= NULL; bzero((char*) &create_info, sizeof(create_info)); create_info.row_type=ROW_TYPE_NOT_USED; create_info.default_table_charset=default_charset_info; /* Force alter table to recreate table */ alter_info.flags= (Alter_info::ALTER_CHANGE_COLUMN | Alter_info::ALTER_RECREATE); if (table_copy) alter_info.requested_algorithm= Alter_info::ALTER_TABLE_ALGORITHM_COPY; bool res= mysql_alter_table(thd, NullS, NullS, &create_info, table_list, &alter_info, 0, (ORDER *) 0, 0); table_list->next_global= next_table; DBUG_RETURN(res); } static void flush_checksum(ha_checksum *row_crc, uchar **checksum_start, size_t *checksum_length) { if (*checksum_start) { *row_crc= my_checksum(*row_crc, *checksum_start, *checksum_length); *checksum_start= NULL; *checksum_length= 0; } } bool mysql_checksum_table(THD *thd, TABLE_LIST *tables, HA_CHECK_OPT *check_opt) { TABLE_LIST *table; List<Item> field_list; Item *item; Protocol *protocol= thd->protocol; DBUG_ENTER("mysql_checksum_table"); /* CHECKSUM TABLE returns results and rollbacks statement transaction, so it should not be used in stored function or trigger. */ DBUG_ASSERT(! thd->in_sub_stmt); field_list.push_back(item= new (thd->mem_root) Item_empty_string(thd, "Table", NAME_LEN*2), thd->mem_root); item->maybe_null= 1; field_list.push_back(item= new (thd->mem_root) Item_int(thd, "Checksum", (longlong) 1, MY_INT64_NUM_DECIMAL_DIGITS), thd->mem_root); item->maybe_null= 1; if (protocol->send_result_set_metadata(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); /* Close all temporary tables which were pre-open to simplify privilege checking. Clear all references to closed tables. */ close_thread_tables(thd); for (table= tables; table; table= table->next_local) table->table= NULL; /* Open one table after the other to keep lock time as short as possible. */ for (table= tables; table; table= table->next_local) { char table_name[SAFE_NAME_LEN*2+2]; TABLE *t; TABLE_LIST *save_next_global; strxmov(table_name, table->db ,".", table->table_name, NullS); /* Remember old 'next' pointer and break the list. */ save_next_global= table->next_global; table->next_global= NULL; table->lock_type= TL_READ; /* Allow to open real tables only. */ table->required_type= FRMTYPE_TABLE; if (thd->open_temporary_tables(table) || open_and_lock_tables(thd, table, FALSE, 0)) { t= NULL; } else t= table->table; table->next_global= save_next_global; protocol->prepare_for_resend(); protocol->store(table_name, system_charset_info); if (!t) { /* Table didn't exist */ protocol->store_null(); } else { /* Call ->checksum() if the table checksum matches 'old_mode' settings */ if (!(check_opt->flags & T_EXTEND) && (((t->file->ha_table_flags() & HA_HAS_OLD_CHECKSUM) && thd->variables.old_mode) || ((t->file->ha_table_flags() & HA_HAS_NEW_CHECKSUM) && !thd->variables.old_mode))) protocol->store((ulonglong)t->file->checksum()); else if (check_opt->flags & T_QUICK) protocol->store_null(); else { /* calculating table's checksum */ ha_checksum crc= 0; uchar null_mask=256 - (1 << t->s->last_null_bit_pos); t->use_all_columns(); if (t->file->ha_rnd_init(1)) protocol->store_null(); else { for (;;) { if (thd->killed) { /* we've been killed; let handler clean up, and remove the partial current row from the recordset (embedded lib) */ t->file->ha_rnd_end(); thd->protocol->remove_last_row(); goto err; } ha_checksum row_crc= 0; int error= t->file->ha_rnd_next(t->record[0]); if (unlikely(error)) { if (error == HA_ERR_RECORD_DELETED) continue; break; } if (t->s->null_bytes) { /* fix undefined null bits */ t->record[0][t->s->null_bytes-1] |= null_mask; if (!(t->s->db_create_options & HA_OPTION_PACK_RECORD)) t->record[0][0] |= 1; row_crc= my_checksum(row_crc, t->record[0], t->s->null_bytes); } uchar *checksum_start= NULL; size_t checksum_length= 0; for (uint i= 0; i < t->s->fields; i++ ) { Field *f= t->field[i]; if (! thd->variables.old_mode && f->is_real_null(0)) { flush_checksum(&row_crc, &checksum_start, &checksum_length); continue; } /* BLOB and VARCHAR have pointers in their field, we must convert to string; GEOMETRY is implemented on top of BLOB. BIT may store its data among NULL bits, convert as well. */ switch (f->type()) { case MYSQL_TYPE_BLOB: case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_GEOMETRY: case MYSQL_TYPE_BIT: { flush_checksum(&row_crc, &checksum_start, &checksum_length); String tmp; f->val_str(&tmp); row_crc= my_checksum(row_crc, (uchar*) tmp.ptr(), tmp.length()); break; } default: if (!checksum_start) checksum_start= f->ptr; DBUG_ASSERT(checksum_start + checksum_length == f->ptr); checksum_length+= f->pack_length(); break; } } flush_checksum(&row_crc, &checksum_start, &checksum_length); crc+= row_crc; } protocol->store((ulonglong)crc); t->file->ha_rnd_end(); } } trans_rollback_stmt(thd); close_thread_tables(thd); } if (thd->transaction_rollback_request) { /* If transaction rollback was requested we honor it. To do this we abort statement and return error as not only CHECKSUM TABLE is rolled back but the whole transaction in which it was used. */ thd->protocol->remove_last_row(); goto err; } /* Hide errors from client. Return NULL for problematic tables instead. */ thd->clear_error(); if (protocol->write()) goto err; } my_eof(thd); DBUG_RETURN(FALSE); err: DBUG_RETURN(TRUE); } /** @brief Check if the table can be created in the specified storage engine. Checks if the storage engine is enabled and supports the given table type (e.g. normal, temporary, system). May do engine substitution if the requested engine is disabled. @param thd Thread descriptor. @param db_name Database name. @param table_name Name of table to be created. @param create_info Create info from parser, including engine. @retval true Engine not available/supported, error has been reported. @retval false Engine available/supported. */ bool check_engine(THD *thd, const char *db_name, const char *table_name, HA_CREATE_INFO *create_info) { DBUG_ENTER("check_engine"); handlerton **new_engine= &create_info->db_type; handlerton *req_engine= *new_engine; handlerton *enf_engine= NULL; bool no_substitution= thd->variables.sql_mode & MODE_NO_ENGINE_SUBSTITUTION; *new_engine= ha_checktype(thd, req_engine, no_substitution); DBUG_ASSERT(*new_engine); if (!*new_engine) DBUG_RETURN(true); /* Enforced storage engine should not be used in ALTER TABLE that does not use explicit ENGINE = x to avoid unwanted unrelated changes.*/ if (!(thd->lex->sql_command == SQLCOM_ALTER_TABLE && !(create_info->used_fields & HA_CREATE_USED_ENGINE))) enf_engine= thd->variables.enforced_table_plugin ? plugin_hton(thd->variables.enforced_table_plugin) : NULL; if (enf_engine && enf_engine != *new_engine) { if (no_substitution) { const char *engine_name= ha_resolve_storage_engine_name(req_engine); my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), engine_name, engine_name); DBUG_RETURN(TRUE); } *new_engine= enf_engine; } if (req_engine && req_engine != *new_engine) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_WARN_USING_OTHER_HANDLER, ER_THD(thd, ER_WARN_USING_OTHER_HANDLER), ha_resolve_storage_engine_name(*new_engine), table_name); } if (create_info->tmp_table() && ha_check_storage_engine_flag(*new_engine, HTON_TEMPORARY_NOT_SUPPORTED)) { if (create_info->used_fields & HA_CREATE_USED_ENGINE) { my_error(ER_ILLEGAL_HA_CREATE_OPTION, MYF(0), hton_name(*new_engine)->str, "TEMPORARY"); *new_engine= 0; DBUG_RETURN(true); } *new_engine= myisam_hton; } DBUG_RETURN(false); }
33.404507
100
0.625077
jiunbae
c113ea03e9db5a31e4a47dc40a69e4463857cd95
2,038
cpp
C++
Engine/src/Platform/RayTracer/Samplers/MultiJittered.cpp
jeroennelis/Engine
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
[ "Apache-2.0" ]
null
null
null
Engine/src/Platform/RayTracer/Samplers/MultiJittered.cpp
jeroennelis/Engine
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
[ "Apache-2.0" ]
null
null
null
Engine/src/Platform/RayTracer/Samplers/MultiJittered.cpp
jeroennelis/Engine
43ed6c76d1eeeeddd7fd2b3b38d17ed72d312f1f
[ "Apache-2.0" ]
null
null
null
#include "enpch.h" #include "MultiJittered.h" #include "Engine/Maths.h" namespace Engine { MultiJittered::MultiJittered() :Sampler() { generate_samples(); } MultiJittered::MultiJittered(const int numSamples) : Sampler(numSamples) { generate_samples(); } MultiJittered::MultiJittered(const int numSamples, const int numSet) : Sampler(numSamples, numSet) { generate_samples(); } MultiJittered::MultiJittered(const MultiJittered& mj) : Sampler(mj) { } MultiJittered::~MultiJittered() { } void MultiJittered::generate_samples(void) { // num_samples needs to be a perfect square int n = (int)sqrt((float)num_samples); float subcell_width = 1.0 / ((float)num_samples); // fill the samples array with dummy points to allow us to use the [ ] notation when we set the // initial patterns glm::vec2 fill_point; for (int j = 0; j < num_samples * num_sets; j++) samples.push_back(fill_point); // distribute points in the initial patterns for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { samples[i * n + j + p * num_samples].x = (i * n + j) * subcell_width + rand_float(0, subcell_width); samples[i * n + j + p * num_samples].y = (j * n + i) * subcell_width + rand_float(0, subcell_width); } // shuffle x coordinates for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int k = rand_int(j, n - 1); float t = samples[i * n + j + p * num_samples].x; samples[i * n + j + p * num_samples].x = samples[i * n + k + p * num_samples].x; samples[i * n + k + p * num_samples].x = t; } // shuffle y coordinates for (int p = 0; p < num_sets; p++) for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { int k = rand_int(j, n - 1); float t = samples[j * n + i + p * num_samples].y; samples[j * n + i + p * num_samples].y = samples[k * n + i + p * num_samples].y; samples[k * n + i + p * num_samples].y = t; } } }
24.261905
105
0.594701
jeroennelis
c114980004646a54d3235646452a9c60715c2618
790
cpp
C++
src/main/src/hr-test8.cpp
jasonwee/cpp_lesson
084d03759956e2ab378c45c93611ed9216e87536
[ "Apache-2.0" ]
null
null
null
src/main/src/hr-test8.cpp
jasonwee/cpp_lesson
084d03759956e2ab378c45c93611ed9216e87536
[ "Apache-2.0" ]
null
null
null
src/main/src/hr-test8.cpp
jasonwee/cpp_lesson
084d03759956e2ab378c45c93611ed9216e87536
[ "Apache-2.0" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { int n=0,i=0,j=0; string temp; cin >> n; vector<vector<int> > a(n, vector<int>(n)); for (i = 0; i < n; i++) { cin >> temp; j = 0; for (char& c : temp) { a[i][j] = c - '0'; j+=1; } } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if ( (i >= 1 ) && (i < n-1) && ( j >= 1 ) && ( j < n-1 ) ) { if ( (a[i][j] > a[i-1][j]) && (a[i][j] > a[i][j+1]) && (a[i][j] > a[i+1][j]) && (a[i][j] > a[i][j-1])) cout << "X"; else cout << a[i][j]; } else { // the one on the edge will never get print X cout << a[i][j]; } } cout << endl; } }
19.268293
110
0.386076
jasonwee
c114d89d3f36bf5664fa842d7f1bf9c3ddded22e
1,016
cpp
C++
Backtracking/letter_phone.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Backtracking/letter_phone.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Backtracking/letter_phone.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; map<char, vector<char>> m; string current; void util(string &A, int i, vector<string> &ans) { if(i >= A.size()) { ans.push_back(current); return; } for(char ch: m[A[i]]) { current.push_back(ch); util(A, i + 1, ans); current.pop_back(); } } vector<string> letterCombinations(string A) { m.insert({'1', vector<char>{'1'}}); m.insert({'2', vector<char>{'a', 'b', 'c'}}); m.insert({'3', vector<char>{'d', 'e', 'f'}}); m.insert({'4', vector<char>{'g', 'h', 'i'}}); m.insert({'5', vector<char>{'j', 'k', 'l'}}); m.insert({'6', vector<char>{'m', 'n', 'o'}}); m.insert({'7', vector<char>{'p', 'q', 'r', 's'}}); m.insert({'8', vector<char>{'t', 'u', 'v'}}); m.insert({'9', vector<char>{'w', 'x', 'y', 'z'}}); m.insert({'0', vector<char>{'0'}}); vector<string> ans; util(A, 0, ans); sort(ans.begin(), ans.end()); return ans; } int main(void) { string s; cin >> s; for(string a: letterCombinations(s)) { cout << a << endl; } return 0; }
20.734694
51
0.540354
aneesh001
c11682a871c77334bfadcc50e6e2df9c4b193e48
6,416
cpp
C++
plugins/QGames/Tga.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
1
2020-07-19T10:19:18.000Z
2020-07-19T10:19:18.000Z
plugins/QGames/Tga.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
null
null
null
plugins/QGames/Tga.cpp
joeriedel/Tread3.0A2
337c4aa74d554e21b50d6bd4406ce0f67aa39144
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // Tga.cpp /////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Joe Riedel // All rights reserved. // // Redistribution and use in source and binary forms, // with or without modification, are permitted provided // that the following conditions are met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // Neither the name of the <ORGANIZATION> nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // // IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT // NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. /////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Tga.h" #include "ByteParser.h" #include <algorithm> static bool UnpackTGAByte3(unsigned char *DestBuffer,const unsigned char *InputPtr,int Pixels, int buffLength) { int Count; do { if (buffLength<1) return false; Count = *InputPtr++; /* Get the counter */ if (Count&0x80) { /* Packed? */ if (buffLength<3) return false; unsigned short Temp; unsigned char Temp2; Count = Count-0x7F; /* Remove the high bit */ Pixels = Pixels-Count; Temp = LoadIntelShort(((const unsigned short *)(InputPtr+1))[0]); /* Get G,R */ Temp2 = InputPtr[0]; /* Blue */ InputPtr = InputPtr+3; buffLength -= 3; do { ((unsigned short *)DestBuffer)[0] = Temp; /* R and G */ DestBuffer[2] = Temp2; /* Blue */ DestBuffer = DestBuffer+3; } while (--Count); } else { ++Count; /* +1 to the count */ if (buffLength<Count) return false; Pixels = Pixels-Count; /* Adjust amount */ buffLength -= Count; do { DestBuffer[0] = InputPtr[2]; /* Red */ DestBuffer[1] = InputPtr[1]; /* Green */ DestBuffer[2] = InputPtr[0]; /* Blue */ DestBuffer = DestBuffer+3; /* Next index */ InputPtr = InputPtr+3; } while (--Count); /* All done? */ } } while (Pixels>0); /* Is there still more? */ return true; } static bool UnpackTGALong(unsigned char *DestBuffer,const unsigned char *InputPtr,int Pixels, int buffLength) { int Count; do { if (buffLength<1) return false; Count = *InputPtr++; /* Get the counter */ if (Count&0x80) { /* Packed? */ if (buffLength<4) return false; unsigned int Temp; Count = Count-0x7F; /* Remove the high bit and add 1 */ Pixels = Pixels-Count; ((unsigned char *)&Temp)[0] = InputPtr[2]; /* Red */ ((unsigned char *)&Temp)[1] = InputPtr[1]; /* Green */ ((unsigned char *)&Temp)[2] = InputPtr[0]; /* Blue */ ((unsigned char *)&Temp)[3] = InputPtr[3]; /* Alpha */ InputPtr = InputPtr+4; buffLength -= 4; do { ((unsigned int *)DestBuffer)[0] = Temp; /* Fill memory */ DestBuffer = DestBuffer+4; } while (--Count); } else { ++Count; /* +1 to the count */ if (buffLength<Count) return false; Pixels = Pixels-Count; /* Adjust amount */ buffLength -= Count; do { DestBuffer[0] = InputPtr[2]; /* Red */ DestBuffer[1] = InputPtr[1]; /* Green */ DestBuffer[2] = InputPtr[0]; /* Blue */ DestBuffer[3] = InputPtr[3]; /* Alpha */ InputPtr = InputPtr+4; DestBuffer = DestBuffer+4; } while (--Count); /* All done? */ } } while (Pixels>0); /* Is there still more? */ return true; } bool CTga::IsTga(const void *buff, int len) { if (len < 18) return false; const unsigned char *ptr = reinterpret_cast<const unsigned char*>(buff); return ptr[2] == 2 || ptr[2] == 10; } bool CTga::ReadInfo(const void *buff, int len, int *width, int *height, int *bpp) { if (!IsTga(buff, len)) return false; CByteParser parser(buff, len); parser.Skip(12); *width = parser.ReadShort(); *height = parser.ReadShort(); int bits = parser.ReadByte(); *bpp = bits / 8; return true; } bool CTga::Read(const void *buff, int len, void **dst, int *width, int *height, int *bpp) { if (!IsTga(buff, len)) return false; CByteParser parser(buff, len); int tagLen = parser.ReadByte(); parser.Skip(1); int type = parser.ReadByte(); parser.Skip(9); //int xorg = parser.ReadShort(); //int yorg = parser.ReadShort(); *width = parser.ReadShort(); *height = parser.ReadShort(); int bits = parser.ReadByte(); *bpp = bits / 8; int flags = parser.ReadByte(); parser.Skip(tagLen); int imgLen = *width * *height * *bpp; len = parser.Left(); if (!len) return false; unsigned char *ptr = new unsigned char[len]; parser.Read(ptr, len); switch (type) { case 2: // BGR uncompressed { *dst = ptr; } break; case 10: // BGR rle { *dst = new unsigned char[imgLen]; if (*bpp == 3) { UnpackTGAByte3((unsigned char*)*dst, ptr, imgLen / *bpp, len); } else { UnpackTGALong((unsigned char*)*dst, ptr, imgLen / *bpp, len); } delete [] ptr; ptr = (unsigned char*)*dst; } break; } unsigned char *work = ptr; for (int i = 0; i < imgLen/(*bpp); ++i) { std::swap(work[0], work[2]); work += *bpp; } if ((flags&32) == 0) { int scan = *width * *bpp; unsigned char *swap = new unsigned char[scan]; for (int y = 0; y < *height/2 ; ++y) { int flipY = *height - y - 1; void *a = &ptr[y * scan]; void *b = &ptr[flipY * scan]; memcpy(swap, a, scan); memcpy(a, b, scan); memcpy(b, swap, scan); } delete [] swap; } // a2l return true; }
30.552381
110
0.618142
joeriedel
c1179bc0c3e93085b89fae559b0685a68a1636d9
24,418
cpp
C++
src/ofxAppContent.cpp
local-projects/ofxLpApp
ac7917ab3f6e83a7c126f512e1397742910a2ef5
[ "MIT" ]
21
2016-10-04T20:49:23.000Z
2020-11-14T11:20:22.000Z
src/ofxAppContent.cpp
local-projects/ofxLpApp
ac7917ab3f6e83a7c126f512e1397742910a2ef5
[ "MIT" ]
2
2020-09-10T21:56:07.000Z
2020-09-17T10:02:36.000Z
src/ofxAppContent.cpp
local-projects/ofxLpApp
ac7917ab3f6e83a7c126f512e1397742910a2ef5
[ "MIT" ]
4
2016-09-11T17:01:18.000Z
2019-05-21T02:48:22.000Z
// // ofxAppContent.cpp // // Created by Oriol Ferrer Mesià aug/2016 // // #include "ofxAppContent.h" #include "ofxAppUtils.h" #include "ofxApp.h" #include "ofxChecksum.h" #include "ofxAppErrorReporter.h" #include "ofxGoogleAnalytics.h" void ofxAppContent::setup( const std::string & ID, const std::string & jsonSrc, const std::string & jsonSrc_offline, bool useOfflineJson, const std::string & jsonDestinationDir_, int numThreads_, int maxDlRetries, int copyBufferSizeKb, int numConcurrentDownloads, int speedLimitKBs, int timeoutDownloads, int timeoutApiEndpoint, bool shouldSkipObjectTests, float idleTimeAfterEachDownload, const std::pair<std::string,std::string> & downloaderCredentials, ofxChecksum::Type checksumType, const ofxSimpleHttp::ProxyConfig & downloaderProxyConfig, const std::pair<std::string,std::string> & apiEndPointCredentials, const ofxSimpleHttp::ProxyConfig & apiEndpointProxyConfig, const map<std::string, std::string> customHeaders, const ofxApp::ParseFunctions & contentCfg, const ofxAssets::DownloadPolicy assetDownloadPolicy, const ofxAssets::UsagePolicy assetUsagePolicy, const ofxAssets::ObjectUsagePolicy & objectUsagePolicy, const std::string & assetsLocationPath, bool skipChecksumTests, float assetErrorsScreenReportTimeSeconds){ state = ContentState::IDLE; parsedObjects.clear(); this->ID = ID; this->assetErrorsScreenReportTimeSeconds = assetErrorsScreenReportTimeSeconds; this->jsonURL = jsonSrc; this->jsonURL_offline = jsonSrc_offline; this->useOfflineJson = useOfflineJson; this->contentCfg = contentCfg; this->assetDownloadPolicy = assetDownloadPolicy; this->assetUsagePolicy = assetUsagePolicy; this->objectUsagePolicy = objectUsagePolicy; this->jsonDestinationDir = jsonDestinationDir_; this->numThreads = numThreads_; this->shouldSkipObjectTests = shouldSkipObjectTests; this->assetsLocationPath = assetsLocationPath; this->shouldSkipSha1Tests = skipChecksumTests; if(skipChecksumTests){ ofLogWarning("ofxAppContent-" + ID) << "Running with skipChecksumTests == TRUE! Never run in this mode in production!"; } //config the http downloader if you need to (proxy, etc) dlc.setMaxConcurrentDownloads(numConcurrentDownloads); dlc.setSpeedLimit(speedLimitKBs); dlc.setCopyBufferSize(copyBufferSizeKb); dlc.setMaxRetries(maxDlRetries); dlc.setTimeOut(timeoutDownloads); dlc.setIdleTimeAfterEachDownload(idleTimeAfterEachDownload); dlc.setCredentials(downloaderCredentials.first, downloaderCredentials.second); dlc.setProxyConfiguration(downloaderProxyConfig); dlc.setChecksumType(checksumType); jsonParser.getHttp().setTimeOut(timeoutApiEndpoint); jsonParser.getHttp().setSpeedLimit(speedLimitKBs); jsonParser.getHttp().setCopyBufferSize(copyBufferSizeKb); //kb jsonParser.getHttp().setProxyConfiguration(apiEndpointProxyConfig); if(apiEndPointCredentials.first.size() || apiEndPointCredentials.second.size()){ jsonParser.getHttp().setCredentials(apiEndPointCredentials.first, apiEndPointCredentials.second); } for(auto & h : customHeaders){ jsonParser.getHttp().addCustomHttpHeader(h.first, h.second); } //subscribe to parsing events ofAddListener(jsonParser.eventJsonDownloaded, this, &ofxAppContent::onJsonDownloaded); ofAddListener(jsonParser.eventJsonDownloadFailed, this, &ofxAppContent::onJsonDownloadFailed); ofAddListener(jsonParser.eventJsonInitialCheckOK, this, &ofxAppContent::onJsonInitialCheckOK); ofAddListener(jsonParser.eventJsonParseFailed, this, &ofxAppContent::onJsonParseFailed); ofAddListener(jsonParser.eventAllObjectsParsed, this, &ofxAppContent::onJsonContentReady); } ofxAppContent::~ofxAppContent(){ ofLogNotice("ofxAppContent-" + ID) << "~ofxAppContent"; } void ofxAppContent::setNumThreads(int nThreads){ numThreads = MAX(nThreads, 1); } void ofxAppContent::setMaxConcurrentDownloads(int nDownloads){ dlc.setMaxConcurrentDownloads(nDownloads); } void ofxAppContent::setJsonDownloadURL(std::string newJsonURL, bool itsOfflineJson){ if(itsOfflineJson){ useOfflineJson = true; this->jsonURL_offline = newJsonURL; ofLogNotice("ofxAppContent-" + ID) << "updating the Offline JSON Content URL of " << ID << " to '" << newJsonURL << "' and setting to use offline"; }else{ ofLogNotice("ofxAppContent-" + ID) << "updating the LIVE JSON Content URL of " << ID << " to '" << newJsonURL << "' and setting to use online"; useOfflineJson = false; this->jsonURL = newJsonURL; } }; void ofxAppContent::fetchContent(){ if(state == ContentState::IDLE || state == ContentState::JSON_PARSE_FAILED || state == ContentState::JSON_DOWNLOAD_FAILED || state == ContentState::JSON_CONTENT_READY ){ parsedObjects.clear(); //FIXME: here we are potentially leaking! setState(ContentState::DOWNLOADING_JSON); startTimestamp = ofGetElapsedTimef(); }else{ ofLogError("ofxAppContent-" + ID) << "Can't fetch content now!"; } } void ofxAppContent::stopAllDownloads(){ dlc.cancelAllDownloads(); } void ofxAppContent::update(float dt){ timeInState += ofGetLastFrameTime(); jsonParser.update(); dlc.update(); assetChecker.update(); switch(state){ case ContentState::CATALOG_ASSETS: if(!isThreadRunning()){ if(shouldSkipSha1Tests){ setState(ContentState::SETUP_TEXTURED_OBJECTS); }else{ setState(ContentState::CHECKING_ASSET_STATUS); } } break; case ContentState::REMOVING_EXPIRED_ASSETS:{ if(!isThreadRunning()){ ofLogNotice("ofxAppContent-" + ID) << "Finished Removing Expired assets."; setState(ContentState::DOWNLOADING_ASSETS); } }break; case ContentState::DOWNLOADING_ASSETS: if(!dlc.isBusy()){ //downloader finished! ofLogNotice("ofxAppContent-" + ID) << "Finished Asset downloads for \"" << ID << "\"!"; setState(ContentState::FILTER_OBJECTS_WITH_BAD_ASSETS); }break; case ContentState::FILTER_OBJECTS_WITH_BAD_ASSETS: if(timeInState > (numIgnoredObjects > 0 ? assetErrorsScreenReportTimeSeconds : 0.0)){ //show this on screen for a sec if we are dropping objects setState(ContentState::SETUP_TEXTURED_OBJECTS); } break; case ContentState::SETUP_TEXTURED_OBJECTS:{ int maxObjectsToSetupInOneFrame = 50; //stagger across frames, to avoid hogging the app int start = numSetupTexuredObjects; int end = MIN(parsedObjects.size(), numSetupTexuredObjects + maxObjectsToSetupInOneFrame); for(int i = start; i < end; i++){ //call the User Supplied Lambda to setup the user's TexturedObject contentCfg.setupTexturedObject( parsedObjects[i] ); numSetupTexuredObjects++; } if(numSetupTexuredObjects == parsedObjects.size()){ setState(ContentState::FILTER_REJECTED_TEXTURED_OBJECTS); } }break; case ContentState::FILTER_REJECTED_TEXTURED_OBJECTS:{ if(timeInState > (numIgnoredObjects > 0 ? assetErrorsScreenReportTimeSeconds : 0.0)){ //show this on screen for a sec if we are dropping objects setState(ContentState::JSON_CONTENT_READY); } } default: break; } } void ofxAppContent::threadedFunction(){ #ifdef TARGET_WIN32 #elif defined(TARGET_LINUX) pthread_setname_np(pthread_self(), string("ofxAppContent " + ID).c_str()); #else pthread_setname_np(string("ofxAppContent " + ID).c_str()); #endif switch (state){ case ContentState::CATALOG_ASSETS:{ ofxApp::CatalogAssetsData d; d.userData = &contentCfg.userData; d.assetsLocation = assetsLocationPath; d.assetUsagePolicy = assetUsagePolicy; d.assetDownloadPolicy = assetDownloadPolicy; for(auto co : parsedObjects){ d.object = co; contentCfg.defineObjectAssets(d); } }break; case ContentState::REMOVING_EXPIRED_ASSETS:{ if(assetsLocationPath.size()){ removeExpiredAssets(); } }break; default: break; } ofSleepMillis(45); //this is a shameful workaround to overcome the bug where too-short-lived threads cause expcetions on windows. //https://github.com/openframeworks/openFrameworks/issues/5262 //content with no asset will create this condition. //FIXME: transition out of ofThread into std::thread/async. } void ofxAppContent::removeExpiredAssets(){ //accumulate all assets that should be in the filesystem //note all paths are turned to absolute vector<string> allExpectedAssets; for(auto co : parsedObjects){ auto assets = co->getAllAssetsInDB(); for(auto & ad : assets){ allExpectedAssets.push_back(ofToDataPath(ad.relativePath, true)); } } if (ofDirectory::doesDirectoryExist(assetsLocationPath)){ //build a list of files that exist in ofDirectory assetsDir; vector<string> allFilesOnAssetFolder; //store all files existing on assets dir vector<string> allEmptyDirs; //store all dirs with 0 files inside for deletion assetsDir.listDir(assetsLocationPath); for(int i = 0; i < assetsDir.numFiles(); i++){ if(assetsDir.getFile(i).isDirectory()){ //if each objectID has its assets in a dir ofDirectory objDir; objDir.listDir(assetsDir.getPath(i)); if(objDir.numFiles() == 0){ allEmptyDirs.push_back(ofToDataPath(assetsDir.getPath(i), true)); }else{ for(int j = 0; j < objDir.numFiles(); j++){ allFilesOnAssetFolder.push_back(ofToDataPath(objDir.getPath(j), true)); } } }else{ //all assets from all objects mixed in the assets dir allFilesOnAssetFolder.push_back(ofToDataPath(assetsDir.getPath(i), true)); } } for(auto & dir : allEmptyDirs){ ofLogWarning("ofxAppContent-" + ID) << "removing empty directory at \"" << ofToDataPath(dir) << "\""; ofDirectory::removeDirectory(dir, true, false); } for(auto & file : allFilesOnAssetFolder){ auto it = std::find(allExpectedAssets.begin(), allExpectedAssets.end(), file); if (it == allExpectedAssets.end()){ //this file on disk is not in the expected asset file list, delete! ofLogWarning("ofxAppContent-" + ID) << "removing expired asset at \"" << ofToDataPath(file) << "\""; ofFile::removeFile(file, false); } } } } void ofxAppContent::setShouldRemoveExpiredAssets(bool set){ shouldRemoveExpiredAssets = set; } void ofxAppContent::setState(ContentState s){ state = s; timeInState = 0; switch (s) { case ContentState::DOWNLOADING_JSON:{ //start the download and parse process contentCfg.userData["jsonURL"] = jsonURL; //always use the live json URL for media download contentCfg.userData["jsonDestinationDir"] = jsonDestinationDir; jsonParser.downloadAndParse(getAdaptativeJsonUrl(), jsonDestinationDir, //directory where to save numThreads, //num threads contentCfg.pointToObjects, contentCfg.parseOneObject, contentCfg.userData ); } break; case ContentState::CATALOG_ASSETS: startThread(); break; case ContentState::CHECKING_ASSET_STATUS:{ //sadly we need to cast our objects to AssetHolder* objects to check them if (parsedObjects.size()) { vector<AssetHolder*> assetObjs; for (int i = 0; i < parsedObjects.size(); i++) { assetObjs.push_back(dynamic_cast<AssetHolder*>(parsedObjects[i])); } ofAddListener(assetChecker.eventFinishedCheckingAllAssets, this, &ofxAppContent::assetCheckFinished); //assetChecker.checkAssets(assetObjs, numThreads); assetChecker.checkAssets(assetObjs, std::thread::hardware_concurrency()); } else { ofLogWarning("ofxAppContent-" + ID) << "There are ZERO parsed objects!"; setState(ContentState::JSON_CONTENT_READY); } }break; case ContentState::REMOVING_EXPIRED_ASSETS: ofLogNotice("ofxAppContent-" + ID) << "Start expired asset removal phase."; startThread(); break; case ContentState::DOWNLOADING_ASSETS: //fill in the list for(int i = 0; i < parsedObjects.size(); i++){ parsedObjects[i]->downloadMissingAssets(dlc); } totalAssetsToDownload = dlc.getNumPendingDownloads(); dlc.setNeedsChecksumMatchToSkipDownload(true); dlc.startDownloading(); break; case ContentState::FILTER_OBJECTS_WITH_BAD_ASSETS:{ int numObjectB4Filter = parsedObjects.size(); if(!shouldSkipObjectTests){ objectsWithBadAssets.clear(); vector<int> badObjects; vector<std::string> badObjectsIds; for(int i = 0; i < parsedObjects.size(); i++){ //do some asset integrity tests... bool allAssetsOK = parsedObjects[i]->areAllAssetsOK(); bool needsAllAssetsToBeOk = objectUsagePolicy.allObjectAssetsAreOK; int numImgAssets = parsedObjects[i]->getAssetDescriptorsForType(ofxAssets::IMAGE).size(); int numVideoAssets = parsedObjects[i]->getAssetDescriptorsForType(ofxAssets::VIDEO).size(); int numAudioAssets = parsedObjects[i]->getAssetDescriptorsForType(ofxAssets::AUDIO).size(); bool rejectObject = false; std::string rejectionReason; //apply all policy rules to decide if object is rejected or not if(needsAllAssetsToBeOk){ if(!allAssetsOK){ rejectObject = true; auto brokenAssets = parsedObjects[i]->getBrokenAssets(); if(rejectionReason.size()) rejectionReason += " | "; rejectionReason += ofToString(brokenAssets.size()) + " Broken Asset(s)"; } } if(numImgAssets < objectUsagePolicy.minNumberOfImageAssets){ rejectObject = true; if(rejectionReason.size()) rejectionReason += " | "; rejectionReason += "Not Enough Images"; ofLogError("ofxAppContent-" + ID) << "Rejecting Object '" << parsedObjects[i]->getObjectUUID() << "' because doesnt have the min # of images! (" << numImgAssets << "/" << objectUsagePolicy.minNumberOfImageAssets << ")" ; } if(numVideoAssets < objectUsagePolicy.minNumberOfVideoAssets){ rejectObject = true; if(rejectionReason.size()) rejectionReason += " | "; rejectionReason += "Not Enough Videos"; ofLogError("ofxAppContent-" + ID) << "Rejecting Object '" << parsedObjects[i]->getObjectUUID() << "' because doesnt have the min # of Videos! (" << numVideoAssets << "/" << objectUsagePolicy.minNumberOfVideoAssets << ")" ; } if(numAudioAssets < objectUsagePolicy.minNumberOfAudioAssets){ rejectObject = true; if(rejectionReason.size()) rejectionReason += " | "; rejectionReason += "Not Enough AudioFiles"; ofLogError("ofxAppContent-" + ID) << "Rejecting Object '" << parsedObjects[i]->getObjectUUID() << "' because doesnt have the min # of Audio Files! (" << numAudioAssets << "/" << objectUsagePolicy.minNumberOfAudioAssets << ")" ; } if (rejectObject){ badObjects.push_back(i); badObjectsIds.push_back(parsedObjects[i]->getObjectUUID()); objectsWithBadAssets += "Object '" + badObjectsIds.back() + "' : " + rejectionReason + "\n"; } } for(int i = badObjects.size() - 1; i >= 0; i--){ ofLogError("ofxAppContent-" + ID) << "Dropping object \"" << parsedObjects[i]->getObjectUUID() << "\""; delete parsedObjects[badObjects[i]]; parsedObjects.erase(parsedObjects.begin() + badObjects[i]); } numIgnoredObjects += badObjects.size(); objectsWithBadAssets = "\nRemoved " + ofToString(badObjects.size()) + " \"" + ID + "\" objects:\n\n" + objectsWithBadAssets + "\n\n" ; }else{ ofLogWarning("ofxAppContent-" + ID) << "skipping Object Drop Policy Tests!! \"" << ID << "\""; } }break; case ContentState::SETUP_TEXTURED_OBJECTS:{ numSetupTexuredObjects = 0; }break; case ContentState::FILTER_REJECTED_TEXTURED_OBJECTS:{ int numObjectB4Filter = parsedObjects.size(); vector<int> badObjects; vector<std::string> badObjectsIds; string log; for(int i = 0; i < numObjectB4Filter; i++){ bool userRejectedObject = !parsedObjects[i]->isValid; if (userRejectedObject){ badObjects.push_back(i); badObjectsIds.push_back(parsedObjects[i]->getObjectUUID()); log += "Object '" + badObjectsIds.back() + "' : Rejected at Setup Textured Object stage - probably cant load img\n"; } } for(int i = badObjects.size() - 1; i >= 0; i--){ ofLogError("ofxAppContent-" + ID) << "Dropping object at setup Textured Object Stage \"" << parsedObjects[i]->getObjectUUID() << "\""; delete parsedObjects[badObjects[i]]; parsedObjects.erase(parsedObjects.begin() + badObjects[i]); } numIgnoredObjects += badObjects.size(); objectsWithBadAssets += "Setup Textured Object Statge\n\nRemoved " + ofToString(badObjects.size()) + " \"" + ID + "\" objects:\n\n" + log; if(numIgnoredObjects > 0){ ofLogWarning("ofxAppContent-" + ID) << objectsWithBadAssets; ofLogWarning("ofxAppContent-" + ID) << "Removed a total of " << numIgnoredObjects << " objects for content type \"" << ID << "\" due to various rasons. Check 'logs/assetStatus.log' for more info."; auto a = ofxApp::get().analytics(); if(a && a->isEnabled()){ a->sendException("ofxApp - Content '" + ID + "' - rejected " + ofToString(numIgnoredObjects) + " objects.", false); } } float pct; if(numObjectB4Filter > 0){ pct = 100.0f * numIgnoredObjects / float(numObjectB4Filter); }else{ pct = 0.0f; } if(pct > 0.0f){ ofLogWarning("ofxAppContent-" + ID) << "Ignored " << ofToString(pct,2) << "% of the objects defined in the \"" << ID << "\" JSON."; } }break; case ContentState::JSON_CONTENT_READY:{ //keep the json as a good one ofFile jsonFile; jsonFile.open(jsonParser.getJsonLocalPath()); std::string jsonPath = jsonParser.getJsonLocalPath(); std::string dir = ofFilePath::getEnclosingDirectory(jsonPath); ofFilePath::createEnclosingDirectory(dir + "knownGood"); std::string oldJsonPath = dir + "/knownGood/" + ID + ".json"; //calc sha1 for the last konwn json, and the fresh one newJsonChecksum = ofxChecksum::calcSha1(jsonParser.getJsonLocalPath()); if(ofFile::doesFileExist(oldJsonPath)){ oldJsonChecksum = ofxChecksum::calcSha1(oldJsonPath); } //replace the old json with the fresh one jsonFile.moveTo(oldJsonPath, false, true); totalDuration = ofGetElapsedTimef() - startTimestamp; }break; default: break; } std::string info = "\"" + ID + "\" > " + getNameForState(state); if (shouldSkipSha1Tests) info += " - SKIPPING CHECKSUM TESTS!"; ofNotifyEvent(eventStateChanged, info); } std::string ofxAppContent::getLastKnownGoodJsonPath(){ std::string dir = ofFilePath::getEnclosingDirectory(jsonParser.getJsonLocalPath()); return dir + "knownGood/" + ID + ".json"; } std::string ofxAppContent::getStatus(){ std::string r; switch (state) { case ContentState::DOWNLOADING_JSON: r = jsonParser.getHttp().drawableString(); break; case ContentState::JSON_DOWNLOAD_FAILED: r = errorMessage; break; case ContentState::CHECKING_JSON: r = jsonParser.getDrawableState(); break; case ContentState::PARSING_JSON: r = jsonParser.getDrawableState(); break; case ContentState::CATALOG_ASSETS: break; case ContentState::CHECKING_ASSET_STATUS: r = assetChecker.getDrawableState(); break; case ContentState::JSON_PARSE_FAILED: r = errorMessage; break; case ContentState::DOWNLOADING_ASSETS: r = dlc.getDrawableInfo(true, false); break; case ContentState::FILTER_OBJECTS_WITH_BAD_ASSETS: r = objectsWithBadAssets; break; case ContentState::SETUP_TEXTURED_OBJECTS: break; case ContentState::FILTER_REJECTED_TEXTURED_OBJECTS: r = objectsWithBadAssets; break; case ContentState::JSON_CONTENT_READY: r = "READY"; break; default: break; } return r; } float ofxAppContent::getPercentDone(){ float p = -1.0f; switch (state) { case ContentState::DOWNLOADING_JSON: p = jsonParser.getHttp().getCurrentDownloadProgress(); break; case ContentState::CHECKING_JSON: p = -1.0; break; case ContentState::PARSING_JSON: p = jsonParser.getTotalProgress(); break; case ContentState::CATALOG_ASSETS: p = -1; break; case ContentState::CHECKING_ASSET_STATUS: p = assetChecker.getProgress(); break; case ContentState::FILTER_OBJECTS_WITH_BAD_ASSETS: p = -1; break; case ContentState::SETUP_TEXTURED_OBJECTS: p = numSetupTexuredObjects / float(parsedObjects.size()); break; case ContentState::DOWNLOADING_ASSETS: p = 1.0 - float(dlc.getNumPendingDownloads()) / totalAssetsToDownload; break; default: break; } return p; } bool ofxAppContent::isReadyToFetchContent(){ return state == ContentState::IDLE || state == ContentState::JSON_PARSE_FAILED || state == ContentState::JSON_DOWNLOAD_FAILED || state == ContentState::JSON_CONTENT_READY; } bool ofxAppContent::foundError(){ return state == ContentState::JSON_DOWNLOAD_FAILED || state == ContentState::JSON_PARSE_FAILED; }; bool ofxAppContent::isContentReady(){ return state == ContentState::JSON_CONTENT_READY; }; // CALBACKS //////////////////////////////////////////////////////////////////////////////////// #pragma mark Callbacks void ofxAppContent::onJsonDownloaded(ofxSimpleHttpResponse & arg){ ofLogNotice("ofxAppContent-" + ID) << "JSON download OK! \"" << getAdaptativeJsonUrl() << "\""; setState(ContentState::CHECKING_JSON); OFXAPP_REPORT("ofxAppJsonDownloadFailed", "JSON Download OK for '" + ID + "'! \"" + getAdaptativeJsonUrl() + "\"", 0); } void ofxAppContent::onJsonDownloadFailed(ofxSimpleHttpResponse & arg){ ofLogError("ofxAppContent-" + ID) << "JSON download failed! \"" << getAdaptativeJsonUrl() << "\""; errorMessage = arg.reasonForStatus + " (" + arg.url + ")"; OFXAPP_REPORT("ofxAppJsonDownloadFailed", "JSON Download Failed for '" + ID + "'! \"" + getAdaptativeJsonUrl() + "\"\nreason: " + arg.reasonForStatus , 2); setState(ContentState::JSON_DOWNLOAD_FAILED); } void ofxAppContent::onJsonInitialCheckOK(){ ofLogNotice("ofxAppContent-" + ID) << "JSON Initial Check OK! \"" << getAdaptativeJsonUrl() << "\""; OFXAPP_REPORT("ofxAppJsonParseFailed", "JSON Parse OK '" + ID + "'! \"" + getAdaptativeJsonUrl() + "\"", 0); setState(ContentState::PARSING_JSON); } void ofxAppContent::onJsonParseFailed(){ ofLogError("ofxAppContent-" + ID) << "JSON Parse Failed! \"" << getAdaptativeJsonUrl() << "\""; OFXAPP_REPORT("ofxAppJsonParseFailed", "JSON Parse Failed for '" + ID + "'! \"" + getAdaptativeJsonUrl() + "\"" , 2); errorMessage = "Json parse of \"" + getAdaptativeJsonUrl() + "\" failed!"; setState(ContentState::JSON_PARSE_FAILED); } void ofxAppContent::onJsonContentReady(vector<ParsedObject*> &parsedObjects_){ ofLogNotice("ofxAppContent-" + ID) << "JSON Content Ready! " << parsedObjects_.size() << " Objects received."; numIgnoredObjects += jsonParser.getNumEntriesInJson() - parsedObjects_.size(); parsedObjects.reserve(parsedObjects_.size()); for(auto o : parsedObjects_){ //ContentObject * co = static_cast<ContentObject*>(o); ContentObject * co = (ContentObject*)(o); parsedObjects.push_back(co); } setState(ContentState::CATALOG_ASSETS); } std::string ofxAppContent::getAdaptativeJsonUrl(){ return useOfflineJson ? jsonURL_offline : jsonURL; } void ofxAppContent::assetCheckFinished(){ ofLogNotice("ofxAppContent-" + ID) << "Asset Check Finished!"; if(shouldRemoveExpiredAssets){ setState(ContentState::REMOVING_EXPIRED_ASSETS); }else{ setState(ContentState::DOWNLOADING_ASSETS); } } std::string ofxAppContent::getNameForState(ofxAppContent::ContentState state){ switch (state) { case ContentState::IDLE: return "IDLE"; case ContentState::DOWNLOADING_JSON: return "DOWNLOADING_JSON"; case ContentState::JSON_DOWNLOAD_FAILED: return "JSON_DOWNLOAD_FAILED"; case ContentState::CHECKING_JSON: return "CHECKING_JSON"; case ContentState::JSON_PARSE_FAILED: return "JSON_PARSE_FAILED"; case ContentState::PARSING_JSON: return "PARSING_JSON"; case ContentState::CATALOG_ASSETS: return "CATALOG_ASSETS"; case ContentState::CHECKING_ASSET_STATUS: return "CHECKING_ASSET_STATUS"; case ContentState::REMOVING_EXPIRED_ASSETS: return "REMOVING_EXPIRED_ASSETS"; case ContentState::DOWNLOADING_ASSETS: return "DOWNLOADING_ASSETS"; case ContentState::FILTER_OBJECTS_WITH_BAD_ASSETS: return "FILTER_OBJECTS_WITH_BAD_ASSETS"; case ContentState::SETUP_TEXTURED_OBJECTS: return "SETUP_TEXTURED_OBJECTS"; case ContentState::FILTER_REJECTED_TEXTURED_OBJECTS: return "FILTER_REJECTED_TEXTURED_OBJECTS"; case ContentState::JSON_CONTENT_READY: return "JSON_CONTENT_READY"; default: break; } return "UNKNOWN STATE"; }
36.718797
201
0.715497
local-projects
c117aaceae41803129778da51a659d80452bd47c
3,871
cpp
C++
cnes/src/otb/Noise.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
null
null
null
cnes/src/otb/Noise.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
null
null
null
cnes/src/otb/Noise.cpp
dardok/ossim-plugins
3406ffed9fcab88fe4175b845381611ac4122c81
[ "MIT" ]
1
2019-11-02T11:01:58.000Z
2019-11-02T11:01:58.000Z
//---------------------------------------------------------------------------- // // "Copyright Centre National d'Etudes Spatiales" // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id$ #include <otb/Noise.h> #include <ossim/base/ossimDpt3d.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimNotify.h> #include <ossim/base/ossimString.h> namespace ossimplugins { static const char NOISE[] = "noise"; static const char NUMBER_OF_NOISE_RECORDS_KW[] = "numberOfNoiseRecords"; static const char NAME_OF_NOISE_POLARISATION_KW[] = "nameOfNoisePolarisation"; Noise::Noise(): _numberOfNoiseRecords(0), _tabImageNoise(), _polarisation("UNDEFINED") { } Noise::~Noise() { } Noise::Noise(const Noise& rhs): _numberOfNoiseRecords(rhs._numberOfNoiseRecords), _tabImageNoise(rhs._tabImageNoise), _polarisation(rhs._polarisation) { } Noise& Noise::operator=(const Noise& rhs) { _numberOfNoiseRecords = rhs._numberOfNoiseRecords; _tabImageNoise = rhs._tabImageNoise; _polarisation = rhs._polarisation; return *this; } bool Noise::saveState(ossimKeywordlist& kwl, const char* prefix) const { std::string pfx; if (prefix) { pfx = prefix; } pfx += NOISE; std::string s = pfx + "." + NAME_OF_NOISE_POLARISATION_KW; kwl.add(prefix, s.c_str(), _polarisation); s = pfx + "." + NUMBER_OF_NOISE_RECORDS_KW; kwl.add(prefix, s.c_str(), _numberOfNoiseRecords); for (unsigned int i = 0; i < _tabImageNoise.size(); ++i) { ossimString s2 = pfx + "[" + ossimString::toString(i).c_str() + "]"; _tabImageNoise[i].saveState(kwl, s2.c_str()); } return true; } bool Noise::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char MODULE[] = "Noise::loadState"; bool result = true; std::string pfx(""); if (prefix) { pfx = prefix; } pfx += NOISE; ossimString s; const char* lookup = 0; std::string s1 = pfx + "."; lookup = kwl.find(s1.c_str(), NAME_OF_NOISE_POLARISATION_KW); if (lookup) { _polarisation = lookup; } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Keyword not found: " << NAME_OF_NOISE_POLARISATION_KW << "\n"; result = false; } lookup = kwl.find(s1.c_str(), NUMBER_OF_NOISE_RECORDS_KW); if (lookup) { s = lookup; _numberOfNoiseRecords = s.toUInt32(); } else { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Keyword not found: " << NUMBER_OF_NOISE_RECORDS_KW << "\n"; result = false; } _tabImageNoise.clear(); for (unsigned int i = 0; i < _numberOfNoiseRecords; ++i) { std::string s2 = pfx + "[" + ossimString::toString(i).c_str() + "]"; ImageNoise in; result = in.loadState(kwl, s2.c_str()); _tabImageNoise.push_back(in); } if( _numberOfNoiseRecords != _tabImageNoise.size() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " Keyword " << NUMBER_OF_NOISE_RECORDS_KW << " is different with the number of ImageNoise nodes \n"; } return result; } std::ostream& Noise::print(std::ostream& out) const { out << setprecision(15) << setiosflags(ios::fixed) << "\n Noise class data members:\n"; const char* prefix = 0; ossimKeywordlist kwl; ossimString pfx; pfx += NOISE; ossimString s = pfx + "." + NUMBER_OF_NOISE_RECORDS_KW; kwl.add(prefix, s.c_str(), _numberOfNoiseRecords); s = pfx + "." + NAME_OF_NOISE_POLARISATION_KW; kwl.add(prefix, s.chars(), _polarisation); for (unsigned int i = 0; i < _tabImageNoise.size(); ++i) { ossimString s2 = pfx + "[" + ossimString::toString(i).c_str() + "]"; _tabImageNoise[i].saveState(kwl, s2.c_str()); } out << kwl; return out; } }
24.043478
122
0.624128
dardok
c118842241e729df29e6c222660b25c9edbaa944
47,148
cpp
C++
DashIO.cpp
dashio-connect/arduino-dashio
93278a02463a40dad31a76b2dc5eb35a4d7547ed
[ "MIT" ]
null
null
null
DashIO.cpp
dashio-connect/arduino-dashio
93278a02463a40dad31a76b2dc5eb35a4d7547ed
[ "MIT" ]
null
null
null
DashIO.cpp
dashio-connect/arduino-dashio
93278a02463a40dad31a76b2dc5eb35a4d7547ed
[ "MIT" ]
null
null
null
/* DashIO.cpp - Library for the DashIO comms protocol. Created by C. Tuffnell November 17, 2020 MIT License Copyright (c) 2020 Craig Tuffnell, DashIO Connect Limited 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 "DashIO.h" #include "DashJSON.h" // Control type IDs #define CONNECT_ID "CONNECT" #define WHO_ID "WHO" #define STATUS_ID "STATUS" #define CONFIG_ID "CFG" #define DEVICE_ID "DVCE" #define DEVICE_VIEW_ID "DVVW" #define LABEL_ID "LBL" #define BUTTON_ID "BTTN" #define MENU_ID "MENU" #define BUTTON_GROUP_ID "BTGP" #define EVENT_LOG_ID "LOG" #define SLIDER_ID "SLDR" #define BAR_ID "BAR" #define KNOB_ID "KNOB" #define KNOB_DIAL_ID "KBDL" #define TEXT_BOX_ID "TEXT" #define SELECTOR_ID "SLCTR" #define GRAPH_ID "GRPH" #define TIME_GRAPH_ID "TGRPH" #define DIRECTION_ID "DIR" #define DIAL_ID "DIAL" #define MAP_ID "MAP" #define BASIC_CONFIG_ID "BAS" #define DEVICE_NAME_ID "NAME" #define WIFI_SETUP_ID "WIFI" #define TCP_SETUP_ID "TCP" #define DASHIO_SETUP_ID "DASHIO" #define MQTT_SETUP_ID "MQTT" // Connection type IDs #define MQTT_CONNECTION_ID "MQTT" #define BLE_CONNECTION_ID "BLE" #define TCP_CONNECTION_ID "TCP" // Alarm #define ALARM_ID "ALM" // Button control states #define BUTTON_ON "ON" #define BUTTON_OFF "OFF" // Graph control line types #define LINE_ID "LINE" #define BAR_GRAPH_ID "BAR" #define SEGMENTED_BAR_ID "SEGBAR" #define PEAK_BAR_ID "PEAKBAR" // MQTT topic tips #define DATA_TOPIC_TIP "data" #define CONTROL_TOPIC_TIP "control" #define ALARM_TOPIC_TIP "alarm" #define ANNOUNCE_TOPIC_TIP "announce" #define WILL_TOPIC_TIP "data" // MQTT basic messages #define MQTT_ONLINE_MSSG "\tONLINE\n" #define MQTT_OFFLINE_MSSG "\tOFFLINE\n" #define MAX_STRING_LEN 64 #define MAX_DEVICE_NAME_LEN 32 #define MAX_DEVICE_TYPE_LEN 32 const char END_DELIM = '\n'; const char DELIM = '\t'; String formatFloat(float value) { if (value == INVALID_FLOAT_VALUE) { return "nan"; } else if (abs(value) < SMALLEST_FLOAT_VALUE) { return "0"; } char buffer[16]; #ifdef ARDUINO_ARCH_AVR dtostrf(value, 5, 2, buffer); return buffer; #else if ((abs(value) < 1.0) || (abs(value) >= 100000)){ sprintf(buffer, "%5.2e", value); } else { sprintf(buffer, "%5.2f", value); } return buffer; #endif } String formatInt(int value) { if (value == INVALID_INT_VALUE) { return "nan"; } else { return String(value); } } MessageData::MessageData(ConnectionType connType) { deviceID.reserve(MAX_STRING_LEN); idStr.reserve(MAX_STRING_LEN); payloadStr.reserve(MAX_STRING_LEN); connectionType = connType; }; void MessageData::processMessage(const String& message) { if (message.length() > 0) { if (messageReceived) { Serial.println(F("Incoming message overflow. Can't process:")); Serial.println(message); } else { for (unsigned int i = 0; i < message.length(); i++) { char chr = message[i]; if (processChar(chr)) { messageReceived = true; } } } } } bool MessageData::processChar(char chr) { bool messageEnd = false; if ((chr == DELIM) || (chr == END_DELIM)) { if ((readStr.length() > 0) || (segmentCount == 1)) { // segmentCount == 1 allows for empty second field ??? maybe should be 2 for empty third field now that we've added deviceID at the front switch (segmentCount) { case 0: if (readStr == WHO_ID) { deviceID = "---"; control = who; } else { deviceID = readStr; control = unknown; } idStr = ""; payloadStr = ""; payloadStr2 = ""; /* payloadStr3 = ""; payloadStr4 = ""; */ break; case 1: if (readStr == WHO_ID) { control = who; } else if (readStr == CONNECT_ID) { control = connect; } else if (readStr == STATUS_ID) { control = status; } else if (readStr == CONFIG_ID) { control = config; } else if (readStr == BUTTON_ID) { control = button; } else if (readStr == SLIDER_ID) { control = slider; } else if (readStr == KNOB_ID) { control = knob; } else if (readStr == TEXT_BOX_ID) { control = textBox; } else if (readStr == TIME_GRAPH_ID) { control = timeGraph; } else if (readStr == MENU_ID) { control = menu; } else if (readStr == BUTTON_GROUP_ID) { control = buttonGroup; } else if (readStr == EVENT_LOG_ID) { control = eventLog; } else if (readStr == SELECTOR_ID) { control = selector; } else if (readStr == DEVICE_NAME_ID) { control = deviceName; } else if (readStr == WIFI_SETUP_ID) { control = wifiSetup; } else if (readStr == TCP_SETUP_ID) { control = tcpSetup; } else if (readStr == DASHIO_SETUP_ID) { control = dashioSetup; } else if (readStr == MQTT_SETUP_ID) { control = mqttSetup; } else { control = unknown; segmentCount == -1; } break; case 2: idStr = readStr; break; case 3: payloadStr = readStr; break; case 4: payloadStr2 = readStr; break; /* case 5: payloadStr3 = readStr; break; case 6: payloadStr4 = readStr; break; */ default: segmentCount = 0; } if (segmentCount >= 0) { segmentCount++; if (chr == END_DELIM) { // End of message, so process message messageEnd = true; segmentCount = -1; // Wait for next start of message } } } else { segmentCount = 0; // Must have no data before DELIM or a DELIM + DELIM, so must be start of message } readStr = ""; } else { readStr += chr; } return messageEnd; } String MessageData::getReceivedMessageForPrint(const String& controlStr) { String message((char *)0); message.reserve(100); message += F("**** "); switch (connectionType) { case BLE_CONN: message += "BLE"; break; case TCP_CONN: message += "TCP"; break; case MQTT_CONN: message += "MQTT"; break; } message += F(" Received ****\n"); message += String(DELIM); message += deviceID; message += String(DELIM); message += controlStr; message += String(DELIM); message += idStr; message += String(DELIM); message += payloadStr; message += String(DELIM); message += payloadStr2; /* message += String(DELIM); message += payloadStr3; message += String(DELIM); message += payloadStr4; */ message += String(END_DELIM); return message; } /* --------------- */ DashioDevice::DashioDevice(const String& _deviceType) { type.reserve(MAX_DEVICE_TYPE_LEN); type = _deviceType; name.reserve(MAX_DEVICE_NAME_LEN); } void DashioDevice::setup(const String& deviceIdentifier) { if (name == "") { name = F("DashIO Device"); } deviceID.reserve(MAX_STRING_LEN); deviceID = deviceIdentifier; } void DashioDevice::setup(const String& deviceIdentifier, const String& _deviceName) { name = _deviceName; deviceID.reserve(MAX_STRING_LEN); deviceID = deviceIdentifier; } void DashioDevice::setup(uint8_t m_address[6], const String& _deviceName) { name = _deviceName; DashioDevice::setup(m_address); } void DashioDevice::setup(uint8_t m_address[6]) { deviceID.reserve(MAX_STRING_LEN); char buffer[20]; String macStr((char *)0); macStr.reserve(20); sprintf(buffer, "%x", m_address[0]); if (m_address[0] < 16) { macStr += "0"; } macStr += buffer; sprintf(buffer, "%x", m_address[1]); if (m_address[1] < 16) { macStr += "0"; } macStr += buffer; sprintf(buffer, "%x", m_address[2]); if (m_address[2] < 16) { macStr += "0"; } macStr += buffer; sprintf(buffer, "%x", m_address[3]); if (m_address[3] < 16) { macStr += "0"; } macStr += buffer; sprintf(buffer, "%x", m_address[4]); if (m_address[4] < 16) { macStr += "0"; } macStr += buffer; sprintf(buffer, "%x", m_address[5]); if (m_address[5] < 16) { macStr += "0"; } macStr += buffer; deviceID = macStr.c_str(); } String DashioDevice::getOnlineMessage() { String message = String(DELIM); message += deviceID; message += MQTT_ONLINE_MSSG; return message; } String DashioDevice::getOfflineMessage() { String message = String(DELIM); message += deviceID; message += MQTT_OFFLINE_MSSG; return message; } String DashioDevice::getWhoMessage() { String message = String(DELIM); message += deviceID; message += String(DELIM); message += WHO_ID; message += String(DELIM); message += type; message += String(DELIM); message += name; message += String(END_DELIM); return message; } String DashioDevice::getConnectMessage() { String message = String(DELIM); message += deviceID; message += String(DELIM); message += CONNECT_ID; message += String(END_DELIM); return message; } String DashioDevice::getDeviceNameMessage() { String message = String(DELIM); message += deviceID; message += String(DELIM); message += DEVICE_NAME_ID; message += String(DELIM); message += name; message += String(END_DELIM); return message; } String DashioDevice::getWifiUpdateAckMessage() { String message = String(DELIM); message += deviceID; message += String(DELIM); message += WIFI_SETUP_ID; message += String(END_DELIM); return message; } String DashioDevice::getTCPUpdateAckMessage() { String message = String(DELIM); message += deviceID; message += String(DELIM); message += TCP_SETUP_ID; message += String(END_DELIM); return message; } String DashioDevice::getDashioUpdateAckMessage() { String message = String(DELIM); message += deviceID; message += String(DELIM); message += DASHIO_SETUP_ID; message += String(END_DELIM); return message; } String DashioDevice::getMQTTUpdateAckMessage() { String message = String(DELIM); message += deviceID; message += String(DELIM); message += MQTT_SETUP_ID; message += String(END_DELIM); return message; } String DashioDevice::getAlarmMessage(const String& controlID, const String& title, const String& description) { String message = String(DELIM); message += deviceID; message += String(DELIM); message += controlID; message += String(DELIM); message += title; message += String(DELIM); message += description; message += String(END_DELIM); return message; } String DashioDevice::getAlarmMessage(Notification alarm) { return getAlarmMessage(alarm.identifier, alarm.title, alarm.description); } String DashioDevice::getControlBaseMessage(const String& controlType, const String& controlID) { String message = String(DELIM); message += deviceID; message += String(DELIM); message += controlType; message += String(DELIM); message += controlID; message += String(DELIM); return message; } String DashioDevice::getButtonMessage(const String& controlID, bool on, const String& iconName, const String& text) { String message = getControlBaseMessage(BUTTON_ID, controlID); if (on) { message += BUTTON_ON; } else { message += BUTTON_OFF; } if (text != "") { message += String(DELIM); message += iconName; message += String(DELIM); message += text; } else { if (iconName != "") { message += String(DELIM); message += iconName; } } message += String(END_DELIM); return message; } String DashioDevice::getTextBoxMessage(const String& controlID, const String& text) { String message = getControlBaseMessage(TEXT_BOX_ID, controlID); message += text; message += String(END_DELIM); return message; } String DashioDevice::getSelectorMessage(const String& controlID, int index) { String message = getControlBaseMessage(SELECTOR_ID, controlID); message += String(index); message += String(END_DELIM); return message; } String DashioDevice::getSelectorMessage(const String& controlID, int index, String* selectionItems, int rows) { String message = getControlBaseMessage(SELECTOR_ID, controlID); message += String(index); for (int i = 0; i < rows; i++) { message += String(DELIM); message += selectionItems[i]; } message += String(END_DELIM); return message; } String DashioDevice::getSliderMessage(const String& controlID, int value) { String message = getControlBaseMessage(SLIDER_ID, controlID); message += formatInt(value); message += String(END_DELIM); return message; } String DashioDevice::getSliderMessage(const String& controlID, float value) { String message = getControlBaseMessage(SLIDER_ID, controlID); message += formatFloat(value); message += String(END_DELIM); return message; } String DashioDevice::getSingleBarMessage(const String& controlID, int value) { String message = getControlBaseMessage(BAR_ID, controlID); message += formatInt(value); message += String(END_DELIM); return message; } String DashioDevice::getSingleBarMessage(const String& controlID, float value) { String message = getControlBaseMessage(BAR_ID, controlID); message += formatFloat(value); message += String(END_DELIM); return message; } String DashioDevice::getDoubleBarMessage(const String& controlID, int value1, int value2) { int barValues[2]; barValues[0] = value1; barValues[1] = value2; return getIntArray(BAR_ID, controlID, barValues, 2); } String DashioDevice::getDoubleBarMessage(const String& controlID, float value1, float value2) { float barValues[2]; barValues[0] = value1; barValues[1] = value2; return getFloatArray(BAR_ID, controlID, barValues, 2); } String DashioDevice::getKnobMessage(const String& controlID, int value) { String message = getControlBaseMessage(KNOB_ID, controlID); message += formatInt(value); message += String(END_DELIM); return message; } String DashioDevice::getKnobMessage(const String& controlID, float value) { String message = getControlBaseMessage(KNOB_ID, controlID); message += formatFloat(value); message += String(END_DELIM); return message; } String DashioDevice::getKnobDialMessage(const String& controlID, int value) { String message = getControlBaseMessage(KNOB_DIAL_ID, controlID); message += formatInt(value); message += String(END_DELIM); return message; } String DashioDevice::getKnobDialMessage(const String& controlID, float value) { String message = getControlBaseMessage(KNOB_DIAL_ID, controlID); message += formatFloat(value); message += String(END_DELIM); return message; } String DashioDevice::getDialMessage(const String& controlID, int value) { String message = getControlBaseMessage(DIAL_ID, controlID); message += formatInt(value); message += String(END_DELIM); return message; } String DashioDevice::getDialMessage(const String& controlID, float value) { String message = getControlBaseMessage(DIAL_ID, controlID); message += formatFloat(value); message += String(END_DELIM); return message; } String DashioDevice::getDirectionMessage(const String& controlID, int value, float speed) { String message = getControlBaseMessage(DIRECTION_ID, controlID); message += formatInt(value); if (speed >= 0) { message += String(DELIM); message += formatFloat(speed); } message += String(END_DELIM); return message; } String DashioDevice::getDirectionMessage(const String& controlID, float value, float speed) { String message = getControlBaseMessage(DIRECTION_ID, controlID); message += formatFloat(value); if (speed >= 0) { message += String(DELIM); message += formatFloat(speed); } message += String(END_DELIM); return message; } String DashioDevice::getMapMessage(const String& controlID, const String& latitude, const String& longitude, const String& mapMessage) { String message = getControlBaseMessage(MAP_ID, controlID); message += latitude; message += String(DELIM); message += longitude; message += String(DELIM); message += message; message += String(END_DELIM); return message; } String DashioDevice::getEventLogMessage(const String& controlID, const String& timeStr, const String& color, String text[], int dataLength) { String message = getControlBaseMessage(EVENT_LOG_ID, controlID); message += timeStr; message += String(DELIM); message += color; for (int i = 0; i < dataLength; i++) { message += String(DELIM); message += text[i]; } message += String(END_DELIM); return message; } String DashioDevice::getBasicConfigData(ControlType controlType, const String& controlID, const String& controlTitle) { String message = String(DELIM); message += getControlTypeStr(controlType); message += String(DELIM); message += controlID; message += String(DELIM); message += controlTitle; return message; } String DashioDevice::getBasicConfigMessage(ControlType controlType, const String& controlID, const String& controlTitle) { String message = String(DELIM); message += deviceID; message += String(DELIM); message += CONFIG_ID; message += String(DELIM); message += BASIC_CONFIG_ID; message += getBasicConfigData(controlType, controlID, controlTitle); message += String(END_DELIM); return message; } String DashioDevice::getBasicConfigMessage(const String& configData) { String message = String(DELIM); message += deviceID; message += String(DELIM); message += CONFIG_ID; message += String(DELIM); message += BASIC_CONFIG_ID; message += configData; message += String(END_DELIM); return message; } String DashioDevice::getFullConfigMessage(ControlType controlType, const String& configData) { String message = String(DELIM); message += deviceID; message += String(DELIM); message += CONFIG_ID; message += String(DELIM); message += getControlTypeStr(controlType); message += String(DELIM); message += configData; message += String(END_DELIM); return message; } String DashioDevice::getGraphLineInts(const String& controlID, const String& graphLineID, const String& lineName, LineType lineType, const String& color, int lineData[], int dataLength) { String message = getControlBaseMessage(GRAPH_ID, controlID); message += graphLineID; message += String(DELIM); message += lineName; message += String(DELIM); message += getLineTypeStr(lineType); message += String(DELIM); message += color; for (int i = 0; i < dataLength; i++) { message += String(DELIM); message += formatInt(lineData[i]); } message += String(END_DELIM); return message; } String DashioDevice::getGraphLineFloats(const String& controlID, const String& graphLineID, const String& lineName, LineType lineType, const String& color, float lineData[], int dataLength) { String message = getControlBaseMessage(GRAPH_ID, controlID); message += graphLineID; message += String(DELIM); message += lineName; message += String(DELIM); message += getLineTypeStr(lineType); message += String(DELIM); message += color; for (int i = 0; i < dataLength; i++) { message += String(DELIM); message += formatFloat(lineData[i]); } message += String(END_DELIM); return message; } String DashioDevice::getTimeGraphLineFloats(const String& controlID, const String& graphLineID, const String& lineName, LineType lineType, const String& color, String times[], float lineData[], int dataLength, bool breakLine) { String message = getControlBaseMessage(TIME_GRAPH_ID, controlID); message += graphLineID; message += String(DELIM); message += lineName; message += String(DELIM); message += getLineTypeStr(lineType); message += String(DELIM); message += color; if (breakLine && (dataLength > 0)) { message += String(DELIM); message += times[0]; message += ","; message += "B"; } for (int i = 0; i < dataLength; i++) { message += String(DELIM); message += times[i]; message += ","; message += formatFloat(lineData[i]); } message += String(END_DELIM); return message; } String DashioDevice::getTimeGraphLineBools(const String& controlID, const String& graphLineID, const String& lineName, LineType lineType, const String& color, String times[], bool lineData[], int dataLength) { String message = getControlBaseMessage(TIME_GRAPH_ID, controlID); message += graphLineID; message += String(DELIM); message += lineName; message += String(DELIM); message += getLineTypeStr(lineType); message += String(DELIM); message += color; for (int i = 0; i < dataLength; i++) { message += String(DELIM); message += times[i]; message += ","; if (lineData[i]) { message += "T"; } else { message += "F"; } } message += String(END_DELIM); return message; } String DashioDevice::getControlTypeStr(ControlType controltype) { switch (controltype) { case connect: return CONNECT_ID; case who: return WHO_ID; case status: return STATUS_ID; case config: return CONFIG_ID; case device: return DEVICE_ID; case deviceView: return DEVICE_VIEW_ID; case label: return LABEL_ID; case button: return BUTTON_ID; case menu: return MENU_ID; case buttonGroup: return BUTTON_GROUP_ID; case eventLog: return EVENT_LOG_ID; case slider: return SLIDER_ID; case knob: return KNOB_ID; case dial: return DIAL_ID; case direction: return DIRECTION_ID; case textBox: return TEXT_BOX_ID; case selector: return SELECTOR_ID; case graph: return GRAPH_ID; case timeGraph: return TIME_GRAPH_ID; case mapper: return MAP_ID; case deviceName: return DEVICE_NAME_ID; case wifiSetup: return WIFI_SETUP_ID; case tcpSetup: return TCP_SETUP_ID; case dashioSetup: return DASHIO_SETUP_ID; case mqttSetup: return MQTT_SETUP_ID; case mqttConn: return MQTT_CONNECTION_ID; case bleConn: return BLE_CONNECTION_ID; case tcpConn: return TCP_CONNECTION_ID; case alarmNotify: return ALARM_ID; case pushToken: return ""; case unknown: return ""; } return ""; } String DashioDevice::getMQTTSubscribeTopic(const String& userName) { mqttSubscrberTopic = getMQTTTopic(userName, control_topic); return mqttSubscrberTopic; } String DashioDevice::getMQTTTopic(const String& userName, MQTTTopicType topic) { String tip; switch (topic) { case data_topic: tip = DATA_TOPIC_TIP; break; case control_topic: tip = CONTROL_TOPIC_TIP; break; case alarm_topic: tip = ALARM_TOPIC_TIP; break; case announce_topic: tip = ANNOUNCE_TOPIC_TIP; break; case will_topic: tip = WILL_TOPIC_TIP; break; } return userName + "/" + deviceID + "/" + tip; } String DashioDevice::getLineTypeStr(LineType lineType) { switch (lineType) { case line: return LINE_ID; case bar: return BAR_GRAPH_ID; case segBar: return SEGMENTED_BAR_ID; case peakBar: return PEAK_BAR_ID; default: return LINE_ID; } } String DashioDevice::getIntArray(const String& controlType, const String& ID, int idata[], int dataLength) { String writeStr = String(DELIM); writeStr += deviceID; writeStr + String(DELIM); writeStr + controlType; writeStr + String(DELIM); writeStr + ID; for (int i = 0; i < dataLength; i++) { writeStr += String(DELIM); writeStr += formatInt(idata[i]); } writeStr += String(END_DELIM); return writeStr; } String DashioDevice::getFloatArray(const String& controlType, const String& ID, float fdata[], int dataLength) { String writeStr = String(DELIM); writeStr + deviceID; writeStr + String(DELIM); writeStr + controlType; writeStr + String(DELIM); writeStr + ID; for (int i = 0; i < dataLength; i++) { writeStr += String(DELIM); writeStr += formatFloat(fdata[i]); } writeStr += String(END_DELIM); return writeStr; } // Configuration String DashioDevice::getConfigMessage(DeviceCfg deviceConfigData) { DashJSON json; json.start(); json.addKeyInt(F("numDeviceViews"), deviceConfigData.numDeviceViews); json.addKeyString(F("deviceSetup"), deviceConfigData.deviceSetup, true); return getFullConfigMessage(device, json.jsonStr); } String DashioDevice::getConfigMessage(DeviceViewCfg deviceViewData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), deviceViewData.controlID); json.addKeyString(F("title"), deviceViewData.title); json.addKeyString(F("iconName"), deviceViewData.iconName); json.addKeyString(F("color"), deviceViewData.color); json.addKeyBool(F("shareColumn"), deviceViewData.shareColumn); json.addKeyInt(F("numColumns"), deviceViewData.numColumns); // Control Default Values json.addKeyInt(F("ctrlMaxFontSize"), deviceViewData.ctrlMaxFontSize); json.addKeyBool(F("ctrlBorderOn"), deviceViewData.ctrlBorderOn); json.addKeyString(F("ctrlBorderColor"), deviceViewData.ctrlBorderColor); json.addKeyString(F("ctrlColor"), deviceViewData.ctrlColor); json.addKeyString(F("ctrlBkgndColor"), deviceViewData.ctrlBkgndColor); json.addKeyInt(F("ctrlBkgndTransparency"), deviceViewData.ctrlBkgndTransparency); // Control Title Box Default Values json.addKeyInt(F("ctrlTitleFontSize"), deviceViewData.ctrlTitleFontSize); json.addKeyString(F("ctrlTitleBoxColor"), deviceViewData.ctrlTitleBoxColor); json.addKeyInt(F("ctrlTitleBoxTransparency"), deviceViewData.ctrlTitleBoxTransparency, true); return getFullConfigMessage(deviceView, json.jsonStr); } String DashioDevice::getConfigMessage(BLEConnCfg connectionData) { DashJSON json; json.start(); json.addKeyString(F("serviceUUID"), connectionData.serviceUUID); json.addKeyString(F("readUUID"), connectionData.readUUID); json.addKeyString(F("writeUUID"), connectionData.writeUUID, true); return getFullConfigMessage(bleConn, json.jsonStr); } String DashioDevice::getConfigMessage(TCPConnCfg connectionData) { DashJSON json; json.start(); json.addKeyString(F("ipAddress"), connectionData.ipAddress); json.addKeyInt(F("port"), connectionData.port, true); return getFullConfigMessage(tcpConn, json.jsonStr); } String DashioDevice::getConfigMessage(MQTTConnCfg connectionData) { DashJSON json; json.start(); json.addKeyString(F("userName"), connectionData.userName); json.addKeyString(F("hostURL"), connectionData.hostURL, true); return getFullConfigMessage(mqttConn, json.jsonStr); } String DashioDevice::getConfigMessage(AlarmCfg alarmData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), alarmData.controlID); json.addKeyString(F("description"), alarmData.description); json.addKeyString(F("soundName"), alarmData.soundName, true); return getFullConfigMessage(alarmNotify, json.jsonStr); } String DashioDevice::getConfigMessage(LabelCfg labelData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), labelData.controlID); json.addKeyString(F("parentID"), labelData.parentID); json.addKeyFloat(F("xPositionRatio"), labelData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), labelData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), labelData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), labelData.graphicsRect.heightRatio); json.addKeyString(F("title"), labelData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(labelData.titlePosition)); json.addKeyString(F("style"), getLabelStyle(labelData.style)); json.addKeyString(F("color"), labelData.color, true); return getFullConfigMessage(label, json.jsonStr); } String DashioDevice::getConfigMessage(ButtonCfg buttonData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), buttonData.controlID); json.addKeyString(F("parentID"), buttonData.parentID); json.addKeyFloat(F("xPositionRatio"), buttonData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), buttonData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), buttonData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), buttonData.graphicsRect.heightRatio); json.addKeyString(F("title"), buttonData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(buttonData.titlePosition)); json.addKeyBool(F("buttonEnabled"), buttonData.buttonEnabled); json.addKeyString(F("iconName"), buttonData.iconName); json.addKeyString(F("text"), buttonData.text); json.addKeyString(F("offColor"), buttonData.offColor); json.addKeyString(F("onColor"), buttonData.onColor, true); return getFullConfigMessage(button, json.jsonStr); } String DashioDevice::getConfigMessage(MenuCfg menuData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), menuData.controlID); json.addKeyString(F("parentID"), menuData.parentID); json.addKeyFloat(F("xPositionRatio"), menuData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), menuData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), menuData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), menuData.graphicsRect.heightRatio); json.addKeyString(F("title"), menuData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(menuData.titlePosition)); json.addKeyString(F("iconName"), menuData.iconName); json.addKeyString(F("text"), menuData.text, true); return getFullConfigMessage(menu, json.jsonStr); } String DashioDevice::getConfigMessage(ButtonGroupCfg groupData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), groupData.controlID); json.addKeyString(F("parentID"), groupData.parentID); json.addKeyFloat(F("xPositionRatio"), groupData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), groupData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), groupData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), groupData.graphicsRect.heightRatio); json.addKeyString(F("title"), groupData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(groupData.titlePosition)); json.addKeyString(F("iconName"), groupData.iconName); json.addKeyString(F("text"), groupData.text); json.addKeyBool(F("gridView"), groupData.gridView, true); return getFullConfigMessage(buttonGroup, json.jsonStr); } String DashioDevice::getConfigMessage(EventLogCfg eventLogData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), eventLogData.controlID); json.addKeyString(F("parentID"), eventLogData.parentID); json.addKeyFloat(F("xPositionRatio"), eventLogData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), eventLogData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), eventLogData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), eventLogData.graphicsRect.heightRatio); json.addKeyString(F("title"), eventLogData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(eventLogData.titlePosition), true); return getFullConfigMessage(eventLog, json.jsonStr); } String DashioDevice::getConfigMessage(KnobCfg knobData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), knobData.controlID); json.addKeyString(F("parentID"), knobData.parentID); json.addKeyFloat(F("xPositionRatio"), knobData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), knobData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), knobData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), knobData.graphicsRect.heightRatio); json.addKeyString(F("title"), knobData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(knobData.titlePosition)); json.addKeyFloat(F("min"), knobData.min); json.addKeyFloat(F("max"), knobData.max); json.addKeyFloat(F("redValue"), knobData.redValue); json.addKeyBool(F("showMinMax"), knobData.showMinMax); json.addKeyString(F("style"), getKnobPresentationStyle(knobData.style)); json.addKeyString(F("knobColor"), knobData.knobColor); json.addKeyBool(F("sendOnlyOnRelease"), knobData.sendOnlyOnRelease); json.addKeyBool(F("dialFollowsKnob"), knobData.dialFollowsKnob); json.addKeyString(F("dialColor"), knobData.dialColor, true); return getFullConfigMessage(knob, json.jsonStr); } String DashioDevice::getConfigMessage(DialCfg dialData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), dialData.controlID); json.addKeyString(F("parentID"), dialData.parentID); json.addKeyFloat(F("xPositionRatio"), dialData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), dialData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), dialData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), dialData.graphicsRect.heightRatio); json.addKeyString(F("title"), dialData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(dialData.titlePosition)); json.addKeyFloat(F("min"), dialData.min); json.addKeyFloat(F("max"), dialData.max); json.addKeyFloat(F("redValue"), dialData.redValue); json.addKeyString(F("dialFillColor"), dialData.dialFillColor); json.addKeyString(F("pointerColor"), dialData.pointerColor); json.addKeyString(F("numberPosition"), getDialNumberPosition(dialData.numberPosition)); json.addKeyBool(F("showMinMax"), dialData.showMinMax); json.addKeyString(F("style"), getDialPresentationStyle(dialData.style)); json.addKeyString(F("units"), dialData.units); json.addKeyInt(F("precision"), dialData.precision, true); return getFullConfigMessage(dial, json.jsonStr); } String DashioDevice::getConfigMessage(DirectionCfg directionData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), directionData.controlID); json.addKeyString(F("parentID"), directionData.parentID); json.addKeyFloat(F("xPositionRatio"), directionData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), directionData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), directionData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), directionData.graphicsRect.heightRatio); json.addKeyString(F("title"), directionData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(directionData.titlePosition)); json.addKeyString(F("pointerColor"), directionData.pointerColor); json.addKeyString(F("style"), getDirectionPresentationStyle(directionData.style)); json.addKeyInt(F("calAngle"), directionData.calAngle); json.addKeyString(F("units"), directionData.units); json.addKeyInt(F("precision"), directionData.precision, true); return getFullConfigMessage(direction, json.jsonStr); } String DashioDevice::getConfigMessage(TextBoxCfg textBoxData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), textBoxData.controlID); json.addKeyString(F("parentID"), textBoxData.parentID); json.addKeyFloat(F("xPositionRatio"), textBoxData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), textBoxData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), textBoxData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), textBoxData.graphicsRect.heightRatio); json.addKeyString(F("title"), textBoxData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(textBoxData.titlePosition)); json.addKeyString(F("format"), getTextFormatStr(textBoxData.format)); json.addKeyString(F("textAlign"), getTextAlignStr(textBoxData.textAlign)); json.addKeyString(F("units"), textBoxData.units); json.addKeyInt(F("precision"), textBoxData.precision); json.addKeyString(F("kbdType"), getKeyboardTypeStr(textBoxData.kbdType)); json.addKeyBool(F("closeKbdOnSend"), textBoxData.closeKbdOnSend, true); return getFullConfigMessage(textBox, json.jsonStr); } String DashioDevice::getConfigMessage(SelectorCfg selectorData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), selectorData.controlID); json.addKeyString(F("parentID"), selectorData.parentID); json.addKeyFloat(F("xPositionRatio"), selectorData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), selectorData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), selectorData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), selectorData.graphicsRect.heightRatio); json.addKeyString(F("title"), selectorData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(selectorData.titlePosition), true); return getFullConfigMessage(selector, json.jsonStr); } String DashioDevice::getConfigMessage(SliderCfg sliderData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), sliderData.controlID); json.addKeyString(F("parentID"), sliderData.parentID); json.addKeyFloat(F("xPositionRatio"), sliderData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), sliderData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), sliderData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), sliderData.graphicsRect.heightRatio); json.addKeyString(F("title"), sliderData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(sliderData.titlePosition)); json.addKeyFloat(F("min"), sliderData.min); json.addKeyFloat(F("max"), sliderData.max); json.addKeyFloat(F("redValue"), sliderData.redValue); json.addKeyBool(F("showMinMax"), sliderData.showMinMax); json.addKeyBool(F("sliderEnabled"), sliderData.sliderEnabled); json.addKeyString(F("knobColor"), sliderData.knobColor); json.addKeyBool(F("sendOnlyOnRelease"), sliderData.sendOnlyOnRelease); json.addKeyBool(F("barFollowsSlider"), sliderData.barFollowsSlider); json.addKeyString(F("barColor"), sliderData.barColor); json.addKeyString(F("barStyle"), getBarStyleStr(sliderData.barStyle), true); return getFullConfigMessage(slider, json.jsonStr); } String DashioDevice::getConfigMessage(GraphCfg graphData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), graphData.controlID); json.addKeyString(F("parentID"), graphData.parentID); json.addKeyFloat(F("xPositionRatio"), graphData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), graphData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), graphData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), graphData.graphicsRect.heightRatio); json.addKeyString(F("title"), graphData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(graphData.titlePosition)); json.addKeyString(F("xAxisLabel"), graphData.xAxisLabel); json.addKeyFloat(F("xAxisMin"), graphData.xAxisMin); json.addKeyFloat(F("xAxisMax"), graphData.xAxisMax); json.addKeyInt(F("xAxisNumBars"), graphData.xAxisNumBars); json.addKeyString(F("xAxisLabelsStyle"), getXAxisLabelsStyleStr(graphData.xAxisLabelsStyle)); json.addKeyString(F("yAxisLabel"), graphData.yAxisLabel); json.addKeyFloat(F("yAxisMin"), graphData.yAxisMin); json.addKeyFloat(F("yAxisMax"), graphData.yAxisMax); json.addKeyInt(F("yAxisNumBars"), graphData.yAxisNumBars, true); return getFullConfigMessage(graph, json.jsonStr); } String DashioDevice::getConfigMessage(TimeGraphCfg timeGraphData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), timeGraphData.controlID); json.addKeyString(F("parentID"), timeGraphData.parentID); json.addKeyFloat(F("xPositionRatio"), timeGraphData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), timeGraphData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), timeGraphData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), timeGraphData.graphicsRect.heightRatio); json.addKeyString(F("title"), timeGraphData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(timeGraphData.titlePosition)); json.addKeyString(F("yAxisLabel"), timeGraphData.yAxisLabel); json.addKeyFloat(F("yAxisMin"), timeGraphData.yAxisMin); json.addKeyFloat(F("yAxisMax"), timeGraphData.yAxisMax); json.addKeyInt(F("yAxisNumBars"), timeGraphData.yAxisNumBars, true); return getFullConfigMessage(timeGraph, json.jsonStr); } String DashioDevice::getConfigMessage(MapCfg mapData) { DashJSON json; json.start(); json.addKeyString(F("controlID"), mapData.controlID); json.addKeyString(F("parentID"), mapData.parentID); json.addKeyFloat(F("xPositionRatio"), mapData.graphicsRect.xPositionRatio); json.addKeyFloat(F("yPositionRatio"), mapData.graphicsRect.yPositionRatio); json.addKeyFloat(F("widthRatio"), mapData.graphicsRect.widthRatio); json.addKeyFloat(F("heightRatio"), mapData.graphicsRect.heightRatio); json.addKeyString(F("title"), mapData.title); json.addKeyString(F("titlePosition"), getTitlePositionStr(mapData.titlePosition), true); return getFullConfigMessage(mapper, json.jsonStr); } String DashioDevice::getTitlePositionStr(TitlePosition tbp) { switch (tbp) { case titleTop: return "TOP"; case titleBottom: return "BOTTOM"; default: return "NONE"; } } String DashioDevice::getLabelStyle(LabelStyle labelStyle) { switch (labelStyle) { case basic: return "BASIC"; case border: return "GROUP"; default: return "GROUP"; } } String DashioDevice::getDialNumberPosition(DialNumberPosition numberPosition) { switch (numberPosition) { case numberLeft: return "LEFT"; case numberRight: return "RIGHT"; case numberCenter: return "CENTER"; default: return "OFF"; } } String DashioDevice::getKnobPresentationStyle(KnobPresentationStyle presentationStyle) { switch (presentationStyle) { case knobPan: return "PAN"; default: return "NORMAL"; } } String DashioDevice::getDialPresentationStyle(DialPresentationStyle presentationStyle) { switch (presentationStyle) { case dialPie: return "PIE"; case dialPieInverted: return "PIEINV"; default: return "BAR"; } } String DashioDevice::getDirectionPresentationStyle(DirectionPresentationStyle presentationStyle) { switch (presentationStyle) { case dirDeg: return "DEG"; case dirDegPS: return "DEGPS"; default: return "NSEW"; } } String DashioDevice::getTextFormatStr(TextFormat format) { switch (format) { case numFmt: return "NUM"; case dateTimeFmt: return "DATETIME"; case dateTimeLongFmt: return "DTLONG"; case intvlFmt: return "INTVL"; default: return "NONE"; } } String DashioDevice::getKeyboardTypeStr(KeyboardType kbd) { switch (kbd) { case hexKbd: return "HEX"; case allKbd: return "ALL"; case numKbd: return "NUM"; case intKbd: return "INT"; case dateKbd: return "DATE"; case timeKbd: return "TIME"; case dateTimeKbd: return "DATETIME"; case intvlKbd: return "INTVL"; default: return "NONE"; } } String DashioDevice::getTextAlignStr(TextAlign align) { switch (align) { case textLeft: return "LEFT"; case textRight: return "RIGHT"; default: return "CENTER"; } } String DashioDevice::getBarStyleStr(BarStyle barStyle) { switch (barStyle) { case segmentedBar: return "SEG"; default: return "SOLID"; } } String DashioDevice::getXAxisLabelsStyleStr(XAxisLabelsStyle xls) { switch (xls) { case labelsOnLines: return "ON"; default: return "BETWEEN"; } }
34.464912
227
0.673984
dashio-connect
c11ca24604be54f64edee25194126d5354d859bd
12,253
cpp
C++
libs2eplugins/src/s2e/Plugins/ExecutionTracers/UserSpaceTracer.cpp
benquike/s2e
f88cb796261d13cc2302c6bf0bc43e5da245ea6a
[ "MIT" ]
2
2021-12-17T07:04:43.000Z
2022-01-28T23:45:45.000Z
libs2eplugins/src/s2e/Plugins/ExecutionTracers/UserSpaceTracer.cpp
benquike/s2e
f88cb796261d13cc2302c6bf0bc43e5da245ea6a
[ "MIT" ]
null
null
null
libs2eplugins/src/s2e/Plugins/ExecutionTracers/UserSpaceTracer.cpp
benquike/s2e
f88cb796261d13cc2302c6bf0bc43e5da245ea6a
[ "MIT" ]
null
null
null
/// /// Copyright (C) 2014-2015, Dependable Systems Laboratory, EPFL /// Copyright (C) 2014-2016, Cyberhaven /// /// 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 <s2e/ConfigFile.h> #include <s2e/S2E.h> #include <s2e/Utils.h> #include <s2e/cpu.h> #include <s2e/Plugins/ExecutionTracers/ExecutionTracer.h> #include <s2e/Plugins/ExecutionTracers/MemoryTracer.h> #include <s2e/Plugins/ExecutionTracers/TranslationBlockTracer.h> #include <s2e/Plugins/OSMonitors/Windows/WindowsMonitor.h> #include <TraceEntries.pb.h> #include "UserSpaceTracer.h" namespace std { template <typename T1, typename T2> struct hash<std::pair<T1, T2>> { std::size_t operator()(std::pair<T1, T2> const &p) const { return p.first ^ p.second; } }; } // namespace std namespace s2e { namespace plugins { // TODO: add support for Linux S2E_DEFINE_PLUGIN(UserSpaceTracer, "Trace execution of user-space Windows processes", "", "ExecutionTracer", "WindowsMonitor"); class UserSpaceTracerState : public PluginState { public: struct TraceInfo { // How many blocks are left to trace for the thread. uint64_t itemsCountLeft; }; using TraceInfoPtr = std::shared_ptr<TraceInfo>; using Pid = uint64_t; using PidTid = std::pair<uint64_t, uint64_t>; using PidTids = std::unordered_map<PidTid, TraceInfoPtr>; using Pids = llvm::DenseSet<Pid>; private: PidTid m_current; TraceInfoPtr m_currentInfo; Pids m_pids; PidTids m_tids; bool m_trace = false; void updateTracing() { bool trace = false; m_currentInfo = nullptr; trace |= m_pids.find(m_current.first) != m_pids.end(); auto it = m_tids.find(m_current); if (it != m_tids.end()) { m_currentInfo = (*it).second; if (m_currentInfo->itemsCountLeft > 0) { --m_currentInfo->itemsCountLeft; trace = true; } } m_trace = trace; } public: inline PidTid getPidTid() const { return m_current; } void setPidTid(uint64_t pid, uint64_t tid) { m_current = PidTid(pid, tid); updateTracing(); } void tracePid(uint64_t pid, bool trace) { if (trace) { m_pids.insert(pid); } else { m_pids.erase(pid); } updateTracing(); } void traceTid(uint64_t pid, uint64_t tid, bool trace, uint64_t maxTraceItems = -1) { auto p = PidTid(pid, tid); if (trace) { if (maxTraceItems > 0) { auto info = std::make_shared<TraceInfo>(); info->itemsCountLeft = maxTraceItems; m_tids[p] = info; } } else { m_tids.erase(p); } updateTracing(); } inline bool traced(bool decrement = false) { if (!m_trace) { return false; } if (decrement && m_currentInfo) { if (m_currentInfo->itemsCountLeft > 0) { --m_currentInfo->itemsCountLeft; return true; } else { traceTid(m_current.first, m_current.second, false); return false; } } return true; } inline bool hasTracedProcesses() const { return !m_tids.empty() || !m_pids.empty(); } void unloadProcess(uint64_t pid) { m_pids.erase(pid); PidTids toErase; for (auto pt : m_tids) { if (pt.first.first == pid) { toErase.insert(pt); } } for (auto pt : toErase) { m_tids.erase(pt.first); } updateTracing(); } void unloadThread(uint64_t pid, uint64_t tid) { m_tids.erase(PidTid(pid, tid)); updateTracing(); } static PluginState *factory(Plugin *p, S2EExecutionState *s) { return new UserSpaceTracerState(); } virtual ~UserSpaceTracerState() { // Destroy any object if needed } virtual UserSpaceTracerState *clone() const { return new UserSpaceTracerState(*this); } }; void UserSpaceTracer::initialize() { m_tracer = s2e()->getPlugin<ExecutionTracer>(); m_memoryTracer = s2e()->getPlugin<MemoryTracer>(); m_monitor = s2e()->getPlugin<WindowsMonitor>(); ConfigFile *cfg = s2e()->getConfig(); auto procs = cfg->getStringList(getConfigKey() + ".processNames"); m_processNames.insert(procs.begin(), procs.end()); if (m_processNames.empty()) { getWarningsStream() << "No process names specified. Tracing will not work unless other plugins enable it.\n"; } m_traceExecution = cfg->getBool(getConfigKey() + ".traceExecution", false); m_traceTranslation = cfg->getBool(getConfigKey() + ".traceTranslation", false); m_traceMemory = cfg->getBool(getConfigKey() + ".traceMemory", false); if (m_traceMemory && !m_memoryTracer) { getWarningsStream() << "Tracing memory requires enabling the MemoryTracer plugin\n"; exit(-1); } if (!m_traceExecution && !m_traceTranslation && !m_traceMemory) { getWarningsStream() << "All tracing options disabled\n"; } m_monitor->onMonitorLoad.connect(sigc::mem_fun(*this, &UserSpaceTracer::onMonitorLoad)); } void UserSpaceTracer::onMonitorLoad(S2EExecutionState *state) { m_monitor->onProcessOrThreadSwitch.connect(sigc::mem_fun(*this, &UserSpaceTracer::onProcessOrThreadSwitch)); m_monitor->onAccessFault.connect(sigc::mem_fun(*this, &UserSpaceTracer::onAccessFault)); m_monitor->onProcessLoad.connect(sigc::mem_fun(*this, &UserSpaceTracer::onProcessLoad)); m_monitor->onThreadExit.connect(sigc::mem_fun(*this, &UserSpaceTracer::onThreadExit)); s2e()->getCorePlugin()->onStateSwitch.connect(sigc::mem_fun(*this, &UserSpaceTracer::onStateSwitch)); } // To minimize overhead, insert instrumentation only when there is at least one process // that needs to be traced. void UserSpaceTracer::updateInstrumentation(S2EExecutionState *state) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); if (plgState->hasTracedProcesses()) { if (m_traceTranslation) { m_tbComplete = s2e()->getCorePlugin()->onTranslateBlockComplete.connect( sigc::mem_fun(*this, &UserSpaceTracer::onTranslateBlockComplete)); } if (m_traceExecution) { m_tbStart = s2e()->getCorePlugin()->onTranslateBlockStart.connect( sigc::mem_fun(*this, &UserSpaceTracer::onTranslateBlockStart)); // This ensures that next translation blocks will be instrumented se_tb_safe_flush(); } } else { m_tbComplete.disconnect(); m_tbStart.disconnect(); se_tb_safe_flush(); } } void UserSpaceTracer::onStateSwitch(S2EExecutionState *current, S2EExecutionState *next) { if (!next) { return; } updateInstrumentation(next); } void UserSpaceTracer::onProcessOrThreadSwitch(S2EExecutionState *state) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); auto pid = m_monitor->getCurrentProcessId(state); auto tid = m_monitor->getCurrentThreadId(state); plgState->setPidTid(pid, tid); } void UserSpaceTracer::onProcessLoad(S2EExecutionState *state, uint64_t pageDir, uint64_t pid, const std::string &imageName) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); if (m_processNames.find(imageName) != m_processNames.end()) { plgState->tracePid(pid, true); } } void UserSpaceTracer::onProcessUnload(S2EExecutionState *state, uint64_t pageDir, uint64_t pid, uint64_t returnCode) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); plgState->unloadProcess(pid); } void UserSpaceTracer::onThreadExit(S2EExecutionState *state, const ThreadDescriptor &thread) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); plgState->unloadThread(thread.Pid, thread.Tid); } // TODO: make this optional void UserSpaceTracer::onAccessFault(S2EExecutionState *state, const S2E_WINMON2_ACCESS_FAULT &AccessFault) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); // Disconnect as soon as the kernel catches an invalid memory access. // This avoids cluttering the execution trace, which would only contain // items up to the faulty instruction. if (plgState->traced()) { if ((uint32_t) AccessFault.StatusCode != 0xc0000005) { return; } getDebugStream(state) << "UserSpaceTracer: Caught MmAccessFault " << " Address: " << hexval(AccessFault.Address) << " AccessMode: " << hexval(AccessFault.AccessMode) << " StatusCode: " << hexval(AccessFault.StatusCode) << " PageDir: " << hexval(state->regs()->getPageDir()) << "\n"; auto p = plgState->getPidTid(); plgState->traceTid(p.first, p.second, false); } } void UserSpaceTracer::onTranslateBlockComplete(S2EExecutionState *state, TranslationBlock *tb, uint64_t endPc) { if ((tb->flags & HF_CPL_MASK) != 3) { return; } DECLARE_PLUGINSTATE(UserSpaceTracerState, state); if (plgState->traced()) { TranslationBlockTracer::trace(state, m_tracer, state->getTb(), s2e_trace::TRACE_BLOCK); } } void UserSpaceTracer::onTranslateBlockStart(ExecutionSignal *signal, S2EExecutionState *state, TranslationBlock *tb, uint64_t pc) { if ((tb->flags & HF_CPL_MASK) != 3) { return; } signal->connect(sigc::mem_fun(*this, &UserSpaceTracer::onExecuteBlockStart)); } void UserSpaceTracer::onExecuteBlockStart(S2EExecutionState *state, uint64_t pc) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); if (plgState->traced(true)) { TranslationBlockTracer::trace(state, m_tracer, state->getTb(), s2e_trace::TRACE_TB_START); } } void UserSpaceTracer::onPrivilegeChange(S2EExecutionState *state, unsigned previous, unsigned current) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); bool trace = current == 3 && plgState->traced(); if (m_traceMemory) { m_memoryTracer->enable(state, MemoryTracer::MEMORY, trace); } } void UserSpaceTracer::startTracing(S2EExecutionState *state, uint64_t pid) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); plgState->tracePid(pid, true); updateInstrumentation(state); } void UserSpaceTracer::startTracing(S2EExecutionState *state, uint64_t pid, uint64_t tid, uint64_t maxTraceItems) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); plgState->traceTid(pid, tid, true, maxTraceItems); updateInstrumentation(state); } void UserSpaceTracer::stopTracing(S2EExecutionState *state, uint64_t pid) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); plgState->tracePid(pid, false); updateInstrumentation(state); } void UserSpaceTracer::stopTracing(S2EExecutionState *state, uint64_t pid, uint64_t tid) { DECLARE_PLUGINSTATE(UserSpaceTracerState, state); plgState->traceTid(pid, tid, false); updateInstrumentation(state); } } // namespace plugins } // namespace s2e
34.226257
118
0.662613
benquike
c11fac388210772f07cb200ee217108a10da0720
615
cc
C++
kythe/cxx/indexer/cxx/testdata/tvar_template/template_ps_defn.cc
BearerPipelineTest/kythe
c496c5c00177e437e28bb3a75a5ef811d5d55ff7
[ "Apache-2.0" ]
1,168
2015-01-27T10:19:25.000Z
2018-10-30T15:07:11.000Z
kythe/cxx/indexer/cxx/testdata/tvar_template/template_ps_defn.cc
BearerPipelineTest/kythe
c496c5c00177e437e28bb3a75a5ef811d5d55ff7
[ "Apache-2.0" ]
2,811
2015-01-29T16:19:04.000Z
2018-11-01T19:48:06.000Z
kythe/cxx/indexer/cxx/testdata/tvar_template/template_ps_defn.cc
BearerPipelineTest/kythe
c496c5c00177e437e28bb3a75a5ef811d5d55ff7
[ "Apache-2.0" ]
165
2015-01-27T19:06:27.000Z
2018-10-30T17:31:10.000Z
// Checks that declarations and definitions of templates are distinguished. //- @C defines/binding FwdTemplate template <typename T> class C; //- @C defines/binding FwdSpec template <> class C <int>; //- @C defines/binding Template //- @C completes/uniquely FwdTemplate template <typename T> class C { }; //- @C defines/binding Spec //- @C completes/uniquely FwdSpec template <> class C <int> { }; //- FwdTemplate.node/kind record //- FwdSpec.node/kind record //- FwdSpec.complete incomplete //- Spec.node/kind record //- Spec.complete definition //- Spec specializes TAppCInt //- FwdSpec specializes TAppCInt
25.625
75
0.726829
BearerPipelineTest
c12061ea6d495f6cbb54a586ee13c5faac0dcc83
2,550
hpp
C++
source/xyo/xyo-managedmemory-tsingletonprocess.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
source/xyo/xyo-managedmemory-tsingletonprocess.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
source/xyo/xyo-managedmemory-tsingletonprocess.hpp
g-stefan/xyo
e203cb699d6bba46eae6c8157f27ea29ab7506f1
[ "MIT", "Unlicense" ]
null
null
null
// // XYO // // Copyright (c) 2020-2021 Grigore Stefan <g_stefan@yahoo.com> // Created by Grigore Stefan <g_stefan@yahoo.com> // // MIT License (MIT) <http://opensource.org/licenses/MIT> // #ifndef XYO_MANAGEDMEMORY_TSINGLETONPROCESS_HPP #define XYO_MANAGEDMEMORY_TSINGLETONPROCESS_HPP #ifndef XYO_MANAGEDMEMORY_TMEMORYSYSTEM_HPP #include "xyo-managedmemory-tmemorysystem.hpp" #endif #ifndef XYO_MANAGEDMEMORY_REGISTRYPROCESS_HPP #include "xyo-managedmemory-registryprocess.hpp" #endif #ifndef XYO_MULTITHREADING_TATOMIC_HPP #include "xyo-multithreading-tatomic.hpp" #endif namespace XYO { namespace ManagedMemory { using namespace XYO::Multithreading; template<typename T> class TSingletonProcess { XYO_DISALLOW_COPY_ASSIGN_MOVE(TSingletonProcess); protected: inline TSingletonProcess() { }; public: static TAtomic<T *> singletonLink; static const char *registryKey(); static void resourceDelete(void *); static void resourceFinalizer(void *); static inline T *getValue() { T *retV = singletonLink.get(); if(retV == nullptr) { initMemory(); return singletonLink.get(); }; return retV; }; static inline void initMemory() { void *registryLink; if(RegistryProcess::checkAndRegisterKey(registryKey(), registryLink, [] { return (singletonLink.get() == nullptr); }, [](void *this__) { T *this_ = reinterpret_cast<T *> (this__); singletonLink.set(this_); })) { TMemorySystem<T>::initMemory(); T *this_ = TMemorySystem<T>::newMemory(); TIfHasIncReferenceCount<T>::incReferenceCount(this_); singletonLink.set(this_); RegistryProcess::setValue( registryLink, RegistryLevel::Singleton, this_, resourceDelete, (THasActiveFinalizer<T>::value) ? resourceFinalizer : nullptr); }; }; }; template<typename T> const char *TSingletonProcess<T>::registryKey() { return typeid(TSingletonProcess<T>).name(); }; template<typename T> TAtomic<T *> TSingletonProcess<T>::singletonLink(nullptr); template<typename T> void TSingletonProcess<T>::resourceDelete(void *this_) { TMemorySystem<T>::deleteMemory(reinterpret_cast<T *>(this_)); }; template<typename T> void TSingletonProcess<T>::resourceFinalizer(void *this_) { TIfHasActiveFinalizer<T>::activeFinalizer(reinterpret_cast<T *>(this_)); }; }; }; #endif
24.056604
79
0.663137
g-stefan
c1233652cc2ab2625d61c8c01b8fe368ad956c66
1,152
cpp
C++
Plugins/org.blueberry.core.runtime/src/internal/berryRegistryContributor.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2022-03-03T12:03:32.000Z
2022-03-03T12:03:32.000Z
Plugins/org.blueberry.core.runtime/src/internal/berryRegistryContributor.cpp
zhaomengxiao/MITK
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2021-12-22T10:19:02.000Z
2021-12-22T10:19:02.000Z
Plugins/org.blueberry.core.runtime/src/internal/berryRegistryContributor.cpp
zhaomengxiao/MITK_lancet
a09fd849a4328276806008bfa92487f83a9e2437
[ "BSD-3-Clause" ]
1
2020-11-27T09:41:18.000Z
2020-11-27T09:41:18.000Z
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "berryRegistryContributor.h" namespace berry { RegistryContributor::RegistryContributor(const QString& actualId, const QString& actualName, const QString& hostId, const QString& hostName) : actualContributorId(actualId), actualContributorName(actualName) { if (!hostId.isEmpty()) { this->hostId = hostId; this->hostName = hostName; } else { this->hostId = actualId; this->hostName = actualName; } } QString RegistryContributor::GetActualId() const { return actualContributorId; } QString RegistryContributor::GetActualName() const { return actualContributorName; } QString RegistryContributor::GetId() const { return hostId; } QString RegistryContributor::GetName() const { return hostName; } }
21.333333
92
0.633681
zhaomengxiao
c12754fe654a4374f75083a3e645efd115126352
6,148
cc
C++
src/app.cc
PaoJiao/slide
fccdcac94e951de113b8f0116084c41974e956da
[ "MIT" ]
null
null
null
src/app.cc
PaoJiao/slide
fccdcac94e951de113b8f0116084c41974e956da
[ "MIT" ]
null
null
null
src/app.cc
PaoJiao/slide
fccdcac94e951de113b8f0116084c41974e956da
[ "MIT" ]
null
null
null
#include "app.h" #include "debug_print.h" namespace slide { App::App(void) { wview_.title = "Slide"; wview_.url = html_data_uri; wview_.width = 480; wview_.height = 320; wview_.resizable = 1; wview_.userdata = this; // The callback for when a webview event is invoked is the handleCommand // method wview_.external_invoke_cb = [](struct webview *w, const char *data) { App *app = static_cast<App *>(w->userdata); app->HandleCommand(data); }; // Command Pattern used. // These must be static to prevent segfault // If new commands are required, just make it here, then // add it's command string to the map as done here. static CreateFileCmd create; static OpenFileCmd open; static ExportPdfCmd pdf; static SetPreviewSizeCmd prev; static SetTextCmd text; static SetPaletteCmd pal; static SetCursorCmd cur; cmds_map_["create_file"] = &create; cmds_map_["open_file"] = &open; cmds_map_["export_pdf"] = &pdf; cmds_map_["set_preview_size"] = &prev; cmds_map_["set_palette"] = &pal; cmds_map_["set_text"] = &text; cmds_map_["set_cursor"] = &cur; } void App::Run(void) { webview_init(&wview_); webview_dispatch(&wview_, [](struct webview *w, void *arg) { App *app = static_cast<App *>(w->userdata); webview_eval(w, CssInject(styles_css).c_str()); webview_eval(w, picodom_js); webview_eval(w, app_js); }, nullptr); while (webview_loop(&wview_, 1) == 0) { /* Intentionally Blank */ } webview_exit(&wview_); } void App::HandleCommand(const std::string &data) { auto json = nlohmann::json::parse(data); auto cmd = json.at("cmd").get<std::string>(); // If the command isn't found, but we try to access it the command_map will // add the key with a null value, so before accessing confirm it's in the map if (cmds_map_.find(cmd) == cmds_map_.end()) { debug_print(cmd << " is not a valid command"); return; } cmds_map_[cmd]->Execute(*this, json); Render(); } void App::RenderCurrentSlide(void) { if (current_slide_ != -1) { debug_print("App::RenderCurrentSlide()"); debug_print("app instance details: " << *this); PNG png(preview_size_.Width(), preview_size_.Height()); slide::Render(png, deck_[current_slide_], foreground_, background_); debug_print("App::RenderCurrentSlide() render complete"); preview_data_uri_ = png.DataUri(); } } void App::Render(void) { auto json = nlohmann::json({}); json["text"] = current_text_; json["previewDataURI"] = preview_data_uri_; // std::cerr << "JSON Dump: " << json.dump() << std::endl; webview_eval( &wview_, ("window.app.state=" + json.dump() + "; window.render()").c_str()); } //----------- Below here is the command implementations for each key in the // command map. // If adding a new command simply add it here. void CreateFileCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Creating File" << std::endl; char path[PATH_MAX]; webview_dialog(&app.webview(), WEBVIEW_DIALOG_TYPE_SAVE, 0, "New presentation...", nullptr, path, PATH_MAX - 1); if (std::string(path).length() != 0) { app.CurrentFile() = std::string(path); webview_set_title(&app.webview(), ("Slide - " + app.CurrentFile()).c_str()); } } void OpenFileCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Opening File" << std::endl; char path[PATH_MAX]; webview_dialog(&app.webview(), WEBVIEW_DIALOG_TYPE_OPEN, 0, "Open presentation...", nullptr, path, sizeof(path) - 1); if (std::string(path).length() != 0) { app.CurrentFile() = path; webview_set_title(&app.webview(), ("Slide - " + app.CurrentFile()).c_str()); std::ifstream ifs(app.CurrentFile()); std::string text((std::istreambuf_iterator<char>(ifs)), (std::istreambuf_iterator<char>())); app.CurrentText() = text; app.Deck() = slide::Parse(app.CurrentText()); } } void ExportPdfCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Exporting to PDF" << std::endl; char path[PATH_MAX]; webview_dialog(&app.webview(), WEBVIEW_DIALOG_TYPE_SAVE, 0, "Export PDF...", nullptr, path, sizeof(path) - 1); if (strlen(path) != 0) { std::string path_str(path); const std::string extension(".pdf"); if (path_str.length() <= extension.length() || path_str.compare(path_str.length() - extension.length(), extension.length(), extension)) { path_str += extension; } // std::cerr << "writing to " << path_str << std::endl; PDF pdf(path_str, 640, 480); for (auto slide : app.Deck()) { pdf.BeginPage(); slide::Render(pdf, slide, app.Foreground(), app.Background()); pdf.EndPage(); } } } void SetPreviewSizeCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Setting Preview Size" << std::endl; app.PreviewSize().Width() = json.at("w").get<int>(); app.PreviewSize().Height() = json.at("h").get<int>(); app.RenderCurrentSlide(); } void SetPaletteCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Setting palette" << std::endl; app.Foreground() = json.at("fg").get<int>(); app.Background() = json.at("bg").get<int>(); app.RenderCurrentSlide(); } void SetTextCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Setting Text" << std::endl; app.CurrentText() = json.at("text").get<std::string>(); app.Deck() = slide::Parse(app.CurrentText()); std::ofstream file(app.CurrentFile()); file << app.CurrentText(); app.RenderCurrentSlide(); } void SetCursorCmd::Execute(App &app, nlohmann::json &json) { // std::cerr << "Setting Cursor" << std::endl; auto cursor = json.at("cursor").get<int>(); app.CurrentSlide() = -1; for (int i = 0; app.CurrentSlide() == -1 && i < app.Deck().size(); i++) { for (auto token : app.Deck()[i]) { if (token.position() >= cursor) { app.CurrentSlide() = i; break; } } } app.RenderCurrentSlide(); } } // namespace slide
32.877005
80
0.621828
PaoJiao
c128913a7f57128044d9526daee53d864ed3b411
183
cpp
C++
src/core/i_heat_source_component.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
3
2015-02-22T20:34:28.000Z
2020-03-04T08:55:25.000Z
src/core/i_heat_source_component.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
22
2015-12-13T16:29:40.000Z
2017-03-04T15:45:44.000Z
src/core/i_heat_source_component.cpp
Reaping2/Reaping2
0d4c988c99413e50cc474f6206cf64176eeec95d
[ "MIT" ]
14
2015-11-23T21:25:09.000Z
2020-07-17T17:03:23.000Z
#include "i_heat_source_component.h" #include <portable_iarchive.hpp> #include <portable_oarchive.hpp> REAPING2_CLASS_EXPORT_IMPLEMENT( IHeatSourceComponent, IHeatSourceComponent );
30.5
78
0.852459
MrPepperoni
c1299f21b1f8a218c5a8dd42e4ce9fd050e391cc
737
cpp
C++
Unidad-3/Aula25/AViciusPikemanEasy.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
Unidad-3/Aula25/AViciusPikemanEasy.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
Unidad-3/Aula25/AViciusPikemanEasy.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // https://open.kattis.com/problems/pikemaneasy typedef long long int ll; ll ARRA[10000]; int COMPARATION(const void *p, const void *q) { int *a = (int *) p; int *b = (int *) q; return *a - *b; } int main(int argc, char const *argv[]) { ll x, y, z, m, n, o = 0 ,p = 0, l = 0, i; cin >> x >> y >> z >> m >> n >> ARRA[0]; for (i = 1; i < x; ++i){ ARRA[i] = (z * ARRA[i-1] + m) % n + 1; } qsort(ARRA, x, sizeof(ll), COMPARATION); for (i = 0; i < x; ++i){ if (l + ARRA[i] <= y){ o = (o + ARRA[i] + l) % 1000000007; l += ARRA[i]; p++; } else break; } cout << p << " " << o << '\n'; return 0; }
21.676471
47
0.447761
luismoroco
c12a5cddd924ce38ee929ca606ed7cac3786cb88
313
hpp
C++
src/copy_and_move/src/Foo.hpp
VincentPopie/Sandbox
882c5bf7325af595739fd9004ba1774ceeee272f
[ "MIT" ]
null
null
null
src/copy_and_move/src/Foo.hpp
VincentPopie/Sandbox
882c5bf7325af595739fd9004ba1774ceeee272f
[ "MIT" ]
null
null
null
src/copy_and_move/src/Foo.hpp
VincentPopie/Sandbox
882c5bf7325af595739fd9004ba1774ceeee272f
[ "MIT" ]
null
null
null
#pragma once #include<string> /* * Class Foo contains a _name attribute. */ class Foo{ public: /* * Foo constructor, set the _name. */ Foo(const std::string& iName): _name(iName){} /* * Retrieve Foo name. */ std::string getName() const { return _name;} private: std::string _name; };
13.041667
47
0.616613
VincentPopie
c12cf46e106a5cb8cedbeef053419ce52ec1c00a
283
hpp
C++
bench/common/operator_new_insane.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
null
null
null
bench/common/operator_new_insane.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
null
null
null
bench/common/operator_new_insane.hpp
snake0/upcxx-2020.10.0
dcd313a65587efcdefdb4fdfb197389a0e390ccd
[ "BSD-3-Clause-LBNL" ]
1
2021-06-10T11:14:25.000Z
2021-06-10T11:14:25.000Z
// This file is intentionally empty. It stands only to pull in // "operator_new_insane.cpp" via nobs's header/source file extension matching. // Since the only two symbols the .cpp defines (operator new/delete) // are already intrinsically defined, there is nothing to be done here.
56.6
78
0.773852
snake0
c12f16268ac7328d71d5a6ac37ddfcc31cf934ab
3,151
cc
C++
mindspore/ccsrc/plugin/device/cpu/kernel/rl/fifo_replay_buffer.cc
httpsgithu/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
1
2022-02-23T09:13:43.000Z
2022-02-23T09:13:43.000Z
mindspore/ccsrc/plugin/device/cpu/kernel/rl/fifo_replay_buffer.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/plugin/device/cpu/kernel/rl/fifo_replay_buffer.cc
949144093/mindspore
c29d6bb764e233b427319cb89ba79e420f1e2c64
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2022 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "plugin/device/cpu/kernel/rl/fifo_replay_buffer.h" #include <cstring> #include <vector> #include <algorithm> #include <memory> #include "kernel/kernel.h" #include "plugin/device/cpu/hal/hardware/cpu_memory_pool.h" namespace mindspore { namespace kernel { FIFOReplayBuffer::FIFOReplayBuffer(size_t capacity, const std::vector<size_t> &schema) : capacity_(capacity), head_(-1), size_(0), schema_(schema) { for (const auto &size : schema) { size_t alloc_size = size * capacity; if (alloc_size == 0) { MS_LOG(ERROR) << "Malloc size can not be 0."; return; } void *ptr = device::cpu::CPUMemoryPool::GetInstance().AllocTensorMem(alloc_size); AddressPtr item = std::make_shared<Address>(ptr, alloc_size); (void)buffer_.emplace_back(item); } } FIFOReplayBuffer::~FIFOReplayBuffer() { for (const auto &item : buffer_) { device::cpu::CPUMemoryPool::GetInstance().FreeTensorMem(item->addr); item->addr = nullptr; } } bool FIFOReplayBuffer::Push(const std::vector<AddressPtr> &inputs) { if (inputs.size() != schema_.size()) { MS_LOG(EXCEPTION) << "Transition element num error. Expect " << schema_.size() << " , but got " << inputs.size(); } // Head point to the latest item. head_ = head_ >= capacity_ ? 0 : head_ + 1; size_ = size_ >= capacity_ ? capacity_ : size_ + 1; for (size_t i = 0; i < inputs.size(); i++) { void *offset = reinterpret_cast<uint8_t *>(buffer_[i]->addr) + head_ * schema_[i]; auto ret = memcpy_s(offset, buffer_[i]->size, inputs[i]->addr, inputs[i]->size); if (ret != EOK) { MS_LOG(EXCEPTION) << "memcpy_s() failed. Error code: " << ret; } } return true; } std::vector<AddressPtr> FIFOReplayBuffer::GetItem(size_t idx) { if (idx >= capacity_ || idx >= size_) { MS_LOG(EXCEPTION) << "Index " << idx << " out of range " << std::min(capacity_, size_); } std::vector<AddressPtr> ret; for (size_t i = 0; i < schema_.size(); i++) { void *offset = reinterpret_cast<uint8_t *>(buffer_[i]->addr) + schema_[i] * idx; ret.push_back(std::make_shared<Address>(offset, schema_[i])); } return ret; } std::vector<std::vector<AddressPtr>> FIFOReplayBuffer::GetItems(const std::vector<size_t> &indices) { std::vector<std::vector<AddressPtr>> ret; for (const auto &idx : indices) { auto item = GetItem(idx); (void)ret.emplace_back(item); } return ret; } const std::vector<AddressPtr> &FIFOReplayBuffer::GetAll() const { return buffer_; } } // namespace kernel } // namespace mindspore
32.484536
117
0.675024
httpsgithu
c12fac520b506da953ffbe92b0e4f58dfac8cf71
3,920
cxx
C++
Applications/AdaptiveParaView/pqCustomDisplayPolicy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
1
2021-07-31T19:38:03.000Z
2021-07-31T19:38:03.000Z
Applications/AdaptiveParaView/pqCustomDisplayPolicy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
null
null
null
Applications/AdaptiveParaView/pqCustomDisplayPolicy.cxx
matthb2/ParaView-beforekitwareswtichedtogit
e47e57d6ce88444d9e6af9ab29f9db8c23d24cef
[ "BSD-3-Clause" ]
2
2019-01-22T19:51:40.000Z
2021-07-31T19:38:05.000Z
#include "pqCustomDisplayPolicy.h" #include <pqPipelineSource.h> #include <vtkSMSourceProxy.h> #include <pqOutputPort.h> #include <vtkPVDataInformation.h> #include <QString> #include <vtkStructuredData.h> #include <pqTwoDRenderView.h> #include <pqApplicationCore.h> #include <pqDataRepresentation.h> #include <pqObjectBuilder.h> #include <QDebug> pqCustomDisplayPolicy::pqCustomDisplayPolicy(QObject *o) : pqDisplayPolicy(o) { } pqCustomDisplayPolicy::~pqCustomDisplayPolicy() { } //----------------------------------------------------------------------------- QString pqCustomDisplayPolicy::getPreferredViewType(pqOutputPort* opPort, bool update_pipeline) const { pqPipelineSource* source = opPort->getSource(); if (update_pipeline) { source->updatePipeline(); } QString view_type = QString::null; // HACK: for now, when update_pipeline is false, we don't do any gather // information as that can result in progress events which may case Qt paint // issues. vtkSMSourceProxy* spProxy = vtkSMSourceProxy::SafeDownCast( source->getProxy()); if (!spProxy || (!update_pipeline && !spProxy->GetOutputPortsCreated())) { // If parts aren't created, don't update the information at all. // Typically means that the filter hasn't been "Applied" even once and // updating information on it may raise errors. return view_type; } vtkPVDataInformation* datainfo = update_pipeline? opPort->getDataInformation(true) : opPort->getCachedDataInformation(); QString className = datainfo? datainfo->GetDataClassName() : QString(); // * Check if we should create the 2D view. if ((className == "vtkImageData" || className == "vtkUniformGrid") && datainfo->GetCompositeDataClassName()==0) { int extent[6]; datainfo->GetExtent(extent); int temp[6]={0, 0, 0, 0, 0, 0}; int dimensionality = vtkStructuredData::GetDataDimension( vtkStructuredData::SetExtent(extent, temp)); if (dimensionality == 2) { return pqTwoDRenderView::twoDRenderViewType(); } } return view_type; } //----------------------------------------------------------------------------- pqDataRepresentation* pqCustomDisplayPolicy::setRepresentationVisibility( pqOutputPort* opPort, pqView* view, bool visible) { if (!opPort) { // Cannot really repr a NULL source. return 0; } pqDataRepresentation* repr = opPort->getRepresentation(view); if (!repr && !visible) { // isn't visible already, nothing to change. return 0; } else if(!repr) { // FIXME:UDA -- can't we simply use createPreferredRepresentation? // No repr exists for this view. // First check if the view exists. If not, we will create a "suitable" view. if (!view) { view = this->getPreferredView(opPort, view); } if (view) { repr = pqApplicationCore::instance()->getObjectBuilder()-> createDataRepresentation(opPort, view); } } if (!repr) { qDebug() << "Cannot show the data in the current view although" "the view reported that it can show the data."; return 0; } repr->setVisible(visible); // If this is the only source displayed in the view, reset the camera to make // sure its visible. Only do so if a source is being turned ON. Otherwise when // the next to last source is turned off, the camera would be reset to fit the // last remaining one which would be unexpected to the user // (hence the conditional on "visible") // // The static pointer makes it not reset the viewpoint when we hide and // show the same thing. static pqView *lview = NULL; if(view->getNumberOfVisibleRepresentations()==1 && visible) { pqRenderViewBase* ren = qobject_cast<pqRenderViewBase*>(view); if (ren && lview != view) { ren->resetCamera(); lview = view; } } return repr; }
29.69697
81
0.653571
matthb2
c1308da8318fd5d74b8b5679b4252086a8d3d663
6,181
cpp
C++
src/utils/base64.cpp
twilio/Breakout_Massive_SDK
314a6460258c730ba5401f4895c08a0196e4cb2a
[ "Apache-2.0" ]
3
2020-06-21T13:26:28.000Z
2021-03-03T23:16:12.000Z
src/utils/base64.cpp
twilio/Breakout_Massive_SDK
314a6460258c730ba5401f4895c08a0196e4cb2a
[ "Apache-2.0" ]
11
2019-11-29T14:46:35.000Z
2020-02-17T10:19:54.000Z
src/utils/base64.cpp
twilio/breakout-massive-iot
314a6460258c730ba5401f4895c08a0196e4cb2a
[ "Apache-2.0" ]
2
2021-03-17T08:59:46.000Z
2021-09-17T05:38:17.000Z
/* Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. * 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. */ /* base64 encoder/decoder. Originally part of main/util.c * but moved here so that support/ab and ap_sha1.c could * use it. This meant removing the ap_palloc()s and adding * ugly 'len' functions, which is quite a nasty cost. */ #include <string.h> #include "base64.h" #include "md5.h" /* aaaack but it's fast and const should make it shared text page. */ static const unsigned char pr2six[256] = { /* ASCII table */ 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, 64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, 64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64}; int owl_base64decode_len(const char *bufcoded) { int nbytesdecoded; register const unsigned char *bufin; register int nprbytes; bufin = (const unsigned char *)bufcoded; while (pr2six[*(bufin++)] <= 63) ; nprbytes = (bufin - (const unsigned char *)bufcoded) - 1; nbytesdecoded = ((nprbytes + 3) / 4) * 3; return nbytesdecoded; } int owl_base64decode(unsigned char *bufplain, const char *bufcoded) { int nbytesdecoded; register const unsigned char *bufin; register unsigned char *bufout; register int nprbytes; bufin = (const unsigned char *)bufcoded; while (pr2six[*(bufin++)] <= 63) ; nprbytes = (bufin - (const unsigned char *)bufcoded) - 1; nbytesdecoded = ((nprbytes + 3) / 4) * 3; bufout = (unsigned char *)bufplain; bufin = (const unsigned char *)bufcoded; while (nprbytes > 4) { *(bufout++) = (unsigned char)(pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4); *(bufout++) = (unsigned char)(pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2); *(bufout++) = (unsigned char)(pr2six[bufin[2]] << 6 | pr2six[bufin[3]]); bufin += 4; nprbytes -= 4; } /* Note: (nprbytes == 1) would be an error, so just ingore that case */ if (nprbytes > 1) { *(bufout++) = (unsigned char)(pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4); } if (nprbytes > 2) { *(bufout++) = (unsigned char)(pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2); } if (nprbytes > 3) { *(bufout++) = (unsigned char)(pr2six[bufin[2]] << 6 | pr2six[bufin[3]]); } nbytesdecoded -= (4 - nprbytes) & 3; return nbytesdecoded; } int owl_base64decode_md5(unsigned char digest[16], const char *bufcoded) { unsigned char bufplain[3]; int nbytesdecoded; register const unsigned char *bufin; register unsigned char *bufout; register int nprbytes; struct MD5Context context; MD5Init(&context); bufin = (const unsigned char *)bufcoded; while (pr2six[*(bufin++)] <= 63) ; nprbytes = (bufin - (const unsigned char *)bufcoded) - 1; nbytesdecoded = ((nprbytes + 3) / 4) * 3; bufin = (const unsigned char *)bufcoded; while (nprbytes > 4) { bufout = bufplain; *(bufout++) = (unsigned char)(pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4); *(bufout++) = (unsigned char)(pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2); *(bufout++) = (unsigned char)(pr2six[bufin[2]] << 6 | pr2six[bufin[3]]); MD5Update(&context, bufplain, 3); bufin += 4; nprbytes -= 4; } bufout = bufplain; /* Note: (nprbytes == 1) would be an error, so just ingore that case */ if (nprbytes > 1) { *(bufout++) = (unsigned char)(pr2six[*bufin] << 2 | pr2six[bufin[1]] >> 4); if (nprbytes > 2) { *(bufout++) = (unsigned char)(pr2six[bufin[1]] << 4 | pr2six[bufin[2]] >> 2); } if (nprbytes > 3) { *(bufout++) = (unsigned char)(pr2six[bufin[2]] << 6 | pr2six[bufin[3]]); } MD5Update(&context, bufplain, nprbytes - 1); } nbytesdecoded -= (4 - nprbytes) & 3; MD5Final(digest, &context); return nbytesdecoded; } static const char basis_64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int owl_base64encode_len(int len) { return ((len + 2) / 3 * 4) + 1; } int owl_base64encode(char *encoded, const unsigned char *string, int len) { int i; char *p; p = encoded; for (i = 0; i < len - 2; i += 3) { *p++ = basis_64[(string[i] >> 2) & 0x3F]; *p++ = basis_64[((string[i] & 0x3) << 4) | ((int)(string[i + 1] & 0xF0) >> 4)]; *p++ = basis_64[((string[i + 1] & 0xF) << 2) | ((int)(string[i + 2] & 0xC0) >> 6)]; *p++ = basis_64[string[i + 2] & 0x3F]; } if (i < len) { *p++ = basis_64[(string[i] >> 2) & 0x3F]; if (i == (len - 1)) { *p++ = basis_64[((string[i] & 0x3) << 4)]; *p++ = '='; } else { *p++ = basis_64[((string[i] & 0x3) << 4) | ((int)(string[i + 1] & 0xF0) >> 4)]; *p++ = basis_64[((string[i + 1] & 0xF) << 2)]; } *p++ = '='; } *p++ = '\0'; return p - encoded; }
35.936047
119
0.58421
twilio
c13115439641c23f745ad4e6df82e19dccb84f1e
553
cpp
C++
Codeforces/474D - Flowers.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
2
2021-04-13T00:19:56.000Z
2021-04-13T01:19:45.000Z
Codeforces/474D - Flowers.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
null
null
null
Codeforces/474D - Flowers.cpp
Joon7891/Competitive-Programming
d860b7ad932cd5a6fb91fdc8c53101da57f4a408
[ "MIT" ]
1
2020-08-26T12:36:08.000Z
2020-08-26T12:36:08.000Z
#include<bits/stdc++.h> #define MOD 1000000007 using namespace std; const int MAXN = 100005; int dp[MAXN]; int prefix[MAXN]; int T, K; int main(){ cin >> T >> K; memset(dp, 0, sizeof(dp)); dp[0] = 1; for (int i = 1; i < MAXN; i++){ dp[i] = dp[i - 1]; if (i - K >= 0) dp[i] = (dp[i] + dp[i - K]) % MOD; } prefix[0] = 0; for (int i = 1; i < MAXN; i++){ prefix[i] = (prefix[i - 1] + dp[i]) % MOD; } for (int i = 0, a, b; i < T; i++){ cin >> a >> b; int ans = (prefix[b] - prefix[a - 1] + MOD) % MOD; cout << ans << endl; } }
18.433333
52
0.484629
Joon7891
c132f471cf543582185d7b30aaaa4942c150155c
1,606
hpp
C++
TopGraph/extendedpersistence/utils/mo_algorithm.hpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
55
2018-01-11T02:20:02.000Z
2022-03-24T06:18:54.000Z
TopGraph/extendedpersistence/utils/mo_algorithm.hpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
10
2016-10-29T08:20:04.000Z
2021-02-27T13:14:53.000Z
TopGraph/extendedpersistence/utils/mo_algorithm.hpp
mityanony404/TopGraph
23595ca5d3dfcd5bc5ebb771800e3fbe9a0d5eed
[ "MIT" ]
11
2016-10-29T06:00:53.000Z
2021-06-16T14:32:43.000Z
#pragma once #include <algorithm> #include <cmath> #include <numeric> #include <tuple> #include <utility> #include <vector> // struct mo_struct { // typedef int64_t value_type; // typedef int64_t result_type; // void add_right(int nr, value_type x_r) { // } // void add_left(int nl, value_type x_nl) { // } // void remove_right(int nr, value_type x_nr) { // } // void remove_left(int nl, value_type x_l) { // } // result_type query() { // return 0; // } // }; template <class Mo> std::vector<typename Mo::result_type> run_mo_algorithm(Mo mo, const std::vector<typename Mo::value_type>& values, const std::vector<std::pair<int, int> >& queries) { int n = values.size(); int m = queries.size(); // sort queries int sq_n = std::sqrt(n); std::vector<int> order(m); std::iota(ALL(order), 0); std::sort(ALL(order), [&](int i, int j) { int l_i, r_i; std::tie(l_i, r_i) = queries[i]; int l_j, r_j; std::tie(l_j, r_j) = queries[j]; return std::make_pair(l_i / sq_n, r_i) < std::make_pair(l_j / sq_n, r_j); }); // compute queries std::vector<typename Mo::result_type> ans(m); int l = 0; int r = 0; for (int j : order) { int nl, nr; std::tie(nl, nr) = queries[j]; for (; r < nr; ++ r) mo.add_right(r + 1, values[r]); for (; nl < l; -- l) mo.add_left(l - 1, values[l - 1]); for (; nr < r; -- r) mo.remove_right(r - 1, values[r - 1]); for (; l < nl; ++ l) mo.remove_left(l + 1, values[l]); ans[j] = mo.query(); } return ans; }
29.740741
165
0.557908
mityanony404
c134aa1e2c11632fb049def56d3a562ad7ab680a
3,989
cpp
C++
Source Code/AsTeRICS/ARE/components/sensor.spacenavigtor3Dmouse/src/main/c++/Mouse3DBridge/Mouse3DBridge/Mouse3DBridge.cpp
EliKabasele/openHAB_MyUI
f6c66a42cca24a484c2bd4013b20b05edaa88161
[ "Apache-2.0" ]
2
2016-06-30T14:32:51.000Z
2017-09-12T18:09:18.000Z
Source Code/AsTeRICS/ARE/components/sensor.spacenavigtor3Dmouse/src/main/c++/Mouse3DBridge/Mouse3DBridge/Mouse3DBridge.cpp
EliKabasele/openHAB_MyUI
f6c66a42cca24a484c2bd4013b20b05edaa88161
[ "Apache-2.0" ]
null
null
null
Source Code/AsTeRICS/ARE/components/sensor.spacenavigtor3Dmouse/src/main/c++/Mouse3DBridge/Mouse3DBridge/Mouse3DBridge.cpp
EliKabasele/openHAB_MyUI
f6c66a42cca24a484c2bd4013b20b05edaa88161
[ "Apache-2.0" ]
null
null
null
/* * AsTeRICS - Assistive Technology Rapid Integration and Construction Set * * * d8888 88888888888 8888888b. 8888888 .d8888b. .d8888b. * d88888 888 888 Y88b 888 d88P Y88b d88P Y88b * d88P888 888 888 888 888 888 888 Y88b. * d88P 888 .d8888b 888 .d88b. 888 d88P 888 888 "Y888b. * d88P 888 88K 888 d8P Y8b 8888888P" 888 888 "Y88b. * d88P 888 "Y8888b. 888 88888888 888 T88b 888 888 888 "888 * d8888888888 X88 888 Y8b. 888 T88b 888 Y88b d88P Y88b d88P * d88P 888 88888P' 888 "Y8888 888 T88b 8888888 "Y8888P" "Y8888P" * * * homepage: http://www.asterics.org * * This project has been partly funded by the European Commission, * Grant Agreement Number 247730 * * * Dual License: MIT or GPL v3.0 with "CLASSPATH" exception * (please refer to the folder LICENSE) * */ /** * Interfaces the 3D Mouse Library for the 3D Mouse plugin. * * @author Karol Pecyna [kpecyna@harpo.com.pl] * Date: Jul 05, 2011 * Time: 11:51:00 AM */ #include "Mouse3DBridge.h" #include <Windows.h> #include "Mouse3DBridgeErrors.h" typedef int (__stdcall *Init) (); typedef int (__stdcall *Close) (); typedef int (__stdcall *Get3DMouseState)(long *x, long *y, long *z, long *Rx, long *Ry, long *Rz, long* buttons); Init init=NULL; Close close=NULL; Get3DMouseState get3DMouseState=NULL; HINSTANCE hLib; bool initated=false; /** * Clears initialized data. */ void Clear() { FreeLibrary((HMODULE)hLib); init=NULL; close=NULL; get3DMouseState=NULL; hLib=NULL; initated=false; } /** * Activates the library. * @return if the returned value is less then 0, the value is an error number. */ JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_spacenavigtor3Dmouse_SpaceNavigtor3DMouseBridge_activate (JNIEnv *, jobject) { if(initated) { return library_initialized; } hLib=LoadLibrary(L"Mouse3Dlibrary.dll"); if(hLib==NULL) { return dll_library_not_found; } init=(Init)GetProcAddress((HMODULE)hLib, "init"); if(init==NULL) { Clear(); return get_function_error; } close=(Close)GetProcAddress((HMODULE)hLib, "close"); if(close==NULL) { Clear(); return get_function_error; } get3DMouseState=(Get3DMouseState)GetProcAddress((HMODULE)hLib, "get3DMouseState"); if(init==NULL) { Clear(); return get_function_error; } int nResult = init(); if(nResult<0) { Clear(); return nResult; } initated=true; return 1; } /** * Dectivates the library. * @return if the returned value is less then 0, the value is an error number. */ JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_spacenavigtor3Dmouse_SpaceNavigtor3DMouseBridge_deactivate (JNIEnv *, jobject) { if(initated==false) { return library_no_initialized; } int nResult=close(); if(nResult<0) { return nResult; } Clear(); return 1; } long tx; long ty; long tz; long tRx; long tRy; long tRz; long buttons; /** * Reads the 3D mouse data. * @param env environment data. * @param outArray Array of the mouse data. * @return if the returned value is less then 0, the value is an error number. */ JNIEXPORT jint JNICALL Java_eu_asterics_component_sensor_spacenavigtor3Dmouse_SpaceNavigtor3DMouseBridge_getData (JNIEnv * env, jobject, jlongArray outArray) { if(initated==false) { return library_no_initialized; } if(outArray==NULL) { return out_array_null; } get3DMouseState(&tx,&ty,&tz,&tRx,&tRy,&tRz,&buttons); jlong* dataOutArray = env->GetLongArrayElements(outArray, 0); if(dataOutArray==NULL) { return array_null; } dataOutArray[0]=tx; dataOutArray[1]=ty; dataOutArray[2]=tz; dataOutArray[3]=tRx; dataOutArray[4]=tRy; dataOutArray[5]=tRz; dataOutArray[6]=buttons; env->ReleaseLongArrayElements(outArray, dataOutArray, 0); return 1; }
20.668394
115
0.668338
EliKabasele
c1370b0b878f3aa84b1789d465972aa9ac652a71
12,439
cpp
C++
src/webots/nodes/WbSphere.cpp
Justin-Fisher/webots
8a39e8e4390612919a8d82c7815aa914f4c079a4
[ "Apache-2.0" ]
1
2021-12-06T02:46:37.000Z
2021-12-06T02:46:37.000Z
src/webots/nodes/WbSphere.cpp
Justin-Fisher/webots
8a39e8e4390612919a8d82c7815aa914f4c079a4
[ "Apache-2.0" ]
null
null
null
src/webots/nodes/WbSphere.cpp
Justin-Fisher/webots
8a39e8e4390612919a8d82c7815aa914f4c079a4
[ "Apache-2.0" ]
null
null
null
// Copyright 1996-2021 Cyberbotics Ltd. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "WbSphere.hpp" #include "WbBoundingSphere.hpp" #include "WbField.hpp" #include "WbFieldChecker.hpp" #include "WbMathsUtilities.hpp" #include "WbMatter.hpp" #include "WbNodeUtilities.hpp" #include "WbOdeGeomData.hpp" #include "WbRay.hpp" #include "WbResizeManipulator.hpp" #include "WbSFBool.hpp" #include "WbSFInt.hpp" #include "WbSimulationState.hpp" #include "WbTokenizer.hpp" #include "WbTransform.hpp" #include "WbVersion.hpp" #include "WbWrenRenderingContext.hpp" #include <wren/config.h> #include <wren/renderable.h> #include <wren/static_mesh.h> #include <wren/transform.h> #include <ode/ode.h> #include <cmath> void WbSphere::init() { mRadius = findSFDouble("radius"); mSubdivision = findSFInt("subdivision"); mIco = findSFBool("ico"); mResizeConstraint = WbWrenAbstractResizeManipulator::UNIFORM; } WbSphere::WbSphere(WbTokenizer *tokenizer) : WbGeometry("Sphere", tokenizer) { init(); if (tokenizer == NULL) mRadius->setValueNoSignal(0.1); else if (tokenizer->fileType() == WbTokenizer::MODEL) { // ensure compatibility with VRML specifications mIco->setValueNoSignal(false); mSubdivision->blockSignals(true); mSubdivision->setValue(24); mSubdivision->blockSignals(false); } } WbSphere::WbSphere(const WbSphere &other) : WbGeometry(other) { init(); } WbSphere::WbSphere(const WbNode &other) : WbGeometry(other) { init(); } WbSphere::~WbSphere() { wr_static_mesh_delete(mWrenMesh); } void WbSphere::postFinalize() { WbGeometry::postFinalize(); connect(mRadius, &WbSFDouble::changed, this, &WbSphere::updateRadius); connect(mSubdivision, &WbSFInt::changed, this, &WbSphere::updateMesh); connect(mIco, &WbSFBool::changed, this, &WbSphere::updateMesh); } void WbSphere::createWrenObjects() { WbGeometry::createWrenObjects(); sanitizeFields(); buildWrenMesh(); if (isInBoundingObject()) connect(WbWrenRenderingContext::instance(), &WbWrenRenderingContext::lineScaleChanged, this, &WbSphere::updateLineScale); emit wrenObjectsCreated(); } void WbSphere::setResizeManipulatorDimensions() { WbVector3 scale(radius(), radius(), radius()); WbTransform *transform = upperTransform(); if (transform) scale *= transform->matrix().scale(); if (isAValidBoundingObject()) scale *= 1.0f + (wr_config_get_line_scale() / LINE_SCALE_FACTOR); resizeManipulator()->updateHandleScale(scale.ptr()); updateResizeHandlesSize(); } void WbSphere::createResizeManipulator() { mResizeManipulator = new WbRegularResizeManipulator(uniqueId(), (WbWrenAbstractResizeManipulator::ResizeConstraint)mResizeConstraint); } bool WbSphere::areSizeFieldsVisibleAndNotRegenerator() const { const WbField *const radius = findField("radius", true); return WbNodeUtilities::isVisible(radius) && !WbNodeUtilities::isTemplateRegeneratorField(radius); } void WbSphere::write(WbVrmlWriter &writer) const { if (writer.isVrml() && mIco->value()) writeExport(writer); else WbGeometry::write(writer); } void WbSphere::exportNodeFields(WbVrmlWriter &writer) const { if (!writer.isVrml() || !mIco->value()) { WbGeometry::exportNodeFields(writer); if (writer.isX3d()) { writer << " subdivision=\'" << mSubdivision->value() << ',' << mSubdivision->value() << "\'"; writer << " ico=\'" << (mIco->value() ? "true" : "false") << "\'"; } return; } // else export icosphere as IndexedFaceSet (VRML default sphere is a UV sphere) if (!mWrenMesh) return; writer.indent(); writer << "creaseAngle 1\n"; const int indexCount = wr_static_mesh_get_index_count(mWrenMesh); unsigned int indices[indexCount]; writer.indent(); writer << "coordIndex [ "; wr_static_mesh_read_data(mWrenMesh, NULL, NULL, NULL, indices); for (int i = 0; i < indexCount; i += 3) writer << indices[i] << " " << indices[i + 1] << " " << indices[i + 2] << " -1 "; writer << "]\n"; } void WbSphere::exportNodeSubNodes(WbVrmlWriter &writer) const { if (!writer.isVrml() || !mIco->value()) { WbGeometry::exportNodeSubNodes(writer); return; } // else export icosphere as IndexedFaceSet (VRML default sphere is a UV sphere) if (!mWrenMesh) return; const int vertexCount = wr_static_mesh_get_vertex_count(mWrenMesh); float vertices[3 * vertexCount]; float normal_data[3 * vertexCount]; float tex_coord_data[2 * vertexCount]; wr_static_mesh_read_data(mWrenMesh, vertices, normal_data, tex_coord_data, NULL); // Write with limited precision to reduce the size of the VRML file. const int precision = 4; // Coordinate writer.indent(); writer << "coord Coordinate {\n"; writer.increaseIndent(); writer.indent(); writer << "point [ "; const double radius = mRadius->value(); for (int i = 0; i < vertexCount; i++) { writer << QString::number(vertices[i * 3] * radius, 'f', precision) << " " << QString::number(vertices[i * 3 + 1] * radius, 'f', precision) << " " << QString::number(vertices[i * 3 + 2] * radius, 'f', precision) << " "; } writer << " ]\n"; writer.decreaseIndent(); writer.indent(); writer << "}\n"; // TextureCoordinate writer.indent(); writer << "texCoord TextureCoordinate {\n"; writer.increaseIndent(); writer.indent(); writer << "point [ "; for (int i = 0; i < vertexCount; i++) writer << QString::number(tex_coord_data[i * 2], 'f', precision) << " " << QString::number(-tex_coord_data[i * 2 + 1], 'f', precision) << " "; writer << " ]\n"; writer.decreaseIndent(); writer.indent(); writer << "}\n"; // Normal writer.indent(); writer << "normal Normal {\n"; writer.increaseIndent(); writer.indent(); writer << " vector [ "; for (int i = 0; i < vertexCount; i++) writer << QString::number(normal_data[i * 3], 'f', precision) << " " << QString::number(normal_data[i * 3 + 1], 'f', precision) << " " << QString::number(normal_data[i * 3 + 2], 'f', precision) << " "; writer << " ]\n"; writer.decreaseIndent(); writer.indent(); writer << "}\n"; } bool WbSphere::sanitizeFields() { bool invalidValue; if (mIco->value()) { invalidValue = WbFieldChecker::resetIntIfNotInRangeWithIncludedBounds(this, mSubdivision, 1, 5, 1); } else invalidValue = WbFieldChecker::resetIntIfNotInRangeWithIncludedBounds(this, mSubdivision, 3, 32, 24); if (invalidValue) return false; if (WbFieldChecker::resetDoubleIfNonPositive(this, mRadius, 1.0)) return false; return true; } void WbSphere::buildWrenMesh() { WbGeometry::deleteWrenRenderable(); wr_static_mesh_delete(mWrenMesh); mWrenMesh = NULL; WbGeometry::computeWrenRenderable(); const bool createOutlineMesh = isInBoundingObject(); mWrenMesh = wr_static_mesh_unit_sphere_new(mSubdivision->value(), mIco->value(), createOutlineMesh); // Restore pickable state setPickable(isPickable()); wr_renderable_set_mesh(mWrenRenderable, WR_MESH(mWrenMesh)); if (createOutlineMesh) updateLineScale(); else updateScale(); } void WbSphere::updateRadius() { if (!sanitizeFields()) return; if (isInBoundingObject()) updateLineScale(); else updateScale(); if (isInBoundingObject()) applyToOdeData(); if (mBoundingSphere && !isInBoundingObject()) mBoundingSphere->setOwnerSizeChanged(); if (resizeManipulator() && resizeManipulator()->isAttached()) setResizeManipulatorDimensions(); emit changed(); } void WbSphere::updateMesh() { if (!sanitizeFields()) return; buildWrenMesh(); emit changed(); } void WbSphere::updateLineScale() { if (!isAValidBoundingObject()) return; const float offset = wr_config_get_line_scale() / LINE_SCALE_FACTOR; const float scaledRadius = static_cast<float>(mRadius->value() * (1.0 + offset)); const float scale[] = {scaledRadius, scaledRadius, scaledRadius}; wr_transform_set_scale(wrenNode(), scale); } void WbSphere::updateScale() { if (!sanitizeFields()) return; const float scaledRadius = static_cast<float>(mRadius->value()); const float scale[] = {scaledRadius, scaledRadius, scaledRadius}; wr_transform_set_scale(wrenNode(), scale); } void WbSphere::rescale(const WbVector3 &scale) { if (scale.x() != 1.0) setRadius(radius() * scale.x()); else if (scale.y() != 1.0) setRadius(radius() * scale.y()); else if (scale.z() != 1.0) setRadius(radius() * scale.z()); } ///////////////// // ODE objects // ///////////////// dGeomID WbSphere::createOdeGeom(dSpaceID space) { if (mRadius->value() <= 0.0) { parsingWarn(tr("'radius' must be positive when used in 'boundingObject'.")); return NULL; } if (WbNodeUtilities::findUpperMatter(this)->nodeType() == WB_NODE_FLUID) checkFluidBoundingObjectOrientation(); return dCreateSphere(space, scaledRadius()); } void WbSphere::applyToOdeData(bool correctSolidMass) { if (mOdeGeom == NULL) return; assert(dGeomGetClass(mOdeGeom) == dSphereClass); dGeomSphereSetRadius(mOdeGeom, scaledRadius()); WbOdeGeomData *const odeGeomData = static_cast<WbOdeGeomData *>(dGeomGetData(mOdeGeom)); assert(odeGeomData); odeGeomData->setLastChangeTime(WbSimulationState::instance()->time()); if (correctSolidMass) applyToOdeMass(); } double WbSphere::scaledRadius() const { const WbVector3 &scale = absoluteScale(); return fabs(mRadius->value() * std::max(std::max(scale.x(), scale.y()), scale.z())); } bool WbSphere::isSuitableForInsertionInBoundingObject(bool warning) const { const bool invalidRadius = mRadius->value() <= 0.0; if (warning && invalidRadius) parsingWarn(tr("'radius' must be positive when used in 'boundingObject'.")); return !invalidRadius; } bool WbSphere::isAValidBoundingObject(bool checkOde, bool warning) const { const bool admissible = WbGeometry::isAValidBoundingObject(checkOde, warning); return admissible && isSuitableForInsertionInBoundingObject(admissible && warning); } ///////////////// // Ray Tracing // ///////////////// bool WbSphere::pickUVCoordinate(WbVector2 &uv, const WbRay &ray, int textureCoordSet) const { WbVector3 collisionPoint; bool collisionExists = computeCollisionPoint(collisionPoint, ray); if (!collisionExists) return false; WbTransform *transform = upperTransform(); WbVector3 pointOnTexture(collisionPoint); if (transform) { pointOnTexture = transform->matrix().pseudoInversed(collisionPoint); pointOnTexture /= absoluteScale(); } const double u = 0.5 + atan2(pointOnTexture.x(), pointOnTexture.z()) * 0.5 * M_1_PI; const double v = 0.5 - WbMathsUtilities::clampedAsin(pointOnTexture.y() / scaledRadius()) * M_1_PI; // result uv.setXy(u, v); return true; } double WbSphere::computeDistance(const WbRay &ray) const { WbVector3 collisionPoint; bool collisionExists = computeCollisionPoint(collisionPoint, ray); if (!collisionExists) return -1; WbVector3 d = ray.origin() - collisionPoint; return d.length(); } bool WbSphere::computeCollisionPoint(WbVector3 &point, const WbRay &ray) const { WbVector3 center; const WbTransform *const transform = upperTransform(); if (transform) center = transform->matrix().translation(); double radius = scaledRadius(); // distance from sphere const std::pair<bool, double> result = ray.intersects(center, radius, true); point = ray.origin() + result.second * ray.direction(); return result.first; } void WbSphere::recomputeBoundingSphere() const { assert(mBoundingSphere); mBoundingSphere->set(WbVector3(), scaledRadius()); } //////////////////////// // Friction Direction // //////////////////////// WbVector3 WbSphere::computeFrictionDirection(const WbVector3 &normal) const { parsingWarn( tr("A Sphere is used in a Bounding object using an asymmetric friction. Sphere does not support asymmetric friction")); return WbVector3(0, 0, 0); }
29.546318
125
0.692178
Justin-Fisher
c13bab36f232703c56a0c73f9aac61c57295541d
1,410
cpp
C++
src/examples/facefilter/lib/facefilter/renderer/android/FaceTrackerFactoryJsonAndroid.cpp
ZJCRT/drishti
7c0da7e71cd4cff838b0b8ef195855cb68951839
[ "BSD-3-Clause" ]
346
2017-05-13T05:12:51.000Z
2022-01-31T08:57:14.000Z
src/examples/facefilter/lib/facefilter/renderer/android/FaceTrackerFactoryJsonAndroid.cpp
ZJCRT/drishti
7c0da7e71cd4cff838b0b8ef195855cb68951839
[ "BSD-3-Clause" ]
238
2017-05-12T20:22:26.000Z
2021-06-08T20:54:11.000Z
src/examples/facefilter/lib/facefilter/renderer/android/FaceTrackerFactoryJsonAndroid.cpp
ZJCRT/drishti
7c0da7e71cd4cff838b0b8ef195855cb68951839
[ "BSD-3-Clause" ]
84
2017-06-30T06:50:56.000Z
2022-03-24T01:21:54.000Z
/*! -*-c++-*- @file FaceTrackerFactoryJsonAndroid.h @brief Implementation of a FaceTrackerFactory to load models from a JSON file using the NDK AssetManager. \copyright Copyright 2017-2018 Elucideye, Inc. All rights reserved. \license{This file is released under the 3 Clause BSD License.} */ #include "facefilter/renderer/android/FaceTrackerFactoryJsonAndroid.h" #include "facefilter/renderer/android/android_asset_istream.h" BEGIN_FACEFILTER_NAMESPACE static std::string cat(const std::string& a, const std::string& b) { return a + b; } FaceTrackerFactoryJsonAndroid::FaceTrackerFactoryJsonAndroid ( void* assetManager, const std::string& sModels, std::shared_ptr<spdlog::logger>& logger ) : assetManager(assetManager) { if (assetManager == nullptr) { throw std::runtime_error("FaceTrackerFactoryJsonAndroid::FaceTrackerFactoryJsonAndroid(): assetManager is null"); } init(sModels, logger); } std::shared_ptr<std::istream> FaceTrackerFactoryJsonAndroid::open_stream(const std::string& filename, std::ios_base::openmode /* mode */) { auto ifs = std::make_shared<android::asset_istream>(static_cast<AAssetManager*>(assetManager), filename.c_str()); if (!ifs || !ifs->good()) { throw std::runtime_error(cat("FaceTrackerFactoryJsonAndroid::open_stream() failed to open ", filename)); } return ifs; } END_FACEFILTER_NAMESPACE
32.790698
121
0.73617
ZJCRT
c13f5206521d4c221977c6376b97b0baff56db4a
27,449
cc
C++
engine/source/2d/assets/ParticleAssetEmitter.cc
close-code/Torque2D
ad141fc7b5f28b75f727ef29dcc93aafbb3f5aa3
[ "MIT" ]
1,309
2015-01-01T02:46:14.000Z
2022-03-14T04:56:02.000Z
engine/source/2d/assets/ParticleAssetEmitter.cc
SwaroopGuvvala/Torque2D
55efccc7c7a4331547f5d71c733a75b8de1189e8
[ "MIT" ]
155
2015-01-11T19:26:32.000Z
2021-11-22T04:08:55.000Z
engine/source/2d/assets/ParticleAssetEmitter.cc
SwaroopGuvvala/Torque2D
55efccc7c7a4331547f5d71c733a75b8de1189e8
[ "MIT" ]
1,595
2015-01-01T23:19:48.000Z
2022-02-17T07:00:52.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // 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 "2d/assets/ParticleAssetEmitter.h" #ifndef _PARTICLE_ASSET_H_ #include "2d/assets/ParticleAsset.h" #endif #ifndef _CONSOLETYPES_H_ #include "console/consoleTypes.h" #endif // Script bindings. #include "ParticleAssetEmitter_ScriptBinding.h" //------------------------------------------------------------------------------ static EnumTable::Enums emitterTypeLookup[] = { { ParticleAssetEmitter::POINT_EMITTER, "POINT" }, { ParticleAssetEmitter::LINE_EMITTER, "LINE" }, { ParticleAssetEmitter::BOX_EMITTER, "BOX" }, { ParticleAssetEmitter::DISK_EMITTER, "DISK" }, { ParticleAssetEmitter::ELLIPSE_EMITTER, "ELLIPSE" }, { ParticleAssetEmitter::TORUS_EMITTER, "TORUS" }, }; //------------------------------------------------------------------------------ static EnumTable EmitterTypeTable(sizeof(emitterTypeLookup) / sizeof(EnumTable::Enums), &emitterTypeLookup[0]); //------------------------------------------------------------------------------ ParticleAssetEmitter::EmitterType ParticleAssetEmitter::getEmitterTypeEnum(const char* label) { // Search for Mnemonic. for(U32 i = 0; i < (sizeof(emitterTypeLookup) / sizeof(EnumTable::Enums)); i++) if( dStricmp(emitterTypeLookup[i].label, label) == 0) return((ParticleAssetEmitter::EmitterType)emitterTypeLookup[i].index); // Warn. Con::warnf( "ParticleAssetEmitter::getEmitterTypeEnum() - Invalid emitter-type '%s'.", label ); return ParticleAssetEmitter::INVALID_EMITTER_TYPE; } //----------------------------------------------------------------------------- const char* ParticleAssetEmitter::getEmitterTypeDescription( const EmitterType emitterType ) { // Search for Mnemonic. for (U32 i = 0; i < (sizeof(emitterTypeLookup) / sizeof(EnumTable::Enums)); i++) { if( emitterTypeLookup[i].index == (S32)emitterType ) return emitterTypeLookup[i].label; } // Warn. Con::warnf( "ParticleAssetEmitter::getEmitterTypeDescription() - Invalid emitter-type." ); return StringTable->EmptyString; } //------------------------------------------------------------------------------ static EnumTable::Enums particleOrientationTypeLookup[] = { { ParticleAssetEmitter::FIXED_ORIENTATION, "FIXED" }, { ParticleAssetEmitter::ALIGNED_ORIENTATION, "ALIGNED" }, { ParticleAssetEmitter::RANDOM_ORIENTATION, "RANDOM" }, }; //------------------------------------------------------------------------------ static EnumTable OrientationTypeTable(sizeof(particleOrientationTypeLookup) / sizeof(EnumTable::Enums), &particleOrientationTypeLookup[0]); //------------------------------------------------------------------------------ ParticleAssetEmitter::ParticleOrientationType ParticleAssetEmitter::getOrientationTypeEnum(const char* label) { // Search for Mnemonic. for(U32 i = 0; i < (sizeof(particleOrientationTypeLookup) / sizeof(EnumTable::Enums)); i++) if( dStricmp(particleOrientationTypeLookup[i].label, label) == 0) return((ParticleAssetEmitter::ParticleOrientationType)particleOrientationTypeLookup[i].index); // Warn. Con::warnf( "ParticleAssetEmitter::getOrientationTypeEnum() - Invalid orientation type '%s'.", label ); return ParticleAssetEmitter::INVALID_ORIENTATION; } //------------------------------------------------------------------------------ const char* ParticleAssetEmitter::getOrientationTypeDescription( const ParticleOrientationType orientationType ) { // Search for Mnemonic. for (U32 i = 0; i < (sizeof(particleOrientationTypeLookup) / sizeof(EnumTable::Enums)); i++) { if( particleOrientationTypeLookup[i].index == (S32)orientationType ) return particleOrientationTypeLookup[i].label; } // Warn. Con::warnf( "ParticleAssetEmitter::getOrientationTypeDescription() - Invalid orientation-type" ); return StringTable->EmptyString; } //------------------------------------------------------------------------------ ParticleAssetEmitter::ParticleAssetEmitter() : mEmitterName( StringTable->EmptyString ), mOwner( NULL ), mEmitterType( POINT_EMITTER ), mEmitterOffset( 0.0f, 0.0f), mEmitterAngle( 0.0f ), mEmitterSize( 10.0f, 10.0f ), mFixedAspect( true ), mOrientationType( FIXED_ORIENTATION ), mKeepAligned( false ), mAlignedAngleOffset( 0.0f ), mRandomAngleOffset( 0.0f ), mRandomArc( 360.0f ), mFixedAngleOffset( 0.0f ), mLinkEmissionRotation( true ), mIntenseParticles( false ), mSingleParticle( false ), mAttachPositionToEmitter( false ), mAttachRotationToEmitter( false ), mOldestInFront( false ), mStaticMode( true ), mImageAsset( NULL ), mImageFrame( 0 ), mRandomImageFrame( false ), mAnimationAsset( NULL ), mBlendMode( true ), mSrcBlendFactor( GL_SRC_ALPHA ), mDstBlendFactor( GL_ONE_MINUS_SRC_ALPHA ), mAlphaTest( -1.0f ) { // Set the pivot point. // NOTE: This is called to set the local AABB. setPivotPoint( Vector2::getZero() ); // Set fixed force angle. // NOTE: This is called to set the fixed-force-direction. setFixedForceAngle( 0.0f ); // Initialize particle fields. mParticleFields.addField( mParticleLife.getBase(), "Lifetime", 1000.0f, 0.0f, 10000.0f, 2.0f ); mParticleFields.addField( mParticleLife.getVariation(), "LifetimeVariation", 1000.0f, 0.0f, 5000.0f, 0.0f ); mParticleFields.addField( mQuantity.getBase(), "Quantity", 1000.0f, 0.0f, 100000.0f, 10.0f ); mParticleFields.addField( mQuantity.getVariation(), "QuantityVariation", 1000.0f, 0.0f, 100000.0f, 0.0f ); mParticleFields.addField( mSizeX.getBase(), "SizeX", 1000.0f, 0.0f, 100.0f, 2.0f ); mParticleFields.addField( mSizeX.getVariation(), "SizeXVariation", 1000.0f, 0.0f, 200.0f, 0.0f ); mParticleFields.addField( mSizeX.getLife(), "SizeXLife", 1.0f, -100.0f, 100.0f, 1.0f ); mParticleFields.addField( mSizeY.getBase(), "SizeY", 1000.0f, 0.0f, 100.0f, 2.0f ); mParticleFields.addField( mSizeY.getVariation(), "SizeYVariation", 1000.0f, 0.0f, 200.0f, 0.0f ); mParticleFields.addField( mSizeY.getLife(), "SizeYLife", 1.0f, -100.0f, 100.0f, 1.0f ); mParticleFields.addField( mSpeed.getBase(), "Speed", 1000.0f, 0.0f, 100.0f, 10.0f ); mParticleFields.addField( mSpeed.getVariation(), "SpeedVariation", 1000.0f, 0.0f, 200.0f, 0.0f ); mParticleFields.addField( mSpeed.getLife(), "SpeedLife", 1.0f, -100.0f, 100.0f, 1.0f ); mParticleFields.addField( mSpin.getBase(), "Spin", 1000.0f, -1000.0f, 1000.0f, 0.0f ); mParticleFields.addField( mSpin.getVariation(), "SpinVariation", 1000.0f, 0.0f, 2000.0f, 0.0f ); mParticleFields.addField( mSpin.getLife(), "SpinLife", 1.0f, -1000.0f, 1000.0f, 1.0f ); mParticleFields.addField( mFixedForce.getBase(), "FixedForce", 1000.0f, -1000.0f, 1000.0f, 0.0f ); mParticleFields.addField( mFixedForce.getVariation(), "FixedForceVariation", 1000.0f, 0.0f, 2000.0f, 0.0f ); mParticleFields.addField( mFixedForce.getLife(), "FixedForceLife", 1.0f, -1000.0f, 1000.0f, 1.0f ); mParticleFields.addField( mRandomMotion.getBase(), "RandomMotion", 1000.0f, 0.0f, 1000.0f, 0.0f ); mParticleFields.addField( mRandomMotion.getVariation(), "RandomMotionVariation", 1000.0f, 0.0f, 2000.0f, 0.0f ); mParticleFields.addField( mRandomMotion.getLife(), "RandomMotionLife", 1.0f, -100.0f, 100.0f, 1.0f ); mParticleFields.addField( mEmissionForce.getBase(), "EmissionForce", 1000.0f, -100.0f, 1000.0f, 5.0f ); mParticleFields.addField( mEmissionForce.getVariation(), "EmissionForceVariation", 1000.0f, -500.0f, 500.0f, 5.0f ); mParticleFields.addField( mEmissionAngle.getBase(), "EmissionAngle", 1000.0f, -180.0f, 180.0f, 0.0f ); mParticleFields.addField( mEmissionAngle.getVariation(), "EmissionAngleVariation", 1000.0f, 0.0f, 360.0f, 0.0f ); mParticleFields.addField( mEmissionArc.getBase(), "EmissionArc", 1000.0f, 0.0f, 360.0f, 360.0f ); mParticleFields.addField( mEmissionArc.getVariation(), "EmissionArcVariation", 1000.0f, 0.0f, 720.0f, 0.0f ); mParticleFields.addField( mRedChannel.getLife(), "RedChannel", 1.0f, 0.0f, 1.0f, 1.0f ); mParticleFields.addField( mGreenChannel.getLife(), "GreenChannel", 1.0f, 0.0f, 1.0f, 1.0f ); mParticleFields.addField( mBlueChannel.getLife(), "BlueChannel", 1.0f, 0.0f, 1.0f, 1.0f ); mParticleFields.addField( mAlphaChannel.getLife(), "AlphaChannel", 1.0f, 0.0f, 1.0f, 1.0f ); // Register for refresh notifications. mImageAsset.registerRefreshNotify( this ); mAnimationAsset.registerRefreshNotify( this ); mNamedImageFrame = ""; mUsingNamedFrame = false; } //------------------------------------------------------------------------------ ParticleAssetEmitter::~ParticleAssetEmitter() { } //------------------------------------------------------------------------------ void ParticleAssetEmitter::initPersistFields() { // Call parent. Parent::initPersistFields(); addProtectedField("EmitterName", TypeString, Offset(mEmitterName, ParticleAssetEmitter), &setEmitterName, &defaultProtectedGetFn, &defaultProtectedWriteFn, ""); addProtectedField("EmitterType", TypeEnum, Offset(mEmitterType, ParticleAssetEmitter), &setEmitterType, &defaultProtectedGetFn, &writeEmitterType, 1, &EmitterTypeTable); addProtectedField("EmitterOffset", TypeVector2, Offset(mEmitterOffset, ParticleAssetEmitter), &setEmitterOffset, &defaultProtectedGetFn, &writeEmitterOffset, ""); addProtectedField("EmitterAngle", TypeF32, Offset(mEmitterAngle, ParticleAssetEmitter), &setEmitterAngle, &defaultProtectedGetFn, &writeEmitterAngle, ""); addProtectedField("EmitterSize", TypeVector2, Offset(mEmitterSize, ParticleAssetEmitter), &setEmitterSize, &defaultProtectedGetFn, &writeEmitterSize, ""); addProtectedField("FixedAspect", TypeBool, Offset(mFixedAspect, ParticleAssetEmitter), &setFixedAspect, &defaultProtectedGetFn, &writeFixedAspect, ""); addProtectedField("FixedForceAngle", TypeF32, Offset(mFixedForceAngle, ParticleAssetEmitter), &setFixedForceAngle, &defaultProtectedGetFn, &writeFixedForceAngle, ""); addProtectedField("OrientationType", TypeEnum, Offset(mOrientationType, ParticleAssetEmitter), &setOrientationType, &defaultProtectedGetFn, &writeOrientationType, 1, &OrientationTypeTable); addProtectedField("KeepAligned", TypeBool, Offset(mKeepAligned, ParticleAssetEmitter), &setKeepAligned, &defaultProtectedGetFn, &writeKeepAligned, ""); addProtectedField("AlignedAngleOffset", TypeF32, Offset(mAlignedAngleOffset, ParticleAssetEmitter), &setAlignedAngleOffset, &defaultProtectedGetFn, &writeAlignedAngleOffset, ""); addProtectedField("RandomAngleOffset", TypeF32, Offset(mRandomAngleOffset, ParticleAssetEmitter), &setRandomAngleOffset, &defaultProtectedGetFn, &writeRandomAngleOffset, ""); addProtectedField("RandomArc", TypeF32, Offset(mRandomArc, ParticleAssetEmitter), &setRandomArc, &defaultProtectedGetFn, &writeRandomArc, ""); addProtectedField("FixedAngleOffset", TypeF32, Offset(mFixedAngleOffset, ParticleAssetEmitter), &setFixedAngleOffset, &defaultProtectedGetFn, &writeFixedAngleOffset, ""); addProtectedField("PivotPoint", TypeVector2, Offset(mPivotPoint, ParticleAssetEmitter), &setPivotPoint, &defaultProtectedGetFn, &writePivotPoint, ""); addProtectedField("LinkEmissionRotation", TypeBool, Offset(mLinkEmissionRotation, ParticleAssetEmitter), &setLinkEmissionRotation, &defaultProtectedGetFn, &writeLinkEmissionRotation, ""); addProtectedField("IntenseParticles", TypeBool, Offset(mIntenseParticles, ParticleAssetEmitter), &setIntenseParticles, &defaultProtectedGetFn, &writeIntenseParticles, ""); addProtectedField("SingleParticle", TypeBool, Offset(mSingleParticle, ParticleAssetEmitter), &setSingleParticle, &defaultProtectedGetFn, &writeSingleParticle, ""); addProtectedField("AttachPositionToEmitter", TypeBool, Offset(mAttachPositionToEmitter, ParticleAssetEmitter), &setAttachPositionToEmitter, &defaultProtectedGetFn, &writeAttachPositionToEmitter, ""); addProtectedField("AttachRotationToEmitter", TypeBool, Offset(mAttachRotationToEmitter, ParticleAssetEmitter), &setAttachRotationToEmitter, &defaultProtectedGetFn, &writeAttachRotationToEmitter, ""); addProtectedField("OldestInFront", TypeBool, Offset(mOldestInFront, ParticleAssetEmitter), &setOldestInFront, &defaultProtectedGetFn, &writeOldestInFront, ""); addProtectedField("BlendMode", TypeBool, Offset(mBlendMode, ParticleAssetEmitter), &setBlendMode, &defaultProtectedGetFn, &writeBlendMode, ""); addProtectedField("SrcBlendFactor", TypeEnum, Offset(mSrcBlendFactor, ParticleAssetEmitter), &setSrcBlendFactor, &defaultProtectedGetFn, &writeSrcBlendFactor, 1, &srcBlendFactorTable, ""); addProtectedField("DstBlendFactor", TypeEnum, Offset(mDstBlendFactor, ParticleAssetEmitter), &setDstBlendFactor, &defaultProtectedGetFn, &writeDstBlendFactor, 1, &dstBlendFactorTable, ""); addProtectedField("AlphaTest", TypeF32, Offset(mAlphaTest, ParticleAssetEmitter), &setAlphaTest, &defaultProtectedGetFn, &writeAlphaTest, ""); addProtectedField("Image", TypeImageAssetPtr, Offset(mImageAsset, ParticleAssetEmitter), &setImage, &getImage, &writeImage, ""); addProtectedField("Frame", TypeS32, Offset(mImageFrame, ParticleAssetEmitter), &setImageFrame, &defaultProtectedGetFn, &writeImageFrame, ""); addProtectedField("NamedFrame", TypeString, Offset(mNamedImageFrame, ParticleAssetEmitter), &setNamedImageFrame, &defaultProtectedGetFn, &writeNamedImageFrame, ""); addProtectedField("RandomImageFrame", TypeBool, Offset(mRandomImageFrame, ParticleAssetEmitter), &setRandomImageFrame, &defaultProtectedGetFn, &writeRandomImageFrame, ""); addProtectedField("Animation", TypeAnimationAssetPtr, Offset(mAnimationAsset, ParticleAssetEmitter), &setAnimation, &getAnimation, &writeAnimation, ""); } //------------------------------------------------------------------------------ void ParticleAssetEmitter::copyTo(SimObject* object) { // Fetch particle asset emitter object. ParticleAssetEmitter* pParticleAssetEmitter = static_cast<ParticleAssetEmitter*>( object ); // Sanity! AssertFatal( pParticleAssetEmitter != NULL, "ParticleAssetEmitter::copyTo() - Object is not the correct type."); // Copy parent. Parent::copyTo( object ); // Copy fields. pParticleAssetEmitter->setEmitterName( getEmitterName() ); pParticleAssetEmitter->setEmitterType( getEmitterType() ); pParticleAssetEmitter->setEmitterOffset( getEmitterOffset() ); pParticleAssetEmitter->setEmitterSize( getEmitterSize() ); pParticleAssetEmitter->setEmitterAngle( getEmitterAngle() ); pParticleAssetEmitter->setFixedAspect( getFixedAspect() ); pParticleAssetEmitter->setFixedForceAngle( getFixedForceAngle() ); pParticleAssetEmitter->setOrientationType( getOrientationType() ); pParticleAssetEmitter->setKeepAligned( getKeepAligned() ); pParticleAssetEmitter->setAlignedAngleOffset( getAlignedAngleOffset() ); pParticleAssetEmitter->setRandomAngleOffset( getRandomAngleOffset() ); pParticleAssetEmitter->setRandomArc( getRandomArc() ); pParticleAssetEmitter->setFixedAngleOffset( getFixedAngleOffset() ); pParticleAssetEmitter->setPivotPoint( getPivotPoint() ); pParticleAssetEmitter->setLinkEmissionRotation( getLinkEmissionRotation() ); pParticleAssetEmitter->setIntenseParticles( getIntenseParticles() ); pParticleAssetEmitter->setSingleParticle( getSingleParticle() ); pParticleAssetEmitter->setAttachPositionToEmitter( getAttachPositionToEmitter() ); pParticleAssetEmitter->setAttachRotationToEmitter( getAttachRotationToEmitter() ); pParticleAssetEmitter->setOldestInFront( getOldestInFront() ); pParticleAssetEmitter->setBlendMode( getBlendMode() ); pParticleAssetEmitter->setSrcBlendFactor( getSrcBlendFactor() ); pParticleAssetEmitter->setDstBlendFactor( getDstBlendFactor() ); pParticleAssetEmitter->setAlphaTest( getAlphaTest() ); pParticleAssetEmitter->setRandomImageFrame( getRandomImageFrame() ); // Static provider? if ( pParticleAssetEmitter->isStaticFrameProvider() ) { // Named image frame? if ( pParticleAssetEmitter->isUsingNamedImageFrame() ) pParticleAssetEmitter->setImage( getImage(), getNamedImageFrame() ); else pParticleAssetEmitter->setImage( getImage(), getImageFrame() ); } else { pParticleAssetEmitter->setAnimation( getAnimation() ); } // Copy particle fields. mParticleFields.copyTo( pParticleAssetEmitter->mParticleFields ); } //----------------------------------------------------------------------------- void ParticleAssetEmitter::setEmitterName( const char* pEmitterName ) { // Sanity! AssertFatal( mEmitterName != NULL, "ParticleAssetEmitter::setEmitterName() - Cannot set a NULL particle asset emitter name." ); // Set the emitter name. mEmitterName = StringTable->insert( pEmitterName ); // Refresh the asset. refreshAsset(); } //----------------------------------------------------------------------------- void ParticleAssetEmitter::setOwner( ParticleAsset* pParticleAsset ) { // Sanity! AssertFatal( mOwner == NULL, "ParticleAssetEmitter::setOwner() - Cannot set an owner when one is already assigned." ); // Set owner. mOwner = pParticleAsset; } //------------------------------------------------------------------------------ void ParticleAssetEmitter::setPivotPoint( const Vector2& pivotPoint ) { // Set the pivot point. mPivotPoint = pivotPoint; // Calculate the local pivot AABB. mLocalPivotAABB[0].Set( -0.5f + mPivotPoint.x, -0.5f + mPivotPoint.y ); mLocalPivotAABB[1].Set( 0.5f + mPivotPoint.x, -0.5f + mPivotPoint.y ); mLocalPivotAABB[2].Set( 0.5f + mPivotPoint.x, 0.5f + mPivotPoint.y ); mLocalPivotAABB[3].Set( -0.5f + mPivotPoint.x, 0.5f + mPivotPoint.y ); // Refresh the asset. refreshAsset(); } //------------------------------------------------------------------------------ void ParticleAssetEmitter::setFixedForceAngle( F32 fixedForceAngle ) { // Set Fixed-Force Angle. mFixedForceAngle = fixedForceAngle; // Calculate the angle in radians. const F32 fixedForceAngleRadians = mDegToRad(mFixedForceAngle); // Set Fixed-Force Direction. mFixedForceDirection.Set( mCos(fixedForceAngleRadians), mSin(fixedForceAngleRadians) ); // Refresh the asset. refreshAsset(); } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setImage( const char* pAssetId, U32 frame ) { // Sanity! AssertFatal( pAssetId != NULL, "ParticleAssetEmitter::setImage() - Cannot use a NULL asset Id." ); // Set static mode. mStaticMode = true; // Clear animation asset. mAnimationAsset.clear(); // Set asset Id. mImageAsset = pAssetId; // Is there an asset? if ( mImageAsset.notNull() ) { // Yes, so is the frame valid? if ( frame >= mImageAsset->getFrameCount() ) { // No, so warn. Con::warnf( "ParticleAssetEmitter::setImage() - Invalid frame '%d' for ImageAsset '%s'.", frame, mImageAsset.getAssetId() ); } else { // Yes, so set the frame. mImageFrame = frame; } } else { // No, so reset the image frame. mImageFrame = 0; } // Using a numerical frame index mUsingNamedFrame = false; // Refresh the asset. refreshAsset(); // Return Okay. return true; } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setImage( const char* pAssetId, const char* frameName ) { // Sanity! AssertFatal( pAssetId != NULL, "ParticleAssetEmitter::setImage() - Cannot use a NULL asset Id." ); // Set static mode. mStaticMode = true; // Clear animation asset. mAnimationAsset.clear(); // Set asset Id. mImageAsset = pAssetId; // Is there an asset? if ( mImageAsset.notNull() ) { // Yes, so is the frame valid? if ( !mImageAsset->containsFrame(frameName) ) { // No, so warn. Con::warnf( "ParticleAssetEmitter::setImage() - Invalid frame '%s' for ImageAsset '%s'.", frameName, mImageAsset.getAssetId() ); } else { // Yes, so set the frame. mNamedImageFrame = StringTable->insert(frameName); } } else { // No, so reset the image frame. mNamedImageFrame = StringTable->insert(StringTable->EmptyString); } // Using a named frame index mUsingNamedFrame = true; // Refresh the asset. refreshAsset(); // Return Okay. return true; } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setImageFrame( const U32 frame ) { // Check Existing Image. if ( mImageAsset.isNull() ) { // Warn. Con::warnf("ParticleAssetEmitter::setImageFrame() - Cannot set Frame without existing asset Id."); // Return Here. return false; } // Check Frame Validity. if ( frame >= mImageAsset->getFrameCount() ) { // Warn. Con::warnf( "ParticleAssetEmitter::setImageFrame() - Invalid Frame #%d for asset Id '%s'.", frame, mImageAsset.getAssetId() ); // Return Here. return false; } // Set Frame. mImageFrame = frame; // Using a numerical frame index. mUsingNamedFrame = false; // Refresh the asset. refreshAsset(); // Return Okay. return true; } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setNamedImageFrame( const char* frameName ) { // Check Existing Image. if ( mImageAsset.isNull() ) { // Warn. Con::warnf("ParticleAssetEmitter::setNamedImageFrame() - Cannot set Frame without existing asset Id."); // Return Here. return false; } // Check Frame Validity. if ( !mImageAsset->containsFrame(frameName) ) { // Warn. Con::warnf( "ParticleAssetEmitter::setNamedImageFrame() - Invalid Frame %s for asset Id '%s'.", frameName, mImageAsset.getAssetId() ); // Return Here. return false; } // Set frame. mNamedImageFrame = StringTable->insert(frameName); // Using a named frame index mUsingNamedFrame = true; // Refresh the asset. refreshAsset(); // Return Okay. return true; } //------------------------------------------------------------------------------ bool ParticleAssetEmitter::setAnimation( const char* pAnimationAssetId ) { // Sanity! AssertFatal( pAnimationAssetId != NULL, "ParticleAssetEmitter::setAnimation() - Cannot use NULL asset Id." ); // Set animated mode. mStaticMode = false; // Clear static asset. mImageAsset.clear(); // Set animation asset. mAnimationAsset = pAnimationAssetId; // Refresh the asset. refreshAsset(); return true; } //------------------------------------------------------------------------------ void ParticleAssetEmitter::refreshAsset( void ) { // Finish if no owner. if ( mOwner == NULL ) return; // Refresh the asset. mOwner->refreshAsset(); } //------------------------------------------------------------------------------ void ParticleAssetEmitter::onAssetRefreshed( AssetPtrBase* pAssetPtrBase ) { // Either the image or animation asset has been refreshed to just refresh the // asset that this emitter may belong to. ParticleAssetEmitter::refreshAsset(); } //------------------------------------------------------------------------------ void ParticleAssetEmitter::onTamlCustomWrite( TamlCustomNodes& customNodes ) { // Debug Profiling. PROFILE_SCOPE(ParticleAssetEmitter_OnTamlCustomWrite); // Write the fields. mParticleFields.onTamlCustomWrite( customNodes ); } //----------------------------------------------------------------------------- void ParticleAssetEmitter::onTamlCustomRead( const TamlCustomNodes& customNodes ) { // Debug Profiling. PROFILE_SCOPE(ParticleAssetEmitter_OnTamlCustomRead); // Read the fields. mParticleFields.onTamlCustomRead( customNodes ); } //----------------------------------------------------------------------------- static void WriteCustomTamlSchema( const AbstractClassRep* pClassRep, TiXmlElement* pParentElement ) { // Sanity! AssertFatal( pClassRep != NULL, "ParticleAssetEmitter::WriteCustomTamlSchema() - ClassRep cannot be NULL." ); AssertFatal( pParentElement != NULL, "ParticleAssetEmitter::WriteCustomTamlSchema() - Parent Element cannot be NULL." ); // Write the particle asset emitter fields. ParticleAssetEmitter particleAssetEmitter; particleAssetEmitter.getParticleFields().WriteCustomTamlSchema( pClassRep, pParentElement ); } //----------------------------------------------------------------------------- IMPLEMENT_CONOBJECT_SCHEMA(ParticleAssetEmitter, WriteCustomTamlSchema);
43.988782
203
0.633611
close-code
c1418e3b4ac3e222cf1b47cb88cce5125c1cb8b3
14,361
cpp
C++
android/android_23/frameworks/base/media/libstagefright/codecs/aacdec/synthesis_sub_band.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_23/frameworks/base/media/libstagefright/codecs/aacdec/synthesis_sub_band.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
android/android_23/frameworks/base/media/libstagefright/codecs/aacdec/synthesis_sub_band.cpp
yakuizhao/intel-vaapi-driver
b2bb0383352694941826543a171b557efac2219b
[ "MIT" ]
null
null
null
/* ------------------------------------------------------------------ * Copyright (C) 1998-2009 PacketVideo * * 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. * ------------------------------------------------------------------- */ /* Filename: synthesis_sub_band.c ------------------------------------------------------------------------------ REVISION HISTORY Who: Date: MM/DD/YYYY Description: ------------------------------------------------------------------------------ INPUT AND OUTPUT DEFINITIONS Int32 vec[], Input vector, 32-bit const Int32 *cosTerms, Cosine Terms Int32 *scratch_mem Scratch memory ------------------------------------------------------------------------------ FUNCTION DESCRIPTION Implement root squared of a number ------------------------------------------------------------------------------ REQUIREMENTS ------------------------------------------------------------------------------ REFERENCES ------------------------------------------------------------------------------ PSEUDO-CODE ------------------------------------------------------------------------------ */ /*---------------------------------------------------------------------------- ; INCLUDES ----------------------------------------------------------------------------*/ #ifdef AAC_PLUS #include "pv_audio_type_defs.h" #include "fxp_mul32.h" #include "dct64.h" #include "synthesis_sub_band.h" #include "mdst.h" #include "dct16.h" /*---------------------------------------------------------------------------- ; MACROS ; Define module specific macros here ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; DEFINES ; Include all pre-processor statements here. Include conditional ; compile variables also. ----------------------------------------------------------------------------*/ #define Qfmt_30(x) (Int32)(x*((Int32)(1<<30)) + (x>=0?0.5F:-0.5F)) #define Qfmt_25(x) (Int32)(x*((Int32)(1<<25))*(1.5625F) + (x>=0?0.5F:-0.5F)) #define SCALE_DOWN_LP Qfmt_30(0.075000F) /* 3/40 */ #define SCALE_DOWN_HQ Qfmt_30(0.009375F*0.64F) /* 3/40 * 1/8 */ /*---------------------------------------------------------------------------- ; LOCAL FUNCTION DEFINITIONS ; Function Prototype declaration ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; LOCAL STORE/BUFFER/POINTER DEFINITIONS ; Variable declaration - defined here and used outside this module ----------------------------------------------------------------------------*/ const Int32 CosTable_64[64] = { Qfmt_25(0.50003765191555F), Qfmt_25(40.74468810335183F), Qfmt_25(0.50033903744282F), Qfmt_25(13.58429025728446F), Qfmt_25(0.50094271763809F), Qfmt_25(8.15384860246681F), Qfmt_25(0.50185051748424F), Qfmt_25(5.82768837784465F), Qfmt_25(0.50306519130137F), Qfmt_25(4.53629093696936F), Qfmt_25(0.50459044322165F), Qfmt_25(3.71524273832697F), Qfmt_25(0.50643095492855F), Qfmt_25(3.14746219178191F), Qfmt_25(0.50859242104981F), Qfmt_25(2.73164502877394F), Qfmt_25(0.51108159270668F), Qfmt_25(2.41416000025008F), Qfmt_25(0.51390632984754F), Qfmt_25(2.16395781875198F), Qfmt_25(0.51707566313349F), Qfmt_25(1.96181784857117F), Qfmt_25(0.52059986630189F), Qfmt_25(1.79520521907789F), Qfmt_25(0.52449054011472F), Qfmt_25(1.65559652426412F), Qfmt_25(0.52876070920749F), Qfmt_25(1.53699410085250F), Qfmt_25(0.53342493339713F), Qfmt_25(1.43505508844143F), Qfmt_25(0.53849943529198F), Qfmt_25(1.34655762820629F), Qfmt_25(0.54400224638178F), Qfmt_25(1.26906117169912F), Qfmt_25(0.54995337418324F), Qfmt_25(1.20068325572942F), Qfmt_25(0.55637499348989F), Qfmt_25(1.13994867510150F), Qfmt_25(0.56329166534170F), Qfmt_25(1.08568506425801F), Qfmt_25(0.57073058801215F), Qfmt_25(1.03694904091039F), Qfmt_25(0.57872188513482F), Qfmt_25(0.99297296126755F), Qfmt_25(0.58729893709379F), Qfmt_25(0.95312587439212F), Qfmt_25(0.59649876302446F), Qfmt_25(0.91688444618465F), Qfmt_25(0.60636246227215F), Qfmt_25(0.88381100455962F), Qfmt_25(0.61693572600507F), Qfmt_25(0.85353675100661F), Qfmt_25(0.62826943197077F), Qfmt_25(0.82574877386279F), Qfmt_25(0.64042033824166F), Qfmt_25(0.80017989562169F), Qfmt_25(0.65345189537513F), Qfmt_25(0.77660065823396F), Qfmt_25(0.66743520092634F), Qfmt_25(0.75481293911653F), Qfmt_25(0.68245012597642F), Qfmt_25(0.73464482364786F), Qfmt_25(0.69858665064723F), Qfmt_25(0.71594645497057F), }; /*---------------------------------------------------------------------------- ; EXTERNAL FUNCTION REFERENCES ; Declare functions defined elsewhere and referenced in this module ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES ; Declare variables used in this module but defined elsewhere ----------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------- ; FUNCTION CODE ----------------------------------------------------------------------------*/ void synthesis_sub_band_LC(Int32 Sr[], Int16 data[]) { Int32 *temp_o1 = (Int32 *) & data[0]; Int i; Int32 *pt_temp_e; Int32 *pt_temp_o = temp_o1; Int32 *pt_temp_x = &Sr[63]; Int32 temp1; Int32 temp2; Int32 temp3; Int32 temp11; Int16 *pt_data_1; Int16 *pt_data_2; Int32 *pt_Sr_1 = Sr; Int16 tmp1; Int16 tmp2; Int16 tmp11; Int16 tmp22; const Int32 *pt_cosTerms = CosTable_48; temp2 = *(pt_temp_x--); for (i = 20; i != 0; i--) { temp1 = *(pt_Sr_1); temp3 = *(pt_cosTerms++); *(pt_Sr_1++) = temp1 + temp2; *(pt_temp_o++) = fxp_mul32_Q31((temp1 - temp2), temp3) << 1; temp2 = *(pt_temp_x--); } for (i = 12; i != 0; i--) { temp1 = *(pt_Sr_1); temp3 = *(pt_cosTerms++); *(pt_Sr_1++) = temp1 + temp2; *(pt_temp_o++) = fxp_mul32_Q26((temp1 - temp2), temp3); temp2 = *(pt_temp_x--); } pv_split_LC(temp_o1, &Sr[32]); dct_16(temp_o1, 1); // Even terms dct_16(&Sr[32], 1); // Odd terms /* merge */ pt_Sr_1 = &temp_o1[31]; pt_temp_e = &temp_o1[15]; pt_temp_o = &Sr[47]; temp1 = *(pt_temp_o--); *(pt_Sr_1--) = temp1; for (i = 5; i != 0; i--) { temp2 = *(pt_temp_o--); *(pt_Sr_1--) = *(pt_temp_e--); *(pt_Sr_1--) = temp1 + temp2; temp3 = *(pt_temp_o--); *(pt_Sr_1--) = *(pt_temp_e--); *(pt_Sr_1--) = temp2 + temp3; temp1 = *(pt_temp_o--); *(pt_Sr_1--) = *(pt_temp_e--); *(pt_Sr_1--) = temp1 + temp3; } pv_split_LC(Sr, &Sr[32]); dct_16(Sr, 1); // Even terms dct_16(&Sr[32], 1); // Odd terms pt_temp_x = &temp_o1[31]; pt_temp_e = &Sr[15]; pt_temp_o = &Sr[47]; pt_data_1 = &data[95]; temp2 = *(pt_temp_x--); temp11 = *(pt_temp_x--); temp1 = *(pt_temp_o--); *(pt_data_1--) = (Int16) fxp_mul32_Q31(temp2, SCALE_DOWN_LP); *(pt_data_1--) = (Int16) fxp_mul32_Q31(temp1, SCALE_DOWN_LP); for (i = 5; i != 0; i--) { *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp2), SCALE_DOWN_LP); temp3 = *(pt_temp_x--); *(pt_data_1--) = (Int16) fxp_mul32_Q31(*(pt_temp_e--), SCALE_DOWN_LP); temp2 = *(pt_temp_o--); *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp3), SCALE_DOWN_LP); temp11 = *(pt_temp_x--); *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp1 + temp2), SCALE_DOWN_LP); *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp3), SCALE_DOWN_LP); temp1 = *(pt_temp_x--); *(pt_data_1--) = (Int16) fxp_mul32_Q31(*(pt_temp_e--), SCALE_DOWN_LP); temp3 = *(pt_temp_o--); *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp1), SCALE_DOWN_LP); temp11 = *(pt_temp_x--); *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp2 + temp3), SCALE_DOWN_LP); *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp1), SCALE_DOWN_LP); temp2 = *(pt_temp_x--); *(pt_data_1--) = (Int16) fxp_mul32_Q31(*(pt_temp_e--), SCALE_DOWN_LP); temp1 = *(pt_temp_o--); *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp2), SCALE_DOWN_LP); temp11 = *(pt_temp_x--); *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp1 + temp3), SCALE_DOWN_LP); } *(pt_data_1--) = (Int16) fxp_mul32_Q31((temp11 + temp2), SCALE_DOWN_LP); *(pt_data_1--) = (Int16) fxp_mul32_Q31(*(pt_temp_e), SCALE_DOWN_LP); /* ---- merge ends---- */ pt_data_1 = &data[95]; pt_data_2 = &data[96]; *(pt_data_2++) = 0; tmp1 = *(pt_data_1--); tmp2 = *(pt_data_1--); tmp11 = *(pt_data_1--); tmp22 = *(pt_data_1--); for (i = 7; i != 0; i--) { *(pt_data_2++) = (-tmp1); *(pt_data_2++) = (-tmp2); *(pt_data_2++) = (-tmp11); *(pt_data_2++) = (-tmp22); tmp1 = *(pt_data_1--); tmp2 = *(pt_data_1--); tmp11 = *(pt_data_1--); tmp22 = *(pt_data_1--); } *(pt_data_2++) = (-tmp1); *(pt_data_2++) = (-tmp2); *(pt_data_2++) = (-tmp11); pt_data_2 = &data[0]; *(pt_data_2++) = tmp22; tmp1 = *(pt_data_1--); tmp2 = *(pt_data_1--); tmp11 = *(pt_data_1--); tmp22 = *(pt_data_1--); for (i = 7; i != 0; i--) { *(pt_data_2++) = tmp1; *(pt_data_2++) = tmp2; *(pt_data_2++) = tmp11; *(pt_data_2++) = tmp22; tmp1 = *(pt_data_1--); tmp2 = *(pt_data_1--); tmp11 = *(pt_data_1--); tmp22 = *(pt_data_1--); } *(pt_data_2++) = tmp1; *(pt_data_2++) = tmp2; *(pt_data_2++) = tmp11; *(pt_data_2) = tmp22; } void synthesis_sub_band_LC_down_sampled(Int32 Sr[], Int16 data[]) { Int i ; Int16 *pt_data_1; pt_data_1 = &data[0]; dct_32(Sr); for (i = 0; i < 16; i++) { pt_data_1[ i] = (Int16)(Sr[16-i] >> 5); pt_data_1[16+i] = (Int16)(Sr[i] >> 5); pt_data_1[32+i] = (Int16)(Sr[16+i] >> 5); } for (i = 0; i < 15; i++) { pt_data_1[49+i] = (Int16)(-Sr[31-i] >> 5); } pt_data_1[48] = 0; } #ifdef HQ_SBR void synthesis_sub_band(Int32 Sr[], Int32 Si[], Int16 data[]) { Int32 i ; Int16 *pt_data_1; Int16 *pt_data_2; Int32 *pt_Sr_1; Int32 *pt_Sr_2; Int32 *pt_Si_1; Int32 *pt_Si_2; Int32 tmp1; Int32 tmp2; Int32 tmp3; Int32 tmp4; Int32 cosx; const Int32 *pt_CosTable = CosTable_64; pt_Sr_1 = &Sr[0]; pt_Sr_2 = &Sr[63]; pt_Si_1 = &Si[0]; pt_Si_2 = &Si[63]; tmp3 = *pt_Sr_1; for (i = 32; i != 0; i--) { tmp4 = *pt_Si_2; cosx = *(pt_CosTable++); *(pt_Sr_1++) = fxp_mul32_Q31(tmp3, cosx); tmp3 = *pt_Si_1; *(pt_Si_1++) = fxp_mul32_Q31(tmp4, cosx); tmp4 = *pt_Sr_2; cosx = *(pt_CosTable++); *(pt_Si_2--) = fxp_mul32_Q31(tmp3, cosx); *(pt_Sr_2--) = fxp_mul32_Q31(tmp4, cosx); tmp3 = *pt_Sr_1; } dct_64(Sr, (Int32 *)data); dct_64(Si, (Int32 *)data); pt_data_1 = &data[0]; pt_data_2 = &data[127]; pt_Sr_1 = &Sr[0]; pt_Si_1 = &Si[0]; tmp1 = *(pt_Sr_1++); tmp3 = *(pt_Sr_1++); tmp2 = *(pt_Si_1++); tmp4 = *(pt_Si_1++); for (i = 32; i != 0; i--) { *(pt_data_1++) = (Int16) fxp_mul32_Q31((tmp2 - tmp1), SCALE_DOWN_HQ); *(pt_data_1++) = (Int16) fxp_mul32_Q31(-(tmp3 + tmp4), SCALE_DOWN_HQ); *(pt_data_2--) = (Int16) fxp_mul32_Q31((tmp1 + tmp2), SCALE_DOWN_HQ); *(pt_data_2--) = (Int16) fxp_mul32_Q31((tmp3 - tmp4), SCALE_DOWN_HQ); tmp1 = *(pt_Sr_1++); tmp3 = *(pt_Sr_1++); tmp2 = *(pt_Si_1++); tmp4 = *(pt_Si_1++); } } const Int32 exp_m0_25_phi[32] = { 0x7FFEFE6E, 0x7FEAFB4A, 0x7FC2F827, 0x7F87F505, 0x7F38F1E4, 0x7ED6EEC6, 0x7E60EBAB, 0x7DD6E892, 0x7D3AE57D, 0x7C89E26D, 0x7BC6DF61, 0x7AEFDC59, 0x7A06D958, 0x790AD65C, 0x77FBD367, 0x76D9D079, 0x75A6CD92, 0x7460CAB2, 0x7308C7DB, 0x719EC50D, 0x7023C248, 0x6E97BF8C, 0x6CF9BCDA, 0x6B4BBA33, 0x698CB796, 0x67BDB505, 0x65DEB27F, 0x63EFB005, 0x61F1AD97, 0x5FE4AB36, 0x5DC8A8E2, 0x5B9DA69C }; void synthesis_sub_band_down_sampled(Int32 Sr[], Int32 Si[], Int16 data[]) { Int16 k; Int16 *pt_data_1; Int32 exp_m0_25; const Int32 *pt_exp = exp_m0_25_phi; Int32 *XX = Sr; Int32 *YY = (Int32 *)data; Int32 tmp1; Int32 tmp2; for (k = 0; k < 32; k++) { exp_m0_25 = *(pt_exp++); tmp1 = Sr[k]; tmp2 = Si[k]; XX[k] = cmplx_mul32_by_16(-tmp1, tmp2, exp_m0_25); YY[31-k] = cmplx_mul32_by_16(tmp2, tmp1, exp_m0_25); } mdct_32(XX); mdct_32(YY); for (k = 0; k < 32; k++) { Si[k] = YY[k]; } pt_data_1 = data; for (k = 0; k < 16; k++) { *(pt_data_1++) = (Int16)((XX[2*k ] + Si[2*k ]) >> 14); *(pt_data_1++) = (Int16)((XX[2*k+1] - Si[2*k+1]) >> 14); } for (k = 15; k > -1; k--) { *(pt_data_1++) = (Int16)(-(XX[2*k+1] + Si[2*k+1]) >> 14); *(pt_data_1++) = (Int16)(-(XX[2*k ] - Si[2*k ]) >> 14); } } #endif /* HQ_SBR */ #endif /* AAC_PLUS */
29.671488
123
0.499478
yakuizhao
c142a8fbfd203162e8cf3259cd848e0a7d879477
439
cpp
C++
3rdparty/pytorch/torch/csrc/api/src/jit.cpp
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
3rdparty/pytorch/torch/csrc/api/src/jit.cpp
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
3rdparty/pytorch/torch/csrc/api/src/jit.cpp
WoodoLee/TorchCraft
999f68aab9e7d50ed3ae138297226dc95fefc458
[ "MIT" ]
null
null
null
#include <torch/jit.h> #include <torch/csrc/jit/script/compiler.h> #include <torch/csrc/jit/stack.h> #include <memory> #include <string> namespace torch { namespace jit { std::shared_ptr<script::Module> compile(const std::string& source) { auto module = std::make_shared<script::Module>(); defineMethodsInModule(module, source, script::nativeResolver, /*self=*/nullptr); return module; } } // namespace jit } // namespace torch
21.95
82
0.722096
WoodoLee
c144552f3079ed40d3570ff9f7e2090fedade582
606
hpp
C++
android-28/android/util/TimeUtils.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/util/TimeUtils.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-28/android/util/TimeUtils.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../JObject.hpp" class JString; namespace java::util { class TimeZone; } namespace android::util { class TimeUtils : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit TimeUtils(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} TimeUtils(QJniObject obj); // Constructors // Methods static java::util::TimeZone getTimeZone(jint arg0, jboolean arg1, jlong arg2, JString arg3); static JString getTimeZoneDatabaseVersion(); }; } // namespace android::util
20.2
150
0.69637
YJBeetle
c1448d8b832318d1fc649c638df8ce0147489690
62,276
cc
C++
protocal/control/control_conf.pb.cc
racestart/g2r
d115ebaab13829d716750eab2ebdcc51d79ff32e
[ "Apache-2.0" ]
1
2020-03-05T12:49:21.000Z
2020-03-05T12:49:21.000Z
protocal/control/control_conf.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
null
null
null
protocal/control/control_conf.pb.cc
gA4ss/g2r
a6e2ee5758ab59fd95704e3c3090dd234fbfb2c9
[ "Apache-2.0" ]
1
2020-03-25T15:06:39.000Z
2020-03-25T15:06:39.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: control/control_conf.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "control/control_conf.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace apollo { namespace control { namespace { const ::google::protobuf::Descriptor* ControlConf_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* ControlConf_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* ControlConf_ControllerType_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_control_2fcontrol_5fconf_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AssignDesc_control_2fcontrol_5fconf_2eproto() { protobuf_AddDesc_control_2fcontrol_5fconf_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "control/control_conf.proto"); GOOGLE_CHECK(file != NULL); ControlConf_descriptor_ = file->message_type(0); static const int ControlConf_offsets_[18] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, control_period_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, max_planning_interval_sec_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, max_planning_delay_threshold_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, driving_mode_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, action_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, soft_estop_brake_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, active_controllers_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, max_steering_percentage_allowed_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, max_status_interval_sec_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, lat_controller_conf_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, lon_controller_conf_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, trajectory_period_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, chassis_period_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, localization_period_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, minimum_speed_resolution_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, mpc_controller_conf_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, query_relative_time_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, minimum_speed_protection_), }; ControlConf_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( ControlConf_descriptor_, ControlConf::default_instance_, ControlConf_offsets_, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, _has_bits_[0]), -1, -1, sizeof(ControlConf), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(ControlConf, _internal_metadata_), -1); ControlConf_ControllerType_descriptor_ = ControlConf_descriptor_->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); inline void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_control_2fcontrol_5fconf_2eproto); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( ControlConf_descriptor_, &ControlConf::default_instance()); } } // namespace void protobuf_ShutdownFile_control_2fcontrol_5fconf_2eproto() { delete ControlConf::default_instance_; delete ControlConf_reflection_; } void protobuf_AddDesc_control_2fcontrol_5fconf_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AddDesc_control_2fcontrol_5fconf_2eproto() { static bool already_here = false; if (already_here) return; already_here = true; GOOGLE_PROTOBUF_VERIFY_VERSION; ::apollo::canbus::protobuf_AddDesc_canbus_2fchassis_2eproto(); ::apollo::control::protobuf_AddDesc_control_2fpad_5fmsg_2eproto(); ::apollo::control::protobuf_AddDesc_control_2flat_5fcontroller_5fconf_2eproto(); ::apollo::control::protobuf_AddDesc_control_2flon_5fcontroller_5fconf_2eproto(); ::apollo::control::protobuf_AddDesc_control_2fmpc_5fcontroller_5fconf_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\032control/control_conf.proto\022\016apollo.con" "trol\032\024canbus/chassis.proto\032\025control/pad_" "msg.proto\032!control/lat_controller_conf.p" "roto\032!control/lon_controller_conf.proto\032" "!control/mpc_controller_conf.proto\"\302\006\n\013C" "ontrolConf\022\026\n\016control_period\030\001 \001(\001\022!\n\031ma" "x_planning_interval_sec\030\002 \001(\001\022$\n\034max_pla" "nning_delay_threshold\030\003 \001(\001\0228\n\014driving_m" "ode\030\004 \001(\0162\".apollo.canbus.Chassis.Drivin" "gMode\022-\n\006action\030\005 \001(\0162\035.apollo.control.D" "rivingAction\022\030\n\020soft_estop_brake\030\006 \001(\001\022F" "\n\022active_controllers\030\007 \003(\0162*.apollo.cont" "rol.ControlConf.ControllerType\022\'\n\037max_st" "eering_percentage_allowed\030\010 \001(\005\022\037\n\027max_s" "tatus_interval_sec\030\t \001(\001\022>\n\023lat_controll" "er_conf\030\n \001(\0132!.apollo.control.LatContro" "llerConf\022>\n\023lon_controller_conf\030\013 \001(\0132!." "apollo.control.LonControllerConf\022\031\n\021traj" "ectory_period\030\014 \001(\001\022\026\n\016chassis_period\030\r " "\001(\001\022\033\n\023localization_period\030\016 \001(\001\022 \n\030mini" "mum_speed_resolution\030\017 \001(\001\022>\n\023mpc_contro" "ller_conf\030\020 \001(\0132!.apollo.control.MPCCont" "rollerConf\022\033\n\023query_relative_time\030\021 \001(\001\022" " \n\030minimum_speed_protection\030\022 \001(\001\"L\n\016Con" "trollerType\022\022\n\016LAT_CONTROLLER\020\000\022\022\n\016LON_C" "ONTROLLER\020\001\022\022\n\016MPC_CONTROLLER\020\002", 1031); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "control/control_conf.proto", &protobuf_RegisterTypes); ControlConf::default_instance_ = new ControlConf(); ControlConf::default_instance_->InitAsDefaultInstance(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_control_2fcontrol_5fconf_2eproto); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_control_2fcontrol_5fconf_2eproto { StaticDescriptorInitializer_control_2fcontrol_5fconf_2eproto() { protobuf_AddDesc_control_2fcontrol_5fconf_2eproto(); } } static_descriptor_initializer_control_2fcontrol_5fconf_2eproto_; // =================================================================== const ::google::protobuf::EnumDescriptor* ControlConf_ControllerType_descriptor() { protobuf_AssignDescriptorsOnce(); return ControlConf_ControllerType_descriptor_; } bool ControlConf_ControllerType_IsValid(int value) { switch(value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const ControlConf_ControllerType ControlConf::LAT_CONTROLLER; const ControlConf_ControllerType ControlConf::LON_CONTROLLER; const ControlConf_ControllerType ControlConf::MPC_CONTROLLER; const ControlConf_ControllerType ControlConf::ControllerType_MIN; const ControlConf_ControllerType ControlConf::ControllerType_MAX; const int ControlConf::ControllerType_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int ControlConf::kControlPeriodFieldNumber; const int ControlConf::kMaxPlanningIntervalSecFieldNumber; const int ControlConf::kMaxPlanningDelayThresholdFieldNumber; const int ControlConf::kDrivingModeFieldNumber; const int ControlConf::kActionFieldNumber; const int ControlConf::kSoftEstopBrakeFieldNumber; const int ControlConf::kActiveControllersFieldNumber; const int ControlConf::kMaxSteeringPercentageAllowedFieldNumber; const int ControlConf::kMaxStatusIntervalSecFieldNumber; const int ControlConf::kLatControllerConfFieldNumber; const int ControlConf::kLonControllerConfFieldNumber; const int ControlConf::kTrajectoryPeriodFieldNumber; const int ControlConf::kChassisPeriodFieldNumber; const int ControlConf::kLocalizationPeriodFieldNumber; const int ControlConf::kMinimumSpeedResolutionFieldNumber; const int ControlConf::kMpcControllerConfFieldNumber; const int ControlConf::kQueryRelativeTimeFieldNumber; const int ControlConf::kMinimumSpeedProtectionFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 ControlConf::ControlConf() : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); // @@protoc_insertion_point(constructor:apollo.control.ControlConf) } void ControlConf::InitAsDefaultInstance() { lat_controller_conf_ = const_cast< ::apollo::control::LatControllerConf*>(&::apollo::control::LatControllerConf::default_instance()); lon_controller_conf_ = const_cast< ::apollo::control::LonControllerConf*>(&::apollo::control::LonControllerConf::default_instance()); mpc_controller_conf_ = const_cast< ::apollo::control::MPCControllerConf*>(&::apollo::control::MPCControllerConf::default_instance()); } ControlConf::ControlConf(const ControlConf& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); MergeFrom(from); // @@protoc_insertion_point(copy_constructor:apollo.control.ControlConf) } void ControlConf::SharedCtor() { _cached_size_ = 0; control_period_ = 0; max_planning_interval_sec_ = 0; max_planning_delay_threshold_ = 0; driving_mode_ = 0; action_ = 0; soft_estop_brake_ = 0; max_steering_percentage_allowed_ = 0; max_status_interval_sec_ = 0; lat_controller_conf_ = NULL; lon_controller_conf_ = NULL; trajectory_period_ = 0; chassis_period_ = 0; localization_period_ = 0; minimum_speed_resolution_ = 0; mpc_controller_conf_ = NULL; query_relative_time_ = 0; minimum_speed_protection_ = 0; ::memset(_has_bits_, 0, sizeof(_has_bits_)); } ControlConf::~ControlConf() { // @@protoc_insertion_point(destructor:apollo.control.ControlConf) SharedDtor(); } void ControlConf::SharedDtor() { if (this != default_instance_) { delete lat_controller_conf_; delete lon_controller_conf_; delete mpc_controller_conf_; } } void ControlConf::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* ControlConf::descriptor() { protobuf_AssignDescriptorsOnce(); return ControlConf_descriptor_; } const ControlConf& ControlConf::default_instance() { if (default_instance_ == NULL) protobuf_AddDesc_control_2fcontrol_5fconf_2eproto(); return *default_instance_; } ControlConf* ControlConf::default_instance_ = NULL; ControlConf* ControlConf::New(::google::protobuf::Arena* arena) const { ControlConf* n = new ControlConf; if (arena != NULL) { arena->Own(n); } return n; } void ControlConf::Clear() { // @@protoc_insertion_point(message_clear_start:apollo.control.ControlConf) #if defined(__clang__) #define ZR_HELPER_(f) \ _Pragma("clang diagnostic push") \ _Pragma("clang diagnostic ignored \"-Winvalid-offsetof\"") \ __builtin_offsetof(ControlConf, f) \ _Pragma("clang diagnostic pop") #else #define ZR_HELPER_(f) reinterpret_cast<char*>(\ &reinterpret_cast<ControlConf*>(16)->f) #endif #define ZR_(first, last) do {\ ::memset(&first, 0,\ ZR_HELPER_(last) - ZR_HELPER_(first) + sizeof(last));\ } while (0) if (_has_bits_[0 / 32] & 191u) { ZR_(control_period_, soft_estop_brake_); max_steering_percentage_allowed_ = 0; } if (_has_bits_[8 / 32] & 65280u) { ZR_(trajectory_period_, minimum_speed_resolution_); max_status_interval_sec_ = 0; if (has_lat_controller_conf()) { if (lat_controller_conf_ != NULL) lat_controller_conf_->::apollo::control::LatControllerConf::Clear(); } if (has_lon_controller_conf()) { if (lon_controller_conf_ != NULL) lon_controller_conf_->::apollo::control::LonControllerConf::Clear(); } if (has_mpc_controller_conf()) { if (mpc_controller_conf_ != NULL) mpc_controller_conf_->::apollo::control::MPCControllerConf::Clear(); } } ZR_(query_relative_time_, minimum_speed_protection_); #undef ZR_HELPER_ #undef ZR_ active_controllers_.Clear(); ::memset(_has_bits_, 0, sizeof(_has_bits_)); if (_internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->Clear(); } } bool ControlConf::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:apollo.control.ControlConf) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(16383); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional double control_period = 1; case 1: { if (tag == 9) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &control_period_))); set_has_control_period(); } else { goto handle_unusual; } if (input->ExpectTag(17)) goto parse_max_planning_interval_sec; break; } // optional double max_planning_interval_sec = 2; case 2: { if (tag == 17) { parse_max_planning_interval_sec: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &max_planning_interval_sec_))); set_has_max_planning_interval_sec(); } else { goto handle_unusual; } if (input->ExpectTag(25)) goto parse_max_planning_delay_threshold; break; } // optional double max_planning_delay_threshold = 3; case 3: { if (tag == 25) { parse_max_planning_delay_threshold: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &max_planning_delay_threshold_))); set_has_max_planning_delay_threshold(); } else { goto handle_unusual; } if (input->ExpectTag(32)) goto parse_driving_mode; break; } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; case 4: { if (tag == 32) { parse_driving_mode: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::canbus::Chassis_DrivingMode_IsValid(value)) { set_driving_mode(static_cast< ::apollo::canbus::Chassis_DrivingMode >(value)); } else { mutable_unknown_fields()->AddVarint(4, value); } } else { goto handle_unusual; } if (input->ExpectTag(40)) goto parse_action; break; } // optional .apollo.control.DrivingAction action = 5; case 5: { if (tag == 40) { parse_action: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::control::DrivingAction_IsValid(value)) { set_action(static_cast< ::apollo::control::DrivingAction >(value)); } else { mutable_unknown_fields()->AddVarint(5, value); } } else { goto handle_unusual; } if (input->ExpectTag(49)) goto parse_soft_estop_brake; break; } // optional double soft_estop_brake = 6; case 6: { if (tag == 49) { parse_soft_estop_brake: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &soft_estop_brake_))); set_has_soft_estop_brake(); } else { goto handle_unusual; } if (input->ExpectTag(56)) goto parse_active_controllers; break; } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; case 7: { if (tag == 56) { parse_active_controllers: int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); if (::apollo::control::ControlConf_ControllerType_IsValid(value)) { add_active_controllers(static_cast< ::apollo::control::ControlConf_ControllerType >(value)); } else { mutable_unknown_fields()->AddVarint(7, value); } } else if (tag == 58) { DO_((::google::protobuf::internal::WireFormat::ReadPackedEnumPreserveUnknowns( input, 7, ::apollo::control::ControlConf_ControllerType_IsValid, mutable_unknown_fields(), this->mutable_active_controllers()))); } else { goto handle_unusual; } if (input->ExpectTag(56)) goto parse_active_controllers; if (input->ExpectTag(64)) goto parse_max_steering_percentage_allowed; break; } // optional int32 max_steering_percentage_allowed = 8; case 8: { if (tag == 64) { parse_max_steering_percentage_allowed: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &max_steering_percentage_allowed_))); set_has_max_steering_percentage_allowed(); } else { goto handle_unusual; } if (input->ExpectTag(73)) goto parse_max_status_interval_sec; break; } // optional double max_status_interval_sec = 9; case 9: { if (tag == 73) { parse_max_status_interval_sec: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &max_status_interval_sec_))); set_has_max_status_interval_sec(); } else { goto handle_unusual; } if (input->ExpectTag(82)) goto parse_lat_controller_conf; break; } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; case 10: { if (tag == 82) { parse_lat_controller_conf: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_lat_controller_conf())); } else { goto handle_unusual; } if (input->ExpectTag(90)) goto parse_lon_controller_conf; break; } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; case 11: { if (tag == 90) { parse_lon_controller_conf: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_lon_controller_conf())); } else { goto handle_unusual; } if (input->ExpectTag(97)) goto parse_trajectory_period; break; } // optional double trajectory_period = 12; case 12: { if (tag == 97) { parse_trajectory_period: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &trajectory_period_))); set_has_trajectory_period(); } else { goto handle_unusual; } if (input->ExpectTag(105)) goto parse_chassis_period; break; } // optional double chassis_period = 13; case 13: { if (tag == 105) { parse_chassis_period: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &chassis_period_))); set_has_chassis_period(); } else { goto handle_unusual; } if (input->ExpectTag(113)) goto parse_localization_period; break; } // optional double localization_period = 14; case 14: { if (tag == 113) { parse_localization_period: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &localization_period_))); set_has_localization_period(); } else { goto handle_unusual; } if (input->ExpectTag(121)) goto parse_minimum_speed_resolution; break; } // optional double minimum_speed_resolution = 15; case 15: { if (tag == 121) { parse_minimum_speed_resolution: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &minimum_speed_resolution_))); set_has_minimum_speed_resolution(); } else { goto handle_unusual; } if (input->ExpectTag(130)) goto parse_mpc_controller_conf; break; } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; case 16: { if (tag == 130) { parse_mpc_controller_conf: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_mpc_controller_conf())); } else { goto handle_unusual; } if (input->ExpectTag(137)) goto parse_query_relative_time; break; } // optional double query_relative_time = 17; case 17: { if (tag == 137) { parse_query_relative_time: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &query_relative_time_))); set_has_query_relative_time(); } else { goto handle_unusual; } if (input->ExpectTag(145)) goto parse_minimum_speed_protection; break; } // optional double minimum_speed_protection = 18; case 18: { if (tag == 145) { parse_minimum_speed_protection: DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< double, ::google::protobuf::internal::WireFormatLite::TYPE_DOUBLE>( input, &minimum_speed_protection_))); set_has_minimum_speed_protection(); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:apollo.control.ControlConf) return true; failure: // @@protoc_insertion_point(parse_failure:apollo.control.ControlConf) return false; #undef DO_ } void ControlConf::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:apollo.control.ControlConf) // optional double control_period = 1; if (has_control_period()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(1, this->control_period(), output); } // optional double max_planning_interval_sec = 2; if (has_max_planning_interval_sec()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(2, this->max_planning_interval_sec(), output); } // optional double max_planning_delay_threshold = 3; if (has_max_planning_delay_threshold()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(3, this->max_planning_delay_threshold(), output); } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; if (has_driving_mode()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 4, this->driving_mode(), output); } // optional .apollo.control.DrivingAction action = 5; if (has_action()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 5, this->action(), output); } // optional double soft_estop_brake = 6; if (has_soft_estop_brake()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(6, this->soft_estop_brake(), output); } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; for (int i = 0; i < this->active_controllers_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 7, this->active_controllers(i), output); } // optional int32 max_steering_percentage_allowed = 8; if (has_max_steering_percentage_allowed()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(8, this->max_steering_percentage_allowed(), output); } // optional double max_status_interval_sec = 9; if (has_max_status_interval_sec()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(9, this->max_status_interval_sec(), output); } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; if (has_lat_controller_conf()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 10, *this->lat_controller_conf_, output); } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; if (has_lon_controller_conf()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 11, *this->lon_controller_conf_, output); } // optional double trajectory_period = 12; if (has_trajectory_period()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(12, this->trajectory_period(), output); } // optional double chassis_period = 13; if (has_chassis_period()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(13, this->chassis_period(), output); } // optional double localization_period = 14; if (has_localization_period()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(14, this->localization_period(), output); } // optional double minimum_speed_resolution = 15; if (has_minimum_speed_resolution()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(15, this->minimum_speed_resolution(), output); } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; if (has_mpc_controller_conf()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 16, *this->mpc_controller_conf_, output); } // optional double query_relative_time = 17; if (has_query_relative_time()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(17, this->query_relative_time(), output); } // optional double minimum_speed_protection = 18; if (has_minimum_speed_protection()) { ::google::protobuf::internal::WireFormatLite::WriteDouble(18, this->minimum_speed_protection(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:apollo.control.ControlConf) } ::google::protobuf::uint8* ControlConf::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:apollo.control.ControlConf) // optional double control_period = 1; if (has_control_period()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(1, this->control_period(), target); } // optional double max_planning_interval_sec = 2; if (has_max_planning_interval_sec()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(2, this->max_planning_interval_sec(), target); } // optional double max_planning_delay_threshold = 3; if (has_max_planning_delay_threshold()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(3, this->max_planning_delay_threshold(), target); } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; if (has_driving_mode()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 4, this->driving_mode(), target); } // optional .apollo.control.DrivingAction action = 5; if (has_action()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 5, this->action(), target); } // optional double soft_estop_brake = 6; if (has_soft_estop_brake()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(6, this->soft_estop_brake(), target); } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; for (int i = 0; i < this->active_controllers_size(); i++) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 7, this->active_controllers(i), target); } // optional int32 max_steering_percentage_allowed = 8; if (has_max_steering_percentage_allowed()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(8, this->max_steering_percentage_allowed(), target); } // optional double max_status_interval_sec = 9; if (has_max_status_interval_sec()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(9, this->max_status_interval_sec(), target); } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; if (has_lat_controller_conf()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 10, *this->lat_controller_conf_, false, target); } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; if (has_lon_controller_conf()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 11, *this->lon_controller_conf_, false, target); } // optional double trajectory_period = 12; if (has_trajectory_period()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(12, this->trajectory_period(), target); } // optional double chassis_period = 13; if (has_chassis_period()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(13, this->chassis_period(), target); } // optional double localization_period = 14; if (has_localization_period()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(14, this->localization_period(), target); } // optional double minimum_speed_resolution = 15; if (has_minimum_speed_resolution()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(15, this->minimum_speed_resolution(), target); } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; if (has_mpc_controller_conf()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 16, *this->mpc_controller_conf_, false, target); } // optional double query_relative_time = 17; if (has_query_relative_time()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(17, this->query_relative_time(), target); } // optional double minimum_speed_protection = 18; if (has_minimum_speed_protection()) { target = ::google::protobuf::internal::WireFormatLite::WriteDoubleToArray(18, this->minimum_speed_protection(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:apollo.control.ControlConf) return target; } int ControlConf::ByteSize() const { // @@protoc_insertion_point(message_byte_size_start:apollo.control.ControlConf) int total_size = 0; if (_has_bits_[0 / 32] & 191u) { // optional double control_period = 1; if (has_control_period()) { total_size += 1 + 8; } // optional double max_planning_interval_sec = 2; if (has_max_planning_interval_sec()) { total_size += 1 + 8; } // optional double max_planning_delay_threshold = 3; if (has_max_planning_delay_threshold()) { total_size += 1 + 8; } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; if (has_driving_mode()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->driving_mode()); } // optional .apollo.control.DrivingAction action = 5; if (has_action()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->action()); } // optional double soft_estop_brake = 6; if (has_soft_estop_brake()) { total_size += 1 + 8; } // optional int32 max_steering_percentage_allowed = 8; if (has_max_steering_percentage_allowed()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->max_steering_percentage_allowed()); } } if (_has_bits_[8 / 32] & 65280u) { // optional double max_status_interval_sec = 9; if (has_max_status_interval_sec()) { total_size += 1 + 8; } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; if (has_lat_controller_conf()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->lat_controller_conf_); } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; if (has_lon_controller_conf()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->lon_controller_conf_); } // optional double trajectory_period = 12; if (has_trajectory_period()) { total_size += 1 + 8; } // optional double chassis_period = 13; if (has_chassis_period()) { total_size += 1 + 8; } // optional double localization_period = 14; if (has_localization_period()) { total_size += 1 + 8; } // optional double minimum_speed_resolution = 15; if (has_minimum_speed_resolution()) { total_size += 1 + 8; } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; if (has_mpc_controller_conf()) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->mpc_controller_conf_); } } if (_has_bits_[16 / 32] & 196608u) { // optional double query_relative_time = 17; if (has_query_relative_time()) { total_size += 2 + 8; } // optional double minimum_speed_protection = 18; if (has_minimum_speed_protection()) { total_size += 2 + 8; } } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; { int data_size = 0; for (int i = 0; i < this->active_controllers_size(); i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->active_controllers(i)); } total_size += 1 * this->active_controllers_size() + data_size; } if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( unknown_fields()); } GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = total_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void ControlConf::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:apollo.control.ControlConf) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } const ControlConf* source = ::google::protobuf::internal::DynamicCastToGenerated<const ControlConf>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:apollo.control.ControlConf) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:apollo.control.ControlConf) MergeFrom(*source); } } void ControlConf::MergeFrom(const ControlConf& from) { // @@protoc_insertion_point(class_specific_merge_from_start:apollo.control.ControlConf) if (GOOGLE_PREDICT_FALSE(&from == this)) { ::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__); } active_controllers_.MergeFrom(from.active_controllers_); if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) { if (from.has_control_period()) { set_control_period(from.control_period()); } if (from.has_max_planning_interval_sec()) { set_max_planning_interval_sec(from.max_planning_interval_sec()); } if (from.has_max_planning_delay_threshold()) { set_max_planning_delay_threshold(from.max_planning_delay_threshold()); } if (from.has_driving_mode()) { set_driving_mode(from.driving_mode()); } if (from.has_action()) { set_action(from.action()); } if (from.has_soft_estop_brake()) { set_soft_estop_brake(from.soft_estop_brake()); } if (from.has_max_steering_percentage_allowed()) { set_max_steering_percentage_allowed(from.max_steering_percentage_allowed()); } } if (from._has_bits_[8 / 32] & (0xffu << (8 % 32))) { if (from.has_max_status_interval_sec()) { set_max_status_interval_sec(from.max_status_interval_sec()); } if (from.has_lat_controller_conf()) { mutable_lat_controller_conf()->::apollo::control::LatControllerConf::MergeFrom(from.lat_controller_conf()); } if (from.has_lon_controller_conf()) { mutable_lon_controller_conf()->::apollo::control::LonControllerConf::MergeFrom(from.lon_controller_conf()); } if (from.has_trajectory_period()) { set_trajectory_period(from.trajectory_period()); } if (from.has_chassis_period()) { set_chassis_period(from.chassis_period()); } if (from.has_localization_period()) { set_localization_period(from.localization_period()); } if (from.has_minimum_speed_resolution()) { set_minimum_speed_resolution(from.minimum_speed_resolution()); } if (from.has_mpc_controller_conf()) { mutable_mpc_controller_conf()->::apollo::control::MPCControllerConf::MergeFrom(from.mpc_controller_conf()); } } if (from._has_bits_[16 / 32] & (0xffu << (16 % 32))) { if (from.has_query_relative_time()) { set_query_relative_time(from.query_relative_time()); } if (from.has_minimum_speed_protection()) { set_minimum_speed_protection(from.minimum_speed_protection()); } } if (from._internal_metadata_.have_unknown_fields()) { mutable_unknown_fields()->MergeFrom(from.unknown_fields()); } } void ControlConf::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:apollo.control.ControlConf) if (&from == this) return; Clear(); MergeFrom(from); } void ControlConf::CopyFrom(const ControlConf& from) { // @@protoc_insertion_point(class_specific_copy_from_start:apollo.control.ControlConf) if (&from == this) return; Clear(); MergeFrom(from); } bool ControlConf::IsInitialized() const { return true; } void ControlConf::Swap(ControlConf* other) { if (other == this) return; InternalSwap(other); } void ControlConf::InternalSwap(ControlConf* other) { std::swap(control_period_, other->control_period_); std::swap(max_planning_interval_sec_, other->max_planning_interval_sec_); std::swap(max_planning_delay_threshold_, other->max_planning_delay_threshold_); std::swap(driving_mode_, other->driving_mode_); std::swap(action_, other->action_); std::swap(soft_estop_brake_, other->soft_estop_brake_); active_controllers_.UnsafeArenaSwap(&other->active_controllers_); std::swap(max_steering_percentage_allowed_, other->max_steering_percentage_allowed_); std::swap(max_status_interval_sec_, other->max_status_interval_sec_); std::swap(lat_controller_conf_, other->lat_controller_conf_); std::swap(lon_controller_conf_, other->lon_controller_conf_); std::swap(trajectory_period_, other->trajectory_period_); std::swap(chassis_period_, other->chassis_period_); std::swap(localization_period_, other->localization_period_); std::swap(minimum_speed_resolution_, other->minimum_speed_resolution_); std::swap(mpc_controller_conf_, other->mpc_controller_conf_); std::swap(query_relative_time_, other->query_relative_time_); std::swap(minimum_speed_protection_, other->minimum_speed_protection_); std::swap(_has_bits_[0], other->_has_bits_[0]); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata ControlConf::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = ControlConf_descriptor_; metadata.reflection = ControlConf_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // ControlConf // optional double control_period = 1; bool ControlConf::has_control_period() const { return (_has_bits_[0] & 0x00000001u) != 0; } void ControlConf::set_has_control_period() { _has_bits_[0] |= 0x00000001u; } void ControlConf::clear_has_control_period() { _has_bits_[0] &= ~0x00000001u; } void ControlConf::clear_control_period() { control_period_ = 0; clear_has_control_period(); } double ControlConf::control_period() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.control_period) return control_period_; } void ControlConf::set_control_period(double value) { set_has_control_period(); control_period_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.control_period) } // optional double max_planning_interval_sec = 2; bool ControlConf::has_max_planning_interval_sec() const { return (_has_bits_[0] & 0x00000002u) != 0; } void ControlConf::set_has_max_planning_interval_sec() { _has_bits_[0] |= 0x00000002u; } void ControlConf::clear_has_max_planning_interval_sec() { _has_bits_[0] &= ~0x00000002u; } void ControlConf::clear_max_planning_interval_sec() { max_planning_interval_sec_ = 0; clear_has_max_planning_interval_sec(); } double ControlConf::max_planning_interval_sec() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.max_planning_interval_sec) return max_planning_interval_sec_; } void ControlConf::set_max_planning_interval_sec(double value) { set_has_max_planning_interval_sec(); max_planning_interval_sec_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.max_planning_interval_sec) } // optional double max_planning_delay_threshold = 3; bool ControlConf::has_max_planning_delay_threshold() const { return (_has_bits_[0] & 0x00000004u) != 0; } void ControlConf::set_has_max_planning_delay_threshold() { _has_bits_[0] |= 0x00000004u; } void ControlConf::clear_has_max_planning_delay_threshold() { _has_bits_[0] &= ~0x00000004u; } void ControlConf::clear_max_planning_delay_threshold() { max_planning_delay_threshold_ = 0; clear_has_max_planning_delay_threshold(); } double ControlConf::max_planning_delay_threshold() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.max_planning_delay_threshold) return max_planning_delay_threshold_; } void ControlConf::set_max_planning_delay_threshold(double value) { set_has_max_planning_delay_threshold(); max_planning_delay_threshold_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.max_planning_delay_threshold) } // optional .apollo.canbus.Chassis.DrivingMode driving_mode = 4; bool ControlConf::has_driving_mode() const { return (_has_bits_[0] & 0x00000008u) != 0; } void ControlConf::set_has_driving_mode() { _has_bits_[0] |= 0x00000008u; } void ControlConf::clear_has_driving_mode() { _has_bits_[0] &= ~0x00000008u; } void ControlConf::clear_driving_mode() { driving_mode_ = 0; clear_has_driving_mode(); } ::apollo::canbus::Chassis_DrivingMode ControlConf::driving_mode() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.driving_mode) return static_cast< ::apollo::canbus::Chassis_DrivingMode >(driving_mode_); } void ControlConf::set_driving_mode(::apollo::canbus::Chassis_DrivingMode value) { assert(::apollo::canbus::Chassis_DrivingMode_IsValid(value)); set_has_driving_mode(); driving_mode_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.driving_mode) } // optional .apollo.control.DrivingAction action = 5; bool ControlConf::has_action() const { return (_has_bits_[0] & 0x00000010u) != 0; } void ControlConf::set_has_action() { _has_bits_[0] |= 0x00000010u; } void ControlConf::clear_has_action() { _has_bits_[0] &= ~0x00000010u; } void ControlConf::clear_action() { action_ = 0; clear_has_action(); } ::apollo::control::DrivingAction ControlConf::action() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.action) return static_cast< ::apollo::control::DrivingAction >(action_); } void ControlConf::set_action(::apollo::control::DrivingAction value) { assert(::apollo::control::DrivingAction_IsValid(value)); set_has_action(); action_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.action) } // optional double soft_estop_brake = 6; bool ControlConf::has_soft_estop_brake() const { return (_has_bits_[0] & 0x00000020u) != 0; } void ControlConf::set_has_soft_estop_brake() { _has_bits_[0] |= 0x00000020u; } void ControlConf::clear_has_soft_estop_brake() { _has_bits_[0] &= ~0x00000020u; } void ControlConf::clear_soft_estop_brake() { soft_estop_brake_ = 0; clear_has_soft_estop_brake(); } double ControlConf::soft_estop_brake() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.soft_estop_brake) return soft_estop_brake_; } void ControlConf::set_soft_estop_brake(double value) { set_has_soft_estop_brake(); soft_estop_brake_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.soft_estop_brake) } // repeated .apollo.control.ControlConf.ControllerType active_controllers = 7; int ControlConf::active_controllers_size() const { return active_controllers_.size(); } void ControlConf::clear_active_controllers() { active_controllers_.Clear(); } ::apollo::control::ControlConf_ControllerType ControlConf::active_controllers(int index) const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.active_controllers) return static_cast< ::apollo::control::ControlConf_ControllerType >(active_controllers_.Get(index)); } void ControlConf::set_active_controllers(int index, ::apollo::control::ControlConf_ControllerType value) { assert(::apollo::control::ControlConf_ControllerType_IsValid(value)); active_controllers_.Set(index, value); // @@protoc_insertion_point(field_set:apollo.control.ControlConf.active_controllers) } void ControlConf::add_active_controllers(::apollo::control::ControlConf_ControllerType value) { assert(::apollo::control::ControlConf_ControllerType_IsValid(value)); active_controllers_.Add(value); // @@protoc_insertion_point(field_add:apollo.control.ControlConf.active_controllers) } const ::google::protobuf::RepeatedField<int>& ControlConf::active_controllers() const { // @@protoc_insertion_point(field_list:apollo.control.ControlConf.active_controllers) return active_controllers_; } ::google::protobuf::RepeatedField<int>* ControlConf::mutable_active_controllers() { // @@protoc_insertion_point(field_mutable_list:apollo.control.ControlConf.active_controllers) return &active_controllers_; } // optional int32 max_steering_percentage_allowed = 8; bool ControlConf::has_max_steering_percentage_allowed() const { return (_has_bits_[0] & 0x00000080u) != 0; } void ControlConf::set_has_max_steering_percentage_allowed() { _has_bits_[0] |= 0x00000080u; } void ControlConf::clear_has_max_steering_percentage_allowed() { _has_bits_[0] &= ~0x00000080u; } void ControlConf::clear_max_steering_percentage_allowed() { max_steering_percentage_allowed_ = 0; clear_has_max_steering_percentage_allowed(); } ::google::protobuf::int32 ControlConf::max_steering_percentage_allowed() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.max_steering_percentage_allowed) return max_steering_percentage_allowed_; } void ControlConf::set_max_steering_percentage_allowed(::google::protobuf::int32 value) { set_has_max_steering_percentage_allowed(); max_steering_percentage_allowed_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.max_steering_percentage_allowed) } // optional double max_status_interval_sec = 9; bool ControlConf::has_max_status_interval_sec() const { return (_has_bits_[0] & 0x00000100u) != 0; } void ControlConf::set_has_max_status_interval_sec() { _has_bits_[0] |= 0x00000100u; } void ControlConf::clear_has_max_status_interval_sec() { _has_bits_[0] &= ~0x00000100u; } void ControlConf::clear_max_status_interval_sec() { max_status_interval_sec_ = 0; clear_has_max_status_interval_sec(); } double ControlConf::max_status_interval_sec() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.max_status_interval_sec) return max_status_interval_sec_; } void ControlConf::set_max_status_interval_sec(double value) { set_has_max_status_interval_sec(); max_status_interval_sec_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.max_status_interval_sec) } // optional .apollo.control.LatControllerConf lat_controller_conf = 10; bool ControlConf::has_lat_controller_conf() const { return (_has_bits_[0] & 0x00000200u) != 0; } void ControlConf::set_has_lat_controller_conf() { _has_bits_[0] |= 0x00000200u; } void ControlConf::clear_has_lat_controller_conf() { _has_bits_[0] &= ~0x00000200u; } void ControlConf::clear_lat_controller_conf() { if (lat_controller_conf_ != NULL) lat_controller_conf_->::apollo::control::LatControllerConf::Clear(); clear_has_lat_controller_conf(); } const ::apollo::control::LatControllerConf& ControlConf::lat_controller_conf() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.lat_controller_conf) return lat_controller_conf_ != NULL ? *lat_controller_conf_ : *default_instance_->lat_controller_conf_; } ::apollo::control::LatControllerConf* ControlConf::mutable_lat_controller_conf() { set_has_lat_controller_conf(); if (lat_controller_conf_ == NULL) { lat_controller_conf_ = new ::apollo::control::LatControllerConf; } // @@protoc_insertion_point(field_mutable:apollo.control.ControlConf.lat_controller_conf) return lat_controller_conf_; } ::apollo::control::LatControllerConf* ControlConf::release_lat_controller_conf() { // @@protoc_insertion_point(field_release:apollo.control.ControlConf.lat_controller_conf) clear_has_lat_controller_conf(); ::apollo::control::LatControllerConf* temp = lat_controller_conf_; lat_controller_conf_ = NULL; return temp; } void ControlConf::set_allocated_lat_controller_conf(::apollo::control::LatControllerConf* lat_controller_conf) { delete lat_controller_conf_; lat_controller_conf_ = lat_controller_conf; if (lat_controller_conf) { set_has_lat_controller_conf(); } else { clear_has_lat_controller_conf(); } // @@protoc_insertion_point(field_set_allocated:apollo.control.ControlConf.lat_controller_conf) } // optional .apollo.control.LonControllerConf lon_controller_conf = 11; bool ControlConf::has_lon_controller_conf() const { return (_has_bits_[0] & 0x00000400u) != 0; } void ControlConf::set_has_lon_controller_conf() { _has_bits_[0] |= 0x00000400u; } void ControlConf::clear_has_lon_controller_conf() { _has_bits_[0] &= ~0x00000400u; } void ControlConf::clear_lon_controller_conf() { if (lon_controller_conf_ != NULL) lon_controller_conf_->::apollo::control::LonControllerConf::Clear(); clear_has_lon_controller_conf(); } const ::apollo::control::LonControllerConf& ControlConf::lon_controller_conf() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.lon_controller_conf) return lon_controller_conf_ != NULL ? *lon_controller_conf_ : *default_instance_->lon_controller_conf_; } ::apollo::control::LonControllerConf* ControlConf::mutable_lon_controller_conf() { set_has_lon_controller_conf(); if (lon_controller_conf_ == NULL) { lon_controller_conf_ = new ::apollo::control::LonControllerConf; } // @@protoc_insertion_point(field_mutable:apollo.control.ControlConf.lon_controller_conf) return lon_controller_conf_; } ::apollo::control::LonControllerConf* ControlConf::release_lon_controller_conf() { // @@protoc_insertion_point(field_release:apollo.control.ControlConf.lon_controller_conf) clear_has_lon_controller_conf(); ::apollo::control::LonControllerConf* temp = lon_controller_conf_; lon_controller_conf_ = NULL; return temp; } void ControlConf::set_allocated_lon_controller_conf(::apollo::control::LonControllerConf* lon_controller_conf) { delete lon_controller_conf_; lon_controller_conf_ = lon_controller_conf; if (lon_controller_conf) { set_has_lon_controller_conf(); } else { clear_has_lon_controller_conf(); } // @@protoc_insertion_point(field_set_allocated:apollo.control.ControlConf.lon_controller_conf) } // optional double trajectory_period = 12; bool ControlConf::has_trajectory_period() const { return (_has_bits_[0] & 0x00000800u) != 0; } void ControlConf::set_has_trajectory_period() { _has_bits_[0] |= 0x00000800u; } void ControlConf::clear_has_trajectory_period() { _has_bits_[0] &= ~0x00000800u; } void ControlConf::clear_trajectory_period() { trajectory_period_ = 0; clear_has_trajectory_period(); } double ControlConf::trajectory_period() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.trajectory_period) return trajectory_period_; } void ControlConf::set_trajectory_period(double value) { set_has_trajectory_period(); trajectory_period_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.trajectory_period) } // optional double chassis_period = 13; bool ControlConf::has_chassis_period() const { return (_has_bits_[0] & 0x00001000u) != 0; } void ControlConf::set_has_chassis_period() { _has_bits_[0] |= 0x00001000u; } void ControlConf::clear_has_chassis_period() { _has_bits_[0] &= ~0x00001000u; } void ControlConf::clear_chassis_period() { chassis_period_ = 0; clear_has_chassis_period(); } double ControlConf::chassis_period() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.chassis_period) return chassis_period_; } void ControlConf::set_chassis_period(double value) { set_has_chassis_period(); chassis_period_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.chassis_period) } // optional double localization_period = 14; bool ControlConf::has_localization_period() const { return (_has_bits_[0] & 0x00002000u) != 0; } void ControlConf::set_has_localization_period() { _has_bits_[0] |= 0x00002000u; } void ControlConf::clear_has_localization_period() { _has_bits_[0] &= ~0x00002000u; } void ControlConf::clear_localization_period() { localization_period_ = 0; clear_has_localization_period(); } double ControlConf::localization_period() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.localization_period) return localization_period_; } void ControlConf::set_localization_period(double value) { set_has_localization_period(); localization_period_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.localization_period) } // optional double minimum_speed_resolution = 15; bool ControlConf::has_minimum_speed_resolution() const { return (_has_bits_[0] & 0x00004000u) != 0; } void ControlConf::set_has_minimum_speed_resolution() { _has_bits_[0] |= 0x00004000u; } void ControlConf::clear_has_minimum_speed_resolution() { _has_bits_[0] &= ~0x00004000u; } void ControlConf::clear_minimum_speed_resolution() { minimum_speed_resolution_ = 0; clear_has_minimum_speed_resolution(); } double ControlConf::minimum_speed_resolution() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.minimum_speed_resolution) return minimum_speed_resolution_; } void ControlConf::set_minimum_speed_resolution(double value) { set_has_minimum_speed_resolution(); minimum_speed_resolution_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.minimum_speed_resolution) } // optional .apollo.control.MPCControllerConf mpc_controller_conf = 16; bool ControlConf::has_mpc_controller_conf() const { return (_has_bits_[0] & 0x00008000u) != 0; } void ControlConf::set_has_mpc_controller_conf() { _has_bits_[0] |= 0x00008000u; } void ControlConf::clear_has_mpc_controller_conf() { _has_bits_[0] &= ~0x00008000u; } void ControlConf::clear_mpc_controller_conf() { if (mpc_controller_conf_ != NULL) mpc_controller_conf_->::apollo::control::MPCControllerConf::Clear(); clear_has_mpc_controller_conf(); } const ::apollo::control::MPCControllerConf& ControlConf::mpc_controller_conf() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.mpc_controller_conf) return mpc_controller_conf_ != NULL ? *mpc_controller_conf_ : *default_instance_->mpc_controller_conf_; } ::apollo::control::MPCControllerConf* ControlConf::mutable_mpc_controller_conf() { set_has_mpc_controller_conf(); if (mpc_controller_conf_ == NULL) { mpc_controller_conf_ = new ::apollo::control::MPCControllerConf; } // @@protoc_insertion_point(field_mutable:apollo.control.ControlConf.mpc_controller_conf) return mpc_controller_conf_; } ::apollo::control::MPCControllerConf* ControlConf::release_mpc_controller_conf() { // @@protoc_insertion_point(field_release:apollo.control.ControlConf.mpc_controller_conf) clear_has_mpc_controller_conf(); ::apollo::control::MPCControllerConf* temp = mpc_controller_conf_; mpc_controller_conf_ = NULL; return temp; } void ControlConf::set_allocated_mpc_controller_conf(::apollo::control::MPCControllerConf* mpc_controller_conf) { delete mpc_controller_conf_; mpc_controller_conf_ = mpc_controller_conf; if (mpc_controller_conf) { set_has_mpc_controller_conf(); } else { clear_has_mpc_controller_conf(); } // @@protoc_insertion_point(field_set_allocated:apollo.control.ControlConf.mpc_controller_conf) } // optional double query_relative_time = 17; bool ControlConf::has_query_relative_time() const { return (_has_bits_[0] & 0x00010000u) != 0; } void ControlConf::set_has_query_relative_time() { _has_bits_[0] |= 0x00010000u; } void ControlConf::clear_has_query_relative_time() { _has_bits_[0] &= ~0x00010000u; } void ControlConf::clear_query_relative_time() { query_relative_time_ = 0; clear_has_query_relative_time(); } double ControlConf::query_relative_time() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.query_relative_time) return query_relative_time_; } void ControlConf::set_query_relative_time(double value) { set_has_query_relative_time(); query_relative_time_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.query_relative_time) } // optional double minimum_speed_protection = 18; bool ControlConf::has_minimum_speed_protection() const { return (_has_bits_[0] & 0x00020000u) != 0; } void ControlConf::set_has_minimum_speed_protection() { _has_bits_[0] |= 0x00020000u; } void ControlConf::clear_has_minimum_speed_protection() { _has_bits_[0] &= ~0x00020000u; } void ControlConf::clear_minimum_speed_protection() { minimum_speed_protection_ = 0; clear_has_minimum_speed_protection(); } double ControlConf::minimum_speed_protection() const { // @@protoc_insertion_point(field_get:apollo.control.ControlConf.minimum_speed_protection) return minimum_speed_protection_; } void ControlConf::set_minimum_speed_protection(double value) { set_has_minimum_speed_protection(); minimum_speed_protection_ = value; // @@protoc_insertion_point(field_set:apollo.control.ControlConf.minimum_speed_protection) } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace control } // namespace apollo // @@protoc_insertion_point(global_scope)
38.066015
135
0.730843
racestart
c1479ada0fad341ed4cad2268e40ee87fc39b67b
132
cpp
C++
benchmark/fenwick/micro/add_byte23bit.cpp
pacman616/hybrid-fenwick-tree
84e7cc8aa84b87937b98d85f3c2ed1998c0d79af
[ "MIT" ]
4
2019-01-10T17:55:43.000Z
2019-11-26T09:33:38.000Z
benchmark/fenwick/micro/add_byte23bit.cpp
pacman616/hybrid-fenwick-tree
84e7cc8aa84b87937b98d85f3c2ed1998c0d79af
[ "MIT" ]
null
null
null
benchmark/fenwick/micro/add_byte23bit.cpp
pacman616/hybrid-fenwick-tree
84e7cc8aa84b87937b98d85f3c2ed1998c0d79af
[ "MIT" ]
null
null
null
#define __HFT_BENCHMARK_FUNCTION__ add<Hybrid<ByteL, BitF, 64, 23>>(name + "/" + "Byte23Bit", queries, re); #include "../micro.cpp"
44
107
0.689394
pacman616
c147f758f577b5d5cff44c73a348ecdb6e887950
23,713
cxx
C++
src/RootPlotFrame.cxx
fermi-lat/st_graph
8f63c2467131068ffa5d214fbe62110280a14204
[ "BSD-3-Clause" ]
null
null
null
src/RootPlotFrame.cxx
fermi-lat/st_graph
8f63c2467131068ffa5d214fbe62110280a14204
[ "BSD-3-Clause" ]
null
null
null
src/RootPlotFrame.cxx
fermi-lat/st_graph
8f63c2467131068ffa5d214fbe62110280a14204
[ "BSD-3-Clause" ]
null
null
null
/** \file RootPlotFrame.cxx \brief Implementation for RootPlotFrame class. \author James Peachey, HEASARC/GSSC */ #include <algorithm> #include <cctype> #include <list> #include <map> #include <sstream> #include <stdexcept> #include <utility> #include "TAxis.h" #include "TCanvas.h" #include "TLatex.h" #include "TMarker.h" #include "TGFrame.h" #include "TGraph.h" #include "TGraphAsymmErrors.h" #include "TH2.h" #include "TMultiGraph.h" #include "TRootEmbeddedCanvas.h" #include "RootPlot.h" #include "RootPlotFrame.h" #include "st_graph/IEventReceiver.h" namespace st_graph { class StMarker : public TMarker { public: StMarker(Marker & marker); virtual ~StMarker(); virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); virtual void Draw(Option_t * option = ""); virtual void SetColor(Color_t tcolor = 1); virtual void SetTextAngle(Float_t angle); private: Marker * m_marker; TLatex * m_label; }; class StLatex : public TLatex { public: StLatex(Marker & marker, StMarker & st_marker); virtual void ExecuteEvent(Int_t event, Int_t px, Int_t py); private: Marker * m_marker; StMarker * m_st_marker; }; class StEmbeddedCanvas : public TRootEmbeddedCanvas { public: typedef std::list<StMarker *> MarkerCont_t; StEmbeddedCanvas(RootPlotFrame * parent, const char * name = "0", const TGWindow * p = 0, UInt_t w = 10, UInt_t h = 10); virtual ~StEmbeddedCanvas(); virtual Bool_t HandleContainerButton(Event_t * event); void addMarker(Marker & marker); void reset(); void setHandleEvents(bool handle_events); private: MarkerCont_t m_marker_cont; RootPlotFrame * m_parent; double m_press_x; double m_press_y; UInt_t m_width; UInt_t m_height; bool m_handle_events; }; StMarker::StMarker(Marker & marker): TMarker(marker.m_x, marker.m_y, 23), m_marker(&marker), m_label(0) { if (!marker.m_text.empty()) m_label = new StLatex(marker, *this); } StMarker::~StMarker() { delete m_label; } void StMarker::ExecuteEvent(Int_t event, Int_t px, Int_t py) { double current_x = fX; double current_y = fY; TMarker::ExecuteEvent(event, px, py); if (fX != current_x) { if (0 != m_label) m_label->SetX(fX); } if (fY != current_y) { if (0 != m_label) m_label->SetY(fY); } } void StMarker::Draw(Option_t * option) { if (0 != m_label) m_label->Draw(option); TMarker::Draw(option); } void StMarker::SetColor(Color_t tcolor) { if (0 != m_label) m_label->SetTextColor(tcolor); TMarker::SetMarkerColor(tcolor); } void StMarker::SetTextAngle(Float_t angle) { if (0 != m_label) m_label->SetTextAngle(angle); } StLatex::StLatex(Marker & marker, StMarker & st_marker): TLatex(marker.m_x, marker.m_y, (" " + marker.m_text).c_str()), m_marker(&marker), m_st_marker(&st_marker) {} void StLatex::ExecuteEvent(Int_t event, Int_t px, Int_t py) { double current_x = fX; double current_y = fY; TLatex::ExecuteEvent(event, px, py); if (fX != current_x) { m_st_marker->SetX(fX); m_marker->m_x = fX; } if (fY != current_y) { m_st_marker->SetY(fY); m_marker->m_y = fY; } } StEmbeddedCanvas::StEmbeddedCanvas(RootPlotFrame * parent, const char * name, const TGWindow * p, UInt_t w, UInt_t h): TRootEmbeddedCanvas(name, p, w, h), m_marker_cont(), m_parent(parent), m_press_x(0.), m_press_y(0.), m_width(w), m_height(h), m_handle_events(false) {} StEmbeddedCanvas::~StEmbeddedCanvas() { for (MarkerCont_t::reverse_iterator itor = m_marker_cont.rbegin(); itor != m_marker_cont.rend(); ++itor) { delete *itor; } } Bool_t StEmbeddedCanvas::HandleContainerButton(Event_t * event) { if (!m_handle_events) return TRootEmbeddedCanvas::HandleContainerButton(event); Bool_t status = kTRUE; bool root_handles_event = true; if (0 != event) { // Determine if this event is inside the frame. double x_min, x_max, y_min, y_max; fCanvas->GetRangeAxis(x_min, y_min, x_max, y_max); double event_x, event_y; fCanvas->AbsPixeltoXY(event->fX, event->fY, event_x, event_y); bool in_frame = x_min <= event_x && event_x <= x_max && y_min <= event_y && event_y <= y_max; Int_t button = event->fCode; if (kButton3 == button) { // Button 3 events inside the plot window are handled by the event handler. if (in_frame) { root_handles_event = false; if (kButtonRelease == event->fType) { IEventReceiver * receiver = m_parent->getReceiver(); double x; double y; fCanvas->AbsPixeltoXY(event->fX, event->fY, x, y); if (0 != receiver) receiver->rightClicked(m_parent, x, y); } } } else { // Find the object with which this event is associated. TObjLink * obj_link = 0; fCanvas->Pick(event->fX, event->fY, obj_link); // See if the associated object is a marker or label. TObject * obj = 0; if (0 != obj_link && 0 != (obj = obj_link->GetObject())) { std::string class_name = obj->ClassName(); if (class_name != "TLatex" && class_name != "TMarker" && kButtonRelease != event->fType) { if (in_frame) { // These events are used to zoom: remap them to look like they come from the X axis. // Add 1 pixel to make the event be slightly below the axis, and 1 more to prevent // round-off errors resulting from the conversion from graph coordinate to pixels. event->fY = fCanvas->YtoAbsPixel(y_min) + 2; } } } } } if (root_handles_event) { status = TRootEmbeddedCanvas::HandleContainerButton(event); } return status; } void StEmbeddedCanvas::addMarker(Marker & marker) { StMarker * st_marker = new StMarker(marker); st_marker->SetTextAngle(45); st_marker->SetColor(int(marker.m_color)); st_marker->Draw(); m_marker_cont.push_back(st_marker); } void StEmbeddedCanvas::reset() { for (MarkerCont_t::reverse_iterator itor = m_marker_cont.rbegin(); itor != m_marker_cont.rend(); ++itor) { delete *itor; } m_marker_cont.clear(); } void StEmbeddedCanvas::setHandleEvents(bool handle_events) { m_handle_events = handle_events; } RootPlotFrame::RootPlotFrame(IFrame * parent, const std::string & title, unsigned int width, unsigned int height, bool delete_parent): RootFrame(parent, 0, 0, delete_parent), m_axes(3), m_plots(), m_tgraphs(), m_title(title), m_canvas(0), m_multi_graph(0), m_th2d(0), m_dimensionality(0) { // Send event messages back to parent. m_receiver = m_parent->getReceiver(); // Hook together Root primitives. TGCompositeFrame * root_frame = dynamic_cast<TGCompositeFrame *>(m_parent->getTGFrame()); if (0 == root_frame) throw std::logic_error("RootPlotFrame constructor was passed a parent frame which cannot contain other Root frames"); TGCanvas * top_canvas = new TGCanvas(root_frame, width, height); TGViewPort * vp = top_canvas->GetViewPort(); root_frame->AddFrame(top_canvas); // Create a special Root TGCanvas which is suitable for embedding plots. //TRootEmbeddedCanvas * plot_canvas = new TRootEmbeddedCanvas(createRootName("TRootEmbeddedCanvas", this).c_str(), vp, vp->GetWidth(), vp->GetHeight(), kFixedSize); StEmbeddedCanvas * plot_canvas = new StEmbeddedCanvas(this, createRootName("StEmbeddedCanvas", this).c_str(), vp, vp->GetWidth(), vp->GetHeight()); top_canvas->SetContainer(plot_canvas); plot_canvas->SetAutoFit(kFALSE); m_canvas = plot_canvas; m_frame = top_canvas; } // Note m_frame will be deleted in the base class destructor. RootPlotFrame::~RootPlotFrame() { // Note: This appears more complicated than necessary, but be careful changing it. Under some circumstances, // a RootPlot needs to delete its parent, but the parent will always attempt to delete the RootPlot in the // process. Thus it is important to ensure the child is detached at the right times to prevent deleting // the parent and/or the child twice. reset(); // Delete Root widgets. delete m_multi_graph; delete m_th2d; } void RootPlotFrame::display() { RootFrame::display(); // Save current pad. TVirtualPad * save_pad = gPad; // Select embedded canvas for drawing. gPad = m_canvas->GetCanvas(); try { // Handle log/linear scaling. if (0 < m_dimensionality) gPad->SetLogx(Axis::eLog == m_axes[0].getScaleMode() ? 1 : 0); if (1 < m_dimensionality) gPad->SetLogy(Axis::eLog == m_axes[1].getScaleMode() ? 1 : 0); if (2 < m_dimensionality) gPad->SetLogz(Axis::eLog == m_axes[2].getScaleMode() ? 1 : 0); // Modifying axes must be done through Root TAxis objects. std::vector<TAxis *> root_axes(3); // Display plot correctly for the current dimensionality. Get Root axes objects. if (m_dimensionality == 2) display2d(root_axes); else if (m_dimensionality == 3) display3d(root_axes); // Flags indicating whether titles have been set. std::vector<bool> title_set(3, false); // Loop over all dimensions, setting axis titles as needed. for (unsigned int index = 0; index != m_dimensionality; ++index) { // If title was not already set, set it. const std::string & title(m_axes[index].getTitle()); if (!title_set[index] && !title.empty()) { root_axes[index]->SetTitle(title.c_str()); root_axes[index]->CenterTitle(kTRUE); title_set[index] = true; } } // Get titles from IPlots. for (std::list<RootPlot *>::iterator itor = m_plots.begin(); itor != m_plots.end(); ++itor) { // Loop over plots, displaying each one's labels. std::vector<Marker> & marker((*itor)->getMarkers()); for (std::vector<Marker>::iterator itor = marker.begin(); itor != marker.end(); ++itor) { m_canvas->addMarker(*itor); } } } catch (...) { gPad = save_pad; throw; } // Force complete update of the display. gPad->Modified(); gPad->Update(); // Restore current pad. gPad = save_pad; } void RootPlotFrame::unDisplay() { // Delete all Root children. This must be done; otherwise there is some kind of seg fault because Root // still tries to redraw TGraphs which are associated with no display. for (std::list<TGraph *>::reverse_iterator itor = m_tgraphs.rbegin(); itor != m_tgraphs.rend(); ++itor) { if (0 != m_multi_graph) m_multi_graph->RecursiveRemove(*itor); delete *itor; } m_tgraphs.clear(); RootFrame::unDisplay(); } void RootPlotFrame::reset() { // Reset canvas. if (0 != m_canvas) m_canvas->reset(); // Delete children. while (!m_plots.empty()) { // Find last child. std::list<RootPlot *>::iterator itor = --m_plots.end(); // Get pointer to the plot. RootPlot * plot = *itor; // Break links between this and the child plot. removePlot(*itor); // Delete the child plot. delete plot; } unDisplay(); } void RootPlotFrame::addPlot(IPlot * plot) { RootPlot * root_plot = dynamic_cast<RootPlot *>(plot); if (0 == root_plot) throw std::logic_error("RootPlotFrame::addPlot cannot add a non-Root plot"); if (m_plots.empty()) m_dimensionality = root_plot->getDimensionality(); else if (m_dimensionality != root_plot->getDimensionality()) throw std::logic_error("RootPlotFrame::addPlot cannot overlay plots with different numbers of dimensions"); else if (m_dimensionality > 2) throw std::logic_error("RootPlotFrame::addPlot cannot overlay 3d plots"); // Make certain plot is not added more than once. if (m_plots.end() == std::find(m_plots.begin(), m_plots.end(), root_plot)) { m_plots.push_back(root_plot); root_plot->setParent(this); } } void RootPlotFrame::removePlot(IPlot * plot) { std::list<RootPlot *>::iterator itor = std::find(m_plots.begin(), m_plots.end(), plot); if (m_plots.end() != itor) { RootPlot * root_plot = dynamic_cast<RootPlot *>(plot); if (0 != root_plot) root_plot->setParent(0); m_plots.erase(itor); } } void RootPlotFrame::addMarker(Marker & marker) { // Save current pad. TVirtualPad * save_pad = gPad; // Select embedded canvas for drawing. gPad = m_canvas->GetCanvas(); m_canvas->addMarker(marker); // Force complete update of the display. gPad->Modified(); gPad->Update(); // Restore current pad. gPad = save_pad; } const std::string & RootPlotFrame::getTitle() const { return m_title; } std::vector<Axis> & RootPlotFrame::getAxes() { return m_axes; } const std::vector<Axis> & RootPlotFrame::getAxes() const { return m_axes; } void RootPlotFrame::display2d(std::vector<TAxis *> & axes) { axes.assign(3, (TAxis *)(0)); // Create or get parent multi-graph. getMultiGraph(); // Enable custom event handling for 2d graphs. m_canvas->setHandleEvents(true); for (std::list<RootPlot *>::iterator itor = m_plots.begin(); itor != m_plots.end(); ++itor) { // Get numeric sequences from data. const std::vector<const ISequence *> sequences((*itor)->getSequences()); // Unpack the sequences: first dimension is the x axis, second is the y. const ISequence * x = sequences.at(0); const ISequence * y = sequences.at(1); // Determine the style of the graph. std::string style = (*itor)->getStyle(); // Depending on the style, create appropriate Root plot object. TGraph * tgraph = 0; if (style == "hist") tgraph = createHistPlot(*x, *y); else tgraph = createScatterPlot(*x, *y); tgraph->SetLineColor((*itor)->getLineColor()); // Handle line style: none, solid, dashed, dotted. std::string line_style = (*itor)->getLineStyle(); int root_line_style = kSolid; if ("dashed" == line_style) { root_line_style = kDashed; } else if ("dotted" == line_style) { root_line_style = kDotted; } if ("none" == line_style) { line_style = ""; } else { std::string type = (*itor)->getCurveType(); if ("curve" == type) line_style = "C"; else line_style = "L"; } tgraph->SetLineStyle(root_line_style); // Keep track of Root object, so it can be deleted later. m_tgraphs.push_back(tgraph); // Connect Root objects. m_multi_graph->Add(tgraph, line_style.c_str()); } // Draw parent TMultiGraph object. m_multi_graph->Draw("A"); // Get axes. Set all three dimensions even though this is 2D. axes.resize(3); axes[0] = m_multi_graph->GetXaxis(); axes[1] = m_multi_graph->GetYaxis(); axes[2] = 0; } void RootPlotFrame::display3d(std::vector<TAxis *> & axes) { axes.assign(3, (TAxis *)(0)); if (m_plots.empty()) return; std::list<RootPlot *>::iterator itor = m_plots.begin(); // Get numeric sequences from data. const std::vector<const ISequence *> sequences((*itor)->getSequences()); // Unpack the sequences: first dimension is the x axis, second is the y. const ISequence * x = sequences.at(0); const ISequence * y = sequences.at(1); // Get data being plotted. const std::vector<std::vector<double> > & z((*itor)->getZData()); // Create Root plotting object. m_th2d = createHistPlot2D(createRootName("TH2D", *itor), *x, *y, z); m_th2d->Draw("lego"); // Get axes. axes[0] = m_th2d->GetXaxis(); axes[1] = m_th2d->GetYaxis(); axes[2] = m_th2d->GetZaxis(); } TGraph * RootPlotFrame::createHistPlot(const ISequence & x, const ISequence & y) { TGraph * retval = 0; // Get arrays of values. std::vector<double> x_low; std::vector<double> x_high; std::vector<double> y_value; // Interpret x as a set of intervals. x.getIntervals(x_low, x_high); // Interpret y as the value in each interval. y.getValues(y_value); // Combine ranges and values into one array for axis and one array for the data; needed for TGraph. std::vector<double> x_vals(x_low.size() * 4); std::vector<double> y_vals(x_low.size() * 4); // Use input arrays to create graphable data. unsigned long idx = 0; unsigned long ii = 0; #if 0 // First point plotted is at the base of the first bin. x_vals[idx] = x_low[ii]; y_vals[idx] = 0.; ++idx; #endif for (ii = 0; ii < x_low.size(); ++ii, ++idx) { // Plot the y value at the left edge. x_vals[idx] = x_low[ii]; y_vals[idx] = y_value[ii]; // Next plot the y value at the right edge. ++idx; x_vals[idx] = x_high[ii]; y_vals[idx] = y_value[ii]; // Exclude the last bin, which requires special handling. if (ii != x_low.size() - 1) { // See if the next bin's left edge is > than the right edge which was just plotted. double next = x_low[ii + 1]; if (next > x_vals[idx]) { // There is a gap in the data, so plot a value of 0. in the gap. ++idx; x_vals[idx] = x_vals[idx - 1]; y_vals[idx] = 0.; ++idx; x_vals[idx] = next; y_vals[idx] = 0.; } #if 0 } else { // Last input point is the last right edge, which should drop to 0. ++idx; x_vals[idx] = x_vals[idx - 1]; y_vals[idx] = 0.; #endif } } // Create the graph. retval = new TGraph(idx, &*x_vals.begin(), &*y_vals.begin()); retval->SetEditable(kFALSE); return retval; } TGraph * RootPlotFrame::createScatterPlot(const ISequence & x, const ISequence & y) { TGraph * retval = 0; // Get arrays of values. std::vector<double> x_pts; std::vector<double> x_low_err; std::vector<double> x_high_err; std::vector<double> y_pts; std::vector<double> y_low_err; std::vector<double> y_high_err; x.getValues(x_pts); x.getSpreads(x_low_err, x_high_err); y.getValues(y_pts); y.getSpreads(y_low_err, y_high_err); // Create the graph. retval = new TGraphAsymmErrors(x.size(), &x_pts[0], &y_pts[0], &x_low_err[0], &x_high_err[0], &y_low_err[0], &y_high_err[0]); retval->SetEditable(kFALSE); return retval; } TH2D * RootPlotFrame::createHistPlot2D(const std::string & root_name, const ISequence & x, const ISequence & y, const std::vector<std::vector<double> > & z) { TH2D * hist = 0; typedef std::vector<double> Vec_t; // Set up x bins. There is one extra for Root's upper cutoff. Vec_t x_bins(x.size() + 1); // Set up intervals, big enough to hold either x or y bins. Vec_t lower(std::max(x.size(), y.size())); Vec_t upper(std::max(x.size(), y.size())); // Get intervals of x axis. x.getIntervals(lower, upper); // Use low edges of input sequence for all but the last bin. for (Vec_t::size_type ii = 0; ii < x.size(); ++ii) x_bins[ii] = lower[ii]; // Last bin is taken from upper bound of last element in sequence. x_bins[x.size()] = upper[x.size() - 1]; // Set up y bins. There is one extra for Root's upper cutoff. Vec_t y_bins(y.size() + 1); // Get intervals of y axis. y.getIntervals(lower, upper); // Use low edges of all bins. for (Vec_t::size_type ii = 0; ii < y.size(); ++ii) y_bins[ii] = lower[ii]; // Last bin is overflow. y_bins[y.size()] = upper[y.size() - 1]; // Create the histogram used to draw the plot. hist = new TH2D(root_name.c_str(), getTitle().c_str(), x_bins.size() - 1, &x_bins[0], y_bins.size() - 1, &y_bins[0]); // Populate the histogram. for (unsigned int ii = 0; ii < x.size(); ++ii) for (unsigned int jj = 0; jj < y.size(); ++jj) hist->SetBinContent(ii + 1, jj + 1, z[ii][jj]); return hist; } std::string RootPlotFrame::createRootName(const std::string & prefix, void * ptr) const { // The Root name of the object (by which it may be looked up) is its address, converted // to a string. This should prevent collisions. std::ostringstream os; os << prefix << " " << ptr; return os.str(); } TMultiGraph * RootPlotFrame::getMultiGraph() { if (0 == m_multi_graph) { class StMultiGraph : public TMultiGraph { public: StMultiGraph(const char * name, const char * title): TMultiGraph(name, title) {} virtual Int_t DistancetoPrimitive(Int_t px, Int_t py) { // The following code was copied from TMultiGraph in Root 4.02.00 and modified. // This is undesirable, but currently the only solution which works. Without this // override, the line: // if (dist < kMaxDiff) {gPad->SetSelected(g); return dist;} // causes the click event to be associated with one of the TGraphs. This is a // problem if this event is a "button release" when dragging and dropping another // object. Because the event gets tied to the TGraph, the button release is not // handled as a "drop", so the object being dragged springs back to its original // position. // // At first a simpler solution was tried in the overridden method, in which the maximum // distance was always returned. However, this broke mouse clicks which were not // associated with the TMultiGraph, because the line: // distance = fHistogram->DistancetoPrimitive(px,py); // was not getting executed. When this method is called, the correct histogram // axis gets selected and that axis can then respond to events, otherwise // no object responds to it. In other words, Root depends on the correct // object being selected as a side-effect of computing the distance to the // object! //*-*- Are we on the axis? const Int_t kMaxDiff = 10; Int_t distance = 9999; // Changed following line, using 0 != to silence warning on Windows. // if (fHistogram) { if (0 != fHistogram) { distance = fHistogram->DistancetoPrimitive(px,py); if (distance <= 0) return distance; } //*-*- Loop on the list of graphs // Changed following line, using 0 == to silence warning on Windows. // if (!fGraphs) return distance; if (0 == fGraphs) return distance; TGraph *g; TIter next(fGraphs); // Added 0 != to silence warning on Windows. // Changed following line, using 0 != to silence warning on Windows. // while ((g = (TGraph*) next())) { while (0 != (g = (TGraph*) next())) { Int_t dist = g->DistancetoPrimitive(px,py); if (dist <= 0) return 0; // Commenting out gPad->SetSelected(g) is the only modification to base class method. if (dist < kMaxDiff) {/* gPad->SetSelected(g); */ return dist;} } return distance; } }; m_multi_graph = new StMultiGraph(createRootName("TMultiGraph", this).c_str(), m_title.c_str()); } return m_multi_graph; } }
33.731152
168
0.621094
fermi-lat
c14f25f5bbb6720ed629b190a760c0a40edd9b54
8,399
hxx
C++
dev/ese/src/os/osstd_.hxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
1
2021-02-02T07:04:07.000Z
2021-02-02T07:04:07.000Z
dev/ese/src/os/osstd_.hxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
null
null
null
dev/ese/src/os/osstd_.hxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #define _CRT_RAND_S #include <stdlib.h> #include <string.h> #pragma prefast(push) #pragma prefast(disable:26006, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:26007, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:28718, "Dont bother us with tchar, someone else owns that.") #pragma prefast(disable:28726, "Dont bother us with tchar, someone else owns that.") #include <tchar.h> #pragma prefast(pop) #include <stddef.h> #include <stdio.h> #include <time.h> #include <limits.h> #include <minmax.h> #include <ctype.h> #include <specstrings.h> #include <algorithm> #include <functional> #if _MSC_VER >= 1100 using namespace std; #endif #define Unused( var ) ( var ) #pragma warning ( disable : 4200 ) #pragma warning ( disable : 4201 ) #pragma warning ( disable : 4355 ) #pragma warning ( disable : 4706 ) #pragma warning ( 3 : 4244 ) #pragma inline_depth( 255 ) #pragma inline_recursion( on ) #include "os.hxx" #include "jet.h" #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> #include <winnt.h> #include <sddl.h> #include <rpc.h> #define wszNtdll L"ntdll.dll" #define wszKernel32 L"kernel32.dll" #define wszAdvapi32 L"advapi32.dll" #define wszPsapi L"psapi.dll" #define wszUser32 L"user32.dll" #define wszKernelBase L"kernelbase.dll" #define wszMinUser L"minuser32.dll" #define wszKernel32Legacy L"kernel32legacy.dll" #define wszRtlSupport L"api-ms-win-core-rtlsupport-l1-1-0.dll" #define wszCoreSysInfo L"api-ms-win-core-sysinfo-l1-1-0.dll" #define wszCoreSynch L"api-ms-win-core-synch-l1-1-0.dll" #define wszCoreHeap L"api-ms-win-core-heap-l1-1-0.dll" #define wszCoreFile L"api-ms-win-core-file-l1-1-0.dll" #define wszCoreProcessThreads L"api-ms-win-core-processthreads-l1-1-1.dll" #define wszCoreThreadpool L"api-ms-win-core-threadpool-l1-1-0.dll" #define wszCoreLoc L"api-ms-win-core-localization-l1-1-0.dll" #define wszCoreReg L"api-ms-win-core-localregistry-l1-1-0.dll" #define wszSecBase L"api-ms-win-security-base-l1-1-0.dll" #define wszCoreDebug L"api-ms-win-core-debug-l1-1-0.dll" #define wszSecSddl L"api-ms-win-security-sddl-l1-1-0.dll" #define wszLsaLookup L"api-ms-win-security-lsalookup-l2-1-0.dll" #define wszWorkingSet L"api-ms-win-core-psapi-l1-1-0.dll" #define szAppModelRuntime L"api-ms-win-appmodel-runtime-l1-1-0.dll" #define szAppModelState L"api-ms-win-appmodel-state-l1-1-0.dll" #define wszEventingProvider L"api-ms-win-eventing-provider-l1-1-0.dll" #define wszEventLogLegacy L"api-ms-win-eventlog-legacy-l1-1-0.dll" #define wszCoreKernel32Legacy L"api-ms-win-core-kernel32-legacy-l1-1-0.dll" #define wszCoreWow64 L"api-ms-win-core-wow64-l1-1-0.dll" #define wszCoreFile12 L"api-ms-win-core-file-l1-2-0.dll" #ifndef ESENT #define wszCoreDebug12 L"api-ms-win-core-debug-l1-1-2.dll" #endif const wchar_t * const g_mwszzNtdllLibs = wszNtdll L"\0"; const wchar_t * const g_mwszzRtlSupportLibs = wszRtlSupport L"\0" wszNtdll L"\0"; const wchar_t * const g_mwszzCpuInfoLibs = wszCoreProcessThreads L"\0" wszKernel32 L"\0"; const wchar_t * const g_mwszzSysInfoLibs = wszCoreSysInfo L"\0" wszKernel32 L"\0"; const wchar_t * const g_mwszzSyncLibs = wszCoreSynch L"\0" wszKernel32 L"\0"; const wchar_t * const g_mwszzHeapLibs = wszCoreHeap L"\0" wszKernel32 L"\0"; const wchar_t * const g_mwszzFileLibs = wszCoreFile12 L"\0" wszCoreFile L"\0" wszKernel32 L"\0" wszKernelBase L"\0"; const wchar_t * const g_mwszzThreadpoolLibs = wszCoreThreadpool L"\0" wszKernel32 L"\0"; #ifdef ESENT const wchar_t * const g_mwszzLocalizationLibs = wszCoreLoc L"\0" wszKernel32 L"\0"; #else const wchar_t * const g_mwszzLocalizationLibs = wszCoreLoc L"\0" wszCoreDebug12 L"\0" wszKernel32 L"\0"; #endif const wchar_t * const g_mwszzCoreDebugLibs = wszCoreDebug L"\0" wszKernel32 L"\0"; const wchar_t * const g_mwszzRegistryLibs = wszCoreReg L"\0" wszAdvapi32 L"\0"; const wchar_t * const g_mwszzSecSddlLibs = wszSecSddl L"\0" wszAdvapi32 L"\0"; const wchar_t * const g_mwszzProcessTokenLibs = wszCoreProcessThreads L"\0" wszAdvapi32 L"\0"; const wchar_t * const g_mwszzAdjPrivLibs = wszSecBase L"\0" wszAdvapi32 L"\0"; const wchar_t * const g_mwszzLookupPrivLibs = wszLsaLookup L"\0" wszAdvapi32 L"\0"; const wchar_t * const g_mwszzUserInterfaceLibs = wszMinUser L"\0" wszUser32 L"\0"; const wchar_t * const g_mwszzWorkingSetLibs = wszWorkingSet L"\0" wszPsapi L"\0"; const wchar_t * const g_mwszzProcessMemLibs = wszWorkingSet L"\0" wszPsapi L"\0" wszKernel32 L"\0"; const wchar_t * const g_mwszzErrorHandlingLegacyLibs = wszCoreKernel32Legacy L"\0" wszKernel32 L"\0"; const wchar_t * const g_mwszzWow64Libs = wszCoreWow64 L"\0" wszKernel32 L"\0"; const wchar_t * const g_mwszzAppModelRuntimeLibs = szAppModelRuntime L"\0"; const wchar_t * const g_mwszzAppModelStateLibs = szAppModelState L"\0"; const wchar_t * const g_mwszzEventingProviderLibs = wszEventingProvider L"\0" wszAdvapi32 L"\0"; const wchar_t * const g_mwszzEventLogLegacyLibs = wszEventLogLegacy L"\0" wszAdvapi32 L"\0"; const wchar_t * const g_mwszzKernel32CoreSystemBroken = wszKernel32 L"\0" wszKernelBase L"\0" wszKernel32Legacy L"\0"; const wchar_t * const g_mwszzAdvapi32CoreSystemBroken = wszAdvapi32 L"\0"; #undef wszNtdll #undef wszKernel32 #undef wszAdvapi32 #undef wszPsapi #undef wszUser32 #define wszNtdll wszNtdll_silly_you_this_dll_is_not_for_you_see_osstd_hxx #define wszKernel32 wszKernel32_silly_you_this_dll_is_not_for_you_see_osstd_hxx #define wszAdvapi32 wszAdvapi32_silly_you_this_dll_is_not_for_you_see_osstd_hxx #define wszPsapi wszPsapi_silly_you_this_dll_is_not_for_you_see_osstd_hxx #define wszUser32 wszUser32_silly_you_this_dll_is_not_for_you_see_osstd_hxx const INT rankCritTaskList = 0; const INT rankAESProv = 1; const INT rankIoStats = 1; const INT rankIOREQ = 2; const INT rankTimerTaskList = 3; const INT rankTimerTaskEntry = 3; const INT rankIOREQPoolCrit = 3; const INT rankOSDiskIOQueueCrit = 4; const INT rankOSDiskSXWL = 6; const INT rankFTLFlushBuffs = 6; const INT rankFTLFlush = 7; const INT rankFTLBuffer = 8; const INT rankOSVolumeSXWL = 8; const INT rankRwlPostTasks = 9; #include "_dev.hxx" #include "_os.hxx" #include "_ostls.hxx" #include "_osdisk.hxx" #include "_osfs.hxx" #include "_osfile.hxx" #include "_oserror.hxx" #include "_reftrace.hxx" #include "blockcache\_blockcache.hxx" const BOOL FUtilIProcessIsWow64(); #ifndef OS_LAYER_VIOLATIONS VOID UtilReportEvent( const EEventType type, const CategoryId catid, const MessageId msgid, const DWORD cString, const WCHAR * rgpszString[], const DWORD cbRawData = 0, void * pvRawData = NULL, const INST * pinst = NULL, const LONG lEventLoggingLevel = 1 ); #ifdef ESENT #include "jetmsg.h" #else #include "jetmsgex.h" #endif #define LoadLibraryA LoadLibrary_not_allowed_use_NTOSFuncXxx_FunctionLoader #define LoadLibraryW LoadLibrary_not_allowed_use_NTOSFuncXxx_FunctionLoader #define LoadLibraryExA LoadLibrary_not_allowed_use_NTOSFuncXxx_FunctionLoader #define LoadLibraryExW LoadLibrary_not_allowed_use_NTOSFuncXxx_FunctionLoader #define GetModuleHandleA GetModuleHandle_not_allowed_use_NTOSFuncXxx_FunctionLoader #define GetModuleHandleW GetModuleHandle_not_allowed_use_NTOSFuncXxx_FunctionLoader #define GetModuleHandleExA GetModuleHandle_not_allowed_use_NTOSFuncXxx_FunctionLoader #define GetModuleHandleExW GetModuleHandle_not_allowed_use_NTOSFuncXxx_FunctionLoader #define GetTickCount GetTickCount_is_protected_function_use_TickOSTimeCurrent #endif
34.995833
128
0.709608
augustoproiete-forks
c150f2eaf7f4da0a1d68dd095749307f558889b8
336
cpp
C++
distributions/uniformgenerator.cpp
KomarDL/Random-numbers-distributions
3fa9b07c6fed9ac446aad83659368a4f2c9b27d3
[ "MIT" ]
null
null
null
distributions/uniformgenerator.cpp
KomarDL/Random-numbers-distributions
3fa9b07c6fed9ac446aad83659368a4f2c9b27d3
[ "MIT" ]
null
null
null
distributions/uniformgenerator.cpp
KomarDL/Random-numbers-distributions
3fa9b07c6fed9ac446aad83659368a4f2c9b27d3
[ "MIT" ]
null
null
null
#include "uniformgenerator.h" UniformGenerator::UniformGenerator(Lemer *lmr, QObject *parent) : BaseGenerator("Равномерное", lmr, parent) { paramAmount = 2; paramNames[0] = "a"; paramNames[1] = "b"; } qreal UniformGenerator::_generate() { return params[0] + (params[1] - params[0]) * lemer->generate(); }
24
108
0.642857
KomarDL
c15218d5e665c1371261e2caaaf75cc3d7b48bc3
1,125
cpp
C++
perf_test/thread/ThreadTest.cpp
armsword/DLog
6b049124098f6c0f622e9a610a87fea27125e0da
[ "MIT" ]
33
2016-09-10T16:42:16.000Z
2021-05-13T07:02:06.000Z
perf_test/thread/ThreadTest.cpp
armsword/DLog
6b049124098f6c0f622e9a610a87fea27125e0da
[ "MIT" ]
1
2016-09-26T16:07:54.000Z
2016-09-26T17:07:29.000Z
perf_test/thread/ThreadTest.cpp
armsword/DLog
6b049124098f6c0f622e9a610a87fea27125e0da
[ "MIT" ]
13
2016-09-14T10:24:15.000Z
2021-01-05T18:46:56.000Z
#include <dlog/logger/Log.h> #include <unistd.h> #include <stdlib.h> #include <sys/time.h> #include <stdint.h> #include <iostream> #include <string.h> #include <pthread.h> using namespace dlog::logger; int64_t currentTime() { struct timeval tval; gettimeofday(&tval, NULL); return (tval.tv_sec * 1000000LL + tval.tv_usec) / 1000000; // 返回秒 } void *print(void* buffer) { for(int i = 0; i < 1500000; i++) { DLOG_LOG(DEBUG, "%s", (char*)buffer); } return ((void*)0); } int main() { DLOG_INIT(); pthread_t tid[2]; char buffer[256]; int i; for(i = 0; i < 255; i++) { buffer[i] = 'A' + rand() % 26; } buffer[i] = '\0'; int64_t begin = currentTime(); for(i = 0; i < 2; i++) { if(pthread_create(&tid[i],NULL,print,buffer) != 0) { std::cout << "create thread error!" << std::endl; exit(1); } } for(i = 0; i < 2; i++) { pthread_join(tid[i], NULL); } int64_t end = currentTime(); int64_t total = end - begin; std::cout << "total time is: " << total << std::endl; return 0; }
21.634615
71
0.537778
armsword
c152bdba5071a5589bb030f6c48876fb4c4a169b
42,535
cpp
C++
AIPDebug/Function-Module/Widget_INDL.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
AIPDebug/Function-Module/Widget_INDL.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
AIPDebug/Function-Module/Widget_INDL.cpp
Bluce-Song/Master-AIP
1757ab392504d839de89460da17630d268ff3eed
[ "Apache-2.0" ]
null
null
null
#include "Widget_INDL.h" #include "ui_Widget_INDL.h" Widget_INDL::Widget_INDL(QWidget *parent) : QWidget(parent), ui(new Ui::Widget_INDL) { ui->setupUi(this); // 电感设置表头 ui->indlTab->horizontalHeader()->setStyleSheet\ ("QHeaderView::section{background-color:#191919;color: white;"\ "padding-left: 4px;border: 1px solid #447684;}"); ui->indlTab->horizontalHeader()->setFixedHeight(35); ui->indlTab->horizontalHeader()->setResizeMode(QHeaderView::Fixed); ui->indlTab->setColumnWidth(0, 45); // -序号 ui->indlTab->setColumnWidth(1, 45); // -端子T1 ui->indlTab->setColumnWidth(2, 45); // -端子T2 ui->indlTab->setColumnWidth(3, 70); // -下限 ui->indlTab->setColumnWidth(4, 70); // -上限 ui->indlTab->setColumnWidth(5, 70); // -Q值下限 ui->indlTab->setColumnWidth(6, 70); // -Q值上限 ui->indlTab->setColumnWidth(7, 60); // -补偿数值 ui->indlTab->setColumnWidth(8, 60); // -标准值 ui->indlTab->setColumnWidth(9, 60); // -使能 ui->indlTab->setColumnWidth(10, 50); // -使能 INDL_Group = new QButtonGroup; INDL_Group->addButton(ui->Key_1, 1); INDL_Group->addButton(ui->Key_2, 2); INDL_Group->addButton(ui->Key_3, 3); INDL_Group->addButton(ui->Key_4, 4); INDL_Group->addButton(ui->Key_5, 5); INDL_Group->addButton(ui->Key_6, 6); INDL_Group->addButton(ui->Key_7, 7); INDL_Group->addButton(ui->Key_8, 8); connect(INDL_Group, SIGNAL(buttonClicked(int)), this, SLOT(join_buttonJudge(int))); ui->dockWidget->hide(); INDL_Labelhide = new QLabel(this); INDL_Labelhide->setGeometry(0, 0, 800, 600); INDL_Labelhide->hide(); INDL_Init_Flag = false; ui->Button_Comp->hide(); Init_Channel_6 = false; } Widget_INDL::~Widget_INDL() { delete ui; } void Widget_INDL::mousePressEvent(QMouseEvent *event) // 处理鼠标被按下事件 { if ((ui->indlTab->currentColumn() == 1) || \ (ui->indlTab->currentColumn() == 2)) { ui->dockWidget->hide(); INDL_Labelhide->hide(); } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: 初始化电感设置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Init() { int i; INDL_Init_Flag = true; ui->indlTab->setRowCount(8); // 设置电感行数 INDL_QTableWidgetItem.clear(); Box_INDL_Grade_List.clear(); INDL_Unit.clear(); INDL_Unit << "uH" << "mH"; // 电感单位 ui->INDL_time->setValue(Copy_INDL_List.at(0).toInt()); ui->INDL_balance->setValue(Copy_INDL_List.at(1).toDouble()); ui->Com_fre->setCurrentIndex(Copy_INDL_List.at(2).toInt()); ui->Com_connetct->setCurrentIndex(Copy_INDL_List.at(3).toInt()); ui->INDL_Max->setValue(Copy_INDL_List.at(4).toInt()); ui->INDL_Min->setValue(Copy_INDL_List.at(5).toInt()); ui->Com_test->setCurrentIndex(Copy_INDL_List.at(6).toInt()); ui->Q_balance->setValue(Copy_INDL_List.at(7).toDouble()); ui->Com_volt->setCurrentIndex(Copy_INDL_List.at(8).toInt()); for (i = 0; i < 8; i++) { ui->indlTab->setRowHeight(i, 53); QTableWidgetItem *INDL_Number = new QTableWidgetItem; // 序号 INDL_Number->setTextAlignment(Qt::AlignCenter); INDL_Number->setText(QString::number(i+1)); INDL_Number->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(i, 0, INDL_Number); QTableWidgetItem *INDL_Point_one = new QTableWidgetItem; // 端子 1 INDL_Point_one->setTextAlignment(Qt::AlignCenter); INDL_Point_one->setText(Copy_INDL_List.at(INDL_init_Number+20*i+0)); INDL_Point_one->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(i, 1, INDL_Point_one); QTableWidgetItem *INDL_Point_two = new QTableWidgetItem; // 端子 2 INDL_Point_two->setTextAlignment(Qt::AlignCenter); INDL_Point_two->setText(Copy_INDL_List.at(INDL_init_Number+20*i+1)); INDL_Point_two->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(i, 2, INDL_Point_two); QTableWidgetItem *Down_Limit = new QTableWidgetItem; // 电感下限 Down_Limit->setTextAlignment(Qt::AlignCenter); Down_Limit->setText(Copy_INDL_List.at(INDL_init_Number+20*i+2)); ui->indlTab->setItem(i, 3, Down_Limit); QTableWidgetItem *Up_Limit = new QTableWidgetItem; // 电感上限 Up_Limit->setTextAlignment(Qt::AlignCenter); Up_Limit->setText(Copy_INDL_List.at(INDL_init_Number+20*i+3)); ui->indlTab->setItem(i, 4, Up_Limit); QTableWidgetItem *QDown_Limit = new QTableWidgetItem; // Q值下限 QDown_Limit->setTextAlignment(Qt::AlignCenter); QDown_Limit->setText(Copy_INDL_List.at(INDL_init_Number+20*i+4)); ui->indlTab->setItem(i, 5, QDown_Limit); QTableWidgetItem *QUp_Limit = new QTableWidgetItem; // Q值上限 QUp_Limit->setTextAlignment(Qt::AlignCenter); QUp_Limit->setText(Copy_INDL_List.at(INDL_init_Number+20*i+5)); ui->indlTab->setItem(i, 6, QUp_Limit); QTableWidgetItem *Stand_INDL = new QTableWidgetItem; // 标准电感 Stand_INDL->setTextAlignment(Qt::AlignCenter); Stand_INDL->setText(Copy_INDL_List.at(INDL_init_Number+20*i+6)); ui->indlTab->setItem(i, 7, Stand_INDL); QTableWidgetItem *UnitItem = new QTableWidgetItem; // UnitItem->setTextAlignment(Qt::AlignCenter); UnitItem->setText(INDL_Unit[Copy_INDL_List.at(INDL_init_Number+20*i+7).toInt()]); UnitItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(i, 10, UnitItem); Box_INDL_Grade_List.append(new QCheckBox); // 测试项目选择 勾选项目 Box_INDL_Grade_List[i]->setStyleSheet\ ("QCheckBox::indicator {image: url(:/image/053.png);"\ "width: 45px;height: 45px;}QCheckBox::indicator:checked "\ "{image: url(:/image/051.png);}"); ui->indlTab->setCellWidget(i, 11, Box_INDL_Grade_List[i]); if (Copy_INDL_List.at(INDL_init_Number + i*20 + 8).toInt() == 2) { // 档位 (高 中 低 微 超微 极微) Box_INDL_Grade_List.at(i)->setChecked(true); } QTableWidgetItem *Compensation = new QTableWidgetItem; // 补偿电感 Compensation->setTextAlignment(Qt::AlignCenter); Compensation->setText(Copy_INDL_List.at(INDL_init_Number + 20*i + 9)); ui->indlTab->setItem(i, 8, Compensation); QTableWidgetItem *R_Compensation = new QTableWidgetItem; // 右工位-补偿电感 R_Compensation->setTextAlignment(Qt::AlignCenter); R_Compensation->setText(Copy_INDL_List.at(INDL_init_Number + 20*i + 10)); ui->indlTab->setItem(i, 9, R_Compensation); } INDL_Init_Flag = false; } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: 电感参数进行快速设置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Quiky_Test_Parameter() { int i; INDL_TestItemsH = 0; INDL_TestItemsL = 0; INDL_TestNumber = 0; for (i = 0; i < 8; i++) { if (Box_INDL_Grade_List.at(i)->checkState() != 2) { continue; } frame.can_id = 0x26; frame.can_dlc = 0x07; frame.data[0] = 0x03; frame.data[1] = i; frame.data[2] = ui->indlTab->item(i, 1)->text().toInt(); // 抽头 frame.data[3] = ui->indlTab->item(i, 2)->text().toInt(); frame.data[4] = 1; frame.data[5] = 0x0b; frame.data[6] = (int)(0x00|0x09); if (i >= 8) { INDL_TestItemsH = INDL_TestItemsH + (1 << (i-8)); // 高字节 } else { INDL_TestItemsL = INDL_TestItemsL + (1 << i); // 低字节 } INDL_TestNumber++; // 测试总数 canSend(frame); usleep(1000); usleep(1000); usleep(1000); usleep(1000); usleep(1000); usleep(1000); } } /****************************************************************************** * version: 1.0 * author: sl * date: 2015.12.30 * brief: 保存 INDL 配置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Test_Parameter() { int i; i = 0; int Indl_Volt = 0; INDL_TestItemsH = 0; INDL_TestItemsL = 0; INDL_TestNumber = 0; if (ui->Com_volt->currentIndex() == 0) { Indl_Volt = 0x08; } else if (ui->Com_volt->currentIndex() == 1) { Indl_Volt = 0x00; } else if (ui->Com_volt->currentIndex() == 2) { Indl_Volt = 0x10; } else { Indl_Volt = 0x08; } for (i = 0; i < 8; i++) { if (Box_INDL_Grade_List.at(i)->checkState() != 2) { continue; } frame.can_id = 0x26; frame.can_dlc = 0x07; frame.data[0] = 0x03; frame.data[1] = i; frame.data[2] = ui->indlTab->item(i, 1)->text().toInt(); // 抽头 frame.data[3] = ui->indlTab->item(i, 2)->text().toInt(); frame.data[4] = ui->INDL_time->text().toInt(); if (ui->Com_fre->currentText() == "1K") { // frame.data[5] 频率 电压 档位 if (ui->indlTab->item(i, 10)->text() == "mH") { if (6.28*1*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 1) { frame.data[5] = 0x0b; } else if (6.28*1*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 10) { frame.data[5] = 0x2b; } else { frame.data[5] = 0x3b; } } else { frame.data[5] = 0x0b; } } else if (ui->Com_fre->currentText() == "10K") { if (ui->indlTab->item(i, 10)->text() == "mH") { if (6.28*10*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 1) { frame.data[5] = 0x0c; } else if (6.28*10*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 10) { frame.data[5] = 0x2c; } else { frame.data[5] = 0x3c; } } else { frame.data[5] = 0x0c; } } else if (ui->Com_fre->currentText() == "100") { if (ui->indlTab->item(i, 10)->text() == "mH") { if (6.28*0.1*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 1) { frame.data[5] = 0x09; } else if (6.28*0.1*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 10) { frame.data[5] = 0x29; } else { frame.data[5] = 0x39; } } else { frame.data[5] = 0x09; } } else if (ui->Com_fre->currentText() == "120") { if (ui->indlTab->item(i, 10)->text() == "mH") { if (6.28*0.12*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 1) { frame.data[5] = 0x0a; } else if (6.28*0.12*ui->indlTab->item(i, 7)->text().toDouble()/1000 < 10) { frame.data[5] = 0x2a; } else { frame.data[5] = 0x3a; } } else { frame.data[5] = 0x0a; } } frame.data[5] = frame.data[5] & 0XE7; frame.data[5] = frame.data[5] | Indl_Volt ; qDebug() << "frame.data[5]------------------" << frame.data[5]; int connetct; // frame.data[6] 连接方式 电压增益 电流增益 if (ui->Com_connetct->currentText() == QString(tr("串联"))) { connetct = 0x00; } else { connetct = 0x40; } if (ui->indlTab->item(i, 10)->text() == "mH") { frame.data[6] = (int)(connetct|0x09); } else { if (ui->indlTab->item(i, 4)->text().toDouble() < 500) { frame.data[6] = (int)(connetct|0x0f); } else { frame.data[6] = (int)(connetct|0x09); } } qDebug() << "frame.data[6]" << frame.data[6]; if (i >= 8) { INDL_TestItemsH = INDL_TestItemsH + (1 << (i-8)); // 高字节 } else { INDL_TestItemsL = INDL_TestItemsL + (1 << i); // 低字节 } INDL_TestNumber++; // 测试总数 canSend(frame); usleep(1000); usleep(1000); usleep(1000); usleep(1000); usleep(1000); usleep(1000); } } /****************************************************************************** * version: 1.0 * author: sl * date: 2015.12.30 * brief: 保存 INDL 配置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Data_Save() { int i; Copy_INDL_List.replace(0, ui->INDL_time->text()); Copy_INDL_List.replace(1, ui->INDL_balance->text()); Copy_INDL_List.replace(2, QString::number(ui->Com_fre->currentIndex())); Copy_INDL_List.replace(3, QString::number(ui->Com_connetct->currentIndex())); Copy_INDL_List.replace(4, ui->INDL_Max->text()); Copy_INDL_List.replace(5, ui->INDL_Min->text()); Copy_INDL_List.replace(6, QString::number(ui->Com_test->currentIndex())); Copy_INDL_List.replace(7, ui->Q_balance->text()); Copy_INDL_List.replace(8,QString::number(ui->Com_volt->currentIndex())); for (i = 0; i < 8; i++) { Copy_INDL_List.replace(INDL_init_Number + 20*i + 0, ui->indlTab->item(i, 1)->text()); // 端子号 Copy_INDL_List.replace(INDL_init_Number + 20*i + 1, ui->indlTab->item(i, 2)->text()); Copy_INDL_List.replace(INDL_init_Number + 20*i + 2, ui->indlTab->item(i, 3)->text()); // 电感上限 下限 Copy_INDL_List.replace(INDL_init_Number + 20*i + 3, ui->indlTab->item(i, 4)->text()); Copy_INDL_List.replace(INDL_init_Number + 20*i + 4, ui->indlTab->item(i, 5)->text()); // Q值上限 下限 Copy_INDL_List.replace(INDL_init_Number + 20*i + 5, ui->indlTab->item(i, 6)->text()); Copy_INDL_List.replace(INDL_init_Number + 20*i + 6, ui->indlTab->item(i, 7)->text()); // 标准电感 Copy_INDL_List.replace(INDL_init_Number + 20*i + 9, ui->indlTab->item(i, 8)->text()); // 补偿 Copy_INDL_List.replace(INDL_init_Number + 20*i + 10, ui->indlTab->item(i, 9)->text()); // 补偿 Copy_INDL_List.replace(INDL_init_Number + 20*i + 8, \ QString::number(Box_INDL_Grade_List.at(i)->checkState())); } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.5.19 * brief: 设置警告弹出框 ******************************************************************************/ void Widget_INDL::Pri_Pwr_WMessage(QString Waring_Text) { QMessageBox *message = new QMessageBox(this); message->setWindowFlags(Qt::FramelessWindowHint); message->setStyleSheet\ ("QMessageBox{border: gray;border-radius: 10px;"\ "padding:2px 4px;background-color: gray;}"); message->setText("\n"+Waring_Text+"\n"); message->addButton(QMessageBox::Ok)->setStyleSheet\ ("height:39px;width:75px;border:5px groove;border:none;"\ "border-radius:10px;padding:2px 4px;"); message->setButtonText(QMessageBox::Ok, QString(tr("确 定"))); message->setIcon(QMessageBox::Warning); message->exec(); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: Conf 配置 INDL 界面 ******************************************************************************/ void Widget_INDL::Pub_Conf_Set_INDL(QString str, int value, int flag) { switch (flag) { case 1: Pri_INDL_Init(); break; case 2: Pri_INDL_Data_Save(); break; case 3: Pri_INDL_Test_Parameter(); break; case 4: Pri_INDL_Test_Start(); break; case 6: Pri_INDL_Default_value(str); break; case 7: Pri_INDL_Auto_Set(str, value); break; case 8: Pri_INDL_Quiky_Test_Parameter(); case 100: if (str.toInt()) { Init_Channel_6 = true; } else { Init_Channel_6 = false; } break; default: break; } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 单位自动设定 ******************************************************************************/ void Widget_INDL::Pri_INDL_Auto_Set(QString str, int value) { if ((str.toDouble() > 1000) && (str.toDouble() < 10000000)) { // 单位设置 mH if (ui->indlTab->item(value-1, 10)->text() != "mH") { on_indlTab_cellClicked(value-1, 10); } ui->indlTab->item(value - 1, 7)->setText(QString::number(str.toDouble()/1000)); on_Button_Auto_clicked(); } else if ((str.toDouble() < 1000)&&(str.toDouble() > 0)) { // 单位设置 uH if (ui->indlTab->item(value-1, 10)->text() != "uH") { on_indlTab_cellClicked(value-1, 10); } ui->indlTab->item(value-1, 7)->setText(str); on_Button_Auto_clicked(); } else { // } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 测试启动 ******************************************************************************/ void Widget_INDL::Pri_INDL_Test_Start() { frame.can_id = 0x26; frame.can_dlc = 0x08; frame.data[0] = 0x01; frame.data[1] = 0x00; frame.data[2] = 0x00; frame.data[3] = 0x13; frame.data[4] = INDL_TestItemsH; frame.data[5] = INDL_TestItemsL; frame.data[6] = 0x07; frame.data[7] = 0x08; canSend(frame); usleep(500); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感默认设置 ******************************************************************************/ void Widget_INDL::Pri_INDL_Default_value(QString number) { int i; for (i = 0; i < 8; i++) { Box_INDL_Grade_List[i]->setChecked(false); } for (i = 0; i < number.size()/2; i++) { ui->indlTab->item(i, 1)->setText(number.mid(i*2, 1)); ui->indlTab->item(i, 2)->setText(number.mid(i*2 + 1, 1)); Box_INDL_Grade_List[i]->setChecked(true); } ui->INDL_time->setValue(1); ui->Com_fre->setCurrentIndex(2); ui->Com_connetct->setCurrentIndex(0); ui->Com_test->setCurrentIndex(0); ui->INDL_Min->setValue(5); ui->INDL_Max->setValue(5); // ui->INDL_balance->setValue(0); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: 端点的选择 ******************************************************************************/ void Widget_INDL::join_buttonJudge(int id) { ui->dockWidget->hide(); INDL_Labelhide->hide(); if (id != 9) { ui->indlTab->currentItem()->setText(QString::number(id)); } } void Widget_INDL::INDL_NetData(QStringList list, QString str) { INDL_Init_Flag = true; int i; if (str == QString(tr("test"))) { for (i = 0; i < 8; i++) { if (list.at(i).toInt() != 0) { Box_INDL_Grade_List[i]->setChecked(true); } else { Box_INDL_Grade_List[i]->setChecked(false); } } } else if (str == QString(tr("port1"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 1)->setText(list.at(i)); } } else if (str == QString(tr("port2"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 2)->setText(list.at(i)); } } else if (str == QString(tr("unit"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 10)->setText(INDL_Unit[list.at(i).toInt()]); Copy_INDL_List.replace(37+20*i, list.at(i)); } } else if (str == QString(tr("min"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 3)->setText(list.at(i)); } } else if (str == QString(tr("max"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 4)->setText(list.at(i)); } } else if (str == QString(tr("qmin"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 5)->setText(list.at(i)); } } else if (str == QString(tr("qmax"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 6)->setText(list.at(i)); } } else if (str == QString(tr("std"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 7)->setText(list.at(i)); } } else if (str == QString(tr("mode"))) { ui->INDL_time->setValue(list.at(0).toDouble()); ui->Com_fre->setCurrentIndex(list.at(1).toInt()); ui->Com_connetct->setCurrentIndex(list.at(2).toInt()); ui->Com_test->setCurrentIndex(list.at(3).toInt()); } else if (str == QString(tr("noun"))) { ui->INDL_balance->setValue(list.at(0).toDouble()); } else if (str == QString(tr("wire_comp1"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 8)->setText(list.at(i)); } } else if (str == QString(tr("wire_comp2"))) { for (i = 0; i < 8; i++) { ui->indlTab->item(i, 9)->setText(list.at(i)); } Pri_INDL_Data_Save(); } else { // } INDL_Init_Flag = false; } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感界面单击 ******************************************************************************/ void Widget_INDL::on_indlTab_cellClicked(int row, int column) { int number_column; ui->Key_1->show(); ui->Key_2->show(); ui->Key_3->show(); ui->Key_4->show(); ui->Key_5->show(); ui->Key_6->show(); ui->Key_7->show(); ui->Key_8->show(); if (Init_Channel_6) { ui->Key_7->hide(); ui->Key_8->hide(); } else { } if (column == 1 || column == 2) { if(column==1) { number_column = ui->indlTab->item(row,2)->text().toInt(); if ((number_column==1) || (number_column==4) || (number_column==7)) { ui->Key_1->hide(); ui->Key_4->hide(); ui->Key_7->hide(); } else if((number_column==2) || (number_column==5) || (number_column==8)) { ui->Key_2->hide(); ui->Key_5->hide(); ui->Key_8->hide(); } else if((number_column==3) || (number_column==6)) { ui->Key_3->hide(); ui->Key_6->hide(); } } else if(column==2) { number_column = ui->indlTab->item(row,1)->text().toInt(); if((number_column==1)||(number_column==4)||(number_column==7)) { ui->Key_1->hide(); ui->Key_4->hide(); ui->Key_7->hide(); } else if((number_column==2)||(number_column==5)||(number_column==8)) { ui->Key_2->hide(); ui->Key_5->hide(); ui->Key_8->hide(); } else if((number_column==3)||(number_column==6)) { ui->Key_3->hide(); ui->Key_6->hide(); } } else { // } INDL_Labelhide->show(); ui->dockWidget->show(); ui->dockWidget->raise(); } else if (column == 10) { INDL_Init_Flag = true; int indlId = (Copy_INDL_List.at(INDL_init_Number + 20*row + 7).toInt() \ + 1)%INDL_Unit.size(); Copy_INDL_List.replace(INDL_init_Number + 20*row + 7, QString::number(indlId)); QTableWidgetItem *UnitItem = new QTableWidgetItem(); // INDL_Unit[indlId] UnitItem->setTextAlignment(Qt::AlignCenter); UnitItem->setText(INDL_Unit[Copy_INDL_List.at(INDL_init_Number+20*row+7).toInt()]); UnitItem->setFlags(Qt::ItemIsSelectable|Qt::ItemIsEnabled); ui->indlTab->setItem(row, 10, UnitItem); if (indlId == 0) { // uH ui->indlTab->item(row, 7)->setText("200.0"); ui->indlTab->item(row, 4)->setText("300.0"); ui->indlTab->item(row, 3)->setText("100.0"); } else if (indlId == 1) { // mH ui->indlTab->item(row, 7)->setText("200.0"); ui->indlTab->item(row, 4)->setText("300.0"); ui->indlTab->item(row, 3)->setText("100.0"); } else { // } // else if (indlId == 2) // H // { // ui->indlTab->item(row, 7)->setText("2.000"); // ui->indlTab->item(row, 4)->setText("3.000"); // ui->indlTab->item(row, 3)->setText("1.000"); // } INDL_Init_Flag = false; } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 输入完成规范设置 ******************************************************************************/ void Widget_INDL::on_indlTab_cellChanged(int row, int column) { QString str; int i, After_Point = 0; if (INDL_Init_Flag) { return; } INDL_Init_Flag = true; if ((column == 3) || (column == 4) || (column == 5) || \ (column == 6) || (column == 7) || (column == 8) || (column == 9)) { str = ui->indlTab->item(row, column)->text(); if (str == NULL) { ui->indlTab->item(row, column)->setText("0"); } for (i = 0; i < str.length(); i++) { // 判断输入是" 0-9 . " if (((str[i] >= '0') && (str[i] <= '9')) || \ (str[i] == '.') || (str[i] == '-')) { // } else { ui->indlTab->item(row, column)->setText("0"); break; } if (str[i] == '.') { // 判断是否规范 After_Point = str.length()-i-1; if ((i == 0)) { ui->indlTab->item(row, column)->setText("0"); } if (i == (str.length()-1)) { ui->indlTab->item(row, column)->setText(ui->indlTab->item\ (row, column)->text().left(i)); } } } if ((column == 3) || (column == 4) || (column == 7) || (column == 9)) { if (ui->indlTab->item(row, 10)->text() == "uH") { // 单位是uH if (ui->indlTab->item(row, column)->text().toDouble() < 1000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 1)); } else { ui->indlTab->item(row, column)->setText("999.9"); } } if (ui->indlTab->item(row, 10)->text() == "mH") { // 单位是mH if (ui->indlTab->item(row, column)->text().toDouble() < 10) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 3)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 100) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 2)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 1000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 1)); } else if (ui->indlTab->item(row, column)->text().toDouble() <= 10000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 0)); } else { ui->indlTab->item(row, column)->setText("10000"); } } } if ((column == 5) || (column == 6)) { if (ui->indlTab->item(row, column)->text().toDouble() == 0) { ui->indlTab->item(row, column)->setText("0.000"); } else if (ui->indlTab->item(row, column)->text().toDouble() < 10) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 3)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 100) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 2)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 1000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 1)); } else if (ui->indlTab->item(row, column)->text().toDouble() < 10000) { ui->indlTab->item(row, column)->setText\ (QString::number(ui->indlTab->item\ (row, column)->text().toDouble(), 'f', 0)); } else { ui->indlTab->item(row, column)->setText("9999"); } } if ((column == 3) || (column == 4)) { if ((ui->indlTab->item(row, 3)->text().toDouble()) > \ (ui->indlTab->item(row, 4)->text().toDouble())) { ui->indlTab->item(row, 3)->setText("0.0"); } } if ((column == 5) || (column == 6)) { if ((ui->indlTab->item(row, 5)->text().toDouble()) > \ (ui->indlTab->item(row, 6)->text().toDouble())) { ui->indlTab->item(row, 5)->setText("0.000"); } } if ((row == 0) && (column == 8)) { for (i = 1; i <= 7; i++) { ui->indlTab->item(i, column)->setText(ui->indlTab->item(0, column)->text()); } } // if ((row == 0) && (column == 9)) { // for (i = 1; i <= 7; i++) { // ui->indlTab->item(i, column)->setText(ui->indlTab->item(0, column)->text()); // } // } } INDL_Init_Flag = false; } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感自动计算 ******************************************************************************/ void Widget_INDL::on_Button_Auto_clicked() { int i; INDL_Init_Flag = true; for (i = 0; i < 8; i++) { // 电感测试项目 8项 if (Box_INDL_Grade_List[i]->checkState() != 2) { continue; } if (ui->indlTab->item(i, 10)->text() == "uH") { if (ui->indlTab->item(i, 7)->text().toDouble()*(100 + \ ui->INDL_Min->text().toInt())/100 > 1000) { ui->indlTab->item(i, 4)->setText("999.9"); } else { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble()*(100 + \ ui->INDL_Min->text().toInt())/100, 'f', 1)); } ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble()*(100 - \ ui->INDL_Max->text().toInt())/100, 'f', 1)); } else if (ui->indlTab->item(i, 10)->text() == "mH") { if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100 + ui->INDL_Min->text().toInt())/100 < 10) { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100, 'f', 3)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100 < 100) { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100, 'f', 2)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100 < 1000) { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100, 'f', 1)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100 <= 10000) { ui->indlTab->item(i, 4)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100+ui->INDL_Min->text().toInt())/100, 'f', 0)); } else { ui->indlTab->item(i, 4)->setText("10000"); } if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Min->text().toInt())/100 < 10) { ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Max->text().toInt())/100, 'f', 3)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Min->text().toInt())/100 < 100) { ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Max->text().toInt())/100, 'f', 2)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Min->text().toInt())/100 < 1000) { ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Max->text().toInt())/100, 'f', 1)); } else if (ui->indlTab->item(i, 7)->text().toDouble() * \ (100- ui->INDL_Min->text().toInt())/100 <= 10000) { ui->indlTab->item(i, 3)->setText\ (QString::number(ui->indlTab->item(i, 7)->text().toDouble() * \ (100 - ui->INDL_Max->text().toInt())/100, 'f', 0)); } else { ui->indlTab->item(i, 3)->setText("10000"); } } else { // } } INDL_Init_Flag = false; } void Widget_INDL::on_INDL_Min_editingFinished() { ui->INDL_Max->setValue(ui->INDL_Min->value()); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.5.19 * brief: 设置警告弹出框 电感 ******************************************************************************/ void Widget_INDL::Pri_INDL_WMessage(QString Waring_Text) { QMessageBox message; message.setWindowFlags(Qt::FramelessWindowHint); message.setStyleSheet\ ("QMessageBox{border: gray;border-radius: 10px;"\ "padding:2px 4px;background-color: gray;}"); message.setText("\n"+Waring_Text+"\n"); message.addButton(QMessageBox::Ok)->setStyleSheet\ ("height:39px;width:75px;border:5px groove;"\ "border:none;border-radius:10px;padding:2px 4px;"); message.setButtonText(QMessageBox::Ok, QString(tr("确 定"))); message.setIcon(QMessageBox::Warning); message.exec(); } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感通道清零 ******************************************************************************/ void Widget_INDL::on_Button_Comp_clicked() { QMessageBox message; message.setWindowFlags(Qt::FramelessWindowHint); message.setStyleSheet\ ("QMessageBox{border:3px groove gray;}background-color: rgb(209, 209, 157);"); message.setText(tr(" 请将清零的端子短接 \n 然后继续操作 ")); message.addButton(QMessageBox::Ok)->setStyleSheet\ ("border:none;height:30px;width:65px;border:5px groove gray;"\ "border-radius:10px;padding:2px 4px;"); message.addButton(QMessageBox::Cancel)->setStyleSheet\ ("border:none;height:30px;width:65px;border:5px groove gray;"\ "border-radius:10px;padding:2px 4px;"); message.setButtonText(QMessageBox::Ok, QString(tr("确 定"))); message.setButtonText(QMessageBox::Cancel, QString(tr("取 消"))); message.setIcon(QMessageBox::Warning); int ret = message.exec(); if (ret == QMessageBox::Ok) { Pri_INDL_Calibration_clear(); Lable_Display(); } if (ret == QMessageBox::Cancel) { // } } /****************************************************************************** * version: 1.0 * author: sl * date: 2016.11.5 * brief: INDL界面, 电感通道清零,下发参数 ******************************************************************************/ void Widget_INDL::Pri_INDL_Calibration_clear() { int i; int INDL_Zero_TestItemsL = 0; for (i = 0; i < 8; i++) { if (Box_INDL_Grade_List.at(i)->checkState() != 2) { continue; } frame.can_id = 0x26; frame.can_dlc = 0x07; frame.data[0] = 0x03; frame.data[1] = i; frame.data[2] = ui->indlTab->item(i, 1)->text().toInt(); // 抽头 frame.data[3] = ui->indlTab->item(i, 2)->text().toInt(); frame.data[4] = 0x01; if (ui->Com_fre->currentText() == "1K") { // frame.data[5] 频率 电压 档位 frame.data[5] = 0x0b; } else { frame.data[5] = 0x0c; } int connetct; // frame.data[6] 连接方式 电压增益 电流增益 if (ui->Com_connetct->currentText() == QString(tr("串联"))) { connetct = 0x00; } else { connetct = 0x40; } if (ui->indlTab->item(i, 10)->text() == "mH") { frame.data[6] = (int)(connetct|0x09); } else { if (ui->indlTab->item(i, 4)->text().toDouble() < 500) { frame.data[6] = (int)(connetct|0x0f); } else { frame.data[6] = (int)(connetct|0x09); } } INDL_Zero_TestItemsL = 1 << i; // 低字节 canSend(frame); usleep(500); break; // 勾选第一个进行 } if (INDL_Zero_TestItemsL != 0) { frame.can_id = 0x26; frame.can_dlc = 0x08; frame.data[0] = 0x01; frame.data[1] = 0x00; frame.data[2] = 0x01; frame.data[3] = 0x13; frame.data[4] = 0x00; frame.data[5] = INDL_Zero_TestItemsL; // 低字节 frame.data[6] = 0x07; frame.data[7] = 0x08; canSend(frame); usleep(500); } } QStringList Widget_INDL::INDL_Test_Param() { QString str; QStringList strSql; QStringList strParam, strTest; strTest.clear(); strParam.clear(); QStringList indl_unit; indl_unit.clear(); indl_unit << "u" << "m"; // << "H" for (int j = 0; j < 8; j++) { if (Box_INDL_Grade_List[j]->checkState() != 2) { // 电感 continue; } if (Copy_INDL_List[7] != "0.0") { str = QString(tr("电感")) + Copy_INDL_List.at(INDL_init_Number+20*j+0) + "-" \ + Copy_INDL_List.at(INDL_init_Number+20*j+1); // 电参 strTest.append(str); str.clear(); // indl_unit[Copy_INDL_List.at(INDL_init_Number+20*j+7).toInt()] + str = Copy_INDL_List.at(INDL_init_Number+20*j+2) + "-" + \ Copy_INDL_List.at(INDL_init_Number+20*j+3) + \ indl_unit[Copy_INDL_List.at(INDL_init_Number+20*j+7).toInt()] +", Q-"; str += Copy_INDL_List.at(INDL_init_Number+20*j+4) + "-" + \ Copy_INDL_List.at(INDL_init_Number+20*j+5); strParam.append(str); str.clear(); strSql.append(tr("电感")); } else { str = QString(tr("电感"))+ Copy_INDL_List.at(INDL_init_Number+20*j+0) + "-" + \ Copy_INDL_List.at(INDL_init_Number+20*j+1); // 电参 strTest.append(str); str.clear(); str = Copy_INDL_List.at(INDL_init_Number+20*j+2) + \ indl_unit[Copy_INDL_List.at(INDL_init_Number+20*j+7).toInt()] + "-" + \ Copy_INDL_List.at(INDL_init_Number+20*j+3) + \ indl_unit[Copy_INDL_List.at(INDL_init_Number+20*j+7).toInt()]; strParam.append(str); str.clear(); strSql.append(tr("电感")); } } if ((Copy_INDL_List[1] != "0.0") && (INDL_TestNumber >= 3)) { strTest.append(QString(tr("电感"))); strParam.append(QString(tr("不平衡度 ")) + Copy_INDL_List[1] + "%"); strSql.append(tr("电感")); } // -将(-电感-)修改为(电感) if ((Copy_INDL_List[7].toDouble() != 0.0)&&(INDL_TestNumber >= 3)) { strTest.append(QString(tr("Q值"))); strParam.append(QString(tr("不平衡度 ")) + Copy_INDL_List[7] + "%"); strSql.append(tr("电感")); } QStringList Back_List; Back_List.append(QString::number(strTest.size())); Back_List.append(QString::number(strParam.size())); Back_List.append(QString::number(strSql.size())); Back_List.append(strTest); Back_List.append(strParam); Back_List.append(strSql); return Back_List; }
41.782908
94
0.476619
Bluce-Song
c1551f37deeec9d8bfa5d44f56b4fab306d79839
3,809
cpp
C++
test/core/task_cancel_t.cpp
yuhonghong66/TorchCraftAI
895994989846be829fb0ed823a552008e807bdbe
[ "MIT" ]
1
2018-11-28T01:16:12.000Z
2018-11-28T01:16:12.000Z
test/core/task_cancel_t.cpp
MenLonII/TorchCraftAI
6920c6c02ee0043e6aa622fc0e5376cf97bc75e6
[ "MIT" ]
null
null
null
test/core/task_cancel_t.cpp
MenLonII/TorchCraftAI
6920c6c02ee0043e6aa622fc0e5376cf97bc75e6
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <cstdlib> #include <fstream> #include "scenario.h" #include "test.h" #include <glog/logging.h> #include "cherrypi.h" #include "modules.h" #include "player.h" #include "utils.h" using namespace cherrypi; namespace { class MockTacticsModule : public Module { public: MockTacticsModule() : Module() {} void step(State* state) override { auto board = state->board(); if (board->hasKey("target_posted") && board->get<bool>("target_posted")) { return; } // Post UPC for attacking enemy start location with all units auto loc = state->tcstate()->start_locations[1 - state->playerId()]; auto units = utils::filterUnits( state->unitsInfo().myUnits(), [](Unit const* u) { return u->active() && !u->type->isBuilding; }); if (units.size() == 0) { return; } postUpc(state, 1, units, loc.x, loc.y); board->post("target_posted", true); } void postUpc( State* state, int srcUpcId, std::vector<Unit*> const& units, int targetX, int targetY) { auto upc = std::make_shared<UPCTuple>(); for (Unit* u : units) { upc->unit[u] = 1.0f / units.size(); } upc->position = Position(targetX, targetY); upc->command[Command::Delete] = 0.9; upc->command[Command::Move] = 0.1; state->board()->postUPC(std::move(upc), srcUpcId, this); } }; /* * checks the overall workflow of cancelation */ class MockCombatModule : public CombatModule { public: MockCombatModule() : CombatModule() {} void step(State* state) override { CombatModule::step(state); if (deletedTasks_) { state->board()->post( "tasks properly deleted", state->board()->tasksOfModule(this).empty()); } for (auto& task : state->board()->tasksOfModule(this)) { if (task->status() == TaskStatus::Unknown) { continue; } if (!cancelledTasks_) { VLOG(1) << "canceling combat tasks"; task->cancel(state); cancelledTasks_ = true; } else { if (task->status() != TaskStatus::Cancelled) { LOG(ERROR) << "incorrect status for task " << task->upcId() << ", expected " << (int)TaskStatus::Cancelled << ", got " << (int)task->status(); state->board()->post("task properly cancelled", false); cancelledTasks_ = false; } else { VLOG(1) << "task cancelled"; state->board()->post("task properly cancelled", true); deletedTasks_ = true; } } } } private: bool cancelledTasks_ = false; bool deletedTasks_ = false; }; } // namespace SCENARIO("task_cancel/12_marines_vs_base") { auto scenario = Scenario("test/maps/12-marines-vs-base.scm", "Terran"); Player bot(scenario.makeClient()); bot.addModule(Module::make<TopModule>()); bot.addModule(Module::make<MockTacticsModule>()); auto combat = Module::make<MockCombatModule>(); bot.addModule(combat); auto combatMicro = Module::make<CombatMicroModule>(); bot.addModule(combatMicro); bot.addModule(Module::make<UPCToCommandModule>()); bot.init(); auto state = bot.state(); do { bot.step(); } while (!state->gameEnded() && bot.steps() <= 2000); EXPECT(state->unitsInfo().myUnits().empty() == false); EXPECT(state->board()->hasKey("task properly cancelled")); EXPECT(state->board()->get<bool>("task properly cancelled")); EXPECT(state->board()->hasKey("tasks properly deleted")); EXPECT(state->board()->get<bool>("tasks properly deleted")); for (auto& u : state->unitsInfo().myUnits()) { EXPECT(u->idle()); } }
28.007353
79
0.612497
yuhonghong66
c15610ad4f2b4e825c0d0a2764b50718b4973b32
7,560
cpp
C++
logview/mainwindow.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
8
2015-11-16T19:15:55.000Z
2021-02-17T23:58:33.000Z
logview/mainwindow.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
5
2015-11-12T00:19:59.000Z
2020-03-23T10:18:19.000Z
logview/mainwindow.cpp
Hayesie88/emstudio
0ae4353e5dcaa76b6306ff0aabd5a89999c4dc1b
[ "MIT" ]
11
2015-03-15T23:02:48.000Z
2021-09-05T14:17:13.000Z
/************************************************************************************ * EMStudio - Open Source ECU tuning software * * Copyright (C) 2020 Michael Carpenter (malcom2073@gmail.com) * * * * This file is a part of EMStudio is licensed MIT as * * defined in LICENSE.md at the top level of this repository * ************************************************************************************/ #include <QDebug> #include <QVBoxLayout> #include <QCheckBox> #include <QFileDialog> #include <QSettings> #include <QMessageBox> #include "mainwindow.h" #include "ui_mainwindow.h" #include "egraph.h" #include "qgraph.h" #include "graphview.h" #include "aboutdialog.h" #include "scatterplotview.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); m_progressDialog=0; // mapView = 0; connect(ui->actionOpen_Megasquirt_Log,SIGNAL(triggered()),this,SLOT(loadMegasquirtLog())); connect(ui->actionOpen_LibreEMS_Log,SIGNAL(triggered()),this,SLOT(loadLibreLog())); connect(ui->actionOpen_Embedded_Lockers_Log,SIGNAL(triggered()),this,SLOT(loadEBLLog())); connect(ui->actionClose_Log,SIGNAL(triggered()),this,SLOT(fileCloseClicked())); connect(ui->actionQuit,SIGNAL(triggered()),this,SLOT(fileQuitClicked())); connect(ui->actionAbout,SIGNAL(triggered()),this,SLOT(aboutMenuClicked())); connect(ui->actionExport_as_CSV,SIGNAL(triggered()),this,SLOT(exportCsvClicked())); //graph = new QGraph(this); //this->setCentralWidget(graph); //graph->setGeometry(100,100,800,600); //graph->show(); //dataSelectionScreen = new DataSelectionScreen(); //connect(dataSelectionScreen,SIGNAL(itemEnabled(QString)),this,SLOT(itemEnabled(QString))); //connect(dataSelectionScreen,SIGNAL(itemDisabled(QString)),this,SLOT(itemDisabled(QString))); //connect(ui->actionSelect_Dialog,SIGNAL(triggered()),this,SLOT(selectDialogClicked())); //dataSelectionScreen->setVisible(false); this->setAttribute(Qt::WA_DeleteOnClose,true); this->menuBar()->setNativeMenuBar(false); // connect(ui->addGraphButton,SIGNAL(clicked()),this,SLOT(addGraphButtonClicked())); // connect(ui->addMapButton,SIGNAL(clicked()),this,SLOT(addMapButtonClicked())); m_logLoaded = false; } void MainWindow::addGraphButtonClicked() { if (!m_logLoaded) { QMessageBox::information(0,"Error","Please load a log first"); return; } GraphView *view = new GraphView(); view->show(); view->passData(&variantList,m_logTypes); m_graphViewList.append(view); } void MainWindow::addMapButtonClicked() { ScatterPlotView *view = new ScatterPlotView(); view->setData(&variantList,m_logTypes); view->show(); return; if (!m_logLoaded) { QMessageBox::information(0,"Error","Please load a log first"); return; } MapView *mapView = new MapView(); mapView->show(); mapView->setGeometry(100,100,800,600); mapView->setData(&variantList,m_logTypes); m_mapViewList.append(mapView); } void MainWindow::logProgress(quint64 pos,quint64 total) { m_progressDialog->setValue(100.0 * ((double)pos / (double)total)); } MainWindow::~MainWindow() { //delete ui; //delete dataSelectionScreen; if (m_progressDialog) { delete m_progressDialog; } if (m_logLoaded) { //m_progressDialog = new QProgressDialog("Closing...","Cancel",0,100); //m_progressDialog->show(); //QApplication::instance()->processEvents(); //fileCloseClicked(); } } void MainWindow::payloadDecoded(QVariantMap map) { if (variantList.size() == 0) { //First incoming map. } variantList.append(map); } void MainWindow::threadDone() { m_progressDialog->hide(); delete m_progressDialog; m_progressDialog = 0; qDebug() << variantList.size() << "records loaded"; m_logLoaded = true; //sender()->deleteLater(); FEMSParser *parser = qobject_cast<FEMSParser*>(sender()); if (parser) { //It's a FEMS parser that sent this m_logTypes = parser->getLogTypes(); } } void MainWindow::loadMegasquirtLog () { QString filename = QFileDialog::getOpenFileName(this,"Select log file to open"); if (filename == "") { return; } fileCloseClicked(); MSParser *parser = new MSParser(this); connect(parser,SIGNAL(done()),this,SLOT(threadDone())); connect(parser,SIGNAL(loadProgress(quint64,quint64)),this,SLOT(logProgress(quint64,quint64))); connect(parser,SIGNAL(payloadDecoded(QVariantMap)),this,SLOT(payloadDecoded(QVariantMap))); connect(parser,SIGNAL(logData(QString,QString)),this,SLOT(logData(QString,QString))); m_progressDialog = new QProgressDialog("Loading file....","Cancel",0,100); m_progressDialog->show(); parser->loadLog(filename); } void MainWindow::loadLibreLog() { QString filename = QFileDialog::getOpenFileName(this,"Select log file to open",QString(),QString(),0,QFileDialog::DontUseCustomDirectoryIcons); if (filename == "") { return; } fileCloseClicked(); FEMSParser *parser = new FEMSParser(this); connect(parser,SIGNAL(done()),this,SLOT(threadDone())); connect(parser,SIGNAL(loadProgress(quint64,quint64)),this,SLOT(logProgress(quint64,quint64))); connect(parser,SIGNAL(payloadDecoded(QVariantMap)),this,SLOT(payloadDecoded(QVariantMap))); connect(parser,SIGNAL(logData(QString,QString)),this,SLOT(logData(QString,QString))); m_progressDialog = new QProgressDialog("Loading file....","Cancel",0,100); m_progressDialog->show(); parser->loadLog(filename); } void MainWindow::loadEBLLog() { QString filename = QFileDialog::getOpenFileName(this,"Select log file to open"); if (filename == "") { return; } fileCloseClicked(); EBLParser *parser = new EBLParser(this); connect(parser,SIGNAL(done()),this,SLOT(threadDone())); connect(parser,SIGNAL(loadProgress(quint64,quint64)),this,SLOT(logProgress(quint64,quint64))); connect(parser,SIGNAL(payloadDecoded(QVariantMap)),this,SLOT(payloadDecoded(QVariantMap))); connect(parser,SIGNAL(logData(QString,QString)),this,SLOT(logData(QString,QString))); m_progressDialog = new QProgressDialog("Loading file....","Cancel",0,100); m_progressDialog->show(); parser->loadLog(filename); } void MainWindow::fileCloseClicked() { variantList.clear(); for (int i=0;i<m_mapViewList.size();i++) { delete m_mapViewList.at(i); } m_mapViewList.clear(); for (int i=0;i<m_graphViewList.size();i++) { delete m_graphViewList.at(i); } m_graphViewList.clear(); m_logLoaded = false; } void MainWindow::fileQuitClicked() { this->close(); } void MainWindow::logData(QString key,QString val) { //ui->textBrowser->append(key + ": " + val); } void MainWindow::aboutMenuClicked() { AboutDialog *d = new AboutDialog(this); d->show(); } void MainWindow::exportCsvClicked() { QString filename = QFileDialog::getSaveFileName(this); if (filename == "") { return; } m_csvExporter = new Exporter_Csv(this); connect(m_csvExporter,SIGNAL(progress(int,int)),this,SLOT(exportProgress(int,int))); connect(m_csvExporter,SIGNAL(done()),this,SLOT(exportThreadDone())); m_csvExporter->startExport(filename,m_logTypes,variantList); m_progressDialog = new QProgressDialog("Exporting....","Cancel",0,100,this); m_progressDialog->show(); } void MainWindow::exportProgress(int pos,int total) { m_progressDialog->setValue(100.0 * ((double)pos / (double)total)); } void MainWindow::exportThreadDone() { m_progressDialog->hide(); delete m_progressDialog; m_progressDialog = 0; }
30.731707
144
0.693783
Hayesie88
c15a6e9462aad5a7e0f9244a61023309a0f960f2
2,099
cpp
C++
activemq-cpp/src/main/decaf/util/concurrent/atomic/AtomicBoolean.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
87
2015-03-02T17:58:20.000Z
2022-02-11T02:52:52.000Z
activemq-cpp/src/main/decaf/util/concurrent/atomic/AtomicBoolean.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
3
2017-05-10T13:16:08.000Z
2019-01-23T20:21:53.000Z
activemq-cpp/src/main/decaf/util/concurrent/atomic/AtomicBoolean.cpp
novomatic-tech/activemq-cpp
d6f76ede90d21b7ee2f0b5d4648e440e66d63003
[ "Apache-2.0" ]
71
2015-04-28T06:04:04.000Z
2022-03-15T13:34:06.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 "AtomicBoolean.h" #include <decaf/lang/Boolean.h> #include <decaf/internal/util/concurrent/Atomics.h> using namespace decaf; using namespace decaf::lang; using namespace decaf::util; using namespace decaf::util::concurrent; using namespace decaf::util::concurrent::atomic; using namespace decaf::internal::util::concurrent; //////////////////////////////////////////////////////////////////////////////// AtomicBoolean::AtomicBoolean() : value(0) { } //////////////////////////////////////////////////////////////////////////////// AtomicBoolean::AtomicBoolean( bool initialValue ) : value(initialValue ? 1 : 0) { } //////////////////////////////////////////////////////////////////////////////// bool AtomicBoolean::compareAndSet( bool expect, bool update ) { int upd = update ? 1 : 0; int exp = expect ? 1 : 0; return Atomics::compareAndSet32(&this->value, exp, upd); } //////////////////////////////////////////////////////////////////////////////// bool AtomicBoolean::getAndSet( bool newValue ) { return Atomics::getAndSet(&this->value, newValue) > 0 ? true : false; } //////////////////////////////////////////////////////////////////////////////// std::string AtomicBoolean::toString() const { return Boolean::toString( this->value ? true : false ); }
38.163636
81
0.594092
novomatic-tech
c15aa8ecbdc05e7b0e73d19824cae5012e571fd9
3,227
cpp
C++
source/formatConv.cpp
MIDA-group/itkAlphaAMD
60bd21338b2213371e6e48fa4ab2a8fbbc61d85e
[ "MIT" ]
1
2018-10-26T15:07:00.000Z
2018-10-26T15:07:00.000Z
source/formatConv.cpp
MIDA-group/itkAlphaAMD
60bd21338b2213371e6e48fa4ab2a8fbbc61d85e
[ "MIT" ]
1
2019-12-21T08:14:45.000Z
2020-02-21T17:28:46.000Z
source/formatConv.cpp
MIDA-group/itkAlphaAMD
60bd21338b2213371e6e48fa4ab2a8fbbc61d85e
[ "MIT" ]
null
null
null
/** * Small program for doing file format conversion. **/ #include <stdio.h> #include <string.h> #include <string> #include "Log.h" #include "common/itkImageProcessingTools.h" template <unsigned int Dim> void FormatConv(std::string in, std::string out, bool isLabel, bool is16Bit) { typedef itk::IPT<double, Dim> IPT; if(isLabel) { // is16Bit is ignored here, all label images are 16 bit in our world typename IPT::LabelImagePointer image = IPT::LoadLabelImage(in.c_str()); IPT::SaveLabelImage(out.c_str(), image); } else { std::cout << "Loading image" << std::endl; typename IPT::ImagePointer image = IPT::LoadImage(in.c_str()); std::cout << "Image loaded" << std::endl; itk::PrintStatistics<typename IPT::ImageType>(image, "Image"); if(is16Bit) IPT::SaveImageU16(out.c_str(), image); else IPT::SaveImageU8(out.c_str(), image); } } int main(int argc, char **argv) { bool vol3DMode = false; // Defaults std::string in; std::string out; bool isLabel = false; bool is16Bit = true; // Parameters for (int pi = 1; pi + 1 < argc; pi += 2) { char mod[512]; char arg[512]; sprintf(mod, "%s", argv[pi]); sprintf(arg, "%s", argv[pi + 1]); if (strcmp(mod, "-in") == 0) { in = arg; } else if (strcmp(mod, "-out") == 0) { out = arg; } else if (strcmp(mod, "-3d") == 0) { vol3DMode = (1 == (unsigned int)atoi(arg)); } else if (strcmp(mod, "-is_label") == 0) { isLabel = (1 == (unsigned int)atoi(arg)); } else if (strcmp(mod, "-is_16_bit") == 0) { is16Bit = (1 == (unsigned int)atoi(arg)); } } if(in.length() > 0 && out.length() > 0) { if (vol3DMode) { FormatConv<3U>(in, out, isLabel, is16Bit); } else { FormatConv<2U>(in, out, isLabel, is16Bit); } } else { if(in.length() == 0) std::cout << "Input file missing." << std::endl; if(out.length() == 0) std::cout << "Output file missing." << std::endl; } // Test read/write transforms itk::CompositeTransform<double, 2U>::Pointer comp = itk::CompositeTransform<double, 2U>::New(); itk::AffineTransform<double, 2U>::Pointer affine = itk::AffineTransform<double, 2U>::New(); itk::TranslationTransform<double, 2U>::Pointer translation = itk::TranslationTransform<double, 2U>::New(); typedef itk::AffineTransform<double, 2U>::ParametersType ParametersType; ParametersType affineTransformParam(6U); affineTransformParam[0] = 1; affineTransformParam[3] = 1; itk::AffineTransform<double, 2U>::InputPointType cor; affine->SetParameters(affineTransformParam); cor.Fill(12); affine->SetCenter(cor); comp->AddTransform(affine); comp->AddTransform(translation); typedef itk::IPT<double, 2U>::BaseTransformType BaseTransformType; typedef itk::IPT<double, 2U>::BaseTransformPointer BaseTransformPointer; itk::IPT<double, 2U>::BaseTransformPointer baseTransform = static_cast<BaseTransformType*>(comp.GetPointer()); itk::IPT<double, 2U>::SaveTransformFile("test.txt", baseTransform); BaseTransformPointer loadedTransform = itk::IPT<double, 2U>::LoadTransformFile("test.txt"); std::cout << (loadedTransform) << std::endl; return 0; }
25.409449
111
0.642392
MIDA-group
c15af3d0e38be40e7776de8adf696eb86ee1f657
1,068
cpp
C++
UVa Online Judge/12247.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
1
2022-02-24T12:44:30.000Z
2022-02-24T12:44:30.000Z
UVa Online Judge/12247.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
null
null
null
UVa Online Judge/12247.cpp
xiezeju/ACM-Code-Archives
db135ed0953adcf5c7ab37a00b3f9458291ce0d7
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; const int INF = 1e9; const long long LLINF = 4e18; const double EPS = 1e-9; int order[6][3] = { 0, 1, 2, 0, 2, 1, 1, 0, 2, 1, 2, 0, 2, 0, 1, 2, 1, 0, }; int used[55]; int f(int P[], int X, int Y) { for (int i = 1; i <= 52; ++ i) { if (!used[i]) { int min = 3; for (int t = 0; t < 6; ++ t) { int count = 0; if (P[order[t][0]] < X) { count ++; } if (P[order[t][1]] < Y) { count ++; } if (P[order[t][2]] < i) { count ++; } if (min > count) { min = count; } } if (min >= 2) { return i; } } } return -1; } int main() { ios::sync_with_stdio(false); int P[3], X, Y; while (~scanf("%d%d%d%d%d",&P[0],&P[1],&P[2],&X,&Y) && P[0]+P[1]+P[2]+X+Y) { for (int i = 1; i <= 52; ++ i) { used[i] = 0; } used[P[0]] = 1; used[P[1]] = 1; used[P[2]] = 1; used[X] = 1; used[Y] = 1; printf("%d\n",f(P, X, Y)); } return 0; }
15.705882
77
0.450375
xiezeju
c15d3e2d6315e3a096157ac58b12433af73bfdda
3,086
cpp
C++
snake.cpp
billlin0904/QSnake
07375173d9597ba3149cba5989c9122e90bb9c44
[ "MIT" ]
null
null
null
snake.cpp
billlin0904/QSnake
07375173d9597ba3149cba5989c9122e90bb9c44
[ "MIT" ]
null
null
null
snake.cpp
billlin0904/QSnake
07375173d9597ba3149cba5989c9122e90bb9c44
[ "MIT" ]
1
2021-01-15T19:44:40.000Z
2021-01-15T19:44:40.000Z
#include <QPainter> #include "gamestage.h" #include "snake.h" Snake::Snake(GameStage *stage) : dir_(Direction::NoMove) , growing_(7) , stage_(stage) { } QPointF Snake::head() const { return head_; } void Snake::setPause(bool pause) { is_pause_ = pause; } QList<QPointF> const & Snake::tail() const { return tail_; } Direction Snake::direction() const noexcept { return dir_; } void Snake::setDirection(Direction dir) noexcept { if (dir_ == Direction::MoveLeft && dir == Direction::MoveRight) { return; } if (dir_ == Direction::MoveRight && dir == Direction::MoveLeft) { return; } if (dir_ == Direction::MoveUp && dir == Direction::MoveDown) { return; } if (dir_ == Direction::MoveDown && dir == Direction::MoveUp) { return; } dir_ = dir; } QRectF Snake::boundingRect() const { auto minX = head_.x(); auto minY = head_.y(); auto maxX = head_.x(); auto maxY = head_.y(); for (auto p : tail_) { maxX = p.x() > maxX ? p.x() : maxX; maxY = p.y() > maxY ? p.y() : maxY; minX = p.x() < minX ? p.x() : minX; minY = p.y() < minY ? p.y() : minY; } const auto tl = mapFromScene(QPointF(minX, minY)); const auto br = mapFromScene(QPointF(maxX, maxY)); return QRectF(tl.x(), tl.y(), br.x() - tl.x() + SNAKE_SIZE, br.y() - tl.y() + SNAKE_SIZE); } QPainterPath Snake::shape() const { QPainterPath path; path.setFillRule(Qt::WindingFill); path.addRect(QRectF(0, 0, SNAKE_SIZE, SNAKE_SIZE)); for (auto p : tail_) { QPointF itemp = mapFromScene(p); path.addRect(QRectF(itemp.x(), itemp.y(), SNAKE_SIZE, SNAKE_SIZE)); } return path; } void Snake::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { painter->fillPath(shape(), Qt::yellow); } void Snake::advance(int step) { if (dir_ == Direction::NoMove) { return; } if (is_pause_) { return; } if (growing_ > 0) { auto tail = head_; tail_ << tail; growing_ -= 1; } else { tail_.removeFirst(); tail_ << head_; } QPointF target; switch (dir_) { case Direction::MoveUp: target = moveUp(); break; case Direction::MoveDown: target = moveDown(); break; case Direction::MoveLeft: target = moveLeft(); break; case Direction::MoveRight: target = moveRight(); break; case Direction::NoMove: break; } head_ = target; setPos(head_); growing_ += stage_->collision(this, target); } QPointF Snake::moveLeft() { QPointF targe = head_; targe.rx() -= 2; return targe; } QPointF Snake::moveRight() { QPointF targe = head_; targe.rx() += 2; return targe; } QPointF Snake::moveUp() { QPointF targe = head_; targe.ry() -= 2; return targe; } QPointF Snake::moveDown() { QPointF targe = head_; targe.ry() += 2; return targe; }
20.711409
83
0.557032
billlin0904
c15e3c785cb37a7398f6be00f7b4cbab557a3520
6,740
cpp
C++
modules/DGM/GraphWeiss.cpp
Pandinosaurus/DGM
33a2e9bdaf446378ec63c10b3a07b257e32aa1ef
[ "BSD-3-Clause" ]
188
2016-04-10T20:33:46.000Z
2022-01-03T10:40:44.000Z
modules/DGM/GraphWeiss.cpp
Pandinosaurus/DGM
33a2e9bdaf446378ec63c10b3a07b257e32aa1ef
[ "BSD-3-Clause" ]
25
2016-04-06T17:18:22.000Z
2021-12-15T13:23:31.000Z
modules/DGM/GraphWeiss.cpp
Pandinosaurus/DGM
33a2e9bdaf446378ec63c10b3a07b257e32aa1ef
[ "BSD-3-Clause" ]
55
2016-08-21T01:21:55.000Z
2021-12-02T11:09:58.000Z
#include "GraphWeiss.h" #include "macroses.h" namespace DirectGraphicalModels { // Constructor CGraphWeiss::CGraphWeiss(byte nStates) : IGraphPairwise(nStates) , m_IDx(0) {} // Destructor: clean up the Node objects CGraphWeiss::~CGraphWeiss(void) { size_t nNodes = m_vpNodes.size(); for (size_t n = 0; n < nNodes; n++) delete m_vpNodes.at(n); m_vpNodes.clear(); } void CGraphWeiss::reset(void) { size_t nNodes = m_vpNodes.size(); for (size_t n = 0; n < nNodes; n++) delete m_vpNodes.at(n); m_vpNodes.clear(); m_IDx = 0; } // Add a new node to the graph with specified potentional size_t CGraphWeiss::addNode(const Mat &pot) { Node *n = new Node(m_IDx, pot); m_vpNodes.push_back(n); return m_IDx++; } // Set or change the potential of node idx void CGraphWeiss::setNode(size_t node, const Mat &pot) { // Assertions DGM_ASSERT_MSG(node < m_vpNodes.size(), "Node %zu is out of range %zu", node, m_vpNodes.size()); if (!m_vpNodes.at(node)->Pot.empty()) m_vpNodes.at(node)->Pot.release(); pot.copyTo(m_vpNodes.at(node)->Pot); } // Return node potential vector void CGraphWeiss::getNode(size_t node, Mat &pot) const { // Assertions DGM_ASSERT_MSG(node < m_vpNodes.size(), "Node %zu is out of range %zu", node, m_vpNodes.size()); DGM_ASSERT_MSG(!m_vpNodes.at(node)->Pot.empty(), "Specified node %zu is not set", node); m_vpNodes.at(node)->Pot.copyTo(pot); } // Return child nodes ID's void CGraphWeiss::getChildNodes(size_t node, vec_size_t &vNodes) const { // Assertion DGM_ASSERT_MSG(node < m_vpNodes.size(), "Node %zu is out of range %zu", node, m_vpNodes.size()); for (size_t e_t = 0; e_t < m_vpNodes.at(node)->to.size(); e_t++) vNodes.push_back(m_vpNodes.at(node)->to.at(e_t)->node2->id); } // Return parent nodes ID's void CGraphWeiss::getParentNodes(size_t node, vec_size_t &vNodes) const { // Assertion DGM_ASSERT_MSG(node < m_vpNodes.size(), "Node %zu is out of range %zu", node, m_vpNodes.size()); for (size_t e_f = 0; e_f < m_vpNodes.at(node)->from.size(); e_f++) vNodes.push_back(m_vpNodes.at(node)->from.at(e_f)->node1->id); } size_t CGraphWeiss::getNumEdges(void) const { size_t res = 0; for (const Node* n : m_vpNodes) res += n->to.size(); return res; } // Add a new (directed) edge to the graph with specified potentional void CGraphWeiss::addEdge(size_t srcNode, size_t dstNode, byte group, const Mat &pot) { // Assertions DGM_ASSERT_MSG(srcNode < m_vpNodes.size(), "The source node index %zu is out of range %zu", srcNode, m_vpNodes.size()); DGM_ASSERT_MSG(dstNode < m_vpNodes.size(), "The destination node index %zu is out of range %zu", dstNode, m_vpNodes.size()); // Check if the edge exists for (size_t e_t = 0; e_t < m_vpNodes.at(srcNode)->to.size(); e_t++) { Edge *edge_to = m_vpNodes.at(srcNode)->to.at(e_t); DGM_ASSERT(edge_to->node2->id != m_vpNodes.at(dstNode)->id); } // e_t // Else: create a new one Edge *e = new Edge(m_vpNodes.at(srcNode), m_vpNodes.at(dstNode), group, pot); m_vpNodes.at(srcNode)->to.push_back(e); m_vpNodes.at(dstNode)->from.push_back(e); } // Set or change the potentional of an directed edge void CGraphWeiss::setEdge(size_t srcNode, size_t dstNode, const Mat &pot) { // Assertions DGM_ASSERT_MSG(srcNode < m_vpNodes.size(), "The source node index %zu is out of range %zu", srcNode, m_vpNodes.size()); DGM_ASSERT_MSG(dstNode < m_vpNodes.size(), "The destination node index %zu is out of range %zu", dstNode, m_vpNodes.size()); Edge* e = findEdge(srcNode, dstNode); DGM_ASSERT_MSG(e, "The edge (%zu)->(%zu) is not found", srcNode, dstNode); pot.copyTo(e->Pot); } void CGraphWeiss::setEdges(std::optional<byte> group, const Mat& pot) { for (Node* n : m_vpNodes) for (Edge* e : n->to) if (!group || e->group_id == group.value()) pot.copyTo(e->Pot); } // Return edge potential matrix void CGraphWeiss::getEdge(size_t srcNode, size_t dstNode, Mat &pot) const { // Assertions DGM_ASSERT_MSG(srcNode < m_vpNodes.size(), "The source node index %zu is out of range %zu", srcNode, m_vpNodes.size()); DGM_ASSERT_MSG(dstNode < m_vpNodes.size(), "The destination node index %zu is out of range %zu", dstNode, m_vpNodes.size()); Edge* e = findEdge(srcNode, dstNode); DGM_ASSERT_MSG(e, "The edge (%zu)->(%zu) is not found", srcNode, dstNode); e->Pot.copyTo(pot); } void CGraphWeiss::setEdgeGroup(size_t srcNode, size_t dstNode, byte group) { // Assertions DGM_ASSERT_MSG(srcNode < m_vpNodes.size(), "The source node index %zu is out of range %zu", srcNode, m_vpNodes.size()); DGM_ASSERT_MSG(dstNode < m_vpNodes.size(), "The destination node index %zu is out of range %zu", dstNode, m_vpNodes.size()); Edge* e = findEdge(srcNode, dstNode); DGM_ASSERT_MSG(e, "The edge (%zu)->(%zu) is not found", srcNode, dstNode); e->group_id = group; } byte CGraphWeiss::getEdgeGroup(size_t srcNode, size_t dstNode) const { // Assertions DGM_ASSERT_MSG(srcNode < m_vpNodes.size(), "The source node index %zu is out of range %zu", srcNode, m_vpNodes.size()); DGM_ASSERT_MSG(dstNode < m_vpNodes.size(), "The destination node index %zu is out of range %zu", dstNode, m_vpNodes.size()); Edge* e = findEdge(srcNode, dstNode); DGM_ASSERT_MSG(e, "The edge (%zu)->(%zu) is not found", srcNode, dstNode); return e->group_id; } void CGraphWeiss::removeEdge(size_t srcNode, size_t dstNode) { // Assertions DGM_ASSERT_MSG(srcNode < m_vpNodes.size(), "The source node index %zu is out of range %zu", srcNode, m_vpNodes.size()); DGM_ASSERT_MSG(dstNode < m_vpNodes.size(), "The destination node index %zu is out of range %zu", dstNode, m_vpNodes.size()); Edge* e = findEdge(srcNode, dstNode); if (!e) { DGM_WARNING("The edge (%zu)->(%zu) is not found", srcNode, dstNode); return; } auto it = std::find(m_vpNodes[srcNode]->to.begin(), m_vpNodes[srcNode]->to.end(), e); m_vpNodes[srcNode]->to.erase(it); it = std::find(m_vpNodes[dstNode]->from.begin(), m_vpNodes[dstNode]->from.end(), e); m_vpNodes[dstNode]->from.erase(it); delete e; } bool CGraphWeiss::isEdgeExists(size_t srcNode, size_t dstNode) const { // Assertions DGM_ASSERT_MSG(srcNode < m_vpNodes.size(), "The source node index %zu is out of range %zu", srcNode, m_vpNodes.size()); DGM_ASSERT_MSG(dstNode < m_vpNodes.size(), "The destination node index %zu is out of range %zu", dstNode, m_vpNodes.size()); return findEdge(srcNode, dstNode) ? true : false; } CGraphWeiss::Edge* CGraphWeiss::findEdge(size_t srcNode, size_t dstNode) const { for (Edge *edge_to : m_vpNodes[srcNode]->to) if (edge_to->node2->id == dstNode) return edge_to; return NULL; } }
33.532338
126
0.684866
Pandinosaurus
c15e786fee61a4dffb6f9d1187f537ae2308be4f
650
cpp
C++
Insert Interval.cpp
jahnvisrivastava100/Leetcode-Solutions
d3acdb1fac94afc704c233235c8914004fe4c846
[ "CC0-1.0" ]
null
null
null
Insert Interval.cpp
jahnvisrivastava100/Leetcode-Solutions
d3acdb1fac94afc704c233235c8914004fe4c846
[ "CC0-1.0" ]
null
null
null
Insert Interval.cpp
jahnvisrivastava100/Leetcode-Solutions
d3acdb1fac94afc704c233235c8914004fe4c846
[ "CC0-1.0" ]
null
null
null
class Solution { public: vector<vector<int>> insert(vector<vector<int>>& I, vector<int>& nI) { vector<vector<int>>res; int i=0, n =size(I); while(i<n && I[i][1] < nI[0] ){//for non overlaping cases res.push_back(I[i]); i++; } vector<int>mI=nI; while(i<n && I[i][0] <= mI[1]){//for overlaping intervals mI[0]=min(I[i][0],mI[0]); mI[1]=max(I[i][1],mI[1]); i++; } res.push_back(mI); while(i<n){ res.push_back(I[i]); i++; } return res; } };
23.214286
73
0.404615
jahnvisrivastava100
c15e881205eb186e6a6c43d0908ccd95d480c91c
610
cpp
C++
apps/myApps/Doshi_u1212719/BehaviorAlgorithms/BehaviorTree/BT.cpp
wanted28496/AIForGames
8b958452ccf268ecd54990135a7a3dd154cab6d4
[ "MIT" ]
null
null
null
apps/myApps/Doshi_u1212719/BehaviorAlgorithms/BehaviorTree/BT.cpp
wanted28496/AIForGames
8b958452ccf268ecd54990135a7a3dd154cab6d4
[ "MIT" ]
null
null
null
apps/myApps/Doshi_u1212719/BehaviorAlgorithms/BehaviorTree/BT.cpp
wanted28496/AIForGames
8b958452ccf268ecd54990135a7a3dd154cab6d4
[ "MIT" ]
null
null
null
#include "BT.h" #include "BTTick.h" #include "BTAction.h" #include "BTBlackboard.h" BT::BT(unsigned int iNodeID, BTTaskBase * iRootNode, BTBlackboard * iBlackboard) : mNodeID(iNodeID), mRootNode(iRootNode), mBlackboard(iBlackboard) { unsigned int i = 0; SetTask(mRootNode, i); } void BT::SetTask(BTTaskBase * iTask, unsigned int & id) { iTask->SetNodeID(id); id++; auto& children = iTask->GetChildren(); for (int i = 0; i < children.size(); i++) { SetTask(children[i], id); } } void BT::Update(float dt) { BTTick* tick = new BTTick(this, mBlackboard); mRootNode->Run(tick); } BT::~BT() { }
17.428571
147
0.668852
wanted28496
c15fcc75e874ce6260fe6ffcba76d171fe94309c
43,778
cpp
C++
Samples/Win7Samples/winbase/rdc/client/RdcSdkTestClient.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/winbase/rdc/client/RdcSdkTestClient.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/winbase/rdc/client/RdcSdkTestClient.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "stdafx.h" #include <new> #include "msrdc.h" #include <string> #include <memory> #include <RdcSdkTestServer.h> #include "smartFileHandle.h" #include "sampleUnknownImpl.h" #include "rdcSdkTestClient.h" #include "simplefilenametable.h" using namespace std; // Size of the buffer used to copy data from source or seed file to the target file. static const size_t g_InputBufferSize = 8192; static const wchar_t g_similarityTableName[] = L"RdcSampleTraitsTable"; static const wchar_t g_filenameTableName[] = L"RdcSampleFilenameTable"; static const unsigned g_maxResults = 10; static BOOL g_deleteSignatures = TRUE; static BOOL g_reuse = FALSE; static BOOL g_createtarget = TRUE; static BOOL g_saveneeds = FALSE; static BOOL g_similarity = FALSE; static ULONG g_recursionDepth = 0; static ULONG g_horizonSize1 = MSRDC_DEFAULT_HORIZONSIZE_1; static ULONG g_horizonSizeN = MSRDC_DEFAULT_HORIZONSIZE_N; static ULONG g_hashWindowSize1 = MSRDC_DEFAULT_HASHWINDOWSIZE_1; static ULONG g_hashWindowSizeN = MSRDC_DEFAULT_HASHWINDOWSIZE_N; /*+--------------------------------------------------------------------------- Class: LocalRdcFileReader Purpose: Provide the IRdcFileReader interface necessary for the MSRDC comparator object. This class simply forwards the call on to the native interfaces. Notes: ----------------------------------------------------------------------------*/ class LocalRdcFileReader : public IRdcFileReader { public: LocalRdcFileReader() : m_Handle ( INVALID_HANDLE_VALUE ) {} virtual ~LocalRdcFileReader() {} void Set ( HANDLE h ) { RDCAssert ( !IsValid() ); m_Handle = h; } bool IsValid() const { return m_Handle != 0 && m_Handle != INVALID_HANDLE_VALUE; } STDMETHOD ( GetFileSize ) ( ULONGLONG * fileSize ) { RDCAssert ( IsValid() ); DebugHresult hr = S_OK; *fileSize = 0; LARGE_INTEGER position = {0}; if ( !GetFileSizeEx ( m_Handle, &position ) ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } else { *fileSize = position.QuadPart; } return hr; } STDMETHOD ( Read ) ( ULONGLONG offsetFileStart, ULONG bytesToRead, ULONG * bytesActuallyRead, BYTE * buffer, BOOL * eof ) { RDCAssert ( IsValid() ); DebugHresult hr = S_OK; *bytesActuallyRead = 0; *eof = FALSE; OVERLAPPED overlapped = {0}; overlapped.Offset = static_cast<DWORD> ( offsetFileStart & 0xffffffff ); overlapped.OffsetHigh = static_cast<DWORD> ( offsetFileStart >> 32 ); if ( ReadFile ( m_Handle, buffer, bytesToRead, bytesActuallyRead, &overlapped ) ) { if ( *bytesActuallyRead < bytesToRead ) { // we must be at EOF *eof = TRUE; } } else { *bytesActuallyRead = 0; hr = HRESULT_FROM_WIN32 ( GetLastError() ); } return hr; } STDMETHOD ( GetFilePosition ) ( ULONGLONG * offsetFromStart ) { RDCAssert ( false ); return E_NOTIMPL; } private: HANDLE m_Handle; }; /*+--------------------------------------------------------------------------- Class: MyFileTransferRdcFileReader Purpose: Provide the IRdcFileReader interface necessary for the MSRDC comparator object. This class simply forwards the call on to RdcSdkTestServer for reading the source and seed signatures. An instance of this object is created for each level of signatures to be read. Notes: ----------------------------------------------------------------------------*/ class MyFileTransferRdcFileReader : public IRdcFileReader { public: MyFileTransferRdcFileReader() : m_SignatureLevel ( ( ULONG ) - 1 ) {} virtual ~MyFileTransferRdcFileReader() {} void Set ( ULONG signatureLevel, IRdcFileTransfer *iRdcFileTransfer, RdcFileHandle rdcFileHandle ) { // Only allow a single initialization RDCAssert ( m_SignatureLevel == ( ULONG ) - 1 ); m_SignatureLevel = signatureLevel; m_RdcFileTransfer = iRdcFileTransfer; m_RdcFileHandle = rdcFileHandle; } STDMETHOD ( GetFileSize ) ( ULONGLONG * fileSize ) { // Assert that we have been initialized RDCAssert ( m_SignatureLevel != ( ULONG ) - 1 ); if ( m_SignatureLevel == ( ULONG ) - 1 ) { return E_FAIL; } DebugHresult hr = m_RdcFileTransfer->GetFileSize ( &m_RdcFileHandle, m_SignatureLevel, fileSize ); return hr; } STDMETHOD ( Read ) ( ULONGLONG offsetFileStart, ULONG bytesToRead, ULONG * bytesActuallyRead, BYTE * buffer, BOOL * eof ) { // Assert that we have been initialized RDCAssert ( m_SignatureLevel != ( ULONG ) - 1 ); if ( m_SignatureLevel == ( ULONG ) - 1 ) { return E_FAIL; } *eof = FALSE; DebugHresult hr = m_RdcFileTransfer->ReadData ( &m_RdcFileHandle, m_SignatureLevel, offsetFileStart, bytesToRead, bytesActuallyRead, buffer ); if ( SUCCEEDED ( hr ) ) { if ( *bytesActuallyRead < bytesToRead ) { *eof = TRUE; } } return hr; } STDMETHOD ( GetFilePosition ) ( ULONGLONG * offsetFromStart ) { RDCAssert ( false ); return E_NOTIMPL; } private: ULONG m_SignatureLevel; CComPtr<IRdcFileTransfer> m_RdcFileTransfer; RdcFileHandle m_RdcFileHandle; }; /*+--------------------------------------------------------------------------- Class: SignatureFileInfo Purpose: Used to call into the RdcSdkTestServer and maintain the state information necessary for each open file. In this sample, there are 2 open files: the source and the seed. Notes: ----------------------------------------------------------------------------*/ class SignatureFileInfo { public: SignatureFileInfo() { Clear(); } DebugHresult OpenRemoteFile ( wchar_t const *sourceMachineName, wchar_t const *sourceFileName, ULONG recursionDepth ); DebugHresult OpenLocalFile ( wchar_t const *sourceFileName, ULONG recursionDepth ) { return OpenRemoteFile ( 0, sourceFileName, recursionDepth ); } DebugHresult GetSimilarityData ( SimilarityData *similarityData ) { if ( m_RdcFileTransfer ) { return m_RdcFileTransfer->GetSimilarityData ( similarityData ); } return E_FAIL; } /*---------------------------------------------------------------------------- Name: CreateSignatureFileReader Create a MyFileTransferRdcFileReader() to provide the input to the MSRDC Comparator. Arguments: signatureLevel Which signature level will be read reader The resulting interface. Returns: ----------------------------------------------------------------------------*/ DebugHresult CreateSignatureFileReader ( ULONG signatureLevel, IRdcFileReader **reader ) { DebugHresult hr = S_OK; RDCAssert ( signatureLevel <= MSRDC_MAXIMUM_DEPTH ); *reader = 0; MyFileTransferRdcFileReader *p = new ( std::nothrow ) SampleUnknownImpl<MyFileTransferRdcFileReader, IRdcFileReader>(); if ( p ) { p->Set ( signatureLevel, m_RdcFileTransfer, m_RdcFileHandle ); *reader = p; p->AddRef(); } else { hr = E_OUTOFMEMORY; } return hr; } ULONG getRdcSignatureDepth() const { return m_RdcFileTransferInfo.m_SignatureDepth; } ULONGLONG GetFileSize() const { return m_RdcFileTransferInfo.m_FileSize; } private: wchar_t m_Filename[ MAX_PATH ]; RdcFileTransferInfo m_RdcFileTransferInfo; RdcFileHandle m_RdcFileHandle; CComPtr<IRdcFileTransfer> m_RdcFileTransfer; void Clear() { memset ( m_Filename, 0, sizeof ( m_Filename ) ); memset ( &m_RdcFileTransferInfo, 0, sizeof ( m_RdcFileTransferInfo ) ); memset ( &m_RdcFileHandle, 0, sizeof ( m_RdcFileHandle ) ); } }; /*--------------------------------------------------------------------------- Name: SignatureFileInfo::OpenRemoteFile Connect to RdcSdkTestServer remotely, or locally if the server name is not provided. Arguments: sourceMachineName The remote machine name, or NULL. sourceFileName The filename. Must be of the form C:\fullpath\filename recursionDepth The signature depth to generate. Returns: ----------------------------------------------------------------------------*/ DebugHresult SignatureFileInfo::OpenRemoteFile ( wchar_t const *sourceMachineName, wchar_t const *sourceFileName, ULONG recursionDepth ) { DebugHresult hr = S_OK; if ( wcslen ( sourceFileName ) >= ARRAYSIZE ( m_Filename ) ) { // Path is too long. return E_INVALIDARG; } wcsncpy_s ( m_Filename, ARRAYSIZE ( m_Filename ), sourceFileName, _TRUNCATE ); m_Filename[ ARRAYSIZE ( m_Filename ) - 1 ] = 0; COSERVERINFO serverInfo = { 0, ( LPWSTR ) sourceMachineName, 0, 0 }; MULTI_QI mQI = { &__uuidof ( IRdcFileTransfer ), 0, S_OK }; hr = CoCreateInstanceEx ( __uuidof ( RdcFileTransfer ), 0, sourceMachineName ? CLSCTX_REMOTE_SERVER : ( CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER ), &serverInfo, 1, &mQI ); if ( SUCCEEDED ( hr ) ) { m_RdcFileTransfer.Attach ( ( IRdcFileTransfer* ) mQI.pItf ); m_RdcFileTransferInfo.m_SignatureDepth = recursionDepth; hr = m_RdcFileTransfer->RdcOpenFile ( m_Filename, &m_RdcFileTransferInfo, &m_RdcFileHandle, g_deleteSignatures, g_horizonSize1, g_horizonSizeN, g_hashWindowSize1, g_hashWindowSizeN ); } return hr; } /*---------------------------------------------------------------------------- Name: CopyDataToTarget Copy data from either the source or seed file to the target file. Arguments: fromFile file reader for the source or seed file. fileOffset Offset into the source or seed file. blockLength Length of the block to be copied targetFile Handle to the target file. ----------------------------------------------------------------------------*/ DebugHresult CopyDataToTarget ( IRdcFileReader *fromFile, ULONGLONG fileOffset, ULONGLONG blockLength, HANDLE targetFile ) { DebugHresult hr = S_OK; if ( targetFile == INVALID_HANDLE_VALUE || targetFile == 0 ) { return hr; } // Copy a buffer full of data at a time. BYTE buffer[ g_InputBufferSize ]; BOOL eof = FALSE; while ( blockLength && !eof && SUCCEEDED ( hr ) ) { ULONG length = static_cast<ULONG> ( min ( blockLength, sizeof ( buffer ) ) ); ULONG bytesActuallyRead = 0; hr = fromFile->Read ( fileOffset, length, &bytesActuallyRead, buffer, &eof ); if ( length != bytesActuallyRead ) { printf ( "Read failed x%x, length=%d, bytesActuallyRead=%d\n", hr, length, bytesActuallyRead ); } if ( SUCCEEDED ( hr ) ) { ULONG bytesActuallyWritten = 0; if ( !WriteFile ( targetFile, buffer, bytesActuallyRead, &bytesActuallyWritten, 0 ) ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } if ( bytesActuallyRead != bytesActuallyWritten ) { printf ( "Oops, write failed, error = x%x, bytesActuallyRead=%d, bytesActuallyWritten=%d\n", hr, bytesActuallyRead, bytesActuallyWritten ); } fileOffset += bytesActuallyRead; blockLength -= bytesActuallyRead; RDCAssert ( eof || bytesActuallyRead == length ); } } if ( eof ) { printf ( "FAILED: EOF reached\n" ); } return hr; } void CheckPosition ( ULONGLONG offset, HANDLE file ) { LARGE_INTEGER zero = {0}; LARGE_INTEGER newPos; if ( SetFilePointerEx ( file, zero, &newPos, FILE_CURRENT ) ) { if ( static_cast<ULONGLONG> ( newPos.QuadPart ) != offset ) { printf ( "Target file position incorrect, is %I64d, should be %I64d, diff=%I64d\n", newPos.QuadPart, offset, offset - newPos.QuadPart ); } } } void sPrintTraits ( string &str, const SimilarityData & traits ) { static const int bufferSize = 100; char hexBuffer[ bufferSize ]; str.clear(); for ( int i = 0; i < ARRAYSIZE ( traits.m_Data ); ++i ) { if ( i != 0 ) str.append ( "-" ); sprintf_s ( hexBuffer, ARRAYSIZE ( hexBuffer ), "%02X", traits.m_Data[ i ] ); str.append ( hexBuffer ); } } void MakeSignatureFileName ( ULONG level, wchar_t ( &sigFileName ) [ MAX_PATH ], wchar_t const *sourceFileName ) { RDCAssert ( level <= MSRDC_MAXIMUM_DEPTH ); if ( level > 0 ) { int n = _snwprintf_s ( sigFileName, ARRAYSIZE ( sigFileName ), _TRUNCATE, L"%s_%d.sig", sourceFileName, level ); RDCAssert ( n != -1 ); UNREFERENCED_PARAMETER ( n ); } else { wcsncpy_s ( sigFileName, ARRAYSIZE ( sigFileName ), sourceFileName, _TRUNCATE ); } sigFileName[ ARRAYSIZE ( sigFileName ) - 1 ] = 0; } /*---------------------------------------------------------------------------- Name: CompareFiles Creates and uses an MSRDC Comparator object to compare the given signature files and constructs the target file. On error, the target file should be deleted by the caller. Arguments: seedSignatures file reader for the seed signatures. (Connected to local RdcSdkTestServer) seedFile file reader for the seed file. (Connected to local RdcSdkTestServer) sourceSignatures file reader for the source signatures. (Connected to remote RdcSdkTestServer) sourceFile file reader for the source file. (Connected to remote RdcSdkTestServer) targetFile NT file handle for the target. bytesFromSource bytesFromSeed ----------------------------------------------------------------------------*/ DebugHresult CompareFiles ( IRdcFileReader *seedSignatures, IRdcFileReader *seedFile, IRdcFileReader *sourceSignatures, IRdcFileReader *sourceFile, HANDLE targetFile, HANDLE needsFile, ULONGLONG *bytesFromSource, ULONGLONG *bytesToTarget, ULONGLONG *bytesFromSeed ) { ULONGLONG totalSeedData = 0; ULONGLONG totalSourceData = 0; ULONGLONG totalSourceSignature = 0; ULONGLONG targetOffset = 0; ULONG needsCount = 0; CComQIPtr<IRdcLibrary> rdcLibrary; CComPtr<IRdcComparator> rdcComparator; // Load the MSRDC inproc DebugHresult hr = rdcLibrary.CoCreateInstance ( __uuidof ( RdcLibrary ), 0, CLSCTX_INPROC_SERVER ); if ( SUCCEEDED ( hr ) ) { hr = rdcLibrary->CreateComparator ( seedSignatures, 1000000 /*MSRDC_MINIMUM_COMPAREBUFFER */, &rdcComparator ); } if ( SUCCEEDED ( hr ) ) { RDC_ErrorCode rdc_ErrorCode = RDC_NoError; BOOL eof = false; BOOL eofOutput = false; DebugHresult hr = S_OK; // Buffer for streaming remote signatures into the comparator. BYTE inputBuffer[ g_InputBufferSize ]; RdcNeed needsArray[ 256 ]; RdcBufferPointer inputPointer = {0}; RdcNeedPointer outputPointer = {0}; ULONGLONG signatureFileOffset = 0; while ( SUCCEEDED ( hr ) && !eofOutput ) { // When the inputPointer is empty, (or first time in this loop) // fill it from the source signature file reader. if ( inputPointer.m_Size == inputPointer.m_Used && !eof ) { ULONG bytesActuallyRead = 0; hr = sourceSignatures->Read ( signatureFileOffset, sizeof ( inputBuffer ), &bytesActuallyRead, inputBuffer, &eof ); // eof is set to true when Read() has read the last byte of // the source signatures. We pass this flag along to the // Comparator. The comparitor will never set eofOutput until // after eof has been set. if ( SUCCEEDED ( hr ) ) { inputPointer.m_Data = inputBuffer; inputPointer.m_Size = bytesActuallyRead; inputPointer.m_Used = 0; signatureFileOffset += bytesActuallyRead; totalSourceSignature += bytesActuallyRead; } } // Initialize the output needs array outputPointer.m_Size = ARRAYSIZE ( needsArray ); outputPointer.m_Used = 0; outputPointer.m_Data = needsArray; if ( SUCCEEDED ( hr ) ) { // Do the comparison operation. // This function may not produce needs output every time. // Also, it may not use all available input each time either. // You may call it with any number of input bytes // and output needs array entries. Obviously, it is more // efficient to given it reasonably sized buffers for each. // This sample waits until Process() consumes an entire input // buffer before reading more data from the source signatures file. // Continue calling this function until it sets "eofOutput" to true. hr = rdcComparator->Process ( eof, &eofOutput, &inputPointer, &outputPointer, &rdc_ErrorCode ); } if ( SUCCEEDED ( hr ) ) { // Empty the needs array completely. for ( ULONG i = 0; i < outputPointer.m_Used; ++i ) { switch ( needsArray[ i ].m_BlockType ) { case RDCNEED_SOURCE: totalSourceData += needsArray[ i ].m_BlockLength; hr = CopyDataToTarget ( sourceFile, needsArray[ i ].m_FileOffset, needsArray[ i ].m_BlockLength, targetFile ); break; case RDCNEED_SEED: totalSeedData += needsArray[ i ].m_BlockLength; hr = CopyDataToTarget ( seedFile, needsArray[ i ].m_FileOffset, needsArray[ i ].m_BlockLength, targetFile ); break; default: hr = E_FAIL; } char needsBuffer[ 256 ]; int n = _snprintf_s ( needsBuffer, ARRAYSIZE ( needsBuffer ), ARRAYSIZE ( needsBuffer ), "NEED: length:%12I64d" "\toffset:%12I64d" "\tsource:%12I64d" "\tblock type:%s\n", needsArray[ i ].m_BlockLength, needsArray[ i ].m_FileOffset, targetOffset, needsArray[ i ].m_BlockType == RDCNEED_SOURCE ? "source" : "seed" ); needsBuffer[ ARRAYSIZE ( needsBuffer ) - 1 ] = 0; if ( needsFile != INVALID_HANDLE_VALUE && needsFile != 0 ) { DWORD written; WriteFile ( needsFile, needsBuffer, n, &written, 0 ); } else { fputs ( needsBuffer, stdout ); } targetOffset += needsArray[ i ].m_BlockLength; CheckPosition ( targetOffset, targetFile ); ++needsCount; } } } } if ( FAILED ( hr ) ) { printf ( "Comparison FAILED, error = x%x\n", hr ); } *bytesFromSource = totalSourceData + totalSourceSignature; *bytesToTarget = totalSourceData + totalSeedData; *bytesFromSeed = totalSeedData; printf ( "Compare: Total Seed Bytes: %I64d, Total Source Bytes: %I64d\n", totalSeedData, *bytesFromSource ); return hr; } void openTraitsTable ( CComQIPtr<ISimilarityTraitsTable> &similarityTraitsTable ) { DebugHresult hr; BYTE *securityDescriptor = 0; RdcCreatedTables tableState; hr = similarityTraitsTable.CoCreateInstance ( __uuidof ( SimilarityTraitsTable ) ); similarityTraitsTable->CreateTable ( const_cast<wchar_t*> ( g_similarityTableName ), FALSE, securityDescriptor, &tableState ); string tableStateString; if ( RDCTABLE_New == tableState ) { tableStateString = "new"; } else if ( RDCTABLE_Existing == tableState ) { tableStateString = "existing"; } else { tableStateString = "unknown or invalid"; RDCAssert ( false ); } printf ( "similarity traits table \"%S\" state is: %s\n", g_similarityTableName, tableStateString.c_str() ); } void printSimilarityResults ( FindSimilarFileIndexResults *results, const DWORD &used, SimpleFilenameTable &t ) { printf ( "%u similarity results were found:\n\n", used ); for ( UINT i = 0; i < used; ++i ) { wstring s; t.lookup ( results[ i ].m_FileIndex, s ); printf ( "\t%u traits matches\t\"%S\"\n", results[ i ].m_MatchCount, s.c_str() ); } printf ( "\n", used ); } /*---------------------------------------------------------------------------- Name: Transfer Transfer a file from a remote host to the local machine. Arguments: remoteMachineName remoteFilename localFilename targetFilename ----------------------------------------------------------------------------*/ DebugHresult Transfer ( wchar_t const *remoteMachineName, wchar_t const *remoteFilename, wchar_t const *localFilename, wchar_t const *targetFilename ) { DebugHresult hr = S_OK; SignatureFileInfo remoteFile; // Connect to RDCSDKTestServer on the remote host hr = remoteFile.OpenRemoteFile ( remoteMachineName, remoteFilename, g_recursionDepth ); ULONG remoteDepth = 0; if ( SUCCEEDED ( hr ) ) { remoteDepth = remoteFile.getRdcSignatureDepth(); } SimilarityData sourceTraits; remoteFile.GetSimilarityData ( &sourceTraits ); SignatureFileInfo localFile; CComQIPtr<ISimilarityTraitsTable> similarityTraitsTable; auto_ptr<SimpleFilenameTable> filenameTable; wstring localFilenameStr; if ( g_similarity ) { openTraitsTable ( similarityTraitsTable ); filenameTable.reset ( new SimpleFilenameTable() ); filenameTable->deserialize ( const_cast<wchar_t*> ( g_filenameTableName ) ); FindSimilarFileIndexResults results[ g_maxResults ] = {0}; DWORD used = 0; hr = similarityTraitsTable->FindSimilarFileIndex ( &sourceTraits, MSRDC_MINIMUM_MATCHESREQUIRED, results, ARRAYSIZE ( results ), &used ); if ( used > 0 ) { printSimilarityResults ( results, used, *filenameTable ); filenameTable->lookup ( results[ 0 ].m_FileIndex, localFilenameStr ); printf ( "Using first entry for similarity.\n" ); localFilename = localFilenameStr.c_str(); } else { printf ( "Similarity was requested, but no matches were found.\n" ); } } printf ( "\nseed name is \"%S\"\n", localFilename ); if ( SUCCEEDED ( hr ) ) { // Connect to RDCSDKTestServer on the local host hr = localFile.OpenLocalFile ( localFilename, remoteDepth ); } ULONG localDepth = 0; if ( SUCCEEDED ( hr ) ) { localDepth = localFile.getRdcSignatureDepth(); } SmartFileHandle localSourceSHandle; SmartFileHandle targetFile; wchar_t sourceSigName[ MAX_PATH ] = {0}; wchar_t needsName[ MAX_PATH + 6 ] = {0}; // +".Needs" CComPtr<IRdcFileReader> seedSignatures; CComPtr<IRdcFileReader> sourceSignatures; CComPtr<IRdcFileReader> seedFile; CComPtr<IRdcFileReader> sourceFile; if ( SUCCEEDED ( hr ) ) { hr = remoteFile.CreateSignatureFileReader ( remoteDepth, &sourceSignatures ); } ULONGLONG bytesFromSourceTotal = 0; ULONGLONG bytesToTargetTotal = 0; for ( ULONG i = remoteDepth; i > 0 && SUCCEEDED ( hr ); --i ) { MakeSignatureFileName ( i - 1, sourceSigName, targetFilename ); wcsncpy_s ( needsName, ARRAYSIZE ( needsName ), sourceSigName, _TRUNCATE ); wcscat_s ( needsName, ARRAYSIZE ( needsName ), L".needs" ); if ( g_createtarget || i > 1 ) { // always create target if target is signature file targetFile.Set ( CreateFile ( sourceSigName, GENERIC_WRITE, FILE_SHARE_DELETE, 0, CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0 ) ); if ( !targetFile.IsValid() ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } } SmartFileHandle needsFile; if ( g_saveneeds ) { // always create target if target is signature file needsFile.Set ( CreateFile ( needsName, GENERIC_WRITE, FILE_SHARE_DELETE, 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0 ) ); if ( !needsFile.IsValid() ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } } if ( SUCCEEDED ( hr ) ) { hr = localFile.CreateSignatureFileReader ( i, &seedSignatures ); } if ( SUCCEEDED ( hr ) ) { hr = localFile.CreateSignatureFileReader ( i - 1, &seedFile ); } if ( SUCCEEDED ( hr ) ) { hr = remoteFile.CreateSignatureFileReader ( i - 1, &sourceFile ); } if ( SUCCEEDED ( hr ) ) { wprintf ( L"\n\n----------\nTransferring: %s\n----------\n\n", sourceSigName ); ULONGLONG bytesFromSource = 0; ULONGLONG bytesToTarget = 0; ULONGLONG bytesFromSeed = 0; hr = CompareFiles ( seedSignatures, seedFile, sourceSignatures, sourceFile, targetFile.GetHandle(), needsFile.GetHandle(), &bytesFromSource, &bytesToTarget, &bytesFromSeed ); bytesFromSourceTotal += bytesFromSource; bytesToTargetTotal += bytesToTarget; if ( targetFile.IsValid() ) { if ( FAILED ( hr ) ) { DeleteFile ( sourceSigName ); } } } targetFile.Close(); localSourceSHandle.Close(); if ( i > 1 ) { localSourceSHandle.Set ( CreateFile ( sourceSigName, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0 ) ); if ( !localSourceSHandle.IsValid() ) { hr = HRESULT_FROM_WIN32 ( GetLastError() ); } if ( SUCCEEDED ( hr ) ) { sourceSignatures.Release(); LocalRdcFileReader *r = new ( std::nothrow ) SampleUnknownImpl<LocalRdcFileReader, IRdcFileReader>(); r->Set ( localSourceSHandle.GetHandle() ); r->AddRef(); sourceSignatures.Attach ( r ); } } if ( g_deleteSignatures ) { MakeSignatureFileName ( i, sourceSigName, targetFilename ); DeleteFile ( sourceSigName ); } sourceFile.Release(); seedSignatures.Release(); seedFile.Release(); } if ( SUCCEEDED ( hr ) ) { ULONGLONG fileSize = remoteFile.GetFileSize(); double savings = 0; if ( bytesFromSourceTotal > fileSize || fileSize == 0 ) { savings = 0; } else { savings = ( double ) ( fileSize - bytesFromSourceTotal ) / fileSize * 100; } printf ( "\n\n----------------------------------------" ); printf ( "\nTransfer : %I64d bytes from source, file size: %I64d, RDC Savings: %2.2f%%, toTargetTotal=%I64d bytes\n", bytesFromSourceTotal, fileSize, savings, bytesToTargetTotal ); printf ( "\n\n----------------------------------------\n\n" ); } if ( SUCCEEDED ( hr ) ) { string traitsStr; sPrintTraits ( traitsStr, sourceTraits ); printf ( "target trait: %s\n", traitsStr.c_str() ); if ( !similarityTraitsTable ) { openTraitsTable ( similarityTraitsTable ); } SimilarityFileIndexT last; hr = similarityTraitsTable->GetLastIndex ( &last ); hr = similarityTraitsTable->Append ( &sourceTraits, ++last ); hr = similarityTraitsTable->CloseTable ( TRUE ); if ( !filenameTable.get() ) { filenameTable.reset ( new SimpleFilenameTable() ); filenameTable->deserialize ( const_cast<wchar_t*> ( g_filenameTableName ) ); } filenameTable->insert ( last, targetFilename ); filenameTable->serialize ( const_cast<wchar_t*> ( g_filenameTableName ) ); } return hr; } DebugHresult CheckVersion() { CComQIPtr<IRdcLibrary> rdcLibrary; ULONG currentVersion = 0; ULONG minimumCompatibleAppVersion = 0; // Load the MSRDC inproc DebugHresult hr = rdcLibrary.CoCreateInstance ( __uuidof ( RdcLibrary ), 0, CLSCTX_INPROC_SERVER ); if ( SUCCEEDED ( hr ) ) { hr = rdcLibrary->GetRDCVersion ( &currentVersion, &minimumCompatibleAppVersion ); } if ( SUCCEEDED ( hr ) ) { if ( currentVersion < MSRDC_MINIMUM_COMPATIBLE_APP_VERSION ) { printf ( "The library is older (%d.%d) that I can accept (%d.%d)\n", HIWORD ( currentVersion ), LOWORD ( currentVersion ), HIWORD ( MSRDC_MINIMUM_COMPATIBLE_APP_VERSION ), LOWORD ( MSRDC_MINIMUM_COMPATIBLE_APP_VERSION ) ); hr = E_FAIL; } else if ( minimumCompatibleAppVersion > MSRDC_VERSION ) { printf ( "The library is newer (%d.%d) that I can accept (%d.%d)\n", HIWORD ( minimumCompatibleAppVersion ), LOWORD ( minimumCompatibleAppVersion ), HIWORD ( MSRDC_VERSION ), LOWORD ( MSRDC_VERSION ) ); hr = E_FAIL; } } return hr; } void Usage ( int argc, wchar_t * argv[] ) { const wchar_t * p = wcschr ( argv[ 0 ], L'\\' ); if ( p ) { ++p; } else { p = argv[ 0 ]; } char const str[] = "Usage: %ws <optional parameters> -c remoteMachine remoteFile(source) localFile(seed) targetfile\n\n" "\t-k\t\tkeep signature files.\n" // "\t-reuse\t\tkeep re-use signature files.\n" "\t-notarget\tdon't build the target -- compare only\n" "\t-saveneeds\tsave the needs information to targetfile.needs\n" "\t-similarity\tuse similarity to override seed selection\n" "\t-r <depth>\trecursion depth\n" "\t-hs1 <size>\t1st recursion level horizon size min=%d max=%d default=%d\n" "\t-hsn <size>\t2+ recursion level horizon size min=%d max=%d default=%d\n" "\t-hws1 <size>\t1st recursion level hash window size min=%d max=%d default=%d\n" "\t-hwsn <size>\t2+ recursion level hash window size min=%d max=%d default=%d\n"; printf ( str, p, MSRDC_MINIMUM_HORIZONSIZE, MSRDC_MAXIMUM_HORIZONSIZE, MSRDC_DEFAULT_HORIZONSIZE_1, MSRDC_MINIMUM_HORIZONSIZE, MSRDC_MAXIMUM_HORIZONSIZE, MSRDC_DEFAULT_HORIZONSIZE_N, MSRDC_MINIMUM_HASHWINDOWSIZE, MSRDC_MAXIMUM_HASHWINDOWSIZE, MSRDC_DEFAULT_HASHWINDOWSIZE_1, MSRDC_MINIMUM_HASHWINDOWSIZE, MSRDC_MAXIMUM_HASHWINDOWSIZE, MSRDC_DEFAULT_HASHWINDOWSIZE_N ); } int __cdecl wmain ( int argc, wchar_t * argv[] ) { wchar_t const * args[ 4 ]; CoInitWrapper coInit; DebugHresult hr = S_OK; int i; for ( i = 1; i < argc; ++i ) { if ( argv[ i ][ 0 ] != L'-' ) { Usage ( argc, argv ); exit ( 1 ); } else if ( argv[ i ][ 1 ] == L'k' ) { g_deleteSignatures = FALSE; } else if ( _wcsicmp ( &argv[ i ][ 1 ], L"reuse" ) == 0 ) { g_reuse = TRUE; } else if ( _wcsicmp ( &argv[ i ][ 1 ], L"notarget" ) == 0 ) { g_createtarget = FALSE; } else if ( _wcsicmp ( &argv[ i ][ 1 ], L"saveneeds" ) == 0 ) { g_saveneeds = TRUE; } else if ( _wcsicmp ( &argv[ i ][ 1 ], L"similarity" ) == 0 ) { g_similarity = TRUE; } else if ( argv[ i ][ 1 ] == L'c' ) { ++i; break; } else if ( argv[ i ][ 1 ] == L'r' ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_DEPTH ) { printf ( "\n\nRequested recursion depth -- \"%i\" is greater than the maximum MSRDC recursion depth (%i).\n\n", t, MSRDC_MAXIMUM_DEPTH ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_DEPTH ) { printf ( "\nRequested recursion depth -- \"%i\" is less than the minimum MSRDC recursion depth (%i).\n\n", t, MSRDC_MINIMUM_DEPTH ); Usage ( argc, argv ); exit ( 1 ); } else { g_recursionDepth = t; } } else if ( wcscmp ( argv[ i ] + 1, L"hs1" ) == 0 ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_HORIZONSIZE ) { printf ( "\n\nRequested horizon size -- \"%i\" is greater than the maximum MSRDC horizon size (%i).\n\n", t, MSRDC_MAXIMUM_HORIZONSIZE ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_HORIZONSIZE ) { printf ( "\n\nRequested horizon size -- \"%i\" is less than the minimum MSRDC horizon size (%i).\n\n", t, MSRDC_MINIMUM_HORIZONSIZE ); Usage ( argc, argv ); exit ( 1 ); } else { g_horizonSize1 = t; } } else if ( wcscmp ( argv[ i ] + 1, L"hsn" ) == 0 ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_HORIZONSIZE ) { printf ( "\n\nRequested horizon size -- \"%i\" is greater than the maximum MSRDC horizon size (%i).\n\n", t, MSRDC_MAXIMUM_HORIZONSIZE ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_HORIZONSIZE ) { printf ( "\n\nRequested horizon size -- \"%i\" is less than the minimum MSRDC horizon size (%i).\n\n", t, MSRDC_MINIMUM_HORIZONSIZE ); Usage ( argc, argv ); exit ( 1 ); } else { g_horizonSizeN = t; } } else if ( wcscmp ( argv[ i ] + 1, L"hws1" ) == 0 ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_HASHWINDOWSIZE ) { printf ( "\n\nRequested hash window size -- \"%i\" is greater than the maximum MSRDC hash window size (%i).\n\n", t, MSRDC_MAXIMUM_HASHWINDOWSIZE ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_HASHWINDOWSIZE ) { printf ( "\n\nRequested hash window size -- \"%i\" is less than the maximinimummum MSRDC hash window size (%i).\n\n", t, MSRDC_MINIMUM_HASHWINDOWSIZE ); Usage ( argc, argv ); exit ( 1 ); } else { g_hashWindowSize1 = t; } } else if ( wcscmp ( argv[ i ] + 1, L"hwsn" ) == 0 ) { wchar_t * p = argv[ ++i ]; ULONG t = wcstoul ( p, &p, 10 ); if ( t > MSRDC_MAXIMUM_HASHWINDOWSIZE ) { printf ( "\n\nRequested hash window size -- \"%i\" is greater than the maximum MSRDC hash window size (%i).\n\n", t, MSRDC_MAXIMUM_HASHWINDOWSIZE ); Usage ( argc, argv ); exit ( 1 ); } else if ( t < MSRDC_MINIMUM_HASHWINDOWSIZE ) { printf ( "\n\nRequested hash window size -- \"%i\" is less than the minimum MSRDC hash window size (%i).\n\n", t, MSRDC_MINIMUM_HASHWINDOWSIZE ); Usage ( argc, argv ); exit ( 1 ); } else { g_hashWindowSizeN = t; } } else { printf ( "\nInvalid parameter: %ws\n\n", argv[ i ] ); Usage ( argc, argv ); exit ( 1 ); } } char *argPurpose [] = {"Remote machine", "Remote file (source)", "Local file (seed)", "Target file"}; int argCount = 0; while ( i < argc ) { args[ argCount++ ] = argv[ i++ ]; } if ( argCount < ARRAYSIZE ( argPurpose ) ) { printf ( "\n%s must be specified.\n\n", argPurpose[ argCount ] ); Usage ( argc, argv ); exit ( 1 ); } hr = coInit.GetHRESULT(); if ( SUCCEEDED ( hr ) ) { hr = CheckVersion(); } if ( SUCCEEDED ( hr ) ) { hr = Transfer ( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] ); } LPVOID lpMsgBuf; FormatMessage ( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, hr, 0, // Default language ( LPTSTR ) & lpMsgBuf, 0, NULL ); _tprintf ( _T ( "Error code: x%08x :: %s" ), hr, lpMsgBuf ); LocalFree ( lpMsgBuf ); if ( FAILED ( hr ) ) { exit ( 1 ); } return 0; }
33.015083
169
0.49036
windows-development
c16422c107ccc84451d2b236f67c3d92592738ff
1,158
cpp
C++
vislib/src/sys/COMException.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
vislib/src/sys/COMException.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
vislib/src/sys/COMException.cpp
masrice/megamol
d48fc4889f500528609053a5445202a9c0f6e5fb
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * COMException.cpp * * Copyright (C) 2006 - 2012 by Visualisierungsinstitut Universitaet Stuttgart. * Alle Rechte vorbehalten. */ #include "vislib/sys/COMException.h" /* * vislib::sys::COMException::COMException */ #ifdef _WIN32 vislib::sys::COMException::COMException(const HRESULT hr, const char* file, const int line) : Super(file, line) { _com_error ce(hr); this->setMsg(ce.ErrorMessage()); } #else /* _WIN32 */ vislib::sys::COMException::COMException(const char* file, const int line) : Super("COMException", file, line) { // Nothing to do. } #endif /* _WIN32 */ /* * vislib::sys::COMException::COMException */ vislib::sys::COMException::COMException(const COMException& rhs) : Super(rhs) { // Nothing to do. } /* * vislib::sys::COMException::~COMException */ vislib::sys::COMException::~COMException(void) { // Nothing to do. } /* * vislib::sys::COMException::operator = */ vislib::sys::COMException& vislib::sys::COMException::operator=(const COMException& rhs) { if (this != &rhs) { Super::operator=(rhs); #ifdef _WIN32 this->hr = rhs.hr; #endif /* _WIN32 */ } return *this; }
21.849057
113
0.659758
masrice
c16757cb4d61960300b92eb5ef4bb4dc01c83568
800
hpp
C++
include/x_copy_paste.hpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
include/x_copy_paste.hpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
include/x_copy_paste.hpp
langenhagen/barn-bookmark-manager
e7db7dba34e92c74ad445d088b57559dbba26f63
[ "MIT" ]
null
null
null
/* Utility functions for easy reading from and writing to the x window system clipboard. Use the external utility `xclip` rather than implemting clipboard capabilities for the X application. This serves 2 purposes. First, avoid the necessity for the caller to implement an x11 application and avoid the complex setup for clipboard capabilities in x window applications. Second, allow access to the clipboard after the calling process terminated. author: andreasl */ #pragma once #include <string> namespace barn { namespace x11 { namespace cp { /*Write the given string to the x window clipboard.*/ void write_to_clipboard(const std::string& str); /*Return a string from the x window clipboard.*/ std::string get_text_from_clipboard(); } // namespace cp } // namespace x11 } // namespace barn
29.62963
100
0.77875
langenhagen
c167f118ba97e7ff21871be25ee3cc62b2574dcf
784
cpp
C++
src/main/cpp/ByteReader.cpp
alexnsouza6/JavaVirtualMachine
d0e1702cc7f68f2a71a6b139326fcd13685e44de
[ "MIT" ]
null
null
null
src/main/cpp/ByteReader.cpp
alexnsouza6/JavaVirtualMachine
d0e1702cc7f68f2a71a6b139326fcd13685e44de
[ "MIT" ]
1
2018-09-24T00:08:56.000Z
2018-09-24T00:08:56.000Z
src/main/cpp/ByteReader.cpp
alexnsouza6/JavaVirtualMachine
d0e1702cc7f68f2a71a6b139326fcd13685e44de
[ "MIT" ]
2
2018-12-09T17:44:49.000Z
2018-12-10T16:41:40.000Z
#ifndef ___BYTEREADER_H___ #define ___BYTEREADER_H___ #define NEUTRAL_BYTE_FOR_OR 0x00; /** * @brief Classe ByteReader. No momento da instanciação define-se qual tipo deseja-se buscar * E assim quando acionado o método byteCatch(FILE * fp) o arquivo busca o binário correspondente. */ template <class T> class ByteReader { public: T byteCatch(FILE * fp); }; /** * @brief byteCatch(FILE * fp) busca o binário correspondendo ao tipo T. * @param FILE * fp : arquivo de acesso. */ template <class T> T ByteReader<T>::byteCatch(FILE * fp) { int num_of_bytes = sizeof(T); T toReturn = NEUTRAL_BYTE_FOR_OR; for(int i = 0; i < num_of_bytes; i++) { toReturn = ((toReturn << 8) | getc(fp)); } return toReturn; } #endif // ___BYTEREADER_H___
23.058824
98
0.678571
alexnsouza6
c169629e883214292d37f58709924011cbd1456d
2,156
cpp
C++
A.cpp
MaowMan/cpp-sprout
64c261a49f02d3070d5c97480f3b71c0ac102f0e
[ "MIT" ]
null
null
null
A.cpp
MaowMan/cpp-sprout
64c261a49f02d3070d5c97480f3b71c0ac102f0e
[ "MIT" ]
null
null
null
A.cpp
MaowMan/cpp-sprout
64c261a49f02d3070d5c97480f3b71c0ac102f0e
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <cstdio> #include <set> int main(){ long long n; std::cin>>n; if (n==2){ long long nxt; std::cin>>nxt; if (nxt==1){ putchar('2'); putchar('\n'); } else{ putchar('1'); putchar('\n'); } } else if (n==3){ long long a,b; std::cin>>a>>b; if (a-(b-a)>0){ std::cout<<a-(b-a)<<std::endl; } else{ if((b-a)%2==0){ std::cout<<a+(b-a)/2<<std::endl; } else{ std::cout<<b+(b-a)<<std::endl; } } } else if(n==4){ long long a,b,c; std::cin>>a>>b>>c; if((b-a)==(c-b)){ if (a-(b-a)>0){ std::cout<<a-(b-a)<<std::endl; } else{ std::cout<<c+(b-a)<<std::endl; } } else{ if((b-a)>(c-b)){ std::cout<<a+(b-a)/2<<std::endl; } else{ std::cout<<b+(c-b)/2<<std::endl; } } } else{ long long a,b,c,d; std::cin>>a>>b>>c>>d; if(((b-a)==(c-b))&&((d-c)==(c-b))){ long long log=(b-a); long long prev,next,cache; prev=c; next=d; while(std::cin>>cache){ prev=next; next=cache; if ((next-prev)!=log){ std::cout<<prev+(next-prev)/2<<std::endl; return 0; } } if ((a-log)>0){ std::cout<<(a-log)<<std::endl; } else{ std::cout<<(next+log)<<std::endl; } } else{ if((b-a)==(c-b)){ std::cout<<c+(d-c)/2<<std::endl; } else if((b-a)==(d-c)){ std::cout<<b+(c-b)/2<<std::endl; } else{ std::cout<<a+(b-a)/2<<std::endl; } return 0; } } }
23.182796
61
0.306586
MaowMan
c16a28ae38352f6dccf39197bdf35e2145fab1a5
4,560
cpp
C++
extensions/aws/processors/DeleteS3Object.cpp
dtrodrigues/nifi-minifi-cpp
87147e2dffcda6cc6e4e0510a57cc88011fda37f
[ "Apache-2.0", "OpenSSL" ]
113
2016-04-30T15:00:13.000Z
2022-03-26T20:42:58.000Z
extensions/aws/processors/DeleteS3Object.cpp
dtrodrigues/nifi-minifi-cpp
87147e2dffcda6cc6e4e0510a57cc88011fda37f
[ "Apache-2.0", "OpenSSL" ]
688
2016-04-28T17:52:38.000Z
2022-03-29T07:58:05.000Z
extensions/aws/processors/DeleteS3Object.cpp
dtrodrigues/nifi-minifi-cpp
87147e2dffcda6cc6e4e0510a57cc88011fda37f
[ "Apache-2.0", "OpenSSL" ]
104
2016-04-28T15:20:51.000Z
2022-03-01T13:39:20.000Z
/** * @file DeleteS3Object.cpp * DeleteS3Object class implementation * * 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 "DeleteS3Object.h" #include <set> #include <memory> #include "core/Resource.h" namespace org { namespace apache { namespace nifi { namespace minifi { namespace aws { namespace processors { const core::Property DeleteS3Object::ObjectKey( core::PropertyBuilder::createProperty("Object Key") ->withDescription("The key of the S3 object. If none is given the filename attribute will be used by default.") ->supportsExpressionLanguage(true) ->build()); const core::Property DeleteS3Object::Version( core::PropertyBuilder::createProperty("Version") ->withDescription("The Version of the Object to delete") ->supportsExpressionLanguage(true) ->build()); const core::Relationship DeleteS3Object::Success("success", "FlowFiles are routed to success relationship"); const core::Relationship DeleteS3Object::Failure("failure", "FlowFiles are routed to failure relationship"); void DeleteS3Object::initialize() { // Add new supported properties setSupportedProperties({Bucket, AccessKey, SecretKey, CredentialsFile, CredentialsFile, AWSCredentialsProviderService, Region, CommunicationsTimeout, EndpointOverrideURL, ProxyHost, ProxyPort, ProxyUsername, ProxyPassword, UseDefaultCredentials, ObjectKey, Version}); // Set the supported relationships setSupportedRelationships({Failure, Success}); } std::optional<aws::s3::DeleteObjectRequestParameters> DeleteS3Object::buildDeleteS3RequestParams( const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::FlowFile> &flow_file, const CommonProperties &common_properties) const { aws::s3::DeleteObjectRequestParameters params(common_properties.credentials, client_config_); context->getProperty(ObjectKey, params.object_key, flow_file); if (params.object_key.empty() && (!flow_file->getAttribute("filename", params.object_key) || params.object_key.empty())) { logger_->log_error("No Object Key is set and default object key 'filename' attribute could not be found!"); return std::nullopt; } logger_->log_debug("DeleteS3Object: Object Key [%s]", params.object_key); context->getProperty(Version, params.version, flow_file); logger_->log_debug("DeleteS3Object: Version [%s]", params.version); params.bucket = common_properties.bucket; params.setClientConfig(common_properties.proxy, common_properties.endpoint_override_url); return params; } void DeleteS3Object::onTrigger(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSession> &session) { logger_->log_trace("DeleteS3Object onTrigger"); std::shared_ptr<core::FlowFile> flow_file = session->get(); if (!flow_file) { context->yield(); return; } auto common_properties = getCommonELSupportedProperties(context, flow_file); if (!common_properties) { session->transfer(flow_file, Failure); return; } auto params = buildDeleteS3RequestParams(context, flow_file, *common_properties); if (!params) { session->transfer(flow_file, Failure); return; } if (s3_wrapper_.deleteObject(*params)) { logger_->log_debug("Successfully deleted S3 object '%s' from bucket '%s'", params->object_key, common_properties->bucket); session->transfer(flow_file, Success); } else { logger_->log_error("Failed to delete S3 object '%s' from bucket '%s'", params->object_key, common_properties->bucket); session->transfer(flow_file, Failure); } } REGISTER_RESOURCE(DeleteS3Object, "This Processor deletes FlowFiles on an Amazon S3 Bucket."); } // namespace processors } // namespace aws } // namespace minifi } // namespace nifi } // namespace apache } // namespace org
40
151
0.75
dtrodrigues
c16b99ef3cd00876bc466ffa454bd2460d2da6cf
774
cpp
C++
CSCI-104/labs/lab4/part2/src/pokemon.cpp
liyang990803/CSCI-103
6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a
[ "MIT" ]
null
null
null
CSCI-104/labs/lab4/part2/src/pokemon.cpp
liyang990803/CSCI-103
6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a
[ "MIT" ]
null
null
null
CSCI-104/labs/lab4/part2/src/pokemon.cpp
liyang990803/CSCI-103
6f84fbc242be90f7a9c3a58bdcc6f54352e4ae5a
[ "MIT" ]
1
2018-03-23T04:19:24.000Z
2018-03-23T04:19:24.000Z
#include "../lib/pokemon.h" #include <cstdlib> Pokemon::Pokemon(std::string n, int h) { name = n; maxhp = h; hp = h; offense = std::rand() % 4 + 6; defense = std::rand() % 5 + 1; } void Pokemon::setMoves(AttackMove* a, AttackMove* b, AttackMove* c, AttackMove* d) { moves.clear(); moves.push_back(a); moves.push_back(b); moves.push_back(c); moves.push_back(d); } int Pokemon::attackPowerOf(int i) { return moves[i]->getPotency() * offense / 10; } int Pokemon::attackedBy(int power) { int damaged = power * (10 - defense) / 10; hp -= damaged; return damaged; } int Pokemon::getHP() { return (hp > 0) ? hp : 0; } std::string Pokemon::getName() { return name; } std::string Pokemon::getMove(int i) { return moves[i]->getName(); }
18
68
0.618863
liyang990803
c16f747647ccb6ccf0e135f0703a310a62eed779
590
cpp
C++
Codeforces/Presents.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
1
2018-08-28T19:58:40.000Z
2018-08-28T19:58:40.000Z
Codeforces/Presents.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
2
2017-04-16T00:48:05.000Z
2017-08-03T20:12:26.000Z
Codeforces/Presents.cpp
aajjbb/contest-files
b8842681b96017063a7baeac52ae1318bf59d74d
[ "Apache-2.0" ]
4
2016-03-04T19:42:00.000Z
2018-01-08T11:42:00.000Z
#include <iostream> #include <algorithm> #include <vector> #include <sstream> using namespace std; int main() { int n, temp; vector<int> v; vector<int>::iterator it; string s; stringstream ss; cin >> n; getline(cin, s); getline(cin, s); ss << s; while(ss >> temp) { v.push_back(temp); } for(int i = 0; i < v.size(); i++) { for(int j = 0; j < v.size(); j++) { if(i + 1 == v[j]) { cout << j + 1 << " "; break; } } } return 0; }
17.352941
45
0.420339
aajjbb
c16fcb448f300c8ccd412297f4be4b9e0d43a547
4,085
cpp
C++
ThirdParty/TLD/src/NNClassifier.cpp
abhineet123/MTF
6cb45c88d924fb2659696c3375bd25c683802621
[ "BSD-3-Clause" ]
100
2016-12-11T00:34:06.000Z
2022-01-27T23:03:40.000Z
ThirdParty/TLD/src/NNClassifier.cpp
siqiyan/MTF
9a76388c907755448bb7223420fe74349130f636
[ "BSD-3-Clause" ]
21
2017-09-04T06:27:13.000Z
2021-07-14T19:07:23.000Z
ThirdParty/TLD/src/NNClassifier.cpp
siqiyan/MTF
9a76388c907755448bb7223420fe74349130f636
[ "BSD-3-Clause" ]
21
2017-02-19T02:12:11.000Z
2020-09-23T03:47:55.000Z
/* Copyright 2011 AIT Austrian Institute of Technology * * This file is part of OpenTLD. * * OpenTLD 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. * * OpenTLD 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 OpenTLD. If not, see <http://www.gnu.org/licenses/>. * */ /* * NNClassifier.cpp * * Created on: Nov 16, 2011 * Author: Georg Nebehay */ #ifdef _WIN32 #pragma warning(disable:4244) #endif #include "mtf/ThirdParty/TLD/NNClassifier.h" #include "mtf/ThirdParty/TLD/DetectorCascade.h" #include "mtf/ThirdParty/TLD/TLDUtil.h" using namespace std; using namespace cv; namespace tld { NNClassifier::NNClassifier() { thetaFP = .5; thetaTP = .65f; truePositives = new vector<NormalizedPatch>(); falsePositives = new vector<NormalizedPatch>(); } NNClassifier::~NNClassifier() { release(); delete truePositives; delete falsePositives; } void NNClassifier::release() { falsePositives->clear(); truePositives->clear(); } float NNClassifier::ncc(float *f1, float *f2) { double corr = 0; double norm1 = 0; double norm2 = 0; int size = TLD_PATCH_SIZE * TLD_PATCH_SIZE; for(int i = 0; i < size; i++) { corr += f1[i] * f2[i]; norm1 += f1[i] * f1[i]; norm2 += f2[i] * f2[i]; } // normalization to <0,1> return (corr / sqrt(norm1 * norm2) + 1) / 2.0; } float NNClassifier::classifyPatch(NormalizedPatch *patch) { if(truePositives->empty()) { return 0; } if(falsePositives->empty()) { return 1; } float ccorr_max_p = 0; //Compare patch to positive patches for(size_t i = 0; i < truePositives->size(); i++) { float ccorr = ncc(truePositives->at(i).values, patch->values); if(ccorr > ccorr_max_p) { ccorr_max_p = ccorr; } } float ccorr_max_n = 0; //Compare patch to negative patches for(size_t i = 0; i < falsePositives->size(); i++) { float ccorr = ncc(falsePositives->at(i).values, patch->values); if(ccorr > ccorr_max_n) { ccorr_max_n = ccorr; } } float dN = 1 - ccorr_max_n; float dP = 1 - ccorr_max_p; float distance = dN / (dN + dP); return distance; } float NNClassifier::classifyBB(const Mat &img, Rect *bb) { NormalizedPatch patch; tldExtractNormalizedPatchRect(img, bb, patch.values); return classifyPatch(&patch); } float NNClassifier::classifyWindow(const Mat &img, int windowIdx) { NormalizedPatch patch; int *bbox = &windows[TLD_WINDOW_SIZE * windowIdx]; tldExtractNormalizedPatchBB(img, bbox, patch.values); return classifyPatch(&patch); } bool NNClassifier::filter(const Mat &img, int windowIdx) { if(!enabled) return true; float conf = classifyWindow(img, windowIdx); if(conf < thetaTP) { return false; } return true; } void NNClassifier::learn(vector<NormalizedPatch> patches) { //TODO: Randomization might be a good idea here for(size_t i = 0; i < patches.size(); i++) { NormalizedPatch patch = patches[i]; float conf = classifyPatch(&patch); if(patch.positive && conf <= thetaTP) { truePositives->push_back(patch); } if(!patch.positive && conf >= thetaFP) { falsePositives->push_back(patch); } } } } /* namespace tld */
21.613757
73
0.598776
abhineet123
c17311fe4d62f2041e8a6d68bdedc80b5266f9cd
833
cpp
C++
src/pan.cpp
Dam-0/grid
5a522de1383c55c199804176d9591abeb3a04d41
[ "MIT" ]
null
null
null
src/pan.cpp
Dam-0/grid
5a522de1383c55c199804176d9591abeb3a04d41
[ "MIT" ]
null
null
null
src/pan.cpp
Dam-0/grid
5a522de1383c55c199804176d9591abeb3a04d41
[ "MIT" ]
null
null
null
#include "grid.h" void Grid::pan(float x, float y) { _cam_x_decimal += x; _cam_y_decimal += y; int cell_pan = floor(_cam_x_decimal); _cam_x += cell_pan; _cam_x_decimal -= cell_pan; cell_pan = floor(_cam_y_decimal); _cam_y += cell_pan; _cam_y_decimal -= cell_pan; _grid_moved = true; } void Grid::applyPanVel(float delta_time) { if (!_pan_vel_x && !_pan_vel_y) return; pan(_pan_vel_x * delta_time / _scale, _pan_vel_y * delta_time / _scale); _pan_vel_x -= _pan_vel_x * _pan_friction * delta_time; _pan_vel_y -= _pan_vel_y * _pan_friction * delta_time; if (abs(_pan_vel_x) < _min_pan_vel && abs(_pan_vel_y) < _min_pan_vel) { _pan_vel_x = 0; _pan_vel_y = 0; } onMouseMotion(_mouse_x, _mouse_y); }
23.8
76
0.618247
Dam-0
c1735723aa711cffcd7fd681735fb812074bb5d5
2,414
cpp
C++
src/Platform.cpp
hubenchang0515/MCL
a47b846b85203269951029b9fa9ff7be450800b4
[ "MIT" ]
null
null
null
src/Platform.cpp
hubenchang0515/MCL
a47b846b85203269951029b9fa9ff7be450800b4
[ "MIT" ]
null
null
null
src/Platform.cpp
hubenchang0515/MCL
a47b846b85203269951029b9fa9ff7be450800b4
[ "MIT" ]
null
null
null
#include "Platform.h" namespace MCL { const Platform Platform::invalid = nullptr; /************************************************************ * @brief get platforms no more then n * @param[in] n the max * @return the platforms ************************************************************/ std::vector<Platform> Platform::get() noexcept { std::vector<Platform> platforms; cl_uint n = 0; cl_int err = clGetPlatformIDs(0, nullptr, &n); if (err != CL_SUCCESS) { return platforms; } cl_platform_id* pids = new cl_platform_id[n]; clGetPlatformIDs(n, pids, nullptr); for (cl_uint i = 0; i < n; i++) { platforms.emplace_back(Platform(pids[i])); } delete[] pids; return platforms; } Platform::Platform(cl_platform_id id) noexcept : m_id(id) { } cl_platform_id Platform::id() const noexcept { return m_id; } std::string Platform::info(cl_platform_info iname) const noexcept { size_t n = 0; cl_int err = clGetPlatformInfo(m_id, iname, 0, nullptr, &n); // n will include the '\0' if (err != CL_SUCCESS || n == 0) { return ""; } char* name = new char[n]; clGetPlatformInfo(m_id, iname, n, name, nullptr); std::string ret = name; delete[] name; return ret; } std::string Platform::profile() const noexcept { return this->info(CL_PLATFORM_PROFILE); } std::string Platform::version() const noexcept { return this->info(CL_PLATFORM_VERSION); } std::string Platform::name() const noexcept { return this->info(CL_PLATFORM_NAME); } std::string Platform::vendor() const noexcept { return this->info(CL_PLATFORM_VENDOR); } std::string Platform::extensions() const noexcept { return this->info(CL_PLATFORM_EXTENSIONS); } bool Platform::operator < (const Platform& another) const noexcept { return m_id < another.m_id; } bool Platform::operator > (const Platform& another) const noexcept { return m_id > another.m_id; } bool Platform::operator == (const Platform& another) const noexcept { return m_id == another.m_id; } bool Platform::operator != (const Platform& another) const noexcept { return m_id != another.m_id; } bool Platform::operator <= (const Platform& another) const noexcept { return m_id <= another.m_id; } bool Platform::operator >= (const Platform& another) const noexcept { return m_id >= another.m_id; } }; // namespace MCL
20.457627
91
0.632974
hubenchang0515
c177156ee9424c7dba839002bda69a7405e50a02
415
hpp
C++
ros2_mod_ws/build/robobo_msgs_aux/rosidl_generator_cpp/robobo_msgs_aux/srv/set_emotion__request.hpp
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
1
2020-05-19T14:33:49.000Z
2020-05-19T14:33:49.000Z
ros2_mod_ws/install/include/robobo_msgs_aux/srv/set_emotion__request.hpp
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
null
null
null
ros2_mod_ws/install/include/robobo_msgs_aux/srv/set_emotion__request.hpp
mintforpeople/robobo-ros2-ios-port
1a5650304bd41060925ebba41d6c861d5062bfae
[ "Apache-2.0" ]
null
null
null
// generated from rosidl_generator_cpp/resource/msg.hpp.em // generated code does not contain a copyright notice #ifndef ROBOBO_MSGS_AUX__SRV__SET_EMOTION__REQUEST_HPP_ #define ROBOBO_MSGS_AUX__SRV__SET_EMOTION__REQUEST_HPP_ #include "robobo_msgs_aux/srv/set_emotion__request__struct.hpp" #include "robobo_msgs_aux/srv/set_emotion__request__traits.hpp" #endif // ROBOBO_MSGS_AUX__SRV__SET_EMOTION__REQUEST_HPP_
37.727273
63
0.872289
mintforpeople
c1771e6362c0c0e415e7b4cdc8a55465a3e8dc3c
390
hpp
C++
TGEngine/util/Debug.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/util/Debug.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
TGEngine/util/Debug.hpp
ThePixly/TGEngine
aff5d5f42c3094dcc37253f4a3f5e09db560a4eb
[ "Apache-2.0" ]
null
null
null
#pragma once #include "..\Stdbase.hpp" SINCE(0, 0, 1) #define printExtend(x) cout << "width:" << x.width << " height:" << x.height << endl; SINCE(0, 0, 1) #define printOffset(v) cout << "x:" << v.x << " y:" << v.y << endl; /* * Prints a version with the Format MAJOR.MINOR.VERSION e.g. 1.0.0 * You can built it with VK_MAKE_VERSION */ SINCE(0, 0, 1) void printVersion(int version);
24.375
86
0.615385
ThePixly
c17763f7783f2c75d77ad6a98e6cc3a5e54a2b0d
8,675
cpp
C++
Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
1
2022-01-31T08:15:30.000Z
2022-01-31T08:15:30.000Z
Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
3
2021-09-08T03:41:27.000Z
2022-03-12T01:01:29.000Z
Code/Framework/AzToolsFramework/Tests/Prefab/PrefabUpdateWithPatchesTests.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Prefab/PrefabDomUtils.h> #include <Prefab/PrefabTestComponent.h> #include <Prefab/PrefabTestDomUtils.h> #include <Prefab/PrefabTestFixture.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzToolsFramework/Entity/EditorEntityContextBus.h> namespace UnitTest { using PrefabUpdateWithPatchesTest = PrefabTestFixture; /* The below tests use an example of car->axle->wheel templates to test that change propagation works correctly within templates. The car template will have axle templates nested under it and the axle template will have wheel templates nested under it. Because of the complexity that arises from multiple levels of prefab nesting, it's easier to write tests using an example scenario than use generic nesting terminology. */ TEST_F(PrefabUpdateWithPatchesTest, ApplyPatchesToInstance_ComponentUpdated_PatchAppliedCorrectly) { // Create a single entity wheel instance with a PrefabTestComponent and create a template out of it. AZ::Entity* wheelEntity = CreateEntity("WheelEntity1", false); PrefabTestComponent* prefabTestComponent = aznew PrefabTestComponent(true); wheelEntity->AddComponent(prefabTestComponent); AZ::ComponentId prefabTestComponentId = prefabTestComponent->GetId(); AzToolsFramework::EditorEntityContextRequestBus::Broadcast( &AzToolsFramework::EditorEntityContextRequests::HandleEntitiesAdded, AzToolsFramework::EntityList{wheelEntity}); AZStd::unique_ptr<Instance> wheelIsolatedInstance = m_prefabSystemComponent->CreatePrefab({ wheelEntity }, {}, WheelPrefabMockFilePath); const TemplateId wheelTemplateId = wheelIsolatedInstance->GetTemplateId(); PrefabDom& wheelTemplateDom = m_prefabSystemComponent->FindTemplateDom(wheelTemplateId); AZStd::vector<EntityAlias> wheelTemplateEntityAliases = wheelIsolatedInstance->GetEntityAliases(); // Validate that the wheel template has the same entities(1) as the instance it was created from. ASSERT_EQ(wheelTemplateEntityAliases.size(), 1); // Validate that the wheel entity has 2 components. One of them is added through HandleEntitiesAdded() in EditorEntityContext. EntityAlias wheelEntityAlias = wheelTemplateEntityAliases.front(); PrefabDomValue* wheelEntityComponents = PrefabTestDomUtils::GetPrefabDomComponentsPath(wheelEntityAlias).Get(wheelTemplateDom); ASSERT_TRUE(wheelEntityComponents != nullptr && wheelEntityComponents->IsObject()); EXPECT_EQ(wheelEntityComponents->MemberCount(), 2); // Extract the component id of the entity in wheel template and verify that it matches with the component id of the wheel instance. PrefabTestDomUtils::ValidateComponentsDomHasId(*wheelEntityComponents, prefabTestComponentId); // Create an axle with 0 entities and 1 wheel instance. AZStd::unique_ptr<Instance> wheel1UnderAxle = m_prefabSystemComponent->InstantiatePrefab(wheelTemplateId); const AZStd::vector<EntityAlias> wheelEntityAliasesUnderAxle = wheel1UnderAxle->GetEntityAliases(); AZStd::unique_ptr<Instance> axleInstance = m_prefabSystemComponent->CreatePrefab({}, MakeInstanceList(AZStd::move(wheel1UnderAxle)), AxlePrefabMockFilePath); const TemplateId axleTemplateId = axleInstance->GetTemplateId(); PrefabDom& axleTemplateDom = m_prefabSystemComponent->FindTemplateDom(axleTemplateId); const AZStd::vector<InstanceAlias> wheelInstanceAliasesUnderAxle = axleInstance->GetNestedInstanceAliases(wheelTemplateId); ASSERT_EQ(wheelInstanceAliasesUnderAxle.size(), 1); // Create a car with 0 entities and 1 axle instance. AZStd::unique_ptr<Instance> axleUnderCar = m_prefabSystemComponent->InstantiatePrefab(axleTemplateId); AZStd::unique_ptr<Instance> carInstance = m_prefabSystemComponent->CreatePrefab({}, MakeInstanceList( AZStd::move(axleUnderCar) ), CarPrefabMockFilePath); const TemplateId carTemplateId = carInstance->GetTemplateId(); const AZStd::vector<InstanceAlias> axleInstanceAliasesUnderCar = carInstance->GetNestedInstanceAliases(axleTemplateId); PrefabDom& carTemplateDom = m_prefabSystemComponent->FindTemplateDom(carTemplateId); InstanceOptionalReference nestedWheelInstanceRef = axleInstance->FindNestedInstance(wheelInstanceAliasesUnderAxle[0]); ASSERT_TRUE(nestedWheelInstanceRef); //get the entity id AZStd::vector<AZ::EntityId> entityIdVector; axleInstance->GetNestedEntityIds([&entityIdVector](AZ::EntityId entityId) { entityIdVector.push_back(entityId); return true; }); ASSERT_EQ(entityIdVector.size(), 3); AZ::EntityId wheelEntityIdUnderAxle = nestedWheelInstanceRef->get().GetEntityId(wheelEntityAlias); // Retrieve the entity pointer from the component application bus. AZ::Entity* wheelEntityUnderAxle = nullptr; axleInstance->GetAllEntitiesInHierarchy([&wheelEntityUnderAxle, wheelEntityIdUnderAxle](AZStd::unique_ptr<AZ::Entity>& entity) { if (entity->GetId() == wheelEntityIdUnderAxle) { wheelEntityUnderAxle = entity.get(); return false; } else { return true; } }); ASSERT_NE(nullptr, wheelEntityUnderAxle); //create document with before change snapshot PrefabDom entityDomBefore; m_instanceToTemplateInterface->GenerateDomForEntity(entityDomBefore, *wheelEntityUnderAxle); PrefabTestComponent* axlewheelComponent = wheelEntityUnderAxle->FindComponent<PrefabTestComponent>(); // Change the bool property of the component from Wheel instance and use it to update the wheel template. axlewheelComponent->m_boolProperty = false; //create document with after change snapshot PrefabDom entityDomAfter; m_instanceToTemplateInterface->GenerateDomForEntity(entityDomAfter, *wheelEntityUnderAxle); InstanceOptionalReference topMostInstanceInHierarchy = m_instanceToTemplateInterface->GetTopMostInstanceInHierarchy(wheelEntityIdUnderAxle); ASSERT_TRUE(topMostInstanceInHierarchy); PrefabDom patches; InstanceOptionalReference wheelInstanceUnderAxle = axleInstance->FindNestedInstance(wheelInstanceAliasesUnderAxle.front()); m_instanceToTemplateInterface->GeneratePatchForLink(patches, entityDomBefore, entityDomAfter, wheelInstanceUnderAxle->get().GetLinkId()); m_instanceToTemplateInterface->ApplyPatchesToInstance(wheelEntityIdUnderAxle, patches, topMostInstanceInHierarchy->get()); m_instanceUpdateExecutorInterface->UpdateTemplateInstancesInQueue(); // Validate that the prefabTestComponent in the wheel instance under axle doesn't have a BoolProperty. // Even though we changed the property to false, it won't be serialized out because it's a default value. PrefabDomValue* wheelInstanceDomUnderAxle = PrefabTestDomUtils::GetPrefabDomInstancePath(wheelInstanceAliasesUnderAxle.front()).Get(axleTemplateDom); wheelEntityComponents = PrefabTestDomUtils::GetPrefabDomComponentsPath(wheelEntityAlias).Get(*wheelInstanceDomUnderAxle); ASSERT_TRUE(wheelEntityComponents != nullptr); AZStd::string componentValueName = AZStd::string::format("Component_[%llu]", prefabTestComponentId); PrefabDomValueReference wheelEntityComponentValue = PrefabDomUtils::FindPrefabDomValue(*wheelEntityComponents, componentValueName.c_str()); ASSERT_TRUE(wheelEntityComponentValue); PrefabDomValueReference wheelEntityComponentBoolPropertyValue = PrefabDomUtils::FindPrefabDomValue(wheelEntityComponentValue->get(), PrefabTestDomUtils::BoolPropertyName); ASSERT_TRUE(wheelEntityComponentBoolPropertyValue.has_value()); ASSERT_TRUE(wheelEntityComponentBoolPropertyValue->get().IsBool()); ASSERT_FALSE(wheelEntityComponentBoolPropertyValue->get().GetBool()); // Validate that the axles under the car have the same DOM as the axle template. PrefabTestDomUtils::ValidatePrefabDomInstances(axleInstanceAliasesUnderCar, carTemplateDom, axleTemplateDom); } }
58.221477
148
0.746282
cypherdotXd
c178696be3dae369267c571130a2a46f475aed5c
654
hpp
C++
supervisor/src/network/websocket/wrapper/events/Disconnection.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
1
2018-11-12T02:48:46.000Z
2018-11-12T02:48:46.000Z
supervisor/src/network/websocket/wrapper/events/Disconnection.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
null
null
null
supervisor/src/network/websocket/wrapper/events/Disconnection.hpp
mdziekon/eiti-tin-ftp-stattr
c8b8c119f6731045f90281d607b98d7a5ffb3bd2
[ "MIT" ]
null
null
null
#ifndef TIN_NETWORK_WEBSOCKET_WRAPPER_EVENTS_DISCONNECTION_HPP #define TIN_NETWORK_WEBSOCKET_WRAPPER_EVENTS_DISCONNECTION_HPP #include <websocketpp/server.hpp> #include "../Event.hpp" namespace tin { namespace network { namespace websocket { namespace wrapper { namespace events { struct Disconnection: public tin::network::websocket::wrapper::Event { websocketpp::connection_hdl connectionHandler; Disconnection(websocketpp::connection_hdl& connectionHandler); virtual void accept(tin::network::websocket::wrapper::ServerVisitor& i); }; }}}}} #endif /* TIN_NETWORK_WEBSOCKET_WRAPPER_EVENTS_DISCONNECTION_HPP */
31.142857
94
0.776758
mdziekon