hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
b797f6952a92c4021981cd5cb50e8fe4b7a6e3a6
969
hpp
C++
include/encstr/unroll.hpp
RequiDev/encstr
5132a31c34a4e41f8fccad491660f0adc891ded5
[ "MIT" ]
28
2018-10-18T06:53:40.000Z
2022-03-01T15:08:53.000Z
include/encstr/unroll.hpp
c3358/encstr
c93f3792ef29d9b5a51dfedef7567ae44dca06fd
[ "MIT" ]
null
null
null
include/encstr/unroll.hpp
c3358/encstr
c93f3792ef29d9b5a51dfedef7567ae44dca06fd
[ "MIT" ]
3
2018-12-12T15:12:03.000Z
2021-09-25T17:54:24.000Z
#pragma once #include <utility> #include <encstr/always_inline.hpp> namespace encstr { template<size_t Count, size_t Step = 1> struct unroll_t { template<typename Fn, typename... Args> ENCSTR_ALWAYS_INLINE constexpr auto operator()(Fn&& fn, Args&&... args) noexcept -> decltype(std::forward<Fn>(fn)(std::declval<size_t>(), std::forward<Args>(args)...)) { unroll_t<Count - Step>{}(std::forward<Fn>(fn), std::forward<Args>(args)...); return std::forward<Fn>(fn)(Count - Step, std::forward<Args>(args)...); } }; template<size_t Step> struct unroll_t<1, Step> { template<typename Fn, typename... Args> ENCSTR_ALWAYS_INLINE constexpr auto operator()(Fn&& fn, Args&&... args) noexcept -> decltype(std::forward<Fn>(fn)(std::declval<size_t>(), std::forward<Args>(args)...)) { return std::forward<Fn>(fn)(0, std::forward<Args>(args)...); } }; }
35.888889
175
0.596491
RequiDev
b79dd052ea1bbb9085036c012610b1dda27aeba4
929
hpp
C++
Source/Tortuga/Components/Light.hpp
zeeshan595/Tortuga
a4a96c73b9c7e1fffb2cea6661d2579709b0a7e1
[ "X11" ]
7
2019-03-06T11:25:27.000Z
2019-05-27T13:27:07.000Z
Source/Tortuga/Components/Light.hpp
zeeshan595/tortuga-library
a4a96c73b9c7e1fffb2cea6661d2579709b0a7e1
[ "X11" ]
3
2019-07-03T10:09:15.000Z
2019-10-12T23:23:31.000Z
Source/Tortuga/Components/Light.hpp
zeeshan595/Tortuga
a4a96c73b9c7e1fffb2cea6661d2579709b0a7e1
[ "X11" ]
null
null
null
#ifndef _LIGHT_COMPONENT #define _LIGHT_COMPONENT #include <glm/glm.hpp> #include "../Core/ECS/Entity.hpp" namespace Tortuga { namespace Components { enum LightType { POINT, DIRECTIONAL }; struct Light : Core::ECS::Component { private: LightType Type = LightType::POINT; glm::vec4 Color = glm::vec4(1, 1, 1, 1); float Intensity = 1.0f; float Range = 10.0f; public: LightType GetType() { return this->Type; } void SetType(LightType type) { this->Type = type; } glm::vec4 GetColor() { return this->Color; } void SetColor(glm::vec4 color) { this->Color = color; } float GetIntensity() { return this->Intensity; } void SetIntensity(float intensity) { this->Intensity = intensity; } float GetRange() { return this->Range; } void SetRange(float range) { this->Range = range; } }; } // namespace Components } // namespace Tortuga #endif
14.292308
42
0.639397
zeeshan595
b7b1b0bcbadf63c38c76aa1bd0fc482b2ab4050e
875
hpp
C++
world/BlockType.hpp
brendanberg01/Voxel
8b56f4fab57a1e7eb63b4794d0b4a193465d71a2
[ "MIT" ]
null
null
null
world/BlockType.hpp
brendanberg01/Voxel
8b56f4fab57a1e7eb63b4794d0b4a193465d71a2
[ "MIT" ]
null
null
null
world/BlockType.hpp
brendanberg01/Voxel
8b56f4fab57a1e7eb63b4794d0b4a193465d71a2
[ "MIT" ]
null
null
null
// // Created by Brendan Berg on 16.03.19. // #ifndef VOXEL_BLOCKTYPE_HPP #define VOXEL_BLOCKTYPE_HPP #include <string> #include <vector> #include <glm/glm.hpp> #include "BlockUtility.hpp" class BlockType { public: BlockType (unsigned int blockID, const std::string& name); BlockType (); unsigned int AddTexture (const std::pair<glm::vec2, glm::vec2>& tile); void SetSideTexture (BlockSide side, unsigned int texture); void SetSolid (); void SetOpaque (); glm::vec2 GetTextureCoordinate (BlockSide side, unsigned int vertex) const; bool IsSolid () const; bool IsOpaque () const; private: unsigned int m_BlockID; std::string m_Name; std::vector<std::pair<glm::vec2, glm::vec2>> m_TextureTiles; std::vector<int> m_SideToTexture; bool m_Solid; bool m_Opaque; }; #endif //VOXEL_BLOCKTYPE_HPP
15.086207
79
0.681143
brendanberg01
5d9be7a72754223955c5c27767b3c003bae7802d
782
hpp
C++
include/conceptslib/detail/concepts/invocable_workaround.hpp
seriouslyhypersonic/experimental_concepts
f736237dfc54a7c89ef1ed3888acf6f0aec3b98a
[ "BSL-1.0" ]
null
null
null
include/conceptslib/detail/concepts/invocable_workaround.hpp
seriouslyhypersonic/experimental_concepts
f736237dfc54a7c89ef1ed3888acf6f0aec3b98a
[ "BSL-1.0" ]
null
null
null
include/conceptslib/detail/concepts/invocable_workaround.hpp
seriouslyhypersonic/experimental_concepts
f736237dfc54a7c89ef1ed3888acf6f0aec3b98a
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) Nuno Alves de Sousa 2019 * * Use, modification and distribution is subject to the Boost Software License, * Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #ifndef DETAIL_INVOCABLE_WORKAROUND_H #define DETAIL_INVOCABLE_WORKAROUND_H #include <conceptslib/detail/concepts/concepts.hpp> #include <conceptslib/detail/functional/invoke.hpp> namespace platform { template<class F, class... Args> using invoke_result_t = functional::invoke_result_t<F, Args...>; REQUIREMENT InvocableReqImp { // Alternative implementation template<class F, class... Args> auto REQUIRES(F&&, Args&&... args) -> invoke_result_t<F, Args...>; }; } // namespace platform #endif //DETAIL_INVOCABLE_WORKAROUND_H
26.066667
79
0.748082
seriouslyhypersonic
5d9d26e143aac52c5b670f1646ee16c13aafaf8e
5,705
hpp
C++
src/w32/wic/wic_fwd.hpp
kei10in/w32
57081311df54dbaa0f31407987a9f291bc785114
[ "MIT" ]
null
null
null
src/w32/wic/wic_fwd.hpp
kei10in/w32
57081311df54dbaa0f31407987a9f291bc785114
[ "MIT" ]
null
null
null
src/w32/wic/wic_fwd.hpp
kei10in/w32
57081311df54dbaa0f31407987a9f291bc785114
[ "MIT" ]
null
null
null
#pragma once #include "../com.hpp" #include "wic_def.hpp" #include "wic_guids.hpp" namespace w32::wic { namespace internal { template <class T> class palette_t; template <class T> class bitmap_source_t; template <class T> class format_converter_t; template <class T> class planar_format_converter_t; template <class T> class bitmap_scaler_t; template <class T> class bitmap_clipper_t; template <class T> class bitmap_flip_rotator_t; template <class T> class bitmap_lock_t; template <class T> class bitmap_t; template <class T> class color_context_t; template <class T> class color_transform_t; template <class T> class fast_metadata_encoder_t; template <class T> class stream_t; template <class T> class enum_metadata_item_t; template <class T> class metadata_query_reader_t; template <class T> class metadata_query_writer_t; template <class T> class bitmap_encoder_t; template <class T> class bitmap_frame_encode_t; template <class T> class planar_bitmap_frame_encode_t; template <class T> class image_encoder_t; template <class T> class bitmap_decoder_t; template <class T> class bitmap_source_transform_t; template <class T> class planar_bitmap_source_transform_t; template <class T> class bitmap_frame_decode_t; template <class T> class progressive_level_control_t; template <class T> class progress_callback_t; template <class T> class bitmap_codec_progress_notification_t; template <class T> class component_info_t; template <class T> class format_converter_info_t; template <class T> class bitmap_codec_info_t; template <class T> class bitmap_encoder_info_t; template <class T> class bitmap_decoder_info_t; template <class T> class pixel_format_info_t; template <class T> class pixel_format_info2_t; template <class T> class imaging_factory_t; template <class T> class imaging_factory2_t; template <class T> class develop_raw_notification_callback_t; template <class T> class develop_raw_t; template <class T> class dds_decoder_t; template <class T> class dds_encoder_t; template <class T> class dds_frame_decode_t; template <class T> class jpeg_frame_decode_t; template <class T> class jpeg_frame_encode_t; } // namespace internal using palette = internal::palette_t<IWICPalette>; using bitmap_source = internal::bitmap_source_t<IWICBitmapSource>; using format_converter = internal::format_converter_t<IWICFormatConverter>; using planar_format_converter = internal::planar_format_converter_t<IWICPlanarFormatConverter>; using bitmap_scaler = internal::bitmap_scaler_t<IWICBitmapScaler>; using bitmap_clipper = internal::bitmap_clipper_t<IWICBitmapClipper>; using bitmap_flip_rotator = internal::bitmap_flip_rotator_t<IWICBitmapFlipRotator>; using bitmap_lock = internal::bitmap_lock_t<IWICBitmapLock>; using bitmap = internal::bitmap_t<IWICBitmap>; using color_context = internal::color_context_t<IWICColorContext>; using color_transform = internal::color_transform_t<IWICColorTransform>; using fast_metadata_encoder = internal::fast_metadata_encoder_t<IWICFastMetadataEncoder>; using stream = internal::stream_t<IWICStream>; using enum_metadata_item = internal::enum_metadata_item_t<IWICEnumMetadataItem>; using metadata_query_reader = internal::metadata_query_reader_t<IWICMetadataQueryReader>; using metadata_query_writer = internal::metadata_query_writer_t<IWICMetadataQueryWriter>; using bitmap_encoder = internal::bitmap_encoder_t<IWICBitmapEncoder>; using bitmap_frame_encode = internal::bitmap_frame_encode_t<IWICBitmapFrameEncode>; using planar_bitmap_frame_encode = internal::planar_bitmap_frame_encode_t<IWICPlanarBitmapFrameEncode>; using image_encoder = internal::image_encoder_t<IWICImageEncoder>; using bitmap_decoder = internal::bitmap_decoder_t<IWICBitmapDecoder>; using bitmap_source_transform = internal::bitmap_source_transform_t<IWICBitmapSourceTransform>; using planar_bitmap_source_transform = internal::planar_bitmap_source_transform_t<IWICPlanarBitmapSourceTransform>; using bitmap_frame_decode = internal::bitmap_frame_decode_t<IWICBitmapFrameDecode>; using progressive_level_control = internal::progressive_level_control_t<IWICProgressiveLevelControl>; using progress_callback = internal::progress_callback_t<IWICProgressCallback>; using bitmap_codec_progress_notification = internal::bitmap_codec_progress_notification_t< IWICBitmapCodecProgressNotification>; using component_info = internal::component_info_t<IWICComponentInfo>; using format_converter_info = internal::format_converter_info_t<IWICFormatConverterInfo>; using bitmap_codec_info = internal::bitmap_codec_info_t<IWICBitmapCodecInfo>; using bitmap_encoder_info = internal::bitmap_encoder_info_t<IWICBitmapEncoderInfo>; using bitmap_decoder_info = internal::bitmap_decoder_info_t<IWICBitmapDecoderInfo>; using pixel_format_info = internal::pixel_format_info_t<IWICPixelFormatInfo>; using pixel_format_info2 = internal::pixel_format_info2_t<IWICPixelFormatInfo2>; using imaging_factory = internal::imaging_factory_t<IWICImagingFactory>; using imaging_factory2 = internal::imaging_factory2_t<IWICImagingFactory2>; using develop_raw_notification_callback = internal::develop_raw_notification_callback_t< IWICDevelopRawNotificationCallback>; using develop_raw = internal::develop_raw_t<IWICDevelopRaw>; using dds_decoder = internal::dds_decoder_t<IWICDdsDecoder>; using dds_encoder = internal::dds_encoder_t<IWICDdsEncoder>; using dds_frame_decode = internal::dds_frame_decode_t<IWICDdsFrameDecode>; using jpeg_frame_decode = internal::jpeg_frame_decode_t<IWICJpegFrameDecode>; using jpeg_frame_encode = internal::jpeg_frame_encode_t<IWICJpegFrameEncode>; } // namespace w32::wic
27.829268
80
0.832252
kei10in
5d9dbcefa28a0bfa083f70a2b6e8d1145ab99f32
815
cpp
C++
src/Object.cpp
cppcooper/gumbo-query
f4c69278f09616e6275acd0dd2ea1d22f3785dc8
[ "MIT" ]
1
2022-02-28T15:51:39.000Z
2022-02-28T15:51:39.000Z
src/Object.cpp
cppcooper/gumbo-query
f4c69278f09616e6275acd0dd2ea1d22f3785dc8
[ "MIT" ]
null
null
null
src/Object.cpp
cppcooper/gumbo-query
f4c69278f09616e6275acd0dd2ea1d22f3785dc8
[ "MIT" ]
null
null
null
/*************************************************************************** * * $Id$ * **************************************************************************/ /** * @file $HeadURL$ * @author $Author$(hoping@baimashi.com) * @date $Date$ * @version $Revision$ * @brief * **/ #include <gumbo-query/Object.h> CObject::CObject() { mReferences = 1; } CObject::~CObject() { if (mReferences != 1) { throw "something wrong, reference count not zero"; } } void CObject::retain() { mReferences++; } void CObject::release() { if (mReferences < 0) { throw "something wrong, reference count is negative"; } if (mReferences == 1) { delete this; } else { mReferences--; } } unsigned int CObject::references() { return mReferences; } /* vim: set ts=4 sw=4 sts=4 tw=100 noet: */
13.583333
76
0.490798
cppcooper
5da468b6b52d1014af4bf260192430b84ccc8f22
16,695
cpp
C++
plugins/my_videobasedtracker/VideoTrackerCalibrationUtility.cpp
ccccjason/OSVR_device_plugin
6c9171265900530341cfa79357151daa39618737
[ "Apache-2.0" ]
1
2022-03-28T05:09:11.000Z
2022-03-28T05:09:11.000Z
plugins/videobasedtracker/VideoTrackerCalibrationUtility.cpp
ccccjason/my_osvr
fdb2a64cbf88211c34f8c8bd42f0f83a6b98769e
[ "Apache-2.0" ]
null
null
null
plugins/videobasedtracker/VideoTrackerCalibrationUtility.cpp
ccccjason/my_osvr
fdb2a64cbf88211c34f8c8bd42f0f83a6b98769e
[ "Apache-2.0" ]
null
null
null
/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. // Internal Includes #include "ConfigurationParser.h" #include "ImageSourceFactories.h" #include "VideoBasedTracker.h" #include <osvr/Server/ConfigureServerFromFile.h> #include "HDKData.h" #include "HDKLedIdentifierFactory.h" #include "CameraParameters.h" #include <osvr/Common/JSONHelpers.h> #include <osvr/Common/JSONEigen.h> // Library/third-party includes #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <json/reader.h> #include <json/value.h> // Standard includes #include <memory> #include <iostream> #include <unordered_set> using std::endl; using namespace osvr::vbtracker; static osvr::server::detail::StreamPrefixer out("[OSVR Video Tracker Calibration] ", std::cout); static osvr::server::detail::StreamPrefixer err("[OSVR Video Tracker Calibration] ", std::cerr); /// @brief OpenCV's simple highgui module refers to windows by their name, so we /// make this global for a simpler demo. static const std::string windowNameAndInstructions( "OSVR tracking camera preview | q or esc to quit"); static int withAnError() { err << "\n"; err << "Press enter to exit." << endl; std::cin.ignore(); return -1; } static Json::Value findVideoTrackerParams(Json::Value const &drivers) { if (!drivers.isArray()) { return Json::Value(Json::nullValue); } for (auto const &entry : drivers) { if (entry["plugin"] == "com_osvr_VideoBasedHMDTracker" && entry["driver"] == "VideoBasedHMDTracker") { return entry["params"]; } } return Json::Value(Json::nullValue); } class TrackerCalibrationApp { public: TrackerCalibrationApp(ImageSourcePtr &&src, osvr::vbtracker::ConfigParams params) : m_src(std::move(src)), m_params(params), m_vbtracker(params) { m_firstNotch = m_params.initialBeaconError * 0.9; m_secondNotch = m_params.initialBeaconError * 0.8; cv::namedWindow(windowNameAndInstructions); } osvr::vbtracker::VideoBasedTracker &vbtracker() { return m_vbtracker; } void run() { /// Turn off the Kalman filter until the user has brought the HMD close. vbtracker().getFirstEstimator().permitKalmanMode(false); /// Get the HMD close. { out << "Bring the HMD into view and fairly close to the camera." << endl; double zDistance = 1000.; while (zDistance > 0.3 && !m_quit) { tryGrabAndProcessFrame([&zDistance](OSVR_ChannelCount sensor, OSVR_Pose3 const &pose) { if (sensor == 0) { zDistance = osvrVec3GetZ(&pose.translation); } }); if (timeToUpdateDisplay()) { m_frame.copyTo(m_display); cv::putText( m_display, "Bring the HMD into view and close to the camera.", cv::Point(30, 30), cv::FONT_HERSHEY_SIMPLEX, 0.4, cv::Scalar(255, 0, 0)); updateDisplay(); } } } if (m_quit) { /// early out. return; } /// Now, we can turn on the Kalman filter. vbtracker().getFirstEstimator().permitKalmanMode(true); out << "OK - you'll now want to move the HMD slowly around the view of " "the camera, and rotate it so that all sides can be seen." << endl; out << "Press 's' to save your calibration when you're done." << endl; m_frame.copyTo(m_display); updateDisplay(); /// these are beacon IDs we disabled (1-based) static const auto IDS_TO_SKIP = std::unordered_set<std::size_t>{ 1, 2, 10, 12, 13, 14, 21, 35, 38, /* plus the rest of the back */ 36, 37, 39, 40}; while (!m_quit) { bool gotDebugData = false; tryGrabAndProcessFrame( [&](OSVR_ChannelCount sensor, OSVR_Pose3 const &pose) { if (sensor == 0) { gotDebugData = true; } }); if (timeToUpdateDisplay() && gotDebugData) { m_frame.copyTo(m_display); { /// Draw circles for each active beacon showing the size of /// the residuals auto &debugData = vbtracker().getFirstEstimator().getBeaconDebugData(); auto nBeacons = debugData.size(); auto nBeaconsActive = size_t{0}; auto nBeaconsIdentified = size_t{0}; for (decltype(nBeacons) i = 0; i < nBeacons; ++i) { if (debugData[i].measurement.x != 0) { nBeaconsIdentified++; } if (debugData[i].variance == 0) { continue; } nBeaconsActive++; #if 0 cv::line(m_display, debugData[i].measurement, debugData[i].measurement + debugData[i].residual, cv::Scalar(0, 255, 0), 2); #else cv::circle(m_display, debugData[i].measurement, cv::norm(debugData[i].residual), cv::Scalar(20, 20, 20), 2); #endif } cv::putText(m_display, std::to_string(nBeaconsActive) + " beacons active of " + std::to_string(nBeaconsIdentified) + " identified this frame", cv::Point(30, 30), cv::FONT_HERSHEY_SIMPLEX, 0.45, cv::Scalar(255, 100, 100)); cv::putText(m_display, "Green labels indicate beacons with " "enough calibration data. S to save " "and quit.", cv::Point(30, 50), cv::FONT_HERSHEY_SIMPLEX, 0.45, cv::Scalar(255, 100, 100)); } { /// Reproject (almost) all beacons std::vector<cv::Point2f> reprojections; vbtracker().getFirstEstimator().ProjectBeaconsToImage( reprojections); std::size_t nBeacons = reprojections.size(); m_nBeacons = nBeacons; for (std::size_t i = 0; i < nBeacons; ++i) { if (IDS_TO_SKIP.find(i + 1) != end(IDS_TO_SKIP)) { continue; // skip this one. } Eigen::Vector3d autocalibVariance = vbtracker() .getFirstEstimator() .getBeaconAutocalibVariance(i); cv::Scalar color{0, 0, 255}; if ((autocalibVariance.array() < Eigen::Array3d::Constant(m_secondNotch)) .all()) { /// Green - good! color = cv::Scalar{0, 255, 0}; } else if ((autocalibVariance.array() < Eigen::Array3d::Constant(m_firstNotch)) .all()) { /// Yellow - better than where you started color = cv::Scalar{0, 255, 255}; } cv::putText(m_display, std::to_string(i + 1), reprojections[i] + cv::Point2f(1, 1), cv::FONT_HERSHEY_SIMPLEX, 0.45, color); } } auto key = updateDisplay(); if ('s' == key || 'S' == key) { m_save = true; m_quit = true; } } } for (std::size_t i = 0; i < m_nBeacons; ++i) { if (IDS_TO_SKIP.find(i + 1) != end(IDS_TO_SKIP)) { continue; // skip this one. } std::cout << "Beacon " << i + 1 << " autocalib variance ratio: " << vbtracker() .getFirstEstimator() .getBeaconAutocalibVariance(i) .transpose() / m_params.initialBeaconError << "\n"; } std::cout << endl; if (m_save) { Json::Value calib(Json::arrayValue); out << "Saving your calibration data..." << endl; auto &estimator = vbtracker().getFirstEstimator(); for (std::size_t i = 0; i < m_nBeacons; ++i) { calib.append(osvr::common::toJson( estimator.getBeaconAutocalibPosition(i))); } std::cout << "\n" << osvr::common::jsonToCompactString(calib) << "\n" << endl; { std::ofstream outfile(m_params.calibrationFile); outfile << osvr::common::jsonToStyledString(calib); outfile.close(); } out << "Done! Press enter to exit." << endl; std::cin.ignore(); } } /// returns true if we processed a frame. template <typename F> bool tryGrabAndProcessFrame(F &&functor) { if (!m_src->grab()) { err << "Failed to grab!" << endl; return false; } m_timestamp = osvr::util::time::getNow(); m_src->retrieve(m_frame, m_imageGray); m_vbtracker.processImage(m_frame, m_imageGray, m_timestamp, std::forward<F>(functor)); m_frameStride = (m_frameStride + 1) % 11; return true; } /// Is it time to update the display window? bool timeToUpdateDisplay() const { return m_frameStride == 0; } /// Set the contents of m_display before calling this. Returns the character /// pressed, if any. char updateDisplay() { cv::imshow(windowNameAndInstructions, m_display); auto key = static_cast<char>(cv::waitKey(1)); if ('q' == key || 'Q' == key || 27 /* esc */ == key) { m_quit = true; } return key; } private: ImageSourcePtr m_src; osvr::vbtracker::ConfigParams m_params; double m_firstNotch; double m_secondNotch; osvr::vbtracker::VideoBasedTracker m_vbtracker; osvr::util::time::TimeValue m_timestamp; cv::Mat m_frame; cv::Mat m_imageGray; // This is the one the steps of the app should mess with. cv::Mat m_display; std::size_t m_frameStride = 0; std::size_t m_nBeacons = 0; bool m_quit = false; bool m_save = false; }; int main(int argc, char *argv[]) { ConfigParams params; /// First step: get the config. { std::string configName(osvr::server::getDefaultConfigFilename()); if (argc > 1) { configName = argv[1]; } else { out << "Using default config file - pass a filename on the command " "line to use a different one." << endl; } Json::Value root; { out << "Using config file '" << configName << "'" << endl; std::ifstream configFile(configName); if (!configFile.good()) { err << "Could not open config file!" << endl; err << "Searched in the current directory; file may be " "misspelled, missing, or in a different directory." << endl; return withAnError(); } Json::Reader reader; if (!reader.parse(configFile, root)) { err << "Could not parse config file as JSON!" << endl; return withAnError(); } } auto trackerParams = findVideoTrackerParams(root["drivers"]); if (trackerParams.isNull()) { out << "Warning: No video tracker params found?" << endl; } // Actually parse those params from JSON to the struct, just like the // plugin would. params = parseConfigParams(trackerParams); } if (params.calibrationFile.empty()) { err << "calibrationFile not specified in configuration file! no clue " "where to write to!" << endl; return withAnError(); } /// Second step: Adjust the config slightly. params.debug = false; params.extraVerbose = false; // don't need those messages params.streamBeaconDebugInfo = true; // want the data being recorded there. /// Third step: Open cam and construct a tracker. auto src = openHDKCameraDirectShow(); if (!src || !src->ok()) { err << "Couldn't find or access the IR camera!" << endl; return withAnError(); } // Set the number of threads for OpenCV to use. cv::setNumThreads(1); TrackerCalibrationApp trackerApp{std::move(src), params}; /// Fourth step: Add the sensors to the tracker. { auto backPanelFixedBeacon = [](int) { return true; }; auto frontPanelFixedBeacon = [](int id) { return (id == 16) || (id == 17) || (id == 19) || (id == 20); }; auto camParams = getHDKCameraParameters(); if (params.includeRearPanel) { // distance between front and back panel target origins, in mm. auto distanceBetweenPanels = params.headCircumference / M_PI * 10. + params.headToFrontBeaconOriginDistance; Point3Vector locations = OsvrHdkLedLocations_SENSOR0; Vec3Vector directions = OsvrHdkLedDirections_SENSOR0; std::vector<double> variances = OsvrHdkLedVariances_SENSOR0; // For the back panel beacons: have to rotate 180 degrees // about Y, which is the same as flipping sign on X and Z // then we must translate along Z by head diameter + // distance from head to front beacon origins for (auto &pt : OsvrHdkLedLocations_SENSOR1) { locations.emplace_back(-pt.x, pt.y, -pt.z - distanceBetweenPanels); variances.push_back(params.backPanelMeasurementError); } // Similarly, rotate the directions. for (auto &vec : OsvrHdkLedDirections_SENSOR1) { directions.emplace_back(-vec[0], vec[1], -vec[2]); } trackerApp.vbtracker().addSensor( createHDKUnifiedLedIdentifier(), camParams, locations, directions, variances, frontPanelFixedBeacon, 4, 0); } else { err << "WARNING: only calibrating the first sensor is currently " "supported!" << endl; // OK, so if we don't have to include the rear panel as part of the // single sensor, that's easy. trackerApp.vbtracker().addSensor( createHDKLedIdentifier(0), camParams, OsvrHdkLedLocations_SENSOR0, OsvrHdkLedDirections_SENSOR0, OsvrHdkLedVariances_SENSOR0, frontPanelFixedBeacon, 6, 0); trackerApp.vbtracker().addSensor( createHDKLedIdentifier(1), camParams, OsvrHdkLedLocations_SENSOR1, OsvrHdkLedDirections_SENSOR1, backPanelFixedBeacon, 4, 0); } } trackerApp.run(); return 0; }
38.556582
146
0.518598
ccccjason
5da7765db463a56f51e4be700d35f3460e6213a5
147
cpp
C++
KFPlugin/KFRobot/KFStateWait.cpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
1
2021-04-26T09:31:32.000Z
2021-04-26T09:31:32.000Z
KFPlugin/KFRobot/KFStateWait.cpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
null
null
null
KFPlugin/KFRobot/KFStateWait.cpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
null
null
null
#include "KFStateWait.hpp" namespace KFrame { bool KFStateWait::CheckState( KFFsm* fsm, KFRobot* robot ) { return false; } }
14.7
62
0.62585
282951387
5da86dca6536dd87cc29260b5b1139cb6cfcf2af
1,240
cpp
C++
src/parse_invocation.cpp
to-miz/tg
84950c00dc62418d1c82ac05489ce0df18ebd4db
[ "MIT" ]
null
null
null
src/parse_invocation.cpp
to-miz/tg
84950c00dc62418d1c82ac05489ce0df18ebd4db
[ "MIT" ]
null
null
null
src/parse_invocation.cpp
to-miz/tg
84950c00dc62418d1c82ac05489ce0df18ebd4db
[ "MIT" ]
null
null
null
struct parsed_invocation { literal_block_t body; int stack_size = 0; int scope_index = -1; bool valid = false; }; parsed_invocation parse_invocation(process_state_t* state, tokenizer_t* tokenizer) { auto impl = [](process_state_t* state, tokenizer_t* tokenizer, parsed_invocation* out) { parsing_state_t parsing = {state->data}; out->scope_index = parsing.push_scope(); auto segment = &out->body.segments.emplace_back(); if (parse_statements(tokenizer, &parsing, segment, {}) != pr_success) return; out->stack_size = parsing.current_stack_size; parsing.current_stack_size = 0; if (!process_parsed_data(*state)) return; auto prev = state->set_scope(out->scope_index); auto prev_file = state->file; state->file = tokenizer->file; bool infer_result = infer_expression_types_block(state, &out->body); state->file = prev_file; state->set_scope(prev); if (!infer_result) return; out->valid = true; out->body.valid = true; determine_block_output(&out->body); parsing.pop_scope(); }; parsed_invocation result = {}; impl(state, tokenizer, &result); return result; }
35.428571
92
0.647581
to-miz
5dab913194448f00e5cec4f25cbf98478074d65a
974
cpp
C++
Object/Mesh.cpp
youch34/DirectX11
abf187e54dfcbf1d869aa345807a54a541097118
[ "Unlicense" ]
null
null
null
Object/Mesh.cpp
youch34/DirectX11
abf187e54dfcbf1d869aa345807a54a541097118
[ "Unlicense" ]
null
null
null
Object/Mesh.cpp
youch34/DirectX11
abf187e54dfcbf1d869aa345807a54a541097118
[ "Unlicense" ]
null
null
null
#include "stdafx.h" #include "Mesh.h" #include "Pipeline/ConstantBuffer.h" Mesh::Mesh(std::vector<Texture2D>& textures) { this->textures = textures; } Mesh::~Mesh() { } void Mesh::Render(ID3D11Device* pDevice, ID3D11DeviceContext* pContext, DirectX::XMMATRIX parent, DirectX::XMMATRIX view_proj) { VertexBuffer vb; vb.Create(pDevice, pContext, vertices); IndexBuffer ib; ib.Create(pDevice, pContext, indices); ConstantMatrix cm; cm.world = transformMatrix * parent; cm.view_proj = view_proj; ConstantBuffer<ConstantMatrix> cb; cb.Create(pDevice, pContext, cm, BindShader::VS, 0u); for (int i = 0; i < textures.size(); i++) { if(textures[i].GetType() == aiTextureType::aiTextureType_DIFFUSE) pContext->PSSetShaderResources(0,1,textures[i].GetAddressofSRV()); } pContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); pContext->DrawIndexed(indices.size(), 0u, 0u); } void Mesh::Update() { }
23.756098
127
0.705339
youch34
5db2426a66a6e3da61d3e9508e7434d1a0943229
1,604
hpp
C++
include/nodes/internal/Export.hpp
bczol/QNodeEditor
427b6fe13049aae62855b893b524f17278e8c06f
[ "BSD-3-Clause" ]
13
2020-02-15T06:08:09.000Z
2021-09-29T00:38:59.000Z
include/nodes/internal/Export.hpp
bczol/QNodeEditor
427b6fe13049aae62855b893b524f17278e8c06f
[ "BSD-3-Clause" ]
null
null
null
include/nodes/internal/Export.hpp
bczol/QNodeEditor
427b6fe13049aae62855b893b524f17278e8c06f
[ "BSD-3-Clause" ]
7
2020-06-24T12:05:14.000Z
2022-01-20T15:26:08.000Z
#pragma once #include "Compiler.hpp" #include "OperatingSystem.hpp" #ifdef NODE_EDITOR_PLATFORM_WINDOWS #define NODE_EDITOR_EXPORT __declspec(dllexport) #define NODE_EDITOR_IMPORT __declspec(dllimport) #define NODE_EDITOR_LOCAL #elif NODE_EDITOR_COMPILER_GNU_VERSION_MAJOR >= 4 || defined(NODE_EDITOR_COMPILER_CLANG) #define NODE_EDITOR_EXPORT __attribute__((visibility("default"))) #define NODE_EDITOR_IMPORT __attribute__((visibility("default"))) #define NODE_EDITOR_LOCAL __attribute__((visibility("hidden"))) #else #define NODE_EDITOR_EXPORT #define NODE_EDITOR_IMPORT #define NODE_EDITOR_LOCAL #endif #ifdef __cplusplus #define NODE_EDITOR_DEMANGLED extern "C" #else #define NODE_EDITOR_DEMANGLED #endif #if defined(NODE_EDITOR_SHARED) && !defined(NODE_EDITOR_STATIC) #ifdef NODE_EDITOR_EXPORTS #define NODE_EDITOR_PUBLIC NODE_EDITOR_EXPORT #else #define NODE_EDITOR_PUBLIC NODE_EDITOR_IMPORT #endif #define NODE_EDITOR_PRIVATE NODE_EDITOR_LOCAL #elif !defined(NODE_EDITOR_SHARED) && defined(NODE_EDITOR_STATIC) #define NODE_EDITOR_PUBLIC #define NODE_EDITOR_PRIVATE #elif defined(NODE_EDITOR_SHARED) && defined(NODE_EDITOR_STATIC) #ifdef NODE_EDITOR_EXPORTS #error "Cannot build as shared and static simultaneously." #else #error "Cannot link against shared and static simultaneously." #endif #else #ifdef NODE_EDITOR_EXPORTS #error "Choose whether to build as shared or static." #else #error "Choose whether to link against shared or static." #endif #endif
35.644444
88
0.763092
bczol
5dc1eb7aed5eb08037017b8182c5717682d4c67c
3,967
cpp
C++
source/Rendering/Shader.cpp
zeskeertwee/Engine
919d9cff18fa16a828ab3dc382f1f8e13337acfc
[ "MIT" ]
7
2021-07-01T16:53:21.000Z
2021-12-03T16:57:19.000Z
source/Rendering/Shader.cpp
zeskeertwee/Engine
919d9cff18fa16a828ab3dc382f1f8e13337acfc
[ "MIT" ]
null
null
null
source/Rendering/Shader.cpp
zeskeertwee/Engine
919d9cff18fa16a828ab3dc382f1f8e13337acfc
[ "MIT" ]
1
2021-09-01T13:33:56.000Z
2021-09-01T13:33:56.000Z
#include "Shader.hpp" #include "Renderer.hpp" #include <iostream> #include <fstream> #include <string> #include <sstream> bool compiled = false; Shader::Shader(const std::string& filepath) : m_FilePath(filepath), m_RendererID(0) { ShaderProgramSource source = ParseShader(filepath); m_RendererID = CreateShader(source.VertexSource, source.FragmentSource); } Shader::~Shader() { GLCall(glDeleteProgram(m_RendererID)); } ShaderProgramSource Shader::ParseShader(const std::string& filepath) { std::ifstream stream(filepath); enum class ShaderType { NONE = -1, VERTEX = 0, FRAGMENT = 1 }; std::string line; std::stringstream ss[2]; ShaderType type = ShaderType::NONE; while (getline(stream, line)) { if (line.find("#shader") != std::string::npos) { if (line.find("vertex") != std::string::npos) { type = ShaderType::VERTEX; } else if (line.find("fragment") != std::string::npos) { type = ShaderType::FRAGMENT; } } else { ss[(int)type] << line << '\n'; } } return { ss[0].str(), ss[1].str() }; } unsigned int Shader::CompileShader(unsigned type, const std::string& source) { unsigned int id = glCreateShader(type); const char* src = source.c_str(); glShaderSource(id, 1, &src, nullptr); glCompileShader(id); int result; glGetShaderiv(id, GL_COMPILE_STATUS, &result); if (result == GL_FALSE) { int length; glGetShaderiv(id, GL_INFO_LOG_LENGTH, &length); char* message = (char*)alloca(length * sizeof(char)); glGetShaderInfoLog(id, length, &length, message); std::cout << "Dodrbal jsi shader inteligente!" << (type == GL_VERTEX_SHADER ? "vertex chytraku" : "fragment chytraku") << std::endl; std::cout << message << std::endl; glDeleteShader(id); return 0; } return id; } unsigned int Shader::CreateShader(const std::string& vertexShader, const std::string& fragmentShader) { unsigned int program = glCreateProgram(); unsigned int vs = CompileShader(GL_VERTEX_SHADER, vertexShader); unsigned int fs = CompileShader(GL_FRAGMENT_SHADER, fragmentShader); glAttachShader(program, vs); glAttachShader(program, fs); glLinkProgram(program); glValidateProgram(program); glDeleteShader(vs); glDeleteShader(fs); return program; } void Shader::Bind() const { GLCall(glUseProgram(m_RendererID)); } void Shader::Unbind() const { GLCall(glUseProgram(0)); compiled = true; } void Shader::SetUniform1i(const std::string& name, int value) { GLCall(glUniform1i(GetUniformLocation(name), value)); } void Shader::SetUniform1f(const std::string& name, float value) { GLCall(glUniform1f(GetUniformLocation(name), value)); } void Shader::SetUniform3f(const std::string& name, float x, float y, float z) { GLCall(glUniform3f(GetUniformLocation(name), x, y, z)); } void Shader::SetUniform3fv(const std::string& name, glm::vec3& vector) { GLCall(glUniform3fv(GetUniformLocation(name), 1, &vector[0])); } void Shader::SetUniform4f(const std::string& name, float v0, float v1, float v2, float v3) { GLCall(glUniform4f(GetUniformLocation(name), v0, v1, v2, v3)); } void Shader::SetUniformMat4f(const std::string& name, const glm::mat4& matrix) { glUniformMatrix4fv(GetUniformLocation(name), 1, GL_FALSE, &matrix[0][0]); } int Shader::GetUniformLocation(const std::string& name) { if (m_UniformLocationCache.find(name) != m_UniformLocationCache.end()) return m_UniformLocationCache[name]; GLCall(int location = glGetUniformLocation(m_RendererID, name.c_str())); if (location == -1) { if(!compiled) { std::cout << "Varovani: uniform '" << name << "' neexistuje!" << std::endl; } } else { m_UniformLocationCache[name] = location; } return location; }
29.385185
140
0.650618
zeskeertwee
5dc1ff4b9c3d257dd2a40aa727580636c5c31aad
858
hpp
C++
byte-mini.hpp
Hypnotron/Line-Shortener
5ab728f64874dc677a95cfc65d9b8b33d604cf61
[ "MIT" ]
null
null
null
byte-mini.hpp
Hypnotron/Line-Shortener
5ab728f64874dc677a95cfc65d9b8b33d604cf61
[ "MIT" ]
null
null
null
byte-mini.hpp
Hypnotron/Line-Shortener
5ab728f64874dc677a95cfc65d9b8b33d604cf61
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> using u8 = std::uint8_t; using u16 = std::uint16_t; using u32 = std::uint32_t; using u64 = std::uint64_t; using s8 = std::int8_t; using s16 = std::int16_t; using s32 = std::int32_t; using s64 = std::int64_t; using u8_fast = std::uint_fast8_t; using u16_fast = std::uint_fast16_t; using u32_fast = std::uint_fast32_t; using u64_fast = std::uint_fast64_t; using s8_fast = std::int_fast8_t; using s16_fast = std::int_fast16_t; using s32_fast = std::int_fast32_t; using s64_fast = std::int_fast64_t; template <typename OutputIteratorType, typename InputIteratorType> void interleave( InputIteratorType left, InputIteratorType right, OutputIteratorType output, size_t length) { for (; length > 0; --length) { *(output++) = *(left++); *(output++) = *(right++); } }
24.514286
66
0.677156
Hypnotron
5dc2b2656e1543403e14e735f9251a65fb28f105
43,281
cpp
C++
FPSLighting/Dependencies/DIRECTX/Samples/C++/Direct3D/DepthOfField/DepthOfField.cpp
billionare/FPSLighting
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
[ "MIT" ]
null
null
null
FPSLighting/Dependencies/DIRECTX/Samples/C++/Direct3D/DepthOfField/DepthOfField.cpp
billionare/FPSLighting
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
[ "MIT" ]
null
null
null
FPSLighting/Dependencies/DIRECTX/Samples/C++/Direct3D/DepthOfField/DepthOfField.cpp
billionare/FPSLighting
c7d646f51cf4dee360dcc7c8e2fd2821b421b418
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------------------- // File: DepthOfField.cpp // // Depth of field // // Copyright (c) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "DXUT.h" #include "DXUTsettingsdlg.h" #include "DXUTcamera.h" #include "SDKmisc.h" #include "resource.h" //#define DEBUG_VS // Uncomment this line to debug vertex shaders //#define DEBUG_PS // Uncomment this line to debug pixel shaders //-------------------------------------------------------------------------------------- // Vertex format //-------------------------------------------------------------------------------------- struct VERTEX { D3DXVECTOR4 pos; DWORD clr; D3DXVECTOR2 tex1; D3DXVECTOR2 tex2; D3DXVECTOR2 tex3; D3DXVECTOR2 tex4; D3DXVECTOR2 tex5; D3DXVECTOR2 tex6; static const DWORD FVF; }; const DWORD VERTEX::FVF = D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX6; //-------------------------------------------------------------------------------------- // Global variables //-------------------------------------------------------------------------------------- ID3DXFont* g_pFont = NULL; // Font for drawing text ID3DXSprite* g_pTextSprite = NULL; // Sprite for batching draw text calls CFirstPersonCamera g_Camera; // A model viewing camera bool g_bShowHelp = true; // If true, it renders the UI control text CDXUTDialogResourceManager g_DialogResourceManager; // manager for shared resources of dialogs CD3DSettingsDlg g_SettingsDlg; // Device settings dialog CDXUTDialog g_HUD; // dialog for standard controls CDXUTDialog g_SampleUI; // dialog for sample specific controls VERTEX g_Vertex[4]; LPDIRECT3DTEXTURE9 g_pFullScreenTexture; LPD3DXRENDERTOSURFACE g_pRenderToSurface; LPDIRECT3DSURFACE9 g_pFullScreenTextureSurf; LPD3DXMESH g_pScene1Mesh; LPDIRECT3DTEXTURE9 g_pScene1MeshTexture; LPD3DXMESH g_pScene2Mesh; LPDIRECT3DTEXTURE9 g_pScene2MeshTexture; int g_nCurrentScene; LPD3DXEFFECT g_pEffect; D3DXVECTOR4 g_vFocalPlane; double g_fChangeTime; int g_nShowMode; DWORD g_dwBackgroundColor; D3DVIEWPORT9 g_ViewportFB; D3DVIEWPORT9 g_ViewportOffscreen; FLOAT g_fBlurConst; DWORD g_TechniqueIndex; D3DXHANDLE g_hFocalPlane; D3DXHANDLE g_hWorld; D3DXHANDLE g_hWorldView; D3DXHANDLE g_hWorldViewProjection; D3DXHANDLE g_hMeshTexture; D3DXHANDLE g_hTechWorldWithBlurFactor; D3DXHANDLE g_hTechShowBlurFactor; D3DXHANDLE g_hTechShowUnmodified; D3DXHANDLE g_hTech[5]; static CHAR* g_TechniqueNames[] = { "UsePS20ThirteenLookups", "UsePS20SevenLookups", "UsePS20SixTexcoords" }; const DWORD g_TechniqueCount = sizeof( g_TechniqueNames ) / sizeof( LPCSTR ); //-------------------------------------------------------------------------------------- // UI control IDs //-------------------------------------------------------------------------------------- #define IDC_TOGGLEFULLSCREEN 1 #define IDC_TOGGLEREF 3 #define IDC_CHANGEDEVICE 4 #define IDC_CHANGE_SCENE 5 #define IDC_CHANGE_TECHNIQUE 6 #define IDC_SHOW_BLUR 7 #define IDC_CHANGE_BLUR 8 #define IDC_CHANGE_FOCAL 9 #define IDC_CHANGE_BLUR_STATIC 10 #define IDC_SHOW_UNBLURRED 11 #define IDC_SHOW_NORMAL 12 #define IDC_CHANGE_FOCAL_STATIC 13 //-------------------------------------------------------------------------------------- // Forward declarations //-------------------------------------------------------------------------------------- bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ); bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ); HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ); void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ); void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ); LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ); void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ); void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ); void CALLBACK OnLostDevice( void* pUserContext ); void CALLBACK OnDestroyDevice( void* pUserContext ); void InitApp(); HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh ); void RenderText(); void SetupQuad( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ); HRESULT UpdateTechniqueSpecificVariables( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ); //-------------------------------------------------------------------------------------- // Entry point to the program. Initializes everything and goes into a message processing // loop. Idle time is used to render the scene. //-------------------------------------------------------------------------------------- INT WINAPI wWinMain( HINSTANCE, HINSTANCE, LPWSTR, int ) { // Enable run-time memory check for debug builds. #if defined(DEBUG) | defined(_DEBUG) _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); #endif // DXUT will create and use the best device (either D3D9 or D3D10) // that is available on the system depending on which D3D callbacks are set below // Set DXUT callbacks DXUTSetCallbackD3D9DeviceAcceptable( IsDeviceAcceptable ); DXUTSetCallbackD3D9DeviceCreated( OnCreateDevice ); DXUTSetCallbackD3D9DeviceReset( OnResetDevice ); DXUTSetCallbackD3D9FrameRender( OnFrameRender ); DXUTSetCallbackD3D9DeviceLost( OnLostDevice ); DXUTSetCallbackD3D9DeviceDestroyed( OnDestroyDevice ); DXUTSetCallbackMsgProc( MsgProc ); DXUTSetCallbackKeyboard( KeyboardProc ); DXUTSetCallbackFrameMove( OnFrameMove ); DXUTSetCallbackDeviceChanging( ModifyDeviceSettings ); DXUTSetCursorSettings( true, true ); InitApp(); DXUTInit( true, true ); // Parse the command line and show msgboxes DXUTSetHotkeyHandling( true, true, true ); DXUTCreateWindow( L"DepthOfField" ); DXUTCreateDevice( true, 640, 480 ); DXUTMainLoop(); return DXUTGetExitCode(); } //-------------------------------------------------------------------------------------- // Initialize the app //-------------------------------------------------------------------------------------- void InitApp() { g_pFont = NULL; g_pFullScreenTexture = NULL; g_pFullScreenTextureSurf = NULL; g_pRenderToSurface = NULL; g_pEffect = NULL; g_vFocalPlane = D3DXVECTOR4( 0.0f, 0.0f, 1.0f, -2.5f ); g_fChangeTime = 0.0f; g_pScene1Mesh = NULL; g_pScene1MeshTexture = NULL; g_pScene2Mesh = NULL; g_pScene2MeshTexture = NULL; g_nCurrentScene = 1; g_nShowMode = 0; g_bShowHelp = TRUE; g_dwBackgroundColor = 0x00003F3F; g_fBlurConst = 4.0f; g_TechniqueIndex = 0; g_hFocalPlane = NULL; g_hWorld = NULL; g_hWorldView = NULL; g_hWorldViewProjection = NULL; g_hMeshTexture = NULL; g_hTechWorldWithBlurFactor = NULL; g_hTechShowBlurFactor = NULL; g_hTechShowUnmodified = NULL; ZeroMemory( g_hTech, sizeof( g_hTech ) ); // Initialize dialogs g_SettingsDlg.Init( &g_DialogResourceManager ); g_HUD.Init( &g_DialogResourceManager ); g_SampleUI.Init( &g_DialogResourceManager ); g_HUD.SetCallback( OnGUIEvent ); int iY = 10; g_HUD.AddButton( IDC_TOGGLEFULLSCREEN, L"Toggle full screen", 35, iY, 125, 22 ); g_HUD.AddButton( IDC_TOGGLEREF, L"Toggle REF (F3)", 35, iY += 24, 125, 22 ); g_HUD.AddButton( IDC_CHANGEDEVICE, L"Change device (F2)", 35, iY += 24, 125, 22, VK_F2 ); g_SampleUI.SetCallback( OnGUIEvent ); iY = 10; g_SampleUI.AddButton( IDC_CHANGE_SCENE, L"Change Scene", 35, iY += 24, 125, 22, 'P' ); g_SampleUI.AddButton( IDC_CHANGE_TECHNIQUE, L"Change Technique", 35, iY += 24, 125, 22, 'N' ); g_SampleUI.AddRadioButton( IDC_SHOW_NORMAL, 1, L"Show Normal", 35, iY += 24, 125, 22, true ); g_SampleUI.AddRadioButton( IDC_SHOW_BLUR, 1, L"Show Blur Factor", 35, iY += 24, 125, 22 ); g_SampleUI.AddRadioButton( IDC_SHOW_UNBLURRED, 1, L"Show Unblurred", 35, iY += 24, 125, 22 ); iY += 24; WCHAR sz[100]; swprintf_s( sz, 100, L"Focal Distance: %0.2f", -g_vFocalPlane.w ); sz[99] = 0; g_SampleUI.AddStatic( IDC_CHANGE_FOCAL_STATIC, sz, 35, iY += 24, 125, 22 ); g_SampleUI.AddSlider( IDC_CHANGE_FOCAL, 50, iY += 24, 100, 22, 0, 100, ( int )( -g_vFocalPlane.w * 10.0f ) ); iY += 24; swprintf_s( sz, 100, L"Blur Factor: %0.2f", g_fBlurConst ); sz[99] = 0; g_SampleUI.AddStatic( IDC_CHANGE_BLUR_STATIC, sz, 35, iY += 24, 125, 22 ); g_SampleUI.AddSlider( IDC_CHANGE_BLUR, 50, iY += 24, 100, 22, 0, 100, ( int )( g_fBlurConst * 10.0f ) ); } //-------------------------------------------------------------------------------------- // Rejects any D3D9 devices that aren't acceptable to the app by returning false //-------------------------------------------------------------------------------------- bool CALLBACK IsDeviceAcceptable( D3DCAPS9* pCaps, D3DFORMAT AdapterFormat, D3DFORMAT BackBufferFormat, bool bWindowed, void* pUserContext ) { // Skip backbuffer formats that don't support alpha blending IDirect3D9* pD3D = DXUTGetD3D9Object(); if( FAILED( pD3D->CheckDeviceFormat( pCaps->AdapterOrdinal, pCaps->DeviceType, AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING, D3DRTYPE_TEXTURE, BackBufferFormat ) ) ) return false; // Must support pixel shader 2.0 if( pCaps->PixelShaderVersion < D3DPS_VERSION( 2, 0 ) ) return false; return true; } //-------------------------------------------------------------------------------------- // Called right before creating a D3D9 or D3D10 device, allowing the app to modify the device settings as needed //-------------------------------------------------------------------------------------- bool CALLBACK ModifyDeviceSettings( DXUTDeviceSettings* pDeviceSettings, void* pUserContext ) { assert( DXUT_D3D9_DEVICE == pDeviceSettings->ver ); HRESULT hr; IDirect3D9* pD3D = DXUTGetD3D9Object(); D3DCAPS9 caps; V( pD3D->GetDeviceCaps( pDeviceSettings->d3d9.AdapterOrdinal, pDeviceSettings->d3d9.DeviceType, &caps ) ); // If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW // then switch to SWVP. if( ( caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT ) == 0 || caps.VertexShaderVersion < D3DVS_VERSION( 1, 1 ) ) { pDeviceSettings->d3d9.BehaviorFlags = D3DCREATE_SOFTWARE_VERTEXPROCESSING; } // Debugging vertex shaders requires either REF or software vertex processing // and debugging pixel shaders requires REF. #ifdef DEBUG_VS if( pDeviceSettings->d3d9.DeviceType != D3DDEVTYPE_REF ) { pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_HARDWARE_VERTEXPROCESSING; pDeviceSettings->d3d9.BehaviorFlags &= ~D3DCREATE_PUREDEVICE; pDeviceSettings->d3d9.BehaviorFlags |= D3DCREATE_SOFTWARE_VERTEXPROCESSING; } #endif #ifdef DEBUG_PS pDeviceSettings->d3d9.DeviceType = D3DDEVTYPE_REF; #endif // For the first device created if its a REF device, optionally display a warning dialog box static bool s_bFirstTime = true; if( s_bFirstTime ) { s_bFirstTime = false; if( pDeviceSettings->d3d9.DeviceType == D3DDEVTYPE_REF ) DXUTDisplaySwitchingToREFWarning( pDeviceSettings->ver ); } return true; } //-------------------------------------------------------------------------------------- // Create any D3D9 resources that will live through a device reset (D3DPOOL_MANAGED) // and aren't tied to the back buffer size //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnCreateDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { WCHAR str[MAX_PATH]; HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9CreateDevice( pd3dDevice ) ); V_RETURN( g_SettingsDlg.OnD3D9CreateDevice( pd3dDevice ) ); // Initialize the font V_RETURN( D3DXCreateFont( pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Arial", &g_pFont ) ); // Load the meshs V_RETURN( LoadMesh( pd3dDevice, TEXT( "tiger\\tiger.x" ), &g_pScene1Mesh ) ); V_RETURN( LoadMesh( pd3dDevice, TEXT( "misc\\sphere.x" ), &g_pScene2Mesh ) ); // Load the mesh textures V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"tiger\\tiger.bmp" ) ); V_RETURN( D3DXCreateTextureFromFile( pd3dDevice, str, &g_pScene1MeshTexture ) ); V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"earth\\earth.bmp" ) ); V_RETURN( D3DXCreateTextureFromFile( pd3dDevice, str, &g_pScene2MeshTexture ) ); DWORD dwShaderFlags = D3DXFX_NOT_CLONEABLE; #if defined( DEBUG ) || defined( _DEBUG ) dwShaderFlags |= D3DXSHADER_DEBUG; #endif #ifdef DEBUG_VS dwShaderFlags |= D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT; #endif #ifdef DEBUG_PS dwShaderFlags |= D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT; #endif V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, L"DepthOfField.fx" ) ); V_RETURN( D3DXCreateEffectFromFile( pd3dDevice, str, NULL, NULL, dwShaderFlags, NULL, &g_pEffect, NULL ) ); return S_OK; } //-------------------------------------------------------------------------------------- // This function loads the mesh and ensures the mesh has normals; it also optimizes the // mesh for the graphics card's vertex cache, which improves performance by organizing // the internal triangle list for less cache misses. //-------------------------------------------------------------------------------------- HRESULT LoadMesh( IDirect3DDevice9* pd3dDevice, WCHAR* strFileName, ID3DXMesh** ppMesh ) { ID3DXMesh* pMesh = NULL; WCHAR str[MAX_PATH]; HRESULT hr; // Load the mesh with D3DX and get back a ID3DXMesh*. For this // sample we'll ignore the X file's embedded materials since we know // exactly the model we're loading. See the mesh samples such as // "OptimizedMesh" for a more generic mesh loading example. V_RETURN( DXUTFindDXSDKMediaFileCch( str, MAX_PATH, strFileName ) ); V_RETURN( D3DXLoadMeshFromX( str, D3DXMESH_MANAGED, pd3dDevice, NULL, NULL, NULL, NULL, &pMesh ) ); DWORD* rgdwAdjacency = NULL; // Make sure there are normals which are required for lighting if( !( pMesh->GetFVF() & D3DFVF_NORMAL ) ) { ID3DXMesh* pTempMesh; V( pMesh->CloneMeshFVF( pMesh->GetOptions(), pMesh->GetFVF() | D3DFVF_NORMAL, pd3dDevice, &pTempMesh ) ); V( D3DXComputeNormals( pTempMesh, NULL ) ); SAFE_RELEASE( pMesh ); pMesh = pTempMesh; } // Optimize the mesh for this graphics card's vertex cache // so when rendering the mesh's triangle list the vertices will // cache hit more often so it won't have to re-execute the vertex shader // on those vertices so it will improve perf. rgdwAdjacency = new DWORD[pMesh->GetNumFaces() * 3]; if( rgdwAdjacency == NULL ) return E_OUTOFMEMORY; V( pMesh->GenerateAdjacency( 1e-6f, rgdwAdjacency ) ); V( pMesh->OptimizeInplace( D3DXMESHOPT_VERTEXCACHE, rgdwAdjacency, NULL, NULL, NULL ) ); delete []rgdwAdjacency; *ppMesh = pMesh; return S_OK; } //-------------------------------------------------------------------------------------- // Create any D3D9 resources that won't live through a device reset (D3DPOOL_DEFAULT) // or that are tied to the back buffer size //-------------------------------------------------------------------------------------- HRESULT CALLBACK OnResetDevice( IDirect3DDevice9* pd3dDevice, const D3DSURFACE_DESC* pBackBufferSurfaceDesc, void* pUserContext ) { HRESULT hr; V_RETURN( g_DialogResourceManager.OnD3D9ResetDevice() ); V_RETURN( g_SettingsDlg.OnD3D9ResetDevice() ); if( g_pFont ) V_RETURN( g_pFont->OnResetDevice() ); if( g_pEffect ) V_RETURN( g_pEffect->OnResetDevice() ); // Setup the camera with view & projection matrix D3DXVECTOR3 vecEye( 1.3f, 1.1f, -3.3f ); D3DXVECTOR3 vecAt ( 0.75f, 0.9f, -2.5f ); g_Camera.SetViewParams( &vecEye, &vecAt ); float fAspectRatio = pBackBufferSurfaceDesc->Width / ( FLOAT )pBackBufferSurfaceDesc->Height; g_Camera.SetProjParams( D3DXToRadian( 60.0f ), fAspectRatio, 0.5f, 100.0f ); pd3dDevice->GetViewport( &g_ViewportFB ); // Backbuffer viewport is identical to frontbuffer, except starting at 0, 0 g_ViewportOffscreen = g_ViewportFB; g_ViewportOffscreen.X = 0; g_ViewportOffscreen.Y = 0; // Create fullscreen renders target texture hr = D3DXCreateTexture( pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height, 1, D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_pFullScreenTexture ); if( FAILED( hr ) ) { // Fallback to a non-RT texture V_RETURN( D3DXCreateTexture( pd3dDevice, pBackBufferSurfaceDesc->Width, pBackBufferSurfaceDesc->Height, 1, 0, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &g_pFullScreenTexture ) ); } D3DSURFACE_DESC desc; g_pFullScreenTexture->GetSurfaceLevel( 0, &g_pFullScreenTextureSurf ); g_pFullScreenTextureSurf->GetDesc( &desc ); // Create a ID3DXRenderToSurface to help render to a texture on cards // that don't support render targets V_RETURN( D3DXCreateRenderToSurface( pd3dDevice, desc.Width, desc.Height, desc.Format, TRUE, D3DFMT_D16, &g_pRenderToSurface ) ); // clear the surface alpha to 0 so that it does not bleed into a "blurry" background // this is possible because of the avoidance of blurring in a non-blurred texel if( SUCCEEDED( g_pRenderToSurface->BeginScene( g_pFullScreenTextureSurf, NULL ) ) ) { pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0x00, 1.0f, 0 ); g_pRenderToSurface->EndScene( 0 ); } D3DXCOLOR colorWhite( 1.0f, 1.0f, 1.0f, 1.0f ); D3DXCOLOR colorBlack( 0.0f, 0.0f, 0.0f, 1.0f ); D3DXCOLOR colorAmbient( 0.25f, 0.25f, 0.25f, 1.0f ); // Get D3DXHANDLEs to the parameters/techniques that are set every frame so // D3DX doesn't spend time doing string compares. Doing this likely won't affect // the perf of this simple sample but it should be done in complex engine. g_hFocalPlane = g_pEffect->GetParameterByName( NULL, "vFocalPlane" ); g_hWorld = g_pEffect->GetParameterByName( NULL, "mWorld" ); g_hWorldView = g_pEffect->GetParameterByName( NULL, "mWorldView" ); g_hWorldViewProjection = g_pEffect->GetParameterByName( NULL, "mWorldViewProjection" ); g_hMeshTexture = g_pEffect->GetParameterByName( NULL, "MeshTexture" ); g_hTechWorldWithBlurFactor = g_pEffect->GetTechniqueByName( "WorldWithBlurFactor" ); g_hTechShowBlurFactor = g_pEffect->GetTechniqueByName( "ShowBlurFactor" ); g_hTechShowUnmodified = g_pEffect->GetTechniqueByName( "ShowUnmodified" ); for( int i = 0; i < g_TechniqueCount; i++ ) g_hTech[i] = g_pEffect->GetTechniqueByName( g_TechniqueNames[i] ); // Set the vars in the effect that doesn't change each frame V_RETURN( g_pEffect->SetVector( "MaterialAmbientColor", ( D3DXVECTOR4* )&colorAmbient ) ); V_RETURN( g_pEffect->SetVector( "MaterialDiffuseColor", ( D3DXVECTOR4* )&colorWhite ) ); V_RETURN( g_pEffect->SetTexture( "RenderTargetTexture", g_pFullScreenTexture ) ); // Check if the current technique is valid for the new device/settings // Start from the current technique, increment until we find one we can use. DWORD OriginalTechnique = g_TechniqueIndex; do { D3DXHANDLE hTech = g_pEffect->GetTechniqueByName( g_TechniqueNames[g_TechniqueIndex] ); if( SUCCEEDED( g_pEffect->ValidateTechnique( hTech ) ) ) break; g_TechniqueIndex++; if( g_TechniqueIndex == g_TechniqueCount ) g_TechniqueIndex = 0; } while( OriginalTechnique != g_TechniqueIndex ); V_RETURN( UpdateTechniqueSpecificVariables( pBackBufferSurfaceDesc ) ); g_HUD.SetLocation( pBackBufferSurfaceDesc->Width - 170, 0 ); g_HUD.SetSize( 170, 170 ); g_SampleUI.SetLocation( pBackBufferSurfaceDesc->Width - 170, pBackBufferSurfaceDesc->Height - 300 ); g_SampleUI.SetSize( 170, 250 ); return S_OK; } //-------------------------------------------------------------------------------------- // Certain parameters need to be specified for specific techniques //-------------------------------------------------------------------------------------- HRESULT UpdateTechniqueSpecificVariables( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ) { LPCSTR strInputArrayName, strOutputArrayName; int nNumKernelEntries; HRESULT hr; D3DXHANDLE hAnnotation; // Create the post-process quad and set the texcoords based on the blur factor SetupQuad( pBackBufferSurfaceDesc ); // Get the handle to the current technique D3DXHANDLE hTech = g_pEffect->GetTechniqueByName( g_TechniqueNames[g_TechniqueIndex] ); if( hTech == NULL ) return S_FALSE; // This will happen if the technique doesn't have this annotation // Get the value of the annotation int named "NumKernelEntries" inside the technique hAnnotation = g_pEffect->GetAnnotationByName( hTech, "NumKernelEntries" ); if( hAnnotation == NULL ) return S_FALSE; // This will happen if the technique doesn't have this annotation V_RETURN( g_pEffect->GetInt( hAnnotation, &nNumKernelEntries ) ); // Get the value of the annotation string named "KernelInputArray" inside the technique hAnnotation = g_pEffect->GetAnnotationByName( hTech, "KernelInputArray" ); if( hAnnotation == NULL ) return S_FALSE; // This will happen if the technique doesn't have this annotation V_RETURN( g_pEffect->GetString( hAnnotation, &strInputArrayName ) ); // Get the value of the annotation string named "KernelOutputArray" inside the technique hAnnotation = g_pEffect->GetAnnotationByName( hTech, "KernelOutputArray" ); if( hAnnotation == NULL ) return S_FALSE; // This will happen if the technique doesn't have this annotation if( FAILED( hr = g_pEffect->GetString( hAnnotation, &strOutputArrayName ) ) ) return hr; // Create a array to store the input array D3DXVECTOR2* aKernel = new D3DXVECTOR2[nNumKernelEntries]; if( aKernel == NULL ) return E_OUTOFMEMORY; // Get the input array V_RETURN( g_pEffect->GetValue( strInputArrayName, aKernel, sizeof( D3DXVECTOR2 ) * nNumKernelEntries ) ); // Get the size of the texture D3DSURFACE_DESC desc; g_pFullScreenTextureSurf->GetDesc( &desc ); // Calculate the scale factor to convert the input array to screen space FLOAT fWidthMod = g_fBlurConst / ( FLOAT )desc.Width; FLOAT fHeightMod = g_fBlurConst / ( FLOAT )desc.Height; // Scale the effect's kernel from pixel space to tex coord space // In pixel space 1 unit = one pixel and in tex coord 1 unit = width/height of texture for( int iEntry = 0; iEntry < nNumKernelEntries; iEntry++ ) { aKernel[iEntry].x *= fWidthMod; aKernel[iEntry].y *= fHeightMod; } // Pass the updated array values to the effect file V_RETURN( g_pEffect->SetValue( strOutputArrayName, aKernel, sizeof( D3DXVECTOR2 ) * nNumKernelEntries ) ); SAFE_DELETE_ARRAY( aKernel ); return S_OK; } //-------------------------------------------------------------------------------------- // Sets up a quad to render the fullscreen render target to the backbuffer // so it can run a fullscreen pixel shader pass that blurs based // on the depth of the objects. It set the texcoords based on the blur factor //-------------------------------------------------------------------------------------- void SetupQuad( const D3DSURFACE_DESC* pBackBufferSurfaceDesc ) { D3DSURFACE_DESC desc; g_pFullScreenTextureSurf->GetDesc( &desc ); FLOAT fWidth5 = ( FLOAT )pBackBufferSurfaceDesc->Width - 0.5f; FLOAT fHeight5 = ( FLOAT )pBackBufferSurfaceDesc->Height - 0.5f; FLOAT fHalf = g_fBlurConst; FLOAT fOffOne = fHalf * 0.5f; FLOAT fOffTwo = fOffOne * sqrtf( 3.0f ); FLOAT fTexWidth1 = ( FLOAT )pBackBufferSurfaceDesc->Width / ( FLOAT )desc.Width; FLOAT fTexHeight1 = ( FLOAT )pBackBufferSurfaceDesc->Height / ( FLOAT )desc.Height; FLOAT fWidthMod = 1.0f / ( FLOAT )desc.Width; FLOAT fHeightMod = 1.0f / ( FLOAT )desc.Height; // Create vertex buffer. // g_Vertex[0].tex1 == full texture coverage // g_Vertex[0].tex2 == full texture coverage, but shifted y by -fHalf*fHeightMod // g_Vertex[0].tex3 == full texture coverage, but shifted x by -fOffTwo*fWidthMod & y by -fOffOne*fHeightMod // g_Vertex[0].tex4 == full texture coverage, but shifted x by +fOffTwo*fWidthMod & y by -fOffOne*fHeightMod // g_Vertex[0].tex5 == full texture coverage, but shifted x by -fOffTwo*fWidthMod & y by +fOffOne*fHeightMod // g_Vertex[0].tex6 == full texture coverage, but shifted x by +fOffTwo*fWidthMod & y by +fOffOne*fHeightMod g_Vertex[0].pos = D3DXVECTOR4( fWidth5, -0.5f, 0.0f, 1.0f ); g_Vertex[0].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f ); g_Vertex[0].tex1 = D3DXVECTOR2( fTexWidth1, 0.0f ); g_Vertex[0].tex2 = D3DXVECTOR2( fTexWidth1, 0.0f - fHalf * fHeightMod ); g_Vertex[0].tex3 = D3DXVECTOR2( fTexWidth1 - fOffTwo * fWidthMod, 0.0f - fOffOne * fHeightMod ); g_Vertex[0].tex4 = D3DXVECTOR2( fTexWidth1 + fOffTwo * fWidthMod, 0.0f - fOffOne * fHeightMod ); g_Vertex[0].tex5 = D3DXVECTOR2( fTexWidth1 - fOffTwo * fWidthMod, 0.0f + fOffOne * fHeightMod ); g_Vertex[0].tex6 = D3DXVECTOR2( fTexWidth1 + fOffTwo * fWidthMod, 0.0f + fOffOne * fHeightMod ); g_Vertex[1].pos = D3DXVECTOR4( fWidth5, fHeight5, 0.0f, 1.0f ); g_Vertex[1].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f ); g_Vertex[1].tex1 = D3DXVECTOR2( fTexWidth1, fTexHeight1 ); g_Vertex[1].tex2 = D3DXVECTOR2( fTexWidth1, fTexHeight1 - fHalf * fHeightMod ); g_Vertex[1].tex3 = D3DXVECTOR2( fTexWidth1 - fOffTwo * fWidthMod, fTexHeight1 - fOffOne * fHeightMod ); g_Vertex[1].tex4 = D3DXVECTOR2( fTexWidth1 + fOffTwo * fWidthMod, fTexHeight1 - fOffOne * fHeightMod ); g_Vertex[1].tex5 = D3DXVECTOR2( fTexWidth1 - fOffTwo * fWidthMod, fTexHeight1 + fOffOne * fHeightMod ); g_Vertex[1].tex6 = D3DXVECTOR2( fTexWidth1 + fOffTwo * fWidthMod, fTexHeight1 + fOffOne * fHeightMod ); g_Vertex[2].pos = D3DXVECTOR4( -0.5f, -0.5f, 0.0f, 1.0f ); g_Vertex[2].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f ); g_Vertex[2].tex1 = D3DXVECTOR2( 0.0f, 0.0f ); g_Vertex[2].tex2 = D3DXVECTOR2( 0.0f, 0.0f - fHalf * fHeightMod ); g_Vertex[2].tex3 = D3DXVECTOR2( 0.0f - fOffTwo * fWidthMod, 0.0f - fOffOne * fHeightMod ); g_Vertex[2].tex4 = D3DXVECTOR2( 0.0f + fOffTwo * fWidthMod, 0.0f - fOffOne * fHeightMod ); g_Vertex[2].tex5 = D3DXVECTOR2( 0.0f - fOffTwo * fWidthMod, 0.0f + fOffOne * fHeightMod ); g_Vertex[2].tex6 = D3DXVECTOR2( 0.0f + fOffTwo * fWidthMod, 0.0f + fOffOne * fHeightMod ); g_Vertex[3].pos = D3DXVECTOR4( -0.5f, fHeight5, 0.0f, 1.0f ); g_Vertex[3].clr = D3DXCOLOR( 0.5f, 0.5f, 0.5f, 0.66666f ); g_Vertex[3].tex1 = D3DXVECTOR2( 0.0f, fTexHeight1 ); g_Vertex[3].tex2 = D3DXVECTOR2( 0.0f, fTexHeight1 - fHalf * fHeightMod ); g_Vertex[3].tex3 = D3DXVECTOR2( 0.0f - fOffTwo * fWidthMod, fTexHeight1 - fOffOne * fHeightMod ); g_Vertex[3].tex4 = D3DXVECTOR2( 0.0f + fOffTwo * fWidthMod, fTexHeight1 - fOffOne * fHeightMod ); g_Vertex[3].tex5 = D3DXVECTOR2( 0.0f + fOffTwo * fWidthMod, fTexHeight1 + fOffOne * fHeightMod ); g_Vertex[3].tex6 = D3DXVECTOR2( 0.0f - fOffTwo * fWidthMod, fTexHeight1 + fOffOne * fHeightMod ); } //-------------------------------------------------------------------------------------- // Handle updates to the scene. This is called regardless of which D3D API is used //-------------------------------------------------------------------------------------- void CALLBACK OnFrameMove( double fTime, float fElapsedTime, void* pUserContext ) { // Update the camera's position based on user input g_Camera.FrameMove( fElapsedTime ); } //-------------------------------------------------------------------------------------- // Render the scene using the D3D9 device //-------------------------------------------------------------------------------------- void CALLBACK OnFrameRender( IDirect3DDevice9* pd3dDevice, double fTime, float fElapsedTime, void* pUserContext ) { // If the settings dialog is being shown, then // render it instead of rendering the app's scene if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.OnRender( fElapsedTime ); return; } HRESULT hr; UINT iPass, cPasses; // First render the world on the rendertarget g_pFullScreenTexture. if( SUCCEEDED( g_pRenderToSurface->BeginScene( g_pFullScreenTextureSurf, &g_ViewportOffscreen ) ) ) { V( pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, g_dwBackgroundColor, 1.0f, 0 ) ); // Get the view & projection matrix from camera D3DXMATRIXA16 matWorld; D3DXMATRIXA16 matView = *g_Camera.GetViewMatrix(); D3DXMATRIXA16 matProj = *g_Camera.GetProjMatrix(); D3DXMATRIXA16 matViewProj = matView * matProj; // Update focal plane g_pEffect->SetVector( g_hFocalPlane, &g_vFocalPlane ); // Set world render technique V( g_pEffect->SetTechnique( g_hTechWorldWithBlurFactor ) ); // Set the mesh texture LPD3DXMESH pSceneMesh; int nNumObjectsInScene; if( g_nCurrentScene == 1 ) { V( g_pEffect->SetTexture( g_hMeshTexture, g_pScene1MeshTexture ) ); pSceneMesh = g_pScene1Mesh; nNumObjectsInScene = 25; } else { V( g_pEffect->SetTexture( g_hMeshTexture, g_pScene2MeshTexture ) ); pSceneMesh = g_pScene2Mesh; nNumObjectsInScene = 3; } static const D3DXVECTOR3 mScene2WorldPos[3] = { D3DXVECTOR3( -0.5f, -0.5f, -0.5f ), D3DXVECTOR3( 1.0f, 1.0f, 2.0f ), D3DXVECTOR3( 3.0f, 3.0f, 5.0f ) }; for( int iObject = 0; iObject < nNumObjectsInScene; iObject++ ) { // setup the world matrix for the current world if( g_nCurrentScene == 1 ) { D3DXMatrixTranslation( &matWorld, -( iObject % 5 ) * 1.0f, 0.0f, ( iObject / 5 ) * 3.0f ); } else { D3DXMATRIXA16 matRot, matPos; D3DXMatrixRotationY( &matRot, ( float )fTime * 0.66666f ); D3DXMatrixTranslation( &matPos, mScene2WorldPos[iObject].x, mScene2WorldPos[iObject].y, mScene2WorldPos[iObject].z ); matWorld = matRot * matPos; } // Update effect vars D3DXMATRIXA16 matWorldViewProj = matWorld * matViewProj; D3DXMATRIXA16 matWorldView = matWorld * matView; V( g_pEffect->SetMatrix( g_hWorld, &matWorld ) ); V( g_pEffect->SetMatrix( g_hWorldView, &matWorldView ) ); V( g_pEffect->SetMatrix( g_hWorldViewProjection, &matWorldViewProj ) ); // Draw the mesh on the rendertarget V( g_pEffect->Begin( &cPasses, 0 ) ); for( iPass = 0; iPass < cPasses; iPass++ ) { V( g_pEffect->BeginPass( iPass ) ); V( pSceneMesh->DrawSubset( 0 ) ); V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); } V( g_pRenderToSurface->EndScene( 0 ) ); } // Clear the backbuffer V( pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET, 0x00000000, 1.0f, 0L ) ); // Begin the scene, rendering to the backbuffer if( SUCCEEDED( pd3dDevice->BeginScene() ) ) { pd3dDevice->SetViewport( &g_ViewportFB ); // Set the post process technique switch( g_nShowMode ) { case 0: V( g_pEffect->SetTechnique( g_hTech[g_TechniqueIndex] ) ); break; case 1: V( g_pEffect->SetTechnique( g_hTechShowBlurFactor ) ); break; case 2: V( g_pEffect->SetTechnique( g_hTechShowUnmodified ) ); break; } // Render the fullscreen quad on to the backbuffer V( g_pEffect->Begin( &cPasses, 0 ) ); for( iPass = 0; iPass < cPasses; iPass++ ) { V( g_pEffect->BeginPass( iPass ) ); V( pd3dDevice->SetFVF( VERTEX::FVF ) ); V( pd3dDevice->DrawPrimitiveUP( D3DPT_TRIANGLESTRIP, 2, g_Vertex, sizeof( VERTEX ) ) ); V( g_pEffect->EndPass() ); } V( g_pEffect->End() ); V( g_HUD.OnRender( fElapsedTime ) ); V( g_SampleUI.OnRender( fElapsedTime ) ); // Render the text RenderText(); // End the scene. pd3dDevice->EndScene(); } } //-------------------------------------------------------------------------------------- // Render the help and statistics text. This function uses the ID3DXFont interface for // efficient text rendering. //-------------------------------------------------------------------------------------- void RenderText() { CDXUTTextHelper txtHelper( g_pFont, g_pTextSprite, 15 ); // Output statistics txtHelper.Begin(); txtHelper.SetInsertionPos( 5, 5 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( DXUTGetFrameStats( DXUTIsVsyncEnabled() ) ); txtHelper.DrawTextLine( DXUTGetDeviceStats() ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); switch( g_nShowMode ) { case 0: txtHelper.DrawFormattedTextLine( L"Technique: %S", g_TechniqueNames[g_TechniqueIndex] ); break; case 1: txtHelper.DrawTextLine( L"Technique: ShowBlurFactor" ); break; case 2: txtHelper.DrawTextLine( L"Technique: ShowUnmodified" ); break; } txtHelper.DrawFormattedTextLine( L"Focal Plane: (%0.1f,%0.1f,%0.1f,%0.1f)", g_vFocalPlane.x, g_vFocalPlane.y, g_vFocalPlane.z, g_vFocalPlane.w ); // Draw help if( g_bShowHelp ) { const D3DSURFACE_DESC* pd3dsdBackBuffer = DXUTGetD3D9BackBufferSurfaceDesc(); txtHelper.SetInsertionPos( 2, pd3dsdBackBuffer->Height - 15 * 6 ); txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 0.75f, 0.0f, 1.0f ) ); txtHelper.DrawTextLine( L"Controls (F1 to hide):" ); txtHelper.SetInsertionPos( 20, pd3dsdBackBuffer->Height - 15 * 5 ); txtHelper.DrawTextLine( L"Look: Left drag mouse\n" L"Move: A,W,S,D or Arrow Keys\n" L"Move up/down: Q,E or PgUp,PgDn\n" L"Reset camera: Home\n" ); } else { txtHelper.SetForegroundColor( D3DXCOLOR( 1.0f, 1.0f, 1.0f, 1.0f ) ); txtHelper.DrawTextLine( L"Press F1 for help" ); } txtHelper.End(); } //-------------------------------------------------------------------------------------- // Handle messages to the application //-------------------------------------------------------------------------------------- LRESULT CALLBACK MsgProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam, bool* pbNoFurtherProcessing, void* pUserContext ) { // Always allow dialog resource manager calls to handle global messages // so GUI state is updated correctly *pbNoFurtherProcessing = g_DialogResourceManager.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; if( g_SettingsDlg.IsActive() ) { g_SettingsDlg.MsgProc( hWnd, uMsg, wParam, lParam ); return 0; } // Give the dialogs a chance to handle the message first *pbNoFurtherProcessing = g_HUD.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; *pbNoFurtherProcessing = g_SampleUI.MsgProc( hWnd, uMsg, wParam, lParam ); if( *pbNoFurtherProcessing ) return 0; // Pass all remaining windows messages to camera so it can respond to user input g_Camera.HandleMessages( hWnd, uMsg, wParam, lParam ); return 0; } //-------------------------------------------------------------------------------------- // Handle key presses //-------------------------------------------------------------------------------------- void CALLBACK KeyboardProc( UINT nChar, bool bKeyDown, bool bAltDown, void* pUserContext ) { if( bKeyDown ) { switch( nChar ) { case VK_F1: g_bShowHelp = !g_bShowHelp; break; } } } //-------------------------------------------------------------------------------------- // Handles the GUI events //-------------------------------------------------------------------------------------- void CALLBACK OnGUIEvent( UINT nEvent, int nControlID, CDXUTControl* pControl, void* pUserContext ) { switch( nControlID ) { case IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen(); break; case IDC_TOGGLEREF: DXUTToggleREF(); break; case IDC_CHANGEDEVICE: g_SettingsDlg.SetActive( !g_SettingsDlg.IsActive() ); break; case IDC_CHANGE_TECHNIQUE: { DWORD OriginalTechnique = g_TechniqueIndex; do { g_TechniqueIndex++; if( g_TechniqueIndex == g_TechniqueCount ) { g_TechniqueIndex = 0; } D3DXHANDLE hTech = g_pEffect->GetTechniqueByName( g_TechniqueNames[g_TechniqueIndex] ); if( SUCCEEDED( g_pEffect->ValidateTechnique( hTech ) ) ) { break; } } while( OriginalTechnique != g_TechniqueIndex ); UpdateTechniqueSpecificVariables( DXUTGetD3D9BackBufferSurfaceDesc() ); break; } case IDC_CHANGE_SCENE: { g_nCurrentScene %= 2; g_nCurrentScene++; switch( g_nCurrentScene ) { case 1: { D3DXVECTOR3 vecEye( 0.75f, 0.8f, -2.3f ); D3DXVECTOR3 vecAt ( 0.2f, 0.75f, -1.5f ); g_Camera.SetViewParams( &vecEye, &vecAt ); break; } case 2: { D3DXVECTOR3 vecEye( 0.0f, 0.0f, -3.0f ); D3DXVECTOR3 vecAt ( 0.0f, 0.0f, 0.0f ); g_Camera.SetViewParams( &vecEye, &vecAt ); break; } } break; } case IDC_CHANGE_FOCAL: { WCHAR sz[100]; g_vFocalPlane.w = -g_SampleUI.GetSlider( IDC_CHANGE_FOCAL )->GetValue() / 10.0f; swprintf_s( sz, 100, L"Focal Distance: %0.2f", -g_vFocalPlane.w ); sz[99] = 0; g_SampleUI.GetStatic( IDC_CHANGE_FOCAL_STATIC )->SetText( sz ); UpdateTechniqueSpecificVariables( DXUTGetD3D9BackBufferSurfaceDesc() ); break; } case IDC_SHOW_NORMAL: g_nShowMode = 0; break; case IDC_SHOW_BLUR: g_nShowMode = 1; break; case IDC_SHOW_UNBLURRED: g_nShowMode = 2; break; case IDC_CHANGE_BLUR: { WCHAR sz[100]; g_fBlurConst = g_SampleUI.GetSlider( IDC_CHANGE_BLUR )->GetValue() / 10.0f; swprintf_s( sz, 100, L"Blur Factor: %0.2f", g_fBlurConst ); sz[99] = 0; g_SampleUI.GetStatic( IDC_CHANGE_BLUR_STATIC )->SetText( sz ); UpdateTechniqueSpecificVariables( DXUTGetD3D9BackBufferSurfaceDesc() ); break; } } } //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9ResetDevice callback //-------------------------------------------------------------------------------------- void CALLBACK OnLostDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9LostDevice(); g_SettingsDlg.OnD3D9LostDevice(); if( g_pFont ) g_pFont->OnLostDevice(); if( g_pEffect ) g_pEffect->OnLostDevice(); SAFE_RELEASE( g_pTextSprite ); SAFE_RELEASE( g_pFullScreenTextureSurf ); SAFE_RELEASE( g_pFullScreenTexture ); SAFE_RELEASE( g_pRenderToSurface ); } //-------------------------------------------------------------------------------------- // Release D3D9 resources created in the OnD3D9CreateDevice callback //-------------------------------------------------------------------------------------- void CALLBACK OnDestroyDevice( void* pUserContext ) { g_DialogResourceManager.OnD3D9DestroyDevice(); g_SettingsDlg.OnD3D9DestroyDevice(); SAFE_RELEASE( g_pEffect ); SAFE_RELEASE( g_pFont ); SAFE_RELEASE( g_pFullScreenTextureSurf ); SAFE_RELEASE( g_pFullScreenTexture ); SAFE_RELEASE( g_pRenderToSurface ); SAFE_RELEASE( g_pScene1Mesh ); SAFE_RELEASE( g_pScene1MeshTexture ); SAFE_RELEASE( g_pScene2Mesh ); SAFE_RELEASE( g_pScene2MeshTexture ); }
41.576369
119
0.59555
billionare
5dc45430aeee85d60feef3c2ae4f1933957f90dc
9,584
hh
C++
source/include/Utilities.hh
leenderthayen/CRADLE
8b7979a201c6d95abbc00cf44159b8fa577a17f5
[ "MIT" ]
null
null
null
source/include/Utilities.hh
leenderthayen/CRADLE
8b7979a201c6d95abbc00cf44159b8fa577a17f5
[ "MIT" ]
3
2019-04-22T13:07:52.000Z
2021-04-13T04:49:09.000Z
source/include/Utilities.hh
leenderthayen/CRADLE
8b7979a201c6d95abbc00cf44159b8fa577a17f5
[ "MIT" ]
1
2021-06-13T19:03:55.000Z
2021-06-13T19:03:55.000Z
#ifndef UTILITIES #define UTILITIES #include <math.h> #include <stdlib.h> #include <string> #include <vector> #include <fstream> #include <iostream> #include <algorithm> #include <map> #include <boost/numeric/ublas/vector.hpp> #include <boost/numeric/ublas/symmetric.hpp> #include <boost/numeric/ublas/matrix.hpp> #include <boost/numeric/ublas/io.hpp> #include <boost/math/special_functions/gamma.hpp> #include <boost/math/special_functions/legendre.hpp> #include <complex> #include "gsl/gsl_sf_gamma.h" #include "gsl/gsl_sf_result.h" #include "gsl/gsl_complex_math.h" namespace utilities { using namespace boost::numeric::ublas; const double PI = 3.14159265359; const double C = 299792458;//m/s const double EMASSC2 = 510.9989461;//keV const double PMASSC2 = 938272.046;//keV const double NMASSC2 = 939565.4133;//keV const double ALPHAMASSC2 = 3727379.508;//keV const double FINESTRUCTURE = 0.0072973525664; const double E = 2.718281828459045; const double HBAR = 6.58211889e-16;//ev*s const double a_CORR = -1.0; const std::string atoms[] = {"H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt"}; inline vector<double> RandomDirection () { double z, phi; vector<double> v(3); z = rand() / (double)RAND_MAX * 2. - 1.; phi = rand() / (double)RAND_MAX * 2. * PI; v(0) = std::sqrt(1.-z*z)*std::cos(phi); v(1) = std::sqrt(1.-z*z)*std::sin(phi); v(2) = z; return v; }; inline double Random(double begin, double end) { return rand() / (double)RAND_MAX * (end - begin) + begin; }; inline double RandomFromDistribution(std::vector<std::vector<double> >& pd) { double begin = pd[0][0]; double end = pd[pd.size()-1][0]; double stepSize = pd[1][0] - pd[0][0]; double max = 0.; for (std::vector<std::vector<double> >::size_type i = 0; i != pd.size(); i++) { if (pd[i][1] > max) { max = pd[i][1]; } } double r = 0.; double q = 0.; do { r = rand() / (double)RAND_MAX; q = rand() / (double)RAND_MAX * max; } while (q > pd[r*pd.size()][1]); return r*(end - begin) + begin; } inline double GetSpeed(double energy, double massc2) { double gamma = energy/massc2 + 1.; return std::sqrt(1.-1./(gamma*gamma))*C; } inline double GetNorm(const vector<double>& v) { double sum = 0.; for (vector<double>::size_type i = 0; i != v.size(); i++) { sum+=v[i]*v[i]; } return std::sqrt(sum); } inline double FourDimDot(vector<double>& a, vector<double>& b) { //Mostly minus convention return a[0]*b[0]-(a[1]*b[1]+a[2]*b[2]+a[3]*b[3]); } inline double CalculateXiBetaDecay(double& cs, double& ct, double& cv, double& ca, double& mf, double& mgt) { return mf*mf*(2.*cs*cs+2.*cv*cv)+mgt*mgt*(2.*ct*ct+2.*ca*ca); } inline double CalculateBetaNeutrinoAsymmetry(double cs, double ct, double cv, double ca, double mf, double mgt) { return (mf*mf*(-2.*cs*cs+2.*cv*cv)+mgt*mgt/3.*(2.*ct*ct-2.*ca*ca))/CalculateXiBetaDecay(cs, ct, cv, ca, mf, mgt); } inline vector<double> NormaliseVector(const vector<double>& v) { vector<double> newV (v); double norm = GetNorm(v); if (norm != 0) { return newV/norm; } return v; } inline double LambdaKinematic(double x, double y, double z) { return x*x+y*y+z*z-2*x*y-2*y*z-2*x*z; } inline double PhaseSpace(double W, double W0) { return std::sqrt(W*W-1.)*W*std::pow(W0-W, 2.); } inline double SimpleFermiFunction(double Z, double v) { double nu = Z*FINESTRUCTURE/v*C; return 2.*PI*nu/(1.-std::pow(E, -2.*PI*nu)); } inline double FermiFunction(double Z, double W, double R) { double gamma = std::sqrt(1.-(FINESTRUCTURE*Z)*(FINESTRUCTURE*Z)); double p = std::sqrt(W*W-1); double first = 2*(gamma+1); //the second term will be incorporated in the fifth //double second = 1/pow(gsl_sf_gamma(2*gamma+1),2); double third = std::pow(2*p*R,2*(gamma-1)); double fourth = std::exp(M_PI*FINESTRUCTURE*Z*W/p); //the fifth is a bit tricky //we use the complex gamma function from GSL gsl_sf_result magn; gsl_sf_result phase; gsl_sf_lngamma_complex_e(gamma, FINESTRUCTURE*Z*W/p,&magn,&phase); //now we have what we want in magn.val //but we incorporate the second term here as well double fifth = std::exp(2*(magn.val-gsl_sf_lngamma(2*gamma+1))); return first*third*fourth*fifth; } inline double ApproximateRadius(double A) { return (1.15+1.8*std::pow(A, -2./3.)-1.2*std::pow(A, -4./3.))*EMASSC2*1000./HBAR/C*std::pow(A, 1./3.); } inline double GetSpectrumHeight(double Z, double A, double Q, double E, bool advancedFermi) { double W = E/EMASSC2+1.; double W0 = Q/EMASSC2+1.; double R = ApproximateRadius(A); if (advancedFermi) { return PhaseSpace(W, W0)*FermiFunction(Z, W, R); } else { return PhaseSpace(W, W0)*SimpleFermiFunction(Z, GetSpeed(E, EMASSC2)); } } inline std::vector<std::vector<double> >* GenerateBetaSpectrum(double Z, double A, double Q, bool advancedFermi) { std::vector<std::vector<double> >* dist = new std::vector<std::vector<double> >(); double stepSize = 1.0; double currentEnergy = stepSize; while(currentEnergy <= Q) { double s = GetSpectrumHeight(Z, A, Q, currentEnergy, advancedFermi); std::vector<double> pair; pair.push_back(currentEnergy); pair.push_back(s); dist->push_back(pair); currentEnergy+=stepSize; } return dist; } inline vector<double> CrossProduct(vector<double> first, vector<double> second) { vector<double> v (3); v(0) = first(1)*second(2) - first(2)*second(1); v(1) = first(2)*second(0) - first(0)*second(2); v(2) = first(0)*second(1) - first(1)*second(0); return v; } inline vector<double> RotateAroundVector(vector<double>& initial, vector<double>& axis, double angle) { vector<double> vect(3); double u = axis[0]; double v = axis[1]; double w = axis[2]; double x = initial[0]; double y = initial[1]; double z = initial[2]; double c = std::cos(angle); double s = std::sin(angle); vect(0) = u*(u*x+v*y+w*z)*(1.-c)+x*c+(-w*y+v*z)*s; vect(1) = v*(u*x+v*y+w*z)*(1.-c)+y*c+(w*x-u*z)*s; vect(2) = w*(u*x+v*y+w*z)*(1.-c)+z*c+(-v*x+u*y)*s; return vect; } inline vector<double> GetParticleDirection(vector<double>& dir2, std::vector<double>& A) { dir2 = NormaliseVector(dir2); std::vector<std::vector<double> > dist; double stepSize = PI/180; double currentAngle = 0.; while (currentAngle <= PI) { std::vector<double> pair; pair.push_back(currentAngle); double W = 0.; for (std::vector<double>::size_type i = 0; i != A.size(); i++) { W+=A[i]*boost::math::legendre_p(i, std::cos(currentAngle)); } pair.push_back(W); dist.push_back(pair); currentAngle+=stepSize; } double theta = 1.-RandomFromDistribution(dist)/PI; theta = std::acos(2*theta-1.); //std::cout << theta; vector<double> perp = CrossProduct(dir2, RandomDirection()); vector<double> dir = RotateAroundVector(dir2, perp, theta); return dir; } inline vector<double> GetParticleDirection(std::vector<vector<double> >& dirs, std::vector<std::vector<double> >& A) { vector<double> dir (3); //TODO return dir; } inline vector<double> LorentzBoost(vector<double>& velocity, vector<double>& v) { double speed = GetNorm(velocity); double beta = speed; double gamma = 1./std::sqrt(1.-std::pow(speed, 2.)); vector<double> dir = NormaliseVector(velocity); symmetric_matrix<double, upper> boost(4,4); boost(0, 0) = gamma; boost(0, 1) = -gamma*beta*dir[0]; boost(0, 2) = -gamma*beta*dir[1]; boost(0, 3) = -gamma*beta*dir[2]; boost(1, 1) = 1.+(gamma-1.)*dir[0]*dir[0]; boost(1, 2) = (gamma-1.)*dir[0]*dir[1]; boost(1, 3) = (gamma-1.)*dir[0]*dir[2]; boost(2, 2) = 1.+(gamma-1.)*dir[1]*dir[1]; boost(2, 3) = (gamma-1.)*dir[1]*dir[2]; boost(3, 3) = 1.+(gamma-1.)*dir[2]*dir[2]; return prod(boost, v); } inline double GetApproximateMass(int Z, int A) { double b = 15.5*A-16.8*std::pow(A, 2.0/3.0)- 0.72*Z*(Z-1)*std::pow(A, -1.0/3.0) - 23.*std::pow(A-2*Z, 2.)/A; if (A%2 == 0) { double asym = 34.*std::pow(A, -3.0/4.0); if (Z%2 == 0) { b+=asym; } else { b-=asym; } } return Z*PMASSC2+(A-Z)*NMASSC2-b; } inline std::vector<std::vector<double> > ReadDistribution(const char * filename) { std::ifstream distReader(filename, std::ifstream::in); if (!distReader.is_open()) { std::cout << "Error: Could not find file " << filename << std::endl; } std::vector<std::vector<double> > dist; double x, y; while (distReader >> x >> y) { std::vector<double> pair; pair.push_back(x); pair.push_back(y); dist.push_back(pair); } return dist; } } #endif
32.488136
671
0.591402
leenderthayen
5dc6384b2d429a210dd324dd305f6ad60449a278
2,894
hpp
C++
asteria/src/variable_hashset.hpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
asteria/src/variable_hashset.hpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
asteria/src/variable_hashset.hpp
MaskRay/asteria
56a9251f5bb80b92e5aff25eac145f8cd2495096
[ "BSD-3-Clause" ]
null
null
null
// This file is part of Asteria. // Copyleft 2018, LH_Mouse. All wrongs reserved. #ifndef ASTERIA_VARIABLE_HASHSET_HPP_ #define ASTERIA_VARIABLE_HASHSET_HPP_ #include "fwd.hpp" #include "variable.hpp" #include "rocket/refcounted_ptr.hpp" namespace Asteria { class Variable_hashset { private: rocket::refcounted_ptr<Variable> *m_data; Size m_nbkt; Size m_size; public: Variable_hashset() noexcept : m_data(nullptr), m_nbkt(0), m_size(0) { } ~Variable_hashset(); Variable_hashset(const Variable_hashset &) = delete; Variable_hashset & operator=(const Variable_hashset &) = delete; private: void do_rehash(Size res_arg); Diff do_find(const rocket::refcounted_ptr<Variable> &var) const noexcept; bool do_insert_unchecked(const rocket::refcounted_ptr<Variable> &var) noexcept; void do_erase_unchecked(Size tpos) noexcept; public: bool empty() const noexcept { return this->m_size == 0; } Size size() const noexcept { return this->m_size; } void clear() noexcept { const auto data = this->m_data; const auto nbkt = this->m_nbkt; for(Size i = 0; i != nbkt; ++i) { data[i] = nullptr; } this->m_size = 0; } template<typename FuncT> void for_each(FuncT &&func) const { const auto data = this->m_data; const auto nbkt = this->m_nbkt; for(Size i = 0; i != nbkt; ++i) { if(data[i]) { std::forward<FuncT>(func)(data[i]); } } } bool has(const rocket::refcounted_ptr<Variable> &var) const noexcept { const auto toff = this->do_find(var); if(toff < 0) { return false; } return true; } Size max_size() const noexcept { const auto max_nbkt = Size(-1) / 2 / sizeof(*(this->m_data)); return max_nbkt / 2; } Size capacity() const noexcept { const auto nbkt = this->m_nbkt; return nbkt / 2; } void reserve(Size res_arg) { if(res_arg <= this->capacity()) { return; } this->do_rehash(res_arg); } bool insert(const rocket::refcounted_ptr<Variable> &var) { this->reserve(this->size() + 1); return this->do_insert_unchecked(var); } bool erase(const rocket::refcounted_ptr<Variable> &var) noexcept { const auto toff = this->do_find(var); if(toff < 0) { return false; } this->do_erase_unchecked(static_cast<Size>(toff)); return true; } void swap(Variable_hashset &other) noexcept { std::swap(this->m_data, other.m_data); std::swap(this->m_nbkt, other.m_nbkt); std::swap(this->m_size, other.m_size); } }; } #endif
24.319328
83
0.575328
MaskRay
5dc7a5571a2d3a4d93038dfbb2d456e762d33a6e
1,117
hpp
C++
node.hpp
almogun9963/ex2.a
00b5bafca4e894785d9cf0d5298078ed9b6487b8
[ "MIT" ]
null
null
null
node.hpp
almogun9963/ex2.a
00b5bafca4e894785d9cf0d5298078ed9b6487b8
[ "MIT" ]
null
null
null
node.hpp
almogun9963/ex2.a
00b5bafca4e894785d9cf0d5298078ed9b6487b8
[ "MIT" ]
null
null
null
// // Created by Almog on 13/04/2020. // #pragma once #include <iostream> class node { std::string name; char gender; node* child; node* left; node* right; int level; public: std::string getName() { return this->name; } char getGender() { return this->gender; } void setChild(node* n) { this->child = n; } node* getChild() { return this->child; } node* getLeft() { return this->left; } node* getRight() { return this->right; } int getLevel() { return this->level; } void setLevel( int l) { this->level = l; } void setLeft(node* n) { this->left = n; } void setRight(node* n) { this->right = n; } void setGender(char g) { this->gender = g; } node(std::string name, int l = 0) { this->name = name; this->level = l; this->left = this->right = this->child = nullptr; } };
16.426471
58
0.444047
almogun9963
5dcc7d2b1a6bad1d9ddae3ce33ec2e5654d91b6b
7,572
cpp
C++
tests/matching.cpp
WolfgangVogl/compile-time-verbal-expressions
7169afac274c98a8afe66440d393d3a9a0a8f7c4
[ "Apache-2.0" ]
5
2019-11-14T21:01:56.000Z
2021-04-15T13:00:12.000Z
tests/matching.cpp
WolfgangVogl/compile-time-verbal-expressions
7169afac274c98a8afe66440d393d3a9a0a8f7c4
[ "Apache-2.0" ]
1
2021-01-27T10:26:13.000Z
2021-01-27T10:26:13.000Z
tests/matching.cpp
WolfgangVogl/compile-time-verbal-expressions
7169afac274c98a8afe66440d393d3a9a0a8f7c4
[ "Apache-2.0" ]
1
2021-01-26T11:38:51.000Z
2021-01-26T11:38:51.000Z
#include <ctve.hpp> #include <ctre.hpp> template <auto& input> constexpr auto create() { using tmp = typename ctll::parser<ctre::pcre, input, ctre::pcre_actions>:: template output<ctre::pcre_context<>>; static_assert(tmp(), "Regular Expression contains syntax error."); using re = decltype(front(typename tmp::output_type::stack_type())); return ctre::regular_expression(re()); } #define CTRE_CREATE(pattern) create<pattern>() using namespace std::string_view_literals; using namespace ctve; static_assert(CTRE_CREATE(digit).match("1"sv)); static_assert(!CTRE_CREATE(digit).match("12"sv)); static_assert(!CTRE_CREATE(digit).match("a"sv)); static inline constexpr auto digits = digit.one_or_more(); static_assert(!CTRE_CREATE(digits).match(""sv)); static_assert(CTRE_CREATE(digits).match("9"sv)); static_assert(CTRE_CREATE(digits).match("42"sv)); static inline constexpr auto findDot = find("."); static_assert(!CTRE_CREATE(findDot).match(""sv)); static_assert(CTRE_CREATE(findDot).match("."sv)); static_assert(!CTRE_CREATE(findDot).match("a"sv)); static inline constexpr auto maybeFoo = maybe("foo"); static_assert(CTRE_CREATE(maybeFoo).match(""sv)); static_assert(!CTRE_CREATE(maybeFoo).match("f"sv)); static_assert(CTRE_CREATE(maybeFoo).match("foo"sv)); static_assert(!CTRE_CREATE(maybeFoo).match("bar"sv)); static_assert(!CTRE_CREATE(maybeFoo).match("foobar"sv)); static inline constexpr auto maybe_f_dot_o = maybe("f.o"); static_assert(CTRE_CREATE(maybe_f_dot_o).match("f.o"sv)); static_assert(!CTRE_CREATE(maybe_f_dot_o).match("foo"sv)); static inline constexpr auto maybe_f_any_o = maybe(find('f') + any_char + then('o')); static_assert(CTRE_CREATE(maybe_f_any_o).match("f.o"sv)); static_assert(CTRE_CREATE(maybe_f_any_o).match("foo"sv)); static_assert(!CTRE_CREATE(maybe_f_any_o).match("f..o"sv)); static inline constexpr auto ctve_is_not_not_great = find("CTVE is ") + not_("not ") + maybe(word + whitespace) + then("great!"); static_assert(CTRE_CREATE(ctve_is_not_not_great).match("CTVE is great!"sv)); static_assert( !CTRE_CREATE(ctve_is_not_not_great).match("CTVE is not great!"sv)); static_assert( CTRE_CREATE(ctve_is_not_not_great).match("CTVE is very great!"sv)); static inline constexpr auto b_to_f = in(range{'b', 'f'}); static_assert(!CTRE_CREATE(b_to_f).match("a"sv)); static_assert(CTRE_CREATE(b_to_f).match("b"sv)); static_assert(!CTRE_CREATE(b_to_f).match("bc"sv)); static_assert(CTRE_CREATE(b_to_f).match("c"sv)); static_assert(CTRE_CREATE(b_to_f).match("f"sv)); static_assert(!CTRE_CREATE(b_to_f).match("g"sv)); static inline constexpr auto wordChar = in(word_char); static_assert(CTRE_CREATE(wordChar).match("a"sv)); static_assert(CTRE_CREATE(wordChar).match("Z"sv)); static_assert(CTRE_CREATE(wordChar).match("0"sv)); static_assert(CTRE_CREATE(wordChar).match("9"sv)); static inline constexpr auto hexadecimalNumber = maybe("0x") + in(digit, range{'a', 'f'}, range{'A', 'F'}).one_or_more(); static_assert(CTRE_CREATE(hexadecimalNumber).match("0x0"sv)); static_assert(CTRE_CREATE(hexadecimalNumber).match("0xff"sv)); static_assert(CTRE_CREATE(hexadecimalNumber).match("3B"sv)); static_assert(!CTRE_CREATE(hexadecimalNumber).match("0xggg"sv)); static inline constexpr auto nanOrHexadecimalNumber = "NaN" || hexadecimalNumber; static_assert(CTRE_CREATE(nanOrHexadecimalNumber).match("NaN"sv)); static_assert(!CTRE_CREATE(nanOrHexadecimalNumber).match("NaN0x0"sv)); static_assert(CTRE_CREATE(nanOrHexadecimalNumber).match("0x0"sv)); static_assert(CTRE_CREATE(nanOrHexadecimalNumber).match("0xff"sv)); static_assert(CTRE_CREATE(nanOrHexadecimalNumber).match("3B"sv)); static_assert(!CTRE_CREATE(nanOrHexadecimalNumber).match("0xggg"sv)); static inline constexpr auto captureName = "Hello " + capture(word) + maybe('!'); static_assert(CTRE_CREATE(captureName).match("Hello you!"sv).get<1>() == "you"sv); static inline constexpr auto zeroOrOneAnyChar = any_char.at_most(1); static_assert(CTRE_CREATE(zeroOrOneAnyChar).match(""sv)); static_assert(CTRE_CREATE(zeroOrOneAnyChar).match("."sv)); static_assert(CTRE_CREATE(zeroOrOneAnyChar).match("a"sv)); static_assert(!CTRE_CREATE(zeroOrOneAnyChar).match("ab"sv)); static inline constexpr auto threeToFiveAB = in('a', 'b').count(3, 5); static_assert(!CTRE_CREATE(threeToFiveAB).match(""sv)); static_assert(!CTRE_CREATE(threeToFiveAB).match("ab"sv)); static_assert(CTRE_CREATE(threeToFiveAB).match("aba"sv)); static_assert(CTRE_CREATE(threeToFiveAB).match("abab"sv)); static_assert(CTRE_CREATE(threeToFiveAB).match("ababb"sv)); static_assert(!CTRE_CREATE(threeToFiveAB).match("ababba"sv)); // would be bad, if the readme example fails unnoticed ;-) static constexpr auto urlPattern = "http" // + maybe('s') // + "://" // + maybe("www.") // + capture(something_not_in(' ', '/', ':')) // + maybe(':' + capture(digit.one_or_more())) // + maybe(capture('/' + anything_not_in(' '))); static constexpr auto testUrl = "https://github.com:443/mrpi/compile-time-verbal-expressions"sv; static_assert(CTRE_CREATE(urlPattern).match(testUrl)); static_assert(CTRE_CREATE(urlPattern).match(testUrl).get<1>() == "github.com"sv); static_assert(CTRE_CREATE(urlPattern).match(testUrl).get<2>() == "443"sv); static_assert(CTRE_CREATE(urlPattern).match(testUrl).get<3>() == "/mrpi/compile-time-verbal-expressions"sv); static constexpr auto cOrPosixUpper = in(posix::xdigit, 'x').one_or_more(); static_assert(!CTRE_CREATE(cOrPosixUpper).match("")); static_assert(CTRE_CREATE(cOrPosixUpper).match("a")); static_assert(CTRE_CREATE(cOrPosixUpper).match("9")); static_assert(CTRE_CREATE(cOrPosixUpper).match("A")); static_assert(CTRE_CREATE(cOrPosixUpper).match("AB")); static_assert(CTRE_CREATE(cOrPosixUpper).match("ABc")); static_assert(CTRE_CREATE(cOrPosixUpper).match("ABcx")); static_assert(!CTRE_CREATE(cOrPosixUpper).match("ABg")); static constexpr auto upperOrDigit = posix::upper || posix::digit; static_assert(CTRE_CREATE(upperOrDigit).match("A")); static_assert(!CTRE_CREATE(upperOrDigit).match("a")); static_assert(CTRE_CREATE(upperOrDigit).match("0")); static constexpr auto escaped = (not_in('\\', '"', ']') || "\\\\" || "\\\"" || "\\]").one_or_more(); static_assert(!CTRE_CREATE(escaped).match(R"(ab\c)")); static_assert(CTRE_CREATE(escaped).match(R"(ab\\c)")); static_assert(!CTRE_CREATE(escaped).match(R"(ab"c)")); static_assert(CTRE_CREATE(escaped).match(R"(ab\"c)")); static_assert(!CTRE_CREATE(escaped).match(R"(ab]c)")); static_assert(CTRE_CREATE(escaped).match(R"(ab\]c)")); constexpr auto uuid1 = "3b42ecd2-647d-42b1-9b0c-b0df0f859384"sv; constexpr auto notUuid1 = "3b42ecd2_647d_42b1_9b0c_b0df0f859384"sv; static constexpr auto hexDigit = in(digit, range{'a', 'f'}); static constexpr auto isUuid = hexDigit.count(8) + '-' + hexDigit.count(4) + '-' + hexDigit.count(4) + '-' + hexDigit.count(4) + '-' + hexDigit.count(12); template<auto& in> constexpr auto ctveShrinkToFit() -> ctve::pattern<in.size()> { return ctve::pattern{ctve::static_string<in.size()>{in.str}}; } static constexpr auto isUuidShort = ctveShrinkToFit<isUuid>(); static_assert(CTRE_CREATE(isUuid).match(uuid1)); static_assert(!CTRE_CREATE(isUuid).match(notUuid1)); static constexpr auto isLikeUuid = in(digit, range{'a', 'f'}, '-').count(36); static_assert(CTRE_CREATE(isLikeUuid).match(uuid1)); static_assert(!CTRE_CREATE(isLikeUuid).match(notUuid1));
44.280702
154
0.729398
WolfgangVogl
5dd0b5b3e8bf433437ab2408cea31f3ea9c634e1
156
cpp
C++
demo/main.cpp
SkatGame/Lab6
0ae71bcbd29a25baf14587f5b8c5e327fd6b9022
[ "MIT" ]
null
null
null
demo/main.cpp
SkatGame/Lab6
0ae71bcbd29a25baf14587f5b8c5e327fd6b9022
[ "MIT" ]
null
null
null
demo/main.cpp
SkatGame/Lab6
0ae71bcbd29a25baf14587f5b8c5e327fd6b9022
[ "MIT" ]
null
null
null
#include <header.hpp> int main(int argc, char *argv[]) { signal(SIGINT, Hasher::signal_catch); Hasher hasher(argc, argv); hasher.start(true); }
22.285714
41
0.660256
SkatGame
5dd2ff3a22c55f6cec97aa0ef4edf1bc8b5e34fa
4,131
hpp
C++
src/heattransfer/radial.hpp
kewin1983/transient-pipeline-flow
4ffe0b61d3d40d9bcb82a3743b2c2e403521835d
[ "MIT" ]
1
2021-03-26T03:30:07.000Z
2021-03-26T03:30:07.000Z
src/heattransfer/radial.hpp
kewin1983/transient-pipeline-flow
4ffe0b61d3d40d9bcb82a3743b2c2e403521835d
[ "MIT" ]
null
null
null
src/heattransfer/radial.hpp
kewin1983/transient-pipeline-flow
4ffe0b61d3d40d9bcb82a3743b2c2e403521835d
[ "MIT" ]
null
null
null
#pragma once #include <armadillo> #include "heattransfer/heattransferbase.hpp" #include "heattransfer/burialmedium.hpp" #include "heattransfer/ambientfluid.hpp" class Pipeline; class PipeWall; /*! * \brief Base class for heat transfer calculation with 1d radial models. * * This contains the description of the burial medium, burial depth, ambient * fluid etc., as well as the 1d radial discretization of the surroundings of * the pipeline (in m_width, m_conductivity, etc.). */ class RadialHeatTransfer : public HeatTransferBase { public: /*! * \brief Constructor that sets up the discretization of the pipe surroundings. * \param diameter Pipe inner diameter [m] * \param pipeWall PipeWall instance * \param burialDepth Distance from top of pipe to top of burial medium [m] * \param burialMedium BurialMedium instance * \param ambientFluid AmbientFluid instance */ RadialHeatTransfer( const double diameter, const PipeWall& pipeWall, const double burialDepth, const BurialMedium& burialMedium, const AmbientFluid& ambientFluid); /*! * \brief Calculate the outer film coefficient. Basically a wrapper around * utils::calcOuterWallFilmCoefficient(const double, const AmbientFluid&) * using the proper arguments. * * \return Outer film coefficient [W/(m2 K)] */ double calculateOuterFilmCoefficient() const; //! The number of discretization elements. virtual arma::uword size() const { return m_width.n_elem; } /*! * \brief Make instance of HeatTransferState from heat flux. Override. * * Makes HeatTransferState instance with the correct temperature property * for 1d radial heat transfer models. * * \param heatFlux Heat flux [W/m2] * \return HeatTransferState instance with temperature. */ virtual HeatTransferState makeState(const double heatFlux) const override { return HeatTransferState(heatFlux, arma::zeros<arma::vec>(size())); } /*! * \brief Make instance of HeatTransferState from heat flux. Override. * * Makes HeatTransferState instance with the correct temperature property * for 1d radial heat transfer models. Performs a linear interpolation * between gas temperature and ambient temperature. This could probably be * improved upon, since there is likely an analytical solution. * * \param heatFlux Heat flux [W/m2] * \param ambientTemperature Ambient temperature [K] * \param gasTemperature Gas temperature [K] * \return HeatTransferState instance with temperature. */ virtual HeatTransferState makeState( const double heatFlux, const double gasTemperature, const double ambientTemperature) const override { arma::vec shellTemperature = arma::linspace( gasTemperature, ambientTemperature, size()); return HeatTransferState(heatFlux, shellTemperature); } protected: double m_diameter; //!< Pipe inner diameter [m] double m_burialDepth; //!< Distance from top of pipe to top of burial medium [m] //! Description of the medium the pipeline is buried in (or on top //! of/suspended above depending on burial depth). BurialMedium m_burialMedium; //! Description of the fluid surrounding the pipeline. AmbientFluid m_ambientFluid; arma::vec m_width; //!< Width of each discretization shell [m] arma::vec m_conductivity; //!< Thermal conductivity of each discretization shell [W/(m K)] arma::vec m_density; //!< Density of each discretization shell [kg/m3] arma::vec m_heatCapacity; //!< Heat capacity of each discretization shell (\f$c_p\f$) [J/(kg K)] //! Bool that determines whether the discretization layers are due to burial //! in the burial medium or not. arma::uvec m_isBurialLayer; arma::vec m_crossSection; //!< Area/cross-section of each shell [m2] arma::vec m_ri; //!< Inner radius [m] arma::vec m_ro; //!< Outer radius [m] };
37.216216
100
0.686032
kewin1983
5dde3e340d4755eaa0f11aecbda1f2e86e103749
57,461
cpp
C++
src/io/dxf/RDxfExporter.cpp
ouxianghui/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
12
2021-03-26T03:23:30.000Z
2021-12-31T10:05:44.000Z
src/io/dxf/RDxfExporter.cpp
15831944/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
null
null
null
src/io/dxf/RDxfExporter.cpp
15831944/ezcam
195fb402202442b6d035bd70853f2d8c3f615de1
[ "MIT" ]
9
2021-06-23T08:26:40.000Z
2022-01-20T07:18:10.000Z
/** * Copyright (c) 2011-2016 by Andrew Mustun. All rights reserved. * * This file is part of the QCAD project. * * QCAD is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QCAD 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 QCAD. */ #include "dxflib/src/dl_attributes.h" #include "dxflib/src/dl_codes.h" #include "dxflib/src/dl_writer_ascii.h" #include <QFileInfo> #include <QFont> #include "RArcEntity.h" #include "RAttributeEntity.h" #include "RBlockReferenceEntity.h" #include "RCircleEntity.h" #include "RColor.h" #include "RDimAlignedEntity.h" #include "RDimAngularEntity.h" #include "RDimDiametricEntity.h" #include "RDimOrdinateEntity.h" #include "RDimRadialEntity.h" #include "RDimRotatedEntity.h" #include "RDimensionEntity.h" #include "RDxfExporter.h" #include "REllipseEntity.h" #include "RHatchEntity.h" #include "RImageEntity.h" #include "RLeaderEntity.h" #include "RLineEntity.h" #include "RPointEntity.h" #include "RPolylineEntity.h" #include "RRayEntity.h" #include "RSettings.h" #include "RSolidEntity.h" #include "RSplineEntity.h" #include "RStorage.h" #include "RTextEntity.h" #include "RTraceEntity.h" #include "RXLineEntity.h" RDxfExporter::RDxfExporter(RDocument& document, RMessageHandler* messageHandler, RProgressHandler* progressHandler) : RFileExporter(document, messageHandler, progressHandler), minimalistic(false) { } QString RDxfExporter::getCorrectedFileName(const QString& fileName, const QString& nameFilter) { QString ret = fileName; QString ext = QFileInfo(ret).suffix().toLower(); if (ext!="dxf") { ret += ".dxf"; } return ret; } bool RDxfExporter::exportFile(const QString& fileName, const QString& nameFilter, bool setFileName) { //qDebug() << "RDxfExporter::exportFile"; if (nameFilter.contains("min")) { minimalistic = true; } // set version for DXF filter: DL_Codes::version exportVersion; if (minimalistic) { exportVersion = DL_Codes::AC1009_MIN; } else if (nameFilter.contains("R12")) { exportVersion = DL_Codes::AC1009; } else { // TODO: drop support for DXF 2000 (not maintainable): exportVersion = DL_Codes::AC1015; } textStyleCounter = 0; imageHandles.clear(); textStyles.clear(); dw = dxf.out((const char*)QFile::encodeName(fileName), exportVersion); if (dw==NULL) { qWarning() << "RS_FilterDxf::fileExport: cannot open file for writing"; return false; } if (setFileName) { document->setFileName(fileName); } if (!minimalistic) { // Header //qDebug() << "RDxfExporter::exportFile: header"; dxf.writeHeader(*dw); // Variables //qDebug() << "RDxfExporter::exportFile: variables"; writeVariables(); // end header dw->sectionEnd(); } // Section TABLES //qDebug() << "RDxfExporter::exportFile: tables"; dw->sectionTables(); // VPORT: if (!minimalistic) { //qDebug() << "RDxfExporter::exportFile: vport"; dxf.writeVPort(*dw); } // Line types: //qDebug() << "RDxfExporter::exportFile: linetypes"; if (minimalistic) { QSharedPointer<RLinetype> lt = document->queryLinetype("CONTINUOUS"); if (!lt.isNull()) { dw->tableLinetypes(1); writeLinetype(lt->getPattern()); } } else { QStringList lts = document->getLinetypeNames().toList(); //qDebug() << "RDxfExporter::exportFile: linetypes table"; dw->tableLinetypes(lts.size()); // continuous must always be the first LTYPE: QSharedPointer<RLinetype> lt = document->queryLinetype("CONTINUOUS"); if (!lt.isNull()) { writeLinetype(lt->getPattern()); } //qDebug() << "RDxfExporter::exportFile: linetypes loop"; for (int i=0; i<lts.size(); i++) { if (lts[i].toUpper()=="CONTINUOUS") { continue; } QSharedPointer<RLinetype> lt = document->queryLinetype(lts[i]); if (!lt.isNull()) { writeLinetype(lt->getPattern()); } } } //qDebug() << "RDxfExporter::exportFile: linetypes table end"; dw->tableEnd(); // Layers: //qDebug() << "RDxfExporter::exportFile: layers"; QStringList layerNames; if (minimalistic) { layerNames.append("0"); } else { layerNames = document->getLayerNames().toList(); } dw->tableLayers(layerNames.size()); for (int i=0; i<layerNames.size(); ++i) { QSharedPointer<RLayer> layer = document->queryLayer(layerNames[i]); if (layer.isNull()) { continue; } writeLayer(*layer); } dw->tableEnd(); if (!minimalistic) { // STYLE: //qDebug() << "writing styles..."; QList<DL_StyleData> uniqueTextStyles; QString dimFont; //dimFont = document->getDimensionFont(); //if (dimFont.toLower()=="standard") { dimFont = "txt"; //} // add text style for dimensions: DL_StyleData style("Standard", 0, // flags 0.0, // fixed height (not fixed) 1.0, // width factor 0.0, // oblique angle 0, // text generation flags 2.5, // last height used (const char*)dimFont.toLocal8Bit(), //"txt", // primary font file "" // big font file ); style.bold = false; style.italic = false; uniqueTextStyles.append(style); // write one text style for each new, unique combination of font, size, etc: QList<REntity::Id> entityIds = document->queryAllEntities(false, true).toList(); for (int i=0; i<entityIds.size(); i++) { REntity::Id id = entityIds[i]; QSharedPointer<REntity> entity = document->queryEntityDirect(id); QSharedPointer<RTextBasedEntity> textEntity = entity.dynamicCast<RTextBasedEntity>(); if (textEntity.isNull()) { continue; } // getStyle assignes a new, unique name for the style: DL_StyleData style = getStyle(*textEntity); style.bold = textEntity->isBold(); style.italic = textEntity->isItalic(); if (uniqueTextStyles.contains(style)) { textStyleCounter--; continue; } textStyles.insert(id, style.name.c_str()); uniqueTextStyles.append(style); } dw->tableStyle(uniqueTextStyles.size()); for (int i=0; i<uniqueTextStyles.size(); i++) { DL_StyleData style = uniqueTextStyles[i]; dxf.writeStyle(*dw, style); } dw->tableEnd(); } // VIEW: if (!minimalistic) { //qDebug() << "writing views..."; dxf.writeView(*dw); } // UCS: if (!minimalistic) { //qDebug() << "writing ucs..."; dxf.writeUcs(*dw); } // Appid: if (!minimalistic) { //qDebug() << "writing appid..."; dw->tableAppid(1); dxf.writeAppid(*dw, "ACAD"); dxf.writeAppid(*dw, "QCAD"); dw->tableEnd(); } // DIMSTYLE: if (!minimalistic) { //qDebug() << "writing dim styles..."; dxf.writeDimStyle(*dw, document->getKnownVariable(RS::DIMASZ, 2.5).toDouble(), document->getKnownVariable(RS::DIMEXE, 0.625).toDouble(), document->getKnownVariable(RS::DIMEXO, 0.625).toDouble(), document->getKnownVariable(RS::DIMGAP, 0.625).toDouble(), document->getKnownVariable(RS::DIMTXT, 2.5).toDouble() ); } // BLOCK_RECORD: QStringList blockNames = document->getBlockNames().toList(); if (exportVersion!=DL_Codes::AC1009 && exportVersion!=DL_Codes::AC1009_MIN) { //qDebug() << "writing block records..."; dxf.writeBlockRecord(*dw); for (int i=0; i<blockNames.size(); ++i) { //qDebug() << "writing block record: " << blockNames[i]; if (blockNames[i].startsWith("*")) { continue; } QSharedPointer<RBlock> blk = document->queryBlock(blockNames[i]); if (blk.isNull()) { continue; } dxf.writeBlockRecord(*dw, std::string((const char*)RDxfExporter::escapeUnicode(blk->getName())) ); } dw->tableEnd(); } // end of tables: //qDebug() << "writing end of section TABLES..."; dw->sectionEnd(); // Section BLOCKS: //qDebug() << "writing blocks..."; dw->sectionBlocks(); if (exportVersion!=DL_Codes::AC1009 && exportVersion!=DL_Codes::AC1009_MIN) { RBlock b1(document, "*Model_Space", RVector(0.0,0.0)); writeBlock(b1); RBlock b2(document, "*Paper_Space", RVector(0.0,0.0)); writeBlock(b2); RBlock b3(document, "*Paper_Space0", RVector(0.0,0.0)); writeBlock(b3); } //if (!minimalistic) { for (int i=0; i<blockNames.size(); ++i) { //qDebug() << "writing block: " << blockNames[i]; if (blockNames[i].startsWith("*") && !blockNames[i].startsWith("*X")) { continue; } QSharedPointer<RBlock> block = document->queryBlock(blockNames[i]); if (block.isNull()) { continue; } writeBlock(*block); } //} dw->sectionEnd(); // Section ENTITIES: //qDebug() << "writing section ENTITIES..."; dw->sectionEntities(); QSet<REntity::Id> blockEntityIds = document->queryBlockEntities(document->getModelSpaceBlockId()); //qDebug() << "writing model space entities with IDs: " << blockEntityIds; QList<REntity::Id> list = document->getStorage().orderBackToFront(blockEntityIds); //qDebug() << "writing ordered entities with IDs: " << list; for (int i=0; i<list.size(); i++) { writeEntity(list[i]); } //qDebug() << "writing end of section ENTITIES..."; dw->sectionEnd(); if (exportVersion!=DL_Codes::AC1009 && exportVersion!=DL_Codes::AC1009_MIN) { //qDebug() << "writing section OBJECTS..."; dxf.writeObjects(*dw, "QCAD_OBJECTS"); if (!minimalistic) { // XRecords: dxf.writeAppDictionary(*dw); QMap<QString, int> handles; // export all QCAD specific document variables: QStringList variables = document->getVariables(); document->setVariable("QCADVersion", RSettings::getVersionString()); variables.sort(); for (int i=0; i<variables.size(); i++) { QString key = variables[i]; handles.insert(key, dxf.writeDictionaryEntry(*dw, std::string((const char*)RDxfExporter::escapeUnicode(key)))); } for (int i=0; i<variables.size(); i++) { QString key = variables[i]; QVariant value = document->getVariable(key); if (handles.contains(key)) { switch (value.type()) { case QVariant::Int: dxf.writeXRecord(*dw, handles.value(key), value.toInt()); break; case QVariant::Double: dxf.writeXRecord(*dw, handles.value(key), value.toDouble()); break; case QVariant::Bool: dxf.writeXRecord(*dw, handles.value(key), value.toBool()); break; case QVariant::String: dxf.writeXRecord(*dw, handles.value(key), std::string((const char*)RDxfExporter::escapeUnicode(value.toString()))); break; case QVariant::Font: if (value.canConvert<QFont>()) { QFont f = value.value<QFont>(); dxf.writeXRecord(*dw, handles.value(key), std::string((const char*)RDxfExporter::escapeUnicode(f.toString()))); } break; case QVariant::UserType: if (value.canConvert<RColor>()) { RColor c = value.value<RColor>(); dxf.writeXRecord(*dw, handles.value(key), std::string((const char*)RDxfExporter::escapeUnicode(c.getName()))); } break; default: qWarning() << "RDxfExporter::exportFile: unsupported extension data type: " << value.type(); Q_ASSERT(false); break; } } } } // IMAGEDEF's from images in entities and images in blocks QStringList written; QSet<REntity::Id> ids = document->queryAllEntities(false, true); QList<REntity::Id> list = document->getStorage().orderBackToFront(ids); for (int i=0; i<list.size(); i++) { QSharedPointer<REntity> e = document->queryEntity(list[i]); if (e.isNull()) { continue; } QSharedPointer<RImageEntity> img = e.dynamicCast<RImageEntity>(); if (img.isNull()) { continue; } QString file = img->getFileName(); if (/*written.contains(file)==0 &&*/ img->getHandle()!=0) { writeImageDef(*img); written.append(file); } } //qDebug() << "writing end of section OBJECTS..."; dxf.writeObjectsEnd(*dw); } //qDebug() << "writing EOF..."; dw->dxfEOF(); //qDebug() << "RDxfExporter::exportFile: close"; dw->close(); //qDebug() << "RDxfExporter::exportFile: delete"; delete dw; dw = NULL; //qDebug() << "RDxfExporter::exportFile: OK"; // check if file was actually written. Windows might not write // any output without reporting an error. if (QFileInfo(fileName).exists()==false) { return false; } return true; } /** * Writes all known variable settings to the DXF file. */ void RDxfExporter::writeVariables() { for (RS::KnownVariable var=RS::ANGBASE; var<RS::MaxKnownVariable; var=(RS::KnownVariable)((int)var+1)) { QString name = RDxfServices::variableToString(var); // skip unsupported variables: if (!DL_Dxf::checkVariable(name.toUtf8(), dxf.getVersion())) { continue; } // skip undefined variables: QVariant value = document->getKnownVariable(var); if (!value.isValid()) { continue; } int code = RDxfServices::getCodeForVariable(var); if (code==-1) { continue; } if (name=="ACADVER" || name=="HANDSEED") { continue; } name = "$" + name; switch (value.type()) { case QVariant::Int: dw->dxfString(9, (const char*)RDxfExporter::escapeUnicode(name)); dw->dxfInt(code, value.toInt()); break; case QVariant::Double: dw->dxfString(9, (const char*)RDxfExporter::escapeUnicode(name)); dw->dxfReal(code, value.toDouble()); break; case QVariant::String: dw->dxfString(9, (const char*)RDxfExporter::escapeUnicode(name)); dw->dxfString(code, (const char*)RDxfExporter::escapeUnicode(value.toString())); break; case QVariant::UserType: if (value.canConvert<RVector>()) { RVector v = value.value<RVector>(); dw->dxfString(9, (const char*)RDxfExporter::escapeUnicode(name)); dw->dxfReal(code, v.x); dw->dxfReal(code+10, v.y); if (RDxfServices::isVariable2D(var)==false) { dw->dxfReal(code+20, v.z); } } break; default: break; } } /* RS_Hash<RS_String, RS_Variable>::iterator it; (graphic->getVariableDict()); for (it=graphic->getVariableDict().begin(); it!=graphic->getVariableDict().end(); ++it) { // exclude variables that are not known to DXF 12: if (!DL_Dxf::checkVariable(it.key().toUtf8(), dxf.getVersion())) { continue; } if (it.key()!="$ACADVER" && it.key()!="$HANDSEED") { dw->dxfString(9, (const char*)RDxfExporter::escapeUnicode( it.key())); switch (it.value().getType()) { case RS2::VariableVoid: break; case RS2::VariableInt: dw->dxfInt(it.value().getCode(), it.value().getInt()); break; case RS2::VariableDouble: dw->dxfReal(it.value().getCode(), it.value().getDouble()); break; case RS2::VariableString: dw->dxfString(it.value().getCode(), (const char*)RDxfExporter::escapeUnicode( it.value().getString())); break; case RS2::VariableVector: dw->dxfReal(it.value().getCode(), it.value().getVector().x); dw->dxfReal(it.value().getCode()+10, it.value().getVector().y); if (isVariableTwoDimensional(it.key())==false) { dw->dxfReal(it.value().getCode()+20, it.value().getVector().z); } break; } } } RS_Layer* current = graphic->getActiveLayer(); if (current!=NULL) { dw->dxfString(9, "$CLAYER"); dw->dxfString(8, (const char*)RDxfExporter::escapeUnicode(current->getName())); } dw->sectionEnd(); */ } void RDxfExporter::writeLinetype(const RLinetypePattern& lt) { int numDashes = lt.getNumDashes(); double* dashes = new double[numDashes]; for (int i=0; i<numDashes; i++) { dashes[i] = lt.getDashLengthAt(i); } dxf.writeLinetype( *dw, DL_LinetypeData( (const char*)RDxfExporter::escapeUnicode(lt.getName()), (const char*)RDxfExporter::escapeUnicode(lt.getDescription()), 0, numDashes, lt.getPatternLength(), dashes ) ); delete[] dashes; } void RDxfExporter::writeLayer(const RLayer& l) { qDebug() << "RS_FilterDxf::writeLayer: " << l.getName(); int colorSign = 1; if (l.isFrozen()) { colorSign = -1; } QSharedPointer<RLinetype> lt = document->queryLinetype(l.getLinetypeId()); if (lt.isNull()) { qDebug() << "Layer " << l.getName() << " has invalid line type ID"; return; } dxf.writeLayer( *dw, DL_LayerData((const char*)RDxfExporter::escapeUnicode(l.getName()), l.isFrozen() + (l.isLocked()<<2)), DL_Attributes(std::string(""), colorSign * RDxfServices::colorToNumber(l.getColor(), dxfColors), RDxfServices::colorToNumber24(l.getColor()), RDxfServices::widthToNumber(l.getLineweight()), (const char*)RDxfExporter::escapeUnicode(lt->getName()))); } void RDxfExporter::writeBlock(const RBlock& b) { QString blockName = b.getName(); if (dxf.getVersion()==DL_Codes::AC1009 || dxf.getVersion()==DL_Codes::AC1009_MIN) { if (blockName.at(0)=='*') { blockName[0] = '_'; } } dxf.writeBlock(*dw, DL_BlockData((const char*)RDxfExporter::escapeUnicode(blockName), 0, b.getOrigin().x, b.getOrigin().y, b.getOrigin().z)); // entities in model space are stored in section ENTITIES, not in block: if (blockName.toLower()==RBlock::modelSpaceName.toLower()) { dxf.writeEndBlock(*dw, (const char*)RDxfExporter::escapeUnicode(b.getName())); return; } QSet<REntity::Id> ids = document->queryBlockEntities(b.getId()); QList<REntity::Id> list = document->getStorage().orderBackToFront(ids); QList<REntity::Id>::iterator it; for (it=list.begin(); it!=list.end(); it++) { writeEntity(*it); } dxf.writeEndBlock(*dw, (const char*)RDxfExporter::escapeUnicode(b.getName())); } void RDxfExporter::writeEntity(REntity::Id id) { QSharedPointer<REntity> e = document->queryEntity(id); if (e.isNull()) { return; } writeEntity(*e); } /** * Writes the given entity to the DXF file. */ void RDxfExporter::writeEntity(const REntity& e) { if (e.isUndone()) { qDebug() << "RDxfExporter::writeEntity: entity undone..."; // never reached: return; } //qDebug() << "RDxfExporter::writeEntity: " << e; attributes = getEntityAttributes(e); switch (e.getType()) { case RS::EntityPoint: writePoint(dynamic_cast<const RPointEntity&>(e)); break; case RS::EntityLine: writeLine(dynamic_cast<const RLineEntity&>(e)); break; case RS::EntityXLine: writeXLine(dynamic_cast<const RXLineEntity&>(e)); break; case RS::EntityRay: writeRay(dynamic_cast<const RRayEntity&>(e)); break; case RS::EntityPolyline: writePolyline(dynamic_cast<const RPolylineEntity&>(e)); break; case RS::EntitySpline: writeSpline(dynamic_cast<const RSplineEntity&>(e)); break; case RS::EntityCircle: writeCircle(dynamic_cast<const RCircleEntity&>(e)); break; case RS::EntityArc: writeArc(dynamic_cast<const RArcEntity&>(e)); break; case RS::EntityEllipse: writeEllipse(dynamic_cast<const REllipseEntity&>(e)); break; case RS::EntityBlockRef: writeBlockReference(dynamic_cast<const RBlockReferenceEntity&>(e)); break; case RS::EntityText: writeText(dynamic_cast<const RTextEntity&>(e)); break; case RS::EntityAttribute: writeAttribute(dynamic_cast<const RAttributeEntity&>(e)); break; case RS::EntityDimAligned: case RS::EntityDimAngular: case RS::EntityDimRotated: case RS::EntityDimRadial: case RS::EntityDimDiametric: case RS::EntityDimOrdinate: writeDimension(dynamic_cast<const RDimensionEntity&>(e)); break; case RS::EntityLeader: writeLeader(dynamic_cast<const RLeaderEntity&>(e)); break; case RS::EntityHatch: writeHatch(dynamic_cast<const RHatchEntity&>(e)); break; case RS::EntityImage: writeImage(dynamic_cast<const RImageEntity&>(e)); break; case RS::EntitySolid: writeSolid(dynamic_cast<const RSolidEntity&>(e)); break; /* case RS::Entity3dFace: write3dFace(dynamic_cast<RS_3dFace*>(e)); break; #ifndef RS_NO_COMPLEX_ENTITIES case RS::EntityContainer: writeEntityContainer(dynamic_cast<RS_EntityContainer*>(e)); break; #endif */ default: break; } } /** * Writes the given Point entity to the file. */ void RDxfExporter::writePoint(const RPointEntity& p) { dxf.writePoint( *dw, DL_PointData(p.getPosition().x, p.getPosition().y, 0.0), attributes); } /** * Writes the given Line entity to the file. */ void RDxfExporter::writeLine(const RLineEntity& l) { dxf.writeLine( *dw, DL_LineData(l.getStartPoint().x, l.getStartPoint().y, l.getStartPoint().z, l.getEndPoint().x, l.getEndPoint().y, l.getEndPoint().z), attributes); } /** * Writes the given XLine entity to the file. */ void RDxfExporter::writeXLine(const RXLineEntity& l) { dxf.writeXLine( *dw, DL_XLineData(l.getBasePoint().x, l.getBasePoint().y, l.getBasePoint().z, l.getSecondPoint().x - l.getBasePoint().x, l.getSecondPoint().y - l.getBasePoint().y, l.getSecondPoint().z - l.getBasePoint().z), attributes); } /** * Writes the given Ray entity to the file. */ void RDxfExporter::writeRay(const RRayEntity& l) { dxf.writeRay( *dw, DL_RayData(l.getBasePoint().x, l.getBasePoint().y, l.getBasePoint().z, l.getSecondPoint().x - l.getBasePoint().x, l.getSecondPoint().y - l.getBasePoint().y, l.getSecondPoint().z - l.getBasePoint().z), attributes); } /** * Writes the given circle entity to the file. */ void RDxfExporter::writeCircle(const RCircleEntity& c) { dxf.writeCircle( *dw, DL_CircleData(c.getCenter().x, c.getCenter().y, 0.0, c.getRadius()), attributes); } /** * Writes the given circle entity to the file. */ void RDxfExporter::writeArc(const RArcEntity& a) { double a1, a2; if (a.isReversed()) { a1 = RMath::rad2deg(a.getEndAngle()); a2 = RMath::rad2deg(a.getStartAngle()); } else { a1 = RMath::rad2deg(a.getStartAngle()); a2 = RMath::rad2deg(a.getEndAngle()); } dxf.writeArc( *dw, DL_ArcData(a.getCenter().x, a.getCenter().y, 0.0, a.getRadius(), a1, a2), attributes); } /** * Writes the given ellipse entity to the file. */ void RDxfExporter::writeEllipse(const REllipseEntity& el) { double startParam = 0.0; double endParam = 0.0; if (el.isFullEllipse()) { startParam = 0.0; endParam = 2.0*M_PI; } else { if (el.isReversed()) { startParam = el.getEndParam(); endParam = el.getStartParam(); } else { startParam = el.getStartParam(); endParam = el.getEndParam(); } } dxf.writeEllipse( *dw, DL_EllipseData(el.getCenter().x, el.getCenter().y, 0.0, el.getMajorPoint().x, el.getMajorPoint().y, 0.0, el.getRatio(), startParam, endParam), attributes); } /** * Writes the given polyline entity to the file. */ void RDxfExporter::writePolyline(const RPolylineEntity& pl) { writePolyline(pl.getPolylineShape(), pl.getPolylineGen()); } void RDxfExporter::writePolyline(const RPolyline& pl, bool plineGen) { int count = pl.countVertices(); dxf.writePolyline( *dw, DL_PolylineData(count, 0, 0, pl.isClosed()*0x1 + plineGen*0x80), attributes ); for (int i=0; i<pl.countVertices(); i++) { RVector v = pl.getVertexAt(i); double bulge = pl.getBulgeAt(i); dxf.writeVertex(*dw, DL_VertexData(v.x, v.y, 0.0, bulge)); } dxf.writePolylineEnd(*dw); } /** * Writes the given spline entity to the file. */ void RDxfExporter::writeSpline(const RSplineEntity& sp) { // write spline as polyline for DXF R12: if (dxf.getVersion()==DL_Codes::AC1009 || dxf.getVersion()==DL_Codes::AC1009_MIN) { int seg = RSettings::getIntValue("Explode/SplineSegments", 64); writePolyline(sp.getData().toPolyline(seg), false); return; } if (sp.countControlPoints() < sp.getDegree()+1) { qWarning() << "RDxfExporter::writeSpline: " << "Discarding spline: not enough control points given."; return; } // number of control points: QList<RVector> cp = sp.getControlPointsWrapped(); int numCtrlPoints = cp.count(); // number of fit points: QList<RVector> fp = sp.getFitPoints(); if (sp.isPeriodic() && !fp.isEmpty()) { fp.append(fp.first()); } int numFitPoints = fp.count(); // number of knots (= number of control points + spline degree + 1) QList<double> knotVector = sp.getActualKnotVector(); // first and last knots are duplicated in DXF: if (!knotVector.isEmpty()) { knotVector.prepend(knotVector.first()); knotVector.append(knotVector.last()); } //int numKnots = numCtrlPoints + sp.getDegree() + 1; int numKnots = knotVector.count(); int flags; if (sp.isClosed()) { flags = 11; } else { flags = 8; } // write spline header: dxf.writeSpline( *dw, DL_SplineData(sp.getDegree(), numKnots, numCtrlPoints, numFitPoints, flags), attributes ); // write spline knots: DL_KnotData kd; for (int i=0; i<numKnots; i++) { kd = DL_KnotData(knotVector[i]); dxf.writeKnot(*dw, kd); } // write spline control points: for (int i=0; i<numCtrlPoints; i++) { dxf.writeControlPoint( *dw, DL_ControlPointData(cp[i].x, cp[i].y, 0.0, 1.0) ); } // write spline fit points (if any): for (int i=0; i<numFitPoints; i++) { dxf.writeFitPoint(*dw, DL_FitPointData(fp[i].x, fp[i].y, 0.0)); } } DL_TextData RDxfExporter::getTextData(const RTextBasedData& t, const QString& styleName) { DL_TextData data( t.getPosition().x, t.getPosition().y, 0.0, t.getAlignmentPoint().x, t.getAlignmentPoint().y, 0.0, t.getTextHeight(), 1.0, // x scale factor 0, // text gen flags 0, // h just 0, // v just (const char*)RDxfExporter::escapeUnicode(t.getEscapedText(true)), (const char*)RDxfExporter::escapeUnicode(styleName), t.getAngle()); if (t.getHAlign()==RS::HAlignAlign && t.getVAlign()==RS::VAlignBottom) { data.vJustification = 0; data.hJustification = 0; } else { switch (t.getHAlign()) { default: case RS::HAlignLeft: data.hJustification = 0; break; case RS::HAlignCenter: data.hJustification = 1; break; case RS::HAlignRight: data.hJustification = 2; break; } switch (t.getVAlign()) { default: case RS::VAlignBase: data.vJustification = 0; break; case RS::VAlignBottom: data.vJustification = 1; break; case RS::VAlignMiddle: data.vJustification = 2; break; case RS::VAlignTop: data.vJustification = 3; break; } } return data; } QString RDxfExporter::getStyleName(const RTextBasedEntity& t) { REntity::Id id = t.getId(); if (!textStyles.contains(id)) { qWarning() << "RDxfExporter::getStyleName: " << "no style for entity with ID: " << id; qDebug() << "Styles:"; qDebug() << textStyles; return QString(); } return textStyles.value(t.getId()); } /** * Writes the given text entity to the file. */ void RDxfExporter::writeText(const RTextEntity& t) { if (t.isSimple()) { writeSimpleText(t); } else { writeMText(t); } } void RDxfExporter::writeAttribute(const RAttributeEntity& t) { DL_TextData tData = getTextData(t.getData(), getStyleName(t)); DL_AttributeData data(tData, (const char*)RDxfExporter::escapeUnicode(t.getTag())); dxf.writeAttribute(*dw, data, attributes); } void RDxfExporter::writeSimpleText(const RTextEntity& t) { DL_TextData data = getTextData(t.getData(), getStyleName(t)); dxf.writeText(*dw, data, attributes); } void RDxfExporter::writeMText(const RTextEntity& t) { // REntity::Id id = t.getId(); // if (!textStyles.contains(id)) { // qWarning() << "RDxfExporter::writeMText: " // << "no style for entity with ID: " << id; // return; // } // QString styleName = textStyles.value(t.getId()); QString styleName = getStyleName(t); int attachmentPoint=1; switch (t.getHAlign()) { default: case RS::HAlignLeft: attachmentPoint=1; break; case RS::HAlignCenter: attachmentPoint=2; break; case RS::HAlignRight: attachmentPoint=3; break; } switch (t.getVAlign()) { default: case RS::VAlignTop: attachmentPoint+=0; break; case RS::VAlignMiddle: attachmentPoint+=3; break; case RS::VAlignBottom: attachmentPoint+=6; break; } int drawingDirection = 1; switch (t.getDrawingDirection()) { default: case RS::LeftToRight: drawingDirection = 1; break; case RS::TopToBottom: drawingDirection = 3; break; case RS::ByStyle: drawingDirection = 5; break; } int lineSpacingStyle = 2; switch (t.getLineSpacingStyle()) { case RS::AtLeast: lineSpacingStyle = 1; break; default: case RS::Exact: lineSpacingStyle = 2; break; } dxf.writeMText( *dw, DL_MTextData(//t.getPosition().x, //t.getPosition().y, t.getAlignmentPoint().x, t.getAlignmentPoint().y, 0.0, //t.getAlignmentPoint().x, //t.getAlignmentPoint().y, 0.0, 0.0, 0.0, t.getTextHeight(), t.getTextWidth(), attachmentPoint, drawingDirection, lineSpacingStyle, t.getLineSpacingFactor(), (const char*)RDxfExporter::escapeUnicode(t.getEscapedText(true)), (const char*)RDxfExporter::escapeUnicode(styleName), t.getAngle()), attributes); } /** * Writes the given dimension entity to the file. */ void RDxfExporter::writeDimension(const RDimensionEntity& d) { // split dimension into simple entities: if (dxf.getVersion()==DL_Codes::AC1009 || dxf.getVersion()==DL_Codes::AC1009_MIN) { // TODO: //writeAtomicEntities(d, RS2::ResolveNone); return; } int dimType; int attachmentPoint=1; // if (d.getHAlign()==RS2::HAlignLeft) { // attachmentPoint=1; // } else if (d.getHAlign()==RS2::HAlignCenter) { attachmentPoint=2; // } else if (d.getHAlign()==RS2::HAlignRight) { // attachmentPoint=3; // } // if (d.getVAlign()==RS2::VAlignTop) { // attachmentPoint+=0; // } else if (d.getVAlign()==RS2::VAlignMiddle) { // attachmentPoint+=3; // } else if (d.getVAlign()==RS2::VAlignBottom) { attachmentPoint+=6; // } switch (d.getType()) { case RS::EntityDimAligned: dimType = 1; break; case RS::EntityDimAngular: dimType = 2; break; case RS::EntityDimRotated: dimType = 0; break; case RS::EntityDimRadial: dimType = 4; break; case RS::EntityDimDiametric: dimType = 3; break; case RS::EntityDimOrdinate: dimType = 6; break; default: dimType = 0; break; } if (d.hasCustomTextPosition()) { dimType |= 0x80; } QString text = d.getMeasurement(false); text.replace("^", "^ "); qDebug() << "dimType: " << dimType; qDebug() << "text: " << d.getMeasurement(false); DL_DimensionData dimData(d.getDefinitionPoint().x, d.getDefinitionPoint().y, 0.0, d.getTextPosition().x, d.getTextPosition().y, 0.0, dimType, attachmentPoint, d.getLineSpacingStyle(), d.getLineSpacingFactor(), (const char*)RDxfExporter::escapeUnicode(text), // TODO: dim style: (const char*)RDxfExporter::escapeUnicode(d.getFontName()), d.getTextAngle(), d.getLinearFactor(), d.getDimScale()); switch (d.getType()) { case RS::EntityDimAligned: { const RDimAlignedEntity* dim = dynamic_cast<const RDimAlignedEntity*>(&d); DL_DimAlignedData dimAlignedData(dim->getExtensionPoint1().x, dim->getExtensionPoint1().y, 0.0, dim->getExtensionPoint2().x, dim->getExtensionPoint2().y, 0.0); dxf.writeDimAligned(*dw, dimData, dimAlignedData, attributes); } break; case RS::EntityDimRotated: { const RDimRotatedEntity* dim = dynamic_cast<const RDimRotatedEntity*>(&d); DL_DimLinearData dimLinearData(dim->getExtensionPoint1().x, dim->getExtensionPoint1().y, 0.0, dim->getExtensionPoint2().x, dim->getExtensionPoint2().y, 0.0, dim->getRotation(), 0.0 // TODO: dl->getOblique() ); dxf.writeDimLinear(*dw, dimData, dimLinearData, attributes); } break; case RS::EntityDimRadial: { const RDimRadialEntity* dim = dynamic_cast<const RDimRadialEntity*>(&d); DL_DimRadialData dimRadialData(dim->getChordPoint().x, dim->getChordPoint().y, 0.0, 0.0 // TODO: dr->getLeader() ); dxf.writeDimRadial(*dw, dimData, dimRadialData, attributes); } break; case RS::EntityDimDiametric: { const RDimDiametricEntity* dim = dynamic_cast<const RDimDiametricEntity*>(&d); DL_DimDiametricData dimDiametricData(dim->getChordPoint().x, dim->getChordPoint().y, 0.0, 0.0 // TODO: dr->getLeader() ); dxf.writeDimDiametric(*dw, dimData, dimDiametricData, attributes); } break; case RS::EntityDimAngular: { const RDimAngularEntity* dim = dynamic_cast<const RDimAngularEntity*>(&d); DL_DimAngularData dimAngularData(dim->getExtensionLine1Start().x, dim->getExtensionLine1Start().y, 0.0, dim->getExtensionLine1End().x, dim->getExtensionLine1End().y, 0.0, dim->getExtensionLine2Start().x, dim->getExtensionLine2Start().y, 0.0, dim->getDimArcPosition().x, dim->getDimArcPosition().y, 0.0); dxf.writeDimAngular(*dw, dimData, dimAngularData, attributes); } break; case RS::EntityDimOrdinate: { const RDimOrdinateEntity* dim = dynamic_cast<const RDimOrdinateEntity*>(&d); DL_DimOrdinateData dimOrdinateData(dim->getDefiningPoint().x, dim->getDefiningPoint().y, 0.0, dim->getLeaderEndPoint().x, dim->getLeaderEndPoint().y, 0.0, dim->isMeasuringXAxis()); dxf.writeDimOrdinate(*dw, dimData, dimOrdinateData, attributes); } break; default: break; } } /** * Writes the given leader entity to the file. */ void RDxfExporter::writeLeader(const RLeaderEntity& l) { if (l.countSegments()>0) { dxf.writeLeader( *dw, DL_LeaderData(l.hasArrowHead(), 0, 3, 0, 0, 1.0, 10.0, l.countVertices()), attributes); bool first = true; for (int i=0; i<l.countSegments(); i++) { QSharedPointer<RShape> seg = l.getSegmentAt(i); if (seg.isNull()) { continue; } QSharedPointer<RLine> line = seg.dynamicCast<RLine>(); if (line.isNull()) { continue; } if (first) { dxf.writeLeaderVertex( *dw, DL_LeaderVertexData(line->getStartPoint().x, line->getStartPoint().y, 0.0)); first = false; } dxf.writeLeaderVertex( *dw, DL_LeaderVertexData(line->getEndPoint().x, line->getEndPoint().y, 0.0)); } } else { qWarning() << "RDxfExporter::writeLeader: " << "dropping leader without segments"; } } /** * Writes the given hatch entity to the file. */ void RDxfExporter::writeHatch(const RHatchEntity& h) { // split hatch into simple entities: if (dxf.getVersion()==DL_Codes::AC1009 || dxf.getVersion()==DL_Codes::AC1009_MIN) { //writeAtomicEntities(h, RS2::ResolveAll); return; } if (h.getLoopCount()==0) { qWarning() << "RDxfExporter::writeHatch: skip hatch without loops"; return; } // check if all of the loops contain entities: // for (RS_Entity* l=h->firstEntity(RS2::ResolveNone); // l!=NULL; // l=h->nextEntity(RS2::ResolveNone)) { // if (l->isContainer() && !l->getFlag(RS2::FlagTemp)) { // if (l->count()==0) { // writeIt = false; // } // } // } DL_HatchData data(h.getLoopCount(), h.isSolid(), h.getScale(), RMath::rad2deg(h.getAngle()), (const char*)RDxfExporter::escapeUnicode(h.getPatternName()), h.getOriginPoint().x, h.getOriginPoint().y); dxf.writeHatch1(*dw, data, attributes); for (int i=0; i<h.getLoopCount(); i++) { QList<QSharedPointer<RShape> > loop = h.getLoopBoundary(i); // Write hatch loops: DL_HatchLoopData lData(loop.size()); dxf.writeHatchLoop1(*dw, lData); // Write hatch loop edges: for (int k=0; k<loop.size(); k++) { QSharedPointer<RShape> shape = loop[k]; // line: QSharedPointer<RLine> line = shape.dynamicCast<RLine>(); if (!line.isNull()) { dxf.writeHatchEdge( *dw, DL_HatchEdgeData(line->getStartPoint().x, line->getStartPoint().y, line->getEndPoint().x, line->getEndPoint().y)); } // arc: QSharedPointer<RArc> arc = shape.dynamicCast<RArc>(); if (!arc.isNull()) { if (!arc->isReversed()) { dxf.writeHatchEdge( *dw, DL_HatchEdgeData(arc->getCenter().x, arc->getCenter().y, arc->getRadius(), arc->getStartAngle(), arc->getEndAngle(), true)); } else { dxf.writeHatchEdge( *dw, DL_HatchEdgeData(arc->getCenter().x, arc->getCenter().y, arc->getRadius(), 2*M_PI-arc->getStartAngle(), 2*M_PI-arc->getEndAngle(), false)); } } // full circle: QSharedPointer<RCircle> circle = shape.dynamicCast<RCircle>(); if (!circle.isNull()) { dxf.writeHatchEdge( *dw, DL_HatchEdgeData(circle->getCenter().x, circle->getCenter().y, circle->getRadius(), 0.0, 2*M_PI, true)); } // ellipse arc: QSharedPointer<REllipse> ellipse = shape.dynamicCast<REllipse>(); if (!ellipse.isNull()) { double startAngle = ellipse->getStartAngle(); double endAngle = ellipse->getEndAngle(); if (ellipse->isFullEllipse()) { startAngle = 0.0; endAngle = 2*M_PI; } else if (ellipse->isReversed()) { startAngle = 2*M_PI - RMath::getNormalizedAngle(startAngle); endAngle = 2*M_PI - RMath::getNormalizedAngle(endAngle); } dxf.writeHatchEdge( *dw, DL_HatchEdgeData(ellipse->getCenter().x, ellipse->getCenter().y, ellipse->getMajorPoint().x, ellipse->getMajorPoint().y, ellipse->getRatio(), startAngle, endAngle, !ellipse->isReversed())); } // spline: QSharedPointer<RSpline> spline = shape.dynamicCast<RSpline>(); if (!spline.isNull()) { QList<double> knotVector = spline->getActualKnotVector(); if (knotVector.size()>0) { knotVector.prepend(knotVector.first()); knotVector.append(knotVector.last()); } std::vector<double> dxfKnotVector; for (int i=0; i<knotVector.size(); i++) { dxfKnotVector.push_back(knotVector[i]); } std::vector<std::vector<double> > dxfControlPoints; QList<RVector> controlPoints = spline->getControlPoints(); for (int i=0; i<controlPoints.size(); i++) { RVector cp = controlPoints[i]; std::vector<double> dxfV; dxfV.push_back(cp.x); dxfV.push_back(cp.y); dxfControlPoints.push_back(dxfV); } std::vector<std::vector<double> > dxfFitPoints; QList<RVector> fitPoints = spline->getFitPoints(); for (int i=0; i<fitPoints.size(); i++) { RVector fp = fitPoints[i]; std::vector<double> dxfV; dxfV.push_back(fp.x); dxfV.push_back(fp.y); dxfFitPoints.push_back(dxfV); } dxf.writeHatchEdge( *dw, DL_HatchEdgeData(spline->getDegree(), false, // rational spline->isPeriodic(), knotVector.size(), spline->countControlPoints(), spline->countFitPoints(), dxfKnotVector, dxfControlPoints, dxfFitPoints, std::vector<double>(), spline->getTangentAtStart().x, spline->getTangentAtStart().y, spline->getTangentAtEnd().x, spline->getTangentAtEnd().y )); } } dxf.writeHatchLoop2(*dw, lData); } dxf.writeHatch2(*dw, data, attributes); } /** * Writes the given image entity to the file. */ void RDxfExporter::writeImage(const RImageEntity& img) { int handle = dxf.writeImage( *dw, DL_ImageData(std::string(""), img.getInsertionPoint().x, img.getInsertionPoint().y, 0.0, img.getUVector().x, img.getUVector().y, 0.0, img.getVVector().x, img.getVVector().y, 0.0, img.getWidth(), img.getHeight(), img.getBrightness(), img.getContrast(), img.getFade()), attributes); imageHandles.insert(img.getId(), handle); } /** * Writes the given solid entity to the file. */ void RDxfExporter::writeSolid(const RSolidEntity& sol) { RVector c1 = sol.getVertexAt(0); RVector c2 = sol.getVertexAt(1); RVector c3 = sol.getVertexAt(2); RVector c4 = c3; if (sol.countVertices()>3) { c4 = sol.getVertexAt(3); } dxf.writeSolid(*dw, DL_SolidData(c1.x, c1.y, c1.z, c2.x, c2.y, c2.z, c3.x, c3.y, c3.z, c4.x, c4.y, c4.z, 0), attributes); } /** * Writes the given trace entity to the file. */ void RDxfExporter::writeTrace(const RTraceEntity& t) { RVector c1 = t.getVertexAt(0); RVector c2 = t.getVertexAt(1); RVector c3 = t.getVertexAt(2); RVector c4 = t.getVertexAt(3); dxf.writeTrace(*dw, DL_TraceData(c1.x, c1.y, c1.z, c2.x, c2.y, c2.z, c3.x, c3.y, c3.z, c4.x, c4.y, c4.z, 0), attributes); } /** * Writes an IMAGEDEF object into an OBJECT section. */ void RDxfExporter::writeImageDef(const RImageEntity& img) { if (!imageHandles.contains(img.getId())) { qWarning() << "RDxfExporter::writeImageDef: no handle for given image"; return; } int handle = imageHandles.value(img.getId()); dxf.writeImageDef( *dw, handle, DL_ImageData((const char*)RDxfExporter::escapeUnicode(img.getFileName()), img.getInsertionPoint().x, img.getInsertionPoint().y, 0.0, img.getUVector().x, img.getUVector().y, 0.0, img.getVVector().x, img.getVVector().y, 0.0, img.getWidth(), img.getHeight(), img.getBrightness(), img.getContrast(), img.getFade())); } /** * Writes the given block reference entity to the file. */ void RDxfExporter::writeBlockReference(const RBlockReferenceEntity& br) { QString blockName = br.getReferencedBlockName(); if (dxf.getVersion()==DL_Codes::AC1009 || dxf.getVersion()==DL_Codes::AC1009_MIN) { if (blockName.at(0)=='*') { blockName[0] = '_'; } } dxf.writeInsert( *dw, DL_InsertData( (const char*)RDxfExporter::escapeUnicode(blockName), br.getPosition().x, br.getPosition().y, 0.0, br.getScaleFactors().x, br.getScaleFactors().y, 0.0, RMath::rad2deg(br.getRotation()), br.getColumnCount(), br.getRowCount(), br.getColumnSpacing(), br.getRowSpacing() ), attributes ); } //void RDxfExporter::writeExplodedEntities(const REntity& entity) { // const RShape* shape = entity.castToConstShape(); // if (shape==NULL) { // qWarning() << "RDxfExporter::writeExplodedEntities: not a shape"; // return; // } // const RExplodable* explodable = dynamic_cast<RExplodable*>(&entity); // if (explodable!=NULL) { // QList<QSharedPointer<RShape> > segments = explodable->getExploded(); // for (int i=0; i<segments.count(); i++) { // segments[i]; // } // } //} /** * \return the entities attributes as a DL_Attributes object. */ DL_Attributes RDxfExporter::getEntityAttributes(const REntity& entity) { // Layer: QString layerName = entity.getLayerName(); if (minimalistic) { layerName = "0"; } // Color: int color = RDxfServices::colorToNumber(entity.getColor(), dxfColors); int color24 = RDxfServices::colorToNumber24(entity.getColor()); // Linetype: QString linetype = document->getLinetypeName(entity.getLinetypeId()); if (minimalistic) { linetype = "CONTINUOUS"; } // Width: int width = RDxfServices::widthToNumber(entity.getLineweight()); DL_Attributes attrib((const char*)RDxfExporter::escapeUnicode(layerName), color, color24, width, (const char*)RDxfExporter::escapeUnicode(linetype)); attrib.setLinetypeScale(entity.getLinetypeScale()); return attrib; } DL_StyleData RDxfExporter::getStyle(const RTextBasedEntity& entity) { QString name = QString("textstyle%1").arg(textStyleCounter++); return DL_StyleData((const char*)RDxfExporter::escapeUnicode(name), 0, // flags 0.0, // fixed height (not fixed) 1.0, // width factor 0.0, // oblique angle 0, // text generation flags entity.getTextHeight(), // last height used (const char*)RDxfExporter::escapeUnicode(entity.getFontName()), // primary font file "" // big font file ); } QByteArray RDxfExporter::escapeUnicode(const QString& str) { // DXF R15: DWGCODEPAGE==ANSI_1252 means latin1: return RDxfServices::escapeUnicode(str).toLatin1(); }
33.388146
139
0.500548
ouxianghui
5ddf2c948a528e38cdf62bc72d3bdc4c12fc61b0
4,178
cpp
C++
OpenGL/src/Application.cpp
Jason-Skillman/OpenGL-Application
1a6974b34670fd22590b212415723010a9e10ddd
[ "Apache-2.0" ]
null
null
null
OpenGL/src/Application.cpp
Jason-Skillman/OpenGL-Application
1a6974b34670fd22590b212415723010a9e10ddd
[ "Apache-2.0" ]
null
null
null
OpenGL/src/Application.cpp
Jason-Skillman/OpenGL-Application
1a6974b34670fd22590b212415723010a9e10ddd
[ "Apache-2.0" ]
null
null
null
#include <GL/glew.h> #include <GLFW/glfw3.h> #include <iostream> #include <fstream> #include <string> #include <sstream> #include "Renderer.h" #include "VertexBuffer.h" #include "VertexBufferLayout.h" #include "IndexBuffer.h" #include "VertexArray.h" #include "Shader.h" #include "Texture.h" #include "glm/glm.hpp" #include "glm/gtc/matrix_transform.hpp" #include "imgui/imgui.h" #include "imgui/imgui_impl_glfw.h" #include "imgui/imgui_impl_opengl3.h" #include "tests/Test.h" #include "tests/TestClearColor.h" #include "tests/TestTexture2D.h" #include "tests/TestBatchRender.h" #include "tests/TestBatchRenderColors.h" #include "tests/TestBatchRenderTextures.h" #include "tests/TestBatchRenderDynamic.h" int main(void) { GLFWwindow* window; /* Initialize the library */ if(!glfwInit()) return -1; glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); /* Create a windowed mode window and its OpenGL context */ window = glfwCreateWindow(800, 600, "OpenGL", NULL, NULL); if(!window) { glfwTerminate(); return -1; } /* Make the window's context current */ glfwMakeContextCurrent(window); //V-sync glfwSwapInterval(1); //Init GLEW //Must be init after a valid context has been created (window) GLenum err = glewInit(); if(GLEW_OK != err) { std::cout << "Error: glewInit() failed to initialize" << std::endl; } std::cout << glGetString(GL_VERSION) << std::endl; { //Enable texture blending GLCall(glEnable(GL_BLEND)); GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)); Renderer renderer; //----- Setup ImGUI ----- IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); (void)io; ImGui::StyleColorsDark(); ImGui_ImplGlfw_InitForOpenGL(window, true); ImGui_ImplOpenGL3_Init((char*)glGetString(GL_NUM_SHADING_LANGUAGE_VERSIONS)); test::Test* currentTest; test::TestMenu* testMenu = new test::TestMenu(currentTest); currentTest = testMenu; //Register all of the tests testMenu->RegisterTest<test::TestClearColor>("Clear Color"); testMenu->RegisterTest<test::TestTexture2D>("Texture 2D"); testMenu->RegisterTest<test::TestBatchRender>("Batch Render - Objects"); testMenu->RegisterTest<test::TestBatchRenderColors>("Batch Render - Colors"); testMenu->RegisterTest<test::TestBatchRenderTextures>("Batch Render - Textures"); testMenu->RegisterTest<test::TestBatchRenderDynamic>("Batch Render - Dynamic"); //Clear //va.Unbind(); //shader.Unbind(); //GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0)); //GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); /* Loop until the user closes the window */ while(!glfwWindowShouldClose(window)) { GLCall(glClearColor(0.0f, 0.0f, 0.0f, 0.0f)); renderer.Clear(); //ImGui New Frame ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); if(currentTest) { currentTest->OnUpdate(0.0f); currentTest->OnRender(); ImGui::Begin("Test"); if(currentTest != testMenu && ImGui::Button("<-")) { delete currentTest; currentTest = testMenu; } currentTest->OnImGuiRender(); ImGui::End(); } //Render ImGui::Render(); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); /* Swap front and back buffers */ glfwSwapBuffers(window); /* Poll for and process events */ glfwPollEvents(); } delete currentTest; if(currentTest != testMenu) delete testMenu; } //Shutdown ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwTerminate(); return 0; }
27.853333
89
0.623265
Jason-Skillman
5ddf9daf553c81961c0da47780a7719356bf7f7e
1,425
cpp
C++
devdc14.cpp
vidit1999/coding_problems
b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a
[ "BSD-2-Clause" ]
1
2020-02-24T18:28:48.000Z
2020-02-24T18:28:48.000Z
devdc14.cpp
vidit1999/coding_problems
b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a
[ "BSD-2-Clause" ]
null
null
null
devdc14.cpp
vidit1999/coding_problems
b6c9fa7fda37d9424cd11bcd54b385fd8cf1ee0a
[ "BSD-2-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Given a positive integer n, return a strictly increasing sequence of numbers so that the sum of the squares is equal to n². If there are multiple solutions, return the result with the largest possible value: For example: decompose(11) must return [1,2,4,10]. Note: there are actually two ways to decompose 11², 11² = 121 = 1 + 4 + 16 + 100 = 1² + 2² + 4² + 10² but you shouldn't return [2,6,9], since 9 is smaller than 10. Hint: Very often will xk be n-1. */ // helper function for decompose bool decomposeHelper(int target, int number, vector<int>& decomposed){ if(target == 0){ return true; } if(target < 0 || (number == 1 && target > 1)){ return false; } for(int i=number-1;i>=1;i--){ if(decomposeHelper(target-i*i,i,decomposed)){ decomposed.push_back(i); return true; } } return false; } // decomposes a number and returns them as a vector vector<int> decompose(int number){ vector<int> v; decomposeHelper(number*number, number, v); return v; } // test function // prints the decomposed values of numbers from 1 to testLast void testFunc(int testLast){ for(int i=1;i<=testLast;i++){ cout << "Number : " << i << " -- decomposed -- "; vector<int> v = decompose(i); for(int i : v) cout << i << " "; cout << "\n"; } } // main function int main(){ testFunc(100); return 0; }
23.75
83
0.64
vidit1999
5ddfec40fee9aa5970c13c6fa6d0561decf1cfe1
2,415
hpp
C++
src/include/streamer/objects.hpp
philip1337/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
2
2017-07-23T23:27:03.000Z
2017-07-24T06:18:13.000Z
src/include/streamer/objects.hpp
Sphinxila/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
null
null
null
src/include/streamer/objects.hpp
Sphinxila/samp-plugin-streamer
54b08afd5e73bd5f68f67f9cf8cc78189bf6ef8a
[ "Apache-2.0" ]
null
null
null
#ifndef OBJECTS_HPP #define OBJECTS_HPP #pragma once #include "config.hpp" #include <limits> #include <string> STREAMER_BEGIN_NS int CreateDynamicObject(int modelid, float x, float y, float z, float rx, float ry, float rz, int worldid, int interiorid, int playerid, float streamDistance, float drawDistance, int areaid, int priority); int DestroyDynamicObject(int id); int IsValidDynamicObject(int id); int SetDynamicObjectPos(int id, float x, float y, float z); //int GetDynamicObjectPos(int id, float &x, float &y, float &z); int SetDynamicObjectRot(int id, float rx, float ry, float rz); //int GetDynamicObjectRot(int id, float &rx, float &ry, float &rz); int SetDynamicObjectNoCameraCol(int id); int GetDynamicObjectNoCameraCol(int id); int MoveDynamicObject(int id, float x, float y, float z, float speed, float rx, float ry, float rz); int StopDynamicObject(int id); int IsDynamicObjectMoving(int id); int AttachCameraToDynamicObject(int playerid, int objectid); int AttachDynamicObjectToObject(int objectid, int attachtoid, float x, float y, float z, float rx, float ry, float rz, bool sync); int AttachDynamicObjectToPlayer(int objectid, int playerid, float x, float y, float z, float rx, float ry, float rz); int AttachDynamicObjectToVehicle(int objectid, int vehicleid, float x, float y, float z, float rx, float ry, float rz); int EditDynamicObject(int playerid, int objectid); int IsDynamicObjectMaterialUsed(int objectid, int materialindex); int GetDynamicObjectMaterial(int objectid, int materialindex, int &modelid, std::string &txdname, std::string &texturename, int &materialcolor); int SetDynamicObjectMaterial(int id, int materialindex, int modelid, std::string txdname, std::string texturename, int materialcolor); int IsDynamicObjectMaterialTextUsed(int id, int materialindex); int GetDynamicObjectMaterialText(int id, int materialindex, std::string &text, int &materialSize, std::string &fontface, int &fontsize, bool &bold, int &fontcolor, int &backcolor, int &textalignment); int SetDynamicObjectMaterialText(int id, int materialindex, std::string text, int materialsize, std::string fontface, int fontsize, bool bold, int fontcolor, int backcolor, int textalignment); int GetPlayerCameraTargetDynObject(int playerrid); int GetDynamicObjectPos(int objectid, float &x, float &y, float &z); int GetDynamicObjectRot(int objectid, float &rx, float &ry, float &rz); STREAMER_END_NS #endif
56.162791
200
0.787992
philip1337
5de13036ea80514d9a3d57d28bf1fc5fa0309b5b
308
cpp
C++
Evo/History/HistorySystem.cpp
pk1954/Solutions
b224522283f82cb7d73b8005e35e0c045edc2fc0
[ "MIT" ]
null
null
null
Evo/History/HistorySystem.cpp
pk1954/Solutions
b224522283f82cb7d73b8005e35e0c045edc2fc0
[ "MIT" ]
null
null
null
Evo/History/HistorySystem.cpp
pk1954/Solutions
b224522283f82cb7d73b8005e35e0c045edc2fc0
[ "MIT" ]
null
null
null
// HistorySystem.cpp // #include "stdafx.h" #include "assert.h" #include "HistorySystem.h" #include "HistorySystemImpl.h" HistorySystem * HistorySystem::CreateHistorySystem() { return new HistorySystemImpl( ); } BYTES HistorySystem::GetSlotWrapperSize( ) { return BYTES( sizeof( HistCacheItem ) ); }
17.111111
52
0.737013
pk1954
5de59dd40368999a5dc2e0f3fdb44e2f24148ecc
15,234
hh
C++
libs/cmdr11/include/cmdr11/cmdr_arg.hh
hedzr/cmdr-cxx
7e4c1b8b92feadb45b3eb22c4e816902ddb4bd12
[ "MIT" ]
5
2021-03-05T02:02:39.000Z
2022-01-01T12:44:02.000Z
libs/cmdr11/include/cmdr11/cmdr_arg.hh
hedzr/cmdr-cxx
7e4c1b8b92feadb45b3eb22c4e816902ddb4bd12
[ "MIT" ]
null
null
null
libs/cmdr11/include/cmdr11/cmdr_arg.hh
hedzr/cmdr-cxx
7e4c1b8b92feadb45b3eb22c4e816902ddb4bd12
[ "MIT" ]
null
null
null
// // Created by Hedzr Yeh on 2021/1/11. // #ifndef CMDR_CXX11_CMDR_ARG_HH #define CMDR_CXX11_CMDR_ARG_HH #include <any> #include <cassert> #include <iomanip> #include <sstream> #include <type_traits> #include <utility> #include <variant> #include "cmdr_cmn.hh" #include "cmdr_string.hh" #include "cmdr_var_t.hh" namespace cmdr::opt { /** * @brief base class for command/flag. */ class bas : public obj { protected: std::string _long{}; std::string _short{}; string_array _aliases{}; std::string _desc_long{}; std::string _description{}; std::string _examples{}; std::string _group{}; bool _hidden : 1; bool _required : 1; bool _special : 1; bool _no_non_special : 1; // These internal flags cannot be used for setter bool _hit_long : 1; bool _hit_special : 1; bool _hit_env : 1; std::string _hit_title{}; int _hit_count{0}; cmd *_owner{nullptr}; public: static bool _alias_right_align; static int _minimal_tab_width; static bool _no_catch_cmdr_biz_error; static bool _no_cmdr_ending; static bool _no_tail_line; static bool _longest_first; static text::distance _jaro_winkler_matching_threshold; public: bas() : _hidden{} , _required{} , _special{} , _no_non_special{} , _hit_long{} , _hit_special{} , _hit_env{} {} ~bas() override = default; bas(const bas &o) { _copy(o); } bas &operator=(const bas &o) { if (this == &o) return *this; _copy(o); return (*this); } [[nodiscard]] bool valid() const { if (_long.empty()) return false; return true; } protected: void _copy(const bas &o) { __COPY(_long); __COPY(_short); __COPY(_aliases); __COPY(_desc_long); __COPY(_description); __COPY(_examples); __COPY(_group); __COPY(_hidden); __COPY(_required); __COPY(_special); __COPY(_no_non_special); __COPY(_hit_long); __COPY(_hit_special); __COPY(_hit_env); __COPY(_hit_title); __COPY(_hit_count); __COPY(_owner); } public: #undef PROP_SET #undef PROP_SET2 #undef PROP_SET3 #define PROP_SET(mn) \ bas &mn(const_chars s) { \ if (s) _##mn = s; \ return (*this); \ } \ std::string const &mn() const { return _##mn; } #define PROP_SET2(mn) \ bas &title_##mn(const_chars s) { \ if (s) _##mn = s; \ return (*this); \ } \ std::string const &title_##mn() const { return _##mn; } #define PROP_SET3(mn, typ) \ bas &title_##mn(const typ &s) { \ _##mn = s; \ return (*this); \ } \ typ const &title_##mn() const { return _##mn; } \ typ &title_##mn() { return _##mn; } #define PROP_SET4(mn, typ) \ bas &mn(const typ &s) { \ _##mn = s; \ return (*this); \ } \ typ mn() const { return _##mn; } #define PROP_SET5(mn, typ) \ bas &mn(const typ &s) { \ _##mn = s; \ return (*this); \ } \ typ const &mn() const { return _##mn; } \ typ &mn() { return _##mn; } PROP_SET2(long) PROP_SET2(short) PROP_SET3(aliases, string_array) PROP_SET(examples) // PROP_SET(group) // PROP_SET(description) PROP_SET(desc_long) PROP_SET4(hidden, bool) PROP_SET4(required, bool) PROP_SET4(special, bool) PROP_SET4(no_non_special, bool) PROP_SET(hit_title) PROP_SET4(hit_count, int) PROP_SET4(hit_long, bool) PROP_SET4(hit_special, bool) PROP_SET4(hit_env, bool) bas &owner(cmd *o); [[nodiscard]] cmd const *owner() const; cmd *owner(); [[nodiscard]] cmd const *root() const; cmd *root(); [[nodiscard]] std::string dotted_key() const; #undef PROP_SET #undef PROP_SET2 #undef PROP_SET3 #undef PROP_SET4 public: bas &update_hit_count(std::string const &hit_title, int inc_hit_count = 1, bool is_long = false, bool is_special = false) { _hit_title = hit_title; _hit_count += inc_hit_count; _hit_long = is_long; _hit_special = is_special; return (*this); } bas &update_hit_count_from_env(std::string const &env_var_name, int inc_hit_count = 1) { _hit_title = env_var_name; _hit_count += inc_hit_count; _hit_long = true; _hit_special = false; _hit_env = true; return (*this); } public: [[nodiscard]] virtual std::string title() const { std::stringstream ss; if (!_long.empty()) { ss << _long; } if (!_short.empty()) { if (ss.tellp() > 0) ss << ',' << ' '; ss << _short; } const auto *sp = " "; for (auto &x : _aliases) { if (ss.tellp() > 0) ss << ',' << sp, sp = ""; ss << x; } return ss.str(); } [[nodiscard]] virtual std::string descriptions() const { std::stringstream ss; ss << _description; return ss.str(); } bas &group(const_chars s) { if (s) _group = s; return (*this); } [[nodiscard]] virtual std::string group_name() const { std::stringstream ss; ss << _group; return ss.str(); } public: [[nodiscard]] std::string const &description() const { if (_description.empty()) return _desc_long; return _description; } // [[nodiscard]] std::string const &examples() const { // return _examples; // } bas &description(const_chars desc, const_chars long_desc = nullptr, const_chars examples = nullptr) { if (desc) _description = desc; if (long_desc) _desc_long = long_desc; if (examples) _examples = examples; return (*this); } bas &titles(const_chars title_long) { if (title_long) this->_long = title_long; return (*this); } // bas &titles(const_chars title_long, const_chars title_short) { // if (title_long) this->_long = title_long; // if (title_short) this->_short = title_short; // return (*this); // } template<typename... T> bas &titles(const_chars title_long, const_chars title_short, T... title_aliases) { if (title_long) this->_long = title_long; if (title_short) this->_short = title_short; #if _MSC_VER this->aliases(title_aliases...); #else if (sizeof...(title_aliases) > 0) { this->aliases(title_aliases...); } #endif // // must_print("%s\n", aliases...); // for (const_chars x : {aliases...}) { // this->_aliases.push_back(x); // } return (*this); } template<typename... T> bas &aliases(T... titles) { (this->_aliases.push_back(titles), ...); // if (sizeof...(title_aliases) > 0) { // // append_to_vector(_aliases, title_aliases...); // for (auto &&x : {title_aliases...}) { // this->_aliases.push_back(x); // } // } return (*this); } public: bool match(std::string const &str, int &len) { if (string::has_prefix(str, _long)) { len = (int) _long.length(); return true; } if (string::has_prefix(str, _short)) { len = (int) _short.length(); return true; } for (auto const &s : _aliases) { if (string::has_prefix(str, s)) { len = (int) s.length(); return true; } } return false; } }; // class bas inline bool bas::_alias_right_align = false; inline int bas::_minimal_tab_width{-1}; inline bool bas::_no_catch_cmdr_biz_error{false}; inline bool bas::_no_cmdr_ending{false}; inline bool bas::_no_tail_line{false}; inline bool bas::_longest_first = true; inline text::distance bas::_jaro_winkler_matching_threshold = 0.83; /** * @brief A flag, such as: '--help', .... */ class arg : public bas { public: typedef std::shared_ptr<vars::variable> var_type; protected: // support_types _default; var_type _default; string_array _env_vars; std::string _placeholder; std::string _toggle_group; // bool _required: 1; types::on_flag_hit _on_flag_hit; public: arg() : _default() {} ~arg() override = default; arg(const arg &o) : bas(o) { _copy(o); } arg &operator=(const arg &o) { if (this == &o) return *this; _copy(o); return (*this); } //arg(const arg &o) = delete; //arg &operator=(const arg &o) = delete; arg(arg &&o) noexcept = default; #if 1 template<typename... Args> explicit arg(Args &&...args) { _default = std::make_shared<vars::variable>(args...); } #else template<typename A, typename... Args, std::enable_if_t< std::is_constructible<vars::variable, A, Args...>::value && !std::is_same<std::decay_t<A>, arg>::value, int> = 0> explicit arg(A &&a0, Args &&...args) : _default(std::forward<A>(a0), std::forward<Args>(args)...) {} template<typename A, std::enable_if_t<!std::is_same<std::decay_t<A>, vars::variable>::value && !std::is_same<std::decay_t<A>, arg>::value, int> = 0> explicit arg(A &&v) : _default(std::forward<A>(v)) {} // explicit arg(vars::streamable_any &&v) // : _default(std::move(v)) {} #endif protected: void _copy(const arg &o) { bas::_copy(o); __COPY(_default); __COPY(_env_vars); __COPY(_placeholder); __COPY(_toggle_group); // __COPY(_required); __COPY(_on_flag_hit); } public: #undef PROP_SET #undef PROP_SET2 #undef PROP_SET3 #define PROP_SET(mn) \ arg &mn(const_chars s) { \ if (s) _##mn = s; \ return (*this); \ } \ std::string const &mn() const { return _##mn; } #define PROP_SET2(mn) \ arg &title_##mn(const_chars s) { \ if (s) _##mn = s; \ return (*this); \ } \ std::string const &title_##mn() const { return _##mn; } #define PROP_SET3(mn, typ) \ arg &mn(typ const &s) { \ _##mn = s; \ return (*this); \ } \ typ const &mn() const { return _##mn; } #define PROP_SET4(mn, typ) \ arg &mn(typ const &s) { \ _##mn = s; \ return (*this); \ } \ typ mn() const { return _##mn; } // PROP_SET3(env_vars, string_array) // PROP_SET(toggle_group) PROP_SET(placeholder) // PROP_SET4(required, bool) // PROP_SET(default) // PROP_SET3(on_flag_hit, auto) #undef PROP_SET #undef PROP_SET2 #undef PROP_SET3 #undef PROP_SET4 arg &on_flag_hit(types::on_flag_hit const &h) { _on_flag_hit = h; return (*this); } [[nodiscard]] auto const &on_flag_hit() const { return _on_flag_hit; } public: [[nodiscard]] std::string title() const override { std::stringstream ss; if (!bas::_long.empty()) { ss << '-' << '-' << bas::_long; if (!_placeholder.empty()) { ss << '=' << _placeholder; } } if (!bas::_short.empty()) { if (ss.tellp() > 0) ss << ',' << ' '; ss << '-' << bas::_short; } const auto *sp = " "; for (auto &x : bas::_aliases) { if (ss.tellp() > 0) ss << ',' << sp, sp = ""; ss << '-' << '-' << x; } return ss.str(); } [[nodiscard]] std::string descriptions() const override { std::stringstream ss; ss << bas::_description; return ss.str(); } [[nodiscard]] std::string group_name() const override { std::stringstream ss; if (bas::_group.empty()) ss << _toggle_group; else ss << bas::_group; return ss.str(); } public: [[nodiscard]] virtual std::string defaults() const; [[nodiscard]] const var_type &default_value() const; var_type &default_value(); [[nodiscard]] virtual const std::string &toggle_group_name() const { return _toggle_group; } [[nodiscard]] virtual bool is_toggleable() const { return !_toggle_group.empty(); } public: arg &default_value(const vars::variable &v); arg &default_value(const_chars v); template<class T> arg &default_value(T const &v); arg &toggle_group(const_chars s) { if (s) _toggle_group = s; if (!bas::_group.empty()) bas::_group = _toggle_group; return (*this); } template<typename... T> arg &env_vars(T... args) { (this->_env_vars.push_back(args), ...); return (*this); } [[nodiscard]] const string_array &env_vars_get() const { return _env_vars; } public: // static vars::variable parse(std::string& s){ // _default.parse(s); // } }; // class arg } // namespace cmdr::opt #endif //CMDR_CXX11_CMDR_ARG_HH
29.523256
131
0.475318
hedzr
5de7117165ec3d6ede9af874228919bbbc058b66
1,235
cpp
C++
src/coordinates/cartesian.cpp
mattstvan/arc
1e86947ba70bacd718dcbecbe08b5d4242fe8117
[ "MIT" ]
null
null
null
src/coordinates/cartesian.cpp
mattstvan/arc
1e86947ba70bacd718dcbecbe08b5d4242fe8117
[ "MIT" ]
null
null
null
src/coordinates/cartesian.cpp
mattstvan/arc
1e86947ba70bacd718dcbecbe08b5d4242fe8117
[ "MIT" ]
1
2022-03-31T02:27:33.000Z
2022-03-31T02:27:33.000Z
#include <cartesian.h> #include <keplerian.h> #include <iostream> /* Cartesian base class methods */ // Default constructor Cartesian::Cartesian() { this->central_body = SUN; this->epoch = DateTime{}; this->position = Vector3{}; this->velocity = Vector3{}; } // Direct constructor Cartesian::Cartesian(CelestialBody& body, DateTime& epoch, Vector3& pos, Vector3& vel) { this->central_body = body; this->epoch = epoch; this->position = pos; this->velocity = vel; } // Constructor from KeplerianElements Cartesian::Cartesian(KeplerianElements& el) { this->central_body = el.central_body; this->epoch = el.epoch; // Compute PQW Position vector Vector3 r_pqw = Vector3{ cos(el.v), sin(el.v), 0.0 }.scale( (el.a * (1.0 - pow(el.e, 2.0))) / (1.0 + el.e * cos(el.v))); // Compute PQW Velocity vector Vector3 v_pqw = Vector3{ sin(-el.v), el.e + cos(el.v), 0.0 }.scale( sqrt(el.central_body.mu / (el.a * pow(1.0 - el.e, 2.0)))); // Rotate PQW Position Vector3 r_final = r_pqw.rot_z(-el.w).rot_x(-el.i).rot_z(-el.o); // Rotate PQW Velocity Vector3 v_final = v_pqw.rot_z(-el.w).rot_x(-el.i).rot_z(-el.o); // Set final position/velocity this->position = r_final; this->velocity = v_final; }
28.068182
72
0.659109
mattstvan
5deb3d98e1445a4b7457cefe314cfea841600665
1,720
cpp
C++
puzzle_app/src/states/MainMenu.cpp
SzyJ/CSC8501_15-Puzzle
6dc3795a425ffc5f5f86c6777d12e63a12d390cb
[ "MIT" ]
null
null
null
puzzle_app/src/states/MainMenu.cpp
SzyJ/CSC8501_15-Puzzle
6dc3795a425ffc5f5f86c6777d12e63a12d390cb
[ "MIT" ]
null
null
null
puzzle_app/src/states/MainMenu.cpp
SzyJ/CSC8501_15-Puzzle
6dc3795a425ffc5f5f86c6777d12e63a12d390cb
[ "MIT" ]
null
null
null
// Author: Szymon Jackiewicz // // Project: puzzle_app // File: MainMenu.cpp // Date: 25/10/2019 #include "MainMenu.h" #include "fsm/Controller.h" #include "Utils/Color.h" #include "Utils/Console.h" #include <iostream> namespace screen { MainMenu::MainMenu() { const char* m_MenuOptions[] = { "Generate random grid", "Create a custom grid", " Load from file ", " Exit " }; m_MainMenu = new WinTUI::Menu(m_MenuOptions, 4); m_MainMenu->SetSelectedBefore([](std::ostream& ostream) { ostream << "* "; WinTUI::Color::SetConsoleColor(WTUI_LIGHT_GREEN); }); m_MainMenu->SetSelectedAfter([](std::ostream& ostream) { WinTUI::Color::ResetConsoleColor(); ostream << " *"; }); m_MainMenu->SetUnselectedBefore([](std::ostream& ostream) { ostream << " "; }); m_MainMenu->SetUnselectedAfter([](std::ostream& ostream) { ostream << " "; }); } MainMenu::~MainMenu() { delete m_MainMenu; } void MainMenu::OnEnter() { m_MainMenu->Show(std::cout); switch (m_MainMenu->GetLastSelected()) { case random: fsm::Controller::Get().GoTo(fsm::States::RandomGrid); break; case build: fsm::Controller::Get().GoTo(fsm::States::GridBuilder); break; case load: fsm::Controller::Get().GoTo(fsm::States::GridLoader); break; case exit: default: break; } } void MainMenu::OnExit() { WinTUI::Console::ClearScreen(); } }
23.561644
67
0.522093
SzyJ
5debebdd343473205354092d49b9d7b56d21f652
34
hpp
C++
tests/var_reference/totally_unused.hpp
selat/headless
a4c3342a8ac32fc219d872c8adf3042e7c7299a1
[ "WTFPL" ]
null
null
null
tests/var_reference/totally_unused.hpp
selat/headless
a4c3342a8ac32fc219d872c8adf3042e7c7299a1
[ "WTFPL" ]
null
null
null
tests/var_reference/totally_unused.hpp
selat/headless
a4c3342a8ac32fc219d872c8adf3042e7c7299a1
[ "WTFPL" ]
null
null
null
#pragma once void unused_func();
8.5
19
0.735294
selat
5dee6f6efeec62437b7290bcc93f8b0edcfa27e2
9,403
hpp
C++
bitsplatform/src/include/bitsplatform.hpp
mini-game-token/mgt.contracts
4dc17dcff9efc29cd2237154c718669d5277d48f
[ "MIT" ]
5
2019-01-07T05:07:12.000Z
2019-07-31T07:57:40.000Z
bitsplatform/src/include/bitsplatform.hpp
mini-game-token/mgt.contracts
4dc17dcff9efc29cd2237154c718669d5277d48f
[ "MIT" ]
null
null
null
bitsplatform/src/include/bitsplatform.hpp
mini-game-token/mgt.contracts
4dc17dcff9efc29cd2237154c718669d5277d48f
[ "MIT" ]
3
2019-01-07T08:38:58.000Z
2019-07-30T06:46:10.000Z
#pragma once #include <eosiolib/eosio.hpp> #include <eosiolib/asset.hpp> #include <eosiolib/transaction.hpp> #include "game.hpp" #include "user.hpp" #include "global.hpp" #include "data.hpp" #include "token/token_stats.hpp" #include "token/token_balance.hpp" #include "referrer/ref_status.hpp" #include "consume/con_status.hpp" #include "bonus/bon_status.hpp" #include <string> using namespace eosio; namespace egame { class [[eosio::contract("bitsplatform")]] platform : public contract { private: user_index _users; game_index _games; bits_global_singleton _global_table; global _global; uint32_t _sys_precision; global get_default_state() { global g; return g; } bool check_point(); /*****token*****/ void sub_balance( name owner, asset value ); void add_balance( name owner, asset value, name ram_payer ); /*****token end*****/ /*****referrer*****/ RefStatusSingleton _ref_status_table; RefStatus _ref_status; RefStatus get_default_ref_status() { RefStatus rs; uint32_t s[3] = {0, 15, 65}; uint32_t g[3] = {5, 10, 20}; string t[3] = {"初来乍到", "略有小成", "傲视群雄"}; rs.standards.insert( rs.standards.begin(), s, s+3 ); rs.gift_tokens.insert( rs.gift_tokens.begin(), g, g+3 ); rs.titles.insert( rs.titles.begin(), t, t+3 ); auto refPool = asset( 60000000000, MGT ); rs.SetPool( refPool ); rs.first_recharge_reward = asset( 100000, MGT ); return rs; } void bind_referrer( name user, name ref ); /** * Perform referrer rewards * @pre user the user account name * @pre type the reward type,0 first charge,1 consume * @pre amount the SYS amount */ void reward_referrer( name user, uint8_t type = 0, int64_t amount = 0 ); /*****referrer end*****/ /*****consume*****/ ConsumeStatusSingleton _con_status_table; ConsumeStatus _con_status; ConsumeStatus get_default_consume_status() { ConsumeStatus cs; auto conPool = asset( 240000000000, MGT ); cs.SetPool( conPool ); cs.first_recharge_reward = asset( 100000, MGT ); return cs; } /** * Perform consumer rewards * @pre user the user account name * @pre type the reward type,0 first charge,1 consume * @pre amount the SYS amount */ void reward_consume( name user, uint8_t type = 0, int64_t amount = 0 ); /*****consume end*****/ /*****bonus*****/ BonusStatus _bon_status; BonusStatusSingleton _bon_status_table; BonusStatus get_default_bonus_status() { BonusStatus bs; bs.min_start = asset( 50000, POINT ); bs.bonus_pool.symbol = POINT; bs.min_start_rate = 5; bs.pool_rate = 50; //bs.min_interval = 24; return bs; } void add_point( asset fee ); void check_bonus(); void clear_bonus_record(); void loop_bonus(); asset calc_income( asset& income ); bool check_supply_rate( const TokenStat& ts ); const TokenStat& get_token_stat( const symbol& sym ); /*****bonus end*****/ public: platform( name receiver, name code, datastream<const char*> ds ); ~platform() { _global_table.set( _global, _self ); _ref_status_table.set( _ref_status, _self ); _con_status_table.set( _con_status, _self ); _bon_status_table.set( _bon_status, _self ); } /*****deposit/withdraw*****/ ACTION deposit( name from, name to, asset quantity, string memo ); ACTION withdraw( const name& to, const asset& quantity ); /*****deposit/withdraw end*****/ /*****Platform management*****/ ACTION settle( const name& game, const uint64_t table, const vector<settlement>& data ); ACTION gamenter( const name& gname, const vector<name>& users, const uint64_t table ); ACTION updateuser( const name& u, const string& nickname, const uint8_t gender, const uint32_t head); ACTION addgame( const game& g); ACTION updategame( const game& g); ACTION delgame( const name& game_name ); ACTION lockuser( const name& gname, const vector<name> users ); ACTION pause(); ACTION open(); ACTION reset(); ACTION claimincome( const name& to, const asset& quantity ); void OnError( const onerror& error ); /*****Platform management end*****/ /*****Token management*****/ ACTION create( name issuer, asset maximum_supply, int16_t team ); ACTION issue( name to, asset quantity, string memo ); ACTION retire( asset quantity, string memo ); ACTION transfer( name from, name to, asset quantity, string memo ); ACTION claim( name to, asset quantity ); ACTION closetoken( name owner, const asset& symbol ); /*****Token management end*****/ /*****referrer*****/ ACTION bindref( name user, name ref ); ACTION addrefpool( name& user, asset& value ); /*****referrer end*****/ /*****consume*****/ ACTION reward( const name& game_name, const name& user, const int64_t amount, const name& ref ); ACTION addconpool( name& user, asset& value ); /*****consume end*****/ /*****bonus*****/ ACTION bonus(); ACTION clearbon(); ACTION bonusout( asset total, const vector<bonusitem>& data ); /*****bonus end*****/ public: static const user& GetUser( const name& tokenContractAccount, const name& account ) { user_index users( tokenContractAccount, tokenContractAccount.value ); const auto& acc = users.get( account.value, "unable to find account" ); return acc; } static const user FindUser( const name& tokenContractAccount, const name& account ) { user_index users( tokenContractAccount, tokenContractAccount.value ); user u; auto aitr = users.find( account.value ); if( aitr != users.end() ) { u = *aitr; } return u; } static const game& GetGame( const name& tokenContractAccount, const name& game ) { game_index games( tokenContractAccount, tokenContractAccount.value ); return games.get( game.value, "unable to find game" ); } static void CheckUser( const name& tokenContractAccount, const name& account ) { user_index users( tokenContractAccount, tokenContractAccount.value ); auto itr = users.find( account.value ); eosio_assert( itr != users.end(), "unknown account" ); eosio_assert( itr->status == 0, "this account has been locked" ); eosio_assert( itr->game_id.value == 0, "already in the game" ); } static bool CheckUserPoint( const name& tokenContractAccount, const name& account, const game& game ) { user_index users( tokenContractAccount, tokenContractAccount.value ); auto uItr = users.find( account.value ); if( uItr != users.end() ) { auto minpoint = max( game.min_point, game.fee_fixed ); return uItr->point >= minpoint; } return false; } static bool IsChinese(const string& str) { bool chinese = true; for(int i = 0; i < str.length(); i++){ if(str[i] >= 0){ chinese = false; break; } } if(chinese) { return str.length() >= 6 && str.length() <= 24; } return chinese; } static bool IsWord(const string& str) { if(str.length() == 0) return false; char c = str.at(0); if(c >= '0' && c <= '9') return false; bool word = true; for(int i = 0; i < str.length(); i++) { c = str.at(i); if( !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) ) { word = false; break; } } if(word) { return str.length() >= 3 && str.length() <= 12; } return word; } /*****token*****/ static asset GetSupply( name tokenContractAccount, symbol_code symCode ) { tokenStats statstable( tokenContractAccount, symCode.raw() ); const auto& st = statstable.get( symCode.raw() ); return st.supply; } static asset GetBalance( name tokenContractAccount, name owner, symbol_code symCode ) { balances accountstable( tokenContractAccount, owner.value ); const auto& ac = accountstable.get( symCode.raw() ); return ac.balance; } /*****token end*****/ }; }
35.483019
112
0.544294
mini-game-token
5defda2d0bbb08af8ca0eebb721a6212a28e7d0c
1,612
hpp
C++
src/GameObjects/DrawableGameObjects/melee.hpp
PierrickLP/PopHead
0c2ddd6d737f556b3f74b91b937b023c8e8010f0
[ "MIT" ]
null
null
null
src/GameObjects/DrawableGameObjects/melee.hpp
PierrickLP/PopHead
0c2ddd6d737f556b3f74b91b937b023c8e8010f0
[ "MIT" ]
null
null
null
src/GameObjects/DrawableGameObjects/melee.hpp
PierrickLP/PopHead
0c2ddd6d737f556b3f74b91b937b023c8e8010f0
[ "MIT" ]
null
null
null
#pragma once #include "GameObjects/GameObject.hpp" #include <array> namespace ph{ class GameData; class Character; class CollisionBody; class Swing { public: Swing(const GameObject& nodeWithAttackableObjects, const sf::Vector2f position, const float damage, const float range, const float rotationRange, float attackAngle); private: void handleHitCharacters(); sf::Vector2f nearestPointOfCharacter(const Character& character) const; float angleOfPointToStart(sf::Vector2f point) const; auto getAttackableCharactersInHitArea() const -> std::vector<Character*>; bool isAngleInAttackRange(float angle) const; static float getFixedAngle(float angle); private: const GameObject& mNodeWithAttackableObjects; const sf::Vector2f mStartPosition; const float mDamage; const float mRange; const float mRotationRange; float mRotation; float mAttackAngle; }; class MeleeWeapon : public GameObject { public: MeleeWeapon(GameData* const, const float damage, const float range, const float rotationRange); void updateCurrent(const sf::Time delta) override; void drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const override; void attack(const sf::Vector2f attackDirection, float attackRotation); private: float getStartAttackRotation(const sf::Vector2f attackDirection) const; sf::Vector2f getRightHandLocalPosition(const sf::Vector2f attackDirection); private: sf::Sprite mSprite; GameData* const mGameData; const float mDamage; const float mRange; const float mRotationRange; float mRotationFromStart; bool mShouldBeDrawn; CollisionBody* mEndOfMelle = nullptr; }; }
26
96
0.797767
PierrickLP
5df019b7c224b97990c91adf33184ec8f531dbc3
3,288
cpp
C++
src/Backends/DirectX12/src/input_attachment_mapping.cpp
jayrulez/LiteFX
482480fee96dd80c73356cd6898ea0e0544ac09d
[ "MIT" ]
8
2021-06-23T09:04:10.000Z
2022-02-06T19:01:21.000Z
src/Backends/DirectX12/src/input_attachment_mapping.cpp
jayrulez/LiteFX
482480fee96dd80c73356cd6898ea0e0544ac09d
[ "MIT" ]
29
2021-06-23T13:59:54.000Z
2021-08-03T14:12:59.000Z
src/Backends/DirectX12/src/input_attachment_mapping.cpp
jayrulez/LiteFX
482480fee96dd80c73356cd6898ea0e0544ac09d
[ "MIT" ]
1
2021-10-30T18:44:02.000Z
2021-10-30T18:44:02.000Z
#include <litefx/backends/dx12.hpp> using namespace LiteFX::Rendering::Backends; // ------------------------------------------------------------------------------------------------ // Implementation. // ------------------------------------------------------------------------------------------------ class DirectX12InputAttachmentMapping::DirectX12InputAttachmentMappingImpl : public Implement<DirectX12InputAttachmentMapping> { public: friend class DirectX12InputAttachmentMapping; private: const DirectX12RenderPass* m_renderPass; RenderTarget m_renderTarget; UInt32 m_location; public: DirectX12InputAttachmentMappingImpl(DirectX12InputAttachmentMapping* parent, const DirectX12RenderPass* renderPass, const RenderTarget& renderTarget, const UInt32& location) : base(parent), m_renderPass(renderPass), m_location(location), m_renderTarget(renderTarget) { } }; // ------------------------------------------------------------------------------------------------ // Interface. // ------------------------------------------------------------------------------------------------ DirectX12InputAttachmentMapping::DirectX12InputAttachmentMapping() noexcept : m_impl(makePimpl<DirectX12InputAttachmentMappingImpl>(this, nullptr, RenderTarget {}, 0)) { } DirectX12InputAttachmentMapping::DirectX12InputAttachmentMapping(const DirectX12RenderPass& renderPass, const RenderTarget& renderTarget, const UInt32& location) : m_impl(makePimpl<DirectX12InputAttachmentMappingImpl>(this, &renderPass, renderTarget, location)) { } DirectX12InputAttachmentMapping::DirectX12InputAttachmentMapping(const DirectX12InputAttachmentMapping& _other) noexcept : m_impl(makePimpl<DirectX12InputAttachmentMappingImpl>(this, _other.m_impl->m_renderPass, _other.m_impl->m_renderTarget, _other.m_impl->m_location)) { } DirectX12InputAttachmentMapping::DirectX12InputAttachmentMapping(DirectX12InputAttachmentMapping&& _other) noexcept : m_impl(makePimpl<DirectX12InputAttachmentMappingImpl>(this, std::move(_other.m_impl->m_renderPass), std::move(_other.m_impl->m_renderTarget), std::move(_other.m_impl->m_location))) { } DirectX12InputAttachmentMapping::~DirectX12InputAttachmentMapping() noexcept = default; DirectX12InputAttachmentMapping& DirectX12InputAttachmentMapping::operator=(const DirectX12InputAttachmentMapping& _other) noexcept { m_impl->m_renderPass = _other.m_impl->m_renderPass; m_impl->m_renderTarget = _other.m_impl->m_renderTarget; m_impl->m_location = _other.m_impl->m_location; return *this; } DirectX12InputAttachmentMapping& DirectX12InputAttachmentMapping::operator=(DirectX12InputAttachmentMapping&& _other) noexcept { m_impl->m_renderPass = std::move(_other.m_impl->m_renderPass); m_impl->m_renderTarget = std::move(_other.m_impl->m_renderTarget); m_impl->m_location = std::move(_other.m_impl->m_location); return *this; } const DirectX12RenderPass* DirectX12InputAttachmentMapping::inputAttachmentSource() const noexcept { return m_impl->m_renderPass; } const UInt32& DirectX12InputAttachmentMapping::location() const noexcept { return m_impl->m_location; } const RenderTarget& DirectX12InputAttachmentMapping::renderTarget() const noexcept { return m_impl->m_renderTarget; }
40.097561
184
0.711679
jayrulez
5df1aabf1882c084dd350b054f0f9c9625af7fc9
372
cpp
C++
blink/src/main.cpp
snakeye/stm32-projects
ed20e723dc1e50111c6b547fc142665b7db7843b
[ "MIT" ]
null
null
null
blink/src/main.cpp
snakeye/stm32-projects
ed20e723dc1e50111c6b547fc142665b7db7843b
[ "MIT" ]
null
null
null
blink/src/main.cpp
snakeye/stm32-projects
ed20e723dc1e50111c6b547fc142665b7db7843b
[ "MIT" ]
null
null
null
#include <Arduino.h> void setup() { pinMode(LED_BUILTIN, OUTPUT); } void loop() { digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second }
26.571429
83
0.596774
snakeye
5df3b02bbe6e4fff2bd9bc48cc09912b1f0aa72e
410
cpp
C++
0746. Min Cost Climbing Stairs/solution_dp.cpp
Pluto-Zy/LeetCode
3bb39fc5c000b344fd8727883b095943bd29c247
[ "MIT" ]
null
null
null
0746. Min Cost Climbing Stairs/solution_dp.cpp
Pluto-Zy/LeetCode
3bb39fc5c000b344fd8727883b095943bd29c247
[ "MIT" ]
null
null
null
0746. Min Cost Climbing Stairs/solution_dp.cpp
Pluto-Zy/LeetCode
3bb39fc5c000b344fd8727883b095943bd29c247
[ "MIT" ]
null
null
null
class Solution { public: int minCostClimbingStairs(vector<int>& cost) { // dp[i]: 爬到第 i 级阶梯的最小体力消耗 // dp[i] = min(dp[i - 1] + cost[i - 1], dp[i - 2] + cost[i - 2]) // dp[0] = 0, dp[1] = 0 int dp_0 = 0, dp_1 = 0; for (int i = 1; i < cost.size(); ++i) { int dp_temp = std::min(dp_1 + cost[i], dp_0 + cost[i - 1]); dp_0 = dp_1; dp_1 = dp_temp; } return dp_1; } };
27.333333
68
0.492683
Pluto-Zy
5df4cb55568837e4362bf0938ebb8ff14cd10709
7,333
cpp
C++
6_TSP/src/controlador.cpp
eduherminio/Academic_ArtificialIntelligence
f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f
[ "MIT" ]
3
2017-05-16T22:25:16.000Z
2019-05-07T16:12:21.000Z
6_TSP/src/controlador.cpp
eduherminio/Academic_ArtificialIntelligence
f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f
[ "MIT" ]
null
null
null
6_TSP/src/controlador.cpp
eduherminio/Academic_ArtificialIntelligence
f0ec4d35cef64a1bf6841ea7ecf1d33017b3745f
[ "MIT" ]
null
null
null
#include "../header/controlador.h" // #include "../header/dialogo_fichero_windows.h" #include "../header/dialogo_fichero_linux.h" #include "../header/recocido_simulado_tsp.h" #include <thread> namespace controlador { void Controlador::registra_observadores() { Observador<Evento_Vista>& observador_vista = vista.get_observador(); observador_vista.registra_observador(Evento_Vista::ejecutar, std::bind(&Controlador::ejecuta_sa_tsp, this)); // Puntero a función: cuando Evento_Vista ejecutar, el controlador se va a ejecuta_sa_tsp observador_vista.registra_observador(Evento_Vista::cargar, std::bind(&Controlador::carga_problema_tsplib, this)); observador_vista.registra_observador(Evento_Vista::detener, std::bind(&Controlador::detiene_sa_tsp, this)); observador_vista.registra_observador(Evento_Vista::iniciar_programa, std::bind(&Controlador::inicia_programa, this)); observador_vista.registra_observador(Evento_Vista::finalizar_programa, std::bind(&Controlador::finaliza_programa, this)); Observador<Evento_Modelo>& observador_modelo = algoritmo_sa_tsp.get_observador(); observador_modelo.registra_observador(Evento_Modelo::nuevo_recorrido, std::bind(&Controlador::push_datos, this)); // Coge datos del modelo y se los pasa a la vista } bool Controlador::carga_problema_tsplib() { std::string fichero_tsp; if (lee_nombre_fichero(fichero_tsp)) { ciudades::Ciudades ciudades; ciudades.carga_ciudades(fichero_tsp, num_ciudades); //Carga el vector de coordenadas y la matriz de distancias if (set_coordenadas_visualizacion(ciudades)) { vista.set_recorrido_optimo(ciudades.get_recorrido_optimo()); vista.set_texto_distancia_optima("Optimum : " + parche::to_string(ciudades.calcula_distancia(ciudades.get_recorrido_optimo()))); vista.set_texto_iteracion(""); vista.set_texto_mejor_distancia(""); ruta.inicializa_ruta(std::move(ciudades)); //Eliminar la llamada de inicializacion // algoritmo_sa_tsp.inicializacion(num_descensos,num_permutaciones,num_exitos_maximo,temperatura,factor_descenso); vista.muestra_boton_ejecutar(); return true; } } return false; } void Controlador::inicia_programa() { inicio_vista = true; //La vista nos garantiza que todos sus recursos están listos } void Controlador::finaliza_programa() { fin_vista = true; detiene_sa_tsp(); c_v_barrera_tsp.notify_one(); //Desbloqueamos hilo ejecutar para acabar el programa while (!fin_hilos); //Nos aseguramos que los hilos tsp y datos han finalizado while (!fin_algoritmo); } void Controlador::ejecuta_sa_tsp() { std::unique_lock<std::mutex>u_l(barrera_tsp); //Bloqueamos añadir nuevo recorrido vista.oculta_boton_cargar(); vista.oculta_boton_ejecutar(); vista.muestra_boton_detener(); inicio_algoritmo = true; c_v_barrera_tsp.notify_one(); //Desbloqueamos hilo ejecutar() } void Controlador::detiene_sa_tsp() { algoritmo_sa_tsp.detener(); while (!fin_algoritmo); vacia_datos(); } void Controlador::ejecutar() { //Estas dimensiones podrian ser leidas desde un fichero de configuracion //o elegidas por linea de comandos const unsigned ancho = 960; //Dimensiones de la ventana const unsigned alto = 720; const unsigned ancho_panel = 250; //Lanzamos el hilo vista hilo_vista = std::thread(&Vista::ejecutar, &vista, ancho, alto, ancho_panel); inicio_vista = false; while (!inicio_vista); //Esperamos a que la vista este inicializada fin_vista = false; //&Recocido_simulado_TSP::set_v_lookup_table(); while (!fin_vista) { // Bloqueamos ///////////////// std::unique_lock<std::mutex>u_l(barrera_tsp); vista.oculta_boton_detener(); vista.oculta_boton_ejecutar(); vista.muestra_boton_cargar(); inicio_algoritmo = false; //Se pone a true al pulsar boton_cargar() while (!inicio_algoritmo && !fin_vista) //fin_vista se pone a true al matar la ventana de la vista c_v_barrera_tsp.wait(u_l); //Esperamos hasta que se inicie un TSP o finalicemos la vista ////////////////////////////////////////////////////////////////// fin_hilos = false; if (!fin_vista) { hilo_cola_datos = std::thread(&Controlador::pop_datos, this); fin_algoritmo = false; hilo_modelo = std::thread(&Recocido_simulado_TSP::ejecutar, &algoritmo_sa_tsp, std::ref(ruta), std::ref(num_ciudades)); if (hilo_modelo.joinable()) hilo_modelo.join(); fin_algoritmo = true; c_v_barrera_datos.notify_one(); //Desbloqueamos el hilo pop_datos() if (hilo_cola_datos.joinable()) hilo_cola_datos.join(); } fin_algoritmo = true; fin_hilos = true; } if (hilo_vista.joinable()) { hilo_vista.join(); } } void Controlador::push_datos() { std::unique_lock<std::mutex>u_l(barrera_datos); //Bloqueamos eliminar recorrido datos.push({ algoritmo_sa_tsp.get_recorrido(),algoritmo_sa_tsp.get_mejor_distancia(),algoritmo_sa_tsp.get_iteracion_actual() }); c_v_barrera_datos.notify_one(); } void Controlador::pop_datos() { while (!fin_algoritmo) { std::unique_lock<std::mutex>u_l(barrera_datos); //Bloqueamos añadir nuevo recorrido while (datos.empty() && !fin_algoritmo) { c_v_barrera_datos.wait(u_l); } if (fin_algoritmo) { while (!datos.empty()) { auto dato = std::move(datos.front()); datos.pop(); vista.actualiza_recorrido(dato.recorrido, "Iterations: " + parche::to_string(dato.iteracion), "Distance: " + parche::to_string(dato.mejor_distancia)); } } else { auto dato = std::move(datos.front()); datos.pop(); u_l.unlock(); //Desbloqueamos lo antes posible vista.actualiza_recorrido(dato.recorrido, "Iterations: " + parche::to_string(dato.iteracion), "Distance: " + parche::to_string(dato.mejor_distancia)); } } } void Controlador::vacia_datos() { std::unique_lock<std::mutex>u_l(barrera_datos); //Bloqueamos while (!datos.empty()) //Vaciamos la cola de datos datos.pop(); } // Transfiere coordenadas desde la clase Ciudades a la clase Canvas bool Controlador::set_coordenadas_visualizacion(const ciudades::Ciudades& ciudades) { double x_min, x_max, y_min, y_max; ciudades.calcula_valores_extremos(x_min, x_max, y_min, y_max); if (x_min == x_max || y_min == y_max) //Las ciudades están en una vertical o en una horizontal { return false; //El problema es trivial y no tiene sentido buscar una solución } std::vector<std::pair<unsigned, unsigned>> coordenadas_canvas; //Coordenadas de las ciudades normalizadas a las dimensiones del CANVAS unsigned x_sup_izq, y_sup_izq, x_inf_der, y_inf_der; vista.get_rectangulo_canvas(x_sup_izq, y_sup_izq, x_inf_der, y_inf_der); double x, y; //coordenadas reales double xn, yn; //coordenadas reales normalizadas en [0,1] unsigned xv, yv; //coordenadas int ajustadas al espacio de visualizacion for (auto &p : ciudades.get_coordenadas()) { x = p.first; y = p.second; xn = (x - x_min) / (x_max - x_min); //No tenemos division por 0 al garantizarlo mas arriba yn = (y - y_min) / (y_max - y_min); xv = unsigned(x_sup_izq + xn * (x_inf_der - x_sup_izq)); yv = unsigned(y_sup_izq + yn * (y_inf_der - y_sup_izq)); coordenadas_canvas.push_back({ yv,xv }); //Coordenadas cambiadas } vista.set_coordenadas(coordenadas_canvas); return true; } }
36.123153
200
0.723033
eduherminio
5df8d0d00371160f0496f9f9e7a68c4f7c596196
5,181
cpp
C++
src/apt.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
7
2016-12-19T21:13:41.000Z
2021-03-19T11:14:29.000Z
src/apt.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
1
2017-06-17T12:14:08.000Z
2017-06-17T14:47:20.000Z
src/apt.cpp
feliwir/libapt
43b05b3de632896cb7d1351191a07c0f0cdf801a
[ "MIT" ]
3
2017-11-07T12:22:10.000Z
2020-04-30T20:48:59.000Z
#include <libapt/apt.hpp> #include <libapt/manager.hpp> #include "displayobject.hpp" #include "characters/character.hpp" #include "characters/movie.hpp" #include "characters/image.hpp" #include "characters/shape.hpp" #include "graphics/buffer.hpp" #include "util.hpp" #include "geometry.hpp" #include <iostream> using namespace libapt; Apt::Apt() { m_geomBuf = std::make_shared<Buffer>(); } Error Apt::LoadConst(const std::string name, std::shared_ptr<IFileProvider> fp) { unsigned int size = 0; const uint8_t* buffer = fp->LoadBinary(name + ".const", size); if (buffer == nullptr) return CONST_NF; Error err = m_const.Load(buffer, size); delete[] buffer; return err; } Error Apt::LoadDat(const std::string name, std::shared_ptr<IFileProvider> fp) { unsigned int size = 0; bool fail = false; const std::string text = fp->LoadText(name + ".dat",fail); if (fail) return CONST_NF; Error err = m_dat.Load(text); return err; } Error Apt::Load(const uint8_t *buffer, unsigned int size, std::shared_ptr<Manager> mngr, const std::string &name) { m_data = buffer; m_manager = mngr; //get the const file Error err = LoadConst(name,mngr->GetFileprovider()); if (err != NO_ERROR) return err; uint8_t *iter = const_cast<uint8_t *>(buffer); //Read the first 8 bytes std::string magic = readString(iter, 8); //Check if this is a valid Apt file if (magic != "Apt Data") return INVALID_APT; //Go back to start iter -= 0x08; iter += m_const.GetAptOffset(); auto ch = Character::Create(iter ,shared_from_this()); if (ch->GetType() != Character::MOVIE) { std::cout << "An apt MUST contain a movie as first character!" << std::endl; return MISSING_MOVIE; } auto m = std::dynamic_pointer_cast<Movie>(ch); uint32_t width = m->GetWidth(); uint32_t height = m->GetHeight(); //Import characters for (const auto& im : m->GetImports()) { auto& movieName = im.GetMovie(); auto ch = mngr->ImportCharacter(movieName, im.GetName()); m->SetCharacter(ch,im.GetCharacter()); } //Load data file LoadDat(name, mngr->GetFileprovider()); //Check all image and shape characters int id = 0; for (const auto& ch : m->GetCharacters()) { if (ch == nullptr) continue; if (ch->GetType() == Character::IMAGE) { auto im = std::dynamic_pointer_cast<Image>(ch); int imgId = im->GetImage(); Dat::Entry e = m_dat.GetEntry(imgId); int texId = 0; if (e.type == Dat::NO_BOUNDS) { texId = e.p1; } else { texId = imgId; } m_imageMap[imgId] = texId; if (m_textures[texId] != nullptr) continue; std::string texPath = "art/Textures/apt_" + name + "_" + std::to_string(texId) + ".tga"; auto tex = std::make_shared<Texture>(); uint32_t fSize = 0; const uint8_t* buffer = mngr->GetFileprovider()->LoadBinary(texPath,fSize); tex->Load(buffer, fSize); delete[] buffer; m_textures[texId] = tex; } else if (ch->GetType() == Character::SHAPE) { auto sh = std::dynamic_pointer_cast<Shape>(ch); int geoId = sh->GetGeometryId(); auto geom = std::make_shared<Geometry>(width,height); bool fail = false; err = NO_ERROR; std::string geomPath = name + "_geometry/" + std::to_string(geoId) + ".ru"; std::string data = mngr->GetFileprovider()->LoadText(geomPath,fail); if (!fail) { err = geom->Load(data); } else { std::cout << "Unable to load geometry file: " << geomPath << std::endl; } if (err != NO_ERROR) { return err; } else { sh->SetGeometry(geom); } m_geometries.push_back(geom); } } //set character of our display object m_movieclip = std::make_shared<DisplayObject>(); m_movieclip->SetCharacter(ch); m_movieclip->SetName("_root"); //compile all geometries for (const auto& g : m_geometries) { g->Compile(shared_from_this()); } m_geomBuf->Finalize(); return NO_ERROR; } std::shared_ptr<Character> Apt::GetExport(const std::string& name) { auto m = std::dynamic_pointer_cast<Movie>(m_movieclip->GetCharacter()); const auto& exports = m->GetExports(); for (const auto& ex : exports) { if (ex.GetName() == name) { return m->GetCharacter(ex.GetCharacter()); } } return nullptr; } void Apt::Render() { m_movieclip->SetFocus(nullptr); m_movieclip->Render(Transformation()); } std::vector<std::shared_ptr<Character>> Apt::GetCharacters() { auto m = std::dynamic_pointer_cast<Movie>(m_movieclip->GetCharacter()); return m->GetCharacters(); } Apt::~Apt() { delete[] m_data; } std::shared_ptr<Texture> Apt::GetTexture(int id) { int texId = m_imageMap[id]; return m_textures[texId]; } uint32_t Apt::GetWidth() { auto m = std::dynamic_pointer_cast<Movie>(m_movieclip->GetCharacter()); return m->GetWidth(); } uint32_t Apt::GetHeight() { auto m = std::dynamic_pointer_cast<Movie>(m_movieclip->GetCharacter()); return m->GetHeight(); } Const::Entry Apt::GetConstant(uint32_t index) { return m_const.GetItem(index); } std::shared_ptr<Character> Apt::GetCharacter(uint32_t id) { auto m = std::dynamic_pointer_cast<Movie>(m_movieclip->GetCharacter()); return m->GetCharacters()[id]; } const bool Apt::HasResized() { return m_manager->HasResized(); }
22.428571
113
0.669948
feliwir
5dfb39659edd6b8b09b906fcd0aa1a236a928630
1,749
hpp
C++
include/cyp/tuple.hpp
ccharly/cyp
c79b972caa65b63e0369b0d06483221838f6ceaf
[ "MIT" ]
null
null
null
include/cyp/tuple.hpp
ccharly/cyp
c79b972caa65b63e0369b0d06483221838f6ceaf
[ "MIT" ]
null
null
null
include/cyp/tuple.hpp
ccharly/cyp
c79b972caa65b63e0369b0d06483221838f6ceaf
[ "MIT" ]
null
null
null
#ifndef CYP_TUPLE_HPP #define CYP_TUPLE_HPP #include <cyp/any.hpp> #include <cyp/static_operators.hpp> #include <utility> #include <vector> namespace cyp { template <typename... Types> class tuple : public std::tuple<Types...> { public: using std::tuple<Types...>::tuple; static constexpr int static_size = sizeof...(Types); public: cyp::any_ref operator[](std::size_t index) { std::vector<any_ref> refs; for_constexpr(*this, [&](auto x) { std::cout << "for: " << typeid(x).name() << std::endl; refs.emplace_back(x); }); return refs.at(index); } cyp::str __str__() const { auto comma = ""; cyp::str str; str += "("; for_constexpr(*this, [&](auto x) { str += comma; str += cyp::str(x); comma = ", "; }); str += ")"; return str; } template <typename Value> bool __contains__(Value const& v) const { return any_constexpr(*this, [&](auto x) { return cyp::__eq__(x, v); }); } template <typename... Types2> bool __eq__case(true_t, std::tuple<Types2...> const& other) const { return all_constexpr_i(*this, [&](auto, auto i) { return std::get<decltype(i)::value>(*this) == std::get<decltype(i)::value>(other); }); } template <typename... Types2> bool __eq__case(false_t, std::tuple<Types2...> const& other) const { (void)other; return false; } template <typename... Types2> bool __eq__(std::tuple<Types2...> const& other) const { return __eq__case(static_bool_t<sizeof...(Types) == sizeof...(Types2)>{}, other); } }; template <typename... Types> tuple<Types...> make_tuple(Types&&... args) { return tuple<Types...>(std::forward<Types>(args)...); } } #endif
23.013158
90
0.59291
ccharly
b90098ec49bf9acb6531b6832c98e7c99d43957d
1,431
cpp
C++
Luogu/P3956.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-09-11T13:17:28.000Z
2020-09-11T13:17:28.000Z
Luogu/P3956.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-10-22T13:36:23.000Z
2020-10-22T13:36:23.000Z
Luogu/P3956.cpp
Insouciant21/solution
8f241ec2076c9c29c0d39c2c285ee12eac1dee9e
[ "Apache-2.0" ]
1
2020-10-22T13:33:11.000Z
2020-10-22T13:33:11.000Z
/* * Problem: P3956 * Author: Insouciant21 * Time: 2020/9/10 19:28:39 * Status: Accepted */ #include <bits/stdc++.h> using namespace std; constexpr auto inf = 0x3f3f3f; int chess[110][110]; int best[110][110]; int movx[4] = {0, 1, 0, -1}, movy[4] = {1, 0, -1, 0}; int m, n; int ans = inf; void dfs(int x, int y, int color, bool magic, int coin) { if (x < 1 || y < 1 || x > m || y > m) return; if (coin >= best[x][y]) return; best[x][y] = coin; if (x == m && y == m) { ans = min(ans, coin); return; } for (int i = 0; i < 4; i++) { int nx = x + movx[i], ny = y + movy[i]; if (chess[nx][ny] != inf) { if (chess[nx][ny] == chess[x][y]) dfs(nx, ny, color, 0, coin); else dfs(nx, ny, chess[nx][ny], 0, coin + 1); } else if (!magic) { chess[nx][ny] = color; dfs(nx, ny, color, 1, coin + 2); chess[nx][ny] = inf; } } } int main() { ios::sync_with_stdio(0); cin >> m >> n; for (int i = 0; i < 110; i++) for (int j = 0; j < 110; j++) chess[i][j] = best[i][j] = inf; for (int i = 0; i < n; i++) { int x, y, c; cin >> x >> y >> c; chess[x][y] = c; } dfs(1, 1, chess[1][1], 0, 0); if (ans != inf) cout << ans << endl; else cout << -1 << endl; return 0; }
22.714286
57
0.422781
Insouciant21
b90168d25d570ea630acbb41fb0d92eb2dcd5eff
936
cpp
C++
Complex.cpp
zevoGet/fft
11bc7914cef4675aaf4cd42245fb337a26fe59e6
[ "BSD-3-Clause" ]
5
2018-12-24T02:10:08.000Z
2019-10-19T13:36:56.000Z
Complex.cpp
zevoGet/fft
11bc7914cef4675aaf4cd42245fb337a26fe59e6
[ "BSD-3-Clause" ]
null
null
null
Complex.cpp
zevoGet/fft
11bc7914cef4675aaf4cd42245fb337a26fe59e6
[ "BSD-3-Clause" ]
1
2019-10-10T11:07:47.000Z
2019-10-10T11:07:47.000Z
#include "Complex.h" #include<cmath> #include <stdio.h> void Complexf::setReal(float real1){ real = real1; }; void Complexf::setIm(float im1){ im = im1; }; float Complexf::getReal(){ return real; }; float Complexf::getIm(){ return im; }; void Complexf::operator +=(Complexf c1){ real = real + c1.getReal(); im = im + c1.getIm(); }; void Complexf::operator *=(Complexf c1){ temp = real; real = real * c1.getReal() - im * c1.getIm(); im = temp * c1.getIm() + im * c1.getReal(); }; void Complexf::show(){ printf("\n.....%f%f\n",real,im);; } float Complexf::getA(){ return real; } void Complexf::setData(Complexf c1){ real = c1.getReal(); im = c1.getIm(); } void Complexf::toStrings(){ real = -real; im = -im; } float Complexf::abs(){ return sqrt(real * real + im * im); } void Complexf::init(){ real = 0; im = 0; }
17.333333
48
0.550214
zevoGet
b9054ec88da477cf37d588c582328f6b16f9e867
1,890
hpp
C++
src/Tests/CoreTests/Tests.hpp
sylvaindeker/Radium-Engine
64164a258b3f7864c73a07c070e49b7138488d62
[ "Apache-2.0" ]
1
2018-04-16T13:55:45.000Z
2018-04-16T13:55:45.000Z
src/Tests/CoreTests/Tests.hpp
sylvaindeker/Radium-Engine
64164a258b3f7864c73a07c070e49b7138488d62
[ "Apache-2.0" ]
null
null
null
src/Tests/CoreTests/Tests.hpp
sylvaindeker/Radium-Engine
64164a258b3f7864c73a07c070e49b7138488d62
[ "Apache-2.0" ]
null
null
null
#ifndef RADIUM_TESTS_HPP_ #define RADIUM_TESTS_HPP_ #include <Core/CoreMacros.hpp> #include <Tests/CoreTests/Manager.hpp> namespace RaTests { /// Base class for all tests. class Test { public: Test() { if ( !TestManager::getInstance() ) { TestManager::createInstance(); } TestManager::getInstance()->add( this ); } virtual void run() = 0; virtual ~Test(){}; }; // Poor man's singleton to automatically instantiate a test. #define RA_TEST_CLASS( TYPE ) \ namespace TYPE##NS { \ TYPE test_instance; \ } /// This macro is similar to "CORE_ASSERT" but will print a message if /// the test condition is false and signal it to the test manager. #define RA_UNIT_TEST( EXP, DESC ) \ MACRO_START \ if ( !( EXP ) ) \ { \ fprintf( stderr, "[TEST FAILED] : %s:%i: `%s` : %s \n", __FILE__, __LINE__, #EXP, DESC ); \ RaTests::TestManager::getInstance()->testFailed( this ); \ } else \ { fprintf( stdout, "[TEST PASSED]\n" ); } \ MACRO_END /// A test that always pass. class DummyTestPass : public Test { virtual void run() override { RA_UNIT_TEST( true, "Dummy test pass." ); } }; /// A test that always fails. class DummyTestFail : public Test { virtual void run() override { RA_UNIT_TEST( false, "Dummy test fail." ); } }; } // namespace RaTests #endif // RADIUM_TESTS_HPP_
36.346154
99
0.462434
sylvaindeker
b90827ea8435073322f2b8a9b8667326f1ef4731
1,858
cpp
C++
theoraplayer/src/theoraplayer.cpp
tonysergi/theoraplayer
5fe4bb2a77004bba67b8f7afd2441c3e51674e61
[ "BSD-3-Clause" ]
83
2015-08-04T06:19:59.000Z
2022-03-25T03:33:55.000Z
theoraplayer/src/theoraplayer.cpp
tonysergi/theoraplayer
5fe4bb2a77004bba67b8f7afd2441c3e51674e61
[ "BSD-3-Clause" ]
32
2015-07-31T22:47:16.000Z
2022-03-16T01:57:49.000Z
theoraplayer/src/theoraplayer.cpp
tonysergi/theoraplayer
5fe4bb2a77004bba67b8f7afd2441c3e51674e61
[ "BSD-3-Clause" ]
40
2015-07-25T03:01:48.000Z
2022-03-29T07:55:34.000Z
/// @file /// @version 2.0 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://opensource.org/licenses/BSD-3-Clause #include <cstdio> #include <string> #include <vector> #include "Manager.h" #include "theoraplayer.h" #include "Utility.h" #ifdef _USE_THEORA #include "Theora/VideoClip_Theora.h" #endif namespace theoraplayer { static void _log(const std::string& output) { printf("%s\n", output.c_str()); } static void (*logFunction)(const std::string&) = _log; std::vector<VideoClip::Format> videoClipFormats; void init(int workerThreadCount) { #ifdef _USE_THEORA log("Initializing theoraplayer with theora support."); #else log("Initializing theoraplayer without any formats."); #endif theoraplayer::manager = new Manager(); #ifdef _USE_THEORA VideoClip::Format theora; theora.name = THEORA_DECODER_NAME; theora.extension = ".ogv"; theora.createFunction = &VideoClip_Theora::create; registerVideoClipFormat(theora); #endif theoraplayer::manager->setWorkerThreadCount(workerThreadCount); } void destroy() { delete theoraplayer::manager; theoraplayer::manager = NULL; videoClipFormats.clear(); } void setLogFunction(void (*function)(const std::string&)) { logFunction = function; if (logFunction == NULL) { logFunction = _log; } } void log(const std::string& message) { (*logFunction)(message); } void registerVideoClipFormat(VideoClip::Format format) { videoClipFormats.push_back(format); } void unregisterVideoClipFormat(const std::string& name) { foreach (VideoClip::Format, it, videoClipFormats) { if ((*it).name == name) { videoClipFormats.erase(it); break; } } } std::vector<VideoClip::Format> getVideoClipFormats() { return videoClipFormats; } }
20.195652
81
0.709903
tonysergi
b9092a063a561d30df09aba32c906865c3637e9f
63,126
cpp
C++
3rdParty/common/sources/PIUActionUtils.cpp
piaoasd123/colorpicker
1323843fc92861f9d84dea65d1f672b61b99a2ff
[ "BSD-3-Clause" ]
2
2017-02-27T02:41:39.000Z
2017-05-18T16:24:38.000Z
3rdParty/common/sources/PIUActionUtils.cpp
fpark12/colorpicker
1323843fc92861f9d84dea65d1f672b61b99a2ff
[ "BSD-3-Clause" ]
null
null
null
3rdParty/common/sources/PIUActionUtils.cpp
fpark12/colorpicker
1323843fc92861f9d84dea65d1f672b61b99a2ff
[ "BSD-3-Clause" ]
null
null
null
// ADOBE SYSTEMS INCORPORATED // Copyright 1993 - 2002 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this // file in accordance with the terms of the Adobe license agreement // accompanying it. If you have received this file from a source // other than Adobe, then your use, modification, or distribution // of it requires the prior written permission of Adobe. //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- // // File: // PIUActionUtils.cpp // // Description: // Utility routines for getting information out of descriptors. // This is the heart of the Listener debug version PIUDumpDescriptor. // //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- // Includes //------------------------------------------------------------------------------- #include "PIUActionUtils.h" #include <sstream> #include <iomanip> #ifdef _DEBUG #include "PSConstantArray.cpp" #endif //------------------------------------------------------------------------------- // Classes //------------------------------------------------------------------------------- // Handy class for the listener debug output // Keeps track of objects that need to be freed class FreeZone { public: FreeZone(); ~FreeZone(); void Add(PIActionReference); void Add(PIActionList); void Add(PIActionDescriptor); void Add(Handle); void Output(ofstream&); private: void Add(const char* text, intptr_t value); vector<char*> v_array; }; //------------------------------------------------------------------------------- // Locals //------------------------------------------------------------------------------- // Local variables so the output file looks nicer static int16 tabLevel; const char* ecs = "if (error) goto returnError;\n\n"; // Local variable that keeps track of things I need to free FreeZone * freeZone = NULL; const int16 maxHashStringSize = 1024; //------------------------------------------------------------------------------- // Local functions //------------------------------------------------------------------------------- // Local function definitions static void DumpInfoFromReference(PIActionReference inputRef, ofstream& fileOut); static void DumpInfoFromList(const PIActionList inputList, ofstream& fileOut); static void DumpInfoFromDescriptor(const PIActionDescriptor inputDesc, ofstream& fileOut); static void TabOver(ofstream & fileOut); static void LongToStr(int32 inputLong, const char* inputKeyType, char* returnString, int32 maxStringSize); static unsigned long StrToLong(const char* inputStr); static void PIUIDToChar(const unsigned long inType, char* outChars); //------------------------------------------------------------------------------- // // UnitsToPixels // // Given a value, units and resolution. Convert to number of pixels // //------------------------------------------------------------------------------- double UnitsToPixels(double value, int units, double resolution) { double newvalue = value; switch (units) { case unitDistance: newvalue = value * resolution / 72.0; break; case unitPixels: newvalue = value; break; case unitPercent: case unitNone: case unitAngle: case unitDensity: default: break; } return newvalue; } //------------------------------------------------------------------------------- // // PixelsToUnits // // Given a value, units and resolution. Convert pixels into units. // //------------------------------------------------------------------------------- double PixelsToUnits(double value, int units, double resolution) { double newvalue = 0.0; switch (units) { case unitDistance: if (resolution) newvalue = value * 72.0 / resolution; break; case unitPixels: newvalue = value; break; case unitPercent: case unitNone: case unitAngle: case unitDensity: default: break; } return newvalue; } //------------------------------------------------------------------------------- // // PIUCheckPlayResult // // Check the descriptor and see if it was a good Play(). // // NOTE: // Some Play() commands are not expected to return a valid result desciptor. // //------------------------------------------------------------------------------- SPErr PIUCheckPlayResult(PIActionDescriptor result) { SPErr error = kSPNoError; Boolean hasKey = false; if (result == NULL) { error = -1; } else { error = sPSActionDescriptor->HasKey(result, keyMessage, &hasKey); if (hasKey) { error = -1; } } return error; } //------------------------------------------------------------------------------- // // PIUDumpDescriptor // // Goes through everything in the result descriptor and dumps it and its // type. Has recursive functions that can get descriptors out of descriptors, // lists out of descriptors, descriptors out of lists, // and all other combinations. // //------------------------------------------------------------------------------- void PIUDumpDescriptor(const DescriptorEventID event, const PIActionDescriptor result, const char* fullpathtofile) { // You probably don't want the overhead of this routine in your // non-debug code, so I'll define this and its strings only for // a debug build: #ifdef _DEBUG if (sPSActionDescriptor == NULL || sPSActionList == NULL || sPSActionReference == NULL || sPSActionControl == NULL) return; freeZone = new FreeZone; if (freeZone == NULL) return; char* eventIDAsString = new char[maxHashStringSize];// the string name of the event if (eventIDAsString == NULL) return; tabLevel = 0; // indentation of the output strings // Create the output file and append to whatever is there #if __PIMac__ ofstream fileOut(fullpathtofile, ios_base::app|ios_base::out); #else // j systems have trouble opening the file with Shift-JIS chars // use this trick FILE * fd = fopen(fullpathtofile, "a"); ofstream fileOut(fd); #endif // Get the event define name for this event LongToStr(event, "event", eventIDAsString, maxHashStringSize); // Wrap each event into a function call with the event as the // function name fileOut << "SPErr Play" << eventIDAsString << "(/*your parameters go here*/void)" << endl; fileOut << "{" << endl; // Set the tab level over one for clarity tabLevel++; TabOver(fileOut); // Create a variable for the "Play" result fileOut << "PIActionDescriptor result = NULL;" << endl; // Create variables to hold all of the possible runtime ID(s) TabOver(fileOut); fileOut << "DescriptorTypeID runtimeKeyID;" << endl; TabOver(fileOut); fileOut << "DescriptorTypeID runtimeTypeID;" << endl; TabOver(fileOut); fileOut << "DescriptorTypeID runtimeObjID;" << endl; TabOver(fileOut); fileOut << "DescriptorTypeID runtimeEnumID;" << endl; TabOver(fileOut); fileOut << "DescriptorTypeID runtimeClassID;" << endl; TabOver(fileOut); fileOut << "DescriptorTypeID runtimePropID;" << endl; TabOver(fileOut); fileOut << "DescriptorTypeID runtimeUnitID;" << endl; TabOver(fileOut); fileOut << "SPErr error = kSPNoError;" << endl; // Main recursive routine for pulling apart a descriptor DumpInfoFromDescriptor(result, fileOut); // Check to see if this is a 'Hash' type of event or a unique ID // string. If it is a unique ID string then you have to get the // runtime ID for that event and play. if (event < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << eventIDAsString << "\", &runtimeEventID);" << endl; TabOver(fileOut); fileOut << ecs; // Update for the "Play" string strcpy(eventIDAsString, "runtimeEventID"); } // Format the "Play" call to the log file TabOver(fileOut); if (result) fileOut << "error = sPSActionControl->Play(&result, " << eventIDAsString << ", desc" << result << ", plugInDialogSilent);" << endl; else fileOut << "error = sPSActionControl->Play(&result, " << eventIDAsString << ", NULL, plugInDialogSilent);" << endl; TabOver(fileOut); fileOut << ecs; fileOut << "returnError:" << endl; TabOver(fileOut); fileOut << "if (result != NULL) sPSActionDescriptor->Free(result);" << endl; freeZone->Output(fileOut); // Finish off the function call TabOver(fileOut); fileOut << "return error;" << endl; fileOut << "}" << endl << endl; delete [] eventIDAsString; delete freeZone; #if __PIWin__ if ( NULL != fd ) { fclose( fd ); } #endif #endif // _DEBUG } // end DumpDescriptor //------------------------------------------------------------------------------- // // DumpInfoFromReference // // Goes through the reference and dumps it and its type. The while loop takes // care of containers in the reference. // //------------------------------------------------------------------------------- static void DumpInfoFromReference(PIActionReference inputRef, ofstream & fileOut) { // You probably don't want the overhead of this routine in your // non-debug code, so I'll define this and its strings only for // a debug build: #ifdef _DEBUG PIActionReference containerRef = NULL; const char* sar = "error = sPSActionReference->"; // If their is no reference, don't bother. if (inputRef == NULL) return; // Create a new reference item TabOver(fileOut); fileOut << "// Move this to the top of the routine!" << endl; TabOver(fileOut); fileOut << "PIActionReference ref" << inputRef << " = NULL;" << endl; // The making of this reference TabOver(fileOut); fileOut << sar << "Make(&ref" << inputRef << ");" << endl; TabOver(fileOut); fileOut << ecs; freeZone->Add(inputRef); // As long as their is a valid reference keep going. // Reference's can have container's which are more pieces to the reference. // They look like another reference but are actually part of the same reference. // So keep track of the original reference number here and use it always below. PIActionReference originalRef = inputRef; // Photoshop has an issue. If you have a multilayerd document and do a search // via the layers panel for layers with a certain name, and the name you are // searching doesn't exist then no layers are selected after you remove the // search. This comes in as a reference that is not valid. I'll add error // checks! OSErr error = 0; char * desiredClassStr = NULL; while (inputRef && ! error) { // Get the form type for this reference. DescriptorFormID formType; error = sPSActionReference->GetForm(inputRef, &formType); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetForm = " << error << endl; continue; } // What class is in the reference DescriptorClassID desiredClass; error = sPSActionReference->GetDesiredClass(inputRef, &desiredClass); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetDesiredClass = " << error << endl; continue; } // Convert the class 'Hash' to the string for output later, "classHash" if (desiredClassStr != NULL) { delete [] desiredClassStr; desiredClassStr = NULL; } desiredClassStr = new char[maxHashStringSize]; if (desiredClassStr == NULL) return; LongToStr(desiredClass, "class", desiredClassStr, maxHashStringSize); if (desiredClass < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << desiredClassStr << "\", &runtimeClassID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(desiredClassStr, "runtimeClassID"); } // Pull the next bit of information out based on the type switch(formType) { case formName: // Get some local variables uint32 nameLength; char* nameString; size_t actualLength; // See how long this string is error = sPSActionReference->GetNameLength(inputRef, &nameLength); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetNameLength = " << error << endl; continue; } // Make some room actualLength = ++nameLength; // make room for the null termination nameString = new char[actualLength]; if (nameString == NULL) return; if ((actualLength == nameLength) && nameString) { // Pull the name out of the reference error = sPSActionReference->GetName(inputRef, nameString, nameLength); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetName = " << error << endl; delete [] nameString; continue; } // Format the output TabOver(fileOut); fileOut << sar << "PutName(ref" << originalRef << ", " << desiredClassStr << ", \"" << nameString << "\");" << endl; } else { // Report the error in the file TabOver(fileOut); fileOut << "ERROR: " << sar << "PutName" << endl; } delete [] nameString; break; case formIndex: // Get some local variables uint32 indexValue; // Pull the index out of the reference error = sPSActionReference->GetIndex(inputRef, &indexValue); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetIndex = " << error << endl; continue; } // Format the output TabOver(fileOut); fileOut << sar << "PutIndex(ref" << originalRef << ", " << desiredClassStr << ", " << indexValue << ");" << endl; break; case formClass: { // Get some local variable DescriptorClassID classValue; // Get the desired class out of the reference error = sPSActionReference->GetDesiredClass(inputRef, &classValue); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetDesiredClass = " << error << endl; continue; } char* cvString = new char[maxHashStringSize]; if (cvString == NULL) return; // Convert the 'Hash' to a "hashString" LongToStr(classValue, "class", cvString, maxHashStringSize); if (classValue < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << cvString << "\", &runtimeClassID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(cvString, "runtimeClassID"); } // Format the output TabOver(fileOut); fileOut << sar << "PutClass(ref" << originalRef << ", " << cvString << ");" << endl; delete [] cvString; break; } case formEnumerated: // Get some local variable DescriptorEnumTypeID enumTypeID; DescriptorEnumID enumID; // Get the enumeration and it's type out error = sPSActionReference->GetEnumerated(inputRef, &enumTypeID, &enumID); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetEnumerated = " << error << endl; continue; } char* enumTypeIDStr; enumTypeIDStr = new char[maxHashStringSize]; if (enumTypeIDStr == NULL) return; char* enumIDStr; enumIDStr = new char[maxHashStringSize]; if (enumIDStr == NULL) return; // Convert the 'Hash' to a "hashString" LongToStr(enumTypeID, "type", enumTypeIDStr, maxHashStringSize); if (enumTypeID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << enumTypeIDStr << "\", &runtimeTypeID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(enumTypeIDStr, "runtimeTypeID"); } LongToStr(enumID, "enum", enumIDStr, maxHashStringSize); if (enumID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << enumIDStr << "\", &runtimeEnumID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(enumIDStr, "runtimeEnumID"); } // Format the output TabOver(fileOut); fileOut << sar << "PutEnumerated(ref" << originalRef << ", " << desiredClassStr << ", " << enumTypeIDStr << ", " << enumIDStr << ");" << endl; delete [] enumIDStr; delete [] enumTypeIDStr; break; case formProperty: // Get some local variable DescriptorKeyID propID; // Pull the information error = sPSActionReference->GetProperty(inputRef, &propID); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetProperty = " << error << endl; continue; } char* propIDStr; propIDStr = new char[maxHashStringSize]; if (propIDStr == NULL) return; LongToStr(propID, "key", propIDStr, maxHashStringSize); if (propID < SmallestHashValue) { //Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << propIDStr << "\", &runtimePropID);" << endl; TabOver(fileOut); fileOut << ecs; // Update for the string strcpy(propIDStr, "runtimePropID"); } // Format the output TabOver(fileOut); fileOut << sar << "PutProperty(ref" << originalRef << ", " << desiredClassStr << ", " << propIDStr << ");" << endl; delete [] propIDStr; break; case formIdentifier: // Get some local variable uint32 identifierID; error = sPSActionReference->GetIdentifier(inputRef, &identifierID); if (error) { TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on GetIdentifier = " << error << endl; continue; } // Format the output TabOver(fileOut); fileOut << sar << "PutIdentifier(ref" << originalRef << ", " << desiredClassStr << ", " << identifierID << ");" << endl; break; case formOffset: // Get some local variable int32 offset; // Pull the info sPSActionReference->GetOffset(inputRef, &offset); // Format the output TabOver(fileOut); fileOut << sar << "PutOffset(ref" << originalRef << ", " << desiredClassStr << ", " << offset << ");" << endl; break; default: // Better not ever, never get into here // Get some local variable char* formTypeStr; formTypeStr = new char[maxHashStringSize]; if (formTypeStr == NULL) return; // Convert the 'Hash' to a "hashString" LongToStr(formType, "form", formTypeStr, maxHashStringSize); if (formType < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << formTypeStr << "\", &runtimeTypeID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(formTypeStr, "runtimeTypeID"); } // Format the output TabOver(fileOut); fileOut << "ERROR: DumpInfoFromReferene on formID = " << formTypeStr << endl; delete [] formTypeStr; break; } // end switch on formType TabOver(fileOut); fileOut << ecs; // make sure you free the ref value in case this is the second time through the loop if (containerRef != NULL) { sPSActionReference->Free(containerRef); containerRef = NULL; } // see if this reference has a container reference to pull apart error = sPSActionReference->GetContainer(inputRef, &containerRef); // it could either err or have a refVale of NULL which is like an error if ( ! error && containerRef != NULL) // Update the inputRef and let the while loop continue inputRef = containerRef; else // Update the inputRef and stop the while loop inputRef = NULL; } // end while if (desiredClassStr != NULL) { delete [] desiredClassStr; desiredClassStr = NULL; } #endif // _DEBUG }// end DumpInfoFromReference //------------------------------------------------------------------------------- // // DumpInfoFromList // // Goes through the list and dumps it and its types. Has recursive functions // that can get descriptors out of descriptors and other combinations. // //------------------------------------------------------------------------------- static void DumpInfoFromList(const PIActionList inputList, ofstream & fileOut) { // You probably don't want the overhead of this routine in your // non-debug code, so I'll define this and its strings only for // a debug build: #ifdef _DEBUG const char* sal = "error = sPSActionList->"; // If no list then no go. if (inputList == NULL) return; // Get the number of items in this list, return on error uint32 listCount = 0; uint32 counter = 0; if (sPSActionList->GetCount(inputList, &listCount)) return; // Format the output TabOver(fileOut); fileOut << "// Move this to the top of the routine!" << endl; TabOver(fileOut); fileOut << "PIActionList list" << inputList << " = NULL;" << endl; TabOver(fileOut); fileOut << sal << "Make(&list" << inputList << ");" << endl; TabOver(fileOut); fileOut << ecs; freeZone->Add(inputList); // Loop throught until all the items are pulled out while (counter < listCount) { DescriptorTypeID typeID; // Get the type information for this list item sPSActionList->GetType(inputList, counter, &typeID); // Pull the next bit of information out based on the type switch (typeID) { case typeSInt64: int64 int64Value; sPSActionList->GetInteger64(inputList, counter, &int64Value); TabOver(fileOut); fileOut << sal << "PutInteger64(list" << inputList << ", " << int64Value << ");" << endl; break; case typeSInt32: /* was typeInteger: */ // Get some local data int32 intValue; // Pull the info sPSActionList->GetInteger(inputList, counter, &intValue); // Format the output TabOver(fileOut); fileOut << sal << "PutInteger(list" << inputList << ", " << intValue << ");" << endl; break; case typeIEEE64BitFloatingPoint: /* was typeFloat: */ // Get some local data double doubleValue; // Pull the info sPSActionList->GetFloat(inputList, counter, &doubleValue); // Format the output TabOver(fileOut); fileOut << sal << "PutFloat(list" << inputList << ", " << doubleValue << ");" << endl; break; case typeUnitFloat: // Get some local data double unitDoubleValue; DescriptorUnitID unitID; char* unitIDStr; unitIDStr = new char[maxHashStringSize]; if (unitIDStr == NULL) return; // Pull the info sPSActionList->GetUnitFloat(inputList, counter, &unitID, &unitDoubleValue); // Convert the 'Hash' to a "hashString" LongToStr(unitID, "unit", unitIDStr, maxHashStringSize); if (unitID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << unitIDStr << "\", &runtimeUnitID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(unitIDStr, "runtimeUnitID"); } // Format the output TabOver(fileOut); fileOut << sal << "PutUnitFloat(list" << inputList << ", " << unitIDStr << ", " << unitDoubleValue << ");" << endl; delete [] unitIDStr; break; case typeChar: { // Get some local data ASZString zString; sPSActionList->GetZString(inputList, counter, &zString); ASUInt32 unicodeLength = sASZString->LengthAsUnicodeCString(zString); ASUnicode * unicodeStr = new ASUnicode[unicodeLength + 1]; sASZString->AsUnicodeCString(zString, unicodeStr, unicodeLength, false); char * multiByteStr = NULL; int multiByteLength = 0; bool conversionOK = false; #if __PIMac__ CFStringRef stringRef = CFStringCreateWithCharacters(NULL, unicodeStr, unicodeLength + 1); // where is the routine to figure out how long this thing is going to be? // make it three times longer than the unicode string ??? multiByteLength = ( unicodeLength + 1 ) * 3; multiByteStr = new char[multiByteLength]; if ( CFStringGetCString(stringRef, multiByteStr, multiByteLength, kCFStringEncodingUTF8)) { conversionOK = true; } #else multiByteLength = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)unicodeStr, unicodeLength, NULL, 0, NULL, NULL); if (multiByteLength > 0) { multiByteStr = new char[multiByteLength]; if ( WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)unicodeStr, unicodeLength, multiByteStr, multiByteLength, NULL, NULL) ) { conversionOK = true; } } #endif if ( conversionOK ) { TabOver(fileOut); fileOut << "// Unicode String as UTF8: " << multiByteStr << endl; } delete [] multiByteStr; delete [] unicodeStr; uint32 charLen; char* charValue; size_t actualLength; // Pull the info sPSActionList->GetStringLength(inputList, counter, &charLen); // Make some room actualLength = ++charLen; // make room for the null termination charValue = new char[actualLength]; if (charValue == NULL) return; if ((actualLength == charLen) && charValue) { sPSActionList->GetString(inputList, counter, charValue, (uint32)actualLength); // Format the output TabOver(fileOut); fileOut << sal << "PutString(list" << inputList << ", \"" << charValue << "\");" << endl; } else { TabOver(fileOut); fileOut << "ERROR: " << sal << "PutString" << endl; } delete [] charValue; break; } case typeBoolean: // Get some local data Boolean boolValue; // Pull the info sPSActionList->GetBoolean(inputList, counter, &boolValue); // Format the output TabOver(fileOut); fileOut << sal << "PutBoolean(list" << inputList << ", " << (boolValue ? "true" : "false") << ");" << endl; break; case typeObject: // Get some local data DescriptorClassID objClassID; char* objClassIDStr; objClassIDStr = new char[maxHashStringSize]; if (objClassIDStr == NULL) return; PIActionDescriptor objDesc; objDesc = NULL; // Pull the info sPSActionList->GetObject(inputList, counter, &objClassID, &objDesc); // Convert the 'Hash' to a "hashString" LongToStr(objClassID, "class", objClassIDStr, maxHashStringSize); // change the indentation level for this object in a list // this makes it easier to read the output file // Recurse into this routine to pull apart the objDesc tabLevel++; DumpInfoFromDescriptor(objDesc, fileOut); tabLevel--; // Check to see if this is a 'Hash' type of event or a unique ID // string. If it is a unique ID string then you have to get the // runtime ID for that event and play. if (objClassID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << objClassIDStr << "\", &runtimeClassID);" << endl; // Update for the string strcpy(objClassIDStr, "runtimeClassID"); TabOver(fileOut); fileOut << ecs; } // Format the output TabOver(fileOut); fileOut << sal << "PutObject(list" << inputList << ", " << objClassIDStr << ", desc" << objDesc << ");" << endl; if (objDesc != NULL) sPSActionDescriptor->Free(objDesc); delete [] objClassIDStr; break; case typeGlobalObject: // Get some local data DescriptorClassID globObjClassID; char* globObjClassIDStr; globObjClassIDStr = new char[maxHashStringSize]; if (globObjClassIDStr == NULL) return; PIActionDescriptor globObjDesc; globObjDesc = NULL; // Pull the info sPSActionList->GetGlobalObject(inputList, counter, &globObjClassID, &globObjDesc); // Convert the 'Hash' to a "hashString" LongToStr(globObjClassID, "class", globObjClassIDStr, maxHashStringSize); // change the indentation level for this object in a list // this makes it easier to read the output file // Recurse into this routine to pull apart the globOsbjDesc tabLevel++; DumpInfoFromDescriptor(globObjDesc, fileOut); tabLevel--; // Check to see if this is a 'Hash' type of event or a unique ID // string. If it is a unique ID string then you have to get the // runtime ID for that event and play. if (globObjClassID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << globObjClassIDStr << "\", &runtimeClassID);" << endl; // Update for the string strcpy(globObjClassIDStr, "runtimeClassID"); TabOver(fileOut); fileOut << ecs; } // Format the output TabOver(fileOut); fileOut << sal << "PutGlobalObject(list" << inputList << ", " << globObjClassIDStr << ", desc" << globObjDesc << ");" << endl; if (globObjDesc != NULL) sPSActionDescriptor->Free(globObjDesc); delete [] globObjClassIDStr; break; case 'enum'://typeEnumerated: // Get some local data DescriptorEnumTypeID enumType; DescriptorEnumID enumValue; char* enumTypeStr; enumTypeStr = new char[maxHashStringSize]; if (enumTypeStr == NULL) return; char* enumValueStr; enumValueStr = new char[maxHashStringSize]; if (enumValueStr == NULL) return; // Pull the info sPSActionList->GetEnumerated( inputList, counter, &enumType, &enumValue); // Convert the 'Hash' to a "hashString" LongToStr(enumValue, "enum", enumValueStr, maxHashStringSize); if (enumValue < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << enumValueStr << "\", &runtimeEnumID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(enumValueStr, "runtimeEnumID"); } LongToStr(enumType, "type", enumTypeStr, maxHashStringSize); if (enumType < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << enumTypeStr << "\", &runtimeTypeID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(enumTypeStr, "runtimeTypeID"); } // Format the output TabOver(fileOut); fileOut << sal << "PutEnumerated(list" << inputList << ", " << enumTypeStr << ", " << enumValueStr << ");" << endl; delete [] enumValueStr; delete [] enumTypeStr; break; case typePath: case typeAlias: { // Get some local data Handle aliasValue = NULL; char* fullPath = new char[BigStrMaxLen*2]; if (fullPath == NULL) return; // Pull the info sPSActionList->GetAlias(inputList, counter, &aliasValue); // Get the information out of the Handle // On Windows it's a char**, on Mac it's a mess if (fullPath != NULL) AliasToFullPath(aliasValue, fullPath, BigStrMaxLen*2); // Format the output TabOver(fileOut); fileOut << "// Move this to the top of the routine!" << endl; TabOver(fileOut); fileOut << "Handle aliasValue = NULL;" << endl; TabOver(fileOut); fileOut << "FullPathToAlias(\"" << fullPath << "\", aliasValue);" << endl; TabOver(fileOut); fileOut << sal << "PutAlias(list" << inputList << ", aliasValue);" << endl; freeZone->Add(aliasValue); delete [] fullPath; sPSHandle->DisposeRegularHandle(aliasValue); break; } case typeValueList: // Get some local data PIActionList actionList; actionList = NULL; // Pull the info sPSActionList->GetList(inputList, counter, &actionList); // change the indentation level for this object in a list // this makes it easier to read the output file // Recurse into this routine to pull apart the actionList tabLevel++; DumpInfoFromList(actionList, fileOut); tabLevel--; // Format the output TabOver(fileOut); fileOut << sal << "PutList(list" << inputList << ", list" << actionList << ");" << endl; if (actionList != NULL) sPSActionList->Free(actionList); break; case typeObjectSpecifier: // Get some local data PIActionReference refValue; refValue = NULL; // Pull the info sPSActionList->GetReference(inputList, counter, &refValue); // change the indentation level for this object in a list // this makes it easier to read the output file // Recurse into this routine to pull apart the refValue tabLevel++; DumpInfoFromReference(refValue, fileOut); tabLevel--; // Format the output TabOver(fileOut); fileOut << sal << "PutReference(list" << inputList << ", ref" << refValue << ");" << endl; if (refValue != NULL) sPSActionReference->Free(refValue); break; case typeType: case typeGlobalClass: // Get some local data DescriptorClassID globClassID; char* globClassIDStr; globClassIDStr = new char[maxHashStringSize]; if (globClassIDStr == NULL) return; // Pull the info sPSActionList->GetClass(inputList, counter, &globClassID); // Convert the 'Hash' to a "hashString" LongToStr(globClassID, "class", globClassIDStr, maxHashStringSize); if (globClassID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << globClassIDStr << "\", &runtimeClassID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(globClassIDStr, "runtimeClassID"); } // Format the output TabOver(fileOut); fileOut << sal << "PutClass(list" << inputList << ", " << globClassIDStr << ");" << endl; delete [] globClassIDStr; break; case typeRawData: // Get some local data int32 dataLength; // Pull the info sPSActionList->GetDataLength(inputList, counter, &dataLength); // Format the output TabOver(fileOut); fileOut << sal << "PutData(list" << inputList << ", " << ", " << dataLength << ", voidPtrToData);" << endl; break; default: // Get some local data char* typeIDStr; typeIDStr = new char[maxHashStringSize]; if (typeIDStr == NULL) return; // Convert the 'Hash' to a "hashString" LongToStr(typeID, "type", typeIDStr, maxHashStringSize); if (typeID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << typeIDStr << "\", &runtimeTypeID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(typeIDStr, "runtimeTypeID"); } // Format the output TabOver(fileOut); fileOut << "ERROR: DumpInfoFromList type: " << typeIDStr << ", entry: " << counter << ", Total Entry: " << listCount << endl; delete [] typeIDStr; break; } // end switch on typeID counter++; // move to the next item in the list TabOver(fileOut); fileOut << ecs; } // end the while loop #endif // _DEBUG } // end DumpInfoFromList //------------------------------------------------------------------------------- // // DumpInfoFromDescriptor // // Goes through each property in the result descriptor and dumps it and its // type. Has recursive functions that can get descriptors out of descriptors // and other combinations. // //------------------------------------------------------------------------------- static void DumpInfoFromDescriptor(const PIActionDescriptor inputDesc, ofstream & fileOut) { // You probably don't want the overhead of this routine in your // non-debug code, so I'll define this and its strings only for // a debug build: #ifdef _DEBUG const char* sad = "error = sPSActionDescriptor->"; // If there is no descriptor then don't bother. if (inputDesc == NULL) return; // counters for this descriptor uint32 descCount = 0; uint32 counter = 0; if (sPSActionDescriptor->GetCount(inputDesc, &descCount)) return; // Format the output TabOver(fileOut); fileOut << "// Move this to the top of the routine!" << endl; TabOver(fileOut); fileOut << "PIActionDescriptor desc" << inputDesc << " = NULL;" << endl << endl; TabOver(fileOut); fileOut << sad << "Make(&desc" << inputDesc << ");" << endl; TabOver(fileOut); fileOut << ecs; freeZone->Add(inputDesc); // loop through all the items in this descriptor pulling apart // each one as it comes while (counter < descCount) { // get the key for this item DescriptorKeyID thisKeyID; sPSActionDescriptor->GetKey(inputDesc, counter, &thisKeyID); // get the type for this key DescriptorTypeID typeID; sPSActionDescriptor->GetType(inputDesc, thisKeyID, &typeID); // Convert the 'Hash' to a "hashString" char* keyIDStr; keyIDStr = new char[maxHashStringSize]; if (keyIDStr == NULL) return; LongToStr(thisKeyID, "key", keyIDStr, maxHashStringSize); if (thisKeyID < SmallestHashValue) { if (typeID != typeObject && typeID != typeGlobalObject && typeID != typeValueList && typeID != typeGlobalClass) { TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << keyIDStr << "\", &runtimeKeyID);" << endl; TabOver(fileOut); fileOut << ecs; } strcpy(keyIDStr, "runtimeKeyID"); } // pull the next bit of information based on the type switch (typeID) { case typeSInt64: int64 int64Value; sPSActionDescriptor->GetInteger64(inputDesc, thisKeyID, &int64Value); TabOver(fileOut); fileOut << sad << "PutInteger64(desc" << inputDesc << ", " << keyIDStr << ", " << int64Value << ");" << endl; break; case typeSInt32: /* was typeInteger: */ // Get some local data int32 intValue; // Pull the info sPSActionDescriptor->GetInteger(inputDesc, thisKeyID, &intValue); // Format the output TabOver(fileOut); fileOut << sad << "PutInteger(desc" << inputDesc << ", " << keyIDStr << ", " << intValue << ");" << endl; break; case typeIEEE64BitFloatingPoint: /* was typeFloat: */ // Get some local data double doubleValue; // Pull the info sPSActionDescriptor->GetFloat(inputDesc, thisKeyID, &doubleValue); // Format the output TabOver(fileOut); fileOut << sad << "PutFloat(desc" << inputDesc << ", " << keyIDStr << ", " << doubleValue << ");" << endl; break; case typeUnitFloat: // Get some local data double unitDoubleValue; DescriptorUnitID unitID; char* unitIDStr; unitIDStr = new char[maxHashStringSize]; if (unitIDStr == NULL) return; // Pull the info sPSActionDescriptor->GetUnitFloat( inputDesc, thisKeyID, &unitID, &unitDoubleValue); // Convert the 'Hash' to a "hashString" LongToStr(unitID, "unit", unitIDStr, maxHashStringSize); if (unitID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << unitIDStr << "\", &runtimeUnitID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(unitIDStr, "runtimeUnitID"); } // Format the output TabOver(fileOut); fileOut << sad << "PutUnitFloat(desc" << inputDesc << ", " << keyIDStr << ", " << unitIDStr << ", " << unitDoubleValue << ");" << endl; delete [] unitIDStr; break; case typeChar: { // Get some local data ASZString zString; sPSActionDescriptor->GetZString(inputDesc, thisKeyID, &zString); ASUInt32 unicodeLength = sASZString->LengthAsUnicodeCString(zString); ASUnicode * unicodeStr = new ASUnicode[unicodeLength + 1]; sASZString->AsUnicodeCString(zString, unicodeStr, unicodeLength, false); char * multiByteStr = NULL; int multiByteLength = 0; bool conversionOK = false; #if __PIMac__ CFStringRef stringRef = CFStringCreateWithCharacters(NULL, unicodeStr, unicodeLength + 1); // where is the routine to figure out how long this thing is going to be? // make it three times longer than the unicode string ??? multiByteLength = ( unicodeLength + 1 ) * 3; multiByteStr = new char[multiByteLength]; if ( CFStringGetCString(stringRef, multiByteStr, multiByteLength, kCFStringEncodingUTF8)) { conversionOK = true; } #else multiByteLength = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)unicodeStr, unicodeLength, NULL, 0, NULL, NULL); if (multiByteLength > 0) { multiByteStr = new char[multiByteLength]; if ( WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)unicodeStr, unicodeLength, multiByteStr, multiByteLength, NULL, NULL) ) { conversionOK = true; } } #endif if ( conversionOK ) { TabOver(fileOut); fileOut << "// Unicode String as UTF8: " << multiByteStr << endl; } delete [] multiByteStr; delete [] unicodeStr; uint32 charLen; size_t requestLen; char* charValue; // Pull the info sPSActionDescriptor->GetStringLength(inputDesc, thisKeyID, &charLen); requestLen = ++charLen; // make room for the null termination // Make some room for the data charValue = new char[requestLen]; if (charValue == NULL) return; // Check for room availability if (requestLen == charLen && charValue) { sPSActionDescriptor->GetString( inputDesc, thisKeyID, charValue, (uint32)requestLen); // Format the output TabOver(fileOut); fileOut << sad << "PutString(desc" << inputDesc << ", " << keyIDStr << ", \"" << charValue << "\");" << endl; } else { TabOver(fileOut); fileOut << "ERROR: " << sad << "PutString" << endl; } // Get rid of our local buffer delete [] charValue; break; } case typeBoolean: // Get some local data Boolean boolValue; // Pull the info sPSActionDescriptor->GetBoolean(inputDesc, thisKeyID, &boolValue); // Format the output TabOver(fileOut); fileOut << sad << "PutBoolean(desc" << inputDesc << ", " << keyIDStr << ", " << (boolValue ? "true" : "false") << ");" << endl; break; case typeObject: // Get some local data PIActionDescriptor objDesc; objDesc = NULL; DescriptorClassID objClassID; char* objClassIDStr; objClassIDStr = new char[maxHashStringSize]; if (objClassIDStr == NULL) return; // Pull the info sPSActionDescriptor->GetObject( inputDesc, thisKeyID, &objClassID, &objDesc); // change the indentation level for this object in a list // this makes it easier to read the output file // Recurse into this routine to pull apart the objDesc tabLevel++; DumpInfoFromDescriptor(objDesc, fileOut); tabLevel--; LongToStr(objClassID, "class", objClassIDStr, maxHashStringSize); // Check to see if this is a 'Hash' type of event or a unique ID // string. If it is a unique ID string then you have to get the // runtime ID for that event and play. if (objClassID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << objClassIDStr << "\", &runtimeObjID);" << endl; // Update for the string strcpy(objClassIDStr, "runtimeObjID"); TabOver(fileOut); fileOut << ecs; } // Dump the key out here so it is less confusing in the log file if (thisKeyID < SmallestHashValue) { LongToStr(thisKeyID, "key", keyIDStr, maxHashStringSize); TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << keyIDStr << "\", &runtimeKeyID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(keyIDStr, "runtimeKeyID"); } // Format the output TabOver(fileOut); fileOut << sad << "PutObject(desc" << inputDesc << ", " << keyIDStr << ", " << objClassIDStr << ", desc" << objDesc << ");" << endl; if (objDesc != NULL) sPSActionDescriptor->Free(objDesc); delete [] objClassIDStr; break; case typeGlobalObject: // Get some local data PIActionDescriptor globObjDesc; globObjDesc = NULL; DescriptorClassID globObjClassID; char* globObjClassIDStr; globObjClassIDStr = new char[maxHashStringSize]; if (globObjClassIDStr == NULL) return; // Pull the info sPSActionDescriptor->GetGlobalObject( inputDesc, thisKeyID, &globObjClassID, &globObjDesc); LongToStr(globObjClassID, "class", globObjClassIDStr, maxHashStringSize); // change the indentation level for this object in a list // this makes it easier to read the output file // Recurse into this routine to pull apart the globObjDesc tabLevel++; DumpInfoFromDescriptor(globObjDesc, fileOut); tabLevel--; // Check to see if this is a 'Hash' type of event or a unique ID // string. If it is a unique ID string then you have to get the // runtime ID for that event and play. if (globObjClassID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << globObjClassIDStr << "\", &runtimeObjID);" << endl; // Update for the string strcpy(globObjClassIDStr, "runtimeObjID"); TabOver(fileOut); fileOut << ecs; } // Dump the key out here so it is less confusing in the log file if (thisKeyID < SmallestHashValue) { LongToStr(thisKeyID, "key", keyIDStr, maxHashStringSize); TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << keyIDStr << "\", &runtimeKeyID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(keyIDStr, "runtimeKeyID"); } // Format the output TabOver(fileOut); fileOut << sad << "PutGlobalObject(desc" << inputDesc << ", " << keyIDStr << ", " << globObjClassIDStr << ", desc" << globObjDesc << ");" << endl; if (globObjDesc != NULL) sPSActionDescriptor->Free(globObjDesc); delete [] globObjClassIDStr; break; case 'enum'://typeEnumerated: // Get some local data DescriptorEnumTypeID enumTypeID; DescriptorEnumID enumID; char* enumTypeIDStr; enumTypeIDStr = new char[maxHashStringSize]; if (enumTypeIDStr == NULL) return; char* enumIDStr; enumIDStr = new char[maxHashStringSize]; if (enumIDStr == NULL) return; // Pull the info sPSActionDescriptor->GetEnumerated( inputDesc, thisKeyID, &enumTypeID, &enumID); LongToStr(enumID, "enum", enumIDStr, maxHashStringSize); // Convert the 'Hash' to a "hashString" if (enumID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << enumIDStr << "\", &runtimeEnumID);" << endl; TabOver(fileOut); fileOut << ecs; // Update for the string strcpy(enumIDStr, "runtimeEnumID"); } LongToStr(enumTypeID, "type", enumTypeIDStr, maxHashStringSize); if (enumTypeID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << enumTypeIDStr << "\", &runtimeTypeID);" << endl; TabOver(fileOut); fileOut << ecs; // Update for the string strcpy(enumTypeIDStr, "runtimeTypeID"); } // Format the output TabOver(fileOut); fileOut << sad << "PutEnumerated(desc" << inputDesc << ", " << keyIDStr << ", " << enumTypeIDStr << ", " << enumIDStr << ");" << endl; delete [] enumTypeIDStr; delete [] enumIDStr; break; case typePath: case typeAlias: { // Get some local data Handle aliasValue = NULL; char* fullPath = new char[BigStrMaxLen*2]; if (fullPath == NULL) return; // Pull the info sPSActionDescriptor->GetAlias(inputDesc, thisKeyID, &aliasValue); // Get the information out of the Handle // On Windows it's a char**, on Mac it's a mess if (fullPath != NULL) AliasToFullPath(aliasValue, fullPath, BigStrMaxLen*2); // Format the output TabOver(fileOut); fileOut << "// Move this to the top of the routine!" << endl; TabOver(fileOut); fileOut << "Handle aliasValue = NULL;" << endl; TabOver(fileOut); fileOut << "FullPathToAlias(\"" << fullPath << "\", aliasValue);" << endl; TabOver(fileOut); fileOut << sad << "PutAlias(desc" << inputDesc << ", " << keyIDStr << ", aliasValue);" << endl; freeZone->Add(aliasValue); delete [] fullPath; sPSHandle->DisposeRegularHandle(aliasValue); break; } case typeValueList: // Get some local data PIActionList listValue; listValue = NULL; // Pull the info sPSActionDescriptor->GetList(inputDesc, thisKeyID, &listValue); // change the indentation level for this object in a list // this makes it easier to read the output file // Recurse into this routine to pull apart the listValue tabLevel++; DumpInfoFromList(listValue, fileOut); tabLevel--; LongToStr(thisKeyID, "key", keyIDStr, maxHashStringSize); if (thisKeyID < SmallestHashValue) { TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << keyIDStr << "\", &runtimeKeyID);" << endl; strcpy(keyIDStr, "runtimeKeyID"); TabOver(fileOut); fileOut << ecs; } // Format the output TabOver(fileOut); fileOut << sad << "PutList(desc" << inputDesc << ", " << keyIDStr << ", list" << listValue << ");" << endl; if (listValue != NULL) sPSActionList->Free(listValue); break; case typeObjectSpecifier: // Get some local data PIActionReference refValue; refValue = NULL; // Pull the info sPSActionDescriptor->GetReference(inputDesc, thisKeyID, &refValue); // change the indentation level for this object in a list // this makes it easier to read the output file // Recurse into this routine to pull apart the refValue tabLevel++; DumpInfoFromReference(refValue, fileOut); tabLevel--; // Format the output TabOver(fileOut); fileOut << sad << "PutReference(desc" << inputDesc << ", " << keyIDStr << ", ref" << refValue << ");" << endl; if (refValue != NULL) sPSActionReference->Free(refValue); break; case typeType: case typeGlobalClass: // Get some local data DescriptorClassID globClassID; char* globClassIDStr; globClassIDStr = new char[maxHashStringSize]; if (globClassIDStr == NULL) return; // Pull the info sPSActionDescriptor->GetClass(inputDesc, thisKeyID, &globClassID); LongToStr(globClassID, "class", globClassIDStr, maxHashStringSize); // Convert the 'Hash' to a "hashString" if (globClassID < SmallestHashValue) { // Format the output TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << globClassIDStr << "\", &runtimeClassID);" << endl; // Update for the string strcpy(globClassIDStr, "runtimeClassID"); TabOver(fileOut); fileOut << ecs; } // Dump the key out here so it is less confusing in the log file if (thisKeyID < SmallestHashValue) { LongToStr(thisKeyID, "key", keyIDStr, maxHashStringSize); TabOver(fileOut); fileOut << "error = sPSActionControl->StringIDToTypeID(\"" << keyIDStr << "\", &runtimeKeyID);" << endl; TabOver(fileOut); fileOut << ecs; strcpy(keyIDStr, "runtimeKeyID"); } // Format the output TabOver(fileOut); fileOut << sad << "PutClass(desc" << inputDesc << ", " << keyIDStr << ", " << globClassIDStr << ");" << endl; delete [] globClassIDStr; break; case typeRawData: // Get some local data int32 dataLength; // Pull the info sPSActionDescriptor->GetDataLength(inputDesc, thisKeyID, &dataLength); // Format the output TabOver(fileOut); fileOut << sad << "PutData(desc" << inputDesc << ", " << keyIDStr << ", " << dataLength << ", voidPtrToData);" << endl; break; default: // Get some local data char* typeIDStr; typeIDStr = new char[maxHashStringSize]; if (typeIDStr == NULL) return; // Convert the 'Hash' to a "hashString" LongToStr(typeID, "xxxx", typeIDStr, maxHashStringSize); // Format the output TabOver(fileOut); fileOut << "ERROR DumpInfoFromDescriptor type: " << typeIDStr << ", key: " << keyIDStr << ", entry: " << counter << endl; delete [] typeIDStr; break; } // end the switch counter++; // go to the next item in the list TabOver(fileOut); fileOut << ecs; delete [] keyIDStr; }// end the while loop #endif // _DEBUG }// end DumpInforFromDescriptor //------------------------------------------------------------------------------- // // TabOver // // Utility function that makes the output file easier to read. // //------------------------------------------------------------------------------- static void TabOver(ofstream & fileOut) { for(int16 numberoftabs = 0; numberoftabs < tabLevel; numberoftabs++) fileOut << " "; } //------------------------------------------------------------------------------- // // PIUIDToChar // // Utility function that converts longs to "Hash" strings // //------------------------------------------------------------------------------- static void PIUIDToChar (const unsigned long inType, /* OUT */ char* outChars) { int8 loopType, loopChar; // Figure out which byte we're dealing with and move it // to the highest character, then mask out everything but // the lowest byte and assign that as the character: for (loopType = 0, loopChar = 3; loopType < 4; loopType++, loopChar--) outChars[loopChar] = (char) ((inType >> (loopType<<3)) & 0xFF); outChars[loopType] = '\0'; } // end PIUIDToChar //------------------------------------------------------------------------------- // // PIUCharToID // // Utility function that converts "Hash" strings to longs // //------------------------------------------------------------------------------- unsigned long PIUCharToID (const char* inChars) { unsigned short loop; ResType outType = 0; for (loop = 0; loop < 4; loop++) { outType <<= 8; // bits per char outType |= inChars[loop]; } return outType; } // end PIUCharToID //------------------------------------------------------------------------------- // You probably don't want the overhead of this routine in your // non-debug code, so I'll define this and its strings only for // a debug build: #ifdef _DEBUG //------------------------------------------------------------------------------- // // LongToStr // // Utility that uses the above structure to convert the int32 value from the // descriptors, lists, and references to output the string name. If it can't // find the constant then it outputs the 'Hash' code. //------------------------------------------------------------------------------- static void LongToStr(int32 inputLong, const char* inputKeyType, char* returnString, int32 maxStringSize) { // don't want to recalculate this all the time static const int32 ArraySize = sizeof(PSConstA) / sizeof(PSConstantArray); bool found = false; // blank it out *returnString = '\0'; // if the input long is a small number then it's a runtime ID // use the control procs to get the string if (inputLong < SmallestHashValue) { if (!(sPSActionControl->TypeIDToStringID(inputLong, returnString, maxHashStringSize))) { found = true; } } // loop through all the above constants looking for the one that matches // in an ideal world you wouldn't need the inputKeyType but there are constants // that break the hash code creation world so we want to make sure if you are // asking for a key you will get a key and not a class or something else if (!found) { for (int32 counter = 0; counter < ArraySize; counter++) if (PSConstA[counter].longVal == inputLong) if (strstr(PSConstA[counter].strStr, inputKeyType)) { strcpy(returnString, PSConstA[counter].strStr); counter = ArraySize;// and stop the for loop found = true; } } // didn't find a match so convert the number to its 'Hash' code if (*returnString == '\0' || !found) { *returnString++ = '\''; PIUIDToChar(inputLong,returnString); returnString[4] = '\''; returnString[5] = '\0'; } } //------------------------------------------------------------------------------- // // StrToLong // // Utility that uses the above structure to convert the string value from the // descriptors, lists, and references to output the long value. //------------------------------------------------------------------------------- static unsigned long StrToLong(const char* inputStr) { // don't want to recalculate this all the time static const int32 ArraySize = sizeof(PSConstA) / sizeof(PSConstantArray); unsigned long returnLong = 0; if (inputStr) for(int32 counter = 0; counter < ArraySize; counter++) if (strcmp(inputStr, PSConstA[counter].strStr) == 0) { returnLong = PSConstA[counter].longVal; break; } return (returnLong); } //------------------------------------------------------------------------------- // // FreeZone::FreeZone // // Constructor for the FreeZone. Doesn't do anything. // //------------------------------------------------------------------------------- FreeZone::FreeZone() {} //------------------------------------------------------------------------------- // // FreeZone::~FreeZone // // Destructor for the FreeZone class. Deletes all the char []'s in the vector. // //------------------------------------------------------------------------------- FreeZone::~FreeZone() { vector<char*>::iterator array_iter = v_array.begin(); vector<char*>::iterator array_end = v_array.end(); while(array_iter != array_end) { delete [] *array_iter; array_iter++; } } //------------------------------------------------------------------------------- // // FreeZone::Add // // Add a reference to the vector using the generic routine. // //------------------------------------------------------------------------------- void FreeZone::Add(PIActionReference reference) { Add("ref", (intptr_t)reference); } //------------------------------------------------------------------------------- // // FreeZone::Add // // Add a list to the vector using the generic routine. // //------------------------------------------------------------------------------- void FreeZone::Add(PIActionList list) { Add("list", (intptr_t)list); } //------------------------------------------------------------------------------- // // FreeZone::Add // // Add a descriptor to the vector using the generic routine. // //------------------------------------------------------------------------------- void FreeZone::Add(PIActionDescriptor descriptor) { Add("desc", (intptr_t)descriptor); } //------------------------------------------------------------------------------- // // FreeZone::Add // // Add a handle to the vector using a special routine. // //------------------------------------------------------------------------------- void FreeZone::Add(Handle /*aliasValue*/) { const size_t s = strlen("aliasValue") + 1; char* ptr = new char[s]; if (ptr == NULL) return; strcpy(ptr, "aliasValue"); v_array.push_back(ptr); } //------------------------------------------------------------------------------- // // FreeZone::Add // // The generic add. // //------------------------------------------------------------------------------- void FreeZone::Add(const char* text, intptr_t value) { const size_t s = strlen(text) + 1; const size_t sa = s + 20; char* ptr = new char[sa]; if (ptr == NULL) return; std::ostringstream temp; temp << text << std::setw(sizeof(void*) * 2) << std::hex << std::setfill('0') << value; strncpy(ptr, temp.str().c_str(), sa - 1); ptr[sa-1] = '\0'; v_array.push_back(ptr); } //------------------------------------------------------------------------------- // // FreeZone::Output // // Dump the vector to the stream. // //------------------------------------------------------------------------------- void FreeZone::Output(ofstream& fileOut) { vector<char*>::iterator array_iter = v_array.begin(); vector<char*>::iterator array_end = v_array.end(); while(array_iter != array_end) { char freeType = (*array_iter)[0]; switch (freeType) { case 'r': TabOver(fileOut); fileOut << "if (" << *array_iter << " != NULL) sPSActionReference->Free(" << *array_iter << ");" << endl; break; case 'l': TabOver(fileOut); fileOut << "if (" << *array_iter << " != NULL) sPSActionList->Free(" << *array_iter << ");" << endl; break; case 'd': TabOver(fileOut); fileOut << "if (" << *array_iter << " != NULL) sPSActionDescriptor->Free(" << *array_iter << ");" << endl; break; case 'a': TabOver(fileOut); fileOut << "if (" << *array_iter << " != NULL) sPSHandle->DisposeRegularHandle(" << *array_iter << ");" << endl; break; } array_iter++; } } #endif // _DEBUG // here all all the known dupes 11/4/98, I don't know of a good (easy) way to figure these out // so if you see a constant that doesn't look like it belongs then check here and figure out // what it should be. //enumBlacks enumBlocks //enumFileInfo enumFillInverse //enumLightOmni enumLightenOnly //enumMagenta enumMagentas //keyBlackLevel keyBlackLimit //keyCenter keyContrast //keyConstant keyConstrain //keyDistortion keyDistribution //keyGrain keyGreen //keyInterfaceIconFrameDimmed keyInterlace //keyInterfaceIconFrameDimmed keyInterpolation //keyInterlace keyInterpolation //keyNumberOfLayers keyNumberOfLevels //keySaturation keyStart //keyTextClickPoint keyTextureCoverage // end PIUActionUtils.cpp
27.327273
106
0.593448
piaoasd123
b90dc2c4eb359ae0b0170434e09e5962fe055694
2,297
cc
C++
codingInterview/54.KthNodeInBST/KthNodeInBST.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
2
2020-12-09T09:55:51.000Z
2021-01-08T11:38:22.000Z
codingInterview/54.KthNodeInBST/KthNodeInBST.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
null
null
null
codingInterview/54.KthNodeInBST/KthNodeInBST.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include "binaryTree.h" using std::cout; using std::endl; using std::vector; class Solution { public: TreeNode* KthNode(TreeNode* pRoot, int k) { if (!pRoot || k == 0) { return nullptr; } return KthNodeCore(pRoot, k); } private: TreeNode* KthNodeCore(TreeNode* pRoot, int& k) { TreeNode* target = nullptr; //cout << "pRoot->val = " << pRoot->val << endl; if (pRoot->left) { target = KthNodeCore(pRoot->left, k); } //当找到结果后,递归返回时,下面两步都不会执行 if (target == nullptr) { if (k == 1) { target = pRoot; } --k; } //当target = pRoot后,这一步不会执行,直接返回target if (target == nullptr && pRoot->right != nullptr) { target = KthNodeCore(pRoot->right, k); } return target; } }; // ====================测试代码==================== void Test(const char* testName, TreeNode* pRoot, int k, bool isNull, int expected) { Solution solution; if (testName != nullptr) printf("%s begins: ", testName); const TreeNode* pTarget = solution.KthNode(pRoot, k); if ((isNull && pTarget == nullptr) || (!isNull && pTarget->val == expected)) printf("Passed.\n"); else printf("FAILED.\n"); } // 8 // 6 10 // 5 7 9 11 void TestA() { TreeNode* pNode8 = new TreeNode(8); TreeNode* pNode6 = new TreeNode(6); TreeNode* pNode10 = new TreeNode(10); TreeNode* pNode5 = new TreeNode(5); TreeNode* pNode7 = new TreeNode(7); TreeNode* pNode9 = new TreeNode(9); TreeNode* pNode11 = new TreeNode(11); connectTreeNodes(pNode8, pNode6, pNode10); connectTreeNodes(pNode6, pNode5, pNode7); connectTreeNodes(pNode10, pNode9, pNode11); Test("TestA0", pNode8, 0, true, -1); Test("TestA1", pNode8, 1, false, 5); Test("TestA2", pNode8, 2, false, 6); Test("TestA3", pNode8, 3, false, 7); Test("TestA4", pNode8, 4, false, 8); Test("TestA5", pNode8, 5, false, 9); Test("TestA6", pNode8, 6, false, 10); Test("TestA7", pNode8, 7, false, 11); Test("TestA8", pNode8, 8, true, -1); destroyTree(pNode8); } int main() { TestA(); return 0; }
27.023529
80
0.543753
stdbilly
b912c1d7be85cc23d42708152fe19c7900e1e1b6
2,630
cpp
C++
MVJ_Engine_base/ModuleProgram.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
MVJ_Engine_base/ModuleProgram.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
MVJ_Engine_base/ModuleProgram.cpp
expelthegrace/ThomasTheEngine
d570c9746725e3f8232753799cce90cdc47a4b48
[ "Unlicense" ]
null
null
null
#include "Application.h" #include "ModuleProgram.h" #include "ModuleRenderExercise.h" #include <vector> ModuleProgram::ModuleProgram() { } ModuleProgram::~ModuleProgram() { } void ModuleProgram::CreateProgram(GLuint& variable, char* vsName, char* fsName) { char* dataVertex = nullptr; FILE* file = nullptr; fopen_s(&file, vsName, "rb"); if (file) { fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); dataVertex = (char*)malloc(size + 1); fread(dataVertex, 1, size, file); dataVertex[size] = 0; fclose(file); } char* dataFragment = nullptr; file = nullptr; fopen_s(&file, fsName, "rb"); if (file) { fseek(file, 0, SEEK_END); int size = ftell(file); rewind(file); dataFragment = (char*)malloc(size + 1); fread(dataFragment, 1, size, file); dataFragment[size] = 0; fclose(file); } GLuint vs = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vs, 1, &dataVertex, 0); glCompileShader(vs); //case compilation error vs GLint params = GL_TRUE; glGetShaderiv(vs, GL_COMPILE_STATUS, &params); GLint maxLength = 0; if (params == GL_FALSE) { std::vector<GLchar> infoLog(maxLength); glGetShaderInfoLog(vs, maxLength, &maxLength, &infoLog[0]); glDeleteShader(vs); } GLuint fs = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fs, 1, &dataFragment, 0); glCompileShader(fs); params = GL_TRUE; maxLength = 1000; //case compilation error fs glGetShaderiv(fs, GL_COMPILE_STATUS, &params); if (params == GL_FALSE) { std::vector<GLchar> infoLog(maxLength); glGetShaderInfoLog(fs, maxLength, &maxLength, &infoLog[0]); glDeleteShader(fs); } variable = glCreateProgram(); glAttachShader(variable, vs); glAttachShader(variable, fs); glLinkProgram(variable); //case compilation error program GLint isLinked = 0; glGetProgramiv(variable, GL_LINK_STATUS, (int *)&isLinked); if (isLinked == GL_FALSE) { GLint maxLength = 0; glGetProgramiv(variable, GL_INFO_LOG_LENGTH, &maxLength); // The maxLength includes the NULL character std::vector<GLchar> infoLog(maxLength); glGetProgramInfoLog(variable, maxLength, &maxLength, &infoLog[0]); // We don't need the program anymore. glDeleteProgram(variable); glDeleteShader(vs); glDeleteShader(fs); } glDeleteShader(GL_VERTEX_SHADER); glDeleteShader(GL_FRAGMENT_SHADER); //glUseProgram(variable); } bool ModuleProgram::Init() { CreateProgram(programLines, "Color.vs", "Color.fs"); CreateProgram(programModel, "ModelShader.vs", "ModelShader.fs"); return true; } update_status ModuleProgram::Update() { return UPDATE_CONTINUE; } bool ModuleProgram::CleanUp() { return true; }
22.869565
81
0.714829
expelthegrace
b91753a8bdb1b4a8b8866d24250284a74ae1e356
7,518
hpp
C++
lab_control_center/Doxygen_lcc_file_descriptions.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
9
2020-06-24T11:22:15.000Z
2022-01-13T14:14:13.000Z
lab_control_center/Doxygen_lcc_file_descriptions.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
1
2021-05-10T13:48:04.000Z
2021-05-10T13:48:04.000Z
lab_control_center/Doxygen_lcc_file_descriptions.hpp
Durrrr95/cpm_lab
e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67
[ "MIT" ]
2
2021-11-08T11:59:29.000Z
2022-03-15T13:50:54.000Z
//Includes file descriptions for the LCC /** * \defgroup lcc_further_files LCC Files * \brief Files for the LCC, e.g. build.bash * \ingroup lcc_further */ /** * \page lcc_further_page LCC Further Files * \subpage lcc_f_build <br> * \subpage lcc_f_gdb <br> * \subpage lcc_f_run <br> * \subpage lcc_f_start <br> * \subpage lcc_f_valgrind <br> * \subpage lcc_f_commonroad <br> * \subpage lcc_f_parameters <br> * \subpage lcc_f_commonroad_file <br> * \subpage lcc_f_file_dialog <br> * \ingroup lcc_further_files */ /** * \page lcc_f_build build.bash * \brief Build script that builds the LCC and pulls the YAML repo; also creates a launcher link */ /** * \page lcc_f_gdb gdb_run.bash * \brief Runs the LCC with GDB (insert 'run' after starting this script in the command line that shows up). Allows for better error tracking. */ /** * \page lcc_f_run run.bash * \brief Runs the LCC with a pre-defined number of vehicles set for the vehicle selection in the UI */ /** * \page lcc_f_start start_lcc.bash * \brief Runs the LCC without the pre-defined number of vehicles */ /** * \page lcc_f_valgrind valgrind_run.bash * \brief Memory-check run of the LCC, rudimentary, unstable */ /** * \page lcc_f_commonroad commonroad_profiles.yaml * \brief YAML file that stores commonroad information for translation/rotation/... for different profiles */ /** * \page lcc_f_parameters parameters.yaml * \brief Parameters set and stored in the lcc, that are distributed by the LCC * within the network as described in https://cpm.embedded.rwth-aachen.de/doc/display/CLD/Parameter+Service and can be edited in the LCC's UI */ /** * \page lcc_f_commonroad_file commonroad_file_chooser.config * \brief Config file that remembers the last chosen commonroad file. Soon outdated and replaced by a YAML file. */ /** * \page lcc_f_file_dialog file_dialog_open_config.config */ ///////////////////////////////////////////////////////////////////////////////////// // BASH FILES /** * \defgroup lcc_bash LCC Bash Files * \brief LCC file descriptions for files in ./bash (for local & distributed / remote deployment & vehicle reboot) * \ingroup lcc_further */ /** * \page lcc_bash_page LCC Bash Files * \subpage lcc_bash_copy <br> * \subpage lcc_bash_env_loc <br> * \subpage lcc_bash_env <br> * \subpage lcc_bash_reboot_r <br> * \subpage lcc_bash_remote_k <br> * \subpage lcc_bash_remote_s <br> * \subpage lcc_bash_tmux_mid <br> * \subpage lcc_bash_tmux_script <br> * \ingroup lcc_bash */ /** * \page lcc_bash_copy ./bash/copy_to_remote.bash * \brief Copies the chosen script to the HLC guest user, starts the script using tmux; * path + script + middleware command line information are transferred as well; * does not check if the HLC is reachable beforehand, this is handled internally by the C++ code that calls this script via timeouts */ /** * \page lcc_bash_env_loc ./bash/environment_variables_local.bash * \brief Sets required environment variables for tmux sessions running locally */ /** * \page lcc_bash_env ./bash/environment_variables.bash * \brief Sets required environment variables for tmux sessions running on the HLC */ /** * \page lcc_bash_reboot_r ./bash/reboot_raspberry.bash * \brief Sends a reboot signal to the vehicle */ /** * \page lcc_bash_remote_k ./bash/remote_kill.bash * \brief Kills the middleware and script tmux sessions on the HLC guest, if it is reachable */ /** * \page lcc_bash_remote_s ./bash/remote_start.bash * \brief Starts middleware and script on the HLC guest via tmux */ /** * \page lcc_bash_tmux_mid ./bash/tmux_middleware.bash * \brief Script to start the middleware on the HLC, called by remote_start internally */ /** * \page lcc_bash_tmux_script ./bash/tmux_script.bash * \brief Script to start the script on the HLC, called by remote_start internally */ //////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////// // UI FILES /** * \defgroup lcc_ui_files LCC UI Files * \brief Short description for the .glade UI files * \ingroup lcc_further */ /** * \page lcc_ui_file_page LCC UI Files * \subpage lcc_ui_master <br> * \subpage lcc_ui_commonroad <br> * \subpage lcc_ui_obstacle_toggle <br> * \subpage lcc_ui_file_chooser <br> * \subpage lcc_ui_file_saver <br> * \subpage lcc_ui_errors <br> * \subpage lcc_ui_logger <br> * \subpage lcc_ui_manual_control <br> * \subpage lcc_ui_monitoring <br> * \subpage lcc_ui_params <br> * \subpage lcc_ui_params_create <br> * \subpage lcc_ui_params_show <br> * \subpage lcc_ui_right_tabs <br> * \subpage lcc_ui_setup <br> * \subpage lcc_ui_upload_window <br> * \subpage lcc_ui_vehicle_toggle <br> * \subpage lcc_ui_timer <br> * \subpage lcc_ui_style <br> * \ingroup lcc_ui_files */ /** * \page lcc_ui_master ./ui/master_layout.glade * \brief Defines the layout of the LCC program, contains all other UI elements */ /** * \page lcc_ui_commonroad ./ui/commonroad/commonroad.glade * \brief Layout of the Commonroad Tab */ /** * \page lcc_ui_obstacle_toggle ./ui/commonroad/obstacle_toggle.glade * \brief Toggle to turn obstacle simulation with trajectory on or off */ /** * \page lcc_ui_file_chooser ./ui/file_chooser/FileChooserDialog.glade * \brief Layout for a file chooser dialog */ /** * \page lcc_ui_file_saver ./ui/file_chooser/FileSaverDialog.glade * \brief Layout for a file saver dialog */ /** * \page lcc_ui_errors ./ui/lcc_errors/lcc_errors.glade * \brief Layout for the tab that displays internal LCC errors or warnings */ /** * \page lcc_ui_logger ./ui/logger/logger.glade * \brief Layout for the tab that shows log messages from the whole network, depending on the log level */ /** * \page lcc_ui_manual_control ./ui/manual_control/manual_control_ui2.glade * \brief Layout for the tab to manually control a vehicle */ /** * \page lcc_ui_monitoring ./ui/monitoring/monitoring_ui.glade * \brief Layout for the monitoring tab on the bottom, that includes vehicle and HLC information including RTT, and HLC reboot options */ /** * \page lcc_ui_params ./ui/params/params.glade * \brief Layout for the Tab where parameters can be seen and set */ /** * \page lcc_ui_params_create ./ui/params/params_create.glade * \brief Layout for a parameter creation or edit window */ /** * \page lcc_ui_params_show ./ui/params/params_show.glade * \brief Layout for a window to inspect param information */ /** * \page lcc_ui_right_tabs ./ui/right_tabs/right_tabs.glade * \brief Layout for all the UI elements shown in tabs on the right side */ /** * \page lcc_ui_setup ./ui/setup/setup.glade * \brief Layout for the setup tab, where the script can be chosen, vehicles can be selected, the simulation can be started or stopped */ /** * \page lcc_ui_upload_window ./ui/setup/upload_window.glade * \brief Layout for an upload window, shown after starting the distributed / remote deployment, which displays upload information */ /** * \page lcc_ui_vehicle_toggle ./ui/setup/vehicle_toggle.glade * \brief Layout for vehicle toggles in the setup tab */ /** * \page lcc_ui_timer ./ui/timer/timer.glade * \brief Layout for the timer tab, where timing information can be seen and the timer can be (re)started and stopped */ /** * \page lcc_ui_style ./ui/style.css * \brief Some custom CSS definitions for the LCC's UI */ ////////////////////////////////////////////////////////////////////////////////////
29.833333
142
0.704576
Durrrr95
b918fb5953527ed7ce17822f21f5200fb1f105bc
8,048
cpp
C++
cosmos_render.cpp
CobaltXII/cosmos
3e468cd3490d5bf55c1eead2a77792b16bde35eb
[ "MIT" ]
2
2019-02-17T12:28:05.000Z
2021-03-18T10:42:14.000Z
cosmos_render.cpp
CobaltXII/cosmos
3e468cd3490d5bf55c1eead2a77792b16bde35eb
[ "MIT" ]
null
null
null
cosmos_render.cpp
CobaltXII/cosmos
3e468cd3490d5bf55c1eead2a77792b16bde35eb
[ "MIT" ]
null
null
null
/* ### cosmos_render To compile, use the command ```bash clang++ cosmos_render.cpp -o cosmos_render -std=c++11 -lOpenCL ``` To run, use the command ```bash ./cosmos_render <frames> [bodies=24576] ``` This will cause cosmos_render to output a bunch of rendered frames to the directory that it was started in. These rendered frames will be image files, produced by rendering the corresponding simulation frames generated by running cosmos_simulate. ## Even more speed To speed up simulations and renders even more, compile with ```bash clang++ cosmos_tool.cpp -o cosmos_tool -std=c++11 -lOpenCL -Ofast -march=native ``` */ #include <iostream> #include <sstream> #include <fstream> #include <ctime> #include <memory> // Include stb_image_write. #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" // Include OpenCL. #ifdef __APPLE__ #define CL_SILENCE_DEPRECATION #include <OpenCL/OpenCL.h> #else #include <CL/cl.h> #endif // Include the kernel source. #define __stringify(source) #source const char* kernel_source = #include "cosmos_render.cl" #undef __stringify size_t kernel_source_size = strlen(kernel_source); // Include the thermal colormap. #define THERMAL_OPEN_CL #include "thermal_colormap.h" // Write a message to std::cout. void say(std::string message) { std::cout << message << std::endl; } // Entry point. int main(int argc, char** argv) { // Parse command line arguments. if (argc != 2) { std::cout << "Usage: " << argv[0] << " <frames> [bodies=24576]" << std::endl; return EXIT_FAILURE; } int frames = atoi(argv[1]); int n = 24576; if (argc == 3) { n = atoi(argv[2]); } // Create variables to hold return codes. cl_int r_code; cl_int r_code1; cl_int r_code2; // Create identifier objects to hold information about the available // platforms and available devices. cl_platform_id platform_id = NULL; cl_device_id device_id = NULL; // Create unsigned integer objects to hold the amount of available // platforms and available devices. cl_uint num_platforms; cl_uint num_devices; // Get the first available platform and store the amount of available // platforms. clGetPlatformIDs(1, &platform_id, &num_platforms); // Get the first available device on the first available platform. Store // the amount of available devices. This device will be referred to as the // 'default device'. clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &num_devices); // Create an OpenCL context on the default device. cl_context context = clCreateContext(0, 1, &device_id, NULL, NULL, &r_code); // Make sure the OpenCL context was created successfully. if (r_code != CL_SUCCESS) { say("Could not create an OpenCL context."); return EXIT_FAILURE; } // Create an OpenCL command queue. cl_command_queue command_queue = clCreateCommandQueue(context, device_id, 0, &r_code); // Make sure the OpenCL command queue was created successfully. if (r_code != CL_SUCCESS) { say("Could not create an OpenCL command queue."); return EXIT_FAILURE; } // Allocate a buffer to hold the frame body data, CPU side. cl_float4* cpu_bodies = (cl_float4*)malloc(n * sizeof(cl_float4)); // Allocate a buffer to hold the frame body data, GPU side. cl_mem gpu_bodies = clCreateBuffer(context, CL_MEM_READ_WRITE, n * sizeof(cl_float4), NULL, &r_code); if (r_code != CL_SUCCESS) { say("Could not allocate GPU memory."); return EXIT_FAILURE; } // PARAM: The dimensions of the image (which is square). int res = 800; int stride_in_bytes = res * 4; // Allocate a buffer to hold the rendered frame, CPU side. unsigned char* cpu_img = (unsigned char*)malloc(res * res * 4 * sizeof(unsigned char)); // Allocate a buffer to hold the rendered frame, GPU side. cl_mem gpu_img = clCreateBuffer(context, CL_MEM_READ_WRITE, res * res * sizeof(cl_uint), NULL, &r_code); if (r_code != CL_SUCCESS) { say("Could not allocate GPU memory."); return EXIT_FAILURE; } // Allocate an array to hold the thermal colormap, GPU side. cl_mem gpu_colormap = clCreateBuffer(context, CL_MEM_READ_WRITE, 256 * sizeof(cl_uint), NULL, &r_code); if (r_code != CL_SUCCESS) { say("Could not allocate GPU memory."); return EXIT_FAILURE; } // Copy the thermal colormap from the CPU to the GPU. r_code = clEnqueueWriteBuffer(command_queue, gpu_colormap, CL_TRUE, 0, 256 * sizeof(cl_uint), thermal_colormap, 0, NULL, NULL); if (r_code != CL_SUCCESS) { say("Could not copy the thermal colormap array from the CPU to the GPU."); return EXIT_FAILURE; } // Create an OpenCL program from the kernel source. cl_program program = clCreateProgramWithSource(context, 1, (const char**)&kernel_source, (const size_t*)&kernel_source_size, &r_code); // Make sure the OpenCL program was created successfully. if (r_code != CL_SUCCESS) { say("Could not create an OpenCL program."); return EXIT_FAILURE; } // Build the OpenCL program. r_code = clBuildProgram(program, 1, &device_id, NULL, NULL, NULL); // Make sure the OpenCL program was built successfully. if (r_code != CL_SUCCESS) { say("Could not build an OpenCL program."); return EXIT_FAILURE; } // Create the OpenCL kernel from the function "n_body_render" within the // OpenCL program. cl_kernel kernel = clCreateKernel(program, "n_body_render", &r_code); // Make sure the OpenCL kernel was created successfully. if (r_code != CL_SUCCESS) { say("Could not create an OpenCL kernel."); return EXIT_FAILURE; } // Set the n parameter of the OpenCL kernel. clSetKernelArg(kernel, 1, sizeof(cl_int), &n); // Set the res parameter of the OpenCL kernel. clSetKernelArg(kernel, 2, sizeof(cl_int), &res); // Set the state parameter of the OpenCL kernel. clSetKernelArg(kernel, 3, sizeof(cl_mem), (void*)&gpu_bodies); // Set the output parameter of the OpenCL kernel. clSetKernelArg(kernel, 4, sizeof(cl_mem), (void*)&gpu_img); // Set the thermal_colormap parameter of the OpenCL kernel. clSetKernelArg(kernel, 5, sizeof(cl_mem), (void*)&gpu_colormap); // PARAM: local_work_size should be modified depending on your GPU. This // should be tested on a realtime renderer first, such as // CobaltXII/boiler/experimental/n_body_cl/. size_t global_work_size = res * res; size_t local_work_size = 256; // Start the render! for (int i = 0; i < frames; i++) { // Get the starting time. clock_t frame_start = clock(); // Load the current frame. std::stringstream name_builder; name_builder << "frame_" << i << ".dat"; std::ifstream frame(name_builder.str()); frame.read((char*)cpu_bodies, n * sizeof(cl_float4)); frame.close(); // Copy the bodies array from the CPU to the GPU. r_code = clEnqueueWriteBuffer(command_queue, gpu_bodies, CL_TRUE, 0, n * sizeof(cl_float4), cpu_bodies, 0, NULL, NULL); if (r_code != CL_SUCCESS) { say("Could not copy the body array from the CPU to the GPU."); return EXIT_FAILURE; } // PARAM: The zoom factor. float inv_scale = i / 60.0f; // Set the inv_scale parameter of the OpenCL kernel. clSetKernelArg(kernel, 0, sizeof(cl_float), &inv_scale); // Generate the current frame. r_code = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (r_code != CL_SUCCESS) { say("Could not invoke the render kernel."); return EXIT_FAILURE; } // Read output back into local CPU memory. clEnqueueReadBuffer(command_queue, gpu_img, CL_TRUE, 0, res * res * sizeof(cl_uint), cpu_img, 0, NULL, NULL); // Save the image. std::stringstream out_name_builder; out_name_builder << "render_" << i << ".png"; stbi_write_png(out_name_builder.str().c_str(), res, res, 4, cpu_img, stride_in_bytes); // Get the ending time. clock_t frame_end = clock(); // Print the frame elapsed time. std::cout << "Frame " << i << " rendered in " << float(frame_end - frame_start) / float(CLOCKS_PER_SEC) << " s" << std::endl; } return EXIT_SUCCESS; }
22.170799
135
0.710611
CobaltXII
2c6f17ea059b881e31434adcb2dd21ea9d384f28
3,185
cpp
C++
Code/ThirdParty/ads/ads_globals.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
67
2018-01-17T17:18:37.000Z
2020-08-24T23:45:56.000Z
Code/ThirdParty/ads/ads_globals.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
132
2018-01-17T17:43:25.000Z
2020-09-01T07:41:17.000Z
Code/ThirdParty/ads/ads_globals.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
5
2021-02-12T15:23:31.000Z
2022-01-09T15:16:21.000Z
/******************************************************************************* ** Qt Advanced Docking System ** Copyright (C) 2017 Uwe Kindler ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ //============================================================================ /// \file ads_globals.cpp /// \author Uwe Kindler /// \date 24.02.2017 /// \brief Implementation of //============================================================================ //============================================================================ // INCLUDES //============================================================================ #include <QVariant> #include <QPainter> #include "DockSplitter.h" #include "ads_globals.h" namespace ads { namespace internal { //============================================================================ void replaceSplitterWidget(QSplitter* Splitter, QWidget* From, QWidget* To) { int index = Splitter->indexOf(From); From->setParent(nullptr); Splitter->insertWidget(index, To); } //============================================================================ CDockInsertParam dockAreaInsertParameters(DockWidgetArea Area) { switch (Area) { case TopDockWidgetArea: return CDockInsertParam(Qt::Vertical, false); case RightDockWidgetArea: return CDockInsertParam(Qt::Horizontal, true); case CenterDockWidgetArea: case BottomDockWidgetArea: return CDockInsertParam(Qt::Vertical, true); case LeftDockWidgetArea: return CDockInsertParam(Qt::Horizontal, false); default: CDockInsertParam(Qt::Vertical, false); } // switch (Area) return CDockInsertParam(Qt::Vertical, false); } //============================================================================ QPixmap createTransparentPixmap(const QPixmap& Source, qreal Opacity) { QPixmap TransparentPixmap(Source.size()); TransparentPixmap.fill(Qt::transparent); QPainter p(&TransparentPixmap); p.setOpacity(Opacity); p.drawPixmap(0, 0, Source); return TransparentPixmap; } //============================================================================ void hideEmptyParentSplitters(CDockSplitter* Splitter) { while (Splitter && Splitter->isVisible()) { if (!Splitter->hasVisibleContent()) { Splitter->hide(); } Splitter = internal::findParent<CDockSplitter*>(Splitter); } } } // namespace internal } // namespace ads //--------------------------------------------------------------------------- // EOF ads_globals.cpp
31.85
80
0.534694
fereeh
2c708af8cdb9744879122b632d0604f867548fbe
18,242
cpp
C++
Statements/Connector.cpp
basselhossam/flowchart-designer-and-simulator
297cb6da45ef02b437f9622fe1662a280b2b37db
[ "MIT" ]
null
null
null
Statements/Connector.cpp
basselhossam/flowchart-designer-and-simulator
297cb6da45ef02b437f9622fe1662a280b2b37db
[ "MIT" ]
null
null
null
Statements/Connector.cpp
basselhossam/flowchart-designer-and-simulator
297cb6da45ef02b437f9622fe1662a280b2b37db
[ "MIT" ]
1
2020-05-21T22:26:35.000Z
2020-05-21T22:26:35.000Z
#include"Connector.h" #include"..\GUI\Output.h" #include"..\ApplicationManager.h" #include"Statement.h" #include"Conditional.h" #include"Start.h" #include"End.h" Connector::Connector(Statement* Src, Statement* Dst, ApplicationManager * AM, bool yes) //When a connector is created, it must have a source statement and a destination statement //There are no free connectors in the folwchart :pManager(AM), yes(yes) { SrcStat = Src; DstStat = Dst; Selected = false; make_connector(Src, Dst, AM); } Connector::Connector(ApplicationManager*AM) :pManager(AM) { } void Connector::make_connector(Statement* Src, Statement* Dst, ApplicationManager * AM) { End = Dst->GetInlet(); End.y -= 20; if (dynamic_cast<Conditional *>(Src)) { if (yes == true) { Start = dynamic_cast<Conditional *>(Src)->get_yout(); path.push_back(Start); Point p(Start.x + 10, Start.y); path.push_back(p); find_path(pManager->get_statement_list(), path, E, S, N); dynamic_cast<Conditional *>(Src)->set_Yout(this); } else { Start = dynamic_cast<Conditional *>(Src)->get_nout(); path.push_back(Start); Point p(Start.x - 10, Start.y); path.push_back(p); find_path(pManager->get_statement_list(), path, W, S, N); dynamic_cast<Conditional *>(Src)->set_Nout(this); } } else { Start = Src->GetOutlet(); path.push_back(Start); Point p(Start.x, Start.y + 10); path.push_back(p); find_path(pManager->get_statement_list(), path, W, E, S); Src->SetConnect(this); } } void Connector::Edit() { bool yes=false; Output *pOut=pManager->GetOutput(); Input * pIn = pManager->GetInput(); Point p; Statement * old_source=SrcStat; Statement * old_destination = DstStat; pOut->PrintMessage("Click on the source statement, or click in the drawing area to cancel editing"); do { pIn->getwindow()->WaitMouseClick(p.x, p.y); SrcStat = pManager->GetStatement(p); if (SrcStat == NULL) { pOut->PrintMessage("Editing was cancelled, try again"); SrcStat = old_source; DstStat = old_destination; Selected = false; return; } else if (dynamic_cast<class End *>(SrcStat)) { pOut->PrintMessage("you can't make the End statement a source statement, choose another one"); SrcStat = NULL; } else if (SrcStat->GetConnect() != old_source->GetConnect() && SrcStat->GetConnect() != NULL) { pOut->PrintMessage("Ohhhh! ,hey friend you are making a fatal mistake, the statement you are choosig has a connector"); SrcStat = NULL; } if (dynamic_cast<Conditional *>(SrcStat)) { if (p.x >= SrcStat->get_lcorner().x + SrcStat->get_width() / 2) { if (dynamic_cast<Conditional *>(SrcStat)->get_YConn() != dynamic_cast<Conditional *>(old_source)->get_YConn() && dynamic_cast<Conditional *>(SrcStat)->get_YConn() != NULL) { pOut->PrintMessage("there is no room for another YES conector"); SrcStat = NULL; } else yes = true; } else { if (dynamic_cast<Conditional *>(SrcStat)->get_NConn() != dynamic_cast<Conditional *>(old_source)->get_NConn() && dynamic_cast<Conditional *>(SrcStat)->get_NConn() != NULL) { pOut->PrintMessage("there is no room for another NO conector"); SrcStat = NULL; } yes = false; } } } while (SrcStat == NULL); //setting the destination statement pOut->PrintMessage("Click on the destination Statement, or click in the drawing area to cancel editing"); do { pIn->getwindow()->WaitMouseClick(p.x, p.y); DstStat = pManager->GetStatement(p); if (DstStat == NULL) { pOut->PrintMessage("Editing was cancelled, try again"); DstStat = old_source; SrcStat = old_destination; Selected = false; return; } else if (DstStat == SrcStat) { DstStat = NULL; pOut->PrintMessage("you can't do such stupid case, choose another statement , or click in the drawing area to cancel editing"); } else if (dynamic_cast<class Start *>(DstStat)) { pOut->PrintMessage("you can't make the Start statement a destination statement"); DstStat = NULL; } } while (DstStat == NULL); if (SrcStat != NULL && DstStat != NULL) { path.clear(); make_connector(SrcStat, DstStat, pManager); Selected = false; } pOut->PrintMessage("Editing completed"); } bool Connector::get_selected() { return Selected; } bool Connector:: check_int(Statement ** St_list, Point start, Point end) { for (int i = 0; i < pManager->get_stat_count(); i++) if (end.y >= St_list[i]->get_lcorner().y && end.y < St_list[i]->get_lcorner().y + St_list[i]->get_height() && end.x >= St_list[i]->get_lcorner().x && end.x <= St_list[i]->get_lcorner().x + St_list[i]->get_width()) return true; else if (end.y >= UI.height - UI.StBrWdth || end.y <= UI.TlBrWdth || end.x >= UI.width || end.x <= 0) return true; return false; } void Connector:: Print_info(Output * pOut) const { pOut->PrintMessage("A connector from the statement " + SrcStat->get_text()+" to the statement " +DstStat->get_text()); } void Connector::set_selected(bool s) { Selected = s; } vector <Point> & Connector:: get_path() { return path; } bool Connector::check_for_direct_path(Point start, Point end, Point & mid) { Statement ** list = pManager->get_statement_list(); int i1, i2; //case 1 mid.x = start.x; mid.y = end.y; i1 = check_barriers(list, start, mid); i2 = check_barriers(list,mid,end); if (i1 == 0 && i2 == 0) return true; else { mid.x = end.x; mid.y = start.y; i1 = check_barriers(list, start, mid); i2 = check_barriers(list, mid, end); if (i1 == 0 && i2 == 0) return true; else return false; } } //bool Connector::check_for_direct_path(Point start, Point end, Point & mid) //{ // Point p1, p2; int Case; bool b = true, a = true, c=true, d=true; // Statement ** St_list = pManager->get_statement_list(); // if (start.x < end.x && end.y > start.y) // { // p1 = start; p2 = end; Case = 1; // } // else if (start.x > end.x&&end.y < start.y) // { // p1 = end; p2 = start; Case = 1; // } // else if (start.x>end.x&&start.y < end.y) // { // p1 = start; p2 = end; Case = 2; // } // else if (start.x<end.x && start.y>end.y) // { // p1 = end; p2 = start; Case = 2; // } // // for (int i = 0; i < pManager->get_stat_count(); i++) // { // if (St_list[i]->get_lcorner().y >= p1.y - St_list[i]->get_height() && St_list[i]->get_lcorner().y <= p2.y) // { // if (St_list[i]->get_lcorner().x <= p1.x && St_list[i]->get_lcorner().x + St_list[i]->get_width() >= p1.x) // b = false; // if (St_list[i]->get_lcorner().x <= p2.x&& St_list[i]->get_lcorner().x + St_list[i]->get_width()>p2.x) // d = false; // } // if (St_list[i]->get_lcorner().x >= p1.x - St_list[i]->get_width() && St_list[i]->get_lcorner().x < p2.x) // { // if (St_list[i]->get_lcorner().y <= p1.y && St_list[i]->get_lcorner().y + St_list[i]->get_height() >= p1.y) // a = false; // if (St_list[i]->get_lcorner().y <= p2.y && St_list[i]->get_lcorner().y + St_list[i]->get_height() >= p2.y) // c = false; // } // } // // if (Case == 1) // { // if (b == true && c == true) // { // mid.x = p1.x; mid.y = p2.y; return 1; // } // else if (a == true && d == true) // { // mid.x = p2.x; mid.y = p1.y; return 1; // } // // } // else // { // if (a == true && b == true) // { // mid.x = p2.x; mid.y = p1.y; return 1; // } // else if (d == true && c == true) // { // mid.x = p1.x; mid.y = p2.y; return 1; // } // } // return 0; //} int Connector::get_last_direc(vector<Point>path) { if (path[path.size() - 2].x == path[path.size() - 1].x && path[path.size() - 1].y > path[path.size() - 2].y) // downwards return 3; else if (path[path.size() - 2].x == path[path.size() - 1].x && path[path.size() - 1].y < path[path.size() - 2].y) //upwards return 1; else if (path[path.size() - 2].y == path[path.size() - 1].y && path[path.size() - 2].x < path[path.size() - 1].x) //right return 2; else return 4; //left } int Connector::check_barriers(Statement ** List, Point p1, Point p2) { Point start, end; if (p1.x == p2.x) //vertical line { if (p1.y > p2.y) { start = p2; end = p1; //start is always the upper point } else { start = p1; end = p2; //the same } for (int i = 0; i<pManager->get_stat_count(); i++) { if (List[i]->get_lcorner().x <= end.x && List[i]->get_lcorner().x + List[i]->get_width()>=end.x) if (List[i]->get_lcorner().y >= start.y - List[i]->get_height() && List[i]->get_lcorner().y <= end.y) return 1; } if (start.y <= UI.TlBrWdth || end.y >= UI.height - UI.StBrWdth) return -1; else return 0; } else { if (p1.x > p2.x) { start = p1; end = p2; } else { start = p2; end = p1; } for (int i = 0; i < pManager->get_stat_count(); i++) { if (List[i]->get_lcorner().y<=end.y && List[i]->get_lcorner().y + List[i]->get_height()>=end.y) if (List[i]->get_lcorner().x >= end.x - List[i]->get_width() && List[i]->get_lcorner().x <= start.x) return 1; } if (end.x <= 0 || start.x >= UI.width) return -1; else return 0; } } void Connector:: modify() { Connector ** list = pManager->get_conn_list(); vector<Point> PATH; for (int i = 0; i < pManager->get_ConnCount(); i++) { if (list[i] != this) { PATH = list[i]->get_path(); for (int g = 1; g < path.size()-1; g++) for (int j = 1; j < list[i]->get_path().size(); j++) { if (path[g].x == path[g - 1].x && PATH[j].x==PATH[j-1].x)//vertical { if ((path[g].y>PATH[j].y && path[g - 1].y < PATH[j].y || path[g].y<PATH[j].y && path[g - 1].y>PATH[j].y) || (path[g].y>PATH[j - 1].y && path[g - 1].y < PATH[j - 1].y || path[g].y<PATH[j - 1].y && path[g - 1].y>PATH[j - 1].y) || (abs(path[g].y - PATH[j].y)<4 || abs(path[g - 1].y - PATH[j].y)<4 || abs(path[g - 1].y - PATH[j - 1].y)<4 || abs(path[g].y - PATH[j-1].y)<4)) { path[g].x += 10; path[g - 1].x += 10; } } else if(path[g].y == path[g - 1].y && PATH[j].y == PATH[j - 1].y)//horizontal { if ((path[g].x>PATH[j].x && path[g - 1].x < PATH[j].x || path[g].x<PATH[j].x && path[g - 1].x>PATH[j].x) || (path[g].x>PATH[j - 1].x && path[g - 1].x < PATH[j - 1].x || path[g].x<PATH[j - 1].x && path[g - 1].x>PATH[j - 1].x) || (abs(path[g].x - PATH[j].x) < 4 || abs(path[g - 1].x - PATH[j].x) < 4 || abs(path[g - 1].x - PATH[j - 1].x) < 4 || abs(path[g].x - PATH[j - 1].x) < 4)) { path[g].y += 10; path[g - 1].y += 10; } } } } } } void Connector::find_path(Statement ** St_list, vector<Point> & v1, direc a, direc b, direc c) { vector<Point> va=v1, vb=v1, vc=v1; bool p1, p2, p3; p1 = set_path(St_list, va, a); p2 = set_path(St_list, vb, b); p3 = set_path(St_list, vc, c); if (p1 == true && p2 == false && p3 == false) v1 = va; else if (p1 == false && p2 == true && p3 == false) v1 = vb; else if (p1 == false && p2 == false && p3 == true) v1 = vc; else if (p1 == true && p2 == true && p3 == false) { if (dist(va)<=dist(vb)) v1 = va; else v1 = vb; } else if (p1 == false && p2 == true && p3 == true) { if (dist(vb) <= dist(vc)) v1 = vb; else v1 = vc; } else if (p1 == true && p2 == false && p3 == true) { if (dist(va) <= dist(vc)) v1 = va; else v1 = vc; } else { if (p1 == false) va.clear(); if (p2 == false) vb.clear(); if (p3 == false) vc.clear(); int va_dist = dist(va); int vb_dist = dist(vb); int vc_dist = dist(vc); int s = min(va_dist,min(vb_dist,vc_dist)); if (s == va_dist) v1 = va; else if (s == vb_dist) v1 = vb; else v1 = vc; } } bool Connector:: set_path(Statement ** St_list, vector<Point> & v1, direc d) { if (v1.size() == 10) return false; Point mid; if (check_for_direct_path(v1[v1.size() - 1], End, mid)) { v1.push_back(mid); v1.push_back(End); return 1; } int k = 0; //for checking the val. of check barriers vector<Point> v2,v3; bool way1, way2; v1.push_back(v1[v1.size() - 1]); if (d == E) //towards east { while (1) { v1[v1.size() - 1].x+=20; k=check_barriers(St_list, v1[v1.size() - 1], v1[v1.size() - 2]); if (k == -1) return false; else if (k == 0) { if (check_for_direct_path(v1[v1.size() - 1], End, mid)) { v1.push_back(mid); v1.push_back(End); return 1; } } else break; } v1[v1.size() - 1].x -= 20; v2 = v1; v3 = v1; way1 = set_path(St_list, v2, N); way2 = set_path(St_list, v3, S); } else if (d == W) //towards east { while (1) { v1[v1.size() - 1].x -= 20; k = check_barriers(St_list, v1[v1.size() - 1], v1[v1.size() - 2]); if (k == -1) return false; else if (k == 0) { if (check_for_direct_path(v1[v1.size() - 1], End, mid)) { v1.push_back(mid); v1.push_back(End); return 1; } } else break; } v1[v1.size() - 1].x += 20; v2 = v1; v3 = v1; way1 = set_path(St_list, v2, N); way2 = set_path(St_list, v3, S); } else if (d == N) //towards north { while (1) { v1[v1.size() - 1].y -= 20; k = check_barriers(St_list, v1[v1.size() - 1], v1[v1.size() - 2]); if (k == -1) return false; else if (k == 0) { if (check_for_direct_path(v1[v1.size() - 1], End, mid)) { v1.push_back(mid); v1.push_back(End); return 1; } } else break; } v1[v1.size() - 1].y += 20; v2 = v1; v3 = v1; way1 = set_path(St_list, v2, E); way2 = set_path(St_list, v3, W); } else if (d == S) //towards south { while (1) { v1[v1.size() - 1].y += 20; k = check_barriers(St_list, v1[v1.size() - 1], v1[v1.size() - 2]); if (k == -1) return false; else if (k == 0) { if (check_for_direct_path(v1[v1.size() - 1], End, mid)) { v1.push_back(mid); v1.push_back(End); return 1; } } else break; } v1[v1.size() - 1].y -= 20; v2 = v1; v3 = v1; way1 = set_path(St_list, v2, E); way2 = set_path(St_list, v3, W); } if (way1 == false && way2 == false) return false; else if (way1 == true && way2 == false) { v1 = v2; return true; } else if (way1 == false && way2 == true) { v1 = v3; return true; } else { if (dist(v3)<=dist(v2)) { v1 = v3; } else v1 = v2; return true; } } int Connector:: dist(vector<Point> v) { int sum = 0, m; for (int i = 1; i < int(v.size()); i++) { if (v[i].x == v[i - 1].x) { m = v[i].y - v[i - 1].y; sum += m < 0 ? -m : m; } else { m = v[i].x - v[i - 1].x; sum += m < 0 ? -m : m; } } return sum; } /* int Connector:: check_for_direct_path(Point start, Point end) { int c1=0, c2=0; //counters for the numbers of the intersections Statement ** ptr = pManager->get_statement_list(); if (end.x> start.x && end.y>start.y) for (int i = 0; i < pManager->get_stat_count(); i++) { if (ptr[i]->get_lcorner().y >= start.y - ptr[i]->get_height() && ptr[i]->get_lcorner().y <= end.y) { if (start.x >= ptr[i]->get_lcorner().x && start.x <= ptr[i]->get_lcorner().x + ptr[i]->get_width()) c1++; else if (end.x >= ptr[i]->get_lcorner().x && end.x <= ptr[i]->get_lcorner().x + ptr[i]->get_width()) c2++; } if (ptr[i]->get_lcorner().x >= start.x - ptr[i]->get_width() && ptr[i]->get_lcorner().x <= end.x) { if (start.y >= ptr[i]->get_lcorner().y && start.y <= ptr[i]->get_lcorner().y + ptr[i]->get_height()) c2++; else if (end.y >= ptr[i]->get_lcorner().y && end.y <= ptr[i]->get_lcorner().y + ptr[i]->get_height()) c1++; } } else if (end.y<start.y && end.x>start.x) for (int i = 0; i < pManager->get_stat_count(); i++) { if () } } */ void Connector::setSrcStat(Statement *Src) { SrcStat = Src; } Statement* Connector::getSrcStat() { return SrcStat; } void Connector::setDstStat(Statement *Dst) { DstStat = Dst; } Statement* Connector::getDstStat() { return DstStat; } void Connector::setStartPoint(Point P) { Start = P; } Point Connector::getStartPoint() { return Start; } void Connector::setEndPoint(Point P) { End = P; } Point Connector::getEndPoint() { return End; } void Connector::Draw(Output* pOut) const { pOut->Draw_connector(path,Selected); ///TODO: Call output to draw a connector from SrcStat to DstStat on the output window } void Connector::Save(ofstream &OutFile){ OutFile << SrcStat->get_ID() << " " << DstStat->get_ID() << " "; Conditional*ptr = dynamic_cast<Conditional*>(SrcStat); if (ptr) { if (ptr->get_YConn() == this) OutFile << 1 << " "; else if (ptr->get_NConn() == this) OutFile << 2 << " "; } else OutFile << 0 << " "; OutFile << endl; } void Connector::Load(ifstream &Infile) { int x, y, z; Infile >> x; for (int i = 0; i<pManager->get_stat_count(); i++) { if (pManager->get_statement_list()[i]->get_ID() == x) { SrcStat = pManager->get_statement_list()[i]; pManager->get_statement_list()[i]->SetConnect(this); break; } } Infile >> y; for (int i = 0; i<pManager->get_stat_count(); i++) { if (pManager->get_statement_list()[i]->get_ID() == y) { DstStat = pManager->get_statement_list()[i]; DstStat->SetConnected(true); break; } } End = DstStat->GetInlet(); End.y -= 20; Selected = false; Infile >> z; Conditional*ptr = dynamic_cast<Conditional*> (SrcStat); if (z != 0 && ptr) { if (z == 1) yes = true; else yes = false; } make_connector(SrcStat, DstStat, pManager); }
25.911932
216
0.544184
basselhossam
2c778ee8f5b00c514c7a70759cb079e9a3ce3a7f
1,867
cpp
C++
src/led.cpp
Schumbi/flurlampe
47b8377e39db2857aa34e5f6f7181921e9330b8a
[ "MIT" ]
null
null
null
src/led.cpp
Schumbi/flurlampe
47b8377e39db2857aa34e5f6f7181921e9330b8a
[ "MIT" ]
null
null
null
src/led.cpp
Schumbi/flurlampe
47b8377e39db2857aa34e5f6f7181921e9330b8a
[ "MIT" ]
null
null
null
#include <Arduino.h> #include "led.hpp" static const uint8_t ON = 1; static const uint8_t OFF = 0; // Implementation of Led Class CLed_base::CLed_base(const uint8_t pin) { this->pin = pin; pinMode(this->pin, OUTPUT); digitalWrite(this->pin, OFF); } CLed_base::~CLed_base() { digitalWrite(this->pin, OFF); } //############################### CLed::CLed(const uint8_t pin) : CLed_base::CLed_base(pin) { this->state = false; } // change power level of LED void CLed::power(bool state) { // store state this->state = state; // set state if(state) digitalWrite(this->pin, ON); else digitalWrite(this->pin, OFF); } // Activate LED void CLed::switch_on() { this->power(true); } // deactivate LED void CLed::switch_off() { this->power(false); } bool CLed::isOn() { return this->state; } //############################### CLed_fade::CLed_fade(const uint8_t pin) : CLed(pin) { this->init = false; } void CLed_fade::setUp(const brightness_t &prog) { this->brightness.max = prog.max; this->brightness.min = prog.min; this->brightness.val = prog.val; this->brightness.fadeAmount = prog.fadeAmount; this->init = true; } void CLed_fade::fade() { int check = 0; // wenn die LED angeschlatet ist if(this->isOn() && this->init) { analogWrite(this->pin, this->brightness.val); brightness_t &b = this->brightness; // avoid overflows check = b.val + b.fadeAmount; if(check > 255) b.fadeAmount = 255 - b.val; if(check < 0) b.fadeAmount = 0 + b.val; b.val = b.val + b.fadeAmount; if(b.val <= b.min || b.val >= b.max) { // reverse direction b.fadeAmount = -b.fadeAmount; } } // nothing will happen, if LED is switched off } void CLed_fade::power(bool state) { // store state this->state = state; // set state if(state) analogWrite(this->pin, this->brightness.min); else analogWrite(this->pin, 0); }
16.522124
47
0.634708
Schumbi
2c79bedccdbf013f38eb112c5bdf8530b2fc4d65
1,185
cpp
C++
recursion/Leaf-Similar_Trees_872.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
recursion/Leaf-Similar_Trees_872.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
recursion/Leaf-Similar_Trees_872.cpp
obviouskkk/leetcode
5d25c3080fdc9f68ae79e0f4655a474a51ff01fc
[ "BSD-3-Clause" ]
null
null
null
/* *********************************************************************** > File Name: Leaf-Similar_Trees_872.cpp > Author: zzy > Mail: 942744575@qq.com > Created Time: Fri 09 Aug 2019 11:21:57 AM CST ********************************************************************** */ #include <stdio.h> #include <vector> #include <string> #include <stdio.h> #include <climits> #include <gtest/gtest.h> using std::vector; using std::string; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; /* * 872. 叶子相似的树 * * 请考虑一颗二叉树上所有的叶子,这些叶子的值按从左到右的顺序排列形成一个 叶值序列 。 * * 判断两棵树的叶子节点组成的序列是否相等 * * */ class Solution { public: void dfs(TreeNode* root, vector<int> & v) { if (root == nullptr) return; if (root->left == nullptr && root->right == nullptr) { v.push_back(root->val); } dfs(root->left, v); dfs(root->right, v); } bool leafSimilar(TreeNode* root1, TreeNode* root2) { vector<int> v1, v2; dfs(root1, v1); dfs(root2, v2); return v1 == v2; } }; TEST(testCase,test0) { } int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc,argv); return RUN_ALL_TESTS(); }
17.686567
74
0.55865
obviouskkk
2c7ecd3ca25f3fc3a264c210cc5db7c367dbd8b2
1,835
cpp
C++
service/src/sys/date.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
4
2021-01-23T14:36:34.000Z
2021-06-07T10:02:28.000Z
service/src/sys/date.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
1
2019-08-04T19:15:56.000Z
2019-08-04T19:15:56.000Z
service/src/sys/date.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
1
2022-01-29T22:41:01.000Z
2022-01-29T22:41:01.000Z
#include <exodus/library.h> libraryinit() function main(in type, in in0, in mode0, out output, in glang) { //c sys in,in,in,out,in //should really be sensitive to timezone in @SW var inx = in0; var mode = mode0; if (inx eq "") { output = ""; return 0; } var nospaces = mode.index("*"); if (nospaces) { mode.converter("*", ""); } if (mode) { if (mode eq "4") { mode = DATEFMT; mode.splicer(2, 1, "4"); } } else { if (DATEFMT) { mode = DATEFMT; } else { mode = "D2/E"; } } //status=0 if (type eq "OCONV") { //dont oconv 1 or 2 digits as they are probably day of month being converted // to proper dates //IF len(inx) gt 2 and inx MATCHES '0N' OR inx MATCHES '"-"0N' OR inx MATCHES '0N.0N' THEN if (inx.length() gt 2 and inx.match("^\\d*$")) { goto ok; } if (inx.match("^-\\d*$") or inx.match("^\\d*\\.\\d*$")) { ok: //language specific (date format could be a pattern in lang?) if (mode eq "L") { var tt = inx.oconv("D4/E"); var mth = glang.a(2).field("|", tt.field("/", 2)); var day = tt.field("/", 1); var year = tt.field("/", 3); //if 1 then output = day ^ " " ^ mth ^ " " ^ year; //end else // output=mth:' ':day:' ':year // end } else { output = oconv(inx, mode); if (output[1] eq "0") { output.splicer(1, 1, " "); } if (output[4] eq "0") { output.splicer(4, 1, " "); } if (output.substr(4, 3).match("^[A-Za-z]{3}$")) { output.splicer(7, 1, ""); output.splicer(3, 1, ""); } if (nospaces) { output.converter(" ", ""); } } } else { output = inx; } } else if (type eq "ICONV") { if (inx.match("^\\d*$") and inx le 31) { inx ^= var().date().oconv("D").substr(4, 9); } output = iconv(inx, mode); } return 0; } libraryexit()
17.47619
92
0.513896
BOBBYWY
2c83e6ae536dcc9983b1c0292c52cb07eed0548a
5,683
hpp
C++
worm.hpp
gcwnow/liero
d86387ef871a809671be790ebf9af6833f38b4bc
[ "BSD-2-Clause" ]
6
2018-04-30T16:11:35.000Z
2021-08-22T07:29:02.000Z
worm.hpp
gameblabla/liero-nspire
1e5a8f2bda190e4895e933c6f7a346f5f39963d6
[ "BSD-2-Clause" ]
null
null
null
worm.hpp
gameblabla/liero-nspire
1e5a8f2bda190e4895e933c6f7a346f5f39963d6
[ "BSD-2-Clause" ]
1
2019-05-16T17:59:26.000Z
2019-05-16T17:59:26.000Z
#ifndef LIERO_WORM_HPP #define LIERO_WORM_HPP #include "math.hpp" #include <SDL/SDL.h> #include <string> #include <cstring> struct Worm; struct Ninjarope { Ninjarope() : out(false) , attached(false) , anchor(0) { } bool out; //Is the ninjarope out? bool attached; Worm* anchor; // If non-zero, the worm the ninjarope is attached to fixed x, y, velX, velY; //Ninjarope props // Not needed as far as I can tell: fixed forceX, forceY; int length, curLen; void process(Worm& owner); }; struct Controls { bool up, down, left, right; bool fire, change, jump; }; struct WormWeapon { WormWeapon() : id(0) , ammo(0) , delayLeft(0) , loadingLeft(0) , available(true) { } int id; int ammo; int delayLeft; int loadingLeft; bool available; }; struct WormSettings { enum { Up, Down, Left, Right, Fire, Change, Jump }; WormSettings() : health(100) , controller(0) , randomName(true) , colour(0) { rgb[0] = 26; rgb[1] = 26; rgb[2] = 62; std::memset(weapons, 0, sizeof(weapons)); } int health; int controller; // CPU / Human Uint32 controls[7]; int weapons[5]; // TODO: Adjustable std::string name; int rgb[3]; bool randomName; int colour; int selWeapX; }; /* typedef struct _settings { long m_iHealth[2]; char m_iController[2]; char m_iWeapTable[40]; long m_iMaxBonuses; long m_iBlood; long m_iTimeToLose; long m_iFlagsToWin; char m_iGameMode; bool m_bShadow; bool m_bLoadChange; bool m_bNamesOnBonuses; bool m_bRegenerateLevel; BYTE m_iControls[2][7]; BYTE m_iWeapons[2][5]; long m_iLives; long m_iLoadingTime; bool m_bRandomLevel; char m_bWormName[2][21]; char m_bLevelFile[13]; BYTE m_iWormRGB[2][3]; bool m_bRandomName[2]; bool m_bMap; bool m_bScreenSync; } SETTINGS, *PSETTINGS; */ struct Viewport; struct Worm { enum { RFDown, RFLeft, RFUp, RFRight }; Worm(WormSettings* settings, int index, int wormSoundID) : x(0), y(0), velX(0), velY(0) , hotspotX(0), hotspotY(0) , aimingAngle(0), aimingSpeed(0) , ableToJump(false), ableToDig(false) //The previous state of some keys , keyChangePressed(false) , movable(false) , animate(false) //Should the worm be animated? , visible(false) //Is the worm visible? , ready(false) //Is the worm ready to play? , flag(false) //Has the worm a flag? , makeSightGreen(false) //Changes the sight color , health(0) //Health left , lives(0) //lives left , kills(0) //Kills made , timer(0) //Timer for GOT , killedTimer(0) //Time until worm respawns , currentFrame(0) , flags(0) //How many flags does this worm have? , currentWeapon(0) , fireConeActive(false) , lastKilledBy(0) , fireCone(0) , leaveShellTimer(0) , settings(settings) , viewport(0) , index(index) , wormSoundID(wormSoundID) , direction(0) { } int keyLeft() { return settings->controls[WormSettings::Left]; } int keyRight() { return settings->controls[WormSettings::Right]; } int keyUp() { return settings->controls[WormSettings::Up]; } int keyDown() { return settings->controls[WormSettings::Down]; } int keyFire() { return settings->controls[WormSettings::Fire]; } int keyChange() { return settings->controls[WormSettings::Change]; } int keyJump() { return settings->controls[WormSettings::Jump]; } void beginRespawn(); void doRespawning(); void process(); void processWeapons(); void processPhysics(); void processMovement(); void processTasks(); void processAiming(); void processWeaponChange(); void processSteerables(); void fire(); void processSight(); void calculateReactionForce(int newX, int newY, int dir); void processLieroAI(); // Move? fixed x, y; //Worm position fixed velX, velY; //Worm velocity int hotspotX, hotspotY; //Hotspots for laser, laser sight, etc. fixed aimingAngle, aimingSpeed; Controls controls; bool ableToJump, ableToDig; //The previous state of some keys bool keyChangePressed; bool movable; bool animate; //Should the worm be animated? bool visible; //Is the worm visible? bool ready; //Is the worm ready to play? bool flag; //Has the worm a flag? bool makeSightGreen; //Changes the sight color int health; //Health left int lives; //lives left int kills; //Kills made int timer; //Timer for GOT int killedTimer; //Time until worm respawns int currentFrame; int flags; //How many flags does this worm have? Ninjarope ninjarope; int currentWeapon; //The selected weapon bool fireConeActive; //Is the firecone showing Worm* lastKilledBy; // What worm that last killed this worm int fireCone; //How much is left of the firecone int leaveShellTimer; //Time until next shell drop WormSettings* settings; Viewport* viewport; int index; // 0 or 1 int wormSoundID; int reacts[4]; WormWeapon weapons[5]; int direction; }; bool checkForWormHit(int x, int y, int dist, Worm* ownWorm); bool checkForSpecWormHit(int x, int y, int dist, Worm& w); #endif // LIERO_WORM_HPP
21.773946
75
0.605666
gcwnow
2c84c897f33da96ee6034986b4326dd8d4334adf
11,857
cpp
C++
src/RTL/Component/Exporting/CIFXViewNodeEncoder.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
44
2016-05-06T00:47:11.000Z
2022-02-11T06:51:37.000Z
src/RTL/Component/Exporting/CIFXViewNodeEncoder.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
3
2016-06-27T12:37:31.000Z
2021-03-24T12:39:48.000Z
src/RTL/Component/Exporting/CIFXViewNodeEncoder.cpp
alemuntoni/u3d
7907b907464a2db53dac03fdc137dcb46d447513
[ "Apache-2.0" ]
15
2016-02-28T11:08:30.000Z
2021-06-01T03:32:01.000Z
//*************************************************************************** // // Copyright (c) 2001 - 2006 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //*************************************************************************** /** @file CIFXViewNodeEncoder.cpp Implementation of the CIFXViewNodeEncoder. The CIFXViewNodeEncoder contains view node encoding functionality that is used by the write manager. */ #include "CIFXViewNodeEncoder.h" #include "IFXBlockTypes.h" #include "IFXCheckX.h" #include "IFXException.h" #include "IFXPalette.h" #include "IFXView.h" #include "IFXMetaDataX.h" #include "IFXAutoRelease.h" // constructor CIFXViewNodeEncoder::CIFXViewNodeEncoder() { m_bInitialized = FALSE; m_uRefCount = 0; } // destructor CIFXViewNodeEncoder::~CIFXViewNodeEncoder() { } // IFXUnknown U32 CIFXViewNodeEncoder::AddRef() { return ++m_uRefCount; } U32 CIFXViewNodeEncoder::Release() { if ( !( --m_uRefCount ) ) { delete this; // This second return point is used so that the deleted object's // reference count isn't referenced after the memory is released. return 0; } return m_uRefCount; } IFXRESULT CIFXViewNodeEncoder::QueryInterface( IFXREFIID interfaceId, void** ppInterface ) { IFXRESULT rc = IFX_OK; if ( ppInterface ) { if ( interfaceId == IID_IFXEncoderX ) { *ppInterface = ( IFXEncoderX* ) this; this->AddRef(); } else if ( interfaceId == IID_IFXUnknown ) { *ppInterface = ( IFXUnknown* ) this; this->AddRef(); } else { *ppInterface = NULL; rc = IFX_E_UNSUPPORTED; } } else rc = IFX_E_INVALID_POINTER; IFXRETURN(rc); } // IFXEncoderX void CIFXViewNodeEncoder::EncodeX( IFXString& rName, IFXDataBlockQueueX& rDataBlockQueue, F64 units ) { IFXDataBlockX* pDataBlock = NULL; IFXPalette* pTexPalette = NULL; IFXView* pView = NULL; U32 attributes = 0; try { // The view node block has the following sections: // // Node data // // 1.1. View node name (IFXString) // 1.2. Parent node name (IFXString) // 1.3. UserPropertyList (IFXString) // 2. Local matrix (16*F32) // // View specific data // // 3. View resource name (IFXString) // // 4. Attributes (U32) // // 5. View Clip Planes & Projection // 5.1 View Near Clip (F32) // 5.2 View Far Clip (F32) // 5.3 View Projection (F32) // or // 5.3 Ortho height (F32) // // 6. Viewport // 6.1 Size (F32 * 2) // 6.2 Position (F32 * 2) // // // 7. Number of backdrops (U32) // For Each Backdrop: // 7.0 Texture Name (IFXString) // 7.1 Texture blend (F32) // 7.2 Backdrop rotation (F32) // 7.3, 7.4 Backdrop location (F32 * 2) // 7.5, 7.6 Backdrop regpoint (I32 * 2) // 7.7, 7.8 Backdrop scale (F32 * 2) // // 7. Number of overlays (U32) // For Each Overlay: // 7.0 Texture Name (IFXString) // 7.1 Texture blend (F32) // 7.2 Overlay rotation (F32) // 7.3, 7.4 Overlay location (F32 * 2) // 7.5, 7.6 Overlay regpoint (I32 * 2) // 7.7, 7.8 Overlay scale (F32 * 2) // // use node base class to encode shared node data (i.e. data that all node // types possess) // check for initialization if ( FALSE == CIFXViewNodeEncoder::m_bInitialized ) throw IFXException( IFX_E_NOT_INITIALIZED ); if( units <= 0.0f ) throw IFXException( IFX_E_INVALID_RANGE ); // get palettes IFXCHECKX(m_pSceneGraph->GetPalette( IFXSceneGraph::TEXTURE, &pTexPalette )); // get the view (node) interface of the node if ( NULL == m_pNode ) throw IFXException( IFX_E_CANNOT_FIND ); // 1. View node name (IFXString) // 2. Parent node name (IFXString) // 3. UserPropertyList (IFXString) // 4. Local matrix (16*F32) CIFXNodeBaseEncoder::CommonNodeEncodeU3D( rName, units ); IFXCHECKX( m_pNode->QueryInterface( IID_IFXView, (void**)&pView ) ); if ( NULL == pView ) throw IFXException( IFX_E_UNSUPPORTED ); // get resource name IFXString sName; U32 uViewResourceIndex = 0; pView->GetViewResourceID( &uViewResourceIndex ); IFXDECLARELOCAL( IFXPalette, pViewResourcePalette ); IFXCHECKX( m_pSceneGraph->GetPalette( IFXSceneGraph::VIEW, &pViewResourcePalette ) ); if ( uViewResourceIndex != (U32)(-1) ) { IFXCHECKX( pViewResourcePalette->GetName( uViewResourceIndex, &sName) ); } else { IFXCHECKX( sName.Assign(L"") ); // make it a null string } // 3. Resource name (IFXString) m_pBitStream->WriteIFXStringX( sName ); // 4. Attributes (U32) /* Attributes: 0x00000000: default values (3-point perspective projection and screen position units in screen pixels) 0x00000001: screen position units: percentage of screen dimension 0x00000002: projection mode: ortho 0x00000004: projection mode: 2-point perspective 0x00000008: projection mode: 1-point perspective */ attributes = pView->GetAttributes(); m_pBitStream->WriteU32X( attributes ); // 5. View Clip Planes & Projection // 5.1 View Near Clip (F32) m_pBitStream->WriteF32X(pView->GetNearClip()/(F32)units); // 5.2 View Far Clip (F32) F32 fTemp = pView->GetFarClip(); if( FLT_MAX * (F32)units < fTemp ) fTemp = FLT_MAX * (F32)units; m_pBitStream->WriteF32X(fTemp/(F32)units); const U32 attributesMasked = attributes & ~IFX_PERCENTDIMEN; // mask screen position unit if( IFX_PERSPECTIVE3 == attributesMasked ) // 3-point perspective, default { IFXCHECKX(pView->GetProjection(&fTemp)); m_pBitStream->WriteF32X(fTemp); } else if ( IFX_ORTHOGRAPHIC == attributesMasked ) // ortho { IFXCHECKX(pView->GetOrthoHeight(&fTemp)); m_pBitStream->WriteF32X(fTemp); } else if( IFX_PERSPECTIVE2 == attributesMasked ) // 2-point perspective { IFXCHECKX(pView->GetProjection(&fTemp)); // Since we don't have support for this type of projection // then just use old value and write it three times to // match the spec m_pBitStream->WriteF32X(fTemp); m_pBitStream->WriteF32X(fTemp); m_pBitStream->WriteF32X(fTemp); } else if( IFX_PERSPECTIVE1 == attributesMasked ) // 1-point perspective { IFXCHECKX(pView->GetProjection(&fTemp)); // Since we don't have support for this type of projection // then just use old value and write it three times to // match the spec m_pBitStream->WriteF32X(fTemp); m_pBitStream->WriteF32X(fTemp); m_pBitStream->WriteF32X(fTemp); } // 6. Viewport IFXF32Rect rcViewport; IFXCHECKX(pView->GetViewport(rcViewport)); // 6.1 Size (F32 * 2) m_pBitStream->WriteF32X(rcViewport.m_Width); m_pBitStream->WriteF32X(rcViewport.m_Height); // 6.2 Position (F32 * 2) m_pBitStream->WriteF32X(rcViewport.m_X); m_pBitStream->WriteF32X(rcViewport.m_Y); U32 uNumLayers = 0; // 7. Number of backdrops IFXCHECKX(pView->GetLayerCount(IFX_VIEW_BACKDROP, uNumLayers)); m_pBitStream->WriteU32X(uNumLayers); // For Each Backdrop: U32 i; for(i = 0; i < uNumLayers; i++) { IFXString tempString; IFXViewLayer layer; IFXCHECKX(pView->GetLayer(IFX_VIEW_BACKDROP, i, layer)); // 7.0 Texture Name (IFXString) IFXCHECKX( pTexPalette->GetName( layer.m_uTextureId, &tempString ) ); m_pBitStream->WriteIFXStringX(tempString); // 7.1 Texture blend (F32) m_pBitStream->WriteF32X(layer.m_fBlend); // 7.2 Backdrop rotation (F32) m_pBitStream->WriteF32X(layer.m_fRotation); // 7.3, 7.4 Backdrop location (F32 * 2) m_pBitStream->WriteF32X((F32)layer.m_iLocX); m_pBitStream->WriteF32X((F32)layer.m_iLocY); // 7.5, 7.6 Backdrop regpoint (I32 * 2) m_pBitStream->WriteI32X(layer.m_iRegX); m_pBitStream->WriteI32X(layer.m_iRegY); // 7.7, 7.8 Backdrop scale (F32 * 2) m_pBitStream->WriteF32X(layer.m_vScale.X()); m_pBitStream->WriteF32X(layer.m_vScale.Y()); } // 7. Number of overlays IFXCHECKX(pView->GetLayerCount(IFX_VIEW_OVERLAY, uNumLayers)); m_pBitStream->WriteU32X(uNumLayers); // For Each Overlay: for(i = 0; i < uNumLayers; i++) { IFXString tempString; IFXViewLayer layer; IFXCHECKX(pView->GetLayer(IFX_VIEW_OVERLAY, i, layer)); // 7.0 Texture Name (IFXString) IFXCHECKX( pTexPalette->GetName( layer.m_uTextureId, &tempString ) ); m_pBitStream->WriteIFXStringX(tempString); // 7.1 Texture blend (F32) m_pBitStream->WriteF32X(layer.m_fBlend); // 7.2 Backdrop rotation (F32) m_pBitStream->WriteF32X(layer.m_fRotation); // 7.3, 7.4 Backdrop location (F32 * 2) m_pBitStream->WriteF32X((F32)layer.m_iLocX); m_pBitStream->WriteF32X((F32)layer.m_iLocY); // 7.5, 7.6 Backdrop regpoint (I32 * 2) m_pBitStream->WriteI32X(layer.m_iRegX); m_pBitStream->WriteI32X(layer.m_iRegY); // 7.7, 7.8 Backdrop scale (F32 * 2) m_pBitStream->WriteF32X(layer.m_vScale.X()); m_pBitStream->WriteF32X(layer.m_vScale.Y()); } // Get the block m_pBitStream->GetDataBlockX( pDataBlock ); // Set the data block type pDataBlock->SetBlockTypeX( BlockType_NodeViewU3D ); // Set the Priority on the Datablock pDataBlock->SetPriorityX(0); // set metadata IFXDECLARELOCAL(IFXMetaDataX, pBlockMD); IFXDECLARELOCAL(IFXMetaDataX, pObjectMD); pDataBlock->QueryInterface(IID_IFXMetaDataX, (void**)&pBlockMD); m_pNode->QueryInterface(IID_IFXMetaDataX, (void**)&pObjectMD); pBlockMD->AppendX(pObjectMD); // Put the data block on the list rDataBlockQueue.AppendBlockX( *pDataBlock ); // clean up: IFXRELEASE( pTexPalette ); IFXRELEASE( pDataBlock ); IFXRELEASE( pView ); } catch ( ... ) { // release IFXCOM objects IFXRELEASE( pDataBlock ); IFXRELEASE( pTexPalette ); IFXRELEASE( pView ); throw; } } void CIFXViewNodeEncoder::InitializeX( IFXCoreServices& rCoreServices ) { try { // initialize base class(es) CIFXNodeBaseEncoder::Initialize( rCoreServices ); // initialize locally if ( TRUE == CIFXNodeBaseEncoder::m_bInitialized ) CIFXViewNodeEncoder::m_bInitialized = TRUE; else CIFXViewNodeEncoder::m_bInitialized = FALSE; } catch ( ... ) { throw; } } void CIFXViewNodeEncoder::SetObjectX( IFXUnknown& rObject ) { IFXNode* pNode = NULL; try { // get the IFXNode interface IFXCHECKX( rObject.QueryInterface( IID_IFXNode, (void**)&pNode ) ); if ( NULL == pNode ) throw IFXException( IFX_E_UNSUPPORTED ); // set the node on the CIFXNodeBaseEncoder base class CIFXNodeBaseEncoder::SetNode( *pNode ); // clean up IFXRELEASE( pNode ); } catch ( ... ) { IFXRELEASE( pNode ); throw; } } // Factory friend IFXRESULT IFXAPI_CALLTYPE CIFXViewNodeEncoder_Factory( IFXREFIID interfaceId, void** ppInterface ) { IFXRESULT rc = IFX_OK; if ( ppInterface ) { // Create the CIFXLoadManager component. CIFXViewNodeEncoder *pComponent = new CIFXViewNodeEncoder; if ( pComponent ) { // Perform a temporary AddRef for our usage of the component. pComponent->AddRef(); // Attempt to obtain a pointer to the requested interface. rc = pComponent->QueryInterface( interfaceId, ppInterface ); // Perform a Release since our usage of the component is now // complete. Note: If the QI fails, this will cause the // component to be destroyed. pComponent->Release(); } else rc = IFX_E_OUT_OF_MEMORY; } else rc = IFX_E_INVALID_POINTER; IFXRETURN( rc ); }
25.664502
104
0.675129
alemuntoni
2c8f9594fe16366658412f7faa80903a46e1e047
506
cpp
C++
Introduction/Basics/Logging.cpp
Campeanu/ProjectZero
33d2ff9f4761e265175b715ba0948d492a7f4541
[ "MIT" ]
null
null
null
Introduction/Basics/Logging.cpp
Campeanu/ProjectZero
33d2ff9f4761e265175b715ba0948d492a7f4541
[ "MIT" ]
null
null
null
Introduction/Basics/Logging.cpp
Campeanu/ProjectZero
33d2ff9f4761e265175b715ba0948d492a7f4541
[ "MIT" ]
null
null
null
// Logging #include <iostream> // This is the main function int main(int argc, char* argv[]) { /** * Every function has a local predefined variable __func__ that looks as follows: * static const char __func__[] = "function-name"; */ std::cout << __func__ << std::endl; std::cout << __FUNCTION__ << std::endl; // __PRETTY_FUNCTION__ not supported on Visual Studio std::cout << __PRETTY_FUNCTION__ << std::endl; std::cout << __LINE__ << std::endl; return 0; }
23
85
0.634387
Campeanu
2c96a50fc9f495ffab483db9d79a784c509f9c39
1,141
hpp
C++
boost/sequence/elements.hpp
ericniebler/time_series
4040119366cc21f25c7734bb355e4a647296a96d
[ "BSL-1.0" ]
11
2015-02-21T11:23:44.000Z
2021-08-15T03:39:29.000Z
boost/sequence/elements.hpp
ericniebler/time_series
4040119366cc21f25c7734bb355e4a647296a96d
[ "BSL-1.0" ]
null
null
null
boost/sequence/elements.hpp
ericniebler/time_series
4040119366cc21f25c7734bb355e4a647296a96d
[ "BSL-1.0" ]
3
2015-05-09T02:25:42.000Z
2019-11-02T13:39:29.000Z
// Copyright David Abrahams 2006. Distributed under the Boost // Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_SEQUENCE_ELEMENTS_DWA200655_HPP # define BOOST_SEQUENCE_ELEMENTS_DWA200655_HPP # include <boost/detail/function1.hpp> # include <boost/detail/pod_singleton.hpp> # include <boost/mpl/placeholders.hpp> # include <boost/property_map/dereference.hpp> namespace boost { namespace sequence { /// INTERNAL ONLY namespace impl { template<typename S, typename T = typename tag<S>::type> struct elements { typedef property_maps::dereference result_type; result_type operator ()(S &s) const { return result_type(); } }; } namespace op { using mpl::_; struct elements : boost::detail::function1<impl::elements<_, impl::tag<_> > > {}; } namespace { op::elements const &elements = boost::detail::pod_singleton<op::elements>::instance; } }} // namespace boost::sequence #endif // BOOST_SEQUENCE_ELEMENTS_DWA200655_HPP
24.276596
89
0.676599
ericniebler
2c99c60d78188610e2610b766e3eb313d58acd0d
948
hpp
C++
qashctl/src/mwdg/mixer_hctl_proxy_switch.hpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
qashctl/src/mwdg/mixer_hctl_proxy_switch.hpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
qashctl/src/mwdg/mixer_hctl_proxy_switch.hpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
/// QasTools: Desktop toolset for the Linux sound system ALSA. /// \copyright See COPYING file. #ifndef __INC_mixer_hctl_proxy_switch_hpp__ #define __INC_mixer_hctl_proxy_switch_hpp__ #include "mixer_hctl_proxy.hpp" #include <QObject> namespace MWdg { /// @brief Mixer_HCTL_Proxy_Switch /// class Mixer_HCTL_Proxy_Switch : public Mixer_HCTL_Proxy { Q_OBJECT // Public methods public: Mixer_HCTL_Proxy_Switch ( QObject * parent_n ); bool switch_state () const; // Signals signals: void sig_switch_state_changed ( bool state_n ); // Public slots public slots: void set_switch_state ( bool state_n ); void update_value_from_source (); // Protected methods protected: void switch_state_changed (); // Private attributes private: bool _switch_state; bool _updating_state; }; inline bool Mixer_HCTL_Proxy_Switch::switch_state () const { return _switch_state; } } // namespace MWdg #endif
15.540984
62
0.738397
amazingidiot
2ca5cf55948708ad5f71ab64b57eef52a172ad3b
7,053
cpp
C++
anno/ImageModel.cpp
urobots-io/anno
8e240185e6fc0908687b15a39c892814a6bddee6
[ "MIT" ]
9
2020-07-17T05:28:52.000Z
2022-03-03T18:26:12.000Z
anno/ImageModel.cpp
urobots-io/anno
8e240185e6fc0908687b15a39c892814a6bddee6
[ "MIT" ]
null
null
null
anno/ImageModel.cpp
urobots-io/anno
8e240185e6fc0908687b15a39c892814a6bddee6
[ "MIT" ]
null
null
null
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com // // Anno Labeling Tool // 2020-2021 (c) urobots GmbH, https://urobots.io #include "ImageModel.h" #include "ColorTransformer.h" ImageModel::ImageModel(QObject *parent) : QObject(parent) { connect(this, &ImageModel::brightness_changed, this, &ImageModel::RebuildPixmap); connect(this, &ImageModel::contrast_changed, this, &ImageModel::RebuildPixmap); connect(this, &ImageModel::grayscale_changed, this, &ImageModel::RebuildPixmap); connect(this, &ImageModel::exr_correction_changed, this, &ImageModel::RebuildPixmap); } ImageModel::~ImageModel() { } void ImageModel::Load(const ImageData& image) { image_ = image; pixmap_ = QPixmap(); RebuildPixmap(); set_loaded(!IsImageEmpty(image_)); } void ImageModel::Clear() { image_ = {}; pixmap_ = QPixmap(); set_loaded(false); } #ifdef ANNO_USE_OPENCV /* Mat::type values for debugging purposes: +--------+----+----+----+----+------+------+------+------+ | | C1 | C2 | C3 | C4 | C(5) | C(6) | C(7) | C(8) | +--------+----+----+----+----+------+------+------+------+ | CV_8U | 0 | 8 | 16 | 24 | 32 | 40 | 48 | 56 | | CV_8S | 1 | 9 | 17 | 25 | 33 | 41 | 49 | 57 | | CV_16U | 2 | 10 | 18 | 26 | 34 | 42 | 50 | 58 | | CV_16S | 3 | 11 | 19 | 27 | 35 | 43 | 51 | 59 | | CV_32S | 4 | 12 | 20 | 28 | 36 | 44 | 52 | 60 | | CV_32F | 5 | 13 | 21 | 29 | 37 | 45 | 53 | 61 | | CV_64F | 6 | 14 | 22 | 30 | 38 | 46 | 54 | 62 | +--------+----+----+----+----+------+------+------+------+ */ namespace { template<class T, int N> std::vector<float> GetChannelValuesForType(cv::Mat &m, int x, int y) { std::vector<float> result; auto p = (T*)&m.at<cv::Vec<T, N>>(y, x); for (int i = 0; i < m.channels(); ++i, ++p) { result.insert(result.begin(), *p); } return result; } template<int N> std::vector<float> GetChannelValues(cv::Mat &m, int x, int y) { switch (m.depth()) { default: return{}; case CV_8U: return GetChannelValuesForType<uint8_t, N>(m, x, y); case CV_8S: return GetChannelValuesForType<int8_t, N>(m, x, y); case CV_16U: return GetChannelValuesForType<uint16_t, N>(m, x, y); case CV_16S: return GetChannelValuesForType<int16_t, N>(m, x, y); case CV_32S: return GetChannelValuesForType<int32_t, N>(m, x, y); case CV_32F: return GetChannelValuesForType<float, N>(m, x, y); case CV_64F: return GetChannelValuesForType<double, N>(m, x, y); } } } std::vector<float> ImageModel::GetBackgroundPixelValues(int x, int y) { std::vector<float> result; if ((unsigned)x >= (unsigned)image_.cols || (unsigned)y >= (unsigned)image_.rows) return result; switch (image_.channels()) { case 1: return GetChannelValues<1>(image_, x, y); case 2: return GetChannelValues<2>(image_, x, y); case 3: return GetChannelValues<3>(image_, x, y); default: return{}; } } QImage ImageModel::ImageFromMat(const cv::Mat& image) { if (image.empty()) { return QImage(); } cv::Mat image_to_convert; if (image.channels() == 1) { // Currently we need this image only to show, so convert opecnv to color, because this is easy cv::cvtColor(image, image_to_convert, cv::COLOR_GRAY2RGB); } else { image_to_convert = image.clone(); // TODO(ia): inefficient. } switch (image_to_convert.type()) { case CV_32FC3: cv::pow(image_to_convert, get_exr_correction(), image_to_convert); image_to_convert.convertTo(image_to_convert, CV_8U, 255); break; case CV_16UC3: image_to_convert.convertTo(image_to_convert, CV_8U, 1. / 65535 * 255); break; case CV_8UC3: break; default: assert(!"Unsupported image type"); return QImage(); } QImage ref_image( // image that references the existing data image_to_convert.data, image_to_convert.cols, image_to_convert.rows, static_cast<int>(image_to_convert.step1()), QImage::Format_RGB888); return ref_image.rgbSwapped(); // swap R & B channels, make a deep copy. } void ImageModel::RebuildPixmap() { auto result = image_.clone(); if (get_grayscale() && result.channels() > 1) { cv::cvtColor(result, result, cv::COLOR_BGR2GRAY); } /* int brightness = get_brightness(); int contrast = get_contrast(); if ((brightness || contrast) && result.depth() <= CV_8S && result.channels() == 3) { ColorTransformer ct(brightness, contrast); for (int y = 0; y < result.rows; y++) { for (int x = 0; x < result.cols; x++) { result.at<cv::Vec3b>(y, x) = ct.Transform(result.at<cv::Vec3b>(y, x)); } } } else if (brightness) { // Fallback to old brightness algorithm if not 3-channels or not 8-bit/channel double beta; switch (result.depth()) { case CV_8U: case CV_8S: beta = brightness; break; default: beta = brightness * 0.01; break; } result.convertTo(result, result.type(), 1, beta); } */ auto image = ImageFromMat(result); int brightness = get_brightness(); int contrast = get_contrast(); if (brightness || contrast) { ColorTransformer ct(brightness, contrast); for (int y = 0; y < image.height(); ++y) { auto p = image.scanLine(y); for (int x = 0; x < image.width(); ++x, p += 3) { ct.TransformB3(p); } } } pixmap_ = QPixmap::fromImage(image); emit pixmap_changed(); } #else std::vector<float> ImageModel::GetBackgroundPixelValues(int x, int y) { if (image_.isNull() || x < 0 || y < 0 || x >= image_.width() || y >= image_.height()) { return {}; } auto color = QColor(image_.pixel(QPoint(x, y))); return { float(color.red()), float(color.green()), float(color.blue()) }; } void ImageModel::RebuildPixmap() { int brightness = get_brightness(); int contrast = get_contrast(); if (brightness || contrast) { ColorTransformer ct(brightness, contrast); auto image = image_.convertToFormat(QImage::Format_RGB888); for (int y = 0; y < image.height(); ++y) { auto p = image.scanLine(y); for (int x = 0; x < image.width(); ++x, p += 3) { ct.TransformB3(p); } } if (get_grayscale()) { pixmap_ = QPixmap::fromImage(image.convertToFormat(QImage::Format_Grayscale8)); } else { pixmap_ = QPixmap::fromImage(image); } } else if (get_grayscale()) { pixmap_ = QPixmap::fromImage(image_.convertToFormat(QImage::Format_Grayscale8)); } else { pixmap_ = QPixmap::fromImage(image_); } emit pixmap_changed(); } #endif
29.144628
102
0.57635
urobots-io
2ca7fc69ececcfab60c1a0939649a398ee019601
13,599
cpp
C++
Source/ExistenceApps/ExistenceComponents/GameStateHandlerComponent.cpp
vivienneanthony/Urho3D-Mastercurrent-Existence
2d75021489996e1abc2fd330ed967cd89a62f40d
[ "Apache-2.0" ]
3
2015-05-22T23:39:03.000Z
2016-04-13T03:52:59.000Z
Source/ExistenceApps/ExistenceComponents/GameStateHandlerComponent.cpp
vivienneanthony/Urho3D-Mastercurrent-Existence
2d75021489996e1abc2fd330ed967cd89a62f40d
[ "Apache-2.0" ]
null
null
null
Source/ExistenceApps/ExistenceComponents/GameStateHandlerComponent.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 "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 "GameStateEvents.h" #include "GameObject.h" #include "EnvironmentBuild.h" #include "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/ExistenceClient.h" #include "GameStateHandlerComponent.h" #include "../ExistenceClient/ExistenceClientUI.h" #include "../../Urho3D/Engine/DebugHud.h" using namespace Urho3D; using namespace std; /// Game State Handler Coponent GameStateHandlerComponent::GameStateHandlerComponent(Context* context) : LogicComponent (context) ,GameStateHandlerApplication(NULL) { /// Debug Info cout << "Debug: Game State Handler Component Constructor - context " << &context << endl; /// constructor /// Debug cout << "Debug: Game State Handler OnStateChange subscribetoevent" << endl; SubscribeToEvent(G_STATES_CHANGE, HANDLER(GameStateHandlerComponent, onStateChange)); } /// Game State Component Deconstructor GameStateHandlerComponent::~GameStateHandlerComponent() { /// Debug Info cout << "Debug: Game State Handler Component Deconstructor " << endl; } /// Register Subsystem void GameStateHandlerComponent::RegisterNewSubsystem(Urho3D::Context* context) { context -> RegisterSubsystem(new GameStateHandlerComponent(context)); /// Debug Info cout << "Debug: Game State Handler RegisterNewSystem " << &context << endl; return; } void GameStateHandlerComponent::RegisterGameStates(Context* context) { /// .... all states here context->RegisterFactory<ExistenceClientStateSingleton>(); context->RegisterFactory<ExistenceClientStateAccount>(); context->RegisterFactory<ExistenceClientStateGameMode>(); context->RegisterFactory<ExistenceClientStateLogin>(); context->RegisterFactory<ExistenceClientStatePlayer>(); context->RegisterFactory<ExistenceClientStateProgress>(); context->RegisterFactory<ExistenceClientStateMainScreen>(); /// Debug Info cout << "Debug: Game State Handler RegisterGameStates " << &context << endl; } /// try to test the state void GameStateHandlerComponent::SetApplication(SharedPtr <ExistenceClient> temp) { GameStateHandlerApplication = temp; return; } /// try to test the state void GameStateHandlerComponent::Start(void) { /// Start ExistenceClientStateSingleton * gameState = new ExistenceClientStateSplash(context_); gameState->Enter(); return; } /// Game Sate Handler Changer State void GameStateHandlerComponent::createState(String newState, Urho3D::VariantMap& eventData) { /// Debug Info cout << "Debug: Game State Handler Component createState" << endl; /// Create a blank pointer ExistenceClientStateSingleton * newgameState=NULL; /// Switch if (String(ExistenceClientStateLogin::GetTypeNameStatic())==newState) { /// change to that state cout << "Debug: Create Login Progress Called" << endl;; state=ExistenceClientStateLogin::GetTypeNameStatic(); /// change to that state ExistenceClientStateSingleton * newgameState = new ExistenceClientStateLogin(context_); /// delete old state delete gameState; gameState=newgameState; gameState->Enter(); } else if (String(ExistenceClientStateGameMode::GetTypeNameStatic())==newState) { /// change to that state cout << "Debug: Create Game Mode Called" << endl; state=ExistenceClientStateGameMode::GetTypeNameStatic(); ///gameState->Exit(); ExistenceClientStateSingleton * newgameState = new ExistenceClientStateGameMode(context_); /// delete old state delete gameState; gameState=newgameState; gameState->Enter(); } else if (String(ExistenceClientStateMainScreen::GetTypeNameStatic())==newState) { /// change to that state cout << "Debug: Create Main Screen Called" << endl; state=ExistenceClientStateMainScreen::GetTypeNameStatic(); ExistenceClientStateSingleton * newgameState = new ExistenceClientStateMainScreen(context_); /// delete old state delete gameState; gameState=newgameState; gameState->Enter(); } else if (String(ExistenceClientStateAccount::GetTypeNameStatic())==newState) { /// change to that state cout << "Debug: Create Main Screen Called" << endl; state=ExistenceClientStateAccount::GetTypeNameStatic(); ExistenceClientStateSingleton * newgameState = new ExistenceClientStateAccount(context_); /// delete old state delete gameState; gameState=newgameState; gameState->Enter(); } else if (String(ExistenceClientStatePlayer::GetTypeNameStatic())==newState) { /// change to that state cout << "Debug: Create Player Called" << endl; state=ExistenceClientStatePlayer::GetTypeNameStatic(); ExistenceClientStateSingleton * newgameState = new ExistenceClientStatePlayer(context_); /// delete old state delete gameState; gameState=newgameState; gameState->Enter(); } else if (String(ExistenceClientStateProgress::GetTypeNameStatic())==newState) { /// change to that state cout << "Debug: Create Progress Called" << endl; state = ExistenceClientStateProgress::GetTypeNameStatic(); ExistenceClientStateSingleton * newgameState = new ExistenceClientStateProgress(context_); /// delete old state delete gameState; gameState=newgameState; gameState->SetParameter(eventData[GameState::P_ARG].GetString()); gameState->Enter(); } else if (String(ExistenceClientStateSplash::GetTypeNameStatic())==newState) { /// change to that state cout << "Debug: Create Splash Called" << endl; state=ExistenceClientStateSplash::GetTypeNameStatic(); ExistenceClientStateSingleton * newgameState = new ExistenceClientStateSplash(context_); /// delete old state delete gameState; gameState=newgameState; gameState->Enter(); } return; } /// onSteChangeHandler void GameStateHandlerComponent::onStateChange( Urho3D::StringHash eventType, Urho3D::VariantMap& eventData ) { /// Debug Info cout << "Debug: Game State Handler Component onStateChange called" << endl; /// intercept state event GameStates newState= static_cast<GameStates>(eventData[GameState::P_CMD].GetInt()); switch (newState) { case GAME_STATE_PROGRESS: //called from intro GameIntroSample /// exit out if(gameState!=NULL) { gameState->Exit(); }; /// create a new state createState(ExistenceClientStateProgress::GetTypeNameStatic(),eventData); break; case GAME_STATE_GAMEMODE: //called from intro GameIntroSample /// exit out if(gameState!=NULL) { gameState->Exit(); }; /// create a new state createState(ExistenceClientStateGameMode::GetTypeNameStatic(),eventData); break; case GAME_STATE_LOGIN: //called from intro GameIntroSample /// exit out if(gameState!=NULL) { gameState->Exit(); }; /// create a new state createState(ExistenceClientStateLogin::GetTypeNameStatic(),eventData); break; case GAME_STATE_PLAYERCREATE: //called from intro GameIntroSample /// exit out if(gameState!=NULL) { gameState->Exit(); }; /// create a new state createState(ExistenceClientStatePlayer::GetTypeNameStatic(),eventData); break; case GAME_STATE_ACCOUNTCREATE: //called from intro GameIntroSample /// exit out if(gameState!=NULL) { gameState->Exit(); }; /// create a new state createState(ExistenceClientStateAccount::GetTypeNameStatic(),eventData); break; case GAME_STATE_MAINMENU: //called from intro GameIntroSample /// exit out if(gameState!=NULL) { gameState->Exit(); }; /// create a new state createState(ExistenceClientStateMainScreen::GetTypeNameStatic(),eventData); break; case GAME_STATE_SPLASH: //called from intro GameIntroSample /// exit out if(gameState!=NULL) { gameState->Exit(); }; /// create a new state createState(ExistenceClientStateSplash::GetTypeNameStatic(),eventData); break; default: cout << "Debug: Unkown State " << newState; break; } return; } /// save state String GameStateHandlerComponent::GetCurrentState(void) { return state; } /// Functions for states int GameStateHandlerComponent::GetConsoleState(void) { int flag; flag = consolestate; return flag; } int GameStateHandlerComponent::SetConsoleState(int flag) { consolestate=flag; return 1; } int GameStateHandlerComponent::GetUIState(void) { int flag; flag=uistate; return flag; } int GameStateHandlerComponent::SetUIState(int flag) { uistate = flag; return 1; } int GameStateHandlerComponent::GetCameraMode(void) { int flag; flag = cameramode; return flag;; } int GameStateHandlerComponent::SetCameraMode(int flag) { cameramode = flag; return 1; } int GameStateHandlerComponent::GetDebugHudMode(void) { int flag; flag = debughud; return flag;; } int GameStateHandlerComponent::SetDebugHudMode(int flag) { debughud = flag; return 1; } /// try to test the state SharedPtr<ExistenceClient> GameStateHandlerComponent::GetApplication(void) { return GameStateHandlerApplication; }
28.750529
108
0.670343
vivienneanthony
2ca9eb45b7944f0eb29d515b2e94f782a73b869a
79,342
cpp
C++
trunk/suiwgx/src/richedit/src/rtfwrit.cpp
OhmPopy/MPFUI
eac88d66aeb88d342f16866a8d54858afe3b6909
[ "MIT" ]
59
2017-08-27T13:27:55.000Z
2022-01-21T13:24:05.000Z
src/suiwgx/richedit/src/rtfwrit.cpp
BigPig0/MPFUI
7042e0a5527ab323e16d2106d715db4f8ee93275
[ "MIT" ]
5
2017-11-26T05:40:23.000Z
2019-04-02T08:58:21.000Z
src/suiwgx/richedit/src/rtfwrit.cpp
BigPig0/MPFUI
7042e0a5527ab323e16d2106d715db4f8ee93275
[ "MIT" ]
49
2017-08-24T08:00:50.000Z
2021-11-07T01:24:41.000Z
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this source code is subject to the terms of the Microsoft shared // source or premium shared source license agreement under which you licensed // this source code. If you did not accept the terms of the license agreement, // you are not authorized to use this source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the SOURCE.RTF on your install media or the root of your tools installation. // THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES. // /* * @doc INTERNAL * * @module RTFWRIT.CPP - RichEdit RTF Writer (w/o objects) | * * This file contains the implementation of the RTF writer * for the RichEdit control, except for embedded objects, * which are handled mostly in rtfwrit2.cpp * * Authors: <nl> * Original RichEdit 1.0 RTF converter: Anthony Francisco <nl> * Conversion to C++ and RichEdit 2.0: Murray Sargent <nl> * Lots of enhancements: Brad Olenick <nl> * */ #include "_common.h" #include "_rtfwrit.h" #include "_objmgr.h" #include "_coleobj.h" ASSERTDATA extern KEYWORD rgKeyword[]; //========================= Global String Constants ================================== BYTE bCharSetANSI = ANSI_CHARSET; // ToDo: make more general #ifdef DEBUG // Quick way to find out what went wrong: rgszParseError[ecParseError] // CHAR * rgszParseError[] = { "No error", "Can't convert to Unicode", // FF "Color table overflow", // FE "Expecting '\\rtf'", // FD "Expecting '{'", // FC "Font table overflow", // FB "General failure", // FA "Keyword too long", // F9 "Lexical analyzer initialize failed", // F8 "No memory", // F7 "Parser is busy", // F6 "PutChar() function failed", // F5 "Stack overflow", // F4 "Stack underflow", // F3 "Unexpected character", // F2 "Unexpected end of file", // F1 "Unexpected token", // F0 "UnGetChar() function failed", // EF "Maximum text length reached", // EE "Streaming out object failed", // ED "Streaming in object failed", // EC "Truncated at CR or LF", // EB "Format-cache failure", // EA NULL // End of list marker }; CHAR * szDest[] = { "RTF", "Color Table", "Font Table", "Binary", "Object", "Object Class", "Object Name", "Object Data", "Field", "Field Result", "Field Instruction", "Symbol", "Paragraph Numbering", "Picture" }; #endif // Most control-word output is done with the following printf formats static const CHAR * rgszCtrlWordFormat[] = { "\\%s", "\\%s%d", "{\\%s", "{\\*\\%s", "{\\%s%d" }; // Special control-word formats static const CHAR szBeginFontEntryFmt[] = "{\\f%d\\%s"; static const CHAR szBulletGroup[] = "{\\pntext\\f%d\\'B7\\tab}"; static const CHAR szBulletFmt[] = "{\\*\\pn\\pnlvlblt\\pnf%d\\pnindent%d{\\pntxtb\\'B7}}"; static const CHAR szBeginNumberGroup[] = "{\\pntext\\f%d "; static const CHAR szEndNumberGroup[] = "\\tab}"; static const CHAR szBeginNumberFmt[] = "{\\*\\pn\\pnlvl%s\\pnf%d\\pnindent%d\\pnstart%d"; static const CHAR szpntxtb[] = "{\\pntxtb(}"; static const CHAR szpntxta[] = "{\\pntxta%c}"; static const CHAR szColorEntryFmt[] = "\\red%d\\green%d\\blue%d;"; static const CHAR szEndFontEntry[] = ";}"; const CHAR szEndGroupCRLF[] = "}\r\n"; static const CHAR szEscape2CharFmt[] = "\\'%02x\\'%02x"; static const CHAR szLiteralCharFmt[] = "\\%c"; static const CHAR szPar[] = "\\par\r\n"; static const CHAR szObjPosHolder[] = "\\objattph\\'20"; static const CHAR szDefaultFont[] = "\\deff0"; static const CHAR szHorzdocGroup[] = "{\\horzdoc}"; static const CHAR szNormalStyle[] = "{ Normal;}"; static const CHAR szHeadingStyle[] = "{\\s%d heading %d;}"; static const CHAR szEndRow[] = "\\row\r\n"; static const CHAR szPwdComment[] = "{\\*\\pwdcomment "; #define szEscapeCharFmt &szEscape2CharFmt[6] const WORD rgiszTerminators[] = { i_cell, 0, i_tab, 0, i_line, i_page}; // Keep these indices in sync with the special character values in _common.h const WORD rgiszSpecial[] = { i_enspace, i_emspace, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, i_endash, i_emdash, 0, 0, 0, i_lquote, i_rquote, 0, 0, i_ldblquote, i_rdblquote, 0, 0, 0, 0, i_bullet }; const WORD rgiszEffects[] = { // Effects keywords i_revised, i_disabled, i_impr, i_embo, // Ordered max CFE_xx to i_shad, i_outl, i_v, i_caps, i_scaps, // min CFE_xx i_disabled, i_protect, i_strike, i_ul, i_i, i_b // (see WriteCharFormat()) }; #define CEFFECTS ARRAY_SIZE(rgiszEffects) const WORD rgiszPFEffects[] = // PF effects keywords { // Ordered max PFE_xx to i_collapsed, i_sbys, i_hyphpar, i_nowidctlpar, // min PFE_xx i_noline, i_pagebb, i_keepn, i_keep, i_rtlpar }; // (see WriteParaFormat()) #define CPFEFFECTS ARRAY_SIZE(rgiszPFEffects) const WORD rgiszUnderlines[] = { i_ul, i_ulw, i_uldb, i_uld, // Std Word underlines i_uldash, i_uldashd, i_uldashdd, i_ulwave, i_ulth, i_ulhair }; #define CUNDERLINES ARRAY_SIZE(rgiszUnderlines) const WORD rgiszFamily[] = // Font family RTF name { // keywords in order of i_fnil, i_froman, i_fswiss, i_fmodern, // bPitchAndFamily i_fscript, i_fdecor // , i_ftech, i_fbidi // TODO }; const WORD rgiszAlignment[] = // Alignment keywords { // Keep in sync with i_ql, i_qr, i_qc, i_qj // alignment constants }; const WORD rgiszTabAlign[] = // Tab alignment keywords { // Keep in sync with tab i_tqc, i_tqr, i_tqdec // alignment constants }; const WORD rgiszTabLead[] = // Tab leader keywords { // Keep in sync with tab i_tldot, i_tlhyph, i_tlul, i_tlth, i_tleq // leader constants }; const WORD rgiszNumberStyle[] = // Numbering style keywords { // Keep in sync with TOM i_pndec, i_pnlcltr, i_pnucltr, // values i_pnlcrm, i_pnucrm, i_pnaiueod, i_pnirohad // GuyBark JupiterJ: added these }; const WORD rgiszBorders[] = // Border combination keywords { i_box, i_brdrt, i_brdrl, i_brdrb, i_brdrr, i_trbrdrt, i_trbrdrl, i_trbrdrb, i_trbrdrr, i_clbrdrt, i_clbrdrl, i_clbrdrb, i_clbrdrr }; const WORD rgiszBorderStyles[] = // Border style keywords { i_brdrdash, i_brdrdashsm, i_brdrdb, i_brdrdot, i_brdrhair, i_brdrs, i_brdrth, i_brdrtriple }; #define CBORDERSTYLES ARRAY_SIZE(rgiszBorderStyles) const WORD rgiszBorderEffects[] = // Border effect keywords { i_brdrbar, i_brdrbtw, i_brdrsh // Reverse order from bits }; const WORD rgiszShadingStyles[] = // Shading style keywords { i_bgbdiag, i_bgcross, i_bgdcross, i_bgdkbdiag, i_bgdkcross, i_bgdkdcross, i_bgdkfdiag, i_bgdkhoriz, i_bgdkvert, i_bgfdiag, i_bghoriz, i_bgvert }; #define CSHADINGSTYLES ARRAY_SIZE(rgiszShadingStyles) // RGB with 2 bits per color type (in BGR order) const COLORREF g_Colors[] = { RGB( 0, 0, 0), // \red0\green0\blue0 RGB( 0, 0, 255), // \red0\green0\blue255 RGB( 0, 255, 255), // \red0\green255\blue255 RGB( 0, 255, 0), // \red0\green255\blue0 RGB(255, 0, 255), // \red255\green0\blue255 RGB(255, 0, 0), // \red255\green0\blue0 RGB(255, 255, 0), // \red255\green255\blue0 RGB(255, 255, 255), // \red255\green255\blue255 RGB( 0, 0, 128), // \red0\green0\blue128 RGB( 0, 128, 128), // \red0\green128\blue128 RGB( 0, 128, 0), // \red0\green128\blue0 RGB(128, 0, 128), // \red128\green0\blue128 RGB(128, 0, 0), // \red128\green0\blue0 RGB(128, 128, 0), // \red128\green128\blue0 RGB(128, 128, 128), // \red128\green128\blue128 RGB(192, 192, 192), // \red192\green192\blue192 }; /* * CRTFWrite::MapsToRTFKeywordW(wch) * * @mfunc * Returns a flag indicating whether the character maps to an RTF keyword * * @rdesc * BOOL TRUE if char maps to RTF keyword */ inline BOOL CRTFWrite::MapsToRTFKeywordW(WCHAR wch) { return IN_RANGE(TAB, wch, CR) || #ifdef PWD_JUPITER // GuyBark Jupiter: Handle the special character for CRLF in table cells. wch == PWD_CRLFINCELL || #endif // PWD_JUPITER wch == CELL || wch == CELL || wch == BSLASH || wch == LBRACE || wch == RBRACE || IN_RANGE(ENSPACE, wch, EMSPACE) || IN_RANGE(ENDASH, wch, EMDASH) || IN_RANGE(LQUOTE, wch, RQUOTE) || IN_RANGE(LDBLQUOTE, wch, RDBLQUOTE) || wch == BULLET || wch == chOptionalHyphen || wch == chNonBreakingSpace; } /* * CRTFWrite::MapsToRTFKeywordA(ch) * * @mfunc * Returns a flag indicating whether the character maps to an RTF keyword * * @rdesc * BOOL TRUE if char maps to RTF keyword */ inline BOOL CRTFWrite::MapsToRTFKeywordA(char ch) { return IN_RANGE(TAB, ch, CR) || ch == CELL || ch == BSLASH || ch == LBRACE || ch == RBRACE; } /* * CRTFWrite::MapToRTFKeywordW(pv, cch, iCharEncoding) * * @mfunc * Examines the first character in the string pointed to by pv and * writes out the corresponding RTF keyword. In situations where * the first and subsequent characters map to a single keyword, we * return the number of additional characters used in the mapping. * * @rdesc * int indicates the number of additional characters used when * the mapping to an RTF keyword involves > 1 characters. */ int CRTFWrite::MapToRTFKeyword( void * pv, //@parm ptr to ansi or Unicode string int cch, int iCharEncoding) { Assert(iCharEncoding == MAPTOKWD_ANSI || iCharEncoding == MAPTOKWD_UNICODE); WCHAR ch = ((iCharEncoding == MAPTOKWD_ANSI) ? *(char *)pv : *(WCHAR *)pv); int cchRet = 0; Assert((iCharEncoding == MAPTOKWD_ANSI) ? MapsToRTFKeywordA(ch) : MapsToRTFKeywordW(ch)); switch(ch) { #ifdef PWD_JUPITER // GuyBark Jupiter: We've hit the special character inserting when // reading the file, to represent a CRLF in a table cell. case PWD_CRLFINCELL: { // Mimic the rtf output by Word97 in this situation. char szParInTable[] = "\r\n\\par"; Puts(szParInTable, strlen(szParInTable)); break; } #endif // PWD_JUPITER case BULLET: case EMDASH: case EMSPACE: case ENDASH: case ENSPACE: case LDBLQUOTE: case LQUOTE: case RDBLQUOTE: case RQUOTE: Assert(ch > 0xFF); if(iCharEncoding != MAPTOKWD_ANSI) { AssertSz(rgiszSpecial[ch - ENSPACE] != 0, "CRTFWrite::WriteText(): rgiszSpecial out-of-sync"); PutCtrlWord(CWF_STR, rgiszSpecial[ch - ENSPACE]); } break; case FF: case VT: case TAB: case CELL: PutCtrlWord(CWF_STR, rgiszTerminators[ch - CELL]); break; case CR: { WCHAR ch1; WCHAR ch2; if(iCharEncoding == MAPTOKWD_ANSI) { char *pch = (char *)pv; ch1 = pch[1]; ch2 = pch[2]; } else { WCHAR *pch = (WCHAR *)pv; ch1 = pch[1]; ch2 = pch[2]; } if(cch > 1 && ch1 == CR && ch2 == LF) { // Translate CRCRLF to a blank (represents soft line break) PutChar(' '); cchRet = 2; break; } if(cch && ch1 == LF) // Ignore LF after CR { cchRet = 1; } if(_pPF->InTable()) // CR terminates a row in our simple { // table model, so output \row Puts(szEndRow, sizeof(szEndRow) - 1); _fCheckInTable = TRUE; break; } } // Fall thru to LF (EOP) case case LF: Puts(szPar, sizeof(szPar) - 1); if(_fBullet) { if(cch > 0) { if(!_nNumber) printF(szBulletGroup, _symbolFont); else if(!_pPF->IsNumberSuppressed()) { WCHAR szNumber[CCHMAXNUMTOSTR]; _pPF->NumToStr(szNumber, ++_nNumber); printF(szBeginNumberGroup, _nFont); WritePcData(szNumber, _cpg, FALSE); printF(szEndNumberGroup); } } else _fBulletPending = TRUE; } break; case chOptionalHyphen: ch = '-'; // Fall thru to printFLiteral printFLiteral: case BSLASH: case LBRACE: case RBRACE: printF(szLiteralCharFmt, ch); break; case chNonBreakingSpace: ch = '~'; goto printFLiteral; } return cchRet; } //======================== CRTFConverter Base Class ================================== /* * CRTFConverter::CRTFConverter() * * @mfunc * RTF Converter constructor */ CRTFConverter::CRTFConverter( CTxtRange * prg, // @parm CTxtRange for transfer EDITSTREAM * pes, // @parm Edit stream for transfer DWORD dwFlags, // @parm Converter flags BOOL fRead) // @parm Initialization for a reader or writer { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFConverter::CRTFConverter"); AssertSz(prg && pes && pes->pfnCallback, "CRTFWrite::CRTFWrite: Bad RichEdit"); _prg = prg; _pes = pes; _ped = prg->GetPed(); _dwFlags = dwFlags; _ecParseError = ecNoError; if(!_ctfi) { ReadFontSubInfo(); } #if defined(DEBUG) && !defined(MACPORT) _hfileCapture = NULL; #if !defined(PEGASUS) if(GetProfileIntA("RICHEDIT DEBUG", "RTFCAPTURE", 0)) { char szTempPath[MAX_PATH] = "\0"; const char cszRTFReadCaptureFile[] = "CaptureRead.rtf"; const char cszRTFWriteCaptureFile[] = "CaptureWrite.rtf"; DWORD cchLength; SideAssert(cchLength = GetTempPathA(MAX_PATH, szTempPath)); // append trailing backslash if neccessary if(szTempPath[cchLength - 1] != '\\') { szTempPath[cchLength] = '\\'; szTempPath[cchLength + 1] = 0; } strcat(szTempPath, fRead ? cszRTFReadCaptureFile : cszRTFWriteCaptureFile); SideAssert(_hfileCapture = CreateFileA(szTempPath, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)); } #endif // !defined(PEGASUS) #endif // defined(DEBUG) && !defined(MACPORT) } //======================== OLESTREAM functions ======================================= DWORD CALLBACK RTFPutToStream ( RTFWRITEOLESTREAM * OLEStream, //@parm OLESTREAM const void * pvBuffer, //@parm Buffer to write DWORD cb) //@parm Bytes to write { return OLEStream->Writer->WriteData ((BYTE *)pvBuffer, cb); } //============================ CRTFWrite Class ================================== /* * CRTFWrite::CRTFWrite() * * @mfunc * RTF writer constructor */ CRTFWrite::CRTFWrite( CTxtRange * prg, // @parm CTxtRange to write EDITSTREAM * pes, // @parm Edit stream to write to DWORD dwFlags) // @parm Write flags : CRTFConverter(prg, pes, dwFlags, FALSE) { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::CRTFWrite"); ZeroMemory(&_CF, sizeof(CCharFormat)); // Setup "previous" CF with RTF _CF.cbSize = sizeof(CHARFORMAT2); // defaults. 12 Pt in twips _CF.dwEffects = CFE_AUTOCOLOR | CFE_AUTOBACKCOLOR;// Font info is given _CF.yHeight = 12*20; // by first font in range // [see end of LookupFont()] if (NULL == _ped) { Assert(_ped); _CF.lcid = (LCID)0; } else { _ped->GetDefaultLCID(&_CF.lcid); } // init OleStream RTFWriteOLEStream.Writer = this; RTFWriteOLEStream.lpstbl->Put = (DWORD (CALLBACK* )(LPOLESTREAM, const void FAR*, DWORD)) RTFPutToStream; RTFWriteOLEStream.lpstbl->Get = NULL; _fIncludeObjects = TRUE; if (dwFlags == SF_RTFNOOBJS) _fIncludeObjects = FALSE; _fNeedDelimeter = FALSE; _nHeadingStyle = 0; // No headings found _nNumber = 0; // No paragraph numbering yet _fCheckInTable = FALSE; _pPF = NULL; _pbAnsiBuffer = NULL; } /* * CRTFWrite::FlushBuffer() * * @mfunc * Flushes output buffer * * @rdesc * BOOL TRUE if successful */ BOOL CRTFWrite::FlushBuffer() { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::FlushBuffer"); LONG cchWritten; if (!_cchBufferOut) return TRUE; #ifdef DEBUG_PASTE if (FromTag(tagRTFAsText)) { CHAR * pchEnd = &_pchRTFBuffer[_cchBufferOut]; CHAR chT = *pchEnd; *pchEnd = 0; TraceString(_pchRTFBuffer); *pchEnd = chT; } #endif _pes->dwError = _pes->pfnCallback(_pes->dwCookie, (unsigned char *)_pchRTFBuffer, _cchBufferOut, &cchWritten); #if defined(DEBUG) && !defined(MACPORT) && !defined(PEGASUS) if(_hfileCapture) { DWORD cbLeftToWrite = _cchBufferOut; DWORD cbWritten2 = 0; BYTE *pbToWrite = (BYTE *)_pchRTFBuffer; while(WriteFile(_hfileCapture, pbToWrite, cbLeftToWrite, &cbWritten2, NULL) && (pbToWrite += cbWritten2, (cbLeftToWrite -= cbWritten2))); } #endif if (_pes->dwError) { _ecParseError = ecPutCharFailed; return FALSE; } AssertSz(cchWritten == _cchBufferOut, "CRTFW::FlushBuffer: incomplete write"); _cchOut += _cchBufferOut; _pchRTFEnd = _pchRTFBuffer; // Reset buffer _cchBufferOut = 0; return TRUE; } /* * CRTFWrite::PutChar(ch) * * @mfunc * Put out the character <p ch> * * @rdesc * BOOL TRUE if successful */ BOOL CRTFWrite::PutChar( CHAR ch) // @parm char to be put { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::PutChar"); CheckDelimeter(); // If _fNeedDelimeter, may need to // PutChar(' ') // Flush buffer if char won't fit if (_cchBufferOut + 1 >= cachBufferMost && !FlushBuffer()) return FALSE; *_pchRTFEnd++ = ch; // Store character in buffer ++_cchBufferOut; return TRUE; } /* * CRTFWrite::CheckInTable(fPutIntbl) * * @mfunc * If _fCheckInTable or !fPutIntbl, output row header RTF. If fPutIntbl * and _fCheckInTable, output \intbl as well. Note that fPutIntbl is * FALSE when a PF is being output, since this control word needs to * be output after the \pard, but the other row RTF needs to be output * before the \pard. * * @rdesc * BOOL TRUE if in table and outputted all relevant \trowd stuff */ BOOL CRTFWrite::CheckInTable( BOOL fPutIntbl) //@parm TRUE if \intbl should be output { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::CheckInTable"); _fCheckInTable = FALSE; if(_pPF->InTable()) { if(!_fRangeHasEOP) return TRUE; LONG cTab = _pPF->cTabCount; LONG h = _pPF->dxOffset; LONG i, j = _pPF->dxStartIndent; LONG k = _pPF->wAlignment; DWORD Tab, Widths; if (!PutCtrlWord(CWF_STR, i_trowd) || // Reset table properties h && !PutCtrlWord(CWF_VAL, i_trgaph, h) || j && !PutCtrlWord(CWF_VAL, i_trleft, j) || IN_RANGE(PFA_RIGHT, k, PFA_CENTER) && !PutCtrlWord(CWF_STR, k == PFA_RIGHT ? i_trqr : i_trqc)) { return FALSE; } PutBorders(TRUE); for(i = 0; i < cTab; i++) { Tab = _pPF->rgxTabs[i]; Widths = Tab >> 24; if(Widths) { for(j = 0; j < 4; j++, Widths >>= 2) { LONG w = Widths & 3; if(w && (!PutCtrlWord(CWF_STR, rgiszBorders[j + 9]) || !PutCtrlWord(CWF_VAL, i_brdrw, 15*w) || !PutCtrlWord(CWF_STR, i_brdrs))) { return FALSE; } } CheckDelimeter(); } if(!PutCtrlWord(CWF_VAL, i_cellx, GetTabPos(Tab))) return FALSE; } if(!fPutIntbl || PutCtrlWord(CWF_STR, i_intbl)) return TRUE; } return FALSE; } /* * CRTFWrite::PutBorders(fInTable) * * @mfunc * If any borders are defined, output their control words * * @rdesc * error code */ EC CRTFWrite::PutBorders( BOOL fInTable) { if(_pPF->wBorderWidth) { DWORD Colors = _pPF->dwBorderColor; DWORD dwEffects = Colors >> 20; LONG i = 1, iMax = 4; // NonBox for loop limits LONG j, k; DWORD Spaces = _pPF->wBorderSpace; DWORD Styles = _pPF->wBorders; DWORD Widths = _pPF->wBorderWidth; if(_pPF->wEffects & PFE_BOX) i = iMax = 0; // For box, only write one set for( ; i <= iMax; i++, Spaces >>= 4, Styles >>= 4, Widths >>= 4, Colors >>= 5) { if(!(Widths & 0xF)) // No width, so no border continue; j = TWIPS_PER_POINT*(Spaces & 0xF); k = Colors & 0x1F; if (!PutCtrlWord(CWF_STR, rgiszBorders[i + 4*fInTable]) || !PutCtrlWord(CWF_STR, rgiszBorderStyles[Styles & 0xF]) || !PutCtrlWord(CWF_VAL, i_brdrw, 10*(Widths & 0xF)) || k && !PutCtrlWord(CWF_VAL, i_brdrcf, LookupColor(g_Colors[k-1]) + 1) || j && !PutCtrlWord(CWF_VAL, i_brsp, j)) { break; } for(j = 3; j--; dwEffects >>= 1) // Output border effects { if (dwEffects & 1 && !PutCtrlWord(CWF_STR, rgiszBorderEffects[j])) { break; } } CheckDelimeter(); // Output a ' ' } } return _ecParseError; } /* * CRTFWrite::Puts(sz, cb) * * @mfunc * Put out the string <p sz> * * @rdesc * BOOL TRUE if successful */ BOOL CRTFWrite::Puts( CHAR const * sz, LONG cb) // @parm String to be put { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::Puts"); if(*sz == '\\' || *sz == '{' || *sz == ' ') _fNeedDelimeter = FALSE; CheckDelimeter(); // If _fNeedDelimeter, may need to // PutChar(' ') // Flush buffer if string won't fit if (cb < 0) return FALSE; if (_cchBufferOut + cb < _cchBufferOut || (_cchBufferOut + cb >= cachBufferMost && !FlushBuffer())) return FALSE; if (cb >= cachBufferMost) // If buffer still can't handle string, { // we have to write string directly LONG cbWritten; #ifdef DEBUG_PASTE if (FromTag(tagRTFAsText)) TraceString(sz); #endif _pes->dwError = _pes->pfnCallback(_pes->dwCookie, (LPBYTE) sz, cb, &cbWritten); _cchOut += cbWritten; #if defined(DEBUG) && !defined(MACPORT) && !defined(PEGASUS) if(_hfileCapture) { DWORD cbLeftToWrite = cb; DWORD cbWritten2 = 0; BYTE *pbToWrite = (BYTE *)sz; while(WriteFile(_hfileCapture, pbToWrite, cbLeftToWrite, &cbWritten2, NULL) && (pbToWrite += cbWritten2, (cbLeftToWrite -= cbWritten2))); } #endif if (_pes->dwError) { _ecParseError = ecPutCharFailed; return FALSE; } AssertSz(cbWritten == cb, "CRTFW::Puts: incomplete write"); } else { CopyMemory(_pchRTFEnd, sz, cb); // Put string into buffer for later _pchRTFEnd += cb; // output _cchBufferOut += cb; } return TRUE; } /* * CRTFWrite::PutCtrlWord(iFormat, iCtrl, iValue) * * @mfunc * Put control word with rgKeyword[] index <p iCtrl> and value <p iValue> * using format rgszCtrlWordFormat[<p iFormat>] * * @rdesc * TRUE if successful * * @devnote * Sets _fNeedDelimeter to flag that next char output must be a control * word delimeter, i.e., not alphanumeric (see PutChar()). */ BOOL CRTFWrite::PutCtrlWord( LONG iFormat, // @parm Format index into rgszCtrlWordFormat LONG iCtrl, // @parm Index into Keyword array LONG iValue) // @parm Control-word parameter value. If missing, { // 0 is assumed TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::PutCtrlWord"); BOOL bRet; const INT c_chT = 60; CHAR szT[c_chT]; LONG cb; cb = sprintF(c_chT, szT, rgszCtrlWordFormat[iFormat], rgKeyword[iCtrl].szKeyword, iValue); _fNeedDelimeter = FALSE; // Truncate if needed cb = min(cb, c_chT); bRet = Puts(szT, cb); _fNeedDelimeter = TRUE; // Ensure next char isn't // alphanumeric return bRet; } /* * CRTFWrite::printF(szFmt, ...) * * @mfunc * Provide formatted output * * @rdesc * TRUE if successful */ BOOL _cdecl CRTFWrite::printF( CONST CHAR * szFmt, // @parm Format string for printf() ...) // @parmvar Parameter list { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::printF"); va_list marker; const INT c_chT = 60; CHAR szT[c_chT]; int cb; va_start(marker, szFmt); cb = W32->WvsprintfA(c_chT, szT, szFmt, marker); va_end(marker); // Truncate if needed cb = min(cb, c_chT); return Puts(szT, cb); } /* * CRTFWrite::sprintF(szBuf, szFmt, ...) * * @mfunc * Provide formatted output to a string buffer * * @rdesc * number of bytes written */ LONG _cdecl CRTFWrite::sprintF( LONG cbBuf, CHAR *szBuf, CONST CHAR * szFmt, // @parm Format string for printf() ...) // @parmvar Parameter list { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::printF"); va_list marker; int cb; va_start(marker, szFmt); cb = W32->WvsprintfA(cbBuf, szBuf, szFmt, marker); va_end(marker); return cb; } /* * CRTFWrite::WritePcData(szData, nCodePage, fIsDBCS) * * @mfunc * Write out the string <p szData> as #PCDATA where any special chars * are protected by leading '\\'. * * @rdesc * EC (_ecParseError) */ EC CRTFWrite::WritePcData( const TCHAR * szData, // @parm #PCDATA string to write INT nCodePage, // @parm code page default value CP_ACP BOOL fIsDBCS) // @parm szData is a DBCS string stuffed into Unicode buffer { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WritePcData"); BYTE ch; BOOL fMissingCodePage; BOOL fMultiByte; const BYTE *pch; const char *pchToDBCSDefault = NULL; BOOL * pfUsedDefault = NULL; if(_dwFlags & SFF_UTF8) // Use UTF-8 for all conversions nCodePage = CP_UTF8; // (doesn't work for unknown cpg's // i.e., if fIsDBCS is TRUE...) if(!*szData) { return _ecParseError; } int DataSize = wcslen(szData) + 1; int BufferSize = DataSize * 2; #ifdef PWD_JUPITER // GuyBark JupiterJ 51164: // Yes, well, "* 2" may be ok for Unicode to DBCS. but it's too small to // cope with conversion to UTF8. So bump it up to always be big enough. BufferSize *= 3; #endif // PWD_JUPITER char *pBuffer = (char *)PvAlloc(BufferSize * 2, GMEM_ZEROINIT); if(!pBuffer) { return ecNoMemory; } #ifdef DEBUG // When WCTMB fails to convert a char, the following default // char is used as a placeholder in the string being converted const char chToDBCSDefault = 0; BOOL fUsedDefault; pchToDBCSDefault = &chToDBCSDefault; pfUsedDefault = &fUsedDefault; #endif int cchRet = WCTMB(fIsDBCS ? INVALID_CODEPAGE : nCodePage, 0, szData, -1, pBuffer, BufferSize, pchToDBCSDefault, pfUsedDefault, &fMissingCodePage); Assert(cchRet > 0); if(!fIsDBCS && fMissingCodePage && nCodePage != CP_ACP) { // Here, the system could not convert the Unicode string because the // code page is not installed on the system. Fallback to CP_ACP. cchRet = WCTMB(CP_ACP, 0, szData, -1, pBuffer, BufferSize, pchToDBCSDefault, pfUsedDefault, &fMissingCodePage); Assert(cchRet > 0); nCodePage = CP_ACP; } AssertSz(!fUsedDefault, "CRTFWrite::WritePcData(): Found character in " "control text which cannot be converted from " "Unicode"); if(cchRet <= 0) { _ecParseError = ecCantUnicode; goto CleanUp; } BufferSize = cchRet; fMultiByte = (BufferSize > DataSize) || fIsDBCS || fMissingCodePage; pch = (BYTE *)pBuffer; ch = *pch; // If _fNeedDelimeter, may need to PutChar(' ') CheckDelimeter(); while (!_ecParseError && (ch = *pch++)) { if(fMultiByte && *pch && IsLeadByte(ch, nCodePage)) { printF(szEscape2CharFmt, ch, *pch++); } else { if(ch == LBRACE || ch == RBRACE || ch == BSLASH) { printF(szLiteralCharFmt, ch); } else if(ch < 32 || ch == ';' || ch > 127) { printF(szEscapeCharFmt, ch); } else { PutChar(ch); } } } CleanUp: FreePv(pBuffer); return _ecParseError; } /* * CRTFWrite::LookupColor(colorref) * * @mfunc * Return color-table index for color referred to by <p colorref>. * If a match isn't found, an entry is added. * * @rdesc * LONG Index into colortable * <lt> 0 on error */ LONG CRTFWrite::LookupColor( COLORREF colorref) // @parm colorref to look for { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::LookupColor"); LONG Count = _colors.Count(); LONG iclrf; COLORREF * pclrf; for(iclrf = 0; iclrf < Count; iclrf++) // Look for color if(_colors.GetAt(iclrf) == colorref) return iclrf; pclrf = _colors.Add(1, NULL); // If we couldn't find it, if(!pclrf) // add it to color table return -1; *pclrf = colorref; return iclrf; } /* * CRTFWrite::LookupFont(pCF) * * @mfunc * Returns index into font table for font referred to by * CCharFormat *<p pCF>. If a match isn't found, an entry is added. * * @rdesc * SHORT Index into fonttable * <lt> 0 on error */ LONG CRTFWrite::LookupFont( CCharFormat const * pCF) // @parm CCharFormat holding font name { // to look up TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::LookupFont"); LONG Count = _fonts.Count(); LONG itf; TEXTFONT * ptf; for(itf = 0; itf < Count; itf++) { // Look for font ptf = _fonts.Elem(itf); if (ptf->bPitchAndFamily == pCF->bPitchAndFamily && // of same pitch, ptf->bCharSet == pCF->bCharSet && // char set, and !wcscmp(ptf->szName, pCF->szFaceName)) // name { return itf; // Found it } } ptf = _fonts.Add(1, NULL); // Didn't find it: if(!ptf) // add to table return -1; ptf->bPitchAndFamily = pCF->bPitchAndFamily; ptf->bCharSet = pCF->bCharSet; ptf->sCodePage = GetCodePage (ptf->bCharSet); wcscpy_s(ptf->szName, pCF->szFaceName); ptf->fNameIsDBCS = (pCF->bInternalEffects & CFEI_FACENAMEISDBCS); #if 0 // Bug1523 - (BradO) I removed this section of code so that a /fN tag is always // emitted for the first run of text. In theory, we should be able to // assume that the first run of text would carry the default font. // It turns out that when reading RTF, Word doesn't use anything predictable // for the font of the first run of text in the absence of an explicit /fN, // thus, we have to explicitly emit a /fN tag for the first run of text. if(!Count) // 0th font is { // default \deff0 _CF.bPitchAndFamily = pCF->bPitchAndFamily; // Set "previous" _CF.bCharSet = pCF->bCharSet; // CF accordingly wcscpy(_CF.szFaceName, pCF->szFaceName); } #endif return itf; } /* * CRTFWrite::BuildTables(prp, cch) * * @mfunc * Build font and color tables for write range of length <p cch> and * charformat run ptr <p prp> * * @rdesc * EC The error code */ EC CRTFWrite::BuildTables( CFormatRunPtr& rpCF, // @parm CF run ptr for start of write range CFormatRunPtr& rpPF, // @parm PF run ptr for start of write range LONG cch) // @parm # chars in write range { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::BuildTables"); LONG i; LONG ifmt = 0; const CCharFormat * pCF = NULL; const CParaFormat * pPF = NULL; CFormatRunPtr rp(rpCF); CFormatRunPtr rpPFtemp(rpPF); LONG cchTotal = cch; while(cch > 0) { ifmt = rp.GetFormat(); // _iFormat for next CF run pCF = _ped->GetCharFormat(ifmt); if( !pCF ) goto CacheError; // Look up character-format *pCF's font and color. If either isn't // found, it is added to appropriate table. Don't lookup color // for CCharFormats with auto-color if (LookupFont(pCF) < 0 || (!(pCF->dwEffects & CFE_AUTOCOLOR) && LookupColor(pCF->crTextColor) < 0) || (!(pCF->dwEffects & CFE_AUTOBACKCOLOR) && LookupColor(pCF->crBackColor) < 0)) { break; } if(!rp.IsValid()) break; cch -= rp.GetCchLeft(); rp.NextRun(); } // now look for bullets; if found, then we need to include // the "Symbol" font cch = cchTotal; _symbolFont = 0; while( cch > 0 ) { ifmt = rpPFtemp.GetFormat(); pPF = _ped->GetParaFormat(ifmt); if( !pPF ) { goto CacheError; } if( pPF->wNumbering == PFN_BULLET ) { // Save the Font index for Symbol. // Reset it to 0 if LookupFont return error. if ( (_symbolFont = LookupFont((CCharFormat *)&cfBullet)) < 0 ) _symbolFont = 0; // We don't need to bother looking for more bullets, since // in RichEdit 2.0, all bullets either have the same font or // have their formatting information in the character format // for the EOP mark. // GuyBark: That may be true, but we still need to keep looping // through the paragraghs for things like the stylesheet below. // break; } WORD Widths = pPF->wBorderWidth; DWORD Colors = pPF->dwBorderColor & 0xFFFFF; while(Widths && Colors) { i = Colors & 0x1F; if(i && (Widths & 0xF)) LookupColor(g_Colors[i - 1]); Widths >>= 4; Colors >>= 5; } i = (pPF->wShadingStyle >> 6) & 31; // Shading forecolor if(i) LookupColor(g_Colors[i - 1]); i = pPF->wShadingStyle >> 11; // Shading backcolor if(i) LookupColor(g_Colors[i - 1]); if(IsHeadingStyle(pPF->sStyle) && pPF->sStyle < _nHeadingStyle) _nHeadingStyle = pPF->sStyle; if(!rpPFtemp.IsValid()) break; cch -= rpPFtemp.GetCchLeft(); rpPFtemp.NextRun(); } return _ecParseError; CacheError: _ecParseError = ecFormatCache; return ecFormatCache; // Access to CF/PF cache failed } /* * CRTFWrite::WriteFontTable() * * @mfunc * Write out font table * * @rdesc * EC The error code */ EC CRTFWrite::WriteFontTable() { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WriteFontTable"); LONG Count = _fonts.Count(); int itf; int m; int pitch; TEXTFONT *ptf; char * szFamily; TCHAR * szTaggedName; if(!Count || !PutCtrlWord(CWF_GRP, i_fonttbl)) // Start font table group goto CleanUp; for (itf = 0; itf < Count; itf++) { ptf = _fonts.Elem(itf); // if (ptf->sCodePage) // if (! PutCtrlWord(CWF_VAL, i_cpg, ptf->sCodePage ) ) // goto CleanUp; // Define font family m = ptf->bPitchAndFamily >> 4; szFamily = rgKeyword[rgiszFamily[m < 6 ? m : 0]].szKeyword; szTaggedName = NULL; // check to see if this is a tagged font if (!ptf->bCharSet || !FindTaggedFont(ptf->szName, ptf->bCharSet, &szTaggedName)) { szTaggedName = NULL; } pitch = ptf->bPitchAndFamily & 0xF; // Write font if (!printF(szBeginFontEntryFmt, itf, szFamily)) // entry, family, goto CleanUp; _fNeedDelimeter = TRUE; if (pitch && !PutCtrlWord(CWF_VAL, i_fprq, pitch)) // and pitch goto CleanUp; if (!ptf->sCodePage && ptf->bCharSet) { ptf->sCodePage = GetCodePage(ptf->bCharSet); } #ifdef PWD_JUPITER // GuyBark: If this is a J font, then store the id here so we can // select it later if necessary when outputting J text chunks. if((_pwdDefaultJFont == -1) && (ptf->sCodePage == 932)) { _pwdDefaultJFont = itf; } #endif // PWD_JUPITER // Write charset. Win32 uses ANSI_CHARSET to mean the default Windows // character set, so find out what it really is extern BYTE bCharSetANSI; if(ptf->bCharSet != DEFAULT_CHARSET) { if(!PutCtrlWord(CWF_VAL, i_fcharset, ptf->bCharSet)) { goto CleanUp; } // We want to skip the \cpgN output if we've already output a \fcharsetN // tag. This is to accomodate RE1.0, which can't handle some \cpgN tags // properly. Specifically, when RE1.0 parses the \cpgN tag it does a // table lookup to obtain a charset value corresponding to the codepage. // Turns out the codepage/charset table for RE1.0 is incomplete and RE1.0 // maps some codepages to charset 0, trouncing the previously read \fcharsetN // value. goto WroteCharSet; } if (ptf->sCodePage && !PutCtrlWord (CWF_VAL, i_cpg, ptf->sCodePage)) { goto CleanUp; } WroteCharSet: #ifdef PWD_JUPITER // GuyBark: // Check if the font has a charset that means a font decoration should be // output with the name. Word 95 uses the decoration. Word 97 will just // ignore it. LPSTR pszDecoration = NULL; // No decoration needed for plain ol' Western ANSI fonts. Don't mess with // the name if we're taking any special action with it either. if(ptf->bCharSet && !szTaggedName && !ptf->fNameIsDBCS) { int i = 0; // Word97 uses a decoration of "Turkish, rather than "Tur". So we'll // use that too. We hit "Tur" first in the decoration array. // Note: the Office converters check for "Turkish" so that may mean, // but we're better off emulating Word 97. // For all the decorations we handle... while(fontDec[i].pszName) { // Is the charset of the font we're outputting the same as the decoration's? if(ptf->bCharSet == fontDec[i].charset) { // Yes! So output the decoration after the name. pszDecoration = fontDec[i].pszName; break; } // Oh well, try the next decoration. ++i; } } #endif // PWD_JUPITER if (szTaggedName) { // Have a tagged font: write out group with real name followed by tagged name if(!PutCtrlWord(CWF_AST, i_fname) || WritePcData(ptf->szName, ptf->sCodePage, ptf->fNameIsDBCS) || !Puts(szEndFontEntry, sizeof(szEndFontEntry) - 1) || WritePcData(szTaggedName, ptf->sCodePage, ptf->fNameIsDBCS) || !Puts(szEndFontEntry, sizeof(szEndFontEntry) - 1)) { goto CleanUp; } } else if(WritePcData(ptf->szName, ptf->sCodePage, ptf->fNameIsDBCS) || #ifdef PWD_JUPITER // GuyBark: We may have a decoration to output with the font name. (pszDecoration && !Puts(pszDecoration, strlen(pszDecoration))) || #endif // PWD_JUPITER !Puts(szEndFontEntry, sizeof(szEndFontEntry) - 1)) // If non-tagged font just write name out { goto CleanUp; } } Puts(szEndGroupCRLF, sizeof(szEndGroupCRLF) - 1); // End font table group CleanUp: return _ecParseError; } /* * CRTFWrite::WriteColorTable() * * @mfunc * Write out color table * * @rdesc * EC The error code */ EC CRTFWrite::WriteColorTable() { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WriteColorTable"); LONG Count = _colors.Count(); COLORREF clrf; LONG iclrf; // GuyBark Jupiter 35396: Now that we allow autocolor, we must ALWAYS // output a color table, even if it only has the one ';' entry. #ifdef PWD_JUPITER if (!PutCtrlWord(CWF_GRP, i_colortbl) // Start color table group #else if (!Count || !PutCtrlWord(CWF_GRP, i_colortbl) // Start color table group #endif // PWD_JUPITER || !PutChar(';')) // with null first entry { goto CleanUp; } for(iclrf = 0; iclrf < Count; iclrf++) { clrf = _colors.GetAt(iclrf); if (!printF(szColorEntryFmt, GetRValue(clrf), GetGValue(clrf), GetBValue(clrf))) goto CleanUp; } Puts(szEndGroupCRLF,sizeof(szEndGroupCRLF) -1); // End color table group CleanUp: return _ecParseError; } /* * CRTFWrite::WriteCharFormat(pCF) * * @mfunc * Write deltas between CCharFormat <p pCF> and the previous CCharFormat * given by _CF, and then set _CF = *<p pCF>. * * @rdesc * EC The error code * * @devnote * For optimal output, could write \\plain and use deltas relative to * \\plain if this results in less output (typically only one change * is made when CF changes, so less output results when compared to * previous CF than when compared to \\plain). */ EC CRTFWrite::WriteCharFormat( const CCharFormat * pCF) // @parm Ptr to CCharFormat { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WriteCharFormat"); DWORD dwEffects = pCF->dwEffects; DWORD dwChanges = dwEffects ^ _CF.dwEffects; LONG i; // Counter LONG iFormat; LONG iValue; // Control-word value LONG i_sz; // Temp ctrl string index DWORD UType; // Underline type LONG yOffset = pCF->yOffset; // GuyBark Jupiter J // For JupiterJ I've added two new numbered list types. This mean // I had to change all the i_xx array to Word arrays not bytes. // AssertSz(cKeywords < 256, // "CRTFWrite::WriteCharFormat: change BYTE i_xx to WORD"); if (dwChanges & CFE_AUTOCOLOR || // Change in autocolor pCF->crTextColor != _CF.crTextColor) // or text color { iValue = 0; // Default autocolor if(!(dwEffects & CFE_AUTOCOLOR)) // Make that text color iValue = LookupColor(pCF->crTextColor) + 1; if(!PutCtrlWord(CWF_VAL, i_cf, iValue)) goto CleanUp; } if (dwChanges & CFE_AUTOBACKCOLOR || // Change in autobackcolor pCF->crBackColor != _CF.crBackColor) // or backcolor { iValue = 0; // Default autobackcolor if(!(dwEffects & CFE_AUTOBACKCOLOR)) // Make that back color iValue = LookupColor(pCF->crBackColor) + 1; if(!PutCtrlWord(CWF_VAL, i_highlight, iValue)) goto CleanUp; } if (pCF->lcid != _CF.lcid && !PutCtrlWord(CWF_VAL, i_lang, LANGIDFROMLCID((WORD)pCF->lcid)) || pCF->sSpacing != _CF.sSpacing && !PutCtrlWord(CWF_VAL, i_expndtw, pCF->sSpacing) || /* FUTURE (alexgo): This code is incorrect and we don't yet handle the Style table. We may want to support this better in a future version. pCF->sStyle != _CF.sStyle && pCF->sStyle > 0 && !PutCtrlWord(CWF_VAL, i_cs, pCF->sStyle) || */ pCF->bAnimation != _CF.bAnimation && !PutCtrlWord(CWF_VAL, i_animtext, pCF->bAnimation) || /* FUTURE (alexgo): this code doesn't work yet, as we don't output the revision table. We may want to support this better in a future version pCF->bRevAuthor != _CF.bRevAuthor && !PutCtrlWord(CWF_VAL, i_revauth, pCF->bRevAuthor) || */ pCF->wKerning != _CF.wKerning && !PutCtrlWord(CWF_VAL, i_kerning, pCF->wKerning/10) ) { goto CleanUp; } UType = _CF.bUnderlineType; // Handle all underline if (UType <= CUNDERLINES && // known and dwEffects & CFM_UNDERLINE && // active changes (UType != pCF->bUnderlineType || // Type change while on dwChanges & CFM_UNDERLINE)) // Turn on { dwChanges &= ~CFE_UNDERLINE; // Suppress underline i = pCF->bUnderlineType; if(i) i--; if(!PutCtrlWord(CWF_STR, rgiszUnderlines[i])) // action in next for() goto CleanUp; // Note: \ul0 turns off } // all underlining // This must be before next stuff if(dwChanges & (CFM_SUBSCRIPT | CFM_SUPERSCRIPT))// change in sub/sup { // status i_sz = dwEffects & CFE_SUPERSCRIPT ? i_super : dwEffects & CFE_SUBSCRIPT ? i_sub : i_nosupersub; if(!PutCtrlWord(CWF_STR, i_sz)) goto CleanUp; } dwChanges &= ((1 << CEFFECTS) - 1) & ~CFE_LINK; // Output keywords for for(i = CEFFECTS; // effects that changed dwChanges && i--; // rgszEffects[] contains dwChanges >>= 1, dwEffects >>= 1) // effect keywords in { // order max CFE_xx to if(dwChanges & 1) // min CFE-xx { // Change from last call iValue = dwEffects & 1; // If effect is off, write iFormat = iValue ? CWF_STR : CWF_VAL; // a 0; else no value if(!PutCtrlWord(iFormat, rgiszEffects[i], iValue)) goto CleanUp; } } if(yOffset != _CF.yOffset) // Change in base line { // position yOffset /= 10; // Default going to up i_sz = i_up; iFormat = CWF_VAL; if(yOffset < 0) // Make that down { i_sz = i_dn; yOffset = -yOffset; } if(!PutCtrlWord(iFormat, i_sz, yOffset)) goto CleanUp; } if (pCF->bPitchAndFamily != _CF.bPitchAndFamily || // Change in font pCF->bCharSet != _CF.bCharSet || lstrcmp(pCF->szFaceName, _CF.szFaceName)) { iValue = LookupFont(pCF); if(iValue < 0 || !PutCtrlWord(CWF_VAL, i_f, iValue)) goto CleanUp; #ifdef PWD_JUPITER // GuyBark: Keep a track of the current font selected. _pwdCurrentFont = iValue; #endif // PWD_JUPITER } if (pCF->yHeight != _CF.yHeight) // Change in font size { iValue = (pCF->yHeight + (pCF->yHeight > 0 ? 5 : -5))/10; if(!PutCtrlWord(CWF_VAL, i_fs, iValue)) goto CleanUp; } _CF = *pCF; // Update previous CCharFormat CleanUp: return _ecParseError; } /* * CRTFWrite::WriteParaFormat(prtp) * * @mfunc * Write out attributes specified by the CParaFormat <p pPF> relative * to para defaults (probably produces smaller output than relative to * previous para format and let's you redefine tabs -- no RTF kill * tab command except \\pard) * * @rdesc * EC The error code */ EC CRTFWrite::WriteParaFormat( const CRchTxtPtr * prtp) // @parm Ptr to rich-text ptr at current cp { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WriteParaFormat"); Assert(_ped); //if(!_fRangeHasEOP) // Don't write para info if // return _ecParseError; // range has no EOPs const CParaFormat * pPFPrev = _pPF; const CParaFormat * pPF = _pPF = prtp->GetPF(); if (NULL == pPF) return _ecParseError; BOOL fInTable = pPF->InTable(); LONG c; // Temporary count LONG cTab = pPF->cTabCount; DWORD dwEffects; DWORD dwRule = pPF->bLineSpacingRule; LONG dy = pPF->dyLineSpacing; LONG i_t, i, j, k; LONG tabAlign, tabLead, tabPos; LONG lDocDefaultTab = _ped->GetDefaultTab(); if(!lDocDefaultTab) lDocDefaultTab = lDefaultTab; if (cTab == 1 && pPF->rgxTabs[0] == lDocDefaultTab + (LONG)PFT_DEFAULT || CheckInTable(FALSE)) { cTab = 0; // Suppress \tab output } AssertSz(cTab >= 0 && cTab <= MAX_TAB_STOPS, "CRTFW::WriteParaFormat: illegal cTabCount"); // Exchange's IMC keys on the \protect tag when it does // its reply-ticking for mail being sent to Internet recipients. // Paragraphs following a \pard and containing a \protect tag are // reply-ticked, so we must ensure that each \pard in a protected range // is followed by a \protect tag. if (_CF.dwEffects & CFE_PROTECTED && !PutCtrlWord(CWF_VAL, i_protect, 0) || !PutCtrlWord(CWF_STR, i_pard) || // Reset para attributes _CF.dwEffects & CFE_PROTECTED && !PutCtrlWord(CWF_STR, i_protect)) { goto CleanUp; } if(fInTable) { if(_fRangeHasEOP && !PutCtrlWord(CWF_STR, i_intbl)) goto CleanUp; } else if(PutBorders(FALSE)) goto CleanUp; if(pPF->wShadingStyle) { i = pPF->wShadingStyle & 15; // Shading patterns j = (pPF->wShadingStyle >> 6) & 31; // Shading forecolor k = pPF->wShadingStyle >> 11; // Shading backcolor if (i && i <= CSHADINGSTYLES && !PutCtrlWord(CWF_STR, rgiszShadingStyles[i - 1]) || j && !PutCtrlWord(CWF_VAL, i_cfpat, LookupColor(g_Colors[j-1]) + 1) || k && !PutCtrlWord(CWF_VAL, i_cbpat, LookupColor(g_Colors[k-1]) + 1)) { goto CleanUp; } } if(pPF->wShadingWeight && !PutCtrlWord(CWF_VAL, i_shading, pPF->wShadingWeight)) goto CleanUp; // Paragraph numbering _fBullet = _fBulletPending = FALSE; _nNumber = pPF->UpdateNumber(_nNumber, pPFPrev); if(pPF->wNumbering) // Write numbering info { LONG iFont = _symbolFont; if(pPF->IsListNumbered()) { const CCharFormat *pCF; WCHAR szNumber[CCHMAXNUMTOSTR]; CTxtPtr rpTX(prtp->_rpTX); CFormatRunPtr rpCF(prtp->_rpCF); rpCF.AdvanceCp(rpTX.FindEOP(tomForward)); rpCF.AdjustBackward(); pCF = _ped->GetCharFormat(rpCF.GetFormat()); iFont = LookupFont(pCF); if(iFont < 0) { iFont = 0; TRACEERRORSZ("CWRTFW::WriteParaFormat: illegal bullet font"); } _nFont = iFont; // TODO: make the following smarter, i.e., may need to increment // _nNumber instead of resetting it to 1. _cpg = GetCodePage(pCF->bCharSet); i = 0; // GuyBark JupiterJ: Assume we want everything before sequence value // if(pPF->wNumbering <= tomListNumberAsUCRoman) if(pPF->wNumbering < tomListNumberAsSequence) i = pPF->wNumbering - tomListNumberAsArabic; WORD wStyle = pPF->wNumberingStyle & 0xF00; WCHAR ch = (wStyle == PFNS_PARENS || wStyle == PFNS_PAREN) ? ')' : (wStyle == PFNS_PERIOD) ? '.' : 0; if(wStyle != PFNS_NONUMBER) // Unless number suppressed { // write \pntext group pPF->NumToStr(szNumber, _nNumber); if (!printF(szBeginNumberGroup, iFont) || WritePcData(szNumber, _cpg, FALSE) || !printF(szEndNumberGroup)) { goto CleanUp; } } if (!printF(szBeginNumberFmt, wStyle == PFNS_NONUMBER ? "cont" : "body", iFont, pPF->wNumberingTab, pPF->wNumberingStart) || !PutCtrlWord(CWF_STR, rgiszNumberStyle[i]) || wStyle == PFNS_PARENS && !printF(szpntxtb) || ch && !printF(szpntxta, ch) || !printF(szEndGroupCRLF)) { goto CleanUp; } } else { if (!printF(szBulletGroup, iFont) || !printF(szBulletFmt, iFont, pPF->wNumberingTab)) { goto CleanUp; } } _fBullet = TRUE; } // Put out para indents. RTF first indent = -PF.dxOffset // RTF left indent = PF.dxStartIndent + PF.dxOffset if(IsHeadingStyle(pPF->sStyle) && !PutCtrlWord(CWF_VAL, i_s, -pPF->sStyle-1)) goto CleanUp; if(!fInTable && (pPF->dxOffset && !PutCtrlWord(CWF_VAL, i_fi, -pPF->dxOffset) || pPF->dxStartIndent + pPF->dxOffset && !PutCtrlWord(CWF_VAL, i_li, pPF->dxStartIndent + pPF->dxOffset) || pPF->dxRightIndent && !PutCtrlWord(CWF_VAL, i_ri, pPF->dxRightIndent))) { goto CleanUp; } if (pPF->dySpaceBefore && !PutCtrlWord(CWF_VAL, i_sb, pPF->dySpaceBefore) || pPF->dySpaceAfter && !PutCtrlWord(CWF_VAL, i_sa, pPF->dySpaceAfter)) { goto CleanUp; } if (dwRule) // Special line spacing active { i = 0; // Default "At Least" or if (dwRule == tomLineSpaceExactly) // "Exactly" line spacing dy = -abs(dy); // Use negative for "Exactly" else if(dwRule == tomLineSpaceMultiple) // RichEdit uses 20 units/line { // RTF uses 240 units/line i++; dy *= 12; } else if (dwRule != tomLineSpaceAtLeast && dy > 0) { i++; // Multiple line spacing if (dwRule <= tomLineSpaceDouble) // 240 units per line dy = 120 * (dwRule + 2); } if (!PutCtrlWord(CWF_VAL, i_sl, dy) || !PutCtrlWord(CWF_VAL, i_slmult, i)) { goto CleanUp; } } dwEffects = pPF->wEffects & ((1 << CPFEFFECTS) - 1); for(c = CPFEFFECTS; dwEffects && c--; // Output PARAFORMAT2 effects dwEffects >>= 1) { // rgiszPFEffects[] contains PF effect keywords in the // order max PFE_xx to min PFE-xx AssertSz(rgiszPFEffects[2] == i_hyphpar, "CRTFWrite::WriteParaFormat(): rgiszPFEffects is out-of-sync with PFE_XXX"); // \hyphpar has opposite logic to our PFE_DONOTHYPHEN so we emit // \hyphpar0 to toggle the property off if (dwEffects & 1 && !PutCtrlWord((c == 2) ? CWF_VAL : CWF_STR, rgiszPFEffects[c], 0)) { goto CleanUp; } } if (!fInTable && IN_RANGE(PFA_RIGHT, pPF->wAlignment, PFA_JUSTIFY) && !PutCtrlWord(CWF_STR, rgiszAlignment[pPF->wAlignment - 1])) { goto CleanUp; } for (i = 0; i < cTab; i++) { pPF->GetTab(i, &tabPos, &tabAlign, &tabLead); AssertSz (tabAlign <= tomAlignBar && tabLead <= 5, "CRTFWrite::WriteParaFormat: illegal tab leader/alignment"); i_t = i_tb; // Default \tb (bar tab) if (tabAlign != tomAlignBar) // It isn't a bar tab { i_t = i_tx; // Use \tx for tabPos if (tabAlign && // Put nonleft alignment !PutCtrlWord(CWF_STR, rgiszTabAlign[tabAlign-1])) { goto CleanUp; } } if (tabLead && // Put nonzero tab leader !PutCtrlWord(CWF_STR, rgiszTabLead[tabLead-1]) || !PutCtrlWord(CWF_VAL, i_t, tabPos)) { goto CleanUp; } } CleanUp: return _ecParseError; } /* * CRTFWrite::WriteText(cwch, lpcwstr, nCodePage, fIsDBCS) * * @mfunc * Write out <p cwch> chars from the Unicode text string <p lpcwstr> taking care to * escape any special chars. The Unicode text string is scanned for characters which * map directly to RTF strings, and the surrounding chunks of Unicode are written * by calling WriteTextChunk. * * @rdesc * EC The error code */ EC CRTFWrite::WriteText( LONG cwch, // @parm # chars in buffer LPCWSTR lpcwstr, // @parm Pointer to text INT nCodePage, // @parm code page to use to convert to DBCS BOOL fIsDBCS) // @parm indicates whether lpcwstr is a Unicode string // or a DBCS string stuffed into a WSTR { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WriteText"); WCHAR *pwchScan; WCHAR *pwchStart; if (_fBulletPending) { _fBulletPending = FALSE; if(!_nNumber) { if(!printF(szBulletGroup, _symbolFont)) goto CleanUp; } else if(!_pPF->IsNumberSuppressed()) { WCHAR szNumber[CCHMAXNUMTOSTR]; _pPF->NumToStr(szNumber, ++_nNumber); if (!printF(szBeginNumberGroup, _nFont) || WritePcData(szNumber, _cpg, FALSE) || !printF(szEndNumberGroup)) { goto CleanUp; } } } if(_fCheckInTable) { CheckInTable(TRUE); if(_ecParseError) goto CleanUp; } pwchScan = const_cast<LPWSTR>(lpcwstr); pwchStart = pwchScan; if(_CF.bCharSet == SYMBOL_CHARSET) { pwchScan += cwch; cwch = 0; } // Step through the Unicode buffer, weeding out characters that have // known translations to RTF strings while(cwch-- > 0) { WCHAR wch = *pwchScan; // If this is a string for which the MultiByteToUnicode conversion // failed, the buffer will be filled with ANSI bytes stuffed into // wchar's (one per). In this case, we don't want to map trail bytes // to RTF strings. if(fIsDBCS && IsLeadByte(wch, nCodePage)) { #ifdef PWD_JUPITER // GuyBark JupiterJ: // If there is no trailing byte then that wasn't really a // lead byte. It was probably an extended ansi character // which incorrectly had a FE font applied to it. if(cwch > 0) { #endif // PWD_JUPITER Assert(cwch); cwch--; pwchScan += 2; continue; #ifdef PWD_JUPITER } #endif // PWD_JUPITER } // if the char is one for which there is an appropriate RTF string // write the preceding chars and output the RTF string if(!IN_RANGE(' ', wch, 'Z') && !IN_RANGE('a', wch, 'z') && !IN_RANGE(chOptionalHyphen + 1, wch, ENSPACE - 1) && #ifdef PWD_JUPITER // GuyBark Jupiter: Handle the special character for CRLF in table cells. (wch <= BULLET || wch == PWD_CRLFINCELL) && #else wch <= BULLET && #endif // PWD_JUPITER MapsToRTFKeywordW(wch)) { if (pwchScan != pwchStart && WriteTextChunk(pwchScan - pwchStart, pwchStart, nCodePage, fIsDBCS)) { goto CleanUp; } // map the char(s) to the RTF string int cwchUsed = MapToRTFKeyword(pwchScan, cwch, MAPTOKWD_UNICODE); cwch -= cwchUsed; pwchScan += cwchUsed; // start of next run of unprocessed chars is one past current char pwchStart = pwchScan + 1; #ifdef TARGET_NT // V-GUYB: Don;t change device code at this late stage. if(cwch) { _fCheckInTable = FALSE; } #endif // TARGET_NT } pwchScan++; } // write the last chunk if (pwchScan != pwchStart && WriteTextChunk(pwchScan - pwchStart, pwchStart, nCodePage, fIsDBCS)) { goto CleanUp; } CleanUp: return _ecParseError; } /* * CRTFWrite::WriteTextChunk(cwch, lpcwstr, nCodePage, fIsDBCS) * * @mfunc * Write out <p cwch> chars from the Unicode text string <p lpcwstr> taking care to * escape any special chars. Unicode chars which cannot be converted to * DBCS chars using the supplied codepage, <p nCodePage>, are written using the * \u RTF tag. * * @rdesc * EC The error code */ EC CRTFWrite::WriteTextChunk( LONG cwch, // @parm # chars in buffer LPCWSTR lpcwstr, // @parm Pointer to text INT nCodePage, // @parm code page to use to convert to DBCS BOOL fIsDBCS) // @parm indicates whether lpcwstr is a Unicode string // or a DBCS string stuffed into a WSTR { // FUTURE(BradO): There is alot of commonality b/t this routine and // WritePcData. We should re-examine these routines and consider // combining them into a common routine. TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WriteTextChunk"); BYTE b; LONG cbAnsi; LONG cbAnsiBufferSize; BYTE * pbAnsiBuffer; BYTE * pbAnsi; BOOL fUsedDefault = FALSE; BOOL fMultiByte; BOOL fMissingCodePage = FALSE; #ifdef PWD_JUPITER // GuyBark: If we're going to output J text below, then we must make // sure a J font is current for the text chunk. RichEdit and Word97 // don;t care, as they look at the unicode, but Word95 relies on the // MBCS equivalent of the unicode. While Word95 and Word97 always have // a J font selected for the run, the Word converters may not. BOOL bSetJFont = FALSE; #endif // PWD_JUPITER // When WideCharToMultiByte fails to convert a char, the following default // char is used as a placeholder in the string being converted // GuyBark JupiterJ 50783: // Originally we were passing a default character os '\0' through to // WideCharToMultiByte(). But the OS code says, if the codepage is FE, // then the MBCS we may end up getting is either one or two bytes // depending on what the second byte if the default character is. But // we shouldn't have to care what the second byte is. If the first // byte is zero (ie the low byte) then we can't have supplied a DBCS // character. Anyway, pass in two zero bytes here. const char szDBCSDefault[2] = {0, 0}; // Allocate temp buffer for ANSI text we convert to cbAnsiBufferSize = cachBufferMost * (nCodePage == CP_UTF8 ? 3 : MB_LEN_MAX); if (!_pbAnsiBuffer) { // If the code page was CP_UTF8, it will always be CP_UTF8 for this instance _pbAnsiBuffer = (BYTE *)PvAlloc(cbAnsiBufferSize, GMEM_FIXED); if (!_pbAnsiBuffer) goto RAMError; } pbAnsiBuffer = _pbAnsiBuffer; // Convert Unicode (or fIsDBCS) buffer to ANSI if(fIsDBCS) { // Supply some bogus code page which will force direct conversion // from wchar to bytes (losing high byte of wchar). // Also, don't want to use default char replacement in this case. cbAnsi = WCTMB(INVALID_CODEPAGE, 0, lpcwstr, cwch, (char *)pbAnsiBuffer, cbAnsiBufferSize, NULL, NULL, NULL); } else { cbAnsi = WCTMB(nCodePage, 0, lpcwstr, cwch, (char *)pbAnsiBuffer, cbAnsiBufferSize, szDBCSDefault, &fUsedDefault, &fMissingCodePage); } Assert(cbAnsi > 0); pbAnsi = pbAnsiBuffer; fMultiByte = (cbAnsi > cwch) || fIsDBCS || fMissingCodePage; while (!_ecParseError && cbAnsi-- > 0) { b = *pbAnsi; // Compare ASCII chars to their Unicode counterparts to check // that we're in sync AssertSz(cwch <= 0 || *lpcwstr > 127 || b == *lpcwstr, "CRTFWrite::WriteText: Unicode and DBCS strings out of sync"); // FUTURE(BradO): MurrayS made a clever change to this code which // caused the RTF writer to output the \uN tag for all ASCII characters // greater than 0x7F. This change was necessitated by the behaviour // of WCTMB whereby Unicode chars which should fail the conversion to ANSI // are converted to some "best-match" for the codepage // (ex. alpha's convert to 'a' with cpg==1252). // // This change was pulled out at the request of Outlook, but should // be considered for RE2.1. This change can be found in version 75 of // this file. Note: NT 5.0 plans to introduce the flag // WC_NO_BEST_FIT_CHARS, which should make our current algorithm output // \uN values whenever the system cannot convert a character correctly. if (!IN_RANGE(' ', b, 'z') && !IN_RANGE('A', b, 'Z') && MapsToRTFKeywordA(b)) { int cchUsed = MapToRTFKeyword(pbAnsi, cbAnsi, MAPTOKWD_ANSI); cbAnsi -= cchUsed; pbAnsi += cchUsed; } else if(nCodePage == CP_UTF8) { PutChar(b); // Output 1st byte in any if(b >= 0xC0) // case. At least 2-byte { // At least 2-byte lead pbAnsi++; // byte, so output a Assert(cbAnsi && IN_RANGE(0x80, *pbAnsi, 0xBF)); cbAnsi--; // trail byte PutChar(*pbAnsi); if(b >= 0xE0) // 3-byte lead byte, so { // output another trail pbAnsi++; // byte Assert(cbAnsi && IN_RANGE(0x80, *pbAnsi, 0xBF)); cbAnsi--; PutChar(*pbAnsi); } } } else if(fMultiByte && cbAnsi && IsLeadByte(b, nCodePage)) { #ifdef PWD_JUPITER // GuyBark: If we have the UNICODE value for the character, output it here. // Then follow it by the MBCS value. This allows the output RTF file to // be more portable later, if it's read on a system that doesn't have the // required code page for the MBCS. if(!fIsDBCS) { // If this is a lead byte, then we will try to output a DBCS value. // This means the UNICODE will ALWAYS be followed by 2 MBCS values. int cb = 2; // Is the current \ucN value good to use? if(cb != _UnicodeBytesPerChar) { // No, so set up \uc2 if(!PutCtrlWord(CWF_VAL, i_uc, cb)) { goto CleanUp; } _UnicodeBytesPerChar = cb; } // Now output the unicode value. if(!PutCtrlWord(CWF_VAL, i_u, (int)*lpcwstr)) { goto CleanUp; } } // If the code page is missing, then the pbAnsi buffer was artifically // created to hold one byte per character. In which case we never want // to jump two bytes per character. if(!fMissingCodePage) { #endif // PWD_JUPITER pbAnsi++; // Output DBCS pair cbAnsi--; #ifdef PWD_JUPITER } #endif // PWD_JUPITER if(fIsDBCS) { lpcwstr++; cwch--; } printF(szEscape2CharFmt, b, *pbAnsi); } else { // GuyBark 3/10/98 17827: // If the character being output is not a character from the lower character set // of an ansi font, then output it with the matching unicode token. Otherwise we // have problems preserving characters from non-existing fonts. The // following test means that we will write out the unicode more often than we // need too, but that just means the output rtf is pretty darn portable. #ifdef PWD_JUPITER if(*lpcwstr != (WCHAR)b) { // The unicode char value is not the same as the equivalent ansi value. // GuyBark: 3/27/97 This is what we'd do if we're were happy always writing // the non-unicode representation as one byte, (ie with the \uc1 token). // But some unicode values we output here can only be represented as double // byte, so we will need to \uc2 token in this case. /* if(!PutCtrlWord(CWF_VAL, i_u, ((cwch > 0) ? (int)*lpcwstr : TEXT('?'))) || !printF(szEscapeCharFmt, b)) { goto CleanUp; } */ int cb, nCodePageUse = nCodePage; BYTE sza[2] = {0}; // If we're outputting J text here, we must make sure a J font is selected. // IMPORTANT: This check was originally added to make sure J text is output // with a font with the J code page. This worked around a problem with the // Office converters, whereby J text may still the 1252 code page selected. // This workaround is never needed here now, as we trap this problem during // the stream in process instead. Keep this code here anyway in case the // stream in failed to recognize the problem. if((_pwdDefaultJFont != -1) && // We have a J font to use if necessary. !bSetJFont && // We haven't yet selected a J font ourselves. (nCodePage == 1252)) // The current font for this chunk is set to be ansi. { // Is the character we're outputting part of the FE unicode range? if(IN_RANGE(0x3000, *lpcwstr, 0x33FF) || // "CJK Symbols and Punctuation", "Hiragana", "Katakana", "Bopomofo", "Hangul Compatibility Jamo", "Kanbun", "Enclosed CJK Letters and Months", "CJK Compatibility" IN_RANGE(0x4E00, *lpcwstr, 0x9FFF) || // "CJK Unified Ideographs" IN_RANGE(0xF900, *lpcwstr, 0xFAFF) || // "CJK Compatibility Ideographs" IN_RANGE(0xFE30, *lpcwstr, 0xFE4F) || // "CJK Compatibility Forms" IN_RANGE(0xFF00, *lpcwstr, 0xFFEF)) // "Halfwidth and Fullwidth Forms" { // Yes! So we will explicitly set the current font to be J in the output file. bSetJFont = TRUE; // Assume that this entire chunk for have the J font. We will restore // the original font after processing this text chunk. if(!PutCtrlWord(CWF_VAL, i_f, _pwdDefaultJFont)) { goto CleanUp; } // Use the J code page (not ansi) for finding the MBCS char below. nCodePageUse = 932; } } // Map the unicode value to MBCS. if(!(cb = WCTMB(nCodePageUse, 0, lpcwstr, 1, (char*)sza, 2, NULL, NULL, NULL))) { // No map possible. So output a single escaped question mark. sza[0] = '?'; cb = 1; } // Output the count of bytes that comprise the MBCS character // if it's not the current value. if(cb != _UnicodeBytesPerChar) { if(!PutCtrlWord(CWF_VAL, i_uc, cb)) { goto CleanUp; } _UnicodeBytesPerChar = cb; } // Now output the unicode token first. if(!PutCtrlWord(CWF_VAL, i_u, ((cwch > 0) ? (int)*lpcwstr : TEXT('?')))) { goto CleanUp; } // Now output the non-unicode equivalent. if(!printF(szEscapeCharFmt, sza[0])) { goto CleanUp; } // If this character has a two byte non-unicode representation, // then output the second byte, also adjust the cbAnsi and pbAnsi if(cb > 1) { cbAnsi--; pbAnsi++; if (!printF(szEscapeCharFmt, sza[1])) { goto CleanUp; } } } else // *** DROP THROUGH TO EXISTING RICHEDIT CODE. *** #endif // PWD_JUPITER if(b == szDBCSDefault[0] && fUsedDefault) { // Here, the WideCharToMultiByte couldn't complete a conversion // so the routine used as a placeholder the default char we provided. // In this case we want to output the original Unicode character. if(!PutCtrlWord(CWF_VAL, i_u, ((cwch > 0) ? (int)*lpcwstr : TEXT('?'))) || #ifndef PWD_JUPITER !printF(szEscapeCharFmt, '?')) #else // We may currently be outputting 2 MBCS bytes per UNICODE character. !printF(szEscapeCharFmt, '?') || (_UnicodeBytesPerChar == 2 && !printF(szEscapeCharFmt, '?'))) #endif // PWD_JUPITER { goto CleanUp; } } else if(!IN_RANGE(32, b, 127)) printF(szEscapeCharFmt, b); else if(b == '\\') printF(szLiteralCharFmt, b); else PutChar(b); } pbAnsi++; lpcwstr++; cwch--; } goto CleanUp; RAMError: _ped->GetCallMgr()->SetOutOfMemory(); _ecParseError = ecNoMemory; CleanUp: #ifdef PWD_JUPITER // GuyBark: If we selected the J font above, restore the previous font now. if(bSetJFont && !PutCtrlWord(CWF_VAL, i_f, _pwdCurrentFont)) { goto CleanUp; } #endif // PWD_JUPITER return _ecParseError; } /* * CRTFWrite::WriteInfo() * * @mfunc * Write out Far East specific data. * * @rdesc * EC The error code */ EC CRTFWrite::WriteInfo() { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WriteInfo"); // TODO(BradO): Ultimately it would be nice to set some kind of // fRTFFE bit to determine whether to write \info stuff. For now, // we rely on the fact that lchars and fchars info actually exists // to determine whether to write out the \info group. #ifdef UNDER_WORK if (!(_dwFlags & fRTFFE) || // Start doc area !PutCtrlWord(CWF_GRP, i_info) || !printF("{\\horzdoc}")) goto CleanUp; // Write out punctuation character info CHAR sz[PUNCT_MAX]; if(UsVGetPunct(_ped->lpPunctObj, PC_FOLLOWING, sz, sizeof(sz)) > PUNCT_MAX - 2) goto CleanUp; if(!Puts("{\\*\\fchars") || WritePcData(sz) || !PutChar(chEndGroup)) goto CleanUp; if(UsVGetPunct(ped->lpPunctObj, PC_LEADING, sz, sizeof(sz)) > PUNCT_MAX+2) goto CleanUp; if(!Puts("{\\*\\lchars") || WritePcData(sz) || !PutChar(chEndGroup)) goto CleanUp; Puts(szEndGroupCRLF); // End info group #endif LPTSTR lpstrLeading = NULL; LPTSTR lpstrFollowing = NULL; // if either succeeds (but evaluate both) if(((_ped->GetLeadingPunct(&lpstrLeading) == NOERROR) + (_ped->GetFollowingPunct(&lpstrFollowing) == NOERROR)) && (lpstrLeading || lpstrFollowing)) { if (!PutCtrlWord(CWF_GRP, i_info) || !Puts(szHorzdocGroup,sizeof(szHorzdocGroup) - 1)) { goto CleanUp; } if(lpstrLeading) { if(!PutCtrlWord(CWF_AST, i_lchars) || WritePcData(lpstrLeading, INVALID_CODEPAGE, TRUE) || !PutChar(chEndGroup)) { goto CleanUp; } } if(lpstrFollowing) { if(!PutCtrlWord(CWF_AST, i_fchars) || WritePcData(lpstrFollowing, INVALID_CODEPAGE, TRUE) || !PutChar(chEndGroup)) { goto CleanUp; } } Puts(szEndGroupCRLF,sizeof(szEndGroupCRLF) - 1); // End info group } CleanUp: return _ecParseError; } /* * CRTFWrite::WriteRtf() * * @mfunc * Write range _prg to output stream _pes. * * @rdesc * LONG Number of chars inserted into text; 0 means none were * inserted, OR an error occurred. */ LONG CRTFWrite::WriteRtf() { TRACEBEGIN(TRCSUBSYSRTFW, TRCSCOPEINTERN, "CRTFWrite::WriteRtf"); LONG cch, cchBuffer; LONG cchCF, cchPF; LONG cchT; LONG cpMin, cpMost; BOOL fOutputEndGroup; LONG i, j; LONG lDocDefaultTab; TCHAR * pch; TCHAR * pchBuffer; CTxtEdit * ped = _ped; CDocInfo * pDocInfo = ped->GetDocInfo(); CRchTxtPtr rtp(*_prg); WORD wCodePage = CP_ACP; CTxtPtr tp(rtp._rpTX); AssertSz(_prg && _pes, "CRTFW::WriteRtf: improper initialization"); // Allocate buffers for text we pick up and for RTF output pchBuffer = (TCHAR *) PvAlloc(cachBufferMost * (sizeof(TCHAR) + 1) + 1, GMEM_FIXED); // Final 1 is for debug if(!pchBuffer) { fOutputEndGroup = FALSE; goto RAMError; } _pchRTFBuffer = (CHAR *)(pchBuffer + cachBufferMost); _pchRTFEnd = _pchRTFBuffer; // Initialize RTF buffer ptr _cchBufferOut = 0; // and character count _cchOut = 0; // and character output cch = _prg->GetRange(cpMin, cpMost); // Get rtp = cpMin and cch > 0 rtp.SetCp(cpMin); _fRangeHasEOP = tp.IsAtEOP() || tp.FindEOP(cch); #ifdef PWD_JUPITER // GuyBark: We need to keep track of the current font selected . _pwdCurrentFont = 0; _pwdDefaultJFont = -1; #endif // PWD_JUPITER // Start \rtfN or \pwdN group i = (_dwFlags & SFF_RTFVAL) >> 16; if (!PutCtrlWord(CWF_GRV, (_dwFlags & SFF_PWD) ? i_pwd : i_rtf, i + 1) || !PutCtrlWord(CWF_STR, i_ansi)) { goto CleanUpNoEndGroup; } #ifdef PWD_REHEADERCOMMENT // GuyBark: Add a comment at the top of a WordPad file to get the attention // of users who trying opening this file in something other than WordPad. if(_dwFlags & SFF_PWD) { int cch2, cbRequired; LPSTR pszaComment = NULL; LPTSTR pszwComment = NULL; HWND hWndControl; // Get the RichEdit control window. if(_ped->TxGetWindow(&hWndControl) == S_OK) { // Can we get a Header comment from PWord? if((cch2 = SendMessage(GetParent(hWndControl), WM_PWORD_GETHEADERCOMMENT, 0, (LPARAM)&pszwComment)) && pszwComment) { // Try to output a multibyte comment in the file. BOOL bErrorWritingComment = TRUE; // RichEdit ALWAYS built unicode. if((cbRequired = WideCharToMultiByte(CP_ACP, 0, pszwComment, cch2, NULL, 0, NULL, NULL))) { // Allocate space for a multibyte version. if((pszaComment = (LPSTR)PvAlloc(cbRequired + 1, GMEM_ZEROINIT))) { // Use the same code page as that associated with this document. // No! Don't use that. The code pafe associated with the document // could be the unicode codepage, (1200). Calling WideCharToMultiByte() // fails here if we supply the unicode code page. So use the default // code page for whatever system the user is running on. if(WideCharToMultiByte(CP_ACP, 0, pszwComment, cch2, pszaComment, cbRequired, NULL, NULL)) { // Make sure it's null terminated. pszaComment[cbRequired] = '\0'; // There is a comment, so output the comment group start. if(printF(szPwdComment)) { // Now output the comment itself. if(Puts(pszaComment, cbRequired)) { // End PWord Comment group. if(PutChar(chEndGroup)) { // It all worked ok! bErrorWritingComment = FALSE; } } } } FreePv(pszaComment); } } // WordPad needs us to free the supplied memory too. LocalFree(pszwComment); // Did we have any problems? if(bErrorWritingComment) { goto CleanUp; } } } } #endif // PWD_REHEADERCOMMENT // Determine the \ansicpgN value if(!pDocInfo) { fOutputEndGroup = TRUE; goto RAMError; } wCodePage = pDocInfo->wCpg; if (_dwFlags & SFF_UTF8 && !PutCtrlWord(CWF_VAL, i_utf, 8) || wCodePage != tomInvalidCpg && wCodePage != CP_ACP && !PutCtrlWord(CWF_VAL, i_ansicpg, wCodePage)) { goto CleanUp; } if(!printF(szDefaultFont)) goto CleanUp; LCID lcid; LANGID langid; if (_ped->GetDefaultLCID(&lcid) == NOERROR && lcid != tomInvalidLCID && (langid = LANGIDFROMLCID(lcid)) && !PutCtrlWord(CWF_VAL, i_deflang, langid)) { goto CleanUp; } if (_ped->GetDefaultLCIDFE(&lcid) == NOERROR && lcid != tomInvalidLCID && (langid = LANGIDFROMLCID(lcid)) && !PutCtrlWord(CWF_VAL, i_deflangfe, langid)) { goto CleanUp; } lDocDefaultTab = pDocInfo->dwDefaultTabStop; if(!lDocDefaultTab) lDocDefaultTab = lDefaultTab; if (lDocDefaultTab != 720 && !PutCtrlWord(CWF_VAL, i_deftab, lDocDefaultTab) || BuildTables(rtp._rpCF, rtp._rpPF, cch) || WriteFontTable() || WriteColorTable()) { goto CleanUp; } if(_nHeadingStyle) { if(!PutCtrlWord(CWF_GRP, i_stylesheet) || !printF(szNormalStyle)) goto CleanUp; for(i = 1; i < -_nHeadingStyle; i++) { if(!printF(szHeadingStyle, i, i)) goto CleanUp; } Puts(szEndGroupCRLF, sizeof(szEndGroupCRLF) - 1); // End font table group } _ped->GetViewKind(&i); _ped->GetViewScale(&j); if (WriteInfo() || _fRangeHasEOP && !PutCtrlWord(CWF_VAL, i_viewkind, i) || (_dwFlags & SFF_PERSISTVIEWSCALE) && j != 100 && !PutCtrlWord(CWF_VAL, i_viewscale, j)) { goto CleanUp; } // Write Unicode character byte count for use by entire document (since // we don't use \plain's and since \ucN behaves as a char formatting tag, // we're safe outputting it only once). if(!PutCtrlWord(CWF_VAL, i_uc, iUnicodeCChDefault)) goto CleanUp; #ifdef PWD_JUPITER // GuyBark: We now output \uc1 and \uc2 _UnicodeBytesPerChar = iUnicodeCChDefault; #endif // PWD_JUPITER while (cch > 0) { // Get next run of chars with same para formatting cchPF = rtp.GetCchLeftRunPF(); cchPF = min(cchPF, cch); AssertSz(cchPF, "CRTFW::WriteRtf: Empty para format run!"); if(WriteParaFormat(&rtp)) // Write paragraph formatting goto CleanUp; while (cchPF > 0) { // Get next run of characters with same char formatting cchCF = rtp.GetCchLeftRunCF(); cchCF = min(cchCF, cchPF); AssertSz(cchCF, "CRTFW::WriteRtf: Empty char format run!"); const CCharFormat * pCF = rtp.GetCF(); if (WriteCharFormat(pCF)) // Write char attributes goto CleanUp; INT nCodePage = (_dwFlags & SFF_UTF8) ? CP_UTF8 : GetCodePage(pCF->bCharSet); while (cchCF > 0) { cchBuffer = min(cachBufferMost, cchCF); cchBuffer = rtp._rpTX.GetText(cchBuffer, pchBuffer); pch = pchBuffer; cchT = cchBuffer; if(cchT > 0) { TCHAR * pchWork = pch; LONG cchWork = cchT; LONG cchTWork; CRchTxtPtr rtpObjectSearch(rtp); while (cchWork >0) { cchT = cchWork ; pch = pchWork; while (cchWork > 0 ) // search for objects { if(*pchWork++ == WCH_EMBEDDING) { break; // Will write out object } cchWork--; } cchTWork = cchT - cchWork; if (cchTWork) // write text before object { if(WriteText(cchTWork, pch, nCodePage, (pCF->bInternalEffects & CFEI_RUNISDBCS))) { goto CleanUp; } } rtpObjectSearch.Advance(cchTWork); if(cchWork > 0) // there is object { DWORD cp = rtpObjectSearch.GetCp(); COleObject *pobj; Assert(_ped->GetObjectMgr()); pobj = _ped->GetObjectMgr()->GetObjectFromCp(cp); if( !pobj ) { goto CleanUp; } // first, commit the object to make sure the pres. // caches, etc. are up-to-date. Don't worry // about errors here. pobj->SaveObject(); if(_fIncludeObjects) { WriteObject(cp, pobj); } else if(!Puts(szObjPosHolder,sizeof(szObjPosHolder) - 1)) { goto CleanUp; } rtpObjectSearch.Advance(1); cchWork--; } } } rtp.Advance(cchBuffer); cchCF -= cchBuffer; cchPF -= cchBuffer; cch -= cchBuffer; } } } CleanUp: // End RTF group Puts(szEndGroupCRLF,sizeof(szEndGroupCRLF) - 1); PutChar(0); FlushBuffer(); CleanUpNoEndGroup: FreePv(pchBuffer); if (_ecParseError != ecNoError) { TRACEERRSZSC("CRTFW::WriteRtf()", _ecParseError); Tracef(TRCSEVERR, "Writing error: %s", rgszParseError[_ecParseError]); if(!_pes->dwError) // Make error code OLE-like _pes->dwError = -abs(_ecParseError); _cchOut = 0; } return _cchOut; RAMError: ped->GetCallMgr()->SetOutOfMemory(); _ecParseError = ecNoMemory; if(fOutputEndGroup) goto CleanUp; goto CleanUpNoEndGroup; }
27.790543
223
0.621953
OhmPopy
2cab9db46a01d3705e701d9d92de0de0a4083806
516
cpp
C++
2019-12/examples/08_error_handling.cpp
st-louis-cpp-meetup/Presentations
2e3a31a6285aabf295a9bf494bf7470844196857
[ "CC-BY-4.0" ]
2
2019-06-20T13:22:30.000Z
2020-03-05T01:19:19.000Z
2019-12/examples/08_error_handling.cpp
st-louis-cpp-meetup/Presentations
2e3a31a6285aabf295a9bf494bf7470844196857
[ "CC-BY-4.0" ]
null
null
null
2019-12/examples/08_error_handling.cpp
st-louis-cpp-meetup/Presentations
2e3a31a6285aabf295a9bf494bf7470844196857
[ "CC-BY-4.0" ]
null
null
null
#include <iostream> #include "fmt/format.h" using namespace std; using namespace fmt; int main() { auto format_with_error = [] (const char* format_str, auto data) { try { cout << format(format_str, data); } catch (format_error& e) { cout << "Error: " << e.what() << "\n"; } }; format_with_error("{:d}", "not a number"); format_with_error("{:d}", 2.34); format_with_error("{:g}", 2); format_with_error("{1}", 1); // bad position format_with_error("{} {}", 1); // bad position return 0; }
19.846154
66
0.610465
st-louis-cpp-meetup
2cb4d31f86e1550dc8b87185c0ca1577ec094312
618
cpp
C++
src/gambit/ast/gambitTree.cpp
Vandise/Gambit-Archive
6db1921d99d76cd10f8f1bd25c46776d435d85a7
[ "MIT" ]
1
2019-02-20T19:19:23.000Z
2019-02-20T19:19:23.000Z
src/gambit/ast/gambitTree.cpp
Vandise/Gambit-Archive
6db1921d99d76cd10f8f1bd25c46776d435d85a7
[ "MIT" ]
null
null
null
src/gambit/ast/gambitTree.cpp
Vandise/Gambit-Archive
6db1921d99d76cd10f8f1bd25c46776d435d85a7
[ "MIT" ]
null
null
null
#include "gambit/ast/gambitTree.hpp" Gambit::Tree::Tree(std::vector<AST::Node*> nodes) { this->nodes = nodes; } Gambit::Tree::~Tree() { } void Gambit::Tree::pushNodes(std::vector<AST::Node*> nodes) { this->nodes = nodes; } void Gambit::Tree::pushBranch(AST::Tree *tree) { this->nodes.push_back(tree); } void Gambit::Tree::pushNode(AST::Node *node) { this->nodes.push_back(node); } int Gambit::Tree::treeSize() { return 0; } void Gambit::Tree::compile(Compiler::iCodeGenerator *cg) { cg->setState(CS_DEFAULT); for (auto &n : nodes) { if (n != nullptr) n->compile(cg); } cg->popState(); }
13.434783
54
0.644013
Vandise
2cb8b3f9a57585de9a7608ba997104ba2b0e131f
330
hpp
C++
src/core/reflang/serializer.class.hpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/core/reflang/serializer.class.hpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/core/reflang/serializer.class.hpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include "serializer.hpp" #include "types.hpp" namespace eXl { namespace reflang { namespace serializer { void SerializeClassHeader(std::ostream& o, const Class& c, String const& iDefineDirective); void SerializeClassSources(std::ostream& o, const Class& c); } } }
18.333333
97
0.687879
eXl-Nic
2cb912a3819f65b33e511d005e5cbbf61740a5fe
1,101
cpp
C++
IconImageProvider.cpp
orbitrc/laniakea-dock
08a03bd82ccab0f6b121eee680d652140f09798d
[ "MIT" ]
null
null
null
IconImageProvider.cpp
orbitrc/laniakea-dock
08a03bd82ccab0f6b121eee680d652140f09798d
[ "MIT" ]
null
null
null
IconImageProvider.cpp
orbitrc/laniakea-dock
08a03bd82ccab0f6b121eee680d652140f09798d
[ "MIT" ]
null
null
null
#include "IconImageProvider.h" #include "Dock.h" IconImageProvider::IconImageProvider(Dock *dock) : QQuickImageProvider(QQuickImageProvider::Pixmap) { this->_dock = dock; } QPixmap IconImageProvider::requestPixmap(const QString& id, QSize *size, const QSize& requestedSize) { int width = 48; int height = 48; if (size) { *size = QSize(width, height); } QPixmap pixmap( requestedSize.width() > 0 ? requestedSize.width() : width, requestedSize.height() > 0 ? requestedSize.height() : height ); // If id is item id. if (this->is_item_id(id)) { Item *item = this->_dock->item_by_id(id); if (item) { return this->_dock->item_default_icon(id); } else { pixmap.fill(QColor(255, 0, 0, 100)); return pixmap; } } // If id is window id. QPixmap p = this->_dock->window_icon(id.toInt()); return p; } bool IconImageProvider::is_item_id(const QString &val) const { if (val.length() == 36 && val[8] == '-') { return true; } return false; }
22.9375
100
0.590372
orbitrc
2cba79d85652d86711ff4fe096900235389f1549
1,862
cpp
C++
libs/pika/iterator_support/tests/unit/boost_iterator_categories.cpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
13
2022-01-17T12:01:48.000Z
2022-03-16T10:03:14.000Z
libs/pika/iterator_support/tests/unit/boost_iterator_categories.cpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
163
2022-01-17T17:36:45.000Z
2022-03-31T17:42:57.000Z
libs/pika/iterator_support/tests/unit/boost_iterator_categories.cpp
pika-org/pika
c80f542b2432a7f108fcfba31a5fe5073ad2b3e1
[ "BSL-1.0" ]
4
2022-01-19T08:44:22.000Z
2022-01-31T23:16:21.000Z
// Copyright (c) 2021 Hartmut Kaiser // // SPDX-License-Identifier: BSL-1.0 // 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 <pika/modules/iterator_support.hpp> #include <pika/testing.hpp> #include <iterator> #include <type_traits> int main() { // convert std tags to traversal tags static_assert(std::is_same<pika::traits::iterator_category_to_traversal_t< std::random_access_iterator_tag>, pika::random_access_traversal_tag>::value, "std::random_access_iterator_tag == pika::random_access_traversal_tag"); static_assert(std::is_same<pika::traits::iterator_category_to_traversal_t< std::bidirectional_iterator_tag>, pika::bidirectional_traversal_tag>::value, "std::bidirectional_iterator_tag == pika::bidirectional_traversal_tag"); static_assert(std::is_same<pika::traits::iterator_category_to_traversal_t< std::forward_iterator_tag>, pika::forward_traversal_tag>::value, "std::forward_iterator_tag == pika::forward_traversal_tag"); static_assert(std::is_same<pika::traits::iterator_category_to_traversal_t< std::output_iterator_tag>, pika::incrementable_traversal_tag>::value, "std::output_iterator_tag == pika::incrementable_traversal_tag"); static_assert(std::is_same<pika::traits::iterator_category_to_traversal_t< std::input_iterator_tag>, pika::single_pass_traversal_tag>::value, "std::input_iterator_tag == pika::single_pass_traversal_tag"); return pika::util::report_errors(); }
47.74359
80
0.653598
pika-org
2cbb466b41c6b10ececef7528da747a861506686
622
cxx
C++
executables/SeparatorGraph.cxx
rsgysel/ChordAlg
23b9c96008a0e0591f877450af97af6ab47d842d
[ "MIT" ]
3
2015-10-30T22:36:50.000Z
2015-12-04T05:49:22.000Z
executables/SeparatorGraph.cxx
rsgysel/ChordAlg
23b9c96008a0e0591f877450af97af6ab47d842d
[ "MIT" ]
null
null
null
executables/SeparatorGraph.cxx
rsgysel/ChordAlg
23b9c96008a0e0591f877450af97af6ab47d842d
[ "MIT" ]
null
null
null
/* * SeparatorGraph - computes the separator graph (minimal separators * and crossing relations) of a graph * * Warning: this computation requires exponential time/space * in general */ #include <iostream> #include "ChordAlgSrc/graph.h" #include "ChordAlgSrc/separator_graph.h" #include "chordalg_options.h" using namespace chordalg; int main(int argc, char** argv) { std::string filename; ChordAlgOptions(argc, argv, &filename); Graph* G = Graph::New(filename); SeparatorGraph* SG = SeparatorGraph::New(G); std::cout << SG->str(); delete SG; delete G; return EXIT_SUCCESS; }
23.037037
69
0.696141
rsgysel
2cbddd1580a9d94e36bda0112df8274f3ba198b1
9,315
inl
C++
src/bin/tools/ValueOperations/BinaryOps.inl
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
19
2020-10-21T10:05:17.000Z
2022-03-20T13:41:50.000Z
src/bin/tools/ValueOperations/BinaryOps.inl
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
4
2021-01-01T15:58:15.000Z
2021-09-19T03:31:09.000Z
src/bin/tools/ValueOperations/BinaryOps.inl
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
4
2020-10-05T09:01:50.000Z
2022-01-11T03:02:39.000Z
//////////////////////////////////////////////////////////////////////////////// // BinaryOp.inl //////////////////////////////////////////////////////////////////////////////// /*! @file // Implements componetwise binary ops on values. To be included by Value.hh */ // Author: Julian Panetta (jpanetta), julian.panetta@gmail.com // Company: New York University // Created: 10/28/2015 16:00:45 //////////////////////////////////////////////////////////////////////////////// struct AddOp : public BinaryOp { virtual Real operator()(Real a, Real b) const { return a + b; } }; struct SubOp : public BinaryOp { virtual Real operator()(Real a, Real b) const { return a - b; } }; struct MulOp : public BinaryOp { virtual Real operator()(Real a, Real b) const { return a * b; } }; struct DivOp : public BinaryOp { virtual Real operator()(Real a, Real b) const { return a / b; } }; // Default implementation--only used if actual implementation not found. // Last template parameter for SFINAE template<class T1, class T2, typename = void> struct BinaryOpImpl { using ResultType = T1; // ResultType can be arbitrary since actual results aren't generated. static std::unique_ptr<ResultType> apply(const BinaryOp &/* op */, T1, T2) { throw std::runtime_error(std::string("Illegal binary operation between ") + typeid(T1).name() + " and " + typeid(T2).name()); } }; // Field a, Field b: Pointwise suboperation template<class _VType1, class _VType2> struct BinaryOpImpl<FieldValue<_VType1>, FieldValue<_VType2>> { using SubImpl = BinaryOpImpl<_VType1, _VType2>; using ResultType = FieldValue<typename SubImpl::ResultType>; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const FieldValue<_VType1> &a, const FieldValue<_VType2> &b) { size_t nElems = a.size(); if ((a.domainType != b.domainType) || (nElems != b.size())) throw std::runtime_error("Binary operation field domain mismatch."); auto result = std::make_unique<ResultType>(a.domainType, nElems); for (size_t i = 0; i < nElems; ++i) (*result)[i] = *SubImpl::apply(op, a[i], b[i]); return result; } }; // Field a, Value Type b: Suboperation between value at each point of a and value b template<class _VType1, class _VType2> struct BinaryOpImpl<FieldValue<_VType1>, _VType2> { using SubImpl = BinaryOpImpl<_VType1, _VType2>; using ResultType = FieldValue<typename SubImpl::ResultType>; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const FieldValue<_VType1> &a, const _VType2 &b) { size_t nElems = a.size(); auto result = std::make_unique<ResultType>(a.domainType, nElems); for (size_t i = 0; i < nElems; ++i) (*result)[i] = *SubImpl::apply(op, a[i], b); return result; } }; // Value Type a, Field b: Suboperation between value a and value at each point of b template<class _VType1, class _VType2> struct BinaryOpImpl<_VType1, FieldValue<_VType2>> { using SubImpl = BinaryOpImpl<_VType1, _VType2>; using ResultType = FieldValue<typename SubImpl::ResultType>; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const _VType1 &a, const FieldValue<_VType2> &b) { size_t nElems = b.size(); auto result = std::make_unique<ResultType>(b.domainType, nElems); for (size_t i = 0; i < nElems; ++i) (*result)[i] = *SubImpl::apply(op, a, b[i]); return result; } }; // Interpolant a, Interpolant b: Suboperation between each nodal value template<class _PointValue1, class _PointValue2> struct BinaryOpImpl<InterpolantValue<_PointValue1>, InterpolantValue<_PointValue2>> { using SubImpl = BinaryOpImpl<_PointValue1, _PointValue2>; using ResultType = InterpolantValue<typename SubImpl::ResultType>; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const InterpolantValue<_PointValue1> &a, const InterpolantValue<_PointValue2> &b) { if (a.dim() != b.dim()) throw std::runtime_error("Binary operation interpolant size mismatch."); auto result = std::make_unique<ResultType>(a.simplexDimension()); for (size_t i = 0; i < a.dim(); ++i) result->value[i] = *SubImpl::apply(op, a.value[i], b.value[i]); return result; } }; // Interpolant a, Point Value b: Suboperation between each nodal value of a and value b // (Disabled for Field/Interpolant second operand to prevent ambiguity) template<class _PointValue1, class _PointValue2> struct BinaryOpImpl<InterpolantValue<_PointValue1>, _PointValue2, typename enable_if_point_value<_PointValue2>::type> { using SubImpl = BinaryOpImpl<_PointValue1, _PointValue2>; using ResultType = InterpolantValue<typename SubImpl::ResultType>; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const InterpolantValue<_PointValue1> &a, const _PointValue2 &b) { auto result = std::make_unique<ResultType>(a.simplexDimension()); for (size_t i = 0; i < a.dim(); ++i) result->value[i] = *SubImpl::apply(op, a.value[i], b); return result; } }; // Point Value a, Interpolant b: Suboperation between value a and each nodal value of b // (Disabled for Field/Interpolant first operand to prevent ambiguity) template<class _PointValue1, class _PointValue2> struct BinaryOpImpl<_PointValue1, InterpolantValue<_PointValue2>, typename enable_if_point_value<_PointValue1>::type> { using SubImpl = BinaryOpImpl<_PointValue1, _PointValue2>; using ResultType = InterpolantValue<typename SubImpl::ResultType>; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const _PointValue1 &a, const InterpolantValue<_PointValue2> &b) { auto result = std::make_unique<ResultType>(b.simplexDimension()); for (size_t i = 0; i < b.dim(); ++i) result->value[i] = *SubImpl::apply(op, a, b.value[i]); return result; } }; // Point Value a, Point Value b: Suboperation between value a and value b // (SFINAE to restrict to subclasses of PointValue) template<class _PointValue> struct BinaryOpImpl<_PointValue, _PointValue, typename enable_if_point_value<_PointValue>::type> { using ResultType = _PointValue; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const _PointValue &a, const _PointValue &b) { if (a.dim() != b.dim()) throw std::runtime_error("Binary operation dimension mismatch."); auto result = std::make_unique<ResultType>(a.N()); for (size_t i = 0; i < a.dim(); ++i) (*result)[i] = op(a[i], b[i]); return result; } }; // Scalar Value a, Point Value b template<class _PointValue> struct BinaryOpImpl<SValue, _PointValue, typename enable_if_point_value<_PointValue>::type> { using ResultType = _PointValue; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const SValue &a, const _PointValue &b) { auto result = std::make_unique<ResultType>(b.N()); for (size_t i = 0; i < b.dim(); ++i) (*result)[i] = op(a.value, b[i]); return result; } }; // Point Value a, Scalar Value b template<class _PointValue> struct BinaryOpImpl<_PointValue, SValue, typename enable_if_point_value<_PointValue>::type> { using ResultType = _PointValue; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const _PointValue &a, const SValue &b) { auto result = std::make_unique<ResultType>(a.N()); for (size_t i = 0; i < a.dim(); ++i) (*result)[i] = op(a[i], b.value); return result; } }; // Scalar Value a, Scalar Value b template<> struct BinaryOpImpl<SValue, SValue> { using ResultType = SValue; using URPtr = std::unique_ptr<ResultType>; static URPtr apply(const BinaryOp &op, const SValue &a, const SValue &b) { auto result = std::make_unique<ResultType>(); result->value = op(a.value, b.value); return result; } }; // Implement the inner stage of double-dispatch for component-wise binary // operations. The outer dispatch level is handled by vtable lookup, so we only // need to implement this inner lookup. // Do this with a sequence of automatically generated dynamic cast type checks. template<class T1> [[ noreturn ]] UVPtr dispatchCWiseBinaryOpImpl(const BinaryOp &/* op */, const T1 &, CVPtr b) { throw std::runtime_error("Unknown dynamic type: " + std::string(typeid(*b).name())); } template<class T1, class TCheck, class... Args> UVPtr dispatchCWiseBinaryOpImpl(const BinaryOp &op, const T1 &a, CVPtr b) { if (auto val = dynamic_cast<const TCheck *>(b)) return BinaryOpImpl<T1, TCheck>::apply(op, a, *val); return dispatchCWiseBinaryOpImpl<T1, Args...>(op, a, b); } template<class T1> UVPtr dispatchCWiseBinaryOp(const BinaryOp &op, const T1 &a, CVPtr b) { return dispatchCWiseBinaryOpImpl<T1, SValue, VValue, SMValue, ISValue, IVValue, ISMValue, FSValue, FVValue, FSMValue, FISValue, FIVValue, FISMValue>(op, a, b); }
49.285714
182
0.659367
pbedenbaugh
2cc2b8a15992b531b0ca709ba11af5175a4c00ee
708
cpp
C++
example12/temperatura.cpp
mateusesm/CPP-Activities
dc5b7063445e58c07738e7e27a8792b3966bee05
[ "MIT" ]
1
2021-11-26T00:26:37.000Z
2021-11-26T00:26:37.000Z
example12/temperatura.cpp
mateusesm/CPP-Activities
dc5b7063445e58c07738e7e27a8792b3966bee05
[ "MIT" ]
null
null
null
example12/temperatura.cpp
mateusesm/CPP-Activities
dc5b7063445e58c07738e7e27a8792b3966bee05
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int temperaturas[100]; int totalTemperatura = 0; int totalDias = 0; int temperatura = 0; while (temperatura != 5) { cout << "Informe a temperatura: (Digite 5 para sair)" << endl; cin >> temperatura; temperaturas[totalDias] = temperatura; totalDias++; totalTemperatura += temperatura; system("clear"); if (temperatura == 5) { cout << "Fim da execução." << endl; } } float media = totalTemperatura/totalDias; cout << "Média das temperaturas " << media << endl; for (int i = 0 ; i < totalDias ; i++) { if (temperaturas[i] > media) { cout << temperaturas[i] << " ficou acima da media. " << endl; } } }
22.83871
66
0.617232
mateusesm
2cc3d6757f4b131d538120e07c47c9946805d723
5,086
cpp
C++
src/lower.cpp
bsurmanski/wlc
e8e1b4965f5f8e1cf22e0b6cb16bac0e49a5c629
[ "MIT" ]
4
2015-02-13T01:14:23.000Z
2019-06-29T19:25:49.000Z
src/lower.cpp
bsurmanski/wlc
e8e1b4965f5f8e1cf22e0b6cb16bac0e49a5c629
[ "MIT" ]
null
null
null
src/lower.cpp
bsurmanski/wlc
e8e1b4965f5f8e1cf22e0b6cb16bac0e49a5c629
[ "MIT" ]
null
null
null
#include <string> #include "ast.hpp" #include "astType.hpp" #include "lower.hpp" #include "message.hpp" #include "token.hpp" // for getting operator precidence using namespace std; // // Code for AST traversal, validation, and lowering // if validate returns true, the AST should be in a consistant state, lowered, and ready for codegen; // else if validate return false, the AST is invalid, and may be left in an inconsistant state. // // // Lower // Lower::Lower() : ASTVisitor() { valid = true; } void Lower::visitFunctionDeclaration(FunctionDeclaration *decl) { if(decl->body) decl->body = decl->body->lower(); } void Lower::visitVariableDeclaration(VariableDeclaration *decl) { if(decl->value) { decl->value = decl->value->lower(); //XXX if statement is work around: // otherwise, on variable declaration of statically-sized arrays with tuple decl, wlc segfault // eg: "int[3] vals = [1, 2, 3]" if(decl->value && decl->value->getType() && !decl->value->getType()->isTuple()) decl->value = decl->value->coerceTo(decl->getType()); } } void Lower::visitUserTypeDeclaration(UserTypeDeclaration *decl) { //XXX lower constructor and destructor? for(int i = 0; i < decl->methods.size(); i++) { decl->methods[i] = dynamic_cast<FunctionDeclaration*>(decl->methods[i]->lower()); } for(int i = 0; i < decl->members.size(); i++) { decl->members[i] = decl->members[i]->lower(); } for(int i = 0; i < decl->staticMembers.size(); i++) { decl->staticMembers[i] = decl->staticMembers[i]->lower(); } decl->scope->accept(this); } void Lower::visitUnaryExpression(UnaryExpression *exp) { //TODO: insert coersion cast exp->lhs = exp->lhs->lower(); } void Lower::visitBinaryExpression(BinaryExpression *exp) { //TODO: insert coersion cast exp->lhs = exp->lhs->lower(); exp->rhs = exp->rhs->lower(); } void Lower::visitCallExpression(CallExpression *exp) { exp->function = exp->function->lower(); std::list<Expression*>::iterator it = exp->args.begin(); while(it != exp->args.end()) { if(!*it) emit_message(msg::FAILURE, "invalid or missing argument in call expression", exp->loc); else *it = (*it)->lower(); it++; } } void Lower::visitIndexExpression(IndexExpression *exp) { exp->lhs = exp->lhs->lower(); exp->index = exp->index->lower(); } void Lower::visitCastExpression(CastExpression *exp) { exp->expression = exp->expression->lower(); } void Lower::visitTupleExpression(TupleExpression *exp) { for(int i = 0; i < exp->members.size(); i++) { exp->members[i] = exp->members[i]->lower(); } } /* * Dot expression is either: * * a) a member lookup * b) static member * c) a scope specifier * d) a method lookup (which must be followed by a call) * e) a UFCS call * * (a), (b), and (c) are similar in function; so are (d) and (e) * * if LHS is a UserType variable (or pointer to), and RHS is a valid member, we have (a) * if RHS is a static member, we have (b) * else if RHS is a valid method name, we have (d) * else if LHS is a package (or some scope token), we have (b) * else if RHS is a valid function name in scope, and it's first parameter matches LHS's type, we have (e) */ void Lower::visitDotExpression(DotExpression *exp) { exp->lhs = exp->lhs->lower(); } void Lower::visitNewExpression(NewExpression *exp) { //XXX newexp->function is resolved after this. // therefore it will *always* be null if(exp->function) exp->function = exp->function->lower()->functionExpression(); std::list<Expression*>::iterator it = exp->args.begin(); while(it != exp->args.end()) { if(!*it) emit_message(msg::FAILURE, "invalid or missing argument in call expression", exp->loc); else *it = (*it)->lower(); it++; } } void Lower::visitCompoundStatement(CompoundStatement *stmt) { for(int i = 0; i < stmt->statements.size(); i++) { stmt->statements[i] = stmt->statements[i]->lower(); } } void Lower::visitBlockStatement(BlockStatement *stmt) { if(stmt->body) { stmt->body = stmt->body->lower(); } } void Lower::visitIfStatement(IfStatement *stmt) { stmt->condition = stmt->condition->lower(); if(stmt->elsebr) { stmt->elsebr = dynamic_cast<ElseStatement*>(stmt->elsebr->lower()); } } void Lower::visitLoopStatement(LoopStatement *stmt) { stmt->condition = stmt->condition->lower(); if(stmt->update) { stmt->update = stmt->update->lower(); } if(stmt->elsebr) { stmt->elsebr = dynamic_cast<ElseStatement*>(stmt->elsebr->lower()); } } void Lower::visitForStatement(ForStatement *stmt) { if(stmt->decl) { stmt->decl = stmt->decl->lower(); } } void Lower::visitSwitchStatement(SwitchStatement *stmt) { stmt->condition = stmt->condition->lower(); } void Lower::visitReturnStatement(ReturnStatement *stmt) { if(stmt->expression) { stmt->expression = stmt->expression->lower(); } }
29.062857
106
0.635273
bsurmanski
2cc638f9a33fedb5df9d00bdcde5a6177d01e954
229
cpp
C++
X5/x5_10.cpp
dlachausse/tcxxpl4e-exercises
90250e81e5afb9118a5064a58a5edc6692168160
[ "CC0-1.0" ]
null
null
null
X5/x5_10.cpp
dlachausse/tcxxpl4e-exercises
90250e81e5afb9118a5064a58a5edc6692168160
[ "CC0-1.0" ]
null
null
null
X5/x5_10.cpp
dlachausse/tcxxpl4e-exercises
90250e81e5afb9118a5064a58a5edc6692168160
[ "CC0-1.0" ]
null
null
null
#include <iostream> #include <fstream> int main() { const char* filename = "integers.txt"; std::ifstream in(filename); int i; while(in >> i) { std::cout << i << '\n'; } in.close(); }
14.3125
42
0.49345
dlachausse
2cc6ad9059d7881305d0c85477b83cd67e2366d2
240
hpp
C++
pythran/pythonic/include/operator_/__pos__.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/operator_/__pos__.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/operator_/__pos__.hpp
artas360/pythran
66dad52d52be71693043e9a7d7578cfb9cb3d1da
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_OPERATOR_POS__HPP #define PYTHONIC_INCLUDE_OPERATOR_POS__HPP #include "pythonic/operator_/pos.hpp" namespace pythonic { namespace operator_ { FPROXY_DECL(pythonic::operator_, __pos__, pos); } } #endif
15
51
0.783333
artas360
2cc6e3a765fa9bce3e03ee43b9c1024f2e2674a7
1,786
hpp
C++
src/protocol/messages/FeeFilter.hpp
tkeycoin/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
3
2020-01-24T04:45:14.000Z
2020-06-30T13:49:58.000Z
src/protocol/messages/FeeFilter.hpp
Dikii27/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
1
2020-06-18T15:51:36.000Z
2020-06-20T17:25:45.000Z
src/protocol/messages/FeeFilter.hpp
Dikii27/tkeycoin2
7fb88605b8874e16c01df1ee2d47f45094d5cf57
[ "MIT" ]
1
2020-10-20T06:50:13.000Z
2020-10-20T06:50:13.000Z
// Copyright (c) 2017-2020 TKEY DMCC LLC & Tkeycoin Dao. All rights reserved. // Website: www.tkeycoin.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. // FeeFilter.hpp #pragma once #include <protocol/types/Message.hpp> namespace protocol::message { /// The feefilter message is a request to the receiving peer to not relay /// any transaction inv messages to the sending peer where the fee rate for /// the transaction is below the fee rate specified in the feefilter message. class FeeFilter final : public Message { DECLARE_MESSAGE(FeeFilter); public: FeeFilter() = default; // Default-constructor explicit FeeFilter(uint64_t feeRate) // Default-constructor : _feeRate(feeRate) { } private: uint64_t _feeRate = 0; }; }
34.346154
81
0.7514
tkeycoin
2cc7ba1a882b6540531dc2d9ef504c58d20703fc
936
cpp
C++
[BOJ 1074] Z.cpp
Yunseong-Jeong/Algorithm
63e177f70dd457bd2c255e799d60415e8198cec7
[ "MIT" ]
null
null
null
[BOJ 1074] Z.cpp
Yunseong-Jeong/Algorithm
63e177f70dd457bd2c255e799d60415e8198cec7
[ "MIT" ]
null
null
null
[BOJ 1074] Z.cpp
Yunseong-Jeong/Algorithm
63e177f70dd457bd2c255e799d60415e8198cec7
[ "MIT" ]
null
null
null
#include <iostream> #pragma warning(disable:4996) using namespace std; long long N, r, c; long long Z(long long pos_x, long long pos_y, long long size) { if (size != 2) { if (pos_x >= size / 2 && pos_y >= size / 2) return (size * size / 4 * 3) + Z(pos_x - size / 2, pos_y - size / 2, size / 2); else if (pos_x >= size / 2) return (size * size / 2) + Z(pos_x - size / 2, pos_y, size / 2); else if (pos_y >= size / 2) return (size * size / 4) + Z(pos_x, pos_y - size / 2, size / 2); else return Z(pos_x, pos_y, size / 2); } else { long long cnt = 0; for (int i = 0; i < 2 ; i++) { for (int j = 0; j < 2; j++) { cnt++; if (i == pos_x && j == pos_y) return cnt; } } } } int main() { scanf("%lld %lld %lld", &N, &r, &c); long long size = 1; for (int i = 0; i < N; i++) { size *= 2; } printf("%lld\n", Z(r, c, size)-1); return 0; }
21.272727
83
0.488248
Yunseong-Jeong
2cc9b06a1f84ae61fb44bff9002f83f66dd7f21c
4,010
cpp
C++
inference_backend/pre_proc/opencv_utils/opencv_utils.cpp
fkhoshne/gst-video-analytics
c76892b40dd5df1caa9bab6a74bdf1fba928e14f
[ "MIT" ]
null
null
null
inference_backend/pre_proc/opencv_utils/opencv_utils.cpp
fkhoshne/gst-video-analytics
c76892b40dd5df1caa9bab6a74bdf1fba928e14f
[ "MIT" ]
null
null
null
inference_backend/pre_proc/opencv_utils/opencv_utils.cpp
fkhoshne/gst-video-analytics
c76892b40dd5df1caa9bab6a74bdf1fba928e14f
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright (C) 2018-2019 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #include "opencv_utils.h" #include "inference_backend/logger.h" #include <opencv2/opencv.hpp> namespace InferenceBackend { namespace Utils { void ImageToMat(const Image &src, cv::Mat &dst) { // TODO: add I420 support switch (src.format) { case FOURCC_BGRX: case FOURCC_BGRA: dst = cv::Mat(src.height, src.width, CV_8UC4, src.planes[0], src.stride[0]); break; case FOURCC_BGR: dst = cv::Mat(src.height, src.width, CV_8UC3, src.planes[0], src.stride[0]); break; case FOURCC_BGRP: { cv::Mat channelB = cv::Mat(src.height, src.width, CV_8UC1, src.planes[0], src.stride[0]); cv::Mat channelG = cv::Mat(src.height, src.width, CV_8UC1, src.planes[1], src.stride[1]); cv::Mat channelR = cv::Mat(src.height, src.width, CV_8UC1, src.planes[2], src.stride[2]); std::vector<cv::Mat> channels{channelB, channelG, channelR}; cv::merge(channels, dst); break; } case FOURCC_RGBP: { cv::Mat channelR = cv::Mat(src.height, src.width, CV_8UC1, src.planes[0], src.stride[0]); cv::Mat channelG = cv::Mat(src.height, src.width, CV_8UC1, src.planes[1], src.stride[1]); cv::Mat channelB = cv::Mat(src.height, src.width, CV_8UC1, src.planes[2], src.stride[2]); std::vector<cv::Mat> channels{channelB, channelG, channelR}; cv::merge(channels, dst); break; } default: throw std::runtime_error("ImageToMat: Unsupported format"); } } void NV12ImageToMats(const Image &src, cv::Mat &y, cv::Mat &uv) { if (src.format != FOURCC_NV12) { throw std::runtime_error("NV12ImageToMats: Unsupported format"); } y = cv::Mat(src.height, src.width, CV_8UC1, src.planes[0], src.stride[0]); uv = cv::Mat(src.height / 2, src.width / 2, CV_8UC2, src.planes[1], src.stride[1]); } template <typename T> void MatToMultiPlaneImageTyped(const cv::Mat &src, Image &dst) { ITT_TASK(__FUNCTION__); const size_t width = dst.width; const size_t height = dst.height; const size_t channels = 3; T *dst_data = (T *)dst.planes[0]; if (src.channels() == 4) { ITT_TASK("4-channel MatToMultiPlaneImageTyped"); for (size_t c = 0; c < channels; c++) { for (size_t h = 0; h < height; h++) { for (size_t w = 0; w < width; w++) { dst_data[c * width * height + h * width + w] = src.at<cv::Vec4b>(h, w)[c]; } } } } else if (src.channels() == 3) { ITT_TASK("3-channel MatToMultiPlaneImageTyped"); for (size_t c = 0; c < channels; c++) { for (size_t h = 0; h < height; h++) { for (size_t w = 0; w < width; w++) { dst_data[c * width * height + h * width + w] = src.at<cv::Vec3b>(h, w)[c]; } } } } else { throw std::runtime_error("Image with unsupported channels number"); } } void MatToMultiPlaneImage(const cv::Mat &src, Image &dst) { switch (dst.format) { case FOURCC_RGBP: MatToMultiPlaneImageTyped<uint8_t>(src, dst); break; case FOURCC_RGBP_F32: MatToMultiPlaneImageTyped<float>(src, dst); break; default: throw std::runtime_error("BGRToImage: Can not convert to desired format. Not implemented"); } } cv::Mat ResizeMat(const cv::Mat &orig_image, const size_t height, const size_t width) { cv::Mat resized_image(orig_image); if (width != (size_t)orig_image.size().width || height != (size_t)orig_image.size().height) { ITT_TASK("cv::resize"); cv::resize(orig_image, resized_image, cv::Size(width, height)); } return resized_image; } } // namespace Utils } // namespace InferenceBackend
36.454545
99
0.574564
fkhoshne
2ccde272fcaee4e4098210a0be0d849a7a25d37b
4,897
cpp
C++
src/BinaryRep/test/BinaryFormatTest.cpp
Andrei-Masilevich/ThorsSerializer
4a532e818c797ae071d689017ec4e4ab4cc0c00c
[ "MIT" ]
null
null
null
src/BinaryRep/test/BinaryFormatTest.cpp
Andrei-Masilevich/ThorsSerializer
4a532e818c797ae071d689017ec4e4ab4cc0c00c
[ "MIT" ]
null
null
null
src/BinaryRep/test/BinaryFormatTest.cpp
Andrei-Masilevich/ThorsSerializer
4a532e818c797ae071d689017ec4e4ab4cc0c00c
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "BinaryFormat.h" #include "IntBinRep.h" using namespace ThorsAnvil::BinaryRep; template<typename T> void checkValue(T const& value, std::string const& expected); TEST(BinaryFormatTest, Construct128) { BinForm128 value = 0xFF; // 16 byte EXPECT_EQ(0xFF, static_cast<unsigned long long int>(value)); } TEST(BinaryFormatTest, Equality128) { BinForm128 value = 0xFF; EXPECT_TRUE(value == 0xFF); EXPECT_TRUE(value != 0xFE); } TEST(BinaryFormatTest, CheckByteOrderOf128) { BinForm128 value = 0x123456789ABCDEF0LL; value <<= 64; value |= 0x9A12BC34DE56F078; std::string expected("\x12\x34\x56\x78\x9A\xBC\xDE\xF0" "\x9A\x12\xBC\x34\xDE\x56\xF0\x78", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, ShiftLeftMoreThan64) { BinForm128 value = 0x123456789ABCDEF0LL; value <<= 68; std::string expected("\x23\x45\x67\x89\xAB\xCD\xEF\x00" "\x00\x00\x00\x00\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, ShiftLeft64) { BinForm128 value = 0x123456789ABCDEF0LL; value <<= 64; std::string expected("\x12\x34\x56\x78\x9A\xBC\xDE\xF0" "\x00\x00\x00\x00\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, ShiftLeftLess64) { BinForm128 value = 0x123456789ABCDEF0LL; value <<= 32; std::string expected("\x00\x00\x00\x00\x12\x34\x56\x78" "\x9A\xBC\xDE\xF0\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, ShiftRightMoreThan64) { BinForm128 value = 0x123456789ABCDEF0LL; value <<= 64; value >>= 68; std::string expected("\x00\x00\x00\x00\x00\x00\x00\x00" "\x01\x23\x45\x67\x89\xAB\xCD\xEF", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, ShiftRight64) { BinForm128 value = 0x123456789ABCDEF0LL; value <<= 64; value >>= 64; std::string expected("\x00\x00\x00\x00\x00\x00\x00\x00" "\x12\x34\x56\x78\x9A\xBC\xDE\xF0", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, ShiftRightLess64) { BinForm128 value = 0x123456789ABCDEF0LL; value <<= 64; value >>= 32; std::string expected("\x00\x00\x00\x00\x12\x34\x56\x78" "\x9A\xBC\xDE\xF0\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, BinaryOrLow) { BinForm128 value1 = 0x3C3C3C3C3C3C3C3CLL; BinForm128 value2 = 0xF00F3CC300FFAA55LL; BinForm128 value = value1 | value2; std::string expected("\x00\x00\x00\x00\x00\x00\x00\x00" "\xFC\x3F\x3C\xFF\x3C\xFF\xBE\x7D", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, BinaryOrHigh) { BinForm128 value1 = 0x3C3C3C3C3C3C3C3CLL; BinForm128 value2 = 0xF00F3CC300FFAA55LL; value1 <<= 64; value2 <<= 64; BinForm128 value = value1 | value2; std::string expected("\xFC\x3F\x3C\xFF\x3C\xFF\xBE\x7D" "\x00\x00\x00\x00\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, BinaryOrStraddle) { BinForm128 value1 = 0x3C3C3C3C3C3C3C3CLL; BinForm128 value2 = 0xF00F3CC300FFAA55LL; value1 <<= 32; value2 <<= 32; BinForm128 value = value1 | value2; std::string expected("\x00\x00\x00\x00\xFC\x3F\x3C\xFF" "\x3C\xFF\xBE\x7D\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, BinaryAndLo) { BinForm128 value1 = 0x3C3C3C3C3C3C3C3CLL; BinForm128 value2 = 0xF00F3CC300FFAA55LL; BinForm128 value = value1 & value2; std::string expected("\x00\x00\x00\x00\x00\x00\x00\x00" "\x30\x0C\x3C\x00\x00\x3C\x28\x14", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, BinaryAndHigh) { BinForm128 value1 = 0x3C3C3C3C3C3C3C3CLL; BinForm128 value2 = 0xF00F3CC300FFAA55LL; value1 <<= 64; value2 <<= 64; BinForm128 value = value1 & value2; std::string expected("\x30\x0C\x3C\x00\x00\x3C\x28\x14" "\x00\x00\x00\x00\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, BinaryAndStraddle) { BinForm128 value1 = 0x3C3C3C3C3C3C3C3CLL; BinForm128 value2 = 0xF00F3CC300FFAA55LL; value1 <<= 32; value2 <<= 32; BinForm128 value = value1 & value2; std::string expected("\x00\x00\x00\x00\x30\x0C\x3C\x00" "\x00\x3C\x28\x14\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); } TEST(BinaryFormatTest, BinForm128HighCheck) { BinForm128 value = binForm128High(0x12345678FFFFFFFFLL); std::string expected("\x12\x34\x56\x78\xFF\xFF\xFF\xFF" "\x00\x00\x00\x00\x00\x00\x00\x00", 16); checkValue(host2Net(value), expected); }
29.323353
109
0.664693
Andrei-Masilevich
2cd18655b2d0b5fb13d53fba707913b9ec7f0694
4,409
cpp
C++
libs/SFGUI-0.2.3/examples/ScrolledWindowViewport.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
1
2016-04-04T09:30:38.000Z
2016-04-04T09:30:38.000Z
libs/SFGUI-0.2.3/examples/ScrolledWindowViewport.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
libs/SFGUI-0.2.3/examples/ScrolledWindowViewport.cpp
Mertank/ToneArm
40c62b0de89ac506bea6674e43578bf4e2631f93
[ "Zlib", "BSD-2-Clause" ]
null
null
null
#include <cstdlib> #include <SFML/Graphics.hpp> // Always include the necessary header files. // Including SFGUI/SFGUI.hpp includes everything // you can possibly need automatically. #include <SFGUI/SFGUI.hpp> class ScrolledWindowViewportExample { public: // Our button click handler. void OnButtonClick(); void Run(); private: // Create an SFGUI. This is required before doing anything with SFGUI. sfg::SFGUI m_sfgui; // Create the ScrolledWindow box pointer here to reach it from OnButtonClick(). sfg::Box::Ptr m_scrolled_window_box; }; void ScrolledWindowViewportExample::OnButtonClick() { m_scrolled_window_box->Pack( sfg::Button::Create( "A Button" ) ); } void ScrolledWindowViewportExample::Run() { // Create the main SFML window sf::RenderWindow app_window( sf::VideoMode( 800, 600 ), "SFGUI ScrolledWindow and Viewport Example", sf::Style::Titlebar | sf::Style::Close ); // We have to do this because we don't use SFML to draw. app_window.resetGLStates(); // Create our main SFGUI window auto window = sfg::Window::Create(); window->SetTitle( "Title" ); // Create a box with 10 pixel spacing. auto box = sfg::Box::Create( sfg::Box::Orientation::VERTICAL, 10.f ); // Create a button and connect the click signal. auto button = sfg::Button::Create( "Add a button" ); button->GetSignal( sfg::Widget::OnLeftClick ).Connect( std::bind( &ScrolledWindowViewportExample::OnButtonClick, this ) ); // Create a box for our ScrolledWindow. ScrolledWindows are bins // and can only contain 1 child widget. m_scrolled_window_box = sfg::Box::Create( sfg::Box::Orientation::VERTICAL ); // Create the ScrolledWindow. auto scrolledwindow = sfg::ScrolledWindow::Create(); // Set the ScrolledWindow to always show the horizontal scrollbar // and only show the vertical scrollbar when needed. scrolledwindow->SetScrollbarPolicy( sfg::ScrolledWindow::HORIZONTAL_ALWAYS | sfg::ScrolledWindow::VERTICAL_AUTOMATIC ); // Add the ScrolledWindow box to the ScrolledWindow // and create a new viewport automatically. scrolledwindow->AddWithViewport( m_scrolled_window_box ); // Always remember to set the minimum size of a ScrolledWindow. scrolledwindow->SetRequisition( sf::Vector2f( 500.f, 100.f ) ); // Create a viewport. auto viewport = sfg::Viewport::Create(); // Always remember to set the minimum size of a Viewport. viewport->SetRequisition( sf::Vector2f( 500.f, 200.f ) ); // Set the vertical adjustment values of the Viewport. viewport->GetVerticalAdjustment()->SetLower( 0.f ); viewport->GetVerticalAdjustment()->SetUpper( 100000000.f ); // Create a box for our Viewport. Viewports are bins // as well and can only contain 1 child widget. auto viewport_box = sfg::Box::Create( sfg::Box::Orientation::VERTICAL ); sf::err() << "Generating random strings, please be patient..." << std::endl; // Create some random text. for( int i = 0; i < 200; i++ ) { std::string str; for( int j = 0; j < 20; j++ ) { str += static_cast<char>( 65 + rand() % 26 ); } // Add the text to the Viewport box. viewport_box->Pack( sfg::Label::Create( str.c_str() ) ); } // Add the Viewport box to the viewport. viewport->Add( viewport_box ); // Add everything to our box. box->Pack( button, false, true ); box->Pack( scrolledwindow, false, true ); box->Pack( viewport, true, true ); // Add the box to the window. window->Add( box ); sf::Clock clock; // Start the game loop while ( app_window.isOpen() ) { // Process events sf::Event event; while ( app_window.pollEvent( event ) ) { // Handle events window->HandleEvent( event ); // Close window : exit if ( event.type == sf::Event::Closed ) { app_window.close(); } } // Update the GUI every 1ms if( clock.getElapsedTime().asMicroseconds() >= 1000 ) { auto delta = static_cast<float>( clock.getElapsedTime().asMicroseconds() ) / 1000000.f; // Update() takes the elapsed time in seconds. window->Update( delta ); // Add a nice automatic scrolling effect to our viewport ;) viewport->GetVerticalAdjustment()->SetValue( viewport->GetVerticalAdjustment()->GetValue() + delta * 10.f ); clock.restart(); } // Clear screen app_window.clear(); // Draw the GUI m_sfgui.Display( app_window ); // Update the window app_window.display(); } } int main() { ScrolledWindowViewportExample example; example.Run(); return 0; }
29.198675
143
0.700839
Mertank
2cd258572dc9881cac9b0c71ef3193ce07415516
9,639
hpp
C++
include/lmrtfy/thread_pool.hpp
Ahajha/LMRTFY
36991b20c823bcb51cc962bed225687b374b4aba
[ "MIT" ]
5
2022-01-08T10:23:04.000Z
2022-02-28T07:15:03.000Z
include/lmrtfy/thread_pool.hpp
Ahajha/LMRTFY
36991b20c823bcb51cc962bed225687b374b4aba
[ "MIT" ]
3
2022-01-08T16:50:54.000Z
2022-02-09T05:01:50.000Z
include/lmrtfy/thread_pool.hpp
Ahajha/LMRTFY
36991b20c823bcb51cc962bed225687b374b4aba
[ "MIT" ]
1
2022-01-08T14:51:52.000Z
2022-01-08T14:51:52.000Z
#pragma once #include <type_traits> #include <condition_variable> #include <future> #include <vector> #include <thread> #include <queue> #include <mutex> #include <functional> #include <utility> #include "function2/function2.hpp" #ifdef __cpp_concepts #include <concepts> #endif namespace lmrtfy { enum class _pool_state : uint8_t { running, stopping, stopped }; /* Base class for thread pool implementations. Not intended to be used directly, though can't do anything useful anyways. Omits push() and the task queue, which need to be specialized by the template subclass. */ template<class task_queue_t> class thread_pool_base { public: explicit thread_pool_base() : n_idle_(0), state(_pool_state::running) {} /*! Waits for all tasks in the queue to be finished, then stops. */ ~thread_pool_base(); /*! Returns the number of threads in the pool. */ [[nodiscard]] std::size_t size() const { return threads.size(); } /*! Returns the number of currently idle threads. */ [[nodiscard]] std::size_t n_idle() const { return n_idle_; } // Various members are either not copyable or movable, thus the pool is neither. thread_pool_base(const thread_pool_base&) = delete; thread_pool_base(thread_pool_base&&) = delete; thread_pool_base& operator=(const thread_pool_base&) = delete; thread_pool_base& operator=(thread_pool_base&&) = delete; protected: std::vector<std::thread> threads; // Number of currently idle threads. Required to ensure the threads are "all-or-nothing", // that is, threads will only stop if they know all other threads will stop. std::size_t n_idle_; // Initially set to running, set to stopping when the destructor is called, then set to // stopped once all threads are idle and there is no more work to be done. _pool_state state; // Used for waking up threads when new tasks are available or the pool is stopping. // Note that according to // https://en.cppreference.com/w/cpp/thread/condition_variable/notify_one // , signals shouldn't need to be guarded by holding a mutex. std::condition_variable signal; // Used for atomic operations on the task queue. Any modifications done to the // thread pool are done while holding this mutex. std::mutex mut; // Queue of tasks to be completed. task_queue_t tasks; // Adds a task to the task queue, notifies one thread, // and returns the future from the task. template<class Ret, class... Args> std::future<Ret> add_task(std::packaged_task<Ret(Args...)>&& task); friend class _worker_thread; }; /*! Thread pool class. Thread_id_t is used to determine the signature of callable objects it accepts. More information about this parameter in push(). */ template<class thread_id_t = void> #ifdef __cpp_concepts // In C++17, the thread ID is "duck-typed" to probably only compile if it is an integral, // but this is not enforced. In C++20, this is enforced, and will likely give more // helpful error messages. requires (std::is_void_v<thread_id_t> || std::integral<thread_id_t>) #endif class thread_pool : public thread_pool_base<std::queue<fu2::unique_function<void(thread_id_t)>>> { public: /*! Creates a thread pool with a given number of threads. Default attempts to use all threads on the given hardware, based on the implementation of std::thread::hardware_concurrency(). */ explicit thread_pool(std::size_t n_threads = std::thread::hardware_concurrency()); /*! Pushes a function and its arguments to the task queue. Returns the result as a future. f should take a thread_id_t as its first parameter, the thread ID is given through this. Thread IDs are numbered in [0, size()). Expects that thread_id_t's maximum value is at least (size() - 1), so that the thread IDs can be passed correctly, behaviour is undefined if not. */ template<class F, class... Args> #ifdef __cpp_concepts // Strictly speaking, this shouldn't cause any compile errors, as std::invoke_result // will produce an error if this does. However, this is here as a nice-to-have, as it // should produce better error messages in C++20. requires std::invocable<F,thread_id_t,Args...> #endif std::future<std::invoke_result_t<F,thread_id_t,Args...>> push(F&& f, Args&&... args); }; /*! Thread pool class. Thread_id_t is used to determine the signature of callable objects it accepts. More information about this parameter in push(). */ template<> class thread_pool<void> : public thread_pool_base<std::queue<fu2::unique_function<void()>>> { public: /*! Creates a thread pool with a given number of threads. Default attempts to use all threads on the given hardware, based on the implementation of std::thread::hardware_concurrency(). */ inline explicit thread_pool(std::size_t n_threads = std::thread::hardware_concurrency()); /*! Pushes a function and its arguments to the task queue. Returns the result as a future. */ template<class F, class... Args> #ifdef __cpp_concepts // Strictly speaking, this shouldn't cause any compile errors, as std::invoke_result // will produce an error if this does. However, this is here as a nice-to-have, as it // should produce better error messages in C++20. requires std::invocable<F,Args...> #endif inline std::future<std::invoke_result_t<F,Args...>> push(F&& f, Args&&... args); }; struct _worker_thread { template<class task_queue_t, class... Args> void operator()(thread_pool_base<task_queue_t>* pool, Args... args) const { std::unique_lock mutex_lock(pool->mut); while (true) { // Try to get a task if (pool->tasks.empty()) { // No tasks, this thread is now idle. ++pool->n_idle_; // If this was the last worker running and the pool is stopping, wake // up all other threads, who are waiting for the others to finish. if (pool->n_idle_ == pool->size() && pool->state == _pool_state::stopping) { pool->state = _pool_state::stopped; // Minor optimization, unlock now instead of having it release // automatically. This also allows the notification to not require // the lock. We also must return now, since it can't be woken up later. mutex_lock.unlock(); pool->signal.notify_all(); return; } // Wait for a signal (wait unlocks and relocks the mutex). A signal is // sent when a new task comes in, the last worker finishes the last task, // or the threads are told to stop. pool->signal.wait(mutex_lock); if (pool->state == _pool_state::stopped) return; --pool->n_idle_; } else { // Grab the next task and run it. auto task = std::move(pool->tasks.front()); pool->tasks.pop(); mutex_lock.unlock(); task(args...); mutex_lock.lock(); } } } }; template<class thread_id_t> #ifdef __cpp_concepts requires (std::is_void_v<thread_id_t> || std::integral<thread_id_t>) #endif thread_pool<thread_id_t>::thread_pool(std::size_t n_threads) { this->threads.reserve(n_threads); for (std::size_t thread_id = 0; thread_id < n_threads; ++thread_id) { this->threads.emplace_back(_worker_thread{}, this, static_cast<thread_id_t>(thread_id)); } } thread_pool<void>::thread_pool(std::size_t n_threads) { this->threads.reserve(n_threads); for (std::size_t thread_id = 0; thread_id < n_threads; ++thread_id) { this->threads.emplace_back(_worker_thread{}, this); } } template<class task_queue_t> thread_pool_base<task_queue_t>::~thread_pool_base() { // Give the waiting threads a command to finish. { std::lock_guard lock(this->mut); this->state = (this->n_idle_ == this->size() && this->tasks.empty()) ? _pool_state::stopped : _pool_state::stopping; } // Signal everyone in case any have gone to sleep. this->signal.notify_all(); // Wait for the computing threads to finish. for (auto& thr : this->threads) { if (thr.joinable()) thr.join(); } } template<class task_queue_t> template<class Ret, class... Args> std::future<Ret> thread_pool_base<task_queue_t>::add_task (std::packaged_task<Ret(Args...)>&& task) { auto fut = task.get_future(); { std::lock_guard lock(this->mut); this->tasks.emplace(std::move(task)); } // Notify one waiting thread so it can wake up and take this new task. this->signal.notify_one(); return fut; } template<class thread_id_t> #ifdef __cpp_concepts requires (std::is_void_v<thread_id_t> || std::integral<thread_id_t>) #endif template<class F, class... Args> #ifdef __cpp_concepts requires std::invocable<F,thread_id_t,Args...> #endif std::future<std::invoke_result_t<F,thread_id_t,Args...>> thread_pool<thread_id_t>::push(F&& f, Args&&... args) { using package_t = std::packaged_task< std::invoke_result_t<F,thread_id_t,Args...>(thread_id_t) >; if constexpr (sizeof...(Args) != 0) { return this->add_task(package_t { // This could be done with a lambda, but we // would need to cover void and non-void cases. std::bind(std::forward<F>(f), std::placeholders::_1, std::forward<Args>(args)...) }); } else { return this->add_task(package_t{std::forward<F>(f)}); } } template<class F, class... Args> #ifdef __cpp_concepts requires std::invocable<F,Args...> #endif std::future<std::invoke_result_t<F,Args...>> thread_pool<void>::push(F&& f, Args&&... args) { using package_t = std::packaged_task<std::invoke_result_t<F,Args...>()>; if constexpr (sizeof...(Args) != 0) { return this->add_task(package_t { // This could be done with a lambda, but we // would need to cover void and non-void cases. std::bind(std::forward<F>(f), std::forward<Args>(args)...) }); } else { return this->add_task(package_t{std::forward<F>(f)}); } } }
29.297872
96
0.70692
Ahajha
2cd67fcdd57a21cc909105f59ae6d56e6c3c2299
693
cpp
C++
src/render/sceneGraph.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
2
2019-12-24T04:00:36.000Z
2022-01-26T02:44:04.000Z
src/render/sceneGraph.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
null
null
null
src/render/sceneGraph.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
2
2020-09-26T04:19:40.000Z
2021-02-19T07:24:57.000Z
#include"renderer/sceneGraph.h" #include "utils/loadshader.h" SceneGraph::SceneGraph() { } SceneGraph::~SceneGraph() { } void SceneGraph::loadAssets(vks::VulkanDevice *vulkanDevice, VkQueue queue, std::shared_ptr<VertexDescriptions> vdo) { models.skybox.loadFromFile(modelPath + "models/cube.obj", vdo->vertexLayout, 1.0f, vulkanDevice, queue); for (auto file : filenames) { vks::Model model; model.loadFromFile(modelPath + "models/" + file, vdo->vertexLayout, 0.25, vulkanDevice, queue); models.nodes[file] = model; } } void SceneGraph::createScene(vks::VulkanDevice *vulkanDevice, VkQueue queue, std::shared_ptr<VertexDescriptions> vdo) { loadAssets(vulkanDevice, queue, vdo); }
28.875
117
0.748918
liuhongyi0101
2cd6bb68b38498003ba18ed08dc1cf70c3f6b146
783
cpp
C++
libs/PPU/Texture.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
3
2019-10-27T22:32:44.000Z
2020-05-21T04:00:46.000Z
libs/PPU/Texture.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
libs/PPU/Texture.cpp
max-delta/retrofit-public
5447fd6399fd74ffbb75494c103940751000db12
[ "X11" ]
null
null
null
#include "stdafx.h" #include "Texture.h" #include "Timing/FrameClock.h" namespace RF::gfx { /////////////////////////////////////////////////////////////////////////////// Texture::Texture() : mLastUsedInFrame( time::CommonClock::time_point() ) { // } Texture::~Texture() { RF_ASSERT( mDeviceRepresentation == kInvalidDeviceTextureID ); } DeviceTextureID Texture::GetDeviceRepresentation() const { UpdateFrameUsage(); return mDeviceRepresentation; } uint32_t Texture::DebugGetWidth() const { return mWidthPostLoad; } uint32_t Texture::DebugGetHeight() const { return mHeightPostLoad; } void Texture::UpdateFrameUsage() const { mLastUsedInFrame = time::FrameClock::now(); } /////////////////////////////////////////////////////////////////////////////// }
14.5
79
0.581098
max-delta
2cd8c310894237bb51cbc3d82e7807e14b8837ec
16,470
hpp
C++
include/eepp/ui/uicodeeditor.hpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
include/eepp/ui/uicodeeditor.hpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
null
null
null
include/eepp/ui/uicodeeditor.hpp
SpartanJ/eepp
21e8ae53af9bc5eb3fd1043376f2b3a4b3ff5fac
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#ifndef EE_UI_UICODEEDIT_HPP #define EE_UI_UICODEEDIT_HPP #include <eepp/ui/doc/syntaxcolorscheme.hpp> #include <eepp/ui/doc/syntaxhighlighter.hpp> #include <eepp/ui/doc/textdocument.hpp> #include <eepp/ui/keyboardshortcut.hpp> #include <eepp/ui/uifontstyleconfig.hpp> #include <eepp/ui/uiwidget.hpp> using namespace EE::Graphics; using namespace EE::UI::Doc; namespace EE { namespace Graphics { class Font; }} // namespace EE::Graphics namespace EE { namespace UI { class UICodeEditor; class UIScrollBar; class UICodeEditorModule { public: virtual void onRegister( UICodeEditor* ) = 0; virtual void onUnregister( UICodeEditor* ) = 0; virtual bool onKeyDown( UICodeEditor*, const KeyEvent& ) { return false; } virtual bool onKeyUp( UICodeEditor*, const KeyEvent& ) { return false; } virtual bool onTextInput( UICodeEditor*, const TextInputEvent& ) { return false; } virtual void update( UICodeEditor* ) {} virtual void preDraw( UICodeEditor*, const Vector2f& /*startScroll*/, const Float& /*lineHeight*/, const TextPosition& /*cursor*/ ) {} virtual void postDraw( UICodeEditor*, const Vector2f& /*startScroll*/, const Float& /*lineHeight*/, const TextPosition& /*cursor*/ ) {} virtual void onFocus( UICodeEditor* ) {} virtual void onFocusLoss( UICodeEditor* ) {} virtual bool onMouseDown( UICodeEditor*, const Vector2i&, const Uint32& ) { return false; } virtual bool onMouseMove( UICodeEditor*, const Vector2i&, const Uint32& ) { return false; } virtual bool onMouseUp( UICodeEditor*, const Vector2i&, const Uint32& ) { return false; } virtual bool onMouseClick( UICodeEditor*, const Vector2i&, const Uint32& ) { return false; } virtual bool onMouseDoubleClick( UICodeEditor*, const Vector2i&, const Uint32& ) { return false; } virtual bool onMouseOver( UICodeEditor*, const Vector2i&, const Uint32& ) { return false; } virtual bool onMouseLeave( UICodeEditor*, const Vector2i&, const Uint32& ) { return false; } virtual void drawBeforeLineText( UICodeEditor*, const Int64&, Vector2f, const Float&, const Float& ){}; virtual void drawAfterLineText( UICodeEditor*, const Int64&, Vector2f, const Float&, const Float& ){}; }; class EE_API DocEvent : public Event { public: DocEvent( Node* node, TextDocument* doc, const Uint32& eventType ) : Event( node, eventType ), doc( doc ) {} TextDocument* getDoc() const { return doc; } protected: TextDocument* doc; }; class EE_API DocSyntaxDefEvent : public DocEvent { public: DocSyntaxDefEvent( Node* node, TextDocument* doc, const Uint32& eventType, const std::string& oldLang, const std::string& newLang ) : DocEvent( node, doc, eventType ), oldLang( oldLang ), newLang( newLang ) {} const std::string& getOldLang() const { return oldLang; } const std::string& getNewLang() const { return newLang; } protected: TextDocument* doc; std::string oldLang; std::string newLang; }; class EE_API UICodeEditor : public UIWidget, public TextDocument::Client { public: static UICodeEditor* New(); static UICodeEditor* NewOpt( const bool& autoRegisterBaseCommands, const bool& autoRegisterBaseKeybindings ); static const std::map<KeyBindings::Shortcut, std::string> getDefaultKeybindings(); UICodeEditor( const bool& autoRegisterBaseCommands = true, const bool& autoRegisterBaseKeybindings = true ); virtual ~UICodeEditor(); virtual Uint32 getType() const; virtual bool isType( const Uint32& type ) const; virtual void setTheme( UITheme* Theme ); virtual void draw(); virtual void scheduledUpdate( const Time& time ); void reset(); bool loadFromFile( const std::string& path ); bool save(); bool save( const std::string& path ); bool save( IOStreamFile& stream ); Font* getFont() const; const UIFontStyleConfig& getFontStyleConfig() const; UICodeEditor* setFont( Font* font ); UICodeEditor* setFontSize( const Float& dpSize ); const Float& getFontSize() const; UICodeEditor* setFontColor( const Color& color ); const Color& getFontColor() const; UICodeEditor* setFontSelectedColor( const Color& color ); const Color& getFontSelectedColor(); UICodeEditor* setFontSelectionBackColor( const Color& color ); const Color& getFontSelectionBackColor() const; UICodeEditor* setFontShadowColor( const Color& color ); const Color& getFontShadowColor() const; UICodeEditor* setFontStyle( const Uint32& fontStyle ); const Uint32& getTabWidth() const; UICodeEditor* setTabWidth( const Uint32& tabWidth ); const Uint32& getFontStyle() const; const Float& getOutlineThickness() const; UICodeEditor* setOutlineThickness( const Float& outlineThickness ); const Color& getOutlineColor() const; UICodeEditor* setOutlineColor( const Color& outlineColor ); const Float& getMouseWheelScroll() const; void setMouseWheelScroll( const Float& mouseWheelScroll ); void setLineNumberPaddingLeft( const Float& dpLeft ); void setLineNumberPaddingRight( const Float& dpRight ); void setLineNumberPadding( const Float& dpPaddingLeft, const Float& dpPaddingRight ); const Float& getLineNumberPaddingLeft() const; const Float& getLineNumberPaddingRight() const; size_t getLineNumberDigits() const; Float getLineNumberWidth() const; const bool& getShowLineNumber() const; void setShowLineNumber( const bool& showLineNumber ); const Color& getLineNumberBackgroundColor() const; void setLineNumberBackgroundColor( const Color& lineNumberBackgroundColor ); const Color& getCurrentLineBackgroundColor() const; void setCurrentLineBackgroundColor( const Color& currentLineBackgroundColor ); const Color& getCaretColor() const; void setCaretColor( const Color& caretColor ); const Color& getWhitespaceColor() const; void setWhitespaceColor( const Color& color ); const SyntaxColorScheme& getColorScheme() const; void setColorScheme( const SyntaxColorScheme& colorScheme ); /** If the document is managed by more than one client you need to NOT auto register base * commands and implement your own logic for those commands, since are dependant of the client * state. * @see registerCommands */ std::shared_ptr<Doc::TextDocument> getDocumentRef() const; const Doc::TextDocument& getDocument() const; Doc::TextDocument& getDocument(); void setDocument( std::shared_ptr<TextDocument> doc ); bool isDirty() const; const bool& isLocked() const; void setLocked( bool locked ); const Color& getLineNumberFontColor() const; void setLineNumberFontColor( const Color& lineNumberFontColor ); const Color& getLineNumberActiveFontColor() const; void setLineNumberActiveFontColor( const Color& lineNumberActiveFontColor ); bool isTextSelectionEnabled() const; void setTextSelection( const bool& active ); KeyBindings& getKeyBindings(); void setKeyBindings( const KeyBindings& keyBindings ); void addKeyBindingString( const std::string& shortcut, const std::string& command, const bool& allowLocked = false ); void addKeyBinding( const KeyBindings::Shortcut& shortcut, const std::string& command, const bool& allowLocked = false ); void replaceKeyBindingString( const std::string& shortcut, const std::string& command, const bool& allowLocked = false ); void replaceKeyBinding( const KeyBindings::Shortcut& shortcut, const std::string& command, const bool& allowLocked = false ); void addKeyBindsString( const std::map<std::string, std::string>& binds, const bool& allowLocked = false ); void addKeyBinds( const std::map<KeyBindings::Shortcut, std::string>& binds, const bool& allowLocked = false ); const bool& getHighlightCurrentLine() const; void setHighlightCurrentLine( const bool& highlightCurrentLine ); const Uint32& getLineBreakingColumn() const; /** Set to 0 to hide. */ void setLineBreakingColumn( const Uint32& lineBreakingColumn ); void addUnlockedCommand( const std::string& command ); void addUnlockedCommands( const std::vector<std::string>& commands ); bool isUnlockedCommand( const std::string& command ); virtual bool applyProperty( const StyleSheetProperty& attribute ); virtual std::string getPropertyString( const PropertyDefinition* propertyDef, const Uint32& propertyIndex = 0 ); const bool& getHighlightMatchingBracket() const; void setHighlightMatchingBracket( const bool& highlightMatchingBracket ); const Color& getMatchingBracketColor() const; void setMatchingBracketColor( const Color& matchingBracketColor ); const bool& getHighlightSelectionMatch() const; void setHighlightSelectionMatch( const bool& highlightSelection ); const Color& getSelectionMatchColor() const; void setSelectionMatchColor( const Color& highlightSelectionMatchColor ); const bool& getEnableColorPickerOnSelection() const; void setEnableColorPickerOnSelection( const bool& enableColorPickerOnSelection ); void setSyntaxDefinition( const SyntaxDefinition& definition ); const SyntaxDefinition& getSyntaxDefinition() const; const bool& getHorizontalScrollBarEnabled() const; void setHorizontalScrollBarEnabled( const bool& horizontalScrollBarEnabled ); const Time& getFindLongestLineWidthUpdateFrequency() const; void setFindLongestLineWidthUpdateFrequency( const Time& findLongestLineWidthUpdateFrequency ); /** Doc commands executed in this editor. */ TextPosition moveToLineOffset( const TextPosition& position, int offset ); void moveToPreviousLine(); void moveToNextLine(); void selectToPreviousLine(); void selectToNextLine(); void registerKeybindings(); void registerCommands(); void moveScrollUp(); void moveScrollDown(); void indent(); void unindent(); void copy(); void cut(); void paste(); void fontSizeGrow(); void fontSizeShrink(); void fontSizeReset(); /** Doc commands executed in this editor. */ const bool& getShowWhitespaces() const; void setShowWhitespaces( const bool& showWhitespaces ); const String& getHighlightWord() const; void setHighlightWord( const String& highlightWord ); const TextRange& getHighlightTextRange() const; void setHighlightTextRange( const TextRange& highlightSelection ); void registerModule( UICodeEditorModule* module ); void unregisterModule( UICodeEditorModule* module ); virtual Int64 getColFromXOffset( Int64 line, const Float& x ) const; virtual Float getColXOffset( TextPosition position ); virtual Float getXOffsetCol( const TextPosition& position ); virtual Float getLineWidth( const Int64& lineIndex ); Float getTextWidth( const String& text ) const; Float getLineHeight() const; Float getCharacterSize() const; Float getGlyphWidth() const; const bool& getColorPreview() const; void setColorPreview( bool colorPreview ); void goToLine( const TextPosition& position, bool centered = true ); bool getAutoCloseBrackets() const; void setAutoCloseBrackets( bool autoCloseBracket ); protected: struct LastXOffset { TextPosition position; Float offset; }; Font* mFont; UIFontStyleConfig mFontStyleConfig; std::shared_ptr<Doc::TextDocument> mDoc; Vector2f mScrollPos; Clock mBlinkTimer; bool mDirtyEditor; bool mCursorVisible; bool mMouseDown; bool mShowLineNumber; bool mShowWhitespaces; bool mLocked; bool mHighlightCurrentLine; bool mHighlightMatchingBracket; bool mHighlightSelectionMatch; bool mEnableColorPickerOnSelection; bool mHorizontalScrollBarEnabled; bool mLongestLineWidthDirty; bool mColorPreview; Uint32 mTabWidth; Vector2f mScroll; Float mMouseWheelScroll; Float mFontSize; Float mLineNumberPaddingLeft; Float mLineNumberPaddingRight; Color mLineNumberFontColor; Color mLineNumberActiveFontColor; Color mLineNumberBackgroundColor; Color mCurrentLineBackgroundColor; Color mCaretColor; Color mWhitespaceColor; Color mLineBreakColumnColor; Color mMatchingBracketColor; Color mSelectionMatchColor; SyntaxColorScheme mColorScheme; SyntaxHighlighter mHighlighter; UIScrollBar* mVScrollBar; UIScrollBar* mHScrollBar; LastXOffset mLastXOffset{ { 0, 0 }, 0.f }; KeyBindings mKeyBindings; std::unordered_set<std::string> mUnlockedCmd; Clock mLastDoubleClick; Uint32 mLineBreakingColumn{ 100 }; TextRange mMatchingBrackets; Float mLongestLineWidth{ 0 }; Time mFindLongestLineWidthUpdateFrequency; Clock mLongestLineWidthLastUpdate; String mHighlightWord; TextRange mHighlightTextRange; Color mPreviewColor; TextRange mPreviewColorRange; std::vector<UICodeEditorModule*> mModules; UICodeEditor( const std::string& elementTag, const bool& autoRegisterBaseCommands = true, const bool& autoRegisterBaseKeybindings = true ); void checkMatchingBrackets(); void updateColorScheme(); void updateLongestLineWidth(); void invalidateEditor(); void invalidateLongestLineWidth(); virtual void findLongestLine(); virtual Uint32 onFocus(); virtual Uint32 onFocusLoss(); virtual Uint32 onTextInput( const TextInputEvent& event ); virtual Uint32 onKeyDown( const KeyEvent& event ); virtual Uint32 onKeyUp( const KeyEvent& event ); virtual Uint32 onMouseDown( const Vector2i& position, const Uint32& flags ); virtual Uint32 onMouseMove( const Vector2i& position, const Uint32& flags ); virtual Uint32 onMouseUp( const Vector2i& position, const Uint32& flags ); virtual Uint32 onMouseClick( const Vector2i& position, const Uint32& flags ); virtual Uint32 onMouseDoubleClick( const Vector2i& position, const Uint32& flags ); virtual Uint32 onMouseOver( const Vector2i& position, const Uint32& flags ); virtual Uint32 onMouseLeave( const Vector2i& position, const Uint32& flags ); virtual void onSizeChange(); virtual void onPaddingChange(); virtual void onCursorPosChange(); void updateEditor(); virtual void onDocumentTextChanged(); virtual void onDocumentCursorChange( const TextPosition& ); virtual void onDocumentSelectionChange( const TextRange& ); virtual void onDocumentLineCountChange( const size_t& lastCount, const size_t& newCount ); virtual void onDocumentLineChanged( const Int64& lineIndex ); virtual void onDocumentUndoRedo( const TextDocument::UndoRedo& ); virtual void onDocumentSaved( TextDocument* ); virtual void onDocumentClosed( TextDocument* doc ); virtual void onDocumentDirtyOnFileSystem( TextDocument* doc ); std::pair<int, int> getVisibleLineRange(); int getVisibleLinesCount(); void scrollToMakeVisible( const TextPosition& position, bool centered = false ); void setScrollX( const Float& val, bool emmitEvent = true ); void setScrollY( const Float& val, bool emmitEvent = true ); void resetCursor(); TextPosition resolveScreenPosition( const Vector2f& position ) const; Vector2f getViewPortLineCount() const; Sizef getMaxScroll() const; void updateScrollBar(); void checkColorPickerAction(); virtual void drawCursor( const Vector2f& startScroll, const Float& lineHeight, const TextPosition& cursor ); virtual void drawMatchingBrackets( const Vector2f& startScroll, const Float& lineHeight ); virtual void drawSelectionMatch( const std::pair<int, int>& lineRange, const Vector2f& startScroll, const Float& lineHeight ); virtual void drawWordMatch( const String& text, const std::pair<int, int>& lineRange, const Vector2f& startScroll, const Float& lineHeight ); virtual void drawLineText( const Int64& index, Vector2f position, const Float& fontSize, const Float& lineHeight ); virtual void drawWhitespaces( const std::pair<int, int>& lineRange, const Vector2f& startScroll, const Float& lineHeight ); virtual void drawTextRange( const TextRange& range, const std::pair<int, int>& lineRange, const Vector2f& startScroll, const Float& lineHeight, const Color& backgrundColor ); virtual void drawLineNumbers( const std::pair<int, int>& lineRange, const Vector2f& startScroll, const Vector2f& screenStart, const Float& lineHeight, const Float& lineNumberWidth, const int& lineNumberDigits, const Float& fontSize ); virtual void drawColorPreview( const Vector2f& startScroll, const Float& lineHeight ); virtual void onFontChanged(); virtual void onFontStyleChanged(); virtual void onDocumentChanged(); virtual Uint32 onMessage( const NodeMessage* msg ); void checkMouseOverColor( const Vector2i& position ); void resetPreviewColor(); void disableEditorFeatures(); Float getViewportWidth( const bool& forceVScroll = false ) const; }; }} // namespace EE::UI #endif // EE_UI_UICODEEDIT_HPP
28.945518
97
0.762963
SpartanJ
2cdb18f15cbe06a3e12b5e419a3bb418f2950b1f
586
cpp
C++
py/cpp_gencode/Se2_Dx_exp_x.cpp
jian-li/sophus
13fb3288311485dc94e3226b69c9b59cd06ff94e
[ "MIT" ]
127
2019-04-23T07:06:42.000Z
2022-03-31T15:36:37.000Z
py/cpp_gencode/Se2_Dx_exp_x.cpp
jian-li/sophus
13fb3288311485dc94e3226b69c9b59cd06ff94e
[ "MIT" ]
1
2021-03-08T07:18:06.000Z
2021-03-08T07:18:06.000Z
py/cpp_gencode/Se2_Dx_exp_x.cpp
jian-li/sophus
13fb3288311485dc94e3226b69c9b59cd06ff94e
[ "MIT" ]
48
2019-05-24T18:51:32.000Z
2021-08-16T01:54:06.000Z
Scalar const c0 = sin(theta); Scalar const c1 = cos(theta); Scalar const c2 = 1.0/theta; Scalar const c3 = c0*c2; Scalar const c4 = -c1 + 1; Scalar const c5 = c2*c4; Scalar const c6 = c1*c2; Scalar const c7 = pow(theta, -2); Scalar const c8 = c0*c7; Scalar const c9 = c4*c7; result[0] = 0; result[1] = 0; result[2] = -c0; result[3] = 0; result[4] = 0; result[5] = c1; result[6] = c3; result[7] = -c5; result[8] = -c3*upsilon[1] + c6*upsilon[0] - c8*upsilon[0] + c9*upsilon[1]; result[9] = c5; result[10] = c3; result[11] = c3*upsilon[0] + c6*upsilon[1] - c8*upsilon[1] - c9*upsilon[0];
25.478261
75
0.62628
jian-li
2ce15d2f1bb8fe46bc63a7c517812b7e76e043d2
932
hpp
C++
Circuit/SessionRunner.hpp
Wang-Yue/Circu
a194bb904f9debab35d24eecb53c091556c17cd6
[ "BSD-3-Clause" ]
8
2018-08-24T01:31:38.000Z
2021-03-01T14:57:59.000Z
Circuit/SessionRunner.hpp
Wang-Yue/Circu
a194bb904f9debab35d24eecb53c091556c17cd6
[ "BSD-3-Clause" ]
1
2019-12-08T13:43:19.000Z
2019-12-13T03:36:16.000Z
Circuit/SessionRunner.hpp
Wang-Yue/Circuit
a194bb904f9debab35d24eecb53c091556c17cd6
[ "BSD-3-Clause" ]
null
null
null
// // SessionRunner.hpp // Circuit // // Created by Yue Wang on 8/18/18. // Copyright © 2018 Yue Wang. All rights reserved. // #ifndef SessionRunner_hpp #define SessionRunner_hpp #include <vector> #include "TypeDefs.hpp" class Synth; class Sample; class Session; template <typename AtomClass> class ChannelRunner; class SessionRunner { public: SessionRunner(Session *session); virtual ~SessionRunner(); void Restart(); void Stop(); ChannelRunner<Synth> *GetSynthChannelRunner(const ChannelIndex &index) const; ChannelIndex GetSynthChannelRunnerCount() const; ChannelRunner<Sample> *GetSampleChannelRunner(const ChannelIndex &index) const; ChannelIndex GetSampleChannelRunnerCount() const; void TickMicrostep(); private: Session *_session; std::vector<ChannelRunner<Synth> *> _synth_channel_runners; std::vector<ChannelRunner<Sample> *> _sample_channel_runners; }; #endif /* SessionRunner_hpp */
23.3
81
0.759657
Wang-Yue
2ce4869c9fbf748652886d91f227194f6cb21da2
2,274
cc
C++
tests/testVector1.cc
TheCubeOfFire/gf
f9587d46add949191fb075f143472033e51920c9
[ "Zlib" ]
null
null
null
tests/testVector1.cc
TheCubeOfFire/gf
f9587d46add949191fb075f143472033e51920c9
[ "Zlib" ]
null
null
null
tests/testVector1.cc
TheCubeOfFire/gf
f9587d46add949191fb075f143472033e51920c9
[ "Zlib" ]
null
null
null
/* * Gamedev Framework (gf) * Copyright (C) 2016-2022 Julien Bernard * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <gf/Vector.h> #include "gtest/gtest.h" TEST(Vector1Test, Access) { gf::Vector<int, 1> vec; vec.data[0] = 42; EXPECT_EQ(42, vec.data[0]); EXPECT_EQ(42, vec[0]); vec[0] = 69; EXPECT_EQ(69, vec.data[0]); EXPECT_EQ(69, vec[0]); } TEST(Vector1Test, Brace1Ctor) { gf::Vector<int, 1> vec{42}; EXPECT_EQ(42, vec[0]); } TEST(Vector1Test, ValueCtor) { gf::Vector<int, 1> vec(42); EXPECT_EQ(42, vec[0]); } TEST(Vector1Test, PointerCtor) { const int data[1] = { 42 }; gf::Vector<int, 1> vec(data); EXPECT_EQ(42, vec[0]); } TEST(Vector1Test, InitCtor) { gf::Vector<int, 1> vec = { 42 }; EXPECT_EQ(42, vec[0]); } TEST(Vector1Test, CopyCtor) { gf::Vector<int, 1> original(42); gf::Vector<int, 1> vec = original; EXPECT_EQ(42, vec[0]); } TEST(Vector1Test, ZeroCtor) { gf::Vector<int, 1> vec = gf::Zero; EXPECT_EQ(0, vec[0]); } TEST(Vector1Test, RangeFor) { gf::Vector<int, 1> vec(1); int expected = 1; for (int elem : vec) { EXPECT_EQ(expected, elem); ++expected; } EXPECT_EQ(expected, 2); } TEST(Vector1Test, Iterator) { gf::Vector<int, 1> vec1(1); EXPECT_EQ(std::distance(vec1.begin(), vec1.end()), 1); const gf::Vector<int, 1> vec2(1); EXPECT_EQ(std::distance(vec2.begin(), vec2.end()), 1); EXPECT_EQ(std::distance(vec2.cbegin(), vec2.cend()), 1); }
24.717391
77
0.670624
TheCubeOfFire
f8edca9ca240b05fbf1ee1a6a125b727ea43c441
3,515
cpp
C++
src/samples/common/shaders.cpp
glines/libmc
4d74c630252a0e46fda9dbec357bd1cd47223f1f
[ "MIT" ]
14
2017-01-10T16:33:25.000Z
2020-05-12T18:49:02.000Z
src/samples/common/shaders.cpp
auntieNeo/libmc
4d74c630252a0e46fda9dbec357bd1cd47223f1f
[ "MIT" ]
null
null
null
src/samples/common/shaders.cpp
auntieNeo/libmc
4d74c630252a0e46fda9dbec357bd1cd47223f1f
[ "MIT" ]
3
2017-09-20T01:05:10.000Z
2020-12-29T09:13:23.000Z
/* * Copyright (c) 2016 Jonathan Glines * Jonathan Glines <jonathan@glines.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. */ #include "shaderProgram.h" #include "shaders.h" namespace mc { namespace samples { #ifdef __EMSCRIPTEN__ #define SHADER_DIR assets_shaders_webgl #else #define SHADER_DIR assets_shaders_glsl #endif #define CAT(a, b) a ## b #define DEFINE_SHADER_BASE(shader, dir) \ std::shared_ptr<ShaderProgram> Shaders:: shader ## Shader() { \ static std::shared_ptr<ShaderProgram> instance = \ std::shared_ptr<ShaderProgram>( \ new ShaderProgram( \ (const char *)CAT(dir, _ ## shader ## _vert), \ CAT(dir, _ ## shader ## _vert_len), \ (const char *)CAT(dir, _ ## shader ## _frag), \ CAT(dir, _ ## shader ## _frag_len) \ )); \ return instance; \ } #define DEFINE_SHADER(shader) DEFINE_SHADER_BASE(shader, SHADER_DIR) #ifdef __EMSCRIPTEN__ #include "assets_shaders_webgl_billboard.vert.c" #include "assets_shaders_webgl_billboard.frag.c" #else #include "assets_shaders_glsl_billboard.vert.c" #include "assets_shaders_glsl_billboard.frag.c" #endif DEFINE_SHADER(billboard) #ifdef __EMSCRIPTEN__ #include "assets_shaders_webgl_billboardPoint.vert.c" #include "assets_shaders_webgl_billboardPoint.frag.c" #else #include "assets_shaders_glsl_billboardPoint.vert.c" #include "assets_shaders_glsl_billboardPoint.frag.c" #endif DEFINE_SHADER(billboardPoint) #ifdef __EMSCRIPTEN__ #include "assets_shaders_webgl_gouraud.vert.c" #include "assets_shaders_webgl_gouraud.frag.c" #else #include "assets_shaders_glsl_gouraud.vert.c" #include "assets_shaders_glsl_gouraud.frag.c" #endif DEFINE_SHADER(gouraud) #ifdef __EMSCRIPTEN__ #include "assets_shaders_webgl_gouraudWinding.vert.c" #include "assets_shaders_webgl_gouraudWinding.frag.c" #else #include "assets_shaders_glsl_gouraudWinding.vert.c" #include "assets_shaders_glsl_gouraudWinding.frag.c" #endif DEFINE_SHADER(gouraudWinding) #ifdef __EMSCRIPTEN__ #include "assets_shaders_webgl_point.vert.c" #include "assets_shaders_webgl_point.frag.c" #else #include "assets_shaders_glsl_point.vert.c" #include "assets_shaders_glsl_point.frag.c" #endif DEFINE_SHADER(point) #ifdef __EMSCRIPTEN__ #include "assets_shaders_webgl_wireframe.vert.c" #include "assets_shaders_webgl_wireframe.frag.c" #else #include "assets_shaders_glsl_wireframe.vert.c" #include "assets_shaders_glsl_wireframe.frag.c" #endif DEFINE_SHADER(wireframe) } }
35.505051
79
0.770128
glines
f8f4868f7e10133c0793d53bfb6cd8debc4ab20b
959
cpp
C++
trunk/libs/graphics/source/buffers.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/graphics/source/buffers.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/graphics/source/buffers.cpp
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include <ang/graphics/graphics.h> using namespace ang; using namespace ang::graphics; using namespace ang::graphics::buffers; //ANG_IMPLEMENT_INTERFACE_CLASS_INFO(ang::graphics::buffers::igpu_buffer, lattelib); //ANG_IMPLEMENT_INTERFACE_CLASS_INFO(ang::graphics::buffers::iindex_buffer, lattelib); //ANG_IMPLEMENT_INTERFACE_CLASS_INFO(ang::graphics::buffers::ivertex_buffer, lattelib); ANG_ENUM_IMPLEMENT(ang::graphics::buffers, buffer_type); ANG_ENUM_IMPLEMENT(ang::graphics::buffers, buffer_usage); ANG_FLAGS_IMPLEMENT(ang::graphics::buffers, buffer_bind_flag); #define MY_TYPE ang::graphics::buffers::igpu_buffer #include <ang/inline/intf_wrapper_specialization.inl> #undef MY_TYPE #define MY_TYPE ang::graphics::buffers::iindex_buffer #include <ang/inline/intf_wrapper_specialization.inl> #undef MY_TYPE #define MY_TYPE ang::graphics::buffers::ivertex_buffer #include <ang/inline/intf_wrapper_specialization.inl> #undef MY_TYPE
31.966667
87
0.816475
ChuyX3
f8f5267031a6d93cb898acb6f278220f9c921a32
2,506
cpp
C++
Source/Foundation/Data/Helper/TimeBasedHelper.cpp
GoPlan/cldeplus
b5c7b95db10f64ac597aa0bf82e1bd94e4c7c940
[ "Apache-2.0" ]
null
null
null
Source/Foundation/Data/Helper/TimeBasedHelper.cpp
GoPlan/cldeplus
b5c7b95db10f64ac597aa0bf82e1bd94e4c7c940
[ "Apache-2.0" ]
null
null
null
Source/Foundation/Data/Helper/TimeBasedHelper.cpp
GoPlan/cldeplus
b5c7b95db10f64ac597aa0bf82e1bd94e4c7c940
[ "Apache-2.0" ]
null
null
null
/* Copyright 2015 LE, Duc-Anh 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 "TimeBasedHelper.h" namespace CLDEPlus { namespace Foundation { namespace Data { namespace Helper { string TimeBasedHelper::DateToISO8601String(const TimeBasedValue::TSDate &date) { string year{std::to_string(date.year)}; string month{std::to_string(date.month)}; string day{std::to_string(date.day)}; string result = year + "-" + month + "-" + day; return result; } string TimeBasedHelper::TimeToISO8601String(const TimeBasedValue::TSTime &time, bool hasMilliSecs, bool hasOffSet) { string hour{std::to_string(time.hour)}; string minute{std::to_string(time.minute)}; string second{std::to_string(time.second)}; string milliSecs = hasMilliSecs ? "." + std::to_string(time.milliSecs) : ""; string offset = hasOffSet ? std::to_string(time.offset) : ""; string result = hour + ":" + minute + ":" + second + milliSecs + offset; return result; } string TimeBasedHelper::DateTimeToISO8601String(const TimeBasedValue::TSDateTime &dateTime, bool hasMilliSecs, bool hasOffSet) { return DateToISO8601String(dateTime.date) + TimeToISO8601String(dateTime.time, hasMilliSecs, hasOffSet); } } } } }
41.766667
107
0.504389
GoPlan
f8fecb821247fc06a946285eb965520afeede292
5,009
cpp
C++
tests/enum.tests.cpp
dynamic-static/core
60442bad208b86fccce0635f8fc391880f106d90
[ "MIT" ]
null
null
null
tests/enum.tests.cpp
dynamic-static/core
60442bad208b86fccce0635f8fc391880f106d90
[ "MIT" ]
2
2017-10-05T18:02:27.000Z
2017-11-22T06:32:43.000Z
tests/enum.tests.cpp
DynamicStatic/Dynamic_Static.Core
60442bad208b86fccce0635f8fc391880f106d90
[ "MIT" ]
null
null
null
/* ========================================== Copyright (c) 2016-2020 Dynamic_Static Patrick Purcell Licensed under the MIT license http://opensource.org/licenses/MIT ========================================== */ #include "dynamic_static/core/enum.hpp" #include "catch2/catch.hpp" #include <type_traits> namespace dst { namespace tests { enum class WidgetType { Unknown = 0, Foo = 1, Bar = 1 << 1, Baz = 1 << 2, Qux = 1 << 3, }; template <> struct EnumClassOperators<WidgetType> { static constexpr bool enabled { true }; }; /** Validates that enum class operator overloads work correctly */ TEST_CASE("EnumClassOperators<>", "[EnumClassOperators<>]") { WidgetType widgetType = WidgetType::Baz; using UnderlyingType = typename std::underlying_type<WidgetType>::type; auto valueType = (UnderlyingType)widgetType; auto widgetTypeResult = widgetType; auto valueTypeResult = valueType; SECTION("operator+()") { widgetTypeResult = widgetType + WidgetType::Qux; valueTypeResult = valueType + (UnderlyingType)WidgetType::Qux; widgetTypeResult = widgetType + 3; valueTypeResult = valueType + 3; } SECTION("operator+=()") { widgetTypeResult += WidgetType::Bar; valueTypeResult += (UnderlyingType)WidgetType::Bar; widgetTypeResult += 3; valueTypeResult += 3; } SECTION("operator++()") { auto widgetTypeResultPrefixIncrement = ++widgetTypeResult; auto widgetTypeResultPostfixIncrement = widgetTypeResult++; auto valueTypeResultPrefixIncrement = ++valueTypeResult; auto valueTypeResultPostfixIncrement = valueTypeResult++; CHECK(widgetTypeResultPrefixIncrement == (WidgetType)valueTypeResultPrefixIncrement); CHECK(widgetTypeResultPostfixIncrement == (WidgetType)valueTypeResultPostfixIncrement); } SECTION("operator-()") { widgetTypeResult = widgetType - WidgetType::Qux; valueTypeResult = valueType - (UnderlyingType)WidgetType::Qux; widgetTypeResult = widgetType - 3; valueTypeResult = valueType - 3; } SECTION("operator-=()") { widgetTypeResult -= WidgetType::Bar; valueTypeResult -= (UnderlyingType)WidgetType::Bar; widgetTypeResult -= 3; valueTypeResult -= 3; } SECTION("operator--()") { auto widgetTypeResultPrefixIncrement = --widgetTypeResult; auto widgetTypeResultPostfixIncrement = widgetTypeResult--; auto valueTypeResultPrefixIncrement = --valueTypeResult; auto valueTypeResultPostfixIncrement = valueTypeResult--; CHECK(widgetTypeResultPrefixIncrement == (WidgetType)valueTypeResultPrefixIncrement); CHECK(widgetTypeResultPostfixIncrement == (WidgetType)valueTypeResultPostfixIncrement); } SECTION("operator~()") { widgetTypeResult = ~widgetTypeResult; valueTypeResult = ~valueTypeResult; } SECTION("operator&()") { widgetTypeResult = widgetTypeResult & WidgetType::Foo; valueTypeResult = valueTypeResult & (UnderlyingType)WidgetType::Foo; } SECTION("operator&=()") { widgetTypeResult &= WidgetType::Qux; valueTypeResult &= (UnderlyingType)WidgetType::Qux; } SECTION("operator|()") { widgetTypeResult = widgetTypeResult | WidgetType::Foo; valueTypeResult = valueTypeResult | (UnderlyingType)WidgetType::Foo; } SECTION("operator|=()") { widgetTypeResult |= WidgetType::Bar; valueTypeResult |= (UnderlyingType)WidgetType::Bar; } SECTION("operator^()") { widgetTypeResult = widgetTypeResult ^ WidgetType::Foo; valueTypeResult = valueTypeResult ^ (UnderlyingType)WidgetType::Foo; } SECTION("operator^=()") { widgetTypeResult ^= WidgetType::Qux; valueTypeResult ^= (UnderlyingType)WidgetType::Qux; } SECTION("operator<<()") { widgetTypeResult = widgetType << WidgetType::Qux; valueTypeResult = valueType << (UnderlyingType)WidgetType::Qux; widgetTypeResult = widgetType << 3; valueTypeResult = valueType << 3; } SECTION("operator<<=()") { widgetTypeResult <<= WidgetType::Qux; valueTypeResult <<= (UnderlyingType)WidgetType::Qux; widgetTypeResult <<= 3; valueTypeResult <<= 3; } SECTION("operator>>()") { widgetTypeResult = widgetType >> WidgetType::Qux; valueTypeResult = valueType >> (UnderlyingType)WidgetType::Qux; widgetTypeResult = widgetType >> 3; valueTypeResult = valueType >> 3; } SECTION("operator>>=()") { widgetTypeResult >>= WidgetType::Qux; valueTypeResult >>= (UnderlyingType)WidgetType::Qux; widgetTypeResult >>= 3; valueTypeResult >>= 3; } CHECK(widgetTypeResult == (WidgetType)valueTypeResult); } } // namespace tests } // namespace dst
31.503145
95
0.639449
dynamic-static
5d0213074f666ae49b764af34c55412a6d962051
5,739
cpp
C++
pitshift.cpp
YepSfx/VibratoVoiceEffect
9fe37cffae368592f5fd69949f62a571144eed21
[ "MIT" ]
null
null
null
pitshift.cpp
YepSfx/VibratoVoiceEffect
9fe37cffae368592f5fd69949f62a571144eed21
[ "MIT" ]
null
null
null
pitshift.cpp
YepSfx/VibratoVoiceEffect
9fe37cffae368592f5fd69949f62a571144eed21
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "dsp_def.h" #include "dsp_util.h" #include "delay.h" #include "pitshift.h" #include <math.h> #define DEF_CH 1 #define DEF_BIT 16 #define DEF_SAMRATE 22050 #define DEF_FADER 1 #define DEF_LOW 24 #define DEF_MID 1000 #define DEF_UPPER 2024 #define DEF_SHIFT 0 #define DEF_VOL 1 #define DEF_DELAYLEN 2048 #define DEF_DELAYGAP 2000 #define DEF_NOTCHGAIN 0.001 #define DEF_SHIFTGAIN 1024 int Compute(PITCHSHIFT *pShift) { pShift->Delay[0] += pShift->Shift[0]; while (pShift->Delay[0] > DEF_UPPER) { pShift->Delay[0] -= DEF_DELAYGAP; if (pShift->Shift[0] != pShift->Shift[1]) pShift->Shift[0] = pShift->Shift[1]; } while (pShift->Delay[0] < DEF_LOW) { pShift->Delay[0] += DEF_DELAYGAP; if (pShift->Shift[0] != pShift->Shift[1]) pShift->Shift[0] = pShift->Shift[1]; } pShift->Delay[1] = pShift->Delay[0] + DEF_MID; while (pShift->Delay[1] > DEF_UPPER) { pShift->Delay[1] -= DEF_DELAYGAP; if (pShift->Shift[0] != pShift->Shift[1]) pShift->Shift[0] = pShift->Shift[1]; } while (pShift->Delay[1] < DEF_LOW) { pShift->Delay[1] += DEF_DELAYGAP; if (pShift->Shift[0] != pShift->Shift[1]) pShift->Shift[0] = pShift->Shift[1]; } pShift->Fader[1] = float(fabs(pShift->Delay[0] - DEF_SHIFTGAIN) * DEF_NOTCHGAIN); pShift->Fader[0] = 1 - pShift->Fader[1]; return TRUE; } int InitPitchShift(PITCHSHIFT *pShift) { InitDelay(&(pShift->Buffer[0])); DoMsgProc(); InitDelay(&(pShift->Buffer[1])); DoMsgProc(); pShift->nCh = DEF_CH; pShift->nBit = DEF_BIT; pShift->nSamplePerSec = DEF_SAMRATE; pShift->Fader[0] = DEF_FADER; pShift->Fader[1] = DEF_FADER; pShift->Delay[0] = DEF_LOW; pShift->Delay[1] = DEF_UPPER; pShift->Shift[0] = DEF_SHIFT; pShift->Shift[1] = DEF_SHIFT; pShift->Vol[0] = DEF_VOL; pShift->Vol[1] = DEF_VOL; pShift->isProc = false; return TRUE; } int MakePitchShift(PITCHSHIFT *pShift) { pShift->Buffer[0].nCh = pShift->nCh; pShift->Buffer[1].nCh = pShift->nCh; pShift->Buffer[0].nBit = pShift->nBit; pShift->Buffer[1].nBit = pShift->nBit; pShift->Buffer[0].nSamplePerSec = pShift->nSamplePerSec; pShift->Buffer[1].nSamplePerSec = pShift->nSamplePerSec; pShift->Buffer[0].WetGain = 1; pShift->Buffer[1].WetGain = 1; pShift->Buffer[0].DryGain = 1; pShift->Buffer[1].DryGain = 1; pShift->isProc = false; MakeDelayLine(&(pShift->Buffer[0]), 1, DEF_DELAYLEN); DoMsgProc(); MakeDelayLine(&(pShift->Buffer[1]), 1, DEF_DELAYLEN); DoMsgProc(); return TRUE; } int SetShiftAmount(PITCHSHIFT *pShift, float amt) { pShift->Shift[1] = amt; pShift->Shift[0] = pShift->Shift[1]; return TRUE; } int ShiftPitch(PITCHSHIFT *pShift, char *pData, int nSam) { int i; INT16 *p16BitBuff, Tmp16M1,Tmp16M2, s16M, Tmp16S1[2], Tmp16S2[2],s16S[2]; INT8 *p8BitBuff, Tmp8M1, Tmp8M2, s8M, Tmp8S1[2], Tmp8S2[2], s8S[2]; while(pShift->isProc == true) DoMsgProc(); pShift->isProc = true; p8BitBuff = pData; p16BitBuff = (INT16*)pData; switch(pShift->nCh) { case 1: if (pShift->nBit==8) { for(i = 0 ; i < nSam ; i++) { Compute(pShift); PutDelay(&(pShift->Buffer[0]),&p8BitBuff[i],1); PutDelay(&(pShift->Buffer[1]),&p8BitBuff[i],1); GetFracDelay(&(pShift->Buffer[0]),&Tmp8M1,1,pShift->Delay[0]); GetFracDelay(&(pShift->Buffer[1]),&Tmp8M2,1,pShift->Delay[1]); s8M = Return8Bit(Set8Bit(Tmp8M1)*pShift->Fader[0] + Set8Bit(Tmp8M2)*pShift->Fader[1]); p8BitBuff[i] = s8M; } }else if (pShift->nBit==16) { for(i = 0 ; i < nSam ; i++) { Compute(pShift); PutDelay(&(pShift->Buffer[0]),(char*)(&p16BitBuff[i]),1); PutDelay(&(pShift->Buffer[1]),(char*)(&p16BitBuff[i]),1); GetFracDelay(&(pShift->Buffer[0]),(char*)(&Tmp16M1),1,pShift->Delay[0]); GetFracDelay(&(pShift->Buffer[1]),(char*)(&Tmp16M2),1,pShift->Delay[1]); s16M =Return16Bit((Tmp16M1*pShift->Fader[0]) + (Tmp16M2*pShift->Fader[1])); p16BitBuff[i] = s16M; } }else{ pShift->isProc = false; return FALSE; } break; case 2: if (pShift->nBit==8) { for(i = 0 ; i < nSam ; i++) { Compute(pShift); Tmp8S1[0] = p8BitBuff[i*2]; Tmp8S1[1] = p8BitBuff[i*2+1]; PutDelay(&(pShift->Buffer[0]),(char*)Tmp8S1,1); PutDelay(&(pShift->Buffer[1]),(char*)Tmp8S1,1); GetFracDelay(&(pShift->Buffer[0]),(char*)Tmp8S1,1,pShift->Delay[0]); GetFracDelay(&(pShift->Buffer[1]),(char*)Tmp8S2,1,pShift->Delay[1]); s8S[0] = Return8Bit(Set8Bit(Tmp8S1[0])*pShift->Fader[0] + Set8Bit(Tmp8S2[0])*pShift->Fader[1]); s8S[1] = Return8Bit(Set8Bit(Tmp8S1[1])*pShift->Fader[0] + Set8Bit(Tmp8S2[1])*pShift->Fader[1]); p8BitBuff[i*2] = s8S[0]; p8BitBuff[i*2+1] = s8S[1]; } }else if (pShift->nBit==16) { for(i = 0 ; i < nSam ; i++) { Compute(pShift); Tmp16S1[0] = p16BitBuff[i*2]; Tmp16S1[1] = p16BitBuff[i*2+1]; PutDelay(&(pShift->Buffer[0]),(char*)Tmp16S1,1); PutDelay(&(pShift->Buffer[1]),(char*)Tmp16S1,1); GetFracDelay(&(pShift->Buffer[0]),(char*)Tmp16S1,1,pShift->Delay[0]); GetFracDelay(&(pShift->Buffer[1]),(char*)Tmp16S2,1,pShift->Delay[1]); s16S[0] = Return16Bit(Tmp16S1[0]*pShift->Fader[0] + Tmp16S2[0]*pShift->Fader[1]); s16S[1] = Return16Bit(Tmp16S1[1]*pShift->Fader[0] + Tmp16S2[1]*pShift->Fader[1]); p16BitBuff[i*2] = s16S[0]; p16BitBuff[i*2+1] = s16S[1]; } }else{ pShift->isProc = false; return FALSE; } break; } pShift->isProc = false; return TRUE; }
24.952174
82
0.601673
YepSfx
5d029d1a07d28841383dea749f0c8980e453c7b5
1,266
cpp
C++
src/IsoGame/Play/Objects/Entities/Enemies/Bosses/Boss1.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
src/IsoGame/Play/Objects/Entities/Enemies/Bosses/Boss1.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
src/IsoGame/Play/Objects/Entities/Enemies/Bosses/Boss1.cpp
Harry09/IsoGame
7320bee14197b66a96f432d4071537b3bb892c13
[ "MIT" ]
null
null
null
#include "Boss1.h" #include <Common\Random.h> #include <Play\Objects\Entities\Enemies\Robot.h> #include <Play\Rooms\Room.h> #include <SFML\Graphics.hpp> Boss1::Boss1(const sf::Vector2f &pos) : Boss(pos) { LoadTextures("enemies\\spaceCraft1", Object::FULL_DIRECTIONS); SetTexture(Directions::S); m_hitbox = sf::FloatRect(64.f, 22.f, 85.f, 91.f); m_health = m_maxHealth = 200; m_scoreValue = 5000; } Boss1::~Boss1() { } void Boss1::Pulse(float deltaTime) { if (m_lastRobotCreated.getElapsedTime().asMilliseconds() > 10000) { m_pParent->AddObject(new Robot(GetPosition(), false)); m_lastRobotCreated.restart(); } if (m_lastMove.getElapsedTime().asMilliseconds() > 2000) { Random random; int moveDir = random.Get<int>(1, 2); if (moveDir == 1) m_horMoveDir = LEFT; else if (moveDir == 2) m_horMoveDir = RIGHT; moveDir = random.Get<int>(1, 2); if (moveDir == 1) m_verMoveDir = UP; else if (moveDir == 2) m_verMoveDir = DOWN; m_lastMove.restart(); } if (m_horCollMoveBlock == LEFT) m_horMoveDir = RIGHT; else if (m_horCollMoveBlock == RIGHT) m_horMoveDir = LEFT; if (m_verCollMoveBlock == UP) m_verMoveDir = DOWN; else if (m_verCollMoveBlock == DOWN) m_verMoveDir = UP; Boss::Pulse(deltaTime); }
18.085714
66
0.680885
Harry09
5d134fb32a17688d254ae3f4fe780ee799d5272c
224
hpp
C++
Effective_C++/Item_12/customer.hpp
ZhuQingping/development_history
84e294044f9b8ec1f02a06e1d24ef3b570a76406
[ "BSD-2-Clause" ]
null
null
null
Effective_C++/Item_12/customer.hpp
ZhuQingping/development_history
84e294044f9b8ec1f02a06e1d24ef3b570a76406
[ "BSD-2-Clause" ]
null
null
null
Effective_C++/Item_12/customer.hpp
ZhuQingping/development_history
84e294044f9b8ec1f02a06e1d24ef3b570a76406
[ "BSD-2-Clause" ]
null
null
null
#ifndef CUSTOMER_HPP #define CUSTOMER_HPP class Customer { public: Customer(std::string); Customer(const Customer& rhs) ; Customer& operator=(const Customer& rhs); private: std::string m_name; }; #endif //CUSTOMER_HPP
14.933333
42
0.745536
ZhuQingping
5d13b99ac7f65b9bed8de2b21d66212c02519680
19,618
cpp
C++
src/uti_phgrm/NewOri/cNewO_NameManager.cpp
rjanvier/micmac
a6caebdacf627430f13f3c6e268ed86fef808e20
[ "CECILL-B" ]
8
2019-05-08T21:43:53.000Z
2021-07-27T20:01:46.000Z
src/uti_phgrm/NewOri/cNewO_NameManager.cpp
rjanvier/micmac
a6caebdacf627430f13f3c6e268ed86fef808e20
[ "CECILL-B" ]
2
2019-05-24T17:11:33.000Z
2019-06-30T17:55:28.000Z
src/uti_phgrm/NewOri/cNewO_NameManager.cpp
rjanvier/micmac
a6caebdacf627430f13f3c6e268ed86fef808e20
[ "CECILL-B" ]
2
2020-06-13T15:07:21.000Z
2021-04-09T07:01:45.000Z
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #include "NewOri.h" const std::string ExtTxtXml = "xml"; const std::string ExtBinDmp = "dmp"; const std::string & ExtXml(bool Bin) { return Bin ? ExtBinDmp : ExtTxtXml; } const std::string cNewO_NameManager::PrefixDirTmp = "NewOriTmp"; cNewO_NameManager::cNewO_NameManager ( const std::string & aExtName, const std::string & aPrefHom, bool Quick, const std::string & aDir, const std::string & anOriCal, const std::string & aPostHom, const std::string & aOriOut ) : mICNM (cInterfChantierNameManipulateur::BasicAlloc(aDir)), mDir (aDir), mPrefOriCal (anOriCal), mPostHom (aPostHom), mPrefHom (aPrefHom), mExtName (aExtName), mQuick (Quick), mOriOut (aOriOut) { if (mOriOut=="") mOriOut = (mQuick ? "Martini" : "MartiniGin") + mExtName +mPrefHom + anOriCal; StdCorrecNameOrient(mPrefOriCal,mDir); mPostfixDir = mExtName + mPrefHom + mPrefOriCal + std::string(mQuick ? "Quick" : "Std"); mDirTmp = std::string(PrefixDirTmp) + mPostfixDir + "/"; ELISE_fp::MkDir(mDir+"Ori-"+mOriOut+"/"); } cVirtInterf_NewO_NameManager * cVirtInterf_NewO_NameManager::StdAlloc(const std::string & aDir, const std::string & anOri, bool Quick) { return new cNewO_NameManager("","",Quick,aDir,anOri,"dat"); } //=============== Surcharge method // "cVirtInterf_NewO_NameManager * cVirtInterf_NewO_NameManager::StdAlloc" // pour adapter avec Suffix homol cVirtInterf_NewO_NameManager * cVirtInterf_NewO_NameManager::StdAlloc(const std::string & aPrefHom, const std::string & aDir,const std::string & anOri,bool Quick) { return new cNewO_NameManager("",aPrefHom,Quick,aDir,anOri,"dat"); } //===================================================================================================== const std::string & cNewO_NameManager::Dir() const { return mDir; } const std::string & cNewO_NameManager::OriOut() const { return mOriOut; } std::string cNewO_NameManager::KeySetCpleOri() const { return "NKS-Set-NewOri-CplIm2OriRel@"+mPostfixDir +"@dmp"; } std::string cNewO_NameManager::KeyAssocCpleOri() const { return "NKS-Assoc-NewOri-CplIm2OriRel@"+mPostfixDir +"@dmp"; } ElPackHomologue cNewO_NameManager::PackOfName(const std::string & aN1,const std::string & aN2) const { std::string aNameH = mICNM->Assoc1To2("NKS-Assoc-CplIm2Hom@"+ mPrefHom+"@"+mPostHom,aN1,aN2,true); if (! ELISE_fp::exist_file(aNameH)) return ElPackHomologue(); return ElPackHomologue::FromFile(aNameH); } cInterfChantierNameManipulateur * cNewO_NameManager::ICNM() { return mICNM; } CamStenope * cInterfChantierNameManipulateur::GlobCalibOfName(const std::string & aName,const std::string & aPrefOriCal,bool aModeFraser) { // std::cout << "cInterfChantierNameManipulateur::GlobCalibOfName \n"; getchar(); if (aPrefOriCal =="") { cMetaDataPhoto aMTD = cMetaDataPhoto::CreateExiv2(Dir() +aName); std::vector<double> aPAF; double aFPix = aMTD.FocPix(); Pt2di aSzIm = aMTD.XifSzIm(); Pt2dr aPP = Pt2dr(aSzIm) / 2.0; bool IsFE; FromString(IsFE,Assoc1To1("NKS-IsFishEye",aName,true)); std::string aNameCal = "CamF" + ToString(aFPix) +"_Sz"+ToString(aSzIm) + "FE"+ToString(IsFE); if (DicBoolFind(mMapName2Calib,aNameCal)) return mMapName2Calib[aNameCal]; CamStenope * aRes = 0; std::vector<double> aVP; std::vector<double> aVE; if (IsFE) { aVE.push_back(aFPix); aVP.push_back(aPP.x); aVP.push_back(aPP.y); aRes = new cCamLin_FishEye_10_5_5 ( false, aFPix,aPP,Pt2dr(aSzIm), aPAF, &aVP, &aVE ); } else { // std::cout << "aModeFraseraModeFraser " << aModeFraser << "\n"; getchar(); if (aModeFraser) aRes = new cCam_Fraser_PPaEqPPs(false,aFPix,aPP,Pt2dr(aSzIm),aPAF,&aVP,&aVE); else aRes = new CamStenopeIdeale(false,aFPix,aPP,aPAF); } aRes->SetSz(aSzIm); mMapName2Calib[aNameCal] = aRes; return aRes; } std::string aNC = StdNameCalib(aPrefOriCal,aName); if (DicBoolFind(mMapName2Calib,aNC)) return mMapName2Calib[aNC]; mMapName2Calib[aNC] = CamOrientGenFromFile(aNC,this); return mMapName2Calib[aNC]; } CamStenope * cNewO_NameManager::CamOfName(const std::string & aName) const { return mICNM->GlobCalibOfName(aName,mPrefOriCal,true); } CamStenope * cNewO_NameManager::CalibrationCamera(const std::string & aName) const { return CamOfName(aName); } ElRotation3D cNewO_NameManager::OriCam2On1(const std::string & aNOri1,const std::string & aNOri2,bool & OK) const { OK = false; bool aN1InfN2 = (aNOri1<aNOri2); std::string aN1 = aN1InfN2?aNOri1:aNOri2; std::string aN2 = aN1InfN2?aNOri2:aNOri1; if (! ELISE_fp::exist_file(NameXmlOri2Im(aN1,aN2,true))) return ElRotation3D::Id; cXml_Ori2Im aXmlO = GetOri2Im(aN1,aN2); OK = aXmlO.Geom().IsInit(); if (!OK) return ElRotation3D::Id; const cXml_O2IRotation & aXO = aXmlO.Geom().Val().OrientAff(); ElRotation3D aR12 = ElRotation3D (aXO.Centre(),ImportMat(aXO.Ori()),true); OK = true; return aN1InfN2 ? aR12.inv() : aR12; // return aN1InfN2 ? aR12 : aR12.inv(); } std::pair<ElRotation3D,ElRotation3D> cNewO_NameManager::OriRelTripletFromExisting ( const std::string & aInOri, const std::string & aN1, const std::string & aN2, const std::string & aN3, bool & Ok ) { std::pair<ElRotation3D,ElRotation3D> aRes(ElRotation3D::Id,ElRotation3D::Id); Ok = false; CamStenope * aCam1 = CamOriOfNameSVP(aN1,aInOri); CamStenope * aCam2 = CamOriOfNameSVP(aN2,aInOri); CamStenope * aCam3 = CamOriOfNameSVP(aN3,aInOri); if (aCam1 && aCam2 && aCam3) { ElRotation3D aRot2Sur1 = (aCam2->Orient() *aCam1->Orient().inv()); ElRotation3D aRot3Sur1 = (aCam3->Orient() *aCam1->Orient().inv()); aRot2Sur1 = aRot2Sur1.inv(); aRot3Sur1 = aRot3Sur1.inv(); double aDist = euclid(aRot2Sur1.tr()); aRot2Sur1.tr() = aRot2Sur1.tr() /aDist; aRot3Sur1.tr() = aRot3Sur1.tr() /aDist; Ok = true; aRes.first = aRot2Sur1; aRes.second = aRot3Sur1; } return aRes; } cResVINM::cResVINM() : mCam1 (0), mCam2 (0), mHom (cElHomographie::Id()), mResHom (-1) { } cResVINM cNewO_NameManager::ResVINM(const std::string & aN1,const std::string & aN2) const { cResVINM aRes; bool Ok; ElRotation3D aR2On1 = OriCam2On1(aN1,aN2,Ok); if (!Ok) { return aRes; } CamStenope* aCam1 = CalibrationCamera(aN1)->Dupl(); CamStenope* aCam2 = CalibrationCamera(aN2)->Dupl(); aCam1->SetOrientation(ElRotation3D::Id); aCam2->SetOrientation(aR2On1); aRes.mCam1 = aCam1; aRes.mCam2 = aCam2; cXml_Ori2Im aXmlO = GetOri2Im(aN1,aN2); aRes.mHom = cElHomographie(aXmlO.Geom().Val().HomWithR().Hom()); aRes.mResHom = aXmlO.Geom().Val().HomWithR().ResiduHom(); return aRes; } std::pair<CamStenope*,CamStenope*> cNewO_NameManager::CamOriRel(const std::string & aN1,const std::string & aN2) const { cResVINM aRV = ResVINM(aN1,aN2); return std::pair<CamStenope*,CamStenope*>(aRV.mCam1,aRV.mCam2); } // cXml_Ori2Im GetOri2Im(const std::string & aN1,const std::string & aN2); std::string cNewO_NameManager::NameOriOut(const std::string & aNameIm) const { return mICNM->Assoc1To1("NKS-Assoc-Im2Orient@-"+OriOut(),aNameIm,true); } CamStenope * cNewO_NameManager::OutPutCamera(const std::string & aName) const { return mICNM->StdCamStenOfNames(aName,OriOut()); } /* */ CamStenope * cInterfChantierNameManipulateur::StdCamStenOfNames(const std::string & aNameIm,const std::string & anOri) { std::string aKey = "NKS-Assoc-Im2Orient@-"+ anOri ; std::string aNameCam = Assoc1To1(aKey,aNameIm,true); return CamOrientGenFromFile(aNameCam,this); } CamStenope * cInterfChantierNameManipulateur::StdCamStenOfNamesSVP(const std::string & aNameIm,const std::string & anOri) { std::string aKey = "NKS-Assoc-Im2Orient@-"+ anOri ; std::string aNameCam = Assoc1To1(aKey,aNameIm,true); if (! ELISE_fp::exist_file(aNameCam)) return 0; return CamOrientGenFromFile(aNameCam,this); } CamStenope * cNewO_NameManager::CamOriOfName(const std::string & aNameIm,const std::string & anOri) { return mICNM->StdCamStenOfNames(aNameIm,anOri); } CamStenope * cNewO_NameManager::CamOriOfNameSVP(const std::string & aNameIm,const std::string & anOri) { std::string aKey = "NKS-Assoc-Im2Orient@-"+ anOri ; std::string aNameCam = mICNM->Assoc1To1(aKey,aNameIm,true); if (! ELISE_fp::exist_file(aNameCam)) return 0; return CamOrientGenFromFile(aNameCam,mICNM); } const std::string & cNewO_NameManager::OriCal() const {return mPrefOriCal;} std::string cNewO_NameManager::NameXmlOri2Im(cNewO_OneIm* aI1,cNewO_OneIm* aI2,bool Bin) const { return NameXmlOri2Im(aI1->Name(),aI2->Name(),Bin); } std::string cNewO_NameManager::NameXmlOri2Im(const std::string & aN1,const std::string & aN2,bool Bin) const { return Dir3POneImage(aN1,true) + "OriRel-" + aN2 + (Bin ? ".dmp" : ".xml"); } /* */ std::string cNewO_NameManager::NameListeImOrientedWith(const std::string & aName,bool Bin) const { return Dir3POneImage(aName) + "ListOrientedsWith-" + aName + (Bin ? ".dmp" : ".xml"); } std::string cNewO_NameManager::RecNameListeImOrientedWith(const std::string & aName,bool Bin) const { return Dir3POneImage(aName) + "RecListOrientedsWith-" + aName + (Bin ? ".dmp" : ".xml"); } std::string cNewO_NameManager::NameListeCpleOriented(bool Bin) const { return Dir3P() + "ListCpleOriented"+ (Bin ? ".dmp" : ".xml"); } std::string cNewO_NameManager::NameListeCpleConnected(bool Bin) const { return Dir3P() + "ListCpleConnected"+ (Bin ? ".dmp" : ".xml"); } std::string cNewO_NameManager::NameRatafiaSom(const std::string & aName,bool Bin) const { return Dir3POneImage(aName) + "Ratafia." + ExtXml(Bin); } std::list<std::string> cNewO_NameManager::ListeImOrientedWith(const std::string & aName) const { return StdGetFromPCP(NameListeImOrientedWith(aName,true),ListOfName).Name(); } std::list<std::string> cNewO_NameManager::Liste2SensImOrientedWith(const std::string & aName) const { std::list<std::string> aRes = ListeImOrientedWith(aName); std::list<std::string> aResRec = StdGetFromPCP(RecNameListeImOrientedWith(aName,true),ListOfName).Name(); std::copy(aResRec.begin(),aResRec.end(),std::back_inserter(aRes)); return aRes; } std::list<std::string> cNewO_NameManager::ListeCompleteTripletTousOri(const std::string & aN1,const std::string & aN2) const { cListOfName aL1 = StdGetFromPCP(NameListeImOrientedWith(aN1,true),ListOfName); cListOfName aL2 = StdGetFromPCP(NameListeImOrientedWith(aN2,true),ListOfName); std::set<std::string> aS1(aL1.Name().begin(),aL1.Name().end()); std::list<std::string> aRes; for (std::list<std::string>::const_iterator it2=aL2.Name().begin() ; it2!=aL2.Name().end() ; it2++) if (DicBoolFind(aS1,*it2)) aRes.push_back(*it2); return aRes; } /* */ std::string cNewO_NameManager::NameTimingOri2Im() const { return Dir3P(true) + "Timing2Im.xml"; } cXml_Ori2Im cNewO_NameManager::GetOri2Im(const std::string & aN1,const std::string & aN2) const { return StdGetFromSI(mDir + NameXmlOri2Im(aN1,aN2,true),Xml_Ori2Im); } /************************ TRIPLETS *****************/ std::string cNewO_NameManager::Dir3P(bool WithMakeDir) const { std::string aRes = mDir + mDirTmp ; if (WithMakeDir) ELISE_fp::MkDir(aRes); return aRes; } std::string cNewO_NameManager::Dir3POneImage(const std::string & aName,bool WithMakeDir) const { std::string aRes = Dir3P(WithMakeDir) + aName + "/"; if (WithMakeDir) ELISE_fp::MkDir(aRes); return aRes; } std::string cNewO_NameManager::Dir3POneImage(cNewO_OneIm * anIm,bool WithMakeDir) const { return Dir3POneImage(anIm->Name(),WithMakeDir); } std::string cNewO_NameManager::Dir3PDeuxImage(const std::string & aName1,const std::string & aName2,bool WithMakeDir) { std::string aRes = Dir3POneImage(aName1,WithMakeDir) + aName2 + "/"; if (WithMakeDir) ELISE_fp::MkDir(aRes); return aRes; } std::string cNewO_NameManager::Dir3PDeuxImage(cNewO_OneIm * anI1,cNewO_OneIm * anI2,bool WithMakeDir) { return Dir3PDeuxImage(anI1->Name(),anI2->Name(),WithMakeDir); } std::string cNewO_NameManager::NameHomFloat(const std::string & aName1,const std::string & aName2) { return Dir3PDeuxImage(aName1,aName2,false) + "HomFloatSym" + ".dat"; } std::string cNewO_NameManager::NameHomFloat(cNewO_OneIm * anI1,cNewO_OneIm * anI2) { return NameHomFloat(anI1->Name(),anI2->Name()); } std::string cNewO_NameManager::NameTripletsOfCple(cNewO_OneIm * anI1,cNewO_OneIm * anI2,bool ModeBin) { return Dir3PDeuxImage(anI1,anI2,false) + "ImsOfTriplets." + std::string(ModeBin ? "dmp" : "xml"); } //======================== std::string cNewO_NameManager::NameAttribTriplet ( const std::string & aPrefix,const std::string & aPost, const std::string & aI1,const std::string & aI2,const std::string & aI3, bool WithMakeDir ) { ELISE_ASSERT(aI1<aI2,"cNO_P3_NameM::NameAttribTriplet"); ELISE_ASSERT(aI2<aI3,"cNO_P3_NameM::NameAttribTriplet"); std::string aDir = Dir3PDeuxImage(aI1,aI2,WithMakeDir); return aDir + "Triplet-" + aPrefix + "-" + aI3 + "." + aPost; } /* */ std::string cNewO_NameManager::NameAttribTriplet ( const std::string & aPrefix,const std::string & aPost, cNewO_OneIm * aI1,cNewO_OneIm * aI2,cNewO_OneIm * aI3, bool WithMakeDir ) { return NameAttribTriplet(aPrefix,aPost,aI1->Name(),aI2->Name(),aI3->Name(),WithMakeDir); } std::string cNewO_NameManager::NameHomTriplet(const std::string & aI1,const std::string & aI2,const std::string & aI3,bool WithMakeDir) { return NameAttribTriplet("Hom","dat",aI1,aI2,aI3,WithMakeDir); } std::string cNewO_NameManager::NameHomTriplet(cNewO_OneIm *aI1,cNewO_OneIm *aI2,cNewO_OneIm *aI3,bool WithMakeDir) { return NameAttribTriplet("Hom","dat",aI1->Name(),aI2->Name(),aI3->Name(),WithMakeDir); } std::string cNewO_NameManager::NameOriInitTriplet(bool ModeBin,cNewO_OneIm *aI1,cNewO_OneIm *aI2,cNewO_OneIm *aI3,bool WithMakeDir) { return NameAttribTriplet("Ori0",(ModeBin ? "dmp" : "xml"),aI1,aI2,aI3,WithMakeDir); } std::string cNewO_NameManager::NameOriOptimTriplet(bool ModeBin,cNewO_OneIm *aI1,cNewO_OneIm *aI2,cNewO_OneIm *aI3,bool WithMakeDir) { return NameAttribTriplet("OriOpt",(ModeBin ? "dmp" : "xml"),aI1,aI2,aI3,WithMakeDir); } std::string cNewO_NameManager::NameOriOptimTriplet(bool ModeBin,const std::string & aN1,const std::string & aN2,const std::string & aN3,bool WithMakeDir) { return NameAttribTriplet("OriOpt",(ModeBin ? "dmp" : "xml"),aN1,aN2,aN3,WithMakeDir); } std::string cNewO_NameManager::NameTopoTriplet(bool aModeBin) { return Dir3P() + "ListeTriplets" + mPrefOriCal +"." + (aModeBin ? "dmp" : "xml"); } std::string cNewO_NameManager::NameCpleOfTopoTriplet(bool aModeBin) { return Dir3P() + "ListeCpleOfTriplets" + mPrefOriCal +"." + (aModeBin ? "dmp" : "xml"); } std::string cNewO_NameManager::NameOriGenTriplet(bool Quick,bool ModeBin,cNewO_OneIm *aI1,cNewO_OneIm *aI2,cNewO_OneIm *aI3) { return Quick ? NameOriInitTriplet (ModeBin,aI1,aI2,aI3) : NameOriOptimTriplet(ModeBin,aI1,aI2,aI3) ; } /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
30.845912
165
0.668162
rjanvier
5d14842ebe20559cd00265352623bb47cce4fd92
546
cpp
C++
Medusa/Medusa/Node/Action/Animation/AnimationManager.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
143
2015-11-18T01:06:03.000Z
2022-03-30T03:08:54.000Z
Medusa/Medusa/Node/Action/Animation/AnimationManager.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
1
2019-10-23T13:00:40.000Z
2019-10-23T13:00:40.000Z
Medusa/Medusa/Node/Action/Animation/AnimationManager.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
45
2015-11-18T01:17:59.000Z
2022-03-05T12:29:45.000Z
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #include "MedusaPreCompiled.h" #include "AnimationManager.h" MEDUSA_BEGIN; AnimationManager::AnimationManager() { } AnimationManager::~AnimationManager(void) { } bool AnimationManager::Initialize() { return true; } bool AnimationManager::Uninitialize() { RETURN_FALSE_IF_FALSE(FrameTask::Uninitialize()); return true; } void AnimationManager::OnUpdate(float dt) { } MEDUSA_END;
15.166667
53
0.752747
tony2u
5d1db21e9b04630caa616f8f8a74b505bcef952b
5,168
cpp
C++
core/pipe_win32.cpp
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
core/pipe_win32.cpp
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
core/pipe_win32.cpp
chwash/wwiv
0d67acdede788f8a4fd2b442e92caeb411552359
[ "Apache-2.0" ]
null
null
null
/**************************************************************************/ /* */ /* WWIV Version 5.x */ /* Copyright (C)1998-2022, WWIV Software Services */ /* */ /* 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 "core/pipe.h" // Always declare wwiv_windows.h first to avoid collisions on defines. #include "core/wwiv_windows.h" #include "core/log.h" #include "fmt/format.h" namespace wwiv::core { static std::string ErrorAsString(DWORD last_error) { LPSTR messageBuffer{nullptr}; const auto size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, last_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), reinterpret_cast<LPSTR>(&messageBuffer), 0, nullptr); std::string message{messageBuffer, size}; // Free the buffer. LocalFree(messageBuffer); return fmt::format("({}): {}", last_error, message); } Pipe::PIPE_HANDLE create_pipe(const std::string& name) { VLOG(2) << "create_pipe: " << name; Pipe::PIPE_HANDLE hPipe = CreateNamedPipe(name.c_str(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 0xff, Pipe::PIPE_BUFFER_SIZE, Pipe::PIPE_BUFFER_SIZE, 0 /* default timeout */, NULL); VLOG(4) << "create_pipe(" << name << "); handle: " << hPipe; return hPipe; } std::string pipe_name(const std::string_view part) { return fmt::format("\\\\.\\PIPE\\{}", part); } bool close_pipe(Pipe::PIPE_HANDLE h, bool server) { VLOG(2) << "close_pipe(" << h << ")"; if (h == INVALID_HANDLE_VALUE) { return true; } if (server) { VLOG(2) << "Flushing File Buffers before shutdown."; FlushFileBuffers(h); } DisconnectNamedPipe(reinterpret_cast<HANDLE>(h)); CloseHandle(reinterpret_cast<HANDLE>(h)); return true; } bool Pipe::Open() { VLOG(2) << "Pipe::Open: " << pipe_name_; for (int i=0; i<30 * 5; i++) { HANDLE h = CreateFile(pipe_name_.c_str(), GENERIC_READ | GENERIC_WRITE, 0, // no sharing NULL, // default security attributes OPEN_EXISTING, // opens existing pipe 0, // default attributes NULL); // no template file if (h != INVALID_HANDLE_VALUE) { handle_ = h; VLOG(3) << "Pipe::Open: sucess opened: " << pipe_name_; return true; } // Exit if an error other than ERROR_PIPE_BUSY occurs. const auto e = GetLastError(); if (e != ERROR_PIPE_BUSY && e != ERROR_FILE_NOT_FOUND) { LOG(WARNING) << "Could not open pipe. Error: " << ErrorAsString(e); return false; } Sleep(200); } VLOG(3) << "Pipe::Open: exiting: " << pipe_name_; return false; } bool Pipe::WaitForClient(std::chrono::duration<double> timeout) { auto end = std::chrono::system_clock::now() + timeout; do { if (ConnectNamedPipe(handle_, nullptr) || GetLastError() == ERROR_PIPE_CONNECTED) { return true; } LOG(WARNING) << "WaitForClient: " << ErrorAsString(GetLastError()); Sleep(250); } while (std::chrono::system_clock::now() <= end); return false; } /** returns the number of bytes written on success */ std::optional<int> Pipe::write(const char* data, int size) { DWORD cbBytesWritten; if (WriteFile(handle_, data, size, &cbBytesWritten, NULL)) { return {cbBytesWritten}; } return std::nullopt; } /** returns the number of bytes read on success */ std::optional<int> Pipe::read(char* data, int size) { DWORD cbBytesRead; if (ReadFile(handle_, data, size, &cbBytesRead, NULL)) { return { cbBytesRead }; } return std::nullopt; } std::optional<char> Pipe::peek() { char ch; DWORD num_read, num_avail, num_leftmsg; if (PeekNamedPipe(handle_, &ch, 1, &num_read, &num_avail, &num_leftmsg) && num_read>0) { return {ch}; } return std::nullopt; } }
37.449275
107
0.54257
chwash
5d1fdb9098a26ffbb90585390d1e0170e62b5199
381
cpp
C++
JaraffeEngine_Vulkan/Engine/Core/HAL/Memory/Memory.cpp
Jaraffe-github/Old_Engines
0586d383af99cfcf076b18dace49e779a55b88e8
[ "BSD-3-Clause" ]
null
null
null
JaraffeEngine_Vulkan/Engine/Core/HAL/Memory/Memory.cpp
Jaraffe-github/Old_Engines
0586d383af99cfcf076b18dace49e779a55b88e8
[ "BSD-3-Clause" ]
null
null
null
JaraffeEngine_Vulkan/Engine/Core/HAL/Memory/Memory.cpp
Jaraffe-github/Old_Engines
0586d383af99cfcf076b18dace49e779a55b88e8
[ "BSD-3-Clause" ]
null
null
null
#include "stdafx.h" #include "Memory.h" #include "Allocator/TBB/TBBAllocator.h" Memory::Memory() { } Memory::~Memory() { } void* Memory::Malloc(size_t Size) { return TBBAllocator::Malloc(Size); } void* Memory::Realloc(void * Original, size_t Size) { return TBBAllocator::Realloc(Original, Size); } void Memory::Free(void * Original) { TBBAllocator::Free(Original); }
14.111111
51
0.692913
Jaraffe-github
5d27966fbc69a5632a823227cb78babd653e0a54
1,242
cpp
C++
src/21.merge-two-sorted-lists.cpp
Hilbert-Yaa/heil-my-lc
075567698e3b826a542f63389e9a8f3136df799a
[ "MIT" ]
null
null
null
src/21.merge-two-sorted-lists.cpp
Hilbert-Yaa/heil-my-lc
075567698e3b826a542f63389e9a8f3136df799a
[ "MIT" ]
null
null
null
src/21.merge-two-sorted-lists.cpp
Hilbert-Yaa/heil-my-lc
075567698e3b826a542f63389e9a8f3136df799a
[ "MIT" ]
null
null
null
/* * @lc app=leetcode id=21 lang=cpp * * [21] Merge Two Sorted Lists */ // @lc code=start #include <bits/stdc++.h> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ // struct ListNode { // int val; // ListNode *next; // ListNode() : val(0), next(nullptr) {} // ListNode(int x) : val(x), next(nullptr) {} // ListNode(int x, ListNode *next) : val(x), next(next) {} // }; class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { if (l1 == NULL) return l2; else if (l2 == NULL) return l1; else { if (l1->val < l2->val) { ListNode *l1_rest = l1->next; l1->next = mergeTwoLists(l1_rest, l2); return l1; } else { ListNode *l2_rest = l2->next; l2->next = mergeTwoLists(l2_rest, l1); return l2; } } } }; // @lc code=end
23.433962
62
0.477456
Hilbert-Yaa
5d285c8e05443687b6eb8b952a6370cea024b3cc
31,902
cpp
C++
himan-lib/source/numerical_functions.cpp
jrintala/fmi-data
625f0a44919e6406440349425ee0b3f1a64a923d
[ "MIT" ]
null
null
null
himan-lib/source/numerical_functions.cpp
jrintala/fmi-data
625f0a44919e6406440349425ee0b3f1a64a923d
[ "MIT" ]
null
null
null
himan-lib/source/numerical_functions.cpp
jrintala/fmi-data
625f0a44919e6406440349425ee0b3f1a64a923d
[ "MIT" ]
null
null
null
/** * @file numerical_functions.cpp */ #include "numerical_functions.h" #include "NFmiInterpolation.h" #include "plugin_factory.h" #include <algorithm> #define HIMAN_AUXILIARY_INCLUDE #include "fetcher.h" #include "neons.h" #include "radon.h" #undef HIMAN_AUXILIARY_INCLUDE using namespace himan; using namespace numerical_functions; integral::integral() : itsComplete(8, true) {} void integral::Params(std::vector<param> theParams) { itsParams = theParams; } void integral::Function(std::function<std::valarray<double>(const std::vector<std::valarray<double>>&)> theFunction) { itsFunction = theFunction; } const std::valarray<double>& integral::Result() const { assert(itsResult.size()); return itsResult; } void integral::Evaluate() { assert(Complete()); auto f = GET_PLUGIN(fetcher); std::vector<info_t> paramInfos; // Create a container that contains the parameter data. This container passed as an argument to the function that is // being integrated over. std::vector<std::valarray<double>> paramsData; std::valarray<double> previousLevelValue; std::valarray<double> currentLevelValue; std::valarray<double> previousLevelHeight; std::valarray<double> currentLevelHeight; std::valarray<bool> missingValueMask; for (int lvl = itsHighestLevel; lvl <= itsLowestLevel; ++lvl) { itsLevel.Value(lvl); // fetch parameters // for (param itsParam:itsParams) <-- only for g++ 4.8 for (unsigned int i = 0; i < itsParams.size(); i++) { param itsParam = itsParams[i]; paramInfos.push_back(f->Fetch(itsConfiguration, itsTime, itsLevel, itsParam, itsType, itsConfiguration->UseCudaForPacking())); paramsData.push_back( std::valarray<double>(paramInfos.back()->Data().Values().data(), paramInfos.back()->Data().Size())); // allocate result container if (!itsResult.size()) itsResult.resize(paramInfos.back()->Data().Size()); // initialize missingValueMask if (!missingValueMask.size()) missingValueMask = std::valarray<bool>(false, paramInfos.back()->Data().Size()); } // fetch height param heightParam; if (itsHeightInMeters) { heightParam = param("HL-M"); } else { heightParam = param("P-HPa"); } info_t heights = f->Fetch(itsConfiguration, itsTime, itsLevel, heightParam, itsType, itsConfiguration->UseCudaForPacking()); currentLevelHeight = std::valarray<double>(heights->Data().Values().data(), heights->Data().Size()); // mask for missing values auto missingValueMaskFunction = std::valarray<bool>(false, heights->Data().Size()); for (unsigned int i = 0; i < paramsData.size(); i++) { missingValueMaskFunction = (paramsData[i] == kFloatMissing || missingValueMaskFunction); } // evaluate integration function if (itsFunction) { currentLevelValue = itsFunction(paramsData); } else { // use first param if no function is given currentLevelValue = paramsData[0]; } // put missing values back in currentLevelValue[missingValueMaskFunction] = kFloatMissing; // update mask of missing values in the result of the integral missingValueMask = (currentLevelHeight == kFloatMissing || currentLevelValue == kFloatMissing || missingValueMask); // move data from current level to previous level if (lvl == itsLowestLevel) { previousLevelHeight = std::move(currentLevelHeight); previousLevelValue = std::move(currentLevelValue); continue; } // perform trapezoideal integration // std::valarray<bool> lowerBoundMask; std::valarray<bool> upperBoundMask; std::valarray<bool> insideBoundsMask; // vectorized form of trapezoideal integration if (itsHeightInMeters) { lowerBoundMask = (previousLevelHeight > itsLowerBound && currentLevelHeight < itsLowerBound); upperBoundMask = (previousLevelHeight > itsUpperBound && currentLevelHeight < itsUpperBound); insideBoundsMask = (previousLevelHeight <= itsUpperBound && currentLevelHeight >= itsLowerBound); } else // height in Pascal { lowerBoundMask = (previousLevelHeight < itsLowerBound && currentLevelHeight > itsLowerBound); upperBoundMask = (previousLevelHeight < itsUpperBound && currentLevelHeight > itsUpperBound); insideBoundsMask = (previousLevelHeight >= itsUpperBound && currentLevelHeight <= itsLowerBound); } // TODO Perhaps it is better to cast valarrays from the mask_array before this step. According to Stroustrup all // operators and mathematical function can be applied to mask_array as well. Unfortunately not the case. itsResult[upperBoundMask] += (Interpolate(std::valarray<double>(currentLevelValue[upperBoundMask]), std::valarray<double>(previousLevelValue[upperBoundMask]), std::valarray<double>(currentLevelHeight[upperBoundMask]), std::valarray<double>(previousLevelHeight[upperBoundMask]), std::valarray<double>(itsUpperBound[upperBoundMask])) + std::valarray<double>(currentLevelValue[upperBoundMask])) / 2 * (std::valarray<double>(itsUpperBound[upperBoundMask]) - std::valarray<double>(currentLevelHeight[upperBoundMask])); itsResult[lowerBoundMask] += (Interpolate(std::valarray<double>(currentLevelValue[lowerBoundMask]), std::valarray<double>(previousLevelValue[lowerBoundMask]), std::valarray<double>(currentLevelHeight[lowerBoundMask]), std::valarray<double>(previousLevelHeight[lowerBoundMask]), std::valarray<double>(itsLowerBound[lowerBoundMask])) + std::valarray<double>(previousLevelValue[lowerBoundMask])) / 2 * (std::valarray<double>(previousLevelHeight[lowerBoundMask]) - std::valarray<double>(itsLowerBound[lowerBoundMask])); itsResult[insideBoundsMask] += (std::valarray<double>(previousLevelValue[insideBoundsMask]) + std::valarray<double>(currentLevelValue[insideBoundsMask])) / 2 * (std::valarray<double>(previousLevelHeight[insideBoundsMask]) - std::valarray<double>(currentLevelHeight[insideBoundsMask])); // serial version of trapezoideal integration /* for (size_t i=0; i<paramInfos.back()->Data().Size(); ++i) { // value is below the lowest limit if (itsHeightInMeters && previousLevelHeight[i] > itsLowerBound[i] && currentLevelHeight[i] < itsLowerBound[i] || !itsHeightInMeters && previousLevelHeight[i] < itsLowerBound[i] && currentLevelHeight[i] > itsLowerBound[i]) { double lowerValue = previousLevelValue[i]+(currentLevelValue[i]-previousLevelValue[i])*(itsLowerBound[i]-previousLevelHeight[i])/(currentLevelHeight[i]-previousLevelHeight[i]); itsResult[i] += (lowerValue + previousLevelValue[i]) / 2 * (previousLevelHeight[i] - itsLowerBound[i]); } // value is above the highest limit else if (itsHeightInMeters && previousLevelHeight[i] > itsUpperBound[i] && currentLevelHeight[i] < itsUpperBound[i] || !itsHeightInMeters && previousLevelHeight[i] < itsUpperBound[i] && currentLevelHeight[i] > itsUpperBound[i]) { double upperValue = previousLevelValue[i]+(currentLevelValue[i]-previousLevelValue[i])*(itsUpperBound[i]-previousLevelHeight[i])/(currentLevelHeight[i]-previousLevelHeight[i]); itsResult[i] += (upperValue + currentLevelValue[i]) / 2 * (itsUpperBound[i] - currentLevelHeight[i]); } else if (itsHeightInMeters && previousLevelHeight[i] <= itsUpperBound[i] && currentLevelHeight[i] >= itsLowerBound[i] || !itsHeightInMeters && previousLevelHeight[i] >= itsUpperBound[i] && currentLevelHeight[i] <= itsLowerBound[i]) { itsResult[i] += (previousLevelValue[i] + currentLevelValue[i]) / 2 * (previousLevelHeight[i] - currentLevelHeight[i]); } }*/ // move data from current level to previous level at the end of the integration step previousLevelHeight = std::move(currentLevelHeight); previousLevelValue = std::move(currentLevelValue); paramInfos.clear(); paramsData.clear(); } // Insert missing values into result itsResult[missingValueMask] = kFloatMissing; } void integral::LowerBound(const std::valarray<double>& theLowerBound) { itsComplete[0] = true; itsLowerBound = theLowerBound; } void integral::UpperBound(const std::valarray<double>& theUpperBound) { itsComplete[1] = true; itsUpperBound = theUpperBound; } void integral::LowerLevelLimit(int theLowestLevel) { itsComplete[2] = true; itsLowestLevel = theLowestLevel; } void integral::UpperLevelLimit(int theHighestLevel) { itsComplete[3] = true; itsHighestLevel = theHighestLevel; } void integral::SetLevelLimits() { assert(itsComplete[0] && itsComplete[1]); producer prod = itsConfiguration->SourceProducer(0); double max_value = itsHeightInMeters ? itsUpperBound.max() : itsUpperBound.min(); double min_value = itsHeightInMeters ? itsLowerBound.min() : itsLowerBound.max(); if (max_value == kFloatMissing || min_value == kFloatMissing) { // itsLogger->Error("Min or max values of given heights are missing"); throw kFileDataNotFound; } auto levelsForMaxHeight = LevelForHeight(prod, max_value); auto levelsForMinHeight = LevelForHeight(prod, min_value); itsHighestLevel = static_cast<int>(levelsForMaxHeight.second.Value()); itsLowestLevel = static_cast<int>(levelsForMinHeight.first.Value()); assert(itsLowestLevel >= itsHighestLevel); itsComplete[2] = true; itsComplete[3] = true; } void integral::ForecastType(forecast_type theType) { itsComplete[4] = true; itsType = theType; } void integral::ForecastTime(forecast_time theTime) { itsComplete[5] = true; itsTime = theTime; } void integral::LevelType(level theLevel) { itsComplete[6] = true; itsLevel = theLevel; } void integral::HeightInMeters(bool theHeightInMeters) { itsComplete[7] = true; itsHeightInMeters = theHeightInMeters; } // TODO add check that all information that is needed is given to the class object bool integral::Complete() { return std::all_of(itsComplete.begin(), itsComplete.end(), [](bool i) { return i == true; }); } std::pair<level, level> integral::LevelForHeight(const producer& prod, double height) const { using boost::lexical_cast; long producerId = 0; // Hybrid level heights are calculated by himan, so coalesce the related // forecast producer id with the himan producer id. switch (prod.Id()) { case 1: case 230: producerId = 230; break; case 131: case 240: producerId = 240; break; case 199: case 210: producerId = 210; break; default: // itsLogger->Error("Unsupported producer for hitool::LevelForHeight(): " + lexical_cast<std::string> // (prod.Id())); break; } std::stringstream query; if (itsHeightInMeters) { query << "SELECT min(CASE WHEN maximum_height <= " << height << " THEN level_value ELSE NULL END) AS lowest_level, " << "max(CASE WHEN minimum_height >= " << height << " THEN level_value ELSE NULL END) AS highest_level " << "FROM " << "hybrid_level_height " << "WHERE " << "producer_id = " << producerId; } else { // Add/subtract 1 already in the query, since due to the composition of the query it will return // the first level that is higher than lower height and vice versa query << "SELECT max(CASE WHEN minimum_pressure <= " << height << " THEN level_value+1 ELSE NULL END) AS lowest_level, " << "min(CASE WHEN maximum_pressure >= " << height << " THEN level_value-1 ELSE NULL END) AS highest_level " << "FROM " << "hybrid_level_height " << "WHERE " << "producer_id = " << producerId; ; } HPDatabaseType dbtype = itsConfiguration->DatabaseType(); std::vector<std::string> row; long absolutelowest = kHPMissingInt; long absolutehighest = kHPMissingInt; if (dbtype == kNeons || dbtype == kNeonsAndRadon) { auto n = GET_PLUGIN(neons); n->NeonsDB().Query(query.str()); row = n->NeonsDB().FetchRow(); absolutelowest = lexical_cast<long>(n->ProducerMetaData(prod.Id(), "last hybrid level number")); absolutehighest = lexical_cast<long>(n->ProducerMetaData(prod.Id(), "first hybrid level number")); } if (row.empty() && (dbtype == kRadon || dbtype == kNeonsAndRadon)) { auto r = GET_PLUGIN(radon); r->RadonDB().Query(query.str()); row = r->RadonDB().FetchRow(); absolutelowest = lexical_cast<long>(r->RadonDB().GetProducerMetaData(prod.Id(), "last hybrid level number")); absolutehighest = lexical_cast<long>(r->RadonDB().GetProducerMetaData(prod.Id(), "first hybrid level number")); } long newlowest = absolutelowest, newhighest = absolutehighest; if (!row.empty()) { // If requested height is below lowest level (f.ex. 0 meters) or above highest (f.ex. 80km) // database query will return null if (row[0] != "") { // SQL query returns the level value that precedes the requested value. // For first hybrid level (the highest ie max), get one level above the max level if possible // For last hybrid level (the lowest ie min), get one level below the min level if possible // This means that we have a buffer of three levels for both directions! newlowest = lexical_cast<long>(row[0]) + 1; if (newlowest > absolutelowest) { newlowest = absolutelowest; } } if (row[1] != "") { newhighest = lexical_cast<long>(row[1]) - 1; if (newhighest < absolutehighest) { newhighest = absolutehighest; } } if (newhighest > newlowest) { newhighest = newlowest; } } assert(newlowest >= newhighest); return std::make_pair<level, level>(level(kHybrid, newlowest), level(kHybrid, newhighest)); } matrix<double> numerical_functions::Filter2D(const matrix<double>& A, const matrix<double>& B) { // find center position of kernel (half of kernel size) matrix<double> ret(A.SizeX(), A.SizeY(), 1, A.MissingValue()); double convolution_value; // accumulated value of the convolution at a given grid point in A double kernel_weight_sum; // accumulated value of the kernel weights in B that are used to compute the convolution // at given point A int ASizeX = int(A.SizeX()); int ASizeY = int(A.SizeY()); int BSizeX = int(B.SizeX()); int BSizeY = int(B.SizeY()); int kCenterX = BSizeX / 2; int kCenterY = BSizeY / 2; // check if data contains missing values if (A.MissingCount() == 0) // if no missing values in the data we can use a faster algorithm { // calculate for inner field // the weights are used as given on input // assert (sum(B) == 1) for (int j = kCenterY; j < ASizeY - kCenterY; ++j) // columns { for (int i = kCenterX; i < ASizeX - kCenterX; ++i) // rows { convolution_value = 0; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); convolution_value += A.At(ii, jj, 0) * B.At(mm, nn, 0); } } const size_t index = ret.Index(i, j, 0); ret[index] = convolution_value; } } // treat boundaries separately // weights get adjusted so that the sum of weights for the active part of the kernel remains 1 // calculate for upper boundary for (int j = 0; j < kCenterY; ++j) // columns { for (int i = 0; i < ASizeX; ++i) // rows { convolution_value = 0; kernel_weight_sum = 0; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { convolution_value += A.At(ii, jj, 0) * B.At(mm, nn, 0); kernel_weight_sum += B.At(mm, nn, 0); } } } const size_t index = ret.Index(i, j, 0); ret[index] = convolution_value / kernel_weight_sum; } } // calculate for lower boundary for (int j = ASizeY - kCenterY; j < ASizeY; ++j) // columns { for (int i = 0; i < ASizeX; ++i) // rows { convolution_value = 0; kernel_weight_sum = 0; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { convolution_value += A.At(ii, jj, 0) * B.At(mm, nn, 0); kernel_weight_sum += B.At(mm, nn, 0); } } } const size_t index = ret.Index(i, j, 0); ret[index] = convolution_value / kernel_weight_sum; } } // calculate for left boundary for (int j = 0; j < ASizeY; ++j) // columns { for (int i = 0; i < kCenterX; ++i) // rows { convolution_value = 0; kernel_weight_sum = 0; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { convolution_value += A.At(ii, jj, 0) * B.At(mm, nn, 0); kernel_weight_sum += B.At(mm, nn, 0); } } } const size_t index = ret.Index(i, j, 0); ret[index] = convolution_value / kernel_weight_sum; } } // calculate for right boundary for (int j = 0; j < ASizeY; ++j) // columns { for (int i = ASizeX - kCenterX; i < ASizeX; ++i) // rows { convolution_value = 0; kernel_weight_sum = 0; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { convolution_value += A.At(ii, jj, 0) * B.At(mm, nn, 0); kernel_weight_sum += B.At(mm, nn, 0); } } } const size_t index = ret.Index(i, j, 0); ret[index] = convolution_value / kernel_weight_sum; } } } else // data contains missing values { std::cout << "util::Filter2D: Data contains missing values -> Choosing slow algorithm." << std::endl; double kernel_missing_count; for (int j = 0; j < ASizeY; ++j) // columns { for (int i = 0; i < ASizeX; ++i) // rows { convolution_value = 0; kernel_weight_sum = 0; kernel_missing_count = 0; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { if (A.IsMissing(ii, jj, 0)) { kernel_missing_count++; continue; } convolution_value += A.At(ii, jj, 0) * B.At(mm, nn, 0); kernel_weight_sum += B.At(mm, nn, 0); } } } if (kernel_missing_count < 3) { const size_t index = ret.Index(i, j, 0); ret[index] = convolution_value / kernel_weight_sum; } else { const size_t index = ret.Index(i, j, 0); ret[index] = himan::kFloatMissing; } } } } return ret; } himan::matrix<double> numerical_functions::Max2D(const himan::matrix<double>& A, const himan::matrix<double>& B) { using himan::kFloatMissing; // find center position of kernel (half of kernel size) himan::matrix<double> ret(A.SizeX(), A.SizeY(), 1, A.MissingValue()); double max_value; // maximum value of the convolution int ASizeX = int(A.SizeX()); int ASizeY = int(A.SizeY()); int BSizeX = int(B.SizeX()); int BSizeY = int(B.SizeY()); int kCenterX = BSizeX / 2; int kCenterY = BSizeY / 2; // calculate for inner field // the weights are used as given on input // assert (sum(B) == 1) assert(B.MissingCount() == 0); for (int j = kCenterY; j < ASizeY - kCenterY; ++j) // columns { for (int i = kCenterX; i < ASizeX - kCenterX; ++i) // rows { max_value = -1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { max_value = fmax(a * b, max_value); } } } const size_t index = ret.Index(i, j, 0); ret[index] = (max_value == -1e38 ? kFloatMissing : max_value); } } // treat boundaries separately // calculate for upper boundary for (int j = 0; j < kCenterY; ++j) // columns { for (int i = 0; i < ASizeX; ++i) // rows { max_value = -1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { max_value = fmax(a * b, max_value); } } } } const size_t index = ret.Index(i, j, 0); ret[index] = (max_value == -1e38 ? kFloatMissing : max_value); } } // calculate for lower boundary for (int j = ASizeY - kCenterY; j < ASizeY; ++j) // columns { for (int i = 0; i < ASizeX; ++i) // rows { max_value = -1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { max_value = fmax(a * b, max_value); } } } } const size_t index = ret.Index(i, j, 0); ret[index] = (max_value == -1e38 ? kFloatMissing : max_value); } } // calculate for left boundary for (int j = 0; j < ASizeY; ++j) // columns { for (int i = 0; i < kCenterX; ++i) // rows { max_value = -1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { max_value = fmax(a * b, max_value); } } } } const size_t index = ret.Index(i, j, 0); ret[index] = (max_value == -1e38 ? kFloatMissing : max_value); } } // calculate for right boundary for (int j = 0; j < ASizeY; ++j) // columns { for (int i = ASizeX - kCenterX; i < ASizeX; ++i) // rows { max_value = -1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { max_value = fmax(a * b, max_value); } } } } const size_t index = ret.Index(i, j, 0); ret[index] = (max_value == -1e38 ? kFloatMissing : max_value); } } return ret; } himan::matrix<double> numerical_functions::Min2D(const himan::matrix<double>& A, const himan::matrix<double>& B) { using himan::kFloatMissing; // find center position of kernel (half of kernel size) himan::matrix<double> ret(A.SizeX(), A.SizeY(), 1, A.MissingValue()); double min_value; // minimum value of the convolution int ASizeX = int(A.SizeX()); int ASizeY = int(A.SizeY()); int BSizeX = int(B.SizeX()); int BSizeY = int(B.SizeY()); int kCenterX = BSizeX / 2; int kCenterY = BSizeY / 2; // calculate for inner field // the weights are used as given on input // assert (sum(B) == 1) assert(B.MissingCount() == 0); for (int j = kCenterY; j < ASizeY - kCenterY; ++j) // columns { for (int i = kCenterX; i < ASizeX - kCenterX; ++i) // rows { min_value = 1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { min_value = fmin(a * b, min_value); } } } const size_t index = ret.Index(i, j, 0); ret[index] = (min_value == 1e38 ? kFloatMissing : min_value); } } // treat boundaries separately // calculate for upper boundary for (int j = 0; j < kCenterY; ++j) // columns { for (int i = 0; i < ASizeX; ++i) // rows { min_value = 1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { min_value = fmin(a * b, min_value); } } } } const size_t index = ret.Index(i, j, 0); ret[index] = (min_value == 1e38 ? kFloatMissing : min_value); } } // calculate for lower boundary for (int j = ASizeY - kCenterY; j < ASizeY; ++j) // columns { for (int i = 0; i < ASizeX; ++i) // rows { min_value = 1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { min_value = fmin(a * b, min_value); } } } } const size_t index = ret.Index(i, j, 0); ret[index] = (min_value == 1e38 ? kFloatMissing : min_value); } } // calculate for left boundary for (int j = 0; j < ASizeY; ++j) // columns { for (int i = 0; i < kCenterX; ++i) // rows { min_value = 1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { min_value = fmin(a * b, min_value); } } } } const size_t index = ret.Index(i, j, 0); ret[index] = (min_value == 1e38 ? kFloatMissing : min_value); } } // calculate for right boundary for (int j = 0; j < ASizeY; ++j) // columns { for (int i = ASizeX - kCenterX; i < ASizeX; ++i) // rows { min_value = 1e38; for (int n = 0; n < BSizeY; ++n) // kernel columns { int nn = BSizeY - 1 - n; // column index of flipped kernel for (int m = 0; m < BSizeX; ++m) // kernel rows { int mm = BSizeX - 1 - m; // row index of flipped kernel // index of input signal, used for checking boundary int ii = i + (m - kCenterX); int jj = j + (n - kCenterY); // ignore input samples which are out of bound if (ii >= 0 && ii < ASizeX && jj >= 0 && jj < ASizeY) { const double a = A.At(ii, jj, 0); const double b = B.At(mm, nn, 0); if (a != kFloatMissing && b != 0) { min_value = fmin(a * b, min_value); } } } } const size_t index = ret.Index(i, j, 0); ret[index] = (min_value == 1e38 ? kFloatMissing : min_value); } } return ret; }
30.267552
158
0.602721
jrintala
5d291df80b68d4fcad10ee06346300cdf51ef886
826
cpp
C++
LitusEngine/src/Litus/Renderer/Renderer.cpp
LitusLuca/LitusEngine
10abe5ea8ed47ed70ade989b1c53dc65da3be192
[ "Unlicense" ]
1
2021-08-31T08:54:07.000Z
2021-08-31T08:54:07.000Z
LitusEngine/src/Litus/Renderer/Renderer.cpp
LitusLuca/LitusEngine
10abe5ea8ed47ed70ade989b1c53dc65da3be192
[ "Unlicense" ]
null
null
null
LitusEngine/src/Litus/Renderer/Renderer.cpp
LitusLuca/LitusEngine
10abe5ea8ed47ed70ade989b1c53dc65da3be192
[ "Unlicense" ]
null
null
null
#include "pch.h" #include "Renderer.h" namespace LT { Renderer::SceneData* Renderer::s_sceneData = new Renderer::SceneData; void Renderer::Init() { RenderCommand::Init(); } void Renderer::Shutdown() { } void Renderer::OnWindowResize(uint32_t width, uint32_t height) { RenderCommand::SetViewPort(0, 0, width, height); } void Renderer::BeginScene(glm::mat4 viewProjectionMatrix) { s_sceneData->ViewProjectionMatrix = viewProjectionMatrix; } void Renderer::EndScene() { } void Renderer::Submit(const Ref<Shader>& shader, const Ref<VertexArray>& vertexArray, const glm::mat4& transform) { shader->Bind(); shader->SetMat4("u_viewProjection", s_sceneData->ViewProjectionMatrix); shader->SetMat4("u_modelMatrix", transform); vertexArray->Bind(); RenderCommand::DrawIndexed(vertexArray); } }
21.179487
114
0.727603
LitusLuca
5d2934fd2c9b9fdc8485ed81ffa83fd4c4daa73c
8,594
cpp
C++
src/wrapper.cpp
mtth/level2
06b3d0000e845317fb28ff00ad7c1776d015996f
[ "MIT" ]
null
null
null
src/wrapper.cpp
mtth/level2
06b3d0000e845317fb28ff00ad7c1776d015996f
[ "MIT" ]
null
null
null
src/wrapper.cpp
mtth/level2
06b3d0000e845317fb28ff00ad7c1776d015996f
[ "MIT" ]
null
null
null
#include "codecs.hpp" #include "wrapper.hpp" #include <chrono> namespace Layer2 { #define LAYER2_BUFFER_SIZE 1024 // Black hole array used to write any overflowing data. We must use this since // Avro's encoder will throw an error when it tries to write and the underlying // stream is full. Since this might happen at every loop, it is cheaper to fake // a successful write rather than catch (which might also have side-effects). static uint8_t BUFFER[LAYER2_BUFFER_SIZE] = {0}; /** * Helper class to handle encoding Avro records to a JavaScript buffer. * */ class BufferOutputStream : public avro::OutputStream { public: enum State { ALMOST_EMPTY, ALMOST_FULL, FULL }; static BufferOutputStream *fromBuffer( v8::Local<v8::Value> buf, float loadFactor ) { if (!node::Buffer::HasInstance(buf)) { return NULL; } v8::Local<v8::Object> obj = buf->ToObject(); uint8_t *data = (uint8_t *) node::Buffer::Data(obj); size_t len = node::Buffer::Length(obj); return new BufferOutputStream(data, len, loadFactor); } BufferOutputStream(uint8_t *data, size_t len, float loadFactor) : _data(data), _len(len), _hwm(len *loadFactor), _pos(0) {}; ~BufferOutputStream() {}; virtual bool next(uint8_t **data, size_t *len) { if (_pos < _hwm) { *data = _data + _pos; *len = _hwm - _pos; _pos = _hwm; } else if (_pos < _len) { *data = _data + _pos; *len = _len - _pos; _pos = _len; } else { *data = BUFFER; *len = LAYER2_BUFFER_SIZE; _pos = _len + 1; } return true; } virtual void backup(size_t len) { _pos -= len; } virtual void flush() {} virtual uint64_t byteCount() const { return _pos; } State getState() const { if (_pos < _len) { return State::ALMOST_EMPTY; } if (_pos == _len) { return State::ALMOST_FULL; } return State::FULL; } private: uint8_t *_data; size_t _len; size_t _hwm; // High watermark. size_t _pos; }; /** * Helper class to handle asynchronous PDU capture. * */ class Worker : public Nan::AsyncWorker { public: Worker(Wrapper *wrapper, v8::Local<v8::Value> buf, Nan::Callback *callback) : AsyncWorker(callback), _wrapper(wrapper), _stream(BufferOutputStream::fromBuffer(buf, 0.9)), _numPdus(0) { _wrapper->_encoder->init(*_stream); } ~Worker() {} void Execute() { std::chrono::time_point<std::chrono::high_resolution_clock> start, current; start = std::chrono::high_resolution_clock::now(); // First, check whether we have a backlogged PDU. if (_wrapper->_packet.pdu()) { avro::encode(*_wrapper->_encoder, _wrapper->_packet); delete _wrapper->_packet.release_pdu(); switch (_stream->getState()) { case BufferOutputStream::State::FULL: SetErrorMessage("buffer too small"); case BufferOutputStream::State::ALMOST_FULL: return; default: ; // Else we have room for more. } } while (true) { Tins::Packet packet(_wrapper->_sniffer->next_packet()); if (!packet) { return; } _numPdus++; avro::encode(*_wrapper->_encoder, packet); switch (_stream->getState()) { case BufferOutputStream::State::FULL: // There wasn't enough room, we have to save the PDU until the next // call (otherwise it will never be transmitted). _wrapper->_packet = packet; --_numPdus; case BufferOutputStream::State::ALMOST_FULL: return; default: // Otherwise, continue looping if the timeout hasn't been reached. current = std::chrono::high_resolution_clock::now(); if ( _wrapper->_timeout && std::chrono::duration_cast<std::chrono::milliseconds>(current - start).count() > _wrapper->_timeout ) { return; } } } } void HandleOKCallback() { Nan::HandleScope scope; // We have to call this to prevent the encoder from resetting the stream // after it has been deleted. _wrapper->_encoder->init(*_stream); v8::Local<v8::Value> argv[] = { Nan::Null(), Nan::New<v8::Number>(_numPdus) }; callback->Call(2, argv); } void HandleErrorCallback() { Nan::HandleScope scope; _wrapper->_encoder->init(*_stream); v8::Local<v8::Value> argv[] = { v8::Exception::Error(Nan::New<v8::String>(ErrorMessage()).ToLocalChecked()) }; callback->Call(1, argv); } private: Wrapper *_wrapper; std::unique_ptr<BufferOutputStream> _stream; uint32_t _numPdus; }; // v8 exposed functions. /** * JavaScript constructor. * * It should always be followed by exactly one call, either to `FromInterface` * or to `FromFile`. Behavior otherwise is undefined. * */ NAN_METHOD(Wrapper::Empty) {} /** * Destructor. * * This is required to close the capture handle deterministically. * */ NAN_METHOD(Wrapper::Destroy) { Wrapper *wrapper = ObjectWrap::Unwrap<Wrapper>(info.This()); wrapper->_sniffer.reset(); } NAN_METHOD(Wrapper::FromInterface) { if ( info.Length() != 7 || !info[0]->IsString() || !(info[1]->IsUndefined() || info[1]->IsUint32()) || // snaplen !(info[2]->IsUndefined() || info[2]->IsBoolean()) || // promisc !(info[3]->IsUndefined() || info[3]->IsBoolean()) || // rfmon !(info[4]->IsUndefined() || info[4]->IsUint32()) || // timeout !(info[5]->IsUndefined() || info[5]->IsUint32()) || // bufferSize !(info[6]->IsUndefined() || info[6]->IsString()) // filter ) { Nan::ThrowError("invalid arguments"); return; } // The device to listen on. Nan::Utf8String dev(info[0]); // Prepare the configuration, only overriding system defaults when a value // has been specified. Tins::SnifferConfiguration config; uint32_t timeout = 0; if (!info[1]->IsUndefined()) { config.set_snap_len(info[1]->Uint32Value()); } if (!info[2]->IsUndefined()) { config.set_promisc_mode(info[2]->BooleanValue()); } if (!info[3]->IsUndefined()) { config.set_rfmon(info[3]->BooleanValue()); } if (!info[4]->IsUndefined()) { timeout = info[4]->Uint32Value(); config.set_timeout(timeout); } if (!info[5]->IsUndefined()) { config.set_buffer_size(info[5]->Uint32Value()); } if (!info[6]->IsUndefined()) { Nan::Utf8String filter(info[6]); config.set_filter(std::string(*filter)); } Tins::Sniffer *sniffer; try { sniffer = new Tins::Sniffer(*dev, config); } catch (std::runtime_error &err) { Nan::ThrowError(err.what()); return; } Wrapper *wrapper = new Wrapper(sniffer, timeout); wrapper->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_METHOD(Wrapper::FromFile) { if ( info.Length() != 2 || !info[0]->IsString() || !(info[1]->IsUndefined() || info[1]->IsString()) // filter ) { Nan::ThrowError("invalid arguments"); return; } // The file to open. Nan::Utf8String path(info[0]); Tins::SnifferConfiguration config; if (!info[1]->IsUndefined()) { Nan::Utf8String filter(info[1]); config.set_filter(std::string(*filter)); } Tins::FileSniffer *sniffer; try { sniffer = new Tins::FileSniffer(*path, config); } catch (std::runtime_error &err) { Nan::ThrowError(err.what()); return; } Wrapper *wrapper = new Wrapper(sniffer, 0); wrapper->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_METHOD(Wrapper::GetPdus) { if ( info.Length() != 2 || !node::Buffer::HasInstance(info[0]) || !info[1]->IsFunction() ) { Nan::ThrowError("invalid arguments"); return; } Wrapper *wrapper = ObjectWrap::Unwrap<Wrapper>(info.This()); Nan::Callback *callback = new Nan::Callback(info[1].As<v8::Function>()); Worker *worker = new Worker(wrapper, info[0], callback); worker->SaveToPersistent("buffer", info[0]); worker->SaveToPersistent("wrapper", info.This()); Nan::AsyncQueueWorker(worker); } /** * Initializer, returns the `Wrapper` JavaScript function template. * */ v8::Local<v8::FunctionTemplate> Wrapper::Init() { v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(Wrapper::Empty); tpl->SetClassName(Nan::New("Wrapper").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "destroy", Wrapper::Destroy); Nan::SetPrototypeMethod(tpl, "getPdus", Wrapper::GetPdus); Nan::SetPrototypeMethod(tpl, "fromInterface", Wrapper::FromInterface); Nan::SetPrototypeMethod(tpl, "fromFile", Wrapper::FromFile); return tpl; } }
27.025157
109
0.634047
mtth
5d31c1d232365f09296bdfe918a3464bdcc7a0e1
933
cpp
C++
LLY/LLY/resource/track.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
3
2015-07-04T03:35:51.000Z
2017-09-10T08:23:25.000Z
LLY/LLY/resource/track.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
null
null
null
LLY/LLY/resource/track.cpp
ooeyusea/GameEngine
85e7ceef7ddf663f9601a8a8787e29e8e8cdb425
[ "MIT" ]
null
null
null
#include "track.h" #include "key_frame.h" namespace lly { void Track::get_interpolate_frame(KeyFrame& frame) { if (_frames.empty()) throw std::logic_error("empty frame"); size_t i = 0; while (i < _frames.size()) { if (frame.get_time_pos() < _frames[i]->get_time_pos()) { break; } ++i; } if (i == _frames.size()) { frame.interpolate_from(_frames[i - 1], _frames[i - 1]); } else if (i == 0) { frame.interpolate_from(_frames[i], _frames[i]); } else frame.interpolate_from(_frames[i - 1], _frames[i]); } void NodeTrack::apply(Skeleton* skeleton, float time_pos, float weight) { TransformFrame frame(time_pos); get_interpolate_frame(frame); frame.apply(skeleton, this, weight); } }
22.756098
75
0.511254
ooeyusea
5d355b7d3457b981c51217959ecf409e4bf68af5
3,750
hpp
C++
TextEditor/Components/MenuBehaviourVertical.hpp
itravers/CS211-TextEditor
47ddf2745f54ae826a96209eb767fe8280f4ce30
[ "Apache-2.0" ]
null
null
null
TextEditor/Components/MenuBehaviourVertical.hpp
itravers/CS211-TextEditor
47ddf2745f54ae826a96209eb767fe8280f4ce30
[ "Apache-2.0" ]
42
2019-09-27T16:46:52.000Z
2019-12-06T18:39:18.000Z
TextEditor/Components/MenuBehaviourVertical.hpp
itravers/CS211-TextEditor
47ddf2745f54ae826a96209eb767fe8280f4ce30
[ "Apache-2.0" ]
null
null
null
#/******************************************************************************** * Isaac Travers * CIS 211 - Data Structures * October 13th, 2019 * * MenuBehaviourVertical.hpp: Extends menu behaviour * responsible for rendering a menu in a vertical * format. *********************************************************************************/ #ifndef MENU_BEHAVIOUR_VERTICAL_HPP #define MENU_BEHAVIOUR_VERTICAL_HPP #include "MenuBehaviour.hpp" //we are defining a class in the namespace TextEditorNamespace namespace TextEditorNamespace { //class EditorWindow; //we are defining a MenuBehaviour class MenuBehaviourVertical : public MenuBehaviour { //We'll be extending this class later, these will be private for extended classes protected: //These will be public for all extended classes public: //constructor MenuBehaviourVertical(vector<string>& _buf) :MenuBehaviour(_buf) { //you know nothing jon snow } /******************************************************************************* * Function Name: menuClicked() * Purpose: Extending classes will need to implement their own menuClicked * If a Menu is clicked this should return the index of that * menu. If a menu is not clicked, it should return -1. *******************************************************************************/ virtual int menuClicked(MEVENT* mEvent, vector<string> items, bool has_border, Location loc) { int returnVal = -1; //returns -1 if the menu was not clicked int margin = 0; //the difference between the left most buffer area and the left most screen area if (has_border)margin++; //if we have a border the margin is increased by 1 int y = loc.y + margin; //check to make sure we have clicked on an item if (mEvent->y >= loc.y + margin && mEvent->y <= loc.y + margin + items.size() - 1) { //we have clicked in the menu //int candidate_returnVal = mEvent->y - margin; int candidate_returnVal = mEvent->y - loc.y - margin; //now check that we are actually clicking on a word itself int startx = loc.x + margin; int endx = startx + items[candidate_returnVal].size() - 1; //check if we are within x values if (mEvent->x >= startx && mEvent->x <= endx) { //we are, set this index as our return index. returnVal = candidate_returnVal; } } return returnVal; } /******************************************************************************* * Function Name: render() * Purpose: Renders the menu in a vertical format *******************************************************************************/ virtual void render(vector<string> items) { // here is were we will do our horizontal rendering for (int i = 0; i < items.size(); i++) { imprintStringOnBuffer(items[i], i, 0); } } /******************************************************************************* * Function Name: getLocationOfItem(string item) * Purpose: Returns the location of the first character * of a menu item *******************************************************************************/ virtual Location getLocationOfItem(int itemNum, int totalItems, bool has_border, Location loc) { int margin = 0; //the difference between the left most buffer area and the left most screen area if (has_border)margin++; //if we have a border the margin is increased by 1 return Location{loc.y+itemNum+margin, loc.x}; } //These will not be available to extended classes, or anyone else. private: }; // end class MenuBehaviourHorizontal } // end TextEditorNamespace #endif
36.764706
101
0.5536
itravers
5d35c3bd930015c52e381c74f9e17899e0d65a51
18,331
hpp
C++
source/zisc/core/zisc/thread/atomic-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
2
2017-10-18T13:24:11.000Z
2018-05-15T00:40:52.000Z
source/zisc/core/zisc/thread/atomic-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
9
2016-09-05T11:07:03.000Z
2019-07-05T15:31:04.000Z
source/zisc/core/zisc/thread/atomic-inl.hpp
byzin/Zisc
c74f50c51f82c847f39a603607d73179004436bb
[ "MIT" ]
null
null
null
/*! \file atomic-inl.hpp \author Sho Ikeda \brief No brief description \details No detailed description. \copyright Copyright (c) 2015-2021 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef ZISC_ATOMIC_INL_HPP #define ZISC_ATOMIC_INL_HPP #include "atomic.hpp" // Standard C++ library #include <condition_variable> #include <atomic> #include <cstddef> #include <mutex> #include <type_traits> #include <utility> // Zisc #include "zisc/concepts.hpp" #include "zisc/non_copyable.hpp" #include "zisc/utility.hpp" #include "zisc/zisc_config.hpp" namespace zisc { /*! \details No detailed description \param [in] order No description. \return No description */ inline constexpr auto Atomic::castMemOrder(const std::memory_order order) noexcept { #if defined(Z_CLANG) using OrderT = decltype(__ATOMIC_SEQ_CST); // memory order value check static_assert(__ATOMIC_RELAXED == zisc::cast<OrderT>(std::memory_order::relaxed)); static_assert(__ATOMIC_CONSUME == zisc::cast<OrderT>(std::memory_order::consume)); static_assert(__ATOMIC_ACQUIRE == zisc::cast<OrderT>(std::memory_order::acquire)); static_assert(__ATOMIC_RELEASE == zisc::cast<OrderT>(std::memory_order::release)); static_assert(__ATOMIC_ACQ_REL == zisc::cast<OrderT>(std::memory_order::acq_rel)); static_assert(__ATOMIC_SEQ_CST == zisc::cast<OrderT>(std::memory_order::seq_cst)); return cast<OrderT>(order); #else // Z_CLANG return order; #endif // Z_CLANG } /*! \details No detailed description \tparam Type No description. \param [out] ptr No description. \param [in] value No description. \param [in] order No description. */ template <TriviallyCopyable Type> inline void Atomic::store(Type* ptr, Type value, const std::memory_order order) noexcept { #if defined(Z_CLANG) __atomic_store(ptr, &value, castMemOrder(order)); #else // Z_CLANG std::atomic_ref<Type>{*ptr}.store(value, order); #endif // Z_CLANG } /*! \details No detailed description \tparam Type No description. \param [in] ptr No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::load(const Type* ptr, const std::memory_order order) noexcept { using T = std::remove_cvref_t<Type>; T* p = const_cast<T*>(ptr); Type result = cast<Type>(0); #if defined(Z_CLANG) __atomic_load(p, &result, castMemOrder(order)); #else // Z_CLANG result = std::atomic_ref<T>{*p}.load(order); #endif // Z_CLANG return result; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::exchange(Type* ptr, Type value, const std::memory_order order) noexcept { Type old = cast<Type>(0); #if defined(Z_CLANG) __atomic_exchange(ptr, &value, &old, castMemOrder(order)); #else // Z_CLANG old = std::atomic_ref<Type>{*ptr}.exchange(value, order); #endif // Z_CLANG return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] cmp No description. \param [in] value No description. \param [in] success_order No description. \param [in] failure_order No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::compareAndExchange(Type* ptr, Type cmp, Type value, const std::memory_order success_order, const std::memory_order failure_order) noexcept { const auto s = castMemOrder(success_order); const auto f = castMemOrder(failure_order); #if defined(Z_CLANG) __atomic_compare_exchange(ptr, &cmp, &value, false, s, f); #else // Z_CLANG std::atomic_ref<Type>{*ptr}.compare_exchange_strong(cmp, value, s, f); #endif // Z_CLANG return cmp; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::add(Type* ptr, const Type value, const std::memory_order order) noexcept { const Type old = #if defined(Z_CLANG) __atomic_fetch_add(ptr, value, castMemOrder(order)); #else // Z_CLANG std::atomic_ref<Type>{*ptr}.fetch_add(value, order); #endif // Z_CLANG return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::sub(Type* ptr, const Type value, const std::memory_order order) noexcept { const Type old = #if defined(Z_CLANG) __atomic_fetch_sub(ptr, value, castMemOrder(order)); #else // Z_CLANG std::atomic_ref<Type>{*ptr}.fetch_sub(value, order); #endif // Z_CLANG return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::increment(Type* ptr, const std::memory_order order) noexcept { constexpr Type one = cast<Type>(1); const Type old = add(ptr, one, order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::decrement(Type* ptr, const std::memory_order order) noexcept { constexpr Type one = cast<Type>(1); const auto old = sub(ptr, one, order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::min(Type* ptr, const Type value, const std::memory_order order) noexcept { const auto func = [](const Type lhs, const Type rhs) { return (lhs < rhs) ? lhs : rhs; }; Type old = cast<Type>(0); #if defined(Z_CLANG) if constexpr (Integer<Type>) old = __atomic_fetch_min(ptr, value, castMemOrder(order)); else #endif // Z_CLANG old = perform(ptr, order, func, value); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \return No description */ template <TriviallyCopyable Type> inline Type Atomic::max(Type* ptr, const Type value, const std::memory_order order) noexcept { const auto func = [](const Type lhs, const Type rhs) { return (lhs < rhs) ? rhs : lhs; }; Type old = cast<Type>(0); #if defined(Z_CLANG) if constexpr (Integer<Type>) old = __atomic_fetch_max(ptr, value, castMemOrder(order)); else #endif // Z_CLANG old = perform(ptr, order, func, value); return old; } /*! \details No detailed description \tparam Int No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <Integer Int> inline Int Atomic::bitAnd(Int* ptr, const Int value, const std::memory_order order) noexcept { const Int old = #if defined(Z_CLANG) __atomic_fetch_and(ptr, value, castMemOrder(order)); #else // Z_CLANG std::atomic_ref<Int>{*ptr}.fetch_and(value, order); #endif // Z_CLANG return old; } /*! \details No detailed description \tparam Int No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <Integer Int> inline Int Atomic::bitOr(Int* ptr, const Int value, const std::memory_order order) noexcept { const Int old = #if defined(Z_CLANG) __atomic_fetch_or(ptr, value, castMemOrder(order)); #else // Z_CLANG std::atomic_ref<Int>{*ptr}.fetch_or(value, order); #endif // Z_CLANG return old; } /*! \details No detailed description \tparam Int No description. \param [in,out] ptr No description. \param [in] value No description. \return No description */ template <Integer Int> inline Int Atomic::bitXor(Int* ptr, const Int value, const std::memory_order order) noexcept { const Int old = #if defined(Z_CLANG) __atomic_fetch_xor(ptr, value, castMemOrder(order)); #else // Z_CLANG std::atomic_ref<Int>{*ptr}.fetch_xor(value, order); #endif // Z_CLANG return old; } /*! \details No detailed description \tparam Type No description. \return No description */ template <TriviallyCopyable Type> inline constexpr bool Atomic::isAlwaysLockFree() noexcept { [[maybe_unused]] constexpr std::size_t size = sizeof(Type); const bool result = #if defined(Z_CLANG) __atomic_always_lock_free(size, nullptr); #else // Z_CLANG std::atomic_ref<Type>::is_always_lock_free; #endif // Z_CLANG return result; } /*! \details No detailed description \tparam Type No description. \return No description */ template <TriviallyCopyable Type> inline bool Atomic::isLockFree() noexcept { [[maybe_unused]] constexpr std::size_t size = sizeof(Type); [[maybe_unused]] Type value = cast<Type>(0); const bool result = #if defined(Z_CLANG) __atomic_is_lock_free(size, nullptr); #else // Z_CLANG std::atomic_ref<Type>{value}.is_lock_free(); #endif // Z_CLANG return result; } /*! \details No detailed description \tparam Type No description. \tparam Function No description. \tparam Types No description. \param [in,out] ptr No description. \param [in] order No description. \param [in] expression No description. \param [in] arguments No description. \return No description */ template <TriviallyCopyable Type, typename Function, typename ...Types> requires InvocableR<Function, Type, Type, Types...> inline Type Atomic::perform(Type* ptr, const std::memory_order order, Function&& expression, Types&&... arguments) noexcept { Type old = *ptr; Type cmp = cast<Type>(0); do { cmp = old; const Type value = expression(cmp, std::forward<Types>(arguments)...); old = compareAndExchange(ptr, cmp, value, order, std::memory_order::acquire); } while (old != cmp); return old; } /*! \details No detailed description \tparam Type No description. \tparam Function No description. \tparam Types No description. \param [in,out] ptr No description. \param [in] expression No description. \param [in] arguments No description. \return No description */ template <TriviallyCopyable Type, typename Function, typename ...Types> requires InvocableR<Function, Type, Type, Types...> inline Type Atomic::perform(Type* ptr, Function&& expression, Types&&... arguments) noexcept { const Type old = perform(ptr, defaultMemOrder(), std::forward<Function>(expression), std::forward<Types>(arguments)...); return old; } /*! \details No detailed description \tparam Type No description. \param [out] ptr No description. \param [in] value No description. \param [in] order No description. */ template <TriviallyCopyable Type> inline void atomic_store(Type* ptr, const Type value, const std::memory_order order) noexcept { Atomic::store(ptr, value, order); } /*! \details No detailed description \tparam Type No description. \param [in] ptr No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_load(const Type* ptr, const std::memory_order order) noexcept { const Type result = Atomic::load(ptr, order); return result; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_exchange(Type* ptr, const Type value, const std::memory_order order) noexcept { const Type old = Atomic::exchange(ptr, value, order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] cmp No description. \param [in] value No description. \param [in] success_order No description. \param [in] failure_order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_compare_exchange(Type* ptr, const Type cmp, const Type value, const std::memory_order success_order, const std::memory_order failure_order) noexcept { const Type old = Atomic::compareAndExchange(ptr, cmp, value, success_order, failure_order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_fetch_add(Type* ptr, const Type value, const std::memory_order order) noexcept { const Type old = Atomic::add(ptr, value, order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_fetch_sub(Type* ptr, const Type value, const std::memory_order order) noexcept { const Type old = Atomic::sub(ptr, value, order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_fetch_inc(Type* ptr, const std::memory_order order) noexcept { const Type old = Atomic::increment(ptr, order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_fetch_dec(Type* ptr, const std::memory_order order) noexcept { const Type old = Atomic::decrement(ptr, order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_fetch_min(Type* ptr, const Type value, const std::memory_order order) noexcept { const Type old = (Atomic::min)(ptr, value, order); return old; } /*! \details No detailed description \tparam Type No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <TriviallyCopyable Type> inline Type atomic_fetch_max(Type* ptr, const Type value, const std::memory_order order) noexcept { const Type old = (Atomic::max)(ptr, value, order); return old; } /*! \details No detailed description \tparam Int No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <Integer Int> inline Int atomic_fetch_and(Int* ptr, const Int value, const std::memory_order order) noexcept { const Int old = Atomic::bitAnd(ptr, value, order); return old; } /*! \details No detailed description \tparam Int No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <Integer Int> inline Int atomic_fetch_or(Int* ptr, const Int value, const std::memory_order order) noexcept { const Int old = Atomic::bitOr(ptr, value, order); return old; } /*! \details No detailed description \tparam Int No description. \param [in,out] ptr No description. \param [in] value No description. \param [in] order No description. \return No description */ template <Integer Int> inline Int atomic_fetch_xor(Int* ptr, const Int value, const std::memory_order order) noexcept { const Int old = Atomic::bitXor(ptr, value, order); return old; } /*! \details No detailed description \tparam kOsSpecified No description. \param [in] word No description. \param [in] old No description. \param [in] order No description. */ template <bool kOsSpecified> inline void atomic_wait(AtomicWord<kOsSpecified>* word, const Atomic::WordValueType old, const std::memory_order order) noexcept { Atomic::wait(word, old, order); } /*! \details No detailed description \tparam kOsSpecified No description. \param [in] word No description. */ template <bool kOsSpecified> inline void atomic_notify_one(AtomicWord<kOsSpecified>* word) noexcept { Atomic::notifyOne(word); } /*! \details No detailed description \tparam kOsSpecified No description. \param [in] word No description. */ template <bool kOsSpecified> inline void atomic_notify_all(AtomicWord<kOsSpecified>* word) noexcept { Atomic::notifyAll(word); } } // namespace zisc #endif // ZISC_ATOMIC_INL_HPP
25.81831
93
0.676722
byzin