hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
befa13fc1b4e41bc3fb840b388540b04f4c83b8b
2,788
cc
C++
vod/src/model/ListWatermarkResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
vod/src/model/ListWatermarkResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
vod/src/model/ListWatermarkResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/vod/model/ListWatermarkResult.h> #include <json/json.h> using namespace AlibabaCloud::Vod; using namespace AlibabaCloud::Vod::Model; ListWatermarkResult::ListWatermarkResult() : ServiceResult() {} ListWatermarkResult::ListWatermarkResult(const std::string &payload) : ServiceResult() { parse(payload); } ListWatermarkResult::~ListWatermarkResult() {} void ListWatermarkResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allWatermarkInfosNode = value["WatermarkInfos"]["WatermarkInfo"]; for (auto valueWatermarkInfosWatermarkInfo : allWatermarkInfosNode) { WatermarkInfo watermarkInfosObject; if(!valueWatermarkInfosWatermarkInfo["CreationTime"].isNull()) watermarkInfosObject.creationTime = valueWatermarkInfosWatermarkInfo["CreationTime"].asString(); if(!valueWatermarkInfosWatermarkInfo["Type"].isNull()) watermarkInfosObject.type = valueWatermarkInfosWatermarkInfo["Type"].asString(); if(!valueWatermarkInfosWatermarkInfo["IsDefault"].isNull()) watermarkInfosObject.isDefault = valueWatermarkInfosWatermarkInfo["IsDefault"].asString(); if(!valueWatermarkInfosWatermarkInfo["WatermarkId"].isNull()) watermarkInfosObject.watermarkId = valueWatermarkInfosWatermarkInfo["WatermarkId"].asString(); if(!valueWatermarkInfosWatermarkInfo["Name"].isNull()) watermarkInfosObject.name = valueWatermarkInfosWatermarkInfo["Name"].asString(); if(!valueWatermarkInfosWatermarkInfo["FileUrl"].isNull()) watermarkInfosObject.fileUrl = valueWatermarkInfosWatermarkInfo["FileUrl"].asString(); if(!valueWatermarkInfosWatermarkInfo["WatermarkConfig"].isNull()) watermarkInfosObject.watermarkConfig = valueWatermarkInfosWatermarkInfo["WatermarkConfig"].asString(); if(!valueWatermarkInfosWatermarkInfo["AppId"].isNull()) watermarkInfosObject.appId = valueWatermarkInfosWatermarkInfo["AppId"].asString(); watermarkInfos_.push_back(watermarkInfosObject); } } std::vector<ListWatermarkResult::WatermarkInfo> ListWatermarkResult::getWatermarkInfos()const { return watermarkInfos_; }
38.722222
105
0.787303
[ "vector", "model" ]
83129cef0deb1cdf1a355543d662889b7026f03f
1,741
cc
C++
vcs/src/model/SaveVideoSummaryTaskVideoRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
vcs/src/model/SaveVideoSummaryTaskVideoRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
vcs/src/model/SaveVideoSummaryTaskVideoRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/vcs/model/SaveVideoSummaryTaskVideoRequest.h> using AlibabaCloud::Vcs::Model::SaveVideoSummaryTaskVideoRequest; SaveVideoSummaryTaskVideoRequest::SaveVideoSummaryTaskVideoRequest() : RpcServiceRequest("vcs", "2020-05-15", "SaveVideoSummaryTaskVideo") { setMethod(HttpRequest::Method::Post); } SaveVideoSummaryTaskVideoRequest::~SaveVideoSummaryTaskVideoRequest() {} std::string SaveVideoSummaryTaskVideoRequest::getCorpId()const { return corpId_; } void SaveVideoSummaryTaskVideoRequest::setCorpId(const std::string& corpId) { corpId_ = corpId; setBodyParameter("CorpId", corpId); } bool SaveVideoSummaryTaskVideoRequest::getSaveVideo()const { return saveVideo_; } void SaveVideoSummaryTaskVideoRequest::setSaveVideo(bool saveVideo) { saveVideo_ = saveVideo; setBodyParameter("SaveVideo", saveVideo ? "true" : "false"); } long SaveVideoSummaryTaskVideoRequest::getTaskId()const { return taskId_; } void SaveVideoSummaryTaskVideoRequest::setTaskId(long taskId) { taskId_ = taskId; setBodyParameter("TaskId", std::to_string(taskId)); }
27.634921
76
0.762206
[ "model" ]
23fe90610db73e1bfdf5eddb523a5e7a48c2ff60
1,900
cpp
C++
tf2_bot_detector/Networking/SteamAPI.cpp
fossabot/tf2_bot_detector
475a11ba2305e33d9b93469e86537f7d2623b61e
[ "MIT" ]
null
null
null
tf2_bot_detector/Networking/SteamAPI.cpp
fossabot/tf2_bot_detector
475a11ba2305e33d9b93469e86537f7d2623b61e
[ "MIT" ]
null
null
null
tf2_bot_detector/Networking/SteamAPI.cpp
fossabot/tf2_bot_detector
475a11ba2305e33d9b93469e86537f7d2623b61e
[ "MIT" ]
null
null
null
#include "SteamAPI.h" #include "HTTPClient.h" #include "HTTPHelpers.h" #include "Config/JSONHelpers.h" #include "Log.h" #include <mh/text/string_insertion.hpp> #include <nlohmann/json.hpp> using namespace std::string_literals; using namespace tf2_bot_detector; using namespace tf2_bot_detector::SteamAPI; duration_t PlayerSummary::GetAccountAge() const { return clock_t::now() - m_CreationTime; } void tf2_bot_detector::SteamAPI::from_json(const nlohmann::json& j, PlayerSummary& d) { d = {}; d.m_SteamID = j.at("steamid"); try_get_to(j, "realname", d.m_RealName); d.m_Nickname = j.at("personaname"); d.m_Status = j.at("personastate"); d.m_Visibility = j.at("communityvisibilitystate"); if (auto found = j.find("profilestate"); found != j.end()) d.m_ProfileConfigured = found->get<int>() != 0; if (auto found = j.find("timecreated"); found != j.end()) d.m_CreationTime = std::chrono::system_clock::time_point(std::chrono::seconds(found->get<uint64_t>())); } std::future<std::vector<PlayerSummary>> tf2_bot_detector::SteamAPI::GetPlayerSummariesAsync( std::string apikey, std::vector<SteamID> steamIDs, const HTTPClient& client) { if (steamIDs.empty()) return {}; if (apikey.empty()) { LogError(std::string(__FUNCTION__) << ": apikey was empty"); return {}; } if (steamIDs.size() > 100) LogError(std::string(__FUNCTION__) << "Attempted to fetch " << steamIDs.size() << " steamIDs at once"); return std::async([apikey, steamIDs{ std::move(steamIDs) }, &client] { std::string url = "https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key="s << apikey << "&steamids="; for (size_t i = 0; i < steamIDs.size(); i++) { if (i != 0) url << ','; url << steamIDs[i].ID64; } auto json = nlohmann::json::parse(client.GetString(url)); return json.at("response").at("players").get<std::vector<PlayerSummary>>(); }); }
27.536232
105
0.681579
[ "vector" ]
23ff5e4e4e7ad8454277a051f49ceac7bcdb89f3
3,722
hpp
C++
src/MapFragment.hpp
liamdev/mapsynth
a0536912b9adf934fce2c937c2caca87547fdcb0
[ "MIT" ]
4
2015-11-13T17:54:50.000Z
2018-09-30T07:14:38.000Z
src/MapFragment.hpp
liamdev/mapsynth
a0536912b9adf934fce2c937c2caca87547fdcb0
[ "MIT" ]
null
null
null
src/MapFragment.hpp
liamdev/mapsynth
a0536912b9adf934fce2c937c2caca87547fdcb0
[ "MIT" ]
1
2020-01-14T21:50:04.000Z
2020-01-14T21:50:04.000Z
/**************************************************************************** File name: MapFragment.hpp Description: Class containing road/building data for a given window of a city. Author: Liam de Valmency Date: 24th April 2013 This source code is licensed under the MIT license. See LICENSE.txt for more information. ****************************************************************************/ #ifndef MAP_FRAGMENT_HPP #define MAP_FRAGMENT_HPP #include <algorithm> #include <vector> #include "MathTools.hpp" #include "Building.hpp" #include "Config.hpp" #include "Path.hpp" #include "RoadGraph.hpp" // Road point which lies on the fragment's boundary. struct RoadEnd{ RoadEnd(float loc, float size, float angle, float* coordPos) : location(loc), size(size), angle(angle), coordPos(coordPos) {}; // Location is distance relative to the edge's top (vertical edge) or left (horizontal edge) point. float location; float size; float angle; // Pointer to the original path point, to allow modification of the road end's actual location, // rather than cached location. float* coordPos; static bool compare(const RoadEnd& lhs, const RoadEnd& rhs){ return lhs.location < rhs.location; }; }; class MapFragment{ public: MapFragment(float xMin = 0, float yMin = 0, float xMax = 0, float yMax = 0) : empty(true), xMin(xMin), yMin(yMin), xMax(xMax), yMax(yMax){}; // Flag for determining the edge to use when comparing fragments. enum CompareDirection {RIGHT, BELOW}; bool isEmpty() const {return empty;}; // Add elements. void addPath(const Path& path); void addBuilding(const Building* building); // Compare compatibility of two fragments, with a given relative positioning. float compareTo(const MapFragment& other, CompareDirection dir) const; // Element counts. size_t pathCount() const {return clippedPaths.size();}; size_t buildingCount() const {return buildings.size();}; size_t topRoadCount() const {return topRoads.size();}; size_t bottomRoadCount() const {return bottomRoads.size();}; size_t leftRoadCount() const {return leftRoads.size();}; size_t rightRoadCount() const {return rightRoads.size();}; // Element access. std::vector<RoadEnd>& getTopRoads() {return topRoads;}; std::vector<RoadEnd>& getBottomRoads() {return bottomRoads;}; std::vector<RoadEnd>& getLeftRoads() {return leftRoads;}; std::vector<RoadEnd>& getRightRoads() {return rightRoads;}; std::vector<const Building*>& getBuildings() {return buildings;}; std::vector<Path>& getPaths() {return clippedPaths;}; // Const element access. const std::vector<RoadEnd>& getTopRoads() const {return topRoads;}; const std::vector<RoadEnd>& getBottomRoads() const {return bottomRoads;}; const std::vector<RoadEnd>& getLeftRoads() const {return leftRoads;}; const std::vector<RoadEnd>& getRightRoads() const {return rightRoads;}; const std::vector<const Building*>& getBuildings() const {return buildings;}; const std::vector<Path>& getPaths() const {return clippedPaths;}; // Position access. float getXMin() const {return xMin;}; float getXMax() const {return xMax;}; float getYMin() const {return yMin;}; float getYMax() const {return yMax;}; // Finds the boundary points within the list of paths, and caches them to avoid repeated lookup. void cacheEdgePoints(); private: std::vector<const Building*> buildings; std::vector<Path> clippedPaths; // Cached end points. std::vector<RoadEnd> topRoads; std::vector<RoadEnd> bottomRoads; std::vector<RoadEnd> leftRoads; std::vector<RoadEnd> rightRoads; bool empty; float xMin, yMin; float xMax, yMax; }; #endif
29.539683
100
0.682697
[ "vector" ]
9b05a409c2dc708d367f7585e0a391c85496bdb5
13,029
cpp
C++
autorally_ws/src/autorally_core/src/xbee/XbeeNode.cpp
ShivamThukral/Wheelchair-Navigation
c5b8d8296b807a6ce17ed01c284708350909b3c3
[ "MIT" ]
2
2022-03-31T05:32:10.000Z
2022-03-31T06:57:54.000Z
autorally_ws/src/autorally_core/src/xbee/XbeeNode.cpp
ShivamThukral/Wheelchair-Navigation
c5b8d8296b807a6ce17ed01c284708350909b3c3
[ "MIT" ]
null
null
null
autorally_ws/src/autorally_core/src/xbee/XbeeNode.cpp
ShivamThukral/Wheelchair-Navigation
c5b8d8296b807a6ce17ed01c284708350909b3c3
[ "MIT" ]
1
2022-03-25T01:13:17.000Z
2022-03-25T01:13:17.000Z
/********************************************** * @file XbeeNode.cpp * @author Brian Goldfain <bgoldfai@gmail.com> * @date May 17, 2013 * @copyright 2012 Georgia Institute of Technology * @brief * * @details This file contains the XbeeNode class implementation ***********************************************/ #include "XbeeNode.h" #include <boost/bind.hpp> int main(int argc, char **argv) { ros::init(argc, argv, "xbeeNode"); ros::NodeHandle nh; std::string xbeePort; if(!nh.getParam("xbeeNode/port", xbeePort)) { ROS_ERROR("Could not get xbeeNode parameters"); return -1; } XbeeNode coordinator(nh, xbeePort); ros::spin(); return 0; } XbeeNode::XbeeNode(ros::NodeHandle &nh, const std::string& port): m_xbee(nh, port), m_nh(nh), m_lastrunstop(0), m_lastTargetedrunstop(0), m_coordinatorAddress("") { std::string nName = ros::this_node::getName(); int transmitPositionRate; if(!nh.getParam(nName+"/transmitPositionRate", transmitPositionRate)) { ROS_ERROR("Could not get all xbee parameters for %s", nName.c_str()); } //until a runstop is received from rf, it will publish runstops //with this name m_runstop.sender = "XbeeNode"; m_runstop.motionEnabled = false; //fill out space for incoming RTCM3 message sequences for(unsigned char i = 'A'; i <= 'Z'; i++) { m_correctionPackets[i] = Rtcm3Packets(); } m_runstopPublisher = nh.advertise<autorally_msgs::runstop> ("runstop", 1); m_gpsRTCM3Publisher = nh.advertise<std_msgs::ByteMultiArray> ("gpsBaseRTCM3", 3); m_xbee.registerReceiveMessageCallback(boost::bind(&XbeeNode::processXbeeMessage, this, _1, _2, _3, _4) ); m_xbeeHeartbeatTimer = nh.createTimer(ros::Duration(0.5), &XbeeNode::xbeeHeartbeatState, this); m_hiTimer = m_nh.createTimer(ros::Duration(1.0), &XbeeNode::sendHi, this); if(transmitPositionRate > 0) { m_transmitPositionTimer = m_nh.createTimer(ros::Duration(1.0/transmitPositionRate), &XbeeNode::transmitPosition, this); m_poseSubscriber = nh.subscribe("pose_estimate", 1, &XbeeNode::odomCallback, this); } } XbeeNode::~XbeeNode() {} void XbeeNode::sendHi(const ros::TimerEvent& /*time*/) { if(m_coordinatorAddress.size() == 0 || m_coordinatorAddress == "--") { //dont send until we read our own node identifier if(m_xbee.getNodeIdentifier() != "-") { std::string sendData = "HI " + m_xbee.getNodeIdentifier(); //std::cout << "SENDING:" << sendData << std::endl; m_xbee.sendTransmitPacket(sendData); } } else { //once we know the address of the coordinator, start sending periodic info to it m_hiTimer.stop(); m_stateTimer = m_nh.createTimer(ros::Duration(1.0), &XbeeNode::sendState, this); } } void XbeeNode::sendState(const ros::TimerEvent& /*time*/) { std::string sendData = "ST " + m_xbee.getNodeIdentifier(); m_xbee.sendTransmitPacket(sendData); } void XbeeNode::xbeeHeartbeatState(const ros::TimerEvent& /*time*/) { if( (ros::Time::now()-m_lastrunstop).toSec() > 1.0) { m_runstop.sender = "XbeeNode(No runstop data from RF)"; m_runstop.motionEnabled = false; m_runstop.header.stamp = ros::Time::now(); m_runstopPublisher.publish(m_runstop); } } void XbeeNode::processXbeeMessage(const std::string& sender, const std::string& /*networkAddress*/, const std::string& data, const bool broadcast) { std::stringstream ss(data); std::string msg; ss >> msg; msg = data.substr(0,2); //std::cout << msg << std::endl; //ROS_INFO_STREAM("Xbee NODE receive:" << data << " -" << msg << "-" << m_coordinatorAddress); if(msg == "AK") { ss >> m_coordinatorAddress; } else if (msg == "OD") { //ROS_ERROR("XbeeNode: Received pose estimate"); if(data.length() == 62) { processXbeeOdom(data, sender); } else ROS_ERROR("XbeeNode: Received incorrect length(%d) odom message \"%s\"", (int)data.length(),data.c_str()); } else if(msg == "RS") { //std::cout << "RS:" << ss << std::endl; m_lastrunstop = ros::Time::now(); if(!broadcast) { m_lastTargetedrunstop = m_lastrunstop; } //if I'm receiving targeted xbee runstop messages, ignore broadcast xbee //runstop messages std::string motionEnabled = "0"; double timeDiff = (m_lastrunstop-m_lastTargetedrunstop).toSec(); if( timeDiff <= 1.0 && !broadcast) { ss >> m_runstop.sender >> motionEnabled; try { m_runstop.motionEnabled = boost::lexical_cast<int>(motionEnabled); } catch(boost::bad_lexical_cast &e) { ROS_ERROR_STREAM("XbeeNode: bad motionEnabled lexical cast from:" << motionEnabled); m_runstop.motionEnabled = 0; } m_runstop.header.stamp = m_lastTargetedrunstop; m_runstopPublisher.publish(m_runstop); } else if(broadcast) { ss >> m_runstop.sender >> motionEnabled; try { m_runstop.motionEnabled = boost::lexical_cast<bool>(motionEnabled); } catch(boost::bad_lexical_cast &e) { ROS_ERROR_STREAM("XbeeNode: bad broadcast motionEnabled lexical cast from:" << motionEnabled); m_runstop.motionEnabled = 0; } m_runstop.header.stamp = m_lastrunstop; m_runstopPublisher.publish(m_runstop); } else { ROS_ERROR("XbeeNode: something wrong with runstop received over xbee"); } } else if(msg == "GC") { try { char seq = data[2]; int seqLen = boost::lexical_cast<int>(data[3]); size_t packetNum = boost::lexical_cast<int>(data[4]); ROS_DEBUG_STREAM("Xbee sequence: " << seq << " seq length: " << seqLen << " packet num: " << packetNum); //just received first packet of new RTCM3 message if(ros::Time::now()-m_correctionPackets[seq].time > ros::Duration(2.0)) { m_correctionPackets[seq].reset(seqLen); } //check to make sure there is space in the packet vector (+1 since packets #s start at 1) if(packetNum < m_correctionPackets[seq].packets.size()) { m_correctionPackets[seq].packets[packetNum] = data.substr(5); ++m_correctionPackets[seq].count; } else { ROS_ERROR_STREAM("Xbee RTCM packet number " << packetNum << " larger than packet vector length " << m_correctionPackets[seq].packets.size()); } if(m_correctionPackets[seq].count == m_correctionPackets[seq].packets.size()-1) { ROS_DEBUG_STREAM("Xbee publishing RTCM3 msg seq " << seq); std::string gpsString; //actual RTCM payload data packets start at 1 for(size_t i = 1; i < m_correctionPackets[seq].packets.size(); ++i) { gpsString += m_correctionPackets[seq].packets[i]; } //clear message data immediately so it can't be accidentally used again m_correctionPackets[seq].packets.clear(); m_correctionPackets[seq].count = 0; //allocate new message, fill it in std_msgs::ByteMultiArrayPtr m_gpsCorrection(new std_msgs::ByteMultiArray); m_gpsCorrection->layout.dim.push_back(std_msgs::MultiArrayDimension()); m_gpsCorrection->layout.dim.front().label = m_msgLabel; for(size_t i = 0; i < gpsString.size(); i++) { m_gpsCorrection->data.push_back(gpsString[i]); } //publish correction into ros m_gpsCorrection->layout.dim.front().size = m_gpsCorrection->data.size(); m_gpsCorrection->layout.dim.front().stride = m_gpsCorrection->data.size(); m_gpsRTCM3Publisher.publish(m_gpsCorrection); m_xbee.m_port.tick("RTCM3 correction"); } } catch(boost::bad_lexical_cast &e) { ROS_ERROR_STREAM("XbeeNode: caught bad lexical cast for GPS RTCM3 msgnum:" << data[4]); } } else if(msg == "HI" || msg == "ST") {} //These will be received but are only needed by coordinator else { ROS_ERROR("XbeeNode: Received unknown message \"%s\"", msg.c_str()); } } void XbeeNode::odomCallback(const nav_msgs::OdometryConstPtr& odom) { m_odometry = *odom; } void XbeeNode::transmitPosition(const ros::TimerEvent& /*time*/) { if(m_odometry.header.stamp > m_lastXbeeOdomTransmit) { char temp[16]; std::string data; data += "OD "; sprintf(temp, "%5i", scaleAndClip(m_odometry.pose.pose.position.x, 500, 0.01)); data += temp; sprintf(temp, "%5i", scaleAndClip(m_odometry.pose.pose.position.y, 500, 0.01)); data += temp; sprintf(temp, "%5i", scaleAndClip(m_odometry.pose.pose.position.z, 500, 0.01)); data += temp; sprintf(temp, "%4i", scaleAndClip(m_odometry.twist.twist.linear.x, 50, 0.01)); data += temp; sprintf(temp, "%4i", scaleAndClip(m_odometry.twist.twist.linear.y, 50, 0.01)); data += temp; sprintf(temp, "%4i", scaleAndClip(m_odometry.twist.twist.linear.z, 50, 0.01)); data += temp; sprintf(temp, "%8i", scaleAndClip(m_odometry.pose.pose.orientation.x, 1, 0.0000001)); data += temp; sprintf(temp, "%8i", scaleAndClip(m_odometry.pose.pose.orientation.y, 1, 0.0000001)); data += temp; sprintf(temp, "%8i", scaleAndClip(m_odometry.pose.pose.orientation.z, 1, 0.0000001)); data += temp; sprintf(temp, "%8i", scaleAndClip(m_odometry.pose.pose.orientation.w, 1, 0.0000001)); data += temp; /*ROS_WARN("[%f %f %f][%f %f %f][%f %f %f %f]", m_odometry.pose.pose.position.x, m_odometry.pose.pose.position.y, m_odometry.pose.pose.position.z, m_odometry.twist.twist.linear.x, m_odometry.twist.twist.linear.y, m_odometry.twist.twist.linear.z, m_odometry.pose.pose.orientation.x, m_odometry.pose.pose.orientation.y, m_odometry.pose.pose.orientation.z, m_odometry.pose.pose.orientation.w); */ //ROS_WARN_STREAM("Sending position:" << data); m_xbee.sendTransmitPacket(data); m_xbee.m_port.tick("pose_estimate broadcast"); m_lastXbeeOdomTransmit = m_odometry.header.stamp; } } int XbeeNode::scaleAndClip(double number, double range, double resolution) { double scaled = (number + range) / resolution; if (scaled >= ((2.0*range)/resolution)) scaled = 2.0*range / resolution; if (scaled < 0) scaled = 0; return (int)scaled; } double XbeeNode::unscaleAndClip(int number, double range, double resolution) { return ((double)number * resolution) - range; } void XbeeNode::processXbeeOdom(const std::string& message, const std::string& sender) { //ROS_WARN_STREAM("Received:" << message << " from:" << sender); nav_msgs::OdometryPtr odom(new nav_msgs::Odometry); odom->pose.pose.position.x = unscaleAndClip(atoi(message.substr(3,5).c_str()), 500, 0.01); odom->pose.pose.position.y = unscaleAndClip(atoi(message.substr(8,5).c_str()), 500, 0.01); odom->pose.pose.position.z = unscaleAndClip(atoi(message.substr(13,5).c_str()), 500, 0.01); odom->twist.twist.linear.x = unscaleAndClip(atoi(message.substr(18,4).c_str()), 50, 0.01); odom->twist.twist.linear.y = unscaleAndClip(atoi(message.substr(22,4).c_str()), 50, 0.01); odom->twist.twist.linear.z = unscaleAndClip(atoi(message.substr(26,4).c_str()), 50, 0.01); odom->pose.pose.orientation.x = unscaleAndClip(atoi(message.substr(30,8).c_str()), 1, 0.0000001); odom->pose.pose.orientation.y = unscaleAndClip(atoi(message.substr(38,8).c_str()), 1, 0.0000001); odom->pose.pose.orientation.z = unscaleAndClip(atoi(message.substr(46,8).c_str()), 1, 0.0000001); odom->pose.pose.orientation.w = unscaleAndClip(atoi(message.substr(54,8).c_str()), 1, 0.0000001); /*ROS_WARN("[%f %f %f][%f %f %f][%f %f %f %f]", odom->pose.pose.position.x, odom->pose.pose.position.y, odom->pose.pose.position.z, odom->twist.twist.linear.x, odom->twist.twist.linear.y, odom->twist.twist.linear.z, odom->pose.pose.orientation.x, odom->pose.pose.orientation.y, odom->pose.pose.orientation.z, odom->pose.pose.orientation.w); */ if(!m_recOdomPublishers[sender]) { ros::NodeHandle nh; m_recOdomPublishers[sender] = nh.advertise<nav_msgs::Odometry> ("/pose_estimate_"+sender, 1); } odom->header.stamp = ros::Time::now(); odom->child_frame_id = sender; odom->header.frame_id = "odom"; m_xbee.m_port.tick("/pose_estimate_"+sender); m_recOdomPublishers[sender].publish(odom); }
34.559682
112
0.617776
[ "vector" ]
9b12ba180444b58989430f1811ce29b023acf2b9
10,239
cpp
C++
llvm-5.0.1.src/lib/Transforms/Scalar/LoopPredication.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
60
2017-12-21T06:49:58.000Z
2022-02-24T09:43:52.000Z
llvm-5.0.1.src/lib/Transforms/Scalar/LoopPredication.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
null
null
null
llvm-5.0.1.src/lib/Transforms/Scalar/LoopPredication.cpp
ShawnLess/TBD
fc98e93b3462509022fdf403978cd82aa05c2331
[ "Apache-2.0" ]
17
2017-12-20T09:54:56.000Z
2021-06-24T05:39:36.000Z
//===-- LoopPredication.cpp - Guard based loop predication pass -----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // The LoopPredication pass tries to convert loop variant range checks to loop // invariant by widening checks across loop iterations. For example, it will // convert // // for (i = 0; i < n; i++) { // guard(i < len); // ... // } // // to // // for (i = 0; i < n; i++) { // guard(n - 1 < len); // ... // } // // After this transformation the condition of the guard is loop invariant, so // loop-unswitch can later unswitch the loop by this condition which basically // predicates the loop by the widened condition: // // if (n - 1 < len) // for (i = 0; i < n; i++) { // ... // } // else // deoptimize // //===----------------------------------------------------------------------===// #include "llvm/Transforms/Scalar/LoopPredication.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LoopPass.h" #include "llvm/Analysis/ScalarEvolution.h" #include "llvm/Analysis/ScalarEvolutionExpander.h" #include "llvm/Analysis/ScalarEvolutionExpressions.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/IntrinsicInst.h" #include "llvm/IR/Module.h" #include "llvm/IR/PatternMatch.h" #include "llvm/Pass.h" #include "llvm/Support/Debug.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/Utils/LoopUtils.h" #define DEBUG_TYPE "loop-predication" using namespace llvm; namespace { class LoopPredication { /// Represents an induction variable check: /// icmp Pred, <induction variable>, <loop invariant limit> struct LoopICmp { ICmpInst::Predicate Pred; const SCEVAddRecExpr *IV; const SCEV *Limit; LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV, const SCEV *Limit) : Pred(Pred), IV(IV), Limit(Limit) {} LoopICmp() {} }; ScalarEvolution *SE; Loop *L; const DataLayout *DL; BasicBlock *Preheader; Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI); Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, Instruction *InsertAt); Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, IRBuilder<> &Builder); bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander); public: LoopPredication(ScalarEvolution *SE) : SE(SE){}; bool runOnLoop(Loop *L); }; class LoopPredicationLegacyPass : public LoopPass { public: static char ID; LoopPredicationLegacyPass() : LoopPass(ID) { initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry()); } void getAnalysisUsage(AnalysisUsage &AU) const override { getLoopAnalysisUsage(AU); } bool runOnLoop(Loop *L, LPPassManager &LPM) override { if (skipLoop(L)) return false; auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); LoopPredication LP(SE); return LP.runOnLoop(L); } }; char LoopPredicationLegacyPass::ID = 0; } // end namespace llvm INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication", "Loop predication", false, false) INITIALIZE_PASS_DEPENDENCY(LoopPass) INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication", "Loop predication", false, false) Pass *llvm::createLoopPredicationPass() { return new LoopPredicationLegacyPass(); } PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U) { LoopPredication LP(&AR.SE); if (!LP.runOnLoop(&L)) return PreservedAnalyses::all(); return getLoopPassPreservedAnalyses(); } Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopICmp(ICmpInst *ICI) { ICmpInst::Predicate Pred = ICI->getPredicate(); Value *LHS = ICI->getOperand(0); Value *RHS = ICI->getOperand(1); const SCEV *LHSS = SE->getSCEV(LHS); if (isa<SCEVCouldNotCompute>(LHSS)) return None; const SCEV *RHSS = SE->getSCEV(RHS); if (isa<SCEVCouldNotCompute>(RHSS)) return None; // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV if (SE->isLoopInvariant(LHSS, L)) { std::swap(LHS, RHS); std::swap(LHSS, RHSS); Pred = ICmpInst::getSwappedPredicate(Pred); } const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS); if (!AR || AR->getLoop() != L) return None; return LoopICmp(Pred, AR, RHSS); } Value *LoopPredication::expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder, ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, Instruction *InsertAt) { Type *Ty = LHS->getType(); assert(Ty == RHS->getType() && "expandCheck operands have different types?"); Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt); Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt); return Builder.CreateICmp(Pred, LHSV, RHSV); } /// If ICI can be widened to a loop invariant condition emits the loop /// invariant condition in the loop preheader and return it, otherwise /// returns None. Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander, IRBuilder<> &Builder) { DEBUG(dbgs() << "Analyzing ICmpInst condition:\n"); DEBUG(ICI->dump()); auto RangeCheck = parseLoopICmp(ICI); if (!RangeCheck) { DEBUG(dbgs() << "Failed to parse the loop latch condition!\n"); return None; } ICmpInst::Predicate Pred = RangeCheck->Pred; const SCEVAddRecExpr *IndexAR = RangeCheck->IV; const SCEV *RHSS = RangeCheck->Limit; auto CanExpand = [this](const SCEV *S) { return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE); }; if (!CanExpand(RHSS)) return None; DEBUG(dbgs() << "IndexAR: "); DEBUG(IndexAR->dump()); bool IsIncreasing = false; if (!SE->isMonotonicPredicate(IndexAR, Pred, IsIncreasing)) return None; // If the predicate is increasing the condition can change from false to true // as the loop progresses, in this case take the value on the first iteration // for the widened check. Otherwise the condition can change from true to // false as the loop progresses, so take the value on the last iteration. const SCEV *NewLHSS = IsIncreasing ? IndexAR->getStart() : SE->getSCEVAtScope(IndexAR, L->getParentLoop()); if (NewLHSS == IndexAR) { DEBUG(dbgs() << "Can't compute NewLHSS!\n"); return None; } DEBUG(dbgs() << "NewLHSS: "); DEBUG(NewLHSS->dump()); if (!CanExpand(NewLHSS)) return None; DEBUG(dbgs() << "NewLHSS is loop invariant and safe to expand. Expand!\n"); Instruction *InsertAt = Preheader->getTerminator(); return expandCheck(Expander, Builder, Pred, NewLHSS, RHSS, InsertAt); } bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard, SCEVExpander &Expander) { DEBUG(dbgs() << "Processing guard:\n"); DEBUG(Guard->dump()); IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator())); // The guard condition is expected to be in form of: // cond1 && cond2 && cond3 ... // Iterate over subconditions looking for for icmp conditions which can be // widened across loop iterations. Widening these conditions remember the // resulting list of subconditions in Checks vector. SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0)); SmallPtrSet<Value *, 4> Visited; SmallVector<Value *, 4> Checks; unsigned NumWidened = 0; do { Value *Condition = Worklist.pop_back_val(); if (!Visited.insert(Condition).second) continue; Value *LHS, *RHS; using namespace llvm::PatternMatch; if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) { Worklist.push_back(LHS); Worklist.push_back(RHS); continue; } if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) { if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) { Checks.push_back(NewRangeCheck.getValue()); NumWidened++; continue; } } // Save the condition as is if we can't widen it Checks.push_back(Condition); } while (Worklist.size() != 0); if (NumWidened == 0) return false; // Emit the new guard condition Builder.SetInsertPoint(Guard); Value *LastCheck = nullptr; for (auto *Check : Checks) if (!LastCheck) LastCheck = Check; else LastCheck = Builder.CreateAnd(LastCheck, Check); Guard->setOperand(0, LastCheck); DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n"); return true; } bool LoopPredication::runOnLoop(Loop *Loop) { L = Loop; DEBUG(dbgs() << "Analyzing "); DEBUG(L->dump()); Module *M = L->getHeader()->getModule(); // There is nothing to do if the module doesn't use guards auto *GuardDecl = M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard)); if (!GuardDecl || GuardDecl->use_empty()) return false; DL = &M->getDataLayout(); Preheader = L->getLoopPreheader(); if (!Preheader) return false; // Collect all the guards into a vector and process later, so as not // to invalidate the instruction iterator. SmallVector<IntrinsicInst *, 4> Guards; for (const auto BB : L->blocks()) for (auto &I : *BB) if (auto *II = dyn_cast<IntrinsicInst>(&I)) if (II->getIntrinsicID() == Intrinsic::experimental_guard) Guards.push_back(II); if (Guards.empty()) return false; SCEVExpander Expander(*SE, *DL, "loop-predication"); bool Changed = false; for (auto *Guard : Guards) Changed |= widenGuardConditions(Guard, Expander); return Changed; }
30.933535
80
0.640785
[ "vector" ]
9b190848aad2f728072b2d60c3d1bb275a0108ee
5,887
cc
C++
src/BristolNTuple_Photons.cc
jjacob/NTupleProduction
5bd3b925a1cdec8a4e1332357becfaba04b7c1c9
[ "Apache-2.0" ]
null
null
null
src/BristolNTuple_Photons.cc
jjacob/NTupleProduction
5bd3b925a1cdec8a4e1332357becfaba04b7c1c9
[ "Apache-2.0" ]
null
null
null
src/BristolNTuple_Photons.cc
jjacob/NTupleProduction
5bd3b925a1cdec8a4e1332357becfaba04b7c1c9
[ "Apache-2.0" ]
null
null
null
#include "BristolAnalysis/NTupleTools/interface/BristolNTuple_Photons.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DataFormats/PatCandidates/interface/Photon.h" #include "DataFormats/PatCandidates/interface/Muon.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/Scalers/interface/DcsStatus.h" #include "FWCore/Framework/interface/ESHandle.h" #include "MagneticField/Engine/interface/MagneticField.h" #include "MagneticField/Records/interface/IdealMagneticFieldRecord.h" #include "RecoEgamma/EgammaTools/interface/ConversionFinder.h" #include "DataFormats/VertexReco/interface/Vertex.h" #include "DataFormats/VertexReco/interface/VertexFwd.h" BristolNTuple_Photons::BristolNTuple_Photons(const edm::ParameterSet& iConfig) : inputTag(iConfig.getParameter<edm::InputTag>("InputTag")), prefix (iConfig.getParameter<std::string> ("Prefix")), suffix (iConfig.getParameter<std::string> ("Suffix")), maxSize (iConfig.getParameter<unsigned int> ("MaxSize")) { produces<std::vector<double> > (prefix + "Px" + suffix); produces<std::vector<double> > (prefix + "Py" + suffix); produces<std::vector<double> > (prefix + "Pz" + suffix); produces<std::vector<double> > (prefix + "Energy" + suffix); produces<std::vector<double> > (prefix + "EcalIso" + suffix); produces<std::vector<double> > (prefix + "HcalIso" + suffix); produces<std::vector<double> > (prefix + "HoE" + suffix); produces<std::vector<double> > (prefix + "TrkIso" + suffix); produces<std::vector<double> > (prefix + "SigmaIEtaIEta" + suffix); produces<std::vector<bool> > (prefix + "TrkVeto" + suffix); produces<std::vector<double> > (prefix + "SCseedEnergy" + suffix); produces<std::vector<double> > (prefix + "SCenergy" + suffix); produces<std::vector<double> > (prefix + "SCeta" + suffix); produces<std::vector<double> > (prefix + "SCphi" + suffix); produces<std::vector<double> > (prefix + "E3x3" + suffix); produces<std::vector<double> > (prefix + "E5x5" + suffix); } void BristolNTuple_Photons::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { std::auto_ptr < std::vector<double> > px(new std::vector<double>()); std::auto_ptr < std::vector<double> > py(new std::vector<double>()); std::auto_ptr < std::vector<double> > pz(new std::vector<double>()); std::auto_ptr < std::vector<double> > energy(new std::vector<double>()); std::auto_ptr < std::vector<double> > ecalIso(new std::vector<double>()); std::auto_ptr < std::vector<double> > hcalIso(new std::vector<double>()); std::auto_ptr < std::vector<double> > hoe(new std::vector<double>()); std::auto_ptr < std::vector<double> > trkIso(new std::vector<double>()); std::auto_ptr < std::vector<double> > sigmaIetaIeta(new std::vector<double>()); std::auto_ptr < std::vector<bool> > trkVeto(new std::vector<bool>()); std::auto_ptr < std::vector<double> > SCseedEnergy(new std::vector<double>()); std::auto_ptr < std::vector<double> > SCenergy(new std::vector<double>()); std::auto_ptr < std::vector<double> > SCeta(new std::vector<double>()); std::auto_ptr < std::vector<double> > SCphi(new std::vector<double>()); std::auto_ptr < std::vector<double> > E3x3(new std::vector<double>()); std::auto_ptr < std::vector<double> > E5x5(new std::vector<double>()); //----------------------------------------------------------------- edm::Handle < std::vector<pat::Photon> > photons; iEvent.getByLabel(inputTag, photons); if (photons.isValid()) { edm::LogInfo("BristolNTuple_PhotonsInfo") << "Total # Photons: " << photons->size(); for (std::vector<pat::Photon>::const_iterator it = photons->begin(); it != photons->end(); ++it) { // exit from loop when you reach the required number of photons if (px->size() >= maxSize) break; px->push_back(it->px()); py->push_back(it->py()); pz->push_back(it->pz()); energy->push_back(it->energy()); ecalIso->push_back(it->ecalIso()); hcalIso->push_back(it->hcalIso()); hoe->push_back(it->hadronicOverEm()); trkIso->push_back(it->trkSumPtHollowConeDR04()); sigmaIetaIeta->push_back(it->sigmaIetaIeta()); trkVeto->push_back(it->hasPixelSeed()); SCseedEnergy->push_back(it->superCluster()->seed()->energy()); SCenergy->push_back(it->superCluster()->energy()); SCeta->push_back(it->superCluster()->eta()); SCphi->push_back(it->superCluster()->phi()); E3x3->push_back(it->e3x3()); E5x5->push_back(it->e5x5()); } } else { edm::LogError("BristolNTuple_PhotonsError") << "Error! Can't get the product " << inputTag; } //----------------------------------------------------------------- // put vectors in the event iEvent.put(px, prefix + "Px" + suffix); iEvent.put(py, prefix + "Py" + suffix); iEvent.put(pz, prefix + "Pz" + suffix); iEvent.put(energy, prefix + "Energy" + suffix); iEvent.put(ecalIso, prefix + "EcalIso" + suffix); iEvent.put(hcalIso, prefix + "HcalIso" + suffix); iEvent.put(hoe, prefix + "HoE" + suffix); iEvent.put(trkIso, prefix + "TrkIso" + suffix); iEvent.put(sigmaIetaIeta, prefix + "SigmaIEtaIEta" + suffix); iEvent.put(trkVeto, prefix + "TrkVeto" + suffix); iEvent.put(SCseedEnergy, prefix + "SCseedEnergy" + suffix); iEvent.put(SCenergy, prefix + "SCenergy" + suffix); iEvent.put(SCeta, prefix + "SCeta" + suffix); iEvent.put(SCphi, prefix + "SCphi" + suffix); iEvent.put(E3x3, prefix + "E3x3" + suffix); iEvent.put(E5x5, prefix + "E5x5" + suffix); }
51.640351
106
0.635298
[ "vector" ]
9b1ecaa1506dda6f5d3c8bf7d31bf2b245c2e844
4,145
cpp
C++
attic/historic/anode/libspark/experiments/FindGoodSegmentDelimiters.cpp
sundys/ZeroTierOne
269501eaa0c22bdc402e689b0d061325fb6ddbce
[ "RSA-MD" ]
8,205
2015-01-02T16:34:03.000Z
2022-03-31T18:18:28.000Z
attic/historic/anode/libspark/experiments/FindGoodSegmentDelimiters.cpp
sundys/ZeroTierOne
269501eaa0c22bdc402e689b0d061325fb6ddbce
[ "RSA-MD" ]
1,401
2015-01-01T05:45:53.000Z
2022-03-31T14:00:00.000Z
attic/historic/anode/libspark/experiments/FindGoodSegmentDelimiters.cpp
sundys/ZeroTierOne
269501eaa0c22bdc402e689b0d061325fb6ddbce
[ "RSA-MD" ]
1,243
2015-01-09T07:30:49.000Z
2022-03-31T12:36:48.000Z
// Searches for good delimiters to cut streams into relatively well sized // segments. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <boost/cstdint.hpp> #include <boost/array.hpp> #include <boost/random/mersenne_twister.hpp> #include <boost/thread.hpp> #include <boost/bind.hpp> #include <boost/shared_ptr.hpp> #include <iostream> #include <vector> #include <map> // Desired size range #define MIN_DESIRED_SIZE 4096 #define MAX_DESIRED_SIZE 131072 #define DELIMITER_SET_SIZE 1 typedef boost::array<boost::uint16_t,DELIMITER_SET_SIZE> DelimArray; struct BestEntry { DelimArray best; double bestScore; std::vector<unsigned char> data; }; boost::mutex bestLock; boost::mutex outLock; std::map<std::string,BestEntry> best; static void runThread(const std::string &fileName) { char tmp[4096]; boost::mt19937 prng; { boost::uint32_t seed; FILE *ur = fopen("/dev/urandom","r"); fread((void *)&seed,1,sizeof(seed),ur); fclose(ur); prng.seed(seed); } BestEntry *myEntry; { boost::mutex::scoped_lock l(bestLock); myEntry = &(best[fileName]); myEntry->bestScore = 99999999.0; } { boost::mutex::scoped_lock l(outLock); std::cout << "*** Reading test data from: " << fileName << std::endl; FILE *f = fopen(fileName.c_str(),"r"); if (f) { int n; while ((n = fread((void *)tmp,1,sizeof(tmp),f)) > 0) { for(int i=0;i<n;++i) myEntry->data.push_back((unsigned char)tmp[i]); } fclose(f); } if (myEntry->data.size() <= 0) { std::cout << "Error: no data read." << std::endl; exit(1); } else std::cout << "*** Read " << myEntry->data.size() << " bytes of test data." << std::endl; std::cout.flush(); } DelimArray current; for(unsigned int i=0;i<DELIMITER_SET_SIZE;++i) current[i] = (boost::uint16_t)prng(); for(;;) { unsigned long numTooShort = 0; unsigned long numTooLong = 0; unsigned long numGood = 0; boost::uint32_t shiftRegister = 0; unsigned long segSize = 0; for(std::vector<unsigned char>::iterator i=myEntry->data.begin();i!=myEntry->data.end();++i) { shiftRegister <<= 1; shiftRegister |= (((boost::uint32_t)*i) & 1); ++segSize; boost::uint16_t transformedShiftRegister = (boost::uint16_t)(shiftRegister); for(DelimArray::iterator d=current.begin();d!=current.end();++d) { if (transformedShiftRegister == *d) { if (segSize < MIN_DESIRED_SIZE) ++numTooShort; else if (segSize > MAX_DESIRED_SIZE) ++numTooLong; else ++numGood; segSize = 0; break; } } } if (segSize) { if (segSize < MIN_DESIRED_SIZE) ++numTooShort; else if (segSize > MAX_DESIRED_SIZE) ++numTooLong; else ++numGood; } if (numGood) { double score = ((double)(numTooShort + numTooLong)) / ((double)numGood); if (score < myEntry->bestScore) { myEntry->best = current; myEntry->bestScore = score; boost::mutex::scoped_lock l(outLock); std::cout << fileName << ": "; for(DelimArray::iterator d=current.begin();d!=current.end();++d) { sprintf(tmp,"0x%.4x",(unsigned int)*d); if (d != current.begin()) std::cout << ','; std::cout << tmp; } std::cout << ": " << numTooShort << " / " << numGood << " / " << numTooLong << " (" << score << ")" << std::endl; std::cout.flush(); if ((numTooShort == 0)&&(numTooLong == 0)) break; } } for(DelimArray::iterator i=current.begin();i!=current.end();++i) *i = (boost::uint16_t)prng(); } } int main(int argc,char **argv) { std::vector< boost::shared_ptr<boost::thread> > threads; for(int i=1;i<argc;++i) { boost::shared_ptr<boost::thread> t(new boost::thread(boost::bind(&runThread,std::string(argv[i])))); threads.push_back(t); } for(std::vector< boost::shared_ptr<boost::thread> >::iterator i=threads.begin();i!=threads.end();++i) (*i)->join(); return 0; }
25.58642
121
0.590109
[ "vector" ]
9b32c03a6d08b589251825589514d54472ab7a4f
3,138
cpp
C++
src/Buckle/Bronze/opts.cpp
flamechain/BELTE
a53ba207ff8b524d75d1b2561022992436550bf3
[ "MIT" ]
3
2022-03-11T15:31:49.000Z
2022-03-11T22:53:55.000Z
src/Buckle/Bronze/opts.cpp
flamechain/belte
c09175c4fb034703290f51a1d63b0ae0cb421665
[ "MIT" ]
null
null
null
src/Buckle/Bronze/opts.cpp
flamechain/belte
c09175c4fb034703290f51a1d63b0ae0cb421665
[ "MIT" ]
null
null
null
#include "opts.hpp" void decode_options(_In_ const vector<string>& args) noexcept { bool specify_stage = false; bool specify_out = false; // defaults state.finish_stage = CompilerStage::linked; state.link_output = "a.exe"; // arg parsing for (size_t i=0; i<args.size(); i++) { string arg = args[i]; if (startswith(arg, "-")) { if (arg == "-E") { specify_stage = true; state.finish_stage = CompilerStage::preprocessed; } else if (arg == "-S") { specify_stage = true; state.finish_stage = CompilerStage::compiled; } else if (arg == "-c") { specify_stage = true; state.finish_stage = CompilerStage::assembled; } else if (arg == "-r") { error = SUCCESS_EXIT_CODE; return; } else if (arg == "-o") { specify_out = true; if (i >= args.size()-1) { RaiseFatalError("missing output filename (with '-o')"); } state.link_output = args[i++]; } else { RaiseFatalError(format("unknown argument '%s'", arg.c_str())); } } else { string filename = arg; vector<string> parts = split_str(filename, "."); string type = parts[parts.size()-1]; FileState task; task.in_filename = filename; if (type == "ble") { task.stage = CompilerStage::raw; } else if (type == "pble") { task.stage = CompilerStage::preprocessed; } else if (type == "s" || type == "asm") { task.stage = CompilerStage::compiled; } else if (type == "o" || type == "obj") { task.stage = CompilerStage::assembled; } else { RaiseWarning(format("unknown file type of input file '%s'; ignoring", filename.c_str())); } state.tasks.push_back(task); } } // final error checking if (specify_out && specify_stage) RaiseFatalError("cannot specify output file with '-E', '-S', or '-c'"); if (state.tasks.size() == 0) RaiseFatalError("no input files"); } void produce_output_filenames() noexcept { if (state.finish_stage == CompilerStage::linked) return; for (FileState file : state.tasks) { string inter = split_str(file.in_filename, ".")[0]; switch (state.finish_stage) { case CompilerStage::preprocessed: inter += ".pble"; break; case CompilerStage::compiled: inter += ".s"; break; case CompilerStage::assembled: inter += ".o"; break; default: break; } } } void clean_output_files() noexcept { if (state.finish_stage == CompilerStage::linked) { delete_file(state.link_output); return; } for (FileState file : state.tasks) { delete_file(file.out_filename); } }
32.020408
109
0.504461
[ "vector" ]
9b32d7a9fbff2bc0dd7c1c567f2528ae71f00a0c
2,206
cpp
C++
ironstack_agent/gui/key_reader.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
ironstack_agent/gui/key_reader.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
ironstack_agent/gui/key_reader.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
#include "key_reader.h" using namespace gui; // constructor key_reader::key_reader() { set_input_sequence(-1000); } // destructor key_reader::~key_reader() { } // clears all keys from the queue void key_reader::clear() { lock_guard<mutex> g(lock); keys.clear(); } // check if at least one key is present bool key_reader::has_key() const { lock_guard<mutex> g(lock); return !keys.empty(); } // get the number of keys in the buffer uint32_t key_reader::get_pending_key_count() const { lock_guard<mutex> g(lock); return keys.size(); } // waits for a certain amount of time for a key to be pressed // if timeout is set to 0, it blocks. default behavior blocks. keystroke key_reader::wait_for_key(uint32_t timeout_ms) { unique_lock<mutex> l(lock); if (timeout_ms == 0) { cond.wait(l); } else { cond.wait_for(l, chrono::milliseconds(timeout_ms)); } if (keys.empty()) { return keystroke(); } else { auto result = keys.front(); keys.pop_front(); return result; } } // non-blocking check to see if a key is in the buffer keystroke key_reader::poll_for_key() { lock_guard<mutex> g(lock); if (keys.empty()) { return keystroke(); } else { auto result = keys.front(); keys.pop_front(); return result; } } // returns a vector of all keys in the buffer vector<keystroke> key_reader::get_all_keys() { lock_guard<mutex> g(lock); vector<keystroke> result; result.reserve(keys.size()); for (const auto& key : keys) { result.push_back(key); } keys.clear(); return result; } // returns the first available key without removing it from the buffer keystroke key_reader::peek_key() const { lock_guard<mutex> g(lock); if (!keys.empty()) { return keys.front(); } else { return keystroke(); } } // returns all available keys without removing them from the buffer vector<keystroke> key_reader::peek_all_keys() const { lock_guard<mutex> g(lock); vector<keystroke> result; result.reserve(keys.size()); for (const auto& key : keys) { result.push_back(key); } return result; } // function to receive keystrokes from the controller void key_reader::process_keypress(const keystroke& key) { unique_lock<mutex> l(lock); keys.push_back(key); cond.notify_all(); }
21.841584
70
0.703536
[ "vector" ]
9b3ff2f56e3353e4cc10521a9208cb65da012509
1,066
cpp
C++
template/src/Wrapper_py/Tools/Frozenbits_generator/Frozenbits_generator.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
15
2021-01-24T11:59:04.000Z
2022-03-23T07:23:44.000Z
template/src/Wrapper_py/Tools/Frozenbits_generator/Frozenbits_generator.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
8
2021-05-24T18:22:45.000Z
2022-03-11T09:48:05.000Z
template/src/Wrapper_py/Tools/Frozenbits_generator/Frozenbits_generator.cpp
aff3ct/py_aff3ct
8afb7e6b1db1b621db0ae4153b29a2e848e09fcf
[ "MIT" ]
4
2021-01-26T19:18:21.000Z
2021-12-07T17:02:34.000Z
#include "Wrapper_py/Tools/Frozenbits_generator/Frozenbits_generator.hpp" namespace py = pybind11; using namespace py::literals; using namespace aff3ct; using namespace aff3ct::module; using namespace aff3ct::tools; using namespace aff3ct::wrapper; Wrapper_Frozenbits_generator ::Wrapper_Frozenbits_generator(py::handle scope) : Wrapper_py(), py::class_<aff3ct::tools::Frozenbits_generator>(scope, "Frozenbits_generator") { } void Wrapper_Frozenbits_generator ::definitions() { this->def("generate", [](aff3ct::tools::Frozenbits_generator& self) { std::vector<bool> fb(self.get_N(), true); self.generate(fb); return fb; }, py::return_value_policy::copy); this->def("get_best_channels", &aff3ct::tools::Frozenbits_generator::get_best_channels); this->def("get_K", &aff3ct::tools::Frozenbits_generator::get_K); this->def("get_N", &aff3ct::tools::Frozenbits_generator::get_N); this->def("get_noise", &Frozenbits_generator::get_noise); this->def("set_noise", &Frozenbits_generator::set_noise); this->def("clone", &Frozenbits_generator::clone); };
29.611111
89
0.761726
[ "vector" ]
9b422f725a939f8023dbaced948b667cd0404931
18,774
cpp
C++
KaplaDemo/samples/sampleViewer3/IJGWin32/jclhuff.cpp
gongyiling/PhysX-3.4
99bc1c62880cf626f9926781e76a528b5276c68b
[ "Unlicense" ]
1,863
2018-12-03T13:06:03.000Z
2022-03-29T07:12:37.000Z
KaplaDemo/samples/sampleViewer3/IJGWin32/jclhuff.cpp
cctxx/PhysX-3.4-1
5e42a5f112351a223c19c17bb331e6c55037b8eb
[ "Unlicense" ]
71
2018-12-03T19:48:39.000Z
2022-01-11T09:30:52.000Z
KaplaDemo/samples/sampleViewer3/IJGWin32/jclhuff.cpp
cctxx/PhysX-3.4-1
5e42a5f112351a223c19c17bb331e6c55037b8eb
[ "Unlicense" ]
265
2018-12-03T14:30:03.000Z
2022-03-25T20:57:01.000Z
/* * jclhuff.c * * Copyright (C) 1991-1998, Thomas G. Lane. * This file is part of the Independent JPEG Group's software. * For conditions of distribution and use, see the accompanying README file. * * This file contains Huffman entropy encoding routines for lossless JPEG. * * Much of the complexity here has to do with supporting output suspension. * If the data destination module demands suspension, we want to be able to * back up to the start of the current MCU. To do this, we copy state * variables into local working storage, and update them back to the * permanent JPEG objects only upon successful completion of an MCU. */ #include "stdafx.h" #define JPEG_INTERNALS //#include "jinclude.h" //#include "jpeglib.h" //#include "jlossls.h" /* Private declarations for lossless codec */ //#include "jchuff.h" /* Declarations shared with jc*huff.c */ /* Expanded entropy encoder object for Huffman encoding. * * The savable_state subrecord contains fields that change within an MCU, * but must not be updated permanently until we complete the MCU. */ typedef struct { INT32 put_buffer; /* current bit-accumulation buffer */ int put_bits; /* # of bits now in it */ } savable_state; /* This macro is to work around compilers with missing or broken * structure assignment. You'll need to fix this code if you have * such a compiler and you change MAX_COMPS_IN_SCAN. */ #ifndef NO_STRUCT_ASSIGN #define ASSIGN_STATE(dest,src) ((dest) = (src)) #else #define ASSIGN_STATE(dest,src) \ ((dest).put_buffer = (src).put_buffer, \ (dest).put_bits = (src).put_bits) #endif typedef struct { int ci, yoffset, MCU_width; } lhe_input_ptr_info; typedef struct { savable_state saved; /* Bit buffer at start of MCU */ /* These fields are NOT loaded into local working state. */ unsigned int restarts_to_go; /* MCUs left in this restart interval */ int next_restart_num; /* next restart number to write (0-7) */ /* Pointers to derived tables (these workspaces have image lifespan) */ c_derived_tbl * derived_tbls[NUM_HUFF_TBLS]; /* Pointers to derived tables to be used for each data unit within an MCU */ c_derived_tbl * cur_tbls[C_MAX_DATA_UNITS_IN_MCU]; #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */ long * count_ptrs[NUM_HUFF_TBLS]; /* Pointers to stats tables to be used for each data unit within an MCU */ long * cur_counts[C_MAX_DATA_UNITS_IN_MCU]; #endif /* Pointers to the proper input difference row for each group of data units * within an MCU. For each component, there are Vi groups of Hi data units. */ JDIFFROW input_ptr[C_MAX_DATA_UNITS_IN_MCU]; /* Number of input pointers in use for the current MCU. This is the sum * of all Vi in the MCU. */ int num_input_ptrs; /* Information used for positioning the input pointers within the input * difference rows. */ lhe_input_ptr_info input_ptr_info[C_MAX_DATA_UNITS_IN_MCU]; /* Index of the proper input pointer for each data unit within an MCU */ int input_ptr_index[C_MAX_DATA_UNITS_IN_MCU]; } lhuff_entropy_encoder; typedef lhuff_entropy_encoder * lhuff_entropy_ptr; /* Working state while writing an MCU. * This struct contains all the fields that are needed by subroutines. */ typedef struct { JOCTET * next_output_byte; /* => next byte to write in buffer */ size_t free_in_buffer; /* # of byte spaces remaining in buffer */ savable_state cur; /* Current bit buffer & DC state */ j_compress_ptr cinfo; /* dump_buffer needs access to this */ } working_state; /* Forward declarations */ METHODDEF(JDIMENSION) encode_mcus_huff (j_compress_ptr cinfo, JDIFFIMAGE diff_buf, JDIMENSION MCU_row_num, JDIMENSION MCU_col_num, JDIMENSION nMCU); METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo)); #ifdef ENTROPY_OPT_SUPPORTED METHODDEF(JDIMENSION) encode_mcus_gather (j_compress_ptr cinfo, JDIFFIMAGE diff_buf, JDIMENSION MCU_row_num, JDIMENSION MCU_col_num, JDIMENSION nMCU); METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo)); #endif /* * Initialize for a Huffman-compressed scan. * If gather_statistics is TRUE, we do not output anything during the scan, * just count the Huffman symbols used and generate Huffman code tables. */ METHODDEF(void) start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics) { j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private; int ci, dctbl, sampn, ptrn, yoffset, xoffset; jpeg_component_info * compptr; if (gather_statistics) { #ifdef ENTROPY_OPT_SUPPORTED losslsc->entropy_encode_mcus = encode_mcus_gather; losslsc->pub.entropy_finish_pass = finish_pass_gather; #else ERREXIT(cinfo, JERR_NOT_COMPILED); #endif } else { losslsc->entropy_encode_mcus = encode_mcus_huff; losslsc->pub.entropy_finish_pass = finish_pass_huff; } for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; dctbl = compptr->dc_tbl_no; if (gather_statistics) { #ifdef ENTROPY_OPT_SUPPORTED /* Check for invalid table indexes */ /* (make_c_derived_tbl does this in the other path) */ if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS) ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl); /* Allocate and zero the statistics tables */ /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */ if (entropy->count_ptrs[dctbl] == NULL) entropy->count_ptrs[dctbl] = (long *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, 257 * SIZEOF(long)); MEMZERO(entropy->count_ptrs[dctbl], 257 * SIZEOF(long)); #endif } else { /* Compute derived values for Huffman tables */ /* We may do this more than once for a table, but it's not expensive */ jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl, & entropy->derived_tbls[dctbl]); } } /* Precalculate encoding info for each sample in an MCU of this scan */ for (sampn = 0, ptrn = 0; sampn < cinfo->data_units_in_MCU;) { compptr = cinfo->cur_comp_info[cinfo->MCU_membership[sampn]]; ci = compptr->component_index; /* ci = cinfo->MCU_membership[sampn]; compptr = cinfo->cur_comp_info[ci];*/ for (yoffset = 0; yoffset < compptr->MCU_height; yoffset++, ptrn++) { /* Precalculate the setup info for each input pointer */ entropy->input_ptr_info[ptrn].ci = ci; entropy->input_ptr_info[ptrn].yoffset = yoffset; entropy->input_ptr_info[ptrn].MCU_width = compptr->MCU_width; for (xoffset = 0; xoffset < compptr->MCU_width; xoffset++, sampn++) { /* Precalculate the input pointer index for each sample */ entropy->input_ptr_index[sampn] = ptrn; /* Precalculate which tables to use for each sample */ entropy->cur_tbls[sampn] = entropy->derived_tbls[compptr->dc_tbl_no]; entropy->cur_counts[sampn] = entropy->count_ptrs[compptr->dc_tbl_no]; } } } entropy->num_input_ptrs = ptrn; /* Initialize bit buffer to empty */ entropy->saved.put_buffer = 0; entropy->saved.put_bits = 0; /* Initialize restart stuff */ entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num = 0; } /* Outputting bytes to the file */ /* Emit a byte, taking 'action' if must suspend. */ #define emit_byte(state,val,action) \ { *(state)->next_output_byte++ = (JOCTET) (val); \ if (--(state)->free_in_buffer == 0) \ if (! dump_buffer(state)) \ { action; } } LOCAL(boolean) dump_buffer (working_state * state) /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */ { struct jpeg_destination_mgr * dest = state->cinfo->dest; if (! (*dest->empty_output_buffer) (state->cinfo)) return FALSE; /* After a successful buffer dump, must reset buffer pointers */ state->next_output_byte = dest->next_output_byte; state->free_in_buffer = dest->free_in_buffer; return TRUE; } /* Outputting bits to the file */ /* Only the right 24 bits of put_buffer are used; the valid bits are * left-justified in this part. At most 16 bits can be passed to emit_bits * in one call, and we never retain more than 7 bits in put_buffer * between calls, so 24 bits are sufficient. */ INLINE LOCAL(boolean) emit_bits (working_state * state, unsigned int code, int size) /* Emit some bits; return TRUE if successful, FALSE if must suspend */ { /* This routine is heavily used, so it's worth coding tightly. */ register INT32 put_buffer = (INT32) code; register int put_bits = state->cur.put_bits; /* if size is 0, caller used an invalid Huffman table entry */ if (size == 0) ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE); put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */ put_bits += size; /* new number of bits in buffer */ put_buffer <<= 24 - put_bits; /* align incoming bits */ put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */ while (put_bits >= 8) { int c = (int) ((put_buffer >> 16) & 0xFF); emit_byte(state, c, return FALSE); if (c == 0xFF) { /* need to stuff a zero byte? */ emit_byte(state, 0, return FALSE); } put_buffer <<= 8; put_bits -= 8; } state->cur.put_buffer = put_buffer; /* update state variables */ state->cur.put_bits = put_bits; return TRUE; } LOCAL(boolean) flush_bits (working_state * state) { if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */ return FALSE; state->cur.put_buffer = 0; /* and reset bit-buffer to empty */ state->cur.put_bits = 0; return TRUE; } /* * Emit a restart marker & resynchronize predictions. */ LOCAL(boolean) emit_restart (working_state * state, int restart_num) { //int ci; if (! flush_bits(state)) return FALSE; emit_byte(state, 0xFF, return FALSE); emit_byte(state, JPEG_RST0 + restart_num, return FALSE); /* The restart counter is not updated until we successfully write the MCU. */ return TRUE; } /* * Encode and output one nMCU's worth of Huffman-compressed differences. */ METHODDEF(JDIMENSION) encode_mcus_huff (j_compress_ptr cinfo, JDIFFIMAGE diff_buf, JDIMENSION MCU_row_num, JDIMENSION MCU_col_num, JDIMENSION nMCU) { j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private; working_state state; int mcu_num, sampn, ci, yoffset, MCU_width, ptrn; //jpeg_component_info * compptr; /* Load up working state */ state.next_output_byte = cinfo->dest->next_output_byte; state.free_in_buffer = cinfo->dest->free_in_buffer; ASSIGN_STATE(state.cur, entropy->saved); state.cinfo = cinfo; /* Emit restart marker if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) if (! emit_restart(&state, entropy->next_restart_num)) return 0; } /* Set input pointer locations based on MCU_col_num */ for (ptrn = 0; ptrn < entropy->num_input_ptrs; ptrn++) { ci = entropy->input_ptr_info[ptrn].ci; yoffset = entropy->input_ptr_info[ptrn].yoffset; MCU_width = entropy->input_ptr_info[ptrn].MCU_width; entropy->input_ptr[ptrn] = diff_buf[ci][MCU_row_num + yoffset] + (MCU_col_num * MCU_width); } for (mcu_num = 0; mcu_num < (int)nMCU; mcu_num++) { /* Inner loop handles the samples in the MCU */ for (sampn = 0; sampn < cinfo->data_units_in_MCU; sampn++) { register int temp, temp2; //, temp3; register int nbits; c_derived_tbl *dctbl = entropy->cur_tbls[sampn]; /* Encode the difference per section H.1.2.2 */ /* Input the sample difference */ temp = *entropy->input_ptr[entropy->input_ptr_index[sampn]]++; if (temp & 0x8000) { /* instead of temp < 0 */ temp = (-temp) & 0x7FFF; /* absolute value, mod 2^16 */ if (temp == 0) /* special case: magnitude = 32768 */ temp2 = temp = 0x8000; temp2 = ~ temp; /* one's complement of magnitude */ } else { temp &= 0x7FFF; /* abs value mod 2^16 */ temp2 = temp; /* magnitude */ } /* Find the number of bits needed for the magnitude of the difference */ nbits = 0; while (temp) { nbits++; temp >>= 1; } /* Check for out-of-range difference values. */ if (nbits > MAX_DIFF_BITS) ERREXIT(cinfo, JERR_BAD_DIFF); /* Emit the Huffman-coded symbol for the number of bits */ if (! emit_bits(&state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits])) return mcu_num; /* Emit that number of bits of the value, if positive, */ /* or the complement of its magnitude, if negative. */ if (nbits && /* emit_bits rejects calls with size 0 */ nbits != 16) /* special case: no bits should be emitted */ if (! emit_bits(&state, (unsigned int) temp2, nbits)) return mcu_num; } /* Completed MCU, so update state */ cinfo->dest->next_output_byte = state.next_output_byte; cinfo->dest->free_in_buffer = state.free_in_buffer; ASSIGN_STATE(entropy->saved, state.cur); /* Update restart-interval state too */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { entropy->restarts_to_go = cinfo->restart_interval; entropy->next_restart_num++; entropy->next_restart_num &= 7; } entropy->restarts_to_go--; } } return nMCU; } /* * Finish up at the end of a Huffman-compressed scan. */ METHODDEF(void) finish_pass_huff (j_compress_ptr cinfo) { j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private; working_state state; /* Load up working state ... flush_bits needs it */ state.next_output_byte = cinfo->dest->next_output_byte; state.free_in_buffer = cinfo->dest->free_in_buffer; ASSIGN_STATE(state.cur, entropy->saved); state.cinfo = cinfo; /* Flush out the last data */ if (! flush_bits(&state)) ERREXIT(cinfo, JERR_CANT_SUSPEND); /* Update state */ cinfo->dest->next_output_byte = state.next_output_byte; cinfo->dest->free_in_buffer = state.free_in_buffer; ASSIGN_STATE(entropy->saved, state.cur); } /* * Huffman coding optimization. * * We first scan the supplied data and count the number of uses of each symbol * that is to be Huffman-coded. (This process MUST agree with the code above.) * Then we build a Huffman coding tree for the observed counts. * Symbols which are not needed at all for the particular image are not * assigned any code, which saves space in the DHT marker as well as in * the compressed data. */ #ifdef ENTROPY_OPT_SUPPORTED /* * Trial-encode one nMCU's worth of Huffman-compressed differences. * No data is actually output, so no suspension return is possible. */ METHODDEF(JDIMENSION) encode_mcus_gather (j_compress_ptr cinfo, JDIFFIMAGE diff_buf, JDIMENSION MCU_row_num, JDIMENSION MCU_col_num, JDIMENSION nMCU) { j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private; int mcu_num, sampn, ci, yoffset, MCU_width, ptrn; //jpeg_component_info * compptr; /* Take care of restart intervals if needed */ if (cinfo->restart_interval) { if (entropy->restarts_to_go == 0) { /* Update restart state */ entropy->restarts_to_go = cinfo->restart_interval; } entropy->restarts_to_go--; } /* Set input pointer locations based on MCU_col_num */ for (ptrn = 0; ptrn < entropy->num_input_ptrs; ptrn++) { ci = entropy->input_ptr_info[ptrn].ci; yoffset = entropy->input_ptr_info[ptrn].yoffset; MCU_width = entropy->input_ptr_info[ptrn].MCU_width; entropy->input_ptr[ptrn] = diff_buf[ci][MCU_row_num + yoffset] + (MCU_col_num * MCU_width); } for (mcu_num = 0; mcu_num < (int)nMCU; mcu_num++) { /* Inner loop handles the samples in the MCU */ for (sampn = 0; sampn < cinfo->data_units_in_MCU; sampn++) { register int temp; register int nbits; c_derived_tbl *dctbl = entropy->cur_tbls[sampn]; long * counts = entropy->cur_counts[sampn]; /* Encode the difference per section H.1.2.2 */ /* Input the sample difference */ temp = *entropy->input_ptr[entropy->input_ptr_index[sampn]]++; if (temp & 0x8000) { /* instead of temp < 0 */ temp = (-temp) & 0x7FFF; /* absolute value, mod 2^16 */ if (temp == 0) /* special case: magnitude = 32768 */ temp = 0x8000; } else temp &= 0x7FFF; /* abs value mod 2^16 */ /* Find the number of bits needed for the magnitude of the difference */ nbits = 0; while (temp) { nbits++; temp >>= 1; } /* Check for out-of-range difference values. */ if (nbits > MAX_DIFF_BITS) ERREXIT(cinfo, JERR_BAD_DIFF); /* Count the Huffman symbol for the number of bits */ counts[nbits]++; } } return nMCU; } /* * Finish up a statistics-gathering pass and create the new Huffman tables. */ METHODDEF(void) finish_pass_gather (j_compress_ptr cinfo) { j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; lhuff_entropy_ptr entropy = (lhuff_entropy_ptr) losslsc->entropy_private; int ci, dctbl; jpeg_component_info * compptr; JHUFF_TBL **htblptr; boolean did_dc[NUM_HUFF_TBLS]; /* It's important not to apply jpeg_gen_optimal_table more than once * per table, because it clobbers the input frequency counts! */ MEMZERO(did_dc, SIZEOF(did_dc)); for (ci = 0; ci < cinfo->comps_in_scan; ci++) { compptr = cinfo->cur_comp_info[ci]; dctbl = compptr->dc_tbl_no; if (! did_dc[dctbl]) { htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl]; if (*htblptr == NULL) *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo); jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[dctbl]); did_dc[dctbl] = TRUE; } } } #endif /* ENTROPY_OPT_SUPPORTED */ METHODDEF(boolean) need_optimization_pass (j_compress_ptr cinfo) { return TRUE; } /* * Module initialization routine for Huffman entropy encoding. */ GLOBAL(void) jinit_lhuff_encoder (j_compress_ptr cinfo) { j_lossless_c_ptr losslsc = (j_lossless_c_ptr) cinfo->codec; lhuff_entropy_ptr entropy; int i; entropy = (lhuff_entropy_ptr) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(lhuff_entropy_encoder)); losslsc->entropy_private = (struct jpeg_entropy_encoder *) entropy; losslsc->pub.entropy_start_pass = start_pass_huff; losslsc->pub.need_optimization_pass = need_optimization_pass; /* Mark tables unallocated */ for (i = 0; i < NUM_HUFF_TBLS; i++) { entropy->derived_tbls[i] = NULL; #ifdef ENTROPY_OPT_SUPPORTED entropy->count_ptrs[i] = NULL; #endif } }
31.237937
79
0.693885
[ "object" ]
9b4cff2f5d9a7b056cf26097f56410789bb902f3
4,759
cpp
C++
platform/ivr/src/cppconn/mysql_parameter_metadata.cpp
lvbaocheng/CC
3febe5ce2804ef681a0d7d2f0011c3f92f2552d6
[ "Apache-2.0" ]
4
2018-08-23T07:08:35.000Z
2020-02-28T07:45:06.000Z
platform/ivr/src/cppconn/mysql_parameter_metadata.cpp
lvbaocheng/CC
3febe5ce2804ef681a0d7d2f0011c3f92f2552d6
[ "Apache-2.0" ]
1
2019-06-21T09:52:18.000Z
2019-06-21T09:52:18.000Z
platform/ivr/src/cppconn/mysql_parameter_metadata.cpp
lvbaocheng/CC
3febe5ce2804ef681a0d7d2f0011c3f92f2552d6
[ "Apache-2.0" ]
22
2018-07-11T06:30:39.000Z
2021-11-12T16:16:14.000Z
/* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/C++ is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. 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 */ #include <stdlib.h> #include "mysql_parameter_metadata.h" #include "nativeapi/native_statement_wrapper.h" #include <cppconn/exception.h> namespace sql { namespace mysql { /* {{{ MySQL_ParameterMetaData::MySQL_ParameterMetaData -I- */ MySQL_ParameterMetaData::MySQL_ParameterMetaData(boost::shared_ptr< NativeAPI::NativeStatementWrapper > & stmt) { // 2nd parameter is to be changed to boost::shared_ptr in case it's kept in the object param_count = stmt->param_count(); } /* }}} */ /* {{{ MySQL_ParameterMetaData::getParameterClassName -U- */ sql::SQLString MySQL_ParameterMetaData::getParameterClassName(unsigned int /* paramNo */) { throw sql::MethodNotImplementedException("MySQL_ParameterMetaData::getParameterClassName()"); return ""; // fool compilers } /* }}} */ /* {{{ MySQL_ParameterMetaData::getParameterCount -I- */ int MySQL_ParameterMetaData::getParameterCount() { return param_count; } /* }}} */ /* {{{ MySQL_ParameterMetaData::getParameterMode -U- */ int MySQL_ParameterMetaData::getParameterMode(unsigned int /* paramNo */) { throw sql::MethodNotImplementedException("MySQL_ParameterMetaData::getParameterClassName()"); return 0; // fool compilers } /* }}} */ /* {{{ MySQL_ParameterMetaData::getParameterType -U- */ int MySQL_ParameterMetaData::getParameterType(unsigned int /* paramNo */) { throw sql::MethodNotImplementedException("MySQL_ParameterMetaData::getParameterClassName()"); return 0; // fool compilers } /* }}} */ /* {{{ MySQL_ParameterMetaData::getParameterTypeName -U- */ sql::SQLString MySQL_ParameterMetaData::getParameterTypeName(unsigned int /* paramNo */) { throw sql::MethodNotImplementedException("MySQL_ParameterMetaData::getParameterClassName()"); return 0; // fool compilers } /* }}} */ /* {{{ MySQL_ParameterMetaData::getPrecision -U- */ int MySQL_ParameterMetaData::getPrecision(unsigned int /* paramNo */) { throw sql::MethodNotImplementedException("MySQL_ParameterMetaData::getParameterClassName()"); return 0; // fool compilers } /* }}} */ /* {{{ MySQL_ParameterMetaData::getScale -U- */ int MySQL_ParameterMetaData::getScale(unsigned int /* paramNo */) { throw sql::MethodNotImplementedException("MySQL_ParameterMetaData::getParameterClassName()"); return 0; // fool compilers } /* }}} */ /* {{{ MySQL_ParameterMetaData::isNullable -U- */ int MySQL_ParameterMetaData::isNullable(unsigned int /* paramNo */) { throw sql::MethodNotImplementedException("MySQL_ParameterMetaData::getParameterClassName()"); return 0; // fool compilers } /* }}} */ /* {{{ MySQL_ParameterMetaData::isSigned -U- */ bool MySQL_ParameterMetaData::isSigned(unsigned int /* paramNo */) { throw sql::MethodNotImplementedException("MySQL_ParameterMetaData::getParameterClassName()"); return 0; // fool compilers } /* }}} */ } /* namespace mysql */ } /* namespace sql */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
33.048611
119
0.632906
[ "object" ]
9b4d2a505e8bed3901c33e204a05468fb68388df
16,342
cpp
C++
scooter/lib/SCMD/src/SCMD.cpp
kisom/robots
7ffc8e7b797448bee42659952d5bb901b69e9068
[ "MIT" ]
null
null
null
scooter/lib/SCMD/src/SCMD.cpp
kisom/robots
7ffc8e7b797448bee42659952d5bb901b69e9068
[ "MIT" ]
null
null
null
scooter/lib/SCMD/src/SCMD.cpp
kisom/robots
7ffc8e7b797448bee42659952d5bb901b69e9068
[ "MIT" ]
null
null
null
/****************************************************************************** SCMD.cpp SCMD Arduino and Teensy Driver Marshall Taylor @ SparkFun Electronics May 20, 2015 https://github.com/sparkfun/Serial_Controlled_Motor_Driver https://github.com/sparkfun/SparkFun_Serial_Controlled_Motor_Driver_Arduino_Library Resources: Uses Wire.h for i2c operation Uses SPI.h for SPI operation Development environment specifics: <arduino/development environment version> <hardware version> <etc> This code is released under the [MIT License](http://opensource.org/licenses/MIT). Please review the LICENSE.md file included with this example. If you have any questions or concerns with licensing, please contact techsupport@sparkfun.com. Distributed as-is; no warranty is given. ******************************************************************************/ //Define USE_ALT_I2C to use the teesny 3 i2c_t3.h library, which allows I2C bus hang resolution // THIS MUST BE DONE WITHIN THIS FILE. Users wishing to do this will probably find themselves // copying SCMD.cpp, SCMD.h, and SCMD_config.h to their project folder and excluding the arduino // library form the IDE entirely. //#define USE_ALT_I2C //Use VERBOSE_SERIAL to add debug serial to an existing Serial object. //Note: Use of VERBOSE_SERIAL adds delays surround RW ops, and should not be used //for functional testing. //#define VERBOSE_SERIAL //See _____ for additional topology notes. #include <stdint.h> #include <math.h> #include "SCMD.h" #include "SCMD_config.h" //Contains #defines for common SCMD register names and values #ifdef USE_ALT_I2C #include <i2c_t3.h> #define I2C_FAULT_TIMEOUT 1000 //in microseconds #else #include "Wire.h" #endif #include "SPI.h" //****************************************************************************// // // Constructor // // Initalizes settings to default. // //****************************************************************************// SCMD::SCMD( void ) { //Construct with these default settings if nothing is specified //Select interface mode settings.commInterface = I2C_MODE; //I2C_MODE or SPI_MODE //Select default I2C address. settings.I2CAddress = 0x58; //Ignored for SPI_MODE //Select default SPI CS pin. settings.chipSelectPin = 10; //Ignored for I2C_MODE } //****************************************************************************// // // Configuration section // // This uses the stored SensorSettings to start the IMU. // // Example usage: // //Configure for SPI mode using default CS pin of 10 // mySensor.settings.commInterface = SPI_MODE; // mySensor.begin(); // //****************************************************************************// uint8_t SCMD::begin( void ) { //Check the settings structure values to determine how to setup the device uint8_t dataToWrite = 0; //Temporary variable switch (settings.commInterface) { case I2C_MODE: Wire.begin(); break; case SPI_MODE: // initalize the data ready and chip select pins: pinMode(settings.chipSelectPin, OUTPUT); digitalWrite(settings.chipSelectPin, HIGH); // Delay to give the target time to clear any faults induced by the low // start the SPI library: SPI.begin(); // Maximum SPI frequency is 1MHz use SPI_CLK_DIV16 SPI.setClockDivider(SPI_CLOCK_DIV32); // Data is read and written MSb first. SPI.setBitOrder(MSBFIRST); // Data is captured on rising edge of clock (CPHA = 0) // Base value of the clock is LOW (CPOL = 0) SPI.setDataMode(SPI_MODE0); break; default: break; } //dummy read readRegister(SCMD_ID); return readRegister(SCMD_ID); } //check if enumeration is complete bool SCMD::ready( void ) { uint8_t statusByte = readRegister(SCMD_STATUS_1); if(( statusByte & SCMD_ENUMERATION_BIT )&&(( statusByte != 0xFF )))//wait for ready flag and not 0xFF { return true; } else { #ifdef VERBOSE_SERIAL Serial.print("-"); #endif return false; } } //check if SCMD is busy bool SCMD::busy( void ) { uint8_t statusByte = readRegister(SCMD_STATUS_1); if( statusByte & (SCMD_BUSY_BIT | SCMD_REM_READ_BIT | SCMD_REM_WRITE_BIT)) { #ifdef VERBOSE_SERIAL Serial.print("."); #endif return true; } else { return false; } } //Enable and disable functions. Call after begin to enable the h-bridges void SCMD::enable( void ) { writeRegister(SCMD_DRIVER_ENABLE, 0x01); } void SCMD::disable( void ) { writeRegister(SCMD_DRIVER_ENABLE, 0x00); } //Reset function void SCMD::reset( void ) { #ifdef USE_ALT_I2C //Blast the Teensy 3.1 i2c control register uint8_t * I2C_CTRL1_reg; I2C_CTRL1_reg = (uint8_t *)0x40066002; *I2C_CTRL1_reg = 0x00; //Waiting seems like a good idea delay(10); Wire.resetBus(); //Strictly resets. Run .begin() afterwards Wire.begin(); #endif } //****************************************************************************// // // Drive Section // //****************************************************************************// //setDrive( ... ) // // Drive a motor at a level // // uint8_t motorNum -- Motor number from 0 to 33 // uint8_t direction -- 0 or 1 for forward and backward // uint8_t level -- 0 to 255 for drive strength void SCMD::setDrive( uint8_t motorNum, uint8_t direction, uint8_t level ) { //convert to 7 bit level = level >> 1; int16_t driveValue; //use to build value to actually write to register //Make sure the motor number is valid if(motorNum < 34) { driveValue = (level * direction) + ((int8_t)level * ((int8_t)direction - 1)); //set to 1/2 drive if direction = 1 or -1/2 drive if direction = 0; (level * direction); driveValue += 128; writeRegister(SCMD_MA_DRIVE + motorNum, driveValue); } } //inversionMode( ... ) // // Configure a motor's direction inversion // // uint8_t motorNum -- Motor number from 0 to 33 // uint8_t polarity -- 0 or 1 for default or inverted void SCMD::inversionMode( uint8_t motorNum, uint8_t polarity ) { uint8_t regTemp; //Select target register if( motorNum < 2 ) { //master if( motorNum == 0 ) writeRegister(SCMD_MOTOR_A_INVERT, polarity & 0x01); if( motorNum == 1 ) writeRegister(SCMD_MOTOR_B_INVERT, polarity & 0x01); } else { if( motorNum < 10 ) { //register: SCMD_INV_2_9 regTemp = SCMD_INV_2_9; motorNum -= 2; } else if( motorNum < 18 ) { //register: SCMD_INV_10_17 regTemp = SCMD_INV_10_17; motorNum -= 10; } else if( motorNum < 26 ) { //register: SCMD_INV_18_25 regTemp = SCMD_INV_18_25; motorNum -= 18; } else if( motorNum < 34 ) { //register: SCMD_INV_26_33 regTemp = SCMD_INV_26_33; motorNum -= 26; } else { //out of range return; } //convert motorNum to one-hot mask uint8_t data = readRegister( regTemp ) & ~( 1 << motorNum ); writeRegister( regTemp, data | ((polarity & 0x01) << motorNum) ); } } //bridgingMode( ... ) // // Configure a driver's bridging state // // uint8_t driverNum -- Number of driver. Master is 0, slave 1 is 1, etc. 0 to 16 // uint8_t bridged -- 0 or 1 for forward and backward void SCMD::bridgingMode( uint8_t driverNum, uint8_t bridged ) { uint8_t regTemp; //Select target register if( driverNum < 1 ) { //master writeRegister(SCMD_BRIDGE, bridged & 0x01); } else { if( driverNum < 9 ) { //register: SCMD_BRIDGE_SLV_L regTemp = SCMD_BRIDGE_SLV_L; driverNum -= 1; } else if( driverNum < 17 ) { //register: SCMD_BRIDGE_SLV_H regTemp = SCMD_BRIDGE_SLV_H; driverNum -= 9; } else { //out of range return; } //convert driverNum to one-hot mask uint8_t data = readRegister( regTemp ) & ~( 1 << driverNum ); writeRegister( regTemp, data | ((bridged & 0x01) << driverNum) ); } } //****************************************************************************// // // Diagnostics // //****************************************************************************// //getDiagnostics( ... ) // // Get diagnostic information from the master // // SCMDDiagnostics &diagObjectReference -- Object to contain returned data void SCMD::getDiagnostics( SCMDDiagnostics &diagObjectReference ) { diagObjectReference.U_I2C_RD_ERR = readRegister( SCMD_U_I2C_RD_ERR ); diagObjectReference.U_I2C_WR_ERR = readRegister( SCMD_U_I2C_WR_ERR ); diagObjectReference.U_BUF_DUMPED = readRegister( SCMD_U_BUF_DUMPED ); diagObjectReference.E_I2C_RD_ERR = readRegister( SCMD_E_I2C_RD_ERR ); diagObjectReference.E_I2C_WR_ERR = readRegister( SCMD_E_I2C_WR_ERR ); diagObjectReference.LOOP_TIME = readRegister( SCMD_LOOP_TIME ); diagObjectReference.SLV_POLL_CNT = readRegister( SCMD_SLV_POLL_CNT ); //Count slaves uint8_t topAddr = readRegister( SCMD_SLV_TOP_ADDR ); if( (topAddr >= START_SLAVE_ADDR) && (topAddr < (START_SLAVE_ADDR + 16))) { //in valid range diagObjectReference.numberOfSlaves = topAddr - START_SLAVE_ADDR + 1; } diagObjectReference.MST_E_ERR = readRegister( SCMD_MST_E_ERR ); diagObjectReference.MST_E_STATUS = readRegister( SCMD_MST_E_STATUS ); diagObjectReference.FSAFE_FAULTS = readRegister( SCMD_FSAFE_FAULTS ); diagObjectReference.REG_OOR_CNT = readRegister( SCMD_REG_OOR_CNT ); diagObjectReference.REG_RO_WRITE_CNT = readRegister( SCMD_REG_RO_WRITE_CNT ); } //getRemoteDiagnostics( ... ) // // Get diagnostic information from a slave // // uint8_t address -- Address of slave to read. Can be 0x50 to 0x5F for slave 1 to 16. // SCMDDiagnostics &diagObjectReference -- Object to contain returned data void SCMD::getRemoteDiagnostics( uint8_t address, SCMDDiagnostics &diagObjectReference ) { diagObjectReference.numberOfSlaves = 0; diagObjectReference.U_I2C_RD_ERR = 0; diagObjectReference.U_I2C_WR_ERR = 0; diagObjectReference.U_BUF_DUMPED = 0; diagObjectReference.E_I2C_RD_ERR = readRemoteRegister( address, SCMD_E_I2C_RD_ERR ); diagObjectReference.E_I2C_WR_ERR = readRemoteRegister( address, SCMD_E_I2C_WR_ERR ); diagObjectReference.LOOP_TIME = readRemoteRegister( address, SCMD_LOOP_TIME ); diagObjectReference.SLV_POLL_CNT = 0; diagObjectReference.MST_E_ERR = 0; diagObjectReference.MST_E_STATUS = 0; diagObjectReference.FSAFE_FAULTS = readRemoteRegister( address, SCMD_FSAFE_FAULTS ); diagObjectReference.REG_OOR_CNT = readRemoteRegister( address, SCMD_REG_OOR_CNT ); diagObjectReference.REG_RO_WRITE_CNT = readRemoteRegister( address, SCMD_REG_RO_WRITE_CNT ); } //resetDiagnosticCounts( ... ) // // Reset the master's diagnostic counters // void SCMD::resetDiagnosticCounts( void ) { writeRegister( SCMD_U_I2C_RD_ERR, 0 ); writeRegister( SCMD_U_I2C_WR_ERR, 0 ); writeRegister( SCMD_U_BUF_DUMPED, 0 ); writeRegister( SCMD_E_I2C_RD_ERR, 0 ); writeRegister( SCMD_E_I2C_WR_ERR, 0 ); //Clear uport time writeRegister( SCMD_LOOP_TIME, 0 ); writeRegister( SCMD_MST_E_ERR, 0 ); writeRegister( SCMD_FSAFE_FAULTS, 0 ); writeRegister( SCMD_REG_OOR_CNT, 0 ); writeRegister( SCMD_REG_RO_WRITE_CNT, 0 ); } //resetRemoteDiagnosticCounts( ... ) // // Reset a slave's diagnostic counters // // uint8_t address -- Address of slave to read. Can be 0x50 to 0x5F for slave 1 to 16. void SCMD::resetRemoteDiagnosticCounts( uint8_t address ) { writeRemoteRegister( address, SCMD_U_I2C_RD_ERR, 0 ); writeRemoteRegister( address, SCMD_U_I2C_WR_ERR, 0 ); writeRemoteRegister( address, SCMD_U_BUF_DUMPED, 0 ); writeRemoteRegister( address, SCMD_E_I2C_RD_ERR, 0 ); writeRemoteRegister( address, SCMD_E_I2C_WR_ERR, 0 ); //Clear uport time writeRemoteRegister( address, SCMD_LOOP_TIME, 0 ); writeRemoteRegister( address, SCMD_ID, 0 ); writeRemoteRegister( address, SCMD_FSAFE_FAULTS, 0 ); writeRemoteRegister( address, SCMD_REG_OOR_CNT, 0 ); writeRemoteRegister( address, SCMD_REG_RO_WRITE_CNT, 0 ); } //****************************************************************************// // // Register Access Functions // //****************************************************************************// //readRegister( ... ) // // Read data from the master // // uint8_t offset -- Address of data to read. Can be 0x00 to 0x7F uint8_t SCMD::readRegister(uint8_t offset) { //Return value uint8_t result; uint8_t numBytes = 1; switch (settings.commInterface) { case I2C_MODE: Wire.beginTransmission(settings.I2CAddress); Wire.write(offset); #ifdef USE_ALT_I2C if(Wire.endTransmission(I2C_STOP, I2C_FAULT_TIMEOUT)) i2cFaults++; #else Wire.endTransmission(); #endif #ifdef USE_ALT_I2C if( Wire.requestFrom(settings.I2CAddress, numBytes, I2C_STOP, I2C_FAULT_TIMEOUT) == 0 )i2cFaults++; #else Wire.requestFrom(settings.I2CAddress, numBytes); #endif while ( Wire.available() ) // slave may send less than requested { result = Wire.read(); // receive a byte as a proper uint8_t } break; case SPI_MODE: // take the chip select low to select the device: digitalWrite(settings.chipSelectPin, LOW); // send the device the register you want to read: SPI.transfer(offset | 0x80); //Ored with "read request" bit // take the chip select high to de-select: digitalWrite(settings.chipSelectPin, HIGH); //For loop delay for 16 Mhz CPU for(volatile int i = 0; i < 50; i++); //do a dummy read digitalWrite(settings.chipSelectPin, LOW); // send a value of 80 to read the first byte returned: result = SPI.transfer(0x80); // take the chip select high to de-select: digitalWrite(settings.chipSelectPin, HIGH); //For loop delay for 16 Mhz CPU for(volatile int i = 0; i < 50; i++); break; default: break; } #ifdef VERBOSE_SERIAL Serial.print("~R"); Serial.print(offset, HEX); Serial.print(":"); Serial.print(result, HEX); Serial.println(""); #endif return result; } //writeRegister( ... ) // // Write data to the master // // uint8_t offset -- Address of data to write. Can be 0x00 to 0x7F // uint8_t dataToWrite -- Data to write. void SCMD::writeRegister(uint8_t offset, uint8_t dataToWrite) { switch (settings.commInterface) { case I2C_MODE: //Write the byte Wire.beginTransmission(settings.I2CAddress); Wire.write(offset); Wire.write(dataToWrite); #ifdef USE_ALT_I2C if(Wire.endTransmission(I2C_STOP,I2C_FAULT_TIMEOUT)) i2cFaults++; #else Wire.endTransmission(); #endif // delay(1); break; case SPI_MODE: // take the chip select low to select the device: digitalWrite(settings.chipSelectPin, LOW); // send the device the register you want to read: SPI.transfer(offset & 0x7F); // send a value of 0 to read the first byte returned: SPI.transfer(dataToWrite); // decrement the number of bytes left to read: // take the chip select high to de-select: digitalWrite(settings.chipSelectPin, HIGH); for(volatile int i = 0; i < 50; i++); break; default: break; } #ifdef VERBOSE_SERIAL Serial.print("~W"); Serial.print(offset, HEX); Serial.print(":"); Serial.print(dataToWrite, HEX); Serial.println(""); #endif } //readRegister( ... ) // // Read data from a slave. Note that this waits 5ms for slave data to be aquired // before making the final read. // // uint8_t address -- Address of slave to read. Can be 0x50 to 0x5F for slave 1 to 16. // uint8_t offset -- Address of data to read. Can be 0x00 to 0x7F uint8_t SCMD::readRemoteRegister(uint8_t address, uint8_t offset) { //while(busy()); writeRegister(SCMD_REM_ADDR, address); writeRegister(SCMD_REM_OFFSET, offset); writeRegister(SCMD_REM_READ, 1); while(busy()); uint8_t result = readRegister(SCMD_REM_DATA_RD); #ifdef VERBOSE_SERIAL Serial.print("~R"); Serial.print(address, HEX); Serial.print(","); Serial.print(offset, HEX); Serial.print(":"); Serial.print(result, HEX); Serial.println(""); #endif return result; } //writeRegister( ... ) // // Write data from a slave // // uint8_t address -- Address of slave to read. Can be 0x50 to 0x5F for slave 1 to 16. // uint8_t offset -- Address of data to write. Can be 0x00 to 0x7F // uint8_t dataToWrite -- Data to write. void SCMD::writeRemoteRegister(uint8_t address, uint8_t offset, uint8_t dataToWrite) { while(busy()); writeRegister(SCMD_REM_ADDR, address); writeRegister(SCMD_REM_OFFSET, offset); writeRegister(SCMD_REM_DATA_WR, dataToWrite); writeRegister(SCMD_REM_WRITE, 1); while(busy()); #ifdef VERBOSE_SERIAL Serial.print("~W"); Serial.print(address, HEX); Serial.print(","); Serial.print(offset, HEX); Serial.print(":"); Serial.print(dataToWrite, HEX); Serial.println(""); #endif }
27.982877
168
0.681496
[ "object" ]
9b4d40844430f9503a956d1bdf797d3d929b3fad
14,298
cc
C++
ns-allinone-2.35/packmime/packmime_OL_ranvar.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2020-05-29T13:04:42.000Z
2020-05-29T13:04:42.000Z
ns-allinone-2.35/packmime/packmime_OL_ranvar.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2019-01-20T17:35:23.000Z
2019-01-22T21:41:38.000Z
ns-allinone-2.35/packmime/packmime_OL_ranvar.cc
nitishk017/ns2project
f037b796ff10300ffe0422580be5855c37d0b140
[ "MIT" ]
1
2021-09-29T16:06:57.000Z
2021-09-29T16:06:57.000Z
/* -*- Mode:C++; c-basic-offset:8; tab-width:8; indent-tabs-mode:t -*- */ /* * Copyright 2002, Statistics Research, Bell Labs, Lucent Technologies and * The University of North Carolina at Chapel Hill * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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) * 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. */ /* * Reference * Stochastic Models for Generating Synthetic HTTP Source Traffic * J. Cao, W.S. Cleveland, Y. Gao, K. Jeffay, F.D. Smith, and M.C. Weigle * IEEE INFOCOM 2004. * * Documentation available at http://dirt.cs.unc.edu/packmime/ * * Contacts: Michele Weigle (mcweigle@cs.unc.edu), * Kevin Jeffay (jeffay@cs.unc.edu) */ #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <assert.h> #include "packmime_OL_ranvar.h" /** * Reference: * Modeling Persistence in Hydrological Time Series Using Fractional * Differencing * By J.R.M. Hosking, Water Resources Research, Vol 20, No 12, P1898-1908, * Dec 1984 * * y[t] = sum_j=1^p (AR[j] * y[t-j]) + x[t] - sum_j=1^q (MA[j] * x[t-j] */ #define ROOT_2 1.4142135623730950488016887242096980785697 /*2^1/2*/ #define E22 1.7155277699214135929603792825575449562416 /*sqrt(8/e) */ #define EPSILON 1e-2 #define Min(a, b) ((a) < (b) ? (a) : (b)) /** * hard wired model constants from fitting BL-MH packet trace * (all tcp, both directions), parameters values from * /home/cao/MySwork/packet/dataObj/superpose/.Data/pac.fit1.para.vs.rate.fit * ; the original code to produce parameters is in superpose_par_vs_rate.S */ //static struct OL_weibull_params pac_ia_weibull_params = { // -0.487, /* shapeParam0 */ // 0.032, /* shapeParam1 */ // 1.702 /* shapeParam2 */ //}; static struct OL_arima_params pac_ia_arima_params = { 0.41, /* d */ 1000, /* number of finite AR rep of farima */ 0, 1, /* pAR=0, qMA */ -1.345, /* varRatioParam0 */ 0.009, /* varRatioParam1 */ 2.217 /* varRatioParam2 */ }; /*:::::::::::::::::::::: Packet Inter-Arrival RanVar :::::::::::::::::*/ static class PackMimeOLPacketIARandomVariableClass : public TclClass { public: PackMimeOLPacketIARandomVariableClass() : TclClass("RandomVariable/PackMimeOLPacketIA"){} TclObject* create(int argc, const char*const* argv) { if (argc == 5) { // bitrate return(new PackMimeOLPacketIARandomVariable((double)atof(argv[4]))); } else if (argc == 6) { // bitrate, RNG RNG* rng = (RNG*)TclObject::lookup(argv[5]); return(new PackMimeOLPacketIARandomVariable((double)atof(argv[4]), rng)); } else if (argc == 7) { // bitrate, RNG RNG* rng = (RNG*)TclObject::lookup(argv[5]); PackMimeOLPacketIARandomVariable *iarng = new PackMimeOLPacketIARandomVariable((double)atof(argv[4]), rng); RandomVariable *sizerng_ = (RandomVariable*)TclObject::lookup(argv[6]); iarng->setPktSizeRng(sizerng_); return(iarng); } else { return(new PackMimeOLPacketIARandomVariable()); } } } class_PacketIAranvar; PackMimeOLPacketIARandomVariable::PackMimeOLPacketIARandomVariable(): fARIMA(NULL), myrng(NULL), sizerng(NULL) { bind_vars(); } PackMimeOLPacketIARandomVariable::PackMimeOLPacketIARandomVariable(double bitrate_) : bitrate(bitrate_), fARIMA(NULL), myrng(NULL), sizerng(NULL) { bind_vars(); } PackMimeOLPacketIARandomVariable::PackMimeOLPacketIARandomVariable(double bitrate_, RNG* rng_) : bitrate(bitrate_), fARIMA(NULL), myrng(rng_), sizerng(NULL) { bind_vars(); } void PackMimeOLPacketIARandomVariable::bind_vars() { bind ("bitrate", &bitrate); bind ("pacrate", &pacrate); bind ("connum", &connum); bind ("conbps", &conbps); bind ("conpacrate", &conpacrate); } /* initialize for pac.ia */ void PackMimeOLPacketIARandomVariable::initialize() { double sigmaTotal; struct OL_arima_params *arima = &pac_ia_arima_params; // struct OL_weibull_params *weibull = &pac_ia_weibull_params; double d = arima->d; double logit_simia; assert(arima->N >= arima->qMA); if (sizerng==NULL) sizerng = new PackMimeOLPacketSizeRandomVariable(); if (conbps<=0) conbps = conpacrate * sizerng->avg() * 8; if (connum<=0) connum = bitrate/conbps; if (pacrate<=0) pacrate = bitrate/sizerng->avg()/8; /** * old method * varRatio = 1.0 - pow(2.0, arima->varRatioParam0 - * arima->varRatioParam1 * pow(log(rate)/LOG2, * arima->varRatioParam2)); */ logit_simia = pow(2.0, -0.6661682 + 0.4192597*log(connum)/LOG2); varRatio = logit_simia/(1+logit_simia); sigmaTotal = 1.0; sigmaNoise = sigmaTotal * pow(varRatio,0.5); sigmaEpsilon = sigmaTotal * pow(exp(2.0*myrng->gammln(1.0-d)-myrng->gammln(1.0-2.0*d))/(2+2*d/(1-d)) * (1-varRatio), 0.5); /** * shape = 1.0 - pow(2.0, * weibull->shapeParam0 - * weibull->shapeParam1 * pow(log(rate)/LOG2, * weibull->shapeParam2)); */ logit_simia = pow(2.0, -2.462267 + 0.4920002*log(connum)/LOG2); shape = logit_simia/(1+logit_simia); scale = 1.0 / (connum * exp(myrng->gammln(1+1.0/shape))); if (!myrng) myrng = new RNG(); fARIMA = new FARIMA(myrng, arima->d, arima->N); } PackMimeOLPacketIARandomVariable::~PackMimeOLPacketIARandomVariable() { delete myrng; delete fARIMA; } /** * generate packet IA according to the marginal distribution */ double PackMimeOLPacketIARandomVariable::transform(double p) { double yt; yt = myrng->qweibull(p, shape, scale); return(yt); } /** * generate packet IA according to Long-Range Dependent plus Noise (LRDN) model */ double PackMimeOLPacketIARandomVariable::value() { double yt; if (fARIMA == NULL) initialize(); yt = fARIMA->Next(); yt = yt * sigmaEpsilon + myrng->rnorm() * sigmaNoise; yt = transform(myrng->pnorm(yt)); return(yt); } double PackMimeOLPacketIARandomVariable::avg() { if (fARIMA == NULL) initialize(); if (pacrate!=0) return (1/pacrate); else return 0; } /** * hard wired model constants from fitting BL-MH packet trace */ static struct OL_arima_params pac_size_arima_params = { 0.41, /* d */ 1000, /* number of finite AR rep of farima */ 0, 1, /* pAR=0, qMA */ -0.051, /* varRatioParam0 */ 0.08, /* varRatioParam1 */ 1.597 /* varRatioParam2 */ }; /*:::::::::::::::::::::: Packet Size RanVar :::::::::::::::::*/ static class PackMimeOLPacketSizeRandomVariableClass : public TclClass { public: PackMimeOLPacketSizeRandomVariableClass() : TclClass("RandomVariable/PackMimeOLPacketSize"){} TclObject* create(int argc, const char*const* argv) { if (argc == 5) { // rate return(new PackMimeOLPacketSizeRandomVariable((double)atof(argv[4]))); } else if (argc == 6) { // rate, RNG RNG* rng = (RNG*)TclObject::lookup(argv[5]); return(new PackMimeOLPacketSizeRandomVariable((double)atof(argv[4]), rng)); } else if (argc == 7) { // rate, RNG, filename RNG* rng = (RNG*)TclObject::lookup(argv[5]); return(new PackMimeOLPacketSizeRandomVariable((double)atof(argv[4]), rng, argv[6])); } else { return(new PackMimeOLPacketSizeRandomVariable()); } } } class_PackMimeOLPacketSizeranvar; PackMimeOLPacketSizeRandomVariable::PackMimeOLPacketSizeRandomVariable(): pac_size_dist_file(NULL), fARIMA(NULL), myrng(NULL) { bind_vars(); } PackMimeOLPacketSizeRandomVariable::PackMimeOLPacketSizeRandomVariable(double bitrate_): bitrate(bitrate_), pac_size_dist_file(NULL), fARIMA(NULL), myrng(NULL) { bind_vars(); } PackMimeOLPacketSizeRandomVariable::PackMimeOLPacketSizeRandomVariable(double bitrate_, RNG* rng_): bitrate(bitrate_), pac_size_dist_file(NULL), fARIMA(NULL), myrng(rng_) { bind_vars(); } PackMimeOLPacketSizeRandomVariable::PackMimeOLPacketSizeRandomVariable(double bitrate_, RNG* rng_, const char *pac_size_dist_file_): bitrate(bitrate_), fARIMA(NULL), myrng(rng_) { bind_vars(); pac_size_dist_file = new char[strlen(pac_size_dist_file_)+1]; strcpy(pac_size_dist_file, pac_size_dist_file_); } void PackMimeOLPacketSizeRandomVariable::bind_vars() { bind ("bitrate", &bitrate); bind ("connum", &connum); bind ("conbps", &conbps); bind ("conpacrate", &conpacrate); } int PackMimeOLPacketSizeRandomVariable::def_size_dist_left[14] = {40, 41, 44, 45, 48, 49, 52, 53, 85, 221, 576, 577, 1401, 1500}; int PackMimeOLPacketSizeRandomVariable::def_size_dist_right[14] = {40, 43, 44, 47, 48, 51, 52, 84, 220, 575, 576, 1400, 1499, 1500}; double PackMimeOLPacketSizeRandomVariable::def_size_prob[14] = {0.300, 0.000, 0.030, 0.000, 0.030, 0.010, 0.060, 0.070, 0.050, 0.070, 0.120, 0.060, 0.050, 0.150 }; /** * initialise for pac.size */ void PackMimeOLPacketSizeRandomVariable::initialize() { double sigmaTotal; struct OL_arima_params *arima = &pac_size_arima_params; double d = arima->d; double logit_simsize; assert(arima->N >= arima->qMA); if (conbps<=0) conbps = conpacrate * avg() * 8; if (connum<=0) connum = bitrate/conbps; /** * old method * varRatio = 1.0 - pow(2.0, * arima->varRatioParam0 - * arima->varRatioParam1 * pow(log(rate)/LOG2, * arima->varRatioParam2)); */ logit_simsize = pow(2.0, -3.117395 + 0.7224436*log(connum)/LOG2); varRatio = logit_simsize/(1+logit_simsize); sigmaTotal = 1.0; sigmaNoise = sigmaTotal * pow(varRatio,0.5); sigmaEpsilon = sigmaTotal * pow(exp(2.0*myrng->gammln(1.0-d)-myrng->gammln(1.0-2.0*d))/(2+2*d/(1-d)) * (1-varRatio), 0.5); if (!myrng) myrng = new RNG(); fARIMA = new FARIMA(myrng, arima->d, arima->N); init_dist(); } void PackMimeOLPacketSizeRandomVariable::init_dist() { int n; if (pac_size_dist_file==NULL) { size_dist_left = def_size_dist_left; size_dist_right = def_size_dist_right; size_prob = def_size_prob; n_size_dist = sizeof(def_size_dist_left)/sizeof(int); } else read_dist(); /* cumsum_size_prob = cumsum(prob0, prob1, prob2, ..., prob(n-1)) * cumsum_size_prob[last] = 1 */ cumsum_size_prob = new double[n_size_dist]; for(n=0; n<n_size_dist; n++){ if(n==0) { cumsum_size_prob[0] = size_prob[0]; } else { cumsum_size_prob[n] = cumsum_size_prob[n-1] + size_prob[n]; } } } void PackMimeOLPacketSizeRandomVariable::read_dist() { FILE *fp; double totalprob; int n; if((fp = fopen(pac_size_dist_file, "r")) == NULL) { fprintf(stderr, "Error: can't open %s\n", pac_size_dist_file); exit(1); } n = 0; /* line number - 1 */ totalprob = 0; do { if(n == 0 ) { fscanf(fp, "%d\n", &n_size_dist); size_dist_left = new int[n_size_dist]; size_dist_right = new int[n_size_dist]; size_prob = new double[n_size_dist]; } else { fscanf(fp, "%d %d %lf\n", &size_dist_left[n-1], &size_dist_right[n-1], &size_prob[n-1]); if(size_dist_right[n-1] < size_dist_left[n-1]) { fprintf(stderr, "Error: size_dist_right must >= size_dist_left\n"); exit(1); } if(n>1) { if(size_dist_left[n-1] != size_dist_right[n-2]+1){ fprintf(stderr, "Error: size_dist_left(n) must = size_dist_right(n-1)+1\n"); exit(1); } } totalprob += size_prob[n-1]; } n++; } while((n <= n_size_dist) && !feof(fp)); if(totalprob>1){ fprintf(stderr, "Error: sum of size_prob > 1, check!\n"); } else { if(totalprob < 1-EPSILON) { fprintf(stderr, "size_prob[%d] increase from %g to %g, so sum of prob. is 1\n", n_size_dist-1, size_prob[n_size_dist-1], size_prob[n_size_dist-1]+(1-totalprob)); } size_prob[n_size_dist-1] = size_prob[n_size_dist-1]+(1-totalprob); } if(n <= n_size_dist) { fprintf(stderr, "Error: wrong value of n_size_dist in %s!\n", pac_size_dist_file); exit(1); } fclose(fp); } PackMimeOLPacketSizeRandomVariable::~PackMimeOLPacketSizeRandomVariable() { delete fARIMA; if(n_size_dist > 0){ delete size_dist_left; delete size_dist_right; delete size_prob; delete cumsum_size_prob; } } /** * generate packet size according to the marginal distribution */ int PackMimeOLPacketSizeRandomVariable::transform(double p) { int i, size; double p1; i = 0; while(p > cumsum_size_prob[i]) i++; p1 = cumsum_size_prob[i]-cumsum_size_prob[i-1]; size = (size_dist_left[i]-1) + (int) (ceil((p-cumsum_size_prob[i-1])/p1 * (size_dist_right[i]-(size_dist_left[i]-1)))); return size; } /** * compute the mean of packet size distribution */ double PackMimeOLPacketSizeRandomVariable::avg() { int i; double m = 0; if (fARIMA == NULL) init_dist(); for(i=0; i<n_size_dist; i++) m += size_prob[i] * (size_dist_left[i]+size_dist_right[i])/2; return m; } /** * generate packet size according to Long-Range Dependent plus Noise (LRDN) model */ double PackMimeOLPacketSizeRandomVariable::value(void) { double yt; if (fARIMA == NULL) initialize(); yt = fARIMA->Next(); yt = yt * sigmaEpsilon + myrng->rnorm() * sigmaNoise; return ((double)transform(myrng->pnorm(yt))); }
29.419753
166
0.67408
[ "shape", "model", "transform" ]
9b5ec1395c0c3a9995acca91cbc079c3dcb29d54
10,547
cpp
C++
tools/mcrl3explore/mcrl3explore.cpp
wiegerw/mcrl3
15260c92ab35930398d6dfb34d31351b05101ca9
[ "BSL-1.0" ]
1
2021-02-22T09:16:39.000Z
2021-02-22T09:16:39.000Z
tools/mcrl3explore/mcrl3explore.cpp
wiegerw/mcrl3
15260c92ab35930398d6dfb34d31351b05101ca9
[ "BSL-1.0" ]
null
null
null
tools/mcrl3explore/mcrl3explore.cpp
wiegerw/mcrl3
15260c92ab35930398d6dfb34d31351b05101ca9
[ "BSL-1.0" ]
null
null
null
// Author(s): Muck van Weerdenburg // Wieger Wesselink 2018 // Copyright: see the accompanying file COPYING or copy at // https://github.com/mCRL2org/mCRL2/blob/master/COPYING // // 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) // /// \file lps2lts_lts.cpp #include <cassert> #include <csignal> #include <memory> #include <string> #include "mcrl2/data/rewriter_tool.h" #include "mcrl2/lps/io.h" #include "mcrl2/lts/detail/exploration.h" #include "mcrl2/lts/lts_io.h" #include "mcrl2/process/action_parse.h" #include "mcrl2/utilities/input_output_tool.h" #include "mcrl2/utilities/logger.h" using namespace mcrl2; using namespace mcrl2::utilities::tools; using namespace mcrl2::utilities; using namespace mcrl2::core; using namespace mcrl2::lts; using namespace mcrl2::lps; using namespace mcrl2::log; using mcrl2::data::tools::rewriter_tool; struct abortable { virtual void abort() = 0; }; struct next_state_abortable: public abortable { lps2lts_algorithm<lps::next_state_generator>* algorithm; explicit next_state_abortable(lps2lts_algorithm<lps::next_state_generator>* algorithm_) : algorithm(algorithm_) {} void abort() override { algorithm->abort(); } }; struct cached_next_state_abortable: public abortable { lps2lts_algorithm<lps::cached_next_state_generator>* algorithm; explicit cached_next_state_abortable(lps2lts_algorithm<lps::cached_next_state_generator>* algorithm_) : algorithm(algorithm_) {} void abort() override { algorithm->abort(); } }; class mcrl3explore_tool: public rewriter_tool<input_output_tool> { protected: typedef rewriter_tool<input_output_tool> super; lts_generation_options m_options; std::string m_filename; abortable* m_abortable = nullptr; public: mcrl3explore_tool(): super("mcrl3explore", "Wieger Wesselink", "generate an LTS from an LPS", "Generate an LTS from the LPS in INFILE and save the result to OUTFILE. " "If INFILE is not supplied, stdin is used. " "If OUTFILE is not supplied, the LTS is not stored.\n" "\n" "If the 'jittyc' rewriter is used, then the MCRL2_COMPILEREWRITER environment " "variable (default value: 'mcrl2compilerewriter') determines the script that " "compiles the rewriter, and MCRL2_COMPILEDIR (default value: '.') determines " "where temporary files are stored.\n" "\n" "Note that mcrl3explore can deliver multiple transitions with the same label between" "any pair of states. If this is not desired, such transitions can be removed by" "applying a strong bisimulation reducton using for instance the tool ltsconvert.\n" "\n" "The format of OUTFILE is determined by its extension (unless it is specified " "by an option). The supported formats are:\n" "\n" +mcrl2::lts::detail::supported_lts_formats_text()+"\n" "If the jittyc rewriter is used, then the MCRL2_COMPILEREWRITER environment " "variable (default value: mcrl2compilerewriter) determines the script that " "compiles the rewriter, and MCRL2_COMPILEDIR (default value: '.') " "determines where temporary files are stored." "\n" "Note that mcrl3explore can deliver multiple transitions with the same " "label between any pair of states. If this is not desired, such " "transitions can be removed by applying a strong bisimulation reducton " "using for instance the tool ltsconvert." ) { } void abort() { m_abortable->abort(); } bool run() override { load_lps(m_options.specification, m_filename); try { if (m_options.use_enumeration_caching) { lps2lts_algorithm<lps::cached_next_state_generator> algorithm; m_abortable = new cached_next_state_abortable(&algorithm); algorithm.generate_lts(m_options); } else { lps2lts_algorithm<lps::next_state_generator> algorithm; m_abortable = new next_state_abortable(&algorithm); algorithm.generate_lts(m_options); } } catch (mcrl2::runtime_error& e) { mCRL2log(error) << e.what() << std::endl; return false; } return true; } protected: void add_options(interface_description& desc) override { super::add_options(desc); desc. add_option("cached", "use enumeration caching techniques to speed up state space generation. "). add_option("dummy", make_mandatory_argument("BOOL"), "replace free variables in the LPS with dummy values based on the value of BOOL: 'yes' (default) or 'no'. ", 'y'). add_option("unused-data", "do not remove unused parts of the data specification. ", 'u'). add_option("max", make_mandatory_argument("NUM"), "explore at most NUM states", 'l'). add_option("todo-max", make_mandatory_argument("NUM"), "keep at most NUM states in todo lists; this option is only relevant for " "breadth-first search, where NUM is the maximum number of states per " "level, and for depth first search, where NUM is the maximum depth. "). add_option("nondeterminism", "detect nondeterministic states, i.e. states with outgoing transitions with the same label to different states. ", 'n'). add_option("deadlock", "detect deadlocks (i.e. for every deadlock a message is printed). ", 'D'). add_option("out", make_mandatory_argument("FORMAT"), "save the output in the specified FORMAT. ", 'o'). add_option("no-info", "do not add state information to OUTFILE. " "Without this option mcrl3explore adds state vector to the LTS. This " "option causes this information to be discarded and states are only " "indicated by a sequence number. Explicit state information is useful " "for visualisation purposes, for instance, but can cause the OUTFILE " "to grow considerably. Note that this option is implicit when writing " "in the AUT format. "). add_option("suppress","in verbose mode, do not print progress messages indicating the number of visited states and transitions. " "For large state spaces the number of progress messages can be quite " "horrendous. This feature helps to suppress those. Other verbose messages, " "such as the total number of states explored, just remain visible. "). add_option("init-tsize", make_mandatory_argument("NUM"), "set the initial size of the internally used hash tables (default is 10000). "); } void parse_options(const command_line_parser& parser) override { super::parse_options(parser); m_options.remove_unused_rewrite_rules = parser.options.count("unused-data") == 0; m_options.detect_deadlock = parser.options.count("deadlock") != 0; m_options.detect_nondeterminism = parser.options.count("nondeterminism") != 0; m_options.outinfo = parser.options.count("no-info") == 0; m_options.suppress_progress_messages = parser.options.count("suppress") != 0; m_options.strat = parser.option_argument_as<mcrl2::data::rewriter::strategy>("rewriter"); m_options.use_enumeration_caching = parser.options.count("cached") > 0; if (parser.options.count("dummy")) { if (parser.options.count("dummy") > 1) { parser.error("Multiple use of option -y/--dummy; only one occurrence is allowed."); } std::string dummy_str(parser.option_argument("dummy")); if (dummy_str == "yes") { m_options.instantiate_global_variables = true; } else if (dummy_str == "no") { m_options.instantiate_global_variables = false; } else { parser.error("Option -y/--dummy has illegal argument '" + dummy_str + "'."); } } if (parser.options.count("max")) { m_options.max_states = parser.option_argument_as<unsigned long> ("max"); } if (parser.options.count("out")) { m_options.outformat = mcrl2::lts::detail::parse_format(parser.option_argument("out")); if (m_options.outformat == lts_none) { parser.error("Format '" + parser.option_argument("out") + "' is not recognised."); } } if (parser.options.count("init-tsize")) { m_options.initial_table_size = parser.option_argument_as< unsigned long >("init-tsize"); } if (parser.options.count("todo-max")) { m_options.todo_max = parser.option_argument_as< unsigned long >("todo-max"); } if (parser.options.count("suppress") && !mCRL2logEnabled(verbose)) { parser.error("Option --suppress requires --verbose (of -v)."); } if (2 < parser.arguments.size()) { parser.error("Too many file arguments."); } if (!parser.arguments.empty()) { m_filename = parser.arguments[0]; } if (1 < parser.arguments.size()) { m_options.filename = parser.arguments[1]; } if (!m_options.filename.empty() && m_options.outformat == lts_none) { m_options.outformat = mcrl2::lts::detail::guess_format(m_options.filename); if (m_options.outformat == lts_none) { mCRL2log(warning) << "no output format set or detected; using default (mcrl2)" << std::endl; m_options.outformat = lts_lts; } } } }; std::unique_ptr<mcrl3explore_tool> tool_instance; static void premature_termination_handler(int) { // Reset signal handlers. signal(SIGABRT, nullptr); signal(SIGINT, nullptr); tool_instance->abort(); } int main(int argc, char** argv) { tool_instance = std::make_unique<mcrl3explore_tool>(); signal(SIGABRT, premature_termination_handler); signal(SIGINT, premature_termination_handler); // At ^C invoke the termination handler. return tool_instance->execute(argc, argv); }
36.877622
137
0.640182
[ "vector" ]
9b608cd2afdc97faa49e8a907c1b31677defad3d
25,461
cpp
C++
src/parse.cpp
bebuch/disposer
8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105
[ "BSL-1.0" ]
null
null
null
src/parse.cpp
bebuch/disposer
8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105
[ "BSL-1.0" ]
24
2017-03-10T10:45:36.000Z
2018-07-05T19:38:58.000Z
src/parse.cpp
bebuch/disposer
8d065cb5cdcbeaecdbe457f5e4e60ff1ecc84105
[ "BSL-1.0" ]
2
2017-02-21T06:45:42.000Z
2020-04-18T11:22:33.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2015-2018 Benjamin Buch // // https://github.com/bebuch/disposer // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) //----------------------------------------------------------------------------- #include <disposer/config/parse_config.hpp> #include <boost/spirit/home/x3.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <istream> #include <map> BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::specialized_parameter, type, value ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::parameter, key, generic_value, specialized_values ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::parameter_set, name, parameters ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::in, name, transfer, variable ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::out, name, variable ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::wait_on, number, type_name ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::parameters, parameter_sets, parameters ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::module, type_name, wait_ons, parameters, inputs, outputs ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::chain, name, id_generator, modules ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::component, name, type_name, parameters ) BOOST_FUSION_ADAPT_STRUCT( disposer::types::parse::config, sets, components, chains ) namespace disposer::parser{ class syntax_error: public std::logic_error{ public: syntax_error(std::string&& message, std::string::iterator pos): std::logic_error(std::move(message)), pos_(pos) {} std::string::iterator pos()const{ return pos_; } private: std::string::iterator const pos_; }; namespace x3 = boost::spirit::x3; using x3::lit; using x3::char_; using x3::eol; using x3::eoi; struct transfer_: x3::symbols< in_transfer >{ transfer_(){ add ("&", in_transfer::copy) ("<", in_transfer::move); } } transfer; /// \brief Parser for line counting template < typename Iterator > std::size_t line_count(Iterator first, Iterator last){ namespace x3 = boost::spirit::x3; using x3::eol; std::size_t n = 1; auto const inc = [&n](x3::unused_type){ ++n; }; x3::phrase_parse(first, last, x3::no_skip[ *(*(x3::omit[char_] - eol) >> eol[inc]) ], x3::space); return n; } /// \brief Get text from the last line template < typename Iterator > std::string get_error_line_before(Iterator first, Iterator pos){ namespace x3 = boost::spirit::x3; using x3::eol; auto line_start = std::find_if( std::make_reverse_iterator(pos), std::make_reverse_iterator(first), [](char c){ return c == '\n' || c == '\r'; }).base(); return std::string(line_start, pos); } /// \brief Get text from the first line template < typename Iterator > std::string get_error_line_after(Iterator pos, Iterator last){ namespace x3 = boost::spirit::x3; using x3::eol; auto line_end = std::find_if( pos, last, [](char c){ return c == '\n' || c == '\r'; }); if(last == line_end){ return std::string(pos, line_end); }else{ return std::string(pos, line_end) + '\n'; } } template < typename Derived > struct error_base{ template < typename Iter, typename Exception, typename Context > x3::error_handler_result on_error( Iter& /*first*/, Iter const& /*last*/, Exception const& x, Context const& /*context*/ ){ throw syntax_error( static_cast< Derived const& >(*this).message(), x.where()); } }; namespace type = types::parse; struct space_tag; x3::rule< space_tag > const space("space"); struct space_lines_tag; x3::rule< space_lines_tag > const space_lines("space_lines"); struct separator_tag; x3::rule< separator_tag > const separator("separator"); struct comment_tag; x3::rule< comment_tag > const comment("comment"); struct keyword_spaces_tag; x3::rule< keyword_spaces_tag, std::string > const keyword_spaces("keyword_spaces"); struct value_spaces_tag; x3::rule< value_spaces_tag, std::string > const value_spaces("value_spaces"); auto const space_def = lit(' ') | '\t' ; auto const space_lines_def = *(*space >> eol) ; auto const separator_def = *space >> (eol >> space_lines >> -comment) ; auto const comment_def = *space >> (lit('#') | ';') >> *(char_ - eol) >> separator ; auto const keyword_spaces_def = +(char_(' ') | char_('\t')) >> !(eol | '=') ; auto const value_spaces_def = +(char_(' ') | char_('\t')) >> !(eol | eoi) ; struct keyword_tag; x3::rule< keyword_tag, std::string > const keyword("keyword"); struct value_tag; x3::rule< value_tag, std::string > const value("value"); auto const keyword_def = (char_ - space - '=' - eol) >> *(keyword_spaces | +(char_ - space - eol - '=')) ; auto const value_def = (char_ - space - eol) >> *(value_spaces | +(char_ - space - eol)) ; struct sets_param_specialization_tag; x3::rule< sets_param_specialization_tag, type::specialized_parameter > const sets_param_specialization("sets_param_specialization"); struct sets_param_tag; x3::rule< sets_param_tag, type::parameter > const sets_param("sets_param"); struct sets_param_prevent_tag; x3::rule< sets_param_prevent_tag > const sets_param_prevent("sets_param_prevent"); struct sets_param_list_tag; x3::rule< sets_param_list_tag, std::vector< type::parameter > > const sets_param_list("sets_param_list"); struct sets_set_tag; x3::rule< sets_set_tag, type::parameter_set > const sets_set("sets_set"); struct sets_set_list_tag; x3::rule< sets_set_list_tag, type::parameter_sets > const sets_set_list("sets_set_list"); struct sets_set_list_checked_tag; x3::rule< sets_set_list_checked_tag, type::parameter_sets > const sets_set_list_checked("sets_set_list_checked"); struct sets_config_tag; x3::rule< sets_config_tag, type::parameter_sets > const sets_config("sets_config"); auto const sets_param_specialization_def = "\t\t\t" > keyword > *space > '=' > *space > value > separator ; auto const sets_param_def = ("\t\t" >> sets_param_prevent >> keyword) > -(*space >> ('=' > *space > value)) > separator > *sets_param_specialization ; auto const sets_param_prevent_def = x3::expect[!("parameter_set" >> *space >> '=')] ; auto const sets_param_list_def = x3::expect[+sets_param] ; auto const sets_set_def = '\t' > keyword > separator > sets_param_list ; auto const sets_set_list_def = x3::expect[+sets_set] ; auto const sets_set_list_checked_def = sets_set_list > &x3::expect[(lit("component") | "chain") >> separator] ; auto const sets_config_def = ("parameter_set" > separator > sets_set_list_checked) | &x3::expect[(lit("component") | "chain") >> separator] ; struct sets_param_specialization_tag: error_base< sets_param_specialization_tag > { const char* message()const{ return "a parameter specialization '\t\t\ttype = value\n'"; } }; struct sets_param_tag: error_base< sets_param_tag >{ const char* message()const{ return "a parameter '\t\tname [= value]\n' with name != " "'parameter_set'"; } }; struct sets_param_prevent_tag: error_base< sets_param_prevent_tag >{ const char* message()const{ return "a parameter, but a parameter name " "('\t\tname [= value]\n') must not be 'parameter_set'"; } }; struct sets_param_list_tag: error_base< sets_param_list_tag >{ const char* message()const{ return "at least one parameter line '\t\tname [= value]\n' " "with name != 'parameter_set'"; } }; struct sets_set_tag: error_base< sets_set_tag >{ const char* message()const{ return "a parameter set line '\tname\n'"; } }; struct sets_set_list_tag: error_base< sets_set_list_tag >{ const char* message()const{ return "at least one parameter set line '\tname\n'"; } }; struct sets_set_list_checked_tag: error_base< sets_set_list_checked_tag >{ const char* message()const{ return "a parameter set line '\tname\n' or a parameter definition " "('\t\tname [= value]\n') or a parameter specialization " "'\t\t\ttype = value\n' or keyword line 'component\n' or " "keyword line 'chain\n'"; } }; struct sets_config_tag: error_base< sets_config_tag >{ template < typename Iter, typename Exception, typename Context > x3::error_handler_result on_error( Iter& first, Iter const& last, Exception const& x, Context const& context ){ msg_ = "keyword line 'parameter_set\n'"; if(x.which() != "separator"){ msg_ += " or keyword line 'component\n' or keyword line " "'chain\n'"; } return error_base::on_error(first, last, x, context); } const char* message()const{ return msg_.c_str(); } std::string msg_; }; struct module_params_tag; x3::rule< module_params_tag, type::parameters > const module_params("module_params"); struct module_params_checked_tag; x3::rule< module_params_checked_tag, type::parameters > const module_params_checked("module_params_checked"); struct module_set_ref_tag; x3::rule< module_set_ref_tag, std::string > const module_set_ref("module_set_ref"); struct module_wait_on_tag; x3::rule< module_wait_on_tag, type::wait_on > const module_wait_on("module_wait_on"); struct module_param_specialization_tag; x3::rule< module_param_specialization_tag, type::specialized_parameter > const module_param_specialization("module_param_specialization"); struct module_param_prevent_tag; x3::rule< module_param_prevent_tag > const module_param_prevent("module_param_prevent"); struct module_param_tag; x3::rule< module_param_tag, type::parameter > const module_param("module_param"); struct input_tag; x3::rule< input_tag, type::in > const input("input"); struct output_tag; x3::rule< output_tag, type::out > const output("output"); struct input_params_tag; x3::rule< input_params_tag, std::vector< type::in > > const input_params("input_params"); struct output_params_tag; x3::rule< output_params_tag, std::vector< type::out > > const output_params("output_params"); struct inputs_tag; x3::rule< inputs_tag, std::vector< type::in > > const inputs("inputs"); struct outputs_tag; x3::rule< outputs_tag, std::vector< type::out > > const outputs("outputs"); struct module_tag; x3::rule< module_tag, type::module > const module("module"); struct chain_tag; x3::rule< chain_tag, type::chain > const chain("chain"); struct chain_config_tag; x3::rule< chain_config_tag, type::chain > const chain_config("chain_config"); struct chain_params_tag; x3::rule< chain_params_tag, std::vector< type::module > > const chain_params("chain_params"); struct id_generator_tag; x3::rule< id_generator_tag, std::string > const id_generator("id_generator"); struct chains_params_tag; x3::rule< chains_params_tag, type::chains > const chains_params("chains_params"); struct chains_tag; x3::rule< chains_tag, type::chains > const chains("chains"); struct component_params_checked_tag; x3::rule< component_params_checked_tag, type::parameters > const component_params_checked("component_params_checked"); struct component_set_ref_tag; x3::rule< component_set_ref_tag, std::string > const component_set_ref("component_set_ref"); struct component_param_specialization_tag; x3::rule< component_param_specialization_tag, type::specialized_parameter > const component_param_specialization("component_param_specialization"); struct component_param_prevent_tag; x3::rule< component_param_prevent_tag > const component_param_prevent("component_param_prevent"); struct component_param_tag; x3::rule< component_param_tag, type::parameter > const component_param("component_param"); struct component_tag; x3::rule< component_tag, type::component > const component("component"); struct component_config_tag; x3::rule< component_config_tag, type::component > const component_config("component_config"); struct component_list_tag; x3::rule< component_list_tag, type::components > const component_list("component_list"); struct component_list_checked_tag; x3::rule< component_list_checked_tag, type::components > const component_list_checked("component_list_checked"); struct components_tag; x3::rule< components_tag, type::components > const components("components"); auto const module_params_def = "\t\t\tparameter" > separator > module_params_checked ; auto const module_params_checked_def = &x3::expect[module_set_ref | module_param] >> (*module_set_ref >> *module_param) ; auto const module_set_ref_def = // wait for = before throw because a parameter name // might begin with parameter_set ("\t\t\t\tparameter_set" >> *space >> '=') > *space > value > separator ; auto const module_wait_on_def = "\t\t\twait_on" > *space > '=' > *space > x3::ulong_ > ':' > value > separator ; auto const module_param_specialization_def = "\t\t\t\t\t" > keyword > *space > '=' > *space > value > separator ; auto const module_param_prevent_def = x3::expect[!("parameter_set" >> *space >> '=')] ; auto const module_param_def = ("\t\t\t\t" >> module_param_prevent >> keyword) > -(*space >> ('=' > *space > value)) > separator > *module_param_specialization ; auto const input_def = "\t\t\t\t" > (keyword >> *space) > ('=' >> *space) > transfer > value > separator ; auto const output_def = "\t\t\t\t" > (keyword >> *space) > ('=' >> *space) > '>' > value > separator ; auto const input_params_def = x3::expect[+input] ; auto const output_params_def = x3::expect[+output] ; auto const inputs_def = ("\t\t\t<-" > separator) >> input_params ; auto const outputs_def = ("\t\t\t->" > separator) >> output_params ; auto const module_def = ("\t\t" > keyword > separator) >> *module_wait_on >> -module_params >> -inputs >> -outputs ; auto const id_generator_def = ('=' >> *space) > value ; auto const chain_params_def = x3::expect[+module] ; auto const chain_def = ('\t' > (keyword >> *space) > -id_generator > separator) >> chain_params ; auto const chain_config_def = x3::no_skip[x3::expect[ space_lines >> -comment >> chain ]]; auto const chains_params_def = x3::expect[+chain] ; auto const chains_def = (x3::expect["chain"] > separator) >> chains_params ; auto const component_params_checked_def = &x3::expect[component_set_ref | component_param] >> (*component_set_ref >> *component_param) ; auto const component_set_ref_def = ("\t\tparameter_set" >> *space >> '=') > *space > value > separator ; auto const component_param_specialization_def = "\t\t\t" > keyword > *space > '=' > *space > value > separator ; auto const component_param_prevent_def = x3::expect[!("parameter_set" >> *space >> '=')] ; auto const component_param_def = ("\t\t" >> component_param_prevent >> keyword) > -(*space >> ('=' > *space > value)) > separator > *component_param_specialization ; auto const component_def = ("\t" > keyword > *space > '=' > *space > value > separator) >> component_params_checked ; auto const component_config_def = x3::no_skip[x3::expect[ space_lines >> -comment >> component ]]; auto const component_list_def = x3::expect[+component] ; auto const component_list_checked_def = component_list > &x3::expect["chain" >> separator] ; auto const components_def = ("component" > separator > component_list_checked) | &x3::expect["chain" >> separator] ; struct config_tag; x3::rule< config_tag, type::config > const config("config"); auto const config_def = x3::no_skip[x3::expect[ space_lines >> -comment >> -sets_config >> -components >> chains ]]; struct module_params_tag: error_base< module_params_tag >{ const char* message()const{ return "keyword line '\t\t\tparameter\n'"; } }; struct module_params_checked_tag: error_base< module_params_checked_tag >{ const char* message()const{ return "at least one parameter set reference line " "'\t\t\t\tparameter_set = name\n', where 'parameter_set' is a " "keyword and 'name' the name of the referenced parameter set " "or one parameter '\t\t\t\tname [= value]\n'"; } }; struct module_set_ref_tag: error_base< module_set_ref_tag >{ const char* message()const{ return "a parameter set reference line " "'\t\t\t\tparameter_set = name\n', where 'parameter_set' is a " "keyword and 'name' the name of the referenced parameter set"; } }; struct module_wait_on_tag: error_base< module_wait_on_tag >{ const char* message()const{ return "a wait_on reference line " "'\t\t\twait_on = number:module\n', where 'wait_on' is a " "keyword, 'number' is the (with 1 beginning) number of the " "referenced module in the current chain and 'module' is the " "type name of the referenced module"; } }; struct modules_params_tag: error_base< modules_params_tag >{ const char* message()const{ return "at least one module line '\tname = module\n'"; } }; struct module_param_prevent_tag: error_base< module_param_prevent_tag >{ const char* message()const{ return "another parameter, but a parameter name " "('\t\t\t\tname [= value]\n') must not be 'parameter_set'"; } }; struct module_param_specialization_tag : error_base< module_param_specialization_tag > { const char* message()const{ return "a parameter specialization '\t\t\t\t\ttype = value\n'"; } }; struct module_param_tag: error_base< module_param_tag >{ const char* message()const{ return "a parameter '\t\t\t\tname [= value]\n' with name != " "'parameter_set'"; } }; struct input_tag: error_base< input_tag >{ const char* message()const{ return "input map '\t\t\t\tinput = {< or &}variable'"; } }; struct output_tag: error_base< output_tag >{ const char* message()const{ return "output map '\t\t\t\toutput = >variable'"; } }; struct input_params_tag: error_base< input_params_tag >{ const char* message()const{ return "at least one input map " "'\t\t\t\tinput = {< or &}variable'"; } }; struct output_params_tag: error_base< output_params_tag >{ const char* message()const{ return "at least one output map " "'\t\t\t\toutput = >variable'"; } }; struct inputs_tag: error_base< inputs_tag >{ const char* message()const{ return "keyword line '\t\t\t<-\n'"; } }; struct outputs_tag: error_base< outputs_tag >{ const char* message()const{ return "keyword line '\t\t\t->\n'"; } }; struct module_tag: error_base< module_tag >{ const char* message()const{ return "a module line '\t\tmodule\n'"; } }; struct chains_params_tag: error_base< chains_params_tag >{ const char* message()const{ return "at least one chain line '\tname [= id_generator]\n'"; } }; struct id_generator_tag: error_base< id_generator_tag >{ const char* message()const{ return "a chain line with id_generator '\tname = id_generator\n'"; } }; struct chains_tag: error_base< chains_tag >{ const char* message()const{ return "keyword line 'chain\n'"; } }; struct component_params_checked_tag : error_base< component_params_checked_tag > { const char* message()const{ return "at least one parameter set reference line " "'\t\t\tparameter_set = name\n', where 'parameter_set' is a " "keyword and 'name' the name of the referenced parameter set " "or one parameter '\t\t\tname [= value]\n'"; } }; struct component_set_ref_tag: error_base< component_set_ref_tag >{ const char* message()const{ return "a parameter set reference line " "'\t\t\tparameter_set = name\n', where 'parameter_set' is a " "keyword and 'name' the name of the referenced parameter set"; } }; struct component_param_prevent_tag : error_base< component_param_prevent_tag > { const char* message()const{ return "another parameter, but a parameter name " "('\t\tname [= value]\n') must not be 'parameter_set'"; } }; struct component_param_specialization_tag : error_base< component_param_specialization_tag > { const char* message()const{ return "a parameter specialization '\t\t\ttype = value\n'"; } }; struct component_tag: error_base< component_tag >{ const char* message()const{ return "a component line '\tname = component\n'"; } }; struct component_param_tag: error_base< component_param_tag >{ const char* message()const{ return "a parameter '\t\tname [= value]\n' with name != " "'parameter_set'"; } }; struct component_list_tag: error_base< component_list_tag >{ const char* message()const{ return "at least one component line '\tname = component\n'"; } }; struct component_list_checked_tag: error_base< component_list_checked_tag >{ const char* message()const{ return "a parameter set line '\tname\n' or a parameter definition " "('\t\tname [= value]\n') or a parameter specialization " "'\t\t\ttype = value\n' or keyword line 'component\n' or " "keyword line 'chain\n'"; } }; struct components_tag: error_base< components_tag >{ template < typename Iter, typename Exception, typename Context > x3::error_handler_result on_error( Iter& first, Iter const& last, Exception const& x, Context const& context ){ msg_ = "keyword line 'component\n'"; if(x.which() != "separator"){ msg_ += " or keyword line 'chain\n'"; } return error_base::on_error(first, last, x, context); } const char* message()const{ return msg_.c_str(); } std::string msg_; }; struct config_tag: error_base< config_tag >{ const char* message()const{ return "keyword line 'parameter_set\n' or keyword line " "'component\n' or keyword line 'chain\n'"; } }; BOOST_SPIRIT_DEFINE(space) BOOST_SPIRIT_DEFINE(space_lines) BOOST_SPIRIT_DEFINE(separator) BOOST_SPIRIT_DEFINE(comment) BOOST_SPIRIT_DEFINE(keyword_spaces) BOOST_SPIRIT_DEFINE(value_spaces) BOOST_SPIRIT_DEFINE(keyword) BOOST_SPIRIT_DEFINE(value) BOOST_SPIRIT_DEFINE(sets_param_specialization) BOOST_SPIRIT_DEFINE(sets_param) BOOST_SPIRIT_DEFINE(sets_param_prevent) BOOST_SPIRIT_DEFINE(sets_param_list) BOOST_SPIRIT_DEFINE(sets_set) BOOST_SPIRIT_DEFINE(sets_set_list) BOOST_SPIRIT_DEFINE(sets_set_list_checked) BOOST_SPIRIT_DEFINE(sets_config) BOOST_SPIRIT_DEFINE(module_param_specialization) BOOST_SPIRIT_DEFINE(module_param) BOOST_SPIRIT_DEFINE(module_param_prevent) BOOST_SPIRIT_DEFINE(module_params) BOOST_SPIRIT_DEFINE(module_params_checked) BOOST_SPIRIT_DEFINE(module_set_ref) BOOST_SPIRIT_DEFINE(module_wait_on) BOOST_SPIRIT_DEFINE(input) BOOST_SPIRIT_DEFINE(output) BOOST_SPIRIT_DEFINE(inputs) BOOST_SPIRIT_DEFINE(outputs) BOOST_SPIRIT_DEFINE(input_params) BOOST_SPIRIT_DEFINE(output_params) BOOST_SPIRIT_DEFINE(module) BOOST_SPIRIT_DEFINE(chain_params) BOOST_SPIRIT_DEFINE(chain) BOOST_SPIRIT_DEFINE(chain_config) BOOST_SPIRIT_DEFINE(id_generator) BOOST_SPIRIT_DEFINE(chains_params) BOOST_SPIRIT_DEFINE(chains) BOOST_SPIRIT_DEFINE(component_params_checked) BOOST_SPIRIT_DEFINE(component_set_ref) BOOST_SPIRIT_DEFINE(component_param_specialization) BOOST_SPIRIT_DEFINE(component_param_prevent) BOOST_SPIRIT_DEFINE(component_param) BOOST_SPIRIT_DEFINE(component) BOOST_SPIRIT_DEFINE(component_config) BOOST_SPIRIT_DEFINE(component_list) BOOST_SPIRIT_DEFINE(component_list_checked) BOOST_SPIRIT_DEFINE(components) BOOST_SPIRIT_DEFINE(config) auto const grammar = config; auto const component_grammar = component_config; auto const chain_grammar = chain_config; } namespace disposer{ template < typename Grammar > typename Grammar::attribute_type parse( std::istream& is, Grammar const& grammar ){ namespace x3 = boost::spirit::x3; std::string str{ std::istreambuf_iterator< char >{is}, std::istreambuf_iterator< char >{} }; typename Grammar::attribute_type config; auto iter = str.begin(); auto end = str.end(); x3::ascii::space_type space; try{ bool const match = phrase_parse(iter, end, grammar, space, config); if(!match || iter != end){ auto const line_number = parser::line_count(str.begin(), iter); auto const before = parser::get_error_line_before(str.begin(), iter); auto const after = parser::get_error_line_after(iter, end); std::ostringstream os; os << "Syntax error at line " << line_number << ", pos " << before.size() << ": '" << before << after << "', incomplete parsing (programming error!)"; throw std::runtime_error(os.str()); } return config; }catch(parser::syntax_error const& e){ auto const line_number = parser::line_count(str.begin(), e.pos()); auto const before = parser::get_error_line_before(str.begin(), e.pos()); auto const after = parser::get_error_line_after(e.pos(), end); std::ostringstream os; os << "Syntax error at line " << line_number << ", pos " << before.size() << ": '" << before << after << "', expected " << e.what(); throw std::runtime_error(os.str()); } } types::parse::config parse(std::istream& is){ return parse(is, parser::grammar); } types::parse::component parse_component(std::istream& is){ return parse(is, parser::component_grammar); } types::parse::chain parse_chain(std::istream& is){ return parse(is, parser::chain_grammar); } }
25.258929
79
0.700837
[ "vector" ]
9b618e1656f55289ac23ca113e36dca3e244da2c
4,239
cc
C++
net/ssl/ssl_config_service.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
net/ssl/ssl_config_service.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
net/ssl/ssl_config_service.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/ssl/ssl_config_service.h" #include <tuple> #include "base/lazy_instance.h" #include "base/synchronization/lock.h" #include "net/ssl/ssl_config_service_defaults.h" namespace net { namespace { // Checks if the config-service managed fields in two SSLConfigs are the same. bool SSLConfigsAreEqual(const net::SSLConfig& config1, const net::SSLConfig& config2) { return std::tie(config1.rev_checking_enabled, config1.rev_checking_required_local_anchors, config1.sha1_local_anchors_enabled, config1.symantec_enforcement_disabled, config1.version_min, config1.version_max, config1.tls13_variant, config1.disabled_cipher_suites, config1.channel_id_enabled, config1.false_start_enabled, config1.require_ecdhe) == std::tie(config2.rev_checking_enabled, config2.rev_checking_required_local_anchors, config2.sha1_local_anchors_enabled, config2.symantec_enforcement_disabled, config2.version_min, config2.version_max, config2.tls13_variant, config2.disabled_cipher_suites, config2.channel_id_enabled, config2.false_start_enabled, config2.require_ecdhe); } } // namespace SSLConfigService::SSLConfigService() : observer_list_(base::ObserverListPolicy::EXISTING_ONLY) {} // GlobalSSLObject holds a reference to a global SSL object, such as the // CRLSet. It simply wraps a lock around a scoped_refptr so that getting a // reference doesn't race with updating the global object. template <class T> class GlobalSSLObject { public: scoped_refptr<T> Get() const { base::AutoLock locked(lock_); return ssl_object_; } bool CompareAndSet(const scoped_refptr<T>& new_ssl_object, const scoped_refptr<T>& old_ssl_object) { base::AutoLock locked(lock_); if (ssl_object_ != old_ssl_object) return false; ssl_object_ = new_ssl_object; return true; } private: scoped_refptr<T> ssl_object_; mutable base::Lock lock_; }; typedef GlobalSSLObject<CRLSet> GlobalCRLSet; base::LazyInstance<GlobalCRLSet>::Leaky g_crl_set = LAZY_INSTANCE_INITIALIZER; // static void SSLConfigService::SetCRLSetIfNewer(scoped_refptr<CRLSet> crl_set) { SetCRLSet(std::move(crl_set), /*if_newer=*/true); } // static void SSLConfigService::SetCRLSetForTesting(scoped_refptr<CRLSet> crl_set) { SetCRLSet(std::move(crl_set), /*if_newer=*/false); } // static scoped_refptr<CRLSet> SSLConfigService::GetCRLSet() { return g_crl_set.Get().Get(); } void SSLConfigService::AddObserver(Observer* observer) { observer_list_.AddObserver(observer); } void SSLConfigService::RemoveObserver(Observer* observer) { observer_list_.RemoveObserver(observer); } void SSLConfigService::NotifySSLConfigChange() { for (auto& observer : observer_list_) observer.OnSSLConfigChanged(); } bool SSLConfigService::SSLConfigsAreEqualForTesting( const net::SSLConfig& config1, const net::SSLConfig& config2) { return SSLConfigsAreEqual(config1, config2); } SSLConfigService::~SSLConfigService() = default; void SSLConfigService::ProcessConfigUpdate(const SSLConfig& old_config, const SSLConfig& new_config) { // Do nothing if the configuration hasn't changed. if (!SSLConfigsAreEqual(old_config, new_config)) NotifySSLConfigChange(); } // static void SSLConfigService::SetCRLSet(scoped_refptr<CRLSet> crl_set, bool if_newer) { // Note: this can be called concurently with GetCRLSet(). while (true) { scoped_refptr<CRLSet> old_crl_set(GetCRLSet()); if (if_newer && old_crl_set && crl_set && old_crl_set->sequence() >= crl_set->sequence()) { LOG(WARNING) << "Refusing to downgrade CRL set from #" << old_crl_set->sequence() << " to #" << crl_set->sequence(); break; } if (g_crl_set.Get().CompareAndSet(crl_set, old_crl_set)) break; } } } // namespace net
32.607692
80
0.704883
[ "object" ]
9b6480721e8901e4db2d86b1136f87194e49e722
6,751
hpp
C++
Code/Source/StringAlg.hpp
christinazavou/Thea
f68293c4a4f5ddc3abda18e2e0b679bcf5163e93
[ "BSD-3-Clause" ]
77
2016-11-06T17:25:54.000Z
2022-03-29T16:30:34.000Z
Code/Source/StringAlg.hpp
christinazavou/Thea
f68293c4a4f5ddc3abda18e2e0b679bcf5163e93
[ "BSD-3-Clause" ]
1
2017-04-22T16:47:04.000Z
2017-04-22T16:47:04.000Z
Code/Source/StringAlg.hpp
christinazavou/Thea
f68293c4a4f5ddc3abda18e2e0b679bcf5163e93
[ "BSD-3-Clause" ]
20
2015-10-17T20:38:50.000Z
2022-02-18T09:56:27.000Z
//============================================================================ // // This file is part of the Thea toolkit. // // This software is distributed under the BSD license, as detailed in the // accompanying LICENSE.txt file. Portions are derived from other works: // their respective licenses and copyright information are reproduced in // LICENSE.txt and/or in the relevant source files. // // Author: Siddhartha Chaudhuri // First version: 2013 // //============================================================================ /* ORIGINAL HEADER @file stringutils.h @maintainer Morgan McGuire, http://graphics.cs.williams.edu @author 2000-09-09 @edited 2010-03-05 */ #ifndef __Thea_StringAlg_hpp_ #define __Thea_StringAlg_hpp_ #include "Common.hpp" #include "BasicStringAlg.hpp" #include "Array.hpp" #include <cctype> #include <sstream> #include <type_traits> #ifdef THEA_WINDOWS # ifndef FNM_NOMATCH # define FNM_NOMATCH 1 /* Match failed. */ # define FNM_NOESCAPE 0x01 /* Disable backslash escaping. */ # define FNM_PATHNAME 0x02 /* Slash must be matched by slash. */ # define FNM_PERIOD 0x04 /* Period must be matched by period. */ # define FNM_LEADING_DIR 0x08 /* Ignore /<tail> after Imatch. */ # define FNM_CASEFOLD 0x10 /* Case insensitive search. */ # endif #else // On non-windows systems, include fnmatch directly. Both GNU/Linux and OS X support all the flags above. # include <fnmatch.h> #endif namespace Thea { /** * Convert a string to a scalar number. The string must contain the number and nothing else except leading/trailing whitespace. */ template <typename T, typename std::enable_if< std::is_arithmetic<T>::value, T >::type * = nullptr> T fromString(std::string const & str) { size_t idx = 0; T x = std::is_integral<T>::value ? (std::is_signed<T>::value ? static_cast<T>(std::stoll(str, &idx)) : static_cast<T>(std::stoull(str, &idx))) : static_cast<T>(std::stold(str, &idx)); // Check that the rest of the string is only whitespace for (size_t i = idx; i < str.size(); ++i) if (!std::isspace(str[i])) throw Error("Could not convert string '" + str + "' to scalar"); return x; } /** * Separates a comma-separated line, properly escaping commas within double quotes (") and super quotes ("""). This matches * Microsoft Excel's CSV output. * * @param s The string to parse. * @param array The comma-separated fields are stored here. * @param strip_quotes If true, strips leading and trailing " and """. * * @see stringSplit, TextInput */ THEA_API void parseCommaSeparated(std::string const & s, Array<std::string> & array, bool strip_quotes = true); /** * Split a string at each occurrence of a splitting character. * * @param s The string to split. * @param split_char The delimiting character. * @param result Used to return the sequence of fields found. * @param skip_empty_fields If true, a sequence of delimiters is treated as a single delimiter. * * @return The number of fields found. */ THEA_API intx stringSplit(std::string const & s, char split_char, Array<std::string> & result, bool skip_empty_fields = false); /** * Split a string at each occurrence of any splitting character from a provided set. * * @param s The string to split. * @param split_chars The set of delimiting characters. E.g. to split a string on whitespace, use * <tt>split_chars = " \t\n\f\r"</tt>. * @param result Used to return the sequence of fields found. * @param skip_empty_fields If true, a sequence of delimiters is treated as a single delimiter. * * @return The number of fields found. */ THEA_API intx stringSplit(std::string const & s, std::string const & split_chars, Array<std::string> & result, bool skip_empty_fields = false); /** * Concatenate a sequence of serializable objects (typically strings), separated by a padding character, string or other * serializable object. */ template <typename IteratorT, typename C> std::string stringJoin(IteratorT begin, IteratorT end, C const & padding) { std::ostringstream out; for (IteratorT iter = begin; iter != end; ++iter) { if (iter != begin) out << padding; out << *iter; } return out.str(); } /** * Concatenate a sequence of serializable objects (typically strings), separated by a padding character, string or other * serializable object. This is shorthand for stringJoin(a.begin(), a.end(), padding). */ template <typename ContainerT, typename C> std::string stringJoin(ContainerT const & a, C const & padding) { return stringJoin(a.begin(), a.end(), padding); } /** Pattern matching flags (enum class). Correspond to flags for POSIX fnmatch. */ struct THEA_API Match { /** Supported values. */ enum Value { /** Treat backslash as an ordinary character, instead of an escape character. */ NOESCAPE = FNM_NOESCAPE, /** * Match a slash in the query only with a slash in the pattern and not by an asterisk (*) or a question mark (?) * metacharacter, nor by a bracket expression ([]) containing a slash. */ PATHNAME = FNM_PATHNAME, /** * A leading period in the query has to be matched exactly by a period in the pattern. A period is considered to be leading * if it is the first character in \a query, or if both FNM_PATHNAME is set and the period immediately follows a slash. */ PERIOD = FNM_PERIOD, /** * If this flag (a GNU extension) is set, the pattern is considered to be matched if it matches an initial segment of the * query which is followed by a slash. This flag is mainly for the internal use of glibc and is only implemented in certain * cases. */ LEADING_DIR = FNM_LEADING_DIR, /** If this flag (a GNU extension) is set, the pattern is matched case-insensitively. */ CASEFOLD = FNM_CASEFOLD }; THEA_ENUM_CLASS_BODY(Match) }; // struct Match /** * Compares a filename or pathname to a pattern. Equivalent (except for boolean instead of integer return value) to function * fnmatch() as specified in POSIX 1003.2-1992, section B.6. * * The function checks whether the \a query argument matches the \a pattern argument, which is a shell wildcard pattern. The * \a flags argument modifies the behaviour; it is the bitwise OR of zero or more Match flags. * * @return True if \a query matches \a pattern, false otherwise. Throws an error if the pattern is malformed. */ THEA_API bool patternMatch(std::string const & pattern, std::string const & query, int flags = 0); } // namespace Thea #endif
35.719577
127
0.668345
[ "object" ]
f92d69b034e0ead6b3b47bf0474a9750b6081964
8,812
cpp
C++
src/sglib/mappers/LongReadMapper.cpp
BenJWard/sg
397924c8346981a6d4726c9cac7bc9c1b623c6fb
[ "MIT" ]
null
null
null
src/sglib/mappers/LongReadMapper.cpp
BenJWard/sg
397924c8346981a6d4726c9cac7bc9c1b623c6fb
[ "MIT" ]
null
null
null
src/sglib/mappers/LongReadMapper.cpp
BenJWard/sg
397924c8346981a6d4726c9cac7bc9c1b623c6fb
[ "MIT" ]
null
null
null
// // Created by Luis Yanes (EI) on 22/03/2018. // #include <sglib/mappers/LongReadMapper.hpp> #include <sglib/utilities/omp_safe.hpp> void LongReadMapper::map_reads(std::unordered_set<uint32_t> readIDs) { std::vector<std::vector<LongReadMapping>> thread_mappings(omp_get_max_threads()); #pragma omp parallel { ASMKMerFactory skf(17); std::vector<kmerPos > read_kmers; #pragma omp for for (uint32_t readID = 1; readID < datastore.size(); ++readID) { if (!((readIDs.size()>0 and readIDs.count(readID)>0) or (readIDs.empty() and read_to_mappings[readID].empty()))) continue; std::string read_seq(datastore.get_read_sequence(readID)); std::string read_name(std::to_string(readID)); int read_len(static_cast<int>(read_seq.length())); int window_size = 500; int window_slide = window_size/4; std::cout << "Processing Read ID " << readID << " " << read_seq.size() << std::endl; std::map<uint32_t , uint32_t > node_score; //===== Create a vector of nodes for every k-mer in the read. read_kmers.clear(); skf.create_kmers(read_seq, 0, read_kmers); //XXX: Ns will produce "deletion-windows" std::cout<<"creating the vector of vectors of node matches... SLOOOOOOW"<<std::endl; std::vector<std::vector<uint32_t>> node_matches(read_kmers.size()); for (auto i=0;i<read_kmers.size();++i){ auto first = std::lower_bound(assembly_kmers.begin(), assembly_kmers.end(), read_kmers[i].kmer); for (auto it = first; it != assembly_kmers.end() && it->kmer == read_kmers[i].kmer; ++it) { node_matches[i].emplace_back(it->contigID); ++node_score[it->contigID]; } } std::cout<<"DONE!"<<std::endl; //===== Rank nodes by how many kmer-hits they have on the read, choose the top N std::cout<<"Ranking nodes"<<std::endl; std::vector<std::pair<uint32_t , uint32_t>> score_node; for (auto &ns:node_score){ score_node.emplace_back(ns.second,ns.first); } std::sort(score_node.rbegin(),score_node.rend()); if (score_node.size()>100) score_node.resize(100); std::cout<<"DONE"<<std::endl; //===== For every window (sliding by win_size/2) save total of kmers in every node of the top N std::cout<<"Collecting votes for the winner nodes"<<std::endl; std::ofstream readout("read" + std::to_string(readID/2) + ".csv"); readout<<"window#"; for (auto n:score_node) readout<<",ctg"<<n.second; readout<<std::endl; //auto num_windows((read_kmers.size()-window_size)/overlap + 1); for (int w_i = 0; w_i * window_slide + window_size < read_kmers.size(); ++w_i) { std::map<uint32_t,uint32_t> win_node_score; auto win_start(w_i * window_slide); auto win_end(w_i * window_slide + window_size); for (int wp_i = win_start; wp_i < win_end and wp_i < read_kmers.size(); wp_i++) { for (auto matchnode:node_matches[wp_i]) ++win_node_score[matchnode]; } std::cout << "Window " << w_i+1 << " " << win_start << " to " << win_end << std::endl; readout<<w_i; for (auto n:score_node) readout<<","<<win_node_score[n.second]; readout<<std::endl; } std::cout<<"DONE"<<std::endl; // if (n_regs0<=1) { // for (int j = 0; j < n_regs0; j++) { // auto node = regs0[j].rid + 1; // LongReadMapping mapping = createMapping(readID, regs0, j, node); // thread_mappings[omp_get_thread_num()].emplace_back(mapping); // } // } // if (n_regs0 > 1) { // for (int j = 0; j < n_regs0 - 1; ++j) { // auto fromNode = regs0[j].rid+1; // auto toNode = regs0[j+1].rid+1; // LongReadMapping fromMapping = createMapping(readID, regs0, j, fromNode); // LongReadMapping toMapping = createMapping(readID, regs0, j+1, toNode); // // if (link_is_valid(fromMapping, toMapping)) { // thread_mappings[omp_get_thread_num()].emplace_back(fromMapping); // thread_mappings[omp_get_thread_num()].emplace_back(toMapping); // } // } // } // for (int i = 0; i<n_regs0;i++) free(regs0[i].p); // free(regs0); } // mm_tbuf_destroy(buf); } for (int thread = 0; thread<omp_get_max_threads(); thread++) { mappings.reserve(thread_mappings.size()); for (const auto &mapping : thread_mappings[thread]) { mappings.emplace_back(mapping); } } update_indexes_from_mappings(); } void LongReadMapper::update_indexes_from_mappings() { for (std::vector<LongReadMapping>::const_iterator mappingItr = mappings.cbegin(); mappingItr != mappings.cend(); ++mappingItr) { auto index = (unsigned long)std::distance(mappings.cbegin(), mappingItr); read_to_mappings[mappingItr->read_id].push_back(index); mappings_in_node[std::abs(mappingItr->node)].push_back(index); } } LongReadMapper::LongReadMapper(SequenceGraph &sg, LongReadsDatastore &ds, uint8_t k) : sg(sg), k(k), datastore(ds) { mappings_in_node.resize(sg.nodes.size()); read_to_mappings.resize(datastore.size()); } void LongReadMapper::update_graph_index() { assembly_kmers.reserve(110000000); ASMKMerFactory skf(17); std::vector<kmerPos > contig_kmers; for (sgNodeID_t n = 1; n < sg.nodes.size(); ++n) { if (sg.nodes[n].sequence.size() >= k) { contig_kmers.clear(); skf.create_kmers(sg.nodes[n].sequence, n, contig_kmers); for (const auto &kmer:contig_kmers) { assembly_kmers.emplace_back(kmer.kmer, kmer.contigID, kmer.offset); } } } std::sort(assembly_kmers.begin(),assembly_kmers.end(), kmerPos::byKmerContigOffset()); } LongReadMapper::~LongReadMapper() {} void LongReadMapper::read(std::string filename) { // Read the mappings from file sglib::OutputLog() << "Reading long read mappings" << std::endl; std::ifstream inf(filename, std::ios_base::binary); auto mapSize(mappings.size()); inf.read(reinterpret_cast<char *>(&k), sizeof(k)); inf.read(reinterpret_cast<char *>(&mapSize), sizeof(mapSize)); mappings.reserve(mapSize); inf.read(reinterpret_cast<char*>(mappings.data()), mappings.size()*sizeof(LongReadMapping)); sglib::OutputLog() << "Updating read mapping indexes!" << std::endl; update_indexes_from_mappings(); sglib::OutputLog() << "Done!" << std::endl; } void LongReadMapper::read(std::ifstream &inf) { auto mapSize(mappings.size()); inf.read(reinterpret_cast<char *>(&k), sizeof(k)); inf.read(reinterpret_cast<char *>(&mapSize), sizeof(mapSize)); mappings.resize(mapSize); inf.read(reinterpret_cast<char*>(mappings.data()), mappings.size()*sizeof(LongReadMapping)); sglib::OutputLog() << "Updating read mapping indexes!" << std::endl; update_indexes_from_mappings(); sglib::OutputLog() << "Done!" << std::endl; } void LongReadMapper::write(std::string filename) { // Write mappings to file sglib::OutputLog() << "Dumping long read mappings" << std::endl; std::ofstream outf(filename, std::ios_base::binary); auto mapSize(mappings.size()); outf.write(reinterpret_cast<const char *>(&k), sizeof(k)); outf.write(reinterpret_cast<const char *>(&mapSize), sizeof(mapSize)); outf.write(reinterpret_cast<const char*>(mappings.data()), mappings.size()*sizeof(LongReadMapping)); sglib::OutputLog() << "Done!" << std::endl; } void LongReadMapper::write(std::ofstream &ofs) { auto mapSize(mappings.size()); ofs.write(reinterpret_cast<char *>(&k), sizeof(k)); ofs.write(reinterpret_cast<char *>(&mapSize), sizeof(mapSize)); mappings.reserve(mapSize); ofs.write(reinterpret_cast<char*>(mappings.data()), mappings.size()*sizeof(LongReadMapping)); sglib::OutputLog() << "Done!" << std::endl; } LongReadMapper LongReadMapper::operator=(const LongReadMapper &other) { if (&sg != &other.sg and &datastore != &other.datastore) { throw ("Can only copy paths from the same SequenceGraph"); } if (&other == this) { return *this; } mappings = other.mappings; update_indexes_from_mappings(); return *this; }
42.776699
132
0.597821
[ "vector" ]
f92da1aa388b6d098ed1e46ba29411e676dcd4e7
13,493
cpp
C++
core/src/main/cpp/tokens/UserIdToken.cpp
sghill/msl
97f53d685389bab496df889d87ccdbd1e9728032
[ "Apache-2.0" ]
559
2015-01-01T14:47:49.000Z
2022-03-05T02:33:53.000Z
core/src/main/cpp/tokens/UserIdToken.cpp
sghill/msl
97f53d685389bab496df889d87ccdbd1e9728032
[ "Apache-2.0" ]
141
2015-01-06T18:43:22.000Z
2020-09-27T02:21:21.000Z
core/src/main/cpp/tokens/UserIdToken.cpp
sghill/msl
97f53d685389bab496df889d87ccdbd1e9728032
[ "Apache-2.0" ]
85
2015-03-04T19:10:35.000Z
2022-02-15T10:34:40.000Z
/** * Copyright (c) 2016-2017 Netflix, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <crypto/ICryptoContext.h> #include <tokens/UserIdToken.h> #include <Date.h> #include <io/MslEncoderFactory.h> #include <io/MslEncoderFormat.h> #include <MslInternalException.h> #include <MslConstants.h> #include <MslCryptoException.h> #include <MslEncodingException.h> #include <MslError.h> #include <MslException.h> #include <tokens/MasterToken.h> #include <tokens/MslUser.h> #include <tokens/TokenFactory.h> #include <util/MslContext.h> #include <util/MslUtils.h> #include <sstream> using namespace std; using namespace netflix::msl::crypto; using namespace netflix::msl::io; using namespace netflix::msl::util; namespace netflix { namespace msl { namespace tokens { namespace { /** Milliseconds per second. */ const int64_t MILLISECONDS_PER_SECOND = 1000; /** Key token data. */ const string KEY_TOKENDATA = "tokendata"; /** Key signature. */ const string KEY_SIGNATURE = "signature"; // tokendata /** Key renewal window timestamp. */ const string KEY_RENEWAL_WINDOW = "renewalwindow"; /** Key expiration_ timestamp. */ const string KEY_EXPIRATION = "expiration"; /** Key master token serial number. */ const string KEY_MASTER_TOKEN_SERIAL_NUMBER = "mtserialnumber"; /** Key user ID token serial number. */ const string KEY_SERIAL_NUMBER = "serialnumber"; /** Key token user data. */ const string KEY_USERDATA = "userdata"; // userdata_ /** Key issuer data. */ const string KEY_ISSUER_DATA = "issuerdata"; /** Key identity. */ const string KEY_IDENTITY = "identity"; } // namespace anonymous UserIdToken::UserIdToken(shared_ptr<MslContext> ctx, shared_ptr<Date> renewalWindow, shared_ptr<Date> expiration, shared_ptr<MasterToken> masterToken, int64_t serialNumber, shared_ptr<MslObject> issuerData, shared_ptr<MslUser> user) : ctx_(ctx) , renewalWindow_(renewalWindow->getTime() / MILLISECONDS_PER_SECOND) , expiration_(expiration->getTime() / MILLISECONDS_PER_SECOND) , mtSerialNumber_(masterToken ? masterToken->getSerialNumber() : -1) , serialNumber_(serialNumber) , issuerdata_(issuerData) , user_(user) , verified_(true) { assert(ctx_); assert(user_); // The expiration_ must appear after the renewal window. if (expiration->before(renewalWindow)) throw MslInternalException("Cannot construct a user ID token that expires before its renewal window opens."); // A master token must be provided. if (!masterToken) throw MslInternalException("Cannot construct a user ID token without a master token."); // The serial number must be within range. if (serialNumber_ < 0 || serialNumber_ > MslConstants::MAX_LONG_VALUE) { stringstream ss; ss << "Serial number " << serialNumber_ << " is outside the valid range."; throw MslInternalException(ss.str()); } // Construct the user data. shared_ptr<MslEncoderFactory> encoder = ctx_->getMslEncoderFactory(); userdata_ = encoder->createObject(); if (issuerdata_) userdata_->put(KEY_ISSUER_DATA, issuerdata_); userdata_->put(KEY_IDENTITY, user_->getEncoded()); } UserIdToken::UserIdToken(shared_ptr<MslContext> ctx, shared_ptr<MslObject> userIdTokenMo, shared_ptr<MasterToken> masterToken) : ctx_(ctx) , renewalWindow_(0ll) , expiration_(0ll) , mtSerialNumber_(masterToken ? masterToken->getSerialNumber() : -1) , serialNumber_(-1) , verified_(false) { assert(ctx_); // Grab the crypto context and encoder-> shared_ptr<crypto::ICryptoContext> cryptoContext = ctx_->getMslCryptoContext(); shared_ptr<io::MslEncoderFactory> encoder = ctx_->getMslEncoderFactory(); if (!userIdTokenMo) throw MslEncodingException(MslError::MSL_PARSE_ERROR, "null useridtoken").setMasterToken(masterToken); // Verify the encoding. try { tokendataBytes_ = userIdTokenMo->getBytes(KEY_TOKENDATA); if (tokendataBytes_->empty()) { stringstream ss; ss << "useridtoken " << userIdTokenMo; throw MslEncodingException(MslError::USERIDTOKEN_TOKENDATA_MISSING, ss.str()).setMasterToken(masterToken); } signatureBytes_ = userIdTokenMo->getBytes(KEY_SIGNATURE); verified_ = cryptoContext->verify(tokendataBytes_, signatureBytes_, encoder); } catch (const MslEncoderException& e) { throw MslEncodingException(MslError::MSL_PARSE_ERROR, "useridtoken " + userIdTokenMo->toString(), e).setMasterToken(masterToken); } // Pull the token data. shared_ptr<ByteArray> plaintext; try { shared_ptr<MslObject> tokendata = encoder->parseObject(tokendataBytes_); renewalWindow_ = tokendata->getLong(KEY_RENEWAL_WINDOW); expiration_ = tokendata->getLong(KEY_EXPIRATION); if (expiration_ < renewalWindow_) throw MslException(MslError::USERIDTOKEN_EXPIRES_BEFORE_RENEWAL, "usertokendata " + tokendata->toString()).setMasterToken(masterToken); mtSerialNumber_ = tokendata->getLong(KEY_MASTER_TOKEN_SERIAL_NUMBER); if (mtSerialNumber_ < 0 || mtSerialNumber_ > MslConstants::MAX_LONG_VALUE) throw MslException(MslError::USERIDTOKEN_MASTERTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "usertokendata " + tokendata->toString()).setMasterToken(masterToken); serialNumber_ = tokendata->getLong(KEY_SERIAL_NUMBER); if (serialNumber_ < 0 || serialNumber_ > MslConstants::MAX_LONG_VALUE) throw MslException(MslError::USERIDTOKEN_SERIAL_NUMBER_OUT_OF_RANGE, "usertokendata " + tokendata->toString()).setMasterToken(masterToken); shared_ptr<ByteArray> ciphertext = tokendata->getBytes(KEY_USERDATA); if (ciphertext->empty()) throw MslException(MslError::USERIDTOKEN_USERDATA_MISSING).setMasterToken(masterToken); if (verified_) { plaintext = cryptoContext->decrypt(ciphertext, encoder); } } catch (const MslEncoderException& e) { throw MslEncodingException(MslError::USERIDTOKEN_TOKENDATA_PARSE_ERROR, "usertokendata " + *Base64::encode(tokendataBytes_), e).setMasterToken(masterToken); } catch (const MslCryptoException& e) { throw MslCryptoException(e).setMasterToken(masterToken); } // Pull the user data. if (plaintext) { try { userdata_ = encoder->parseObject(plaintext); if (userdata_->has(KEY_ISSUER_DATA)) issuerdata_ = userdata_->getMslObject(KEY_ISSUER_DATA, encoder); const string identity = userdata_->getString(KEY_IDENTITY); if (identity.empty()) throw MslException(MslError::USERIDTOKEN_IDENTITY_INVALID, "userdata_ " + userdata_->toString()).setMasterToken(masterToken); shared_ptr<TokenFactory> factory = ctx->getTokenFactory(); user_ = factory->createUser(ctx_, identity); if (!user_) throw MslInternalException("TokenFactory.createUser() returned null in violation of the interface contract."); } catch (const MslEncoderException& e) { throw MslEncodingException(MslError::USERIDTOKEN_USERDATA_PARSE_ERROR, "userdata_ " + *Base64::encode(plaintext), e).setMasterToken(masterToken); } } // Verify serial numbers. if (!masterToken || (mtSerialNumber_ != masterToken->getSerialNumber())) { stringstream ss; ss << "uit mtserialnumber " << mtSerialNumber_ << "; mt " << masterToken; throw MslException(MslError::USERIDTOKEN_MASTERTOKEN_MISMATCH, ss.str()).setMasterToken(masterToken); } } shared_ptr<Date> UserIdToken::getRenewalWindow() const { return make_shared<Date>(renewalWindow_ * MILLISECONDS_PER_SECOND); } bool UserIdToken::isRenewable(shared_ptr<Date> now) const { if (now) return renewalWindow_ * MILLISECONDS_PER_SECOND <= now->getTime(); if (isVerified()) return renewalWindow_ * MILLISECONDS_PER_SECOND <= ctx_->getTime(); return true; } shared_ptr<Date> UserIdToken::getExpiration() const { return make_shared<Date>(expiration_ * MILLISECONDS_PER_SECOND); } bool UserIdToken::isExpired(shared_ptr<Date> now) const { if (now) return expiration_ * MILLISECONDS_PER_SECOND <= now->getTime(); if (isVerified()) return expiration_ * MILLISECONDS_PER_SECOND <= ctx_->getTime(); return false; } bool UserIdToken::isBoundTo(shared_ptr<MasterToken> masterToken) { return masterToken && masterToken->getSerialNumber() == mtSerialNumber_; } shared_ptr<ByteArray> UserIdToken::toMslEncoding(std::shared_ptr<io::MslEncoderFactory> encoder, const io::MslEncoderFormat& format) const { // Return any cached encoding. const map<MslEncoderFormat, shared_ptr<ByteArray>>::const_iterator it = encodings_.find(format); if (it != encodings_.end()) return it->second; // If we parsed this token (i.e. did not create it from scratch) then // we should not re-encrypt or re-sign as there is no guarantee out MSL // crypto context is capable of encrypting and signing with the same // keys, even if it is capable of decrypting and verifying. shared_ptr<ByteArray> data, signature; if (tokendataBytes_ || signatureBytes_) { data = tokendataBytes_; signature = signatureBytes_; } // // Otherwise create the token data and signature. else { // Grab the MSL token crypto context. shared_ptr<ICryptoContext> cryptoContext; try { cryptoContext = ctx_->getMslCryptoContext(); } catch (const MslCryptoException& e) { throw MslEncoderException("Error creating the MSL crypto context.", e); } // Encrypt the user data. shared_ptr<ByteArray> plaintext = encoder->encodeObject(userdata_, format); shared_ptr<ByteArray> ciphertext; try { ciphertext = cryptoContext->encrypt(plaintext, encoder, format); } catch (const MslCryptoException& e) { throw MslEncoderException("Error encrypting the user data.", e); } // Construct the token data. shared_ptr<MslObject> tokendata = encoder->createObject(); tokendata->put(KEY_RENEWAL_WINDOW, renewalWindow_); tokendata->put(KEY_EXPIRATION, expiration_); tokendata->put(KEY_MASTER_TOKEN_SERIAL_NUMBER, mtSerialNumber_); tokendata->put(KEY_SERIAL_NUMBER, serialNumber_); tokendata->put(KEY_USERDATA, ciphertext); // Sign the token data. data = encoder->encodeObject(tokendata, format); try { signature = cryptoContext->sign(data, encoder, format); } catch (const MslCryptoException& e) { throw MslEncoderException("Error signing the token data.", e); } } // Encode the token. shared_ptr<MslObject> token = encoder->createObject(); token->put(KEY_TOKENDATA, data); token->put(KEY_SIGNATURE, signature); shared_ptr<ByteArray> encoding = encoder->encodeObject(token, format); // Cache and return the encoding. encodings_.insert(make_pair(format, encoding)); return encoding; } string UserIdToken::toString() const { shared_ptr<MslEncoderFactory> encoder = ctx_->getMslEncoderFactory(); shared_ptr<MslObject> userdataMo = encoder->createObject(); if (isDecrypted()) { if (issuerdata_) userdataMo->put(KEY_ISSUER_DATA, issuerdata_); userdataMo->put<string>(KEY_IDENTITY, user_->getEncoded()); // java version just uses default Object.toString here } shared_ptr<MslObject> tokendataMo = encoder->createObject(); tokendataMo->put(KEY_RENEWAL_WINDOW, renewalWindow_); tokendataMo->put(KEY_EXPIRATION, expiration_); tokendataMo->put(KEY_MASTER_TOKEN_SERIAL_NUMBER, mtSerialNumber_); tokendataMo->put(KEY_SERIAL_NUMBER, serialNumber_); tokendataMo->put(KEY_USERDATA, userdataMo); MslObject mslObj; mslObj.put(KEY_TOKENDATA, tokendataMo); mslObj.put<string>(KEY_SIGNATURE, ""); return mslObj.toString(); } string UserIdToken::uniqueKey() const { stringstream ss; ss << serialNumber_ << ":" << mtSerialNumber_; return ss.str(); } /** * @param obj the reference object with which to compare. * @return true if the other object is a user ID token with the same serial * number bound to the same master token. * @see java.lang.Object#equals(java.lang.Object) */ bool UserIdToken::equals(shared_ptr<const UserIdToken> other) const { if (!other) return false; if (this == other.get()) return true; return serialNumber_ == other->serialNumber_ && mtSerialNumber_ == other->mtSerialNumber_; } bool operator==(const UserIdToken& a, const UserIdToken& b) { shared_ptr<const UserIdToken> ap(&a, &MslUtils::nullDeleter<UserIdToken>); shared_ptr<const UserIdToken> bp(&b, &MslUtils::nullDeleter<UserIdToken>); return ap->equals(bp); } }}} // namespace netflix::msl::tokens
39.110145
164
0.704291
[ "object" ]
f930cda75f98bf80a4519e6d143b1c21e5d4b404
3,172
cxx
C++
csankey/_csankey.cxx
kirin123kirin/csankey
64ed153391a1122a3194e4febcb2947c2b847deb
[ "MIT" ]
null
null
null
csankey/_csankey.cxx
kirin123kirin/csankey
64ed153391a1122a3194e4febcb2947c2b847deb
[ "MIT" ]
null
null
null
csankey/_csankey.cxx
kirin123kirin/csankey
64ed153391a1122a3194e4febcb2947c2b847deb
[ "MIT" ]
null
null
null
/* csankey.cpp | MIT License | https://github.com/kirin123kirin/csankey/raw/main/LICENSE */ #include "csankey.hpp" extern "C" PyObject* to_sankeyhtml_py(PyObject* self, PyObject* args, PyObject* kwargs) { PyObject* o, *res; int header = -1; const char* kwlist[3] = {"o", "header", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i", (char**)kwlist, &o, &header)) return NULL; if(!PyList_Check(o) && !PyTuple_Check(o)) return PyErr_Format(PyExc_TypeError, "argument is list or tuple object only."); SankeyData<wchar_t, PyObject*> snk(o); bool r; if(header == -1) r = snk.parse(); else r = snk.parse((bool)header); if (r && (res = snk.to_html()) != NULL) return res; return PyErr_Format(PyExc_ValueError, "Unknown Error Occured."); } extern "C" PyObject* to_sankeyjson_py(PyObject* self, PyObject* args, PyObject* kwargs) { PyObject* o; std::wstring jsondata; int header = -1; const char* kwlist[3] = {"o", "header", NULL}; if(!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i", (char**)kwlist, &o, &header)) return NULL; if(!PyList_Check(o) && !PyTuple_Check(o)) return PyErr_Format(PyExc_TypeError, "argument is list or tuple object only."); SankeyData<wchar_t, PyObject*> snk(o); bool r; if(header == -1) r = snk.parse(); else r = snk.parse((bool)header); if (r && !(jsondata = snk.to_json()).empty()) return PyUnicode_FromWideChar(jsondata.data(), (Py_ssize_t)jsondata.size()); return PyErr_Format(PyExc_ValueError, "Unknown Error Occured."); } #define MODULE_NAME _csankey #define MODULE_NAME_S "_csankey" /* {{{ */ // this module description #define MODULE_DOCS \ "Make html data of Sankey Diagram.\n" \ "Sankey diagram made using d3.js and the sankey plugin.\n" \ "" #define to_sankeyhtml_py_DESC "\n" #define to_sankeyjson_py_DESC "\n" /* }}} */ #define PY_ADD_METHOD(py_func, c_func, desc) \ { py_func, (PyCFunction)c_func, METH_VARARGS, desc } #define PY_ADD_METHOD_KWARGS(py_func, c_func, desc) \ { py_func, (PyCFunction)c_func, METH_VARARGS | METH_KEYWORDS, desc } /* Please extern method define for python */ /* PyMethodDef Parameter Help * https://docs.python.org/ja/3/c-api/structures.html#c.PyMethodDef */ static PyMethodDef py_methods[] = {PY_ADD_METHOD_KWARGS("to_sankeyhtml", to_sankeyhtml_py, to_sankeyhtml_py_DESC), PY_ADD_METHOD_KWARGS("to_sankeyjson", to_sankeyjson_py, to_sankeyjson_py_DESC), {NULL, NULL, 0, NULL}}; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef py_defmod = {PyModuleDef_HEAD_INIT, MODULE_NAME_S, MODULE_DOCS, 0, py_methods}; #define PARSE_NAME(mn) PyInit_##mn #define PARSE_FUNC(mn) \ PyMODINIT_FUNC PARSE_NAME(mn)() { return PyModule_Create(&py_defmod); } #else #define PARSE_NAME(mn) \ init##mn(void) { (void)Py_InitModule3(MODULE_NAME_S, py_methods, MODULE_DOCS); } #define PARSE_FUNC(mn) PyMODINIT_FUNC PARSE_NAME(mn) #endif PARSE_FUNC(MODULE_NAME);
33.389474
114
0.653216
[ "object" ]
f93b06139562d358f73db3d18f51f6c383d07090
6,582
cpp
C++
StarChicken/src/scene/SceneRenderer.cpp
Drillgon200/StarChicken
8a3932f3d0092a9a9e0fdc65e58e63d1021f5229
[ "Unlicense" ]
2
2021-12-13T09:43:32.000Z
2022-03-02T04:16:34.000Z
StarChicken/src/scene/SceneRenderer.cpp
Drillgon200/StarChicken
8a3932f3d0092a9a9e0fdc65e58e63d1021f5229
[ "Unlicense" ]
null
null
null
StarChicken/src/scene/SceneRenderer.cpp
Drillgon200/StarChicken
8a3932f3d0092a9a9e0fdc65e58e63d1021f5229
[ "Unlicense" ]
null
null
null
#include "SceneRenderer.h" #include "Scene.h" #include "..\graphics\Framebuffer.h" #include "..\resources\DefaultResources.h" #include "..\graphics\RenderPass.h" namespace scene { SceneRenderer::SceneRenderer(Scene* scene) : scene{ scene } { } void SceneRenderer::prepare_render_world(vku::RenderPass& renderPass) { VkCommandBuffer cmdBuf = vku::graphics_cmd_buf(); geometryManager.begin_frame(cmdBuf, scene->cameras); for (Camera* cam : scene->cameras) { for (geom::Model* model : scene->sceneModels) { //TODO replace with real scene traversal with CPU culling and stuff cam->add_render_model(*model); } } geometryManager.update_cam_sets(cmdBuf, scene->cameras); geometryManager.send_data(cmdBuf, scene->cameras); geometryManager.cull_depth_prepass(cmdBuf, scene->cameras, renderPass, *depthFramebuffer); vku::memory_barrier(cmdBuf, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); generate_depth_pyramid(cmdBuf); geometryManager.cull(cmdBuf, scene->cameras); vku::image_barrier(cmdBuf, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_ALL_GRAPHICS_BIT, VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_MEMORY_WRITE_BIT, depthFramebuffer->get_depth_texture()->get_image(), VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); renderPass.begin_pass(cmdBuf, *depthFramebuffer); for (Camera* cam : scene->cameras) { vkCmdSetViewport(cmdBuf, 0, 1, &cam->viewport); geometryManager.draw(cmdBuf, *scene->cameras[0], vku::WORLD_RENDER_PASS_DEPTH, cam->cameraIndex); } renderPass.end_pass(cmdBuf); vku::memory_barrier(cmdBuf, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT); //generate_depth_pyramid(cmdBuf); } void SceneRenderer::render_world(Camera& cam, vku::WorldRenderPass pass) { VkCommandBuffer cmdBuf = vku::graphics_cmd_buf(); vkCmdSetViewport(cmdBuf, 0, 1, &cam.viewport); geometryManager.draw(cmdBuf, *scene->cameras[0], pass, cam.cameraIndex); } void SceneRenderer::generate_depth_pyramid(VkCommandBuffer cmdBuf) { vku::image_barrier(cmdBuf, VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, depthFramebuffer->get_depth_texture()->get_image(), VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); depthPyramidDownsample->bind(cmdBuf); int32_t imageDimension[3]{ vku::swapChainExtent.width, vku::swapChainExtent.height, 1 }; for (uint32_t i = 0; i < depthPyramidLevels; i++) { imageDimension[0] = std::max(1, imageDimension[0] / 2); imageDimension[1] = std::max(1, imageDimension[1] / 2); depthPyramidDownsampleSets[i]->bind(cmdBuf, *depthPyramidDownsample, 0); vkCmdPushConstants(cmdBuf, depthPyramidDownsample->get_layout(), VK_SHADER_STAGE_COMPUTE_BIT, 0, 3 * sizeof(uint32_t), imageDimension); imageDimension[2] = 0; vkCmdDispatch(cmdBuf, (imageDimension[0] + 15) / 16, (imageDimension[1] + 15) / 16, 1); vku::image_barrier(cmdBuf, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT, depthPyramid->get_image(), VK_IMAGE_ASPECT_COLOR_BIT, 0, depthPyramid->get_mip_levels(), 0, 1, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL); } } void SceneRenderer::framebuffer_resized(VkCommandBuffer cmdBuf, uint32_t newX, uint32_t newY) { if (!depthPyramid) { return; } if (depthPyramidLevels > 0) { for (uint32_t i = 0; i < depthPyramidLevels; i++) { delete depthPyramidReadUniforms[i]; delete depthPyramidWriteUniforms[i]; vku::destroy_descriptor_set(depthPyramidDownsampleSets[i]); } delete[] depthPyramidReadUniforms; delete[] depthPyramidWriteUniforms; delete[] depthPyramidDownsampleSets; depthPyramid->destroy(); } depthPyramidLevels = static_cast<uint32_t>(std::floor(std::log2(std::max(newX, newY)))); depthPyramid->create(cmdBuf, newX / 2, newY / 2, depthPyramidLevels, nullptr, vku::TEXTURE_TYPE_DEPTH_MINMAX_MIP, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); depthPyramidReadUniforms = new vku::UniformTexture2D * [depthPyramidLevels]; depthPyramidWriteUniforms = new vku::UniformStorageImage * [depthPyramidLevels]; depthPyramidDownsampleSets = new vku::DescriptorSet * [depthPyramidLevels]; for (uint32_t i = 0; i < depthPyramidLevels; i++) { if (i == 0) { depthPyramidReadUniforms[i] = new vku::UniformTexture2D(framebuffer->get_depth_texture()->get_image_view(0), VK_SHADER_STAGE_COMPUTE_BIT, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); } else { depthPyramidReadUniforms[i] = new vku::UniformTexture2D(depthPyramid->get_image_view(i - 1), VK_SHADER_STAGE_COMPUTE_BIT, VK_IMAGE_LAYOUT_GENERAL); } depthPyramidWriteUniforms[i] = new vku::UniformStorageImage(depthPyramid->get_image_view(i)); depthPyramidDownsampleSets[i] = vku::create_descriptor_set({ depthPyramidReadUniforms[i], depthPyramidWriteUniforms[i], resources::minSampler, resources::maxSampler }); } if (depthPyramidUniform) { for (uint32_t i = 0; i < NUM_FRAME_DATA; i++) { depthPyramidUniform->update_texture(i, depthPyramid->get_image_view()); } } } void SceneRenderer::init(VkCommandBuffer cmdBuf, vku::RenderPass* renderPass, vku::RenderPass* depthPass, vku::RenderPass* objectIdPass, vku::Framebuffer* mainFramebuffer, vku::Framebuffer* mainDepthFramebuffer) { framebuffer = mainFramebuffer; depthFramebuffer = mainDepthFramebuffer; depthPyramidLevels = 0; depthPyramid = new vku::Texture(); framebuffer_resized(cmdBuf, vku::swapChainExtent.width, vku::swapChainExtent.height); depthPyramidUniform = new vku::UniformTexture2D(depthPyramid->get_image_view(), VK_SHADER_STAGE_COMPUTE_BIT, VK_IMAGE_LAYOUT_GENERAL); geometryManager.set_render_pass(renderPass, depthPass, objectIdPass); geometryManager.init(1024, 1024, 32, 32, 2048); depthPyramidDownsample = (new vku::ComputePipeline())->name("min_max_downsample").descriptor_set(*depthPyramidDownsampleSets[0]).push_constant(VkPushConstantRange{ VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uint32_t) * 3 }).build(); } void SceneRenderer::cleanup() { geometryManager.cleanup(); delete depthPyramidUniform; delete depthPyramid; delete depthPyramidDownsample; } }
54.85
234
0.784412
[ "model" ]
f93ec0787f312a849b11a0e3206a9462e336a22b
33,805
cpp
C++
Programs/ResourceEditor/Classes/Modification/Private/ModificationModule.cpp
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Programs/ResourceEditor/Classes/Modification/Private/ModificationModule.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Programs/ResourceEditor/Classes/Modification/Private/ModificationModule.cpp
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#include "Classes/Modification/ModificationModule.h" #include "Classes/Modification/Private/ModificationData.h" #include <REPlatform/DataNodes/SceneData.h> #include <REPlatform/Scene/Systems/CollisionSystem.h> #include <REPlatform/DataNodes/SelectionData.h> #include <TArc/Controls/DoubleSpinBox.h> #include <TArc/Controls/Label.h> #include <TArc/Controls/QtBoxLayouts.h> #include <TArc/Core/ContextAccessor.h> #include <TArc/Core/FieldBinder.h> #include <TArc/Qt/QtIcon.h> #include <TArc/Utils/ModuleCollection.h> #include <TArc/Utils/Utils.h> #include <TArc/WindowSubSystem/ActionUtils.h> #include <TArc/WindowSubSystem/QtAction.h> #include <Reflection/ReflectedMeta.h> #include <Reflection/ReflectedTypeDB.h> namespace ModificationModuleDetails { const QString toolbarName = "Modifications Toolbar"; } struct ModificationInternalData : public DAVA::TArcDataNode { DAVA::DoubleSpinBox* xFieldControl = nullptr; DAVA::DoubleSpinBox* yFieldControl = nullptr; DAVA::DoubleSpinBox* zFieldControl = nullptr; DAVA_VIRTUAL_REFLECTION_IN_PLACE(ModificationInternalData, DAVA::TArcDataNode) { } }; void ModificationModule::PostInit() { GetAccessor()->GetGlobalContext()->CreateData(std::make_unique<ModificationInternalData>()); BindData(); CreateToolbar(); CreateActions(); } void ModificationModule::BindData() { using namespace DAVA; fieldBinder = std::make_unique<DAVA::FieldBinder>(GetAccessor()); FieldDescriptor selectionField; selectionField.type = ReflectedTypeDB::Get<SelectionData>(); selectionField.fieldName = FastName(SelectionData::selectionPropertyName); FieldDescriptor selectionBoxField; selectionBoxField.type = ReflectedTypeDB::Get<SelectionData>(); selectionBoxField.fieldName = FastName(SelectionData::selectionBoxPropertyName); FieldDescriptor transformTypeField; transformTypeField.type = ReflectedTypeDB::Get<ModificationData>(); transformTypeField.fieldName = FastName(ModificationData::transformTypeField); fieldBinder->BindField(transformTypeField, [this](const Any&) { RecalculateTransformableSelectionField(); }); fieldBinder->BindField(selectionField, [this](const Any&) { RecalculateTransformableSelectionField(); }); fieldBinder->BindField(selectionBoxField, [this](const Any&) { RecalculateTransformableSelectionField(); }); } void ModificationModule::CreateToolbar() { using namespace DAVA; using namespace ModificationModuleDetails; QList<QString> location = QList<QString>() << "View" << "Toolbars"; InsertionParams after = { InsertionParams::eInsertionMethod::AfterItem, "Main Toolbar" }; ActionPlacementInfo toolbarTogglePlacement(CreateMenuPoint(location, after)); GetUI()->DeclareToolbar(DAVA::mainWindowKey, toolbarTogglePlacement, toolbarName); } void ModificationModule::CreateActions() { using namespace DAVA; using namespace ModificationModuleDetails; ContextAccessor* accessor = GetAccessor(); UI* ui = GetUI(); FieldDescriptor sceneField; sceneField.type = ReflectedTypeDB::Get<SceneData>(); sceneField.fieldName = FastName(SceneData::scenePropertyName); FieldDescriptor transformTypeField; transformTypeField.type = ReflectedTypeDB::Get<ModificationData>(); transformTypeField.fieldName = FastName(ModificationData::transformTypeField); FieldDescriptor transformPivotField; transformPivotField.type = ReflectedTypeDB::Get<ModificationData>(); transformPivotField.fieldName = FastName(ModificationData::transformPivotField); auto isSceneNotEmpty = [](const Any& value) -> Any { return value.CanCast<SceneData::TSceneType>() && value.Cast<SceneData::TSceneType>().Get() != nullptr; }; auto isTrue = [](const Any& value) -> Any { return value.Get<bool>(false); }; auto makeBindable = [](QtAction* action) { KeyBindableActionInfo info; info.blockName = "Modification"; info.context = action->shortcutContext(); info.defaultShortcuts << action->shortcuts(); MakeActionKeyBindable(action, info); }; QString lastSeparatorName = "modification last"; // last separator in menu { QAction* lastSeparator = new QtActionSeparator(lastSeparatorName); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, "Place on landscape" })); ui->AddAction(DAVA::mainWindowKey, placementInfo, lastSeparator); } // action Select { const QString actionName = "Select"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/modify_select.png")); action->setShortcutContext(Qt::WindowShortcut); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); action->SetStateUpdationFunction(QtAction::Checked, transformTypeField, [](const DAVA::Any& value) -> DAVA::Any { return value.CanCast<Selectable::TransformType>() && value.Cast<Selectable::TransformType>() == Selectable::TransformType::Disabled; }); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::SetTransformType, this, Selectable::TransformType::Disabled)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // action Move { const QString actionName = "Move"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/modify_move.png")); action->setShortcutContext(Qt::WindowShortcut); action->setShortcut(QKeySequence("Q")); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); action->SetStateUpdationFunction(QtAction::Checked, transformTypeField, [](const DAVA::Any& value) -> DAVA::Any { return value.CanCast<Selectable::TransformType>() && value.Cast<Selectable::TransformType>() == Selectable::TransformType::Translation; }); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::SetTransformType, this, Selectable::TransformType::Translation)); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::ForceUpdateXYZControls, this)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // action Rotate { const QString actionName = "Rotate"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/modify_rotate.png")); action->setShortcutContext(Qt::WindowShortcut); action->setShortcut(QKeySequence("E")); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); action->SetStateUpdationFunction(QtAction::Checked, transformTypeField, [](const DAVA::Any& value) -> DAVA::Any { return value.CanCast<Selectable::TransformType>() && value.Cast<Selectable::TransformType>() == Selectable::TransformType::Rotation; }); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::SetTransformType, this, Selectable::TransformType::Rotation)); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::ForceUpdateXYZControls, this)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // action Scale { const QString actionName = "Scale"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/modify_scale.png")); action->setShortcutContext(Qt::WindowShortcut); action->setShortcut(QKeySequence("R")); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); action->SetStateUpdationFunction(QtAction::Checked, transformTypeField, [](const DAVA::Any& value) -> DAVA::Any { return value.CanCast<Selectable::TransformType>() && value.Cast<Selectable::TransformType>() == Selectable::TransformType::Scale; }); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::SetTransformType, this, Selectable::TransformType::Scale)); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::ForceUpdateXYZControls, this)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // separator in menu & toolbar { QAction* separator = new QtActionSeparator("sep1"); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, separator); } // action Transform In Local Coordinates { const QString actionName = "Transform In Local Coordinates"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/local_coordinates.png")); action->setShortcutContext(Qt::WindowShortcut); action->setShortcut(QKeySequence("G")); FieldDescriptor transformInLocalField; transformInLocalField.type = DAVA::ReflectedTypeDB::Get<ModificationData>(); transformInLocalField.fieldName = DAVA::FastName(ModificationData::transformInLocalField); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); action->SetStateUpdationFunction(QtAction::Checked, transformInLocalField, isTrue); connections.AddConnection(action, &QAction::triggered, [this](bool value) { SetTransformInLocalCoordinates(value); }); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // separator in menu & toolbar { QAction* separator = new QtActionSeparator("sep2"); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, separator); } // action Use Selection Center { const QString actionName = "Use Selection Center"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/pivot_common.png")); action->setShortcutContext(Qt::WindowShortcut); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); action->SetStateUpdationFunction(QtAction::Checked, transformPivotField, [](const DAVA::Any& value) -> DAVA::Any { return value.CanCast<Selectable::TransformPivot>() && value.Cast<Selectable::TransformPivot>() == Selectable::TransformPivot::CommonCenter; }); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::SetTransformPivot, this, Selectable::TransformPivot::CommonCenter)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // action Use Pivot Point Center { const QString actionName = "Use Pivot Point Center"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/pivot_center.png")); action->setShortcutContext(Qt::WindowShortcut); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); action->SetStateUpdationFunction(QtAction::Checked, transformPivotField, [](const DAVA::Any& value) -> DAVA::Any { return value.CanCast<Selectable::TransformPivot>() && value.Cast<Selectable::TransformPivot>() == Selectable::TransformPivot::ObjectCenter; }); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::SetTransformPivot, this, Selectable::TransformPivot::ObjectCenter)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // separator in toolbar { QAction* separator = new QtActionSeparator("sep3"); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); ui->AddAction(DAVA::mainWindowKey, placementInfo, separator); } // action Lock Transform { const QString actionName = "Lock Transform"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/lock_add.png")); action->setShortcutContext(Qt::WindowShortcut); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::OnLockTransform, this)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // action Unlock Transform { const QString actionName = "Unlock Transform"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/lock_delete.png")); action->setShortcutContext(Qt::WindowShortcut); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::OnUnlockTransform, this)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // separator in menu { QAction* separator = new QtActionSeparator("sep4"); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, separator); } FieldDescriptor singleModifyField; singleModifyField.type = DAVA::ReflectedTypeDB::Get<ModificationData>(); singleModifyField.fieldName = DAVA::FastName(ModificationData::modifyingSingleItemField); // action Zero Pivot Point { const QString actionName = "Zero Pivot Point"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/pivot_move_to_zero.png")); action->setShortcutContext(Qt::WindowShortcut); action->SetStateUpdationFunction(QtAction::Enabled, singleModifyField, isTrue); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::OnZeroPivotPoint, this)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // action Center Pivot Point { const QString actionName = "Center Pivot Point"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/pivot_mote_to_center.png")); action->setShortcutContext(Qt::WindowShortcut); action->SetStateUpdationFunction(QtAction::Enabled, singleModifyField, isTrue); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::OnCenterPivotPoint, this)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // separator in menu & toolbar { QAction* separator = new QtActionSeparator("sep5"); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); placementInfo.AddPlacementPoint(CreateMenuPoint("Edit", { InsertionParams::eInsertionMethod::BeforeItem, lastSeparatorName })); ui->AddAction(DAVA::mainWindowKey, placementInfo, separator); } // action Manual Transform Mode - Absolute/Offset { const QString actionName = "Manual Transform Mode - Absolute/Offset"; QtAction* action = new QtAction(accessor, actionName); QIcon icon; icon.addFile(":/QtIcons/move_absolute.png", QSize(), QIcon::Normal, QIcon::State::Off); icon.addFile(":/QtIcons/move_offset.png", QSize(), QIcon::Normal, QIcon::State::On); action->setIcon(icon); action->setShortcutContext(Qt::WindowShortcut); FieldDescriptor pivotModeField; pivotModeField.type = DAVA::ReflectedTypeDB::Get<ModificationData>(); pivotModeField.fieldName = DAVA::FastName(ModificationData::pivotModeField); action->SetStateUpdationFunction(QtAction::Enabled, sceneField, isSceneNotEmpty); action->SetStateUpdationFunction(QtAction::Checked, pivotModeField, [](const DAVA::Any& value) -> DAVA::Any { return value.CanCast<EntityModificationSystem::PivotMode>() && value.Cast<EntityModificationSystem::PivotMode>() == EntityModificationSystem::PivotRelative; }); connections.AddConnection(action, &QAction::triggered, [this](bool value) { GetModificationData()->SetPivotMode(value ? EntityModificationSystem::PivotRelative : EntityModificationSystem::PivotAbsolute); }); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } DAVA::FieldDescriptor enableModificationWidgetField; enableModificationWidgetField.type = DAVA::ReflectedTypeDB::Get<ModificationData>(); enableModificationWidgetField.fieldName = DAVA::FastName(ModificationData::manualModificationEnabledField); // manual modification bar { QWidget* bar = CreateManualModificationControlBar(); const QString actionName = "Manual Modification Bar"; QtAction* action = new QtAction(accessor, actionName); AttachWidgetToAction(action, bar); action->SetStateUpdationFunction(QtAction::Enabled, enableModificationWidgetField, isTrue); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } // action Reset Transform { const QString actionName = "Reset Transform"; QtAction* action = new QtAction(accessor, actionName); action->setIcon(SharedIcon(":/QtIcons/ccancel.png")); action->setShortcutContext(Qt::WindowShortcut); action->SetStateUpdationFunction(QtAction::Enabled, enableModificationWidgetField, isTrue); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::OnResetTransform, this)); connections.AddConnection(action, &QAction::triggered, Bind(&ModificationModule::ForceUpdateXYZControls, this)); makeBindable(action); ActionPlacementInfo placementInfo; placementInfo.AddPlacementPoint(CreateToolbarPoint(toolbarName)); ui->AddAction(DAVA::mainWindowKey, placementInfo, action); } } QWidget* ModificationModule::CreateManualModificationControlBar() { using namespace DAVA; ContextAccessor* accessor = GetAccessor(); UI* ui = GetUI(); Reflection reflection = DAVA::Reflection::Create(DAVA::ReflectedObject(this)); QWidget* widget = new QWidget; QtHBoxLayout* horizontalLayout = new QtHBoxLayout(widget); horizontalLayout->setSpacing(2); horizontalLayout->setContentsMargins(2, 1, 2, 1); { Label::Params p(accessor, ui, DAVA::mainWindowKey); p.fields[Label::Fields::IsVisible].BindConstValue(true); p.fields[Label::Fields::Text] = ModificationModule::xLabelField; Label* xLabel = new Label(p, accessor, reflection, widget); horizontalLayout->AddControl(xLabel); } { DoubleSpinBox::Params p(accessor, ui, DAVA::mainWindowKey); p.fields[DoubleSpinBox::Fields::IsVisible].BindConstValue(true); p.fields[DoubleSpinBox::Fields::IsEnabled] = ModificationModule::manualModificationEnabledField; p.fields[DoubleSpinBox::Fields::ShowSpinArrows] = ModificationModule::manualModificationArrowsEnabledField; p.fields[DoubleSpinBox::Fields::Value] = ModificationModule::xValueField; DoubleSpinBox* xAxisSpinBox = new DoubleSpinBox(p, accessor, reflection, widget); xAxisSpinBox->ToWidgetCast()->setMinimumSize(QSize(80, 0)); horizontalLayout->AddControl(xAxisSpinBox); GetModificationInternalData()->xFieldControl = xAxisSpinBox; } { Label::Params p(accessor, ui, DAVA::mainWindowKey); p.fields[Label::Fields::IsVisible] = ModificationModule::scaleModeOffField; p.fields[Label::Fields::Text].BindConstValue("Y:"); Label* yLabel = new Label(p, accessor, reflection, widget); horizontalLayout->AddControl(yLabel); } { DoubleSpinBox::Params p(accessor, ui, DAVA::mainWindowKey); p.fields[DoubleSpinBox::Fields::IsVisible] = ModificationModule::scaleModeOffField; p.fields[DoubleSpinBox::Fields::IsEnabled] = ModificationModule::manualModificationEnabledField; p.fields[DoubleSpinBox::Fields::ShowSpinArrows] = ModificationModule::manualModificationArrowsEnabledField; p.fields[DoubleSpinBox::Fields::Value] = ModificationModule::yValueField; DoubleSpinBox* yAxisSpinBox = new DoubleSpinBox(p, accessor, reflection, widget); yAxisSpinBox->ToWidgetCast()->setMinimumSize(QSize(80, 0)); horizontalLayout->AddControl(yAxisSpinBox); GetModificationInternalData()->yFieldControl = yAxisSpinBox; } { Label::Params p(accessor, ui, DAVA::mainWindowKey); p.fields[Label::Fields::IsVisible] = ModificationModule::scaleModeOffField; p.fields[Label::Fields::Text].BindConstValue("Z:"); Label* yLabel = new Label(p, accessor, reflection, widget); horizontalLayout->AddControl(yLabel); } { DoubleSpinBox::Params p(accessor, ui, DAVA::mainWindowKey); p.fields[DoubleSpinBox::Fields::IsVisible] = ModificationModule::scaleModeOffField; p.fields[DoubleSpinBox::Fields::IsEnabled] = ModificationModule::manualModificationEnabledField; p.fields[DoubleSpinBox::Fields::ShowSpinArrows] = ModificationModule::manualModificationArrowsEnabledField; p.fields[DoubleSpinBox::Fields::Value] = ModificationModule::zValueField; DoubleSpinBox* zAxisSpinBox = new DoubleSpinBox(p, accessor, reflection, widget); zAxisSpinBox->ToWidgetCast()->setMinimumSize(QSize(80, 0)); horizontalLayout->AddControl(zAxisSpinBox); GetModificationInternalData()->zFieldControl = zAxisSpinBox; } return widget; } void ModificationModule::OnContextCreated(DAVA::DataContext* context) { DAVA::SceneData* sceneData = context->GetData<DAVA::SceneData>(); DAVA::SceneEditor2* scene = sceneData->GetScene().Get(); DVASSERT(scene != nullptr); std::unique_ptr<ModificationData> modificationData = std::make_unique<ModificationData>(); modificationData->modificationSystem = scene->GetSystem<DAVA::EntityModificationSystem>(); context->CreateData(std::move(modificationData)); } DAVA::SceneEditor2* ModificationModule::GetCurrentScene() const { const DAVA::DataContext* ctx = GetAccessor()->GetActiveContext(); if (ctx != nullptr) { DAVA::SceneData* data = ctx->GetData<DAVA::SceneData>(); if (data != nullptr) { return data->GetScene().Get(); } } return nullptr; } const DAVA::SelectableGroup& ModificationModule::GetCurrentSelection() const { DAVA::SelectionData* selectionData = GetAccessor()->GetActiveContext()->GetData<DAVA::SelectionData>(); if (selectionData != nullptr) { return selectionData->GetSelection(); } static DAVA::SelectableGroup emptyGroup; return emptyGroup; } ModificationData* ModificationModule::GetModificationData() const { const DAVA::DataContext* context = GetAccessor()->GetActiveContext(); return (context != nullptr) ? context->GetData<ModificationData>() : nullptr; } void ModificationModule::RecalculateTransformableSelectionField() { using namespace DAVA; ModificationData* modificationData = GetModificationData(); if (modificationData != nullptr) { SceneEditor2* scene = GetCurrentScene(); DVASSERT(scene != nullptr); SceneCollisionSystem* collisionSystem = scene->GetSystem<SceneCollisionSystem>(); DVASSERT(collisionSystem != nullptr); const SelectableGroup& selection = GetCurrentSelection(); DAVA::Vector<Selectable> tranformableObjects; tranformableObjects.reserve(selection.GetSize()); for (const Selectable& item : selection.GetContent()) { if (item.SupportsTransformType(modificationData->GetTransformType())) { Selectable obj(item.GetContainedObject()); obj.SetBoundingBox(collisionSystem->GetUntransformedBoundingBox(item.GetContainedObject())); tranformableObjects.push_back(obj); } } SelectableGroup transformableSelection; transformableSelection.Add(tranformableObjects); transformableSelection.RebuildIntegralBoundingBox(); modificationData->modificationSystem->SetTransformableSelection(transformableSelection); } } void ModificationModule::SetTransformType(DAVA::Selectable::TransformType transformType) { GetModificationData()->SetTransformType(transformType); } void ModificationModule::SetTransformPivot(DAVA::Selectable::TransformPivot transformPivot) { GetModificationData()->SetTransformPivot(transformPivot); } void ModificationModule::SetTransformInLocalCoordinates(bool value) { GetModificationData()->SetTransformInLocalCoordinates(value); } void ModificationModule::OnResetTransform() { GetModificationData()->modificationSystem->ResetTransform(GetCurrentSelection()); } void ModificationModule::OnLockTransform() { GetModificationData()->modificationSystem->LockTransform(GetCurrentSelection(), true); } void ModificationModule::OnUnlockTransform() { GetModificationData()->modificationSystem->LockTransform(GetCurrentSelection(), false); } void ModificationModule::OnCenterPivotPoint() { GetModificationData()->modificationSystem->MovePivotCenter(GetCurrentSelection()); } void ModificationModule::OnZeroPivotPoint() { GetModificationData()->modificationSystem->MovePivotZero(GetCurrentSelection()); } bool ModificationModule::IsModificationEnabled() const { ModificationData* data = GetModificationData(); return (data != nullptr) ? data->GetManualModificationEnabled() : false; } bool ModificationModule::IsModificationArrowsEnabled() const { ModificationData* data = GetModificationData(); return (data != nullptr) ? data->GetManualModificationArrowsEnabled() : false; } bool ModificationModule::IsScaleModeOff() const { ModificationData* data = GetModificationData(); return (data != nullptr) ? data->GetScaleModeOff() : true; } DAVA::String ModificationModule::GetLabelX() const { ModificationData* data = GetModificationData(); return (data != nullptr) ? data->GetXLabelText() : "X:"; } DAVA::Any ModificationModule::GetValueX() const { static DAVA::Any emptyString = DAVA::String(""); ModificationData* data = GetModificationData(); return (data != nullptr) ? data->GetValueX() : emptyString; } DAVA::Any ModificationModule::GetValueY() const { static DAVA::Any emptyString = DAVA::String(""); ModificationData* data = GetModificationData(); return (data != nullptr) ? data->GetValueY() : emptyString; } DAVA::Any ModificationModule::GetValueZ() const { static DAVA::Any emptyString = DAVA::String(""); ModificationData* data = GetModificationData(); return (data != nullptr) ? data->GetValueZ() : emptyString; } void ModificationModule::SetValueX(const DAVA::Any& value) { ModificationData* data = GetModificationData(); if (data != nullptr) { data->SetValueX(value); } } void ModificationModule::SetValueY(const DAVA::Any& value) { ModificationData* data = GetModificationData(); if (data != nullptr) { data->SetValueY(value); } } void ModificationModule::SetValueZ(const DAVA::Any& value) { ModificationData* data = GetModificationData(); if (data != nullptr) { data->SetValueZ(value); } } ModificationInternalData* ModificationModule::GetModificationInternalData() const { const DAVA::DataContext* context = GetAccessor()->GetGlobalContext(); return (context != nullptr) ? context->GetData<ModificationInternalData>() : nullptr; } void ModificationModule::ForceUpdateXYZControls() { ModificationInternalData* data = GetModificationInternalData(); data->xFieldControl->ForceUpdate(); data->yFieldControl->ForceUpdate(); data->zFieldControl->ForceUpdate(); } DAVA_VIRTUAL_REFLECTION_IMPL(ModificationModule) { DAVA::ReflectionRegistrator<ModificationModule>::Begin() .ConstructorByPointer() .Field(manualModificationEnabledField, &ModificationModule::IsModificationEnabled, nullptr) .Field(manualModificationArrowsEnabledField, &ModificationModule::IsModificationArrowsEnabled, nullptr) .Field(scaleModeOffField, &ModificationModule::IsScaleModeOff, nullptr) .Field(xLabelField, &ModificationModule::GetLabelX, nullptr) .Field(xValueField, &ModificationModule::GetValueX, &ModificationModule::SetValueX)[DAVA::M::FloatNumberAccuracy(3)] .Field(yValueField, &ModificationModule::GetValueY, &ModificationModule::SetValueY)[DAVA::M::FloatNumberAccuracy(3)] .Field(zValueField, &ModificationModule::GetValueZ, &ModificationModule::SetValueZ)[DAVA::M::FloatNumberAccuracy(3)] .End(); } const char* ModificationModule::manualModificationEnabledField = "isManualModificationEnabled"; const char* ModificationModule::manualModificationArrowsEnabledField = "isManualModificationArrowsEnabled"; const char* ModificationModule::scaleModeOffField = "scaleModeOff"; const char* ModificationModule::xLabelField = "xLabel"; const char* ModificationModule::xValueField = "xValue"; const char* ModificationModule::yValueField = "yValue"; const char* ModificationModule::zValueField = "zValue"; DECL_TARC_MODULE(ModificationModule);
42.737042
201
0.70531
[ "vector", "transform" ]
f9490145c36cb9ae284cde8697d9e3b1b8f18111
1,592
cpp
C++
Algorithms/57.Insert-Interval/solution.cpp
moranzcw/LeetCode_Solutions
49a7e33b83d8d9ce449c758717f74a69e72f808e
[ "MIT" ]
178
2017-07-09T23:13:11.000Z
2022-02-26T13:35:06.000Z
Algorithms/57.Insert-Interval/solution.cpp
cfhyxxj/LeetCode-NOTES
455d33aae54d065635d28ebf37f815dc4ace7e63
[ "MIT" ]
1
2020-10-10T16:38:03.000Z
2020-10-10T16:38:03.000Z
Algorithms/57.Insert-Interval/solution.cpp
cfhyxxj/LeetCode-NOTES
455d33aae54d065635d28ebf37f815dc4ace7e63
[ "MIT" ]
82
2017-08-19T07:14:39.000Z
2022-02-17T14:07:55.000Z
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) { int i = 0; int len = intervals.size(); if(0 == len) { intervals.push_back(newInterval); return intervals; } vector<Interval> re; //find the insert position of start. while(i < len && intervals[i].end < newInterval.start) { re.push_back(intervals[i]); ++i; } //at the right, if(i == len) { re.push_back(newInterval); return re; } int j = i; //find the insert position of end. while(j < len && intervals[j].end < newInterval.end) { ++j; } Interval jion; jion.start = min(intervals[i].start, newInterval.start); if(j == len) { jion.end = newInterval.end; re.push_back(jion); return re; } if(newInterval.end < intervals[j].start) { --j; jion.end = newInterval.end; re.push_back(jion); } else { jion.end = intervals[j].end; re.push_back(jion); } ++j; while(j < len) { re.push_back(intervals[j]); ++j; } return re; } };
23.761194
79
0.452261
[ "vector" ]
f953427aa0749db42308b2499023e5de2a012a6e
1,696
cc
C++
sling/nlp/document/features.cc
JDzvonik/sling
3000f6ff7ae5c2d5ddcae13ad3599e35bf375ec5
[ "Apache-2.0" ]
2,023
2017-10-13T01:39:21.000Z
2022-03-27T14:24:09.000Z
sling/nlp/document/features.cc
JDzvonik/sling
3000f6ff7ae5c2d5ddcae13ad3599e35bf375ec5
[ "Apache-2.0" ]
166
2017-10-26T00:36:03.000Z
2021-10-08T13:32:32.000Z
sling/nlp/document/features.cc
JDzvonik/sling
3000f6ff7ae5c2d5ddcae13ad3599e35bf375ec5
[ "Apache-2.0" ]
316
2017-10-12T20:34:28.000Z
2022-02-02T16:03:45.000Z
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "sling/nlp/document/features.h" #include "sling/base/types.h" #include "sling/nlp/document/document.h" #include "sling/util/unicode.h" namespace sling { namespace nlp { void DocumentFeatures::Extract(const Document &document, int begin, int end) { if (end == -1) end = document.num_tokens(); int length = end - begin; features_.resize(length); bool in_quote = false; for (int i = 0; i < length; ++i) { const string &word = document.token(begin + i).word(); TokenFeatures &f = features_[i]; // Look up token word in lexicon and get word features. f.word = lexicon_->Lookup(word, &f.prefix, &f.suffix, &f.shape); // Re-compute context-sensitive features. if (i == 0 || document.token(i).brk() >= SENTENCE_BREAK) { if (f.shape.capitalization == WordShape::CAPITALIZED) { f.shape.capitalization = WordShape::INITIAL; } } if (f.shape.quote == WordShape::UNKNOWN_QUOTE) { f.shape.quote = in_quote ? WordShape::CLOSE_QUOTE : WordShape::OPEN_QUOTE; in_quote = !in_quote; } } } } // namespace nlp } // namespace sling
32.615385
80
0.685142
[ "shape" ]
f95eebc1ac480590288c1709e1ccf63f95b041ba
14,839
cpp
C++
Source/ExistenceApps/ExistenceClient/ExistenceClientStateAccount.cpp
vivienneanthony/Urho3D-Mastercurrent-Existence
2d75021489996e1abc2fd330ed967cd89a62f40d
[ "Apache-2.0" ]
3
2015-05-22T23:39:03.000Z
2016-04-13T03:52:59.000Z
Source/ExistenceApps/ExistenceClient/ExistenceClientStateAccount.cpp
vivienneanthony/Urho3D-Mastercurrent-Existence
2d75021489996e1abc2fd330ed967cd89a62f40d
[ "Apache-2.0" ]
null
null
null
Source/ExistenceApps/ExistenceClient/ExistenceClientStateAccount.cpp
vivienneanthony/Urho3D-Mastercurrent-Existence
2d75021489996e1abc2fd330ed967cd89a62f40d
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) 2008-2014 the Urho3D project. // // 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 <Urho3D/Urho3D.h> #include "../../../Urho3D/Core/CoreEvents.h" #include "../../../Urho3D/Engine/Engine.h" #include "../../../Urho3D/UI/Font.h" #include "../../../Urho3D/Input/Input.h" #include "../../../Urho3D/Core/ProcessUtils.h" #include "../../../Urho3D/UI/Text.h" #include "../../../Urho3D/UI/UI.h" #include "../../../Urho3D/Scene/Scene.h" #include "../../../Urho3D/Graphics/StaticModel.h" #include "../../../Urho3D/Graphics/Octree.h" #include "../../../Urho3D/Graphics/Model.h" #include "../../../Urho3D/Graphics/Material.h" #include "../../../Urho3D/Graphics/Camera.h" #include "../../../Urho3D/Resource/ResourceCache.h" #include "../../../Urho3D/Graphics/Renderer.h" #include "../../../Urho3D/Graphics/Camera.h" #include "../../../Urho3D/UI/Window.h" #include "../../../Urho3D/UI/Button.h" #include "../../../Urho3D/UI/LineEdit.h" #include "../../../Urho3D/UI/UIElement.h" #include "../../../Urho3D/Math/BoundingBox.h" #include "../../../Urho3D/UI/UIEvents.h" #include "../../../Urho3D/Graphics/DebugRenderer.h" #include "../../../Urho3D/IO/File.h" #include "../../../Urho3D/IO/FileSystem.h" #include "../../../Urho3D/Resource/XMLFile.h" #include "../../../Urho3D/Resource/XMLElement.h" #include "../../../Urho3D/IO/Deserializer.h" #include "../../../Urho3D/UI/Cursor.h" #include "../../../Urho3D/IO/FileSystem.h" #include "../../../Urho3D/UI/ListView.h" #include "../../../Urho3D/Engine/Console.h" #include "../../../Urho3D/Physics/RigidBody.h" #include "../../../Urho3D/Physics/CollisionShape.h" #include "../../../Urho3D/Physics/PhysicsWorld.h" #include "../../../Urho3D/Graphics/Animation.h" #include "../../../Urho3D/Graphics/AnimatedModel.h" #include "../../../Urho3D/Graphics/AnimationController.h" #include "../ExistenceComponents/Character.h" #include "../../../Urho3D/Graphics/Terrain.h" #include "../../../Urho3D/Engine/EngineEvents.h" #include "../../../Urho3D/Graphics/Zone.h" #include "../../../Urho3D/IO/Log.h" #include "../../../Urho3D/Graphics/Skybox.h" #include "../../../Urho3D/UI/Sprite.h" #include "../../../Urho3D/Graphics/StaticModelGroup.h" #include "../../../Urho3D/Graphics/BillboardSet.h" #include "../../../Urho3D/Math/Random.h" #include "../../../Urho3D/Graphics/RenderPath.h" #include "../../../Urho3D/Math/Color.h" #include "../ExistenceComponents/GameStateHandlerComponent.h" #include "../ExistenceComponents/GameStateEvents.h" #include "../ExistenceComponents/GameObject.h" #include "../ExistenceComponents/EnvironmentBuild.h" #include "../ExistenceComponents/Manager.h" #include "../Account.h" #include <string> #include <iostream> #include <sstream> #include <vector> #include <iterator> #include <algorithm> #include <locale> #include <ctime> #include <cmath> #include <iomanip> #include <fstream> #include <cstdlib> #include <iostream> #include <utility> #include <algorithm> #include "../../../Urho3D/Procedural/Procedural.h" #include "../../../Urho3D/Procedural/ProceduralTerrain.h" #include "../../../Urho3D/Procedural/RandomNumberGenerator.h" #include "ExistenceClient.h" #include "ExistenceClientStateAccount.h" #include "ExistenceClientUI.h" #include "../../Urho3D/Engine/DebugHud.h" #define DEFAULTSIZE 4096 using namespace std; using namespace Urho3D; /// State Account Constructor ExistenceClientStateAccount::ExistenceClientStateAccount(Context* context): ExistenceClientStateSingleton (context) ,Existence(NULL) { /// Debug cout << "Debug: State Account Constructor" << endl; /// Get component GameStateHandlerComponent * gamestatehandlercomponent_ = GetSubsystem<GameStateHandlerComponent>(); /// Set aApplication Existence = gamestatehandlercomponent_->GetApplication(); /// Set UI State gamestatehandlercomponent_->SetUIState(UI_ACCOUNTCREATIONINTERFACE); /// Debug cout << "Debug: State Account Constructor Test Value " << Existence->testvalue << endl; return; } /// State Account Desctructor ExistenceClientStateAccount::~ExistenceClientStateAccount() { /// Debug cout << "Debug: State Account Deconstructor" << endl; return; } /// State Account Enter void ExistenceClientStateAccount::Enter() { /// Debug cout << "Debug: State Account Enter" << endl; /// create UI Account(); return; } /// State Account Exit void ExistenceClientStateAccount::Exit() { /// Debug cout << "Debug: State Account Exit" << endl; return; } /// State Account On Update void ExistenceClientStateAccount::OnUpdate(StringHash eventType, VariantMap& eventData) { /// Debug cout << "Debug: State Account OnUpdate" << endl; return; } void ExistenceClientStateAccount::SetParameter(String parameter_) { /// Do Nothing return; } /// State Account UI void ExistenceClientStateAccount::Account(void) { /// Set variables bool CurrentStateIsLogin=true; /// Load the user interace CreateAccountScreenUI(); return; } /// Create a account UI void ExistenceClientStateAccount::CreateAccountScreenUI(void) { /// Get Needed SubSystems ResourceCache* cache = GetSubsystem<ResourceCache>(); Renderer* renderer = GetSubsystem<Renderer>(); Graphics* graphics = GetSubsystem<Graphics>(); UI* ui = GetSubsystem<UI>(); GameStateHandlerComponent * gamestatehandlercomponent_ = GetSubsystem<GameStateHandlerComponent>(); /// Clear screen ui->Clear(); /// Get rendering window size as floats float width = (float)graphics->GetWidth(); float height = (float)graphics->GetHeight(); /// Create the Window and add it to the UI's root node Existence->window_= new Window(context_); Existence->uiRoot_->AddChild(Existence->window_); /// Define UIElements and childrens types UIElement* titleBar = new UIElement(context_); UIElement* confirmpassword1UIElement = new UIElement(context_); UIElement* confirmpassword2UIElement = new UIElement(context_); UIElement* playerUIElement = new UIElement(context_); UIElement* playernameinputUIElement = new UIElement(context_); UIElement* blankUIElement = new UIElement(context_); Text* blankText = new Text(context_); UIElement* blank2UIElement = new UIElement(context_); Text* blank2Text = new Text(context_); Button* newaccount2Button = new Button(context_); Text* windowTitle = new Text(context_); LineEdit* usernameInput=new LineEdit(context_); LineEdit* emailInput=new LineEdit(context_); LineEdit* passwordInput1=new LineEdit(context_); LineEdit* passwordInput2=new LineEdit(context_); LineEdit* firstnameInput=new LineEdit(context_); LineEdit* middlenameInput=new LineEdit(context_); LineEdit* lastnameInput=new LineEdit(context_); Text* confirmpassword1Text = new Text(context_); Text* nameText = new Text(context_); Text* confirmpassword2Text = new Text(context_); Text* emailText = new Text(context_); /// Setup alignments titleBar->SetMinSize(0,32); titleBar->SetVerticalAlignment(VA_TOP); titleBar->SetLayoutMode(LM_HORIZONTAL); confirmpassword1UIElement->SetLayoutMode(LM_HORIZONTAL); confirmpassword2UIElement->SetLayoutMode(LM_HORIZONTAL); playerUIElement->SetLayoutMode(LM_HORIZONTAL); playernameinputUIElement->SetMinSize(0,32); playernameinputUIElement->SetLayoutMode(LM_HORIZONTAL); blankUIElement->SetLayoutMode(LM_HORIZONTAL); blankUIElement->SetFixedHeight(16); /// Set Window size and layout settings Existence ->window_->SetMinSize(384, 192); Existence ->window_->SetLayout(LM_VERTICAL, 6, IntRect(6, 6, 6, 6)); Existence ->window_->SetAlignment(HA_CENTER, VA_CENTER); Existence ->window_->SetName("CreateAccountWindow"); Existence ->window_->SetMovable(false); Existence ->window_->SetOpacity(.6); /// Create Window 'titlebar' container windowTitle->SetName("CreateAccount"); windowTitle->SetText("Username"); usernameInput->SetName("usernameInput"); usernameInput->SetText("<Enter Username>"); usernameInput->SetMaxLength(24); usernameInput->SetMinHeight(24); emailText->SetName("emailText"); emailText->SetText("Email"); emailInput->SetName("emailInput"); emailInput->SetText("<Enter Email>"); emailInput->SetMaxLength(24); emailInput->SetMinHeight(24); /// Setup first password text confirmpassword1Text->SetName("Password"); confirmpassword1Text->SetText("Password"); passwordInput1->SetName("passwordInput1"); passwordInput1->SetText("<Enter Password>"); passwordInput1->SetMaxLength(24); passwordInput1->SetMinHeight(24); /// Setup confirm password text confirmpassword2Text->SetName("Password"); confirmpassword2Text->SetText("Confirm Password"); passwordInput2->SetName("passwordInput2"); passwordInput2->SetText("<Enter Password2>"); passwordInput2->SetMaxLength(24); passwordInput2->SetMinHeight(24); /// Add the controls to the title bar confirmpassword1UIElement-> AddChild(confirmpassword1Text); confirmpassword2UIElement-> AddChild(confirmpassword2Text); nameText->SetName("Name"); nameText->SetText("Name"); firstnameInput->SetName("firstnameInput"); firstnameInput->SetText("<firstname>"); firstnameInput->SetMaxLength(24); firstnameInput->SetMinHeight(24); firstnameInput->SetFixedWidth(125); middlenameInput->SetName("middlenameInput"); middlenameInput->SetText("<middlename>"); middlenameInput->SetMaxLength(24); middlenameInput->SetMinHeight(24); middlenameInput->SetFixedWidth(125); lastnameInput->SetName("lastnameInput"); lastnameInput->SetText("<lastname>"); lastnameInput->SetMaxLength(24); lastnameInput->SetMinHeight(24); lastnameInput->SetFixedWidth(125); blankText->SetName("blank"); blankText->SetText(" "); blank2Text->SetName("blank2"); blank2Text->SetText(" "); /// Add Children titleBar->AddChild(windowTitle); Existence->window_->AddChild(titleBar); Existence->window_->AddChild(usernameInput); Existence->window_->AddChild(emailText); Existence->window_->AddChild(emailInput); Existence->window_->AddChild(confirmpassword1UIElement); Existence->window_->AddChild(passwordInput1); Existence->window_->AddChild(confirmpassword2UIElement); Existence->window_->AddChild(passwordInput2); blankUIElement-> AddChild(blankText); Existence->window_->AddChild(blankUIElement); blank2UIElement-> AddChild(blank2Text); playerUIElement-> AddChild(nameText); playernameinputUIElement->AddChild(firstnameInput); playernameinputUIElement->AddChild(middlenameInput); playernameinputUIElement->AddChild(lastnameInput); /// declare buttons newaccount2Button->SetName("NewAccountLogin"); newaccount2Button->SetStyle("continueButton"); /// add children Existence ->window_->AddChild(playerUIElement); Existence ->window_->AddChild(playernameinputUIElement); Existence ->window_->AddChild(blank2UIElement); Existence->window_->AddChild(newaccount2Button); /// Apply styles Existence->window_->SetStyleAuto(); windowTitle->SetStyleAuto(); confirmpassword1Text->SetStyleAuto(); confirmpassword2Text->SetStyleAuto(); passwordInput2->SetStyleAuto(); passwordInput1->SetStyleAuto(); nameText->SetStyleAuto(); emailText->SetStyleAuto(); emailInput->SetStyleAuto(); firstnameInput->SetStyleAuto(); middlenameInput->SetStyleAuto(); lastnameInput->SetStyleAuto(); usernameInput->SetStyleAuto(); blank2Text->SetStyleAuto(); blankText->SetStyleAuto(); /// Subscribe to Handler SubscribeToEvent(newaccount2Button, E_RELEASED, HANDLER(ExistenceClientStateAccount, CreateAccountUIHandleClosePressed)); return; } /// Create Accooount UI Handler void ExistenceClientStateAccount::CreateAccountUIHandleClosePressed(StringHash eventType, VariantMap& eventData) { /// Get Needed SubSystems UI* ui_ = GetSubsystem<UI>(); GameStateHandlerComponent * gamestatehandlercomponent_ = GetSubsystem<GameStateHandlerComponent>(); /// Get line objects LineEdit* firstnameLineEdit = (LineEdit*)ui_->GetRoot()->GetChild("firstnameInput", true); LineEdit* middlenameLineEdit = (LineEdit*)ui_->GetRoot()->GetChild("middlenameInput", true); LineEdit* lastnameLineEdit= (LineEdit*)ui_->GetRoot()->GetChild("lastnameInput", true); LineEdit* usernameLineEdit= (LineEdit*)ui_->GetRoot()->GetChild("usernameInput", true); LineEdit* password1LineEdit = (LineEdit*)ui_->GetRoot()->GetChild("passwordInput1", true); LineEdit* password2LineEdit = (LineEdit*)ui_->GetRoot()->GetChild("passwordInput2", true); LineEdit* emailLineEdit = (LineEdit*)ui_->GetRoot()->GetChild("emailInput", true); String firstnameInput = firstnameLineEdit->GetText(); String middlenameInput = middlenameLineEdit->GetText(); String lastnameInput = lastnameLineEdit->GetText(); String usernameInput = usernameLineEdit->GetText(); String password1Input = password1LineEdit->GetText(); String password2Input = password2LineEdit->GetText(); String emailInput = emailLineEdit->GetText(); accountinformation account; account.email=emailInput.CString(); account.username=usernameInput.CString(); account.firstname=firstnameInput.CString(); account.lastname=lastnameInput.CString(); account.middlename=middlenameInput.CString(); account.password=password1Input.CString(); /// Save Account Information Existence -> SaveAccount(account); /// Erase the UI Existence -> EraseUI(); ///ExistenceGameState -> SendEvent("GAME_STATE_PLAYERCREATE"); return; }
34.191244
125
0.713053
[ "vector", "model" ]
f97dffe9bd1f229ff74c89df64c9ae0ef419fc67
1,881
hpp
C++
pysim/cppsource/CommonSystemImpl.hpp
freol35241/pysim
36faf67d00ff644a593f20994c0f15053d600886
[ "BSD-3-Clause" ]
9
2018-01-15T07:43:57.000Z
2022-01-11T20:21:38.000Z
pysim/cppsource/CommonSystemImpl.hpp
freol35241/pysim
36faf67d00ff644a593f20994c0f15053d600886
[ "BSD-3-Clause" ]
31
2016-05-06T23:21:53.000Z
2021-11-04T22:40:25.000Z
pysim/cppsource/CommonSystemImpl.hpp
freol35241/pysim
36faf67d00ff644a593f20994c0f15053d600886
[ "BSD-3-Clause" ]
7
2017-03-02T14:55:48.000Z
2018-04-11T06:29:35.000Z
#pragma once #include <vector> #include <map> #include <memory> #include "SimulatableSystem.hpp" #include "Variable.hpp" #include "ConnectionHandler.hpp" namespace pysim { struct CommonSystemImplPrivate; class StoreHandler; class CommonSystemImpl : public SimulatableSystemInterface { public: CommonSystemImpl(); virtual ~CommonSystemImpl(); ////////////////////////////////////////////////////////////////////////// // Inherited from Simulatable System ////////////////////////////////////////////////////////////////////////// void copyoutputs(); void copystateoutputs(); double getNextUpdateTime(); bool do_comparison(); std::vector<double*> getStatePointers(); std::vector<double*> getDerPointers(); void doStoreStep(double time); bool getDiscrete(); ////////////////////////////////////////////////////////////////////////// // Interface used from python ////////////////////////////////////////////////////////////////////////// void store(const char* name); StoreHandler* getStoreHandlerP(); void add_compare_greater(char* comparename, double comparevalue); void add_compare_smaller(char* comparename, double comparevalue); //Parameter handling template <typename T> std::vector<std::string> getParNames(); template <typename T> T getPar(char* name); template <typename T> void setPar(char* name, T value); std::map<std::string, std::string> getParDescriptionMap(); ////////////////////////////////////////////////////////////////////////// // Attributes ////////////////////////////////////////////////////////////////////////// Variable inputs; Variable outputs; Variable states; Variable ders; ConnectionHandler connectionHandler; protected: std::unique_ptr<CommonSystemImplPrivate> d_ptr; }; }
27.661765
78
0.528974
[ "vector" ]
f98249a4faac72ab8f2ebbd7d9a43eb9850f5c2f
3,733
cpp
C++
sources/dansandu/chocolate/transform.cpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
sources/dansandu/chocolate/transform.cpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
sources/dansandu/chocolate/transform.cpp
dansandu/chocolate
a90bf78a6891f578a7718329527ae56b502b57c2
[ "MIT" ]
null
null
null
#include "dansandu/chocolate/transform.hpp" #include "dansandu/math/common.hpp" using dansandu::math::common::close; using dansandu::math::matrix::crossProduct; using dansandu::math::matrix::dotProduct; using dansandu::math::matrix::normalized; namespace dansandu::chocolate::transform { Matrix4 scale(const float x, const float y, const float z) { // clang-format off return Matrix4{{{ x, 0.0f, 0.0f, 0.0f}, {0.0f, y, 0.0f, 0.0f}, {0.0f, 0.0f, z, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}}; // clang-format on } Matrix4 translate(const float x, const float y, const float z) { // clang-format off return Matrix4{{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, { x, y, z, 1.0f}}}; // clang-format on } Matrix4 translate(const ConstantVector3View vector) { return translate(vector.x(), vector.y(), vector.z()); } Matrix4 rotateByX(const float radians) { const auto cos = std::cos(radians); const auto sin = std::sin(radians); // clang-format off return Matrix4{{{1.0f, 0.0f, 0.0f, 0.0f}, {0.0f, cos, sin, 0.0f}, {0.0f, -sin, cos, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}}; // clang-format on } Matrix4 rotateByY(const float radians) { const auto cos = std::cos(radians); const auto sin = std::sin(radians); // clang-format off return Matrix4{{{ cos, 0.0f, -sin, 0.0f}, {0.0f, 1.0f, 0.0f, 0.0f}, { sin, 0.0f, cos, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}}; // clang-format on } Matrix4 rotateByZ(const float radians) { const auto cos = std::cos(radians); const auto sin = std::sin(radians); // clang-format off return Matrix4{{{ cos, sin, 0.0f, 0.0f}, {-sin, cos, 0.0f, 0.0f}, {0.0f, 0.0f, 1.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 1.0f}}}; // clang-format on } Matrix4 lookAt(const ConstantVector3View eye, const ConstantVector3View target, const ConstantVector3View up) { const auto w = normalized(eye - target); const auto u = normalized(crossProduct(up, w)); const auto v = crossProduct(w, u); // clang-format off return translate(-eye) * Matrix4{{{u.x(), v.x(), w.x(), 0.0f}, {u.y(), v.y(), w.y(), 0.0f}, {u.z(), v.z(), w.z(), 0.0f}, { 0.0f, 0.0f, 0.0f, 1.0f}}}; // clang-format on } Matrix4 perspective(const float near, const float far, const float fieldOfViewRadians, const float aspect) { const auto ctg = 1.0f / std::tan(0.5f * fieldOfViewRadians); const auto p33 = (far + near) / (near - far); const auto p43 = 2.0f * far * near / (near - far); // clang-format off return Matrix4{{{ ctg, 0.0f, 0.0f, 0.0f}, {0.0f, aspect * ctg, 0.0f, 0.0f}, {0.0f, 0.0f, p33, -1.0f}, {0.0f, 0.0f, p43, 0.0f}}}; // clang-format on } Matrix4 viewport(const float width, const float height) { const auto x = width / 2.0f; const auto y = height / 2.0f; return scale(x, y, 1.0f) * translate(x, y, -1.0f); } Vertices dehomogenized(const ConstantVerticesView vertices) { auto result = static_cast<Vertices>(vertices); for (auto i = 0; i < result.rowCount(); ++i) { for (auto j = 0; j < result.columnCount(); ++j) { result(i, j) /= result(i, result.columnCount() - 1); } } return result; } }
31.108333
109
0.519153
[ "vector", "transform" ]
f988f714ccc1ccca6fcd6e9c6914fd6c54bdf01e
1,217
cc
C++
blaze/blaze/operator/op/sigmoid_op.cc
Ru-Xiang/x-deeplearning
04cc0497150920c64b06bb8c314ef89977a3427a
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
blaze/blaze/operator/op/sigmoid_op.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
blaze/blaze/operator/op/sigmoid_op.cc
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* * \file sigmoid_op.cc * \desc The sigmoid operator */ #include "blaze/operator/op/sigmoid_op.h" #include <omp.h> #include <math.h> #include "blaze/math/activation.h" #include "blaze/math/vml.h" namespace blaze { template <typename DType> void SigmoidKernel(const SigmoidParam<DType>& params) { VML_Exp<DType, CPUContext>(params.size, params.x, params.y, nullptr); for (int k = 0; k < params.size; ++k) { params.y[k] = params.y[k] / (1 + params.y[k]); } } template <> bool SigmoidOp<CPUContext>::RunOnDevice() { Blob* X = this->Input(0); Blob* Y = this->Output(0); TYPE_SWITCH(X->data_type(), DType, { // Reshape Y->Reshape(X->shape()); // lauch cpu kernel SigmoidParam<DType> params(X->as<DType>(), X->size(), Y->as<DType>()); SigmoidKernel(params); }); return true; } REGISTER_CPU_OPERATOR(Sigmoid, SigmoidOp<CPUContext>); // Input: X Output: Y OPERATOR_SCHEMA(Sigmoid) .NumInputs(1) .NumOutputs(1) .AllowInplace({{0, 0}}) .IdenticalTypeOfInput(0) .SetAttr<bool>(kAttrIsElementWise, true) .SetDoc(R"DOC( Sigmoid activation. )DOC") .Input(0, "X", "1D input tensor") .Output(0, "Y", "1D output tensor"); } // namespace blaze
22.127273
74
0.643385
[ "shape" ]
f9891044c8dd7f41690e8fcdf778df131ed3004c
7,030
cpp
C++
BlackVision/Test/Model/TestSerialization/Source/TestInterpolators/InvalidInterpolations.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
1
2022-01-28T11:43:47.000Z
2022-01-28T11:43:47.000Z
BlackVision/Test/Model/TestSerialization/Source/TestInterpolators/InvalidInterpolations.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
BlackVision/Test/Model/TestSerialization/Source/TestInterpolators/InvalidInterpolations.cpp
black-vision-engine/bv-engine
85089d41bb22afeaa9de070646e12aa1777ecedf
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "Mathematics/Transform/MatTransform.h" #include "Utils/Comparators/ParamComparator.h" #include "Utils/Serialization/Serialize.h" #include "Framework/UseLoggerTests.h" #include "Mathematics/Interpolators/CompositeInterpolator.h" #include "Mathematics/Interpolators/CompositeInterpolator.inl" #include "Utils/Accessors/CompositeInterpolatorAccessor.h" using namespace bv; // *********************** // Xml contains more keys then expected numbers of interpolators. // Interpolators with curve_type set in xml should be created. TEST( Serialization_ParamValModel, Interpolators_MoreKeysThenInterpolators ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/NotEnoughInterpolators.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 4 ); EXPECT_EQ( actualEvals[ 2 ]->GetType(), EvaluatorType::ET_LINEAR ); EXPECT_EQ( actualEvals[ 3 ]->GetType(), EvaluatorType::ET_LINEAR ); } // *********************** // Keys are not ordered by time. This means, that someon manually modified scene xml. // There's no way to determine evaluators order. Best option is to leave order as it is. TEST( Serialization_ParamValModel, Interpolators_BadKeysOrder ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/BadKeysOrder.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); ASSERT_EQ( actual->GetNumKeys(), 4 ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 3 ); // In this xml all evaluators have different curve type. This helpes to determine their order. EXPECT_EQ( actualEvals[ 0 ]->GetCurveType(), CurveType::CT_BEZIER ); EXPECT_EQ( actualEvals[ 1 ]->GetCurveType(), CurveType::CT_POINT ); EXPECT_EQ( actualEvals[ 2 ]->GetCurveType(), CurveType::CT_LINEAR ); } // *********************** // More interpolators then needed for number of keys in xml. // Ignore all redundant interpolators. TEST( Serialization_ParamValModel, Interpolators_ToManyInterpolators ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/ToManyInterpolators.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 2 ); } // *********************** // There're no interpolators in xml. We should create default interpolators. TEST( Serialization_ParamValModel, Interpolators_LackOfInterpolatorsInXML ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/LackOfInterpolators.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 2 ); } // *********************** // There're no interpolations marker. We should create default interpolators. TEST( Serialization_ParamValModel, Interpolators_NoInterpolationsMarkerInXML ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/NoInterpolationsMarker.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 2 ); } // *********************** // Interpolator without type should be simply ignored. TEST( Serialization_ParamValModel, Interpolators_InterpolatorWithoutType ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/InterpolatorWithoutType.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 2 ); EXPECT_EQ( actualEvals[ 0 ]->GetCurveType(), CurveType::CT_BEZIER ); EXPECT_EQ( actualEvals[ 1 ]->GetCurveType(), CurveType::CT_LINEAR ); } // *********************** // Keys are set in the same time. Interpolator for the second key should be ignored. // Note: This is no ideal solution since we don't know what someone, who modified xml, actually meant. // But there's no way to determine, what interpolators should be used. TEST( Serialization_ParamValModel, Interpolators_DoubledKey ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/DoubledKeys.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 2 ); EXPECT_EQ( actualEvals[ 0 ]->GetCurveType(), CurveType::CT_POINT ); EXPECT_EQ( actualEvals[ 1 ]->GetCurveType(), CurveType::CT_QUARTIC_INOUT ); } // *********************** // One key has not parsing time value. Key will be ignored. Interpolations will be used // in order of occurance in file. // Note: It could be better solution to ignore interpolator the same way as in DoubledKey test. // I'm not sure if it's worth the work needed for this. TEST( Serialization_ParamValModel, Interpolators_NotParsingKey ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/NotParsingKeyTime.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 2 ); EXPECT_EQ( actualEvals[ 0 ]->GetCurveType(), CurveType::CT_POINT ); EXPECT_EQ( actualEvals[ 1 ]->GetCurveType(), CurveType::CT_LINEAR ); } // *********************** // NaN key time will be parsed correctly but keys shouldn't be added. // Behavior of interpolations should be equal to doubled keys. TEST( Serialization_ParamValModel, Interpolators_NaNKeyTime ) { auto actual = Deserialize< CompositeInterpolator< TimeType, float > >( "TestAssets/Serialization/Interpolators/NANKeyTime.xml", "interpolator" ); ASSERT_NE( actual, nullptr ); auto & actualEvals = TEST_ACCESSOR( CompositeInterpolator )::GetEvaluators( actual.get() ); ASSERT_EQ( actualEvals.size(), 2 ); EXPECT_EQ( actualEvals[ 0 ]->GetCurveType(), CurveType::CT_POINT ); EXPECT_EQ( actualEvals[ 1 ]->GetCurveType(), CurveType::CT_QUARTIC_INOUT ); ASSERT_EQ( actual->GetNumKeys(), 3 ); EXPECT_EQ( actual->GetKeys()[ 0 ].val, 3.0f ); EXPECT_EQ( actual->GetKeys()[ 1 ].val, 5.0f ); EXPECT_EQ( actual->GetKeys()[ 2 ].val, 7.0f ); }
44.213836
163
0.704125
[ "transform" ]
f9934a2dde802bdeec77a58dced2d491714f212d
784
hpp
C++
src/org/apache/poi/ss/usermodel/DataValidation_ErrorStyle.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/usermodel/DataValidation_ErrorStyle.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/usermodel/DataValidation_ErrorStyle.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/usermodel/DataValidation.java #pragma once #include <fwd-POI.hpp> #include <org/apache/poi/ss/usermodel/fwd-POI.hpp> #include <java/lang/Object.hpp> struct default_init_tag; class poi::ss::usermodel::DataValidation_ErrorStyle final : public ::java::lang::Object { public: typedef ::java::lang::Object super; static constexpr int32_t STOP { int32_t(0) }; static constexpr int32_t WARNING { int32_t(1) }; static constexpr int32_t INFO { int32_t(2) }; // Generated DataValidation_ErrorStyle(); protected: DataValidation_ErrorStyle(const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: virtual ::java::lang::Class* getClass0(); friend class DataValidation; };
23.058824
75
0.71301
[ "object" ]
f997e12b2437b3367d80626ae3e68f217378da75
2,276
cpp
C++
src/metrics/main.cpp
DataDog/dd-native-metrics-js
1970b459913faf6415a11386edb7bc9c2a063e8a
[ "Apache-2.0" ]
1
2021-08-19T18:00:11.000Z
2021-08-19T18:00:11.000Z
src/metrics/main.cpp
DataDog/dd-native-metrics-js
1970b459913faf6415a11386edb7bc9c2a063e8a
[ "Apache-2.0" ]
null
null
null
src/metrics/main.cpp
DataDog/dd-native-metrics-js
1970b459913faf6415a11386edb7bc9c2a063e8a
[ "Apache-2.0" ]
null
null
null
#include "EventLoop.hpp" #include "Object.hpp" namespace datadog { namespace { void before_gc(v8::Isolate* isolate, v8::GCType type, v8::GCCallbackFlags flags, void* data) { reinterpret_cast<EventLoop*>(data)->gc.before(type); } void after_gc(v8::Isolate* isolate, v8::GCType type, v8::GCCallbackFlags flags, void* data) { reinterpret_cast<EventLoop*>(data)->gc.after(type); } static void start(const v8::FunctionCallbackInfo<v8::Value>& info) { EventLoop* data = reinterpret_cast<EventLoop*>(info.Data().As<v8::External>()->Value()); v8::Isolate* isolate = v8::Isolate::GetCurrent(); data->enable(); isolate->AddGCPrologueCallback(before_gc, data); isolate->AddGCEpilogueCallback(after_gc, data); } static void stop(const v8::FunctionCallbackInfo<v8::Value>& info) { EventLoop* data = reinterpret_cast<EventLoop*>(info.Data().As<v8::External>()->Value()); v8::Isolate* isolate = v8::Isolate::GetCurrent(); data->disable(); isolate->RemoveGCPrologueCallback(before_gc, data); isolate->RemoveGCEpilogueCallback(after_gc, data); } static void stats(const v8::FunctionCallbackInfo<v8::Value>& info) { EventLoop* data = reinterpret_cast<EventLoop*>(info.Data().As<v8::External>()->Value()); Object obj; data->inject(obj); data->gc.inject(obj); data->process.inject(obj); data->heap.inject(obj); info.GetReturnValue().Set(obj.to_json()); } } NODE_MODULE_INIT() { v8::Isolate* isolate = context->GetIsolate(); EventLoop* data = new EventLoop(isolate); v8::Local<v8::External> external = v8::External::New(isolate, data); exports->Set( context, Nan::New("start").ToLocalChecked(), v8::FunctionTemplate::New(isolate, start, external)->GetFunction(context).ToLocalChecked() ).FromJust(); exports->Set( context, Nan::New("stop").ToLocalChecked(), v8::FunctionTemplate::New(isolate, stop, external)->GetFunction(context).ToLocalChecked() ).FromJust(); exports->Set( context, Nan::New("stats").ToLocalChecked(), v8::FunctionTemplate::New(isolate, stats, external)->GetFunction(context).ToLocalChecked() ).FromJust(); } }
32.056338
98
0.654657
[ "object" ]
f9990e79bb90c4edf57da4184a5839bc4139fcb8
3,974
cpp
C++
reference/raytracer1/testapp.cpp
chensibaba/CG_proj1
4fb65f87ab873babc41c7817d45925aa3e59f094
[ "MIT" ]
2
2019-04-12T14:44:00.000Z
2021-12-12T18:29:14.000Z
reference/raytracer1/testapp.cpp
chensibaba/CG_proj1
4fb65f87ab873babc41c7817d45925aa3e59f094
[ "MIT" ]
null
null
null
reference/raytracer1/testapp.cpp
chensibaba/CG_proj1
4fb65f87ab873babc41c7817d45925aa3e59f094
[ "MIT" ]
null
null
null
// Don't look here. The interesting stuff is elsewhere. #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <stdlib.h> #include "common.h" #include "raytracer.h" #include "scene.h" #include "surface.h" #define SCRWIDTH 800 #define SCRHEIGHT 600 static WNDCLASS wc; static HWND wnd; static char bitmapbuffer[sizeof( BITMAPINFO ) + 16]; static BITMAPINFO* bh; HDC window_hdc; Raytracer::Surface* surface = 0; Pixel* buffer = 0; Raytracer::Engine* tracer = 0; void DrawWindow(); static LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam ) { int result = 0, keycode = 0; switch (message) { case WM_PAINT: if (!buffer) break; StretchDIBits( window_hdc, 0, 0, SCRWIDTH, SCRHEIGHT, 0, 0, SCRWIDTH, SCRHEIGHT, buffer, bh, DIB_RGB_COLORS, SRCCOPY ); ValidateRect( wnd, NULL ); break; case WM_KEYDOWN: if ((wParam & 0xFF) != 27) break; case WM_CLOSE: ReleaseDC( wnd, window_hdc ); DestroyWindow( wnd ); SystemParametersInfo( SPI_SETSCREENSAVEACTIVE, 1, 0, 0 ); ExitProcess( 0 ); break; default: result = DefWindowProc(hWnd,message,wParam,lParam); } return result; } int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { RECT rect; int cc; wc.style = CS_OWNDC | CS_VREDRAW | CS_HREDRAW; wc.lpfnWndProc = WndProc; wc.cbClsExtra = wc.cbWndExtra = 0; wc.hInstance = 0; wc.hIcon = NULL; wc.hCursor = LoadCursor(0,IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "raytracer"; if (!RegisterClass(&wc)) return FALSE; rect.left = rect.top = 0; rect.right = SCRWIDTH, rect.bottom = SCRHEIGHT; AdjustWindowRect( &rect, WS_POPUP|WS_SYSMENU|WS_CAPTION, 0 ); rect.right -= rect.left, rect.bottom -= rect.top; wnd = CreateWindowEx( 0, "raytracer", "raytracer", WS_OVERLAPPEDWINDOW & ~WS_MAXIMIZEBOX & ~WS_THICKFRAME, CW_USEDEFAULT, CW_USEDEFAULT, rect.right, rect.bottom, 0, 0, 0, 0 ); ShowWindow(wnd,SW_NORMAL); for ( cc = 0; cc < sizeof( BITMAPINFOHEADER ) + 16; cc++ ) bitmapbuffer[cc] = 0; bh = (BITMAPINFO *)&bitmapbuffer; bh->bmiHeader.biSize = sizeof( BITMAPINFOHEADER ); bh->bmiHeader.biPlanes = 1; bh->bmiHeader.biBitCount = 32; bh->bmiHeader.biCompression = BI_BITFIELDS; bh->bmiHeader.biWidth = SCRWIDTH, bh->bmiHeader.biHeight = -SCRHEIGHT; ((unsigned long*)bh->bmiColors)[0] = 255 << 16; ((unsigned long*)bh->bmiColors)[1] = 255 << 8; ((unsigned long*)bh->bmiColors)[2] = 255; window_hdc = GetDC(wnd); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, 0, 0, 0); // prepare output canvas surface = new Raytracer::Surface( SCRWIDTH, SCRHEIGHT ); buffer = surface->GetBuffer(); surface->Clear( 0 ); surface->InitCharset(); surface->Print( "timings:", 2, 2, 0xffffffff ); // prepare renderer tracer = new Raytracer::Engine(); tracer->GetScene()->InitScene(); tracer->SetTarget( surface->GetBuffer(), SCRWIDTH, SCRHEIGHT ); int tpos = 60; // go while (1) { int fstart = GetTickCount(); tracer->InitRender(); // while (!tracer->RenderTiles()) DrawWindow(); while (!tracer->Render()) DrawWindow(); int ftime = GetTickCount() - fstart; char t[] = "00:00.000"; t[6] = (ftime / 100) % 10 + '0'; t[7] = (ftime / 10) % 10 + '0'; t[8] = (ftime % 10) + '0'; int secs = (ftime / 1000) % 60; int mins = (ftime / 60000) % 100; t[3] = ((secs / 10) % 10) + '0'; t[4] = (secs % 10) + '0'; t[1] = (mins % 10) + '0'; t[0] = ((mins / 10) % 10) + '0'; surface->Print( t, tpos, 2, 0xffffffff ); tpos += 100; } return 1; } void DrawWindow() { MSG message; HACCEL haccel = 0; InvalidateRect( wnd,NULL,TRUE ); SendMessage( wnd, WM_PAINT, 0, 0 ); while (PeekMessage( &message, wnd, 0, 0, PM_REMOVE )) { if (TranslateAccelerator( wnd, haccel, &message ) == 0) { TranslateMessage( &message ); DispatchMessage( &message ); } } Sleep( 0 ); }
29.879699
122
0.649975
[ "render" ]
f99d75e511722e6693110badaf42245cfe5f9d63
1,402
cpp
C++
codeforces/F - Maximum White Subtree/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/F - Maximum White Subtree/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/F - Maximum White Subtree/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: * kzvd4729 created: Mar/12/2020 20:16 * solution_verdict: Accepted language: GNU C++14 * run_time: 280 ms memory_used: 32900 KB * problem: https://codeforces.com/contest/1324/problem/F ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int cl[N+2],sub[N+2],ans[N+2]; vector<int>adj[N+2]; void dfs(int node,int par) { sub[node]=1; if(!cl[node])sub[node]=-1; for(auto x:adj[node]) { if(x==par)continue; dfs(x,node);sub[node]+=max(0,sub[x]); } } void dds(int node,int par,int ad) { ad=max(ad,0); //cout<<node<<" ** "<<ad<<endl; ans[node]=sub[node]+ad; for(auto x:adj[node]) { if(x==par)continue; dds(x,node,ad+sub[node]-max(0,sub[x])); } } int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n; for(int i=1;i<=n;i++)cin>>cl[i]; for(int i=1;i<n;i++) { int u,v;cin>>u>>v; adj[u].push_back(v);adj[v].push_back(u); } dfs(1,-1);dds(1,-1,0); for(int i=1;i<=n;i++)cout<<ans[i]<<" "; cout<<endl; return 0; }
29.208333
111
0.435806
[ "vector" ]
f99ec2b0a66dd817ee875bed931755ac34a8942e
832
cpp
C++
2021/June/Circuits/a-binary-palindrome.cpp
Sky-Nik/HackerEarth
0e7dfea2c654571d5f816a80796c0db50a9f706c
[ "MIT" ]
null
null
null
2021/June/Circuits/a-binary-palindrome.cpp
Sky-Nik/HackerEarth
0e7dfea2c654571d5f816a80796c0db50a9f706c
[ "MIT" ]
null
null
null
2021/June/Circuits/a-binary-palindrome.cpp
Sky-Nik/HackerEarth
0e7dfea2c654571d5f816a80796c0db50a9f706c
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<int64_t> a = {0, 1}; void solve() { int64_t n; cin >> n; int64_t m = n; int i = distance(a.begin(), lower_bound(a.begin(), a.end(), n)); if (i) { m = min(m, n - a[i - 1]); } if (i < int(a.size())) { m = min(m, a[i] - n); } cout << m << "\n"; } int main() { ios::sync_with_stdio(0),cin.tie(0),cout.tie(0); int h = 16; for (int k = 0; k <= h; ++k) { for (int64_t m = 1; m < (1 << k); m += 2) { int64_t r = 0; for (int i = 0; i < k; ++i) { r <<= 1; if (m & (1 << i)) { r |= 1; } } a.push_back((r << k) | m); a.push_back((r << (k + 1)) | m); a.push_back((r << (k + 1)) | (1 << k) | m); } } sort(a.begin(), a.end()); int t; cin >> t; while (t--) solve(); return 0; }
22.486486
66
0.41226
[ "vector" ]
f9a3793787fe2fd9121502d65ec3f2d1c04ad389
586
cpp
C++
Environment/GameWindow.cpp
willshi88/Reversi-Game
9dae6c48b7e7694619eee51eb72cc16099e27007
[ "MIT" ]
null
null
null
Environment/GameWindow.cpp
willshi88/Reversi-Game
9dae6c48b7e7694619eee51eb72cc16099e27007
[ "MIT" ]
null
null
null
Environment/GameWindow.cpp
willshi88/Reversi-Game
9dae6c48b7e7694619eee51eb72cc16099e27007
[ "MIT" ]
null
null
null
#include "GameWindow.h" #include "GamePanel.h" namespace game { GameWindow::GameWindow() { GamePanel *gp = new GamePanel(); this->add(gp); this->setTitle(L"Reversi v0.1"); this->setDefaultCloseOperation(WindowConstants::EXIT_ON_CLOSE); this->pack(); this->setVisible(true); //this.setSize(500,500); //JAVA TO C++ CONVERTER TODO TASK: A 'delete gp' statement was not added since gp was passed to a method or constructor. Handle memory management manually. } void GameWindow::main(std::vector<std::wstring> &args) { new GameWindow(); } }
23.44
156
0.677474
[ "vector" ]
f9a75c4acdb9fada0d7f284b488b13896929448c
10,425
cpp
C++
modules/web/httpserver.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
16
2021-07-14T23:32:31.000Z
2022-03-24T16:25:15.000Z
modules/web/httpserver.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-20T20:39:47.000Z
2021-09-16T20:57:59.000Z
modules/web/httpserver.cpp
spiralgenetics/biograph
33c78278ce673e885f38435384f9578bfbf9cdb8
[ "BSD-2-Clause" ]
9
2021-07-15T19:38:35.000Z
2022-01-31T19:24:56.000Z
#include <assert.h> #include <string.h> #include <sys/prctl.h> #include <algorithm> #include <iomanip> #include <iostream> #include <utility> #include <vector> #include "Poco/Net/AcceptCertificateHandler.h" #include "Poco/Net/Context.h" #include "Poco/Net/HTTPBasicCredentials.h" #include "Poco/Net/HTTPRequestHandler.h" #include "Poco/Net/HTTPRequestHandlerFactory.h" #include "Poco/Net/HTTPResponse.h" #include "Poco/Net/HTTPServer.h" #include "Poco/Net/HTTPServerRequest.h" #include "Poco/Net/HTTPServerResponse.h" #include "Poco/Net/NetSSL.h" #include "Poco/Net/SSLManager.h" #include "Poco/Net/SecureServerSocket.h" #include "Poco/Net/ServerSocket.h" #include "Poco/URI.h" #include "Poco/Util/ServerApplication.h" #include "base/base.h" #include "modules/io/config.h" #include "modules/io/hexdump.h" #include "modules/io/log.h" #include "modules/io/utils.h" #include "modules/web/httpserver.h" using namespace Poco::Net; using namespace Poco::Util; using namespace Poco; std::mutex http_server::g_mutex; http_server* http_server::g_server = nullptr; class RequestHandler : public HTTPRequestHandler { public: RequestHandler(http_server* srv) : m_srv(srv) {} void handleRequest(HTTPServerRequest& request, HTTPServerResponse& response) override { http_request req(request, response); m_srv->handle(req); } private: http_server* m_srv; }; class RequestHandlerFactory : public HTTPRequestHandlerFactory { public: RequestHandlerFactory(http_server* srv) : m_srv(srv) {} HTTPRequestHandler* createRequestHandler(const HTTPServerRequest& request) override { return new RequestHandler(m_srv); } private: http_server* m_srv; }; int connection::base_read(char* buf, size_t len) { std::istream& istr = m_req.stream(); auto ret = 0; // Read until len or EOF for (size_t i = 0; i < len; i++) { auto c = istr.get(); if (c == EOF) { break; } buf[i] = c; ret++; } if (CONF(log_http_traffic)) { SPLOG_P(LOG_DEBUG, "connection::base_read> %d bytes", ret); if (ret > 0) { std::string chunk(buf, std::min(ret, 100)); auto dump = hexdump(chunk); SPLOG_P(LOG_DEBUG, "\n%s", dump.c_str()); } } return ret; } void connection::finish_headers() { CHECK(!m_send); m_send = &m_resp.send(); } int connection::base_write(const char* buf, int len) { CHECK(m_send); m_send->write(buf, len); if (CONF(log_http_traffic)) { SPLOG_P(LOG_DEBUG, "connection::base_write> %d bytes", len); if (len > 0) { std::string chunk(buf, std::min(len, 100)); auto dump = hexdump(chunk); SPLOG_P(LOG_DEBUG, "\n%s", dump.c_str()); } } return len; } std::string http_request::get_header(const std::string& name) const { if (m_connection.m_req.has(name)) { return m_connection.m_req.get(name); } throw io_exception("No such header: " + name); } std::string http_request::get_header(const std::string& name, const std::string& def) const { return (m_connection.m_req.get(name, def)); } void http_request::for_headers( const std::function<void(const std::string&, const std::string&)>& write) const { NameValueCollection& headers = m_connection.m_req; for (const auto& hdr : headers) { write(hdr.first, hdr.second); } } std::string http_request::find_variable(const std::string& name, const std::function<std::string()>& no_query_string, const std::function<std::string()>& var_not_found) { if (m_query_variables.empty()) { return no_query_string(); } auto it = m_query_variables.find(name); if (it != m_query_variables.cend()) { return (*it).second; } return var_not_found(); } std::string http_request::get_variable(const std::string& name) { return find_variable( name, []() -> std::string { throw variable_does_not_exist("No query string"); }, [&name]() -> std::string { throw variable_does_not_exist(printstring("Failed to get variable %s", name.c_str())); }); } std::string http_request::get_variable(const std::string& name, const std::string& def) { auto ret_def = [&def] { return def; }; return find_variable(name, ret_def, ret_def); } std::string http_request::get_query() const { return m_query_str; } void http_request::send_continue() { m_connection.m_resp.sendContinue(); } void http_request::send_status(int code, const std::string& message) { m_connection.m_resp.setStatusAndReason(HTTPResponse::HTTPStatus(code), message); } void http_request::send_header(const std::string& header, const std::string& value) { // LOG("Response header: %s: %s", header.c_str(), value.c_str()); m_connection.m_resp.set(header, value); } void http_request::finish_headers() { m_connection.finish_headers(); } void http_request::finish_body(const std::string& body) { m_connection.write(body.c_str(), body.size()); } http_request::http_request(HTTPServerRequest& req, HTTPServerResponse& resp) : m_connection(req, resp) { Poco::URI uri(req.getURI()); m_uri = uri.getPath(); m_query_str = uri.getQuery(); for (const auto& param : uri.getQueryParameters()) { m_query_variables[param.first] = param.second; } // Strip out any double slashes in the URI. // TODO(nils): Figure out why we're generating double slashes in the first // place and remove this kludgery. for (;;) { auto pos = m_uri.find("//"); if (pos == std::string::npos) { break; } m_uri = m_uri.substr(0, pos) + m_uri.substr(pos + 1); } } bool http_request::get_auth(std::string& scheme, std::string& user, std::string& password) { bool has_auth = m_connection.m_req.hasCredentials(); std::string encoded; if (has_auth) { m_connection.m_req.getCredentials(scheme, encoded); HTTPBasicCredentials creds(m_connection.m_req); user = creds.getUsername(); password = creds.getPassword(); } return has_auth; } namespace { static Context::Ptr get_ssl_context() { static bool ssl_initted = false; static Context::Ptr g_ssl_context; if (ssl_initted) { return g_ssl_context; } initializeSSL(); SharedPtr<InvalidCertificateHandler> ptrCert; Context::Ptr ptrContext; g_ssl_context = new Context(Context::SERVER_USE, CONF_S(pem_file), CONF_S(ssl_certificates_chain), "" /* no CA location specified; use default instead */, Context::VERIFY_NONE, 9, true /* load default CAs */, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); ptrCert = new AcceptCertificateHandler(false); SSLManager::instance().initializeServer(0, ptrCert, g_ssl_context); ssl_initted = true; return g_ssl_context; } } // namespace http_server& http_server::get() { std::lock_guard<std::mutex> l(g_mutex); if (g_server == nullptr) { g_server = new http_server(); } return *g_server; } void http_server::register_handler(handler& handler, const std::string& uri_regex, const std::string& method_regex) { std::lock_guard<std::mutex> l(g_mutex); m_handlers.emplace_back(handler, uri_regex, method_regex); } void http_server::start(const bind_list_t& bl, const std::string& pem_path, const std::string& ssl_certificates_chain_path) { try { std::lock_guard<std::mutex> l(g_mutex); CHECK(!bl.empty()); for (size_t i = 0; i < bl.size(); i++) { auto port = bl[i].port; std::string ip = bl[i].ip; if (ip.empty()) { ip = "127.0.0.1"; } ServerSocket sock; if (bl[i].ssl) { sock = SecureServerSocket(SocketAddress(ip, port), 64, get_ssl_context()); } else { sock = ServerSocket(SocketAddress(ip, port)); } auto new_http = new HTTPServer(new RequestHandlerFactory(this), sock, new HTTPServerParams); new_http->start(); m_servers.emplace_back(new_http); SPLOG("Server listening on %s port %d%s", ip.c_str(), port, bl[i].ssl ? " (ssl)" : ""); } } catch (const Poco::Exception& poco_except) { SPLOG("Got error starting server: %s", poco_except.message().c_str()); throw std::runtime_error("Could not start server: " + poco_except.message()); } } void http_server::stop() { std::lock_guard<std::mutex> l(g_mutex); SPLOG("Server shutting down"); for (const auto& srv : m_servers) { srv->stop(); } m_servers.clear(); } void http_server::handle(http_request& request) { if (CONF(log_http_requests)) { SPLOG("%s -> %s %s", request.peer().c_str(), request.method().c_str(), request.uri().c_str()); } for (auto& handler : m_handlers) { if (handler.match(request)) { request.conn().mark_valid(); handler.m_handler.handle(request); return; } } SPLOG("HTTP error, code 404: Not Found -> %s", request.peer().c_str()); request.send_status(404, "Not Found"); request.send_header("Content-Type", "text/plain"); request.finish_headers(); request.conn().print( "Please use biograph to access this service. https://www.spiralgenetics.com/"); } http_server::handler_reg::handler_reg(handler& handler, const std::string& uri_regex, const std::string& method_regex) : m_handler(handler) { try { uri = boost::regex(uri_regex, boost::regex_constants::extended); method = boost::regex(method_regex, boost::regex_constants::extended); } catch (const boost::regex_error& err) { throw io_exception("Invalid regex"); } } bool http_server::handler_reg::match(http_request& request) { return boost::regex_match(request.uri(), request.m_uri_match, uri) && boost::regex_match(request.m_connection.m_req.getMethod(), request.m_method_match, method); } struct error_response_json { TRANSFER_OBJECT { VERSION(0); FIELD(success); FIELD(error); FIELD(status); } bool success = false; std::string error; unsigned status = 500; }; void error_response(http_request& request, unsigned code, const std::string& msg) { SPLOG("HTTP error, code %d: %s -> %s", code, msg.c_str(), request.peer().c_str()); request.send_status(code, msg); request.send_header("Content-Type", "application/json"); error_response_json json; json.error = msg; json.status = code; auto body = json_serialize(json); request.send_header("Content-Length", printstring("%ld", body.size())); request.finish_headers(); request.conn().write(body.data(), body.size()); }
30.130058
100
0.671463
[ "vector" ]
3908cbef869ac7d4b6ae36810f2a942fed64ddbd
6,124
cpp
C++
src/confirmed.cpp
tarhan/AMQP-CPP
98a43d8e5b939b06fa86daac8599c6f0233763d6
[ "Apache-2.0" ]
null
null
null
src/confirmed.cpp
tarhan/AMQP-CPP
98a43d8e5b939b06fa86daac8599c6f0233763d6
[ "Apache-2.0" ]
null
null
null
src/confirmed.cpp
tarhan/AMQP-CPP
98a43d8e5b939b06fa86daac8599c6f0233763d6
[ "Apache-2.0" ]
null
null
null
/** * Confirmed.cpp * * Implementation for Confirmed class. * * @author Michael van der Werve <michael.vanderwerve@mailerq.com> * @copyright 2020 Copernica BV */ /** * Includes */ #include "includes.h" /** * Begin of namespaces */ namespace AMQP { /** * Called when the deliverytag(s) are acked * @param deliveryTag * @param multiple */ void Confirmed::onAck(uint64_t deliveryTag, bool multiple) { // monitor the object, watching for destruction since these ack/nack handlers // could destruct the object Monitor monitor(this); // single element is simple if (!multiple) { // find the element auto iter = _handlers.find(deliveryTag); // we did not find it (this should not be possible, unless somebody explicitly called) // the base-class publish methods for some reason. if (iter == _handlers.end()) return Throttle::onAck(deliveryTag, multiple); // call the ack handler iter->second->reportAck(); // if the monitor is no longer valid, we stop (we're done) if (!monitor) return; // erase it from the map _handlers.erase(iter); } // do multiple at once else { // find the last element, inclusive auto upper = _handlers.upper_bound(deliveryTag); // call the handlers for (auto iter = _handlers.begin(); iter != upper; iter++) { // call the handler iter->second->reportAck(); // if we were destructed in the meantime, we leap out if (!monitor) return; } // erase all acknowledged items _handlers.erase(_handlers.begin(), upper); } // make sure the object is still valid if (!monitor) return; // call base handler, will advance on the throttle if needed. we call this _after_ we're // done processing the callbacks, since one of the callbacks might close the channel, or publish // more stuff. additionally, if it does destroy the channel, we are doing a lot of extra publishing // for nothing. also, we call some extra handlers, and otherwise we might get onAcked after onClosed Throttle::onAck(deliveryTag, multiple); } /** * Called when the deliverytag(s) are nacked * @param deliveryTag * @param multiple */ void Confirmed::onNack(uint64_t deliveryTag, bool multiple) { // monitor the object, watching for destruction since these ack/nack handlers // could destruct the object Monitor monitor(this); // single element is simple if (!multiple) { // find the element auto iter = _handlers.find(deliveryTag); // we did not find it (this should not be possible, unless somebody explicitly called) // the base-class publish methods for some reason. if (iter == _handlers.end()) return Throttle::onNack(deliveryTag, multiple); // call the ack handler iter->second->reportNack(); // if the monitor is no longer valid, we stop (we're done) if (!monitor) return; // erase it from the map _handlers.erase(iter); } // nack multiple elements else { // find the last element, inclusive auto upper = _handlers.upper_bound(deliveryTag); // call the handlers for (auto iter = _handlers.begin(); iter != upper; iter++) { // call the handler iter->second->reportNack(); // if we were destructed in the meantime, we leap out if (!monitor) return; } // erase all acknowledged items _handlers.erase(_handlers.begin(), upper); } // make sure the object is still valid if (!monitor) return; // call base handler, will advance on the throttle if needed. we call this _after_ we're // done processing the callbacks, since one of the callbacks might close the channel, or publish // more stuff. additionally, if it does destroy the channel, we are doing a lot of extra publishing // for nothing. also, we call some extra handlers, and otherwise we might get onAcked after onClosed Throttle::onNack(deliveryTag, multiple); } /** * Method that is called to report an error * @param message */ void Confirmed::reportError(const char *message) { // monitor the object, watching for destruction since these ack/nack handlers // could destruct the object Monitor monitor(this); // move the handlers out auto handlers = std::move(_handlers); // iterate over all the messages // call the handlers for (const auto &iter : handlers) { // call the handler iter.second->reportError(message); // if we were destructed in the meantime, we leap out if (!monitor) return; } // if the monitor is no longer valid, leap out if (!monitor) return; // call base class to let it handle the errors Throttle::reportError(message); } /** * Publish a message to an exchange. See amqpcpp/channel.h for more details on the flags. * Delays actual publishing depending on the publisher confirms sent by RabbitMQ. * * @param exchange the exchange to publish to * @param routingkey the routing key * @param envelope the full envelope to send * @param message the message to send * @param size size of the message * @param flags optional flags */ DeferredConfirmedPublish &Confirmed::publish(const std::string &exchange, const std::string &routingKey, const Envelope &envelope, int flags) { // copy the current identifier, this will be the ID that will come back auto current = _current; // publish the entire thing, and remember if it failed at any point bool failed = !Throttle::publish(exchange, routingKey, envelope, flags); // create the open auto handler = std::make_shared<DeferredConfirmedPublish>(failed); // add it to the open handlers _handlers[current] = handler; // return the dereferenced handler return *handler; } /** * End of namespaces */ }
29.728155
141
0.64484
[ "object" ]
390dffbfa356892815377c76b237edcd87d82b92
2,094
hpp
C++
include/tori/core/string.hpp
mocabe/Neco-lang-v2
a30075802492fa5c2d1725a2ba0e3e06dde4ce13
[ "MIT" ]
null
null
null
include/tori/core/string.hpp
mocabe/Neco-lang-v2
a30075802492fa5c2d1725a2ba0e3e06dde4ce13
[ "MIT" ]
7
2019-02-11T13:50:25.000Z
2019-10-28T15:39:18.000Z
include/tori/core/string.hpp
mocabe/tori
a30075802492fa5c2d1725a2ba0e3e06dde4ce13
[ "MIT" ]
null
null
null
// Copyright (c) 2018-2019 mocabe(https://github.com/mocabe) // This code is licensed under MIT license. #pragma once /// \file String #if !defined(TORI_NO_LOCAL_INCLUDE) # include "type_gen.hpp" #endif #include <string> #include <cstring> #include <string> // utf8 macro #define utf8(Str) ::TORI_NS::detail::to_u8(u8##Str) namespace TORI_NS::detail { class string_object_value { // TODO: support char8_t in C++20 public: string_object_value(nullptr_t) = delete; string_object_value() { m_ptr = new char[1] {'\0'}; } string_object_value(const char* str) { size_t s = std::strlen(str); auto buff = new char[s + 1]; std::copy(str, str + s + 1, buff); m_ptr = buff; } string_object_value(const std::string& str) { auto buff = new char[str.size() + 1]; std::copy(str.c_str(), str.c_str() + str.size() + 1, buff); m_ptr = buff; } string_object_value(const string_object_value& other) { auto len = std::strlen(other.c_str()); auto buff = new char[len + 1]; std::copy(other.m_ptr, other.m_ptr + len + 1, buff); m_ptr = buff; } string_object_value(string_object_value&& other) { m_ptr = other.m_ptr; other.m_ptr = nullptr; } ~string_object_value() noexcept { delete[] m_ptr; } /// c_str [[nodiscard]] const char* c_str() const noexcept { return reinterpret_cast<const char*>(m_ptr); } private: char* m_ptr; }; namespace interface { /// UTF-8 String object. /// Does not guarantee anything about encoding. User must ensure /// input byte sequence is null(`0x00`)-terminated UTF-8 string. using String = Box<string_object_value>; namespace literals { /// String object literal [[nodiscard]] inline object_ptr<String> operator"" _S(const char* str, size_t) { return make_object<String>(str); } } // namespace literals } // namespace interface } // namespace TORI_NS::detail // String TORI_DECL_TYPE(String)
20.94
68
0.614613
[ "object" ]
391198fe3b4a5cea0e131734805c983c63136f1c
2,900
cpp
C++
src/devices/cpu/threadPool.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
src/devices/cpu/threadPool.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
src/devices/cpu/threadPool.cpp
enerc/zsearch
60cdcd245b66d14fe4e2be1d26eb2b1877d4b098
[ "Apache-2.0" ]
null
null
null
#include "threadPool.hpp" #include <unistd.h> #include "../../common/log.hpp" #include "../../queries/model/root.hpp" using namespace queries::model; using namespace std; namespace devices { ThreadPool* ThreadPoolManager::instance = nullptr; static std::vector<sem_t> sems; static std::vector<ThreadParam> params; static volatile uint64_t *active; void * ShutdownTask(void* threadData) { pthread_exit(nullptr); } void *ThreadFunc(void* threadData) { const uint32_t i = *(uint32_t*)threadData; while (true) { sem_wait(&sems[i]); switch (params[i].action) { case actionExecShutdown: (params[i].func)(&params[i]); break; case actionExecShaderOnCpu: { RootModel *b = (RootModel*)params[i].thisClass; b->addResultCount(b->execShaderThreadOnCpu(params[i].me,params[i].nbThreads)); break; } } active[i] = false; } return (void*) nullptr; } ThreadPool::ThreadPool(uint32_t nbThreads) { threads.resize(nbThreads); params.resize(nbThreads); active = (uint64_t*)malloc(nbThreads*sizeof(uint64_t)); sems.resize(nbThreads); threadIds.resize(nbThreads); for (int i=0; i< threads.size(); i++) { active[i] = false; int s = sem_init(&sems[i],PTHREAD_PROCESS_SHARED,0); if (s != 0) { Log::error("Failed to create ThreadPool semaphore"); } threadIds[i] = i; } for (int i=0; i< threadIds.size(); i++) { pthread_t t; pthread_create(&t, nullptr, ThreadFunc, &threadIds.at(i)); threads[i]= t; cpu_set_t set; CPU_ZERO( &set ); CPU_SET( i, &set ); pthread_setaffinity_np(t, sizeof(&set), &set); } } ThreadPool::~ThreadPool() { free((void *) active); } void ThreadPool::addTask(const ThreadParam &p) { while (true) { // Look for an available node for (int i=0; i< threads.size(); i++) { if (!active[i]) { active[i] = true; params[i] = p; sem_post(&sems[i]); return; } } // all threads busy usleep(1000L); } } void ThreadPool::wait() { bool working = true; while (working) { working = false; for (int i=0; i< threads.size(); i++) { working |= active[i]; } if (working) { usleep(1000L); } } } void ThreadPool::shutdown() { ThreadParam p; p.func = ShutdownTask; p.action = actionExecShutdown; for (int i=0; i< threadIds.size(); i++) { params[i] = p; sem_post(&sems[i]); } for (int i=0; i< threadIds.size(); i++) { void* status; pthread_join(threads[i],&status); } threads.clear(); sems.clear(); params.clear(); } }
24.576271
94
0.546207
[ "vector", "model" ]
391294f523c1231ea3c0ef94bb1aa09e805ea067
12,683
hpp
C++
src/common/lsutil/include/public/ls2-helpers/servicepoint.hpp
webosose/com.webos.service.videooutput
119a0df4272259ffc72a05489f6ca8054eca0ae3
[ "Apache-2.0" ]
2
2019-05-06T05:27:42.000Z
2020-06-12T02:23:32.000Z
src/common/lsutil/include/public/ls2-helpers/servicepoint.hpp
webosose/com.webos.service.videooutput
119a0df4272259ffc72a05489f6ca8054eca0ae3
[ "Apache-2.0" ]
null
null
null
src/common/lsutil/include/public/ls2-helpers/servicepoint.hpp
webosose/com.webos.service.videooutput
119a0df4272259ffc72a05489f6ca8054eca0ae3
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2016-2019 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 #pragma once #include <string> #include <vector> #include <algorithm> #include <luna-service2/lunaservice.hpp> #include "jsonrequest.hpp" #include "jsonresponse.hpp" namespace LSHelpers { /** * @brief Luna client object. Manages lifetime of a collection of method handlers and ongoing luna calls. * Tracks ongoing calls and cancels them if the ServicePoint is destroyed. * There can be multiple ServicePoints per luna handle. * * Recommended usage is to have a single ServicePoint for each C++ class with handler methods. * That way all pending calls and subscriptions will be stopped on object destruction. * Ensuring no access after free conditions. * * Multithreading: * * The setup functions - registerSignal, registerMethod are not thread safe. * The call, subscribe, cancelCall methods are thread safe. * * The method handler and response callback methods are executed in the context of the event loop * used by luna handle regardless of the thread it was called from. * * Example: * @code class MyClass { public: MyClass(LS::Handle* handle):mLunaClient(handle) { mLunaClient.registerMethod("/", "myMethod", this, &MyClass::handleMyMethod); mLunaClient.callMultiReply( "luna://com.webos.service.stuff/getStatus", pbnjson::JObject {{"subscribe", true}}, this, &MyClass::getStatusResponse); } pbnjson::JValue MyClass::handleMyMethod(JsonRequest& request) { std::string data; request.get("data", data); request.finishParseOrThrow(); if (data.length() == 0) { return ErrorResponse(104, "Data is empty"); } //Do something with data... return true; } void getStatusResponse(LunaResponse& response) { std::string status; std::string payload; response.get("status",status); response.get("payload",payload).optional(); response.finishParseOrThrow(); if (status == "ping") { mLunaClient.callOneReply( "luna://com.webos.service.stuff/pong", pbnjson::JObject {{"payload", payload}}, nullptr); } } void doStuff(const std::string& data) { mLunaClient.callOneReply( "luna://com.webos.service.stuff/doStuff", pbnjson::JObject {{"data", data}}, nullptr); } void doStuffAndReactToResult(const std::string& data) { mLunaClient.callOneReply( "luna://com.webos.service.stuff/doStuff", pbnjson::JObject {{"data", data}}, [](LSHelpers::JsonResponse& response) { if (response.isSuccess()) { // Do suff on succcess } }); } ServicePoint mLunaClient; }; * @endcode */ class ServicePoint { public: explicit ServicePoint(LS::Handle* handle); ~ServicePoint(); /** * Not copyable. */ ServicePoint(const ServicePoint&) = delete; ServicePoint& operator=(const ServicePoint&) = delete; inline LS::Handle* getHandle() { return this->mHandle; } /** * Registers a new method on the bus. * Helper method that accepts a object pointer and method pointer. * @param category category name. For example "/" * @param methodName the method name * @param handler handler method or lambda to call. * @param schema json schema to use. If set, will validate the request against the schema before calling the handler method. * @throws std::logic_error if a method is already registered with specified category and name. */ void registerMethod(const std::string& category, const std::string& methodName, const JsonRequest::Handler& handler, const pbnjson::JSchema& schema = pbnjson::JSchema::AllSchema()); /** * Helper method that accepts a object pointer and method pointer. * Example: @code lunaService.registerMethod("/", "myMethod", this, &MyObj::myMethod); @endcode * @param category category name. For example "/" * @param methodName the method name * @param object pointer to the object to call * @param handler pointer to object's member method * @param schema json schema to use. If set, will validate the request against the schema before calling the handler method. * @throws std::logic_error if a method is already registered with specified category and name. */ template<typename T> void registerMethod(const std::string& category, const std::string& methodName, T* object, pbnjson::JValue (T::* handler) (JsonRequest& request), const pbnjson::JSchema& schema = pbnjson::JSchema::AllSchema()) { registerMethod(category, methodName, std::bind(handler, object, std::placeholders::_1), schema); }; /** * Registers a new signal on the bus. * This just makes the signal visible to introspection. * Note that all services share a common namespace for signal categories. * So your category should be unique. The service name is disregarded when handling signals. * * Example: @code service.registerSignal("/myservice","signal"); @endcode * @param category category name. For example "/myservice" * @param methodName the method name. */ void registerSignal(const std::string& category, const std::string& methodName); /** * Make a one reply call. * If this call succeeds (does not throw) the handler method is guaranteed to be eventually called. * Regardless of any error condition within the luna bus. * You can use response.isSuccess() to check if the response is a success or not, response.finishParse does this internally. * @param uri * @param params * @param handler - if set the handler method will be called. If not set, nothing will be called. * @return luna message token that can be used ot cancel the call (even when no callback is set). * @throw LS::Error on luna error */ inline LSMessageToken callOneReply(const std::string& uri, const pbnjson::JValue& params, const JsonResponse::Handler& handler) { return makeCall(uri, params, true, handler); } /** * Make a one reply call - convenience method that accepts pointer and member method instead of std::function. * @tparam T * @param uri * @param params * @param object * @param handler * @return */ template<typename T> inline LSMessageToken callOneReply(const std::string& uri, const pbnjson::JValue& params, T* object, void (T::* handler) (JsonResponse& response)) { return callOneReply(uri, params, std::bind(handler, object, std::placeholders::_1)); } /** * Make a multi reply call. The call is active until cancelCall or client is deleted. * If this call succeeds (does not throw) the handler method is guaranteed to be eventually called at least once. * Regardless of any error condition within the luna bus. * You can use response.isSuccess to check if the response is a success or not. * @param uri * @param params * @param handler - mandatory response handler. * @return luna token, that can be used ot cancel the call. * @throw LS::Error on luna error, std::logic_error if no response handler. */ inline LSMessageToken callMultiReply(const std::string& uri, const pbnjson::JValue& params, const JsonResponse::Handler& handler) { return makeCall(uri, params, false, handler); } /** * Make a multi reply call - convenience method that accepts pointer and member method instead of std::function. * @tparam T * @param uri * @param params * @param object * @param handler * @return */ template<typename T> inline LSMessageToken callMultiReply(const std::string& uri, const pbnjson::JValue& params, T* object, void (T::* handler) (JsonResponse& response)) { return callMultiReply(uri, params, std::bind(handler, object, std::placeholders::_1)); } /** * Sends a signal to all subscribers. * @param category - signal category * @param method - signal method * @param payload - payload to send */ void sendSignal(const std::string& category, const std::string& method, const pbnjson::JValue& payload); /** * Subscribe to a signal. * Note that the response handler receives only signal responses. * Or error response from hub if there is error while subscribing. * @param category category name to monitor * @param methodName method name to monitor * @param handler callback function * @return luna token, can be used to cancel the call. */ inline LSMessageToken subscribeToSignal(const std::string& category, const std::string& methodName, const JsonResponse::Handler& handler) { // Consume the first response if it's successful. std::shared_ptr<bool> firstResponse { new bool (true) }; auto wrapperFunc = [handler, firstResponse](JsonResponse& response) -> void { if (*firstResponse.get() && response.isSuccess()) { *firstResponse.get() = false; return; } handler(response); }; return makeCall("luna://com.webos.service.bus/signal/addmatch", pbnjson::JObject{{ "category",category}, {"method", methodName}}, false, wrapperFunc); } /** * Subscribe to a signal. * * @param category category name to monitor * @param methodName method name to monitor * @param object object to call callback function on * @param handler callback function * @return luna token, can be used to cancel the call. */ template<typename T> inline LSMessageToken subscribeToSignal(const std::string& category, const std::string& methodName, T* object, void (T::* handler) (JsonResponse& response)) { return callSignal(category, methodName, std::bind(handler, object, std::placeholders::_1)); } /** * Cancels the call and removes any queued replies. * The handler method will not be called after this. * @param token */ void cancelCall(LSMessageToken token); private: // Internal call object struct Call { Call(ServicePoint* _service, LSMessageToken _token, const JsonResponse::Handler& _handler, bool _oneReply) :service(_service) , token(_token) , handler(_handler) , oneReply(_oneReply) {} ServicePoint* service; LSMessageToken token; JsonResponse::Handler handler; bool oneReply; }; //Internal method object struct MethodInfo { MethodInfo(ServicePoint* _service, const JsonRequest::Handler& _handler, const pbnjson::JSchema& _schema, const std::string& _category, const std::string& _method) : service(_service) , handler(_handler) , schema(_schema) , category(_category) , method(_method) {} ServicePoint* service; JsonRequest::Handler handler; pbnjson::JSchema schema; std::string category; std::string method; }; LSMessageToken makeCall(const std::string& uri, const pbnjson::JValue& params, bool oneReply, const JsonResponse::Handler& handler); void cancelCall(Call* call); void registerMethodImpl(MethodInfo& method); void unregisterMethodImpl(MethodInfo& method); static bool methodHandler(LSHandle *sh, LSMessage *msg, void *method_context); static bool removedMethodHandler(LSHandle *sh, LSMessage *msg, void *method_context); static bool callResponseHandler(LSHandle *sh, LSMessage *reply, void *ctx); // Instance variables LS::Handle* mHandle; // Need unique ptr, because we will be passing pointers around. std::vector<std::unique_ptr<MethodInfo> > mMethods; std::unordered_map<LSMessageToken, std::unique_ptr<Call> > mCalls; std::mutex mCallsMutex; // Lock access to mCalls. }; } // namespace LSHelpers;
32.857513
133
0.665773
[ "object", "vector" ]
391603bfd76fd56836623378306bbdd12c00024c
4,237
hpp
C++
solver/Hint.hpp
cuzdav/illum
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
[ "MIT" ]
null
null
null
solver/Hint.hpp
cuzdav/illum
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
[ "MIT" ]
null
null
null
solver/Hint.hpp
cuzdav/illum
b78b6477f8d3fbf31408e419f671dbfe421b4e9e
[ "MIT" ]
null
null
null
#pragma once #include "AnnotatedMove.hpp" #include "BasicBoard.hpp" #include "Coord.hpp" #include "DecisionType.hpp" #include "SingleMove.hpp" #include <fmt/core.h> #include <fmt/ostream.h> #include <iosfwd> #include <span> #include <vector> namespace solver { class Hint { public: using MovesSpan = std::span<AnnotatedMove const>; // A cluster of moves (usually just 1) considered to be done "together" class ExplainStep { public: using value_type = AnnotatedMove; using iterator = AnnotatedMove const *; using const_iterator = iterator; ExplainStep(DecisionType reason = DecisionType::NONE) : reason_{reason} {} MovesSpan moves() const; bool add(AnnotatedMove const & move); int size() const; AnnotatedMove & operator[](int idx) { return moves_[idx]; } AnnotatedMove const & operator[](int idx) const { return moves_[idx]; } const_iterator begin() const { return moves_; } iterator begin() { return moves_; } const_iterator end() const { return moves_ + count_; } iterator end() { return moves_ + count_; } friend std::ostream & operator<<(std::ostream &, Hint const &); private: AnnotatedMove moves_[4]{}; DecisionType reason_; int count_ = 0; }; using ExplainSteps = std::vector<ExplainStep>; using ConstIterator = ExplainSteps::const_iterator; ExplainStep const & next_moves() const; ExplainSteps const & explain_steps() const; DecisionType reason() const; ConstIterator begin() const; ConstIterator end() const; bool has_error() const { return has_error_; } static Hint create(model::BasicBoard const & board); private: Hint(DecisionType reason); private: bool has_error_ = false; DecisionType reason_; ExplainStep next_moves_; // what to play ExplainSteps explain_steps_; // shows contradiction }; inline Hint::Hint(DecisionType reason) : reason_(reason), next_moves_{} {} inline Hint::MovesSpan Hint::ExplainStep::moves() const { return {moves_, moves_ + count_}; } inline bool Hint::ExplainStep::add(AnnotatedMove const & move) { if (count_ == 4) { return false; } moves_[count_++] = move; return true; } inline int Hint::ExplainStep::size() const { return count_; } inline Hint::ExplainStep const & Hint::next_moves() const { return next_moves_; } inline DecisionType Hint::reason() const { return reason_; } inline Hint::ExplainSteps const & Hint::explain_steps() const { return explain_steps_; } inline Hint::ConstIterator Hint::begin() const { return explain_steps_.begin(); } inline Hint::ConstIterator Hint::end() const { return explain_steps_.end(); } } // namespace solver template <> struct fmt::formatter<::solver::Hint::ExplainStep> { template <typename ParseContext> constexpr auto parse(ParseContext & ctx) { return ctx.begin(); } template <typename FormatContext> auto format(::solver::Hint::ExplainStep const & step, FormatContext & ctx) { fmt::format_to(ctx.out(), "#<Step\n"); for (solver::AnnotatedMove const & step : step.moves()) { fmt::format_to(ctx.out(), "\t\t{}\n", step); } return fmt::format_to(ctx.out(), "\t]>"); } }; template <> struct fmt::formatter<::solver::Hint> { template <typename ParseContext> constexpr auto parse(ParseContext & ctx) { return ctx.begin(); } template <typename FormatContext> auto format(::solver::Hint const & hint, FormatContext & ctx) { fmt::format_to(ctx.out(), "#<Hint:\n" "\treason={}\n" "\tnext_move={},\n" "\tSteps: [\n", hint.reason(), hint.next_moves()); for (auto const & step : hint.explain_steps()) { fmt::format_to(ctx.out(), "\t{}\n", step); } return fmt::format_to(ctx.out(), "\t]>"); } }; void inline f() { solver::AnnotatedMove m; std::cout << fmt::format("{}", m); solver::DecisionType d{}; std::cout << fmt::format("{}", d); // auto hint = solver::Hint::create(model::BasicBoard{}); // fmt::format("{}", hint); }
21.291457
78
0.628511
[ "vector", "model" ]
391bfa79c9b0ac7e969b40dd80d3611916adf788
1,117
cpp
C++
plugins/d3d9/src/state/ffp/misc/make_states.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/d3d9/src/state/ffp/misc/make_states.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/d3d9/src/state/ffp/misc/make_states.cpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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) #include <sge/d3d9/state/render.hpp> #include <sge/d3d9/state/render_vector.hpp> #include <sge/d3d9/state/convert/bool_to_dword.hpp> #include <sge/d3d9/state/ffp/misc/make_states.hpp> #include <sge/renderer/state/ffp/misc/parameters.hpp> sge::d3d9::state::render_vector sge::d3d9::state::ffp::misc::make_states( sge::renderer::state::ffp::misc::parameters const &_parameters) { return sge::d3d9::state::render_vector{ sge::d3d9::state::render( D3DRS_LOCALVIEWER, sge::d3d9::state::convert::bool_to_dword(_parameters.local_viewer().get())), sge::d3d9::state::render( D3DRS_NORMALIZENORMALS, sge::d3d9::state::convert::bool_to_dword(_parameters.normalize_normals().get())), sge::d3d9::state::render( D3DRS_POINTSPRITEENABLE, sge::d3d9::state::convert::bool_to_dword(_parameters.enable_point_sprites().get()))}; }
42.961538
95
0.693823
[ "render" ]
391d6be01a82315ef92f3335e67abc458c045638
11,772
cxx
C++
Pose Editor/src/view_glfw/ViewerGUI.cxx
avatarxargo/Pose-Editor
7ef206d4201698d53a24f11f65cfb031aa5ae3f9
[ "MIT" ]
null
null
null
Pose Editor/src/view_glfw/ViewerGUI.cxx
avatarxargo/Pose-Editor
7ef206d4201698d53a24f11f65cfb031aa5ae3f9
[ "MIT" ]
null
null
null
Pose Editor/src/view_glfw/ViewerGUI.cxx
avatarxargo/Pose-Editor
7ef206d4201698d53a24f11f65cfb031aa5ae3f9
[ "MIT" ]
null
null
null
/// <title>Viewer GUI</title> /// <desc> /// Specific implementation of the ViewerInterface. /// You could substitute a headless or some other graphics library implementation /// in place of it and the rest of the application could operate without any issues. /// </desc> /// <date>9/4/2021</date> /// <version>1.0</version> /// <author>David Hrusa</author> /// <email>hrusadav@gmail.com</email> #define FOOTER_HEIGHT 30 #define INDENT_SIZE 20 #include "ViewerGUI.h" bool ViewerGUI::ViewerGLFW::init() { /* configure glfw */ if (!glfwInit()) return false; m_Window = glfwCreateWindow(1280, 720, "Pose Editor", NULL, NULL); if (!m_Window) { glfwTerminate(); return false; } glfwMakeContextCurrent(m_Window); glewInit(); glClearColor(0.7f, 0.5f, 0.9f, 1.0f); /* configure imgui */ IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); /* Setup Platform/Renderer bindings */ ImGui_ImplGlfw_InitForOpenGL(m_Window, true); ImGui_ImplOpenGL3_Init(); //glsl_version /* configure file browser */ m_FileOpenDialog = ImGui::FileBrowser(); m_FileOpenDialog.SetTitle("open file"); m_FileOpenDialog.SetTypeFilters({ ".csv" }); m_FileSaveDialog = ImGui::FileBrowser(ImGuiFileBrowserFlags_EnterNewFilename | ImGuiFileBrowserFlags_CreateNewDir); m_FileSaveDialog.SetTitle("save file"); m_FileSaveDialog.SetTypeFilters({ ".csv" }); /* load fonts */ //m_Font = io.Fonts->AddFontFromFileTTF("data/arial.ttf", 10.0f); /* load textures */ m_upIcon = createGLTextureBuffer("data/ico_up.bmp"); m_downIcon = createGLTextureBuffer("data/ico_down.bmp"); m_childIcon = createGLTextureBuffer("data/ico_child.bmp"); m_closeIcon = createGLTextureBuffer("data/ico_close.bmp"); return true; } void ViewerGUI::ViewerGLFW::renderUI() { /* top bar menu */ if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("File")) { if (ImGui::MenuItem("New", "", false, true)) { m_Controller->cmdNewFile(); } if (ImGui::MenuItem("Open", "", false, true)) { m_FileOpenDialog.SetPwd(m_FileOpenDialog.GetPwd()); //refresh folder m_FileOpenDialog.Open(); } if (ImGui::MenuItem("Save", "", false, m_InternalPawn.loaded)) { m_Controller->cmdSaveFile(m_InternalPawn.originalFilePath); } if (ImGui::MenuItem("Save As")) { m_FileSaveDialog.SetPwd(m_FileSaveDialog.GetPwd()); //refresh folder m_FileSaveDialog.Open(); m_FileSaveDialog.SetInputText(m_InternalPawn.originalFileName); } ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } /* file browsing dialogs */ m_FileOpenDialog.Display(); m_FileSaveDialog.Display(); if (m_FileOpenDialog.HasSelected()) { std::string openPath = m_FileOpenDialog.GetSelected().string(); m_FileOpenDialog.ClearSelected(); m_Controller->cmdOpenFile(openPath); } if (m_FileSaveDialog.HasSelected()) { std::string savePath = m_FileSaveDialog.GetSelected().string(); m_FileSaveDialog.ClearSelected(); m_Controller->cmdSaveFile(savePath); } /* pop up messages */ if (m_PopupCloseNoSave) { m_PopupCloseNoSave = false; ImGui::OpenPopup("confirmClose"); } if (ImGui::BeginPopup("confirmClose")) { ImGui::Text("%s has unsaved changes. Are you sure you want to exit the application?", m_InternalPawn.originalFileName.c_str()); if (ImGui::Button("Close Anyway")) { m_Controller->setApplicationActive(false); } ImGui::SameLine(); if (ImGui::Button("Cancel")) { ImGui::CloseCurrentPopup(); } ImGui::EndPopup(); } /* main editor window */ ImGui::Begin("Bone Editor"); { /* File Info */ float maxw = ImGui::GetContentRegionAvail().x; ImGui::Text("%s", m_InternalPawn.originalFileName.c_str()); /* simple toggle */ ImGui::SameLine(); ImGui::SetCursorPosX(maxw - 170); ImGui::Text("simple"); ImGui::SameLine(); ImGui::SetCursorPosX(maxw - 120); ImGui::PushID("simple"); ImGui::Checkbox("", &m_ShowSimple); ImGui::PopID(); /* hierarchy toggle */ ImGui::SameLine(); ImGui::SetCursorPosX(maxw - 85); ImGui::Text("hierarchy"); ImGui::SameLine(); ImGui::SetCursorPosX(maxw - 15); ImGui::PushID("hierarchy"); ImGui::Checkbox("", &m_ShowHierarchy); ImGui::PopID(); ImGui::Separator(); /* Node Inspectors */ ImGui::BeginChild("node block", ImVec2(-1, (-FOOTER_HEIGHT - 5 + ImGui::GetContentRegionAvail().y))); { if (m_ShowHierarchy) { /* traverse from root elements with indentation */ auto roots = PoseDataUtil::pawnGetBoneChildren(m_InternalPawn, -1); for (auto rootidx : roots) { auto& bone = m_InternalPawn.bones[rootidx]; renderBoneUI(rootidx, bone); m_IndentCount = 0; recursiveHierarchyRenderUI(bone.id); } } else { /* traverse regularly */ int boneidx = 0; for (PoseData::BoneData bone : m_InternalPawn.bones) { renderBoneUI(boneidx, bone); boneidx++; } } } ImGui::EndChild(); /* footer with a bone spawning button */ ImGui::BeginChild("footer block", ImVec2(-1, FOOTER_HEIGHT)); ImGui::Separator(); if (ImGui::Button("+ bone")) { m_Controller->cmdBoneAdd(-1); } ImGui::EndChild(); } ImGui::End(); } void ViewerGUI::ViewerGLFW::renderBoneUI(int boneidx, PoseData::BoneData& bone, int indent) { ImGui::PushID(boneidx); float indentDistance = static_cast<float>(indent) * INDENT_SIZE; float maxw = ImGui::GetContentRegionAvail().x; ImGui::TextColored(ImVec4(0.71f, 0.30f, 0.62f, 1.f), ("[" + std::to_string(bone.id) + "] " + bone.displayName).c_str()); /* controls */ if (!m_ShowHierarchy) { ImGui::SameLine(); ImGui::PushID("up"); ImGui::SetCursorPosX(indentDistance + maxw - 100); if (ImGui::ImageButton((void*)m_upIcon, { 15,15 })) { m_Controller->cmdBoneMoveUp(bone.id); } ImGui::PopID(); ImGui::SameLine(); ImGui::PushID("down"); ImGui::SetCursorPosX(indentDistance + maxw - 75); if (ImGui::ImageButton((void*)m_downIcon, { 15,15 })) { m_Controller->cmdBoneMoveDown(bone.id); } ImGui::PopID(); } ImGui::SameLine(); ImGui::PushID("addchild"); ImGui::SetCursorPosX(indentDistance + maxw - 50); if (ImGui::ImageButton((void*)m_childIcon, { 15,15 })) { m_Controller->cmdBoneAdd(bone.id); } ImGui::PopID(); ImGui::SameLine(); ImGui::PushID("remove"); ImGui::SetCursorPosX(indentDistance + maxw - 25); if (ImGui::ImageButton((void*)m_closeIcon, { 15,15 })) { m_Controller->cmdBoneRemove(bone.id); } ImGui::PopID(); /* only show editor when simple is unchecked */ if (!m_ShowSimple) { ImGui::PushItemWidth(-1); /* name */ ImGui::Text("name"); ImGui::SameLine(); ImGui::SetCursorPosX(indentDistance + 50); if (ImGui::InputText("", &(bone.displayName))) { m_Controller->cmdBoneSetName(bone.id, bone.displayName); } /* parent */ ImGui::Text("parent"); ImGui::SameLine(); ImGui::SetCursorPosX(indentDistance + 50); std::string selectedName = "[Root]"; int pcoord = PoseDataUtil::pawnFindBoneId(m_InternalPawn, bone.parent); if (pcoord >= 0) { selectedName = m_InternalPawn.bones[pcoord].displayName; } if (ImGui::BeginCombo("combo", selectedName.c_str())) { if (ImGui::Selectable("[Root]", pcoord < 0)) { m_Controller->cmdBoneSetParent(bone.id, -1); } int pidx = 0; for (PoseData::BoneData pbone : m_InternalPawn.bones) { if (ImGui::Selectable(pbone.displayName.c_str(), pidx++ == pcoord)) { m_Controller->cmdBoneSetParent(bone.id, pbone.id); } } ImGui::EndCombo(); } /* angle */ ImGui::Text("angle"); ImGui::SameLine(); ImGui::SetCursorPosX(indentDistance + 50); ImGui::PopItemWidth(); ImGui::PushItemWidth((maxw - 50) / 3 - 10); ImGui::PushID("angx"); if (ImGui::SliderFloat("", &glm::value_ptr(bone.eulerRotation)[0], -179.f, 179.f)) { m_Controller->cmdBoneSetRotation(bone.id, bone.eulerRotation); } ImGui::PopID(); ImGui::SameLine(); ImGui::PushID("angy"); ImGui::SetCursorPosX(indentDistance + 50 + (maxw - 50) / 3); if (ImGui::SliderFloat("", &glm::value_ptr(bone.eulerRotation)[1], -89.f, 89.f)) { m_Controller->cmdBoneSetRotation(bone.id, bone.eulerRotation); } ImGui::PopID(); ImGui::SameLine(); ImGui::PushID("angz"); ImGui::SetCursorPosX(indentDistance + 50 + 2 * (maxw - 50) / 3); if (ImGui::SliderFloat("", &glm::value_ptr(bone.eulerRotation)[2], -179.f, 179.f)) { m_Controller->cmdBoneSetRotation(bone.id, bone.eulerRotation); } ImGui::PopID(); ImGui::PopItemWidth(); } ImGui::Separator(); ImGui::PopID(); } void ViewerGUI::ViewerGLFW::recursiveHierarchyRenderUI(ID boneId) { auto children = PoseDataUtil::pawnGetBoneChildren(m_InternalPawn, boneId); ImGui::Indent(INDENT_SIZE); m_IndentCount++; for (auto childidx : children) { auto& bone = m_InternalPawn.bones[childidx]; renderBoneUI(childidx, bone, m_IndentCount); recursiveHierarchyRenderUI(bone.id); } ImGui::Unindent(INDENT_SIZE); m_IndentCount--; } GLuint ViewerGUI::ViewerGLFW::createGLTextureBuffer(std::string path) { GLuint tex = 0; try { cimg_library::CImg<unsigned char> imgdata(path.c_str()); imgdata.permute_axes("cxyz"); glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 64, 64, 0, GL_RGB, GL_UNSIGNED_BYTE, imgdata); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); } catch (const std::exception&) { //these icons are just for visual flare, so this catch prevents the application from failing to a missing texture. No need to handle further. } return tex; } void ViewerGUI::ViewerGLFW::destroyGLTextureBuffer(GLuint handle) { glDeleteBuffers(1, &handle); } void ViewerGUI::ViewerGLFW::updateRender() { glClear(GL_COLOR_BUFFER_BIT); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); renderUI(); // Render dear imgui into screen ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); int display_w, display_h; glfwGetFramebufferSize(m_Window, &display_w, &display_h); glViewport(0, 0, display_w, display_h); glfwSwapBuffers(m_Window); } void ViewerGUI::ViewerGLFW::updateEvents() { glfwPollEvents(); /* Detect closing of the window */ if (glfwWindowShouldClose(m_Window)) { if (!m_InternalPawn.saved) { m_PopupCloseNoSave = true; glfwSetWindowShouldClose(m_Window, false); } else { m_Controller->setApplicationActive(false); } } } void ViewerGUI::ViewerGLFW::update() { updateRender(); updateEvents(); } void ViewerGUI::ViewerGLFW::cleanUp() { /* clean up imgui */ ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); /* unload textures */ destroyGLTextureBuffer(m_upIcon); destroyGLTextureBuffer(m_downIcon); destroyGLTextureBuffer(m_childIcon); destroyGLTextureBuffer(m_closeIcon); // This will kill glfw for all other Application Instances on this thread, // but if they are using another kind of viewer they will be fine. // It is a little inelegant, but I prefer this over polluting non-viewer components with glfw references. glfwTerminate(); } void ViewerGUI::ViewerGLFW::updateView(const PoseData::BonePawn currentPawn) { m_InternalPawn = PoseDataUtil::pawnDeepCopy(currentPawn); std::stringstream ss(""); if (m_InternalPawn.loaded) ss << "Pose Editor - " << m_InternalPawn.originalFilePath; else ss << "Pose Editor"; if (!m_InternalPawn.saved) ss << "* - Unsaved Changes"; ss.flush(); glfwSetWindowTitle(m_Window, ss.str().c_str()); // the UI will adapt on the next render call. } void ViewerGUI::ViewerGLFW::setController(std::shared_ptr<PoseEditor::Controller> _controller) { m_Controller = _controller; }
29.283582
143
0.700051
[ "render" ]
391ec0498ebafd525c9101af84ece0f632aea839
369
hpp
C++
src/radial_pts.hpp
JLRipley314/spherically-symmetric-Z2-edgb
c2311a79d2ec08073541c98f6b06b6f54fbb58e4
[ "MIT" ]
null
null
null
src/radial_pts.hpp
JLRipley314/spherically-symmetric-Z2-edgb
c2311a79d2ec08073541c98f6b06b6f54fbb58e4
[ "MIT" ]
null
null
null
src/radial_pts.hpp
JLRipley314/spherically-symmetric-Z2-edgb
c2311a79d2ec08073541c98f6b06b6f54fbb58e4
[ "MIT" ]
2
2021-07-06T01:45:19.000Z
2021-07-30T18:35:09.000Z
#ifndef _RADIAL_PTS_HPP_ #define _RADIAL_PTS_HPP_ #include <vector> /*===========================================================================*/ class Radial_pts { public: std::vector<double> x; std::vector<double> r; const double cl; Radial_pts( const int nx, const double dx, const double cl ); ~Radial_pts(void); private: }; #endif
16.043478
79
0.528455
[ "vector" ]
3928f3e7b225aeb3575f8f0cc911b3f403fe16c2
1,467
cpp
C++
Homeworks/Homework5/MinElementsSum/Source.cpp
nia-flo/FMI-DataStructuresAndAlgorithms
1040b14e0b008015a4a035c0db19c7b22d72ba79
[ "MIT" ]
null
null
null
Homeworks/Homework5/MinElementsSum/Source.cpp
nia-flo/FMI-DataStructuresAndAlgorithms
1040b14e0b008015a4a035c0db19c7b22d72ba79
[ "MIT" ]
null
null
null
Homeworks/Homework5/MinElementsSum/Source.cpp
nia-flo/FMI-DataStructuresAndAlgorithms
1040b14e0b008015a4a035c0db19c7b22d72ba79
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int main() { int N, d; cin >> N >> d; vector<long long> input(N); vector<int> minElementIdx(N); for (int i = 0; i < N; i++) { cin >> input[i]; if (i < d) { if (i == 0 || input[i] < input[minElementIdx[i - 1]]) { minElementIdx[i] = i; for (int j = i - 1; j >= 0; j--) { if (input[i] < input[minElementIdx[j]]) { minElementIdx[j] = i; } } } else { minElementIdx[i] = minElementIdx[i - 1]; } } else { if (minElementIdx[i - 1] <= i - d || input[i] < input[minElementIdx[i - 1]]) { minElementIdx[i] = i; for (int j = 1; j < d; j++) { if (input[i - j] < input[minElementIdx[i]]) { minElementIdx[i] = i - j; } } } else { minElementIdx[i] = minElementIdx[i - 1]; } } } long long minElementsSum = 0; for (int i = d - 1; i < N; i++) { minElementsSum += input[minElementIdx[i]]; } cout << minElementsSum << '\n'; return 0; }
22.921875
88
0.345603
[ "vector" ]
393f770118646ae91cce66bf8e5076ba973d63b5
7,710
cc
C++
src/detectors/macleod/addon/macleod.cc
cristovao-trevisan/pitchfinder
3d4ecec71e3bebe5c61f9bfb3f2726ea5daf13fa
[ "MIT" ]
28
2017-08-15T18:13:40.000Z
2022-01-17T07:45:38.000Z
src/detectors/macleod/addon/macleod.cc
cristovao-trevisan/pitchfinder
3d4ecec71e3bebe5c61f9bfb3f2726ea5daf13fa
[ "MIT" ]
2
2020-01-27T19:51:13.000Z
2021-09-09T23:22:36.000Z
src/detectors/macleod/addon/macleod.cc
cristovao-trevisan/pitchfinder
3d4ecec71e3bebe5c61f9bfb3f2726ea5daf13fa
[ "MIT" ]
5
2017-11-25T15:43:28.000Z
2021-06-19T16:07:23.000Z
#include <nan.h> #include <limits> #include "macleod.h" Nan::Persistent<v8::Function> MacLeod::constructor; bool max(double a, double b) { if (b < a) return a; return b; } void MacLeod::Init(v8::Local<v8::Object> exports) { Nan::HandleScope scope; // Prepare constructor template v8::Local<v8::Context> context = exports->CreationContext(); v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); tpl->SetClassName(Nan::New("MacLeod").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); // Prototype Nan::SetPrototypeMethod(tpl, "getPitch", getPitch); Nan::SetPrototypeMethod(tpl, "getResult", getResult); constructor.Reset(tpl->GetFunction(context).ToLocalChecked()); exports->Set(context, Nan::New("MacLeod").ToLocalChecked(), tpl->GetFunction(context).ToLocalChecked()); } void MacLeod::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext(); unsigned int bufferSize = info[0]->IsUndefined() ? DEFAULT_MACLEOD_BUFFER_SIZE : info[0]->NumberValue(context).FromJust(); double sampleRate = info[1]->IsUndefined() ? DEFAULT_MACLEOD_SAMPLE_RATE : info[1]->NumberValue(context).FromJust(); double cutoff = info[2]->IsUndefined() ? DEFAULT_MACLEOD_CUTOFF : info[2]->NumberValue(context).FromJust(); double freqCutoff = info[3]->IsUndefined() ? DEFAULT_MACLEOD_LOWER_PITCH_CUTOFF : info[3]->NumberValue(context).FromJust(); double probabilityThreshold = info[4]->IsUndefined() ? DEFAULT_MACLEOD_PROBABILITY_THRESHOLD : info[4]->NumberValue(context).FromJust(); MacLeod* obj = new MacLeod(bufferSize, sampleRate, cutoff, freqCutoff, probabilityThreshold); obj->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } void MacLeod::init(unsigned int bufferSize, double sampleRate, double cutoff, double freqCutoff, double probabilityThreshold) { this->nsdf = new double[bufferSize]; this->bufferSize = bufferSize; this->sampleRate = sampleRate; this->cutoff = cutoff; this->lowerPitchCutoff = freqCutoff; this->probabilityThreshold = probabilityThreshold; } MacLeod::MacLeod() { init(DEFAULT_MACLEOD_BUFFER_SIZE, DEFAULT_MACLEOD_SAMPLE_RATE, DEFAULT_MACLEOD_CUTOFF, DEFAULT_MACLEOD_LOWER_PITCH_CUTOFF, DEFAULT_MACLEOD_PROBABILITY_THRESHOLD); }; MacLeod::MacLeod(unsigned int bufferSize, double sampleRate, double cutoff, double freqCutoff, double probabilityThreshold) { init(bufferSize, sampleRate, cutoff, freqCutoff, probabilityThreshold); }; MacLeod::~MacLeod() { delete[] nsdf; }; void MacLeod::getPitch(const Nan::FunctionCallbackInfo<v8::Value>& info) { MacLeod* obj = ObjectWrap::Unwrap<MacLeod>(info.Holder()); assert(info[0]->IsFloat64Array()); v8::Local<v8::Float64Array> input = info[0].As<v8::Float64Array>(); assert(input->Length() <= obj->bufferSize); Nan::TypedArrayContents<double> inputData(input); double pitch = obj->calculatePitch((*inputData), input->Length()); if (obj->probability < obj->probabilityThreshold) pitch = -1; info.GetReturnValue().Set(Nan::New(pitch)); } void MacLeod::getResult(const Nan::FunctionCallbackInfo<v8::Value>& info) { v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext(); MacLeod* obj = ObjectWrap::Unwrap<MacLeod>(info.Holder()); assert(info[0]->IsFloat64Array()); v8::Local<v8::Float64Array> input = info[0].As<v8::Float64Array>(); assert(input->Length() <= obj->bufferSize); Nan::TypedArrayContents<double> inputData(input); double pitch = obj->calculatePitch((*inputData), input->Length()); v8::Local<v8::Object> result = Nan::New<v8::Object>(); result->Set(context, Nan::New("pitch").ToLocalChecked(), Nan::New(pitch)); result->Set(context, Nan::New("probability").ToLocalChecked(), Nan::New(obj->probability)); info.GetReturnValue().Set(result); } void MacLeod::normalizedSquareDifference(double* data, size_t dataSize) { for (size_t tau = 0; tau < dataSize; tau++) { double acf = 0; double divisorM = 0; for (size_t i = 0; i < dataSize - tau; i++) { acf += data[i] * data[i+tau]; divisorM += data[i] * data[i] + data[i + tau] * data[i + tau]; } nsdf[tau] = 2 * acf / divisorM; } } void MacLeod::parabolicInterpolation(unsigned int tau) { double nsdfa = nsdf[tau - 1]; double nsdfb = nsdf[tau]; double nsdfc = nsdf[tau + 1]; double bValue = tau; double bottom = nsdfc + nsdfa - 2 * nsdfb; if (bottom == 0) { turningPointX = bValue; turningPointY = nsdfb; } else { double delta = nsdfa - nsdfc; turningPointX = bValue + delta / (2 * bottom); turningPointY = nsdfb - delta * delta / (8 * bottom); } } void MacLeod::peakPicking(size_t dataSize) { unsigned int pos = 0; unsigned int curMaxPos = 0; // find the first negative zero crossing. while (pos < (dataSize - 1) / 3 && nsdf[pos] > 0) { pos++; } // loop over all the values below zero. while (pos < dataSize - 1 && nsdf[pos] <= 0) { pos++; } // can happen if output[0] is NAN if (pos == 0) { pos = 1; } while (pos < dataSize - 1) { assert(nsdf[pos] >= 0); if (nsdf[pos] > nsdf[pos - 1] && nsdf[pos] >= nsdf[pos + 1]) { if (curMaxPos == 0) { // the first max (between zero crossings) curMaxPos = pos; } else if (nsdf[pos] > nsdf[curMaxPos]) { // a higher max (between the zero crossings) curMaxPos = pos; } } pos++; // a negative zero crossing if (pos < dataSize - 1 && nsdf[pos] <= 0) { // if there was a maximum add it to the list of maxima if (curMaxPos > 0) { maxPositions.push_back(curMaxPos); curMaxPos = 0; // clear the maximum position, so we start // looking for a new ones } while (pos < dataSize - 1 && nsdf[pos] <= 0) { pos++; // loop over all the values below zero } } } if (curMaxPos > 0) { maxPositions.push_back(curMaxPos); } } double MacLeod::calculatePitch (double* data, size_t dataSize) { double pitch; maxPositions.clear(); periodEstimates.clear(); ampEstimates.clear(); // 1. Calculute the normalized square difference for each Tau value. normalizedSquareDifference(data, dataSize); // 2. Peak picking time: time to pick some peaks. peakPicking(dataSize); double highestAmplitude = - std::numeric_limits<double>::infinity(); unsigned int tau; for (unsigned int i = 0; i < maxPositions.size(); i++) { tau = maxPositions[i]; // make sure every annotation has a probability attached highestAmplitude = max(highestAmplitude, nsdf[tau]); if (nsdf[tau] > MACLEOD_SMALL_CUTOFF) { // calculates turningPointX and Y parabolicInterpolation(tau); // store the turning points ampEstimates.push_back(turningPointY); periodEstimates.push_back(turningPointX); // remember the highest amplitude highestAmplitude = max(highestAmplitude, turningPointY); } } if (periodEstimates.size() > 0) { // use the overall maximum to calculate a cutoff. // The cutoff value is based on the highest value and a relative // threshold. double actualCutoff = cutoff * highestAmplitude; unsigned int periodIndex = 0; for (unsigned int i = 0; i < ampEstimates.size(); i++) { if (ampEstimates[i] >= actualCutoff) { periodIndex = i; break; } } double period = periodEstimates[periodIndex]; double pitchEstimate = sampleRate / period; if (pitchEstimate > lowerPitchCutoff) { pitch = pitchEstimate; } else { pitch = -1; } } else { // no pitch detected. pitch = -1; } probability = highestAmplitude; return pitch; }
34.266667
164
0.672503
[ "object" ]
3942f9b0798a9b22c8a3b6d2c90835d01e29be4b
55,685
cpp
C++
sql/SqlValues.cpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
5
2021-01-15T16:59:59.000Z
2022-02-28T15:41:00.000Z
sql/SqlValues.cpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
null
null
null
sql/SqlValues.cpp
josefschmeisser/TardisDB
0d805c4730533fa37c3668acd592404027b9b0d6
[ "Apache-2.0" ]
1
2021-06-22T04:53:38.000Z
2021-06-22T04:53:38.000Z
#include "sql/SqlValues.hpp" #include <llvm/IR/Module.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/TypeBuilder.h> #include <functional> #include <limits> #include "codegen/CodeGen.hpp" #include "codegen/PhiNode.hpp" #include "foundations/exceptions.hpp" #include "foundations/LegacyTypes.hpp" #include "foundations/StringPool.hpp" #include "sql/SqlType.hpp" #include "utils/general.hpp" #include "utils/llvm.hpp" namespace Sql { //----------------------------------------------------------------------------- // common functions // the same as shown in Types.hpp static cg_hash_t genIntHash(llvm::Value * value) { cg_hash_t x(value); // zero extend cg_hash_t r(88172645463325252ul); r = r ^ x; r = r ^ (r << 13ul); r = r ^ (r >> 7ul); r = r ^ (r << 17ul); return r; } static cg_hash_t genStringHash(CodeGen & codeGen, cg_ptr8_t & str, cg_size_t len) { auto & funcGen = codeGen.getCurrentFunctionGen(); #ifdef __APPLE__ cg_hash_t result(0ull); #else cg_hash_t result(0ul); #endif // iterate over all characters #ifdef __APPLE__ LoopGen loopGen(funcGen, {{"index", cg_size_t(0ull)}, {"result", result}}); #else LoopGen loopGen(funcGen, {{"index", cg_size_t(0ul)}, {"result", result}}); #endif cg_size_t index(loopGen.getLoopVar(0)); { LoopBodyGen bodyGen(loopGen); cg_ptr8_t ptr = str + index; cg_char_t c( codeGen->CreateLoad(codeGen->getInt8Ty(), ptr) ); // Functions::genPrintfCall("hash iteration: %lu - char: %c\n", index, c); // apply the same hash algorithm as in Types.hpp cg_hash_t x( codeGen->CreateZExt( c, result.llvmValue->getType() ) ); result = cg_hash_t(loopGen.getLoopVar(1)); result = ((result << 5ul) | (result >> 27ul)) ^ x; } cg_size_t nextIndex(index + 1ul); loopGen.loopDone(nextIndex < len, {nextIndex, result}); return result; } //----------------------------------------------------------------------------- // Value Value::Value(SqlType type) : type(type) { } Value::~Value() { } value_op_t Value::castString(const std::string & str, SqlType type) { assert(!type.nullable); switch (type.typeID) { case SqlType::TypeID::UnknownID: return UnknownValue::create(); case SqlType::TypeID::BoolID: return Bool::castString(str); case SqlType::TypeID::IntegerID: return Integer::castString(str); case SqlType::TypeID::VarcharID: return Varchar::castString(str, type); case SqlType::TypeID::CharID: return Char::castString(str, type); case SqlType::TypeID::NumericID: return Numeric::castString(str, type); case SqlType::TypeID::DateID: return Date::castString(str); case SqlType::TypeID::TimestampID: return Timestamp::castString(str); case SqlType::TypeID::TextID: return Text::castString(str, type); default: unreachable(); } } value_op_t Value::castString(cg_ptr8_t str, cg_size_t length, SqlType type) { assert(!type.nullable); switch (type.typeID) { case SqlType::TypeID::UnknownID: return UnknownValue::create(); case SqlType::TypeID::BoolID: return Bool::castString(str, length); case SqlType::TypeID::IntegerID: return Integer::castString(str, length); case SqlType::TypeID::VarcharID: return Varchar::castString(str, length, type); case SqlType::TypeID::CharID: return Char::castString(str, length, type); case SqlType::TypeID::NumericID: return Numeric::castString(str, length, type); case SqlType::TypeID::DateID: return Date::castString(str, length); case SqlType::TypeID::TimestampID: return Timestamp::castString(str, length); case SqlType::TypeID::TextID: return Text::castString(str, length, type); default: unreachable(); } } value_op_t Value::fromRawValues(const std::vector<llvm::Value *> & values, SqlType type) { value_op_t sqlValue; SqlType notNullType = type; notNullType.nullable = false; switch (type.typeID) { case SqlType::TypeID::UnknownID: return UnknownValue::create(); case SqlType::TypeID::BoolID: sqlValue = Bool::fromRawValues(values); break; case SqlType::TypeID::IntegerID: sqlValue = Integer::fromRawValues(values); break; case SqlType::TypeID::VarcharID: sqlValue = Varchar::fromRawValues(values, notNullType); break; case SqlType::TypeID::CharID: sqlValue = Char::fromRawValues(values, notNullType); break; case SqlType::TypeID::NumericID: sqlValue = Numeric::fromRawValues(values, notNullType); break; case SqlType::TypeID::DateID: sqlValue = Date::fromRawValues(values); break; case SqlType::TypeID::TimestampID: sqlValue = Timestamp::fromRawValues(values); break; case SqlType::TypeID::TextID: sqlValue = Text::fromRawValues(values, notNullType); break; default: unreachable(); } if (type.nullable) { #ifndef USE_INTERNAL_NULL_INDICATOR return NullableValue::create(std::move(sqlValue), cg_bool_t(values.back())); #else return NullableValue::create(std::move(sqlValue)); #endif } else { return sqlValue; } } value_op_t Value::load(llvm::Value * ptr, SqlType type) { if (type.nullable) { return NullableValue::load(ptr, type); } switch (type.typeID) { case SqlType::TypeID::UnknownID: return UnknownValue::create(); case SqlType::TypeID::BoolID: throw NotImplementedException(); // TODO case SqlType::TypeID::IntegerID: return Integer::load(ptr); case SqlType::TypeID::LongIntegerID: return LongInteger::load(ptr); case SqlType::TypeID::VarcharID: return Varchar::load(ptr, type); case SqlType::TypeID::CharID: return Char::load(ptr, type); case SqlType::TypeID::NumericID: return Numeric::load(ptr, type); case SqlType::TypeID::DateID: return Date::load(ptr); case SqlType::TypeID::TimestampID: return Timestamp::load(ptr); case SqlType::TypeID::TextID: return Text::load(ptr, type); default: unreachable(); } } llvm::Value * Value::getLLVMValue() const { return _llvmValue; } std::vector<llvm::Value *> Value::getRawValues() const { return { _llvmValue }; } size_t Value::getSize() const { return getValueSize(type); } llvm::Type * Value::getLLVMType() const { return toLLVMTy(type); } cg_bool_t Value::compare(const Value & other, ComparisonMode mode) const { auto & codeGen = getThreadLocalCodeGen(); cg_bool_t cmp(false); // map to the corrosponding LLVM instructions switch (mode) { case ComparisonMode::less: cmp = cg_bool_t( codeGen->CreateICmpSLT( _llvmValue, other.getLLVMValue() ) ); break; case ComparisonMode::leq: cmp = cg_bool_t( codeGen->CreateICmpSLE( _llvmValue, other.getLLVMValue() ) ); break; case ComparisonMode::eq: cmp = cg_bool_t( codeGen->CreateICmpEQ( _llvmValue, other.getLLVMValue() ) ); break; case ComparisonMode::geq: cmp = cg_bool_t( codeGen->CreateICmpSGE( _llvmValue, other.getLLVMValue() ) ); break; case ComparisonMode::gtr: cmp = cg_bool_t( codeGen->CreateICmpSGT( _llvmValue, other.getLLVMValue() ) ); break; default: unreachable(); } return cmp; } //----------------------------------------------------------------------------- // Integer Integer::Integer(llvm::Value * value) : Value(getIntegerTy()) { this->_llvmValue = value; } Integer::Integer(value_type constantValue) : Value(getIntegerTy()) { _llvmValue = cg_value_type(constantValue); } value_op_t Integer::clone() const { Value * cloned = new Integer(_llvmValue); return value_op_t(cloned); } value_op_t Integer::castString(const std::string & str) { Integer::value_type raw = castStringToIntegerValue(str.c_str(), static_cast<uint32_t>(str.length())); llvm::Value * value = cg_value_type(raw); value_op_t sqlValue( new Integer(value) ); return sqlValue; } value_op_t Integer::castString(cg_ptr8_t str, cg_size_t length) { cg_value_type raw = genCastStringToIntegerValueCall(str, length); value_op_t sqlValue( new Integer(raw) ); return sqlValue; } value_op_t Integer::fromRawValues(const std::vector<llvm::Value *> & values) { assert(!values.empty()); return value_op_t(new Integer(values.front())); } value_op_t Integer::load(llvm::Value * ptr) { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * integerTy = getPointeeType(ptr); assert(integerTy == cg_value_type::getType()); llvm::Value * value = codeGen->CreateLoad(integerTy, ptr); // Functions::genPrintfCall("Integer::load ptr: %p value: %d\n", ptr, value); value_op_t sqlValue( new Integer(value) ); return sqlValue; } void Integer::store(llvm::Value * ptr) const { // Functions::genPrintfCall("Integer::store ptr: %p value %d\n", ptr, _llvmValue); auto & codeGen = getThreadLocalCodeGen(); codeGen->CreateStore(_llvmValue, ptr); } cg_hash_t Integer::hash() const { return genIntHash(_llvmValue); } void Integer::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t Integer::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } auto & codeGen = getThreadLocalCodeGen(); return cg_bool_t( codeGen->CreateICmpEQ(_llvmValue, other.getLLVMValue()) ); } //----------------------------------------------------------------------------- // Long Integer LongInteger::LongInteger(llvm::Value * value) : Value(getLongIntegerTy()) { this->_llvmValue = value; } LongInteger::LongInteger(value_type constantValue) : Value(getLongIntegerTy()) { _llvmValue = cg_value_type(constantValue); } value_op_t LongInteger::clone() const { Value *cloned = new LongInteger(_llvmValue); return value_op_t(cloned); } value_op_t LongInteger::castString(const std::string & str) { LongInteger::value_type raw = castStringToUnsignedLongIntegerValue(str.c_str(), static_cast<uint64_t>(str.length())); llvm::Value * value = cg_value_type(raw); value_op_t sqlValue( new LongInteger(value) ); return sqlValue; } value_op_t LongInteger::castString(cg_ptr8_t str, cg_size_t length) { cg_value_type raw = genCastStringToUnsignedLongIntegerValueCall(str, length); value_op_t sqlValue( new LongInteger(raw) ); return sqlValue; } value_op_t LongInteger::fromRawValues(const std::vector<llvm::Value *> & values) { assert(!values.empty()); return value_op_t(new LongInteger(values.front())); } value_op_t LongInteger::load(llvm::Value * ptr) { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * integerTy = getPointeeType(ptr); assert(integerTy == cg_value_type::getType()); llvm::Value * value = codeGen->CreateLoad(integerTy, ptr); //Functions::genPrintfCall("Integer::load ptr: %p\n", ptr, value); value_op_t sqlValue( new LongInteger(value) ); return sqlValue; } void LongInteger::store(llvm::Value * ptr) const { // Functions::genPrintfCall("Integer::store ptr: %p value %d\n", ptr, _llvmValue); auto & codeGen = getThreadLocalCodeGen(); codeGen->CreateStore(_llvmValue, ptr); } cg_hash_t LongInteger::hash() const { return genIntHash(_llvmValue); } void LongInteger::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t LongInteger::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } auto & codeGen = getThreadLocalCodeGen(); return cg_bool_t( codeGen->CreateICmpEQ(_llvmValue, other.getLLVMValue()) ); } //----------------------------------------------------------------------------- // Numeric Numeric::Numeric(SqlType type, llvm::Value * value) : Value(type) { this->_llvmValue = value; assert(type.typeID == SqlType::TypeID::NumericID && !type.nullable); } Numeric::Numeric(SqlType type, value_type constantValue) : Value(type) { _llvmValue = cg_value_type(constantValue); } value_op_t Numeric::clone() const { Value * cloned = new Numeric(type, _llvmValue); return value_op_t(cloned); } value_op_t Numeric::castString(const std::string & str, SqlType type) { int64_t raw = castStringToNumericValue( str.c_str(), static_cast<uint32_t>(str.size()), type.numericLayout.length, type.numericLayout.precision ); llvm::Value * value = cg_value_type(raw); value_op_t sqlValue( new Numeric(type, value) ); return sqlValue; } value_op_t Numeric::castString(cg_ptr8_t str, cg_size_t length, SqlType type) { cg_i64_t raw = genCastStringToNumericValueCall( str, length, cg_unsigned_t(type.numericLayout.precision), cg_unsigned_t(type.numericLayout.precision) ); value_op_t sqlValue( new Numeric(type, raw) ); return sqlValue; } value_op_t Numeric::fromRawValues(const std::vector<llvm::Value *> & values, SqlType type) { assert(!values.empty()); return value_op_t(new Numeric(type, values.front())); } value_op_t Numeric::load(llvm::Value * ptr, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * numericTy = getPointeeType(ptr); assert(numericTy == cg_value_type::getType()); llvm::Value * value = codeGen->CreateLoad(numericTy, ptr); value_op_t sqlValue( new Numeric(type, value) ); return sqlValue; } void Numeric::store(llvm::Value * ptr) const { auto & codeGen = getThreadLocalCodeGen(); codeGen->CreateStore(_llvmValue, ptr); } cg_hash_t Numeric::hash() const { // can be used for all integral types return genIntHash(_llvmValue); } void Numeric::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t Numeric::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } auto & codeGen = getThreadLocalCodeGen(); return cg_bool_t( codeGen->CreateICmpEQ(_llvmValue, other.getLLVMValue()) ); } //----------------------------------------------------------------------------- // Bool Bool::Bool(llvm::Value * value) : Value(getBoolTy()) { this->_llvmValue = value; } Bool::Bool(value_type constantValue) : Value(getBoolTy()) { auto & codeGen = getThreadLocalCodeGen(); _llvmValue = codeGen->getInt1(constantValue); } value_op_t Bool::clone() const { Value * cloned = new Bool(_llvmValue); return value_op_t(cloned); } value_op_t Bool::castString(const std::string & str) { auto & codeGen = getThreadLocalCodeGen(); llvm::Value * value; if (str == "true") { // TODO case insensitive value = codeGen->getInt1(true); } else if (str == "false") { value = codeGen->getInt1(false); } else { throw InvalidOperationException("invalid string representation of a boolean value"); } value_op_t sqlValue( new Bool(value) ); return sqlValue; } value_op_t Bool::castString(cg_ptr8_t str, cg_size_t length) { throw NotImplementedException(); } value_op_t Bool::fromRawValues(const std::vector<llvm::Value *> & values) { assert(!values.empty()); return value_op_t(new Bool(values.front())); } value_op_t Bool::load(llvm::Value * ptr) { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * boolTy = getPointeeType(ptr); assert(boolTy == codeGen->getInt1Ty()); llvm::Value * value = codeGen->CreateLoad(boolTy, ptr); value_op_t sqlValue( new Bool(value) ); return sqlValue; } void Bool::store(llvm::Value * ptr) const { auto & codeGen = getThreadLocalCodeGen(); codeGen->CreateStore(_llvmValue, ptr); } cg_hash_t Bool::hash() const { return genIntHash(_llvmValue); } void Bool::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t Bool::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } auto & codeGen = getThreadLocalCodeGen(); return cg_bool_t( codeGen->CreateICmpEQ(_llvmValue, other.getLLVMValue()) ); } //----------------------------------------------------------------------------- // BasicString BasicString::BasicString(SqlType type, llvm::Value * value, llvm::Value * length) : Value(type) { this->_llvmValue = value; this->_length = length; } std::vector<llvm::Value *> BasicString::getRawValues() const { return { _llvmValue, _length }; } static inline unsigned lengthIndicatorSize(size_t length) { return (length < 256) ? 8 : (length < 65536) ? 16 : 32; } llvm::Value * BasicString::loadStringLength(llvm::Value * ptr, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); unsigned size = lengthIndicatorSize(type.length); // depending on the max size the length indicator has different sizes switch (size) { case 8: // load i8 return codeGen->CreateLoad(codeGen->getInt8Ty(), ptr); case 16: // load i16 return codeGen->CreateLoad(codeGen->getInt16Ty(), ptr); case 32: // load i32 return codeGen->CreateLoad(codeGen->getInt32Ty(), ptr); default: unreachable(); } } cg_bool_t BasicString::equalBuffers(const BasicString & str1, const BasicString & str2) { auto & codeGen = getThreadLocalCodeGen(); auto & funcGen = codeGen.getCurrentFunctionGen(); // two strings can only be equal if they are of equal length cg_bool_t lenEQ( codeGen->CreateICmpEQ(str1.getLength(), str2.getLength()) ); // now check if the strings actually match IfGen check( funcGen, lenEQ, {{"eq", cg_bool_t(false)}} ); { cg_size_t len(str1.getLength()); cg_voidptr_t s1(str1.getLLVMValue()); cg_voidptr_t s2(str2.getLLVMValue()); cg_int_t diff = Functions::genMemcmpCall(s1, s2, len); check.setVar( 0, diff == cg_int_t(0) ); } check.EndIf(); return cg_bool_t( check.getResult(0) ); } //----------------------------------------------------------------------------- // Char Char::Char(SqlType type, llvm::Value * value, llvm::Value * length) : BasicString(type, value, length) { assert(type.typeID == SqlType::TypeID::CharID && !type.nullable); } value_op_t Char::clone() const { return value_op_t( new Char(type, _llvmValue, _length) ); } value_op_t Char::castString(const std::string & str, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); llvm::Value * strValue, * length; // only Chars with a length of 1 need special treatment if (type.length == 1) { assert(str.size() == 1); strValue = codeGen->getInt8(static_cast<uint8_t>(str[0])); length = codeGen->getInt8(1); } else { unsigned len = static_cast<unsigned>(str.size()); uint32_t maxLen = type.length; // str should fit into the provided Varchar type if (len > maxLen) { throw std::runtime_error("type mismatch"); } unsigned size = lengthIndicatorSize(type.length); length = codeGen->getIntN(size, len); strValue = codeGen->CreateGlobalString(str); } return value_op_t( new Char(type, strValue, length) ); } value_op_t Char::castString(cg_ptr8_t str, cg_size_t length, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); llvm::Value * strValue, * truncLength; // only Chars with a length of 1 need special treatment if (type.length == 1) { truncLength = codeGen->getInt8(1); strValue = codeGen->CreateLoad(codeGen->getInt8Ty(), str); } else { unsigned size = lengthIndicatorSize(type.length); truncLength = codeGen->CreateTrunc(length, codeGen->getIntNTy(size)); strValue = str; } return value_op_t( new Char(type, strValue, truncLength) ); } value_op_t Char::fromRawValues(const std::vector<llvm::Value *> & values, SqlType type) { assert(values.size() >= 2); return value_op_t(new Char(type, values[0], values[1])); } value_op_t Char::load(llvm::Value * ptr, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); llvm::Value * strValue, * length; llvm::Type * charTy = getPointeeType(ptr); // only Chars with a length of 1 need special treatment if (type.length == 1) { strValue = codeGen->CreateLoad(charTy, ptr); length = codeGen->getInt8(1); } else { strValue = codeGen->CreateStructGEP(charTy, ptr, 1); length = loadStringLength(ptr, type); } return value_op_t( new Char(type, strValue, length) ); } void Char::store(llvm::Value * ptr) const { auto & codeGen = getThreadLocalCodeGen(); // only Chars with a length of 1 need special treatment if (type.length == 1) { codeGen->CreateStore(_llvmValue, ptr); } else { llvm::Type * valueTy = getLLVMType(); // store the Char's length codeGen->CreateStore(_length, ptr); // store the Char's data llvm::Value * strPtr = codeGen->CreateStructGEP(valueTy, ptr, 1); #if LLVM_VERSION_MAJOR < 7 codeGen->CreateMemCpy(strPtr, _llvmValue, _length, 0); #else /* CallInst * CreateMemCpy ( Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr) */ codeGen->CreateMemCpy(strPtr, 1, _llvmValue, 1, _length); #endif } } cg_hash_t Char::hash() const { // only Chars with a length of 1 need special treatment if (type.length == 1) { return genIntHash(_llvmValue); } else { auto & codeGen = getThreadLocalCodeGen(); cg_ptr8_t strPtr(_llvmValue); return genStringHash(codeGen, strPtr, cg_size_t(_length)); } } void Char::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t Char::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } auto & codeGen = getThreadLocalCodeGen(); if (type.length == 1) { return cg_bool_t( codeGen->CreateICmpEQ(_llvmValue, other.getLLVMValue()) ); } else { return equalBuffers(*this, static_cast<const BasicString &>(other)); } } cg_bool_t Char::compare(const Value & other, ComparisonMode mode) const { throw NotImplementedException("Char::compare"); } //----------------------------------------------------------------------------- // Text /*Text::Text(SqlType type, llvm::Value * value, llvm::Value * length) : BasicString(type, value, length) { }*/ Text::Text(llvm::Value * value) : BasicString(getTextTy(), value, getThreadLocalCodeGen()->getInt8(16)) { } Text::Text(SqlType type, llvm::Value * value) : BasicString(type, value, getThreadLocalCodeGen()->getInt8(16)) { assert(type.typeID == SqlType::TypeID::TextID && !type.nullable); } value_op_t Text::clone() const { return value_op_t( new Text(type, _llvmValue) ); } void storeText(char *dest, uint8_t * beginPtr, size_t len) { if (len > 15) { uint8_t * endPtr = beginPtr+len; uintptr_t first_value = reinterpret_cast<uintptr_t>(beginPtr); first_value ^= static_cast<uintptr_t>(1) << (8*sizeof(uintptr_t)-1); memcpy(dest,(char*)&first_value,8); memcpy(dest + 8, &endPtr, 8); } else { dest[0] = (char) len; memcpy(&dest[1],beginPtr,len); free(beginPtr); } } void storeTextGen(char *dest, const uint8_t * bytes, size_t len) { if (len > 15) { std::unique_ptr<uint8_t[]> data(new uint8_t[len]); std::memcpy(data.get(), bytes, len); auto & storedStr = StringPool::instance().put(sql_string_t(len, std::move(data))); uint8_t * beginPtr = storedStr.second.get(); uint8_t * endPtr = beginPtr+len; uintptr_t first_value = reinterpret_cast<uintptr_t>(beginPtr); first_value ^= static_cast<uintptr_t>(1) << (8*sizeof(uintptr_t)-1); memcpy(dest,(char*)&first_value,8); memcpy(dest + 8, &endPtr, 8); } else { dest[0] = (char) len; memcpy(&dest[1],bytes,len); } } void* textBegin(char *stringPtr) { uint8_t len = stringPtr[0]; if (len > 15) { uintptr_t *uintptr = reinterpret_cast<uintptr_t *>(stringPtr); return (void*) uintptr[0]; } return (void*) &stringPtr[1]; } uint64_t getLengthText(char *stringPtr) { uint8_t len = stringPtr[0]; if (len > 15) { uintptr_t *uintptr = reinterpret_cast<uintptr_t *>(stringPtr); uintptr_t first_value = uintptr[0]; uintptr_t second_value = uintptr[1]; len = second_value - first_value; } return len; } value_op_t Text::castString(const std::string & str, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); //llvm::Value * strValue = codeGen->CreateGlobalString(std::string("AAAAAAAAAAAAAAAA")); cg_voidptr_t arrayPtr = cg_voidptr_t( llvm::cast<llvm::Value>(codeGen->CreateAlloca(llvm::Type::getInt64Ty(codeGen.getLLVMContext()),2)) ); size_t len = str.size(); uint8_t* data = new uint8_t[len]; std::memcpy(data, str.c_str(), len); uint8_t * beginPtr; if (len > 15) { std::unique_ptr<uint8_t[]> dataPtr(data); auto & storedStr = StringPool::instance().put(sql_string_t(len, std::move(dataPtr))); beginPtr = storedStr.second.get(); } else { beginPtr = data; } llvm::FunctionType * funcTy = llvm::TypeBuilder<void (void *, void *, size_t), false>::get(codeGen.getLLVMContext()); llvm::Function * func = llvm::cast<llvm::Function>( getThreadLocalCodeGen().getCurrentModuleGen().getModule().getOrInsertFunction("storeText", funcTy) ); getThreadLocalCodeGen().getCurrentModuleGen().addFunctionMapping(func,(void *)&storeText); codeGen->CreateCall(func, { arrayPtr, cg_ptr8_t::fromRawPointer(beginPtr) , cg_u64_t(len) }); return value_op_t( new Text(type, arrayPtr) ); } value_op_t Text::castString(cg_ptr8_t str, cg_size_t length, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); cg_voidptr_t arrayPtr = cg_voidptr_t( llvm::cast<llvm::Value>(codeGen->CreateAlloca(llvm::Type::getInt64Ty(codeGen.getLLVMContext()),2)) ); auto & context = codeGen.getLLVMContext(); llvm::FunctionType * funcTy = llvm::TypeBuilder<void (const char *, const char*, size_t), false>::get(context); llvm::CallInst * result = codeGen.CreateCall(&storeTextGen, funcTy, {arrayPtr, str, length}); return value_op_t( new Text(type, arrayPtr) ); } value_op_t Text::fromRawValues(const std::vector<llvm::Value *> & values, SqlType type) { return value_op_t(new Text(values.front())); } value_op_t Text::load(llvm::Value * ptr, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); //llvm::Type * llvmType = toLLVMTy(type); cg_voidptr_t arrayPtr = cg_voidptr_t( llvm::cast<llvm::Value>(codeGen->CreateAlloca(llvm::Type::getInt64Ty(codeGen.getLLVMContext()),2)) ); //llvm::Value * begin = codeGen->CreateStructGEP(llvmType, ptr, 0); //llvm::Value * strPtr = codeGen->CreateGlobalString(std::string("AAAAAAAAAAAAAAAA")); codeGen->CreateMemCpy(arrayPtr, 0, ptr, 0, 16); /*llvm::FunctionType * funcTy = llvm::TypeBuilder<int (void *), false>::get(codeGen.getLLVMContext()); llvm::Function * func = llvm::cast<llvm::Function>( getThreadLocalCodeGen().getCurrentModuleGen().getModule().getOrInsertFunction("getLengthText", funcTy) ); getThreadLocalCodeGen().getCurrentModuleGen().addFunctionMapping(func,(void *)&getLengthText); llvm::CallInst * result = codeGen->CreateCall(func, { strPtr }); cg_u64_t length = cg_u64_t( llvm::cast<llvm::Value>(result) );*/ return value_op_t( new Text(type, arrayPtr) ); } void Text::store(llvm::Value * ptr) const { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * valueTy = getLLVMType(); // store the Char's data //llvm::Value * strPtr = codeGen->CreateStructGEP(valueTy, ptr, 0); #if LLVM_VERSION_MAJOR < 7 codeGen->CreateMemCpy(strPtr, _llvmValue, _length, 0); #else /* CallInst * CreateMemCpy ( Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr) */ //strValue = codeGen->CreateLoad(charTy, ptr); codeGen->CreateMemCpy(ptr, 0, _llvmValue, 0, 16); #endif } cg_hash_t Text::hash() const { auto & codeGen = getThreadLocalCodeGen(); llvm::FunctionType * funcTy = llvm::TypeBuilder<int (void *), false>::get(codeGen.getLLVMContext()); llvm::Function * func = llvm::cast<llvm::Function>( getThreadLocalCodeGen().getCurrentModuleGen().getModule().getOrInsertFunction("getLengthText", funcTy) ); getThreadLocalCodeGen().getCurrentModuleGen().addFunctionMapping(func,(void *)&getLengthText); llvm::CallInst * result = codeGen->CreateCall(func, { _llvmValue }); cg_u64_t length = cg_u64_t( llvm::cast<llvm::Value>(result) ); llvm::FunctionType * funcTyBegin = llvm::TypeBuilder<void* (void *), false>::get(codeGen.getLLVMContext()); llvm::Function * funcBegin = llvm::cast<llvm::Function>( getThreadLocalCodeGen().getCurrentModuleGen().getModule().getOrInsertFunction("textBegin", funcTyBegin) ); getThreadLocalCodeGen().getCurrentModuleGen().addFunctionMapping(funcBegin,(void *)&textBegin); llvm::CallInst * resultBegin = codeGen->CreateCall(funcBegin, { _llvmValue }); cg_voidptr_t begin = cg_voidptr_t( llvm::cast<llvm::Value>(resultBegin) ); return genStringHash(codeGen, begin, length); } void Text::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t Text::equals(const Value & other) const { auto & codeGen = getThreadLocalCodeGen(); if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } llvm::FunctionType * funcTy = llvm::TypeBuilder<int (void *), false>::get(codeGen.getLLVMContext()); llvm::Function * func = llvm::cast<llvm::Function>( getThreadLocalCodeGen().getCurrentModuleGen().getModule().getOrInsertFunction("getLengthText", funcTy) ); getThreadLocalCodeGen().getCurrentModuleGen().addFunctionMapping(func,(void *)&getLengthText); llvm::CallInst * _otherLength = codeGen->CreateCall(func, { static_cast<const Text &>(other).getLLVMValue() }); cg_u64_t otherlength = cg_u64_t( llvm::cast<llvm::Value>(_otherLength) ); llvm::CallInst * _thisLength = codeGen->CreateCall(func, { _llvmValue }); cg_u64_t thisLength = cg_u64_t( llvm::cast<llvm::Value>(_thisLength) ); cg_bool_t isLengthEqual = otherlength == thisLength; llvm::FunctionType * funcTyBegin = llvm::TypeBuilder<void* (void *), false>::get(codeGen.getLLVMContext()); llvm::Function * funcBegin = llvm::cast<llvm::Function>( getThreadLocalCodeGen().getCurrentModuleGen().getModule().getOrInsertFunction("textBegin", funcTyBegin) ); getThreadLocalCodeGen().getCurrentModuleGen().addFunctionMapping(funcBegin,(void *)&textBegin); IfGen check( codeGen.getCurrentFunctionGen(), isLengthEqual, {{"isEqual", cg_bool_t(true)}} ); { llvm::CallInst * _otherBegin = codeGen->CreateCall(funcBegin, { static_cast<const Text &>(other).getLLVMValue() }); cg_voidptr_t otherBegin = cg_voidptr_t( llvm::cast<llvm::Value>(_otherBegin) ); llvm::CallInst * _thisBegin = codeGen->CreateCall(funcBegin, { _llvmValue }); cg_voidptr_t thisBegin = cg_voidptr_t( llvm::cast<llvm::Value>(_thisBegin) ); cg_int_t compareResult = Functions::genMemcmpCall(otherBegin,thisBegin,thisLength); check.setVar(0, cg_bool_t(compareResult == cg_int_t(0))); } check.EndIf(); cg_bool_t result(check.getResult(0)); cg_bool_t _result = isLengthEqual && result; return _result; } cg_bool_t Text::compare(const Value & other, ComparisonMode mode) const { throw NotImplementedException("Text::compare"); } //----------------------------------------------------------------------------- // Varchar Varchar::Varchar(SqlType type, llvm::Value * value, llvm::Value * length) : BasicString(type, value, length) { assert(type.typeID == SqlType::TypeID::VarcharID && !type.nullable); } value_op_t Varchar::clone() const { return value_op_t( new Varchar(type, _llvmValue, _length) ); } value_op_t Varchar::castString(const std::string & str, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); unsigned len = static_cast<unsigned>(str.size()); uint32_t maxLen = type.length; // str should fit into the provided Varchar type if (len > maxLen) { throw std::runtime_error("type mismatch"); } unsigned size = lengthIndicatorSize(type.length); llvm::Value * length = codeGen->getIntN(size, len); llvm::Value * strValue = codeGen->CreateGlobalString(str); return value_op_t( new Varchar(type, strValue, length) ); } value_op_t Varchar::castString(cg_ptr8_t str, cg_size_t length, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); unsigned size = lengthIndicatorSize(type.length); llvm::Value * truncLength = codeGen->CreateTrunc(length, codeGen->getIntNTy(size)); return value_op_t( new Varchar(type, str, truncLength) ); } value_op_t Varchar::fromRawValues(const std::vector<llvm::Value *> & values, SqlType type) { assert(values.size() >= 2); return value_op_t(new Varchar(type, values[0], values[1])); } value_op_t Varchar::load(llvm::Value * ptr, SqlType type) { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * varcharTy = getPointeeType(ptr); llvm::Value * strPtr = codeGen->CreateStructGEP(varcharTy, ptr, 1); llvm::Value * length = loadStringLength(ptr, type); return value_op_t( new Varchar(type, strPtr, length) ); } void Varchar::store(llvm::Value * ptr) const { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * valueTy = getLLVMType(); // store the Varchar's length codeGen->CreateStore(_length, ptr); // store the Varchar's data llvm::Value * strPtr = codeGen->CreateStructGEP(valueTy, ptr, 1); // Functions::genPrintfCall("store Varchar at: %p\n", strPtr); #if LLVM_VERSION_MAJOR < 7 codeGen->CreateMemCpy(strPtr, _llvmValue, _length, 0); #else /* CallInst * CreateMemCpy ( Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size, bool isVolatile=false, MDNode *TBAATag=nullptr, MDNode *TBAAStructTag=nullptr, MDNode *ScopeTag=nullptr, MDNode *NoAliasTag=nullptr) */ codeGen->CreateMemCpy(strPtr, 1, _llvmValue, 1, _length); #endif } cg_hash_t Varchar::hash() const { auto & codeGen = getThreadLocalCodeGen(); cg_ptr8_t strPtr(_llvmValue); return genStringHash(codeGen, strPtr, cg_size_t(_length)); } void Varchar::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t Varchar::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } return equalBuffers(*this, static_cast<const BasicString &>(other)); } cg_bool_t Varchar::compare(const Value & other, ComparisonMode mode) const { throw NotImplementedException("Varchar::compare"); } //----------------------------------------------------------------------------- // Date Date::Date(llvm::Value * value) : Value(getDateTy()) { this->_llvmValue = value; } Date::Date(value_type constantValue) : Value(getDateTy()) { _llvmValue = cg_value_type(constantValue); } value_op_t Date::clone() const { Value * cloned = new Date(_llvmValue); return value_op_t(cloned); } value_op_t Date::castString(const std::string & str) { value_type raw = castStringToDateValue(str.c_str(), static_cast<uint32_t>(str.length())); llvm::Value * value = cg_value_type(raw); value_op_t sqlValue( new Date(value) ); return sqlValue; } value_op_t Date::castString(cg_ptr8_t str, cg_size_t length) { cg_value_type raw = genCastStringToDateValueCall(str, length); value_op_t sqlValue( new Date(raw) ); return sqlValue; } value_op_t Date::fromRawValues(const std::vector<llvm::Value *> & values) { assert(!values.empty()); return value_op_t(new Date(values.front())); } value_op_t Date::load(llvm::Value * ptr) { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * dateTy = getPointeeType(ptr); assert(dateTy == cg_value_type::getType()); llvm::Value * value = codeGen->CreateLoad(dateTy, ptr); value_op_t sqlValue( new Date(value) ); return sqlValue; } void Date::store(llvm::Value * ptr) const { auto & codeGen = getThreadLocalCodeGen(); codeGen->CreateStore(_llvmValue, ptr); } cg_hash_t Date::hash() const { // can be used for all integral types return genIntHash(_llvmValue); } void Date::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t Date::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } auto & codeGen = getThreadLocalCodeGen(); return cg_bool_t( codeGen->CreateICmpEQ(_llvmValue, other.getLLVMValue()) ); } //----------------------------------------------------------------------------- // Timestamp Timestamp::Timestamp(llvm::Value * value) : Value(getTimestampTy()) { this->_llvmValue = value; } Timestamp::Timestamp(value_type constantValue) : Value(getTimestampTy()) { _llvmValue = cg_value_type(constantValue); } value_op_t Timestamp::clone() const { Value * cloned = new Timestamp(_llvmValue); return value_op_t(cloned); } value_op_t Timestamp::castString(const std::string & str) { value_type raw = castStringToTimestampValue(str.c_str(), static_cast<uint32_t>(str.length())); llvm::Value * value = cg_value_type(raw); value_op_t sqlValue( new Timestamp(value) ); return sqlValue; } value_op_t Timestamp::castString(cg_ptr8_t str, cg_size_t length) { cg_value_type raw = genCastStringToTimestampValueCall(str, length); value_op_t sqlValue( new Timestamp(raw) ); return sqlValue; } value_op_t Timestamp::fromRawValues(const std::vector<llvm::Value *> & values) { assert(!values.empty()); return value_op_t(new Timestamp(values.front())); } value_op_t Timestamp::load(llvm::Value * ptr) { auto & codeGen = getThreadLocalCodeGen(); llvm::Type * timestampTy = getPointeeType(ptr); assert(timestampTy == cg_value_type::getType()); llvm::Value * value = codeGen->CreateLoad(timestampTy, ptr); value_op_t sqlValue( new Timestamp(value) ); return sqlValue; } void Timestamp::store(llvm::Value * ptr) const { auto & codeGen = getThreadLocalCodeGen(); codeGen->CreateStore(_llvmValue, ptr); } cg_hash_t Timestamp::hash() const { // can be used for all integral types return genIntHash(_llvmValue); } void Timestamp::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t Timestamp::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } if (isNullable(other)) { return other.equals(*this); } auto & codeGen = getThreadLocalCodeGen(); return cg_bool_t( codeGen->CreateICmpEQ(_llvmValue, other.getLLVMValue()) ); } //----------------------------------------------------------------------------- // UnknownValue UnknownValue::UnknownValue() : Value(getUnknownTy()) { } value_op_t UnknownValue::create() { return value_op_t(new UnknownValue); } std::vector<llvm::Value *> UnknownValue::getRawValues() const { return { }; } void UnknownValue::store(llvm::Value * ptr) const { // nop } cg_hash_t UnknownValue::hash() const { // arbitrary constant return cg_hash_t(0x2c8e4eecfc696c50ul); } value_op_t UnknownValue::clone() const { return create(); } void UnknownValue::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t UnknownValue::equals(const Value & other) const { return cg_bool_t(false); } cg_bool_t UnknownValue::compare(const Value & other, ComparisonMode mode) const { return cg_bool_t(false); } //----------------------------------------------------------------------------- // NullableValue (with external null indicator) #ifndef USE_INTERNAL_NULL_INDICATOR /// NullableValue (with external null indicator) NullableValue::NullableValue(value_op_t sqlValue, cg_bool_t nullIndicator) : Value( Sql::toNullableTy( sqlValue->type ) ), _sqlValue(std::move(sqlValue)), _nullIndicator(nullIndicator) { // Functions::genPrintfCall("NullableValue ctor nullable %d\n", _nullIndicator.llvmValue); assert(!_sqlValue->type.nullable && type.typeID != SqlType::TypeID::UnknownID); assert(dynamic_cast<NullableValue *>(_sqlValue.get()) == nullptr); // do not nest NullableValues this->_llvmValue = _sqlValue->getLLVMValue(); } value_op_t NullableValue::getNull(SqlType type) { SqlType notNullableType = toNotNullableTy(type); switch (type.typeID) { case SqlType::TypeID::BoolID: { value_op_t nullBool = Integer::castString("false"); return create(std::move(nullBool), cg_bool_t(true)); } case SqlType::TypeID::IntegerID: { value_op_t nullInteger = Integer::castString("0"); return create(std::move(nullInteger), cg_bool_t(true)); } case SqlType::TypeID::NumericID: { value_op_t nullNumeric = Numeric::castString("0", notNullableType); return create(std::move(nullNumeric), cg_bool_t(true)); } case SqlType::TypeID::VarcharID: { value_op_t nullVarchar = Varchar::castString(std::string(type.length, ' '), notNullableType); return create(std::move(nullVarchar), cg_bool_t(true)); } case SqlType::TypeID::CharID: { value_op_t nullChar = Char::castString(std::string(type.length, ' '), notNullableType); return create(std::move(nullChar), cg_bool_t(true)); } case SqlType::TypeID::DateID: // TODO case SqlType::TypeID::TimestampID: // TODO throw NotImplementedException(); default: unreachable(); } } value_op_t NullableValue::create(value_op_t value, cg_bool_t nullIndicator) { return value_op_t( new NullableValue(std::move(value), nullIndicator) ); } value_op_t NullableValue::create(const Value & value, cg_bool_t nullIndicator) { const Value & assoc = getAssociatedValue(value); return create(assoc.clone(), nullIndicator); } value_op_t NullableValue::load(llvm::Value * ptr, SqlType type) { assert(type.nullable); auto & codeGen = getThreadLocalCodeGen(); llvm::Type * valueTy = Sql::toLLVMTy(type); llvm::Value * innerValuePtr = codeGen->CreateStructGEP(valueTy, ptr, 0); SqlType notNullableType = Sql::toNotNullableTy(type); value_op_t sqlValue = Value::load(innerValuePtr, notNullableType); llvm::Value * nullIndicatorPtr = codeGen->CreateStructGEP(valueTy, ptr, 1); cg_bool_t nullIndicator( codeGen->CreateLoad(cg_bool_t::getType(), nullIndicatorPtr) ); return NullableValue::create(std::move(sqlValue), cg_bool_t(nullIndicator)); } value_op_t NullableValue::clone() const { value_op_t cloned = _sqlValue->clone(); return create(std::move(cloned), _nullIndicator); } std::vector<llvm::Value *> NullableValue::getRawValues() const { auto values = _sqlValue->getRawValues(); values.push_back(_nullIndicator.llvmValue); return values; } void NullableValue::store(llvm::Value * ptr) const { assert(type.nullable); auto & codeGen = getThreadLocalCodeGen(); llvm::Type * valueTy = getLLVMType(); llvm::Value * innerValuePtr = codeGen->CreateStructGEP(valueTy, ptr, 0); _sqlValue->store(innerValuePtr); llvm::Value * nullIndicatorPtr = codeGen->CreateStructGEP(valueTy, ptr, 1); codeGen->CreateStore(_nullIndicator.llvmValue, nullIndicatorPtr); } cg_hash_t NullableValue::hash() const { cg_hash_t nullHash = 0x4d1138f9dd82ae2f; // arbitrary random number PhiNode<llvm::Value> result(nullHash, "hash"); IfGen nullCheck(!isNull()); { result = _sqlValue->hash(); } nullCheck.EndIf(); return cg_hash_t( result.get() ); } cg_bool_t NullableValue::isNull() const { return _nullIndicator; } Value & NullableValue::getValue() const { return *_sqlValue; } void NullableValue::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t NullableValue::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } PhiNode<llvm::Value> result(cg_bool_t(false), "equals"); IfGen nullCheck(!isNull()); { result = _sqlValue->equals(other); } nullCheck.EndIf(); return cg_bool_t(result.get()); } cg_bool_t NullableValue::compare(const Value & other, ComparisonMode mode) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } PhiNode<llvm::Value> result(cg_bool_t(false), "result"); IfGen nullCheck(!isNull()); { result = _sqlValue->compare(other, mode); } nullCheck.EndIf(); return cg_bool_t(result.get()); } #else // null constants static Integer::value_type integerNullIndicator = std::numeric_limits<typename Integer::value_type>::min(); static Numeric::value_type numericNullIndicator = std::numeric_limits<typename Numeric::value_type>::min(); // bool: nothing // TODO: static Char::length_type charNullIndicator = numeric_limits<typename Char::length_type>::max(); // TODO: static Varchar::length_type varcharNullIndicator = numeric_limits<typename Varchar::length_type>::max(); static Date::value_type dateNullIndicator = std::numeric_limits<typename Date::value_type>::max(); static Timestamp::value_type timestampNullIndicator = std::numeric_limits<typename Timestamp::value_type>::max(); /// NullableValue (with internal null indicator) NullableValue::NullableValue(value_op_t sqlValue) : Value( Sql::toNullableTy( sqlValue->type ) ), _sqlValue(std::move(sqlValue)) { assert(!_sqlValue->type.nullable && type.typeID != SqlType::TypeID::UnknownID); assert(dynamic_cast<NullableValue *>(_sqlValue.get()) == nullptr); // do not nest NullableValues this->_llvmValue = _sqlValue->getLLVMValue(); } value_op_t NullableValue::getNull(SqlType type) { SqlType notNullableType = toNotNullableTy(type); switch (type.typeID) { case SqlType::TypeID::BoolID: { throw InvalidOperationException("use an external null indicator instead"); } case SqlType::TypeID::IntegerID: { value_op_t nullInteger( new Integer(integerNullIndicator) ); return create(std::move(nullInteger)); } case SqlType::TypeID::NumericID: { value_op_t nullNumeric( new Numeric(notNullableType, numericNullIndicator) ); return create(std::move(nullNumeric)); } case SqlType::TypeID::VarcharID: { throw NotImplementedException(); } case SqlType::TypeID::CharID: { throw NotImplementedException(); } case SqlType::TypeID::DateID: { value_op_t nullDate( new Date(dateNullIndicator) ); return create(std::move(nullDate)); } case SqlType::TypeID::TimestampID: { value_op_t nullTimestamp( new Timestamp(timestampNullIndicator) ); return create(std::move(nullTimestamp)); } default: unreachable(); } } value_op_t NullableValue::create(value_op_t value) { return value_op_t( new NullableValue(std::move(value)) ); } value_op_t NullableValue::create(const Value & value) { const Value & assoc = getAssociatedValue(value); return create(assoc.clone()); } value_op_t NullableValue::load(llvm::Value * ptr, SqlType type) { assert(type.nullable); SqlType notNullableType = Sql::toNotNullableTy(type); value_op_t sqlValue = Value::load(ptr, notNullableType); return NullableValue::create(std::move(sqlValue)); } value_op_t NullableValue::clone() const { value_op_t cloned = _sqlValue->clone(); return create(std::move(cloned)); } std::vector<llvm::Value *> NullableValue::getRawValues() const { return _sqlValue->getRawValues(); } void NullableValue::store(llvm::Value * ptr) const { assert(type.nullable); _sqlValue->store(ptr); } cg_hash_t NullableValue::hash() const { cg_hash_t nullHash = 0x4d1138f9dd82ae2f; // arbitrary random number PhiNode<llvm::Value> result(nullHash, "hash"); IfGen nullCheck(!isNull()); { result = _sqlValue->hash(); } nullCheck.EndIf(); return cg_hash_t( result.get() ); } cg_bool_t NullableValue::isNull() const { switch (type.typeID) { case SqlType::TypeID::BoolID: { throw InvalidOperationException("use an external null indicator instead"); } case SqlType::TypeID::IntegerID: { Integer::cg_value_type a(integerNullIndicator); Integer::cg_value_type b(_sqlValue->getLLVMValue()); return (a == b); } case SqlType::TypeID::NumericID: { Numeric::cg_value_type a(numericNullIndicator); Numeric::cg_value_type b(_sqlValue->getLLVMValue()); return (a == b); } case SqlType::TypeID::VarcharID: { throw NotImplementedException(); } case SqlType::TypeID::CharID: { throw NotImplementedException(); } case SqlType::TypeID::DateID: { Date::cg_value_type a(dateNullIndicator); Date::cg_value_type b(_sqlValue->getLLVMValue()); return (a == b); } case SqlType::TypeID::TimestampID: { Timestamp::cg_value_type a(timestampNullIndicator); Timestamp::cg_value_type b(_sqlValue->getLLVMValue()); return (a == b); } default: unreachable(); } } Value & NullableValue::getValue() const { return *_sqlValue; } void NullableValue::accept(ValueVisitor & visitor) { visitor.visit(*this); } cg_bool_t NullableValue::equals(const Value & other) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } PhiNode<llvm::Value> result(cg_bool_t(false), "equals"); IfGen nullCheck(!isNull()); { result = _sqlValue->equals(other); } nullCheck.EndIf(); return cg_bool_t(result.get()); } cg_bool_t NullableValue::compare(const Value & other, ComparisonMode mode) const { if (!Sql::equals(type, other.type, SqlTypeEqualsMode::WithoutNullable)) { return cg_bool_t(false); } PhiNode<llvm::Value> result(cg_bool_t(false), "result"); IfGen nullCheck(!isNull()); { result = _sqlValue->compare(other, mode); } nullCheck.EndIf(); return cg_bool_t(result.get()); } #endif // USE_INTERNAL_NULL_INDICATOR //----------------------------------------------------------------------------- // utils bool isNullable(const Value & value) { return (dynamic_cast<const NullableValue *>(&value) != nullptr); } bool mayBeNull(const Value & value) { if (value.type.typeID == SqlType::TypeID::UnknownID) { return true; } return (dynamic_cast<const NullableValue *>(&value) != nullptr); } bool isUnknown(const Value & value) { return (value.type.typeID == SqlType::TypeID::UnknownID); } const Value & getAssociatedValue(const Value & value) { if (const NullableValue * nv = dynamic_cast<const NullableValue *>(&value)) { return nv->getValue(); } else { return value; } } bool isNumerical(const Value & value) { using TypeID = SqlType::TypeID; auto typeID = value.type.typeID; return (typeID == TypeID::UnknownID || typeID == TypeID::IntegerID || typeID == TypeID::NumericID); } #ifdef USE_INTERNAL_NULL_INDICATOR llvm::Value * getNullIndicator(SqlType type) { switch (type.typeID) { case SqlType::TypeID::BoolID: return nullptr; case SqlType::TypeID::IntegerID: return Integer::cg_value_type(integerNullIndicator); case SqlType::TypeID::NumericID: return Numeric::cg_value_type(numericNullIndicator); case SqlType::TypeID::VarcharID: { throw NotImplementedException(); } case SqlType::TypeID::CharID: { throw NotImplementedException(); } case SqlType::TypeID::DateID: return Date::cg_value_type(dateNullIndicator); case SqlType::TypeID::TimestampID: return Timestamp::cg_value_type(timestampNullIndicator); default: unreachable(); } } #endif // USE_INTERNAL_NULL_INDICATOR } // end namespace Sql
30.280044
171
0.638538
[ "vector" ]
39434b0ba020af7ad39ab0dba27d8853522c57fc
635
cpp
C++
Makefile.cpp
marcospb19/Makefile
2ea3854c70d8ea08fda3ca3095ecb199151cd6c6
[ "MIT" ]
2
2019-10-24T23:40:39.000Z
2020-11-28T18:05:23.000Z
Makefile.cpp
marcospb19/Makefile
2ea3854c70d8ea08fda3ca3095ecb199151cd6c6
[ "MIT" ]
1
2020-03-25T18:53:09.000Z
2020-09-07T13:07:28.000Z
Makefile.cpp
marcospb19/Makefile
2ea3854c70d8ea08fda3ca3095ecb199151cd6c6
[ "MIT" ]
1
2019-10-24T15:56:31.000Z
2019-10-24T15:56:31.000Z
# Final program name PROGRAM = # Default target and pseudo-targets .DEFAULT_GOAL = $(PROGRAM) .PHONY = clean .PHONY = install # Compiler, Compilation flags, link flags CC = clang++ # g++ CFLAGS = -O2 -Wall -Wextra -Wshadow -std=c++11 LDFLAGS = # Object files to be built OBJECTS = cppfile1.o cppfile2.o ### Main targets $(PROGRAM): $(OBJECTS) $(CC) $(LDFLAGS) -o $(PROGRAM) $(OBJECTS) %.o: %.cpp $(CC) $(CFLAGS) -c $^ -o $@ ### ### Pseudo-targets clean: @rm $(OBJECTS) 2> /dev/null || exit 0 install: $(PROGRAM) @sudo cp $(PROGRAM) /usr/bin/ && \ echo "Installed, Thank you!" || \ echo "Some error occured." ###
16.710526
46
0.620472
[ "object" ]
3944b6512e08e636b7659ec1a877155e100b3154
17,419
hpp
C++
include/hecl/BitVector.hpp
linkmauve/hecl
57bfd8cb3fefb3e57caddef46b636d762ec642a1
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
hecl/include/hecl/BitVector.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
include/hecl/BitVector.hpp
RetroView/hecl
2d1328c04bdbe9928ae89ec5b51bedb51a0133f1
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
//===- llvm/ADT/BitVector.h - Bit vectors -----------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the BitVector class. // //===----------------------------------------------------------------------===// #pragma once #include "MathExtras.hpp" #include <algorithm> #include <cassert> #include <climits> #include <cstdint> #include <cstdlib> #include <cstring> namespace hecl { namespace llvm { class BitVector { typedef unsigned long BitWord; enum { BITWORD_SIZE = (unsigned)sizeof(BitWord) * CHAR_BIT }; static_assert(BITWORD_SIZE == 64 || BITWORD_SIZE == 32, "Unsupported word size"); BitWord* Bits; // Actual bits. unsigned Size; // Size of bitvector in bits. unsigned Capacity; // Number of BitWords allocated in the Bits array. public: typedef unsigned size_type; // Encapsulation of a single bit. class reference { friend class BitVector; BitWord* WordRef; unsigned BitPos; reference(); // Undefined public: reference(BitVector& b, unsigned Idx) { WordRef = &b.Bits[Idx / BITWORD_SIZE]; BitPos = Idx % BITWORD_SIZE; } reference(const reference&) = default; reference& operator=(reference t) { *this = bool(t); return *this; } reference& operator=(bool t) { if (t) *WordRef |= BitWord(1) << BitPos; else *WordRef &= ~(BitWord(1) << BitPos); return *this; } explicit operator bool() const { return ((*WordRef) & (BitWord(1) << BitPos)) != 0; } }; /// BitVector default ctor - Creates an empty bitvector. BitVector() : Size(0), Capacity(0) { Bits = nullptr; } /// BitVector ctor - Creates a bitvector of specified number of bits. All /// bits are initialized to the specified value. explicit BitVector(unsigned s, bool t = false) : Size(s) { Capacity = NumBitWords(s); Bits = (BitWord*)std::malloc(Capacity * sizeof(BitWord)); init_words(Bits, Capacity, t); if (t) clear_unused_bits(); } /// BitVector copy ctor. BitVector(const BitVector& RHS) : Size(RHS.size()) { if (Size == 0) { Bits = nullptr; Capacity = 0; return; } Capacity = NumBitWords(RHS.size()); Bits = (BitWord*)std::malloc(Capacity * sizeof(BitWord)); std::memcpy(Bits, RHS.Bits, Capacity * sizeof(BitWord)); } BitVector(BitVector&& RHS) : Bits(RHS.Bits), Size(RHS.Size), Capacity(RHS.Capacity) { RHS.Bits = nullptr; RHS.Size = RHS.Capacity = 0; } ~BitVector() { std::free(Bits); } /// empty - Tests whether there are no bits in this bitvector. bool empty() const { return Size == 0; } /// size - Returns the number of bits in this bitvector. size_type size() const { return Size; } /// count - Returns the number of bits which are set. size_type count() const { unsigned NumBits = 0; for (unsigned i = 0; i < NumBitWords(size()); ++i) NumBits += countPopulation(Bits[i]); return NumBits; } /// any - Returns true if any bit is set. bool any() const { for (unsigned i = 0; i < NumBitWords(size()); ++i) if (Bits[i] != 0) return true; return false; } /// all - Returns true if all bits are set. bool all() const { for (unsigned i = 0; i < Size / BITWORD_SIZE; ++i) if (Bits[i] != ~0UL) return false; // If bits remain check that they are ones. The unused bits are always zero. if (unsigned Remainder = Size % BITWORD_SIZE) return Bits[Size / BITWORD_SIZE] == (1UL << Remainder) - 1; return true; } /// none - Returns true if none of the bits are set. bool none() const { return !any(); } /// find_first - Returns the index of the first set bit, -1 if none /// of the bits are set. int find_first() const { for (unsigned i = 0; i < NumBitWords(size()); ++i) if (Bits[i] != 0) return i * BITWORD_SIZE + countTrailingZeros(Bits[i]); return -1; } /// find_next - Returns the index of the next set bit following the /// "Prev" bit. Returns -1 if the next set bit is not found. int find_next(unsigned Prev) const { ++Prev; if (Prev >= Size) return -1; unsigned WordPos = Prev / BITWORD_SIZE; unsigned BitPos = Prev % BITWORD_SIZE; BitWord Copy = Bits[WordPos]; // Mask off previous bits. Copy &= ~0UL << BitPos; if (Copy != 0) return WordPos * BITWORD_SIZE + countTrailingZeros(Copy); // Check subsequent words. for (unsigned i = WordPos + 1; i < NumBitWords(size()); ++i) if (Bits[i] != 0) return i * BITWORD_SIZE + countTrailingZeros(Bits[i]); return -1; } /// find_first_contiguous - Returns the index of the first contiguous /// set of bits of "Length", -1 if no contiguous bits found. int find_first_contiguous(unsigned Length, unsigned BucketSz) const { for (int idx = find_first(); idx != -1; idx = find_next(idx)) { if (idx + Length > size()) return -1; bool good = true; for (unsigned i = 0; i < Length; ++i) { int ThisIdx = idx + i; if (!test(ThisIdx)) { good = false; idx = ThisIdx; break; } } if (good) { unsigned space = BucketSz - (idx % BucketSz); if (space >= Length) return idx; } } return -1; } /// clear - Clear all bits. void clear() { Size = 0; } /// resize - Grow or shrink the bitvector. void resize(unsigned N, bool t = false) { if (N > Capacity * BITWORD_SIZE) { unsigned OldCapacity = Capacity; grow(N); init_words(&Bits[OldCapacity], (Capacity - OldCapacity), t); } // Set any old unused bits that are now included in the BitVector. This // may set bits that are not included in the new vector, but we will clear // them back out below. if (N > Size) set_unused_bits(t); // Update the size, and clear out any bits that are now unused unsigned OldSize = Size; Size = N; if (t || N < OldSize) clear_unused_bits(); } void reserve(unsigned N) { if (N > Capacity * BITWORD_SIZE) grow(N); } // Set, reset, flip BitVector& set() { init_words(Bits, Capacity, true); clear_unused_bits(); return *this; } BitVector& set(unsigned Idx) { assert(Bits && "Bits never allocated"); Bits[Idx / BITWORD_SIZE] |= BitWord(1) << (Idx % BITWORD_SIZE); return *this; } /// set - Efficiently set a range of bits in [I, E) BitVector& set(unsigned I, unsigned E) { assert(I <= E && "Attempted to set backwards range!"); assert(E <= size() && "Attempted to set out-of-bounds range!"); if (I == E) return *this; if (I / BITWORD_SIZE == E / BITWORD_SIZE) { BitWord EMask = 1UL << (E % BITWORD_SIZE); BitWord IMask = 1UL << (I % BITWORD_SIZE); BitWord Mask = EMask - IMask; Bits[I / BITWORD_SIZE] |= Mask; return *this; } BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE); Bits[I / BITWORD_SIZE] |= PrefixMask; I = alignTo(I, BITWORD_SIZE); for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE) Bits[I / BITWORD_SIZE] = ~0UL; BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1; if (I < E) Bits[I / BITWORD_SIZE] |= PostfixMask; return *this; } BitVector& reset() { init_words(Bits, Capacity, false); return *this; } BitVector& reset(unsigned Idx) { Bits[Idx / BITWORD_SIZE] &= ~(BitWord(1) << (Idx % BITWORD_SIZE)); return *this; } /// reset - Efficiently reset a range of bits in [I, E) BitVector& reset(unsigned I, unsigned E) { assert(I <= E && "Attempted to reset backwards range!"); assert(E <= size() && "Attempted to reset out-of-bounds range!"); if (I == E) return *this; if (I / BITWORD_SIZE == E / BITWORD_SIZE) { BitWord EMask = 1UL << (E % BITWORD_SIZE); BitWord IMask = 1UL << (I % BITWORD_SIZE); BitWord Mask = EMask - IMask; Bits[I / BITWORD_SIZE] &= ~Mask; return *this; } BitWord PrefixMask = ~0UL << (I % BITWORD_SIZE); Bits[I / BITWORD_SIZE] &= ~PrefixMask; I = alignTo(I, BITWORD_SIZE); for (; I + BITWORD_SIZE <= E; I += BITWORD_SIZE) Bits[I / BITWORD_SIZE] = 0UL; BitWord PostfixMask = (1UL << (E % BITWORD_SIZE)) - 1; if (I < E) Bits[I / BITWORD_SIZE] &= ~PostfixMask; return *this; } BitVector& flip() { for (unsigned i = 0; i < NumBitWords(size()); ++i) Bits[i] = ~Bits[i]; clear_unused_bits(); return *this; } BitVector& flip(unsigned Idx) { Bits[Idx / BITWORD_SIZE] ^= BitWord(1) << (Idx % BITWORD_SIZE); return *this; } // Indexing. reference operator[](unsigned Idx) { assert(Idx < Size && "Out-of-bounds Bit access."); return reference(*this, Idx); } bool operator[](unsigned Idx) const { assert(Idx < Size && "Out-of-bounds Bit access."); BitWord Mask = BitWord(1) << (Idx % BITWORD_SIZE); return (Bits[Idx / BITWORD_SIZE] & Mask) != 0; } bool test(unsigned Idx) const { return (*this)[Idx]; } /// Test if any common bits are set. bool anyCommon(const BitVector& RHS) const { unsigned ThisWords = NumBitWords(size()); unsigned RHSWords = NumBitWords(RHS.size()); for (unsigned i = 0, e = std::min(ThisWords, RHSWords); i != e; ++i) if (Bits[i] & RHS.Bits[i]) return true; return false; } // Comparison operators. bool operator==(const BitVector& RHS) const { unsigned ThisWords = NumBitWords(size()); unsigned RHSWords = NumBitWords(RHS.size()); unsigned i; for (i = 0; i != std::min(ThisWords, RHSWords); ++i) if (Bits[i] != RHS.Bits[i]) return false; // Verify that any extra words are all zeros. if (i != ThisWords) { for (; i != ThisWords; ++i) if (Bits[i]) return false; } else if (i != RHSWords) { for (; i != RHSWords; ++i) if (RHS.Bits[i]) return false; } return true; } bool operator!=(const BitVector& RHS) const { return !(*this == RHS); } /// Intersection, union, disjoint union. BitVector& operator&=(const BitVector& RHS) { unsigned ThisWords = NumBitWords(size()); unsigned RHSWords = NumBitWords(RHS.size()); unsigned i; for (i = 0; i != std::min(ThisWords, RHSWords); ++i) Bits[i] &= RHS.Bits[i]; // Any bits that are just in this bitvector become zero, because they aren't // in the RHS bit vector. Any words only in RHS are ignored because they // are already zero in the LHS. for (; i != ThisWords; ++i) Bits[i] = 0; return *this; } /// reset - Reset bits that are set in RHS. Same as *this &= ~RHS. BitVector& reset(const BitVector& RHS) { unsigned ThisWords = NumBitWords(size()); unsigned RHSWords = NumBitWords(RHS.size()); unsigned i; for (i = 0; i != std::min(ThisWords, RHSWords); ++i) Bits[i] &= ~RHS.Bits[i]; return *this; } /// test - Check if (This - RHS) is zero. /// This is the same as reset(RHS) and any(). bool test(const BitVector& RHS) const { unsigned ThisWords = NumBitWords(size()); unsigned RHSWords = NumBitWords(RHS.size()); unsigned i; for (i = 0; i != std::min(ThisWords, RHSWords); ++i) if ((Bits[i] & ~RHS.Bits[i]) != 0) return true; for (; i != ThisWords; ++i) if (Bits[i] != 0) return true; return false; } BitVector& operator|=(const BitVector& RHS) { if (size() < RHS.size()) resize(RHS.size()); for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i) Bits[i] |= RHS.Bits[i]; return *this; } BitVector& operator^=(const BitVector& RHS) { if (size() < RHS.size()) resize(RHS.size()); for (size_t i = 0, e = NumBitWords(RHS.size()); i != e; ++i) Bits[i] ^= RHS.Bits[i]; return *this; } // Assignment operator. const BitVector& operator=(const BitVector& RHS) { if (this == &RHS) return *this; Size = RHS.size(); unsigned RHSWords = NumBitWords(Size); if (Size <= Capacity * BITWORD_SIZE) { if (Size) std::memcpy(Bits, RHS.Bits, RHSWords * sizeof(BitWord)); clear_unused_bits(); return *this; } // Grow the bitvector to have enough elements. Capacity = RHSWords; assert(Capacity > 0 && "negative capacity?"); BitWord* NewBits = (BitWord*)std::malloc(Capacity * sizeof(BitWord)); std::memcpy(NewBits, RHS.Bits, Capacity * sizeof(BitWord)); // Destroy the old bits. std::free(Bits); Bits = NewBits; return *this; } const BitVector& operator=(BitVector&& RHS) { if (this == &RHS) return *this; std::free(Bits); Bits = RHS.Bits; Size = RHS.Size; Capacity = RHS.Capacity; RHS.Bits = nullptr; RHS.Size = RHS.Capacity = 0; return *this; } void swap(BitVector& RHS) { std::swap(Bits, RHS.Bits); std::swap(Size, RHS.Size); std::swap(Capacity, RHS.Capacity); } //===--------------------------------------------------------------------===// // Portable bit mask operations. //===--------------------------------------------------------------------===// // // These methods all operate on arrays of uint32_t, each holding 32 bits. The // fixed word size makes it easier to work with literal bit vector constants // in portable code. // // The LSB in each word is the lowest numbered bit. The size of a portable // bit mask is always a whole multiple of 32 bits. If no bit mask size is // given, the bit mask is assumed to cover the entire BitVector. /// setBitsInMask - Add '1' bits from Mask to this vector. Don't resize. /// This computes "*this |= Mask". void setBitsInMask(const uint32_t* Mask, unsigned MaskWords = ~0u) { applyMask<true, false>(Mask, MaskWords); } /// clearBitsInMask - Clear any bits in this vector that are set in Mask. /// Don't resize. This computes "*this &= ~Mask". void clearBitsInMask(const uint32_t* Mask, unsigned MaskWords = ~0u) { applyMask<false, false>(Mask, MaskWords); } /// setBitsNotInMask - Add a bit to this vector for every '0' bit in Mask. /// Don't resize. This computes "*this |= ~Mask". void setBitsNotInMask(const uint32_t* Mask, unsigned MaskWords = ~0u) { applyMask<true, true>(Mask, MaskWords); } /// clearBitsNotInMask - Clear a bit in this vector for every '0' bit in Mask. /// Don't resize. This computes "*this &= Mask". void clearBitsNotInMask(const uint32_t* Mask, unsigned MaskWords = ~0u) { applyMask<false, true>(Mask, MaskWords); } private: unsigned NumBitWords(unsigned S) const { return (S + BITWORD_SIZE - 1) / BITWORD_SIZE; } // Set the unused bits in the high words. void set_unused_bits(bool t = true) { // Set high words first. unsigned UsedWords = NumBitWords(Size); if (Capacity > UsedWords) init_words(&Bits[UsedWords], (Capacity - UsedWords), t); // Then set any stray high bits of the last used word. unsigned ExtraBits = Size % BITWORD_SIZE; if (ExtraBits) { BitWord ExtraBitMask = ~0UL << ExtraBits; if (t) Bits[UsedWords - 1] |= ExtraBitMask; else Bits[UsedWords - 1] &= ~ExtraBitMask; } } // Clear the unused bits in the high words. void clear_unused_bits() { set_unused_bits(false); } void grow(unsigned NewSize) { Capacity = std::max(NumBitWords(NewSize), Capacity * 2); assert(Capacity > 0 && "realloc-ing zero space"); Bits = (BitWord*)std::realloc(Bits, Capacity * sizeof(BitWord)); clear_unused_bits(); } void init_words(BitWord* B, unsigned NumWords, bool t) { memset(B, 0 - (int)t, NumWords * sizeof(BitWord)); } template <bool AddBits, bool InvertMask> void applyMask(const uint32_t* Mask, unsigned MaskWords) { static_assert(BITWORD_SIZE % 32 == 0, "Unsupported BitWord size."); MaskWords = std::min(MaskWords, (size() + 31) / 32); const unsigned Scale = BITWORD_SIZE / 32; unsigned i; for (i = 0; MaskWords >= Scale; ++i, MaskWords -= Scale) { BitWord BW = Bits[i]; // This inner loop should unroll completely when BITWORD_SIZE > 32. for (unsigned b = 0; b != BITWORD_SIZE; b += 32) { uint32_t M = *Mask++; if (InvertMask) M = ~M; if (AddBits) BW |= BitWord(M) << b; else BW &= ~(BitWord(M) << b); } Bits[i] = BW; } for (unsigned b = 0; MaskWords; b += 32, --MaskWords) { uint32_t M = *Mask++; if (InvertMask) M = ~M; if (AddBits) Bits[i] |= BitWord(M) << b; else Bits[i] &= ~(BitWord(M) << b); } if (AddBits) clear_unused_bits(); } public: /// Return the size (in bytes) of the bit vector. size_t getMemorySize() const { return Capacity * sizeof(BitWord); } }; static inline size_t capacity_in_bytes(const BitVector& X) { return X.getMemorySize(); } } // end namespace llvm } // end namespace hecl namespace std { /// Implement std::swap in terms of BitVector swap. inline void swap(hecl::llvm::BitVector& LHS, hecl::llvm::BitVector& RHS) { LHS.swap(RHS); } } // end namespace std
29.573854
118
0.592629
[ "vector" ]
39543e8032f55db67edebb3e6ddaf69f86715320
1,721
cpp
C++
src/Sprite.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
1
2019-06-19T10:19:33.000Z
2019-06-19T10:19:33.000Z
src/Sprite.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
null
null
null
src/Sprite.cpp
ApertaTeam/utengine
e641a76b6c0042a4b581f1ec51798b74f2bb5293
[ "MIT" ]
1
2019-06-19T09:00:15.000Z
2019-06-19T09:00:15.000Z
#include "Sprite.h" #include "BatchHandler.h" namespace UT { Sprite::Sprite() { textureId = -1; textureRect = sf::IntRect(0, 0, 0, 0); color = sf::Color::White; } Sprite::Sprite(int texId, sf::IntRect texRect) { textureId = texId; textureRect = texRect; color = sf::Color::White; } void Sprite::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); const auto& rect = textureRect; sf::FloatRect transformRect({0, 0}, sf::Vector2f(rect.width, rect.height)); transformRect = states.transform.transformRect(transformRect); sf::VertexArray arr(sf::Quads, 4); arr[0].position = sf::Vector2f(transformRect.left, transformRect.top); arr[1].position = sf::Vector2f(transformRect.left + transformRect.width, transformRect.top); arr[2].position = sf::Vector2f(transformRect.left + transformRect.width, transformRect.top + transformRect.height); arr[3].position = sf::Vector2f(transformRect.left, transformRect.top + transformRect.height); arr[0].texCoords = sf::Vector2f(textureRect.left, textureRect.top); arr[1].texCoords = sf::Vector2f(textureRect.left +textureRect.width, textureRect.top); arr[2].texCoords = sf::Vector2f(textureRect.left +textureRect.width, textureRect.top + textureRect.height); arr[3].texCoords = sf::Vector2f(textureRect.left, textureRect.top + textureRect.height); arr[0].color = color; arr[1].color = color; arr[2].color = color; arr[3].color = color; BatchHandler::getInstance().DrawSpriteRect(textureId, arr, target); } }
38.244444
123
0.647879
[ "transform" ]
39589f82fb1bdc9fe2e9d524653a2638b2e0bfed
4,179
hh
C++
contrib/fluxbox/src/FbTk/ImageControl.hh
xk2600/lightbox
987d901366fe706de1a8bbd1efd49b87abff3e0b
[ "BSD-2-Clause" ]
null
null
null
contrib/fluxbox/src/FbTk/ImageControl.hh
xk2600/lightbox
987d901366fe706de1a8bbd1efd49b87abff3e0b
[ "BSD-2-Clause" ]
2
2017-05-30T05:21:59.000Z
2018-03-14T07:21:33.000Z
src/FbTk/ImageControl.hh
antix-skidoo/fluxbox
b83ee923f4ab2ab51f3b8c14343bda0579e538c6
[ "MIT" ]
null
null
null
// ImageControl.hh for FbTk - Fluxbox Toolkit // Copyright (c) 2001 - 2003 Henrik Kinnunen (fluxbox at users.sourceforge.net) // // from Image.hh for Blackbox - an X11 Window manager // Copyright (c) 1997 - 2000 Brad Hughes (bhughes at tcac.net) // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef FBTK_IMAGECONTROL_HH #define FBTK_IMAGECONTROL_HH #include "Orientation.hh" #include "Timer.hh" #include "NotCopyable.hh" #include <X11/Xlib.h> // for Visual* etc #include <list> #include <vector> namespace FbTk { class Texture; /// Holds screen info, color tables and caches textures class ImageControl: private NotCopyable { public: ImageControl(int screen_num, int colors_per_channel = 4, unsigned long cache_timeout = 300000l, unsigned long cache_max = 200l); virtual ~ImageControl(); int depth() const { return m_screen_depth; } int colorsPerChannel() const { return m_colors_per_channel; } size_t nrColors() const { return m_colors.size(); } const XColor* colors() const { return &m_colors[0]; } int screenNumber() const { return m_screen_num; } Visual *visual() const { return m_visual; } /** Render to pixmap @param width width of pixmap @param height height of pixmap @param src_texture texture type to render @param orient Orientation of the texture. @param use_cache whether or not to use cache @return pixmap of the rendered image, on failure None */ Pixmap renderImage(unsigned int width, unsigned int height, const FbTk::Texture &src_texture, Orientation orient = ROT0, bool use_cache = true); void installRootColormap(); void removeImage(Pixmap thepix); void colorTables(const unsigned char **, const unsigned char **, const unsigned char **, int *, int *, int *, int *, int *, int *) const; void getGradientBuffers(unsigned int, unsigned int, unsigned int **, unsigned int **); void cleanCache(); private: /** Search cache for a specific pixmap @return None if no cache was found */ Pixmap searchCache(unsigned int width, unsigned int height, const Texture &text, Orientation orient) const; void createColorTable(); Timer m_timer; Colormap m_colormap; std::vector<XColor> m_colors; ///< color table Visual *m_visual; int bits_per_pixel; int red_offset, green_offset, blue_offset, red_bits, green_bits, blue_bits; int m_colors_per_channel; ///< number of colors per channel int m_screen_depth; ///< bit depth of screen int m_screen_num; ///< screen number unsigned char red_color_table[256]; unsigned char green_color_table[256]; unsigned char blue_color_table[256]; // TextureRenderer uses these buffers std::vector<unsigned int> grad_xbuffer; std::vector<unsigned int> grad_ybuffer; struct Cache; typedef std::list<Cache *> CacheList; mutable CacheList cache; unsigned long cache_max; }; } // end namespace FbTk #endif // FBTK_IMAGECONTROL_HH
35.117647
111
0.6961
[ "render", "vector" ]
395bbc3a1544acf57a4c496ae5cea01134d65111
47,455
cpp
C++
src/buffer.cpp
RaftLib/ipc
608dcb10e1acb84e0f3be89639a91abe5395566b
[ "Apache-2.0" ]
6
2021-08-04T20:03:16.000Z
2021-08-17T16:16:10.000Z
src/buffer.cpp
RaftLib/ipc
608dcb10e1acb84e0f3be89639a91abe5395566b
[ "Apache-2.0" ]
9
2021-08-05T01:14:13.000Z
2021-08-31T21:39:28.000Z
src/buffer.cpp
RaftLib/ipc
608dcb10e1acb84e0f3be89639a91abe5395566b
[ "Apache-2.0" ]
null
null
null
/** * buffer.cpp - * @author: Jonathan Beard * @version: Fri Mar 13 09:35:16 2020 * * Copyright 2020 Jonathan Beard * * 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 <fcntl.h> #include <semaphore.h> #include <cstring> #include <unistd.h> #include <shm> #include <sstream> #include <utility> #include <type_traits> #include <typeinfo> #include <signal.h> #include "sem.hpp" #include <buffer> #include <errno.h> #include "allocation_metadata.hpp" #include "allocationexception.hpp" ipc::global_err_t ipc::buffer::gb_err; void ipc::buffer::shutdown_handler( int signum ) { std::cerr << "Shutting down ipc buffer\n"; std::perror( ipc::buffer::gb_err.err_msg.str().c_str() ); UNUSED( signum ); //get rid of semaphores, doesn't matter if these fail ipc::sem::final_close( ipc::buffer::gb_err.buffer->index_sem_name ); ipc::sem::final_close( ipc::buffer::gb_err.buffer->alloc_sem_name ); std::cerr << "ipc::buffer::gb_err: " << ipc::buffer::gb_err.shm_handle << "\n"; //give this a shot even if it's null shm::close( ipc::buffer::gb_err.shm_handle, (void**)&ipc::buffer::gb_err.buffer, ipc::buffer::gb_err.buffer->allocated_size, false, true ); } void ipc::buffer::register_signal_handlers() { struct sigaction action; sigemptyset( &action.sa_mask ); action.sa_flags = 0; action.sa_handler = ipc::buffer::shutdown_handler; sigaction (SIGUSR1, &action, nullptr ); sigaction (SIGSEGV, &action, nullptr ); sigaction (SIGKILL, &action, nullptr ); sigaction (SIGINT, &action, nullptr ); } ipc::buffer::buffer() : buffer_base() { //nothing to see here } ipc::buffer* ipc::buffer::initialize( const std::string shm_handle ) { //stupid sanity check assert( shm_handle.length() > 0 ); ipc::buffer::gb_err.shm_handle = shm_handle; /** constants **/ const auto buffer_size_nbytes = 1 << ipc::buffer_size_pow_two; const auto meta_size_bytes = sizeof( ipc::buffer_base ); /** * because of the way the structures are laid out, this should * be a multiple of the overall page size. */ const auto size_we_need = buffer_size_nbytes + meta_size_bytes; void *memory( nullptr ); memory = shm::init( shm_handle, size_we_need, false /** don't zero **/, nullptr /** no placement **/ ); if( memory == (void*)-1) { auto *output( shm::eopen< ipc::buffer >( shm_handle ) ); while( output->cookie.load( std::memory_order_seq_cst) != ipc::buffer::cookie_in_use ) { //spin while parent is setting things up. __asm__ volatile( "nop" : : : ); } ipc::buffer::gb_err.buffer = output; return( output ); } //we're here, then we're the first ones, lots to do. /** * STEP 1, set up semaphore name and semaphore for alloc */ /** * avoid duplicate code with lambda */ auto sem_allocate_f = []( const std::string &&name, const int proj_id, ipc::sem::sem_key_t &sem_name )->auto { ipc::sem::generate_key( ipc::sem::semaphore_length - 1, proj_id, sem_name ); auto sem_id = ipc::sem::open( sem_name, ipc::sem::sem_create, ipc::sem::file_rdwr ); if( sem_id == ipc::sem::sem_error ) { ipc::buffer::gb_err.err_msg << "Failed to open semaphore, exiting!!" ; shutdown_handler( 0 ); } if( ipc::sem::main_init( sem_id ) == -1 ) { ipc::buffer::gb_err.err_msg << "failed to init index semaphore, (" << name << "), exiting"; shutdown_handler( 0 ); } /** * changed from std::pair to returning the active/open * sem so we don't run into the ret val optimization bug */ return( sem_id ); }; ipc::sem::sem_key_t alloc_sem_name = {0}; auto sem_alloc = sem_allocate_f( "alloc", 0x13, alloc_sem_name ); ipc::sem::sem_key_t index_sem_name = {0}; auto sem_index = sem_allocate_f( "index", 0x14, index_sem_name ); /** * STEP 2, set up object allocation */ assert( memory != nullptr ); auto *out_buffer = new (memory) ipc::buffer(); ipc::buffer::gb_err.buffer = out_buffer; /** * STEP 3, initialize data structures inside object * remember to copy over semaphore names * - index_start - offset should equal 0, which is invalid * - index_end - offset should equal 0, which is invalid * - index_sem_name - generate semaphore name, copy here * - alloc_sem_name - generate alloc anme, copy here * - allocated_size - should be set to initial buffer size * - free_start_offset - set initially to "data" start * - cookie, set to cookie value once all written */ /** * copy these after we have the semaphore, and * after the constructor was called. */ //strcopy index ipc::sem::key_copy( out_buffer->index_sem_name, ipc::sem::semaphore_length - 1, index_sem_name ); //strcopy alloc sem name ipc::sem::key_copy( out_buffer->alloc_sem_name, ipc::sem::semaphore_length - 1, alloc_sem_name ); out_buffer->allocated_size = size_we_need; out_buffer->databuffer_size = buffer_size_nbytes; ipc::sem::close( sem_alloc ); ipc::sem::close( sem_index ); out_buffer->cookie.store( ipc::buffer_base::cookie_in_use, std::memory_order_seq_cst); return( out_buffer ); } std::string ipc::buffer::get_tmp_dir() { #if defined __linux char *dir = getenv( "TMPDIR" ); if( dir != nullptr ) { return( std::string( dir ) ); } else { return( "/tmp" ); } #else #pragma message ("tmp directory helper not yet implemented for non-linux platforms, returning (./)") return( "./" ); #endif } void ipc::buffer::destruct( ipc::buffer *b, const std::string &shm_handle, const bool unlink, const bool unmap ) { if( unlink ) { if( ipc::sem::final_close( b->index_sem_name ) == -1 ) { std::stringstream errstr; errstr << "error on destruction with sem name (" << b->index_sem_name << ")"; std::perror( errstr.str().c_str() ); } if( ipc::sem::final_close( b->alloc_sem_name ) == -1 ) { std::stringstream errstr; errstr << "error on destruction with sem name (" << b->alloc_sem_name << ")"; std::perror( errstr.str().c_str() ); } } if( unmap ) { shm::close( shm_handle, (void**)&b, b->allocated_size, false, unlink ); } return; } ipc::channel_id_t ipc::buffer::add_channel( ipc::thread_local_data *data, const channel_id_t channel_id, const ipc::channel_type type, const ipc::direction_t dir, const std::size_t additional_bytes, ipc::buffer::shm_seg::init_func_t f ) { assert( data != nullptr ); const auto size_to_allocate( sizeof( ipc::channel_index_t ) ); const auto channel_info_multiple = ipc::buffer::heap_t::get_block_multiple( size_to_allocate ); //we're here, we should have enough local mem const auto meta_multiple = ipc::buffer::heap_t::get_block_multiple( sizeof( ipc::allocate_metadata ) ); ipc::channel_info *channel = nullptr; ipc::channel_id_t channel_start = ipc::null_channel; /** * Acquire semaphore, must go after allocate otherwise we have * nested semaphore acquire and deadlock. */ auto sem = data->index_semaphore; if( ipc::sem::wait( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to wait, plz debug at line (" << __LINE__ << ")" << " with sem value: " << sem; shutdown_handler( 0 ); } //returns block that is modulo block_size channel_start = ipc::buffer::find_channel_buffer_offset( data, channel_id, &channel ); if( channel_start < ipc::valid_offset ) { const auto additional_byte_multiple = ipc::buffer::heap_t::get_block_multiple( additional_bytes ); // Create new node -- will have to acquire allocation semaphore // BEWARE - we already grabbed index semaphore, they're now nested std::size_t blocks_to_allocate = channel_info_multiple + meta_multiple + additional_byte_multiple; void *mem_for_new_channel = ipc::buffer::global_buffer_allocate( data, blocks_to_allocate, true ); if( mem_for_new_channel == nullptr ) { channel_start = ipc::channel_alloc_err; goto POST; } const auto meta_offset = ipc::buffer::calculate_block_offset( &data->buffer->data, mem_for_new_channel ); /** need to calculate channel start, don't change pointer yet, we need that **/ channel_start = meta_offset + meta_multiple; //make an actual meta-data structure new (mem_for_new_channel) ipc::allocate_metadata( channel_start /** help the allocator find the base and de-allocate this block **/, channel_info_multiple + additional_byte_multiple /** count of blocks allocated, not including metadata **/ ); mem_for_new_channel = ipc::buffer::translate_block( &data->buffer->data, channel_start ); //initialize new channel structure auto *node_to_add = new (mem_for_new_channel) ipc::channel_index_t( channel_id /** id **/, ipc::nodebase::normal /** node type **/, channel_id ); /** * this gives you a pointer back to the first block that is not the "meta" node */ channel = &(**node_to_add); channel->meta.type = type; switch( channel->meta.type ) { case( ipc::mpmc_record ): { //set up dummy node for LF queue auto dummy_info_multiple = ipc::buffer::heap_t::get_block_multiple( sizeof( ipc::record_index_t ) ); void *mem_for_dummy_node = ipc::buffer::global_buffer_allocate( data, dummy_info_multiple, true ); auto *dummy_record = new (mem_for_dummy_node) ipc::record_index_t( ipc::nodebase::dummy ); channel->meta.dummy_node_offset = ipc::buffer::calculate_block_offset( &data->buffer->data, dummy_record ); ipc::buffer::mpmc_lock_free::init( channel, dummy_record, &data->buffer->data ); } break; case( ipc::spsc_record ): { ipc::buffer::spsc_lock_free::init( channel ); } break; case( ipc::shared ): { const auto seg_base = channel_start + channel_info_multiple; auto *seg_ptr = ipc::buffer::translate_block( &data->buffer->data, seg_base ); /** * this function knows the length, it's just to initialize, must * be within the semaphore region so that the memory is allocated * before anything is handed back to the "user-level" programmer. */ ipc::buffer::shm_seg::init( &data->buffer->data /** buff base **/, channel /** channel base **/, seg_ptr /** base of shared **/, f ); } break; default: assert( false ); } if( ! ipc::buffer::channel_list_t::insert( &(data->buffer->data), channel_start, &(data->buffer->channel_list) ) ) { channel_start = ipc::channel_err; } } /** * else, find_channel_buffer_offset function has set channel ptr to something valid * and the output contains the pointer to channel_info. */ //two directions on the channel, producer or consumer switch( dir ) { case( ipc::producer ): { channel->meta.ref_count_prod++ /** atomic inc **/; } break; case( ipc::consumer ): { channel->meta.ref_count_cons++ /** atomic inc **/; } break; case( ipc::dir_not_set ): { if( channel->meta.type == ipc::shared ) { channel->meta.ref_count_shd++ /** atomic inc **/; } } break; default: { //shouldn't be here assert( false ); } } POST: // Release semaphore /** * keep in mind, we jump here if we can't allocate memory too, * so check ret channel pointer for null below before adding it * to the TLS. */ if( ipc::sem::post( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to post semaphore, exiting given we can't recover from this " << "sem val(" << sem << ") @ line " << __LINE__; shutdown_handler( 0 ); } if( channel != nullptr /** only case if we couldn't allocate mem for channel **/ ) { /** insert zero count allocation struct into local calling TLS **/ data->channel_local_allocation.insert( std::make_pair( channel_id, ipc::local_allocation_info( dir ) ) ); /** insert channel structure into calling TLS **/ data->channel_map.insert( std::make_pair( channel_id, channel ) ); } return( channel_start ); } ipc::channel_id_t ipc::buffer::add_spsc_lf_record_channel( ipc::thread_local_data *data, const channel_id_t channel_id, ipc::direction_t dir ) { return( ipc::buffer::add_channel( data, channel_id, ipc::spsc_record, dir ) ); } ipc::channel_id_t ipc::buffer::add_shared_segment( ipc::thread_local_data *tls, const channel_id_t channel_id, const std::size_t n_bytes, ipc::buffer::shm_seg::init_func_t f ) { return( ipc::buffer::add_channel( tls, channel_id, ipc::shared, ipc::dir_not_set, n_bytes, f ) ); } ipc::tx_code ipc::buffer::open_shared_segment( ipc::thread_local_data *tls_data, const channel_id_t channel_id, void **data ) { assert( tls_data != nullptr ); /** check that channel exists for this tls structure **/ auto channel_found = tls_data->channel_map.find( channel_id ); if( channel_found == tls_data->channel_map.end() ) { return( ipc::no_such_channel ); } auto *channel_info = (*channel_found).second; const auto tx_code = ipc::buffer::shm_seg::get_segment( channel_info, data, &tls_data->buffer->data ); return( tx_code ); } std::size_t ipc::buffer::get_record_size( ipc::thread_local_data *data, void *ptr ) { /** get number of blocks for the metadata **/ auto data_block_offset = calculate_block_offset( &data->buffer->data, ptr ); const auto meta_multiple = ipc::buffer::heap_t::get_block_multiple( sizeof( ipc::allocate_metadata ) ); auto meta_offset = data_block_offset - meta_multiple; auto *meta_data = (ipc::allocate_metadata*) ipc::buffer::translate_block( &data->buffer->data, meta_offset); return( meta_data->block_count << ipc::block_size_power_two ); } //ipc::channel_id_t //ipc::buffer::add_mn_lf_channel( ipc::thread_local_data *data, // const channel_id_t channel_id ) //{ // return( ipc::buffer::add_channel( data, channel_id, ipc::mpmc_record ) ); //} // bool ipc::buffer::has_active_channels( ipc::thread_local_data *tls ) { return( ipc::buffer::channel_list_t::size( &tls->buffer->channel_list ) != 0 ); } bool ipc::buffer::has_channel( ipc::thread_local_data *tls, const ipc::channel_id_t channel, const bool blocking ) { bool found = false; ipc::channel_info *ch_st = nullptr; do{ //come back here if( ipc::buffer::find_channel( tls, channel, &ch_st ) != ipc::channel_not_found ) { found = true; assert( ch_st != nullptr ); } }while( ! found && blocking ); return( found ); } bool ipc::buffer::channel_has_producers( ipc::thread_local_data *tls, const ipc::channel_id_t channel ) { const auto found = tls->channel_map.find( channel ); if( found == tls->channel_map.cend() ) { return( false ); } //else return( (*(*found).second).meta.ref_count_prod > 0 ); } std::size_t ipc::buffer::channel_has_data( ipc::thread_local_data *data, const channel_id_t channel_id ) { const auto channel_found = data->channel_map.find( channel_id ); if( channel_found == data->channel_map.cend() ) { //FIXME - should we return some error code using negative spectrum? return( 0 /** no data **/ ); } auto *channel_info = (*channel_found).second; std::size_t size = 0; switch( channel_info->meta.type ) { case( ipc::mpmc_record): { assert( false /** unimplemented **/ ); return( 0 ); } break; case( ipc::spsc_record ): { size = ipc::buffer::spsc_lock_free::min_consumer_size( channel_info ); } break; default: assert( false ); } return( size ); } ipc::channel_map_t ipc::buffer::get_channel_list( ipc::thread_local_data *data ) { auto channel_map_output = ipc::make_channel_map(); /** we don't want list changed out from under us **/ auto sem = data->index_semaphore; if( ipc::sem::wait( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to wait, plz debug at line (" << __LINE__ << ")" << " with sem value: " << sem; shutdown_handler( 0 ); } //populate channel map ipc::ptr_offset_t current_offset = ipc::invalid_ptr_offset; do { current_offset = ipc::buffer::channel_list_t::get_next( current_offset, &data->buffer->data, &data->buffer->channel_list ); if( current_offset != ipc::invalid_ptr_offset ) { auto *channel_index_struct = (ipc::channel_index_t*) translate_block( &data->buffer->data, current_offset ); auto &ele = (**channel_index_struct); channel_map_output->insert( std::make_pair( ele.meta.channel_id, ele.meta.type ) ); } }while( current_offset != ipc::invalid_ptr_offset ); /** release sem **/ if( ipc::sem::post( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to post semaphore, exiting given we can't recover from this " << "sem val(" << sem << ") @ line " << __LINE__; shutdown_handler( 0 ); } return( channel_map_output ); } ipc::channel_id_t ipc::buffer::find_channel( ipc::thread_local_data *data, const channel_id_t channel_id, ipc::channel_info **channel ) { ipc::channel_id_t output = ipc::channel_not_found; /** acquire sem **/ auto sem = data->index_semaphore; if( ipc::sem::wait( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to wait, plz debug at line (" << __LINE__ << ")" << " with sem value: " << sem; shutdown_handler( 0 ); } output = ipc::buffer::find_channel_buffer_offset( data, channel_id, channel ); /** release sem **/ if( ipc::sem::post( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to post semaphore, exiting given we can't recover from this " << "sem val(" << sem << ") @ line " << __LINE__; shutdown_handler( 0 ); } return( output ); } bool ipc::buffer::remove_channel( ipc::thread_local_data *data, const channel_id_t channel_id ) { /** acquire sem **/ auto sem = data->index_semaphore; if( ipc::sem::wait( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to wait, plz debug at line (" << __LINE__ << ")" << " with sem value: " << sem; shutdown_handler( 0 ); } /** * get offset to the outter index structure, this is w.r.t. to blocks. */ const auto channel_offset = ipc::buffer::find_channel_block( data, channel_id ); if( channel_offset >= ipc::valid_offset ) { /** remove the node **/ ipc::buffer::channel_list_t::remove( &data->buffer->data, channel_offset, &data->buffer->channel_list ); auto *channel_index_struct = (ipc::channel_index_t*) translate_block( &data->buffer->data, channel_offset ); /** finally, free channel entry itself **/ ipc::buffer::free_record( data, channel_index_struct ); } //chennel_offset should have an appropriate error message /** release sem **/ if( ipc::sem::post( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to post semaphore, exiting given we can't recover from this " << "sem val(" << sem << ") @ line " << __LINE__; shutdown_handler( 0 ); } return( channel_offset >= ipc::valid_offset ); } void ipc::buffer::free_channel_memory( ipc::thread_local_data *data, ipc::local_allocation_info &info ) { /** free data that is previously there **/ if( info.blocks_available > 0 ) { //TODO - make sure this is actually going off of blocks vs. ptr offset, //return blocks must be modulo block size. ipc::buffer::_free( data, info.local_allocation, info.blocks_available ); } info.blocks_available = 0; info.local_allocation = 0; } void ipc::buffer::unlink_channel( ipc::thread_local_data *tls, ipc::channel_id_t channel ) { //get ptr for channel ipc::channel_info *ch_ptr = tls->channel_map[ channel ]; //get rid of our local data allocation, return to buffer auto &th_local_allocation = tls->channel_local_allocation[ channel ]; ipc::buffer::free_channel_memory( tls, th_local_allocation ); /** * Acquire semaphore, must go after allocate otherwise we have * nested semaphore acquire and deadlock. */ auto sem = tls->index_semaphore; if( ipc::sem::wait( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to wait, plz debug at line (" << __LINE__ << ")" << " with sem value: " << sem; shutdown_handler( 0 ); } /** * these are not atomic, do not move outside of semaphore!! * two directions on the channel, producer or consumer */ switch( th_local_allocation.dir ) { /** * decrement refcount, if zero then free channel allocation, * must get semaphore first. */ case( ipc::producer ): { //this part needs index sem --(ch_ptr->meta.ref_count_prod); } break; case( ipc::consumer ): { //this part needs index sem --(ch_ptr->meta.ref_count_cons); } break; case( ipc::dir_not_set ): { if( ch_ptr->meta.type == ipc::shared ) { --(ch_ptr->meta.ref_count_shd); } } break; default: { //shouldn't be here assert( false ); } } /** release sem **/ if( ipc::sem::post( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to post semaphore, exiting given we can't recover from this " << "sem val(" << sem << ") @ line " << __LINE__; shutdown_handler( 0 ); } switch( ch_ptr->meta.type ) { case( ipc::spsc_record ): case( ipc::mpmc_record ): { if( ch_ptr->meta.ref_count_prod == 0 && ch_ptr->meta.ref_count_cons == 0 ) { ipc::buffer::remove_channel( tls, channel ); } } break; case( ipc::shared ): { if( ch_ptr->meta.ref_count_shd == 0 ) { ipc::buffer::remove_channel( tls, channel ); } } break; default: { assert( false ); } } //remove everything from local map tls->channel_local_allocation.erase( channel ); tls->channel_map.erase( channel ); } void ipc::buffer::unlink_channels( ipc::thread_local_data *tls ) { for( auto ch_pair : tls->channel_map ) { //get ptr for channel ipc::channel_info *ch_ptr = ch_pair.second; //get rid of our local data allocation, return to buffer auto &th_local_allocation = tls->channel_local_allocation[ ch_pair.first /** channel id **/ ]; ipc::buffer::free_channel_memory( tls, th_local_allocation ); /** * decrement refcount, if zero then free channel allocation, * must get semaphore first. */ /** * Acquire semaphore, must go after allocate otherwise we have * nested semaphore acquire and deadlock. */ auto sem = tls->index_semaphore; if( ipc::sem::wait( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to wait, plz debug at line (" << __LINE__ << ")" << " with sem value: " << sem; shutdown_handler( 0 ); } //two directions on the channel, producer or consumer switch( th_local_allocation.dir ) { case( ipc::producer ): { //this part needs index sem --(ch_ptr->meta.ref_count_prod); } break; case( ipc::consumer ): { //this part needs index sem --(ch_ptr->meta.ref_count_cons); } break; case( ipc::dir_not_set ): { if( ch_ptr->meta.type == ipc::shared ) { --(ch_ptr->meta.ref_count_shd); } } break; default: { //shouldn't be here assert( false ); } } /** release sem **/ if( ipc::sem::post( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to post semaphore, exiting given we can't recover from this " << "sem val(" << sem << ") @ line " << __LINE__; shutdown_handler( 0 ); } if( ch_ptr->meta.ref_count_prod == 0 && ch_ptr->meta.ref_count_cons == 0 ) { ipc::buffer::remove_channel( tls, ch_pair.first ); } } //clear map tls->channel_map.clear(); tls->channel_local_allocation.clear(); } void* ipc::buffer::thread_local_allocate( ipc::thread_local_data *data, const std::size_t blocks, const channel_id_t channel_id ) { void *output = nullptr; auto info_iterator = data->channel_local_allocation.find( channel_id ); if( info_iterator == data->channel_local_allocation.end() ) { //FIXME - could return an error code here like mmap return( nullptr ); } auto &local_allocation = (*info_iterator).second.local_allocation; auto &blocks_available = (*info_iterator).second.blocks_available; /** * we've gotten here, so we know we should at least have enough * free memory to allocate the metadata structure + the requested * user-visible data blocks (that's the parameter given in the * function call. */ ipc::buffer::create_meta_record( &data->buffer->data, local_allocation, blocks_available, blocks ); /** * get output pointer. */ output = ipc::buffer::translate_block( &data->buffer->data, local_allocation ); /** * now we need to go ahead an increment the local block count, not * ours anymore. */ local_allocation += blocks; blocks_available -= blocks; return( output ); } void ipc::buffer::create_meta_record( void *data_buffer_start, ipc::ptr_offset_t &allocation_base, std::size_t &blocks_avail, const std::size_t multiple ) { //we're here, we should have enough local mem const auto meta_multiple = ipc::buffer::heap_t::get_block_multiple( sizeof( ipc::allocate_metadata ) ); void *meta_alloc = ipc::buffer::translate_block( data_buffer_start, allocation_base /** base offset **/ ); assert( meta_alloc != nullptr ); //blocks are guaranteed to be sequential allocation_base += meta_multiple; //make an actual meta-data structure new (meta_alloc) ipc::allocate_metadata( allocation_base /** help the allocator find the base and de-allocate this block **/, multiple /** count of blocks allocated, not including this one **/ ); blocks_avail -= meta_multiple; return; } /** returns offset w.r.t. our buffer **/ ipc::ptr_offset_t ipc::buffer::find_channel_buffer_offset( ipc::thread_local_data *data, const channel_id_t channel_id, ipc::channel_info **channel ) { assert( *channel == nullptr ); //this is the index node, not the channel info struct itself const auto found_node_offset( find_channel_block( data, channel_id ) ); if( found_node_offset < ipc::valid_offset ) { return( ipc::channel_not_found ); } /** translate index pointer **/ auto *temp_index = (ipc::channel_index_t*) ipc::buffer::translate_block( &data->buffer->data, found_node_offset ); *channel = &(**temp_index); return( ipc::buffer::calculate_buffer_offset( &data->buffer->data, *channel ) ); } /** returns block **/ ipc::ptr_offset_t ipc::buffer::find_channel_block( ipc::thread_local_data *data, const channel_id_t channel_id ) { assert( data != nullptr ); ipc::channel_index_t temp_node( channel_id /** node_id **/, ipc::nodebase::normal /** node type **/, channel_id ); //initialize to null effectively ipc::ptr_offset_t found_node_offset( ipc::ptr_not_found ); found_node_offset = ipc::buffer::channel_list_t::find( &(data->buffer->data), temp_node, &(data->buffer->channel_list) ); return( found_node_offset ); } void* ipc::buffer::global_buffer_allocate( ipc::thread_local_data *data, std::size_t &blocks_needed, bool force_size ) { /** * if we're here we need to go out to the global buffer, * then the calling function can call the thread local * allocate function. */ /** * STEP 0: either allocate a multiple of our standard block size * or if the nbytes requested is bigger, try to allocate something * larger, as in 3x block size. */ const auto blocks_for_data = blocks_needed * 3; const auto large_block_multiple = ipc::buffer::heap_t::get_block_multiple( ipc::buffer::global_block_inc ); /** * STEP 1: calculate the multiple of increment size to allocate here. */ const std::int64_t block_usage_estimate = (blocks_for_data > large_block_multiple ? blocks_for_data : large_block_multiple ); /** * give the option to force the size to exactly the multiple specified * and just assign it here. */ blocks_needed = ( force_size ? blocks_needed : block_usage_estimate ); /** * STEP 2: initialize output pointer. */ void *output = nullptr; //get thread local version of allocate semaphore /** LOCK **/ auto sem = data->allocate_semaphore; if( ipc::sem::wait( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to wait, plz debug at line (" << __LINE__ << ")" << " with sem value: " << sem; shutdown_handler( 0 ); } if( blocks_needed <= ipc::meta_info::heap_t::get_blocks_avail( &data->buffer->heap ) ) { /** * STEP 3: set start pointer to the current free start */ const auto block_base = ipc::meta_info::heap_t::get_n_blocks( blocks_needed, &data->buffer->heap ); output = ipc::buffer::translate_block( (void *) &data->buffer->data, block_base /** base offset **/ ); } //if not the right size, go to sem_post and we end up here. /** UNLOCK **/ if( ipc::sem::post( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to post semaphore, exiting given we can't recover from this " << "sem val(" << sem << ") @ line " << __LINE__; shutdown_handler( 0 ); } return( output /** null or valid pointer **/); } void* ipc::buffer::allocate_record( ipc::thread_local_data *data, const std::size_t nbytes, const ipc::channel_id_t channel_id ) { assert( data != nullptr ); /** check that channel exists for this tls structure **/ auto channel_found = data->channel_local_allocation.find( channel_id ); if( channel_found == data->channel_local_allocation.end() ) { return( nullptr ); } //check minimum bytes for single allocation, requested + meta const std::size_t meta_blocks = heap_t::get_block_multiple( sizeof( ipc::allocate_metadata ) ); std::size_t data_blocks = heap_t::get_block_multiple( nbytes ); auto &th_local_allocation = (*channel_found).second; if( (meta_blocks + data_blocks) <= th_local_allocation.blocks_available /** check thread local buffer **/) { //allocate from local buffer, this func calls meta builder func return( ipc::buffer::thread_local_allocate( data, data_blocks, channel_id ) ); } /** free data that is previously there **/ ipc::buffer::free_channel_memory( data, th_local_allocation ); /** else allocate from global buffer **/ std::size_t global_blocks_allocated = data_blocks;; auto *ret_ptr = ipc::buffer::global_buffer_allocate( data, global_blocks_allocated ); if( ret_ptr == nullptr ) { //global buffer allocate failed return( nullptr ); } th_local_allocation.local_allocation = calculate_block_offset( &data->buffer->data, ret_ptr ); th_local_allocation.blocks_available = global_blocks_allocated; /** * call normal allocate given we now have memory to give * back, this will set up the meta header. */ return( ipc::buffer::thread_local_allocate( data, data_blocks, channel_id ) ); return( nullptr ); } void ipc::buffer::_free( ipc::thread_local_data *data, const ipc::ptr_offset_t block_base, const std::size_t blocks ) { /** LOCK **/ auto sem = data->allocate_semaphore; if( ipc::sem::wait( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to wait, plz debug at line (" << __LINE__ << ")" << " with sem value: " << sem; shutdown_handler( 0 ); } /** * FIXME - need to formalize the allocate vs. send policy. * we want to be able to allocate thread local blocks while * being able to allocate locally and still send records without * having to re-acquire the semaphore. */ heap_t::return_n_blocks( block_base, blocks, &data->buffer->heap ); //HERE /** UNLOCK **/ if( ipc::sem::post( sem ) == ipc::sem::uni_error ) { ipc::buffer::gb_err.err_msg << "Failed to post semaphore, exiting given we can't recover from this " << "sem val(" << sem << ") @ line " << __LINE__; shutdown_handler( 0 ); } } void ipc::buffer::free_record( ipc::thread_local_data *data, void *ptr ) { /** get number of blocks for the metadata **/ auto data_block_offset = calculate_block_offset( &data->buffer->data, ptr ); const auto meta_multiple = ipc::buffer::heap_t::get_block_multiple( sizeof( ipc::allocate_metadata ) ); auto meta_offset = data_block_offset - meta_multiple; auto *meta_data = (ipc::allocate_metadata*) ipc::buffer::translate_block( &data->buffer->data, meta_offset); const auto blocks_to_free = meta_multiple + meta_data->block_count; ipc::buffer::_free( data, meta_offset, blocks_to_free ); return; } ipc::tx_code ipc::buffer::send_record( ipc::thread_local_data *tls_data, const ipc::channel_id_t channel_id, void **record ) { //FIXME - need to check record for meta info region //at block - 1. assert( tls_data != nullptr ); /** check that channel exists for this tls structure **/ auto channel_found = tls_data->channel_map.find( channel_id ); if( channel_found == tls_data->channel_map.end() ) { return( ipc::no_such_channel ); } //get channel structure auto *channel_info = (*channel_found).second; ipc::tx_code ret_code = tx_error; switch( channel_info->meta.type ) { case( ipc::mpmc_record): { //allocate a record object, doesn't matter if it's local or global auto *mem_for_record_node = allocate_record( tls_data, sizeof( ipc::record_index_t ), channel_id ); auto *record_node = new (mem_for_record_node) ipc::record_index_t( ipc::nodebase::normal ); /** * FIXME - might need to check the return code to see if the block offset * is within range. */ (**record_node) = ipc::buffer::calculate_block_offset( &tls_data->buffer->data, *record ); /** * technically this always succeeds at the moment..unless * something bad happens. */ ret_code = ipc::buffer::mpmc_lock_free::push( channel_info, record_node, &tls_data->buffer->data ); } break; case( ipc::spsc_record ): { /** * the mpmc one we have to make a lock-free node, but for this * ringbuffer, we just put in the raw pointer. */ ret_code = ipc::buffer::spsc_lock_free::push( channel_info, *record, &tls_data->buffer->data ); } break; default: assert( false ); } //if success then record node and record no longer belong to us. return( ret_code ); } ipc::tx_code ipc::buffer::receive_record( ipc::thread_local_data *tls_data, const ipc::channel_id_t channel_id, void **record ) { assert( tls_data != nullptr ); *record = nullptr; /** check that channel exists for this tls structure **/ auto channel_found = tls_data->channel_map.find( channel_id ); if( channel_found == tls_data->channel_map.end() ) { return( ipc::no_such_channel ); } auto *channel_info = (*channel_found).second; ipc::tx_code ret_code = ipc::tx_success; switch( channel_info->meta.type ) { case( ipc::mpmc_record ): { //we'll receive data here, will need to unpact from queue node ipc::record_index_t *ptr = nullptr; ret_code = ipc::buffer::mpmc_lock_free::pop( channel_info, &ptr, &tls_data->buffer->data ); //need to check ret code if( ret_code != tx_success ) { //return a correct error code of our own, likely just retransmit //record is already nullptr return( ret_code ); } //else *record = ipc::buffer::translate_block( &tls_data->buffer->data, (**ptr ) ); //sanity check assert( *record != nullptr ); //already checked ptr as non-null, free the record node. ipc::buffer::free_record( tls_data, ptr ); } break; case( ipc::spsc_record ): { /** * spsc ringbuffer returns pointer directly, no need * to do much else, just return the ret_code * back to the caller. */ ret_code = ipc::buffer::spsc_lock_free::pop( channel_info, record, &tls_data->buffer->data ); } break; default: assert( false ); } return( ret_code ); } ipc::thread_local_data* ipc::buffer::get_tls_structure( ipc::buffer *buffer, const ipc::thread_id_t thread_id ) { ipc::thread_local_data *ptr = nullptr; //called in the context of the calling thread ID ptr = new thread_local_data(); errno = 0; ptr->index_semaphore = ipc::sem::open( buffer->index_sem_name, 0x0, ipc::sem::file_rdwr ); /** * Open semaphore. */ if( ptr->index_semaphore == ipc::sem::sem_error ) { ipc::buffer::gb_err.err_msg << "Failed to open index semaphore!!"; shutdown_handler( 0 ); } ptr->allocate_semaphore = ipc::sem::open( buffer->alloc_sem_name, 0x0, ipc::sem::file_rdwr ); if( ptr->allocate_semaphore == ipc::sem::sem_error ) { ipc::buffer::gb_err.err_msg << "Failed to open allocate semaphore!!"; shutdown_handler( 0 ); } //call subinit function if( ipc::sem::sub_init( ptr->allocate_semaphore ) == -1 ) { ipc::buffer::gb_err.err_msg << "failed to initialize semaphore"; shutdown_handler( 0 ); } if( ipc::sem::sub_init( ptr->index_semaphore ) == -1 ) { ipc::buffer::gb_err.err_msg << "failed to initialize index semaphore"; shutdown_handler( 0 ); } // tls is now allocated (and semaphores open), now register this thread in the index ptr->buffer = buffer; ptr->thread_id = thread_id; return( ptr ); } void ipc::buffer::close_tls_structure( ipc::thread_local_data* data ) { ipc::buffer::unlink_channels( data ); // Close semaphores ipc::sem::close( data->allocate_semaphore ); ipc::sem::close( data->index_semaphore ); ::free( data ); return; }
32.931992
119
0.533411
[ "object" ]
39605a0a901374c44d7b9b249f8227691b067159
39,109
cxx
C++
main/xmloff/source/text/txtexppr.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/xmloff/source/text/txtexppr.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/xmloff/source/text/txtexppr.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include "txtexppr.hxx" #include <com/sun/star/table/BorderLine.hpp> #include <com/sun/star/text/SizeType.hpp> #include <com/sun/star/text/WrapTextMode.hpp> #include <com/sun/star/text/TextContentAnchorType.hpp> #include <com/sun/star/awt/FontFamily.hpp> #include <com/sun/star/awt/FontPitch.hpp> #include <com/sun/star/awt/FontUnderline.hpp> #include <com/sun/star/text/XChapterNumberingSupplier.hpp> #include <tools/debug.hxx> #include <xmloff/txtprmap.hxx> #include <xmloff/xmlexp.hxx> #include "XMLSectionFootnoteConfigExport.hxx" //UUUU #include <xmlsdtypes.hxx> using ::rtl::OUString; using ::rtl::OUStringBuffer; using namespace ::com::sun::star; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::style; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::text; using namespace ::com::sun::star::awt; void XMLTextExportPropertySetMapper::handleElementItem( SvXMLExport& rExp, const XMLPropertyState& rProperty, sal_uInt16 nFlags, const ::std::vector< XMLPropertyState > *pProperties, sal_uInt32 nIdx ) const { XMLTextExportPropertySetMapper *pThis = ((XMLTextExportPropertySetMapper *)this); switch( getPropertySetMapper()->GetEntryContextId( rProperty.mnIndex ) ) { case CTF_DROPCAPFORMAT: pThis->maDropCapExport.exportXML( rProperty.maValue, bDropWholeWord, sDropCharStyle ); pThis->bDropWholeWord = sal_False; pThis->sDropCharStyle = OUString(); break; case CTF_TABSTOP: pThis->maTabStopExport.Export( rProperty.maValue ); break; case CTF_TEXTCOLUMNS: pThis->maTextColumnsExport.exportXML( rProperty.maValue ); break; case CTF_BACKGROUND_URL: { DBG_ASSERT( pProperties && nIdx >= 3, "property vector missing" ); const Any *pPos = 0, *pFilter = 0, *pTrans = 0; if( pProperties && nIdx >= 3 ) { const XMLPropertyState& rTrans = (*pProperties)[nIdx-3]; // #99657# transparency may be there, but doesn't have to be. // If it's there, it must be in the right position. if( CTF_BACKGROUND_TRANSPARENCY == getPropertySetMapper() ->GetEntryContextId( rTrans.mnIndex ) ) pTrans = &rTrans.maValue; const XMLPropertyState& rPos = (*pProperties)[nIdx-2]; DBG_ASSERT( CTF_BACKGROUND_POS == getPropertySetMapper() ->GetEntryContextId( rPos.mnIndex ), "invalid property map: pos expected" ); if( CTF_BACKGROUND_POS == getPropertySetMapper() ->GetEntryContextId( rPos.mnIndex ) ) pPos = &rPos.maValue; const XMLPropertyState& rFilter = (*pProperties)[nIdx-1]; DBG_ASSERT( CTF_BACKGROUND_FILTER == getPropertySetMapper() ->GetEntryContextId( rFilter.mnIndex ), "invalid property map: filter expected" ); if( CTF_BACKGROUND_FILTER == getPropertySetMapper() ->GetEntryContextId( rFilter.mnIndex ) ) pFilter = &rFilter.maValue; } sal_uInt32 nPropIndex = rProperty.mnIndex; pThis->maBackgroundImageExport.exportXML( rProperty.maValue, pPos, pFilter, pTrans, getPropertySetMapper()->GetEntryNameSpace( nPropIndex ), getPropertySetMapper()->GetEntryXMLName( nPropIndex ) ); } break; case CTF_SECTION_FOOTNOTE_END: XMLSectionFootnoteConfigExport::exportXML(rExp, sal_False, pProperties, nIdx, getPropertySetMapper()); break; case CTF_SECTION_ENDNOTE_END: XMLSectionFootnoteConfigExport::exportXML(rExp, sal_True, pProperties, nIdx, getPropertySetMapper()); break; default: SvXMLExportPropertyMapper::handleElementItem( rExp, rProperty, nFlags, pProperties, nIdx ); break; } } void XMLTextExportPropertySetMapper::handleSpecialItem( SvXMLAttributeList& rAttrList, const XMLPropertyState& rProperty, const SvXMLUnitConverter& rUnitConverter, const SvXMLNamespaceMap& rNamespaceMap, const ::std::vector< XMLPropertyState > *pProperties, sal_uInt32 nIdx ) const { XMLTextExportPropertySetMapper *pThis = ((XMLTextExportPropertySetMapper *)this); switch( getPropertySetMapper()->GetEntryContextId( rProperty.mnIndex ) ) { case CTF_DROPCAPWHOLEWORD: DBG_ASSERT( !bDropWholeWord, "drop whole word is set already!" ); pThis->bDropWholeWord = *(sal_Bool *)rProperty.maValue.getValue(); break; case CTF_DROPCAPCHARSTYLE: DBG_ASSERT( !sDropCharStyle.getLength(), "drop char style is set already!" ); rProperty.maValue >>= pThis->sDropCharStyle; break; case CTF_NUMBERINGSTYLENAME: case CTF_PAGEDESCNAME: case CTF_OLDTEXTBACKGROUND: case CTF_BACKGROUND_POS: case CTF_BACKGROUND_FILTER: case CTF_BACKGROUND_TRANSPARENCY: case CTF_SECTION_FOOTNOTE_NUM_OWN: case CTF_SECTION_FOOTNOTE_NUM_RESTART: case CTF_SECTION_FOOTNOTE_NUM_RESTART_AT: case CTF_SECTION_FOOTNOTE_NUM_TYPE: case CTF_SECTION_FOOTNOTE_NUM_PREFIX: case CTF_SECTION_FOOTNOTE_NUM_SUFFIX: case CTF_SECTION_ENDNOTE_NUM_OWN: case CTF_SECTION_ENDNOTE_NUM_RESTART: case CTF_SECTION_ENDNOTE_NUM_RESTART_AT: case CTF_SECTION_ENDNOTE_NUM_TYPE: case CTF_SECTION_ENDNOTE_NUM_PREFIX: case CTF_SECTION_ENDNOTE_NUM_SUFFIX: case CTF_DEFAULT_OUTLINE_LEVEL: case CTF_OLD_FLOW_WITH_TEXT: // There's nothing to do here! break; default: SvXMLExportPropertyMapper::handleSpecialItem(rAttrList, rProperty, rUnitConverter, rNamespaceMap, pProperties, nIdx ); break; } } XMLTextExportPropertySetMapper::XMLTextExportPropertySetMapper( const UniReference< XMLPropertySetMapper >& rMapper, SvXMLExport& rExp ) : SvXMLExportPropertyMapper( rMapper ), rExport( rExp ), bDropWholeWord( sal_False ), maDropCapExport( rExp ), maTabStopExport( rExp ), maTextColumnsExport( rExp ), maBackgroundImageExport( rExp ) { } XMLTextExportPropertySetMapper::~XMLTextExportPropertySetMapper() { } void XMLTextExportPropertySetMapper::ContextFontFilter( XMLPropertyState *pFontNameState, XMLPropertyState *pFontFamilyNameState, XMLPropertyState *pFontStyleNameState, XMLPropertyState *pFontFamilyState, XMLPropertyState *pFontPitchState, XMLPropertyState *pFontCharsetState ) const { OUString sFamilyName; OUString sStyleName; sal_Int16 nFamily = FontFamily::DONTKNOW; sal_Int16 nPitch = FontPitch::DONTKNOW; rtl_TextEncoding eEnc = RTL_TEXTENCODING_DONTKNOW; OUString sTmp; if( pFontFamilyNameState && (pFontFamilyNameState->maValue >>= sTmp ) ) sFamilyName = sTmp; if( pFontStyleNameState && (pFontStyleNameState->maValue >>= sTmp ) ) sStyleName = sTmp; sal_Int16 nTmp = sal_Int16(); if( pFontFamilyState && (pFontFamilyState->maValue >>= nTmp ) ) nFamily = nTmp; if( pFontPitchState && (pFontPitchState->maValue >>= nTmp ) ) nPitch = nTmp; if( pFontCharsetState && (pFontCharsetState->maValue >>= nTmp ) ) eEnc = (rtl_TextEncoding)nTmp; OUString sName( ((SvXMLExport&)GetExport()).GetFontAutoStylePool()->Find( sFamilyName, sStyleName, nFamily, nPitch, eEnc ) ); if( sName.getLength() ) { pFontNameState->maValue <<= sName; if( pFontFamilyNameState ) pFontFamilyNameState->mnIndex = -1; if( pFontStyleNameState ) pFontStyleNameState->mnIndex = -1; if( pFontFamilyState ) pFontFamilyState->mnIndex = -1; if( pFontPitchState ) pFontPitchState->mnIndex = -1; if( pFontCharsetState ) pFontCharsetState->mnIndex = -1; } else { pFontNameState->mnIndex = -1; } if( pFontFamilyNameState && (0 == sFamilyName.getLength()) ) { pFontFamilyNameState->mnIndex = -1; } if( pFontStyleNameState && (0 == sStyleName.getLength()) ) { pFontStyleNameState->mnIndex = -1; } } void XMLTextExportPropertySetMapper::ContextFontHeightFilter( XMLPropertyState* pCharHeightState, XMLPropertyState* pCharPropHeightState, XMLPropertyState* pCharDiffHeightState ) const { if( pCharPropHeightState ) { sal_Int32 nTemp = 0; pCharPropHeightState->maValue >>= nTemp; if( nTemp == 100 ) { pCharPropHeightState->mnIndex = -1; pCharPropHeightState->maValue.clear(); } else { pCharHeightState->mnIndex = -1; pCharHeightState->maValue.clear(); } } if( pCharDiffHeightState ) { float nTemp = 0; pCharDiffHeightState->maValue >>= nTemp; if( nTemp == 0. ) { pCharDiffHeightState->mnIndex = -1; pCharDiffHeightState->maValue.clear(); } else { pCharHeightState->mnIndex = -1; pCharHeightState->maValue.clear(); } } } // helper method; implementation below bool lcl_IsOutlineStyle(const SvXMLExport&, const OUString&); static void lcl_checkMultiProperty(XMLPropertyState *const pState, XMLPropertyState *const pRelState) { if (pState && pRelState) { sal_Int32 nTemp = 0; pRelState->maValue >>= nTemp; if (100 == nTemp) { pRelState->mnIndex = -1; pRelState->maValue.clear(); } else { pState->mnIndex = -1; pState->maValue.clear(); } } } void XMLTextExportPropertySetMapper::ContextFilter( ::std::vector< XMLPropertyState >& rProperties, Reference< XPropertySet > rPropSet ) const { // filter font XMLPropertyState *pFontNameState = 0; XMLPropertyState *pFontFamilyNameState = 0; XMLPropertyState *pFontStyleNameState = 0; XMLPropertyState *pFontFamilyState = 0; XMLPropertyState *pFontPitchState = 0; XMLPropertyState *pFontCharsetState = 0; XMLPropertyState *pFontNameCJKState = 0; XMLPropertyState *pFontFamilyNameCJKState = 0; XMLPropertyState *pFontStyleNameCJKState = 0; XMLPropertyState *pFontFamilyCJKState = 0; XMLPropertyState *pFontPitchCJKState = 0; XMLPropertyState *pFontCharsetCJKState = 0; XMLPropertyState *pFontNameCTLState = 0; XMLPropertyState *pFontFamilyNameCTLState = 0; XMLPropertyState *pFontStyleNameCTLState = 0; XMLPropertyState *pFontFamilyCTLState = 0; XMLPropertyState *pFontPitchCTLState = 0; XMLPropertyState *pFontCharsetCTLState = 0; // filter char height point/percent XMLPropertyState* pCharHeightState = NULL; XMLPropertyState* pCharPropHeightState = NULL; XMLPropertyState* pCharDiffHeightState = NULL; XMLPropertyState* pCharHeightCJKState = NULL; XMLPropertyState* pCharPropHeightCJKState = NULL; XMLPropertyState* pCharDiffHeightCJKState = NULL; XMLPropertyState* pCharHeightCTLState = NULL; XMLPropertyState* pCharPropHeightCTLState = NULL; XMLPropertyState* pCharDiffHeightCTLState = NULL; // filter left margin measure/percent XMLPropertyState* pParaLeftMarginState = NULL; XMLPropertyState* pParaLeftMarginRelState = NULL; // filter right margin measure/percent XMLPropertyState* pParaRightMarginState = NULL; XMLPropertyState* pParaRightMarginRelState = NULL; // filter first line indent measure/percent XMLPropertyState* pParaFirstLineState = NULL; XMLPropertyState* pParaFirstLineRelState = NULL; // filter ParaTopMargin/Relative XMLPropertyState* pParaTopMarginState = NULL; XMLPropertyState* pParaTopMarginRelState = NULL; // filter ParaTopMargin/Relative XMLPropertyState* pParaBottomMarginState = NULL; XMLPropertyState* pParaBottomMarginRelState = NULL; // filter (Left|Right|Top|Bottom|)BorderWidth XMLPropertyState* pAllBorderWidthState = NULL; XMLPropertyState* pLeftBorderWidthState = NULL; XMLPropertyState* pRightBorderWidthState = NULL; XMLPropertyState* pTopBorderWidthState = NULL; XMLPropertyState* pBottomBorderWidthState = NULL; // filter (Left|Right|Top|)BorderDistance XMLPropertyState* pAllBorderDistanceState = NULL; XMLPropertyState* pLeftBorderDistanceState = NULL; XMLPropertyState* pRightBorderDistanceState = NULL; XMLPropertyState* pTopBorderDistanceState = NULL; XMLPropertyState* pBottomBorderDistanceState = NULL; // filter (Left|Right|Top|Bottom|)Border XMLPropertyState* pAllBorderState = NULL; XMLPropertyState* pLeftBorderState = NULL; XMLPropertyState* pRightBorderState = NULL; XMLPropertyState* pTopBorderState = NULL; XMLPropertyState* pBottomBorderState = NULL; // filter height properties XMLPropertyState* pHeightMinAbsState = NULL; XMLPropertyState* pHeightMinRelState = NULL; XMLPropertyState* pHeightAbsState = NULL; XMLPropertyState* pHeightRelState = NULL; XMLPropertyState* pSizeTypeState = NULL; // filter width properties XMLPropertyState* pWidthMinAbsState = NULL; XMLPropertyState* pWidthMinRelState = NULL; XMLPropertyState* pWidthAbsState = NULL; XMLPropertyState* pWidthRelState = NULL; XMLPropertyState* pWidthTypeState = NULL; // wrap XMLPropertyState* pWrapState = NULL; XMLPropertyState* pWrapContourState = NULL; XMLPropertyState* pWrapContourModeState = NULL; XMLPropertyState* pWrapParagraphOnlyState = NULL; // anchor XMLPropertyState* pAnchorTypeState = NULL; // horizontal position and relation XMLPropertyState* pHoriOrientState = NULL; XMLPropertyState* pHoriOrientMirroredState = NULL; XMLPropertyState* pHoriOrientRelState = NULL; XMLPropertyState* pHoriOrientRelFrameState = NULL; XMLPropertyState* pHoriOrientMirrorState = NULL; // --> OD 2004-08-09 #i28749# - horizontal position and relation for shapes XMLPropertyState* pShapeHoriOrientState = NULL; XMLPropertyState* pShapeHoriOrientMirroredState = NULL; XMLPropertyState* pShapeHoriOrientRelState = NULL; XMLPropertyState* pShapeHoriOrientRelFrameState = NULL; XMLPropertyState* pShapeHoriOrientMirrorState = NULL; // <-- // vertical position and relation XMLPropertyState* pVertOrientState = NULL; XMLPropertyState* pVertOrientAtCharState = NULL; XMLPropertyState* pVertOrientRelState = NULL; XMLPropertyState* pVertOrientRelPageState = NULL; XMLPropertyState* pVertOrientRelFrameState = NULL; XMLPropertyState* pVertOrientRelAsCharState = NULL; // --> OD 2004-08-09 #i28749# - vertical position and relation for shapes XMLPropertyState* pShapeVertOrientState = NULL; XMLPropertyState* pShapeVertOrientAtCharState = NULL; XMLPropertyState* pShapeVertOrientRelState = NULL; XMLPropertyState* pShapeVertOrientRelPageState = NULL; XMLPropertyState* pShapeVertOrientRelFrameState = NULL; // <-- // filter underline color XMLPropertyState* pUnderlineState = NULL; XMLPropertyState* pUnderlineColorState = NULL; XMLPropertyState* pUnderlineHasColorState = NULL; // filter list style name XMLPropertyState* pListStyleName = NULL; // filter fo:clip XMLPropertyState* pClip11State = NULL; XMLPropertyState* pClipState = NULL; // filter fo:margin XMLPropertyState* pAllParaMargin = NULL; XMLPropertyState* pAllParaMarginRel = NULL; XMLPropertyState* pAllMargin = NULL; //UUUU XMLPropertyState* pRepeatOffsetX = NULL; XMLPropertyState* pRepeatOffsetY = NULL; sal_Bool bNeedsAnchor = sal_False; for( ::std::vector< XMLPropertyState >::iterator aIter = rProperties.begin(); aIter != rProperties.end(); ++aIter ) { XMLPropertyState *propertie = &(*aIter); if( propertie->mnIndex == -1 ) continue; switch( getPropertySetMapper()->GetEntryContextId( propertie->mnIndex ) ) { case CTF_CHARHEIGHT: pCharHeightState = propertie; break; case CTF_CHARHEIGHT_REL: pCharPropHeightState = propertie; break; case CTF_CHARHEIGHT_DIFF: pCharDiffHeightState = propertie; break; case CTF_CHARHEIGHT_CJK: pCharHeightCJKState = propertie; break; case CTF_CHARHEIGHT_REL_CJK: pCharPropHeightCJKState = propertie; break; case CTF_CHARHEIGHT_DIFF_CJK: pCharDiffHeightCJKState = propertie; break; case CTF_CHARHEIGHT_CTL: pCharHeightCTLState = propertie; break; case CTF_CHARHEIGHT_REL_CTL: pCharPropHeightCTLState = propertie; break; case CTF_CHARHEIGHT_DIFF_CTL: pCharDiffHeightCTLState = propertie; break; case CTF_PARALEFTMARGIN: pParaLeftMarginState = propertie; break; case CTF_PARALEFTMARGIN_REL: pParaLeftMarginRelState = propertie; break; case CTF_PARARIGHTMARGIN: pParaRightMarginState = propertie; break; case CTF_PARARIGHTMARGIN_REL: pParaRightMarginRelState = propertie; break; case CTF_PARAFIRSTLINE: pParaFirstLineState = propertie; break; case CTF_PARAFIRSTLINE_REL: pParaFirstLineRelState = propertie; break; case CTF_PARATOPMARGIN: pParaTopMarginState = propertie; break; case CTF_PARATOPMARGIN_REL: pParaTopMarginRelState = propertie; break; case CTF_PARABOTTOMMARGIN: pParaBottomMarginState = propertie; break; case CTF_PARABOTTOMMARGIN_REL: pParaBottomMarginRelState = propertie; break; case CTF_ALLBORDERWIDTH: pAllBorderWidthState = propertie; break; case CTF_LEFTBORDERWIDTH: pLeftBorderWidthState = propertie; break; case CTF_RIGHTBORDERWIDTH: pRightBorderWidthState = propertie; break; case CTF_TOPBORDERWIDTH: pTopBorderWidthState = propertie; break; case CTF_BOTTOMBORDERWIDTH: pBottomBorderWidthState = propertie; break; case CTF_ALLBORDERDISTANCE: pAllBorderDistanceState = propertie; break; case CTF_LEFTBORDERDISTANCE: pLeftBorderDistanceState = propertie; break; case CTF_RIGHTBORDERDISTANCE: pRightBorderDistanceState = propertie; break; case CTF_TOPBORDERDISTANCE: pTopBorderDistanceState = propertie; break; case CTF_BOTTOMBORDERDISTANCE: pBottomBorderDistanceState = propertie; break; case CTF_ALLBORDER: pAllBorderState = propertie; break; case CTF_LEFTBORDER: pLeftBorderState = propertie; break; case CTF_RIGHTBORDER: pRightBorderState = propertie; break; case CTF_TOPBORDER: pTopBorderState = propertie; break; case CTF_BOTTOMBORDER: pBottomBorderState = propertie; break; case CTF_FRAMEHEIGHT_MIN_ABS: pHeightMinAbsState = propertie; break; case CTF_FRAMEHEIGHT_MIN_REL: pHeightMinRelState = propertie; break; case CTF_FRAMEHEIGHT_ABS: pHeightAbsState = propertie; break; case CTF_FRAMEHEIGHT_REL: pHeightRelState = propertie; break; case CTF_SIZETYPE: pSizeTypeState = propertie; break; case CTF_FRAMEWIDTH_MIN_ABS: pWidthMinAbsState = propertie; break; case CTF_FRAMEWIDTH_MIN_REL: pWidthMinRelState = propertie; break; case CTF_FRAMEWIDTH_ABS: pWidthAbsState = propertie; break; case CTF_FRAMEWIDTH_REL: pWidthRelState = propertie; break; case CTF_FRAMEWIDTH_TYPE: pWidthTypeState = propertie; break; case CTF_WRAP: pWrapState = propertie; break; case CTF_WRAP_CONTOUR: pWrapContourState = propertie; break; case CTF_WRAP_CONTOUR_MODE: pWrapContourModeState = propertie; break; case CTF_WRAP_PARAGRAPH_ONLY: pWrapParagraphOnlyState = propertie; break; case CTF_ANCHORTYPE: pAnchorTypeState = propertie; break; case CTF_HORIZONTALPOS: pHoriOrientState = propertie; bNeedsAnchor = sal_True; break; case CTF_HORIZONTALPOS_MIRRORED: pHoriOrientMirroredState = propertie; bNeedsAnchor = sal_True; break; case CTF_HORIZONTALREL: pHoriOrientRelState = propertie; bNeedsAnchor = sal_True; break; case CTF_HORIZONTALREL_FRAME: pHoriOrientRelFrameState = propertie; bNeedsAnchor = sal_True; break; case CTF_HORIZONTALMIRROR: pHoriOrientMirrorState = propertie; bNeedsAnchor = sal_True; break; case CTF_VERTICALPOS: pVertOrientState = propertie; bNeedsAnchor = sal_True; break; case CTF_VERTICALPOS_ATCHAR: pVertOrientAtCharState = propertie; bNeedsAnchor = sal_True; break; case CTF_VERTICALREL: pVertOrientRelState = propertie; bNeedsAnchor = sal_True; break; case CTF_VERTICALREL_PAGE: pVertOrientRelPageState = propertie; bNeedsAnchor = sal_True; break; case CTF_VERTICALREL_FRAME: pVertOrientRelFrameState = propertie; bNeedsAnchor = sal_True; break; case CTF_VERTICALREL_ASCHAR: pVertOrientRelAsCharState = propertie; bNeedsAnchor = sal_True; break; // --> OD 2004-08-09 #i28749# - handle new CTFs for shape positioning properties case CTF_SHAPE_HORIZONTALPOS: pShapeHoriOrientState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_HORIZONTALPOS_MIRRORED: pShapeHoriOrientMirroredState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_HORIZONTALREL: pShapeHoriOrientRelState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_HORIZONTALREL_FRAME: pShapeHoriOrientRelFrameState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_HORIZONTALMIRROR: pShapeHoriOrientMirrorState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_VERTICALPOS: pShapeVertOrientState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_VERTICALPOS_ATCHAR: pShapeVertOrientAtCharState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_VERTICALREL: pShapeVertOrientRelState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_VERTICALREL_PAGE: pShapeVertOrientRelPageState = propertie; bNeedsAnchor = sal_True; break; case CTF_SHAPE_VERTICALREL_FRAME: pShapeVertOrientRelFrameState = propertie; bNeedsAnchor = sal_True; break; // <-- case CTF_FONTNAME: pFontNameState = propertie; break; case CTF_FONTFAMILYNAME: pFontFamilyNameState = propertie; break; case CTF_FONTSTYLENAME: pFontStyleNameState = propertie; break; case CTF_FONTFAMILY: pFontFamilyState = propertie; break; case CTF_FONTPITCH: pFontPitchState = propertie; break; case CTF_FONTCHARSET: pFontCharsetState = propertie; break; case CTF_FONTNAME_CJK: pFontNameCJKState = propertie; break; case CTF_FONTFAMILYNAME_CJK: pFontFamilyNameCJKState = propertie; break; case CTF_FONTSTYLENAME_CJK: pFontStyleNameCJKState = propertie; break; case CTF_FONTFAMILY_CJK: pFontFamilyCJKState = propertie; break; case CTF_FONTPITCH_CJK: pFontPitchCJKState = propertie; break; case CTF_FONTCHARSET_CJK: pFontCharsetCJKState = propertie; break; case CTF_FONTNAME_CTL: pFontNameCTLState = propertie; break; case CTF_FONTFAMILYNAME_CTL: pFontFamilyNameCTLState = propertie; break; case CTF_FONTSTYLENAME_CTL: pFontStyleNameCTLState = propertie; break; case CTF_FONTFAMILY_CTL: pFontFamilyCTLState = propertie; break; case CTF_FONTPITCH_CTL: pFontPitchCTLState = propertie; break; case CTF_FONTCHARSET_CTL: pFontCharsetCTLState = propertie; break; case CTF_UNDERLINE: pUnderlineState = propertie; break; case CTF_UNDERLINE_COLOR: pUnderlineColorState = propertie; break; case CTF_UNDERLINE_HASCOLOR: pUnderlineHasColorState = propertie; break; case CTF_NUMBERINGSTYLENAME: pListStyleName = propertie; break; case CTF_TEXT_CLIP11: pClip11State = propertie; break; case CTF_TEXT_CLIP: pClipState = propertie; break; case CTF_PARAMARGINALL: pAllParaMargin = propertie; break; case CTF_PARAMARGINALL_REL: pAllParaMarginRel = propertie; break; case CTF_MARGINALL: pAllMargin = propertie; break; //UUUU case CTF_REPEAT_OFFSET_X: pRepeatOffsetX = propertie; break; //UUUU case CTF_REPEAT_OFFSET_Y: pRepeatOffsetY = propertie; break; //UUUU case CTF_FILLGRADIENTNAME: case CTF_FILLHATCHNAME: case CTF_FILLBITMAPNAME: case CTF_FILLTRANSNAME: { OUString aStr; if( (propertie->maValue >>= aStr) && 0 == aStr.getLength() ) propertie->mnIndex = -1; } break; } } //UUUU if( pRepeatOffsetX && pRepeatOffsetY ) { sal_Int32 nOffset = 0; if( ( pRepeatOffsetX->maValue >>= nOffset ) && ( nOffset == 0 ) ) pRepeatOffsetX->mnIndex = -1; else pRepeatOffsetY->mnIndex = -1; } if( pFontNameState ) ContextFontFilter( pFontNameState, pFontFamilyNameState, pFontStyleNameState, pFontFamilyState, pFontPitchState, pFontCharsetState ); if( pFontNameCJKState ) ContextFontFilter( pFontNameCJKState, pFontFamilyNameCJKState, pFontStyleNameCJKState, pFontFamilyCJKState, pFontPitchCJKState, pFontCharsetCJKState ); if( pFontNameCTLState ) ContextFontFilter( pFontNameCTLState, pFontFamilyNameCTLState, pFontStyleNameCTLState, pFontFamilyCTLState, pFontPitchCTLState, pFontCharsetCTLState ); if( pCharHeightState && (pCharPropHeightState || pCharDiffHeightState ) ) ContextFontHeightFilter( pCharHeightState, pCharPropHeightState, pCharDiffHeightState ); if( pCharHeightCJKState && (pCharPropHeightCJKState || pCharDiffHeightCJKState ) ) ContextFontHeightFilter( pCharHeightCJKState, pCharPropHeightCJKState, pCharDiffHeightCJKState ); if( pCharHeightCTLState && (pCharPropHeightCTLState || pCharDiffHeightCTLState ) ) ContextFontHeightFilter( pCharHeightCTLState, pCharPropHeightCTLState, pCharDiffHeightCTLState ); if( pUnderlineColorState || pUnderlineHasColorState ) { sal_Bool bClear = !pUnderlineState; if( !bClear ) { sal_Int16 nUnderline = 0; pUnderlineState->maValue >>= nUnderline; bClear = FontUnderline::NONE == nUnderline; } if( bClear ) { if( pUnderlineColorState ) pUnderlineColorState->mnIndex = -1; if( pUnderlineHasColorState ) pUnderlineHasColorState->mnIndex = -1; } } lcl_checkMultiProperty(pParaLeftMarginState, pParaLeftMarginRelState); lcl_checkMultiProperty(pParaRightMarginState, pParaRightMarginRelState); lcl_checkMultiProperty(pParaTopMarginState, pParaTopMarginRelState); lcl_checkMultiProperty(pParaBottomMarginState, pParaBottomMarginRelState); lcl_checkMultiProperty(pParaFirstLineState, pParaFirstLineRelState); if (pAllParaMargin) { pAllParaMargin->mnIndex = -1; // just export individual attributes... pAllParaMargin->maValue.clear(); } if (pAllParaMarginRel) { pAllParaMarginRel->mnIndex = -1; // just export individual attributes... pAllParaMarginRel->maValue.clear(); } if (pAllMargin) { pAllMargin->mnIndex = -1; // just export individual attributes... pAllMargin->maValue.clear(); } if( pAllBorderWidthState ) { if( pLeftBorderWidthState && pRightBorderWidthState && pTopBorderWidthState && pBottomBorderWidthState ) { table::BorderLine aLeft, aRight, aTop, aBottom; pLeftBorderWidthState->maValue >>= aLeft; pRightBorderWidthState->maValue >>= aRight; pTopBorderWidthState->maValue >>= aTop; pBottomBorderWidthState->maValue >>= aBottom; if( aLeft.Color == aRight.Color && aLeft.InnerLineWidth == aRight.InnerLineWidth && aLeft.OuterLineWidth == aRight.OuterLineWidth && aLeft.LineDistance == aRight.LineDistance && aLeft.Color == aTop.Color && aLeft.InnerLineWidth == aTop.InnerLineWidth && aLeft.OuterLineWidth == aTop.OuterLineWidth && aLeft.LineDistance == aTop.LineDistance && aLeft.Color == aBottom.Color && aLeft.InnerLineWidth == aBottom.InnerLineWidth && aLeft.OuterLineWidth == aBottom.OuterLineWidth && aLeft.LineDistance == aBottom.LineDistance ) { pLeftBorderWidthState->mnIndex = -1; pLeftBorderWidthState->maValue.clear(); pRightBorderWidthState->mnIndex = -1; pRightBorderWidthState->maValue.clear(); pTopBorderWidthState->mnIndex = -1; pTopBorderWidthState->maValue.clear(); pBottomBorderWidthState->mnIndex = -1; pBottomBorderWidthState->maValue.clear(); } else { pAllBorderWidthState->mnIndex = -1; pAllBorderWidthState->maValue.clear(); } } else { pAllBorderWidthState->mnIndex = -1; pAllBorderWidthState->maValue.clear(); } } if( pAllBorderDistanceState ) { if( pLeftBorderDistanceState && pRightBorderDistanceState && pTopBorderDistanceState && pBottomBorderDistanceState ) { sal_Int32 aLeft = 0, aRight = 0, aTop = 0, aBottom = 0; pLeftBorderDistanceState->maValue >>= aLeft; pRightBorderDistanceState->maValue >>= aRight; pTopBorderDistanceState->maValue >>= aTop; pBottomBorderDistanceState->maValue >>= aBottom; if( aLeft == aRight && aLeft == aTop && aLeft == aBottom ) { pLeftBorderDistanceState->mnIndex = -1; pLeftBorderDistanceState->maValue.clear(); pRightBorderDistanceState->mnIndex = -1; pRightBorderDistanceState->maValue.clear(); pTopBorderDistanceState->mnIndex = -1; pTopBorderDistanceState->maValue.clear(); pBottomBorderDistanceState->mnIndex = -1; pBottomBorderDistanceState->maValue.clear(); } else { pAllBorderDistanceState->mnIndex = -1; pAllBorderDistanceState->maValue.clear(); } } else { pAllBorderDistanceState->mnIndex = -1; pAllBorderDistanceState->maValue.clear(); } } if( pAllBorderState ) { if( pLeftBorderState && pRightBorderState && pTopBorderState && pBottomBorderState ) { table::BorderLine aLeft, aRight, aTop, aBottom; pLeftBorderState->maValue >>= aLeft; pRightBorderState->maValue >>= aRight; pTopBorderState->maValue >>= aTop; pBottomBorderState->maValue >>= aBottom; if( aLeft.Color == aRight.Color && aLeft.InnerLineWidth == aRight.InnerLineWidth && aLeft.OuterLineWidth == aRight.OuterLineWidth && aLeft.LineDistance == aRight.LineDistance && aLeft.Color == aTop.Color && aLeft.InnerLineWidth == aTop.InnerLineWidth && aLeft.OuterLineWidth == aTop.OuterLineWidth && aLeft.LineDistance == aTop.LineDistance && aLeft.Color == aBottom.Color && aLeft.InnerLineWidth == aBottom.InnerLineWidth && aLeft.OuterLineWidth == aBottom.OuterLineWidth && aLeft.LineDistance == aBottom.LineDistance ) { pLeftBorderState->mnIndex = -1; pLeftBorderState->maValue.clear(); pRightBorderState->mnIndex = -1; pRightBorderState->maValue.clear(); pTopBorderState->mnIndex = -1; pTopBorderState->maValue.clear(); pBottomBorderState->mnIndex = -1; pBottomBorderState->maValue.clear(); } else { pAllBorderState->mnIndex = -1; pAllBorderState->maValue.clear(); } } else { pAllBorderState->mnIndex = -1; pAllBorderState->maValue.clear(); } } sal_Int16 nSizeType = SizeType::FIX; if( pSizeTypeState ) { pSizeTypeState->maValue >>= nSizeType; pSizeTypeState->mnIndex = -1; } if( pHeightMinAbsState ) { sal_Int16 nRel = sal_Int16(); if( (SizeType::FIX == nSizeType) || ( pHeightMinRelState && ( !(pHeightMinRelState->maValue >>= nRel) || nRel > 0 ) ) ) { pHeightMinAbsState->mnIndex = -1; } // export SizeType::VARIABLE als min-width="0" if( SizeType::VARIABLE == nSizeType ) pHeightMinAbsState->maValue <<= static_cast<sal_Int32>( 0 ); } if( pHeightMinRelState && SizeType::MIN != nSizeType) pHeightMinRelState->mnIndex = -1; if( pHeightAbsState && pHeightMinAbsState && -1 != pHeightMinAbsState->mnIndex ) pHeightAbsState->mnIndex = -1; if( pHeightRelState && SizeType::FIX != nSizeType) pHeightRelState->mnIndex = -1; // frame width nSizeType = SizeType::FIX; if( pWidthTypeState ) { pWidthTypeState->maValue >>= nSizeType; pWidthTypeState->mnIndex = -1; } if( pWidthMinAbsState ) { sal_Int16 nRel = sal_Int16(); if( (SizeType::FIX == nSizeType) || ( pWidthMinRelState && ( !(pWidthMinRelState->maValue >>= nRel) || nRel > 0 ) ) ) { pWidthMinAbsState->mnIndex = -1; } // export SizeType::VARIABLE als min-width="0" if( SizeType::VARIABLE == nSizeType ) pWidthMinAbsState->maValue <<= static_cast<sal_Int32>( 0 ); } if( pWidthMinRelState && SizeType::MIN != nSizeType) pWidthMinRelState->mnIndex = -1; if( pWidthAbsState && pWidthMinAbsState && -1 != pWidthMinAbsState->mnIndex ) pWidthAbsState->mnIndex = -1; if( pWidthRelState && SizeType::FIX != nSizeType) pWidthRelState->mnIndex = -1; if( pWrapState ) { WrapTextMode eVal; pWrapState->maValue >>= eVal; switch( eVal ) { case WrapTextMode_NONE: // no wrapping: disable para-only and contour if( pWrapParagraphOnlyState ) pWrapParagraphOnlyState->mnIndex = -1; // no break case WrapTextMode_THROUGHT: // wrap through: disable only contour if( pWrapContourState ) pWrapContourState->mnIndex = -1; break; default: break; } if( pWrapContourModeState && (!pWrapContourState || !*(sal_Bool *)pWrapContourState ->maValue.getValue() ) ) pWrapContourModeState->mnIndex = -1; } TextContentAnchorType eAnchor = TextContentAnchorType_AT_PARAGRAPH; if( pAnchorTypeState ) pAnchorTypeState->maValue >>= eAnchor; else if( bNeedsAnchor ) { Any aAny = rPropSet->getPropertyValue( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("AnchorType") ) ); aAny >>= eAnchor; } // states for frame positioning attributes { if( pHoriOrientState && pHoriOrientMirroredState ) { if( pHoriOrientMirrorState && *(sal_Bool *)pHoriOrientMirrorState->maValue.getValue() ) pHoriOrientState->mnIndex = -1; else pHoriOrientMirroredState->mnIndex = -1; } if( pHoriOrientMirrorState ) pHoriOrientMirrorState->mnIndex = -1; if( pHoriOrientRelState && TextContentAnchorType_AT_FRAME == eAnchor ) pHoriOrientRelState->mnIndex = -1; if( pHoriOrientRelFrameState && TextContentAnchorType_AT_FRAME != eAnchor ) pHoriOrientRelFrameState->mnIndex = -1;; if( pVertOrientState && TextContentAnchorType_AT_CHARACTER == eAnchor ) pVertOrientState->mnIndex = -1; if( pVertOrientAtCharState && TextContentAnchorType_AT_CHARACTER != eAnchor ) pVertOrientAtCharState->mnIndex = -1; if( pVertOrientRelState && TextContentAnchorType_AT_PARAGRAPH != eAnchor && TextContentAnchorType_AT_CHARACTER != eAnchor ) pVertOrientRelState->mnIndex = -1; if( pVertOrientRelPageState && TextContentAnchorType_AT_PAGE != eAnchor ) pVertOrientRelPageState->mnIndex = -1; if( pVertOrientRelFrameState && TextContentAnchorType_AT_FRAME != eAnchor ) pVertOrientRelFrameState->mnIndex = -1; if( pVertOrientRelAsCharState && TextContentAnchorType_AS_CHARACTER != eAnchor ) pVertOrientRelAsCharState->mnIndex = -1; } // --> OD 2004-08-09 #i28749# - states for shape positioning properties if ( eAnchor != TextContentAnchorType_AS_CHARACTER && ( GetExport().getExportFlags() & EXPORT_OASIS ) == 0 ) { // no export of shape positioning properties, // if shape isn't anchored as-character and // destination file format is OpenOffice.org file format if ( pShapeHoriOrientState ) pShapeHoriOrientState->mnIndex = -1; if ( pShapeHoriOrientMirroredState ) pShapeHoriOrientMirroredState->mnIndex = -1; if ( pShapeHoriOrientRelState ) pShapeHoriOrientRelState->mnIndex = -1; if ( pShapeHoriOrientRelFrameState ) pShapeHoriOrientRelFrameState->mnIndex = -1; if ( pShapeHoriOrientMirrorState ) pShapeHoriOrientMirrorState->mnIndex = -1; if ( pShapeVertOrientState ) pShapeVertOrientState->mnIndex = -1; if ( pShapeVertOrientAtCharState ) pShapeVertOrientAtCharState->mnIndex = -1; if ( pShapeVertOrientRelState ) pShapeVertOrientRelState->mnIndex = -1; if ( pShapeVertOrientRelPageState ) pShapeVertOrientRelPageState->mnIndex = -1; if ( pShapeVertOrientRelFrameState ) pShapeVertOrientRelFrameState->mnIndex = -1; } else { // handling of shape positioning property states as for frames - see above if( pShapeHoriOrientState && pShapeHoriOrientMirroredState ) { if( pShapeHoriOrientMirrorState && *(sal_Bool *)pShapeHoriOrientMirrorState->maValue.getValue() ) pShapeHoriOrientState->mnIndex = -1; else pShapeHoriOrientMirroredState->mnIndex = -1; } if( pShapeHoriOrientMirrorState ) pShapeHoriOrientMirrorState->mnIndex = -1; if( pShapeHoriOrientRelState && TextContentAnchorType_AT_FRAME == eAnchor ) pShapeHoriOrientRelState->mnIndex = -1; if( pShapeHoriOrientRelFrameState && TextContentAnchorType_AT_FRAME != eAnchor ) pShapeHoriOrientRelFrameState->mnIndex = -1;; if( pShapeVertOrientState && TextContentAnchorType_AT_CHARACTER == eAnchor ) pShapeVertOrientState->mnIndex = -1; if( pShapeVertOrientAtCharState && TextContentAnchorType_AT_CHARACTER != eAnchor ) pShapeVertOrientAtCharState->mnIndex = -1; if( pShapeVertOrientRelState && TextContentAnchorType_AT_PARAGRAPH != eAnchor && TextContentAnchorType_AT_CHARACTER != eAnchor ) pShapeVertOrientRelState->mnIndex = -1; if( pShapeVertOrientRelPageState && TextContentAnchorType_AT_PAGE != eAnchor ) pShapeVertOrientRelPageState->mnIndex = -1; if( pShapeVertOrientRelFrameState && TextContentAnchorType_AT_FRAME != eAnchor ) pShapeVertOrientRelFrameState->mnIndex = -1; } // <-- // list style name: remove list style if it is the default outline style if( pListStyleName != NULL ) { OUString sListStyleName; pListStyleName->maValue >>= sListStyleName; if( lcl_IsOutlineStyle( GetExport(), sListStyleName ) ) pListStyleName->mnIndex = -1; } if( pClipState != NULL && pClip11State != NULL ) pClip11State->mnIndex = -1; SvXMLExportPropertyMapper::ContextFilter(rProperties,rPropSet); } bool lcl_IsOutlineStyle(const SvXMLExport &rExport, const OUString & rName) { Reference< XChapterNumberingSupplier > xCNSupplier(rExport.GetModel(), UNO_QUERY); OUString sOutlineName; OUString sName(RTL_CONSTASCII_USTRINGPARAM("Name")); if (xCNSupplier.is()) { Reference<XPropertySet> xNumRule( xCNSupplier->getChapterNumberingRules(), UNO_QUERY ); DBG_ASSERT( xNumRule.is(), "no chapter numbering rules" ); if (xNumRule.is()) { xNumRule->getPropertyValue(sName) >>= sOutlineName; } } return rName == sOutlineName; }
38.043774
124
0.723619
[ "shape", "vector" ]
396d370ae7b3f7931c88f0b5ae00c7f07470f187
481
cpp
C++
leetcode/cpp/1207.unique-number-of-occurrences.cpp
phiysng/leetcode
280e8b1a0b45233deb2262ceec85b8174e9b2ced
[ "BSD-3-Clause" ]
3
2019-04-12T19:12:55.000Z
2020-05-29T07:55:16.000Z
leetcode/cpp/1207.unique-number-of-occurrences.cpp
phiysng/leetcode
280e8b1a0b45233deb2262ceec85b8174e9b2ced
[ "BSD-3-Clause" ]
null
null
null
leetcode/cpp/1207.unique-number-of-occurrences.cpp
phiysng/leetcode
280e8b1a0b45233deb2262ceec85b8174e9b2ced
[ "BSD-3-Clause" ]
null
null
null
class Solution { public: bool uniqueOccurrences(vector<int> &arr) { unordered_map<int, int> map; for (int i : arr) { map[i]++; } unordered_set<int> set; for (auto &p : map) { if (set.find(p.second) == set.end()) { set.insert(p.second); } else { return false; } } return true; } };
18.5
48
0.376299
[ "vector" ]
396ec58e7426f42b264e4f0655aedb99c57325a9
1,017
cpp
C++
codeforces/rounds/#358/dfs.cpp
GinugaSaketh/Codes
e934aa5652dd86231a42e3f7f84b145eb35bf47d
[ "MIT" ]
null
null
null
codeforces/rounds/#358/dfs.cpp
GinugaSaketh/Codes
e934aa5652dd86231a42e3f7f84b145eb35bf47d
[ "MIT" ]
null
null
null
codeforces/rounds/#358/dfs.cpp
GinugaSaketh/Codes
e934aa5652dd86231a42e3f7f84b145eb35bf47d
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define ll long long int net; int v[100005]; vector <vector <pair<int,ll> > > adj; int a[100005]; ll d[100005]; void dfs1(int v_){ //cout<<v_<<" asfc"<<endl; net++; int i; for(i=0;i<adj[v_].size();i++){ int u; u=adj[v_][i].first; //ll dist=adj[v][i].second; if(v[u]==0){ v[u]=1; //d[u]=dist+max(0,d[v_]); dfs1(u); } } } void dfs(int v_){ //cout<<v_<<" "<<a[v_]<<endl; if(d[v_]>a[v_]){ dfs1(v_); } int i; for(i=0;i<adj[v_].size();i++){ int u; u=adj[v_][i].first; ll dist=adj[v_][i].second; if(v[u]==0){ v[u]=1; d[u]=dist+max(0LL,d[v_]); dfs(u); } } } int main(){ int n; cin>>n; int i; for(i=0;i<=n;i++){ v[i]=0; } adj.resize(n+5); for(i=1;i<=n;i++){ cin>>a[i]; } int p; ll c; net=0; for(i=1;i<n;i++){ cin>>p>>c; //i+1 and p adj[i+1].push_back(make_pair(p,c)); adj[p].push_back(make_pair(i+1,c)); } v[1]=1; d[1]=0; dfs(1); cout<<net<<endl; return 0; }
9.504673
37
0.490659
[ "vector" ]
397b3252dcb2f988a0ec1427d1b4606e834a6a77
964
cpp
C++
copasi/undoFramework/UndoReactionData.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/undoFramework/UndoReactionData.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/undoFramework/UndoReactionData.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
// Copyright (C) 2014 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. /* * UndoReactionData.cpp * * Created on: 15 Aug 2014 * Author: dada */ #include <QtCore/QList> #include "model/CMetab.h" #include "UndoSpecieData.h" #include "UndoReactionData.h" UndoReactionData::UndoReactionData() { // TODO Auto-generated constructor stub } UndoReactionData::~UndoReactionData() { // TODO Auto-generated destructor stub } CReactionInterface *UndoReactionData::getRi() const { return mpRi; } void UndoReactionData::setRi(CReactionInterface *mpRi) { this->mpRi = mpRi; } QList<UndoSpecieData*> *UndoReactionData::getSpecieDependencyObjects() const { return mSpecieDependencyObjects; } void UndoReactionData::setSpecieDependencyObjects(QList<UndoSpecieData*> *specieDependencyObjects) { mSpecieDependencyObjects = specieDependencyObjects; }
20.083333
98
0.759336
[ "model" ]
397dc3940a02a40fa7464becd02125ea5af955dd
3,848
cpp
C++
HDOJ/1281.cpp
miaowh/ICPC
c1f141ea005fb5d9582878e154c49f22b0f217ff
[ "MIT" ]
1
2021-06-15T05:43:37.000Z
2021-06-15T05:43:37.000Z
HDOJ/1281.cpp
MiaoWH/ICPC
c1f141ea005fb5d9582878e154c49f22b0f217ff
[ "MIT" ]
null
null
null
HDOJ/1281.cpp
MiaoWH/ICPC
c1f141ea005fb5d9582878e154c49f22b0f217ff
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int maxn = 205; struct Tarjan { vector<int> G[maxn]; int scc, dfs_clock, top; // scc: 强连通分量的数量 bool instack[maxn]; int dfn[maxn], low[maxn], belong[maxn], Stack[maxn]; void tarjan(int u) { dfn[u] = low[u] = ++dfs_clock; instack[u] = true; Stack[top++] = u; for (auto &v : G[u]) { if (!dfn[v]) { tarjan(v); low[u] = min(low[u], low[v]); } else if (instack[v]) low[u] = min(low[u], dfn[v]); } if (dfn[u] == low[u]) { ++scc; int cnt = 0; int now; while (top > 0) { now = Stack[--top]; instack[now] = false; belong[now] = u; ++cnt; if (now == u) break; } } } void solve(int n) { memset(instack, 0, sizeof(instack)); memset(dfn, 0, sizeof(dfn)); scc = dfs_clock = top = 0; for (int i = 0; i < n; i++) { if (!dfn[i]) tarjan(i); } } } tarjan; struct MaxMatch { int n, m, clk; vector<int> G[maxn], rG[maxn]; int vis[maxn], ls[maxn], rs[maxn]; void init(int n, int m) { this->n = n, this->m = m; for (int i = 0; i < n + m; i++) G[i].clear(), rG[i].clear(); memset(rs, -1, sizeof(rs)); memset(ls, -1, sizeof(ls)); memset(vis, -1, sizeof(vis)); } void addEdge(int u, int v) { G[u].push_back(v); rG[v].push_back(u); } bool dfs(int u) { for (auto &v : G[u]) { if (vis[v] == clk) continue; vis[v] = clk; if (rs[v] == -1 || dfs(rs[v])) { ls[u] = v; rs[v] = u; return true; } } return false; } int match() { int ret = 0; for (clk = 0; clk < n; clk++) if (dfs(clk)) ++ret; return ret; } // --------------------------------------- bool lskp[maxn], rskp[maxn]; void dfs_kp_ls(int u) { vis[u] = 1; for (auto &v : G[u]) { if (rs[v] == -1 || vis[rs[v]]) continue; dfs_kp_ls(rs[v]); } } void dfs_kp_rs(int u) { vis[u] = 1; for (auto &v : rG[u]) { if (ls[v] == -1 || vis[ls[v]]) continue; dfs_kp_rs(ls[v]); } } // O(n+m) int findKeyPoint() { // match(); memset(lskp, 0, sizeof(lskp)); memset(rskp, 0, sizeof(rskp)); memset(vis, 0, sizeof(vis)); int ret = 0; for (int i = 0; i < n; i++) if (ls[i] == -1) dfs_kp_ls(i); for (int i = 0; i < n; i++) if (!vis[i]) lskp[i] = 1, ret++; memset(vis, 0, sizeof(vis)); for (int i = 0; i < m; i++) if (rs[i] == -1) dfs_kp_rs(i); for (int i = 0; i < m; i++) if (!vis[i]) rskp[i] = 1, ret++; return ret; } // ----------------------------------------- vector<pair<int, int>> edges; bool ke[maxn]; int findKeyEdge() { findKeyPoint(); memset(ke, 0, sizeof(ke)); for (int i = 0; i < n + m; i++) tarjan.G[i].clear(); for (auto &e : edges) { if (ls[e.first] == e.second) { tarjan.G[e.first].push_back(e.second + n); } else { tarjan.G[e.second + n].push_back(e.first); } } tarjan.solve(n + m); int ret = 0; for (int i = 0; i < edges.size(); i++) { auto e = edges[i]; if (ls[e.first] != e.second) continue; if (!lskp[e.first] || !rskp[e.second]) continue; if (tarjan.belong[e.first] != tarjan.belong[e.second + n]) { ke[i] = 1; ret++; continue; } } return ret; } } bio; int n, m, k; int main() { int kase = 1; while (~scanf("%d%d%d", &n, &m, &k)) { bio.init(n, m); bio.edges.clear(); for (int i = 0, u, v; i < k; i++) { scanf("%d%d", &u, &v); u--, v--; bio.edges.push_back({u, v}); bio.addEdge(u, v); } int num = bio.match(); int ans = bio.findKeyEdge(); printf("Board %d have %d important blanks for %d chessmen.\n", kase++, ans, num); } }
23.753086
79
0.456601
[ "vector" ]
30300ce378f78843c86bd7b48dc8581b599ee5e8
3,143
cpp
C++
mat.cpp
secretcod3r/new_repo2
6635f982e63642cfc0d261e16294648feefd3c75
[ "MIT" ]
null
null
null
mat.cpp
secretcod3r/new_repo2
6635f982e63642cfc0d261e16294648feefd3c75
[ "MIT" ]
null
null
null
mat.cpp
secretcod3r/new_repo2
6635f982e63642cfc0d261e16294648feefd3c75
[ "MIT" ]
null
null
null
// @author: Alon Firestein #include "mat.hpp" #include <iostream> #include <string> #include <stdexcept> #include <vector> #include <cctype> using namespace std; // Function to return the created mat for the factory :) string print_mat(int col, int row, char symbol_a, char symbol_b) { // Initalizing counters for tracking rows and columns int row_counter = 0; int col_counter = 0; // Initializing a 2D array using vectors to serve as the mat we are creating for the factory vector<vector<char>> mat(row, vector<char> (col)); // The symbols are alternating, so we start we the first symbol to alternate them every "round" char current_symbol = symbol_a; while (row_counter < row && col_counter < col) { // Filling the top row each time for (int i = col_counter; i < col; ++i) { mat[row_counter][i] = current_symbol; } row_counter++; // Filling the right-side col each time for (int i = row_counter; i < row; ++i) { mat[i][col-1] = current_symbol; } col--; // Filling the bottom row each time if (row_counter < row) { for (int i = col-1; i >= col_counter; --i) { mat[row-1][i] = current_symbol; } row--; } // Filling the left-side col each time if (col_counter < col) { for (int i = row-1; i >= row_counter; --i) { mat[i][col_counter] = current_symbol; } col_counter++; } // Checking the current symbol, and flipping it for the next iteration of the mat creation. if (current_symbol == symbol_a) { current_symbol = symbol_b; } else { current_symbol = symbol_a; } } string result; // Print the filled matrix for (int i = 0; i < mat.size(); i++) { for (int j = 0; j < mat[i].size(); j++) { result += mat[i][j]; } result += "\n"; } return result; } //Checking and approving the input int input_check(int col, int row, char symbol_a, char symbol_b) { // If number is even if (col%2==0 || row%2==0) { return 0; } // If number is negative if (col < 0 || row < 0) { return 0; } const int min_ascii_char = 33; const int max_ascii_char = 126; // If symbol has a lower value than our proper ascii symbol if (symbol_a < min_ascii_char || symbol_b < min_ascii_char) { return 0; } // If symbol has a higher value than our proper ascii symbol if (symbol_a > max_ascii_char || symbol_b > max_ascii_char) { return 0; } return 1; // Input is valid! } namespace ariel { string mat(int col, int row, char symbol_a, char symbol_b) { if (input_check(col, row, symbol_a, symbol_b) != 0) { return print_mat(col, row, symbol_a, symbol_b); } throw std::invalid_argument("ERROR: Invalid input to print mat!\n - Rows and Cols should be odd numbers.\n - Mat should be made of symbols, not numbers or letters."); } }
28.315315
174
0.573974
[ "vector" ]
30487062d644576ef345637e775af2ea35c7b2ba
7,133
cpp
C++
BCPlayerBuilder/BCPlayerBuilder.cpp
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
BCPlayerBuilder/BCPlayerBuilder.cpp
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
BCPlayerBuilder/BCPlayerBuilder.cpp
CommanderAsdasd/bcplayer
bf3481c9f08fb810660367b083392304479daaef
[ "MIT" ]
null
null
null
// BCPlayer builder ////////////////////////////////////////////// // use this program to make necessary changes to BeepComp //////// // source files to build a monolithic BCPlayer.cpp /////////////// #include <iostream> #include <string> #include <fstream> #include <vector> #include <windows.h> using namespace std; std::string str; vector<string> sourceCPP; int main() { system("cls"); str = ""; // first // add all the cpp files to be included // in the right order... (MPlayer will be added last) sourceCPP.push_back("source_cpp/BCPlayerBase.cpp"); sourceCPP.push_back("source_cpp/Sound.cpp"); sourceCPP.push_back("source_cpp/SFX.cpp"); sourceCPP.push_back("source_cpp/MData.cpp"); sourceCPP.push_back("source_cpp/DData.cpp"); sourceCPP.push_back("source_cpp/Astro.cpp"); sourceCPP.push_back("source_cpp/Fall.cpp"); sourceCPP.push_back("source_cpp/LFO.cpp"); sourceCPP.push_back("source_cpp/OSC.cpp"); sourceCPP.push_back("source_cpp/NOSC.cpp"); sourceCPP.push_back("source_cpp/DelayLine.cpp"); sourceCPP.push_back("source_cpp/MML.cpp"); sourceCPP.push_back("source_cpp/MPlayer.cpp"); // number of cpp files we have int nCPPFiles = sourceCPP.size(); string line; ifstream inFile; for(int i=0; i<nCPPFiles; i++) { inFile.open(sourceCPP[i].c_str()); if(!inFile) cout << "Error opening: " << sourceCPP[i] << endl; while( getline(inFile, line) ) { str += line + "\n"; } inFile.close(); str += "\n\n\n\n"; } // now rewrite the include directives... for example // #include "MML.h" will become #include "BC/MML.h" cout << "rewriting the header filenames to BC/---.h ...\n"; string header[11] = { "\"MData.h", "\"DData.h", "\"Astro.h", "\"LFO.h", "\"OSC.h", "\"OSC.h", "\"NOSC.h", "\"DelayLine.h", "\"MML.h", "\"MPlayer.h", "\"Fall.h" }; // there are 10 target filenames to rewrite for(int i=0; i<11; i++) { bool done = false; size_t found; while(!done) { found = str.find(header[i]); if(found!=string::npos) // target found! { str.erase(found, 1); // first erase the starting double quote str.insert(found, "\"BC/"); } else done = true; } } cout << "...finished!\n"; // comment out windows.h references... cout << "commenting out windows.h references...\n"; bool done = false; size_t found; while(!done) { found = str.find("#include <windows.h>"); if(found!=string::npos) // found! { str.insert(found+1, "?"); str.insert(found, "//"); } else done = true; } while(!done) { found = str.find("#include <Windows.h>"); if(found!=string::npos) // found! { str.insert(found+1, "?"); str.insert(found, "//"); } else done = true; } cout << "..finished!\n"; // comment out certain sections ... export functions etc. cout << "taking care of parts that need to be commented out...\n"; done = false; string target = "/*-----[BCPLAYER][STARTCOMMENTOUT]-----*/"; int nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "/*----------"); } else done = true; } done = false; target = "/*-----[BCPLAYER][ENDCOMMENTOUT]-----*/"; nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "----------*/"); } else done = true; } cout << "..finished!\n"; // adjust MPlayer.cpp file cout << "fixing up MPlayer.cpp now...\n"; done = false; target = "/*-----[BCPLAYER][CALLSFX]-----*/"; nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "mix += sfx->getOutput(channel);"); } else done = true; } done = false; target = "/*-----[BCPLAYER][CALLSFXINCALLBACK]-----*/"; nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "soundAmplitudeLeft = sfx->getOutput(0);\n\t\t\tsoundAmplitudeRight = sfx->getOutput(1);"); } else done = true; } done = false; target = "/*-----[BCPLAYER][ADDSFXBINDER]-----*/"; nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "void MPlayer::bindSFX(SFX *sfxObj)\n\t{ sfx = sfxObj; }"); } else done = true; } cout << "...finished!\n"; // finally write the contents of our string to BCPlayer.cpp ofstream outFile("target_cpp/BCPlayer.cpp", ios::trunc); if(!outFile) cout << "Cannot access or create the target file target_cpp/BCPlayer.cpp!\n"; else cout << "Writing BCPlayer.cpp file now...\n"; outFile << str; outFile.close(); cout << "Finished! Look in target_cpp folder :)\n"; // now we'll adjust MPlayer.h file, also! cout << "fixing up MPlayer.h now...\n"; ifstream inFile2("source_h/MPlayer.h"); if(!inFile2) cout << "Error opening: " << "source_h/MPlayer.h" << endl; str = ""; while( getline(inFile2, line) ) { str += line + "\n"; } inFile2.close(); // search and replace! done = false; target = "/*-----[BCPLAYER][INCLUDESFXHEADER]-----*/"; nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "#include \"SFX.h\""); } else done = true; } done = false; target = "/*-----[BCPLAYER][ADDSFXPROPERTIES]-----*/"; nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "void bindSFX(SFX* sfxObj);\n\tSFX* sfx;"); } else done = true; } // change portaudio.h target place to BC/ folder done = false; target = "#include <portaudio.h>"; nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "#include \"BC/portaudio.h\""); } else done = true; } done = false; target = "#include \"portaudio.h\""; nCharsToErase = strlen(target.c_str()); while(!done) { found = str.find(target); if(found!=string::npos) // found! { str.erase(found, nCharsToErase); str.insert(found, "#include \"BC/portaudio.h\""); } else done = true; } cout << "...finished!\n"; // finally write the contents of our string to MPlayer.h ofstream outFile2("target_h/MPlayer.h", ios::trunc); if(!outFile2) cout << "Cannot access or create the target file target_h/MPlayer.h!\n"; else cout << "Writing MPlayer.h file now...\n"; outFile2 << str; outFile2.close(); cout << "Finished! Look in target_h folder :)\n"; ShellExecute(NULL, "open", "target_cpp", NULL, NULL, SW_SHOWNORMAL); ShellExecute(NULL, "open", "target_h", NULL, NULL, SW_SHOWNORMAL); return 0; }
23.084142
112
0.615449
[ "vector" ]
304f3b66970edff347ca76c216a6573ef1e91d5e
3,719
cc
C++
idle-gc.cc
bnoordhuis/node-idle-gc
822708fa92758fb8df3b500f3986fab67a9e4c50
[ "ISC" ]
34
2015-01-18T16:59:49.000Z
2020-03-13T22:31:48.000Z
idle-gc.cc
bnoordhuis/node-idle-gc
822708fa92758fb8df3b500f3986fab67a9e4c50
[ "ISC" ]
3
2015-04-14T17:18:49.000Z
2017-05-23T08:46:06.000Z
idle-gc.cc
bnoordhuis/node-idle-gc
822708fa92758fb8df3b500f3986fab67a9e4c50
[ "ISC" ]
6
2015-12-19T12:01:17.000Z
2019-02-02T07:54:05.000Z
/* * Copyright (c) 2012, Ben Noordhuis <info@bnoordhuis.nl> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "compat.h" #include "compat-inl.h" #include "node.h" #include "uv.h" #include "v8.h" #include <stdio.h> #include <stdlib.h> namespace { namespace C = ::compat; typedef enum { STOP, RUN, PAUSE } gc_state_t; bool trace_gc; int64_t interval; v8::Isolate* isolate; gc_state_t state; gc_state_t prev_state; uv_timer_t timer_handle; uv_check_t check_handle; uv_prepare_t prepare_handle; void Trace() { static const char states[3][6] = { "STOP", "RUN", "PAUSE" }; printf("[idle gc] prev_state=%s state=%s\n", states[prev_state], states[state]); } bool IdleNotification() { #if NODE_VERSION_AT_LEAST(0, 12, 0) static const int idle_time_in_ms = 5; return isolate->IdleNotification(idle_time_in_ms); #else return v8::V8::IdleNotification(); #endif } void Timer(uv_timer_t*) { if (IdleNotification()) state = PAUSE; if (trace_gc) Trace(); } void Check(uv_check_t*) { prev_state = state; } void Prepare(uv_prepare_t*) { if (state == PAUSE && prev_state == PAUSE) state = RUN; if (state == RUN) { uv_timer_start(&timer_handle, reinterpret_cast<uv_timer_cb>(Timer), interval, 0); } } void Stop() { state = STOP; uv_timer_stop(&timer_handle); uv_check_stop(&check_handle); uv_prepare_stop(&prepare_handle); } C::ReturnType Stop(const C::ArgumentType& args) { C::ReturnableHandleScope handle_scope(args); Stop(); return handle_scope.Return(); } C::ReturnType Start(const C::ArgumentType& args) { C::ReturnableHandleScope handle_scope(args); Stop(); interval = args[0]->IsNumber() ? args[0]->IntegerValue() : 0; if (interval <= 0) interval = 5000; // Default to 5 seconds. state = RUN; uv_check_start(&check_handle, reinterpret_cast<uv_check_cb>(Check)); uv_prepare_start(&prepare_handle, reinterpret_cast<uv_prepare_cb>(Prepare)); return handle_scope.Return(); } void Init(v8::Local<v8::Object> obj) { isolate = v8::Isolate::GetCurrent(); uv_timer_init(uv_default_loop(), &timer_handle); uv_check_init(uv_default_loop(), &check_handle); uv_prepare_init(uv_default_loop(), &prepare_handle); uv_unref(reinterpret_cast<uv_handle_t*>(&timer_handle)); uv_unref(reinterpret_cast<uv_handle_t*>(&check_handle)); uv_unref(reinterpret_cast<uv_handle_t*>(&prepare_handle)); obj->Set(C::String::NewFromUtf8(isolate, "stop"), C::FunctionTemplate::New(isolate, Stop)->GetFunction()); obj->Set(C::String::NewFromUtf8(isolate, "start"), C::FunctionTemplate::New(isolate, Start)->GetFunction()); #if NODE_VERSION_AT_LEAST(1, 0, 0) // v8::Isolate::IdleNotification() is a no-op without --use_idle_notification. { static const char flag[] = "--use_idle_notification"; v8::V8::SetFlagsFromString(flag, sizeof(flag) - 1); } #endif const char* var = getenv("IDLE_GC_TRACE"); trace_gc = (var != NULL && atoi(var) != 0); } NODE_MODULE(idle_gc, Init) } // anonymous namespace
26.564286
80
0.711213
[ "object" ]
304f930b85219c75168e8e5a4bdef916cb10ebb0
4,152
hpp
C++
include/whack/codegen/expressions/factors/memberinitlist.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
54
2018-10-28T07:18:31.000Z
2022-03-08T20:30:40.000Z
include/whack/codegen/expressions/factors/memberinitlist.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
null
null
null
include/whack/codegen/expressions/factors/memberinitlist.hpp
onchere/whack
0702e46f13855d4efd8dd0cb67af2fddfb84b00c
[ "Apache-2.0" ]
5
2018-10-28T14:43:53.000Z
2020-04-26T19:52:58.000Z
/** * Copyright 2018-present Onchere Bironga * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef WHACK_MEMBERINITLIST_HPP #define WHACK_MEMBERINITLIST_HPP #pragma once #include "structmember.hpp" namespace whack::codegen::expressions::factors { class MemberInitList final : public Factor { public: explicit MemberInitList(const mpc_ast_t* const ast) : Factor(kMemberInitList), state_{ast->state} { for (auto i = 0; i < ast->children_num; i += 4) { const llvm::StringRef name{ast->children[i]->contents}; for (const auto& [varName, _] : values_) { if (varName == name) { warning("member `{}` already declared for the member " "initializer list at line {}", name.data(), state_.row + 1); } } values_.emplace_back( std::pair{name, getExpressionValue(ast->children[i + 2])}); } } llvm::Expected<llvm::Value*> codegen(llvm::IRBuilder<>& builder) const final { small_vector<llvm::StringRef> typeNames; small_vector<llvm::Value*> values; small_vector<llvm::Type*> types; for (const auto& [member, value] : values_) { auto v = value->codegen(builder); if (!v) { return v.takeError(); } typeNames.push_back(member); auto val = getLoadedValue(builder, *v); if (!val) { return val.takeError(); } values.push_back(*val); types.push_back((*val)->getType()); } const auto type = llvm::StructType::create(builder.getContext(), types, "::memberinitlist", true); const auto ret = builder.CreateAlloca(type, 0, nullptr, type->getName()); for (size_t i = 0; i < values.size(); ++i) { const auto ptr = builder.CreateStructGEP(type, ret, i, ""); builder.CreateStore(values[i], ptr); } addStructTypeMetadata(builder.GetInsertBlock()->getModule(), "structures", type->getStructName(), typeNames); return ret; } llvm::Expected<llvm::Value*> codegen(llvm::IRBuilder<>& builder, llvm::Type* const type) const { if (!type->isStructTy()) { return error("cannot use a member initializer list for type " "at line {}", state_.row + 1); } const auto module = builder.GetInsertBlock()->getParent()->getParent(); const auto structName = type->getStructName().str(); const auto obj = builder.CreateAlloca(type, 0, nullptr, structName); for (const auto& [member, value] : values_) { const auto idx = StructMember::getIndex(*module, structName, member); if (!idx) { return error("field `{}` does not exist for struct `{}` at line {}", member.data(), structName, state_.row + 1); } const auto ptr = builder.CreateStructGEP(type, obj, idx.value(), member); auto v = value->codegen(builder); if (!v) { return v.takeError(); } auto val = getLoadedValue(builder, *v, false); if (!val) { return val.takeError(); } if ((*val)->getType() != ptr->getType()->getPointerElementType()) { return error("type mismatch: cannot assign value to " "field `{}` of struct `{}` at line {}", member.data(), structName, state_.row + 1); } builder.CreateStore(*val, ptr); } return obj; } private: const mpc_state_t state_; std::vector<std::pair<llvm::StringRef, expr_t>> values_; }; } // end namespace whack::codegen::expressions::factors #endif // WHACK_MEMBERINITLIST_HPP
36.104348
80
0.608141
[ "vector" ]
3053f5117bcda482dff6d91d0e234f9b38238006
1,320
hpp
C++
modules/core/sdk/include/nt2/core/container/dsl/generator.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/core/sdk/include/nt2/core/container/dsl/generator.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
null
null
null
modules/core/sdk/include/nt2/core/container/dsl/generator.hpp
pbrunet/nt2
2aeca0f6a315725b335efd5d9dc95d72e10a7fb7
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_CORE_CONTAINER_DSL_GENERATOR_HPP_INCLUDED #define NT2_CORE_CONTAINER_DSL_GENERATOR_HPP_INCLUDED #include <nt2/core/container/dsl/forward.hpp> #include <nt2/core/container/dsl/details/generator.hpp> #include <nt2/core/container/dsl/details/trait_transform.hpp> #include <boost/proto/traits.hpp> namespace nt2 { namespace container { //========================================================================== /*! * proto::transform performing the computation of the type and generation * of a nt2::container::expression **/ //========================================================================== template<class Domain> struct generator_transform : details::trait_transform< details::generator, Domain > { typedef void proto_use_basic_expr_; }; } } #endif
37.714286
80
0.535606
[ "transform" ]
30594cb4bfaf479f8baac0baa6a3939a0ed46802
4,097
hpp
C++
src/character/bodyPart.hpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
18
2016-05-26T18:11:31.000Z
2022-02-10T20:00:52.000Z
src/character/bodyPart.hpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
null
null
null
src/character/bodyPart.hpp
Galfurian/RadMud
1362cb0ee1b7a17386e57a98e29dd8baeea75af3
[ "MIT" ]
2
2016-06-30T15:20:01.000Z
2020-08-27T18:28:33.000Z
/// @file bodyPart.hpp /// @author Enrico Fraccaroli /// @date Jan 08 2017 /// @copyright /// Copyright (c) 2017 Enrico Fraccaroli <enrico.fraccaroli@gmail.com> /// Permission is hereby granted, free of charge, to any person obtaining a /// copy of this software and associated documentation files (the "Software"), /// to deal in the Software without restriction, including without limitation /// the rights to use, copy, modify, merge, publish, distribute, sublicense, /// and/or sell copies of the Software, and to permit persons to whom the /// Software is furnished to do so, subject to the following conditions: /// The above copyright notice and this permission notice shall be included /// in all copies or substantial portions of the Software. /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL /// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING /// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER /// DEALINGS IN THE SOFTWARE. #pragma once #include "table.hpp" #include "material.hpp" #include <string> #include <vector> #include <memory> class ResourceModel; /// The flags of a body part. using BodyPartFlag = enum class BodyPartFlag_t { None = 0, ///< [0] No flag. CanWear = 1, ///< [1] The equipment can be worn on the the body part. CanWield = 2, ///< [2] The body part can be used to wield something. Internal = 4 ///< [4] The body part is an internal part. ///< [8] ///< [16] ///< [32] ///< [64] ///< [128] }; /// @brief An anatomic part of the body. class BodyPart { public: /// @brief A structure to hold information about the resources provided /// by a body part. struct BodyResource { /// The provided resource. std::shared_ptr<ResourceModel> resource; /// The material of the resource. Material * material; /// The quantity. int quantity; /// The difficulty (DC) associated with the resources. int difficulty; }; /// @brief A structure which holds information about the attack which can /// be performed with a body part. struct BodyWeapon { /// The name of the attack. std::string name; /// The article of the attack. std::string article; /// The minimum damage. unsigned int minDamage; /// The maximum damage. unsigned int maxDamage; /// The range of the natural weapon. int range; /// Returns the name of the attack. std::string getName(bool colored = false) const; /// Randomly roll the weapon damage. unsigned int rollDamage() const; }; /// The virtual number. unsigned int vnum; /// The name. std::string name; /// The description. std::string description; /// The flags associated with the body part. unsigned int flags; /// The resources which can be produced from this body part. std::vector<BodyResource> resources; /// The weapon ability of this body part. std::shared_ptr<BodyWeapon> weapon; /// @brief Constructor. BodyPart(); /// @brief Destructor. virtual ~BodyPart(); /// @brief Check the correctness of the body part. /// @return <b>True</b> if the body part has correct values,<br> /// <b>False</b> otherwise. bool check(); /// @brief Return the name of the body part with all lowercase characters. /// @param capital If true the first letters of the description are /// changed to upper case. /// @return The name of the character. std::string getDescription(bool capital = false) const; /// @brief Fills the provided table with the information concerning /// the body part. void getSheet(Table & sheet) const; };
33.859504
79
0.648279
[ "vector" ]
305d7249ff087bbd2a19f60745a736f7f4fb48af
5,076
cpp
C++
simulation/quadrotor_simulation/src/pose_pub.cpp
Sanjeeev-K/Quad-rotor-Project
69abf20edc822d5e15127df0d3f7f00ab2b03dbf
[ "MIT" ]
null
null
null
simulation/quadrotor_simulation/src/pose_pub.cpp
Sanjeeev-K/Quad-rotor-Project
69abf20edc822d5e15127df0d3f7f00ab2b03dbf
[ "MIT" ]
null
null
null
simulation/quadrotor_simulation/src/pose_pub.cpp
Sanjeeev-K/Quad-rotor-Project
69abf20edc822d5e15127df0d3f7f00ab2b03dbf
[ "MIT" ]
2
2019-11-25T23:36:44.000Z
2019-11-28T20:07:25.000Z
#include "../include/quadrotor_simulation/pose_pub.h" PosePub::PosePub(ros::NodeHandle* nodehandle, string fileName, string delimeter):nh_(*nodehandle), fileName_(fileName), delimeter_(delimeter) { // constructor ROS_INFO("In class constructor of PosePub"); getPath(); initVec(); initSub(); initPub(); } void PosePub::getPath() { ifstream file(fileName_); string line = ""; vector<vector<string>> dataList; // Iterate through each line and split the content using delimeter while (getline(file, line)) { vector<string> vec; boost::algorithm::split(vec, line, boost::is_any_of(delimeter_)); dataList.push_back(vec); } // Close the File file.close(); for (auto rows : dataList) { vector<double> pathEle; for (auto ele : rows) { pathEle.push_back(stod(ele)); } path.push_back(pathEle); } } void PosePub::initSub() { // ROS_INFO("Initializing Subscribers"); stop_sub_ = nh_.subscribe("/drone1/ground_truth_to_tf/pose", 1, &PosePub::eventCallback,this); // currentpos_sub_ = nh_.subscribe("/drone1/ground_truth_to_tf/pose", 1, &PosePub::currentposCallback,this); } void PosePub::initVec() { currentPose = vector<double> (vector<double> (7, 0)); goalPose = vector<double> (vector<double> (7, 0)); } void PosePub::initPub() { // ROS_INFO("Initializing Publishers"); goalpos_pub_ = nh_.advertise<geometry_msgs::PoseStamped>("/drone1/command/pose", 1, true); controlinput_pub_ = nh_.advertise<geometry_msgs::Twist>("/drone1/cmd_vel", 1, true); markerarray_pub_ = nh_.advertise<visualization_msgs::MarkerArray>("/visualization_markerarray", 10); } void PosePub::eventCallback(const geometry_msgs::PoseStamped& odom1) { currentPose[0] = odom1.pose.position.x; currentPose[1] = odom1.pose.position.y; currentPose[2] = odom1.pose.position.z; // currentPose[3] = odom3.pose.orientation.x; // currentPose[4] = odom3.pose.orientation.y; // currentPose[5] = odom3.pose.orientation.z; // currentPose[6] = odom3.pose.orientation.w; goalPose[0] = path[path_index][0]; goalPose[1] = path[path_index][1]; goalPose[2] = path[path_index][2]; // cout << "enter" << endl; path_marker.type = visualization_msgs::Marker::CUBE_LIST; path_marker.action = visualization_msgs::Marker::ADD; path_marker.ns = "paths"; path_marker.scale.x = 0.1; path_marker.scale.y = 0.1; path_marker.scale.z = 0.1; path_marker.header.frame_id = "/world"; path_marker.color.a = 1.0; path_marker.id = 0; path_marker.lifetime = ros::Duration(); geometry_msgs::Point obj; obj.x = odom1.pose.position.x; obj.y = odom1.pose.position.y; // std::cout << "pos: " << obj.x << " " << obj.y << std::endl; obj.z = odom1.pose.position.z; path_marker.points.push_back(obj); path_marker.color.g = 0.0; path_marker.color.r = 1.0; path_marker.colors.push_back(path_marker.color); path_marker.header.stamp = ros::Time::now(); path_marker_array.markers.push_back(path_marker); markerarray_pub_.publish(path_marker_array); path_marker_array.markers.pop_back(); int pathsize = path.size(); // cout << "Xinit pose: " << currentPose[0] << " Yinit pose: " << currentPose[1] << " Zinit pose: " << currentPose[2] <<endl; // cout << "Xtarget pose: " << goalPose[0] << " Ytarget pose: " << goalPose[1] << " Ztarget pose: " << goalPose[2] <<endl; if ((abs(currentPose[0] - goalPose[0])<reachedCheck) && (abs(currentPose[1] - goalPose[1])<reachedCheck ) && (abs(currentPose[2] - goalPose[2])<reachedCheck)) { path_index++; goalPose[0] = path[path_index][0]; goalPose[1] = path[path_index][1]; goalPose[2] = path[path_index][2]; // goalPose[3] = path[path_index-1][3]; // goalPose[4] = path[path_index-1][4]; // goalPose[5] = path[path_index-1][5]; // goalPose[6] = path[path_index-1][6]; goal_pose.header.frame_id="world"; // goal_pose.header.stamp = ros::Time::now(); goal_pose.pose.position.x = goalPose[0]; goal_pose.pose.position.y = goalPose[1]; goal_pose.pose.position.z = goalPose[2]; goal_pose.pose.orientation.x = goalPose[3]; goal_pose.pose.orientation.y = goalPose[4]; goal_pose.pose.orientation.z = goalPose[5]; goal_pose.pose.orientation.w = goalPose[6]; goalpos_pub_.publish(goal_pose); } } PosePub::~PosePub() { } int main(int argc, char** argv) { ros::init(argc, argv, "pose_pub"); //node name string fileName = "/home/han/quadrotor_ws/src/quadrotor_demo/path.csv"; string delimeter = ","; ros::NodeHandle nh; // create a node handle; need to pass this to the class constructor PosePub posepub(&nh, fileName, delimeter); //instantiate an ExampleRosClass object and pass in pointer to nodehandle for constructor to use ROS_INFO("Initializing posepub..."); ros::spin(); return 0; }
36
144
0.64342
[ "object", "vector" ]
3072194bc0df6300f5bd50d9bf409695f79c0ccc
15,232
cpp
C++
src/util.cpp
akivajp/lev
945aa438ce4718f60cde35556c55655515cb423b
[ "MIT" ]
null
null
null
src/util.cpp
akivajp/lev
945aa438ce4718f60cde35556c55655515cb423b
[ "MIT" ]
null
null
null
src/util.cpp
akivajp/lev
945aa438ce4718f60cde35556c55655515cb423b
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////// // Name: src/util.hpp // Purpose: source for utility functions // Author: Akiva Miura <akiva.miura@gmail.com> // Created: 01/18/2011 // Copyright: (C) 2010-2011 Akiva Miura // Licence: MIT License ///////////////////////////////////////////////////////////////////////////// // pre-compiled header #include "prec.h" // declartions #include "lev/util.hpp" // dependencies #include "lev/debug.hpp" #include "lev/entry.hpp" //#include "lev/fs.hpp" #include "lev/string.hpp" // libraries #include <boost/format.hpp> #include <luabind/luabind.hpp> #ifdef _WIN32 #include <windows.h> #endif // _WIN32 static const char *code_using = "-- looking up of varnames\n\ local lookup = function(env, varname)\n\ meta = getmetatable(env)\n\ if meta.__owner[varname] ~= nil then\n\ return meta.__owner[varname]\n\ end\n\ for i,t in ipairs(meta.__lookup) do\n\ if t[varname] ~= nil then\n\ return t[varname]\n\ end\n\ end\n\ if (meta.__parent == meta.__owner) then\n\ -- non sense to look up twice for the same table\n\ return nil\n\ end\n\ return meta.__parent[varname]\n\ end\n\ \n\ -- subtituting the new value\n\ local substitute = function(env, key, value)\n\ meta = getmetatable(env)\n\ meta.__owner[key] = value\n\ end\n\ \n\ -- like using directive\n\ return function(...)\n\ -- getting environment of the caller and its metatable\n\ local env = getfenv(2)\n\ local meta = getmetatable(env) or {}\n\ -- getting the caller itself\n\ local f = _G.setfenv(2, env)\n\ if (meta.__caller == f) then\n\ -- setup was already done, changing looking up preference\n\ if (...) == nil then\n\ -- 1st arg is nil, resetting looking up setting\n\ if #{...} >= 2 then\n\ meta.__lookup = lev.util.reverse({_G.select(2, ...)})\n\ else\n\ meta.__lookup = {}\n\ end\n\ return env\n\ end\n\ for i,val in _G.ipairs({...}) do\n\ lev.util.remove_first(meta.__lookup, val)\n\ table.insert(meta.__lookup, 1, val)\n\ end\n\ return env\n\ end\n\ \n\ -- setting new looking up mechanism\n\ local newenv = {}\n\ local newmeta = {}\n\ newmeta.__caller = f\n\ newmeta.__index = lookup\n\ newmeta.__lookup = lev.util.reverse({...})\n\ newmeta.__newindex = substitute\n\ newmeta.__owner = meta.__owner or env\n\ newmeta.__parent = env\n\ setmetatable(newenv, newmeta)\n\ setfenv(2, newenv)\n\ return newenv\n\ end\n\ "; int luaopen_lev_util(lua_State *L) { using namespace lev; using namespace luabind; open(L); globals(L)["require"]("lev.base"); module(L, "lev") [ namespace_("util") [ def("copy_table", &util::copy_table), def("find_member", &util::find_member), def("execute", &util::execute), def("print_table", &util::print_table), def("open", &util::open), def("open", &util::open1), def("serialize", &util::serialize1), def("tostring", &util::tostring) ] ]; object lev = globals(L)["lev"]; object util = lev["util"]; register_to(util, "execute_code", &util::execute_code_l); register_to(util, "merge", &util::merge); register_to(util, "remove_first", &util::remove_first); register_to(util, "reverse", &util::reverse); load_to(util, "using", code_using); lev["execute"] = util["execute"]; lev["execute_code"] = util["execute_code"]; globals(L)["package"]["loaded"]["lev.util"] = util; return 0; } namespace lev { luabind::object util::copy_function(luabind::object func) { using namespace luabind; lua_State *L = func.interpreter(); if (! L) { return object(); } return globals(L)["loadstring"](globals(L)["string"]["dump"](func)); } luabind::object util::copy_table(luabind::object table) { using namespace luabind; lua_State *L = table.interpreter(); if (L and type(table) == LUA_TTABLE) { object t = newtable(L); for (iterator i(table), end; i != end; i++) { t[i.key()] = *i; } return t; } else { return object(); } } luabind::object util::find_member(luabind::object table, luabind::object var) { using namespace luabind; if (! table.is_valid()) { return object(); } if (type(table) != LUA_TTABLE) { return object(); } for (iterator i(table), end; i != end; i++) { if (*i == var) { return i.key(); } } return object(); } bool util::execute(const std::string &target) { // wxString exe = wxStandardPaths::Get().GetExecutablePath(); // wxExecute(exe + wxT(" ") + wxString(target.c_str(), wxConvUTF8)); // return true; } int util::execute_code_l(lua_State *L) { using namespace luabind; const char *code = ""; // object t = util::get_merged(L, 1, -1); // if (t["code"]) { code = object_cast<const char *>(t["code"]); } // else if (t["c"]) { code = object_cast<const char *>(t["c"]); } // else if (t["lua.string1"]) { code = object_cast<const char *>(t["lua.string1"]); } // // try { // std::string prefix = application::get_app()->get_name() + "/" + "localcode"; // object tmp = globals(L)["lev"]["classes"]["temp_name"]["create"](prefix, ".lua"); // std::string name = object_cast<const char *>(tmp["name"]); // FILE *out = fopen(name.c_str(), "w"); // if (out == NULL) { throw -1; } // int len = strlen(code); // if (fwrite(code, 1, len, out) != len) { throw -2; } // fclose(out); // util::execute("\"" + name + "\""); // // lua_pushboolean(L, true); // return 1; // } // catch (...) { // lua_pushboolean(L, false); // return 1; // } return 0; } luabind::object util::get_merged(lua_State *L, int begin, int end) { using namespace luabind; if (end < 0) { end = lua_gettop(L) + 1 + end; } if (end < begin) { return newtable(L); } lua_pushcfunction(L, &util::merge); newtable(L).push(L); for (int i = begin; i <= end; i++) { object(from_stack(L, i)).push(L); } lua_call(L, end + 2 - begin, 1); object t(from_stack(L, -1)); lua_pop(L, 1); return t; } int util::merge(lua_State *L) { using namespace luabind; int n = lua_gettop(L); // 1st arg must be table luaL_checktype(L, 1, LUA_TTABLE); object target(from_stack(L, 1)); for (int i = 2; i <= n; i++) { object arg(from_stack(L, i)); int num_type = type(arg); if (num_type == LUA_TBOOLEAN) { target["lua.boolean"] = arg; for (int j = 1; ; ++j) { std::string key = boost::io::str(boost::format("lua.boolean%1%") % j); if (! target[key]) { target[key] = arg; break; } } } else if (num_type == LUA_TFUNCTION) { target["lua.function"] = arg; for (int j = 1; ; ++j) { std::string key = boost::io::str(boost::format("lua.function%1%") % j); if (! target[key]) { target[key] = arg; break; } } } else if (num_type == LUA_TNUMBER) { target["lua.number"] = arg; for (int j = 1; ; ++j) { std::string key = boost::io::str(boost::format("lua.number%1%") % j); if (! target[key]) { target[key] = arg; break; } } } else if (num_type == LUA_TSTRING) { target["lua.string"] = arg; for (int j = 1; ; ++j) { std::string key = boost::io::str(boost::format("lua.string%1%") % j); if (! target[key]) { target[key] = arg; break; } } } else if (num_type == LUA_TTABLE) { for (iterator i(arg), end; i != end; ++i) { if (type(i.key()) == LUA_TNUMBER) { object tmp = *i; lua_pushcfunction(L, &util::merge); target.push(L); tmp.push(L); lua_call(L, 2, 0); } else if (type(i.key()) == LUA_TSTRING) { target[i.key()] = *i; for (int j = 1; ; ++j) { std::string key = (boost::format("%1%%2%") % i.key() % j).str(); if (!target[key]) { target[key] = *i; break; } } } else { target[i.key()] = *i; } } } else if (num_type == LUA_TUSERDATA) { object obj_id; try { obj_id = arg["type_id"]; } catch (...) { // error on index access, continue to next iteration continue; } if (obj_id.is_valid() && type(obj_id) == LUA_TNUMBER) { base::type_id id = (base::type_id)object_cast<int>(obj_id); while (id != base::LEV_TNONE) { const char *name = base::get_type_name_by_id(id); target[name] = arg; for (int j = 1; ; ++j) { std::string key = (boost::format("%1%%2%") % name % j).str(); if (! target[key]) { target[key] = arg; break; } } id = base::get_base_id(id); } } target["lua.userdata"] = arg; for (int j = 1; ; ++j) { std::string key = boost::io::str(boost::format("lua.userdata%1%") % j); if (! target[key]) { target[key] = arg; break; } } } else if (num_type == LUA_TNIL) { // nothing to do } } target.push(L); return 1; } bool util::open(const std::string &path, const std::string &type) { #ifdef _WIN32 ShellExecute(0, "open", path.c_str(), 0, 0, SW_SHOWDEFAULT); return true; #else if (path.empty()) { return false; } int unused = system((std::string("xdg-open ") + path).c_str()); return true; #endif // _WIN32 // wxMimeTypesManager manager; // wxFileType *ft = NULL; // if (! type.empty()) // { // ft = manager.GetFileTypeFromExtension(wxString(type.c_str(), wxConvUTF8)); // if (! ft) { ft = manager.GetFileTypeFromMimeType(wxString(type.c_str(), wxConvUTF8)); } // if (! ft) { return false; } // } // else // { // wxString ext(file_system::get_ext(path).c_str(), wxConvUTF8); // if (path.find("http://") == 0 || path.find("https://") == 0) // { // ft = manager.GetFileTypeFromMimeType(wxT("text/html")); // } // else // { // ft = manager.GetFileTypeFromExtension(ext); // } // if (! ft) { return false; } // } // wxString command = ft->GetOpenCommand(wxString(path.c_str(), wxConvUTF8)); // wxExecute(command); // return true; } bool util::print_table(luabind::object t) { using namespace luabind; lua_State *L = t.interpreter(); if (!t) { return false; } if (type(t) == LUA_TTABLE) { for (iterator i(t), end; i != end; i++) { globals(L)["print"](i.key(), *i); } } else { globals(L)["print"](t); } return true; } // find "value" from "t" and remove first one int util::remove_first(lua_State *L) { using namespace luabind; luaL_checktype(L, 1, LUA_TTABLE); luaL_checkany(L, 2); object table(from_stack(L, 1)); object value(from_stack(L, 2)); object fn_remove = globals(L)["table"]["remove"]; for (iterator i(table), end; i != end; i++) { if (*i == value) { object res = (*i); res.push(L); fn_remove(table, i.key()); return 1; } } lua_pushnil(L); return 1; } // return new order-reversed table of "t" int util::reverse(lua_State *L) { using namespace luabind; luaL_checktype(L, 1, LUA_TTABLE); object table(from_stack(L, 1)); object rev = newtable(L); object fn_insert = globals(L)["table"]["insert"]; for (iterator i(table), end; i != end; i++) { fn_insert(rev, 1, *i); } rev.push(L); return 1; } // looking up of "varnames" static int lookup(lua_State *L) { using namespace luabind; luaL_checktype(L, 1, LUA_TTABLE); luaL_checkstring(L, 2); object env(from_stack(L, 1)); object varname(from_stack(L, 2)); object meta = getmetatable(env); if (meta["__owner"][varname] != nil) { meta["__owner"][varname].push(L); return 1; } for (iterator i(meta["__lookup"]), end; i != end; i++) { if ((*i)[varname] != nil) { (*i)[varname].push(L); return 1; } } // non sense to look up twice for the same table if (meta["__parent"] == meta["__owner"]) { return 0; } meta["__parent"][varname].push(L); return 1; } std::string util::serialize(luabind::object var, int indent) { using namespace luabind; lua_State *L = var.interpreter(); if (indent > 20) { luaL_error(L, "a cyclic linkage was detected!"); return ""; } if (! var.is_valid()) { return "nil"; } if (type(var) == LUA_TNIL) { return "nil"; } if (type(var) == LUA_TBOOLEAN) { if (var) { return "true"; } else { return "false"; } } if (type(var) == LUA_TNUMBER) { return object_cast<const char *>(globals(L)["tostring"](var)); } else if (type(var) == LUA_TSTRING) { // unistr str(object_cast<const char *>(var)); // std::string str(object_cast<const char *>(var)); // str.Replace(wxT("\\"), wxT("\\\\"), true); var = var["gsub"](var, "\\", "\\\\"); // str.Replace(wxT("\""), wxT("\\\""), true); var = var["gsub"](var, "\"", "\\\""); // str.Replace(wxT("\'"), wxT("\\\'"), true); var = var["gsub"](var, "\'", "\\\'"); // str.Replace(wxT("\n"), wxT("\\\n"), true); var = var["gsub"](var, "\n", "\\n"); std::string str(object_cast<const char *>(var)); return "\"" + str + "\""; } else if (type(var) == LUA_TTABLE) { std::string str_indent = ""; for (int i = 0; i < indent; i++) { str_indent += " "; } iterator i(var), end; std::string str_exp = "{\n"; for (; i != end; i++) { if (type(i.key()) != LUA_TNUMBER && type(i.key()) != LUA_TSTRING) { continue; } str_exp += str_indent + " [" + serialize(i.key(), 0) + "] = "; str_exp += serialize(*i, indent + 2) + ",\n"; } str_exp += str_indent + "}"; return str_exp; } return "nil"; } std::string util::tostring(luabind::object obj) { using namespace luabind; if (! obj.is_valid()) { return ""; } lua_State *L = obj.interpreter(); size_t len; try { const char *str = object_cast<const char *>(globals(L)["tostring"](obj)); if (! str) { return ""; } return str; } catch (...) { lev::debug_print("error on util::tostring"); return ""; } } }
26.082192
95
0.515034
[ "object" ]
308fc8447ccab8f96304cf2f3e77812bab090fdc
286
cpp
C++
Adobe/12.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
Adobe/12.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
Adobe/12.cpp
aabhas-sao/6Companies30Days
0c07f62b05e18c36fc5262cd51c251b8a6301a2f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<int> leaders(int a[], int n) { int x = INT_MIN; vector<int> ans; for (int i = n - 1; i >= 0; i--) { if (a[i] >= x) { ans.push_back(a[i]); x = a[i]; } } reverse(ans.begin(), ans.end()); return ans; }
16.823529
37
0.503497
[ "vector" ]
30910d80b857cee642f10139c383008f5d4bc833
2,510
cpp
C++
src/tabcat.cpp
Bleskocvok/tabcat
50212e354c5a61105d66b980eec411416a254d0d
[ "BSD-3-Clause" ]
1
2021-07-15T19:12:38.000Z
2021-07-15T19:12:38.000Z
src/tabcat.cpp
Bleskocvok/tabcat
50212e354c5a61105d66b980eec411416a254d0d
[ "BSD-3-Clause" ]
null
null
null
src/tabcat.cpp
Bleskocvok/tabcat
50212e354c5a61105d66b980eec411416a254d0d
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <vector> #include <string_view> #include "include/table.hpp" #include "include/unicode.hpp" #include "include/printer.hpp" #include "app_settings.hpp" // argument includes #include "delimiter.hpp" #include "disable_border.hpp" #include "help.hpp" #include "version.hpp" #include "format.hpp" #include "locale.hpp" #include "file.hpp" #include "output_file.hpp" #include "highlight.hpp" void perform_app(const std::vector<std::string_view>& args); std::vector<std::string_view> get_arg_vec(int argc, char** argv); int main(int argc, char** argv) { auto arg_vec = get_arg_vec(argc, argv); try { perform_app(arg_vec); } catch (invalid_table& ex) { std::cerr << "Invalid table: " << ex.what() << std::endl; return 1; } catch (std::exception& ex) { std::cerr << "Error: " << ex.what() << std::endl; return 2; } return 0; } std::vector<std::string_view> get_arg_vec(int argc, char** argv) { std::vector<std::string_view> arg_vec; arg_vec.reserve(argc); for (int i = 0; i < argc; i++) { arg_vec.push_back(argv[i]); } return arg_vec; } void perform_app(const std::vector<std::string_view>& args) { using namespace std::string_literals; assert(args.size() >= 1); set_locale_all("en_US.utf8"); app_settings app; app.program_name = args[0]; // parsing app.args.emplace<delimiter>(); app.args.emplace<locale>(); // output style app.args.emplace<format>(); app.args.emplace<output_file>(); app.args.emplace<highlight>(); // borders disabling app.args.emplace<disable_border<border_pos::top>>(); app.args.emplace<disable_border<border_pos::bot>>(); app.args.emplace<disable_border<border_pos::left>>(); app.args.emplace<disable_border<border_pos::right>>(); app.args.emplace<disable_border<border_pos::header>>(); app.args.emplace<disable_border<border_pos::del>>(); // other app.args.emplace<version>(); app.args.emplace<help>(); // file app.args.file_emplace<file>(); auto error = app.args.perform(args, app); if (error) throw std::runtime_error(*error); if (app.state != app_state::cont) return; app.input->open(); table tab = table::parse(app.input->istream(), app.parse); app.input->close(); app.output->open(); app.print.output(app.output->ostream()); app.print.print(tab); app.output->close(); }
22.410714
65
0.635857
[ "vector" ]
309429a7444789c95f239c4a979e05ec6676d045
31,679
hpp
C++
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_tunnel_vpdn_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
17
2016-12-02T05:45:49.000Z
2022-02-10T19:32:54.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_tunnel_vpdn_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
2
2017-03-27T15:22:38.000Z
2019-11-05T08:30:16.000Z
cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_tunnel_vpdn_oper.hpp
CiscoDevNet/ydk-cpp
ef7d75970f2ef1154100e0f7b0a2ee823609b481
[ "ECL-2.0", "Apache-2.0" ]
11
2016-12-02T05:45:52.000Z
2019-11-07T08:28:17.000Z
#ifndef _CISCO_IOS_XR_TUNNEL_VPDN_OPER_ #define _CISCO_IOS_XR_TUNNEL_VPDN_OPER_ #include <memory> #include <vector> #include <string> #include <ydk/types.hpp> #include <ydk/errors.hpp> namespace cisco_ios_xr { namespace Cisco_IOS_XR_tunnel_vpdn_oper { class Vpdn : public ydk::Entity { public: Vpdn(); ~Vpdn(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::shared_ptr<ydk::Entity> clone_ptr() const override; ydk::augment_capabilities_function get_augment_capabilities_function() const override; std::string get_bundle_yang_models_location() const override; std::string get_bundle_name() const override; std::map<std::pair<std::string, std::string>, std::string> get_namespace_identity_lookup() const override; class Sessions; //type: Vpdn::Sessions class TunnelDestinations; //type: Vpdn::TunnelDestinations class VpdnMirroring; //type: Vpdn::VpdnMirroring class VpdnRedundancy; //type: Vpdn::VpdnRedundancy class HistoryFailures; //type: Vpdn::HistoryFailures std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::Sessions> sessions; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::TunnelDestinations> tunnel_destinations; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::VpdnMirroring> vpdn_mirroring; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::VpdnRedundancy> vpdn_redundancy; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::HistoryFailures> history_failures; }; // Vpdn class Vpdn::Sessions : public ydk::Entity { public: Sessions(); ~Sessions(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class Session; //type: Vpdn::Sessions::Session ydk::YList session; }; // Vpdn::Sessions class Vpdn::Sessions::Session : public ydk::Entity { public: Session(); ~Session(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf session_label; //type: string ydk::YLeaf setup_time; //type: uint32 ydk::YLeaf parent_interface_name; //type: string class Session_; //type: Vpdn::Sessions::Session::Session_ class L2tp; //type: Vpdn::Sessions::Session::L2tp class Subscriber; //type: Vpdn::Sessions::Session::Subscriber class Configuration; //type: Vpdn::Sessions::Session::Configuration std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::Sessions::Session::Session_> session; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::Sessions::Session::L2tp> l2tp; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::Sessions::Session::Subscriber> subscriber; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::Sessions::Session::Configuration> configuration; }; // Vpdn::Sessions::Session class Vpdn::Sessions::Session::Session_ : public ydk::Entity { public: Session_(); ~Session_(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf last_change; //type: string ydk::YLeaf interface_name; //type: string ydk::YLeaf username; //type: string ydk::YLeaf domain_name; //type: string ydk::YLeaf state; //type: SessionState ydk::YLeaf l2tp_session_id; //type: uint16 ydk::YLeaf l2tp_tunnel_id; //type: uint16 ydk::YLeaf srg_slave; //type: boolean }; // Vpdn::Sessions::Session::Session_ class Vpdn::Sessions::Session::L2tp : public ydk::Entity { public: L2tp(); ~L2tp(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf local_endpoint; //type: string ydk::YLeaf remote_endpoint; //type: string ydk::YLeaf call_serial_number; //type: uint32 ydk::YLeaf is_l2tp_class_attribute_mask_set; //type: boolean ydk::YLeaf local_tunnel_id; //type: uint16 ydk::YLeaf remote_tunnel_id; //type: uint16 ydk::YLeaf local_session_id; //type: uint16 ydk::YLeaf remote_session_id; //type: uint16 ydk::YLeaf remote_port; //type: uint16 ydk::YLeaf tunnel_client_authentication_id; //type: string ydk::YLeaf tunnel_server_authentication_id; //type: string ydk::YLeaf tunnel_assignment_id; //type: string ydk::YLeaf is_tunnel_authentication_enabled; //type: boolean }; // Vpdn::Sessions::Session::L2tp class Vpdn::Sessions::Session::Subscriber : public ydk::Entity { public: Subscriber(); ~Subscriber(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf nas_port_id_val; //type: string ydk::YLeaf nas_port_type; //type: string ydk::YLeaf physical_channel_id; //type: uint32 ydk::YLeaf receive_connect_speed; //type: uint64 ydk::YLeaf transmit_connect_speed; //type: uint64 }; // Vpdn::Sessions::Session::Subscriber class Vpdn::Sessions::Session::Configuration : public ydk::Entity { public: Configuration(); ~Configuration(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf template_name; //type: string ydk::YLeaf vrf_name; //type: string ydk::YLeaf l2tp_busy_timeout; //type: uint16 ydk::YLeaf tos_mode; //type: TosMode ydk::YLeaf tos; //type: uint8 ydk::YLeaf dsl_line_forwarding; //type: boolean class VpnId; //type: Vpdn::Sessions::Session::Configuration::VpnId std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::Sessions::Session::Configuration::VpnId> vpn_id; }; // Vpdn::Sessions::Session::Configuration class Vpdn::Sessions::Session::Configuration::VpnId : public ydk::Entity { public: VpnId(); ~VpnId(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; ydk::YLeaf oui; //type: uint32 ydk::YLeaf index_; //type: uint32 }; // Vpdn::Sessions::Session::Configuration::VpnId class Vpdn::TunnelDestinations : public ydk::Entity { public: TunnelDestinations(); ~TunnelDestinations(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class TunnelDestination; //type: Vpdn::TunnelDestinations::TunnelDestination ydk::YList tunnel_destination; }; // Vpdn::TunnelDestinations class Vpdn::TunnelDestinations::TunnelDestination : public ydk::Entity { public: TunnelDestination(); ~TunnelDestination(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf vrf_name; //type: string ydk::YLeaf address; //type: string ydk::YLeaf vrf_name_xr; //type: string ydk::YLeaf load; //type: uint32 ydk::YLeaf status; //type: LsgStatus ydk::YLeaf connects; //type: uint32 ydk::YLeaf disconnects; //type: uint32 ydk::YLeaf retry; //type: uint32 ydk::YLeaf status_change_time; //type: uint32 }; // Vpdn::TunnelDestinations::TunnelDestination class Vpdn::VpdnMirroring : public ydk::Entity { public: VpdnMirroring(); ~VpdnMirroring(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf sync_not_conn_cnt; //type: uint32 ydk::YLeaf sso_err_cnt; //type: uint32 ydk::YLeaf sso_batch_err_cnt; //type: uint32 ydk::YLeaf alloc_err_cnt; //type: uint32 ydk::YLeaf alloc_cnt; //type: uint32 class QadSendStats; //type: Vpdn::VpdnMirroring::QadSendStats class QadRecvStats; //type: Vpdn::VpdnMirroring::QadRecvStats class QadSendStatsLastClear; //type: Vpdn::VpdnMirroring::QadSendStatsLastClear class QadRecvStatsLastClear; //type: Vpdn::VpdnMirroring::QadRecvStatsLastClear std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::VpdnMirroring::QadSendStats> qad_send_stats; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::VpdnMirroring::QadRecvStats> qad_recv_stats; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::VpdnMirroring::QadSendStatsLastClear> qad_send_stats_last_clear; std::shared_ptr<cisco_ios_xr::Cisco_IOS_XR_tunnel_vpdn_oper::Vpdn::VpdnMirroring::QadRecvStatsLastClear> qad_recv_stats_last_clear; }; // Vpdn::VpdnMirroring class Vpdn::VpdnMirroring::QadSendStats : public ydk::Entity { public: QadSendStats(); ~QadSendStats(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf msgs_sent; //type: uint32 ydk::YLeaf acks_sent; //type: uint32 ydk::YLeaf no_partner; //type: uint32 ydk::YLeaf sends_failed; //type: uint32 ydk::YLeaf acks_failed; //type: uint32 ydk::YLeaf pending_acks; //type: uint32 ydk::YLeaf timeouts; //type: uint32 ydk::YLeaf suspends; //type: uint32 ydk::YLeaf resumes; //type: uint32 ydk::YLeaf sends_fragment; //type: uint32 ydk::YLeaf qad_last_seq_number; //type: uint32 ydk::YLeaf qad_frag_count; //type: uint32 ydk::YLeaf qad_ack_count; //type: uint32 ydk::YLeaf qad_unknown_acks; //type: uint32 ydk::YLeaf qad_timeouts; //type: uint32 ydk::YLeaf qad_rx_count; //type: uint32 ydk::YLeaf qad_rx_list_count; //type: uint32 ydk::YLeaf qad_rx_list_q_size; //type: uint32 ydk::YLeaf qad_rx_first_seq_number; //type: uint32 }; // Vpdn::VpdnMirroring::QadSendStats class Vpdn::VpdnMirroring::QadRecvStats : public ydk::Entity { public: QadRecvStats(); ~QadRecvStats(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf msgs_recvd; //type: uint32 ydk::YLeaf acks_recvd; //type: uint32 ydk::YLeaf recvd_acks_failed; //type: uint32 ydk::YLeaf init_drops; //type: uint32 ydk::YLeaf msg_drops; //type: uint32 ydk::YLeaf ooo_drops; //type: uint32 ydk::YLeaf stale_msgs; //type: uint32 }; // Vpdn::VpdnMirroring::QadRecvStats class Vpdn::VpdnMirroring::QadSendStatsLastClear : public ydk::Entity { public: QadSendStatsLastClear(); ~QadSendStatsLastClear(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf msgs_sent; //type: uint32 ydk::YLeaf acks_sent; //type: uint32 ydk::YLeaf no_partner; //type: uint32 ydk::YLeaf sends_failed; //type: uint32 ydk::YLeaf acks_failed; //type: uint32 ydk::YLeaf pending_acks; //type: uint32 ydk::YLeaf timeouts; //type: uint32 ydk::YLeaf suspends; //type: uint32 ydk::YLeaf resumes; //type: uint32 ydk::YLeaf sends_fragment; //type: uint32 ydk::YLeaf qad_last_seq_number; //type: uint32 ydk::YLeaf qad_frag_count; //type: uint32 ydk::YLeaf qad_ack_count; //type: uint32 ydk::YLeaf qad_unknown_acks; //type: uint32 ydk::YLeaf qad_timeouts; //type: uint32 ydk::YLeaf qad_rx_count; //type: uint32 ydk::YLeaf qad_rx_list_count; //type: uint32 ydk::YLeaf qad_rx_list_q_size; //type: uint32 ydk::YLeaf qad_rx_first_seq_number; //type: uint32 }; // Vpdn::VpdnMirroring::QadSendStatsLastClear class Vpdn::VpdnMirroring::QadRecvStatsLastClear : public ydk::Entity { public: QadRecvStatsLastClear(); ~QadRecvStatsLastClear(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf msgs_recvd; //type: uint32 ydk::YLeaf acks_recvd; //type: uint32 ydk::YLeaf recvd_acks_failed; //type: uint32 ydk::YLeaf init_drops; //type: uint32 ydk::YLeaf msg_drops; //type: uint32 ydk::YLeaf ooo_drops; //type: uint32 ydk::YLeaf stale_msgs; //type: uint32 }; // Vpdn::VpdnMirroring::QadRecvStatsLastClear class Vpdn::VpdnRedundancy : public ydk::Entity { public: VpdnRedundancy(); ~VpdnRedundancy(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf session_total; //type: uint32 ydk::YLeaf session_synced; //type: uint32 ydk::YLeaf state; //type: VpdnState ydk::YLeaf start_time; //type: uint64 ydk::YLeaf finish_time; //type: uint64 ydk::YLeaf abort_time; //type: uint64 }; // Vpdn::VpdnRedundancy class Vpdn::HistoryFailures : public ydk::Entity { public: HistoryFailures(); ~HistoryFailures(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; class HistoryFailure; //type: Vpdn::HistoryFailures::HistoryFailure ydk::YList history_failure; }; // Vpdn::HistoryFailures class Vpdn::HistoryFailures::HistoryFailure : public ydk::Entity { public: HistoryFailure(); ~HistoryFailure(); bool has_data() const override; bool has_operation() const override; std::vector<std::pair<std::string, ydk::LeafData> > get_name_leaf_data() const override; std::string get_segment_path() const override; std::shared_ptr<ydk::Entity> get_child_by_name(const std::string & yang_name, const std::string & segment_path) override; void set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix) override; void set_filter(const std::string & value_path, ydk::YFilter yfliter) override; std::map<std::string, std::shared_ptr<ydk::Entity>> get_children() const override; bool has_leaf_or_child_of_name(const std::string & name) const override; std::string get_absolute_path() const override; ydk::YLeaf username; //type: string ydk::YLeaf remote_name; //type: string ydk::YLeaf username_xr; //type: string ydk::YLeaf domain_name; //type: string ydk::YLeaf mid; //type: uint16 ydk::YLeaf nas; //type: string ydk::YLeaf destination_address; //type: string ydk::YLeaf remote_client_id; //type: uint16 ydk::YLeaf home_gateway; //type: string ydk::YLeaf source_address; //type: string ydk::YLeaf local_client_id; //type: uint16 ydk::YLeaf event_time; //type: string ydk::YLeaf error_repeat_count; //type: uint16 ydk::YLeaf failure_type; //type: VpdnFailcode }; // Vpdn::HistoryFailures::HistoryFailure class SessionState : public ydk::Enum { public: static const ydk::Enum::YLeaf idle; static const ydk::Enum::YLeaf connected; static const ydk::Enum::YLeaf established; static int get_enum_value(const std::string & name) { if (name == "idle") return 0; if (name == "connected") return 1; if (name == "established") return 2; return -1; } }; class VpdnState : public ydk::Enum { public: static const ydk::Enum::YLeaf initial_state; static const ydk::Enum::YLeaf init_sync_in_progress; static const ydk::Enum::YLeaf steady_state; static int get_enum_value(const std::string & name) { if (name == "initial-state") return 0; if (name == "init-sync-in-progress") return 1; if (name == "steady-state") return 2; return -1; } }; class VpdnFailcode : public ydk::Enum { public: static const ydk::Enum::YLeaf unknown; static const ydk::Enum::YLeaf peer_action; static const ydk::Enum::YLeaf authentication; static const ydk::Enum::YLeaf authentication_error; static const ydk::Enum::YLeaf authentication_failed; static const ydk::Enum::YLeaf authorization; static const ydk::Enum::YLeaf authorization_failed; static const ydk::Enum::YLeaf home_gatewayfailure; static const ydk::Enum::YLeaf connection_termination; static const ydk::Enum::YLeaf no_resources_available; static const ydk::Enum::YLeaf timer_expiry; static const ydk::Enum::YLeaf session_mid_exceeded; static const ydk::Enum::YLeaf soft_shut; static const ydk::Enum::YLeaf session_limit_exceeded; static const ydk::Enum::YLeaf administrative; static const ydk::Enum::YLeaf link_failure; static const ydk::Enum::YLeaf security; static const ydk::Enum::YLeaf tunnel_in_resync; static const ydk::Enum::YLeaf call_prarmeters; static int get_enum_value(const std::string & name) { if (name == "unknown") return 0; if (name == "peer-action") return 1; if (name == "authentication") return 2; if (name == "authentication-error") return 3; if (name == "authentication-failed") return 4; if (name == "authorization") return 5; if (name == "authorization-failed") return 6; if (name == "home-gatewayfailure") return 7; if (name == "connection-termination") return 8; if (name == "no-resources-available") return 9; if (name == "timer-expiry") return 10; if (name == "session-mid-exceeded") return 11; if (name == "soft-shut") return 12; if (name == "session-limit-exceeded") return 13; if (name == "administrative") return 14; if (name == "link-failure") return 15; if (name == "security") return 16; if (name == "tunnel-in-resync") return 17; if (name == "call-prarmeters") return 18; return -1; } }; class LsgStatus : public ydk::Enum { public: static const ydk::Enum::YLeaf none; static const ydk::Enum::YLeaf active; static const ydk::Enum::YLeaf down; static const ydk::Enum::YLeaf testable; static const ydk::Enum::YLeaf testing; static int get_enum_value(const std::string & name) { if (name == "none") return 0; if (name == "active") return 1; if (name == "down") return 2; if (name == "testable") return 3; if (name == "testing") return 4; return -1; } }; class TosMode : public ydk::Enum { public: static const ydk::Enum::YLeaf default_; static const ydk::Enum::YLeaf set; static const ydk::Enum::YLeaf reflect; static int get_enum_value(const std::string & name) { if (name == "default") return 0; if (name == "set") return 1; if (name == "reflect") return 2; return -1; } }; } } #endif /* _CISCO_IOS_XR_TUNNEL_VPDN_OPER_ */
47.28209
162
0.673759
[ "vector" ]
309d1f027f7638deb09c74d2f68417a397a1c4f1
512
cpp
C++
devertexwahn/flatland/math/refract.cpp
Vertexwahn/FlatlandRT
37d09fde38b25eff5f802200b43628efbd1e3198
[ "Apache-2.0" ]
62
2021-09-21T18:58:02.000Z
2022-03-07T02:17:43.000Z
devertexwahn/flatland/math/refract.cpp
Vertexwahn/FlatlandRT
37d09fde38b25eff5f802200b43628efbd1e3198
[ "Apache-2.0" ]
null
null
null
devertexwahn/flatland/math/refract.cpp
Vertexwahn/FlatlandRT
37d09fde38b25eff5f802200b43628efbd1e3198
[ "Apache-2.0" ]
null
null
null
#include "flatland/math/refract.h" FLATLAND_BEGIN_NAMESPACE // Copied from pbrt, Version 3 with minor modifications (see README.md for license information) // Source: https://github.com/mmp/pbrt-v3/blob/0aa90372efce97df39cffcaa33b276d7d0772d30/src/core/geometry.h#L1213 // http://www.pbr-book.org/3ed-2018/Reflection_Models/Specular_Reflection_and_Transmission.html Normal2f faceforward(const Normal2f &n, const Vector2f &v) { return (n.dot(v) < 0.f) ? Normal2f(-n.x(),n.y()) : n; } FLATLAND_END_NAMESPACE
42.666667
113
0.775391
[ "geometry" ]
30a825036580d1ce5f8e5b5c2e35c53ff9d90b73
16,900
cpp
C++
utility/tests/DAG_unittest.cpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
31
2016-01-20T05:43:46.000Z
2022-02-07T09:14:06.000Z
utility/tests/DAG_unittest.cpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
221
2016-01-20T18:25:10.000Z
2016-06-26T02:58:12.000Z
utility/tests/DAG_unittest.cpp
spring-operator/quickstep
3e98776002eb5db7154031fd6ef1a7f000a89d81
[ "Apache-2.0" ]
17
2016-01-20T04:00:21.000Z
2019-03-12T02:41:25.000Z
/** * Copyright 2011-2015 Quickstep Technologies LLC. * Copyright 2015 Pivotal Software, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #include <algorithm> #include <cstddef> #include <utility> #include <vector> #include "utility/DAG.hpp" #include "gtest/gtest.h" using std::find; using std::pair; using std::vector; namespace quickstep { class DummyPayload { public: explicit DummyPayload(const int payload_value) : payload_value_(payload_value) { } inline int getPayloadValue() const { return payload_value_; } private: int payload_value_; }; TEST(DAGTest, AddNodeTest) { const int kPayloadCount = 300; DAG<DummyPayload, int> dag_; // Create a DAG with 300 nodes and test if the index assignment is correct. for (int index = 0; index < kPayloadCount; ++index) { EXPECT_EQ(static_cast<std::size_t>(index), dag_.createNode(new DummyPayload(index))); } } TEST(DAGTest, PayloadTest) { const int kPayloadCount = 300; DAG<DummyPayload, int> dag_; // Create a DAG with 300 nodes and test if the payload is returned correctly. for (int index = 0; index < kPayloadCount; ++index) { EXPECT_EQ(static_cast<std::size_t>(index), dag_.createNode(new DummyPayload(index + 5))); } // If all indices are correct, check the payload. for (int index = 0; index < kPayloadCount; ++index) { EXPECT_EQ(index + 5, dag_.getNodePayload(index).getPayloadValue()); EXPECT_EQ(index + 5, dag_.getNodePayloadMutable(index)->getPayloadValue()); } } TEST(DAGTest, SelfCycleTest) { DAG<DummyPayload, int> dag_; // No cycle in empty DAG. EXPECT_FALSE(dag_.hasCycle()); ASSERT_EQ(0u, dag_.createNode(new DummyPayload(34))); // No cycle with single node. EXPECT_FALSE(dag_.hasCycle()); ASSERT_EQ(1u, dag_.createNode(new DummyPayload(44))); dag_.createLink(0, 1, 1); // This should test createLink function too. EXPECT_FALSE(dag_.hasCycle()); dag_.createLink(0, 0, 1); EXPECT_TRUE(dag_.hasCycle()); } TEST(DAGTest, TwoNodesCycleTest) { DAG<DummyPayload, int> dag_; // Two nodes with cycle. ASSERT_EQ(0u, dag_.createNode(new DummyPayload(2))); ASSERT_EQ(1u, dag_.createNode(new DummyPayload(3))); dag_.createLink(0, 1, 2); EXPECT_FALSE(dag_.hasCycle()); dag_.createLink(1, 0, 3); EXPECT_TRUE(dag_.hasCycle()); } TEST(DAGTest, CycleExistenceTest) { const int kNodeSize = 5; DAG<DummyPayload, int> dag_; for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } /* * 0 1 * \ / * 2 * / \ * 3->4 * */ dag_.createLink(0, 2, 3); dag_.createLink(1, 2, 4); dag_.createLink(2, 3, 3); dag_.createLink(2, 4, 4); dag_.createLink(3, 4, 5); EXPECT_FALSE(dag_.hasCycle()); dag_.createLink(4, 3, 1); EXPECT_TRUE(dag_.hasCycle()); } TEST(DAGTest, FiveNodesCycleTest) { const int kNodeSize = 5; DAG<DummyPayload, int> dag_; for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } /* * 1->2->3 * ^ | * | v * 0 <-- 4 * */ dag_.createLink(0, 1, 0); dag_.createLink(1, 2, 0); dag_.createLink(2, 3, 0); dag_.createLink(3, 4, 0); dag_.createLink(4, 0, 1); EXPECT_TRUE(dag_.hasCycle()); dag_.createLink(3, 0, 3); EXPECT_TRUE(dag_.hasCycle()); } TEST(DAGTest, DisconnectedComponentsNoCycleTest) { const int kNodeSize = 5; DAG<DummyPayload, int> dag_; // A graph with 5 nodes. Nodes 1, 2, 3 and 4 are put in one component. Node 0 // is in another component. Both the components are acyclic. for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } // All 5 nodes are disconnected. EXPECT_FALSE(dag_.hasCycle()); dag_.createLink(1, 2, 3); dag_.createLink(2, 3, 2); dag_.createLink(3, 4, 1); // Node 0 is in a separate component. EXPECT_FALSE(dag_.hasCycle()); } TEST(DAGTest, DisconnectedComponentsWithCycleTest) { const int kNodeSize = 6; DAG<DummyPayload, int> dag_; // A graph with 6 nodes. Nodes 1, 2 and 3 are put in one component. Nodes 0, // 4 and 5 are in another component. Both the components have cycle within // themselves. for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } dag_.createLink(1, 2, 4); dag_.createLink(2, 3, 5); dag_.createLink(3, 2, 2); // Component with nodes 1, 2 and 3 is cyclic. EXPECT_TRUE(dag_.hasCycle()); dag_.createLink(0, 4, 3); EXPECT_TRUE(dag_.hasCycle()); dag_.createLink(4, 5, 2); // Make the second component with nodes 0, 4 and 5 cyclic. dag_.createLink(5, 0, 4); EXPECT_TRUE(dag_.hasCycle()); } TEST(DAGTest, SixNodeStagesTest) { const int kNodeSize = 6; DAG<DummyPayload, int> dag_; for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } /* * 0 1 2 * \ / / * 3 / * \/ * 4 * | * 5 */ dag_.createLink(0, 3, 0); dag_.createLink(1, 3, 1); dag_.createLink(2, 4, 2); dag_.createLink(3, 4, 2); dag_.createLink(4, 5, 1); vector<pair<vector<DAG<DummyPayload, int>::size_type_nodes>, vector<DAG<DummyPayload, int>::size_type_nodes> > > stages = dag_.computeStageSequence(); ASSERT_EQ(4u, stages.size()); // stages[0] EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 0), stages[0].first.end()); EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 1), stages[0].first.end()); EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 2), stages[0].first.end()); // Check if there's no other element in stages[0].first than the ones we've // tested. EXPECT_EQ(3u, stages[0].first.size()); EXPECT_NE(find(stages[0].second.begin(), stages[0].second.end(), 0), stages[0].second.end()); EXPECT_NE(find(stages[0].second.begin(), stages[0].second.end(), 1), stages[0].second.end()); EXPECT_EQ(2u, stages[0].second.size()); // stages[1] EXPECT_NE(find(stages[1].first.begin(), stages[1].first.end(), 3), stages[1].first.end()); EXPECT_EQ(1u, stages[1].first.size()); EXPECT_NE(find(stages[1].second.begin(), stages[1].second.end(), 2), stages[1].second.end()); EXPECT_NE(find(stages[1].second.begin(), stages[1].second.end(), 3), stages[1].second.end()); EXPECT_EQ(2u, stages[1].second.size()); // stages[2] EXPECT_NE(find(stages[2].first.begin(), stages[2].first.end(), 4), stages[2].first.end()); EXPECT_EQ(1u, stages[2].first.size()); EXPECT_NE(find(stages[2].second.begin(), stages[2].second.end(), 4), stages[2].second.end()); EXPECT_EQ(1u, stages[2].second.size()); // stages[3] EXPECT_NE(find(stages[3].first.begin(), stages[3].first.end(), 5), stages[3].first.end()); EXPECT_EQ(1u, stages[3].first.size()); EXPECT_NE(find(stages[3].second.begin(), stages[3].second.end(), 5), stages[3].second.end()); EXPECT_EQ(1u, stages[3].second.size()); } TEST(DAGTest, DiamondNoCycleStagesTest) { const int kNodeSize = 5; DAG<DummyPayload, int> dag_; for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } /* * 0 * / \ * v v * 1 2 * \ / * v * 3 * | * v * 4 * */ dag_.createLink(0, 1, 2); dag_.createLink(0, 2, 1); dag_.createLink(1, 3, 1); dag_.createLink(2, 3, 1); dag_.createLink(3, 4, 1); ASSERT_FALSE(dag_.hasCycle()); vector<pair<vector<DAG<DummyPayload, int>::size_type_nodes>, vector<DAG<DummyPayload, int>::size_type_nodes> > > stages = dag_.computeStageSequence(); ASSERT_EQ(4u, stages.size()); // stages[0] EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 0), stages[0].first.end()); EXPECT_EQ(1u, stages[0].first.size()); EXPECT_NE(find(stages[0].second.begin(), stages[0].second.end(), 0), stages[0].second.end()); EXPECT_EQ(1u, stages[0].second.size()); // stages[1] EXPECT_NE(find(stages[1].first.begin(), stages[1].first.end(), 1), stages[1].first.end()); EXPECT_NE(find(stages[1].first.begin(), stages[1].first.end(), 2), stages[1].first.end()); EXPECT_EQ(2u, stages[1].first.size()); EXPECT_NE(find(stages[1].second.begin(), stages[1].second.end(), 1), stages[1].second.end()); EXPECT_NE(find(stages[1].second.begin(), stages[1].second.end(), 2), stages[1].second.end()); EXPECT_EQ(2u, stages[1].second.size()); // stages[2] EXPECT_NE(find(stages[2].first.begin(), stages[2].first.end(), 3), stages[2].first.end()); EXPECT_EQ(1u, stages[2].first.size()); EXPECT_NE(find(stages[2].second.begin(), stages[2].second.end(), 3), stages[2].second.end()); EXPECT_EQ(1u, stages[2].second.size()); // stages[3] EXPECT_NE(find(stages[3].first.begin(), stages[3].first.end(), 4), stages[3].first.end()); EXPECT_EQ(1u, stages[3].first.size()); EXPECT_NE(find(stages[3].second.begin(), stages[3].second.end(), 4), stages[3].second.end()); EXPECT_EQ(1u, stages[3].second.size()); } TEST(DAGTest, DiamondCycleExistenceTest) { const int kNodeSize = 5; DAG<DummyPayload, int> dag_; // A cycle is present within the diamond shape for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } /* * 0 * / ^ * v \ * 1 2 * \ / * v / * 3 * | * v * 4 * */ dag_.createLink(0, 1, 1); dag_.createLink(1, 3, 2); dag_.createLink(3, 2, 1); dag_.createLink(3, 4, 2); dag_.createLink(2, 0, 1); ASSERT_TRUE(dag_.hasCycle()); } TEST(DAGTest, DisconnectedComponentsNoCycleStagesTest) { const int kNodeSize = 5; DAG<DummyPayload, int> dag_; // A graph with 5 nodes. Nodes 1, 2, 3 and 4 are put in one component. Node 0 // is in another component. Both the components are acyclic. As node 0 has no // dependencies, it can be processed in any stage, starting from 0 till 4. for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } dag_.createLink(1, 2, 0); dag_.createLink(2, 3, 1); dag_.createLink(3, 4, 2); EXPECT_FALSE(dag_.hasCycle()); vector<pair<vector<DAG<DummyPayload, int>::size_type_nodes>, vector<DAG<DummyPayload, int>::size_type_nodes> > > stages = dag_.computeStageSequence(); ASSERT_EQ(4u, stages.size()); // stages[0] Node 0 can begin execution here. EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 0), stages[0].first.end()); EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 1), stages[0].first.end()); EXPECT_EQ(2u, stages[0].first.size()); EXPECT_NE(find(stages[0].second.begin(), stages[0].second.end(), 1), stages[0].second.end()); EXPECT_EQ(1u, stages[0].second.size()); // stages[1] EXPECT_NE(find(stages[1].first.begin(), stages[1].first.end(), 2), stages[1].first.end()); EXPECT_EQ(1u, stages[1].first.size()); EXPECT_NE(find(stages[1].second.begin(), stages[1].second.end(), 2), stages[1].second.end()); EXPECT_EQ(1u, stages[1].second.size()); // stages[2] EXPECT_NE(find(stages[2].first.begin(), stages[2].first.end(), 3), stages[2].first.end()); EXPECT_EQ(1u, stages[2].first.size()); EXPECT_NE(find(stages[2].second.begin(), stages[2].second.end(), 3), stages[2].second.end()); EXPECT_EQ(1u, stages[2].second.size()); // stages[3] Node 0 must finish execution here. EXPECT_NE(find(stages[3].first.begin(), stages[3].first.end(), 4), stages[3].first.end()); EXPECT_EQ(1u, stages[3].first.size()); EXPECT_NE(find(stages[3].second.begin(), stages[3].second.end(), 0), stages[3].second.end()); EXPECT_NE(find(stages[3].second.begin(), stages[3].second.end(), 4), stages[3].second.end()); EXPECT_EQ(2u, stages[3].second.size()); } TEST(DAGTest, LinkMetadataIntTest) { DAG<DummyPayload, int> dag_; const int kNodeSize = 2; for (int index = 0; index < kNodeSize; ++index) { EXPECT_EQ(static_cast<std::size_t>(index), dag_.createNode(new DummyPayload(index))); } dag_.createLink(0, 1, 0); EXPECT_EQ(0, dag_.getLinkMetadata(0, 1)); dag_.createLink(1, 0, 1); EXPECT_EQ(1, dag_.getLinkMetadata(1, 0)); // Change the weight of the link 0->1 dag_.setLinkMetadata(0, 1, 2); EXPECT_EQ(2, dag_.getLinkMetadata(0, 1)); } TEST(DAGTest, LinkMetadataBoolTest) { DAG<DummyPayload, bool> dag_; const int kNodeSize = 2; for (int index = 0; index < kNodeSize; ++index) { EXPECT_EQ(static_cast<std::size_t>(index), dag_.createNode(new DummyPayload(index))); } dag_.createLink(0, 1, false); EXPECT_FALSE(dag_.getLinkMetadata(0, 1)); dag_.createLink(1, 0, false); EXPECT_FALSE(dag_.getLinkMetadata(1, 0)); // Change the weight of the link 0->1 dag_.setLinkMetadata(0, 1, true); EXPECT_TRUE(dag_.getLinkMetadata(0, 1)); // Make sure link weight 1->0 is not affected. EXPECT_FALSE(dag_.getLinkMetadata(1, 0)); // Change the weight of the link 0->1 again dag_.setLinkMetadata(0, 1, false); EXPECT_FALSE(dag_.getLinkMetadata(0, 1)); // Make sure link weight 1->0 is not affected. EXPECT_FALSE(dag_.getLinkMetadata(1, 0)); } #ifdef QUICKSTEP_DEBUG TEST(DAGDeathTest, SixNodeStagesCycleTest) { const int kNodeSize = 6; DAG<DummyPayload, int> dag_; for (int node_index = 0; node_index < kNodeSize; ++node_index) { ASSERT_EQ(static_cast<std::size_t>(node_index), dag_.createNode(new DummyPayload(node_index))); } /* * 0 1 2 * \ / / * 3 / * \/ * 4 * | * 5 */ dag_.createLink(0, 3, 0); dag_.createLink(1, 3, 1); dag_.createLink(2, 4, 0); dag_.createLink(3, 4, 1); dag_.createLink(4, 5, 0); vector<pair<vector<DAG<DummyPayload, int>::size_type_nodes>, vector<DAG<DummyPayload, int>::size_type_nodes> > > stages = dag_.computeStageSequence(); ASSERT_EQ(4u, stages.size()); // stages[0] EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 0), stages[0].first.end()); EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 1), stages[0].first.end()); EXPECT_NE(find(stages[0].first.begin(), stages[0].first.end(), 2), stages[0].first.end()); // Check if there's no other element in stages[0].first than the ones we've // tested. EXPECT_EQ(3u, stages[0].first.size()); EXPECT_NE(find(stages[0].second.begin(), stages[0].second.end(), 0), stages[0].second.end()); EXPECT_NE(find(stages[0].second.begin(), stages[0].second.end(), 1), stages[0].second.end()); EXPECT_EQ(2u, stages[0].second.size()); // stages[1] EXPECT_NE(find(stages[1].first.begin(), stages[1].first.end(), 3), stages[1].first.end()); EXPECT_EQ(1u, stages[1].first.size()); EXPECT_NE(find(stages[1].second.begin(), stages[1].second.end(), 2), stages[1].second.end()); EXPECT_NE(find(stages[1].second.begin(), stages[1].second.end(), 3), stages[1].second.end()); EXPECT_EQ(2u, stages[1].second.size()); // stages[2] EXPECT_NE(find(stages[2].first.begin(), stages[2].first.end(), 4), stages[2].first.end()); EXPECT_EQ(1u, stages[2].first.size()); EXPECT_NE(find(stages[2].second.begin(), stages[2].second.end(), 4), stages[2].second.end()); EXPECT_EQ(1u, stages[2].second.size()); // stages[3] EXPECT_NE(find(stages[3].first.begin(), stages[3].first.end(), 5), stages[3].first.end()); EXPECT_EQ(1u, stages[3].first.size()); EXPECT_NE(find(stages[3].second.begin(), stages[3].second.end(), 5), stages[3].second.end()); EXPECT_EQ(1u, stages[3].second.size()); dag_.createLink(5, 4, 3); // computeStageSequence goes in an infinite loop when graph has cycle // DCHECK(!hasCycle()) should abort the execution EXPECT_DEATH(dag_.computeStageSequence(), ""); } #endif } // namespace quickstep
29.964539
95
0.653018
[ "shape", "vector" ]
dd767198f6bd569d669f82545b533a31ffc4572d
400
cpp
C++
209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
209-minimum-size-subarray-sum/209-minimum-size-subarray-sum.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
class Solution { public: int minSubArrayLen(int target, vector<int>& nums) { int i = 0; int sum = 0; int ans = INT_MAX; for(int j = 0;j<nums.size();++j){ sum += nums[j]; while(sum >= target){ ans = min(ans,j+1 - i); sum -= nums[i++]; } } return (ans != INT_MAX) ? ans : 0; } };
23.529412
55
0.4075
[ "vector" ]
dd793bfeb61856ef1b38638c0a87d112e2f8ac7d
13,391
cpp
C++
src/fmtc/Primaries.cpp
inflation/fmtconv
bf03a8a1a4103c0bdf4b4c23da5b79933876ca4a
[ "WTFPL" ]
null
null
null
src/fmtc/Primaries.cpp
inflation/fmtconv
bf03a8a1a4103c0bdf4b4c23da5b79933876ca4a
[ "WTFPL" ]
null
null
null
src/fmtc/Primaries.cpp
inflation/fmtconv
bf03a8a1a4103c0bdf4b4c23da5b79933876ca4a
[ "WTFPL" ]
null
null
null
/***************************************************************************** Primaries.cpp Author: Laurent de Soras, 2016 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fmtc/fnc.h" #include "fmtc/Primaries.h" #include "fmtcl/Mat3.h" #include "fstb/def.h" #include "fstb/fnc.h" #include "vsutl/CpuOpt.h" #include "vsutl/FrameRefSPtr.h" #include <cassert> #include <cstdio> namespace fmtc { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ Primaries::Primaries (const ::VSMap &in, ::VSMap &out, void *user_data_ptr, ::VSCore &core, const ::VSAPI &vsapi) : vsutl::FilterBase (vsapi, "primaries", ::fmParallel, 0) , _clip_src_sptr (vsapi.propGetNode (&in, "clip", 0, 0), vsapi) , _vi_in (*_vsapi.getVideoInfo (_clip_src_sptr.get ())) , _vi_out (_vi_in) , _sse_flag (false) , _sse2_flag (false) , _avx_flag (false) , _avx2_flag (false) , _prim_s () , _prim_d () , _mat_main () , _proc_uptr () { fstb::unused (user_data_ptr, core); vsutl::CpuOpt cpu_opt (*this, in, out); _sse_flag = cpu_opt.has_sse (); _sse2_flag = cpu_opt.has_sse2 (); _avx_flag = cpu_opt.has_avx (); _avx2_flag = cpu_opt.has_avx2 (); _proc_uptr = std::unique_ptr <fmtcl::MatrixProc> (new fmtcl::MatrixProc ( _sse_flag, _sse2_flag, _avx_flag, _avx2_flag )); // Checks the input clip if (_vi_in.format == 0) { throw_inval_arg ("only constant pixel formats are supported."); } // Source colorspace const ::VSFormat & fmt_src = *_vi_in.format; check_colorspace (fmt_src, "input"); // Destination colorspace (currently the same as the source) const ::VSFormat & fmt_dst = fmt_src; check_colorspace (fmt_dst, "output"); // Output format is validated. _vi_out.format = &fmt_dst; // Primaries _prim_s.init (*this, in, out, "prims"); _prim_s.init (*this, in, out, "rs", "gs", "bs", "ws"); if (! _prim_s.is_ready ()) { throw_inval_arg ("input primaries not set."); } _prim_d = _prim_s; _prim_d.init (*this, in, out, "primd"); _prim_d.init (*this, in, out, "rd", "gd", "bd", "wd"); assert (_prim_d.is_ready ()); const fmtcl::Mat3 mat_conv = compute_conversion_matrix (); _mat_main.insert3 (mat_conv); _mat_main.clean3 (1); prepare_matrix_coef ( *this, *_proc_uptr, _mat_main, fmt_dst, true, fmt_src, true ); if (_vsapi.getError (&out) != 0) { throw -1; } } void Primaries::init_filter (::VSMap &in, ::VSMap &out, ::VSNode &node, ::VSCore &core) { fstb::unused (in, out, core); _vsapi.setVideoInfo (&_vi_out, 1, &node); } const ::VSFrameRef * Primaries::get_frame (int n, int activation_reason, void * &frame_data_ptr, ::VSFrameContext &frame_ctx, ::VSCore &core) { fstb::unused (frame_data_ptr); assert (n >= 0); ::VSFrameRef * dst_ptr = 0; ::VSNodeRef & node = *_clip_src_sptr; if (activation_reason == ::arInitial) { _vsapi.requestFrameFilter (n, &node, &frame_ctx); } else if (activation_reason == ::arAllFramesReady) { vsutl::FrameRefSPtr src_sptr ( _vsapi.getFrameFilter (n, &node, &frame_ctx), _vsapi ); const ::VSFrameRef & src = *src_sptr; const int w = _vsapi.getFrameWidth (&src, 0); const int h = _vsapi.getFrameHeight (&src, 0); dst_ptr = _vsapi.newVideoFrame (_vi_out.format, w, h, &src, &core); uint8_t * const dst_ptr_arr [fmtcl::MatrixProc::NBR_PLANES] = { _vsapi.getWritePtr (dst_ptr, 0), _vsapi.getWritePtr (dst_ptr, 1), _vsapi.getWritePtr (dst_ptr, 2) }; const int dst_str_arr [fmtcl::MatrixProc::NBR_PLANES] = { _vsapi.getStride (dst_ptr, 0), _vsapi.getStride (dst_ptr, 1), _vsapi.getStride (dst_ptr, 2) }; const uint8_t * const src_ptr_arr [fmtcl::MatrixProc::NBR_PLANES] = { _vsapi.getReadPtr (&src, 0), _vsapi.getReadPtr (&src, 1), _vsapi.getReadPtr (&src, 2) }; const int src_str_arr [fmtcl::MatrixProc::NBR_PLANES] = { _vsapi.getStride (&src, 0), _vsapi.getStride (&src, 1), _vsapi.getStride (&src, 2) }; _proc_uptr->process ( dst_ptr_arr, dst_str_arr, src_ptr_arr, src_str_arr, w, h ); // Output properties ::VSMap & dst_prop = *(_vsapi.getFramePropsRW (dst_ptr)); const fmtcl::PrimariesPreset preset_d = _prim_d._preset; if (preset_d >= 0 && preset_d < fmtcl::PrimariesPreset_NBR_ELT) { _vsapi.propSetInt (&dst_prop, "_Primaries", int (preset_d), ::paReplace); } else { _vsapi.propDeleteKey (&dst_prop, "_Primaries"); } } return (dst_ptr); } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void Primaries::RgbSystem::init (const vsutl::FilterBase &filter, const ::VSMap &in, ::VSMap &out, const char *preset_0) { assert (preset_0 != 0); std::string preset_str = filter.get_arg_str (in, out, preset_0, ""); fstb::conv_to_lower_case (preset_str); _preset = conv_string_to_primaries (preset_str); if (_preset >= 0) { set (_preset); } } void Primaries::RgbSystem::init (const vsutl::FilterBase &filter, const ::VSMap &in, ::VSMap &out, const char r_0 [], const char g_0 [], const char b_0 [], const char w_0 []) { assert (r_0 != 0); assert (g_0 != 0); assert (b_0 != 0); assert (w_0 != 0); const bool ready_old_flag = is_ready (); std::array <Vec2, NBR_PLANES> rgb_old = _rgb; Vec2 w_old = _white; const char * name_0_arr [NBR_PLANES] = { r_0, g_0, b_0 }; for (int k = 0; k < NBR_PLANES; ++k) { _init_flag_arr [k] |= read_coord_tuple (_rgb [k], filter, in, out, name_0_arr [k]); } _init_flag_arr [NBR_PLANES] |= read_coord_tuple (_white, filter, in, out, w_0); if (ready_old_flag && is_ready () && (rgb_old != _rgb || w_old != _white)) { _preset = fmtcl::PrimariesPreset_UNDEF; } } bool Primaries::RgbSystem::read_coord_tuple (Vec2 &c, const vsutl::FilterBase &filter, const ::VSMap &in, ::VSMap &out, const char *name_0) { bool set_flag = false; typedef std::vector <double> Vect; Vect v_def; Vect c_v = filter.get_arg_vflt (in, out, name_0, v_def); if (c_v.size () != 0) { if (c_v.size () != c.size ()) { fstb::snprintf4all ( filter._filter_error_msg_0, filter._max_error_buf_len, "%s: wrong number of coordinates (expected %d).", name_0, int (c.size ()) ); filter.throw_inval_arg (filter._filter_error_msg_0); } double sum = 0; for (size_t k = 0; k < c_v.size (); ++k) { sum += c_v [k]; c [k] = c_v [k]; } if (c [1] == 0) { fstb::snprintf4all ( filter._filter_error_msg_0, filter._max_error_buf_len, "%s: y coordinate cannot be 0.", name_0 ); filter.throw_inval_arg (filter._filter_error_msg_0); } set_flag = true; } return (set_flag); } void Primaries::check_colorspace (const ::VSFormat &fmt, const char *inout_0) const { assert (inout_0 != 0); if (fmt.subSamplingW != 0 || fmt.subSamplingH != 0) { fstb::snprintf4all ( _filter_error_msg_0, _max_error_buf_len, "%s must be 4:4:4.", inout_0 ); throw_inval_arg (_filter_error_msg_0); } if (fmt.colorFamily != ::cmRGB) { fstb::snprintf4all ( _filter_error_msg_0, _max_error_buf_len, "%s colorspace must be RGB (assumed linear).", inout_0 ); throw_inval_arg (_filter_error_msg_0); } if ( (fmt.sampleType == ::stInteger && fmt.bitsPerSample != 16) || (fmt.sampleType == ::stFloat && fmt.bitsPerSample != 32)) { fstb::snprintf4all ( _filter_error_msg_0, _max_error_buf_len, "pixel bitdepth not supported, " "%s must be 16-bit integer or 32-bit float.", inout_0 ); throw_inval_arg (_filter_error_msg_0); } assert (fmt.numPlanes == NBR_PLANES); } fmtcl::Mat3 Primaries::compute_conversion_matrix () const { fmtcl::Mat3 rgb2xyz = compute_rgb2xyz (_prim_s); fmtcl::Mat3 xyz2rgb = compute_rgb2xyz (_prim_d).invert (); fmtcl::Mat3 adapt = compute_chroma_adapt (_prim_s, _prim_d); return xyz2rgb * adapt * rgb2xyz; } // http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html fmtcl::Mat3 Primaries::compute_rgb2xyz (const RgbSystem &prim) { fmtcl::Mat3 m; if (prim._preset == fmtcl::PrimariesPreset_CIEXYZ) { m = fmtcl::Mat3 (1, fmtcl::Mat3::Preset_DIAGONAL); } else { const fmtcl::Vec3 white = conv_xy_to_xyz (prim._white); fmtcl::Mat3 xyzrgb; for (int k = 0; k < NBR_PLANES; ++k) { fmtcl::Vec3 comp_xyz = conv_xy_to_xyz (prim._rgb [k]); xyzrgb.set_col (k, comp_xyz); } fmtcl::Vec3 s = xyzrgb.compute_inverse () * white; for (int u = 0; u < NBR_PLANES; ++u) { m.set_col (u, xyzrgb.get_col (u) * s [u]); } } return m; } // http://www.brucelindbloom.com/index.html?Eqn_ChromAdapt.html fmtcl::Mat3 Primaries::compute_chroma_adapt (const RgbSystem &prim_s, const RgbSystem &prim_d) { fmtcl::Vec3 white_s = conv_xy_to_xyz (prim_s._white); fmtcl::Vec3 white_d = conv_xy_to_xyz (prim_d._white); // Bradford adaptation const fmtcl::Mat3 ma ({ fmtcl::Vec3 ( 0.8951, 0.2664, -0.1614), fmtcl::Vec3 (-0.7502, 1.7135, 0.0367), fmtcl::Vec3 ( 0.0389, -0.0685, 1.0296) }); fmtcl::Vec3 crd_s = ma * white_s; fmtcl::Vec3 crd_d = ma * white_d; fmtcl::Mat3 scale (0.0); for (int k = 0; k < NBR_PLANES; ++k) { assert (crd_s [k] != 0); scale [k] [k] = crd_d [k] / crd_s [k]; } return ma.compute_inverse () * scale * ma; } // Obtains X, Y, Z from (x, y) // Y is assumed to be 1.0 // X = x / y // Z = (1 - x - y) / y // http://www.brucelindbloom.com/index.html?Eqn_xyY_to_XYZ.html fmtcl::Vec3 Primaries::conv_xy_to_xyz (const RgbSystem::Vec2 &xy) { fmtcl::Vec3 xyz; // When y is null, X = Y = Z = 0. if (fstb::is_null (xy [1])) { xyz [0] = 0; xyz [1] = 0; xyz [2] = 0; } else { xyz [0] = xy [0] / xy [1]; xyz [1] = 1; xyz [2] = (1 - xy [0] - xy [1]) / xy [1]; } return xyz; } // str should be already converted to lower case fmtcl::PrimariesPreset Primaries::conv_string_to_primaries (const std::string &str) { fmtcl::PrimariesPreset preset = fmtcl::PrimariesPreset_UNDEF; if ( str == "709" || str == "1361" || str == "61966-2-1" || str == "61966-2-4" || str == "hdtv" || str == "srgb") { preset = fmtcl::PrimariesPreset_BT709; } else if ( str == "470m" || str == "ntsc") { preset = fmtcl::PrimariesPreset_FCC; } else if ( str == "470m93" || str == "ntscj") { preset = fmtcl::PrimariesPreset_NTSCJ; } else if ( str == "470bg" || str == "601-625" || str == "1358-625" || str == "1700-625" || str == "pal" || str == "secam") { preset = fmtcl::PrimariesPreset_BT470BG; } else if ( str == "170m" || str == "601-525" || str == "1358-525" || str == "1700-525") { preset = fmtcl::PrimariesPreset_SMPTE170M; } else if ( str == "240m") { preset = fmtcl::PrimariesPreset_SMPTE240M; } else if ( str == "filmc") { preset = fmtcl::PrimariesPreset_GENERIC_FILM; } else if ( str == "2020" || str == "2100" || str == "uhdtv") { preset = fmtcl::PrimariesPreset_BT2020; } else if ( str == "61966-2-2" || str == "scrgb") { preset = fmtcl::PrimariesPreset_SCRGB; } else if ( str == "adobe98") { preset = fmtcl::PrimariesPreset_ADOBE_RGB_98; } else if ( str == "adobewide") { preset = fmtcl::PrimariesPreset_ADOBE_RGB_WIDE; } else if ( str == "apple") { preset = fmtcl::PrimariesPreset_APPLE_RGB; } else if ( str == "photopro" || str == "romm") { preset = fmtcl::PrimariesPreset_ROMM; } else if ( str == "ciergb") { preset = fmtcl::PrimariesPreset_CIERGB; } else if ( str == "ciexyz") { preset = fmtcl::PrimariesPreset_CIEXYZ; } else if ( str == "p3d65" || str == "dcip3") { preset = fmtcl::PrimariesPreset_P3D65; } else if ( str == "aces") { preset = fmtcl::PrimariesPreset_ACES; } else if ( str == "ap1") { preset = fmtcl::PrimariesPreset_ACESAP1; } else if ( str == "sgamut" || str == "sgamut3") { preset = fmtcl::PrimariesPreset_SGAMUT; } else if ( str == "sgamut3cine") { preset = fmtcl::PrimariesPreset_SGAMUT3CINE; } else if ( str == "alexa") { preset = fmtcl::PrimariesPreset_ALEXA; } else if ( str == "vgamut") { preset = fmtcl::PrimariesPreset_VGAMUT; } else if ( str == "p3dci") { preset = fmtcl::PrimariesPreset_P3DCI; } else if ( str == "p3d60") { preset = fmtcl::PrimariesPreset_P3D60; } else if ( str == "3213") { preset = fmtcl::PrimariesPreset_EBU3213E; } return preset; } } // namespace fmtc /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
22.929795
174
0.600702
[ "vector" ]
dd81d70f3d116162c09a2ac2611d537f90d61ccb
1,143
hpp
C++
include/wise.kernel/server/service/db/detail/db_pool.hpp
npangunion/wise.kernel
a44f852f5e7ade2c5f95f5d615daaf154bc69468
[ "MIT" ]
1
2020-03-01T04:05:59.000Z
2020-03-01T04:05:59.000Z
include/wise.kernel/server/service/db/detail/db_pool.hpp
npangunion/wise.kernel
a44f852f5e7ade2c5f95f5d615daaf154bc69468
[ "MIT" ]
null
null
null
include/wise.kernel/server/service/db/detail/db_pool.hpp
npangunion/wise.kernel
a44f852f5e7ade2c5f95f5d615daaf154bc69468
[ "MIT" ]
null
null
null
#pragma once #include "db.hpp" #include "db_command.hpp" #include <wise/dbc/dbc.hpp> namespace wise { /// per runner db pool of connection and command class db_pool { public: /// constructor db_pool(); /// setup by connecting to each db. throws wise::exception if fail bool start(const std::vector<db>& dbs); /// cleanup ~db_pool(); /// returns command. create one if not exists. db_command::ptr get(const std::string& db, const topic& pic, const std::wstring& query); /// to test and debug bool has_db(const std::string& db) const; /// to test and debug bool has_command(const std::string& db, const topic& pic) const; private: struct cmd_key { std::string db; topic pic; /// comparison operator for map bool operator < (const cmd_key& rhs) const { return db < rhs.db && pic < rhs.pic; } bool operator == (const cmd_key& rhs) const { return db == rhs.db && pic == rhs.pic; } }; using db_map = std::map<std::string, db>; using cmd_map = std::map<cmd_key, db_command::ptr>; private: bool setup_pool(const std::vector<db>& dbs); private: db_map dbs_; cmd_map cmds_; }; } // wise
18.435484
89
0.662292
[ "vector" ]
dd8856bf571b68327b8ad2ced9d4475dc227d2ce
1,722
cpp
C++
11626.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
11626.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
11626.cpp
felikjunvianto/kfile-uvaoj-submissions
5bd8b3b413ca8523abe412b0a0545f766f70ce63
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> using namespace std; int t,n,x,y,z,a,b; char stat[2]; vector<PII> convex; long long det(PII p,PII q,PII r) { long long a=(long long)p.fi*(q.se-r.se); long long b=(long long)q.fi*(r.se-p.se); long long c=(long long)r.fi*(p.se-q.se); return(a+b+c); } long long dis(PII i) { long long x=(long long)i.fi-convex[0].fi; long long y=(long long)i.se-convex[0].se; return(x*x+y*y); } bool cf(PII i,PII j) { if(det(convex[0],i,j)==0) return(dis(i)<dis(j)); int xa=i.fi-convex[0].fi;int ya=i.se-convex[0].se; int xb=j.fi-convex[0].fi;int yb=j.se-convex[0].se; return(atan2(ya,xa)<atan2(yb,xb)); } int main() { scanf("%d",&t); while(t--) { scanf("%d",&n); convex.clear(); z=0; while(n--) { scanf("%d %d %s",&a,&b,stat); if(stat[0]=='Y') { convex.pb(mp(a,b)); if((convex[z].se>convex.back().se)||((convex[z].se==convex.back().se)&&(convex[z].fi<convex.back().fi))) z=convex.size()-1; } } swap(convex[0],convex[z]); sort(++convex.begin(),convex.end(),cf); z=0; n=convex.size(); for(x=0;x<n;x++) if((convex[z].fi>convex[x].fi)||((convex[z].fi==convex[x].fi)&&(convex[z].se>convex[x].se))) z=x; printf("%d\n",n); for(x=0;x<n;x++) printf("%d %d\n",convex[(x+z)%n].fi,convex[(x+z)%n].se); } return 0; }
20.746988
110
0.569106
[ "vector" ]
dd89f581fe69b67b13a921fbb43c342102222f27
431
cpp
C++
JB/Week3/2437_Balances/main.cpp
lee20h/ALPS_2020_Summer_Study
3656d5c6ab44f7f43c1f8c691e75352495c76adc
[ "Apache-2.0" ]
1
2020-08-02T14:30:03.000Z
2020-08-02T14:30:03.000Z
JB/Week3/2437_Balances/main.cpp
alps-jbnu/ALPS_2020_Summer_Study
3656d5c6ab44f7f43c1f8c691e75352495c76adc
[ "Apache-2.0" ]
null
null
null
JB/Week3/2437_Balances/main.cpp
alps-jbnu/ALPS_2020_Summer_Study
3656d5c6ab44f7f43c1f8c691e75352495c76adc
[ "Apache-2.0" ]
2
2020-07-09T14:53:29.000Z
2020-07-17T10:39:00.000Z
#include <bits/stdc++.h> #define ll long long using namespace std; int N; vector<int> vec; int main() { ios::sync_with_stdio(false); cin.tie(0); ll ans = 0; cin >> N; while(cin >> N) vec.push_back(N); sort(vec.begin(), vec.end()); for(int i = 0; i < vec.size(); i++) { if(ans + 1 < vec[i]) break; ans += vec[i]; } cout << ans + 1; }
17.958333
42
0.461717
[ "vector" ]
dd8ef6fa4f8627e8284fbd17c7896e3310e221e8
1,850
cpp
C++
tools/Vitis-AI-Runtime/VART/xir/src/xir/tensor/tensor.cpp
hito0512/Vitis-AI
996459fb96cb077ed2f7e789d515893b1cccbc95
[ "Apache-2.0" ]
848
2019-12-03T00:16:17.000Z
2022-03-31T22:53:17.000Z
tools/Vitis-AI-Runtime/VART/xir/src/xir/tensor/tensor.cpp
wangyifan778/Vitis-AI
f61061eef7550d98bf02a171604c9a9f283a7c47
[ "Apache-2.0" ]
656
2019-12-03T00:48:46.000Z
2022-03-31T18:41:54.000Z
tools/Vitis-AI-Runtime/VART/xir/src/xir/tensor/tensor.cpp
wangyifan778/Vitis-AI
f61061eef7550d98bf02a171604c9a9f283a7c47
[ "Apache-2.0" ]
506
2019-12-03T00:46:26.000Z
2022-03-30T10:34:56.000Z
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "xir/tensor/tensor.hpp" #include "xir/tensor/tensor_imp.hpp" namespace xir { std::unique_ptr<Tensor> Tensor::create(const std::string& name, const std::vector<std::int32_t>& shape, const DataType& data_type) { return std::unique_ptr<Tensor>{ static_cast<Tensor*>(new TensorImp(name, shape, data_type))}; } // TODO:: legacy API std::unique_ptr<Tensor> Tensor::create(const std::string& name, const std::vector<std::int32_t>& shape, const DataType::Type& data_type, const std::int32_t bit_width) { return create(name, shape, DataType{data_type, bit_width}); } std::unique_ptr<Tensor> Tensor::clone(const Tensor* tensor) { auto ret = std::unique_ptr<Tensor>{static_cast<Tensor*>(new TensorImp( tensor->get_name(), tensor->get_shape(), tensor->get_data_type()))}; ret->set_attrs(tensor->get_attrs()); return ret; } std::unique_ptr<Tensor> Tensor::clone(const Tensor* tensor, const std::string& name) { auto ret = clone(tensor); ret->rename(name); return ret; } } // namespace xir
34.90566
78
0.630811
[ "shape", "vector" ]
dd90e65002a172918fbbc66cb0fa766c361d2a8e
11,424
cpp
C++
flashlight/fl/experimental/memory/allocator/CompositeMemoryAllocator.cpp
codekansas/flashlight
6b9e1f5d00269bda8ca6f453ab7f15bd2b8627f9
[ "BSD-3-Clause" ]
1
2021-05-26T11:56:41.000Z
2021-05-26T11:56:41.000Z
flashlight/fl/experimental/memory/allocator/CompositeMemoryAllocator.cpp
codekansas/flashlight
6b9e1f5d00269bda8ca6f453ab7f15bd2b8627f9
[ "BSD-3-Clause" ]
null
null
null
flashlight/fl/experimental/memory/allocator/CompositeMemoryAllocator.cpp
codekansas/flashlight
6b9e1f5d00269bda8ca6f453ab7f15bd2b8627f9
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include "flashlight/fl/experimental/memory/allocator/CompositeMemoryAllocator.h" #include <algorithm> #include <cstddef> #include <cstdint> #include <limits> #include <sstream> #include <stdexcept> #include "flashlight/fl/common/Histogram.h" #include "flashlight/fl/common/Logging.h" #include "flashlight/fl/common/Utils.h" namespace fl { std::string CompositeMemoryAllocator::AllocatorAndCriteria::prettyString() const { std::stringstream ss; ss << "AllocatorAndCriteria{" << std::endl << "maxAllocationSize=" << prettyStringMemorySize(maxAllocationSize) << std::endl << " allocator=" << allocator->prettyString() << std::endl << '}'; return ss.str(); } CompositeMemoryAllocator::CompositeMemoryAllocator(std::string name) : MemoryAllocator(name), totalNumberOfAllocations_(0), arenaSizeInBlocks_(0), arenaSizeInBytes_(0), failToAllocate_(false), oomEventCount_(0) {} void CompositeMemoryAllocator::add(AllocatorAndCriteria allocatorAndCriteria) { const MemoryAllocator::Stats stats = allocatorAndCriteria.allocator->getStats(); arenaSizeInBlocks_ += stats.statsInBlocks.arenaSize; arenaSizeInBytes_ += stats.statsInBytes.arenaSize; allocatorsAndCriterias_.push_back(std::move(allocatorAndCriteria)); std::sort(allocatorsAndCriterias_.begin(), allocatorsAndCriterias_.end()); } bool CompositeMemoryAllocator::jitTreeExceedsMemoryPressure(size_t bytes) { if (bytes == 0) { return false; } for (size_t i = 0; i < allocatorsAndCriterias_.size(); ++i) { if (allocatorsAndCriterias_[i].maxAllocationSize >= bytes) { return allocatorsAndCriterias_[i].allocator->jitTreeExceedsMemoryPressure( bytes); } } return false; } void* CompositeMemoryAllocator::allocate(size_t size) { if (size == 0) { return nullptr; } void* ptr = nullptr; std::vector<std::string> errors; for (size_t i = 0; i < allocatorsAndCriterias_.size(); ++i) { // Try allocate if size is below the allocators maxAllocationSize. if (allocatorsAndCriterias_[i].maxAllocationSize >= size) { try { ptr = allocatorsAndCriterias_[i].allocator->allocate(size); } catch (std::exception& ex) { // Catch the OOM exception because maybe the next allocator can satisfy // the request. // errors.push_back(ex.what()); } if (ptr) { ptrToAllocation_[ptr] = {size, i}; break; } } } // When getLogLevel()==0 only log when ptr==0 std::string oomErrorDescription; if (!ptr || (!errors.empty())) { std::stringstream ss; failToAllocate_ = true; Stats stats = getStats(); const size_t totalFreeMem = stats.statsInBytes.arenaSize - stats.statsInBytes.allocatedCount; ss << "CompositeMemoryAllocator::allocateImpl(size=" << prettyStringMemorySize(size) << ')' << " totalFreeMem=" << prettyStringMemorySize(totalFreeMem) << " (totalFreeMem - size)=" << prettyStringMemorySize(totalFreeMem - size) << " (size / totalFreeMem)=" << (static_cast<double>(size) / totalFreeMem) << " experienced a"; if (ptr) { ss << " partial"; } else { ss << " !full!"; } ss << " allocation error={"; for (const std::string& error : errors) { ss << '{' << error << "},"; } ss << '}' << std::endl; ss << "Dumping memory state at time of OOM:" << std::endl << prettyString(); oomErrorDescription = ss.str(); if (ptr) { if (getLogLevel() > 1) { FL_LOG(fl::WARNING) << oomErrorDescription; } } else { if (getLogLevel() > 0) { FL_LOG(fl::ERROR) << oomErrorDescription; } if (!oomEventCount_) { firstOomStats_.stats = getStats(); firstOomStats_.allocationSize = size; firstOomStats_.description = oomErrorDescription; } ++oomEventCount_; throw std::invalid_argument(oomErrorDescription); } } ++totalNumberOfAllocations_; return ptr; } void CompositeMemoryAllocator::free(void* ptr) { auto itr = ptrToAllocation_.find(ptr); if (itr != ptrToAllocation_.end()) { allocatorsAndCriterias_[itr->second.allocatorsAndCriteriasIndex] .allocator->free(ptr); } else { std::stringstream ss; ss << "CompositeMemoryAllocator::free(ptr=" << ptr << ") pointer is not managed allocator."; throw std::invalid_argument(ss.str()); } } CompositeMemoryAllocator::FirstOomStats::FirstOomStats() : allocationSize(0) {} std::string CompositeMemoryAllocator::FirstOomStats::prettyString() const { std::stringstream ss; const size_t freeMem = stats.statsInBytes.arenaSize - stats.statsInBytes.allocatedCount; ss << "allocationSize=" << prettyStringMemorySize(allocationSize) << " freeMem=" << prettyStringMemorySize(freeMem) << " (free - allocationSize)=" << prettyStringMemorySize(freeMem - allocationSize) << " (allocationSize / free)=" << (static_cast<double>(allocationSize) / freeMem) << " description={" << description << '}'; return ss.str(); } std::string CompositeMemoryAllocator::prettyString() const { const MemoryAllocator::Stats stats = getStats(); std::stringstream ss; ss << "CompositeMemoryAllocator{stats=" << stats.prettyString() << std::endl; if (oomEventCount_) { ss << "First OOM event stats={" << firstOomStats_.prettyString() << '}' << std::endl; } if (ptrToAllocation_.empty()) { ss << std::endl << "CompositeMemoryAllocator currently has no allocations." << std::endl; } else { ss << std::endl << "CompositeMemoryAllocator currenly allocated higtogram:" << std::endl; std::vector<size_t> currentAllocationSize(ptrToAllocation_.size()); for (const auto& ptrAndAllocation : ptrToAllocation_) { currentAllocationSize.push_back(ptrAndAllocation.second.size); } HistogramStats<size_t> hist = FixedBucketSizeHistogram<size_t>( currentAllocationSize.begin(), currentAllocationSize.end(), kHistogramBucketCountPrettyString); ss << hist.prettyString() << std::endl; // Show double high resolution when bucket[0] have > 100 items. if (!hist.buckets.empty() && currentAllocationSize.size() > 100) { const HistogramBucket<size_t>& largestCountBucket = hist.buckets[0]; if (largestCountBucket.count > 100) { HistogramStats<size_t> hiResHist = FixedBucketSizeHistogram<size_t>( currentAllocationSize.begin(), currentAllocationSize.end(), kHistogramBucketCountPrettyString, largestCountBucket.startInclusive, largestCountBucket.endExclusive); ss << std::endl << "Currently allocated hi-resolution:" << std::endl << hiResHist.prettyString() << std::endl; // Show double high resolution when bucket[0] have > 100 items. if (!hiResHist.buckets.empty()) { const HistogramBucket<size_t>& doubleLargestCountBucket = hiResHist.buckets[0]; if (doubleLargestCountBucket.count > 100) { HistogramStats<size_t> doubleHiResHist = FixedBucketSizeHistogram<size_t>( currentAllocationSize.begin(), currentAllocationSize.end(), kHistogramBucketCountPrettyString, doubleLargestCountBucket.startInclusive, doubleLargestCountBucket.endExclusive); ss << std::endl << "Currently allocated double hi-resolution:" << std::endl << doubleHiResHist.prettyString() << std::endl; } } } } } ss << " allocatorsAndCriterias_.size()=" << allocatorsAndCriterias_.size() << " allcatorsAndCriterias={" << std::endl; for (const AllocatorAndCriteria& allocatorAndCriteria : allocatorsAndCriterias_) { ss << std::endl << allocatorAndCriteria.prettyString(); } ss << "}}"; return ss.str(); } size_t CompositeMemoryAllocator::getAllocatedSizeInBytes(void* ptr) const { auto itr = ptrToAllocation_.find(ptr); if (itr != ptrToAllocation_.end()) { return itr->second.size; } else { std::stringstream ss; ss << "CompositeMemoryAllocator::getAllocatedSizeInBytes(ptr=" << ptr << ") pointer is not managed allocator."; throw std::invalid_argument(ss.str()); } } void CompositeMemoryAllocator::setLogLevel(int logLevel) { for (const AllocatorAndCriteria& allocatorAndCriteria : allocatorsAndCriterias_) { allocatorAndCriteria.allocator->setLogLevel(logLevel); }; MemoryAllocator::setLogLevel(logLevel); } MemoryAllocator::Stats CompositeMemoryAllocator::getStats() const { Stats stats; stats.failToAllocate = failToAllocate_; // Arena is set to the minimum arena of all allocators; stats.arena = reinterpret_cast<void*>(std::numeric_limits<std::uintptr_t>::max()); stats.statsInBlocks.arenaSize = arenaSizeInBlocks_; stats.statsInBytes.arenaSize = arenaSizeInBytes_; stats.allocationsCount = totalNumberOfAllocations_; stats.oomEventCount += oomEventCount_; // External fragmentation is taken from the last (the catch all) arena. const AllocatorAndCriteria& lastAllocatorAndCriteria = allocatorsAndCriterias_.back(); const Stats lastAllocatorStats = lastAllocatorAndCriteria.allocator->getStats(); stats.externalFragmentationScore += lastAllocatorStats.externalFragmentationScore; stats.maxExternalFragmentationScore += lastAllocatorStats.maxExternalFragmentationScore; double blockSize = 0.0; for (const AllocatorAndCriteria& allocatorAndCriteria : allocatorsAndCriterias_) { MemoryAllocator::Stats curStats = allocatorAndCriteria.allocator->getStats(); // Weight is the current allocator arena size relative to sum of all // arenas. const double weight = static_cast<double>(curStats.statsInBytes.arenaSize) / arenaSizeInBytes_; stats.arena = std::min(stats.arena, curStats.arena); blockSize += static_cast<double>(curStats.blockSize) * weight; stats.deAllocationsCount += curStats.deAllocationsCount; stats.internalFragmentationScore += curStats.internalFragmentationScore * weight; stats.maxInternalFragmentationScore += curStats.maxInternalFragmentationScore * weight; stats.statsInBytes.allocatedCount += curStats.statsInBytes.allocatedCount; stats.statsInBytes.maxAllocatedCount += curStats.statsInBytes.maxAllocatedCount; stats.statsInBlocks.allocatedCount += curStats.statsInBlocks.allocatedCount; stats.statsInBlocks.maxAllocatedCount += curStats.statsInBlocks.maxAllocatedCount; stats.performanceCost += curStats.performanceCost; stats.subArenaStats.push_back(std::move(curStats)); } // blockSize is set to weighted average of all allocator. The weight // is determined by arena size. stats.blockSize = blockSize; stats.statsInBytes.freeCount = stats.statsInBytes.arenaSize - stats.statsInBytes.allocatedCount; stats.statsInBlocks.freeCount = stats.statsInBlocks.arenaSize - stats.statsInBlocks.allocatedCount; return stats; } }; // namespace fl
34.306306
81
0.681197
[ "vector" ]
dd92f8326d5dc2b2f45114ae45eb3bfdf64b08fd
6,367
cpp
C++
willow/src/op/onehot.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
61
2020-07-06T17:11:46.000Z
2022-03-12T14:42:51.000Z
willow/src/op/onehot.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
1
2021-02-25T01:30:29.000Z
2021-11-09T11:13:14.000Z
willow/src/op/onehot.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
6
2020-07-15T12:33:13.000Z
2021-11-07T06:55:00.000Z
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #include <memory> #include <popart/graph.hpp> #include <popart/op/onehot.hpp> #include <popart/opmanager.hpp> #include <popart/opserialiser.hpp> #include <popart/tensor.hpp> #include <popart/tensordata.hpp> #include <popart/tensors.hpp> #include <popart/typefunctor.hpp> namespace popart { OnehotOp::OnehotOp(const OperatorIdentifier &_opid, int64_t axis_, const Op::Settings &settings_) : Op(_opid, settings_), axis(axis_) {} std::unique_ptr<Op> OnehotOp::clone() const { return std::make_unique<OnehotOp>(*this); } void OnehotOp::setup() { // The output type is the same as the input values auto outputType = inInfo(getValuesInIndex()).dataType(); // The outshape is the same as the indices plus an additional // dimension at the axis for the one-hot representation auto outputShape = inInfo(getIndicesInIndex()).shape(); // Add the additional axis if (axis != -1) { outputShape.insert(outputShape.begin() + axis, onehotAxisDim); } else { outputShape.push_back(onehotAxisDim); } outInfo(getOutIndex()) = TensorInfo(outputType, outputShape); } void OnehotOp::connectInTensor(InIndex inIndex, TensorId tenId) { if (inIndex == 1) { // Determine the dimension of the onehot axis TensorId depthId = tenId; // check 2 : that there is already a tensor with the shape tensor's name if (!getGraph().getTensors().contains(depthId)) { throw error("no Tensor named `" + depthId + "' recorded in Ir. " + " This is the second input in the OneHot constructor. "); } Tensor *depthTensor = getGraph().getTensors().get(depthId); // check 3 : that the tensor has data if (!depthTensor->hasTensorData()) { throw error("The depth Tensor `" + depthId + "' does not have data"); } TensorData *depthTensorData = depthTensor->tensorData(); // check 4 : that it only has 1 element (i.e. rank 0) if (depthTensor->info.nelms() != 1) { throw error("The depth tensor should be rank 0 in OneHot"); } onehotAxisDim = typefunctor::get<typefunctor::Int64FromVoid, int64_t>( depthTensor->info.dataType(), depthTensorData->data()); } else { defaultConnectInTensor(inIndex, tenId); } } std::vector<std::unique_ptr<Op>> OnehotOp::getGradOps() { std::vector<std::unique_ptr<Op>> upops; upops.emplace_back(std::make_unique<OnehotGradOp>(*this)); return upops; } void OnehotOp::appendOutlineAttributes(OpSerialiserBase &os) const { Op::appendOutlineAttributes(os); os.appendAttribute("axis", axis); os.appendAttribute("depth", onehotAxisDim); } OnehotGradOp::OnehotGradOp(const OnehotOp &fwdOp_) : Op(Onnx::GradOperators::OneHotGrad, fwdOp_.getSettings()), axis(fwdOp_.getAxis()), outputShape(fwdOp_.inInfo(OnehotOp::getValuesInIndex()).shape()) {} std::unique_ptr<Op> OnehotGradOp::clone() const { return std::make_unique<OnehotGradOp>(*this); } void OnehotGradOp::setup() { outInfo(getOutIndex()) = TensorInfo(inInfo(getGradInIndex()).dataType(), outputShape); } const std::vector<GradInOutMapper> &OnehotGradOp::gradInputInfo() const { static const std::vector<GradInOutMapper> inInfo = { {getGradInIndex(), OnehotOp::getOutIndex(), GradOpInType::GradOut}, {getIndicesInIndex(), OnehotOp::getIndicesInIndex(), GradOpInType::In}}; return inInfo; } const std::map<int, int> &OnehotGradOp::gradOutToNonGradIn() const { static const std::map<int, int> outInfo = { {getOutIndex(), OnehotOp::getValuesInIndex()}}; return outInfo; } void OnehotGradOp::appendOutlineAttributes(OpSerialiserBase &os) const { Op::appendOutlineAttributes(os); os.appendAttribute("axis", axis); } namespace { // Do we support all types as there is a cast in the definition static OpDefinition::DataTypes T1 = {DataType::UINT8, DataType::UINT16, DataType::UINT32, DataType::UINT64, DataType::INT8, DataType::INT16, DataType::INT32, DataType::INT64, DataType::FLOAT16, DataType::FLOAT}; static OpDefinition::DataTypes T2 = {DataType::UINT8, DataType::UINT16, DataType::UINT32, DataType::UINT64, DataType::INT8, DataType::INT16, DataType::INT32, DataType::INT64, DataType::FLOAT16, DataType::FLOAT}; static OpDefinition::DataTypes T3 = {DataType::UINT8, DataType::UINT16, DataType::UINT32, DataType::UINT64, DataType::INT8, DataType::INT16, DataType::INT32, DataType::INT64, DataType::FLOAT16, DataType::FLOAT, DataType::BOOL}; static OpDefinition onehotOpDef({OpDefinition::Inputs({ {"indices", T1}, {"depth", T2}, {"values", T3}, }), OpDefinition::Outputs({{"output", T3}}), OpDefinition::Attributes({{"axis", {"*"}}})}); static OpCreator<OnehotOp> onehotOpCreator( OpDefinitions({ {Onnx::Operators::OneHot_9, onehotOpDef}, {Onnx::Operators::OneHot_11, onehotOpDef}, }), [](const OpCreatorInfo &info) { int64_t axis = info.attributes.getAttribute<Attributes::Int>("axis", -1); return std::unique_ptr<Op>(new OnehotOp(info.opid, axis, info.settings)); }, true); } // namespace } // namespace popart
35.569832
79
0.561018
[ "shape", "vector" ]
dda1d452698eb7696b7cc30912475da78910df19
1,561
cpp
C++
Problems/0381. Insert Delete GetRandom O(1) - Duplicates allowed.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0381. Insert Delete GetRandom O(1) - Duplicates allowed.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
Problems/0381. Insert Delete GetRandom O(1) - Duplicates allowed.cpp
KrKush23/LeetCode
2a87420a65347a34fba333d46e1aa6224c629b7a
[ "MIT" ]
null
null
null
class RandomizedCollection { vector<int> nums{}; map<int, unordered_set<int>> m{}; // {val, indices in array} public: /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */ bool insert(int val) { m[val].insert(nums.size()); nums.push_back(val); return m[val].size() == 1; //if '1' => wasn't present EARLIER } /** Removes a value from the collection. Returns true if the collection contained the specified element. */ bool remove(int val) { if(m.count(val) and m[val].size() > 0 ){ //size of VECTOR should also be > 0 auto free_pos = *m[val].begin(); // get INDEX m[val].erase(m[val].begin()); // remove index from map nums[free_pos] = nums.back(); // swap with LAST m[nums.back()].insert(free_pos); // add INDEX to LAST's map m[nums.back()].erase(nums.size()-1); // erase previous index from LAST's map nums.pop_back(); // remove from vector return true; } return false; } /** Get a random element from the collection. */ int getRandom() { int i = rand()%nums.size(); return nums[i]; } }; /** * Your RandomizedCollection object will be instantiated and called as such: * RandomizedCollection* obj = new RandomizedCollection(); * bool param_1 = obj->insert(val); * bool param_2 = obj->remove(val); * int param_3 = obj->getRandom(); */
36.302326
123
0.577835
[ "object", "vector" ]
dda5e6ec5f1fd52c62367da478cb0e547282e882
321
cc
C++
choosing_teams.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
null
null
null
choosing_teams.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
3
2021-01-04T18:33:39.000Z
2021-01-04T19:37:21.000Z
choosing_teams.cc
maximilianbrine/github-slideshow
76e4d6a7e57da61f1ddca4d8aa8bc5d2fd78bea1
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> int main() { int n, k; std::cin >> n >> k; std::vector<int> players; for (int i = 0; i < n; ++i) { int y; std::cin >> y; if (y <= 5 - k) { players.push_back(y); } } std::cout << players.size() / 3 << std::endl; return 0; }
21.4
49
0.448598
[ "vector" ]
ddad3019e8bbd7bfcf7443a0c07e7e5ab388143e
2,689
cpp
C++
queue/C++/0641-design-circular-deque(1)/main.cpp
ljyljy/LeetCode-Solution-in-Good-Style
0998211d21796868061eb22e2cbb9bcd112cedce
[ "Apache-2.0" ]
1
2020-04-02T13:31:31.000Z
2020-04-02T13:31:31.000Z
queue/C++/0641-design-circular-deque(1)/main.cpp
lemonnader/LeetCode-Solution-Well-Formed
baabdb1990fd49ab82a712e121f49c4f68b29459
[ "Apache-2.0" ]
null
null
null
queue/C++/0641-design-circular-deque(1)/main.cpp
lemonnader/LeetCode-Solution-Well-Formed
baabdb1990fd49ab82a712e121f49c4f68b29459
[ "Apache-2.0" ]
1
2021-06-17T09:21:54.000Z
2021-06-17T09:21:54.000Z
#include <iostream> #include <vector> using namespace std; class MyCircularDeque { private: vector<int> arr; int front; int rear; int capacity; public: /** Initialize your data structure here. Set the size of the deque to be k. */ MyCircularDeque(int k) { capacity = k + 1; arr.assign(capacity, 0); front = 0; rear = 0; } /** Adds an item at the front of Deque. Return true if the operation is successful. */ bool insertFront(int value) { if (isFull()) { return false; } front = (front - 1 + capacity) % capacity; arr[front] = value; return true; } /** Adds an item at the rear of Deque. Return true if the operation is successful. */ bool insertLast(int value) { if (isFull()) { return false; } arr[rear] = value; rear = (rear + 1) % capacity; return true; } /** Deletes an item from the front of Deque. Return true if the operation is successful. */ bool deleteFront() { if (isEmpty()) { return false; } // front 被设计在数组的开头,所以是 +1 front = (front + 1) % capacity; return true; } /** Deletes an item from the rear of Deque. Return true if the operation is successful. */ bool deleteLast() { if (isEmpty()) { return false; } // rear 被设计在数组的末尾,所以是 -1 rear = (rear - 1 + capacity) % capacity; return true; } /** Get the front item from the deque. */ int getFront() { if (isEmpty()) { return -1; } return arr[front]; } /** Get the last item from the deque. */ int getRear() { if (isEmpty()) { return -1; } // 当 rear 为 0 时防止数组越界 return arr[(rear - 1 + capacity) % capacity]; } /** Checks whether the circular deque is empty or not. */ bool isEmpty() { return front == rear; } /** Checks whether the circular deque is full or not. */ bool isFull() { // 注意:这个设计是非常经典的做法 return (rear + 1) % capacity == front; } }; /** * Your MyCircularDeque object will be instantiated and called as such: * MyCircularDeque* obj = new MyCircularDeque(k); * bool param_1 = obj->insertFront(value); * bool param_2 = obj->insertLast(value); * bool param_3 = obj->deleteFront(); * bool param_4 = obj->deleteLast(); * int param_5 = obj->getFront(); * int param_6 = obj->getRear(); * bool param_7 = obj->isEmpty(); * bool param_8 = obj->isFull(); */ int main() { std::cout << "Hello, World!" << std::endl; return 0; }
24.445455
95
0.547415
[ "object", "vector" ]
ddafae8dadf7f2a5633d0050582c55fa4d8186ed
1,954
hpp
C++
inc/ResourceManagement/Model.hpp
Arxcel/bomberman
f1e9b8e3fa669c5136323d8e79f857f8ea25343f
[ "MIT" ]
null
null
null
inc/ResourceManagement/Model.hpp
Arxcel/bomberman
f1e9b8e3fa669c5136323d8e79f857f8ea25343f
[ "MIT" ]
null
null
null
inc/ResourceManagement/Model.hpp
Arxcel/bomberman
f1e9b8e3fa669c5136323d8e79f857f8ea25343f
[ "MIT" ]
null
null
null
#ifndef MODEL_H #define MODEL_H #include <string> #include <fstream> #include <sstream> #include <iostream> #include <map> #include <vector> #include <memory.h> #include <assimp/Importer.hpp> #include <assimp/scene.h> #include <assimp/postprocess.h> #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "ResourceManagement/Mesh.hpp" #include "ResourceManagement/Shader.hpp" #include "ResourceManagement/Texture.hpp" #include "Utilities/AABB.hpp" class Animation; class AABB; class Model { public: Model(std::string const &path, glm::vec3 scale, glm::vec3 offset, glm::vec3 axis, float angle, float glossiness); Model& operator=(const Model&) = default; ~Model(); void draw(std::shared_ptr<Shader> const& shader, std::vector<glm::mat4> const& transforms); void transform(glm::mat4 const & aTransform); void setAnimation(Animation const& anim); bool mAnimated; private: void makeUnitModel(); void loadModel(std::string const& path); void processNode(aiNode const* node, aiScene const* scene); void processMesh(aiMesh const* mesh, aiScene const* scene); std::map<std::string, unsigned int> processBones(aiMesh const* mesh, std::vector<glm::mat4> & aOffsets, std::vector<WeightData> & vertices); std::vector<Vertex> loadVertices(aiMesh const* mesh); std::vector<unsigned int> loadIndices(aiMesh const* mesh); std::vector<std::shared_ptr<Texture>> loadTextures(aiMesh const* mesh, aiScene const* scene); std::vector<std::shared_ptr<Texture>> loadMaterialTextures(aiMaterial *mat, aiTextureType type, TextureType texType); private: std::vector<std::unique_ptr<Mesh>> mMeshes; std::string mDirectory; AABB mAABB; glm::mat4 mTransFormMatrix; float mGlossiness; Assimp::Importer *mImporter; }; #endif
33.118644
145
0.679632
[ "mesh", "vector", "model", "transform" ]
ddbfa7007bbd9d678f889727060f070aa596f543
13,115
cpp
C++
base/fs/hsm/engine/hsmeng/rswriter.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/fs/hsm/engine/hsmeng/rswriter.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/fs/hsm/engine/hsmeng/rswriter.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 2000 Microsoft Corporation Module Name: rswriter.cpp Abstract: Implements CRssJetWriter methods Author: Ran Kalach [rankala] 4/4/2000 Revision History: --*/ #include "stdafx.h" #include "rsevents.h" #include "rswriter.h" // Include these 2 files just for VSS_E_WRITERERROR_TIMEOUT definition #include "vss.h" #include "vswriter.h" #include "aclapi.h" #ifndef INITGUID #define INITGUID #include <guiddef.h> #undef INITGUID #else #include <guiddef.h> #endif #ifdef __cplusplus extern "C" { #endif DEFINE_GUID(RSS_WRITER_GUID, 0xb959d2c3L, 0x18bb, 0x4607, 0xb0, 0xca, 0x68, 0x8c, 0xd0, 0xd4, 0x1a, 0x50); // {b959d2c3-18bb-4607-b0ca-688cd0d41a50} #ifdef __cplusplus } #endif #define FILES_TO_EXCLUDE OLESTR("%SystemRoot%\\System32\\RemoteStorage\\FsaDb\\*;%SystemRoot%\\System32\\RemoteStorage\\Trace\\*") #define FILES_TO_INCLUDE OLESTR("") CRssJetWriter::CRssJetWriter() /*++ Routine Description: Constructor Arguments: None Return Value: None Notes: We create the events in the constructor because these events might be required before the Init code could be done (Init must be called after Jet is initialized --*/ { HRESULT hr = S_OK; PSID pSystemSID = NULL; PACL pACL = NULL; PSECURITY_DESCRIPTOR pSD = NULL; #define WRITER_EVENTS_NUM_ACE 1 EXPLICIT_ACCESS ea[WRITER_EVENTS_NUM_ACE]; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; SECURITY_ATTRIBUTES sa; WsbTraceIn(OLESTR("CRssJetWriter::CRssJetWriter"), OLESTR("")); m_bTerminating = FALSE; try { for (int index=0; index<WRITER_EVENTS_NUM; index++) { m_syncHandles[index] = NULL; } // Create the events // Note: Currently Engine and IDB sync events are created here, FSA event already should already exist // If initializtion order of RSS modles is changed - the CreateEent and OpenEvent calls for these // named events may need to switch. // Method of interest for this matter (of init order) are CHsmServer::Init and CFsaServer::Init // Create an SD with ACL for local-system only memset(ea, 0, sizeof(EXPLICIT_ACCESS) * WRITER_EVENTS_NUM_ACE); WsbAssertStatus( AllocateAndInitializeSid( &SIDAuthNT, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &pSystemSID) ); ea[0].grfAccessPermissions = FILE_ALL_ACCESS; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance = SUB_CONTAINERS_AND_OBJECTS_INHERIT; ea[0].Trustee.pMultipleTrustee = NULL; ea[0].Trustee.MultipleTrusteeOperation = NO_MULTIPLE_TRUSTEE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_USER; ea[0].Trustee.ptstrName = (LPTSTR) pSystemSID; WsbAffirmNoError(SetEntriesInAcl(WRITER_EVENTS_NUM_ACE, ea, NULL, &pACL)); pSD = (PSECURITY_DESCRIPTOR) WsbAlloc(SECURITY_DESCRIPTOR_MIN_LENGTH); WsbAffirmPointer(pSD); WsbAffirmStatus(InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)); WsbAffirmStatus(SetSecurityDescriptorDacl( pSD, TRUE, // fDaclPresent flag pACL, FALSE)); // not a default DACL sa.nLength = sizeof (SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = pSD; sa.bInheritHandle = FALSE; // Create teh actual events WsbAffirmHandle(m_syncHandles[INTERNAL_EVENT_INDEX] = CreateEvent(NULL, FALSE, TRUE, NULL)); WsbAffirmHandle(m_syncHandles[1] = OpenEvent(EVENT_ALL_ACCESS, FALSE, HSM_FSA_STATE_EVENT)); WsbAffirmHandle(m_syncHandles[2] = CreateEvent(&sa, FALSE, TRUE, HSM_ENGINE_STATE_EVENT)); WsbAffirmHandle(m_syncHandles[3] = CreateEvent(&sa, FALSE, TRUE, HSM_IDB_STATE_EVENT)); } WsbCatch(hr); m_hrInit = hr; if (pSystemSID) { FreeSid(pSystemSID); } if (pACL) { LocalFree(pACL); } if (pSD) { WsbFree(pSD); } WsbTraceOut(OLESTR("CRssJetWriter::CRssJetWriter"), OLESTR("hr = <%ls>"), WsbHrAsString(hr)); } CRssJetWriter::~CRssJetWriter( ) /*++ Routine Description: Destructor - free resources Arguments: None Return Value: None --*/ { WsbTraceIn(OLESTR("CRssJetWriter::~CRssJetWriter"), OLESTR("")); // Close event handles for (int index=0; index<WRITER_EVENTS_NUM; index++) { if (NULL != m_syncHandles[index]) { CloseHandle(m_syncHandles[index]); m_syncHandles[index] = NULL; } } WsbTraceOut(OLESTR("CRssJetWriter::~CRssJetWriter"), OLESTR("")); } HRESULT CRssJetWriter::Init(void) /*++ Routine Description: Initialize Snapshot synchronization Arguments: None Return Value: S_OK - Success --*/ { HRESULT hr = S_OK; WsbTraceIn(OLESTR("CRssJetWriter::Init"), OLESTR("")); try { // Don't do anything if the basic initialization done in the constructor failed WsbAffirmHr(m_hrInit); GUID rssGuid = RSS_WRITER_GUID; WsbAffirmHr(Initialize( rssGuid, RSS_BACKUP_NAME, TRUE, FALSE, FILES_TO_INCLUDE, FILES_TO_EXCLUDE )); } WsbCatch(hr); WsbTraceOut(OLESTR("CRssJetWriter::Init"), OLESTR("hr = <%ls>"), WsbHrAsString(hr)); return hr; } HRESULT CRssJetWriter::Terminate(void) /*++ Routine Description: Terminate Snapshot synchronization Arguments: None Return Value: S_OK - Success --*/ { HRESULT hr = S_OK; WsbTraceIn(OLESTR("CRssJetWriter::Terminate"), OLESTR("")); try { DWORD status, errWait; WsbAffirmHr(m_hrInit); // Avoid terminating in the middle of snapshot status = WaitForSingleObject(m_syncHandles[INTERNAL_EVENT_INDEX], INTERNAL_WAIT_TIMEOUT); errWait = GetLastError(); // Whatever the status is - uninitialize underlying writer mechanizm m_bTerminating = TRUE; Uninitialize(); // Check Wait status: if (status == WAIT_OBJECT_0) { // The expected case if (! SetEvent(m_syncHandles[INTERNAL_EVENT_INDEX])) { // Don't abort, just trace error WsbTraceAlways(OLESTR("CRssJetWriter::Terminate: SetEvent returned unexpected error %lu\n"), GetLastError()); } WsbTrace(OLESTR("CRssJetWriter::Terminate: Terminating after a successful wait\n")); } else { // In case of failure we cannot trust Thaw/Abort to be called so we signal the evnets InternalEnd(); switch (status) { case WAIT_TIMEOUT: WsbTraceAlways(OLESTR("CRssJetWriter::Terminate: Wait for Single Object timed out after %lu ms\n"), INTERNAL_WAIT_TIMEOUT); hr = E_FAIL; break; case WAIT_FAILED: WsbTraceAlways(OLESTR("CRssJetWriter::Terminate: Wait for Single Object returned error %lu\n"), errWait); hr = HRESULT_FROM_WIN32(errWait); break; default: WsbTraceAlways(OLESTR("CRssJetWriter::Terminate: Wait for Single Object returned unexpected status %lu\n"), status); hr = E_UNEXPECTED; break; } } } WsbCatch(hr); WsbTraceOut(OLESTR("CRssJetWriter::Terminate"), OLESTR("hr = <%ls>"), WsbHrAsString(hr)); return hr; } HRESULT CRssJetWriter::InternalEnd(void) /*++ Routine Description: Set all events Arguments: None Return Value: S_OK - Success --*/ { HRESULT hr = S_OK; WsbTraceIn(OLESTR("CRssJetWriter::InternalEnd"), OLESTR("")); try { WsbAffirmHr(m_hrInit); // Set all events DWORD errSet; for (int index=0; index<WRITER_EVENTS_NUM; index++) { if (NULL != m_syncHandles[index]) { if (! SetEvent(m_syncHandles[index])) { // Don't abort, just save error errSet = GetLastError(); WsbTraceAlways(OLESTR("CRssJetWriter::InternalEnd: SetEvent returned error %lu for event number %d\n"), errSet, index); hr = HRESULT_FROM_WIN32(errSet); } } } } WsbCatch(hr); WsbTraceOut(OLESTR("CRssJetWriter::InternalEnd"), OLESTR("hr = <%ls>"), WsbHrAsString(hr)); return hr; } // // CVssJetWriter overloaded methods // bool STDMETHODCALLTYPE CRssJetWriter::OnFreezeBegin() /*++ Routine Description: Handles Freeze Start event Arguments: None Return Value: TRUE - Success, OK to freeze FALSE - Failure, Don't freeze --*/ { HRESULT hr = S_OK; bool bRet; WsbTraceIn(OLESTR("CRssJetWriter::OnFreezeBegin"), OLESTR("")); try { WsbAffirmHr(m_hrInit); // Just wait for all sync events DWORD status = WaitForMultipleObjects(WRITER_EVENTS_NUM, m_syncHandles, TRUE, EVENT_WAIT_TIMEOUT); // Comparing (status == WAIT_OBJECT_0) || (status > WAIT_OBJECT_0) intsead of (status >= WAIT_OBJECT_0) // to avoid error C4296 - "expression is always true" if ( ((status == WAIT_OBJECT_0) || (status > WAIT_OBJECT_0)) && (status <= WAIT_OBJECT_0 + WRITER_EVENTS_NUM - 1) ) { // Freeze is ready to go... WsbTrace(OLESTR("CRssJetWriter::OnFreezeBegin: All events are nonsignaled, freeze is reday to go\n")); // If we are terminating, no Thaw/Abort will be called - therefore, set the events if (m_bTerminating) { InternalEnd(); } } else { // Something wrong... DWORD errWait = GetLastError(); // Set all events in case of an error InternalEnd(); switch(status) { case WAIT_FAILED: WsbTraceAlways(OLESTR("CRssJetWriter::OnFreezeBegin: Wait for Multiple Objects returned error %lu\n"), errWait); WsbThrow(HRESULT_FROM_WIN32(errWait)); break; case WAIT_TIMEOUT: // Timeout means that one of the sync components is taking too long WsbTraceAlways(OLESTR("CRssJetWriter::OnFreezeBegin: Wait for Multiple Objects timed out after %lu ms\n"), EVENT_WAIT_TIMEOUT); WsbThrow(VSS_E_WRITERERROR_TIMEOUT); break; default: WsbTraceAlways(OLESTR("CRssJetWriter::OnFreezeBegin: Wait for Multiple Objects returned unexpected status %lu\n"), status); WsbThrow(E_UNEXPECTED); break; } } } WsbCatch(hr); if (S_OK == hr) { bRet = CVssJetWriter::OnFreezeBegin(); } else { bRet = false; } WsbTraceOut(OLESTR("CRssJetWriter::OnFreezeBegin"), OLESTR("hr = <%ls> , bRet = <%ls>"), WsbHrAsString(hr), WsbBoolAsString(bRet)); return bRet; } bool STDMETHODCALLTYPE CRssJetWriter::OnThawEnd(IN bool fJetThawSucceeded) /*++ Routine Description: Handles Thaw End event Arguments: fJetThawSucceeded - Ignored Return Value: TRUE - Success FALSE - Failure --*/ { bool bRet; WsbTraceIn(OLESTR("CRssJetWriter::OnThawEnd"), OLESTR("")); // Return value is determined by base class, ignore internal errors here bRet = CVssJetWriter::OnThawEnd(fJetThawSucceeded); // Release all waiting events InternalEnd(); WsbTraceOut(OLESTR("CRssJetWriter::OnThawEnd"), OLESTR("bRet = <%ls>"), WsbBoolAsString(bRet)); return bRet; } void STDMETHODCALLTYPE CRssJetWriter::OnAbortEnd() /*++ Routine Description: Handles Abort End event Arguments: None Return Value: None --*/ { WsbTraceIn(OLESTR("CRssJetWriter::OnAbortEnd"), OLESTR("")); // Call base class imp. CVssJetWriter::OnAbortEnd(); // Release all waiting events InternalEnd(); WsbTraceOut(OLESTR("CRssJetWriter::OnAbortEnd"), OLESTR("")); }
26.875
148
0.57987
[ "object" ]
ddbfba77702a3263579f8aebffbd424c5be302ae
6,223
cpp
C++
Source/SystemQOR/MSWindows/WinQL/MediaFoundation/WinQLMediaSink.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/SystemQOR/MSWindows/WinQL/MediaFoundation/WinQLMediaSink.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/SystemQOR/MSWindows/WinQL/MediaFoundation/WinQLMediaSink.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//WinQLMediaSink.cpp // Copyright Querysoft Limited 2013, 2015 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #include "WinQL/CodeServices/WinQLPolicy.h" #include "WinQL/Application/Threading/WinQLCriticalSection.h" #include "WinQL/MediaFoundation/MediaSink.h" #include "WinQAPI/MedFoundAPI.h" //-------------------------------------------------------------------------------- namespace nsWin32 { //-------------------------------------------------------------------------------- namespace nsMediaFoundation { __QOR_IMPLEMENT_OCLASS_LUID( CMediaSink ); //-------------------------------------------------------------------------------- CMediaSink::CMediaSink() { _WINQ_FCONTEXT( "CMediaSink::CMediaSink" ); m_ulStatus = 0; } //-------------------------------------------------------------------------------- CMediaSink::~CMediaSink() { _WINQ_FCONTEXT( "CMediaSink::~CMediaSink" ); } //-------------------------------------------------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CASFMediaSink ); //-------------------------------------------------------------------------------- CASFMediaSink::CASFMediaSink( IMFByteStream* pIByteStream ) : CMediaSink() { _WINQ_FCONTEXT( "CASFMediaSink::CASFMediaSink" ); m_ulStatus = m_MFLibrary.MFCreateASFMediaSink( reinterpret_cast< ::IMFByteStream* >( pIByteStream ), reinterpret_cast< ::IMFMediaSink** >( &m_p ) ); } //-------------------------------------------------------------------------------- CASFMediaSink::~CASFMediaSink() { _WINQ_FCONTEXT( "CASFMediaSink::~CASFMediaSink" ); } //-------------------------------------------------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CMP3MediaSink ); //-------------------------------------------------------------------------------- CMP3MediaSink::CMP3MediaSink( IMFByteStream* pTargetByteStream ) : CMediaSink() { _WINQ_FCONTEXT( "CMP3MediaSink::CMP3MediaSink" ); m_ulStatus = m_MFLibrary.MFCreateMP3MediaSink( reinterpret_cast< ::IMFByteStream* >( pTargetByteStream ), reinterpret_cast< ::IMFMediaSink** >( &m_p ) ); } //-------------------------------------------------------------------------------- CMP3MediaSink::~CMP3MediaSink() { _WINQ_FCONTEXT( "CMP3MediaSink::~CMP3MediaSink" ); } //-------------------------------------------------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CMP4MediaSink ); //-------------------------------------------------------------------------------- CMP4MediaSink::CMP4MediaSink( IMFByteStream* pIByteStream, IMFMediaType* pVideoMediaType, IMFMediaType* pAudioMediaType ) : CMediaSink() { _WINQ_FCONTEXT( "CMP4MediaSink::CMP4MediaSink" ); m_ulStatus = m_MFLibrary.MFCreateMPEG4MediaSink( reinterpret_cast< ::IMFByteStream* >( pIByteStream ), reinterpret_cast< ::IMFMediaType* >( pVideoMediaType ), reinterpret_cast< ::IMFMediaType* >( pAudioMediaType ), reinterpret_cast< ::IMFMediaSink** >( &m_p ) ); } //-------------------------------------------------------------------------------- CMP4MediaSink::~CMP4MediaSink() { _WINQ_FCONTEXT( "CMP4MediaSink::~CMP4MediaSink" ); } //-------------------------------------------------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( C3GPMediaSink ); //-------------------------------------------------------------------------------- C3GPMediaSink::C3GPMediaSink( IMFByteStream* pIByteStream, IMFMediaType* pVideoMediaType, IMFMediaType* pAudioMediaType ) : CMediaSink() { _WINQ_FCONTEXT( "C3GPMediaSink::C3GPMediaSink" ); m_ulStatus = m_MFLibrary.MFCreate3GPMediaSink( reinterpret_cast< ::IMFByteStream* >( pIByteStream ), reinterpret_cast< ::IMFMediaType* >( pVideoMediaType ), reinterpret_cast< ::IMFMediaType* >( pAudioMediaType ), reinterpret_cast< ::IMFMediaSink** >( &m_p ) ); } //-------------------------------------------------------------------------------- C3GPMediaSink::~C3GPMediaSink() { _WINQ_FCONTEXT( "C3GPMediaSink::~C3GPMediaSink" ); } //-------------------------------------------------------------------------------- __QOR_IMPLEMENT_OCLASS_LUID( CASFStreamingMediaSink ); //-------------------------------------------------------------------------------- CASFStreamingMediaSink::CASFStreamingMediaSink( IMFByteStream* pIByteStream ) : CMediaSink() { _WINQ_FCONTEXT( "CASFStreamingMediaSink::CASFStreamingMediaSink" ); m_ulStatus = m_MFLibrary.MFCreateASFStreamingMediaSink( reinterpret_cast< ::IMFByteStream* >( pIByteStream ), reinterpret_cast< ::IMFMediaSink** >( &m_p ) ); } //-------------------------------------------------------------------------------- CASFStreamingMediaSink::~CASFStreamingMediaSink() { _WINQ_FCONTEXT( "CASFStreamingMediaSink::~CASFStreamingMediaSink" ); } }//nsMediaFoundation }//nsWin32
41.211921
138
0.553431
[ "object" ]
ddd2e4bd3e715a5970e1f1fd1b426eee38966f53
1,816
cpp
C++
src/Action.cpp
GT-RAIL/waypoint_planner
169d5eee23e000e78e75d019d6ed1d9a9600ef04
[ "BSD-3-Clause" ]
2
2018-12-05T21:48:05.000Z
2020-08-19T09:29:10.000Z
src/Action.cpp
GT-RAIL/waypoint_planner
169d5eee23e000e78e75d019d6ed1d9a9600ef04
[ "BSD-3-Clause" ]
null
null
null
src/Action.cpp
GT-RAIL/waypoint_planner
169d5eee23e000e78e75d019d6ed1d9a9600ef04
[ "BSD-3-Clause" ]
2
2019-07-22T11:37:57.000Z
2021-08-01T17:30:05.000Z
#include "waypoint_planner/Action.h" const uint8_t Action::OBSERVE = 0; const uint8_t Action::MOVE = 1; const uint8_t Action::PERCH = 2; const uint8_t Action::UNPERCH = 3; using std::vector; Action::Action(uint8_t action_type) { this->action_type = action_type; } Action::Action(uint8_t action_type, geometry_msgs::Point action_goal) { this->action_type = action_type; this->action_goal = action_goal; } void Action::setActionType(uint8_t action_type) { this->action_type = action_type; } void Action::setGoal(geometry_msgs::Point action_goal) { this->action_goal = action_goal; } uint8_t Action::actionType() { return action_type; } geometry_msgs::Point Action::actionGoal() { return action_goal; } void Action::duration(geometry_msgs::Point s1, geometry_msgs::Point s2, vector<double> &durations, vector<double> &probabilities) { if (action_type == OBSERVE) { durations.push_back(2.0); probabilities.push_back(1.0); } else if (action_type == PERCH || action_type == UNPERCH) { durations.push_back(2.0); probabilities.push_back(1.0); } else { // planning + execution time calculation, assuming the robot moves at .75 m/s on average double base_planning_time = 2.0; double base_travel_time = sqrt(pow(s1.x - s2.x, 2) + pow(s1.y - s2.y, 2) + pow(s1.z - s2.z, 2)) / .75; double discretization = 0.1; double scale_lower_bound = 1.0; double scale_upper_bound = 1.5; int steps = static_cast<int>((scale_upper_bound - scale_lower_bound)/discretization) + 1; double uniform_probability = 1.0/static_cast<double>(steps); for (int i = 0; i < steps; i ++) { durations.push_back(base_planning_time + (scale_lower_bound + i*discretization)*base_travel_time); probabilities.push_back(uniform_probability); } } }
25.577465
106
0.704846
[ "vector" ]
ddd92ea76fa00012d4153e9085cb7cc4420b456c
1,554
cpp
C++
src/main.cpp
istvan-vonfedak/lambda-calculus-interpreter
8da5137ae329285a425f29a29f82c4f75af17962
[ "MIT" ]
null
null
null
src/main.cpp
istvan-vonfedak/lambda-calculus-interpreter
8da5137ae329285a425f29a29f82c4f75af17962
[ "MIT" ]
null
null
null
src/main.cpp
istvan-vonfedak/lambda-calculus-interpreter
8da5137ae329285a425f29a29f82c4f75af17962
[ "MIT" ]
null
null
null
#include "betaReducer.hpp" int main(int argc, char * argv[]) { const bool printDebug = (argc > 1)? true : false; std::cout<<"- Type exit to quit program.\n"; while(true) { // input string that stores line that is read in std::string in; std::cout<<"\n input: "; getline(std::cin,in); if(in == "exit") break; if(printDebug) std::cout<<"\n------------------------\n\n"; if(printDebug) std::cout<<"Lexical Analizer Output:\n\n"; // string vector that stores the result of the lexical analizer std::vector<std::string> tokens; // perform the lexical analysis lexicalAnalyser(in, tokens); // print the output if(printDebug) { for(int i = 0; i < tokens.size(); i++) std::cout<<tokens[i]<<std::endl; } if(printDebug) std::cout<<"\n------------------------\n\n"; if(printDebug) std::cout<<"Parser Output:\n\n"; // parse the data using the string tokens Lambda * ptr = parser(tokens); // print the result if(printDebug) printSimple(ptr); if(printDebug) std::cout<<"\n------------------------\n\n"; if(printDebug) std::cout<<"Beta Reduction Output:\n\n"; // perform the recursive beta reduction Lambda * result = betaReducer(ptr); std::cout<<"output: "; printSimple(result); std::cout<<"\n"; if(printDebug) std::cout<<"------------------------\n\n"; // clean up to avoid memory leaks delete ptr; delete result; tokens.clear(); in.clear(); } return 0; }
29.884615
68
0.550193
[ "vector" ]
50b341fa4656044acd1ec28ac412137a8b2705be
10,951
cpp
C++
wisdom/sentinel/haspfeature.cpp
chenghuaiyu/caffe
b16e30408a8c26c1bb72b807ae04f81c7389869c
[ "BSD-2-Clause" ]
1
2020-01-18T16:44:03.000Z
2020-01-18T16:44:03.000Z
wisdom/sentinel/haspfeature.cpp
chenghuaiyu/caffe
b16e30408a8c26c1bb72b807ae04f81c7389869c
[ "BSD-2-Clause" ]
null
null
null
wisdom/sentinel/haspfeature.cpp
chenghuaiyu/caffe
b16e30408a8c26c1bb72b807ae04f81c7389869c
[ "BSD-2-Clause" ]
null
null
null
//////////////////////////////////////////////////////////////////// // Copyright (C) 2011, SafeNet, Inc. All rights reserved. // // HASP(R) is a registered trademark of SafeNet, Inc. // // // //////////////////////////////////////////////////////////////////// #include "hasp_api_cpp_.h" //////////////////////////////////////////////////////////////////// //! \mainpage Overview //! //! This document describes Sentinel HASP high layer API. //! //! \section __helpers__ Helper Classes //! //! For the sake of convenience several helper classes are //! implemented. These allow a more flexible access to certain //! parameters required by the low level API. //! //! \subsection __ChaspFeature__ The ChaspFeature Class //! //! The ChaspFeature class encapsulates a feature identifier of a //! HASP protection key feature. //! //! \subsection __ChaspTime__ The ChaspTime Class //! //! This class encapsulates the date/time functionality provided //! by a HASP protection key. //! //! \subsection __ChaspHandle__ The ChaspHandle Class //! //! This class is used internally by the ChaspBase class. ChaspHandle //! holds the the index into the Chasp - ChaspImpl map and some //! state informations in addition. A unique usage counter of the //! the index in the map and a logout counter is used to check if a //! logout occured. //! //! \section __key__ The Key Classes //! //! This section describes the classes for accessing a Hasp protection //! key. //! The basic concept of the implementation is to provide a private //! class implementing all methods for accessing a Hasp protection key //! via the low level API. The access to this class is controlled via //! a helper mapping class maintaining a lock mechanism, which //! permits the access to the private class from different threads. //! The design of the public interface is straight foreward. //! Main concept is to provide classes, which just act as wrappers. //! The advantage of this design is, that these classes can be //! easily replaced (i.e. for implementing a .net assembly or a //! COM interface). //! The Base of these classes is the ChaspBase class. //! The implementation of this class is pure virtual. Main purpose //! of it is to maintain the mapping to the private key class. //! //! \subsection __ChaspBase__ The ChaspBase Class //! //! This is a pure virtual class. No instance shall ever directly //! be created from this class. Purpose of this class is to provide //! methods for creating a, attaching to and detaching from a //! private key object via the map object. //! //! \subsection __Chasp__ The Chasp class //! //! The Chasp class represents the main public class. Through //! this class a Hasp protection key can be accessed. There //! can be any number of instances referencing the same //! Hasp protection key. //! //! In addition this class provides the methods for gaining access //! to the Hasp key's file operation class \ref ChaspFile and the //! legacy class \ref ChaspLegacy //! (for old Hasp4 compatible actions). //! //! \subsection __ChaspFile__ The ChaspFile class //! //! The ChaspFile class is used for file i/o operations on a //! Hasp protection key. Objects of this class are instantiated via //! the Chasp class. //! //! //! \subsection __ChaspLegacy__ The ChaspLegacy class //! //! The ChaspLegacy class is used to get access to the legacy //! functions of a Hasp4. Objects of this class are instatiated //! via the Chasp class. //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// //! \struct ChaspFeature hasp_api_cpp.h //! \brief Class holding a Hasp key feature id. //! //! The ChaspFeature class holds the feature identifier of a Hasp //! key. Furthermore methods are implemented allowing the feature //! to be manipulated. Through the static method //! \ref fromProgramNumber an old Hasp4 program number (FAS) can be //! converted into a Hasp key feature. //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// // Construction/Destruction //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// //! Constructs a ChaspFeature object with the feature identifier //! \a ulFeature. //////////////////////////////////////////////////////////////////// ChaspFeature::ChaspFeature(hasp_u32_t ulFeature) : m_ulFeature(ulFeature) { } //////////////////////////////////////////////////////////////////// //! Destroys the object. //////////////////////////////////////////////////////////////////// ChaspFeature::~ChaspFeature() { } //////////////////////////////////////////////////////////////////// // Implementation //////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////// ChaspFeature ChaspFeature::defaultFeature() { return ChaspFeature(HASP_DEFAULT_FID); } //////////////////////////////////////////////////////////////////// //! Returns the feature identifier. //////////////////////////////////////////////////////////////////// hasp_u32_t ChaspFeature::feature() const { return m_ulFeature; } //////////////////////////////////////////////////////////////////// //! Special operator enabling the ChaspFeature to behave like a //! \a hasp_u32_t primitive type. //////////////////////////////////////////////////////////////////// ChaspFeature::operator hasp_feature_t() const { return m_ulFeature; } //////////////////////////////////////////////////////////////////// //! Strips the options from a classic Hasp protection key feature, //! else does nothing. //////////////////////////////////////////////////////////////////// hasp_u32_t ChaspFeature::featureId() const { return isProgNum() ? m_ulFeature & ~HASP_PROGNUM_OPT_MASK : m_ulFeature; } //////////////////////////////////////////////////////////////////// //! Creates and returns a ChaspFeature instance based on a //! feature id //! //! \param ulFeature The feature id to be used //! \return A ChaspFeature class //! If the feature is a program number //! the default feature will be returned //////////////////////////////////////////////////////////////////// ChaspFeature ChaspFeature::fromFeature(hasp_u32_t ulFeature) { if (HASP_PROGNUM_FEATURETYPE == (ulFeature & HASP_FEATURETYPE_MASK)) return ChaspFeature::defaultFeature(); return ChaspFeature(ulFeature); } //////////////////////////////////////////////////////////////////// //! Converts an old Hasp4 program number (FAS) into a Hasp protection //! key compliant feature identifier. //! //! \param ulProgNumber The Hasp4 program number to //! be converted. //! \return A feature class for a Hasp4 program //! number. //////////////////////////////////////////////////////////////////// ChaspFeature ChaspFeature::fromProgNum(hasp_u32_t ulProgNum) { ulProgNum &= HASP_PROGNUM_MASK; return ChaspFeature(HASP_PROGNUM_FEATURETYPE|ulProgNum); } //////////////////////////////////////////////////////////////////// //! Returns the set options of a legacy Hasp4 feature. //////////////////////////////////////////////////////////////////// hasp_u32_t ChaspFeature::getOptions() const { return isProgNum() ? m_ulFeature & HASP_PROGNUM_OPT_MASK : optDefault; } //////////////////////////////////////////////////////////////////// //! Returs whether the option \a ulOption is present in the feature. //! //! \note This method is only applicable for //! Hasp4 features. For Hasp protection //! key features the method always returns //! \a false. //////////////////////////////////////////////////////////////////// bool ChaspFeature::hasOption(hasp_u32_t ulOption) const { if (!isProgNum()) return optDefault == ulOption; hasp_u32_t ulOptions = m_ulFeature & HASP_PROGNUM_OPT_MASK; return (optDefault == ulOption) ? (optDefault == ulOptions) : (ulOption == (ulOptions & ulOption)); } //////////////////////////////////////////////////////////////////// //! Returns \a true if the feature is the default HASP key or the //! default classic feature. //////////////////////////////////////////////////////////////////// bool ChaspFeature::isDefault() const { return featureId() == static_cast<hasp_u32_t>(isProgNum() ? HASP_PROGNUM_DEFAULT_FID : HASP_DEFAULT_FID); } //////////////////////////////////////////////////////////////////// //! Returns \a true if the feature is a classic Hasp4 feature. //////////////////////////////////////////////////////////////////// bool ChaspFeature::isProgNum() const { return HASP_PROGNUM_FEATURETYPE == (m_ulFeature & HASP_FEATURETYPE_MASK); } //////////////////////////////////////////////////////////////////// //! //////////////////////////////////////////////////////////////////// ChaspFeature ChaspFeature::progNumDefault() { return ChaspFeature(HASP_PROGNUM_DEFAULT_FID); } //////////////////////////////////////////////////////////////////// //! Sets or removes options for a classic Hasp4 feature. //! //! \param ulAdd The options to be added. //! \param ulRemove The options to be removed. //! //! \return \a true on success, \a false //! otherwise. //! //! \note The method always returns \a false //! if the feature is HASP protection key feature. //////////////////////////////////////////////////////////////////// bool ChaspFeature::setOptions(hasp_u32_t ulAdd, hasp_u32_t ulRemove) { if (!isProgNum()) return false; if (optNotRemote == (ulAdd & optNotRemote)) { ulAdd &= ~optNotLocal; ulRemove |= optNotLocal; } if (optNotLocal == (ulAdd & optNotLocal)) { ulAdd &= ~optNotRemote; ulRemove |= optNotRemote; } m_ulFeature |= ulAdd & HASP_PROGNUM_OPT_MASK; m_ulFeature &= ~(ulRemove & HASP_PROGNUM_OPT_MASK); return true; } //////////////////////////////////////////////////////////////////// //! Returns the feature identifier as a human readable string. //////////////////////////////////////////////////////////////////// std::string ChaspFeature::toString() const { std::ostringstream stream; stream << m_ulFeature; return std::string(stream.str()); }
38.424561
78
0.502511
[ "object" ]
50b81a731176dc1d5b2c1146e522006a8bccdb4c
2,560
cc
C++
gcj/2013/round_qulification_b.cc
neutronest/goodgoodstudy
34e03912a285cdfff249872a3aecf41c6a45c446
[ "MIT" ]
null
null
null
gcj/2013/round_qulification_b.cc
neutronest/goodgoodstudy
34e03912a285cdfff249872a3aecf41c6a45c446
[ "MIT" ]
null
null
null
gcj/2013/round_qulification_b.cc
neutronest/goodgoodstudy
34e03912a285cdfff249872a3aecf41c6a45c446
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <vector> #include <string> using namespace std; class Solution { public: bool solve(int rows, int cols, vector<vector<int>> mat) { vector<vector<int>> oriMat(rows, vector<int>(cols, 100)); int maxVal = -1; for (auto r = 0; r < rows; r++) { maxVal = -1; for(auto i=0; i<cols; i++) { if (maxVal < mat[r][i]) { maxVal = mat[r][i]; } } for(auto i=0; i<cols; i++) { if (oriMat[r][i] > maxVal) { oriMat[r][i] = maxVal; } } } for (auto c = 0; c < cols; c++) { maxVal = -1; for(auto i=0; i<rows; i++) { if (maxVal < mat[i][c]) { maxVal = mat[i][c]; } } for(auto i=0; i<rows; i++) { if (oriMat[i][c] > maxVal) { oriMat[i][c] = maxVal; } } } for (auto i=0; i<rows; i++) { for(auto j=0; j<cols; j++) { if (oriMat[i][j] != mat[i][j]) { return false; } } } return true; } bool isValid(int r, int c, vector<vector<int>> mat) { int rows = mat.size(); int cols = mat[0].size(); vector<int> neibourHeights; // check up value if exists if (r > 0) { neibourHeights.push_back(mat[r-1][c]); } // check down value if exists if (r < rows-1) { neibourHeights.push_back(mat[r+1][c]); } // check left value is exists if (c > 0) { neibourHeights.push_back(mat[r][c-1]); } if (c < cols-1) { neibourHeights.push_back(mat[r][c+1]); } int biggerAcc = 0; for (auto i=0; i < neibourHeights.size(); i++) { if (mat[r][c] > neibourHeights[i]) { biggerAcc += 1; } } return biggerAcc > 0; } }; int main() { int T; int n, m; int case_idx = 0; int h; vector<vector<int>> mat; Solution solution = Solution(); cin>>T; while (case_idx < T) { mat.clear(); cin>>n>>m; for(auto i=0; i<n; i++) { vector<int> temp; for(auto j=0; j<m; j++) { cin>>h; temp.push_back(h); } mat.push_back(temp); } bool res = solution.solve(n, m, mat); if (res) { cout<<"Case #"<<(case_idx+1)<<": YES"<<endl; } else { cout<<"Case #"<<(case_idx+1)<<": NO"<<endl; } case_idx += 1; } }
22.45614
61
0.433203
[ "vector" ]
50be1bcd82451fc1c42959bc99a8a47f226119e4
3,569
hpp
C++
include/dds/core/InstanceHandle.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
575
2015-01-22T20:05:04.000Z
2020-06-01T10:06:12.000Z
include/dds/core/InstanceHandle.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
1,110
2015-04-20T19:30:34.000Z
2020-06-01T08:13:52.000Z
include/dds/core/InstanceHandle.hpp
jason-fox/Fast-RTPS
af466cfe63a8319cc9d37514267de8952627a9a4
[ "Apache-2.0" ]
273
2015-08-10T23:34:42.000Z
2020-05-28T13:03:32.000Z
/* * Copyright 2010, Object Management Group, Inc. * Copyright 2010, PrismTech, Corp. * Copyright 2010, Real-Time Innovations, Inc. * Copyright 2019, Proyectos y Sistemas de Mantenimiento SL (eProsima). * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef OMG_DDS_CORE_INSTANCE_HANDLE_HPP_ #define OMG_DDS_CORE_INSTANCE_HANDLE_HPP_ #include <vector> #include <iostream> #include <dds/core/types.hpp> #include <dds/core/Value.hpp> #include <dds/core/detail/InstanceHandle.hpp> namespace dds { namespace core { /** * @brief * Class to hold the handle associated with in sample instance. */ class InstanceHandle : public Value<detail::InstanceHandle> { public: /** * Create an nil instance handle. */ OMG_DDS_API InstanceHandle(); /** * Create an nil instance handle. * * @param nullHandle placeholder */ OMG_DDS_API InstanceHandle( const null_type& nullHandle); /** * Copy an existing InstancHandle * * @param other InstanceHandle to copy */ OMG_DDS_API InstanceHandle( const InstanceHandle& other); /** @cond */ OMG_DDS_API ~InstanceHandle(); /** @endcond */ /** * @cond * Parametric constructor for creating an instance-handle * from some other type. This function is intended for internal * usage. */ OMG_DDS_API InstanceHandle( const detail::InstanceHandle& arg0); /** @endcond */ public: /** * Assign an existing InstancHandle to this InstancHandle * * @param that The InstanceHandle to assign to this */ OMG_DDS_API InstanceHandle& operator =( const InstanceHandle& that); /** * Compare this InstanceHandle to another InstanceHandle * * @param that The InstanceHandle to compare * @return true if they match */ OMG_DDS_API bool operator ==( const InstanceHandle& that) const; /** * Compare this InstanceHandle to another InstanceHandle * * @param that The InstanceHandle to compare * @return true if this is less than that */ OMG_DDS_API bool operator <( const InstanceHandle& that) const; /** * Compare this InstanceHandle to another InstanceHandle * * @param that The InstanceHandle to compare * @return true if this is greater than that */ OMG_DDS_API bool operator >( const InstanceHandle& that) const; public: /** * Create an nil instance handle. * * @return a nil InstanceHandle */ OMG_DDS_API static const InstanceHandle nil(); /** * Check if the InstanceHandle is nil. * * @return true if the InstanceHandle is nil */ OMG_DDS_API bool is_nil() const; }; typedef std::vector<InstanceHandle> InstanceHandleSeq; } //namespace core } //namespace dds inline std::ostream& operator <<( std::ostream& os, const dds::core::InstanceHandle& h); #endif //OMG_DDS_CORE_INSTANCE_HANDLE_HPP_
24.784722
75
0.66181
[ "object", "vector" ]
50d50b5aba21925c6b8bb343550b32ef069d785e
89,693
cpp
C++
production/libs/fog/Fog/Src/Fog/G2d/Imaging/Codecs/GifCodec.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
production/libs/fog/Fog/Src/Fog/G2d/Imaging/Codecs/GifCodec.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
production/libs/fog/Fog/Src/Fog/G2d/Imaging/Codecs/GifCodec.cpp
Lewerow/DetailIdentifier
bd5e0b3b55b5ce5b24db51ae45ed53298d331687
[ "MIT" ]
null
null
null
// [Fog-G2d] // // [License] // MIT, See COPYING file in package #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif // _MSC_VER // [Precompiled Headers] #if defined(FOG_PRECOMP) #include FOG_PRECOMP #endif // FOG_PRECOMP // [Dependencies] #include <Fog/Core/Global/Init_p.h> #include <Fog/Core/Math/Math.h> #include <Fog/Core/Memory/MemOps.h> #include <Fog/Core/Tools/InternedString.h> #include <Fog/Core/Tools/Stream.h> #include <Fog/Core/Tools/String.h> #include <Fog/G2d/Imaging/Image.h> #include <Fog/G2d/Imaging/ImageCodec.h> #include <Fog/G2d/Imaging/ImageCodecProvider.h> #include <Fog/G2d/Imaging/ImageConverter.h> #include <Fog/G2d/Imaging/ImageDecoder.h> #include <Fog/G2d/Imaging/ImageEncoder.h> #include <string.h> // [giflib] /****************************************************************************** * "Gif-Lib" - Yet another gif library. * * Written by: Gershon Elber IBM PC Ver 1.1, Aug. 1990 ****************************************************************************** * The kernel of the GIF Decoding process can be found here. ****************************************************************************** * History: * 16 Jun 89 - Version 1.0 by Gershon Elber. * 3 Sep 90 - Version 1.1 by Gershon Elber (Support for Gif89, Unique names). *****************************************************************************/ // The GIFLIB distribution is Copyright (c) 1997 Eric S. Raymond // // 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. // [giflib hash table] int _GifError; #define HT_SIZE 8192 // 12bits = 4096 or twice as big! #define HT_KEY_MASK 0x1FFF // 13bits keys. #define HT_KEY_NUM_BITS 13 // 13bits keys. #define HT_MAX_KEY 8191 // 13bits - 1, maximal code possible. #define HT_MAX_CODE 4095 // Biggest code possible in 12 bits. // The 32 bits of the long are divided into two parts for the key & code: // 1. The code is 12 bits as our compression algorithm is limited to 12bits // 2. The key is 12 bits Prefix code + 8 bit new char or 20 bits. // The key is the upper 20 bits. The code is the lower 12. #define HT_GET_KEY(l) (l >> 12) #define HT_GET_CODE(l) (l & 0x0FFF) #define HT_PUT_KEY(l) (l << 12) #define HT_PUT_CODE(l) (l & 0x0FFF) struct GifHashTableType { uint32_t HTable[HT_SIZE]; }; static GifHashTableType *_InitHashTable(void); static void _ClearHashTable(GifHashTableType *HashTable); static void _InsertHashTable(GifHashTableType *HashTable, uint32_t Key, int Code); static int _ExistsHashTable(GifHashTableType *HashTable, uint32_t Key); static int KeyItem(uint32_t Item); // Initialize HashTable - allocate the memory needed and clear it. static GifHashTableType *_InitHashTable(void) { GifHashTableType *HashTable; if ((HashTable = (GifHashTableType *) Fog::MemMgr::alloc(sizeof(GifHashTableType))) == NULL) { return NULL; } _ClearHashTable(HashTable); return HashTable; } // Routine to clear the HashTable to an empty state. // This part is a little machine depended. Use the commented part otherwise. static void _ClearHashTable(GifHashTableType *HashTable) { memset(HashTable -> HTable, 0xFF, HT_SIZE * sizeof(uint32_t)); } // Routine to insert a new Item into the HashTable. The data is assumed to be // new one. static void _InsertHashTable(GifHashTableType *HashTable, uint32_t Key, int Code) { int HKey = KeyItem(Key); uint32_t *HTable = HashTable -> HTable; while (HT_GET_KEY(HTable[HKey]) != 0xFFFFFL) { HKey = (HKey + 1) & HT_KEY_MASK; } HTable[HKey] = HT_PUT_KEY(Key) | HT_PUT_CODE(Code); } // Routine to test if given Key exists in HashTable and if so returns its code // Returns the Code if key was found, -1 if not. static int _ExistsHashTable(GifHashTableType *HashTable, uint32_t Key) { int HKey = KeyItem(Key); uint32_t *HTable = HashTable -> HTable, HTKey; while ((HTKey = HT_GET_KEY(HTable[HKey])) != 0xFFFFFL) { if (Key == HTKey) return HT_GET_CODE(HTable[HKey]); HKey = (HKey + 1) & HT_KEY_MASK; } return -1; } // Routine to generate an HKey for the hashtable out of the given unique key. // The given Key is assumed to be 20 bits as follows: lower 8 bits are the // new postfix character, while the upper 12 bits are the prefix code. // Because the average hit ratio is only 2 (2 hash references per entry), // evaluating more complex keys (such as twin prime keys) does not worth it! static int KeyItem(uint32_t item) { return ((item >> 12) ^ item) & HT_KEY_MASK; } // [giflib - header] #define GIF_ERROR 0 #define GIF_OK 1 #define GIF_STAMP "GIFVER" /* First chars in file - GIF stamp. */ #define GIF_STAMP_LEN (sizeof(GIF_STAMP) - 1) #define GIF_VERSION_POS 3 /* Version first character in stamp. */ #define GIF87_STAMP "GIF87a" /* First chars in file - GIF stamp. */ #define GIF89_STAMP "GIF89a" /* First chars in file - GIF stamp. */ #define GIF_FILE_BUFFER_SIZE 16384 /* Files uses bigger buffers than usual. */ // GIF89 extension function codes #define COMMENT_EXT_FUNC_CODE 0xfe /* comment */ #define GRAPHICS_EXT_FUNC_CODE 0xf9 /* graphics control */ #define PLAINTEXT_EXT_FUNC_CODE 0x01 /* plaintext */ #define APPLICATION_EXT_FUNC_CODE 0xff /* application block */ #define LZ_MAX_CODE 4095 /* Biggest code possible in 12 bits. */ #define LZ_BITS 12 #define FLUSH_OUTPUT 4096 /* Impossible code, to signal flush. */ #define FIRST_CODE 4097 /* Impossible code, to signal first. */ #define NO_SUCH_CODE 4098 /* Impossible code, to signal empty. */ #define FILE_STATE_WRITE 0x01 #define FILE_STATE_SCREEN 0x02 #define FILE_STATE_IMAGE 0x04 #define FILE_STATE_READ 0x08 #define IS_READABLE(GifFile) (GifFile->FileState & FILE_STATE_READ) #define IS_WRITEABLE(GifFile) (GifFile->FileState & FILE_STATE_WRITE) typedef int GifBooleanType; typedef uint8_t GifPixelType; typedef uint8_t *GifRowType; typedef uint16_t GifPrefixType; typedef int GifWord; #include <Fog/Core/C++/PackByte.h> struct GifColorType { uint8_t Red; uint8_t Green; uint8_t Blue; }; #include <Fog/Core/C++/PackRestore.h> struct ColorMapObject { int ColorCount; int BitsPerPixel; GifColorType *Colors; /* allocated on the heap */ }; struct GifImageDesc { GifWord Left; /* Current image dimensions. */ GifWord Top; GifWord Width; GifWord Height; GifWord Interlace; /* Sequential/Interlaced lines. */ ColorMapObject *ColorMap; /* The local color map */ }; /* This is the in-core version of an extension record */ struct ExtensionBlock { int ByteCount; char *Bytes; /* on heap */ int Function; /* Holds the type of the Extension block. */ }; /* This holds an image header, its unpacked raster bits, and extensions */ struct SavedImage { GifImageDesc ImageDesc; unsigned char *RasterBits; /* on heap */ int Function; /* DEPRECATED: Use ExtensionBlocks[x].Function instead */ int ExtensionBlockCount; ExtensionBlock *ExtensionBlocks; /* on heap */ }; enum GifRecordType { UNDEFINED_RECORD_TYPE, SCREEN_DESC_RECORD_TYPE, IMAGE_DESC_RECORD_TYPE, /* Begin with ',' */ EXTENSION_RECORD_TYPE, /* Begin with '!' */ TERMINATE_RECORD_TYPE /* Begin with ';' */ }; struct GifFileType { GifWord SWidth; GifWord SHeight; /* Screen dimensions. */ GifWord SColorResolution; /* How many colors can we generate? */ GifWord SBackGroundColor; /* I hope you understand this one... */ ColorMapObject *SColorMap; /* NULL if not exists. */ int ImageCount; /* Number of current image */ GifImageDesc Image; /* Block describing current image */ SavedImage *SavedImages; /* Use this to accumulate file state */ // Private members Fog::Stream* stream; GifWord FileState; /* Where all this data goes to! */ GifWord BitsPerPixel; /* Bits per pixel (Codes uses at least this + 1). */ GifWord ClearCode; /* The CLEAR LZ code. */ GifWord EOFCode; /* The EOF LZ code. */ GifWord RunningCode; /* The next code algorithm can generate. */ GifWord RunningBits; /* The number of bits required to represent RunningCode. */ GifWord MaxCode1; /* 1 bigger than max. possible code, in RunningBits bits. */ GifWord LastCode; /* The code before the current code. */ GifWord CrntCode; /* Current algorithm code. */ GifWord StackPtr; /* For character stack (see below). */ GifWord CrntShiftState; /* Number of bits in CrntShiftDWord. */ unsigned long CrntShiftDWord;/* For bytes decomposition into codes. */ unsigned long PixelCount; /* Number of pixels in image. */ uint8_t Buf[256]; /* Compressed input is buffered here. */ uint8_t Stack[LZ_MAX_CODE]; /* Decoded pixels are stacked here. */ uint8_t Suffix[LZ_MAX_CODE + 1]; /* So we can trace the codes. */ GifPrefixType Prefix[LZ_MAX_CODE + 1]; GifHashTableType *HashTable; }; // [giflib function prototypes] static GifFileType *DGifOpen(Fog::Stream* stream); static int DGifGetScreenDesc(GifFileType * GifFile); static int DGifGetRecordType(GifFileType * GifFile, GifRecordType * GifType); static int DGifGetImageDesc(GifFileType * GifFile); static int DGifGetLine(GifFileType * GifFile, GifPixelType * GifLine, int GifLineLen); static int DGifGetPixel(GifFileType * GifFile, GifPixelType GifPixel); static int DGifGetExtension(GifFileType * GifFile, int *GifExtCode, uint8_t ** GifExtension); static int DGifGetExtensionNext(GifFileType * GifFile, uint8_t ** GifExtension); static int DGifGetCode(GifFileType * GifFile, int *GifCodeSize, uint8_t ** GifCodeBlock); static int DGifGetCodeNext(GifFileType * GifFile, uint8_t ** GifCodeBlock); static int DGifGetLZCodes(GifFileType * GifFile, int *GifCode); static int DGifCloseFile(GifFileType * GifFile); #define D_GIF_ERR_OPEN_FAILED 101 /* And DGif possible errors. */ #define D_GIF_ERR_READ_FAILED 102 #define D_GIF_ERR_NOT_GIF_FILE 103 #define D_GIF_ERR_NO_SCRN_DSCR 104 #define D_GIF_ERR_NO_IMAG_DSCR 105 #define D_GIF_ERR_NO_COLOR_MAP 106 #define D_GIF_ERR_WRONG_RECORD 107 #define D_GIF_ERR_DATA_TOO_BIG 108 #define D_GIF_ERR_NOT_ENOUGH_MEM 109 #define D_GIF_ERR_CLOSE_FAILED 110 #define D_GIF_ERR_NOT_READABLE 111 #define D_GIF_ERR_IMAGE_DEFECT 112 #define D_GIF_ERR_EOF_TOO_SOON 113 static GifFileType *EGifOpen(Fog::Stream* stream); static int EGifSpew(GifFileType * GifFile); static void EGifSetGifVersion(const char *Version); static int EGifPutScreenDesc(GifFileType * GifFile, int GifWidth, int GifHeight, int GifColorRes, int GifBackGround, const ColorMapObject * GifColorMap); static int EGifPutImageDesc(GifFileType * GifFile, int GifLeft, int GifTop, int Width, int GifHeight, int GifInterlace, const ColorMapObject * GifColorMap); static int EGifPutLine(GifFileType * GifFile, GifPixelType * GifLine, int GifLineLen); static int EGifPutPixel(GifFileType * GifFile, GifPixelType GifPixel); static int EGifPutComment(GifFileType * GifFile, const char *GifComment); static int EGifPutExtensionFirst(GifFileType * GifFile, int GifExtCode, int GifExtLen, const void* GifExtension); static int EGifPutExtensionNext(GifFileType * GifFile, int GifExtCode, int GifExtLen, const void* GifExtension); static int EGifPutExtensionLast(GifFileType * GifFile, int GifExtCode, int GifExtLen, const void* GifExtension); static int EGifPutExtension(GifFileType * GifFile, int GifExtCode, int GifExtLen, const void* GifExtension); static int EGifPutCode(GifFileType * GifFile, int GifCodeSize, const uint8_t * GifCodeBlock); static int EGifPutCodeNext(GifFileType * GifFile, const uint8_t * GifCodeBlock); static int EGifCloseFile(GifFileType * GifFile); #define E_GIF_ERR_OPEN_FAILED 1 /* And EGif possible errors. */ #define E_GIF_ERR_WRITE_FAILED 2 #define E_GIF_ERR_HAS_SCRN_DSCR 3 #define E_GIF_ERR_HAS_IMAG_DSCR 4 #define E_GIF_ERR_NO_COLOR_MAP 5 #define E_GIF_ERR_DATA_TOO_BIG 6 #define E_GIF_ERR_NOT_ENOUGH_MEM 7 #define E_GIF_ERR_DISK_IS_FULL 8 #define E_GIF_ERR_CLOSE_FAILED 9 #define E_GIF_ERR_NOT_WRITEABLE 10 static int QuantizeBuffer(unsigned int Width, unsigned int Height, int *ColorMapSize, uint8_t * RedInput, uint8_t * GreenInput, uint8_t * BlueInput, uint8_t * OutputBuffer, GifColorType * OutputColorMap); // Support for the in-core structures allocation (slurp mode). static void ApplyTranslation(SavedImage * Image, GifPixelType Translation[]); static void MakeExtension(SavedImage * New, int Function); static int AddExtensionBlock(SavedImage * New, int Len, unsigned char ExtData[]); static void FreeExtension(SavedImage * Image); static SavedImage *MakeSavedImage(GifFileType * GifFile, const SavedImage * CopyFrom); static void FreeSavedImages(GifFileType * GifFile); // Return smallest bitfield size n will fit in. static int BitSize(int n) { int i; for (i = 1; i <= 8; i++) if ((1 << i) >= n) break; return i; } // [giflib - ColorMap object functions] // Allocate a color map of given size; initialize with contents of // ColorMap if that pointer is non-NULL. static ColorMapObject *MakeMapObject(int ColorCount, const GifColorType * ColorMap) { ColorMapObject *Object; /*** FIXME: Our ColorCount has to be a power of two. Is it necessary to * make the user know that or should we automatically round up instead? */ if (ColorCount != (1 << BitSize(ColorCount))) return NULL; Object = (ColorMapObject *)Fog::MemMgr::alloc(sizeof(ColorMapObject)); if (Object == (ColorMapObject *) NULL) return NULL; Object->Colors = (GifColorType *)Fog::MemMgr::calloc(ColorCount * sizeof(GifColorType)); if (Object->Colors == (GifColorType *) NULL) return NULL; Object->ColorCount = ColorCount; Object->BitsPerPixel = BitSize(ColorCount); if (ColorMap) { memcpy((char *)Object->Colors, (char *)ColorMap, ColorCount * sizeof(GifColorType)); } return (Object); } // Free a color map object static void FreeMapObject(ColorMapObject * Object) { if (Object != NULL) { Fog::MemMgr::free(Object->Colors); Fog::MemMgr::free(Object); /*** FIXME: * When we are willing to break API we need to make this function * FreeMapObject(ColorMapObject **Object) * and do this assignment to NULL here: * *Object = NULL; */ } } // Compute the union of two given color maps and return it. If result can't // fit into 256 colors, NULL is returned, the allocated union otherwise. // ColorIn1 is copied as is to ColorUnion, while colors from ColorIn2 are // copied iff they didn't exist before. ColorTransIn2 maps the old // ColorIn2 into ColorUnion color map table. static ColorMapObject *UnionColorMap( const ColorMapObject * ColorIn1, const ColorMapObject * ColorIn2, GifPixelType ColorTransIn2[]) { int i, j, CrntSlot, RoundUpTo, NewBitSize; ColorMapObject *ColorUnion; /* * Allocate table which will hold the result for sure. */ ColorUnion = MakeMapObject(Fog::Math::max(ColorIn1->ColorCount, ColorIn2->ColorCount) * 2, NULL); if (ColorUnion == NULL) return (NULL); /* Copy ColorIn1 to ColorUnionSize; */ /*** FIXME: What if there are duplicate entries into the colormap to begin * with? */ for (i = 0; i < ColorIn1->ColorCount; i++) ColorUnion->Colors[i] = ColorIn1->Colors[i]; CrntSlot = ColorIn1->ColorCount; /* * Potentially obnoxious hack: * * Back CrntSlot down past all contiguous {0, 0, 0} slots at the end * of table 1. This is very useful if your display is limited to * 16 colors. */ while (ColorIn1->Colors[CrntSlot - 1].Red == 0 && ColorIn1->Colors[CrntSlot - 1].Green == 0 && ColorIn1->Colors[CrntSlot - 1].Blue == 0) CrntSlot--; /* Copy ColorIn2 to ColorUnionSize (use old colors if they exist): */ for (i = 0; i < ColorIn2->ColorCount && CrntSlot <= 256; i++) { /* Let's see if this color already exists: */ /*** FIXME: Will it ever occur that ColorIn2 will contain duplicate * entries? So we should search from 0 to CrntSlot rather than * ColorIn1->ColorCount? */ for (j = 0; j < ColorIn1->ColorCount; j++) if (memcmp (&ColorIn1->Colors[j], &ColorIn2->Colors[i], sizeof(GifColorType)) == 0) break; if (j < ColorIn1->ColorCount) ColorTransIn2[i] = j; /* color exists in Color1 */ else { /* Color is new - copy it to a new slot: */ ColorUnion->Colors[CrntSlot] = ColorIn2->Colors[i]; ColorTransIn2[i] = CrntSlot++; } } if (CrntSlot > 256) { FreeMapObject(ColorUnion); return ((ColorMapObject *) NULL); } NewBitSize = BitSize(CrntSlot); RoundUpTo = (1 << NewBitSize); if (RoundUpTo != ColorUnion->ColorCount) { GifColorType *Map = ColorUnion->Colors; /* * Zero out slots up to next power of 2. * We know these slots exist because of the way ColorUnion's * start dimension was computed. */ for (j = CrntSlot; j < RoundUpTo; j++) Map[j].Red = Map[j].Green = Map[j].Blue = 0; /* perhaps we can shrink the map? */ if (RoundUpTo < ColorUnion->ColorCount) ColorUnion->Colors = (GifColorType *)Fog::MemMgr::realloc(Map, sizeof(GifColorType) * RoundUpTo); } ColorUnion->ColorCount = RoundUpTo; ColorUnion->BitsPerPixel = NewBitSize; return (ColorUnion); } // Apply a given color translation to the raster bits of an image static void ApplyTranslation(SavedImage * Image, GifPixelType Translation[]) { int i; int RasterSize = Image->ImageDesc.Height * Image->ImageDesc.Width; for (i = 0; i < RasterSize; i++) Image->RasterBits[i] = Translation[Image->RasterBits[i]]; } // [giflib extension record functions] static void MakeExtension(SavedImage * New, int Function) { New->Function = Function; /*** FIXME: * Someday we might have to deal with multiple extensions. * ??? Was this a note from Gershon or from me? Does the multiple * extension blocks solve this or do we need multiple Functions? Or is * this an obsolete function? (People should use AddExtensionBlock * instead?) * Looks like AddExtensionBlock needs to take the int Function argument * then it can take the place of this function. Right now people have to * use both. Fix AddExtensionBlock and add this to the deprecation list. */ } static int AddExtensionBlock(SavedImage * New, int Len, unsigned char ExtData[]) { ExtensionBlock *ep; if (New->ExtensionBlocks == NULL) New->ExtensionBlocks=(ExtensionBlock *)Fog::MemMgr::alloc(sizeof(ExtensionBlock)); else New->ExtensionBlocks = (ExtensionBlock *)Fog::MemMgr::realloc(New->ExtensionBlocks, sizeof(ExtensionBlock) * (New->ExtensionBlockCount + 1)); if (New->ExtensionBlocks == NULL) return (GIF_ERROR); ep = &New->ExtensionBlocks[New->ExtensionBlockCount++]; ep->ByteCount=Len; ep->Bytes = (char *)Fog::MemMgr::alloc(ep->ByteCount); if (ep->Bytes == NULL) return (GIF_ERROR); if (ExtData) { memcpy(ep->Bytes, ExtData, Len); ep->Function = New->Function; } return (GIF_OK); } static void FreeExtension(SavedImage *Image) { ExtensionBlock *ep; if ((Image == NULL) || (Image->ExtensionBlocks == NULL)) return; for (ep = Image->ExtensionBlocks; ep < (Image->ExtensionBlocks + Image->ExtensionBlockCount); ep++) { Fog::MemMgr::free((char *)ep->Bytes); } Fog::MemMgr::free((char *)Image->ExtensionBlocks); Image->ExtensionBlocks = NULL; } // [giflib - image block allocation functions] // Private Function: // Frees the last image in the GifFile->SavedImages array static void FreeLastSavedImage(GifFileType *GifFile) { SavedImage *sp; if ((GifFile == NULL) || (GifFile->SavedImages == NULL)) return; /* Remove one SavedImage from the GifFile */ GifFile->ImageCount--; sp = &GifFile->SavedImages[GifFile->ImageCount]; /* Deallocate its Colormap */ if (sp->ImageDesc.ColorMap) { FreeMapObject(sp->ImageDesc.ColorMap); sp->ImageDesc.ColorMap = NULL; } /* Deallocate the image data */ if (sp->RasterBits) Fog::MemMgr::free((char *)sp->RasterBits); /* Deallocate any extensions */ if (sp->ExtensionBlocks) FreeExtension(sp); /*** FIXME: We could Fog::MemMgr::realloc the GifFile->SavedImages structure but is * there a point to it? Saves some memory but we'd have to do it every * time. If this is used in FreeSavedImages then it would be inefficient * (The whole array is going to be deallocated.) If we just use it when * we want to Fog::MemMgr::free the last Image it's convenient to do it here. */ } // Append an image block to the SavedImages array static SavedImage *MakeSavedImage(GifFileType * GifFile, const SavedImage * CopyFrom) { SavedImage *sp; if (GifFile->SavedImages == NULL) GifFile->SavedImages = (SavedImage *)Fog::MemMgr::alloc(sizeof(SavedImage)); else GifFile->SavedImages = (SavedImage *)Fog::MemMgr::realloc(GifFile->SavedImages, sizeof(SavedImage) * (GifFile->ImageCount + 1)); if (GifFile->SavedImages == NULL) return ((SavedImage *)NULL); sp = &GifFile->SavedImages[GifFile->ImageCount++]; memset((char *)sp, '\0', sizeof(SavedImage)); if (CopyFrom) { memcpy((char *)sp, CopyFrom, sizeof(SavedImage)); /* * Make our own allocated copies of the heap fields in the * copied record. This guards against potential aliasing * problems. */ /* first, the local color map */ if (sp->ImageDesc.ColorMap) { sp->ImageDesc.ColorMap = MakeMapObject( CopyFrom->ImageDesc.ColorMap->ColorCount, CopyFrom->ImageDesc.ColorMap->Colors); if (sp->ImageDesc.ColorMap == NULL) { FreeLastSavedImage(GifFile); return (SavedImage *)(NULL); } } /* next, the raster */ sp->RasterBits = (unsigned char *)Fog::MemMgr::alloc(sizeof(GifPixelType) * CopyFrom->ImageDesc.Height * CopyFrom->ImageDesc.Width); if (sp->RasterBits == NULL) { FreeLastSavedImage(GifFile); return (SavedImage *)(NULL); } memcpy(sp->RasterBits, CopyFrom->RasterBits, sizeof(GifPixelType) * CopyFrom->ImageDesc.Height * CopyFrom->ImageDesc.Width); /* finally, the extension blocks */ if (sp->ExtensionBlocks) { sp->ExtensionBlocks = (ExtensionBlock *)Fog::MemMgr::alloc( sizeof(ExtensionBlock) * CopyFrom->ExtensionBlockCount); if (sp->ExtensionBlocks == NULL) { FreeLastSavedImage(GifFile); return (SavedImage *)(NULL); } memcpy(sp->ExtensionBlocks, CopyFrom->ExtensionBlocks, sizeof(ExtensionBlock) * CopyFrom->ExtensionBlockCount); // For the moment, the actual blocks can take their // chances with Fog::MemMgr::free(). We'll fix this later. // // FIXME: [Better check this out... Toshio] // 2004 May 27: Looks like this was an ESR note. // It means the blocks are shallow copied from InFile to // OutFile. However, I don't see that in this code.... // Did ESR fix it but never remove this note (And other notes // in gifspnge?) } } return sp; } static void FreeSavedImages(GifFileType * GifFile) { SavedImage *sp; if ((GifFile == NULL) || (GifFile->SavedImages == NULL)) return; for (sp = GifFile->SavedImages; sp < GifFile->SavedImages + GifFile->ImageCount; sp++) { if (sp->ImageDesc.ColorMap) { FreeMapObject(sp->ImageDesc.ColorMap); sp->ImageDesc.ColorMap = NULL; } if (sp->RasterBits) Fog::MemMgr::free((char *)sp->RasterBits); if (sp->ExtensionBlocks) FreeExtension(sp); } Fog::MemMgr::free((char *)GifFile->SavedImages); GifFile->SavedImages=NULL; } // [giflib - dgif] #define READ(_gif, _buf, _len) (_gif->stream->read(_buf, _len)) static int DGifGetWord(GifFileType *GifFile, GifWord *Word); static int DGifSetupDecompress(GifFileType *GifFile); static int DGifDecompressLine(GifFileType *GifFile, GifPixelType *Line, int LineLen); static int DGifGetPrefixChar(GifPrefixType *Prefix, int Code, int ClearCode); static int DGifDecompressInput(GifFileType *GifFile, int *Code); static int DGifBufferedInput(GifFileType *GifFile, uint8_t *Buf, uint8_t *NextByte); /****************************************************************************** * GifFileType constructor with user supplied input function (TVT) *****************************************************************************/ static GifFileType *DGifOpen(Fog::Stream* stream) { uint8_t Buf[GIF_STAMP_LEN + 1]; GifFileType *GifFile; GifFile = (GifFileType *)Fog::MemMgr::calloc(sizeof(GifFileType)); if (GifFile == NULL) { _GifError = D_GIF_ERR_NOT_ENOUGH_MEM; return NULL; } GifFile->FileState = FILE_STATE_READ; GifFile->stream = stream; /* Lets see if this is a GIF file: */ if (READ(GifFile, Buf, GIF_STAMP_LEN) != GIF_STAMP_LEN) { _GifError = D_GIF_ERR_READ_FAILED; Fog::MemMgr::free((char *)GifFile); return NULL; } /* The GIF Version number is ignored at this time. Maybe we should do * something more useful with it. */ Buf[GIF_STAMP_LEN] = 0; if (strncmp(GIF_STAMP, (const char*)Buf, GIF_VERSION_POS) != 0) { _GifError = D_GIF_ERR_NOT_GIF_FILE; Fog::MemMgr::free((char *)GifFile); return NULL; } if (DGifGetScreenDesc(GifFile) == GIF_ERROR) { Fog::MemMgr::free((char *)GifFile); return NULL; } _GifError = 0; return GifFile; } /****************************************************************************** * This routine should be called before any other DGif calls. Note that * this routine is called automatically from DGif file open routines. *****************************************************************************/ static int DGifGetScreenDesc(GifFileType * GifFile) { int i, BitsPerPixel; uint8_t Buf[3]; if (!IS_READABLE(GifFile)) { /// This file was NOT open for reading: _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } // Put the screen descriptor into the file: if (DGifGetWord(GifFile, &GifFile->SWidth) == GIF_ERROR || DGifGetWord(GifFile, &GifFile->SHeight) == GIF_ERROR) { return GIF_ERROR; } if (READ(GifFile, Buf, 3) != 3) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } GifFile->SColorResolution = (((Buf[0] & 0x70) + 1) >> 4) + 1; BitsPerPixel = (Buf[0] & 0x07) + 1; GifFile->SBackGroundColor = Buf[1]; if (Buf[0] & 0x80) { // Do we have global color map? GifFile->SColorMap = MakeMapObject(1 << BitsPerPixel, NULL); if (GifFile->SColorMap == NULL) { _GifError = D_GIF_ERR_NOT_ENOUGH_MEM; return GIF_ERROR; } // Get the global color map: for (i = 0; i < GifFile->SColorMap->ColorCount; i++) { if (READ(GifFile, Buf, 3) != 3) { FreeMapObject(GifFile->SColorMap); GifFile->SColorMap = NULL; _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } GifFile->SColorMap->Colors[i].Red = Buf[0]; GifFile->SColorMap->Colors[i].Green = Buf[1]; GifFile->SColorMap->Colors[i].Blue = Buf[2]; } } else { GifFile->SColorMap = NULL; } return GIF_OK; } /****************************************************************************** * This routine should be called before any attempt to read an image. *****************************************************************************/ static int DGifGetRecordType(GifFileType * GifFile, GifRecordType * Type) { uint8_t Buf; if (!IS_READABLE(GifFile)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (READ(GifFile, &Buf, 1) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } switch (Buf) { case ',': *Type = IMAGE_DESC_RECORD_TYPE; break; case '!': *Type = EXTENSION_RECORD_TYPE; break; case ';': *Type = TERMINATE_RECORD_TYPE; break; default: *Type = UNDEFINED_RECORD_TYPE; _GifError = D_GIF_ERR_WRONG_RECORD; return GIF_ERROR; } return GIF_OK; } /****************************************************************************** * This routine should be called before any attempt to read an image. * Note it is assumed the Image desc. header (',') has been read. *****************************************************************************/ static int DGifGetImageDesc(GifFileType * GifFile) { int i, BitsPerPixel; uint8_t Buf[3]; SavedImage *sp; if (!IS_READABLE(GifFile)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (DGifGetWord(GifFile, &GifFile->Image.Left) == GIF_ERROR || DGifGetWord(GifFile, &GifFile->Image.Top) == GIF_ERROR || DGifGetWord(GifFile, &GifFile->Image.Width) == GIF_ERROR || DGifGetWord(GifFile, &GifFile->Image.Height) == GIF_ERROR) { return GIF_ERROR; } if (READ(GifFile, Buf, 1) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } BitsPerPixel = (Buf[0] & 0x07) + 1; GifFile->Image.Interlace = (Buf[0] & 0x40); if (Buf[0] & 0x80)\ { /* Does this image have local color map? */ /*** FIXME: Why do we check both of these in order to do this? * Why do we have both Image and SavedImages? */ if (GifFile->Image.ColorMap && GifFile->SavedImages == NULL) FreeMapObject(GifFile->Image.ColorMap); GifFile->Image.ColorMap = MakeMapObject(1 << BitsPerPixel, NULL); if (GifFile->Image.ColorMap == NULL) { _GifError = D_GIF_ERR_NOT_ENOUGH_MEM; return GIF_ERROR; } /* Get the image local color map: */ for (i = 0; i < GifFile->Image.ColorMap->ColorCount; i++) { if (READ(GifFile, Buf, 3) != 3) { FreeMapObject(GifFile->Image.ColorMap); _GifError = D_GIF_ERR_READ_FAILED; GifFile->Image.ColorMap = NULL; return GIF_ERROR; } GifFile->Image.ColorMap->Colors[i].Red = Buf[0]; GifFile->Image.ColorMap->Colors[i].Green = Buf[1]; GifFile->Image.ColorMap->Colors[i].Blue = Buf[2]; } } else if (GifFile->Image.ColorMap) { FreeMapObject(GifFile->Image.ColorMap); GifFile->Image.ColorMap = NULL; } if (GifFile->SavedImages) { if ((GifFile->SavedImages = (SavedImage *)Fog::MemMgr::realloc(GifFile->SavedImages, sizeof(SavedImage) * (GifFile->ImageCount + 1))) == NULL) { _GifError = D_GIF_ERR_NOT_ENOUGH_MEM; return GIF_ERROR; } } else { if ((GifFile->SavedImages = (SavedImage *) Fog::MemMgr::alloc(sizeof(SavedImage))) == NULL) { _GifError = D_GIF_ERR_NOT_ENOUGH_MEM; return GIF_ERROR; } } sp = &GifFile->SavedImages[GifFile->ImageCount]; memcpy(&sp->ImageDesc, &GifFile->Image, sizeof(GifImageDesc)); if (GifFile->Image.ColorMap != NULL) { sp->ImageDesc.ColorMap = MakeMapObject( GifFile->Image.ColorMap->ColorCount, GifFile->Image.ColorMap->Colors); if (sp->ImageDesc.ColorMap == NULL) { _GifError = D_GIF_ERR_NOT_ENOUGH_MEM; return GIF_ERROR; } } sp->RasterBits = (unsigned char *)NULL; sp->ExtensionBlockCount = 0; sp->ExtensionBlocks = (ExtensionBlock *) NULL; GifFile->ImageCount++; GifFile->PixelCount = (long)GifFile->Image.Width * (long)GifFile->Image.Height; DGifSetupDecompress(GifFile); /* Reset decompress algorithm parameters. */ return GIF_OK; } /****************************************************************************** * Get one full scanned line (Line) of length LineLen from GIF file. *****************************************************************************/ static int DGifGetLine(GifFileType * GifFile, GifPixelType * Line, int LineLen) { uint8_t *Dummy; if (!IS_READABLE(GifFile)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (!LineLen) LineLen = GifFile->Image.Width; if ((GifFile->PixelCount -= LineLen) > 0xffff0000) { _GifError = D_GIF_ERR_DATA_TOO_BIG; return GIF_ERROR; } if (DGifDecompressLine(GifFile, Line, LineLen) == GIF_OK) { if (GifFile->PixelCount == 0) { /* We probably would not be called any more, so lets clean * everything before we return: need to flush out all rest of * image until empty block (size 0) detected. We use GetCodeNext. */ do { if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR) return GIF_ERROR; } while (Dummy != NULL) ; } return GIF_OK; } else return GIF_ERROR; } /****************************************************************************** * Put one pixel (Pixel) into GIF file. *****************************************************************************/ static int DGifGetPixel(GifFileType * GifFile, GifPixelType Pixel) { uint8_t *Dummy; if (!IS_READABLE(GifFile)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (--GifFile->PixelCount > 0xffff0000) { _GifError = D_GIF_ERR_DATA_TOO_BIG; return GIF_ERROR; } if (DGifDecompressLine(GifFile, &Pixel, 1) == GIF_OK) { if (GifFile->PixelCount == 0) { /* We probably would not be called any more, so lets clean * everything before we return: need to flush out all rest of * image until empty block (size 0) detected. We use GetCodeNext. */ do if (DGifGetCodeNext(GifFile, &Dummy) == GIF_ERROR) return GIF_ERROR; while (Dummy != NULL) ; } return GIF_OK; } else return GIF_ERROR; } /****************************************************************************** * Get an extension block (see GIF manual) from gif file. This routine only * returns the first data block, and DGifGetExtensionNext should be called * after this one until NULL extension is returned. * The Extension should NOT be freed by the user (not dynamically allocated). * Note it is assumed the Extension desc. header ('!') has been read. *****************************************************************************/ static int DGifGetExtension(GifFileType * GifFile, int *ExtCode, uint8_t ** Extension) { uint8_t Buf; if (!IS_READABLE(GifFile)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (READ(GifFile, &Buf, 1) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *ExtCode = Buf; return DGifGetExtensionNext(GifFile, Extension); } /****************************************************************************** * Get a following extension block (see GIF manual) from gif file. This * routine should be called until NULL Extension is returned. * The Extension should NOT be freed by the user (not dynamically allocated). *****************************************************************************/ static int DGifGetExtensionNext(GifFileType * GifFile, uint8_t ** Extension) { uint8_t Buf; if (READ(GifFile, &Buf, 1) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } if (Buf > 0) { *Extension = GifFile->Buf; /* Use private unused buffer. */ (*Extension)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */ if (READ(GifFile, &((*Extension)[1]), Buf) != Buf) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } } else { *Extension = NULL; } return GIF_OK; } /****************************************************************************** * This routine should be called last, to close the GIF file. *****************************************************************************/ static int DGifCloseFile(GifFileType * GifFile) { if (!IS_READABLE(GifFile)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (GifFile->Image.ColorMap) { FreeMapObject(GifFile->Image.ColorMap); GifFile->Image.ColorMap = NULL; } if (GifFile->SColorMap) { FreeMapObject(GifFile->SColorMap); GifFile->SColorMap = NULL; } if (GifFile->SavedImages) { FreeSavedImages(GifFile); GifFile->SavedImages = NULL; } Fog::MemMgr::free(GifFile); return GIF_OK; } /****************************************************************************** * Get 2 bytes (word) from the given file: *****************************************************************************/ static int DGifGetWord(GifFileType * GifFile, GifWord *Word) { unsigned char c[2]; if (READ(GifFile, c, 2) != 2) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *Word = (((unsigned int)c[1]) << 8) + c[0]; return GIF_OK; } /****************************************************************************** * Get the image code in compressed form. This routine can be called if the * information needed to be piped out as is. Obviously this is much faster * than decoding and encoding again. This routine should be followed by calls * to DGifGetCodeNext, until NULL block is returned. * The block should NOT be freed by the user (not dynamically allocated). *****************************************************************************/ static int DGifGetCode(GifFileType * GifFile, int *CodeSize, uint8_t ** CodeBlock) { if (!IS_READABLE(GifFile)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } *CodeSize = GifFile->BitsPerPixel; return DGifGetCodeNext(GifFile, CodeBlock); } /****************************************************************************** * Continue to get the image code in compressed form. This routine should be * called until NULL block is returned. * The block should NOT be freed by the user (not dynamically allocated). *****************************************************************************/ static int DGifGetCodeNext(GifFileType * GifFile, uint8_t ** CodeBlock) { uint8_t Buf; if (READ(GifFile, &Buf, 1) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } if (Buf > 0) { *CodeBlock = GifFile->Buf; /* Use private unused buffer. */ (*CodeBlock)[0] = Buf; /* Pascal strings notation (pos. 0 is len.). */ if (READ(GifFile, &((*CodeBlock)[1]), Buf) != Buf) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } } else { *CodeBlock = NULL; GifFile->Buf[0] = 0; /* Make sure the buffer is empty! */ GifFile->PixelCount = 0; /* And local info. indicate image read. */ } return GIF_OK; } /****************************************************************************** * Setup the LZ decompression for this image: *****************************************************************************/ static int DGifSetupDecompress(GifFileType * GifFile) { int i, BitsPerPixel; uint8_t CodeSize; GifPrefixType *Prefix; READ(GifFile, &CodeSize, 1); /* Read Code size from file. */ BitsPerPixel = CodeSize; GifFile->Buf[0] = 0; /* Input Buffer empty. */ GifFile->BitsPerPixel = BitsPerPixel; GifFile->ClearCode = (1 << BitsPerPixel); GifFile->EOFCode = GifFile->ClearCode + 1; GifFile->RunningCode = GifFile->EOFCode + 1; GifFile->RunningBits = BitsPerPixel + 1; /* Number of bits per code. */ GifFile->MaxCode1 = 1 << GifFile->RunningBits; /* Max. code + 1. */ GifFile->StackPtr = 0; /* No pixels on the pixel stack. */ GifFile->LastCode = NO_SUCH_CODE; GifFile->CrntShiftState = 0; /* No information in CrntShiftDWord. */ GifFile->CrntShiftDWord = 0; Prefix = GifFile->Prefix; for (i = 0; i <= LZ_MAX_CODE; i++) Prefix[i] = NO_SUCH_CODE; return GIF_OK; } /****************************************************************************** * The LZ decompression routine: * This version decompress the given gif file into Line of length LineLen. * This routine can be called few times (one per scan line, for example), in * order the complete the whole image. *****************************************************************************/ static int DGifDecompressLine(GifFileType * GifFile, GifPixelType * Line, int LineLen) { int i = 0; int j, CrntCode, EOFCode, ClearCode, CrntPrefix, LastCode, StackPtr; uint8_t *Stack, *Suffix; GifPrefixType *Prefix; StackPtr = GifFile->StackPtr; Prefix = GifFile->Prefix; Suffix = GifFile->Suffix; Stack = GifFile->Stack; EOFCode = GifFile->EOFCode; ClearCode = GifFile->ClearCode; LastCode = GifFile->LastCode; if (StackPtr != 0) { /* Let pop the stack off before continueing to read the gif file: */ while (StackPtr != 0 && i < LineLen) Line[i++] = Stack[--StackPtr]; } while (i < LineLen) { /* Decode LineLen items. */ if (DGifDecompressInput(GifFile, &CrntCode) == GIF_ERROR) return GIF_ERROR; if (CrntCode == EOFCode) { /* Note however that usually we will not be here as we will stop * decoding as soon as we got all the pixel, or EOF code will * not be read at all, and DGifGetLine/Pixel clean everything. */ if (i != LineLen - 1 || GifFile->PixelCount != 0) { _GifError = D_GIF_ERR_EOF_TOO_SOON; return GIF_ERROR; } i++; } else if (CrntCode == ClearCode) { /* We need to start over again: */ for (j = 0; j <= LZ_MAX_CODE; j++) Prefix[j] = NO_SUCH_CODE; GifFile->RunningCode = GifFile->EOFCode + 1; GifFile->RunningBits = GifFile->BitsPerPixel + 1; GifFile->MaxCode1 = 1 << GifFile->RunningBits; LastCode = GifFile->LastCode = NO_SUCH_CODE; } else { /* Its regular code - if in pixel range simply add it to output * stream, otherwise trace to codes linked list until the prefix * is in pixel range: */ if (CrntCode < ClearCode) { /* This is simple - its pixel scalar, so add it to output: */ Line[i++] = CrntCode; } else { /* Its a code to needed to be traced: trace the linked list * until the prefix is a pixel, while pushing the suffix * pixels on our stack. If we done, pop the stack in reverse * (thats what stack is good for!) order to output. */ if (Prefix[CrntCode] == NO_SUCH_CODE) { /* Only allowed if CrntCode is exactly the running code: * In that case CrntCode = XXXCode, CrntCode or the * prefix code is last code and the suffix char is * exactly the prefix of last code! */ if (CrntCode == GifFile->RunningCode - 2) { CrntPrefix = LastCode; Suffix[GifFile->RunningCode - 2] = Stack[StackPtr++] = DGifGetPrefixChar(Prefix, LastCode, ClearCode); } else { _GifError = D_GIF_ERR_IMAGE_DEFECT; return GIF_ERROR; } } else { CrntPrefix = CrntCode; } /* Now (if image is O.K.) we should not get an NO_SUCH_CODE * During the trace. As we might loop forever, in case of * defective image, we count the number of loops we trace * and stop if we got LZ_MAX_CODE. obviously we can not * loop more than that. */ j = 0; while (j++ <= LZ_MAX_CODE && CrntPrefix > ClearCode && CrntPrefix <= LZ_MAX_CODE) { Stack[StackPtr++] = Suffix[CrntPrefix]; CrntPrefix = Prefix[CrntPrefix]; } if (j >= LZ_MAX_CODE || CrntPrefix > LZ_MAX_CODE) { _GifError = D_GIF_ERR_IMAGE_DEFECT; return GIF_ERROR; } /* Push the last character on stack: */ Stack[StackPtr++] = CrntPrefix; /* Now lets pop all the stack into output: */ while (StackPtr != 0 && i < LineLen) Line[i++] = Stack[--StackPtr]; } if (LastCode != NO_SUCH_CODE) { Prefix[GifFile->RunningCode - 2] = LastCode; if (CrntCode == GifFile->RunningCode - 2) { /* Only allowed if CrntCode is exactly the running code: * In that case CrntCode = XXXCode, CrntCode or the * prefix code is last code and the suffix char is * exactly the prefix of last code! */ Suffix[GifFile->RunningCode - 2] = DGifGetPrefixChar(Prefix, LastCode, ClearCode); } else { Suffix[GifFile->RunningCode - 2] = DGifGetPrefixChar(Prefix, CrntCode, ClearCode); } } LastCode = CrntCode; } } GifFile->LastCode = LastCode; GifFile->StackPtr = StackPtr; return GIF_OK; } /****************************************************************************** * Routine to trace the Prefixes linked list until we get a prefix which is * not code, but a pixel value (less than ClearCode). Returns that pixel value. * If image is defective, we might loop here forever, so we limit the loops to * the maximum possible if image O.k. - LZ_MAX_CODE times. *****************************************************************************/ static int DGifGetPrefixChar(GifPrefixType *Prefix, int Code, int ClearCode) { int i = 0; while (Code > ClearCode && i++ <= LZ_MAX_CODE) Code = Prefix[Code]; return Code; } /****************************************************************************** * Interface for accessing the LZ codes directly. Set Code to the real code * (12bits), or to -1 if EOF code is returned. *****************************************************************************/ static int DGifGetLZCodes(GifFileType * GifFile, int *Code) { uint8_t *CodeBlock; if (!IS_READABLE(GifFile)) { /* This file was NOT open for reading: */ _GifError = D_GIF_ERR_NOT_READABLE; return GIF_ERROR; } if (DGifDecompressInput(GifFile, Code) == GIF_ERROR) return GIF_ERROR; if (*Code == GifFile->EOFCode) { /* Skip rest of codes (hopefully only NULL terminating block): */ do { if (DGifGetCodeNext(GifFile, &CodeBlock) == GIF_ERROR) return GIF_ERROR; } while (CodeBlock != NULL) ; *Code = -1; } else if (*Code == GifFile->ClearCode) { /* We need to start over again: */ GifFile->RunningCode = GifFile->EOFCode + 1; GifFile->RunningBits = GifFile->BitsPerPixel + 1; GifFile->MaxCode1 = 1 << GifFile->RunningBits; } return GIF_OK; } /****************************************************************************** * The LZ decompression input routine: * This routine is responsable for the decompression of the bit stream from * 8 bits (bytes) packets, into the real codes. * Returns GIF_OK if read successfully. *****************************************************************************/ static int DGifDecompressInput(GifFileType * GifFile, int *Code) { static unsigned short CodeMasks[] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff }; uint8_t NextByte; /* The image can't contain more than LZ_BITS per code. */ if (GifFile->RunningBits > LZ_BITS) { _GifError = D_GIF_ERR_IMAGE_DEFECT; return GIF_ERROR; } while (GifFile->CrntShiftState < GifFile->RunningBits) { /* Needs to get more bytes from input stream for next code: */ if (DGifBufferedInput(GifFile, GifFile->Buf, &NextByte) == GIF_ERROR) { return GIF_ERROR; } GifFile->CrntShiftDWord |= ((unsigned long)NextByte) << GifFile->CrntShiftState; GifFile->CrntShiftState += 8; } *Code = GifFile->CrntShiftDWord & CodeMasks[GifFile->RunningBits]; GifFile->CrntShiftDWord >>= GifFile->RunningBits; GifFile->CrntShiftState -= GifFile->RunningBits; /* If code cannot fit into RunningBits bits, must raise its size. Note * however that codes above 4095 are used for special signaling. * If we're using LZ_BITS bits already and we're at the max code, just * keep using the table as it is, don't increment GifFile->RunningCode. */ if (GifFile->RunningCode < LZ_MAX_CODE + 2 && ++GifFile->RunningCode > GifFile->MaxCode1 && GifFile->RunningBits < LZ_BITS) { GifFile->MaxCode1 <<= 1; GifFile->RunningBits++; } return GIF_OK; } /****************************************************************************** * This routines read one gif data block at a time and buffers it internally * so that the decompression routine could access it. * The routine returns the next byte from its internal buffer (or read next * block in if buffer empty) and returns GIF_OK if succesful. *****************************************************************************/ static int DGifBufferedInput(GifFileType * GifFile, uint8_t * Buf, uint8_t * NextByte) { if (Buf[0] == 0) { /* Needs to read the next buffer - this one is empty: */ if (READ(GifFile, Buf, 1) != 1) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } /* There shouldn't be any empty data blocks here as the LZW spec * says the LZW termination code should come first. Therefore we * shouldn't be inside this routine at that point. */ if (Buf[0] == 0) { _GifError = D_GIF_ERR_IMAGE_DEFECT; return GIF_ERROR; } if (READ(GifFile, &Buf[1], Buf[0]) != Buf[0]) { _GifError = D_GIF_ERR_READ_FAILED; return GIF_ERROR; } *NextByte = Buf[1]; Buf[1] = 2; /* We use now the second place as last char read! */ Buf[0]--; } else { *NextByte = Buf[Buf[1]++]; Buf[0]--; } return GIF_OK; } #ifndef _GBA_NO_FILEIO /****************************************************************************** * This routine reads an entire GIF into core, hanging all its state info off * the GifFileType pointer. Call DGifOpenFileName() or DGifOpenFileHandle() * first to initialize I/O. Its inverse is EGifSpew(). ******************************************************************************/ static int DGifSlurp(GifFileType * GifFile) { int ImageSize; GifRecordType RecordType; SavedImage *sp; uint8_t *ExtData; SavedImage temp_save; temp_save.ExtensionBlocks = NULL; temp_save.ExtensionBlockCount = 0; do { if (DGifGetRecordType(GifFile, &RecordType) == GIF_ERROR) return (GIF_ERROR); switch (RecordType) { case IMAGE_DESC_RECORD_TYPE: if (DGifGetImageDesc(GifFile) == GIF_ERROR) return (GIF_ERROR); sp = &GifFile->SavedImages[GifFile->ImageCount - 1]; ImageSize = sp->ImageDesc.Width * sp->ImageDesc.Height; sp->RasterBits = (unsigned char *)Fog::MemMgr::alloc(ImageSize * sizeof(GifPixelType)); if (sp->RasterBits == NULL) return GIF_ERROR; if (DGifGetLine(GifFile, sp->RasterBits, ImageSize) == GIF_ERROR) return (GIF_ERROR); if (temp_save.ExtensionBlocks) { sp->ExtensionBlocks = temp_save.ExtensionBlocks; sp->ExtensionBlockCount = temp_save.ExtensionBlockCount; temp_save.ExtensionBlocks = NULL; temp_save.ExtensionBlockCount = 0; /* FIXME: The following is wrong. It is left in only for * backwards compatibility. Someday it should go away. Use * the sp->ExtensionBlocks->Function variable instead. */ sp->Function = sp->ExtensionBlocks[0].Function; } break; case EXTENSION_RECORD_TYPE: if (DGifGetExtension(GifFile, &temp_save.Function, &ExtData) == GIF_ERROR) return (GIF_ERROR); while (ExtData != NULL) { /* Create an extension block with our data */ if (AddExtensionBlock(&temp_save, ExtData[0], &ExtData[1]) == GIF_ERROR) return (GIF_ERROR); if (DGifGetExtensionNext(GifFile, &ExtData) == GIF_ERROR) return (GIF_ERROR); temp_save.Function = 0; } break; case TERMINATE_RECORD_TYPE: break; default: /* Should be trapped by DGifGetRecordType */ break; } } while (RecordType != TERMINATE_RECORD_TYPE); /* Just in case the Gif has an extension block without an associated * image... (Should we save this into a savefile structure with no image * instead? Have to check if the present writing code can handle that as * well.... */ if (temp_save.ExtensionBlocks) FreeExtension(&temp_save); return (GIF_OK); } #endif /* _GBA_NO_FILEIO */ // --------------------------------------------------------------------------- // giflib - egif // --------------------------------------------------------------------------- // Masks given codes to BitsPerPixel, to make sure all codes are in range: static GifPixelType CodeMask[] = { 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff }; static char GifVersionPrefix[GIF_STAMP_LEN + 1] = GIF87_STAMP; #define WRITE(_gif, _buf, _len) (_gif->stream->write(_buf, _len)) static int EGifPutWord(int Word, GifFileType * GifFile); static int EGifSetupCompress(GifFileType * GifFile); static int EGifCompressLine(GifFileType * GifFile, GifPixelType * Line, int LineLen); static int EGifCompressOutput(GifFileType * GifFile, int Code); static int EGifBufferedOutput(GifFileType * GifFile, uint8_t * Buf, int c); /****************************************************************************** * Output constructor that takes user supplied output function. * Basically just a copy of EGifOpenFileHandle. (MRB) *****************************************************************************/ static GifFileType *EGifOpen(Fog::Stream* stream) { GifFileType *GifFile; GifFile = (GifFileType *)Fog::MemMgr::calloc(sizeof(GifFileType)); if (GifFile == NULL) { _GifError = E_GIF_ERR_NOT_ENOUGH_MEM; return NULL; } GifFile->HashTable = _InitHashTable(); if (GifFile->HashTable == NULL) { Fog::MemMgr::free(GifFile); _GifError = E_GIF_ERR_NOT_ENOUGH_MEM; return NULL; } GifFile->stream = stream; GifFile->FileState = FILE_STATE_WRITE; _GifError = 0; return GifFile; } /****************************************************************************** * Routine to set current GIF version. All files open for write will be * using this version until next call to this routine. Version consists of * 3 characters as "87a" or "89a". No test is made to validate the version. *****************************************************************************/ static void EGifSetGifVersion(const char *Version) { strncpy(GifVersionPrefix + GIF_VERSION_POS, Version, 3); } /****************************************************************************** * This routine should be called before any other EGif calls, immediately * follows the GIF file openning. *****************************************************************************/ static int EGifPutScreenDesc(GifFileType * GifFile, int Width, int Height, int ColorRes, int BackGround, const ColorMapObject * ColorMap) { int i; uint8_t Buf[3]; if (GifFile->FileState & FILE_STATE_SCREEN) { /* If already has screen descriptor - something is wrong! */ _GifError = E_GIF_ERR_HAS_SCRN_DSCR; return GIF_ERROR; } if (!IS_WRITEABLE(GifFile)) { /* This file was NOT open for writing: */ _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } /* First write the version prefix into the file. */ #ifndef DEBUG_NO_PREFIX if (WRITE(GifFile, (unsigned char *)GifVersionPrefix, strlen(GifVersionPrefix)) != strlen(GifVersionPrefix)) { _GifError = E_GIF_ERR_WRITE_FAILED; return GIF_ERROR; } #endif /* DEBUG_NO_PREFIX */ GifFile->SWidth = Width; GifFile->SHeight = Height; GifFile->SColorResolution = ColorRes; GifFile->SBackGroundColor = BackGround; if (ColorMap) { GifFile->SColorMap = MakeMapObject(ColorMap->ColorCount, ColorMap->Colors); if (GifFile->SColorMap == NULL) { _GifError = E_GIF_ERR_NOT_ENOUGH_MEM; return GIF_ERROR; } } else { GifFile->SColorMap = NULL; } /* * Put the logical screen descriptor into the file: */ /* Logical Screen Descriptor: Dimensions */ EGifPutWord(Width, GifFile); EGifPutWord(Height, GifFile); /* Logical Screen Descriptor: Packed Fields */ /* Note: We have actual size of the color table default to the largest * possible size (7+1 == 8 bits) because the decoder can use it to decide * how to display the files. */ Buf[0] = (ColorMap ? 0x80 : 0x00) | /* Yes/no global colormap */ ((ColorRes - 1) << 4) | /* Bits allocated to each primary color */ (ColorMap ? ColorMap->BitsPerPixel - 1 : 0x07 ); /* Actual size of the color table. */ Buf[1] = BackGround; /* Index into the ColorTable for background color */ Buf[2] = 0; /* Pixel Aspect Ratio */ #ifndef DEBUG_NO_PREFIX WRITE(GifFile, Buf, 3); #endif /* DEBUG_NO_PREFIX */ /* If we have Global color map - dump it also: */ #ifndef DEBUG_NO_PREFIX if (ColorMap != NULL) { for (i = 0; i < ColorMap->ColorCount; i++) { /* Put the ColorMap out also: */ Buf[0] = ColorMap->Colors[i].Red; Buf[1] = ColorMap->Colors[i].Green; Buf[2] = ColorMap->Colors[i].Blue; if (WRITE(GifFile, Buf, 3) != 3) { _GifError = E_GIF_ERR_WRITE_FAILED; return GIF_ERROR; } } } #endif /* DEBUG_NO_PREFIX */ /* Mark this file as has screen descriptor, and no pixel written yet: */ GifFile->FileState |= FILE_STATE_SCREEN; return GIF_OK; } /****************************************************************************** * This routine should be called before any attempt to dump an image - any * call to any of the pixel dump routines. *****************************************************************************/ static int EGifPutImageDesc(GifFileType * GifFile, int Left, int Top, int Width, int Height, int Interlace, const ColorMapObject * ColorMap) { int i; uint8_t Buf[3]; if (GifFile->FileState & FILE_STATE_IMAGE && GifFile->PixelCount > 0xffff0000) { /* If already has active image descriptor - something is wrong! */ _GifError = E_GIF_ERR_HAS_IMAG_DSCR; return GIF_ERROR; } if (!IS_WRITEABLE(GifFile)) { /* This file was NOT open for writing: */ _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } GifFile->Image.Left = Left; GifFile->Image.Top = Top; GifFile->Image.Width = Width; GifFile->Image.Height = Height; GifFile->Image.Interlace = Interlace; if (ColorMap) { GifFile->Image.ColorMap = MakeMapObject(ColorMap->ColorCount, ColorMap->Colors); if (GifFile->Image.ColorMap == NULL) { _GifError = E_GIF_ERR_NOT_ENOUGH_MEM; return GIF_ERROR; } } else { GifFile->Image.ColorMap = NULL; } /* Put the image descriptor into the file: */ Buf[0] = ','; /* Image seperator character. */ #ifndef DEBUG_NO_PREFIX WRITE(GifFile, Buf, 1); #endif /* DEBUG_NO_PREFIX */ EGifPutWord(Left, GifFile); EGifPutWord(Top, GifFile); EGifPutWord(Width, GifFile); EGifPutWord(Height, GifFile); Buf[0] = (ColorMap ? 0x80 : 0x00) | (Interlace ? 0x40 : 0x00) | (ColorMap ? ColorMap->BitsPerPixel - 1 : 0); #ifndef DEBUG_NO_PREFIX WRITE(GifFile, Buf, 1); #endif /* DEBUG_NO_PREFIX */ /* If we have Global color map - dump it also: */ #ifndef DEBUG_NO_PREFIX if (ColorMap != NULL) { for (i = 0; i < ColorMap->ColorCount; i++) { /* Put the ColorMap out also: */ Buf[0] = ColorMap->Colors[i].Red; Buf[1] = ColorMap->Colors[i].Green; Buf[2] = ColorMap->Colors[i].Blue; if (WRITE(GifFile, Buf, 3) != 3) { _GifError = E_GIF_ERR_WRITE_FAILED; return GIF_ERROR; } } } #endif /* DEBUG_NO_PREFIX */ if (GifFile->SColorMap == NULL && GifFile->Image.ColorMap == NULL) { _GifError = E_GIF_ERR_NO_COLOR_MAP; return GIF_ERROR; } /* Mark this file as has screen descriptor: */ GifFile->FileState |= FILE_STATE_IMAGE; GifFile->PixelCount = (long)Width *(long)Height; /* Reset compress algorithm parameters. */ EGifSetupCompress(GifFile); return GIF_OK; } /****************************************************************************** * Put one full scanned line (Line) of length LineLen into GIF file. *****************************************************************************/ static int EGifPutLine(GifFileType * GifFile, GifPixelType * Line, int LineLen) { int i; GifPixelType Mask; if (!IS_WRITEABLE(GifFile)) { /* This file was NOT open for writing: */ _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } if (!LineLen) LineLen = GifFile->Image.Width; if (GifFile->PixelCount < (unsigned)LineLen) { _GifError = E_GIF_ERR_DATA_TOO_BIG; return GIF_ERROR; } GifFile->PixelCount -= LineLen; /* Make sure the codes are not out of bit range, as we might generate * wrong code (because of overflow when we combine them) in this case: */ Mask = CodeMask[GifFile->BitsPerPixel]; for (i = 0; i < LineLen; i++) Line[i] &= Mask; return EGifCompressLine(GifFile, Line, LineLen); } /****************************************************************************** * Put one pixel (Pixel) into GIF file. *****************************************************************************/ static int EGifPutPixel(GifFileType * GifFile, GifPixelType Pixel) { if (!IS_WRITEABLE(GifFile)) { /* This file was NOT open for writing: */ _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } if (GifFile->PixelCount == 0) { _GifError = E_GIF_ERR_DATA_TOO_BIG; return GIF_ERROR; } --GifFile->PixelCount; /* Make sure the code is not out of bit range, as we might generate * wrong code (because of overflow when we combine them) in this case: */ Pixel &= CodeMask[GifFile->BitsPerPixel]; return EGifCompressLine(GifFile, &Pixel, 1); } /****************************************************************************** * Put a comment into GIF file using the GIF89 comment extension block. *****************************************************************************/ static int EGifPutComment(GifFileType * GifFile, const char *Comment) { unsigned int length = (uint)strlen(Comment); char *buf; if (length <= 255) { return EGifPutExtension(GifFile, COMMENT_EXT_FUNC_CODE, length, Comment); } else { buf = (char *)Comment; if (EGifPutExtensionFirst(GifFile, COMMENT_EXT_FUNC_CODE, 255, buf) == GIF_ERROR) return GIF_ERROR; length -= 255; buf = buf + 255; // Break the comment into 255 byte sub blocks. while (length > 255) { if (EGifPutExtensionNext(GifFile, 0, 255, buf) == GIF_ERROR) return GIF_ERROR; buf = buf + 255; length -= 255; } // Output any partial block and the clear code. if (length > 0) { if (EGifPutExtensionLast(GifFile, 0, length, buf) == GIF_ERROR) return GIF_ERROR; } else { if (EGifPutExtensionLast(GifFile, 0, 0, NULL) == GIF_ERROR) return GIF_ERROR; } } return GIF_OK; } /****************************************************************************** * Put a first extension block (see GIF manual) into gif file. Here more * extensions can be dumped using EGifPutExtensionNext until * EGifPutExtensionLast is invoked. *****************************************************************************/ static int EGifPutExtensionFirst(GifFileType * GifFile, int ExtCode, int ExtLen, const void* Extension) { uint8_t Buf[3]; if (!IS_WRITEABLE(GifFile)) { // This file was NOT open for writing. _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } if (ExtCode == 0) { WRITE(GifFile, (uint8_t *)&ExtLen, 1); } else { Buf[0] = '!'; Buf[1] = ExtCode; Buf[2] = ExtLen; WRITE(GifFile, Buf, 3); } WRITE(GifFile, Extension, ExtLen); return GIF_OK; } /****************************************************************************** * Put a middle extension block (see GIF manual) into gif file. *****************************************************************************/ static int EGifPutExtensionNext(GifFileType * GifFile, int ExtCode, int ExtLen, const void* Extension) { uint8_t Buf; if (!IS_WRITEABLE(GifFile)) { // This file was NOT open for writing. _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } Buf = ExtLen; WRITE(GifFile, &Buf, 1); WRITE(GifFile, Extension, ExtLen); return GIF_OK; } /****************************************************************************** * Put a last extension block (see GIF manual) into gif file. *****************************************************************************/ static int EGifPutExtensionLast(GifFileType * GifFile, int ExtCode, int ExtLen, const void* Extension) { uint8_t Buf; if (!IS_WRITEABLE(GifFile)) { // This file was NOT open for writing. _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } // If we are given an extension sub-block output it now. if (ExtLen > 0) { Buf = ExtLen; WRITE(GifFile, &Buf, 1); WRITE(GifFile, Extension, ExtLen); } // Write the block terminator. Buf = 0; WRITE(GifFile, &Buf, 1); return GIF_OK; } /****************************************************************************** * Put an extension block (see GIF manual) into gif file. * Warning: This function is only useful for Extension blocks that have at * most one subblock. Extensions with more than one subblock need to use the * EGifPutExtension{First,Next,Last} functions instead. *****************************************************************************/ static int EGifPutExtension(GifFileType * GifFile, int ExtCode, int ExtLen, const void* Extension) { uint8_t Buf[3]; if (!IS_WRITEABLE(GifFile)) { // This file was NOT open for writing. _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } if (ExtCode == 0) { WRITE(GifFile, (uint8_t *)&ExtLen, 1); } else { Buf[0] = '!'; /* Extension Introducer 0x21 */ Buf[1] = ExtCode; /* Extension Label */ Buf[2] = ExtLen; /* Extension length */ WRITE(GifFile, Buf, 3); } WRITE(GifFile, Extension, ExtLen); Buf[0] = 0; WRITE(GifFile, Buf, 1); return GIF_OK; } /****************************************************************************** * Put the image code in compressed form. This routine can be called if the * information needed to be piped out as is. Obviously this is much faster * than decoding and encoding again. This routine should be followed by calls * to EGifPutCodeNext, until NULL block is given. * The block should NOT be freed by the user (not dynamically allocated). *****************************************************************************/ static int EGifPutCode(GifFileType * GifFile, int CodeSize, const uint8_t * CodeBlock) { if (!IS_WRITEABLE(GifFile)) { // This file was NOT open for writing. _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } /* No need to dump code size as Compression set up does any for us: */ /* * Buf = CodeSize; * if (WRITE(GifFile, &Buf, 1) != 1) * { * _GifError = E_GIF_ERR_WRITE_FAILED; * return GIF_ERROR; * } */ return EGifPutCodeNext(GifFile, CodeBlock); } /****************************************************************************** * Continue to put the image code in compressed form. This routine should be * called with blocks of code as read via DGifGetCode/DGifGetCodeNext. If * given buffer pointer is NULL, empty block is written to mark end of code. *****************************************************************************/ static int EGifPutCodeNext(GifFileType* GifFile, const uint8_t* CodeBlock) { uint8_t Buf; if (CodeBlock != NULL) { if (WRITE(GifFile, CodeBlock, CodeBlock[0] + 1) != (unsigned)(CodeBlock[0] + 1)) { _GifError = E_GIF_ERR_WRITE_FAILED; return GIF_ERROR; } } else { Buf = 0; if (WRITE(GifFile, &Buf, 1) != 1) { _GifError = E_GIF_ERR_WRITE_FAILED; return GIF_ERROR; } // And local info. indicate image read. GifFile->PixelCount = 0; } return GIF_OK; } /****************************************************************************** * This routine should be called last, to close GIF file. *****************************************************************************/ static int EGifCloseFile(GifFileType* GifFile) { uint8_t Buf; if (GifFile == NULL) return GIF_ERROR; if (!IS_WRITEABLE(GifFile)) { // This file was NOT open for writing. _GifError = E_GIF_ERR_NOT_WRITEABLE; return GIF_ERROR; } Buf = ';'; WRITE(GifFile, &Buf, 1); if (GifFile->Image.ColorMap) { FreeMapObject(GifFile->Image.ColorMap); GifFile->Image.ColorMap = NULL; } if (GifFile->SColorMap) { FreeMapObject(GifFile->SColorMap); GifFile->SColorMap = NULL; } if (GifFile->HashTable) { Fog::MemMgr::free(GifFile->HashTable); } Fog::MemMgr::free(GifFile); return GIF_OK; } /****************************************************************************** * Put 2 bytes (word) into the given file: *****************************************************************************/ static int EGifPutWord(int Word, GifFileType * GifFile) { unsigned char c[2]; c[0] = Word & 0xff; c[1] = (Word >> 8) & 0xff; #ifndef DEBUG_NO_PREFIX if (WRITE(GifFile, c, 2) == 2) return GIF_OK; else return GIF_ERROR; #else return GIF_OK; #endif /* DEBUG_NO_PREFIX */ } /****************************************************************************** * Setup the LZ compression for this image: *****************************************************************************/ static int EGifSetupCompress(GifFileType * GifFile) { int BitsPerPixel; uint8_t Buf; // Test and see what color map to use, and from it # bits per pixel. if (GifFile->Image.ColorMap) BitsPerPixel = GifFile->Image.ColorMap->BitsPerPixel; else if (GifFile->SColorMap) BitsPerPixel = GifFile->SColorMap->BitsPerPixel; else { _GifError = E_GIF_ERR_NO_COLOR_MAP; return GIF_ERROR; } Buf = BitsPerPixel = (BitsPerPixel < 2 ? 2 : BitsPerPixel); WRITE(GifFile, &Buf, 1); /* Write the Code size to file. */ GifFile->Buf[0] = 0; /* Nothing was output yet. */ GifFile->BitsPerPixel = BitsPerPixel; GifFile->ClearCode = (1 << BitsPerPixel); GifFile->EOFCode = GifFile->ClearCode + 1; GifFile->RunningCode = GifFile->EOFCode + 1; GifFile->RunningBits = BitsPerPixel + 1; /* Number of bits per code. */ GifFile->MaxCode1 = 1 << GifFile->RunningBits; /* Max. code + 1. */ GifFile->CrntCode = FIRST_CODE; /* Signal that this is first one! */ GifFile->CrntShiftState = 0; /* No information in CrntShiftDWord. */ GifFile->CrntShiftDWord = 0; /* Clear hash table and send Clear to make sure the decoder do the same. */ _ClearHashTable(GifFile->HashTable); if (EGifCompressOutput(GifFile, GifFile->ClearCode) == GIF_ERROR) { _GifError = E_GIF_ERR_DISK_IS_FULL; return GIF_ERROR; } return GIF_OK; } /****************************************************************************** * The LZ compression routine: * This version compresses the given buffer Line of length LineLen. * This routine can be called a few times (one per scan line, for example), in * order to complete the whole image. ******************************************************************************/ static int EGifCompressLine(GifFileType * GifFile, GifPixelType * Line, int LineLen) { int i = 0, CrntCode, NewCode; unsigned long NewKey; GifPixelType Pixel; GifHashTableType *HashTable; HashTable = GifFile->HashTable; if (GifFile->CrntCode == FIRST_CODE) /* Its first time! */ CrntCode = Line[i++]; else CrntCode = GifFile->CrntCode; /* Get last code in compression. */ /* Decode LineLen items. */ while (i < LineLen) { Pixel = Line[i++]; /* Get next pixel from stream. */ /* Form a new unique key to search hash table for the code combines * CrntCode as Prefix string with Pixel as postfix char. */ NewKey = (((uint32_t) CrntCode) << 8) + Pixel; if ((NewCode = _ExistsHashTable(HashTable, NewKey)) >= 0) { /* This Key is already there, or the string is old one, so * simple take new code as our CrntCode: */ CrntCode = NewCode; } else { /* Put it in hash table, output the prefix code, and make our * CrntCode equal to Pixel. */ if (EGifCompressOutput(GifFile, CrntCode) == GIF_ERROR) { _GifError = E_GIF_ERR_DISK_IS_FULL; return GIF_ERROR; } CrntCode = Pixel; /* If however the HashTable if full, we send a clear first and * Clear the hash table. */ if (GifFile->RunningCode >= LZ_MAX_CODE) { /* Time to do some clearance: */ if (EGifCompressOutput(GifFile, GifFile->ClearCode) == GIF_ERROR) { _GifError = E_GIF_ERR_DISK_IS_FULL; return GIF_ERROR; } GifFile->RunningCode = GifFile->EOFCode + 1; GifFile->RunningBits = GifFile->BitsPerPixel + 1; GifFile->MaxCode1 = 1 << GifFile->RunningBits; _ClearHashTable(HashTable); } else { /* Put this unique key with its relative Code in hash table: */ _InsertHashTable(HashTable, NewKey, GifFile->RunningCode++); } } } /* Preserve the current state of the compression algorithm: */ GifFile->CrntCode = CrntCode; if (GifFile->PixelCount == 0) { /* We are done - output last Code and flush output buffers: */ if (EGifCompressOutput(GifFile, CrntCode) == GIF_ERROR) { _GifError = E_GIF_ERR_DISK_IS_FULL; return GIF_ERROR; } if (EGifCompressOutput(GifFile, GifFile->EOFCode) == GIF_ERROR) { _GifError = E_GIF_ERR_DISK_IS_FULL; return GIF_ERROR; } if (EGifCompressOutput(GifFile, FLUSH_OUTPUT) == GIF_ERROR) { _GifError = E_GIF_ERR_DISK_IS_FULL; return GIF_ERROR; } } return GIF_OK; } /****************************************************************************** * The LZ compression output routine: * This routine is responsible for the compression of the bit stream into * 8 bits (bytes) packets. * Returns GIF_OK if written successfully. *****************************************************************************/ static int EGifCompressOutput(GifFileType * GifFile, int Code) { int retval = GIF_OK; if (Code == FLUSH_OUTPUT) { while (GifFile->CrntShiftState > 0) { /* Get Rid of what is left in DWord, and flush it. */ if (EGifBufferedOutput(GifFile, GifFile->Buf, GifFile->CrntShiftDWord & 0xff) == GIF_ERROR) retval = GIF_ERROR; GifFile->CrntShiftDWord >>= 8; GifFile->CrntShiftState -= 8; } GifFile->CrntShiftState = 0; /* For next time. */ if (EGifBufferedOutput(GifFile, GifFile->Buf, FLUSH_OUTPUT) == GIF_ERROR) retval = GIF_ERROR; } else { GifFile->CrntShiftDWord |= ((long)Code) << GifFile->CrntShiftState; GifFile->CrntShiftState += GifFile->RunningBits; while (GifFile->CrntShiftState >= 8) { /* Dump out full bytes: */ if (EGifBufferedOutput(GifFile, GifFile->Buf, GifFile->CrntShiftDWord & 0xff) == GIF_ERROR) retval = GIF_ERROR; GifFile->CrntShiftDWord >>= 8; GifFile->CrntShiftState -= 8; } } /* If code cannot fit into RunningBits bits, must raise its size. Note */ /* however that codes above 4095 are used for special signaling. */ if (GifFile->RunningCode >= GifFile->MaxCode1 && Code <= 4095) { GifFile->MaxCode1 = 1 << ++GifFile->RunningBits; } return retval; } /****************************************************************************** * This routines buffers the given characters until 255 characters are ready * to be output. If Code is equal to -1 the buffer is flushed (EOF). * The buffer is Dumped with first byte as its size, as GIF format requires. * Returns GIF_OK if written successfully. *****************************************************************************/ static int EGifBufferedOutput(GifFileType * GifFile, uint8_t * Buf, int c) { if (c == FLUSH_OUTPUT) { /* Flush everything out. */ if (Buf[0] != 0 && WRITE(GifFile, Buf, Buf[0] + 1) != (unsigned)(Buf[0] + 1)) { _GifError = E_GIF_ERR_WRITE_FAILED; return GIF_ERROR; } /* Mark end of compressed data, by an empty block (see GIF doc): */ Buf[0] = 0; if (WRITE(GifFile, Buf, 1) != 1) { _GifError = E_GIF_ERR_WRITE_FAILED; return GIF_ERROR; } } else { if (Buf[0] == 255) { /* Dump out this buffer - it is full: */ if (WRITE(GifFile, Buf, Buf[0] + 1) != (unsigned)(Buf[0] + 1)) { _GifError = E_GIF_ERR_WRITE_FAILED; return GIF_ERROR; } Buf[0] = 0; } Buf[++Buf[0]] = c; } return GIF_OK; } /****************************************************************************** * This routine writes to disk an in-core representation of a GIF previously * created by DGifSlurp(). *****************************************************************************/ static int EGifSpew(GifFileType * GifFileOut) { int i, j, gif89 = false; int bOff; /* Block Offset for adding sub blocks in Extensions */ char SavedStamp[GIF_STAMP_LEN + 1]; for (i = 0; i < GifFileOut->ImageCount; i++) { for (j = 0; j < GifFileOut->SavedImages[i].ExtensionBlockCount; j++) { int function = GifFileOut->SavedImages[i].ExtensionBlocks[j].Function; if (function == COMMENT_EXT_FUNC_CODE || function == GRAPHICS_EXT_FUNC_CODE || function == PLAINTEXT_EXT_FUNC_CODE || function == APPLICATION_EXT_FUNC_CODE) { gif89 = true; } } } strncpy(SavedStamp, GifVersionPrefix, GIF_STAMP_LEN); if (gif89) { strncpy(GifVersionPrefix, GIF89_STAMP, GIF_STAMP_LEN); } else { strncpy(GifVersionPrefix, GIF87_STAMP, GIF_STAMP_LEN); } if (EGifPutScreenDesc(GifFileOut, GifFileOut->SWidth, GifFileOut->SHeight, GifFileOut->SColorResolution, GifFileOut->SBackGroundColor, GifFileOut->SColorMap) == GIF_ERROR) { strncpy(GifVersionPrefix, SavedStamp, GIF_STAMP_LEN); return GIF_ERROR; } strncpy(GifVersionPrefix, SavedStamp, GIF_STAMP_LEN); for (i = 0; i < GifFileOut->ImageCount; i++) { SavedImage *sp = &GifFileOut->SavedImages[i]; int SavedHeight = sp->ImageDesc.Height; int SavedWidth = sp->ImageDesc.Width; ExtensionBlock *ep; /* this allows us to delete images by nuking their rasters */ if (sp->RasterBits == NULL) continue; if (sp->ExtensionBlocks) { for (j = 0; j < sp->ExtensionBlockCount; j++) { ep = &sp->ExtensionBlocks[j]; if (j == sp->ExtensionBlockCount - 1 || (ep+1)->Function != 0) { /*** FIXME: Must check whether outputting * <ExtLen><Extension> is ever valid or if we should just * drop anything with a 0 for the Function. (And whether * we should drop here or in EGifPutExtension) */ if (EGifPutExtension(GifFileOut, (ep->Function != 0) ? ep->Function : '\0', ep->ByteCount, ep->Bytes) == GIF_ERROR) { return (GIF_ERROR); } } else { EGifPutExtensionFirst(GifFileOut, ep->Function, ep->ByteCount, ep->Bytes); for (bOff = j+1; bOff < sp->ExtensionBlockCount; bOff++) { ep = &sp->ExtensionBlocks[bOff]; if (ep->Function != 0) break; EGifPutExtensionNext(GifFileOut, 0, ep->ByteCount, ep->Bytes); } EGifPutExtensionLast(GifFileOut, 0, 0, NULL); j = bOff-1; } } } if (EGifPutImageDesc(GifFileOut, sp->ImageDesc.Left, sp->ImageDesc.Top, SavedWidth, SavedHeight, sp->ImageDesc.Interlace, sp->ImageDesc.ColorMap) == GIF_ERROR) { return GIF_ERROR; } for (j = 0; j < SavedHeight; j++) { if (EGifPutLine(GifFileOut, sp->RasterBits + j * SavedWidth, SavedWidth) == GIF_ERROR) return GIF_ERROR; } } if (EGifCloseFile(GifFileOut) == GIF_ERROR) return GIF_ERROR; return GIF_OK; } namespace Fog { // ============================================================================ // [Fog::GifDecoder] // ============================================================================ struct FOG_NO_EXPORT GifDecoder : public ImageDecoder { FOG_DECLARE_OBJECT(GifDecoder, ImageDecoder) GifDecoder(ImageCodecProvider* provider); virtual ~GifDecoder(); virtual void reset(); virtual err_t readHeader(); virtual err_t readImage(Image& image); private: GifFileType* _context; bool openGif(); void closeGif(); }; // ============================================================================ // [Fog::GifEncoder] // ============================================================================ struct FOG_NO_EXPORT GifEncoder : public ImageEncoder { FOG_DECLARE_OBJECT(GifEncoder, ImageEncoder) GifEncoder(ImageCodecProvider* provider); virtual ~GifEncoder(); virtual err_t writeImage(const Image& image); }; // ============================================================================ // [Fog::GifCodecProvider] // ============================================================================ struct GifCodecProvider : public ImageCodecProvider { GifCodecProvider(); virtual ~GifCodecProvider(); virtual uint32_t checkSignature(const void* mem, size_t length) const; virtual err_t createCodec(uint32_t codecType, ImageCodec** codec) const; }; GifCodecProvider::GifCodecProvider() { // Name of ImageCodecProvider. _name = FOG_S(GIF); // Supported codecs. _codecType = IMAGE_CODEC_DECODER; // Supported streams. _streamType = IMAGE_STREAM_GIF; // Supported extensions. _imageExtensions.reserve(1); _imageExtensions.append(FOG_S(gif)); } GifCodecProvider::~GifCodecProvider() { } uint32_t GifCodecProvider::checkSignature(const void* mem, size_t length) const { if (!mem || length < 3) return 0; const uint8_t* m = (const uint8_t*)mem; if (memcmp(m, "GIF", 3) != 0) return 0; if (length < 6) return 75; if (memcmp(m + 3, "87a", 3) != 0) return 0; if (memcmp(m + 3, "89a", 3) != 0) return 0; return 90; } err_t GifCodecProvider::createCodec(uint32_t codecType, ImageCodec** codec) const { ImageCodec* c = NULL; switch (codecType) { case IMAGE_CODEC_DECODER: c = fog_new GifDecoder(const_cast<GifCodecProvider*>(this)); break; case IMAGE_CODEC_ENCODER: return ERR_IMAGE_NO_ENCODER; default: return ERR_RT_INVALID_ARGUMENT; } if (FOG_IS_NULL(c)) return ERR_RT_OUT_OF_MEMORY; *codec = c; return ERR_OK; } // ============================================================================ // [Fog::GifDecoder] // ============================================================================ GifDecoder::GifDecoder(ImageCodecProvider* provider) : ImageDecoder(provider), _context(NULL) { } GifDecoder::~GifDecoder() { closeGif(); } void GifDecoder::reset() { closeGif(); ImageDecoder::reset(); } bool GifDecoder::openGif() { return (_context != NULL) || (getStream().isOpen() && (_context = DGifOpen(&_stream)) != NULL); } void GifDecoder::closeGif() { if (_context) DGifCloseFile(_context); _context = NULL; } err_t GifDecoder::readHeader() { // Don't read header more than once. if (isHeaderDone()) return _headerResult; // Mark header as done. _headerDone = true; if (!openGif()) return (_headerResult = ERR_IMAGEIO_INTERNAL_ERROR); _size.w = _context->SWidth; _size.h = _context->SHeight; _depth = _context->BitsPerPixel; _planes = 1; _actualFrame = 0; _framesCount = 0xFFFFFFFF; _format = IMAGE_FORMAT_I8; // Success. return (_headerResult = ERR_OK); } err_t GifDecoder::readImage(Image& image) { // read gif header if (readHeader() != ERR_OK) return getHeaderResult(); uint32_t *ptr; GifRowType *rows = NULL; GifRecordType rec; ColorMapObject *cmap; int i, j, done = 0, bg, r, g, b, w = 0, h = 0; int intoffset[] = { 0, 4, 2, 1 }; int intjump[] = { 8, 8, 4, 2 }; int transp = -1; err_t error = ERR_OK; uint32_t format = IMAGE_FORMAT_XRGB32; do { if (DGifGetRecordType(_context, &rec) == GIF_ERROR) { // ERROR... rec = TERMINATE_RECORD_TYPE; } if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) { if (DGifGetImageDesc(_context) == GIF_ERROR) { // ERROR... rec = TERMINATE_RECORD_TYPE; } w = _context->Image.Width; h = _context->Image.Height; rows = (GifRowType*)Fog::MemMgr::calloc(h * sizeof(GifRowType *)); if (!rows) { error = ERR_RT_OUT_OF_MEMORY; goto _End; } for (i = 0; i < h; i++) { rows[i] = (GifRowType)Fog::MemMgr::alloc(w * sizeof(GifPixelType)); if (!rows[i]) { error = ERR_RT_OUT_OF_MEMORY; goto _End; } } if (_context->Image.Interlace) { for (i = 0; i < 4; i++) { for (j = intoffset[i]; j < h; j += intjump[i]) { DGifGetLine(_context, rows[j], w); } } } else { for (i = 0; i < h; i++) { DGifGetLine(_context, rows[i], w); } } done = 1; } else if (rec == EXTENSION_RECORD_TYPE) { int ext_code; uint8_t* ext = NULL; DGifGetExtension(_context, &ext_code, &ext); while (ext) { if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) { transp = (int)ext[4]; } ext = NULL; DGifGetExtensionNext(_context, &ext); } } } while (rec != TERMINATE_RECORD_TYPE && !done); if (transp >= 0) format = IMAGE_FORMAT_PRGB32; if ((error = image.create(SizeI(w, h), format))) goto _End; bg = _context->SBackGroundColor; cmap = (_context->Image.ColorMap ? _context->Image.ColorMap : _context->SColorMap); ptr = (uint32_t*)image.getFirstX(); for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { if (rows[i][j] == transp) { //r = cmap->Colors[bg].Red; //g = cmap->Colors[bg].Green; //b = cmap->Colors[bg].Blue; //*ptr++ = 0x00FFFFFF & ((r << 16) | (g << 8) | b); *ptr++ = 0; } else { r = cmap->Colors[rows[i][j]].Red; g = cmap->Colors[rows[i][j]].Green; b = cmap->Colors[rows[i][j]].Blue; *ptr++ = (0xFF000000) | (r << 16) | (g << 8) | b; } } } _End: if (rows) { for (i = 0; i < h; i++) { if (rows[i]) Fog::MemMgr::free(rows[i]); } Fog::MemMgr::free(rows); } image._modified(); return error; } // ============================================================================ // [Fog::GifEncoder] // ============================================================================ // TODO GifEncoder::GifEncoder(ImageCodecProvider* provider) : ImageEncoder(provider) { } GifEncoder::~GifEncoder() { } err_t GifEncoder::writeImage(const Image& image) { // TODO return 0; } } // Fog namespace FOG_IMPLEMENT_OBJECT(Fog::GifDecoder) FOG_IMPLEMENT_OBJECT(Fog::GifEncoder) // =========================================================================== // [Init / Fini] // =========================================================================== namespace Fog { FOG_NO_EXPORT void ImageCodecProvider_initGIF(void) { ImageCodecProvider* provider = fog_new GifCodecProvider(); ImageCodecProvider::addProvider(provider); provider->deref(); } } // Fog namespace
30.907305
156
0.60134
[ "object" ]
50d8fe2bd15ba44a62b02de9ad8292840d7c4076
571
cpp
C++
folders/LeetCode C++ Solutions/rotate-array.cpp
angelopassaro/Hacktoberfest-1
21f90f5d49efba9b1a27f4d9b923f5017ab43f0e
[ "Apache-2.0" ]
1
2020-10-06T01:20:07.000Z
2020-10-06T01:20:07.000Z
folders/LeetCode C++ Solutions/rotate-array.cpp
angelopassaro/Hacktoberfest-1
21f90f5d49efba9b1a27f4d9b923f5017ab43f0e
[ "Apache-2.0" ]
null
null
null
folders/LeetCode C++ Solutions/rotate-array.cpp
angelopassaro/Hacktoberfest-1
21f90f5d49efba9b1a27f4d9b923f5017ab43f0e
[ "Apache-2.0" ]
null
null
null
/** * Author: Siddhant Pandya * Problem: 189. Rotate Array */ class Solution { public: void rotate(vector<int>& nums, int k) { k %= nums.size(); vector<int> arr(nums.size()); int i=nums.size()-k,y=0; for(int x=i;x<nums.size();x++) { arr[y]=nums[x]; y++; } for(int x=0;x<i;x++) { arr[y]=nums[x]; y++; } for(int x=0;x<nums.size();x++) { nums[x]=arr[x]; } } };
19.689655
44
0.362522
[ "vector" ]
50e2d7af1436b7d6b3429dfe1d6b0961522e09e5
2,409
cc
C++
248/248.cc
coderfive/hihocoder
dbc31e25d73f85265c3a6f363cc8a242c69e0c06
[ "MIT" ]
null
null
null
248/248.cc
coderfive/hihocoder
dbc31e25d73f85265c3a6f363cc8a242c69e0c06
[ "MIT" ]
null
null
null
248/248.cc
coderfive/hihocoder
dbc31e25d73f85265c3a6f363cc8a242c69e0c06
[ "MIT" ]
null
null
null
#include <vector> #include <iostream> struct lnode { int left, right ; }; lnode level_nodes[101][101]; int level[101]; int child[101]; int parent[101]; bool is_leaf[101]; int dist[101][101]; int main () { int N, M, K, edges = 1; std::cin >> N >> M >> K; std::vector<int> A(M); for (auto & a : A) std::cin >> a; int last = 0, cur; for (int i = 0; i < M; i++) { last = 0; for (int j = 0; j < A[i]; j++) { std::cin >> cur; level[cur] = i; level_nodes[i][cur].left = last; level_nodes[i][last].right = cur; last = cur; } level_nodes[i][0].left = cur; } std::vector<int> leaves(K); for (auto & a : leaves) { std::cin >> a; is_leaf[a] = true; } parent[level_nodes[0][0].right] = 0; for (int i = 0; i < K; i++) for (int j = 0; j < K; j++) { std::cin >> cur; dist[leaves[i]][leaves[j]] = cur; dist[leaves[j]][leaves[i]] = cur; } for (int l = M-1; l > 0; l--) { int n = level_nodes[l][0].right; int tmp = n; int il = l-1; for (int in = level_nodes[il][0].right; in ; in = level_nodes[il][in].right) { if (is_leaf[in]) continue; parent[tmp] = in; child[in] = tmp; tmp = in; break; } } for (int l = M-1; l > 0; l--) { int n = level_nodes[l][0].right; for (int j = 1; j < A[l]; j++) { int left = n; n = level_nodes[l][n].right; int ch = left, nch = n; while (!is_leaf[ch]) ch = child[ch]; while (!is_leaf[nch]) nch = child[nch]; int d = dist[ch][nch] - (level[ch] - level[left]) - (level[nch]-level[n]); int il = l-1; if (d == 2) parent[n] = parent[left]; else { left = parent[left]; for (int in = level_nodes[il][left].right; in ; in = level_nodes[il][in].right) { if (is_leaf[in]) continue; parent[n] = in; child[in] = n; break; } } } } for (int i = 1; i <= N; i++) std::cout << parent[i] << ' '; return 0; }
28.341176
97
0.403902
[ "vector" ]
50eec474b3faecba4f43bd90f99d68f946a5afff
8,866
cc
C++
mysql-server/router/src/routing/src/dest_round_robin.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/router/src/routing/src/dest_round_robin.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/router/src/routing/src/dest_round_robin.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2017, 2020, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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 */ #include "dest_round_robin.h" #include <chrono> #include <iterator> #include <memory> #include <stdexcept> #include "common.h" // rename_thread #include "mysql/harness/logging/logging.h" #include "mysql/harness/net_ts/impl/poll.h" #include "mysql/harness/net_ts/impl/socket.h" #include "mysql/harness/net_ts/impl/socket_error.h" #include "mysql/harness/net_ts/internet.h" #include "mysql/harness/net_ts/io_context.h" #include "mysql/harness/net_ts/socket.h" #include "mysql/harness/stdx/expected.h" #include "mysqlrouter/destination.h" IMPORT_LOG_FUNCTIONS() using mysql_harness::TCPAddress; using namespace std::chrono_literals; // Timeout for trying to connect with quarantined servers static constexpr auto kQuarantinedConnectTimeout = 1000ms; // How long we pause before checking quarantined servers again (seconds) static const auto kQuarantineCleanupInterval = 3s; // Make sure Quarantine Manager Thread is run even with nothing in quarantine static const auto kTimeoutQuarantineConditional = 2s; void *DestRoundRobin::run_thread(void *context) { static_cast<DestRoundRobin *>(context)->quarantine_manager_thread(); return nullptr; } void DestRoundRobin::start(const mysql_harness::PluginFuncEnv * /*env*/) { quarantine_thread_.run(&run_thread, this); } class QuanrantinableDestination : public Destination { public: QuanrantinableDestination(std::string id, std::string host, uint16_t port, DestRoundRobin *balancer, size_t ndx) : Destination(std::move(id), std::move(host), port), balancer_{balancer}, ndx_{ndx} {} void connect_status(std::error_code ec) override { if (ec != std::error_code()) { balancer_->add_to_quarantine(ndx_); } } bool good() const override { return !balancer_->is_quarantined(ndx_); } private: DestRoundRobin *balancer_; size_t ndx_; }; Destinations DestRoundRobin::destinations() { Destinations dests; { std::lock_guard<std::mutex> lk(mutex_update_); const auto end = destinations_.end(); const auto begin = destinations_.begin(); const auto sz = destinations_.size(); auto cur = begin; // move iterator forward and remember the position as 'last' std::advance(cur, start_pos_); auto last = cur; size_t n = start_pos_; // for start_pos == 2: // // 0 1 2 3 4 x // ^ ^ ^ // | | `- end // | `- last|cur // `- begin // from last to end; // // dests = [2 3 4] for (; cur != end; ++cur, ++n) { auto const &dest = *cur; dests.push_back(std::make_unique<QuanrantinableDestination>( dest.str(), dest.address(), dest.port(), this, n)); } // from begin to before-last // // dests = [2 3 4] + [0 1] // for (cur = begin, n = 0; cur != last; ++cur, ++n) { auto const &dest = *cur; dests.push_back(std::make_unique<QuanrantinableDestination>( dest.str(), dest.address(), dest.port(), this, n)); } if (++start_pos_ >= sz) start_pos_ = 0; } return dests; } DestRoundRobin::~DestRoundRobin() { stopper_.set_value(); quarantine_.serialize_with_cv([](auto &, auto &cv) { cv.notify_one(); }); quarantine_thread_.join(); } void DestRoundRobin::add_to_quarantine(const size_t index) noexcept { assert(index < size()); if (index >= size()) { log_debug("Impossible server being quarantined (index %zu)", index); return; } quarantine_.serialize_with_cv([this, index](auto &q, auto &cv) { if (!q.has(index)) { log_debug("Quarantine destination server %s (index %zu)", destinations_.at(index).str().c_str(), index); q.add(index); cv.notify_one(); } }); } static stdx::expected<void, std::error_code> tcp_port_alive( net::io_context &io_ctx, const std::string &host, uint16_t port, std::chrono::milliseconds connect_timeout) { net::ip::tcp::resolver resolver(io_ctx); const auto resolve_res = resolver.resolve(host, std::to_string(port)); if (!resolve_res) { return resolve_res.get_unexpected(); } std::error_code last_ec{}; // try all known addresses of the hostname for (auto const &resolved : resolve_res.value()) { net::ip::tcp::socket sock(io_ctx); auto open_res = sock.open(resolved.endpoint().protocol()); if (!open_res) { return open_res.get_unexpected(); } sock.native_non_blocking(true); const auto connect_res = sock.connect(resolved.endpoint()); if (!connect_res) { if (connect_res.error() == make_error_condition(std::errc::operation_in_progress) || connect_res.error() == make_error_condition(std::errc::operation_would_block)) { std::array<pollfd, 1> pollfds = {{ {sock.native_handle(), POLLOUT, 0}, }}; const auto wait_res = net::impl::poll::poll( pollfds.data(), pollfds.size(), connect_timeout); if (!wait_res) { last_ec = wait_res.error(); } else { net::socket_base::error err; const auto status_res = sock.get_option(err); if (!status_res) { last_ec = status_res.error(); } else if (err.value() != 0) { last_ec = net::impl::socket::make_error_code(err.value()); } else { // success, we can continue return {}; } } } else { last_ec = connect_res.error(); } } else { // everything is fine, we are connected return {}; } // it failed, try the next address } return stdx::make_unexpected(last_ec); } std::vector<size_t> Quarantine::quarantined() const { return quarantined_; } void Quarantine::add(size_t ndx) { quarantined_.push_back(ndx); } bool Quarantine::has(size_t ndx) const { const auto it = std::find(quarantined_.begin(), quarantined_.end(), ndx); return it != quarantined_.end(); } size_t Quarantine::size() const { return quarantined_.size(); } bool Quarantine::empty() const { return quarantined_.empty(); } void Quarantine::erase(size_t ndx) { quarantined_.erase(std::remove(quarantined_.begin(), quarantined_.end(), ndx), quarantined_.end()); } void DestRoundRobin::cleanup_quarantine() noexcept { auto cpy_quarantined( quarantine_([](auto const &q) { return q.quarantined(); })); // Nothing to do when nothing quarantined if (cpy_quarantined.empty()) return; for (auto const ndx : cpy_quarantined) { if (stopped_.wait_for(0s) == std::future_status::ready) { return; } const auto addr = destinations_.at(ndx); const auto sock_res = tcp_port_alive(io_ctx_, addr.address(), addr.port(), kQuarantinedConnectTimeout); if (sock_res) { log_debug("Unquarantine destination server %s (index %zu)", addr.str().c_str(), ndx); quarantine_([ndx](auto &q) { q.erase(ndx); }); } } } void DestRoundRobin::quarantine_manager_thread() noexcept { mysql_harness::rename_thread( "RtQ:<unknown>"); // TODO change <unknown> to instance name while (stopped_.wait_for(0s) != std::future_status::ready) { // wait until something got added to quarantie or shutdown quarantine_.wait_for(kTimeoutQuarantineConditional, [this](auto &q) { return !q.empty() || stopped_.wait_for(0s) == std::future_status::ready; }); // if we aren't shutting down, cleanup and wait if (stopped_.wait_for(0s) != std::future_status::ready) { cleanup_quarantine(); // Temporize stopped_.wait_for(kQuarantineCleanupInterval); } } } size_t DestRoundRobin::size_quarantine() { return quarantine_([](auto &q) { return q.size(); }); }
30.467354
80
0.660388
[ "vector" ]
50f2814697e3b2e917316646be56938858d79e76
6,750
cxx
C++
src/font/glyph_compiler.cxx
repagh/freetype-direct-gl
a6d909b134bd06933d38e3db6a6e39ae6142aefd
[ "MIT" ]
35
2018-08-27T14:30:55.000Z
2022-01-20T15:04:50.000Z
src/font/glyph_compiler.cxx
repagh/freetype-direct-gl
a6d909b134bd06933d38e3db6a6e39ae6142aefd
[ "MIT" ]
2
2019-01-01T20:43:22.000Z
2020-07-24T14:11:02.000Z
src/font/glyph_compiler.cxx
repagh/freetype-direct-gl
a6d909b134bd06933d38e3db6a6e39ae6142aefd
[ "MIT" ]
6
2018-12-11T07:19:15.000Z
2021-12-24T01:16:22.000Z
#include <ft2build.h> #include FT_FREETYPE_H #include FT_STROKER_H // #include FT_ADVANCES_H #include FT_LCD_FILTER_H #include <cassert> #include <iostream> #include "opengl.h" #include "glyph_compiler.h" #include "err_msg.h" #include "cu2qu.h" namespace ftdgl { namespace impl { enum Kind { SOLID, QUADRATIC_CURVE }; struct compile_context_s { uint8_t * addr; size_t size; int contourCount; FT_Pos firstX, firstY, currentX, currentY; int unitPerEM; }; static int MoveToFunction(const FT_Vector *to, void *user); static int LineToFunction(const FT_Vector *to, void *user); static int ConicToFunction(const FT_Vector *control, const FT_Vector *to, void *user); static int CubicToFunction(const FT_Vector *controlOne, const FT_Vector *controlTwo, const FT_Vector *to, void *user); static void AppendTriangle(compile_context_s * context, FT_Pos x1, FT_Pos y1, FT_Pos x2, FT_Pos y2, FT_Pos x3, FT_Pos y3, Kind kind); size_t compile_glyph(uint8_t * addr, int unitPerEM, FT_Outline & outline) { FT_Outline_Funcs callbacks; compile_context_s context {.addr=addr, .size=0, .contourCount=0, .firstX=0, .firstY=0, .currentX=0, .currentY=0, .unitPerEM = unitPerEM }; callbacks.move_to = MoveToFunction; callbacks.line_to = LineToFunction; callbacks.conic_to = ConicToFunction; callbacks.cubic_to = CubicToFunction; callbacks.shift = 0; callbacks.delta = 0; FT_Error error = FT_Outline_Decompose(&outline, &callbacks, &context); if (error) { err_msg(error, __LINE__); return 0; } return context.size; } int MoveToFunction(const FT_Vector *to, void *user) { compile_context_s * context = reinterpret_cast<compile_context_s*>(user); context->firstX = context->currentX = to->x; context->firstY = context->currentY = to->y; context->contourCount = 0; return 0; } int LineToFunction(const FT_Vector *to, void *user) { compile_context_s * context = reinterpret_cast<compile_context_s*>(user); if (++context->contourCount >= 2) { AppendTriangle(context, context->firstX, context->firstY, context->currentX, context->currentY, to->x, to->y, SOLID); } context->currentX = to->x; context->currentY = to->y; return 0; } int ConicToFunction(const FT_Vector *control, const FT_Vector *to, void *user) { compile_context_s * context = reinterpret_cast<compile_context_s*>(user); if (++context->contourCount >= 2) { AppendTriangle(context, context->firstX, context->firstY, context->currentX, context->currentY, to->x, to->y, SOLID); } AppendTriangle(context, context->currentX, context->currentY, control->x, control->y, to->x, to->y, QUADRATIC_CURVE); context->currentX = to->x; context->currentY = to->y; return 0; } int CubicToFunction(const FT_Vector *controlOne, const FT_Vector *controlTwo, const FT_Vector *to, void *user) { compile_context_s * context = reinterpret_cast<compile_context_s*>(user); if (++context->contourCount >= 2) { AppendTriangle(context, context->firstX, context->firstY, context->currentX, context->currentY, to->x, to->y, SOLID); } point_type_vector spline_points; point_type_vector ctl_points{ {(double)context->currentX, (double)context->currentY}, {(double)controlOne->x, (double)controlOne->y}, {(double)controlTwo->x, (double)controlTwo->y}, {(double)to->x, (double)to->y} }; if (curve_to_quadratic(ctl_points, spline_points)) { auto it = spline_points.begin() + 1; while(it != spline_points.end() - 2) { auto x = std::real(*it), y = std::imag(*it); auto nx = std::real(*(it + 1)), ny = std::imag(*(it + 1)); auto implied_x = .5 * (x + nx), implied_y = .5 * (y + ny); AppendTriangle(context, context->currentX, context->currentY, x, y, implied_x, implied_y, QUADRATIC_CURVE); context->currentX = implied_x; context->currentY = implied_y; it++; } auto x = std::real(*it), y = std::imag(*it); auto nx = std::real(*(it + 1)), ny = std::imag(*(it + 1)); AppendTriangle(context, context->currentX, context->currentY, x, y, nx, ny, QUADRATIC_CURVE); } else { AppendTriangle(context, context->currentX, context->currentY, controlOne->x, controlOne->y, to->x, to->y, QUADRATIC_CURVE); AppendTriangle(context, context->currentX, context->currentY, controlTwo->x, controlTwo->y, to->x, to->y, QUADRATIC_CURVE); } context->currentX = to->x; context->currentY = to->y; return 0; } static void AppendVertex(compile_context_s * context, FT_Pos x, FT_Pos y, GLfloat s, GLfloat t) { GLfloat* p = reinterpret_cast<GLfloat*>(context->addr); *p++ = (GLfloat)x / 64.0;//context->unitPerEM; *p++ = (GLfloat)y / 64.0;//context->unitPerEM; *p++ = s; *p++ = t; context->addr += sizeof(GLfloat) * 4; context->size += sizeof(GLfloat) * 4; } void AppendTriangle(compile_context_s * context, FT_Pos x1, FT_Pos y1, FT_Pos x2, FT_Pos y2, FT_Pos x3, FT_Pos y3, Kind kind) { switch(kind) { case SOLID: AppendVertex(context, x1, y1, 0, 1); AppendVertex(context, x2, y2, 0, 1); AppendVertex(context, x3, y3, 0, 1); break; case QUADRATIC_CURVE: AppendVertex(context, x1, y1, 0, 0); AppendVertex(context, x2, y2, 0.5, 0); AppendVertex(context, x3, y3, 1, 1); break; } } } //namespace impl } //namespace ftdgl
29.867257
103
0.538667
[ "solid" ]
50f535bb19689fb9203cba1e5d5e3352154939d0
44,181
cpp
C++
Morphs/Importers/Utils/Framework/Source/GeometryWriter.cpp
SergioRZMasson/BabylonPolymorph
9def147959dc6292a36f9a2b055edf1d58cb2851
[ "MIT" ]
16
2020-01-09T13:36:46.000Z
2021-11-16T10:09:54.000Z
Morphs/Importers/Utils/Framework/Source/GeometryWriter.cpp
SergioRZMasson/BabylonPolymorph
9def147959dc6292a36f9a2b055edf1d58cb2851
[ "MIT" ]
30
2020-01-09T00:49:50.000Z
2020-07-14T18:21:52.000Z
Morphs/Importers/Utils/Framework/Source/GeometryWriter.cpp
SergioRZMasson/BabylonPolymorph
9def147959dc6292a36f9a2b055edf1d58cb2851
[ "MIT" ]
10
2020-04-09T14:10:29.000Z
2022-03-18T09:18:40.000Z
/******************************************************** * * * Copyright (C) Microsoft. All rights reserved. * * * ********************************************************/ #include "FrameworkPch.h" #include <functional> #include <memory> #include <vector> #include <Framework/Vertex.h> #include <Framework/Frame.h> #include <Framework/GeometryWriter.h> #include <Framework/Types.h> namespace { inline uint32_t GetIndexBufferElementSizeInBytes(uint32_t numVertices) { return (numVertices >= std::numeric_limits<uint16_t>::max()) ? sizeof(uint32_t) : sizeof(uint16_t); } } namespace Babylon { namespace Framework { namespace V1 { class GeometryWriter : public IGeometryWriter, public CommonFrameWriter { private: static const uint32_t sVERSION = 1; public: GeometryWriter(); virtual ~GeometryWriter(); virtual void BeginFrame( std::shared_ptr<IBuffer> const& outputBuffer, uint32_t numMeshes, EByteOrder byteOrder) override; virtual void BeginFrame( std::shared_ptr<IBuffer> const& outputBuffer, uint32_t numMeshes, EByteOrder byteOrder, EFrameQuality quality) override; virtual Frame* EndFrame() override; virtual void BeginMesh(uint32_t meshId, uint32_t parentId = 0, uint32_t materialId = 0, uint32_t skeletonId = 0) override; virtual void EndMesh() override; virtual void AddJoint(uint32_t id, int parentJointIndex, const float* invBindMatrix, const float* transform) override; virtual VertexData LockVertexData(uint32_t numVertices, uint32_t numIndices, uint32_t formatMask, bool areIndices32bit = true) override; virtual void UnlockVertexData(const VertexData& data) override; virtual void SetSkeletonId(uint32_t skeletonID) override; virtual uint32_t GetSkeletonId() const override; virtual void SetTransform(_In_reads_(16) const float* transform) override; virtual const float* GetTransform() override; virtual void SetBoundingBox(_In_reads_(3) const float* center, _In_reads_(3) const float* extents) override; virtual void SetFlags(uint32_t flags) override; virtual void AddVertex(_In_reads_(numVertices) const Vertex* pVertices, uint32_t numVertices) override; virtual void AddIndex(_In_reads_(numIndices) const uint32_t* pIndices, uint32_t numIndices) override; virtual uint32_t GetVersion() const override; virtual void SetSourceMeshID(uint32_t sourceMeshId) override; virtual uint32_t GetVertexBufferSize() const override; virtual uint32_t GetIndexBufferSize() const override; protected: void Reset(); inline bool IsValidMesh() const { return m_meshId != 0; } void EndMeshSegment(); void EndNodeSegment(); void EndSkeletonSegment(); void EndMeshInstanceSegment(); uint32_t WriteArray( _In_reads_bytes_(numElements*elementSizeInBytes) void* srcArray, uint32_t numElements, uint32_t elementSizeInBytes, std::shared_ptr<IBuffer> const& outputBuffer); uint32_t WriteIndexArray( _In_reads_bytes_(numElements * GetIndexBufferElementSizeInBytes(numVertices)) void* srcArray, uint32_t numElements, uint32_t numVertices, std::shared_ptr<IBuffer> const& outputBuffer); private: GeometryWriter(const GeometryWriter& rhs); GeometryWriter& operator=(const GeometryWriter& other); enum BufferIDs { kBufferPos = 0, kBufferkNormal, kBufferTangent, kBufferColor, kBufferUV0, kBufferUV1, kBufferIndex, kBufferJointIndices, kBufferJointWeights, kNumBuffers //Must be last }; enum IndexType { kIndexUnknown = 0, kIndexSmall, kIndexBig }; // Working buffers MemoryBuffer m_buffers[kNumBuffers]; uint32_t m_meshId; uint32_t m_materialId; uint32_t m_skeletonId; uint32_t m_meshParentId; uint32_t m_totalVertices; uint32_t m_totalIndices; IndexType m_indexType; float m_transform[16]; float m_bbox[6]; uint16_t m_flags; bool m_hasBoundingBox; uint32_t m_sourceMeshId; InstanceType m_instanceType; bool m_hasLockedData; // True if a caller holds a lock on our data bool m_areIndices32bit = true; std::vector<SkeletonSegment::Joint> m_joints; }; GeometryWriter::GeometryWriter() { m_meshId = 0; m_meshParentId = 0; m_indexType = kIndexUnknown; m_totalIndices = 0; m_totalVertices = 0; m_hasLockedData = false; m_instanceType = InstanceType::None; m_flags = 0; } GeometryWriter::~GeometryWriter() { } uint32_t GeometryWriter::GetVersion() const { return sVERSION; } void GeometryWriter::Reset() { this->DoReset(); m_meshId = 0; m_meshParentId = 0; m_materialId = 0; m_skeletonId = 0; m_indexType = kIndexUnknown; m_totalIndices = 0; m_totalVertices = 0; m_frameStartOffset = 0; m_hasLockedData = false; m_flags = 0; m_hasBoundingBox = false; m_joints.clear(); m_instanceType = None; memset(m_bbox, 0, sizeof(m_bbox)); // Reset all buffers for (int i = 0; i < kNumBuffers; ++i) { m_buffers[i].Reset(); } } //--------------------------------------------------------------------- void GeometryWriter::BeginFrame( std::shared_ptr<Babylon::Framework::IBuffer> const& outputBuffer, uint32_t numMeshes, EByteOrder byteOrder) { BeginFrame(outputBuffer, numMeshes, byteOrder, EFrameQuality::kHigh); } void GeometryWriter::BeginFrame( std::shared_ptr<Babylon::Framework::IBuffer> const& outputBuffer, uint32_t numMeshes, EByteOrder byteOrder, EFrameQuality quality) { Reset(); this->SetFrameQualityLevel(quality); this->DoBeginFrame(outputBuffer, numMeshes, byteOrder, kFrameGeom); } //--------------------------------------------------------------------- Frame* GeometryWriter::EndFrame() { if (m_meshId != 0) { throw Utils::BabylonFailException("Missing call to EndMesh"); } return this->DoEndFrame(); } //--------------------------------------------------------------------- void GeometryWriter::BeginMesh(uint32_t meshId, uint32_t parentId, uint32_t materialId, uint32_t skeletonId) { if (m_outputBuffer == nullptr) { throw Utils::BabylonFailException("GeometryWriter::BeginMesh: You must call BeginFrame first"); } if (m_meshId != 0) { throw Utils::BabylonFailException("Call to BeginMesh without a call to EndMesh"); } if (meshId == 0) { throw Utils::BabylonInvalidArgException("Invalid meshId of 0 specified"); } BabylonAssertExpr(m_hasLockedData == false, "GeoemtryWriter::BeginMesh - has locked data"); // Reset all buffers for (int i = 0; i < kNumBuffers; ++i) { m_buffers[i].Reset(); } // Set transform to identity memset(m_transform, 0, sizeof(m_transform)); m_transform[0] = m_transform[5] = m_transform[10] = m_transform[15] = 1.0f; memset(m_bbox, 0, sizeof(m_bbox)); m_hasBoundingBox = false; m_meshId = meshId; m_meshParentId = parentId; m_materialId = materialId; m_skeletonId = skeletonId; } //--------------------------------------------------------------------- void GeometryWriter::EndMesh() { if (m_outputBuffer == nullptr) { throw Utils::BabylonFailException("GeoemtryWriter::EndMesh - NULL output buffer"); } if (!IsValidMesh()) { throw Utils::BabylonFailException("GeoemtryWriter::EndMesh - Need to call BeginMesh first"); } if ((m_totalIndices % 3) != 0) { throw Utils::BabylonFailException("GeoemtryWriter::EndMesh - Invalid index count"); } BabylonAssertExpr(m_hasLockedData == false, "GeoemtryWriter::EndMesh - has locked data"); // Ensure data is valid if (m_totalVertices > 0 && m_joints.size() > 0) { throw Utils::BabylonFailException("GeoemtryWriter::EndMesh - Cannot have Joint and Vertex data on same object"); } if (m_instanceType != None && m_joints.size() > 0) { throw Utils::BabylonFailException("GeoemtryWriter::EndMesh - Cannot have Joint data within an instance segment"); } if (m_instanceType != None && m_totalVertices > 0) { throw Utils::BabylonFailException("GeoemtryWriter::EndMesh - Cannot have Vertex data within an instance segment"); } if (m_totalVertices > 0) { EndMeshSegment(); } else if (m_joints.size() > 0) { EndSkeletonSegment(); } else if (m_instanceType != InstanceType::None) { EndMeshInstanceSegment(); } else { EndNodeSegment(); } // Update state ++m_numItems; // Reset the state m_meshId = 0; m_meshParentId = 0; m_indexType = kIndexUnknown; m_totalIndices = 0; m_totalVertices = 0; m_joints.clear(); m_sourceMeshId = 0; m_instanceType = None; m_flags = 0; } //--------------------------------------------------------------------- void GeometryWriter::EndMeshSegment() { // Write out a MeshSegment which contains mesh geometry data // Copy the serialized streams to the output buffer MeshSegment segment; memset(&segment, 0, sizeof(segment)); segment.Version = m_byteSwapU32(MeshSegment::kVersion0); segment.MeshID = m_byteSwapU32(m_meshId); segment.ParentID = m_byteSwapU32(m_meshParentId); segment.MaterialID = m_byteSwapU32(m_materialId); segment.NumVertices = m_byteSwapU32(m_totalVertices); segment.NumIndices = m_byteSwapU32(m_totalIndices); segment.Type = MeshBaseSegment::kTypeGeometry; segment.Flags = m_byteSwapU16(m_flags); if (m_skeletonId) { // This mesh is linked to a skeleton. This extra information is described by an extension header: MeshSkeletonBinding skeletonBinding; memset(&skeletonBinding, 0, sizeof(skeletonBinding)); skeletonBinding.SkeletonID = m_byteSwapU32(m_skeletonId); AddExtensionHeader(ExtensionHeader::kMeshSkeletonBinding, skeletonBinding); } // Transform uint32_t* srcTransform = (uint32_t*)m_transform; for (int i = 0; i < 16; ++i, ++srcTransform) { *srcTransform = m_byteSwapU32(*srcTransform); } memcpy_s(segment.Transform, sizeof(float) * 16, m_transform, sizeof(float) * 16); // Calculate format mask if (m_totalIndices > 0) { if (GetIndexBufferElementSizeInBytes(m_totalVertices) == sizeof(uint32_t)) { segment.FormatMask |= MeshSegment::kHasBigIndices; } else { segment.FormatMask |= MeshSegment::kHasIndices; } } if (m_buffers[kBufferPos].GetSizeInBytes() > 0) segment.FormatMask |= MeshSegment::kHasPosition; if (m_buffers[kBufferColor].GetSizeInBytes() > 0) { segment.FormatMask |= MeshSegment::kHasColor; // New files have this additional flag for vertex colors segment.Flags |= MeshSegment::Flags::kDisplayVertexColors; } if (m_buffers[kBufferkNormal].GetSizeInBytes() > 0) segment.FormatMask |= MeshSegment::kHasNormals; if (m_buffers[kBufferTangent].GetSizeInBytes() > 0) segment.FormatMask |= MeshSegment::kHasTangents; if (m_buffers[kBufferUV0].GetSizeInBytes() > 0) segment.FormatMask |= MeshSegment::kHasUV0; if (m_buffers[kBufferUV1].GetSizeInBytes() > 0) segment.FormatMask |= MeshSegment::kHasUV1; if (m_buffers[kBufferJointIndices].GetSizeInBytes() > 0 && m_buffers[kBufferJointWeights].GetSizeInBytes() > 0) segment.FormatMask |= MeshSegment::kHasJointData; if (m_hasBoundingBox) { uint32_t* bbox = (uint32_t*)m_bbox; bbox[0] = m_byteSwapU32(bbox[0]); bbox[1] = m_byteSwapU32(bbox[1]); bbox[2] = m_byteSwapU32(bbox[2]); bbox[3] = m_byteSwapU32(bbox[3]); bbox[4] = m_byteSwapU32(bbox[4]); bbox[5] = m_byteSwapU32(bbox[5]); memcpy_s(segment.BoundsCenter, sizeof(float) * 3, &bbox[0], sizeof(float) * 3); memcpy_s(segment.BoundsExtents, sizeof(float) * 3, &bbox[3], sizeof(float) * 3); segment.FormatMask |= MeshSegment::kHasBoundingBox; } segment.FormatMask = m_byteSwapU32(segment.FormatMask); segment.Flags = m_byteSwapU16(segment.Flags); // Write header... uint32_t headerOffset = m_outputBuffer->WriteDataRaw(&segment, sizeof(segment), 4); // Save mesh offset m_savedItemOffsets.push_back(headerOffset); // Write the arrays uint32_t firstExtensionHeaderOffset = FlushExtensionHeaders(); uint32_t posOffset = 0; uint32_t colOffset = 0; uint32_t normalOffset = 0; uint32_t tangentOffset = 0; uint32_t uv0Offset = 0; uint32_t uv1Offset = 0; uint32_t indexOffset = 0; uint32_t jointIndexOffset = 0; uint32_t jointWeightOffset = 0; if (m_buffers[kBufferPos].GetSizeInBytes() > 0) posOffset = WriteArray(static_cast<void*>(m_buffers[kBufferPos].GetBuffer()), m_totalVertices * 3, sizeof(float), m_outputBuffer); if (m_buffers[kBufferColor].GetSizeInBytes() > 0) colOffset = WriteArray(static_cast<void*>(m_buffers[kBufferColor].GetBuffer()), m_totalVertices, sizeof(uint32_t), m_outputBuffer); if (m_buffers[kBufferkNormal].GetSizeInBytes() > 0) { normalOffset = WriteArray(static_cast<void*>(m_buffers[kBufferkNormal].GetBuffer()), m_totalVertices * 3, sizeof(float), m_outputBuffer); } if (m_buffers[kBufferTangent].GetSizeInBytes() > 0) { tangentOffset = WriteArray(static_cast<void*>(m_buffers[kBufferTangent].GetBuffer()), m_totalVertices * 4, sizeof(float), m_outputBuffer); } if (m_buffers[kBufferUV0].GetSizeInBytes() > 0) { uv0Offset = WriteArray(static_cast<void*>(m_buffers[kBufferUV0].GetBuffer()), m_totalVertices * 2, sizeof(float), m_outputBuffer); } if (m_buffers[kBufferUV1].GetSizeInBytes() > 0) { uv1Offset = WriteArray(static_cast<void*>(m_buffers[kBufferUV1].GetBuffer()), m_totalVertices * 2, sizeof(float), m_outputBuffer); } if (m_buffers[kBufferJointIndices].GetSizeInBytes() > 0) { jointIndexOffset = WriteArray(static_cast<void*>(m_buffers[kBufferJointIndices].GetBuffer()), m_totalVertices * 4, sizeof(uint8_t), m_outputBuffer); } if (m_buffers[kBufferJointWeights].GetSizeInBytes() > 0) { jointWeightOffset = WriteArray(static_cast<void*>(m_buffers[kBufferJointWeights].GetBuffer()), m_totalVertices * 4, sizeof(uint8_t), m_outputBuffer); } // Write indices if (m_totalIndices > 0) { indexOffset = WriteIndexArray(static_cast<void*>(m_buffers[kBufferIndex].GetBuffer()), m_totalIndices, m_totalVertices, m_outputBuffer); } // Patch the offsets (these are relative to the mesh header, not the frame)... MeshSegment* pHeader = (MeshSegment*)m_outputBuffer->GetBuffer(headerOffset); pHeader->OffsetToFirstExtensionHeader = firstExtensionHeaderOffset == 0 ? firstExtensionHeaderOffset : (firstExtensionHeaderOffset - headerOffset); pHeader->OffsetColors = colOffset == 0 ? colOffset : (colOffset - headerOffset); pHeader->OffsetNormals = normalOffset == 0 ? normalOffset : (normalOffset - headerOffset); pHeader->OffsetTangents = tangentOffset == 0 ? tangentOffset : (tangentOffset - headerOffset); pHeader->OffsetUV0 = uv0Offset == 0 ? uv0Offset : (uv0Offset - headerOffset); pHeader->OffsetUV1 = uv1Offset == 0 ? uv1Offset : (uv1Offset - headerOffset); pHeader->OffsetPos = posOffset == 0 ? posOffset : (posOffset - headerOffset); pHeader->OffsetIndices = indexOffset == 0 ? indexOffset : (indexOffset - headerOffset); pHeader->OffsetJointIndices = jointIndexOffset == 0 ? jointIndexOffset : (jointIndexOffset - headerOffset); pHeader->OffsetJointWeights = jointWeightOffset == 0 ? jointWeightOffset : (jointWeightOffset - headerOffset); pHeader->OffsetToFirstExtensionHeader = m_byteSwapU32(pHeader->OffsetToFirstExtensionHeader); pHeader->OffsetColors = m_byteSwapU32(pHeader->OffsetColors); pHeader->OffsetNormals = m_byteSwapU32(pHeader->OffsetNormals); pHeader->OffsetTangents = m_byteSwapU32(pHeader->OffsetTangents); pHeader->OffsetUV0 = m_byteSwapU32(pHeader->OffsetUV0); pHeader->OffsetUV1 = m_byteSwapU32(pHeader->OffsetUV1); pHeader->OffsetPos = m_byteSwapU32(pHeader->OffsetPos); pHeader->OffsetIndices = m_byteSwapU32(pHeader->OffsetIndices); pHeader->OffsetJointIndices = m_byteSwapU32(pHeader->OffsetJointIndices); pHeader->OffsetJointWeights = m_byteSwapU32(pHeader->OffsetJointWeights); } //--------------------------------------------------------------------- void GeometryWriter::EndNodeSegment() { // Write out a NodeSegment which specifies a sceneNode in the hierarchy, and // contains only a transform NodeSegment segment; memset(&segment, 0, sizeof(segment)); segment.Version = m_byteSwapU32(MeshSegment::kVersion0); segment.MeshID = m_byteSwapU32(m_meshId); segment.ParentID = m_byteSwapU32(m_meshParentId); segment.Type = MeshBaseSegment::kTypeNode; if (m_hasBoundingBox) { uint32_t* bbox = reinterpret_cast<uint32_t*>(m_bbox); bbox[0] = m_byteSwapU32(bbox[0]); bbox[1] = m_byteSwapU32(bbox[1]); bbox[2] = m_byteSwapU32(bbox[2]); bbox[3] = m_byteSwapU32(bbox[3]); bbox[4] = m_byteSwapU32(bbox[4]); bbox[5] = m_byteSwapU32(bbox[5]); memcpy_s(segment.BoundsCenter, sizeof(float) * 3, &bbox[0], sizeof(float) * 3); memcpy_s(segment.BoundsExtents, sizeof(float) * 3, &bbox[3], sizeof(float) * 3); } // Transform uint32_t* srcTransform = (uint32_t*)m_transform; for (int i = 0; i < 16; ++i, ++srcTransform) { *srcTransform = m_byteSwapU32(*srcTransform); } memcpy_s(segment.Transform, sizeof(float) * 16, m_transform, sizeof(float) * 16); // Write header... uint32_t headerOffset = m_outputBuffer->WriteDataRaw(&segment, sizeof(segment), 4); // Save mesh offset m_savedItemOffsets.push_back(headerOffset); } //--------------------------------------------------------------------- void GeometryWriter::EndSkeletonSegment() { // Write out a NodeSegment which specifies a sceneNode in the hierarchy, and // contains only a transform uint16_t numJoints = (uint16_t)m_joints.size(); uint32_t headerOffset = m_outputBuffer->ReserveSpace(sizeof(SkeletonSegment) + sizeof(SkeletonSegment::Joint) * numJoints, 4); SkeletonSegment* segment = (SkeletonSegment*)m_outputBuffer->GetBuffer(headerOffset); segment->Version = m_byteSwapU32(SkeletonSegment::kVersion0); segment->MeshID = m_byteSwapU32(m_meshId); segment->ParentID = m_byteSwapU32(m_meshParentId); segment->NumJoints = m_byteSwapU16(numJoints); segment->Type = MeshBaseSegment::kTypeSkeleton; void* pJointData = m_outputBuffer->GetBuffer(headerOffset + sizeof(SkeletonSegment)); memcpy_s(pJointData, sizeof(SkeletonSegment::Joint) * numJoints, &m_joints[0], sizeof(SkeletonSegment::Joint) * numJoints); // Save mesh offset m_savedItemOffsets.push_back(headerOffset); } //--------------------------------------------------------------------- void GeometryWriter::EndMeshInstanceSegment() { MeshInstanceSegment segment; memset(&segment, 0, sizeof(segment)); segment.Version = m_byteSwapU32(MeshInstanceSegment::kVersion0); segment.MeshID = m_byteSwapU32(m_meshId); segment.SourceMeshID = m_byteSwapU32(m_sourceMeshId); segment.MaterialID = m_byteSwapU32(m_materialId); segment.ParentID = m_byteSwapU32(m_meshParentId); segment.Type = MeshBaseSegment::kTypeInstance; uint32_t* srcTransform = (uint32_t*)m_transform; for (int i = 0; i < 16; ++i, ++srcTransform) { *srcTransform = m_byteSwapU32(*srcTransform); } if (m_instanceType == InstanceType::Primitive) segment.IsPrimitive = 1; memcpy_s(segment.Transform, sizeof(float) * 16, m_transform, sizeof(float) * 16); if (m_hasBoundingBox) { uint32_t* bbox = (uint32_t*)m_bbox; bbox[0] = m_byteSwapU32(bbox[0]); bbox[1] = m_byteSwapU32(bbox[1]); bbox[2] = m_byteSwapU32(bbox[2]); bbox[3] = m_byteSwapU32(bbox[3]); bbox[4] = m_byteSwapU32(bbox[4]); bbox[5] = m_byteSwapU32(bbox[5]); memcpy_s(segment.BoundsCenter, sizeof(float) * 3, &bbox[0], sizeof(float) * 3); memcpy_s(segment.BoundsExtents, sizeof(float) * 3, &bbox[3], sizeof(float) * 3); segment.HasBoundingBox = 1; } // Write header (which in this case is the entire segment). uint32_t headerOffset = m_outputBuffer->WriteDataRaw(&segment, sizeof(segment), 4); // Save mesh instance offset. m_savedItemOffsets.push_back(headerOffset); } //--------------------------------------------------------------------- void GeometryWriter::SetSourceMeshID(uint32_t sourceMeshId) { m_sourceMeshId = sourceMeshId; m_instanceType = Mesh; } //--------------------------------------------------------------------- void GeometryWriter::AddJoint(uint32_t id, int parentJointIndex, const float* invBindMatrix, const float* transform) { if (parentJointIndex < 0) parentJointIndex = -1; if (parentJointIndex >= (int)m_joints.size()) { throw Utils::BabylonFailException("GeometryWriter::AddJoint - Invalid parent joint index"); } SkeletonSegment::Joint j; j.Id = m_byteSwapU32(id); j.ParentJointIndex = parentJointIndex; uint32_t* pIdx = (uint32_t*)&j.ParentJointIndex; *pIdx = m_byteSwapU32(*pIdx); memcpy_s(j.InverseBindMatrix, sizeof(float) * 16, invBindMatrix, sizeof(float) * 16); memcpy_s(j.Transform, sizeof(float) * 16, transform, sizeof(float) * 16); /*uint32_t* srcTransform = (uint32_t*)j.InverseBindMatrix; for (int i = 0; i < 16; ++i, ++srcTransform) { *srcTransform = m_byteSwapU32(*srcTransform); }*/ m_joints.push_back(j); } //--------------------------------------------------------------------- VertexData GeometryWriter::LockVertexData(uint32_t numVertices, uint32_t numIndices, uint32_t formatMask, bool areIndices32bit) { BabylonAssertExpr(m_hasLockedData == false, "GeoemtryWriter::LockVertexData - already locked"); BabylonAssertExpr(m_totalVertices == 0, "GeoemtryWriter::LockVertexData - lock only allowed on new meshes"); BabylonAssertExpr(m_totalIndices == 0, "GeoemtryWriter::LockVertexData - lock only allowed on new meshes"); m_hasLockedData = true; VertexData ret; memset(&ret, 0, sizeof(ret)); // Reserve space // Position uint32_t offset = m_buffers[kBufferPos].ReserveSpace(numVertices * sizeof(float) * 3, 4); ret.m_positionData = (float*)m_buffers[kBufferPos].GetBuffer(offset); if ((formatMask & MeshSegment::kHasColor) != 0) { offset = m_buffers[kBufferColor].ReserveSpace(numVertices * sizeof(uint32_t), 4); ret.m_colorData = (uint32_t*)m_buffers[kBufferColor].GetBuffer(offset); } if ((formatMask & MeshSegment::kHasNormals) != 0) { offset = m_buffers[kBufferkNormal].ReserveSpace(numVertices * sizeof(float) * 3, 4); ret.m_normalData = (float*)m_buffers[kBufferkNormal].GetBuffer(offset); } if ((formatMask & MeshSegment::kHasTangents) != 0) { offset = m_buffers[kBufferTangent].ReserveSpace(numVertices * sizeof(float) * 4, 4); ret.m_tangentData = (float*)m_buffers[kBufferTangent].GetBuffer(offset); } if ((formatMask & MeshSegment::kHasUV0) != 0) { offset = m_buffers[kBufferUV0].ReserveSpace(numVertices * sizeof(float) * 2, 4); ret.m_uvData[0] = (float*)m_buffers[kBufferUV0].GetBuffer(offset); } if ((formatMask & MeshSegment::kHasUV1) != 0) { offset = m_buffers[kBufferUV1].ReserveSpace(numVertices * sizeof(float) * 2, 4); ret.m_uvData[1] = (float*)m_buffers[kBufferUV1].GetBuffer(offset); } if ((formatMask & MeshSegment::kHasJointData) != 0) { offset = m_buffers[kBufferJointIndices].ReserveSpace(numVertices * sizeof(uint8_t) * 4, 4); ret.m_jointIndices = (uint8_t*)m_buffers[kBufferJointIndices].GetBuffer(offset); offset = m_buffers[kBufferJointWeights].ReserveSpace(numVertices * sizeof(uint8_t) * 4, 4); ret.m_jointWeights = (uint8_t*)m_buffers[kBufferJointWeights].GetBuffer(offset); } if (numIndices > 0) { uint32_t size = 0; uint32_t align = 0; if (areIndices32bit) { size = numIndices * sizeof(uint32_t); align = 4; m_areIndices32bit = true; } else { size = numIndices * sizeof(uint16_t); align = 2; m_areIndices32bit = false; } // Note: this allocates according to numIndices rather than numVertices because // this is for the index data (unlike all the cases above). offset = m_buffers[kBufferIndex].ReserveSpace(size, align); ret.m_indexData = (uint32_t*)m_buffers[kBufferIndex].GetBuffer(offset); } ret.m_numIndicesLocked = numIndices; ret.m_numVerticesLocked = numVertices; // Update counts m_totalVertices += numVertices; m_totalIndices += numIndices; return ret; } //--------------------------------------------------------------------- void GeometryWriter::UnlockVertexData(const VertexData& data) { BabylonUnusedParameter(data); BabylonAssertExpr(m_hasLockedData == true, "GeoemtryWriter::UnlockVertexData - not locked"); BabylonAssertExpr(data.m_numIndicesLocked == m_totalIndices, "GeoemtryWriter::UnlockVertexData - unexpected index count"); BabylonAssertExpr(data.m_numVerticesLocked == m_totalVertices, "GeoemtryWriter::UnlockVertexData - unexpected vertex count"); m_hasLockedData = false; } //--------------------------------------------------------------------- void GeometryWriter::SetSkeletonId(uint32_t skeletonID) { m_skeletonId = skeletonID; } //--------------------------------------------------------------------- uint32_t GeometryWriter::GetSkeletonId() const { return m_skeletonId; } //--------------------------------------------------------------------- void GeometryWriter::SetTransform(_In_reads_(16) const float* transform) { memcpy_s(m_transform, sizeof(float) * 16, transform, sizeof(float) * 16); } //--------------------------------------------------------------------- const float* GeometryWriter::GetTransform() { return m_transform; } //--------------------------------------------------------------------- void GeometryWriter::SetBoundingBox(_In_reads_(3) const float* center, _In_reads_(3) const float* extents) { memcpy_s(&m_bbox[0], 3 * sizeof(float), center, 3 * sizeof(float)); memcpy_s(&m_bbox[3], 3 * sizeof(float), extents, 3 * sizeof(float)); m_hasBoundingBox = true; } //--------------------------------------------------------------------- void GeometryWriter::SetFlags(uint32_t flags) { m_flags = static_cast<uint16_t>(flags); } //--------------------------------------------------------------------- // <summary> // Write and byte swap the specified vertex array to the output buffer // </summary> uint32_t GeometryWriter::WriteArray(_In_reads_bytes_(numElements*elementSizeInBytes)void* srcArray, uint32_t numElements, uint32_t elementSizeInBytes, std::shared_ptr<Babylon::Framework::IBuffer> const& outputBuffer) { // Byte swap the array elements first if (elementSizeInBytes > sizeof(uint32_t)) { throw Utils::BabylonInvalidArgException("Element size not supported. Add support if you need it"); } uint32_t bufferOffset = outputBuffer->WriteDataRaw(srcArray, elementSizeInBytes * numElements, elementSizeInBytes); srcArray = outputBuffer->GetBuffer(bufferOffset); if (elementSizeInBytes == sizeof(uint16_t)) { uint16_t* p = (uint16_t*)srcArray; for (uint32_t i = 0; i < numElements; ++i, ++p) { *p = m_byteSwapU16(*p); } } else if (elementSizeInBytes == sizeof(uint32_t)) { uint32_t* p = (uint32_t*)srcArray; for (uint32_t i = 0; i < numElements; ++i, ++p) { *p = m_byteSwapU32(*p); } } return bufferOffset; } //--------------------------------------------------------------------- // <summary> // Write the index array to the final output buffer. // The source array is either a uint32_t* or uint16_t* buffer, depending on m_areIndices32bit flag. // The final format of the indices depends on the number of vertices referenced by the indices. // If less than 65535, then we output uint16_t* array. Else it's a 32bit array. // </summary> uint32_t GeometryWriter::WriteIndexArray( _In_reads_bytes_(numElements * GetIndexBufferElementSizeInBytes(numVertices)) void* srcArray, uint32_t numElements, uint32_t numVertices, std::shared_ptr<Babylon::Framework::IBuffer> const& outputBuffer) { uint32_t elementSizeInBytes = GetIndexBufferElementSizeInBytes(numVertices); uint32_t bufferOffset = outputBuffer->ReserveSpace(elementSizeInBytes * numElements, elementSizeInBytes); void* destArray = outputBuffer->GetBuffer(bufferOffset); if (elementSizeInBytes == sizeof(uint16_t)) { uint16_t* dest = (uint16_t*)destArray; if(m_areIndices32bit) { uint32_t* src = (uint32_t*)srcArray; for (uint32_t i = 0; i < numElements; ++i, ++dest, ++src) { *dest = m_byteSwapU16((uint16_t)*src); } } else { uint16_t* src = (uint16_t*)srcArray; for(uint32_t i = 0; i < numElements; ++i,++dest,++src) { *dest = m_byteSwapU16(*src); } } } else { uint32_t* dest = (uint32_t*)destArray; uint32_t* src = (uint32_t*)srcArray; for (uint32_t i = 0; i < numElements; ++i, ++dest, ++src) { *dest = m_byteSwapU32(*src); } } return bufferOffset; } //--------------------------------------------------------------------- void GeometryWriter::AddVertex(_In_reads_(numVertices) const Vertex* pVertices, uint32_t numVertices) { BabylonAssertExpr(m_hasLockedData == false, "GeoemtryWriter::AddVertex - has locked data"); // Serialize all vertex data. We serialize into intermediate buffers, which will later be // combined into the output buffer. We DO NOT byte swap at this stage, instead do it later on // inside EndMesh. This will allow us to vectorize the byte-swapping since we're dealing with // uniform arrays if (!IsValidMesh()) { throw Utils::BabylonFailException("Need to call BeginMesh first"); } for (uint32_t i = 0; i < numVertices; ++i) { auto v = pVertices[i]; m_buffers[kBufferPos].WriteDataRaw(v.Position, sizeof(float) * 3); BabylonAssertExpr(v.HasNormal || m_buffers[kBufferkNormal].GetSizeInBytes() == 0, "GeometryWriter::AddVertex - If a vertex has a normal, they all need to!"); BabylonAssertExpr(v.HasTangent || m_buffers[kBufferTangent].GetSizeInBytes() == 0, "GeometryWriter::AddVertex - If a vertex has a tngent, they all need to!"); BabylonAssertExpr(v.HasUV0 || m_buffers[kBufferUV0].GetSizeInBytes() == 0, "GeometryWriter::AddVertex - If a vertex has UV0, they all need to!"); BabylonAssertExpr(v.HasUV1 || m_buffers[kBufferUV1].GetSizeInBytes() == 0, "GeometryWriter::AddVertex - If a vertex has UV1, they all need to!"); BabylonAssertExpr(v.HasColor || m_buffers[kBufferColor].GetSizeInBytes() == 0, "GeometryWriter::AddVertex - If a vertex has COLOR, they all need to!"); if (v.HasNormal) { m_buffers[kBufferkNormal].WriteDataRaw(v.Normal, sizeof(float) * 3); } if (v.HasTangent) { m_buffers[kBufferTangent].WriteDataRaw(v.Tangent, sizeof(float) * 4); } if (v.HasUV0) { m_buffers[kBufferUV0].WriteDataRaw(v.UV0, sizeof(float) * 2); } if (v.HasUV1) { m_buffers[kBufferUV1].WriteDataRaw(v.UV1, sizeof(float) * 2); } if (v.HasColor) { m_buffers[kBufferColor].WriteDataRaw(v.Rgba, sizeof(uint8_t) * 4); } } m_totalVertices += numVertices; } //--------------------------------------------------------------------- void GeometryWriter::AddIndex(_In_reads_(numIndices) const uint32_t* pIndices, uint32_t numIndices) { if (!IsValidMesh()) { throw Utils::BabylonFailException("Need to call BeginMesh first"); } if (m_indexType == kIndexSmall) { throw Utils::BabylonFailException("Have both SMALL and BIG indices. Not allowed."); } if ((numIndices % 3) != 0) { numIndices -= (numIndices % 3); } if (numIndices <= 0) { throw Utils::BabylonInvalidArgException("GeometryWriter: Index count must be multiple of 3 and greater and 0"); } BabylonAssertExpr(m_hasLockedData == false, "GeoemtryWriter::AddIndex - has locked data"); m_buffers[kBufferIndex].WriteDataRaw(pIndices, numIndices * sizeof(uint32_t)); m_totalIndices += numIndices; } uint32_t GeometryWriter::GetVertexBufferSize() const { uint32_t result = 0; for (int i = 0; i < kNumBuffers; ++i) { result += m_buffers[i].GetSizeInBytes(); } return result; } uint32_t GeometryWriter::GetIndexBufferSize() const { return m_buffers[kBufferIndex].GetSizeInBytes(); } } // namespace V1 BABYLON_SDK_API IGeometryWriter* GeometryWriterCreate() { return new V1::GeometryWriter(); } BABYLON_SDK_API void GeometryWriterDestroy(IGeometryWriter*& pWriter) { if (pWriter == nullptr) return; delete pWriter; pWriter = nullptr; } } // Namespace Framework } // Namespace Babylon
43.485236
178
0.499581
[ "mesh", "geometry", "object", "vector", "transform" ]
50f6136d28a3e71e987e8d290f1054c467b07994
14,353
cpp
C++
torob/src/map_publisher.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
7
2016-12-10T15:44:00.000Z
2020-08-27T17:40:11.000Z
torob/src/map_publisher.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
2
2020-04-14T15:19:53.000Z
2021-01-26T21:26:47.000Z
torob/src/map_publisher.cpp
CARMinesDouai/MutiRobotExplorationPackages
725f36eaa22adb33be7f5961db1a0f8e50fdadbd
[ "MIT" ]
2
2017-01-29T03:01:06.000Z
2021-12-15T14:59:10.000Z
#include "map_publisher.h" #include <sstream> #define trb_Unknown_Cell -1 #define trb_Occupied_Cell 1 #define trb_Free_Cell 0 #define MAP_IDX(sx, i, j) ((sx) * (j) + (i))// compute linear index for given map coords //#define trb_map_width_metre 50 // map width [metre] //#define trb_map_height_metre 50 // map height [metre] using namespace geometry_msgs; using namespace std; ros::Publisher grap_to_map_publisher; // graph of the map ros::Publisher robot_model_publisher; // robot model ros::Publisher _map_publisher; // grid of the map ros::Publisher _map_publisher_m; //grid of the map metadata ros::Subscriber scanSub; // scan nav_msgs::GetMap::Response map_; // our map double trb_resolution_; // map resolution std::string trb_map_frame_; // map resolution bool is_first_map_; // map resolution int trb_offset_x, trb_offset_y; // map resolution int trb_map_width_pixel, trb_map_height_pixel; // map resolution double trb_map_width_metre; double trb_map_height_metre; void initialize_map_publisher(ros::NodeHandle &node, ros::NodeHandle &node_private){ initialize_map_publisher( node, node_private, "/map_2"); } void initialize_map_publisher(ros::NodeHandle &node, ros::NodeHandle &node_private, std::string map_topic) { //publisher for graph and robot model grap_to_map_publisher = node.advertise<visualization_msgs::MarkerArray>("graph_map",1); robot_model_publisher = node.advertise<visualization_msgs::Marker>("robot_torob",1); //======================================================================================MAP //map to be seen in arviz _map_publisher = node.advertise<nav_msgs::OccupancyGrid>( map_topic, 1, true); stringstream mapmeta_topic; mapmeta_topic << map_topic << "_metadata"; _map_publisher_m = node.advertise<nav_msgs::MapMetaData>( mapmeta_topic.str(), 1, true); //other param. //node_private.getParam("trb_resolution",trb_resolution_); node_private.getParam("trb_map_width_metre",trb_map_width_metre); node_private.getParam("trb_map_height_metre",trb_map_height_metre); trb_map_frame_ = "map";// grid map frame trb_resolution_ = 0.05;// grid map resolution trb_map_width_metre=50; trb_map_height_metre=50; is_first_map_=true; // if the first map calculate it all, otherwise, we just update out graph lines on the map // cout<<trb_resolution_<<endl; // cout<<trb_map_width_metre<<endl; // cout<<trb_map_height_metre<<endl; trb_map_width_pixel = (float)trb_map_width_metre/trb_resolution_; // torop map width [pixel] trb_map_height_pixel = (float)trb_map_height_metre /trb_resolution_;// torop width [pixel] trb_offset_x = - trb_map_width_metre/2; // torop map origin on X [pixel] trb_offset_y = - trb_map_height_metre/2; // torop map origin on Y [pixel] //cout<<trb_map_width_pixel<<" :: "<<trb_map_height_pixel<<endl;cout<<trb_offset_x<<" :: "<<trb_offset_y<<endl; //======================================================================================MAP } void publishMapAsGraph(const mia::VisiMap & visimap, float robot_x, float robot_y)//&(_moinag.torob->visibility()->a_visibility); { // cout<<"publish graph: " << endl; //std::vector<float> torob_graph; //read the graph int nbVertex= boost::num_vertices(visimap.a_map); visualization_msgs::MarkerArray marray_g; //graph nodes visualization_msgs::Marker map_nd; map_nd.header.frame_id = "map"; map_nd.header.stamp = ros::Time::now(); map_nd.id = 0; map_nd.ns = "totob"; map_nd.type = visualization_msgs::Marker::SPHERE; map_nd.pose.position.x= 0.0; map_nd.pose.position.y= 0.0; map_nd.pose.position.z= 0.0; map_nd.scale.x= 0.1; map_nd.scale.y= 0.1; map_nd.scale.z = 0.1; map_nd.color.r = 1.0; map_nd.color.g= 0; map_nd.color.b = 0.0; map_nd.color.a = 1.0; map_nd.lifetime = ros::Duration(0); map_nd.action = visualization_msgs::Marker::ADD; int iv= 0; mia::Graph2::vertex_iterator vt, vtEnd; for( boost::tie(vt, vtEnd)= boost::vertices(visimap.a_map) ; vt != vtEnd ; ++vt ) { map_nd.id= iv; ++iv; map_nd.pose.position.x = visimap.a_map[*vt].x; map_nd.pose.position.y = visimap.a_map[*vt].y; marray_g.markers.push_back( visualization_msgs::Marker(map_nd) ); } //graph edges visualization_msgs::Marker map_edge; map_edge.header.frame_id = "map"; map_edge.header.stamp = ros::Time::now(); map_edge.action = visualization_msgs::Marker::ADD; map_edge.ns = "totob"; map_edge.id = 0; map_edge.type = visualization_msgs::Marker::LINE_STRIP; map_edge.scale.x = 0.1; map_edge.scale.y = 0.1; map_edge.scale.z = 0.1; map_edge.color.r = 0.0; map_edge.color.g = 0.0; map_edge.color.b = 1.0; map_edge.color.a = 1.0; clearMap(); geometry_msgs::Point min, max; { boost::tie(vt, vtEnd)= boost::vertices(visimap.a_map); min.x= visimap.a_map[*vt].x; min.y= visimap.a_map[*vt].y; max.x= visimap.a_map[*vt].x; max.y= visimap.a_map[*vt].y; for( ++vt; vt != vtEnd; ++vt) { if( visimap.a_map[*vt].x < min.x ) min.x= visimap.a_map[*vt].x; if( visimap.a_map[*vt].y < min.y ) min.y= visimap.a_map[*vt].y; if( visimap.a_map[*vt].x > max.x ) max.x= visimap.a_map[*vt].x; if( visimap.a_map[*vt].y > max.y ) max.y= visimap.a_map[*vt].y; } trb_map_width_pixel= 2+(int)((max.x-min.x)/trb_resolution_); trb_map_height_pixel= 2+(int)((max.y-min.y)/trb_resolution_); } int ie= nbVertex; mia::Graph2::edge_iterator et, etEnd; int nbEdges(0); for( boost::tie(et, etEnd)= boost::edges( visimap.a_map ) ; et != etEnd ; ++et ) { int source= boost::source( *et, visimap.a_map ); int target= boost::target( *et, visimap.a_map ); if( visimap.a_map[source].type == mia::Node2::type_obstacle && visimap.a_map[target].type == mia::Node2::type_obstacle ) { ++nbEdges; map_edge.id = ie; ++ie; map_edge.points.clear(); geometry_msgs::Point p; p.x= visimap.a_map[source].x; p.y= visimap.a_map[source].y; p.z= 0.0; map_edge.points.push_back(p); //====================================>>>>>>>>>>=========================MAP RELATED CODE //first point of the line //p.x = rand() % (int)trb_map_width_metre; //p.y = rand() % (int)trb_map_height_metre; int x1( 1+(int)((p.x-min.x)/trb_resolution_) ), y1( 1+(int)((p.y-min.y)/trb_resolution_) ); //cout<<" x1 "<<p.x<<endl; //cout<<" y1 "<<p.y<<endl; //====================================<<<<<<<<<<=========================MAP RELATED CODE p.x= visimap.a_map[target].x; p.y= visimap.a_map[target].y; map_edge.points.push_back(p); //====================================>>>>>>>>>>=========================MAP RELATED CODE //p.x = rand() % (int)trb_map_width_metre; //p.y = rand() % (int)trb_map_height_metre; //second point of the line int x2( 1+(int)((p.x-min.x)/trb_resolution_) ), y2( 1+(int)((p.y-min.y)/trb_resolution_) ); //cout<<trb_map_width_pixel<<" trb_map_width_metre x1 "<<p.x<<endl; //cout<<" y2 "<<x1<<endl; //cout<<" x2 "<<x2<<endl; //cout<<trb_map_height_pixel<<"trb_map_height_metre y2 "<<y2<<endl; //Shifting to the midle of the map //bhm_line(int(x1), int(y1), int(x2), int(y2), 1); int int_x1(x1);//+trb_map_width_pixel/2); int int_y1(y1);//+trb_map_height_pixel/2); int int_x2(x2);//+trb_map_width_pixel/2); int int_y2(y2);//+trb_map_height_pixel/2); if( int_x1 < 0 || int_y1 < 0 || int_x2 < 0 || int_y2 < 0 ) { cerr << "ERROR edge [" << source << ", " << target << "] n°" << ie; cerr << " segment (" << x1 << ", " << y1 << ") -> (" << x2 << ", " << y2 << ")"; cerr << " pixel (" << int_x1 << ", " << int_y1 << ") -> (" << int_x2 << ", " << int_y2 << ")" << endl; } else bhm_line( int_x1, int_y1, int_x2, int_y2, 1);//ex. fixed line: bhm_line( 0, 0, 300, 700, 1); //========================================================================MAP RELATED CODE marray_g.markers.push_back( visualization_msgs::Marker(map_edge) ); } } //====================================>>>>>>>>>>=========================MAP RELATED CODE // Set the header information on the map map_.map.header.stamp = ros::Time::now(); map_.map.header.frame_id = trb_map_frame_; _map_publisher.publish(map_.map); _map_publisher_m.publish(map_.map.info); //cout<<trb_map_width_pixel<<" :mmmmmm: "<<trb_map_height_pixel<<endl;cout<<trb_offset_x<<" :mmmmmmmmmm: "<<trb_offset_y<<endl; //====================================<<<<<<<<<<=========================MAP RELATED CODE //robot model as a cube visualization_msgs::Marker robot_md; robot_md.header.frame_id = "odom"; robot_md.header.stamp = ros::Time::now(); robot_md.id = 0; robot_md.ns = "totob"; robot_md.type = visualization_msgs::Marker::CUBE; robot_md.pose.position.x = robot_x; robot_md.pose.position.y = robot_y; robot_md.pose.position.z = 0.0; robot_md.scale.x = 0.9;robot_md.scale.y = 0.9;robot_md.scale.z = 0.9; robot_md.color.r = 0.0; robot_md.color.g = 1.0;robot_md.color.b = 0.0;robot_md.color.a = 1.0; robot_md.lifetime = ros::Duration(0); map_nd.action = visualization_msgs::Marker::DELETE; /*for (; id < marker_count_; id++) { map_nd.id = id; marray_g.markers.push_back(visualization_msgs::Marker(map_nd)); }*/ //marker_count_ = marray_g.markers.size(); //we publish the graph grap_to_map_publisher.publish(marray_g); //we publish the robot model as a cube robot_model_publisher.publish(robot_md); // cout<<"\t-publishing graph size: "<<marray_g.markers.size(); // cout<<"\npublish graph end." << endl; } void bhm_line(int x1,int y1,int x2,int y2,int c) { int x,y,dx,dy,dx1,dy1,px,py,xe,ye,i; dx=x2-x1; dy=y2-y1; dx1=fabs(dx); dy1=fabs(dy); px=2*dy1-dx1; py=2*dx1-dy1; if(dy1<=dx1) { if(dx>=0){ x=x1; y=y1; xe=x2; }else{ x=x2; y=y2; xe=x1; } putpixel(x,y,c); for(i=0;x<xe;i++) { x=x+1; if(px<0){ px=px+2*dy1; }else{ if((dx<0 && dy<0) || (dx>0 && dy>0)){ y=y+1; }else{ y=y-1; } px=px+2*(dy1-dx1); } //delay(0); putpixel(x,y,c); } }else{ if(dy>=0){ x=x1; y=y1; ye=y2; }else{ x=x2; y=y2; ye=y1; } putpixel(x,y,c); for(i=0;y<ye;i++) { y=y+1; if(py<=0){ py=py+2*dx1; }else{ if((dx<0 && dy<0) || (dx>0 && dy>0)) { x=x+1; }else{ x=x-1; } py=py+2*(dx1-dy1); } //delay(0); putpixel(x,y,c); } } } void clearMap() { for (int y=0; y<map_.map.info.height; y++) for (int x=0; x< map_.map.info.width; x++) { map_.map.data[MAP_IDX(map_.map.info.width, x, y)] = 0; } } void putpixel(int x, int y, int c) { if( 0 <= x && x < map_.map.info.width && 0 <= y && y < map_.map.info.height ) map_.map.data[MAP_IDX(map_.map.info.width, x, y)] = 100; } bool mapUpdate() { // cout<<"from map reseting up param before 0"<<endl; if(is_first_map_) { map_.map.info.resolution = trb_resolution_; map_.map.info.origin.position.x = 0.0; map_.map.info.origin.position.y = 0.0; map_.map.info.origin.position.z = 0.0; map_.map.info.origin.orientation.x = 0.0; map_.map.info.origin.orientation.y = 0.0; map_.map.info.origin.orientation.z = 0.0; map_.map.info.origin.orientation.w = 1.0; is_first_map_=false; } //we change the output map position if it does not corresponds to our origins if(map_.map.info.width != (unsigned int) trb_map_width_pixel || map_.map.info.height != (unsigned int) trb_map_height_pixel || map_.map.info.origin.position.x != trb_offset_x || map_.map.info.origin.position.y != trb_offset_y ) { map_.map.info.origin.position.x = trb_offset_x; map_.map.info.origin.position.y = trb_offset_y; map_.map.info.width = trb_map_width_pixel; map_.map.info.height = trb_map_height_pixel; map_.map.data.resize(map_.map.info.width * map_.map.info.height); // cout<<"from map reseting up param "<<map_.map.info.width<<endl; // cout<<"from map reseting up param "<<map_.map.info.origin.position.y<<endl; } //cout<<"from map reseting up param before 2"<<endl; if(is_first_map_== false) return true; for (int y=0; y<trb_map_height_pixel; y++)//we may select only specific cells { for (int x=0; x< trb_map_width_pixel; x++) { // Getting the value at position x,y //kt_int8u value = occ_grid->GetValue(karto::Vector2<kt_int32s>(x, y)); int trb_value = rand() % 3; if(trb_value == 2) trb_value=-1; trb_value=-1; switch (trb_value) { case -1://trb_Unknown_Cell: map_.map.data[MAP_IDX(map_.map.info.width, x, y)] = -1; break; case 1://trb_Occupied_Cell: map_.map.data[MAP_IDX(map_.map.info.width, x, y)] = 100; break; case 0://trb_Free_Cell: map_.map.data[MAP_IDX(map_.map.info.width, x, y)] = 0; break; default: ROS_WARN("Unknown cell value at %d, %d", x, y); break; } } } // Set the header information on the map map_.map.header.stamp = ros::Time::now(); map_.map.header.frame_id = trb_map_frame_; _map_publisher.publish(map_.map); _map_publisher_m.publish(map_.map.info); //delete occ_grid; return true; }
34.092637
131
0.57103
[ "vector", "model" ]
50f8f3a69467b952cda62efb9db58416e194f8b6
2,689
hxx
C++
main/sd/source/ui/sidebar/RecentMasterPagesSelector.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sd/source/ui/sidebar/RecentMasterPagesSelector.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sd/source/ui/sidebar/RecentMasterPagesSelector.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef SD_SIDEBAR_PANELS_RECENT_MASTER_PAGES_SELECTOR_HXX #define SD_SIDEBAR_PANELS_RECENT_MASTER_PAGES_SELECTOR_HXX #include "MasterPagesSelector.hxx" namespace sd { namespace sidebar { /** Show the recently used master pages (that are not currently used). */ class RecentMasterPagesSelector : public MasterPagesSelector { public: static MasterPagesSelector* Create ( ::Window* pParent, ViewShellBase& rViewShellBase, const cssu::Reference<css::ui::XSidebar>& rxSidebar); protected: DECL_LINK(MasterPageListListener, void*); virtual void Fill (ItemList& rItemList); using sd::sidebar::MasterPagesSelector::Fill; /** Forward this call to the base class but save and restore the currently selected item. Assign the given master page to the list of pages. @param pMasterPage This master page will usually be a member of the list of all available master pages as provided by the MasterPageContainer. @param rPageList The pages to which to assign the master page. These pages may be slides or master pages themselves. */ virtual void AssignMasterPageToPageList ( SdPage* pMasterPage, const ::boost::shared_ptr<std::vector<SdPage*> >& rpPageList); virtual void ProcessPopupMenu (Menu& rMenu); private: RecentMasterPagesSelector ( ::Window* pParent, SdDrawDocument& rDocument, ViewShellBase& rBase, const ::boost::shared_ptr<MasterPageContainer>& rpContainer, const cssu::Reference<css::ui::XSidebar>& rxSidebar); virtual ~RecentMasterPagesSelector (void); virtual void LateInit (void); }; } } // end of namespace sd::sidebar #endif
33.6125
74
0.681666
[ "vector" ]
50fd5283e289bfea5f1b70f27d815647479a3516
19,867
cc
C++
L1Trigger/L1TMuonBarrel/src/L1TMuonBarrelParamsHelper.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
L1Trigger/L1TMuonBarrel/src/L1TMuonBarrelParamsHelper.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
L1Trigger/L1TMuonBarrel/src/L1TMuonBarrelParamsHelper.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "L1Trigger/L1TMuonBarrel/interface/L1TMuonBarrelParamsHelper.h" void L1TMuonBarrelParamsHelper::print(std::ostream& out) const { out << "L1 BMTF Parameters" << std::endl; out << "Firmware version: " << fwVersion_ << std::endl; } L1TMuonBarrelParamsHelper::L1TMuonBarrelParamsHelper(const L1TMuonBarrelParams& barrelParams) : L1TMuonBarrelParams( barrelParams) //: L1TMuonBarrelParams_PUBLIC(cast_to_L1TMuonBarrelParams_PUBLIC(barrelParams)) //: m_params_helper(barrelParams) { // if (pnodes_.size() != 2) // pnodes_.resize(2); } void L1TMuonBarrelParamsHelper::configFromPy(std::map<std::string, int>& allInts, std::map<std::string, bool>& allBools, std::map<std::string, std::vector<std::string> > allMasks, unsigned int fwVersion, const std::string& AssLUTpath) { set_PT_Assignment_nbits_Phi(allInts["PT_Assignment_nbits_Phi"]); set_PT_Assignment_nbits_PhiB(allInts["PT_Assignment_nbits_PhiB"]); set_PHI_Assignment_nbits_Phi(allInts["PHI_Assignment_nbits_Phi"]); set_PHI_Assignment_nbits_PhiB(allInts["PHI_Assignment_nbits_PhiB"]); set_Extrapolation_nbits_Phi(allInts["Extrapolation_nbits_Phi"]); set_Extrapolation_nbits_PhiB(allInts["Extrapolation_nbits_PhiB"]); set_BX_min(allInts["BX_min"]); set_BX_max(allInts["BX_max"]); set_Extrapolation_Filter(allInts["Extrapolation_Filter"]); set_OutOfTime_Filter_Window(allInts["OutOfTime_Filter_Window"]); set_OutOfTime_Filter(allBools["OutOfTime_Filter"]); set_Open_LUTs(allBools["Open_LUTs"]); set_EtaTrackFinder(allBools["EtaTrackFinder"]); set_Extrapolation_21(allBools["Extrapolation_21"]); setFwVersion(fwVersion); set_DisableNewAlgo(allBools["DisableNewAlgo"]); setAssLUTPath(AssLUTpath); ///Read Pt assignment Luts std::vector<LUT> pta_lut(0); pta_lut.reserve(19); std::vector<int> pta_threshold(10); if (load_pt(pta_lut, pta_threshold, allInts["PT_Assignment_nbits_Phi"], AssLUTpath) != 0) { cout << "Can not open files to load pt-assignment look-up tables for L1TMuonBarrelTrackProducer!" << endl; } setpta_lut(pta_lut); setpta_threshold(pta_threshold); ///Read Phi assignment Luts std::vector<LUT> phi_lut(0); phi_lut.reserve(2); if (load_phi(phi_lut, allInts["PHI_Assignment_nbits_Phi"], allInts["PHI_Assignment_nbits_PhiB"], AssLUTpath) != 0) { cout << "Can not open files to load phi-assignment look-up tables for L1TMuonBarrelTrackProducer!" << endl; } setphi_lut(phi_lut); l1mudttfparams.reset(); //KK l1mudttfqualplut .load(); //KK: Do these LUTs ever change and is it safe to initialize it from the release files like that? l1mudttfetaplut.load(); //KK // the data members of the Helper class loaded above are transient, push those to the persistent storage of the base class: lutparams_.eta_lut_ = l1mudttfetaplut.m_lut; lutparams_.qp_lut_ = l1mudttfqualplut.m_lut; for (int wh = -3; wh < 4; wh++) { int sec = 0; for (char& c : allMasks["mask_phtf_st1"].at(wh + 3)) { int mask = c - '0'; l1mudttfmasks.set_inrec_chdis_st1(wh, sec, mask); sec++; } sec = 0; for (char& c : allMasks["mask_phtf_st2"].at(wh + 3)) { int mask = c - '0'; l1mudttfmasks.set_inrec_chdis_st2(wh, sec, mask); sec++; } sec = 0; for (char& c : allMasks["mask_phtf_st3"].at(wh + 3)) { int mask = c - '0'; l1mudttfmasks.set_inrec_chdis_st3(wh, sec, mask); sec++; } sec = 0; for (char& c : allMasks["mask_phtf_st4"].at(wh + 3)) { int mask = c - '0'; l1mudttfmasks.set_inrec_chdis_st4(wh, sec, mask); sec++; } sec = 0; for (char& c : allMasks["mask_ettf_st1"].at(wh + 3)) { int mask = c - '0'; l1mudttfmasks.set_etsoc_chdis_st1(wh, sec, mask); sec++; } sec = 0; for (char& c : allMasks["mask_ettf_st2"].at(wh + 3)) { int mask = c - '0'; l1mudttfmasks.set_etsoc_chdis_st2(wh, sec, mask); sec++; } sec = 0; for (char& c : allMasks["mask_ettf_st3"].at(wh + 3)) { int mask = c - '0'; l1mudttfmasks.set_etsoc_chdis_st3(wh, sec, mask); //Not used in BMTF - mask l1mudttfmasks.set_inrec_chdis_csc(wh, sec, true); sec++; } } ///Read Extrapolation Luts std::vector<L1TMuonBarrelParams::LUTParams::extLUT> ext_lut(0); ext_lut.reserve(12); if (load_ext(ext_lut, allInts["PHI_Assignment_nbits_Phi"], allInts["PHI_Assignment_nbits_PhiB"]) != 0) { cout << "Can not open files to load extrapolation look-up tables for L1TMuonBarrelTrackProducer!" << endl; } setext_lut(ext_lut); //l1mudttfextlut.load(); } void L1TMuonBarrelParamsHelper::configFromDB(l1t::TriggerSystem& trgSys) { std::map<std::string, std::string> procRole = trgSys.getProcToRoleAssignment(); //Cleaning the default masking from the prototype l1mudttfmasks.reset(); for (auto it_proc = procRole.begin(); it_proc != procRole.end(); it_proc++) { std::string procId = it_proc->first; std::map<std::string, l1t::Parameter> settings = trgSys.getParameters(procId.c_str()); std::vector<std::string> paths = settings["regTable"].getTableColumn<std::string>("register_path"); std::vector<unsigned int> vals = settings["regTable"].getTableColumn<unsigned int>("register_value"); for (unsigned int row = 0; row < paths.size(); row++) { if (paths[row].find("open_lut") != std::string::npos) { //std::cout << "Value is: " << vals[row] << std::endl; set_Open_LUTs(vals[row]); } if (paths[row].find("sel_21") != std::string::npos) { //std::cout << "Value is: " << vals[row] << std::endl; set_Extrapolation_21(vals[row]); } if (paths[row].find("dis_newalgo") != std::string::npos) { //std::cout << "Value is: " << vals[row] << std::endl; //int fwv = (vals[row]==1) ? 1 : 2; //setFwVersion(fwv); bool disnewalgo = (vals[row] == 1); set_DisableNewAlgo(disnewalgo); } string masks[5] = {"mask_ctrl_N2", "mask_ctrl_N1", "mask_ctrl_0", "mask_ctrl_P1", "mask_ctrl_P2"}; for (int m = 0; m < 5; m++) { if (paths[row].find(masks[m]) != std::string::npos) { ///Converts the last bit to int int mask = 0x1 & vals[row]; int mask_all = vals[row]; ///All bits must be the same if (!(mask_all == 0x111111 || mask_all == 0x222222 || mask_all == 0x333333 || mask_all == 0x444444 || mask_all == 0x555555 || mask_all == 0x666666 || mask_all == 0x777777)) cerr << "BMTF: Cannot re-emulate properly. Individual link masking cannot be handled." << endl; if ((mask & 1) > 0) { for (int sec = 0; sec < 12; sec++) { if (masks[m] == "mask_ctrl_N2") { l1mudttfmasks.set_inrec_chdis_st1(-3, sec, true); //l1mudttfmasks.set_etsoc_chdis_st1(-3,sec,true); } if (masks[m] == "mask_ctrl_N1") { l1mudttfmasks.set_inrec_chdis_st1(-2, sec, true); //l1mudttfmasks.set_etsoc_chdis_st1(-2,sec,true); } if (masks[m] == "mask_ctrl_0") { l1mudttfmasks.set_inrec_chdis_st1(-1, sec, true); l1mudttfmasks.set_inrec_chdis_st1(1, sec, true); //l1mudttfmasks.set_etsoc_chdis_st1(-1,sec,true); //l1mudttfmasks.set_etsoc_chdis_st1(1,sec,true); } if (masks[m] == "mask_ctrl_P1") { l1mudttfmasks.set_inrec_chdis_st1(2, sec, true); //l1mudttfmasks.set_etsoc_chdis_st1(2,sec,true); } if (masks[m] == "mask_ctrl_P2") { l1mudttfmasks.set_inrec_chdis_st1(3, sec, true); //l1mudttfmasks.set_etsoc_chdis_st1(3,sec,true); } } } if ((mask & 2) > 0) { for (int sec = 0; sec < 12; sec++) { if (masks[m] == "mask_ctrl_N2") { l1mudttfmasks.set_inrec_chdis_st2(-3, sec, true); //l1mudttfmasks.set_etsoc_chdis_st2(-3,sec,true); } if (masks[m] == "mask_ctrl_N1") { l1mudttfmasks.set_inrec_chdis_st2(-2, sec, true); //l1mudttfmasks.set_etsoc_chdis_st2(-2,sec,true); } if (masks[m] == "mask_ctrl_0") { l1mudttfmasks.set_inrec_chdis_st2(-1, sec, true); l1mudttfmasks.set_inrec_chdis_st2(1, sec, true); //l1mudttfmasks.set_etsoc_chdis_st2(-1,sec,true); //l1mudttfmasks.set_etsoc_chdis_st2(1,sec,true); } if (masks[m] == "mask_ctrl_P1") { l1mudttfmasks.set_inrec_chdis_st2(2, sec, true); //l1mudttfmasks.set_etsoc_chdis_st2(2,sec,true); } if (masks[m] == "mask_ctrl_P2") { l1mudttfmasks.set_inrec_chdis_st2(3, sec, true); //l1mudttfmasks.set_etsoc_chdis_st2(3,sec,true); } } } if ((mask & 4) > 0) { for (int sec = 0; sec < 12; sec++) { if (masks[m] == "mask_ctrl_N2") { l1mudttfmasks.set_inrec_chdis_st3(-3, sec, true); //l1mudttfmasks.set_etsoc_chdis_st3(-3,sec,true); } if (masks[m] == "mask_ctrl_N1") { l1mudttfmasks.set_inrec_chdis_st3(-2, sec, true); //l1mudttfmasks.set_etsoc_chdis_st3(-2,sec,true); } if (masks[m] == "mask_ctrl_0") { l1mudttfmasks.set_inrec_chdis_st3(-1, sec, true); l1mudttfmasks.set_inrec_chdis_st3(1, sec, true); //l1mudttfmasks.set_etsoc_chdis_st3(-1,sec,true); //l1mudttfmasks.set_etsoc_chdis_st3(1,sec,true); } if (masks[m] == "mask_ctrl_P1") { l1mudttfmasks.set_inrec_chdis_st3(2, sec, true); //l1mudttfmasks.set_etsoc_chdis_st3(2,sec,true); } if (masks[m] == "mask_ctrl_P2") { l1mudttfmasks.set_inrec_chdis_st3(3, sec, true); //l1mudttfmasks.set_etsoc_chdis_st3(3,sec,true); } } } if ((mask & 8) > 0) { for (int sec = 0; sec < 12; sec++) { if (masks[m] == "mask_ctrl_N2") { l1mudttfmasks.set_inrec_chdis_st4(-3, sec, true); } if (masks[m] == "mask_ctrl_N1") { l1mudttfmasks.set_inrec_chdis_st4(-2, sec, true); } if (masks[m] == "mask_ctrl_0") { l1mudttfmasks.set_inrec_chdis_st4(-1, sec, true); l1mudttfmasks.set_inrec_chdis_st4(1, sec, true); } if (masks[m] == "mask_ctrl_P1") { l1mudttfmasks.set_inrec_chdis_st4(2, sec, true); } if (masks[m] == "mask_ctrl_P2") { l1mudttfmasks.set_inrec_chdis_st4(3, sec, true); } } } } ///if register path } ///for masks } ///for it tRow } ///for it procRole } ///if configDB int L1TMuonBarrelParamsHelper::load_pt(std::vector<LUT>& pta_lut, std::vector<int>& pta_threshold, unsigned short int nbitphi, std::string AssLUTpath) { // maximal number of pt assignment methods const int MAX_PTASSMETH = 19; const int MAX_PTASSMETHA = 12; // pt assignment methods enum PtAssMethod { PT12L, PT12H, PT13L, PT13H, PT14L, PT14H, PT23L, PT23H, PT24L, PT24H, PT34L, PT34H, PB12H, PB13H, PB14H, PB21H, PB23H, PB24H, PB34H, NODEF }; // get directory name string pta_str = ""; // precision : in the look-up tables the following precision is used : // phi ...12 bits (address) and pt ...5 bits // now convert phi and phib to the required precision int nbit_phi = nbitphi; int sh_phi = 12 - nbit_phi; // loop over all pt-assignment methods for (int pam = 0; pam < MAX_PTASSMETH; pam++) { switch (pam) { case PT12L: { pta_str = "pta12l"; break; } case PT12H: { pta_str = "pta12h"; break; } case PT13L: { pta_str = "pta13l"; break; } case PT13H: { pta_str = "pta13h"; break; } case PT14L: { pta_str = "pta14l"; break; } case PT14H: { pta_str = "pta14h"; break; } case PT23L: { pta_str = "pta23l"; break; } case PT23H: { pta_str = "pta23h"; break; } case PT24L: { pta_str = "pta24l"; break; } case PT24H: { pta_str = "pta24h"; break; } case PT34L: { pta_str = "pta34l"; break; } case PT34H: { pta_str = "pta34h"; break; } case PB12H: { pta_str = "ptb12h_Feb2016"; break; } case PB13H: { pta_str = "ptb13h_Feb2016"; break; } case PB14H: { pta_str = "ptb14h_Feb2016"; break; } case PB21H: { pta_str = "ptb21h_Feb2016"; break; } case PB23H: { pta_str = "ptb23h_Feb2016"; break; } case PB24H: { pta_str = "ptb24h_Feb2016"; break; } case PB34H: { pta_str = "ptb34h_Feb2016"; break; } } // assemble file name const string& lutpath = AssLUTpath; edm::FileInPath lut_f = edm::FileInPath(string(lutpath + pta_str + ".lut")); string pta_file = lut_f.fullPath(); // open file L1TriggerLutFile file(pta_file); if (file.open() != 0) return -1; // get the right shift factor int shift = sh_phi; int adr_old = -2048 >> shift; if (pam >= MAX_PTASSMETHA) adr_old = -512 >> shift; LUT tmplut; int number = -1; int sum_pt = 0; if (file.good()) { int threshold = file.readInteger(); pta_threshold[pam / 2] = threshold; } // read values and shift to correct precision while (file.good()) { int adr = (file.readInteger()) >> shift; int pt = file.readInteger(); number++; //cout<<pam<<" "<<number<<" "<<MAX_PTASSMETHA<<endl; if (adr != adr_old) { assert(number); tmplut.insert(make_pair(adr_old, (sum_pt / number))); adr_old = adr; number = 0; sum_pt = 0; } sum_pt += pt; if (!file.good()) file.close(); } file.close(); pta_lut.push_back(tmplut); } return 0; } int L1TMuonBarrelParamsHelper::load_phi(std::vector<LUT>& phi_lut, unsigned short int nbit_phi, unsigned short int nbit_phib, std::string AssLUTpath) { // precision : in the look-up tables the following precision is used : // address (phib) ...10 bits, phi ... 12 bits int sh_phi = 12 - nbit_phi; int sh_phib = 10 - nbit_phib; string phi_str; // loop over all phi-assignment methods for (int idx = 0; idx < 2; idx++) { switch (idx) { case 0: { phi_str = "phi12"; break; } case 1: { phi_str = "phi42"; break; } } // assemble file name edm::FileInPath lut_f = edm::FileInPath(string(AssLUTpath + phi_str + ".lut")); string phi_file = lut_f.fullPath(); // open file L1TriggerLutFile file(phi_file); if (file.open() != 0) return -1; LUT tmplut; int number = -1; int adr_old = -512 >> sh_phib; int sum_phi = 0; // read values while (file.good()) { int adr = (file.readInteger()) >> sh_phib; int phi = file.readInteger(); number++; if (adr != adr_old) { assert(number); tmplut.insert(make_pair(adr_old, ((sum_phi / number) >> sh_phi))); adr_old = adr; number = 0; sum_phi = 0; } sum_phi += phi; if (!file.good()) file.close(); } file.close(); phi_lut.push_back(tmplut); } return 0; } /* int L1TMuonBarrelParamsESProducer::getPtLutThreshold(int pta_ind, std::vector<int>& pta_threshold) const { if ( pta_ind >= 0 && pta_ind < 13/2 ) { return pta_threshold[pta_ind]; } else { cerr << "PtaLut::getPtLutThreshold : can not find threshold " << pta_ind << endl; return 0; } } */ // // load extrapolation look-up tables // int L1TMuonBarrelParamsHelper::load_ext(std::vector<L1TMuonBarrelParams::LUTParams::extLUT>& ext_lut, unsigned short int nbit_phi, unsigned short int nbit_phib) { //max. number of Extrapolations const int MAX_EXT = 12; // extrapolation types enum Extrapolation { EX12, EX13, EX14, EX21, EX23, EX24, EX34, EX15, EX16, EX25, EX26, EX56 }; // get directory name string defaultPath = "L1Trigger/L1TMuon/data/bmtf_luts/"; string ext_dir = "LUTs_Ext/"; string ext_str = ""; // precision : in the look-up tables the following precision is used : // phi ...12 bits (low, high), phib ...10 bits (address) // now convert phi and phib to the required precision int sh_phi = 12 - nbit_phi; int sh_phib = 10 - nbit_phib; // loop over all extrapolations for (int ext = 0; ext < MAX_EXT; ext++) { switch (ext) { case EX12: ext_str = "ext12"; break; case EX13: ext_str = "ext13"; break; case EX14: ext_str = "ext14"; break; case EX21: ext_str = "ext21"; break; case EX23: ext_str = "ext23"; break; case EX24: ext_str = "ext24"; break; case EX34: ext_str = "ext34"; break; case EX15: ext_str = "ext15"; break; case EX16: ext_str = "ext16"; break; case EX25: ext_str = "ext25"; break; case EX26: ext_str = "ext26"; break; case EX56: ext_str = "ext56"; break; } // assemble file name edm::FileInPath lut_f = edm::FileInPath(string(defaultPath + ext_dir + ext_str + ".lut")); string ext_file = lut_f.fullPath(); // open file L1TriggerLutFile file(ext_file); if (file.open() != 0) return -1; // if ( L1MuDTTFConfig::Debug(1) ) cout << "Reading file : " // << file.getName() << endl; L1TMuonBarrelParams::LUTParams::extLUT tmplut; int number = -1; int adr_old = -512 >> sh_phib; int sum_low = 0; int sum_high = 0; // read values and shift to correct precision while (file.good()) { int adr = (file.readInteger()) >> sh_phib; // address (phib) int low = (file.readInteger()); // low value (phi) int high = (file.readInteger()); // high value (phi) number++; if (adr != adr_old) { tmplut.low[adr_old] = sum_low >> sh_phi; tmplut.high[adr_old] = sum_high >> sh_phi; adr_old = adr; number = 0; sum_low = 0; sum_high = 0; } if (number == 0) sum_low = low; if (number == 0) sum_high = high; if (!file.good()) file.close(); } file.close(); ext_lut.push_back(tmplut); } return 0; }
30.564615
139
0.554588
[ "vector" ]